Project import generated by Copybara.

GitOrigin-RevId: afe48a2ce03f8a886db15c5944e5df0d1b6cf3da
diff --git a/.dir-locals.el b/.dir-locals.el
new file mode 100644
index 0000000..3af5c9b
--- /dev/null
+++ b/.dir-locals.el
@@ -0,0 +1,16 @@
+;; Per-directory local variables for GNU Emacs 23 and later.
+
+((nil
+  . ((fill-column . 78)
+     (tab-width   .  4)
+     (indent-tabs-mode . nil)
+     (show-trailing-whitespace . t)
+     (c-basic-offset . 2)
+     (ispell-check-comments . exclusive)
+     (ispell-local-dictionary . "british")
+     (safe-local-variable-values
+	  '((c-default-style . "gnu")
+	    (sentence-end-double-space . f)
+        (eval add-hook 'prog-mode-hook #'flyspell-prog-mode)
+        (flyspell-issue-message-flag . f) ; avoid messages for every word
+        )))))
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..6004a2e
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,8 @@
+*.m4	eol=lf
+*.sh	eol=lf
+configure.ac	eol=lf
+makefile.am	eol=lf
+.gitattributes	eol=lf
+*.key	eol=lf
+*.crt	eol=lf
+*.pem	eol=lf
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
new file mode 100644
index 0000000..f1023d5
--- /dev/null
+++ b/.gitlab-ci.yml
@@ -0,0 +1,124 @@
+# we utilize the images generated by the build-images project, to
+# speed up CI runs. We also use ccache and store config.cache
+# to speed up compilation. We include a version number in cache
+# name to allow expiration of old caches.
+
+cache:
+  key: "$CI_JOB_NAME-ver1"
+  paths:
+    - cache/
+
+before_script:
+  # CCache Config
+  - mkdir -p cache
+  - export CCACHE_BASEDIR="${PWD}"
+  - export CCACHE_DIR="${PWD}/cache"
+  - export CC="ccache gcc"
+
+after_script:
+  # somehow after_script looses environment
+  - export CCACHE_BASEDIR="${PWD}"
+  - export CCACHE_DIR="${PWD}/cache"
+  - ccache -s
+
+variables:
+  BUILD_IMAGES_PROJECT: libmicrohttpd/build-images
+  DEBIAN_BUILD: buildenv-debian-stretch
+  MINGW_BUILD: buildenv-debian-mingw
+  GET_SOURCES_ATTEMPTS: "3"
+  CONFIGURE_BASE_FLAGS: --cache-file cache/config.cache
+  CFLAGS_DEFAULT: ""
+
+# In this build we combine
+#  * gcc
+#  * check
+gcc/Stretch:
+  image: $CI_REGISTRY/$BUILD_IMAGES_PROJECT:$DEBIAN_BUILD
+  script:
+    - export CFLAGS="$CFLAGS_DEFAULT"
+    - ./bootstrap
+    - ./configure $CONFIGURE_BASE_FLAGS --enable-build-type=debug --disable-sanitizers
+    - make -j$(nproc) && make -k check
+  tags:
+    - shared
+    - linux
+  artifacts:
+    expire_in: 2 weeks
+    when: on_failure
+    paths:
+      - ./*.log
+      - src/*/*.log
+      - src/*/*/*.log
+
+# In this build we combine
+#  * clang
+#  * ASan, UBSan
+#  * check
+Sanitizers/Stretch:
+  image: $CI_REGISTRY/$BUILD_IMAGES_PROJECT:$DEBIAN_BUILD
+  script:
+    - export CFLAGS="$CFLAGS_DEFAULT"
+    - ./bootstrap
+    - export CC="ccache clang"
+    - export ASAN_SYMBOLIZER_PATH=/usr/lib/llvm-3.8/bin/llvm-symbolizer
+    - ./configure $CONFIGURE_BASE_FLAGS --disable-doc --enable-build-type=debug --enable-sanitizers
+    - make -j$(nproc) && make -k check
+  tags:
+    - shared
+    - linux
+  artifacts:
+    expire_in: 2 weeks
+    when: on_failure
+    paths:
+      - ./*.log
+      - src/*/*.log
+      - src/*/*/*.log
+
+Scan-Build/Debian:
+  image: $CI_REGISTRY/$BUILD_IMAGES_PROJECT:$DEBIAN_BUILD
+  script:
+    - export CFLAGS="$CFLAGS_DEFAULT"
+    - export CC="clang-3.8"
+    - ./bootstrap
+    - scan-build --use-cc=clang-3.8 ./configure $CONFIGURE_BASE_FLAGS --enable-build-type=debug --disable-sanitizers
+    - scan-build --use-cc="ccache clang-3.8" -v -enable-checker security,nullability --status-bugs -o scan-build make -j$(nproc)
+    - scan-build --use-cc="ccache clang-3.8" -v -enable-checker security,nullability --status-bugs -o scan-build make -k check
+  tags:
+    - shared
+    - linux
+  except:
+    - tags
+  artifacts:
+    expire_in: 2 weeks
+    when: on_failure
+    paths:
+      - scan-build/*
+
+MinGW/Debian:
+  image: $CI_REGISTRY/$BUILD_IMAGES_PROJECT:$MINGW_BUILD
+  script:
+    - export CFLAGS="$CFLAGS_DEFAULT"
+    - export CC="ccache $PREFIX-gcc"
+    - ./bootstrap
+    - ./configure $CONFIGURE_BASE_FLAGS --build=x86_64-pc-linux-gnu --host=$PREFIX --enable-build-type=release
+    - make -j$(nproc)
+  tags:
+    - shared
+    - linux
+
+dist/Stretch:
+  image: $CI_REGISTRY/$BUILD_IMAGES_PROJECT:$DEBIAN_BUILD
+  script:
+    - export CFLAGS="$CFLAGS_DEFAULT"
+    - ./bootstrap
+    - ./configure $CONFIGURE_BASE_FLAGS --enable-build-type=release
+    - make -j$(nproc) dist
+  tags:
+    - shared
+    - linux
+  artifacts:
+    name: "$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA"
+    expire_in: 2 weeks
+    when: on_success
+    paths:
+      - ./libmicrohttpd-*.*.*.tar.??
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..9773fb9
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "contrib/build-common"]
+	path = contrib/build-common
+	url = https://git.taler.net/build-common.git
diff --git a/AUTHORS b/AUTHORS
index 8a04096..4cbfe0e 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,12 +1,12 @@
 Primary developers:
 Christian Grothoff <christian@grothoff.org> (maintainer)
-Andrey Uzunov <andrey.uzunov@gmail.com> (maintainer for libmicrospdy)
+Evgeny Grin (Karlson2k) <k2k@narod.ru> (maintainer)
+Andrey Uzunov <andrey.uzunov@gmail.com> (libmicrospdy experiment)
 Nils Durner <durner@gnunet.org> (W32 port)
 Sagie Amir (TLS/SSL support using GNUtls)
 Richard Alimi <rich@velvetsea.net> (performance)
 Amr Ali <amr.ali.cc@gmail.com> (digest authentication)
 Matthieu Speder <mspeder@users.sourceforge.net> (basic authentication, client certificates)
-Evgeny Grin (Karlson2k) <k2k@narod.ru> (W32 port)
 
 Code contributions also came from:
 Chris GauthierDickey <chrisg@cs.du.edu>
@@ -23,6 +23,7 @@
 Colin Caughie <c.caughie@indigovision.com>
 David Carvalho <andaris@gmail.com>
 David Reiss <dreiss@facebook.com>
+Markus Doppelbauer <doppelbauer@gmx.net>
 Matt Holiday
 Michael Cronenworth <mike@cchtml.com>
 Milan Straka <straka@ufal.mff.cuni.cz>
@@ -54,8 +55,22 @@
 Robert Groenenberg <robert.groenenberg@broadforward.com>
 Denis Dowling <denis.dowling@hsd.com.au>
 Louis Benoit <louisbenoit@videotron.ca>
-
+Flavio Coelin <flavio.ceolin@intel.com>
+Silvio Clecio <silvioprog@gmail.com>
+Robert D Kosisko <rkocisko@gmail.com>
+Tal Moaz <tmoaz@cisco.com>
+Dirk Brinkmeier
+Jose Bollo <jobol@nonadev.net>
+Jonathan McDougall <jonathanmcdougall@gmail.com>
+Tim Ruhsen <tim.ruehsen@gmx.de>
+Lawrence Sebald <lawrence.sebald@nasa.gov> (iovec-based responses)
 
 Documentation contributions also came from:
 Marco Maggi <marco.maggi-ipsu@poste.it>
 Sebastian Gerhardt <sebgerhardt@gmx.net>
+
+Special thanks to:
+Florian Weimer <fweimer@redhat.com>
+Ramakrishnan Muthukrishnan <ram@leastauthority.com>
+Gervasa Markham <grev@mozilla.com>
+Liz Steininger <liz@leastauthority.com>
diff --git a/Android.mk b/Android.mk
index 10e7f6f..a42b681 100644
--- a/Android.mk
+++ b/Android.mk
@@ -15,32 +15,84 @@
 #
 LOCAL_PATH := $(my-dir)
 
-include $(CLEAR_VARS)
+microhttpdIncludes := \
+    $(LOCAL_PATH)/$(LOCAL_PATH)/src/microhttpd/basicauth.h \
+    $(LOCAL_PATH)/src/microhttpd/connection.h \
+    $(LOCAL_PATH)/src/microhttpd/connection_https.h \
+    $(LOCAL_PATH)/src/microhttpd/digestauth.h \
+    $(LOCAL_PATH)/src/microhttpd/gen_auth.h \
+    $(LOCAL_PATH)/src/microhttpd/internal.h \
+    $(LOCAL_PATH)/src/microhttpd/md5_ext.h \
+    $(LOCAL_PATH)/src/microhttpd/md5.h \
+    $(LOCAL_PATH)/src/microhttpd/memorypool.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_align.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_assert.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_bithelpers.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_byteorder.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_compat.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_itc.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_itc_types.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_limits.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_locks.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_md5_wrap.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_mono_clock.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_panic.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_send.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_sha256_wrap.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_sockets.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_str.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_str_types.h \
+    $(LOCAL_PATH)/src/microhttpd/mhd_threads.h \
+    $(LOCAL_PATH)/src/microhttpd/postprocessor.h \
+    $(LOCAL_PATH)/src/microhttpd/response.h \
+    $(LOCAL_PATH)/src/microhttpd/sha1.h \
+    $(LOCAL_PATH)/src/microhttpd/sha256_ext.h \
+    $(LOCAL_PATH)/src/microhttpd/sha256.h \
+    $(LOCAL_PATH)/src/microhttpd/sha512_256.h \
+    $(LOCAL_PATH)/src/microhttpd/sysfdsetsize.h \
+    $(LOCAL_PATH)/src/microhttpd/test_helpers.h \
+    $(LOCAL_PATH)/src/microhttpd/tsearch.h
 
+# libmicrohttpd shared library
+# ========================================================
+include $(CLEAR_VARS)
 LOCAL_MODULE := libmicrohttpd
 LOCAL_CFLAGS := -Wno-sign-compare -Wno-unused-parameter
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/src/include
 
 LOCAL_C_INCLUDES := \
     $(LOCAL_PATH)/src/include \
+    $(LOCAL_PATH)/src/lib \
     $(LOCAL_PATH)/src/microhttpd \
-    external/boringssl/include \
-
-LOCAL_SHARED_LIBRARIES := libssl libcrypto
+    $(microhttpdIncludes) \
+    external/boringssl/include
 
 LOCAL_SRC_FILES := \
-    src/microhttpd/base64.c \
     src/microhttpd/basicauth.c \
     src/microhttpd/connection.c \
-    src/microhttpd/connection_https.c \
     src/microhttpd/daemon.c \
     src/microhttpd/digestauth.c \
+    src/microhttpd/gen_auth.c \
     src/microhttpd/internal.c \
     src/microhttpd/md5.c \
     src/microhttpd/memorypool.c \
+    src/microhttpd/mhd_compat.c \
+    src/microhttpd/mhd_itc.c \
+    src/microhttpd/mhd_mono_clock.c \
+    src/microhttpd/mhd_panic.c \
+    src/microhttpd/mhd_send.c \
+    src/microhttpd/mhd_sockets.c \
+    src/microhttpd/mhd_str.c \
+    src/microhttpd/mhd_threads.c \
     src/microhttpd/postprocessor.c \
     src/microhttpd/reason_phrase.c \
     src/microhttpd/response.c \
-    src/microhttpd/tsearch.c \
+    src/microhttpd/sha1.c \
+    src/microhttpd/sha256.c \
+    src/microhttpd/sha512_256.c \
+    src/microhttpd/sysfdsetsize.c \
+    src/microhttpd/tsearch.c
+
+LOCAL_SHARED_LIBRARIES := libssl libcrypto
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/COPYING b/COPYING
index 9b3e553..2f076bc 100644
--- a/COPYING
+++ b/COPYING
@@ -462,49 +462,3 @@
 DAMAGES.
 
 		     END OF TERMS AND CONDITIONS
-
-           How to Apply These Terms to Your New Libraries
-
-  If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change.  You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
-  To apply these terms, attach the following notices to the library.  It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the library's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    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 2.1 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, write to the Free Software
-    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the
-  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
-  <signature of Ty Coon>, 1 April 1990
-  Ty Coon, President of Vice
-
-That's all there is to it!
-
-
diff --git a/ChangeLog b/ChangeLog
index 57dd440..3caf710 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,1867 @@
+Web 29 Mar 2023 20:56:00 CEST
+    Bumped version as the hotfix was released based on the separate branch. -EG
+
+Sun Feb 26 05:49:30 PM CET 2023
+    Fix potential DoS vector in MHD_PostProcessor discovered
+    by Gynvael Coldwind and Dejan Alvadzijevic (CVE-2023-27371). -CG
+
+Sun 26 Dec 2021 20:30:00 MSK
+    Releasing GNU libmicrohttpd 0.9.75 -EG
+
+December 2021
+    Fixed Makefile warning on MinGW.
+    Fixed compiler warning on MinGW.
+    Fixed "configure" portability (for NetBSD).
+    MSVC project cosmetics.
+    MSVC fixed project to fix linker warning.
+    Fixed compiler warning on some platforms.
+    Further improved test_client_put_stop to get stable results on all
+    platforms.
+    Added workaround for platforms (like OpenBSD) where system monotonic clocks
+    may jump forward and back.
+    Added more checks in test_large_put, increased timeout (was too small for
+    this test). -EG
+
+Sun 19 Dec 2021 18:30:00 MSK
+    Releasing GNU libmicrohttpd 0.9.74 -EG
+
+December 2021
+    Fixed doxy for MHD_suspend_connection().
+    Some code improvements for new test test_client_put_stop.
+    Added special log message if thread creation failed due to system limits.
+    Fully restructured new_connection_process_() to correctly handle errors,
+    fixed missing decrement of number of daemon connections if any error
+    encountered, fixed app notification of connection termination when app has
+    not been notified about connection start, fixed (highly unlikely) reset of
+    the list of connections if reached daemon's connections limit.
+    configure: fixed some compiler warnings reported in config.log.
+    Fixed tests on FreeBSD to support system-limited rate of RST packets and
+    'blackhole' system setting. -EG
+    Fixed tests for libmagic to really use libmagic in examples. -CG
+    Used tricks in code formatting to workaround uncrustify bugs.
+    configure: improved compatibility with various shells.
+    configure: added selective enable of sanitizers.
+    Fixed compatibility with old GnuTLS versions.
+    Fixed tests compatibility with old libcurl versions.
+    Fixed busy-waiting in test_timeout (fixed CPU load spikes in the test).
+    test_https_time_out: check rewritten, previously it is was no-op.
+    test_upgrade{,_large}: fixed passing of socket value to GnuTLS on W32.
+    Simplified Makefile for HTTPS tests.
+    Added detection of old broken GnuTLS builds (on RHEL6 and clones) and
+    disabled some tests broken with these builds.
+    Muted compiler warnings with old libcurl versions.
+    Reworked dlltool support: added support for weakened oversimplified
+    half-broken llvm-dlltool
+    Silenced MS lib tool warning and MS lib tool invocation.
+    Added Makefiles rules for automatic regeneration of all required files if
+    anything is missing.
+    Added Makefile silent rules support for W32 RC and W32 static libs.
+    Added local patches for autotools (mainly for libtool) to build MHD
+    correctly on modern MinGW64/Clang.
+    Updated HTTP headers macros from registry. -EG
+
+November 2021
+    Clarified comments and doxy for MHD_str* and related tests.
+    MHD_uint32_to_strx(): rewritten for readability and minor optimization,
+    used indexes instead of pointers.
+    Documented in doxy how to use MHD_AccessHandlerCallback.
+    mhd_sockets: added more network error codes.
+    W32 socket pair: set TCP_NODELAY to avoid unwanted buffering and delays.
+    Additional doxy fixes in microhttpd.h.
+    Fixed blocking sockets setting in tests and examples for W32.
+    Added checks for fcntl() results in tests and examples.
+    Added series of tests based on simple HTTP client implementation developed
+    for testing of MHD.
+    Renamed 'early_response' connection flag to 'discard_request' and reworked
+    handling of connection's flags.
+    Clarified request termination reasons doxy, fixed reporting of
+    MHD_REQUEST_TERMINATED_READ_ERROR (previously this code was not really used
+    in reporting).
+    Enforce all libcurl tests exit code to be zero or one.
+    Rewritten client upload processing: removed redundant checks, fixed
+    skipping of chunk closure when not data is not received yet, fixed skipping
+    of the last LF in termination chunk, handle correctly chunk sizes with more
+    than 16 digits (leading zeros are valid according to HTTP RFC), fixed
+    handling of CRCR, LFCR, LFLF, and bare CR as single line delimiters, report
+    error when invalid chunk format is received without waiting to receive
+    (possibly missing) end of the line, reply to the client with special error
+    if chunk size is too large to be handled by MHD (>16 EiB).
+    Added error reply if client used too large request payload (>16 EiB).
+    Fixed return value for MHD_FEATURE_AUTOSUPPRESS_SIGPIPE on W32, now it
+    returns MHD_YES as W32 does not need sigpipe suppression.
+    configure: reordered and improved headers detection. Some headers require
+    other headers to be included before, now configure supports it.
+    Added missing ifdef guard for <stdbool.h>.
+    mhd_sockets: reordered includes for better compatibility.
+    Some code readability and formatting improvements. -EG
+
+October 2021
+    Added test family test_toolarge to check correct handling of the buffers
+    when the size of data is larger than free space.
+    Fixed missing updated of read and write buffers sizes.
+    Added detection and use of supported "noreturn" keyword for function
+    declaration. It should help compiler and static analyser.
+    Added support for leak sanitizer.
+    Fixed analyser errors on W32.
+    Partially reworked memory allocation from the pool, more robust
+    implementation, always track read and write buffers.
+    Added custom memory poisoning in memory pool with address sanitizer.
+    Added missing update of the read buffer size.
+    Addition for doxy for new behaviour of MHD_del_response_header().
+    Added two tests with non-standard symbols in requests.
+    Removed double close of connection with error in headers processing.
+    Respond to the client with error if chunked request has broken chunked
+    encoding as required by HTTP RFC instead of just closing the connection.
+    Fixed request headers processing. Do not recognize bare CR as end of line.
+    Fixed processing of CRCR, bare CR, LFCR, and LFLF as end of the line for
+    request chunked encoding. Now only CRLF or bare LF are recognized as end
+    of line.
+    Added Lawrence Sebald to the AUTHORS file (iovec-based responses).
+    Check for PAGESIZE and PAGE_SIZE macros and check whether they can be used
+    for static variable initialization.
+    Include "MHD_config.h" before all other includes to set macros required to
+    be set before standard includes.
+    Chunked response: abort with error if application returns more data than
+    requested.
+    Monotonic clock: use only native clock on W32 as all other clocks are just
+    wrappers.
+    W32: fixed builds with MSVC, added projects for VS2022, added MSVC
+    universal project that use latest available toolset, use C17 if supported.
+    Chunked response: fixed calculation of number of bytes left to send.
+    microhttpd.h: doxy clarifications for sockets polling.
+    Updated HTTP statuses, methods, and headers names from the registries.
+    Further improved doxy for MHD_add_response_header().
+    A few comments improvements and clarifications.
+    Added internal connection's flag indicating discard of the request. -EG
+    Websockets update by David Gausmann. -DG
+    Fixed reported value for MHD_CONNECTION_INFO_CONNECTION_TIMEOUT.
+    Minor code readability improvements in MHD_set_connection_option().
+    Improved doxy for MHD_get_timeout().
+    Memorypool: minor code improvements. -EG
+
+September 2021
+    Improved system includes headers detection and usage. Removed unused
+    headers detection.
+    Added indirect calculation of maximum values at compile time by
+    using types size detection. These values are used only to mute
+    compiler warnings.
+    Fixed pre-compiler errors if various *_MAX macros defined with
+    non-digits symbols not readable for pre-compiler.
+    Limit number of used CPU cores in tests to 6, unless heavy tests are
+    enabled.
+    Disabled parallel tests with libcurl if heavy tests are enabled.
+    configure: removed '--enable-sanitizer' and added '--enable-sanitizers'
+    parameters. Added testing for supported sanitizers and enabling only
+    supported sanitizers.
+    Added support for run-time sanitizers settings for tests when
+    sanitizers are enabled.
+    Added support for undefined behavior sanitizer without run-time library.
+    Fixed various undefined behavior sanitizer detected errors, improved
+    portability.
+    Fixed how bitwise NOT is used with enum, fixed portability.
+    microhttpd.h: changed macros MHD_CONTENT_READER_* to use ssize_t.
+    test_postprocessor: added more check, improved error reporting, added
+    new test data.
+    postprocessor: fixed undefined behavior (memcpy(), memmove() with zero
+    size and NULL pointer).
+    Updated copyright year in W32 DLLs.
+    postprocessor: fixed empty key processing.
+    test_postprocessor: added tests with hex-encoded values.
+    postprocessor: fixed incomplete processing of the last part of hex-encoded
+    value if data was broken into certain sized pieces.
+    Used type specifiers for printf() from inttypes.h to improved compatibility
+    with various run-time libs. Fallback to standard values if type specifiers
+    are not defined.
+    Added detection of used run-time library (MSVCRT/UCRT) on W32.
+    testcurl: fixed incorrect case-insensitive match for method name. Method
+    name must be checked by using case-sensitive match.
+    microhttpd.h: clarified some doxy descriptions.
+    Prevented potential double sending of error responses.
+    Fixed application notification with MHD_REQUEST_TERMINATED_COMPLETED_OK
+    when error response has been sent (MHD_REQUEST_TERMINATED_WITH_ERROR is
+    used).
+    Avoid trying to send error response if response is already being sent.
+    Improved log error message when error response is processing. -EG
+
+August 2021
+    Silently drop "keep-alive" token from response "connection" header,
+    "keep-alive" cannot be enforced and always enabled if possible.
+    Further improved doxy for MHD_add_response_header().
+    Added detection of the "Date:" header in the response headers set by
+    app at response forming time.
+    Disallow space in response header name, allow tab in response header
+    value.
+    Added internal MHD_uint8_to_str_pad() function.
+    Used internal MHD_uint8_to_str_pad() in datestamp generation function.
+    Added detection and reporting of incorrect "Upgrade" responses. -EG
+    Fixed short busy waiting (up to one second) when connection is going
+    to be closed. -AI
+    Minor improvement for test_callback, test_get_chunked
+    Fixed chunked responses with known size.
+    Added two more tests for chunked response.
+    Fixed chunked responses with predefined data (without data callback).
+    Fixed calculation of the buffer size for the next response chunk.
+    Completely rewritten reply header build function. The old version
+    had several levels of hacks, was unmaintainable, did not follow
+    HTTP specification in details; fixed used caseless header matching
+    where case-sensitive matching must be used; removed two passes of
+    header building. New version use clear logic and can be extended
+    when needed.
+    Changed behaviour: "Connection: keep-alive" is not being sent
+    for HTTP/1.1 connection (as per HTTP RFC).
+    test_get_chunked: fixed error reporting.
+    HTTPS tests: fixed memory leaks if function failed.
+    libcurl tests: improved handling of curl multi_*.
+    Added two tests for correct choice of "Keep-Alive" or "Close".
+    Simplified Makefile for testcurl.
+    Fixed select() error handling in tests.
+    microhttpd.h: minor macro formatting
+    Changed behaviour: if response size is unknown and chunked encoding is
+    allowed, chunked encoding is used even for non-keep-alive connection as
+    required by HTTP RFC.
+    Added two more tests for chunked replies.
+    Simplified keepalive_possible(); added new value for MHD_ConnKeepAlive,
+    added third state "Upgrade".
+    Changed behaviour: used HTTP/1.1 replies for HTTP/1.0 requests as
+    required by HTTP RFC. HTTP/1.0 reply still can be enforced by response
+    flag.
+    Added more doxy for MHD_ResponseFlags, added new names with the same
+    values as old names: MHD_RF_HTTP_1_0_COMPATIBLE_STRICT and
+    MHD_RF_HTTP_1_0_SERVER.
+    Added new value MHD_RF_SEND_KEEP_ALIVE_HEADER to enforce sending of
+    "Connection: keep-alive" even for HTTP/1.1 clients when keep-alive is
+    used.
+    test_get_close_keep_alive: added more combinations of parameters to
+    check.
+    Added separate flag for chunked response in connection instead of
+    reusing the same flag as for chunked request.
+    Added new connection's flag "stop_with_error".
+    Fixed empty first line processing: the request could be not processed
+    unless something else kicks next processing the same connection again.
+    Added new connection states: MHD_CONNECTION_REQ_LINE_RECEIVING,
+    MHD_CONNECTION_FULL_REQ_RECEIVED, MHD_CONNECTION_START_REPLY to
+    simplify states logic.
+    Changed write buffer allocation logic: as connection buffer size is
+    known and fixed, use initially use full buffer for writing and reduce
+    size of part used for writing if another allocation from the same
+    buffer needs to be done. Implemented helper function to automatically
+    reduce the size of read or write part to allocate buffer for other
+    needs.
+    Added define of NDEBUG if neither _DEBUG nor NDEBUG are defined.
+    As accepted sockets inherit non-blocking flag from listening socket
+    on all platform except Linux, track this state to use less number
+    of syscalls.
+    Fixed compiler and static analyser warnings.
+    Moved HTTPS tests helper file to the HTTPS tests directory.
+    Minor Makefiles cleanup.
+    Added support for new monotonic clock ids.
+    Added new internal monotonic clock function with milliseconds accuracy.
+    Fixed support of custom connection timeout in thread-per-connection mode.
+    Added more error checking to test_timeout.
+    microhttpd.h: removed duplicated macro.
+    Refined timeouts handling. Switched from seconds resolution to milliseconds
+    resolution, added automatic detection and support of low-resolution system
+    clock to avoid busy-waiting at connection expiration. Added log message
+    for too large timeout period (> 146 million years) with trim to supported
+    values. -EG
+
+Wed 04 Aug 2021 06:56:52 PM CEST
+    Introduce new MHD_CONNECTION_INFO_HTTP_STATUS. -CG
+
+July 2021
+    Added automatic response flags with detection when response
+    is being formed.
+    Added special processing for response "Connection" headers, combined
+    multiple "Connection" headers into single header.
+    Restructured MSVC project files.
+    Changed MSVC project defaults to Vista+ (WinXP is still supported).
+    Fixed copy-paste error in mhd_aligh.h, added support for MSVC.
+    Added internal function for printing hex and decimals numbers.
+    Reply chunked body handling fixes, used new internal functions
+    instead of snprintf().
+    Added automatic response flag when app sets chunked encoding header.
+    New internal function for chunked reply footer forming. Unification with
+    reply header forming function just over-complicated things and made
+    function hardly maintainable.
+    Added new function MHD_get_reason_phrase_len_for(), related tests and
+    updated scripts for response phrases.
+    Added more tests for chunked replies.
+    Added function to reset connection state after finishing processing of
+    request-reply to prepare for the next request.
+    Added even more tests for chunked replies.
+    Added internal function for printing uint64_t decimal numbers. -EG
+
+June 2021
+    Tests: implemented checking of response footer.
+    Fixed loss of incoming data if more than half of buffer is
+    used for the next request data.
+    Fixed completely broken calculation of request header size.
+    Chunked response: do not ask app callback for more data then
+    it is possible to process (more than 16 MBytes).
+    Check and report if app used wrong response code (>999 or <100)
+    Refuse to add second "Transfer-Encoding" header.
+    HTTPS tests: check whether all libcurl function succeeded.
+    HTTPS tests: implemented new detection of TLS backend.
+    HTTPS tests: fixed tests with new TLS defaults (SSL forbidden).
+    Implemented detection of basic HTTP methods, fixed wrong
+    caseless matching for HTTP method names.
+    MHD_create_response_*() functions: improved doxy.
+    MHD_add_response_header: added detailed comment about automatic
+    headers.
+    Do not allow responses with 1xx codes for HTTP/1.0 requests.
+    Fixed used order of headers: now user response headers are used in
+    the same order as was added by application.
+    Added new internal function MHD_get_response_element_n_().
+    Added detection of more compiler built-ins for bits rotations.
+    Minor optimisation of caseless strings matching.
+    Added MHD_str_remove_token_caseless_() function and tests.
+    Added MHD_str_remove_tokens_caseless_() function and tests. -EG
+
+May 2021
+    Doxy description clarifications for MHD_get_timeout() and related
+    functions.
+    Added MHD_create_response_from_buffer_with_free_callback_cls().
+    Added SHA-1 calculation (required for WebSockets).
+    Added new internal header mhd_aligh.h for checking alignment of
+    variables.
+    Fixed SHA-256 and MD5 calculation with unaligned data.
+    Added tests for hashes with unaligned data.
+    Used compiler built-ins for bits rotations.
+    Added detection of HTTP version at early stage.
+    Added early response of unsupported HTTP version.
+    Fixed wrong caseless matches for HTTP version strings.
+    Added calculation of error responses at compile time (avoided
+    repeated strlen() for known data). -EG
+
+April 2021
+    New test for reply chunked encoding. -EG
+
+Mon 26 Apr 2021 02:09:46 PM CEST
+    Importing experimental Websocket support by David Gausmann. -CG
+
+Sun 25 Apr 2021 14:00:00 MSK
+    Releasing GNU libmicrohttpd 0.9.73. -EG
+
+Sat 24 Apr 2021 23:00:00 MSK
+    Fixed build with Clang and Visual Studio.
+    MSVS project files updated.
+    Enabled bind port autodetection with MSVS builds. -EG
+
+Fri 23 Apr 2021 14:27:00 MSK
+    Fixed build without TLS lib.
+    Fixed build without system poll() function.
+    Fixed compiler warnings on 32-bit platforms.
+    Fixed various compiler warnings. -EG
+
+Thu 22 Apr 2021 12:32:00 MSK
+    Fixed some typos.
+    Force disable TCP_CORK, TCP_NOPUSH, and TCP_NODELAY before switching
+    connection to "upgraded" mode.
+    Improved portability of the test-suite for upgraded connections. -EG
+
+Tue 20 Apr 2021 17:11:00 MSK
+    Disabled NLS by default in configure. -EG
+
+Mon 19 Apr 2021 18:58:00 MSK
+    Fixed testzzuf/test_put_chanked to correctly use MHD.
+    Added internal error code for TLS errors.
+    Added all missing messages to the .pot file.
+    Detect more types of errors for receiving data and report
+    error description in the MHD log.
+    Added support for ALPN on TLS connections if supported by
+    used TLS library. -EG
+
+Sun 18 Apr 2021 20:47:00 MSK
+    Removed dead code.
+    Limited iov-backed responses size to SSIZE_MAX as limited by
+    system calls.
+    Report error message in MHD log for send errors. -EG
+
+Sat 17 Apr 2021 18:50:00 MSK
+    Unified upgrade test behavior for all platforms.
+    Some code simplification and unification.
+    Compiler warning (false positive) fixed. -EG
+
+Fri 16 Apr 2021 17:58:00 MSK
+    Used run-time value if IOV_MAX if available.
+    Fixed portability of error handling for sending functions.
+    Detect pipes/unix sockets on fly and do not use TCP/IP specific
+    functions with them.
+    Fixed support of UNIX sockets on non-Linux kernels. -EG
+
+Fri 16 Apr 2021 10:23:39 AM CEST
+    Detect if a socket is a UNIX domain socket and do not try to play
+    with TCP corking options in this case (avoids useless failed
+    syscalls). -CG
+
+Thu 15 Apr 2021 18:56:00 MSK
+    Fixed configure '--enable-sanitizer' parameter.
+    Stopped pushing of partial responses when limited by system maximum size
+    for sendmsg(). -EG
+
+Web 14 Apr 2021 22:20:00 MSK
+    Fixed: use sendmsg() in POSIX-compatible way, do not try to send more
+    than IOV_MAX elements per single call. -EG
+
+Sun 11 Apr 2021 15:44:00 MSK
+    Updated test TLS certificates to not expired modern versions, restored
+    HTTPS examples compatibility with modern browsers.
+    TCP_NODELAY is not pre-enabled for HTTPS connection as it actually
+    does not speed-up TLS handshakes on moders OSes. -EG
+
+Thu 01 Apr 2021 21:29:46 MSK
+    Fixed MD5 digest authorization broken when compiled without variable
+    length arrays support (notably with MSVC).
+    Fixed and muted compiler warning.
+    Deeper test with zzuf if configured with --enable-heavy-tests.
+    Removed run-check of assert() in configure to avoid core dumps. -EG
+
+Thu 01 Apr 2021 17:46:00 MSK
+    Added new function MHD_run_wait() useful for single-threaded applications
+    without other network activity.
+    Added tests for the new function. -EG
+
+Wed 17 Mar 2021 20:53:33 MSK
+    Re-factored startup log parameters processing. Warn user if wrong logger
+    could be used potentially.
+    Added headers doxy with information about minimal MHD version when
+    particular symbols were introduced.
+    Added new daemon option to indicate SIGPIPE handling by application for
+    daemons being run in application thread. -EG
+
+Wed 24 Feb 2021 19:23:00 MSK
+    SIGPIPE-related macro minor refactoring for readability.
+    Added new response iov function (and related framework), based on the patch
+    provided by Lawrence Sebald and Damon N. Earp from NASA. -EG
+
+Thu 04 Feb 2021 06:41:34 PM CET
+    Fix PostProcessor to always properly stop iteration when application callback
+    tells it to do so. -CG
+
+Sun 24 Jan 2021 21:30:00 MSK
+    Added '--enable-heavy-tests' configure parameter.
+    Minor configure.ac and Makefiles fixes. -EG
+
+Tue 19 Jan 2021 17:59:00 MSK
+    Fixed compatibility with autoconf. 2.70
+    Updated M4 macros. -EG
+
+Wed 06 Jan 2021 08:39:58 PM CET
+    Return timeout of zero also for connections awaiting cleanup. -CG
+
+Tue 29 Dec 2020 15:39:00 MSK
+    Improved speed of TLS handshake by pre-enabling TCP_NODELAY. -EG
+
+Mon 28 Dec 2020 21:36:00 MSK
+    Releasing libmicrohttpd 0.9.72. -EG
+
+Mon 28 Dec 2020 09:37:00 MSK
+    Completely reworked and rewritten TCP_CORK, TCP_NOPUSH, TCP_NODELAY and
+    MSG_MORE handling. Reduced number of sys-calls, fixed portability for
+    FreeBSD, OpenBSD, NetBSD, Darwin, W32, Solaris.
+    Removed usage of gnutls_record_cork() as it fully blocks stream until
+    final block is ready.
+    Fixed compatibility with C90 compilers.
+    Really started using sendmsg() for header + body combined single-call
+    response sending.
+    Fixed sending of response body by sendmsg() when it shouldn't be sent,
+    like responses for HEAD requests.
+    Improved error handling for gnutls_record_send().
+    Updated W32 resources for .DLLs.
+    Fixed building with various disabled features (like messages, HTTPS,
+    http-upgrade, authorization etc.)
+    Fixed possible SIGPIPE generation when sendfile() is used (it was always
+    possible on Linux that sendfile() produce SIGPIPE, now it's fixed).
+    Several compiler warnings muted and/or fixed in the lib code and in
+    the examples. -EG
+
+Sun 01 Nov 2020 17:17:00 MSK
+    Fixed conflict with system CPU_COUNT macro.
+    Minor improvements of error reporting in MHD daemon.
+    Fixed FTBFS with GnuTLS versions before 3.1.9
+    Fixed test_add_conn for multi-CPU machines.
+    Fixed analyzer warnings.
+    Fixed use-after-free and resources leaks for upgraded connections
+    in TLS mode with thread-per-connection. -EG
+
+Sun 25 Oct 2020 19:31:00 MSK
+    Fixed epoll mode without listening socket.
+    Minor improvements of thread sync.
+    Fixed broken sendfile on FreeBSD.
+    Fixed broken MHD with thread-pool and without listening socket.
+    Added four tests for MHD_add_connection().
+    Fixed several resources leaks in error handlers.
+    Re-implemented scheme of handling of externally added connections,
+    fixed thread-safety. -EG
+
+Wed 21 Oct 2020 10:00:58 AM CEST
+    Corking should be OFF when sending the footer (#6610). -AP/CG
+
+Wed 07 Oct 2020 11:07:00 MSK
+    W32 default target version changed to Vista, XP is still supported.
+    Minor fixes and additional asserts for memorypool.
+    IPv6 tests are not used if IPv6 is disabled at run-time. -EG
+
+Sun 27 Sep 2020 10:08:03 PM CEST
+    Fixed incorrect triggering of epoll edge polling for
+    "upgraded" TLS connections.  Fixed a few cases where
+    gnutls_record_uncork() return value was still ignored,
+    possibly causing buffer to not be flushed correctly. -CG
+
+Sat 26 Sep 2020 08:18:02 PM CEST
+    Make MHD_USE_NO_LISTEN_SOCKET work in conjunction with
+    MHD internal threads. -CG/DE
+
+Thu 24 Sep 2020 16:55:00 MSK
+    Fixed compiler warnings on W32.
+    Minor optimisation of MHD_YES/MHD_NO internal usage.
+    Refactor and cleanup of internal debugging macros.
+    Updated HTTP status codes, header names and methods from
+    the registries.
+    Fixed portability of test_upgrade_large.
+    Minor testsuite fixes.
+    Restored parallel build of libmicrohttpd (except tests). -EG
+
+Fri 11 Sep 2020 10:08:22 PM CEST
+    Fix crash problem in PostProcessor reported by MD. -CG
+    Fix GnuTLS configure test to check for gnutls_record_uncork. -CG
+
+Wed 19 Aug 2020 09:40:39 AM CEST
+    Add logic to check on MHD_pool_reallocate() failure reported on the
+    mailinglist (will NOT yet fix the issue). -CG
+
+Sun 26 Jul 2020 01:56:54 PM CEST
+    Add MHD_create_response_from_pipe() to allow creating a response based
+    on data read from a pipe. -CG
+
+Fri Jul 10 15:04:51 CEST 2020
+    Fixed Postprocessor URL-encoded parsing if '%' fell on boundary. -CG/MD
+
+Thu 02 Jul 2020 09:56:23 PM CEST
+    Fixed return type of MHD_queue_basic_auth_fail_response. -CA/CG
+
+Sun 28 Jun 2020 09:36:01 PM CEST
+    Fix buffer overflow issue in URL parser.
+    Releasing libmicrohttpd 0.9.71. -CG
+
+Tue 16 Jun 2020 08:44:22 PM CEST
+    Add logic to try again if GNUtls uncork() fails. -CG
+
+Wed 10 Jun 2020 09:44:29 PM CEST
+    Fixed PostProcessor bug discovered by MD, which given certain parser
+    boundaries caused the returned values to be wrong. -CG/MD
+
+Wed 08 Apr 2020 10:53:01 PM CEST
+    Introduce `enum MHD_Result` for #MHD_YES/#MHD_NO to avoid using 'int' so much.
+    Note that this change WILL cause compiler warnings until (most) MHD callbacks
+    in application code change their return type from 'int' to 'enum MHD_Result'.
+    That said, avoiding possible confusions of different enums is going to make
+    the code more robust in the future. For conditional compilation, test
+    for "MHD_VERSION >= 0x00097002". -CG
+
+Tue 07 Apr 2020 02:58:39 PM BRT
+    Fixed #5501 (Added example for how to provide a tiny threaded websocket server). -SC
+
+Tue 31 Mar 2020 02:36:40 PM BRT
+    Fixed #6142 (applied several spelling fixes). -DKG/-SC
+
+Sat 07 Mar 2020 05:20:33 PM CET
+    Fixed #6090 (misc. severe socket handling bugs on OS X). -CG
+
+Sat 08 Feb 2020 09:12:54 PM CET
+    Fixed 100-continue handling for PATCH method (#6068).
+    Fixed FTBFS from wrong #endif position for certain builds (#6025).
+    Fixed connection overflow issue when combining MHD_USE_NO_LISTEN_SOCKET
+    with MHD_USE_THREAD_PER_CONNECTION (#6036).
+    Updated m4 script to fix FTBFS when using -Werror=unused-but-set-parameter (#6078).
+    Releasing libmicrohttpd 0.9.70. -CG
+
+Thu Dec 26 14:43:27 CET 2019
+    Adding fix for urlencoding of keys without values in
+    post-processor logic. -CG
+
+Tue 24 Dec 2019 03:32:18 PM CET
+    Adding patch from Ethan Tuttle with test case for urlencoding
+    in post-processor for keys without values. -CG/ET
+
+Sun 15 Dec 2019 02:12:02 PM CET
+    Fix send() call (affects Mac OS X). #5977 -CG/fbrault
+    Releasing libmicrohttpd 0.9.69. -CG
+
+Fri 29 Nov 2019 11:22:25 PM CET
+    If application suspends a connection before we could send 100 CONTINUE,
+    give application another shot at queuing a reply before the upload begins. -CG
+
+Sat 26 Oct 2019 06:53:05 PM CEST
+    Fix regression where MHD would fail to return an empty response
+    when used with HTTPS.
+    Releasing libmicrohttpd 0.9.68. -CG/TR
+
+Fri 25 Oct 2019 02:31:59 PM CEST
+    Introduce MHD_RF_INSANITY_HEADER_CONTENT_LENGTH. -CG
+
+Thu 17 Oct 2019 04:50:52 PM CEST
+    Integrate 0-byte send() method for uncorking for old FreeBSD/OS X
+    systems into new mhd_send.c logic for uncorking.
+    Releasing libmicrohttpd 0.9.67. -CG
+
+Fri 18 Aug 2019 00:00:00 PM UTC
+    Fixes and optimizations for the setsockopt handling:
+    * Added: MHD_UPGRADE_ACTION_CORK_ON and MHD_UPGRADE_ACTION_CORK_OFF
+      to enum MHD_UpgradeAction (turn corking on/off on the underlying
+      socket).
+    * Use calls and flags native to the system for corking and
+      other operations, tested with performance improvements on
+      FreeBSD, Debian Linux, NetBSD, and cygwin. In particular,
+      this adds selective usage of MSG_MORE, NODELAY, TCP_NOPUSH,
+      TCP_CORK. -ng0
+
+Fri 09 Aug 2019 10:07:27 AM CEST
+    Copy compiler and linker hardening flags from GNUnet (updating
+    configure.ac). -CG
+
+Thu 01 Aug 2019 01:23:36 PM CEST
+    Releasing libmicrohttpd 0.9.66. -CG
+
+Thu 01 Aug 2019 12:53:49 AM CEST
+    Fix issue with discarding unhandled upload data discovered
+    by Florian Dold. -CG
+
+Mon 29 Jul 2019 08:01:50 PM CEST
+    Fix hanging situation with large transmission over upgraded
+    (i.e. Web socket) connection with epoll() and HTTPS enabled
+    (as reported by Viet on the mailinglist). -CG
+
+Thu 25 Jul 2019 02:40:12 PM CEST
+    Fixing regression introduced in cc5032b85 (bit mask matching
+    of the header kinds in MHD_lookup_connection_value()), as
+    reported by Jose Bollo on the mailinglist. -CG/JB
+
+Tue Jul 16 19:56:14 CEST 2019
+    Add MHD_OPTION_HTTPS_CERT_CALLBACK2 to allow OCSP stapling
+    and MHD_FEATURE_HTTPS_CERT_CALLBACK2 to check for. -TR
+
+Fri Jul 05 2019 22:30:40 MSK
+	Releasing libmicrohttpd 0.9.65. -EG
+
+Sun Jun 23 2019 21:27:43 MSK
+	Many fixes and improvements for connection-specific memory pool:
+	* Added asserts;
+	* Added testing of reallocation;
+	* Reallocation code rewritten to avoid extra allocation, when
+	  possible to reuse already allocated memory;
+	* Large memory pools aligned to system page size;
+	* Large memory pools on W32 are cleared more securely after use,
+	  optimised usage of system memory.
+	Better handled connection's memory shortage situations:
+	* error response could be sent to client even if all buffer space
+	  was used;
+	* if buffer space become low when receiving, do not allocate last
+	  buffer space and use small receive blocks instead.
+	Improved sending speed by using all available buffer space for
+	sending. -EG
+
+Sun Jun 09 2019 20:27:04 MSK
+	Releasing libmicrohttpd 0.9.64. -EG
+
+Sun Jun 09 2019 20:03:16 MSK
+	Updated HTTP headers, methods and status codes from registries,
+	Added scripts to import new headers, methods and status codes from
+	registries,
+	Minor doxyget comment fix,
+	Added missing MSVS project files to tarball.
+	Reodered includes in microhttpd.h -EG
+
+Mon 03 Jun 2019 11:45:52 PM CEST
+	Apply MHD_-prefix to hash functions, even if they are not in the
+	officially exported API. -CG/DB
+
+Sun Jun 02 01:52:11 MSK 2019
+	Support usage of SOCK_NOSIGPIPE on Solaris 11.4 and NetBSD 7+,
+	finally avoid SIGPIPE on Solaris. -EG
+
+Sat Jun 01 22:51:50 MSK 2019
+	Do not report errors if AF_UNIX socket is used on *BSD. -EG
+
+Thu May 30 23:32:09 MSK 2019
+	Improved detection of 'getsockname()' in configure.
+	Avoided using 'getsockname()' in code if not detected. -EG
+
+Sun May 26 23:32:49 MSK 2019
+	Fixed some tests on W32. -EG
+
+Sun May 26 23:05:42 MSK 2019
+	Better detection of sockaddr member in configure, fixed build on *BSD,
+	Fixed compiler warnings,
+	Updated and fixed libcurl tests. -EG
+
+Tue May 21 22:12:43 MSK 2019
+	Fixed doxygen comments,
+	Avoid dropping 'const' qualifier in macros,
+	Fixed some compiler warnings,
+	Properly support automatic port detections on some platforms,
+	Added checks for too long TLS parameters strings. -EG
+
+Tue May 21 17:52:48 MSK 2019
+	Spelling fixes. -EG
+
+Mon May 20 15:39:35 MSK 2019
+	Compiler warning fixes. -EG/CG
+	Fixed example for non-64bits platforms. -EG
+
+Wed May 15 23:51:49 MSK 2019
+	Optimized and improved processing speed by using precalculated and
+	already calculated lengths of strings. -EG
+
+Wed May 15 14:54:00 MSK 2019
+	Fixed build from source on GNU Hurd. -EG
+
+Mon May  6 11:58:00 MSK 2019
+	Updated README and COPYING files. MHD remains LGPLv2.1-licensed. -EG
+
+Fri May  3 20:08:00 MSK 2019
+	Store connection's keys and values with sizes;
+	Speedup keys search be comparing key length first;
+	Added functions for working with keys and values with binary zeros;
+	Fixed test_postprocessor_amp to fail on problems. -EG
+
+Wed May  1 16:40:00 MSK 2019
+	Reverted change of MHD_KeyValueIterator, implemented MHD_KeyValueIteratorN
+	with sizes for connection's key and value to get keys and values
+	with binary zeros. -EG
+
+Mon 29 Apr 2019 01:26:39 AM BRT
+	Fixed signed/unsigned comparison in example http_chunked_compression.c. -SC/TR
+
+Sun Apr 21 16:40:00 MSK 2019
+	Improved compatibility with MSVC compilers;
+	Fixed MHD compilation by Clang/LLVM in VS;
+	Used MSVC intrinsics for bit rotations and bytes swap;
+	Added project files for VS2019. -EG
+
+Fri Apr 19 23:00:00 MSK 2019
+	Rewritten SHA-256 calculations from scratch to avoid changing LGPL version;
+	Added usage of GCC/Clang built-ins for bytes swap to significantly improve
+	speed of MD5 and SHA-256 calculation on platforms with known endianness.
+	Added test for SHA-256 calculations. -EG
+
+Wed Apr 17 20:52:00 MSK 2019
+	Refactoring of mhd5.c: optimized, dead code removed;
+	Faster MD5 calculation on little endian platforms;
+	Bit manipulations moved to separate header file.
+	Added tests for MD5 calculations. -EG
+
+Mon 15 Apr 2019 05:33:52 PM CEST
+	Add MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT and
+	MHD_USE_INSECURE_TLS_EARLY_DATA flags. -CG
+
+Thu Apr 11 11:37:00 MSK 2019
+	Fixed MSVC 'Release' builds;
+	Fixed usage of MSVC's assert. -EG
+
+Wed Apr 10 14:31:00 MSK 2019
+	Improved shell compatibility for 'bootstrap', removed bash-ism.
+	Added wrapper script 'autogen.sh'. -EG
+
+Mon 08 Apr 2019 03:06:05 PM CEST
+	Fix close() checks as suggested by MK on the mailinglist
+        (#3926). -MK/CG
+
+Wed 20 Mar 2019 10:20:24 AM CET
+	Adding additional "value_length" argument to MHD_KeyValueIterator
+	callback to support binary zeros in values.  This is done in a
+	backwards-compatible way, but may require adding a cast to existing
+	code to avoid a compiler warning. -CG
+
+Sun Feb 10 21:00:37 BRT 2019
+	Added example for how to compress a chunked HTTP response. -SC
+
+Sun 10 Feb 2019 05:03:44 PM CET
+	Releasing libmicrohttpd 0.9.63. -CG
+
+Sat 09 Feb 2019 01:51:02 PM CET
+	Extended test_get to test URI logging and query string parsing
+	to avoid regression fixed in previous patch in the future. -CG
+
+Thu Feb  7 16:16:12 CET 2019
+	Preliminary patch for the raw query string issue, to be tested. -CG
+
+Tue Jan  8 02:57:21 BRT 2019
+	Added minimal example for how to compress HTTP response. -SC
+
+Wed Dec 19 00:06:03 CET 2018
+	Check for GNUTLS_E_AGAIN instead of GNUTLS_E_INTERRUPTED when
+	giving up on a TLS connection. -LM/CG
+
+Thu Dec 13 22:48:14 CET 2018
+	Fix connection timeout logic if in thread-per-connection mode the
+	working thread takes longer than the timeout to queue the response. -CG
+
+Tue Dec 11 09:58:32 CET 2018
+	Add logic to avoid VLA arrays with compilers that do not support them. -CG
+
+Sat Dec  8 23:15:53 CET 2018
+	Fixed missing WSA_FLAG_OVERLAPPED which can cause W32 to block on
+	socket races when using threadpool. (See very detailed description
+	of the issue in the libmicrohttpd mailinglist post of today.) -JM
+
+Sat Dec  8 22:53:56 CET 2018
+	Added test for RFC 7616 and documented new API.
+	Releasing libmicrohttpd 0.9.62. -CG
+
+Sat Dec  8 17:34:58 CET 2018
+	Adding support for RFC 7616, experimental, needs
+	testing and documentation still! -CG
+
+Fri Dec  7 12:37:17 CET 2018
+	Add option to build MHD without any threads
+	and MHD_FEATURE_THREADS to test for it.  -CG
+
+Thu Dec  6 13:25:08 BRT 2018
+	Renamed all occurrences from _model(s)_ to _mode(s)_. -SC
+
+Thu Dec  6 12:50:11 BRT 2018
+	Optimized the function MHD_create_response_from_callback() for
+	Windows by increasing its internal buffer size and allowed to customize
+	it via macro MHD_FD_BLOCK_SIZE. -SC
+
+Thu Dec  6 02:11:15 BRT 2018
+	Referenced the gnutls_load_file() function in the HTTPs examples. -SC
+
+Wed Dec  5 18:08:59 CET 2018
+	Fix regression causing URLs to be unescaped twice. -CG
+
+Sun Nov 18 13:08:11 CET 2018
+	Parse arguments with (properly) escaped URLs correctly.
+	(making things work with recent cURL changes, #5473).
+	Replace sprintf with snprintf in testcases.
+	Releasing libmicrohttpd 0.9.61. -CG
+
+Wed Nov 14 14:01:21 CET 2018
+	Fix build issue with GnuTLS < 3.0. -CG
+
+Mon Nov 12 19:50:43 CET 2018
+	Fix #5473 (test case failure due to change in libcurl). -eworm
+
+Thu Nov  8 14:53:27 CET 2018
+	Add MHD_create_response_from_buffer_with_free_callback. -CG
+
+Tue Nov  6 19:43:47 CET 2018
+	Upgrading to gettext 0.19.8.
+	Releasing libmicrohttpd 0.9.60. -CG
+
+Thu Nov  1 16:29:59 CET 2018
+	Enable using epoll() without listen socket. -JB
+
+Sat Oct 20 12:44:16 CEST 2018
+	In thread-per-connection mode, signal main thread for
+	thread termination for instant clean-up and application
+	notification about closed connections. -CG
+
+Tue Oct 16 20:43:41 CEST 2018
+	Add MHD_RF_HTTP_VERSION_1_0_RESPONSE option to make MHD
+	act more like an HTTP/1.0 server. -GH
+
+Fri Oct  5 18:44:45 CEST 2018
+	MHD_add_response_header() now prevents applications from
+	setting a "Transfer-Encoding" header to values other than
+	"identity" or "chunked" as other transfer encodings are
+	not supported by MHD. (Note that usually MHD will pick the
+	transfer encoding correctly automatically, but applications
+	can use the header to force a particular behavior.)
+	Fixing #5411 (never set Content-length if Transfer-Encoding
+	is given). -CG
+
+Sat Jul 14 11:42:15 CEST 2018
+	Add MHD_OPTION_GNUTLS_PSK_CRED_HANDLER to allow use of PSK with
+	TLS connections. -CG/TM
+
+Sat Jul 14 11:03:37 CEST 2018
+	Integrate patch for checking digest authentication based on
+	a digest, allowing servers to store passwords only hashed.
+	Adding new function MHD_digest_auth_check_digest(). -CG/DB
+
+Sat Mar 10 12:15:35 CET 2018
+	Upgrade to gettext-0.19.8.1. Switching to more canonical
+	gettext integration. -CG
+
+Fri Mar  2 21:44:24 CET 2018
+	Ensure MHD_RequestCompletedCallback is always called from
+	the correct thread (even on shutdown and for upgraded connections). -CG
+
+Tue Feb 27 23:27:02 CET 2018
+	Ensure MHD_RequestCompletedCallback is also called for
+	upgraded connections. -CG
+
+Fri Feb 16 03:09:33 CET 2018
+	Fixing #5278 as suggested by reporter. -CG/texec
+
+Thu Feb  1 10:12:22 CET 2018
+	Releasing GNU libicrohttpd 0.9.59. -CG
+
+Thu Feb  1 08:39:50 CET 2018
+	Fix masking operation. -CG/silvioprog
+
+Mon Jan 29 17:33:54 CET 2018
+	Fix deadlock when failing to prepare chunked response
+	(#5260). -CG/ghaderer
+
+Thu Jan  4 12:24:33 CET 2018
+	Fix __clang_major__ related warnings for non-clang
+	compilers reported by Tim on the mailinglist. -CG
+
+Mon Dec 11 17:11:00 MSK 2017
+	Fixed tests on platforms with huge number of CPUs.
+	Doxygen configuration was updated.
+	Various doxygen fixes. -EG
+
+Mon Dec 07 21:08:00 MSK 2017
+	Releasing GNU libmicrohttpd 0.9.58. -EG
+
+Mon Dec 07 16:01:00 MSK 2017
+	Fixed HTTPS tests on modern platforms. -EG
+
+Mon Dec 04 15:43:00 MSK 2017
+	Minor documentation installation fixes. -EG
+
+Mon Nov 27 22:58:38 CET 2017
+	Tolerate AF_UNIX when trying to determine our binding port
+	from socket.  Use `sockaddr_storage` instead of trying to
+	guess the sockaddr type before calling getsockname(). -CG
+
+Mon Nov 27 22:24:00 MSK 2017
+	Releasing GNU libmicrohttpd 0.9.57. -EG
+
+Mon Nov 27 21:36:00 MSK 2017
+	Updated README. -EG
+
+Mon Nov 27 18:37:00 MSK 2017
+	Corrected names in W32 DLL resources.
+	Reordered and clarified configure summary message.
+	Additional compiler warning mutes for builds with various configure
+	parameters.
+	Fixed tests on Cygwin.
+	Used larger SETSIZE for Cygwin (same value as for native W32).
+	Minor fixes for Cygwin.
+	Added configure parameter to force disable usage of sendfile().
+	Minor testsuite fixes.
+	Really fixed builds with optimisation for size. -EG
+
+Sat Nov 25 18:37:00 MSK 2017
+	Fixed build with optimisation for size. -EG
+
+Fri Nov 24 20:14:02 CET 2017
+	Releasing GNU libmicrohttpd 0.9.56. -CG
+
+Thu Nov 23 17:40:00 MSK 2017
+	Added MHD_FEATURE_SENDFILE enum value and report. -EG
+
+Thu Nov 23 08:56:00 MSK 2017
+	Fixed receiving large requests in TLS mode with epoll.
+	Improved GnuTLS and libgcrypt detection in configure, do not ignore
+	flags in GNUTLS_{CFLAGS,LIBS} variables.
+	Added special trick for Solaris/Openindiana to find GnuTLS-3 with
+	right bitness.
+	Added support for Solaris sendfile(3) function.
+	Fixed dataraces with thread ID on W32 and pthread. Now check for
+	correct thread in MHD_queue_response() works correctly.
+	Fixed and silenced compiler warnings in tests and examples.
+	Removed usage of TLS flags in examples where TLS is not required.
+	Added support for MultiSSL in https tests with libcurl >= 7.56.0.
+	Improved detection of OFF_T_MAX, SIZE_MAX. Added macros for
+	SSIZE_MAX in mhd_limits.h. There are some platforms that really
+	require those macros.
+	Added support for Darwin's sendfile() function.
+	Updated .gitignore files.
+	Reworked mhd_sys_extentions.m4 with better support of modern
+	platforms, more reliable detection of required macros, and
+	detection of disabling of system-specific features by
+	_XOPEN_SOURCE macro. -EG
+
+Wed Nov  1 20:43:00 MSK 2017
+	Mixed and muted many compiler warnings. Now GCC's flags
+	-Wall -Wextra could be used for building.
+	Fixed compilation of examples without libmagic.
+	Better detection of libgnutls in configure.
+	Reworked launch of nested configure in "po" directory to
+	prevent useless reconfiguration.
+	Fixed some wrong asserts.
+	Enabled "test_options" test.
+	Use "test_start_stop" without libcurl.
+	Use chunks with sendfile() to prevent locking thread for
+	single connection with large file.
+	Added support for FreeBSD's sendfile with additional
+	optimisations for FreeBSD 11.
+	Refactoring and improvements for MHD_start_daemon_va() and
+	MHD_stop_daemon().
+	Fixed testing with GnuTLS >= 3.6.0. -EG
+
+Mon Oct  9 22:38:07 CEST 2017
+	Add MHD_free() to allow proper free()-ing of username/password
+	data returned via MHD_digest_auth_get_username() or
+	MHD_basic_auth_get_username_password() on Windows. -CG
+
+Tue Sep 26 14:00:58 CEST 2017
+	Fixing race involving setting "at_limit" flag. -CG
+
+Tue Sep 08 21:39:00 MSK 2017
+	Fixed build of examples when MHD build with non-pthread lib.
+	MHD_queue_response(): added check for using in correct thread.
+	Fixed sending responses larger 16 KiB in TLS mode with epoll.
+	Improved doxy for MHD_get_timeout() and related functions.
+	Minor internal refactoring. -EG
+
+Tue Jul 23 11:32:00 MSK 2017
+	Updated chunked_example.c to provide real illustration of usage of
+	chunked encoding. -EG
+
+Thu Jul 13 21:41:00 MSK 2017
+	Restored SIGPIPE suppression in TLS mode.
+	Added new value MHD_FEATURE_AUTOSUPPRESS_SIGPIPE so application could
+	check whether SIGPIPE handling is required.
+	Used GNUTLS_NONBLOCK for TLS sessions. -EG
+
+Tue Jun 20 23:52:00 MSK 2017
+	Libgcrypt is now optional and required only for old GnuTLS versions. -EG
+
+Wed Jun 14 21:42:00 MSK 2017
+	Added support for debug assert() and new configure parameter
+	--enable-asserts for debug builds.
+	Removed non-functional Symbian support. -EG
+
+Mon Jun 05 23:34:00 MSK 2017
+	More internal refactoring:
+	merged MHD_tls_connection_handle_read/write() with non-TLS version,
+	reduced and unified number of layers for network processing (before
+	refactoring MHD_tls_connection_handle_read->MHD_connection_handle_read->
+	do_read->recv_tls_adapter->GnuTLS->recv_param_adapter - 5 MHD layers;
+	after refactoring MHD_connection_handle_read->recv_tls_adapter->GnuTLS -
+	2 MHD layers),
+	simplified and removed dead code from
+	MHD_connection_handle_read/write() without functional change. -EG
+
+Mon Jun 05 22:20:00 MSK 2017
+	Internal refactoring:
+	used TCP sockets directly with GnuTLS (performance improvement),
+	moved some connection-related code from daemon.c to
+	connection.c/connection_https.c,
+	removed hacks around sendfile() and implemented correct support of
+	sendfile(),
+	removed do_read() and do_write() to reduce number of layer around send()
+	and recv() and to improve readability and maintainability of code,
+	implemented separate tracking of TLS layer state, independent of HTTP
+	connection stage. -EG
+
+Sun Jun 04 15:02:00 MSK 2017
+	Improved thread-safety of MHD_add_connection() and
+	internal_add_connection(), minor optimisations. -EG
+
+Sun May 28 23:26:00 MSK 2017
+	Releasing GNU libmicrohttpd 0.9.55. -EG
+
+Sun May 21 18:48:00 MSK 2017
+	Fixed build with disabled "UPGRADE".
+	Fixed possible null-dereference in HTTPS test.
+	Fixed compiler warning in process_request_body(), minor optimizations.
+	Do not allow suspend of "upgraded" connections.
+	Fixed returned value for MHD_CONNECTION_INFO_CONNECTION_SUSPENDED.
+	Fixed removal from timeout lists of non-existing connections in
+	cleanup_connection().
+	Fixed double locking of mutex. -EG
+
+Sun May 14 15:05:00 MSK 2017
+	Fixed resuming connections and closing upgraded connections in select()
+	mode with thread-per-connection. -EG
+
+Sun May 14 14:49:00 MSK 2017
+	Removed extra call to resume connections in MHD_run().
+	Handle resumed connection without delay in epoll mode.
+	Update states of resumed connection after resume in thread-per-connection
+	mode.
+	Fixed resuming connections and closing upgraded connections in poll()
+	mode with thread-per-connection. -EG
+
+Thu May 11 22:37:00 MSK 2017
+	Faster start really processing data in resumed connections. -EG
+
+Thu May 11 14:24:00 MSK 2017
+	Do not add any "Connection" headers for "upgrade" connections. -EG
+
+Wed May 10 23:09:00 MSK 2017
+	Resume resuming connection before other processing in external polling
+	mode. -EG
+
+Tue May  9 23:16:00 MSK 2017
+	Fixed: Do not add "Connection: Keep-Alive" header for "upgrade"
+	connections. -EG
+
+Tue May  9 21:01:00 MSK 2017
+	Fixed: check all "Connection" headers of request for "Close" and "Upgrade"
+	tokens instead of using only first "Connection" header with full string
+	match. -EG
+
+Tue May  9 12:28:00 MSK 2017
+	Revert: continue match footers in MHD_get_response_header() for backward
+	compatibility. -EG
+
+Mon May  8 19:30:00 MSK 2017
+	Fixed: use case-insensitive matching for header name in
+	MHD_get_response_header(), match only headers (not footers). -EG
+
+Fri May  5 20:57:00 MSK 2017
+	Fixed null dereference when connection has "Upgrade" request and
+	connection is not upgraded.  -JB/EG
+	Better handle Keep-Alive/Close. -EG
+
+Tue May  2 18:37:53 CEST 2017
+	Update manual. -CG
+	Add MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE.
+	Releasing GNU libmicrohttpd 0.9.54. -CG
+
+Thu Apr 27 22:31:00 CEST 2017
+	Replaced flags MHD_USE_PEDANTIC_CHECKS and MHD_USE_PERMISSIVE_CHECKS by
+	single option MHD_OPTION_STRICT_FOR_CLIENT. Flag MHD_USE_PEDANTIC_CHECKS
+	is still supported. -EG
+
+Tue Apr 26 15:11:00 CEST 2017
+	Fixed shift in HTTP reasons strings.
+	Added test for HTTP reasons strings. -EG
+
+Tue Apr 25 19:11:00 CEST 2017
+	Allow flag MHD_USE_POLL with MHD_USE_THREAD_PER_CONNECTION and without
+	flag MHD_USE_INTERNAL_POLLING_THREAD for backward compatibility. -EG
+
+Mon Apr 24 17:29:45 CEST 2017
+	Enforce RFC 7230's rule on no whitespace by default,
+	introduce new MHD_USE_PERMISSIVE_CHECKS to disable. -CG
+
+Sun Apr 23 20:05:44 CEST 2017
+	Enforce RFC 7230's rule on no whitespace in HTTP header
+	field names if MHD_USE_PEDANTIC_CHECKS is set. -CG
+
+Sun Apr 23 19:20:33 CEST 2017
+	Replace remaining occurrences of sprintf() with
+	MHD_snprintf_(). Thanks to Ram for pointing this out. -CG
+
+Sat Apr 22 20:39:00 MSK 2017
+	Fixed builds in Linux without epoll.
+	Check for invalid --with-thread= configure parameters.
+	Fixed support for old libgcrypt on W32 with W32 threads. -EG
+
+Tue Apr 11 22:17:00 MSK 2017
+	Releasing GNU libmicrohttpd 0.9.53. -EG
+
+Mon Apr 10 19:50:20 MSK 2017
+	HTTPS tests: skip tests instead of failing if HTTPS is not supported by
+	libcurl.
+	HTTPS tests: fixed return values so testsuite is able to correctly
+	interpret it.
+	Fixed ignored result of epoll test in test_https_get_select. -EG
+
+Thu Apr 06 23:02:07 MSK 2017
+	Make zzuf tests compatible with *BSD platforms. -EG
+
+Thu Apr 06 22:14:22 MSK 2017
+	Added warning for hypothetical extra large timeout.
+	Fixed incorrect timeout calculation under extra rare conditions.
+	Fixed accidental usage of IPv6 in testsuite in specific conditions. -EG
+
+Wed Apr 05 14:14:22 MSK 2017
+	Updated autoinit_funcs.h to latest upstream version with proper support of
+	Oracle/Sun compiler. -EG
+
+Wed Apr 05 12:53:26 MSK 2017
+	Fixed some compiler warnings.
+	Fixed error snprintf() errors detection in digestauth.c.
+	Converted many run-time 'strlen()' to compile-time calculations. -EG
+
+Sun Mar 26 13:49:01 MSK 2017
+	Internal refactoring for simplification and unification.
+	Minor optimizations and minor fixes.
+	MHD_USE_ITC used again in thread pool mode. -EG
+
+Sat Mar 25 20:58:24 CET 2017
+	Remove dead MHD_strx_to_sizet-functions and associated
+	test cases from code. -CG
+
+Sat Mar 25 20:40:10 CET 2017
+	Allow chunk size > 16 MB (up to 2^64-1). Ignore
+	chunk extensions instead of triggering an error.
+	(fixes #4967). -CG
+
+Tue Mar 25 20:59:18 MSK 2017
+	Check for invalid combinations of flags and options in
+	MHD_start_daemon(). -EG
+
+Tue Mar 21 13:51:04 CET 2017
+	Use "-lrt" to link libmicrohttpd if we are using
+	clock_gettime() as needed by glibc < 2.17. -CG
+
+Tue Mar 21 13:42:07 CET 2017
+	Allow chaining of suspend-resume calls withuot
+	the application processing data from the network. -CG
+
+Mon Mar 20 0:51:24 MSK 2017
+	Added autoconf module for detection whatever shutdown of listening socket
+	trigger select. This is only reliable method to use such feature as some
+	platforms change behaviour from version to version. -EG
+
+Sun Mar 19 13:57:30 MSK 2017
+	Rewritten logic of handling "upgraded" TLS connections in epoll mode:
+	used edge trigger instead of level trigger,
+	upgraded "ready" connection are stored in DL-list,
+	fixed handling of more than 128 ready connections,
+	fixed busy-waiting for idle "upgraded" TLS connections. -EG
+
+Fri Mar 17 10:45:31 MSK 2017
+	If read buffer is full, MHD need to receive remote data and application
+	suspended connection, do not fail while connection is suspended and give
+	application one more chance to read data from buffer once connection is
+	resumed. -EG
+
+Thu Mar 16 23:45:29 MSK 2017
+	Allow again to run MHD in external epoll mode by
+	MHD_run_from_select() - this allow unification of user code
+	and produce no harm for performance. Especially useful with
+	MHD_USE_AUTO flag. -EG
+
+Thu Mar 16 23:12:07 MSK 2017
+	Idle connection should be disconnected *after* "timeout" number of
+	second, not *before* this number. -EG/VT
+
+Thu Mar 16 22:31:54 MSK 2017
+	Unified update of last activity on connections.
+	Update last activity only if something is really transmitted.
+	Update last activity each time when something is transmitted.
+	Removed early duplicated check for timeout on HTTPS connections.
+	Removed update of last active time for connections without timeout.
+	Fixed reset of timeout timer on resumed connections.
+	Fixed never-expired timeouts on HTTPS connections.
+	Fixed thread-safety of MHD_set_connection_option(). -EG
+
+Thu Mar 16 21:05:08 MSK 2017
+	Fixed minor bug resulted in slight slowdown of HTTPS connection
+	handshake. -EG
+
+Thu Mar 16 20:35:59 MSK 2017
+	Improved thread-safety for DL-lists. -EG
+
+Thu Mar 16 17:55:01 MSK 2017
+	Fixed thread-safety of MHD_get_daemon_info() for
+	MHD_DAEMON_INFO_CURRENT_CONNECTIONS. -EG
+
+Thu Mar 16 16:49:07 MSK 2017
+	Added ability to get actual daemon flags via MHD_get_daemon_info().
+	Fixed test_upgrade to work in request mode.
+	Fixed compiler warnings in test_upgrade. -EG
+
+Wed Mar 15 23:29:59 MSK 2017
+	Prevented socket read/write if connection is suspended.
+	Added missing resets of 'connection->in_idle'.
+	Reworked handling of suspended connection: ensure that
+	connection is not disconnected by timeout, always
+	updated read/write states right after suspending. -EG
+
+Wed Mar 15 21:02:26 MSK 2017
+	Added new enum value MHD_CONNECTION_INFO_CONNECTION_TIMEOUT
+	to get connection timeout by MHD_get_connection_info(). -EG
+
+Sat Mar 11 12:03:45 CET 2017
+	Fix largepost example from tutorial to properly generate
+	error pages. -CG
+	Fix largepost example, must only queue replies either before upload
+	happens or after upload is done, not while upload is ongoing
+
+Fri Mar 10 16:37:12 CET 2017
+	Fix hypothetical integer overflow for very, very large
+	timeout values. -CG
+
+Fri Mar 10 16:22:54 CET 2017
+	Handle case that we do not listen at all more gracefully
+	in MHD_start_daemon() and not pass '-1' to helper functions
+	that expect a valid socket. -CG
+
+Tue Mar  7 12:11:44 BRT 2017
+	Updates file `.gitignore`.
+
+Tue Mar  7 10:37:45 BRT 2017
+	Updated the MHD_OPTION_URI_LOG_CALLBACK's documentation.
+
+Mon Mar  6 21:46:59 BRT 2017
+	Added the i18n example fixing #4924. -SC
+
+Wed Mar 1 23:47:05 CET 2017
+	Minor internal optimisations.
+	Changed closure connection monitoring logic: now all connections are
+	monitored for OOB data (which treated as error), connections are not
+	monitored any more for incoming data if incoming data is not required for
+	processing. except_fd_set is not optional now for MHD_get_fdset(),
+	MHD_get_fdset2() and MHD_run_from_select().
+	Improved connection processing in epoll mode: now connection can process
+	both read and write each turn.
+	Updated HTTP response codes; updated and added all missing standard HTTP
+	headers names (and headers categories); updated and added all missing
+	standard and additional HTTP methods. Now MHD return status
+	MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE (431) instead of old
+	MHD_HTTP_REQUEST_ENTITY_TOO_LARGE (413) for very long header.
+	Reworked handling of data pending in TLS buffers, resolved busy-waiting
+	if incoming data is pending in TLS buffers and connection is in
+	LOOP_INFO_WRITE mode.
+	Do not clear 'ready' flag in epoll mode if send()/recv() result is
+	EINTERRUPTED.
+	Better detection of unready connection state: used less number of calls of
+	recv()/send() in epoll mode.
+	Configure: do not run gcrypt and GnuTLS tests if HTTPS is disabled by
+	configure parameter.
+	Fixed wrong value returned by MHD_get_timeout().
+	All double-linked lists now walked from tail to head. As new items are
+	added to head, this result in more uniform processing time.
+	Improved sockets errors handling in epoll mode.
+	OOB data on 'upgraded' sockets is treated as error. -EG
+
+Thu Feb 16 11:20:05 CET 2017
+	Replace tsearch configure check with code from gnulib. -CG
+
+Wed Feb 15 13:35:36 CET 2017
+	Fixing a few very rare race conditions for thread-pool or
+	thread-per-connection operations during shutdown.
+	Various minor cosmetic improvements.
+	Fixed #4884 and #4888 (solaris portability issues). -CG
+
+Wed Feb 08 22:33:10 MSK 2016
+	Ported test_quiesce_stream to W32.
+	Improved precompiler flags selection of OpenBSD.
+	Fixed sending responses backed by files not supported by sendfile().
+	Fixed thread safety for responses backed by file FD.
+	Updated fileserver_example.
+	Improved handling of 'upgraded' TLS forwarding in select() and poll()
+	modes.
+	Fixed processing of incoming TLS data in epoll mode if more than 128
+	connections are active.
+	Fixed accepting more than 128 incoming connection in epoll mode.
+	Improved test_large_put, added poll() and epoll testing.
+	Added test_large_put_inc for testing of incremental buffer processing.
+	Rewritten epoll connection processing logic: handle all connection one
+	time per turn instead of trying to handle all active connection until all
+	pending data is dried. Result is more uniform connection processing
+	period. -EG
+
+Wed Nov 23 15:24:10 MSK 2016
+	Used SO_REUSEADDR (on non-W32) alongside with SO_REUSEPORT if option
+	MHD_OPTION_LISTENING_ADDRESS_REUSE was set. -EG
+
+Wed Nov 23 12:48:23 MSK 2016
+	Move all gettext-related staff to 'po' subdirectory.
+	Excluded gettext files generation from normal build.
+	Removed generated files from GIT. -EG
+
+Tue Nov 15 19:08:43 MSK 2016
+	Fixed forwarding "upgraded" TLS connections for
+	chunks sizes larger than buffer size. -EG
+
+Mon Nov 14 22:18:30 MSK 2016
+	Fixed unintentional usage of SO_REUSEADDR on W32.
+	Added support for SO_EXCLBIND on Solaris.
+	Fixed using MHD with MHD_OPTION_LISTENING_ADDRESS_REUSE
+	on Linux kernels before 3.9 (longterm 3.2 and 3.4
+	are still supported). -EG
+
+Sun Nov 13 19:16:38 CET 2016
+	Fixed a few race issues on suspend-resume in cases where the
+	application uses threads even though MHD did not (or at least
+	had no internal need for locking). Also fixed DLL handling of
+	the timeout list, avoiding manipulating it for suspended
+	connections.  Finally, eliminated calling application logic
+	on suspended connections (which before could happen under
+	certain circumstances). -CG
+
+Thu Nov 11 20:49:23 MSK 2016
+	Added support for various forms of
+	pthread_attr_setname_np() so thread names will be set
+	more efficiently on certain platforms (Solaris, NetBSD etc.) -EG
+
+Thu Nov 10 21:50:35 MSK 2016
+	Added rejection in MHD_start_daemon() of invalid combinations
+	of daemon flags.
+	Added MHD_USE_AUTO and MHD_USE_AUTO_INTERNAL_THREAD for
+	automatic selection of polling function depending on
+	platform capabilities and requested mode. -EG
+
+Thu Nov 10 17:49:56 MSK 2016
+	Ported "upgrade" tests to W32 and other platforms, used
+	"gnutls-cli" instead of "openssl" in tests, minor bugs
+	fixed, added verbose reporting if requested.
+	"Upgrade" processing - changed internal handling logic, improved
+	and refactored, bugs fixed, fixed sigpipe on Darwin, added
+	printing error to log, fixed compilation without HTTPS.
+	Added 'configure' parameter "--disable-httpupgrade" for building
+	minimal-sized MHD versions.
+	Added feature check "MHD_FEATURE_UPGRADE".
+	Responses destroyed (freed) earlier if possible.
+	Added many remarks in code comments about thread safety.
+	Some data races and other multithread-related issues are fixed,
+	including usage of closed sockets (may resulted in accidental closing
+	of wrong socket).
+	SO_NOSIGPIPE is used on all platform which support it, not only
+	on Darwin.
+	Added support for suspending connections in thread-per-connection
+	mode (itself almost useless, mostly to unify modes support).
+	Fixed Inter-Thread Communication channel usage in epoll modes.
+	Reworked daemon cleanups and handling MHD_stop_daemon(): resources
+	are freed only by specific threads, data races and other fixes.
+	Started usage of C99 standard 'bool' where supported with
+	fallback to 'int'.
+	Renamed many MHD flags. Now they are self-explainable and more
+	obvious, like MHD_USE_INTERNAL_POLLING_THREAD instead of
+	MHD_USE_SELECT_INTERNALLY. Old flag names are supported for
+	backward compatibility.
+	Improved processing of "fast" connections: now full sequence
+	"read request - send reply headers - send reply body" is processed
+	after single select()/poll(). If connection is slow, request is huge
+	or response in not immediately ready - connection will be processed
+	in "traditional" way.
+	Added usage of "calloc()" where supported.
+	Minor documentation fixes.
+	Minor improvements and fixes. -EG
+	"Upgrade" test fixes.
+	Documentation updated.
+	Added HTTP "Upgrade" example. -CG
+
+Mon Oct 17 19:08:18 CEST 2016
+	Fixed misc. issues relating to upgrade.
+	Releasing experimental 0.9.52. -CG
+
+Wed Oct 12 14:26:20 CEST 2016
+	Migrated repository from Subversion to Git. -CG
+
+Tue Oct 11 18:09:56 CEST 2016
+	Deprecated MHD_USE_SSL, use MHD_USE_TLS instead. -CG
+
+Tue Oct 11 18:14:40 MSK 2016
+	Code internal refactoring: 'pipes' renamed to 'inter-thread
+	communication (channels)/ITCs', as code can use different types
+	of communications.
+	Optimizations: ITCs now always created in non-blocking mode.
+	Added configure parameter to choose ITC type.
+	Updated documentation and comments.
+	Minor errors fixed (related to heavy load). -EG
+
+Thu Sep 22 17:51:04 CEST 2016
+	Implementing support for eventfd() instead of pipe() for
+	signaling (on platforms that support it); fixing #3557. -CG
+
+Thu Sep 22 11:03:43 CEST 2016
+	Simplify internal error handling logic by folding it into the
+	MHD_socket_close_, MHD_mutex_lock_, MHD_mutex_unlock_ and
+	MHD_mutex_destroy_ functions. -CG
+
+Tue Sep 13 22:20:26 MSK 2016
+	Added autoconf macro to enable maximum platform
+	features. Fixed compiling on Solaris. -EG
+
+Wed Sep  7 12:57:57 CEST 2016
+	Fixing #4641. -Hawk
+
+Wed Sep  7 00:28:59 CEST 2016
+	Adding remaining "_"-markups for i18n (#4614). -CG
+
+Tue Sep  6 23:39:56 CEST 2016
+	Allow out-of-order nonces for digest authentication (#4636). -CG
+
+Tue Sep  6 21:29:09 CEST 2016
+	Martin was right, "socket_context" should be "void *"
+	in `union MHD_ConnectionInfo`.  -MS
+
+Sun Sep  4 18:16:32 CEST 2016
+	Fixing potential memory leak (#4634). -CG
+
+Sun Sep  4 17:25:45 CEST 2016
+	Tests for "Upgrade" logic are now in place and passing.
+	However, still need to make sure code is portable. -CG
+
+Sat Sep  3 11:56:20 CEST 2016
+	Adding logic for handling HTTP "Upgrade" in thread-per-connection
+	mode. Also still untested. -CG
+
+Sat Aug 27 21:01:43 CEST 2016
+	Adding a few extra safety checks around HTTP "Upgrade"
+	(against wrong uses of API), and a testcase. -CG
+
+Sat Aug 27 20:07:53 CEST 2016
+	Adding completely *untested* logic for HTTP "Upgrade"
+	handling. -CG
+
+Sat Aug 27 18:20:38 CEST 2016
+	Releasing libmicrohttpd 0.9.51. -CG
+
+Tue Aug 23 22:54:07 MSK 2016
+	Internal refactoring: W32 compatibility layer was finally
+	replaced with several specialized abstraction layers for
+	sockets, control pipes (inter-thread communication) and
+	generic functions. Now all major platform functions
+	(including threads and mutex) are implemented in thin
+	abstraction layers.
+	Improved performance on W32 due to eliminating
+	translation of error to POSIX codes and using W32 codes
+	directly (through macros).
+	Improved error reporting on all platforms.
+	Improved error handling and reporting on Darwin.
+	Minor fixes. -EG
+
+Tue Aug 16 15:14:30 MSK 2016
+	Minor improvement for monotonic clock.
+	Minor configure fix for non-bash shells. -EG
+
+Mon Aug 15 13:06:52 CEST 2016
+	Fixed possible crash due to write to read-only region of
+	memory given ill-formed HTTP request (write was otherwise
+	harmless, writing 0 to where there was already a 0).
+	Fixed issue with closed connection slots not immediately
+	being available again for new connections if we reached
+	our connection limit.
+	Avoid even accept()ing connections in certain thread modes
+	if we are at the connection limit and
+	MHD_USE_PIPE_FOR_SHUTDOWN is available. -CG
+
+Wed Aug 10 16:42:57 MSK 2016
+	Moved threads, locks and mutex abstraction to separate files,
+	some minor errors fixed, added support for thread name functions
+	on various platforms, added configure flag for disable thread
+	naming. -EG
+
+Sat Jul 23 20:45:51 CEST 2016
+	Added macro detection of speed/size compiler optimization.
+	Added different implementation of functions in mhd_str.c for
+	size optimization. Enabled automatically if compiler size
+	optimization is detected or MHD_FAVOR_SMALL_CODE is defined.
+	Added unit tests for all mhd_str.c functions. -EG
+
+Sat Jul 16 21:54:49 CEST 2016
+	Warn user if they sent connection into blocking
+	state by not processing all POST data, not suspending,
+	and not running in external select mode. -CG
+
+Fri Jul  8 21:35:07 CEST 2016
+	Fix FIXME in tutorial. -CG
+
+Fri Jul  8 15:57:06 CEST 2016
+	Adding support for 308 status code. -CG
+
+Sat Jun 25 13:49:31 CEST 2016
+	Use shutdown to trigger select on NetBSD. -EG
+
+Thu Jun  2 09:55:50 CEST 2016
+	Releasing libmicrohttpd 0.9.50. -CG
+
+Wed Jun  1 21:59:34 CEST 2016
+	Do not send "Content-Length" header for 1xx/204/304 status codes. -CG
+
+Tue May 17 13:32:21 CEST 2016
+	Allow clients to determine whether a connection is suspended;
+	introduces MHD_CONNECTION_INFO_CONNECTION_SUSPENDED. -CG/FC
+
+Sun May 15 12:17:25 CEST 2016
+	Fix handling system or process resource limit exhaustion upon
+	accept(). -CG/CP
+
+Thu May 12 08:42:19 CEST 2016
+	Fix handling of partial writes in MHD_USE_EPOLL_LINUX_ONLY; only
+	consider sockets returning EAGAIN as unready. -CG/CP
+
+Mon May  2 06:08:26 CEST 2016
+	Adding logic to help address FE performance issue as
+	discussed on the mailinglist with subject
+        "single-threaded daemon, multiple pending requests, responses batched".
+	The new logic is only enabled when MHD_USE_EPOLL_TURBO is set.
+	Note that some additional refactoring was also done to clean up
+	the code and avoid code duplication, which may have actually fixed
+	an unrelated issue with HTTPS and a POLL-style event loop. -CG
+
+Sat Apr 30 10:22:37 CEST 2016
+	Added clarifications to manual based on questions on list. -CG
+
+Sat Apr 23 20:12:01 CET 2016
+	Tests perf_get_concurrent and test_concurrent_stop ported to use
+	pthread instead of fork(). Added more error detections. -EG
+
+Sat Apr 23 16:06:30 CET 2016
+	Improved test_quiesce test. -EG
+
+Sat Apr 23 15:39:38 CET 2016
+	Notify other threads in MHD_quiesce_daemon() so listen socket FD
+	is removed from awaiting select() and poll(). -EG
+
+Sat Apr 23 14:17:15 CET 2016
+	Revert "shutdown trigger select" on Darwin. Fixed daemon shutdown
+	on Darwin without "MHD_USE_PIPE_FOR_SHUTDOWN" option. -EG
+
+Fri Apr 22 14:29:28 CET 2016
+	Fixed race conditions when stopping quiesced daemon with thread
+	pool. -EG
+
+Wed Apr 20 18:12:30 CET 2016
+	Fixed macros in sysfdsetsize.c which could prevent compiling with
+	non-default FD_SETSIZE.
+	Fixed comments in mhd_str.c.
+	Updated test_post.c to not ignore specific error on W32 if libcurl
+	is built with workaround for WinSock bug. -EG
+
+Mon Apr 18 19:35:14 CET 2016
+	Fixed data races leading to inability in rare situations to
+	resume suspended connection. -EG
+
+Tue Apr 13 21:46:01 CET 2016
+	Removed unneeded locking for global timeout list in
+	MHD_USE_THREAD_PER_CONNECTION mode.
+	Added 'simplepost' and 'largepost' examples to VS projects.
+	Added strtoXX() locale-independent replacement functions.
+	Added more error checking and minor fixes in digest auth
+	functions - should improve security.
+	Ignored specific errors in 'test_post' test until libcurl
+	will implement workaround for WinSock bug.
+	Fixed handling of caller-supplied socket with
+	MHD_OPTION_LISTEN_SOCKET (regression in 0.9.49).
+	Minor fixes.
+	Various cosmetics and comments fixes. -EG
+
+Sat Apr 09 13:05:42 CET 2016
+	Releasing libmicrohttpd 0.9.49. -EG
+
+Fri Apr 08 18:32:17 CET 2016
+	Some minor internal fixes, addition error checking and
+	micro optimizations.
+	Reworked usage of sockets shutdown() - now work equally
+	on all platforms, disconnection should be "more graceful". -EG
+
+Tue Mar 15 21:52:27 CET 2016
+	Do not crash if pthread_create() fails. -DD
+
+Tue Mar 15 20:29:34 CET 2016
+	Do not use eready DLL data structure unless
+	we are actually using epoll(). -DD/CG
+
+Fri Feb  5 20:43:11 CET 2016
+	Fixed testsuite compile warning on W32.
+	Added check test for triggering poll() on
+	listen socket. -EG
+
+Thu Feb  4 11:38:11 CET 2016
+	Added some buffer overrun protection.
+	Fixed handling of malformed URI with spaces. -EG
+
+Wed Feb  3 15:41:57 CET 2016
+	Make signal-pipe non-blocking and drain it. -CG
+
+Sat Jan 30 15:49:07 CET 2016
+	Fix running select() with empty fdsets on W32. -EG
+
+Mon Jan 25 13:45:50 CET 2016
+	Added check test for triggering select() on
+	listen socket. -EG
+
+Thu Jan 21 19:35:18 CET 2016
+	Fixed old bug with making sockets non-blocking on
+	various platforms so now sockets are really
+	non-blocking on all supported platforms.
+	Reworked and fixed code for using SOCK_CLOEXEC,
+	SOCK_NONBLOCK and EPOLL_CLOEXEC resulting in
+	fewer used system calls. -EG
+
+Tue Jan 19 20:59:59 CET 2016
+	Cleaned up and optimized with minor fixes code for
+	making sockets non-blocking non-inheritable. -EG
+
+Tue Jan 19 11:14:18 CET 2016
+	Removed workaround for Cygwin non-blocking sockets:
+	handling non-blocking sockets were fixed in Cygwin
+	and libmicrohttpd how uses non-blocking sockets on
+	all platforms. -EG
+
+Mon Jan 18 23:54:45 CET 2016
+	Cleaned up examples to avoid giving oversimplified code
+	that may lead to complications if adopted naively. -CG
+
+Sun Jan 17 11:18:55 CET 2016
+	Do no refuse to send response if sendfile() failed with
+	EINVAL (common error for files located on SMB/CIF). -EG
+
+Sat Jan 16 19:14:39 CET 2016
+	Use US-ASCII only (instead of user locale settings) when
+	performing caseless string comparison as required by
+	standard. -EG
+
+Tue Jan 12 16:10:09 CET 2016
+	Fixed declaraion of MHD_get_reason_phrase_for(). -EG
+
+Mon Jan 11 19:58:50 CET 2016
+	Configure.ac small fixes and refactoring. -EG
+
+Fri Dec 18 15:54:50 CET 2015
+	Releasing libmicrohttpd 0.9.48. -CG
+
+Tue Dec  15 18:35:55 CET 2015
+	Improved compatibility with VS2010 and other older
+	compilers. -EG
+
+Tue Dec  8 21:48:44 CET 2015
+	Default backlog size for listen socket was changed from
+	32 to SOMAXCONN, added new option MHD_OPTION_LISTEN_BACKLOG_SIZE
+	to override default backlog size.
+	If not all connections can be handled by MHD_select() than
+	at least some of connections will be processed instead of
+	failing without any processing.
+	Fixed redefenition of FD_SETSIZE on W32 so select() will
+	work with 2000 connections instead of 64.
+	Better handled redefenition of FD_SETSIZE on all
+	platforms. -EG
+
+Sat Dec  5 17:30:45 CET 2015
+	Close sockets more aggressively in multi-threaded
+	mode (possibly relevant for idle servers). -CG
+
+Fri Dec  4 13:53:05 CET 2015
+	Releasing libmicrohttpd 0.9.47. -CG
+
+Thu Dec  3 18:21:44 CET 2015
+	Reworked VS project files. Used x64 build tools by
+	default, many optimizations, fixes.
+	Added project files for VS 2015. -EG
+
+Tue Dec  1 14:05:13 CET 2015
+	SPDY is dead, killing experimental libmicrospdy. -CG
+
+Tue Dec  1 10:01:12 CET 2015
+	New logic for controlling socket buffer modes.
+	Eliminated delay before last packet in response and before
+	"100 Continue" response on all platforms. Also response
+	header are pushed to client without waiting for response
+	body. -EG
+
+Wed Nov 25 17:02:53 CET 2015
+	Remove 200ms delay observable with keep-alive on Darwin
+	and *BSD platforms. -EG
+
+Tue Nov 10 15:25:48 CET 2015
+	Fix issue with shutdown if connection was resumed just
+	before shutdown. -FC
+
+Fri Nov  6 22:54:38 CET 2015
+	Fixing the buffer shrinkage issue, this time with test. -CG
+	Releasing libmicrohttpd 0.9.46. -CG
+
+Tue Nov  3 23:24:52 CET 2015
+	Undoing change from Sun Oct 25 15:29:23 CET 2015
+	as the original code was counter-intuitive but
+	correct, and the new code does break pipelining.
+	Ignore empty lines at the beginning of an HTTP
+	request (more tolerant implementation). -CG
+
+Sat Oct 31 15:52:52 CET 2015
+	Releasing libmicrohttpd 0.9.45. -CG
+
+Tue Oct 27 12:08:02 CET 2015
+	Rework deprecation maros: fix errors with old GCC versions,
+	improved support for old clang and new GCC. -EG
+
+Sun Oct 25 23:05:32 CET 2015
+	Return correct header kind in MHD_get_connection_values()
+	even if a bitmask is used for the "kind" argument. -FC/CG
+
+Sun Oct 25 15:29:23 CET 2015
+	Fixing transient resource leak affecting long-lived
+	connections with a lot of keep-alive and HTTP request
+	pipelining under certain circumstances (which reduced
+	the receive window).
+	Fixed assertion failure triggered by a race in
+	thread-per-connection mode on shutdown in rare
+	circumstances. -CG
+
+Mon Oct  5 11:53:52 CEST 2015
+	Deduplicate code between digestauth and connection
+	parsing logic for URI arguments, shared code moved
+	to new MHD_parse_arguments_ function in internal.c. -CG
+
+Thu Oct  1 21:22:05 CEST 2015
+	Releasing libmicrohttpd 0.9.44. -CG
+
+Wed Sep 30 21:05:38 CEST 2015
+	Various fixes for W32 VS project files. -EG
+
+Fri Sep 25 09:49:10 CEST 2015
+	Fix digest authentication with URL arguments where
+	value-less keys are given before the last argument.
+	Thanks to MA for reporting. -CG
+
+Tue Sep 22 19:17:54 CEST 2015
+	Do not use shutdown() on listen socket if MHD_USE_PIPE_FOR_SHUTDOWN
+	is set. -CG
+
+Wed Sep 16 11:06:02 CEST 2015
+	Releasing libmicrohttpd 0.9.43. -CG
+
+Wed Sep  2 16:50:31 CEST 2015
+ 	Call resume_suspended_connections() when the user is running
+	its own mainloop and calls MHD_run_from_select() to support
+	resuming connections with external select. -FC
+
+Sun Aug 30 14:53:51 CEST 2015
+	Correct documentation as to when MHD_USE_EPOLL_LINUX_ONLY
+	is allowed. -CG
+
+Thu Aug 27 09:38:44 CEST 2015
+	Reimplement monotonic clock functions for better
+	support various platforms.
+	Print more information during configure. -EG
+
+Fri Aug 14 14:13:55 CEST 2015
+	Export MHD_get_reason_phrase_for() symbol. -CG
+
+Sat Aug  8 12:19:47 CEST 2015
+	Added checks for overflows and buffer overruns, fixed
+	possible buffer overrun.
+	Updated md5 implementation.
+	Fixed many compiler warning (mostly for VC compiler). -EG
+
+Tue Aug  4 13:50:23 CEST 2015
+	Fix failure to properly clean up timed out connections
+	if running in external select mode without listen socket,
+	which caused busy waiting until new connections arrived.
+	(Fixes #3924, thanks to slimp for reporting and testcase). -CG
+
+Sun Aug  2 19:08:20 CEST 2015
+	Ignore close() errors on sockets except for EBADF,
+	fixes #3926. -CG
+
+Sat Jun 27 22:16:27 CEST 2015
+	Make sure to decrement connection counter before
+	calling connection notifier so that
+	MHD_DAEMON_INFO_CURRENT_CONNECTIONS does not
+	present stale information (relevant if this is
+	used for termination detection of a daemon
+	stopped via MHD_quiesce_daemon()). Thanks to
+	Markus Doppelbauer for reporting. -CG
+
+Fri Jun 26 23:17:20 CEST 2015
+	Fix (automatic) handling of HEAD requests with
+	MHD_create_response_from_callback() and HTTP/1.1
+	connection keep-alive. Thanks to Cristian Klein
+	for reporting. -CG
+
+Tue Jun 09 18:30:17 CEST 2015
+	Add new functions MHD_create_response_from_fd64() and
+	MHD_create_response_from_fd_at_offset64(). -EG
+
+Thu Jun  4 13:37:05 CEST 2015
+	Fixing memory leak in digest authentication. -AW
+
+Wed Jun 03 21:23:47 CEST 2015
+	Add deprecation compiler messages for deprecated functions
+	and macros. -EG
+
+Fri May 29 12:23:01 CEST 2015
+	Fixing digest authentication when used in combination
+	with escaped characters in URLs. -CG/AW
+
 Wed May 13 11:49:09 CEST 2015
 	Releasing libmicrohttpd 0.9.42. -CG
 
@@ -239,7 +2103,7 @@
 	Changed configure flag from '--disable-pipe' to
 	'--enable-socketpair'.
 	Added configure flags '--disable-doc' and '--disable-examples'.
-	Narrowed down extrenal lib specific compiler and linker flags
+	Narrowed down external lib specific compiler and linker flags
 	usage. -EG
 
 Wed Feb 26 17:42:34 CET 2014
@@ -345,7 +2209,7 @@
 Fri Nov 29 20:17:03 CET 2013
 	Eliminating theoretical stack overflow by limiting length
 	of URIs in authentication headers to 32k (only applicable
-	if the application explicitly raised the memroy limits,
+	if the application explicitly raised the memory limits,
 	and only applies to MHD_digest_auth_check). Issue was
 	reported by Florian Weimer. -CG
 
@@ -573,7 +2437,7 @@
 	at ~1500 MB/s on this system). -CG
 
 Fri Mar 29 16:44:29 CET 2013
-	Renaming testcases to consistenly begin with test_;
+	Renaming testcases to consistently begin with test_;
 	Changing build system to build examples in doc/.
 	Releasing libmicrohttpd 0.9.26. -CG
 
@@ -720,7 +2584,7 @@
 Tue May 29 13:45:15 CEST 2012
 	Fixing bug where MHD failed to call connection termination callback
 	if a connection either was closed due to read errors or if MHD
-	was terminated with certain threading models.  Added new
+	was terminated with certain threading modes.  Added new
 	termination code MHD_REQUEST_TERMINATED_READ_ERROR for the
 	read-termination cause. -CG
 
@@ -1222,7 +3086,7 @@
 	aligned (fixes bus errors on Sparc). -CG
 
 Thu Dec 17 20:26:52 CET 2009
-	poll.h is not stricly required anymore. -ND
+	poll.h is not strictly required anymore. -ND
 
 Fri Dec  4 13:17:50 CET 2009
 	Adding MHD_OPTION_ARRAY. -CG
@@ -1293,11 +3157,11 @@
 
 Fri May 15 11:00:20 MDT 2009
 	 Grow reserved read buffer more aggressively so that we are not
-	 needlessly stuck reading only a handfull of bytes in each iteration. -CG
+	 needlessly stuck reading only a handful of bytes in each iteration. -CG
 
 Thu May 14 21:20:30 MDT 2009
 	 Fixed issue where the "NOTIFY_COMPLETED" handler could be called
-	 twice (if a socket error or timeout occured for a pipelined
+	 twice (if a socket error or timeout occurred for a pipelined
 	 connection after successfully completing a request and before
 	 the next request was successfully transmitted).  This could
 	 confuse applications not expecting to see a connection "complete"
@@ -1461,7 +3325,7 @@
 	 Fixed a problem (introduced in 0.2.3) with handling very
 	 large requests (the code did not return proper error code).
 	 If "--enable-messages" is specified, the code now includes
-	 reasonable default HTML webpages for various build-in
+	 reasonable default HTML webpages for various built-in
 	 errors (such as request too large and malformed requests).
 	 Without that flag, the webpages returned will still be
 	 empty.
@@ -1587,7 +3451,7 @@
 	 HTTP 400 status back if this is violated). - CG
 
 Tue Aug 21 01:01:46 MDT 2007
-	 Fixing assertion failure that occured when a client
+	 Fixing assertion failure that occurred when a client
 	 closed the connection after sending some data but
 	 not the full headers. - CG
 
diff --git a/INSTALL b/INSTALL
deleted file mode 100644
index 2099840..0000000
--- a/INSTALL
+++ /dev/null
@@ -1,370 +0,0 @@
-Installation Instructions
-*************************
-
-Copyright (C) 1994-1996, 1999-2002, 2004-2013 Free Software Foundation,
-Inc.
-
-   Copying and distribution of this file, with or without modification,
-are permitted in any medium without royalty provided the copyright
-notice and this notice are preserved.  This file is offered as-is,
-without warranty of any kind.
-
-Basic Installation
-==================
-
-   Briefly, the shell command `./configure && make && make install'
-should configure, build, and install this package.  The following
-more-detailed instructions are generic; see the `README' file for
-instructions specific to this package.  Some packages provide this
-`INSTALL' file but do not implement all of the features documented
-below.  The lack of an optional feature in a given package is not
-necessarily a bug.  More recommendations for GNU packages can be found
-in *note Makefile Conventions: (standards)Makefile Conventions.
-
-   The `configure' shell script attempts to guess correct values for
-various system-dependent variables used during compilation.  It uses
-those values to create a `Makefile' in each directory of the package.
-It may also create one or more `.h' files containing system-dependent
-definitions.  Finally, it creates a shell script `config.status' that
-you can run in the future to recreate the current configuration, and a
-file `config.log' containing compiler output (useful mainly for
-debugging `configure').
-
-   It can also use an optional file (typically called `config.cache'
-and enabled with `--cache-file=config.cache' or simply `-C') that saves
-the results of its tests to speed up reconfiguring.  Caching is
-disabled by default to prevent problems with accidental use of stale
-cache files.
-
-   If you need to do unusual things to compile the package, please try
-to figure out how `configure' could check whether to do them, and mail
-diffs or instructions to the address given in the `README' so they can
-be considered for the next release.  If you are using the cache, and at
-some point `config.cache' contains results you don't want to keep, you
-may remove or edit it.
-
-   The file `configure.ac' (or `configure.in') is used to create
-`configure' by a program called `autoconf'.  You need `configure.ac' if
-you want to change it or regenerate `configure' using a newer version
-of `autoconf'.
-
-   The simplest way to compile this package is:
-
-  1. `cd' to the directory containing the package's source code and type
-     `./configure' to configure the package for your system.
-
-     Running `configure' might take a while.  While running, it prints
-     some messages telling which features it is checking for.
-
-  2. Type `make' to compile the package.
-
-  3. Optionally, type `make check' to run any self-tests that come with
-     the package, generally using the just-built uninstalled binaries.
-
-  4. Type `make install' to install the programs and any data files and
-     documentation.  When installing into a prefix owned by root, it is
-     recommended that the package be configured and built as a regular
-     user, and only the `make install' phase executed with root
-     privileges.
-
-  5. Optionally, type `make installcheck' to repeat any self-tests, but
-     this time using the binaries in their final installed location.
-     This target does not install anything.  Running this target as a
-     regular user, particularly if the prior `make install' required
-     root privileges, verifies that the installation completed
-     correctly.
-
-  6. You can remove the program binaries and object files from the
-     source code directory by typing `make clean'.  To also remove the
-     files that `configure' created (so you can compile the package for
-     a different kind of computer), type `make distclean'.  There is
-     also a `make maintainer-clean' target, but that is intended mainly
-     for the package's developers.  If you use it, you may have to get
-     all sorts of other programs in order to regenerate files that came
-     with the distribution.
-
-  7. Often, you can also type `make uninstall' to remove the installed
-     files again.  In practice, not all packages have tested that
-     uninstallation works correctly, even though it is required by the
-     GNU Coding Standards.
-
-  8. Some packages, particularly those that use Automake, provide `make
-     distcheck', which can by used by developers to test that all other
-     targets like `make install' and `make uninstall' work correctly.
-     This target is generally not run by end users.
-
-Compilers and Options
-=====================
-
-   Some systems require unusual options for compilation or linking that
-the `configure' script does not know about.  Run `./configure --help'
-for details on some of the pertinent environment variables.
-
-   You can give `configure' initial values for configuration parameters
-by setting variables in the command line or in the environment.  Here
-is an example:
-
-     ./configure CC=c99 CFLAGS=-g LIBS=-lposix
-
-   *Note Defining Variables::, for more details.
-
-Compiling For Multiple Architectures
-====================================
-
-   You can compile the package for more than one kind of computer at the
-same time, by placing the object files for each architecture in their
-own directory.  To do this, you can use GNU `make'.  `cd' to the
-directory where you want the object files and executables to go and run
-the `configure' script.  `configure' automatically checks for the
-source code in the directory that `configure' is in and in `..'.  This
-is known as a "VPATH" build.
-
-   With a non-GNU `make', it is safer to compile the package for one
-architecture at a time in the source code directory.  After you have
-installed the package for one architecture, use `make distclean' before
-reconfiguring for another architecture.
-
-   On MacOS X 10.5 and later systems, you can create libraries and
-executables that work on multiple system types--known as "fat" or
-"universal" binaries--by specifying multiple `-arch' options to the
-compiler but only a single `-arch' option to the preprocessor.  Like
-this:
-
-     ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
-                 CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
-                 CPP="gcc -E" CXXCPP="g++ -E"
-
-   This is not guaranteed to produce working output in all cases, you
-may have to build one architecture at a time and combine the results
-using the `lipo' tool if you have problems.
-
-Installation Names
-==================
-
-   By default, `make install' installs the package's commands under
-`/usr/local/bin', include files under `/usr/local/include', etc.  You
-can specify an installation prefix other than `/usr/local' by giving
-`configure' the option `--prefix=PREFIX', where PREFIX must be an
-absolute file name.
-
-   You can specify separate installation prefixes for
-architecture-specific files and architecture-independent files.  If you
-pass the option `--exec-prefix=PREFIX' to `configure', the package uses
-PREFIX as the prefix for installing programs and libraries.
-Documentation and other data files still use the regular prefix.
-
-   In addition, if you use an unusual directory layout you can give
-options like `--bindir=DIR' to specify different values for particular
-kinds of files.  Run `configure --help' for a list of the directories
-you can set and what kinds of files go in them.  In general, the
-default for these options is expressed in terms of `${prefix}', so that
-specifying just `--prefix' will affect all of the other directory
-specifications that were not explicitly provided.
-
-   The most portable way to affect installation locations is to pass the
-correct locations to `configure'; however, many packages provide one or
-both of the following shortcuts of passing variable assignments to the
-`make install' command line to change installation locations without
-having to reconfigure or recompile.
-
-   The first method involves providing an override variable for each
-affected directory.  For example, `make install
-prefix=/alternate/directory' will choose an alternate location for all
-directory configuration variables that were expressed in terms of
-`${prefix}'.  Any directories that were specified during `configure',
-but not in terms of `${prefix}', must each be overridden at install
-time for the entire installation to be relocated.  The approach of
-makefile variable overrides for each directory variable is required by
-the GNU Coding Standards, and ideally causes no recompilation.
-However, some platforms have known limitations with the semantics of
-shared libraries that end up requiring recompilation when using this
-method, particularly noticeable in packages that use GNU Libtool.
-
-   The second method involves providing the `DESTDIR' variable.  For
-example, `make install DESTDIR=/alternate/directory' will prepend
-`/alternate/directory' before all installation names.  The approach of
-`DESTDIR' overrides is not required by the GNU Coding Standards, and
-does not work on platforms that have drive letters.  On the other hand,
-it does better at avoiding recompilation issues, and works well even
-when some directory options were not specified in terms of `${prefix}'
-at `configure' time.
-
-Optional Features
-=================
-
-   If the package supports it, you can cause programs to be installed
-with an extra prefix or suffix on their names by giving `configure' the
-option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
-
-   Some packages pay attention to `--enable-FEATURE' options to
-`configure', where FEATURE indicates an optional part of the package.
-They may also pay attention to `--with-PACKAGE' options, where PACKAGE
-is something like `gnu-as' or `x' (for the X Window System).  The
-`README' should mention any `--enable-' and `--with-' options that the
-package recognizes.
-
-   For packages that use the X Window System, `configure' can usually
-find the X include and library files automatically, but if it doesn't,
-you can use the `configure' options `--x-includes=DIR' and
-`--x-libraries=DIR' to specify their locations.
-
-   Some packages offer the ability to configure how verbose the
-execution of `make' will be.  For these packages, running `./configure
---enable-silent-rules' sets the default to minimal output, which can be
-overridden with `make V=1'; while running `./configure
---disable-silent-rules' sets the default to verbose, which can be
-overridden with `make V=0'.
-
-Particular systems
-==================
-
-   On HP-UX, the default C compiler is not ANSI C compatible.  If GNU
-CC is not installed, it is recommended to use the following options in
-order to use an ANSI C compiler:
-
-     ./configure CC="cc -Ae -D_XOPEN_SOURCE=500"
-
-and if that doesn't work, install pre-built binaries of GCC for HP-UX.
-
-   HP-UX `make' updates targets which have the same time stamps as
-their prerequisites, which makes it generally unusable when shipped
-generated files such as `configure' are involved.  Use GNU `make'
-instead.
-
-   On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot
-parse its `<wchar.h>' header file.  The option `-nodtk' can be used as
-a workaround.  If GNU CC is not installed, it is therefore recommended
-to try
-
-     ./configure CC="cc"
-
-and if that doesn't work, try
-
-     ./configure CC="cc -nodtk"
-
-   On Solaris, don't put `/usr/ucb' early in your `PATH'.  This
-directory contains several dysfunctional programs; working variants of
-these programs are available in `/usr/bin'.  So, if you need `/usr/ucb'
-in your `PATH', put it _after_ `/usr/bin'.
-
-   On Haiku, software installed for all users goes in `/boot/common',
-not `/usr/local'.  It is recommended to use the following options:
-
-     ./configure --prefix=/boot/common
-
-Specifying the System Type
-==========================
-
-   There may be some features `configure' cannot figure out
-automatically, but needs to determine by the type of machine the package
-will run on.  Usually, assuming the package is built to be run on the
-_same_ architectures, `configure' can figure that out, but if it prints
-a message saying it cannot guess the machine type, give it the
-`--build=TYPE' option.  TYPE can either be a short name for the system
-type, such as `sun4', or a canonical name which has the form:
-
-     CPU-COMPANY-SYSTEM
-
-where SYSTEM can have one of these forms:
-
-     OS
-     KERNEL-OS
-
-   See the file `config.sub' for the possible values of each field.  If
-`config.sub' isn't included in this package, then this package doesn't
-need to know the machine type.
-
-   If you are _building_ compiler tools for cross-compiling, you should
-use the option `--target=TYPE' to select the type of system they will
-produce code for.
-
-   If you want to _use_ a cross compiler, that generates code for a
-platform different from the build platform, you should specify the
-"host" platform (i.e., that on which the generated programs will
-eventually be run) with `--host=TYPE'.
-
-Sharing Defaults
-================
-
-   If you want to set default values for `configure' scripts to share,
-you can create a site shell script called `config.site' that gives
-default values for variables like `CC', `cache_file', and `prefix'.
-`configure' looks for `PREFIX/share/config.site' if it exists, then
-`PREFIX/etc/config.site' if it exists.  Or, you can set the
-`CONFIG_SITE' environment variable to the location of the site script.
-A warning: not all `configure' scripts look for a site script.
-
-Defining Variables
-==================
-
-   Variables not defined in a site shell script can be set in the
-environment passed to `configure'.  However, some packages may run
-configure again during the build, and the customized values of these
-variables may be lost.  In order to avoid this problem, you should set
-them in the `configure' command line, using `VAR=value'.  For example:
-
-     ./configure CC=/usr/local2/bin/gcc
-
-causes the specified `gcc' to be used as the C compiler (unless it is
-overridden in the site shell script).
-
-Unfortunately, this technique does not work for `CONFIG_SHELL' due to
-an Autoconf limitation.  Until the limitation is lifted, you can use
-this workaround:
-
-     CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash
-
-`configure' Invocation
-======================
-
-   `configure' recognizes the following options to control how it
-operates.
-
-`--help'
-`-h'
-     Print a summary of all of the options to `configure', and exit.
-
-`--help=short'
-`--help=recursive'
-     Print a summary of the options unique to this package's
-     `configure', and exit.  The `short' variant lists options used
-     only in the top level, while the `recursive' variant lists options
-     also present in any nested packages.
-
-`--version'
-`-V'
-     Print the version of Autoconf used to generate the `configure'
-     script, and exit.
-
-`--cache-file=FILE'
-     Enable the cache: use and save the results of the tests in FILE,
-     traditionally `config.cache'.  FILE defaults to `/dev/null' to
-     disable caching.
-
-`--config-cache'
-`-C'
-     Alias for `--cache-file=config.cache'.
-
-`--quiet'
-`--silent'
-`-q'
-     Do not print messages saying which checks are being made.  To
-     suppress all normal output, redirect it to `/dev/null' (any error
-     messages will still be shown).
-
-`--srcdir=DIR'
-     Look for the package's source code in directory DIR.  Usually
-     `configure' can determine that directory automatically.
-
-`--prefix=DIR'
-     Use DIR as the installation prefix.  *note Installation Names::
-     for more details, including other options available for fine-tuning
-     the installation locations.
-
-`--no-create'
-`-n'
-     Run the configure checks, but stop before creating any output
-     files.
-
-`configure' also accepts some other, not widely useful, options.  Run
-`configure --help' for more details.
diff --git a/MHD_config.h b/MHD_config.h
index 185ea3b..56a0dba 100644
--- a/MHD_config.h
+++ b/MHD_config.h
@@ -1,52 +1,103 @@
 /* MHD_config.h.  Generated from MHD_config.h.in by configure.  */
 /* MHD_config.h.in.  Generated from configure.ac by autoheader.  */
 
-#define _GNU_SOURCE  1
-
 /* Define if building universal (internal helper macro) */
 /* #undef AC_APPLE_UNIVERSAL_BUILD */
 
-/* disable basic Auth support */
+/* Define to 1 if libmicrohttpd is compiled with Basic Auth support. */
 #define BAUTH_SUPPORT 1
 
+/* Define to 1 if libmicrohttpd is compiled with HTTP cookie parsing support.
+   */
+#define COOKIE_SUPPORT 1
+
 /* This is a Cygwin system */
 /* #undef CYGWIN */
 
-/* disable digest Auth support */
+/* Define to 1 if libmicrohttpd is compiled with Digest Auth support. */
 #define DAUTH_SUPPORT 1
 
-/* define to 0 to disable epoll support */
-/* #undef EPOLL_SUPPORT */
+/* Define to 1 to enable epoll support */
+#define EPOLL_SUPPORT 1
 
 /* This is a FreeBSD system */
 /* #undef FREEBSD */
 
-/* Define to 1 if you have the `accept4' function. */
+/* Define to '1' if '__attribute__((no_sanitize("address")))' works for
+   pointers compare */
+/* #undef FUNC_ATTR_NOSANITIZE_WORKS */
+
+/* Define to '1' if '__attribute__((no_sanitize("pointer-compare")))' works */
+/* #undef FUNC_ATTR_PTRCOMPARE_WORKS */
+
+/* Define to '1' if '__attribute__((no_sanitize("pointer-subtract")))' works
+   */
+/* #undef FUNC_ATTR_PTRSUBTRACT_WORKS */
+
+/* Define to '1' if cast to 'uintptr_t' works for safely processing
+   user-poisoned pointer */
+/* #undef FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS */
+
+/* Define to `1' if host machine runs on GNU Hurd. */
+/* #undef GNU_HURD */
+
+/* Define to 1 if you have the 'accept4' function. */
 #define HAVE_ACCEPT4 1
 
 /* Define to 1 if you have the <arpa/inet.h> header file. */
 #define HAVE_ARPA_INET_H 1
 
-/* Have clock_gettime */
+/* Define if you have usable assert() and assert.h */
+/* #undef HAVE_ASSERT */
+
+/* Define to 1 if you have the real boolean type. */
+#define HAVE_BUILTIN_TYPE_BOOL 1
+
+/* Define to 1 if you have the `gmtime_s' function in C11 form. */
+/* #undef HAVE_C11_GMTIME_S */
+
+/* Define to 1 if you have the usable `calloc' function. */
+#define HAVE_CALLOC 1
+
+/* Define to '1' if you have clock_gettime() function */
 #define HAVE_CLOCK_GETTIME 1
 
-/* Define to 1 if you have the declaration of `SOCK_NONBLOCK', and to 0 if you
-   don't. */
-#define HAVE_DECL_SOCK_NONBLOCK 1
+/* Define to 1 if you have the 'clock_get_time' function. */
+/* #undef HAVE_CLOCK_GET_TIME */
 
-/* Define to 1 if you have the declaration of `TCP_CORK', and to 0 if you
-   don't. */
-#define HAVE_DECL_TCP_CORK 1
+/* Define to 1 if your compiler supports 'alignof()' */
+#define HAVE_C_ALIGNOF 1
 
-/* Define to 1 if you have the declaration of `TCP_NOPUSH', and to 0 if you
+/* Define to 1 if C supports variable-length arrays. */
+#define HAVE_C_VARARRAYS 1
+
+/* Define to 1 if you have Darwin-style sendfile(2). */
+/* #undef HAVE_DARWIN_SENDFILE */
+
+/* Define to 1 if you have the declaration of `CTL_NET', and to 0 if you
    don't. */
-#define HAVE_DECL_TCP_NOPUSH 0
+/* #undef HAVE_DECL_CTL_NET */
+
+/* Define to 1 if you have the declaration of `ICMPCTL_ICMPLIM', and to 0 if
+   you don't. */
+/* #undef HAVE_DECL_ICMPCTL_ICMPLIM */
+
+/* Define to 1 if you have the declaration of `IPPROTO_ICMP', and to 0 if you
+   don't. */
+/* #undef HAVE_DECL_IPPROTO_ICMP */
+
+/* Define to 1 if you have the declaration of `PF_INET', and to 0 if you
+   don't. */
+/* #undef HAVE_DECL_PF_INET */
 
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #define HAVE_DLFCN_H 1
 
-/* Define if you have epoll_create1 function. */
-/* #undef HAVE_EPOLL_CREATE1 */
+/* Define to 1 if you have the <endian.h> header file. */
+#define HAVE_ENDIAN_H 1
+
+/* Define to 1 if you have the 'epoll_create1' function. */
+#define HAVE_EPOLL_CREATE1 1
 
 /* Define to 1 if you have the <errno.h> header file. */
 #define HAVE_ERRNO_H 1
@@ -54,110 +105,192 @@
 /* Define to 1 if you have the <fcntl.h> header file. */
 #define HAVE_FCNTL_H 1
 
+/* Define to 1 if you have the usable `fork' function. */
+#define HAVE_FORK 1
+
+/* Define to 1 if you have FreeBSD-style sendfile(2). */
+/* #undef HAVE_FREEBSD_SENDFILE */
+
 /* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
 #define HAVE_FSEEKO 1
 
 /* Define to 1 if you have the <gcrypt.h> header file. */
 /* #undef HAVE_GCRYPT_H */
 
-/* Define to 1 if you have `gmtime_s' function (only for W32). */
-/* #undef HAVE_GMTIME_S */
+/* Define to 1 if you have the 'gethrtime' function. */
+/* #undef HAVE_GETHRTIME */
+
+/* Define to 1 if you have the 'gettimeofday' function. */
+#define HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the 'gmtime_r' function. */
+#define HAVE_GMTIME_R 1
+
+/* Define to 1 if you have the 'gnutls_check_version' function. */
+/* #undef HAVE_GNUTLS_CHECK_VERSION */
 
 /* Define to 1 if you have the <gnutls/gnutls.h> header file. */
 /* #undef HAVE_GNUTLS_GNUTLS_H */
 
-/* Provides IPv6 headers */
+/* Define to '1' if you have IPv6 headers */
 #define HAVE_INET6 1
 
+/* Define to 1 if you have the <inetLib.h> header file. */
+/* #undef HAVE_INETLIB_H */
+
 /* Define to 1 if you have the <inttypes.h> header file. */
 #define HAVE_INTTYPES_H 1
 
 /* Define to 1 if you have a functional curl library. */
-/* #undef HAVE_LIBCURL */
+#define HAVE_LIBCURL 1
 
 /* Define to 1 if you have the <limits.h> header file. */
 #define HAVE_LIMITS_H 1
 
+/* Define to 1 if you have linux-style sendfile(2). */
+#define HAVE_LINUX_SENDFILE 1
+
 /* can use shutdown on listen sockets */
 #define HAVE_LISTEN_SHUTDOWN 1
 
-/* Define to 1 if you have the <locale.h> header file. */
-#define HAVE_LOCALE_H 1
+/* Define to 1 if you have the 'lseek64' function. */
+#define HAVE_LSEEK64 1
 
-/* Define to 1 if you have the <magic.h> header file. */
-/* #undef HAVE_MAGIC_H */
+/* Define to 1 if you have the <machine/endian.h> header file. */
+/* #undef HAVE_MACHINE_ENDIAN_H */
 
-/* Define to 1 if you have the <math.h> header file. */
-#define HAVE_MATH_H 1
+/* Define to 1 if you have the <machine/param.h> header file. */
+/* #undef HAVE_MACHINE_PARAM_H */
 
-/* Define to 1 if you have the `memmem' function. */
+/* Define to 1 if you have the 'magic_open' function. */
+/* #undef HAVE_MAGIC_OPEN */
+
+/* Define to 1 if you have the 'memmem' function. */
 #define HAVE_MEMMEM 1
 
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Disable error messages */
+/* Define to 1 to enable support for error messages. */
 #define HAVE_MESSAGES 1
 
+/* Define to 1 if you have the 'nanosleep' function. */
+#define HAVE_NANOSLEEP 1
+
 /* Define to 1 if you have the <netdb.h> header file. */
 #define HAVE_NETDB_H 1
 
+/* Define to 1 if you have the <netinet/icmp_var.h> header file. */
+/* #undef HAVE_NETINET_ICMP_VAR_H */
+
 /* Define to 1 if you have the <netinet/in.h> header file. */
 #define HAVE_NETINET_IN_H 1
 
+/* Define to 1 if you have the <netinet/in_systm.h> header file. */
+#define HAVE_NETINET_IN_SYSTM_H 1
+
+/* Define to 1 if you have the <netinet/ip.h> header file. */
+#define HAVE_NETINET_IP_H 1
+
+/* Define to 1 if you have the <netinet/ip_icmp.h> header file. */
+#define HAVE_NETINET_IP_ICMP_H 1
+
 /* Define to 1 if you have the <netinet/tcp.h> header file. */
 #define HAVE_NETINET_TCP_H 1
 
-/* Define to 1 if you have the <openssl/engine.h> header file. */
-#define HAVE_OPENSSL_ENGINE_H 1
+/* Define to 1 if you have the <net/if.h> header file. */
+#define HAVE_NET_IF_H 1
 
-/* Define to 1 if you have the <openssl/err.h> header file. */
-#define HAVE_OPENSSL_ERR_H 1
+/* Define if you have usable pipe2(2) function */
+/* #undef HAVE_PIPE2_FUNC */
 
-/* Define to 1 if you have the <openssl/evp.h> header file. */
-#define HAVE_OPENSSL_EVP_H 1
-
-/* Define to 1 if you have the <openssl/pem.h> header file. */
-#define HAVE_OPENSSL_PEM_H 1
-
-/* Define to 1 if you have the <openssl/rand.h> header file. */
-#define HAVE_OPENSSL_RAND_H 1
-
-/* Define to 1 if you have the <openssl/rsa.h> header file. */
-#define HAVE_OPENSSL_RSA_H 1
-
-/* Define to 1 if you have the <openssl/sha.h> header file. */
-#define HAVE_OPENSSL_SHA_H 1
-
-/* Define to 1 if you have the `poll' function. */
+/* Define to 1 if you have the 'poll' function. */
 #define HAVE_POLL 1
 
 /* Define to 1 if you have the <poll.h> header file. */
 #define HAVE_POLL_H 1
 
-/* define to 1 if MHD was build with postprocessor.c */
+/* Define to 1 if libmicrohttpd is compiled with postprocessor support. */
 #define HAVE_POSTPROCESSOR 1
 
+/* Define to 1 if you have the 'pread' function. */
+#define HAVE_PREAD 1
+
+/* Define to 1 if you have the 'pread64' function. */
+#define HAVE_PREAD64 1
+
+/* Define if you have IBM i form (or Solaris form) of
+   pthread_attr_setname_np(3) function. */
+/* #undef HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI */
+
+/* Define if you have NetBSD form (or OSF1 form) of pthread_attr_setname_np(3)
+   function. */
+/* #undef HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD */
+
 /* Define to 1 if you have the <pthread.h> header file. */
 #define HAVE_PTHREAD_H 1
 
+/* Define to 1 if you have the <pthread_np.h> header file. */
+/* #undef HAVE_PTHREAD_NP_H */
+
 /* Have PTHREAD_PRIO_INHERIT. */
 #define HAVE_PTHREAD_PRIO_INHERIT 1
 
-/* Define if you have pthread_setname_np function. */
-#define HAVE_PTHREAD_SETNAME_NP 1
+/* Define if you have Darwin form of pthread_setname_np(3) function. */
+/* #undef HAVE_PTHREAD_SETNAME_NP_DARWIN */
 
-/* Define to 1 if you have the <search.h> header file. */
-#define HAVE_SEARCH_H 1
+/* Define if you have GNU/Linux form of pthread_setname_np(3) function. */
+#define HAVE_PTHREAD_SETNAME_NP_GNU 1
 
-/* Do we have sockaddr_in.sin_len? */
-/* #undef HAVE_SOCKADDR_IN_SIN_LEN */
+/* Define if you have NetBSD form (or OSF1 form) of pthread_setname_np(3)
+   function. */
+/* #undef HAVE_PTHREAD_SETNAME_NP_NETBSD */
+
+/* Define if you have FreeBSD form of pthread_set_name_np(3) function. */
+/* #undef HAVE_PTHREAD_SET_NAME_NP_FREEBSD */
+
+/* Define to 1 if you have the pthread_sigmask(3) function. */
+#define HAVE_PTHREAD_SIGMASK 1
+
+/* Define to 1 if you have the 'rand' function. */
+/* #undef HAVE_RAND */
+
+/* Define to 1 if you have the 'random' function. */
+#define HAVE_RANDOM 1
+
+/* Define to 1 if you have the <sanitizer/asan_interface.h> header file. */
+/* #undef HAVE_SANITIZER_ASAN_INTERFACE_H */
+
+/* Define to 1 if you have the <sdkddkver.h> header file. */
+/* #undef HAVE_SDKDDKVER_H */
+
+/* Define to 1 if you have the 'sendfile64' function. */
+#define HAVE_SENDFILE64 1
+
+/* Define to '1' if your have sendmsg() function */
+#define HAVE_SENDMSG 1
+
+/* Define to 1 if you have the <signal.h> header file. */
+#define HAVE_SIGNAL_H 1
+
+/* Define to 1 if you have the 'snprintf' function. */
+#define HAVE_SNPRINTF 1
+
+/* Define to 1 if you have the <sockLib.h> header file. */
+/* #undef HAVE_SOCKLIB_H */
 
 /* SOCK_NONBLOCK is defined in a socket header */
 #define HAVE_SOCK_NONBLOCK 1
 
-/* Define to 1 if you have the <spdylay/spdylay.h> header file. */
-/* #undef HAVE_SPDYLAY_SPDYLAY_H */
+/* Define to 1 if you have Solaris-style sendfile(3). */
+/* #undef HAVE_SOLARIS_SENDFILE */
+
+/* Define to 1 if you have the <stdalign.h> header file. */
+#define HAVE_STDALIGN_H 1
+
+/* Define to 1 if you have the <stdbool.h> header file and <stdbool.h> defines
+   'bool' type. */
+#define HAVE_STDBOOL_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define HAVE_STDDEF_H 1
 
 /* Define to 1 if you have the <stdint.h> header file. */
 #define HAVE_STDINT_H 1
@@ -174,12 +307,48 @@
 /* Define to 1 if you have the <string.h> header file. */
 #define HAVE_STRING_H 1
 
+/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
+/* #undef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+
+/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
+/* #undef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+
+/* Define to 1 if `ss_len' is a member of `struct sockaddr_storage'. */
+/* #undef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */
+
+/* Define to 1 if you have the 'sysconf' function. */
+#define HAVE_SYSCONF 1
+
+/* Define to 1 if you have the 'sysctl' function. */
+/* #undef HAVE_SYSCTL */
+
+/* Define to 1 if you have the 'sysctlbyname' function. */
+/* #undef HAVE_SYSCTLBYNAME */
+
+/* Define to 1 if you have the <sys/byteorder.h> header file. */
+/* #undef HAVE_SYS_BYTEORDER_H */
+
+/* Define to 1 if you have the <sys/endian.h> header file. */
+/* #undef HAVE_SYS_ENDIAN_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/isa_defs.h> header file. */
+/* #undef HAVE_SYS_ISA_DEFS_H */
+
+/* Define to 1 if you have the <sys/machine.h> header file. */
+/* #undef HAVE_SYS_MACHINE_H */
+
 /* Define to 1 if you have the <sys/mman.h> header file. */
 #define HAVE_SYS_MMAN_H 1
 
 /* Define to 1 if you have the <sys/msg.h> header file. */
 #define HAVE_SYS_MSG_H 1
 
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define HAVE_SYS_PARAM_H 1
+
 /* Define to 1 if you have the <sys/select.h> header file. */
 #define HAVE_SYS_SELECT_H 1
 
@@ -189,115 +358,214 @@
 /* Define to 1 if you have the <sys/stat.h> header file. */
 #define HAVE_SYS_STAT_H 1
 
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+/* #undef HAVE_SYS_SYSCTL_H */
+
 /* Define to 1 if you have the <sys/time.h> header file. */
 #define HAVE_SYS_TIME_H 1
 
 /* Define to 1 if you have the <sys/types.h> header file. */
 #define HAVE_SYS_TYPES_H 1
 
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the 'timespec_get' function. */
+#define HAVE_TIMESPEC_GET 1
+
 /* Define to 1 if you have the <time.h> header file. */
 #define HAVE_TIME_H 1
 
 /* Define to 1 if you have the <unistd.h> header file. */
 #define HAVE_UNISTD_H 1
 
+/* Define to 1 if you have the 'usleep' function. */
+#define HAVE_USLEEP 1
+
+/* Define to 1 if you have the `gmtime_s' function in W32 form. */
+/* #undef HAVE_W32_GMTIME_S */
+
+/* Define to 1 if you have the usable `waitpid' function. */
+#define HAVE_WAITPID 1
+
+/* Define to 1 if you have the <windows.h> header file. */
+/* #undef HAVE_WINDOWS_H */
+
 /* Define to 1 if you have the <winsock2.h> header file. */
 /* #undef HAVE_WINSOCK2_H */
 
+/* Define to 1 if you have the 'writev' function. */
+#define HAVE_WRITEV 1
+
 /* Define to 1 if you have the <ws2tcpip.h> header file. */
 /* #undef HAVE_WS2TCPIP_H */
 
-/* disable HTTPS support */
-#define HTTPS_SUPPORT 1
+/* Define to 1 if you have the 'WSAPoll' function. */
+/* #undef HAVE_WSAPOLL */
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#define HAVE_ZLIB_H 1
+
+/* Define to 1 if you have the '__asan_address_is_poisoned' function. */
+/* #undef HAVE___ASAN_ADDRESS_IS_POISONED */
+
+/* Define to 1 if you have the '__asan_region_is_poisoned' function. */
+/* #undef HAVE___ASAN_REGION_IS_POISONED */
+
+/* Define to 1 if your compiler supports __FUNCTION__ magic-macro. */
+/* #undef HAVE___FUNCTION__ */
+
+/* Define to 1 if your compiler supports __func__ magic-macro. */
+#define HAVE___FUNC__ 1
+
+/* Define to 1 if your compiler supports __PRETTY_FUNCTION__ magic-macro. */
+/* #undef HAVE___PRETTY_FUNCTION__ */
+
+/* Define to 1 if libmicrohttpd is compiled with HTTPS support. */
+/* #undef HTTPS_SUPPORT */
+
+/* Define to 1 if your C compiler supports inline functions. */
+#define INLINE_FUNC 1
 
 /* Defined if libcurl supports AsynchDNS */
-/* #undef LIBCURL_FEATURE_ASYNCHDNS */
+#define LIBCURL_FEATURE_ASYNCHDNS 1
 
 /* Defined if libcurl supports IDN */
-/* #undef LIBCURL_FEATURE_IDN */
+#define LIBCURL_FEATURE_IDN 1
 
 /* Defined if libcurl supports IPv6 */
-/* #undef LIBCURL_FEATURE_IPV6 */
+#define LIBCURL_FEATURE_IPV6 1
 
 /* Defined if libcurl supports KRB4 */
 /* #undef LIBCURL_FEATURE_KRB4 */
 
 /* Defined if libcurl supports libz */
-/* #undef LIBCURL_FEATURE_LIBZ */
+#define LIBCURL_FEATURE_LIBZ 1
 
 /* Defined if libcurl supports NTLM */
-/* #undef LIBCURL_FEATURE_NTLM */
+#define LIBCURL_FEATURE_NTLM 1
 
 /* Defined if libcurl supports SSL */
-/* #undef LIBCURL_FEATURE_SSL */
+#define LIBCURL_FEATURE_SSL 1
 
 /* Defined if libcurl supports SSPI */
 /* #undef LIBCURL_FEATURE_SSPI */
 
 /* Defined if libcurl supports DICT */
-/* #undef LIBCURL_PROTOCOL_DICT */
+#define LIBCURL_PROTOCOL_DICT 1
 
 /* Defined if libcurl supports FILE */
-/* #undef LIBCURL_PROTOCOL_FILE */
+#define LIBCURL_PROTOCOL_FILE 1
 
 /* Defined if libcurl supports FTP */
-/* #undef LIBCURL_PROTOCOL_FTP */
+#define LIBCURL_PROTOCOL_FTP 1
 
 /* Defined if libcurl supports FTPS */
-/* #undef LIBCURL_PROTOCOL_FTPS */
+#define LIBCURL_PROTOCOL_FTPS 1
 
 /* Defined if libcurl supports HTTP */
-/* #undef LIBCURL_PROTOCOL_HTTP */
+#define LIBCURL_PROTOCOL_HTTP 1
 
 /* Defined if libcurl supports HTTPS */
-/* #undef LIBCURL_PROTOCOL_HTTPS */
+#define LIBCURL_PROTOCOL_HTTPS 1
 
 /* Defined if libcurl supports IMAP */
-/* #undef LIBCURL_PROTOCOL_IMAP */
+#define LIBCURL_PROTOCOL_IMAP 1
 
 /* Defined if libcurl supports LDAP */
-/* #undef LIBCURL_PROTOCOL_LDAP */
+#define LIBCURL_PROTOCOL_LDAP 1
 
 /* Defined if libcurl supports POP3 */
-/* #undef LIBCURL_PROTOCOL_POP3 */
+#define LIBCURL_PROTOCOL_POP3 1
 
 /* Defined if libcurl supports RTSP */
-/* #undef LIBCURL_PROTOCOL_RTSP */
+#define LIBCURL_PROTOCOL_RTSP 1
 
 /* Defined if libcurl supports SMTP */
-/* #undef LIBCURL_PROTOCOL_SMTP */
+#define LIBCURL_PROTOCOL_SMTP 1
 
 /* Defined if libcurl supports TELNET */
-/* #undef LIBCURL_PROTOCOL_TELNET */
+#define LIBCURL_PROTOCOL_TELNET 1
 
 /* Defined if libcurl supports TFTP */
-/* #undef LIBCURL_PROTOCOL_TFTP */
+#define LIBCURL_PROTOCOL_TFTP 1
 
 /* This is a Linux kernel */
 #define LINUX 1
 
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
 #define LT_OBJDIR ".libs/"
 
-/* Define to use pair of sockets instead of pipes for signaling */
-/* #undef MHD_DONT_USE_PIPES */
+/* Define to '1' if you have address sanitizer enabled */
+/* #undef MHD_ASAN_ACTIVE */
 
-/* gnuTLS lib version - used in conjunction with cURL */
-/* #undef MHD_REQ_CURL_GNUTLS_VERSION */
+/* Define to '1' if user memory poison is used */
+/* #undef MHD_ASAN_POISON_ACTIVE */
 
-/* NSS lib version - used in conjunction with cURL */
-/* #undef MHD_REQ_CURL_NSS_VERSION */
+/* Define to '1' to use fast (and larger) code version */
+#define MHD_FAVOR_FAST_CODE 1
 
-/* required cURL SSL version to run tests */
-/* #undef MHD_REQ_CURL_OPENSSL_VERSION */
+/* Define to '1' to use compact code version */
+/* #undef MHD_FAVOR_SMALL_CODE */
 
-/* required cURL version to run tests */
-/* #undef MHD_REQ_CURL_VERSION */
+/* Define to 1 if you have suitable libmagic. */
+/* #undef MHD_HAVE_LIBMAGIC */
+
+/* Define to 1 if you have __builtin_bswap32() builtin function */
+#define MHD_HAVE___BUILTIN_BSWAP32 1
+
+/* Define to 1 if you have __builtin_bswap64() builtin function */
+#define MHD_HAVE___BUILTIN_BSWAP64 1
+
+/* Define to `1' if HTTPS require initialisation of libgcrypt */
+/* #undef MHD_HTTPS_REQUIRE_GCRYPT */
+
+/* Define to 1 if libmicrohttpd is compiled with MD5 hashing support. */
+#define MHD_MD5_SUPPORT 1
+
+/* Define to 1 if libmicrohttpd is compiled with MD5 hashing by TLS library.
+   */
+/* #undef MHD_MD5_TLSLIB */
+
+/* Define to 1 to disable setting name on generated threads */
+/* #undef MHD_NO_THREAD_NAMES */
+
+/* tls plugins */
+#define MHD_PLUGIN_INSTALL_PREFIX "/usr/local/lib/libmicrohttpd"
+
+/* Define to 1 if libmicrohttpd is compiled with SHA-256 hashing support. */
+#define MHD_SHA256_SUPPORT 1
+
+/* Define to 1 if libmicrohttpd is compiled with SHA-256 hashing by TLS
+   library. */
+/* #undef MHD_SHA256_TLSLIB */
+
+/* Define to 1 if libmicrohttpd is compiled with SHA-512/256 hashing support.
+   */
+#define MHD_SHA512_256_SUPPORT 1
+
+/* Define if you have usable `getsockname' function. */
+#define MHD_USE_GETSOCKNAME 1
+
+/* Define if you have usable PAGESIZE macro */
+/* #undef MHD_USE_PAGESIZE_MACRO */
+
+/* Define if you have PAGESIZE macro usable for static init */
+/* #undef MHD_USE_PAGESIZE_MACRO_STATIC */
+
+/* Define if you have usable PAGE_SIZE macro */
+/* #undef MHD_USE_PAGE_SIZE_MACRO */
+
+/* Define if you have PAGE_SIZE macro usable for static init */
+/* #undef MHD_USE_PAGE_SIZE_MACRO_STATIC */
 
 /* define to use pthreads */
 #define MHD_USE_POSIX_THREADS 1
 
+/* Define to 1 if you have properly working tsearch(), tfind() and tdelete()
+   functions. */
+#define MHD_USE_SYS_TSEARCH 1
+
 /* define to use W32 threads */
 /* #undef MHD_USE_W32_THREADS */
 
@@ -326,38 +594,65 @@
 #define PACKAGE_BUGREPORT "libmicrohttpd@gnu.org"
 
 /* Define to the full name of this package. */
-#define PACKAGE_NAME "libmicrohttpd"
+#define PACKAGE_NAME "GNU libmicrohttpd"
 
 /* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libmicrohttpd 0.9.42"
+#define PACKAGE_STRING "GNU libmicrohttpd 0.9.76"
 
 /* Define to the one symbol short name of this package. */
 #define PACKAGE_TARNAME "libmicrohttpd"
 
 /* Define to the home page for this package. */
-#define PACKAGE_URL ""
+#define PACKAGE_URL "https://www.gnu.org/software/libmicrohttpd/"
 
 /* Define to the version of this package. */
-#define PACKAGE_VERSION "0.9.42"
+#define PACKAGE_VERSION "0.9.76"
 
 /* Define to necessary symbol if this constant uses a non-standard name on
    your system. */
 /* #undef PTHREAD_CREATE_JOINABLE */
 
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `int64_t', as computed by sizeof. */
+#define SIZEOF_INT64_T 8
+
+/* The size of `size_t', as computed by sizeof. */
+#define SIZEOF_SIZE_T 8
+
+/* The size of `tv_sec' member of `struct timeval', as computed by sizeof */
+#define SIZEOF_STRUCT_TIMEVAL_TV_SEC 8
+
+/* The size of `uint64_t', as computed by sizeof. */
+#define SIZEOF_UINT64_T 8
+
+/* The size of `unsigned int', as computed by sizeof. */
+#define SIZEOF_UNSIGNED_INT 4
+
+/* The size of `unsigned long long', as computed by sizeof. */
+#define SIZEOF_UNSIGNED_LONG_LONG 8
+
 /* This is a Solaris system */
 /* #undef SOLARIS */
 
 /* This is a BSD system */
 /* #undef SOMEBSD */
 
-/* disable libmicrospdy support */
-#define SPDY_SUPPORT 0
-
-/* Define to 1 if you have the ANSI C header files. */
+/* Define to 1 if all of the C90 standard headers exist (not just the ones
+   required in a freestanding environment). This macro is provided for
+   backward compatibility; new code need not use it. */
 #define STDC_HEADERS 1
 
+/* Define to 1 if libmicrohttpd is compiled with HTTP Upgrade support. */
+#define UPGRADE_SUPPORT 1
+
+/* Define to 1 if your kernel supports IPv6 and IPv6 is enabled and useful for
+   testing. */
+#define USE_IPV6_TESTING 1
+
 /* Version number of package */
-#define VERSION "0.9.42"
+#define VERSION "0.9.76"
 
 /* This is a Windows system */
 /* #undef WINDOWS */
@@ -374,11 +669,6 @@
 # endif
 #endif
 
-/* Enable large inode numbers on Mac OS X 10.5.  */
-#ifndef _DARWIN_USE_64_BIT_INODE
-# define _DARWIN_USE_64_BIT_INODE 1
-#endif
-
 /* Number of bits in a file offset, on hosts where this is settable. */
 /* #undef _FILE_OFFSET_BITS */
 
@@ -388,11 +678,47 @@
 /* Define for large files, on AIX-style hosts. */
 /* #undef _LARGE_FILES */
 
-/* defines how to decorate public symbols while building */
+/* defines how to decorate public symbols while building the library */
 #define _MHD_EXTERN __attribute__((visibility("default"))) extern
 
-/* Need with solaris or errno doesnt work */
+/* Define to 1 to enable "heavy" test paths. */
+/* #undef _MHD_HEAVY_TESTS */
+
+/* Define to use eventFD for inter-thread communication */
+#define _MHD_ITC_EVENTFD 1
+
+/* Define to use pipe for inter-thread communication */
+/* #undef _MHD_ITC_PIPE */
+
+/* Define to use socketpair for inter-thread communication */
+/* #undef _MHD_ITC_SOCKETPAIR */
+
+/* Define to supported 'noreturn' function declaration */
+#define _MHD_NORETURN _Noreturn
+
+/* Define to 1 to enable "very heavy" test paths. */
+/* #undef _MHD_VHEAVY_TESTS */
+
+/* Define to prefix which will be used with MHD static inline functions. */
+#define _MHD_static_inline static inline __attribute__((always_inline))
+
+/* Need with solaris or errno does not work */
 /* #undef _REENTRANT */
 
+/* Define to 1 if C does not support variable-length arrays, and if the
+   compiler does not already define this. */
+/* #undef __STDC_NO_VLA__ */
+
+/* Define to type name which will be used as boolean type. */
+/* #undef bool */
+
 /* Define curl_free() as free() if our version of curl lacks curl_free. */
 /* #undef curl_free */
+
+/* Define to value interpreted by compiler as boolean "false", if "false" is
+   not defined by system headers. */
+/* #undef false */
+
+/* Define to value interpreted by compiler as boolean "true", if "true" is not
+   defined by system headers. */
+/* #undef true */
diff --git a/MHD_config.h.in b/MHD_config.h.in
deleted file mode 100644
index e476cda..0000000
--- a/MHD_config.h.in
+++ /dev/null
@@ -1,397 +0,0 @@
-/* MHD_config.h.in.  Generated from configure.ac by autoheader.  */
-
-#define _GNU_SOURCE  1
-
-/* Define if building universal (internal helper macro) */
-#undef AC_APPLE_UNIVERSAL_BUILD
-
-/* disable basic Auth support */
-#undef BAUTH_SUPPORT
-
-/* This is a Cygwin system */
-#undef CYGWIN
-
-/* disable digest Auth support */
-#undef DAUTH_SUPPORT
-
-/* define to 0 to disable epoll support */
-#undef EPOLL_SUPPORT
-
-/* This is a FreeBSD system */
-#undef FREEBSD
-
-/* Define to 1 if you have the `accept4' function. */
-#undef HAVE_ACCEPT4
-
-/* Define to 1 if you have the <arpa/inet.h> header file. */
-#undef HAVE_ARPA_INET_H
-
-/* Have clock_gettime */
-#undef HAVE_CLOCK_GETTIME
-
-/* Define to 1 if you have the declaration of `SOCK_NONBLOCK', and to 0 if you
-   don't. */
-#undef HAVE_DECL_SOCK_NONBLOCK
-
-/* Define to 1 if you have the declaration of `TCP_CORK', and to 0 if you
-   don't. */
-#undef HAVE_DECL_TCP_CORK
-
-/* Define to 1 if you have the declaration of `TCP_NOPUSH', and to 0 if you
-   don't. */
-#undef HAVE_DECL_TCP_NOPUSH
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#undef HAVE_DLFCN_H
-
-/* Define if you have epoll_create1 function. */
-#undef HAVE_EPOLL_CREATE1
-
-/* Define to 1 if you have the <errno.h> header file. */
-#undef HAVE_ERRNO_H
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#undef HAVE_FCNTL_H
-
-/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
-#undef HAVE_FSEEKO
-
-/* Define to 1 if you have the <gcrypt.h> header file. */
-#undef HAVE_GCRYPT_H
-
-/* Define to 1 if you have `gmtime_s' function (only for W32). */
-#undef HAVE_GMTIME_S
-
-/* Define to 1 if you have the <gnutls/gnutls.h> header file. */
-#undef HAVE_GNUTLS_GNUTLS_H
-
-/* Provides IPv6 headers */
-#undef HAVE_INET6
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#undef HAVE_INTTYPES_H
-
-/* Define to 1 if you have a functional curl library. */
-#undef HAVE_LIBCURL
-
-/* Define to 1 if you have the <limits.h> header file. */
-#undef HAVE_LIMITS_H
-
-/* can use shutdown on listen sockets */
-#undef HAVE_LISTEN_SHUTDOWN
-
-/* Define to 1 if you have the <locale.h> header file. */
-#undef HAVE_LOCALE_H
-
-/* Define to 1 if you have the <magic.h> header file. */
-#undef HAVE_MAGIC_H
-
-/* Define to 1 if you have the <math.h> header file. */
-#undef HAVE_MATH_H
-
-/* Define to 1 if you have the `memmem' function. */
-#undef HAVE_MEMMEM
-
-/* Define to 1 if you have the <memory.h> header file. */
-#undef HAVE_MEMORY_H
-
-/* Disable error messages */
-#undef HAVE_MESSAGES
-
-/* Define to 1 if you have the <netdb.h> header file. */
-#undef HAVE_NETDB_H
-
-/* Define to 1 if you have the <netinet/in.h> header file. */
-#undef HAVE_NETINET_IN_H
-
-/* Define to 1 if you have the <netinet/tcp.h> header file. */
-#undef HAVE_NETINET_TCP_H
-
-/* Define to 1 if you have the <openssl/engine.h> header file. */
-#undef HAVE_OPENSSL_ENGINE_H
-
-/* Define to 1 if you have the <openssl/err.h> header file. */
-#undef HAVE_OPENSSL_ERR_H
-
-/* Define to 1 if you have the <openssl/evp.h> header file. */
-#undef HAVE_OPENSSL_EVP_H
-
-/* Define to 1 if you have the <openssl/pem.h> header file. */
-#undef HAVE_OPENSSL_PEM_H
-
-/* Define to 1 if you have the <openssl/rand.h> header file. */
-#undef HAVE_OPENSSL_RAND_H
-
-/* Define to 1 if you have the <openssl/rsa.h> header file. */
-#undef HAVE_OPENSSL_RSA_H
-
-/* Define to 1 if you have the <openssl/sha.h> header file. */
-#undef HAVE_OPENSSL_SHA_H
-
-/* Define to 1 if you have the `poll' function. */
-#undef HAVE_POLL
-
-/* Define to 1 if you have the <poll.h> header file. */
-#undef HAVE_POLL_H
-
-/* define to 1 if MHD was build with postprocessor.c */
-#undef HAVE_POSTPROCESSOR
-
-/* Define to 1 if you have the <pthread.h> header file. */
-#undef HAVE_PTHREAD_H
-
-/* Have PTHREAD_PRIO_INHERIT. */
-#undef HAVE_PTHREAD_PRIO_INHERIT
-
-/* Define if you have pthread_setname_np function. */
-#undef HAVE_PTHREAD_SETNAME_NP
-
-/* Define to 1 if you have the <search.h> header file. */
-#undef HAVE_SEARCH_H
-
-/* Do we have sockaddr_in.sin_len? */
-#undef HAVE_SOCKADDR_IN_SIN_LEN
-
-/* SOCK_NONBLOCK is defined in a socket header */
-#undef HAVE_SOCK_NONBLOCK
-
-/* Define to 1 if you have the <spdylay/spdylay.h> header file. */
-#undef HAVE_SPDYLAY_SPDYLAY_H
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#undef HAVE_STDINT_H
-
-/* Define to 1 if you have the <stdio.h> header file. */
-#undef HAVE_STDIO_H
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#undef HAVE_STDLIB_H
-
-/* Define to 1 if you have the <strings.h> header file. */
-#undef HAVE_STRINGS_H
-
-/* Define to 1 if you have the <string.h> header file. */
-#undef HAVE_STRING_H
-
-/* Define to 1 if you have the <sys/mman.h> header file. */
-#undef HAVE_SYS_MMAN_H
-
-/* Define to 1 if you have the <sys/msg.h> header file. */
-#undef HAVE_SYS_MSG_H
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#undef HAVE_SYS_SELECT_H
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#undef HAVE_SYS_SOCKET_H
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#undef HAVE_SYS_STAT_H
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#undef HAVE_SYS_TIME_H
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#undef HAVE_SYS_TYPES_H
-
-/* Define to 1 if you have the <time.h> header file. */
-#undef HAVE_TIME_H
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#undef HAVE_UNISTD_H
-
-/* Define to 1 if you have the <winsock2.h> header file. */
-#undef HAVE_WINSOCK2_H
-
-/* Define to 1 if you have the <ws2tcpip.h> header file. */
-#undef HAVE_WS2TCPIP_H
-
-/* disable HTTPS support */
-#undef HTTPS_SUPPORT
-
-/* Defined if libcurl supports AsynchDNS */
-#undef LIBCURL_FEATURE_ASYNCHDNS
-
-/* Defined if libcurl supports IDN */
-#undef LIBCURL_FEATURE_IDN
-
-/* Defined if libcurl supports IPv6 */
-#undef LIBCURL_FEATURE_IPV6
-
-/* Defined if libcurl supports KRB4 */
-#undef LIBCURL_FEATURE_KRB4
-
-/* Defined if libcurl supports libz */
-#undef LIBCURL_FEATURE_LIBZ
-
-/* Defined if libcurl supports NTLM */
-#undef LIBCURL_FEATURE_NTLM
-
-/* Defined if libcurl supports SSL */
-#undef LIBCURL_FEATURE_SSL
-
-/* Defined if libcurl supports SSPI */
-#undef LIBCURL_FEATURE_SSPI
-
-/* Defined if libcurl supports DICT */
-#undef LIBCURL_PROTOCOL_DICT
-
-/* Defined if libcurl supports FILE */
-#undef LIBCURL_PROTOCOL_FILE
-
-/* Defined if libcurl supports FTP */
-#undef LIBCURL_PROTOCOL_FTP
-
-/* Defined if libcurl supports FTPS */
-#undef LIBCURL_PROTOCOL_FTPS
-
-/* Defined if libcurl supports HTTP */
-#undef LIBCURL_PROTOCOL_HTTP
-
-/* Defined if libcurl supports HTTPS */
-#undef LIBCURL_PROTOCOL_HTTPS
-
-/* Defined if libcurl supports IMAP */
-#undef LIBCURL_PROTOCOL_IMAP
-
-/* Defined if libcurl supports LDAP */
-#undef LIBCURL_PROTOCOL_LDAP
-
-/* Defined if libcurl supports POP3 */
-#undef LIBCURL_PROTOCOL_POP3
-
-/* Defined if libcurl supports RTSP */
-#undef LIBCURL_PROTOCOL_RTSP
-
-/* Defined if libcurl supports SMTP */
-#undef LIBCURL_PROTOCOL_SMTP
-
-/* Defined if libcurl supports TELNET */
-#undef LIBCURL_PROTOCOL_TELNET
-
-/* Defined if libcurl supports TFTP */
-#undef LIBCURL_PROTOCOL_TFTP
-
-/* This is a Linux kernel */
-#undef LINUX
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-#undef LT_OBJDIR
-
-/* Define to use pair of sockets instead of pipes for signaling */
-#undef MHD_DONT_USE_PIPES
-
-/* gnuTLS lib version - used in conjunction with cURL */
-#undef MHD_REQ_CURL_GNUTLS_VERSION
-
-/* NSS lib version - used in conjunction with cURL */
-#undef MHD_REQ_CURL_NSS_VERSION
-
-/* required cURL SSL version to run tests */
-#undef MHD_REQ_CURL_OPENSSL_VERSION
-
-/* required cURL version to run tests */
-#undef MHD_REQ_CURL_VERSION
-
-/* define to use pthreads */
-#undef MHD_USE_POSIX_THREADS
-
-/* define to use W32 threads */
-#undef MHD_USE_W32_THREADS
-
-/* This is a MinGW system */
-#undef MINGW
-
-/* This is a NetBSD system */
-#undef NETBSD
-
-/* This is an OpenBSD system */
-#undef OPENBSD
-
-/* This is a OS/390 system */
-#undef OS390
-
-/* This is an OS X system */
-#undef OSX
-
-/* Some strange OS */
-#undef OTHEROS
-
-/* Name of package */
-#undef PACKAGE
-
-/* Define to the address where bug reports for this package should be sent. */
-#undef PACKAGE_BUGREPORT
-
-/* Define to the full name of this package. */
-#undef PACKAGE_NAME
-
-/* Define to the full name and version of this package. */
-#undef PACKAGE_STRING
-
-/* Define to the one symbol short name of this package. */
-#undef PACKAGE_TARNAME
-
-/* Define to the home page for this package. */
-#undef PACKAGE_URL
-
-/* Define to the version of this package. */
-#undef PACKAGE_VERSION
-
-/* Define to necessary symbol if this constant uses a non-standard name on
-   your system. */
-#undef PTHREAD_CREATE_JOINABLE
-
-/* This is a Solaris system */
-#undef SOLARIS
-
-/* This is a BSD system */
-#undef SOMEBSD
-
-/* disable libmicrospdy support */
-#undef SPDY_SUPPORT
-
-/* Define to 1 if you have the ANSI C header files. */
-#undef STDC_HEADERS
-
-/* Version number of package */
-#undef VERSION
-
-/* This is a Windows system */
-#undef WINDOWS
-
-/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
-   significant byte first (like Motorola and SPARC, unlike Intel). */
-#if defined AC_APPLE_UNIVERSAL_BUILD
-# if defined __BIG_ENDIAN__
-#  define WORDS_BIGENDIAN 1
-# endif
-#else
-# ifndef WORDS_BIGENDIAN
-#  undef WORDS_BIGENDIAN
-# endif
-#endif
-
-/* Enable large inode numbers on Mac OS X 10.5.  */
-#ifndef _DARWIN_USE_64_BIT_INODE
-# define _DARWIN_USE_64_BIT_INODE 1
-#endif
-
-/* Number of bits in a file offset, on hosts where this is settable. */
-#undef _FILE_OFFSET_BITS
-
-/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
-#undef _LARGEFILE_SOURCE
-
-/* Define for large files, on AIX-style hosts. */
-#undef _LARGE_FILES
-
-/* defines how to decorate public symbols while building */
-#undef _MHD_EXTERN
-
-/* Need with solaris or errno doesnt work */
-#undef _REENTRANT
-
-/* Define curl_free() as free() if our version of curl lacks curl_free. */
-#undef curl_free
diff --git a/Makefile.am b/Makefile.am
index 03f42c0..218d7b1 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,14 +1,432 @@
 # This Makefile.am is in the public domain
 ACLOCAL_AMFLAGS = -I m4
-SUBDIRS = contrib src m4 .
-EXTRA_DIST = acinclude.m4 libmicrohttpd.pc.in libmicrospdy.pc.in  \
-  w32/VS2013/libmicrohttpd.sln w32/VS2013/libmicrohttpd.vcxproj w32/VS2013/libmicrohttpd.vcxproj.filters \
-  w32/VS2013/hellobrowser.vcxproj w32/VS2013/hellobrowser.vcxproj.filters w32/VS2013/MHD_config.h \
-  w32/VS2013/gen_dll_res.ps1 w32/VS2013/microhttpd_dll_res_vc.rc.in w32/VS2013/microhttpd_dll_res_vc.rc
-
-pkgconfigdir = $(libdir)/pkgconfig
-pkgconfig_DATA = libmicrohttpd.pc libmicrospdy.pc
+SUBDIRS = contrib m4 src .
 
 if BUILD_DOC
 SUBDIRS += doc
 endif
+
+
+W32COMMON = w32/common/gen_dll_res.ps1 w32/common/microhttpd_dll_res_vc.rc.in w32/common/microhttpd_dll_res_vc.rc \
+  w32/common/MHD_config.h w32/common/vs_dirs.props \
+  w32/common/common-build-settings.props w32/common/libmicrohttpd-build-settings.props \
+  w32/common/apps-build-settings.props \
+  w32/common/project-configs.props w32/common/project-configs-xp.props \
+  w32/common/libmicrohttpd-files.vcxproj w32/common/libmicrohttpd-filters.vcxproj \
+  w32/common/hellobrowser-files.vcxproj w32/common/hellobrowser-filters.vcxproj
+W32VS2013 = w32/VS2013/libmicrohttpd.vcxproj w32/VS2013/libmicrohttpd.vcxproj.filters \
+  w32/VS2013/hellobrowser.vcxproj w32/VS2013/hellobrowser.vcxproj.filters \
+  w32/VS2013/simplepost.vcxproj w32/VS2013/largepost.vcxproj \
+  w32/VS2013/libmicrohttpd.sln
+W32VS2015 = w32/VS2015/libmicrohttpd.vcxproj w32/VS2015/libmicrohttpd.vcxproj.filters \
+  w32/VS2015/hellobrowser.vcxproj w32/VS2015/hellobrowser.vcxproj.filters \
+  w32/VS2015/simplepost.vcxproj w32/VS2015/largepost.vcxproj \
+  w32/VS2015/libmicrohttpd.sln
+W32VS2017 = w32/VS2017/libmicrohttpd.vcxproj w32/VS2017/libmicrohttpd.vcxproj.filters \
+  w32/VS2017/hellobrowser.vcxproj w32/VS2017/hellobrowser.vcxproj.filters \
+  w32/VS2017/simplepost.vcxproj w32/VS2017/largepost.vcxproj \
+  w32/VS2017/libmicrohttpd.sln
+W32VS2019 = w32/VS2019/libmicrohttpd.vcxproj w32/VS2019/libmicrohttpd.vcxproj.filters \
+  w32/VS2019/hellobrowser.vcxproj w32/VS2019/hellobrowser.vcxproj.filters \
+  w32/VS2019/simplepost.vcxproj w32/VS2019/largepost.vcxproj \
+  w32/VS2019/libmicrohttpd.sln
+W32VS2022 = w32/VS2022/libmicrohttpd.vcxproj w32/VS2022/libmicrohttpd.vcxproj.filters \
+  w32/VS2022/hellobrowser.vcxproj w32/VS2022/hellobrowser.vcxproj.filters \
+  w32/VS2022/simplepost.vcxproj w32/VS2022/largepost.vcxproj \
+  w32/VS2022/libmicrohttpd.sln
+W32VSAV = w32/VS-Any-Version/libmicrohttpd.vcxproj w32/VS-Any-Version/libmicrohttpd.vcxproj.filters \
+  w32/VS-Any-Version/hellobrowser.vcxproj w32/VS-Any-Version/hellobrowser.vcxproj.filters \
+  w32/VS-Any-Version/simplepost.vcxproj w32/VS-Any-Version/largepost.vcxproj \
+  w32/VS-Any-Version/libmicrohttpd.sln
+
+EXTRA_DIST = \
+  libmicrohttpd.pc.in \
+  $(W32COMMON) $(W32VS2013) $(W32VS2015) $(W32VS2017) \
+  $(W32VS2019) $(W32VS2022) $(W32VSAV)
+
+pkgconfigdir = $(libdir)/pkgconfig
+pkgconfig_DATA = libmicrohttpd.pc
+
+EXTRA_DIST += pre-dist-hook-dummy
+MOSTLYCLEANFILES = pre-dist-hook-dummy
+DISTCLEANFILES = 
+MAINTAINERCLEANFILES = m4/c_backported.m4
+
+pre-dist-hook-dummy: pre-dist-hook Makefile
+	@echo "dummy" > $@
+
+dist-hook: dist-po
+	@chmod u+w '$(distdir)/pre-dist-hook-dummy' && \
+	  rm -f '$(distdir)/pre-dist-hook-dummy'
+	@rm -f pre-dist-hook-dummy
+	@if test -w '$(distdir)/m4/c_backported.m4'; then \
+	  echo "Use empty m4/c_backported.m4 for dist target"; \
+	  touch -r '$(distdir)/m4/c_backported.m4' '$(distdir)/m4/c_backported.m4-tmst' && \
+	    echo 'dnl Not used for distribution' > '$(distdir)/m4/c_backported.m4' && \
+	    touch -r '$(distdir)/m4/c_backported.m4-tmst' '$(distdir)/m4/c_backported.m4' && \
+	    rm -f '$(distdir)/m4/c_backported.m4-tmst'; \
+	else \
+	  true; \
+	fi
+
+dist-custm: distdir
+	@test -n "$(ARC_CMD)" || \
+	  { echo 'The valid archive command must be defined by "ARC_CMD".' >&2; false; }
+	@test -n "$(ARC_EXT)" || \
+	  { echo 'The archive file extention must be set by "ARC_EXT".' >&2; false; }
+	-rm -f '$(distdir).$(ARC_EXT)'
+	tardir=$(distdir) && $(am__tar) | $(ARC_CMD) >$(distdir).$(ARC_EXT)
+	$(am__post_remove_distdir)
+
+dist-custm2: distdir
+	@test -n "$(ARC_CMD)" || \
+	  { echo 'The valid archive command must be defined by "ARC_CMD".' >&2; false; }
+	@test -n "$(ARC_EXT)" || \
+	  { echo 'The archive file extention must be set by "ARC_EXT".' >&2; false; }
+	-rm -f '$(distdir).$(ARC_EXT)'
+	tardir=$(distdir) && $(am__tar) >$(distdir).tar && $(ARC_CMD) $(distdir).tar
+	rm -f $(distdir).tar
+	$(am__post_remove_distdir)
+
+pre-dist-hook: pre-dist-hook-doc
+	@echo "Preparing to make dist"
+
+pre-dist-hook-doc:
+	@echo "Preparing to make dist in doc"
+	@if test -w '$(top_srcdir)/doc' ; then \
+	  $(am__cd) doc && $(MAKE) $(AM_MAKEFLAGS) update-stamp; \
+	else \
+	  echo "Source tree is read-only, skipping force doc update"; \
+	fi;
+
+.PHONY: pre-dist-hook pre-dist-hook-doc
+
+# Works with old automake versions (<1.12.2) as "false"
+MHD_V = $(AM_V_P) false
+
+distclean-local: distclean-po
+
+maintainer-clean-local: maintainer-clean-po
+
+srcdir_po = $(top_srcdir)/po
+
+PO_ACLOCAL_M4 = $(srcdir_po)/aclocal.m4
+
+PO_MAIN_FILES = $(srcdir_po)/Makefile.in.in $(srcdir_po)/remove-potcdate.sin \
+  $(srcdir_po)/quot.sed $(srcdir_po)/boldquot.sed \
+  $(srcdir_po)/en@quot.header $(srcdir_po)/en@boldquot.header \
+  $(srcdir_po)/insert-header.sin $(srcdir_po)/Rules-quot
+
+PO_EXTRA_FILES = $(srcdir_po)/Makevars.template
+
+PO_ROOT_FILES = $(srcdir_po)/ABOUT-NLS
+
+PO_M4_FILES = $(srcdir_po)/m4/gettext.m4 $(srcdir_po)/m4/host-cpu-c-abi.m4 \
+  $(srcdir_po)/m4/iconv.m4 $(srcdir_po)/m4/intlmacosx.m4 \
+  $(srcdir_po)/m4/lib-ld.m4 $(srcdir_po)/m4/lib-link.m4 \
+  $(srcdir_po)/m4/lib-prefix.m4 $(srcdir_po)/m4/nls.m4 \
+  $(srcdir_po)/m4/po.m4 $(srcdir_po)/m4/progtest.m4
+
+PO_AUX_FILES = $(srcdir_po)/$(MHD_AUX_DIR)/config.rpath
+
+# All autopoint-created files
+PO_ALL_FILES = $(PO_MAIN_FILES) $(PO_EXTRA_FILES) $(PO_ROOT_FILES) \
+  $(PO_M4_FILES) $(PO_AUX_FILES)
+
+am__po_aclocal_m4_deps = $(PO_M4_FILES) $(srcdir_po)/configure.ac
+am__po_configure_deps = $(am__po_aclocal_m4_deps) $(PO_ACLOCAL_M4)
+
+$(PO_ACLOCAL_M4): $(am__po_aclocal_m4_deps)
+	@{ $(MHD_V) && echo "Building $@" ; } || true
+	@echo "cd $(srcdir_po) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)" && \
+	  $(am__cd) '$(srcdir_po)' && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
+
+# Do update po/configure.ac only if template files updated
+$(srcdir_po)/configure.ac: $(srcdir_po)/po-configure.ac.in $(top_srcdir)/configure.ac
+	@{ $(MHD_V) && echo "Building $@" ; } || true
+	@$(MAKE) $(AM_MAKEFLAGS) po/po-configure.ac
+	@cp -f po/po-configure.ac '$@'
+
+$(top_srcdir)/po-configure: $(srcdir_po)/configure.ac $(PO_ACLOCAL_M4) $(PO_AUX_FILES) $(srcdir_po)/$(MHD_AUX_DIR)/install-sh
+	@{ $(MHD_V) && echo "Building $@" ; } || true
+	@echo "cd $(srcdir_po) && $(AUTOCONF)" && \
+	  ( $(am__cd) '$(srcdir_po)' && $(AUTOCONF) )
+	mv -f '$(srcdir_po)/configure' '$@'
+	-chmod a-x '$@'
+
+EXTRA_DIST += $(top_srcdir)/$(MHD_AUX_DIR)/config.rpath $(srcdir_po)/$(MHD_AUX_DIR)/install-sh \
+  $(PO_ALL_FILES) \
+  $(PO_ACLOCAL_M4) \
+  $(srcdir_po)/po-configure.ac.in $(srcdir_po)/configure.ac \
+  $(top_srcdir)/po-configure \
+  $(srcdir_po)/stamp-m.in
+
+DISTCLEANFILES += config.main.log po-config.log po/stamp-m
+MAINTAINERCLEANFILES += $(srcdir_po)/configure.ac
+
+$(srcdir_po)/stamp-m.in:
+	@: > '$@'
+
+po-config.status: $(top_srcdir)/po-configure $(top_srcdir)/$(MHD_AUX_DIR)/install-sh $(top_srcdir)/$(MHD_AUX_DIR)/config.rpath
+	@if test -f config.log; then \
+	  mv -f config.log config.main.log; \
+	else \
+	  true; \
+	fi
+	@SHELL@ '$(top_srcdir)/po-configure' $(ac_configure_args) --silent --no-create --no-recursion --disable-option-checking
+	@mv -f config.log po-config.log
+	@if test -f config.main.log; then \
+	  mv -f config.main.log config.log; \
+	else \
+	  true; \
+	fi
+
+po/Makefile: $(srcdir_po)/Makefile.in.in $(srcdir_po)/Makevars po-config.status $(srcdir_po)/POTFILES.in $(srcdir_po)/stamp-m.in
+	@: && @SHELL@ ./po-config.status po/stamp-m po/Makefile.in po-directories
+
+dist-po: po/Makefile $(PO_MAIN_FILES)
+	@dir1="po"; dir2="$(distdir)/po"; \
+	$(am__relativize); \
+	rel_distsubdir=$$reldir; \
+	echo "cd po && $(MAKE) $(AM_MAKEFLAGS) distdir='$$rel_distsubdir' distdir" && \
+	$(am__cd) po && $(MAKE) $(AM_MAKEFLAGS) distdir="$$rel_distsubdir" distdir
+
+$(srcdir_po)/POTFILES.in: $(top_srcdir)/src/microhttpd/Makefile.am
+	@echo "cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) update-po-POTFILES.in" && \
+	$(am__cd) '$(top_builddir)/src/microhttpd' && $(MAKE) $(AM_MAKEFLAGS) update-po-POTFILES.in
+
+AUTOPOINT = autopoint
+AUTOPOINT_FLAGS = 
+
+APIM_LOCK_BASE = autopoint-updating-lock
+APIM_TMSTMP_BASE = autopoint-timestamp
+APIM_TMSTMP_TMP_BASE = $(APIM_TMSTMP_BASE)-tmp
+APIM_TRIGGER_BASE = autopoint-trigger
+APIM_LOCK = $(srcdir_po)/$(APIM_LOCK_BASE)
+APIM_TMSTMP = $(srcdir_po)/$(APIM_TMSTMP_BASE)
+APIM_TMSTMP_TMP = $(srcdir_po)/$(APIM_TMSTMP_TMP_BASE)
+APIM_TRIGGER = $(srcdir_po)/$(APIM_TRIGGER_BASE)
+# Run 'autopoint' even if no file missing
+FORCE_AUTOPOINT_CHECK = no
+
+LOCK_TIMEOUT_VALUE = 120
+
+EXTRA_DIST += $(APIM_TMSTMP) $(APIM_TRIGGER)
+
+sleep_with_timeout = \
+    sleep 1; \
+    sec_waiting=`expr ${sec_waiting} + 1`; \
+    if test $${sec_waiting} -gt '$(LOCK_TIMEOUT_VALUE)'; then \
+        echo "Waiting timeout" 1>&2; \
+        rmdir "$${lock_name}" ; \
+        exit 1; \
+    fi
+
+wait_for_unlock = \
+    test -n "$${lock_name}" || lock_name='$(APIM_LOCK)'; \
+    if test -d "$${lock_name}"; then \
+        { $(MHD_V) && \
+            echo "Autopoint files are being updated in parallel thread, wait"; } || : ; \
+        sec_waiting=0; \
+        while test -d "$${lock_name}"; do \
+            $(sleep_with_timeout) ; \
+        done; \
+    fi
+
+apim_prepare = \
+    $(am__cd) '$(srcdir_po)' || exit 1; \
+    lock_name='$(APIM_LOCK_BASE)'; \
+    { trap "rm -rf $(APIM_TMSTMP_BASE) $(APIM_TMSTMP_TMP_BASE) $${lock_name} po" HUP ABRT INT TERM 2>/dev/null && \
+    trap "rm -rf $(APIM_TMSTMP_BASE) $(APIM_TMSTMP_TMP_BASE) $${lock_name} po" PIPE 2>/dev/null ; } || \
+    trap "rm -rf $(APIM_TMSTMP_BASE) $(APIM_TMSTMP_TMP_BASE) $${lock_name} po" 1 2 13 15; \
+    lock_held='false'; \
+    sec_waiting=0; \
+    while : ; do \
+        if mkdir "$${lock_name}" 2>/dev/null; then lock_held=':' ; else : ; fi; \
+        $${lock_held} && break || : ; \
+        test 'xyes' = 'x$(FORCE_AUTOPOINT_CHECK)' || break ; \
+        $(sleep_with_timeout) ; \
+    done; \
+    if $${lock_held} ; then \
+        rm -f '$(APIM_TMSTMP_BASE)' '$(APIM_TMSTMP_TMP_BASE)' || exit 1; \
+        echo 'timestamp' > '$(APIM_TMSTMP_TMP_BASE)' || exit 1; \
+        if test 'xyes' = 'x$(FORCE_AUTOPOINT_CHECK)'; then \
+            call_autopoint=':'; check_all='false'; \
+        else \
+            call_autopoint='false'; check_all=':'; \
+        fi; \
+        if $(MHD_V) ; then apim_echo='echo' ; else apim_echo=':'; fi ;\
+        $$apim_echo "Sync autopoint files"; \
+        files_missing='false'; \
+        $(MKDIR_P) 'po'; \
+        $(MKDIR_P) '$(MHD_AUX_DIR)'; \
+        main_f_names=`for f in $(PO_MAIN_FILES) $(PO_EXTRA_FILES); do echo "$$f"; done | $(SED) -e 's|^.*/||'`; \
+        root_f_names=`for f in $(PO_ROOT_FILES); do echo "$$f"; done | $(SED) -e 's|^.*/||'`; \
+        m4_f_names=`for f in $(PO_M4_FILES); do echo "$$f"; done | $(SED) -e 's|^.*/||'`; \
+        aux_f_names=`for f in $(PO_AUX_FILES); do echo "$$f"; done | $(SED) -e 's|^.*/||'`; \
+        for f in $${main_f_names}; do \
+            if test -f "$$f"; then \
+                 cp -f "$$f" "po/$$f" ; \
+            else \
+                $$apim_echo "Missing $(srcdir_po)/$$f" ; \
+                files_missing=':' ; \
+            fi; \
+        done; \
+        if $${check_all} ; then \
+            for f in $${root_f_names}; do \
+                if test -f "./$$f"; then : ; \
+                else \
+                    $$apim_echo "Missing $(srcdir_po)/$$f" ; \
+                    files_missing=':' ; \
+                fi; \
+            done; \
+            for f in $${m4_f_names}; do \
+                if test -f "m4/$$f"; then : ; \
+                else \
+                    $$apim_echo "Missing $(srcdir_po)/m4/$$f" ; \
+                    files_missing=':' ; \
+                fi; \
+            done; \
+            for f in $${aux_f_names}; do \
+                if test -f "$(MHD_AUX_DIR)/$$f"; then : ;\
+                else \
+                    $$apim_echo "Missing $(srcdir_po)/$(MHD_AUX_DIR)/$$f" ; \
+                    files_missing=':' ; \
+                fi; \
+            done; \
+        fi; \
+        if $${files_missing} ; then \
+            call_autopoint=':' ; \
+            $$apim_echo "Some files are missing, call autopoint to restore them" ; \
+        elif $${call_autopoint}; then $$apim_echo "Check and update autopoint files" ; \
+        fi; \
+        rc_code=0; \
+        if $${call_autopoint} ; then \
+            echo '  cd $(srcdir_po) && $(AUTOPOINT) $(AUTOPOINT_FLAGS)'; \
+            '$(AUTOPOINT)' $(AUTOPOINT_FLAGS) || rc_code=1; \
+        fi; \
+        if test "$${rc_code}" = "0"; then \
+            $$apim_echo "Re-sync autopoint files back"; \
+            for f in $${aux_f_names}; do \
+                if test -f "$(MHD_AUX_DIR)/$$f"; then \
+                    touch -f "$(MHD_AUX_DIR)/$$f" && \
+                    cp -f "$(MHD_AUX_DIR)/$$f" "../$(MHD_AUX_DIR)/$$f"; \
+                else \
+                    $$apim_echo "Still missing $(srcdir_po)/$(MHD_AUX_DIR)/$$f" 1>&2 ; \
+                    rc_code=1; \
+                fi; \
+            done; \
+            for f in $${m4_f_names}; do \
+                if test -f "m4/$$f"; then \
+                    touch "m4/$$f"; \
+                else \
+                    $$apim_echo "Still missing $(srcdir_po)/m4/$$f" 1>&2 ; \
+                    rc_code=1; \
+                fi; \
+            done; \
+            for f in $${root_f_names}; do \
+                if test -f "./$$f"; then \
+                    touch "./$$f"; \
+                else \
+                    $$apim_echo "Still missing $(srcdir_po)/$$f" 1>&2 ; \
+                    rc_code=1; \
+                fi; \
+            done; \
+            for f in $${main_f_names}; do \
+                if test -f "po/$$f"; then \
+                    cp -f "po/$$f" "$$f"; \
+                else \
+                    $$apim_echo "Still missing $(srcdir_po)/$$f" 1>&2 ; \
+                    rc_code=1; \
+                fi; \
+            done; \
+        fi; \
+        if test $${rc_code} = 0; then \
+            cp -fp '$(APIM_TMSTMP_TMP_BASE)' '$(APIM_TMSTMP_BASE)' ; \
+            touch -r '$(APIM_TMSTMP_TMP_BASE)' '$(APIM_TMSTMP_BASE)' ; \
+            $$apim_echo "All autopoint files have been synced"; \
+            rm -f '$(APIM_TMSTMP_TMP_BASE)'; \
+        else \
+            rm -f '$(APIM_TMSTMP_BASE)' '$(APIM_TMSTMP_TMP_BASE)'; \
+        fi; \
+        rm -fr 'po'; \
+        rmdir "$${lock_name}"; \
+        exit $${rc_code} ; \
+    else \
+        $(wait_for_unlock) ; \
+        test -f '$(APIM_TMSTMP_BASE)' || exit 1; \
+    fi; \
+    :
+
+mostlyclean-local: mostlyclean-autopoint-update
+mostlyclean-autopoint-update:
+	-test -d '$(APIM_LOCK)' && rm -rf '$(APIM_LOCK)'
+	-test -d '$(srcdir_po)/po' && rm -rf '$(srcdir_po)/po'
+	rm -f '$(APIM_TMSTMP_TMP)'
+
+$(APIM_TRIGGER):
+	@echo "autopoint files rebuild trigger" > "$@"
+
+$(APIM_TMSTMP): $(srcdir_po)/configure.ac $(APIM_TRIGGER)
+	@ $(apim_prepare)
+
+.DELETE_ON_ERROR: $(APIM_TMSTMP)
+
+$(PO_ALL_FILES): $(APIM_TMSTMP) $(srcdir_po)/configure.ac
+	@ ( $(apim_prepare) )
+	@test -f '$@'
+
+prepare-autopoint: $(srcdir_po)/configure.ac
+	@ ( $(apim_prepare) )
+	@test -f '$(APIM_TMSTMP)'
+
+check-prepare-autopoint: $(srcdir_po)/$(MHD_AUX_DIR)/install-sh $(APIM_TMSTMP)
+	@echo "Check all autopoint files"; \
+	    files_missing='false'; \
+	    for f in $(PO_ALL_FILES); do \
+	        if test -f "$$f"; then : ; \
+	        else \
+	            echo "Missing $$f" ; \
+	            files_missing=':' ; \
+	        fi; \
+	    done; \
+	    if $${files_missing}; then \
+	        $(MAKE) $(AM_MAKEFLAGS) prepare-autopoint || exit 1; \
+	    else \
+	        exit 0; \
+	    fi
+
+# This could be used to update autopoint files for git or for 'dist' target
+update-autopoint-force:
+	$(MAKE) $(AM_MAKEFLAGS) 'FORCE_AUTOPOINT_CHECK=yes' 'AUTOPOINT_FLAGS=$(AUTOPOINT_FLAGS) -f' prepare-autopoint
+
+autopoint-files-all: $(APIM_TRIGGER) $(APIM_TMSTMP) $(PO_MAIN_FILES) $(PO_EXTRA_FILES) $(PO_M4_FILES) $(PO_AUX_FILES) $(srcdir_po)/$(MHD_AUX_DIR)/install-sh
+
+$(top_srcdir)/$(MHD_AUX_DIR)/config.rpath: $(srcdir_po)/$(MHD_AUX_DIR)/config.rpath
+	cp -f '$(srcdir_po)/$(MHD_AUX_DIR)/config.rpath' '$@'
+
+$(srcdir_po)/$(MHD_AUX_DIR)/install-sh: $(top_srcdir)/$(MHD_AUX_DIR)/install-sh
+	$(MKDIR_P) '$(srcdir_po)/$(MHD_AUX_DIR)'
+	cp -f '$(top_srcdir)/$(MHD_AUX_DIR)/install-sh' '$@'
+
+.PHONY: mostlyclean-autopoint-update prepare-autopoint update-autopoint-force check-prepare-autopoint autopoint-files-all
+
+distclean-po:
+	@( if test -f po/Makefile; then \
+	   $(am__cd) po && $(MAKE) $(AM_MAKEFLAGS) distclean; \
+	else \
+	  true; \
+	fi )
+	-rm -f po-config.status po/Makefile po/stamp-m
+	-rm -f po/POTFILES po/remove-potcdate.sed po/Makefile.in
+
+maintainer-clean-po:
+	@( if test -f po/Makefile; then \
+	  $(am__cd) po && $(MAKE) $(AM_MAKEFLAGS) maintainer-clean; \
+	else \
+	  true; \
+	fi )
+	-rm -f po/$(PACKAGE_TARNAME).pot
+	-rm -rf $(srcdir_po)/autom4te.cache
+
+.PHONY: distclean-po maintainer-clean-po
diff --git a/Makefile.in b/Makefile.in
deleted file mode 100644
index 7b2ebbc..0000000
--- a/Makefile.in
+++ /dev/null
@@ -1,931 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@BUILD_DOC_TRUE@am__append_1 = doc
-subdir = .
-DIST_COMMON = INSTALL NEWS README AUTHORS ChangeLog \
-	$(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/configure $(am__configure_deps) \
-	$(srcdir)/MHD_config.h.in $(srcdir)/libmicrohttpd.pc.in \
-	$(srcdir)/libmicrospdy.pc.in \
-	$(top_srcdir)/w32/VS2013/microhttpd_dll_res_vc.rc.in COPYING \
-	compile config.guess config.sub depcomp install-sh missing \
-	ltmain.sh
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
- configure.lineno config.status.lineno
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = MHD_config.h
-CONFIG_CLEAN_FILES = libmicrohttpd.pc libmicrospdy.pc \
-	w32/VS2013/microhttpd_dll_res_vc.rc
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(pkgconfigdir)"
-DATA = $(pkgconfig_DATA)
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	cscope distdir dist dist-all distcheck
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \
-	$(LISP)MHD_config.h.in
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-CSCOPE = cscope
-DIST_SUBDIRS = contrib src m4 . doc
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-distdir = $(PACKAGE)-$(VERSION)
-top_distdir = $(distdir)
-am__remove_distdir = \
-  if test -d "$(distdir)"; then \
-    find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \
-      && rm -rf "$(distdir)" \
-      || { sleep 5 && rm -rf "$(distdir)"; }; \
-  else :; fi
-am__post_remove_distdir = $(am__remove_distdir)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-DIST_ARCHIVES = $(distdir).tar.gz
-GZIP_ENV = --best
-DIST_TARGETS = dist-gzip
-distuninstallcheck_listfiles = find . -type f -print
-am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \
-  | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$'
-distcleancheck_listfiles = find . -type f -print
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-ACLOCAL_AMFLAGS = -I m4
-SUBDIRS = contrib src m4 . $(am__append_1)
-EXTRA_DIST = acinclude.m4 libmicrohttpd.pc.in libmicrospdy.pc.in  \
-  w32/VS2013/libmicrohttpd.sln w32/VS2013/libmicrohttpd.vcxproj w32/VS2013/libmicrohttpd.vcxproj.filters \
-  w32/VS2013/hellobrowser.vcxproj w32/VS2013/hellobrowser.vcxproj.filters w32/VS2013/MHD_config.h \
-  w32/VS2013/gen_dll_res.ps1 w32/VS2013/microhttpd_dll_res_vc.rc.in w32/VS2013/microhttpd_dll_res_vc.rc
-
-pkgconfigdir = $(libdir)/pkgconfig
-pkgconfig_DATA = libmicrohttpd.pc libmicrospdy.pc
-all: MHD_config.h
-	$(MAKE) $(AM_MAKEFLAGS) all-recursive
-
-.SUFFIXES:
-am--refresh: Makefile
-	@:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      echo ' cd $(srcdir) && $(AUTOMAKE) --gnu'; \
-	      $(am__cd) $(srcdir) && $(AUTOMAKE) --gnu \
-		&& exit 0; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    echo ' $(SHELL) ./config.status'; \
-	    $(SHELL) ./config.status;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	$(SHELL) ./config.status --recheck
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	$(am__cd) $(srcdir) && $(AUTOCONF)
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	$(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
-$(am__aclocal_m4_deps):
-
-MHD_config.h: stamp-h1
-	@test -f $@ || rm -f stamp-h1
-	@test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1
-
-stamp-h1: $(srcdir)/MHD_config.h.in $(top_builddir)/config.status
-	@rm -f stamp-h1
-	cd $(top_builddir) && $(SHELL) ./config.status MHD_config.h
-$(srcdir)/MHD_config.h.in:  $(am__configure_deps) 
-	($(am__cd) $(top_srcdir) && $(AUTOHEADER))
-	rm -f stamp-h1
-	touch $@
-
-distclean-hdr:
-	-rm -f MHD_config.h stamp-h1
-libmicrohttpd.pc: $(top_builddir)/config.status $(srcdir)/libmicrohttpd.pc.in
-	cd $(top_builddir) && $(SHELL) ./config.status $@
-libmicrospdy.pc: $(top_builddir)/config.status $(srcdir)/libmicrospdy.pc.in
-	cd $(top_builddir) && $(SHELL) ./config.status $@
-w32/VS2013/microhttpd_dll_res_vc.rc: $(top_builddir)/config.status $(top_srcdir)/w32/VS2013/microhttpd_dll_res_vc.rc.in
-	cd $(top_builddir) && $(SHELL) ./config.status $@
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-distclean-libtool:
-	-rm -f libtool config.lt
-install-pkgconfigDATA: $(pkgconfig_DATA)
-	@$(NORMAL_INSTALL)
-	@list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(pkgconfigdir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \
-	  $(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \
-	done
-
-uninstall-pkgconfigDATA:
-	@$(NORMAL_UNINSTALL)
-	@list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \
-	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-	dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir)
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscope: cscope.files
-	test ! -s cscope.files \
-	  || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS)
-clean-cscope:
-	-rm -f cscope.files
-cscope.files: clean-cscope cscopelist
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-	-rm -f cscope.out cscope.in.out cscope.po.out cscope.files
-
-distdir: $(DISTFILES)
-	$(am__remove_distdir)
-	test -d "$(distdir)" || mkdir "$(distdir)"
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-	-test -n "$(am__skip_mode_fix)" \
-	|| find "$(distdir)" -type d ! -perm -755 \
-		-exec chmod u+rwx,go+rx {} \; -o \
-	  ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
-	  ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
-	  ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
-	|| chmod -R a+r "$(distdir)"
-dist-gzip: distdir
-	tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
-	$(am__post_remove_distdir)
-
-dist-bzip2: distdir
-	tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2
-	$(am__post_remove_distdir)
-
-dist-lzip: distdir
-	tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz
-	$(am__post_remove_distdir)
-
-dist-xz: distdir
-	tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz
-	$(am__post_remove_distdir)
-
-dist-tarZ: distdir
-	@echo WARNING: "Support for shar distribution archives is" \
-	               "deprecated." >&2
-	@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
-	tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
-	$(am__post_remove_distdir)
-
-dist-shar: distdir
-	@echo WARNING: "Support for distribution archives compressed with" \
-		       "legacy program 'compress' is deprecated." >&2
-	@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
-	shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
-	$(am__post_remove_distdir)
-
-dist-zip: distdir
-	-rm -f $(distdir).zip
-	zip -rq $(distdir).zip $(distdir)
-	$(am__post_remove_distdir)
-
-dist dist-all:
-	$(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:'
-	$(am__post_remove_distdir)
-
-# This target untars the dist file and tries a VPATH configuration.  Then
-# it guarantees that the distribution is self-contained by making another
-# tarfile.
-distcheck: dist
-	case '$(DIST_ARCHIVES)' in \
-	*.tar.gz*) \
-	  GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\
-	*.tar.bz2*) \
-	  bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\
-	*.tar.lz*) \
-	  lzip -dc $(distdir).tar.lz | $(am__untar) ;;\
-	*.tar.xz*) \
-	  xz -dc $(distdir).tar.xz | $(am__untar) ;;\
-	*.tar.Z*) \
-	  uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
-	*.shar.gz*) \
-	  GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\
-	*.zip*) \
-	  unzip $(distdir).zip ;;\
-	esac
-	chmod -R a-w $(distdir)
-	chmod u+w $(distdir)
-	mkdir $(distdir)/_build $(distdir)/_inst
-	chmod a-w $(distdir)
-	test -d $(distdir)/_build || exit 0; \
-	dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
-	  && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
-	  && am__cwd=`pwd` \
-	  && $(am__cd) $(distdir)/_build \
-	  && ../configure \
-	    $(AM_DISTCHECK_CONFIGURE_FLAGS) \
-	    $(DISTCHECK_CONFIGURE_FLAGS) \
-	    --srcdir=.. --prefix="$$dc_install_base" \
-	  && $(MAKE) $(AM_MAKEFLAGS) \
-	  && $(MAKE) $(AM_MAKEFLAGS) dvi \
-	  && $(MAKE) $(AM_MAKEFLAGS) check \
-	  && $(MAKE) $(AM_MAKEFLAGS) install \
-	  && $(MAKE) $(AM_MAKEFLAGS) installcheck \
-	  && $(MAKE) $(AM_MAKEFLAGS) uninstall \
-	  && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
-	        distuninstallcheck \
-	  && chmod -R a-w "$$dc_install_base" \
-	  && ({ \
-	       (cd ../.. && umask 077 && mkdir "$$dc_destdir") \
-	       && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
-	       && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
-	       && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
-	            distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
-	      } || { rm -rf "$$dc_destdir"; exit 1; }) \
-	  && rm -rf "$$dc_destdir" \
-	  && $(MAKE) $(AM_MAKEFLAGS) dist \
-	  && rm -rf $(DIST_ARCHIVES) \
-	  && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \
-	  && cd "$$am__cwd" \
-	  || exit 1
-	$(am__post_remove_distdir)
-	@(echo "$(distdir) archives ready for distribution: "; \
-	  list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
-	  sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x'
-distuninstallcheck:
-	@test -n '$(distuninstallcheck_dir)' || { \
-	  echo 'ERROR: trying to run $@ with an empty' \
-	       '$$(distuninstallcheck_dir)' >&2; \
-	  exit 1; \
-	}; \
-	$(am__cd) '$(distuninstallcheck_dir)' || { \
-	  echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \
-	  exit 1; \
-	}; \
-	test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \
-	   || { echo "ERROR: files left after uninstall:" ; \
-	        if test -n "$(DESTDIR)"; then \
-	          echo "  (check DESTDIR support)"; \
-	        fi ; \
-	        $(distuninstallcheck_listfiles) ; \
-	        exit 1; } >&2
-distcleancheck: distclean
-	@if test '$(srcdir)' = . ; then \
-	  echo "ERROR: distcleancheck can only run from a VPATH build" ; \
-	  exit 1 ; \
-	fi
-	@test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
-	  || { echo "ERROR: files left in build directory after distclean:" ; \
-	       $(distcleancheck_listfiles) ; \
-	       exit 1; } >&2
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(DATA) MHD_config.h
-installdirs: installdirs-recursive
-installdirs-am:
-	for dir in "$(DESTDIR)$(pkgconfigdir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -f $(am__CONFIG_DISTCLEAN_FILES)
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-hdr \
-	distclean-libtool distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am: install-pkgconfigDATA
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -f $(am__CONFIG_DISTCLEAN_FILES)
-	-rm -rf $(top_srcdir)/autom4te.cache
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-pkgconfigDATA
-
-.MAKE: $(am__recursive_targets) all install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \
-	am--refresh check check-am clean clean-cscope clean-generic \
-	clean-libtool cscope cscopelist-am ctags ctags-am dist \
-	dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \
-	dist-xz dist-zip distcheck distclean distclean-generic \
-	distclean-hdr distclean-libtool distclean-tags distcleancheck \
-	distdir distuninstallcheck dvi dvi-am html html-am info \
-	info-am install install-am install-data install-data-am \
-	install-dvi install-dvi-am install-exec install-exec-am \
-	install-html install-html-am install-info install-info-am \
-	install-man install-pdf install-pdf-am install-pkgconfigDATA \
-	install-ps install-ps-am install-strip installcheck \
-	installcheck-am installdirs installdirs-am maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
-	uninstall-am uninstall-pkgconfigDATA
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/NEWS b/NEWS
index 20d61fc..c7f4948 100644
--- a/NEWS
+++ b/NEWS
@@ -1,2 +1,269 @@
+Sun 26 Feb 2023 17:49:30 CET
+Released GNU libmicrohttpd 0.9.76 hotfix. -CG
+
+    This is a hotfix release.
+    This only change since previous release is fixed potential DoS vector
+    in MHD_PostProcessor discovered by Gynvael Coldwind and Dejan
+    Alvadzijevic (CVE-2023-27371).
+    While the researchers have not been able to exploit this attack vector
+    when libmicrohttpd is compiled with the standard GNU C library, it is
+    recommended that you update MHD as soon as possible if your
+    applications are using (optional) MHD_PostProcessor functionality.
+
+    -- Evgeny Grin (Karlson2k)
+
+Sun 26 Dec 2021 20:30:00 MSK
+Released GNU libmicrohttpd 0.9.75 -EG
+
+    This is a correction release.
+    The main improvement is the implementation of workaround for some
+    OSes (like OpenBSD 7) where "monotonic" clock may jump back. Now
+    MHD is able to automatically detect such situation and recover if
+    the jump is small. This workaround is needed with increased
+    accuracy of connection timeout introduced in previous version, as
+    with lower accuracy (v0.9.73 and before) these jumpbacks were
+    unnoticeable.
+    Other changes: fixed some compiler, Makefile, and configure
+    warnings on specific platforms; one test further improved.
+
+    -- Evgeny Grin (Karlson2k)
+
+
+Sun 19 Dec 2021 18:30:00 MSK
+Released GNU libmicrohttpd 0.9.74
+
+    This release brings a lot of fixes and improvements, and
+    important new features.
+    The most significant addition is the new experimental
+    implementation of WebSockets contributed by David Gausmann. This
+    implementation is not fully tested yet so currently it is disabled
+    by default.
+    Other changes include a lot of improvements and clarifications
+    in doxy comments in microhttpd.h header file, improved compliance
+    with the RFC HTTP specifications, the new implementation of reply
+    header forming, the new implementation of request chunked encoding
+    parsing, new automatic error replies, internal optimisations, and
+    many important fixes, including fixes for long-standing bugs.
+
+    More detailed list of notable changes:
+
+    API changes:
+    + Added new function MHD_get_reason_phrase_len_for().
+    + Added MHD_CONNECTION_INFO_HTTP_STATUS type of information
+      queried by MHD_get_connection_info().
+    + Added new response flag MHD_RF_SEND_KEEP_ALIVE_HEADER to force
+      sending of "keep-alive" header even if not required by RFC.
+    + Added new response creation function
+      MHD_create_response_from_buffer_with_free_callback_cls() with
+      custom cleanup callback.
+    + Added new response flag MHD_RF_HTTP_1_0_COMPATIBLE_STRICT with
+      the same functionality as existing MHD_RF_HTTP_VERSION_1_0_ONLY
+      flag. The old flag will be deprecated.
+    + Added new response flag MHD_RF_HTTP_1_0_SERVER with the same
+      functionality as existing MHD_RF_HTTP_VERSION_1_0_RESPONSE flag.
+      The old flag will be deprecated.
+
+    New features:
+    + Added experimental WebSockets extension with separate header.
+      Disabled by default as it is not fully tested yet.
+    + Added '--enable-sanitizers[=address,undefined,leak,user-poison]'
+      configure parameter (instead of '--enable-sanitizer'),
+      implemented custom memory poisoning for memory pools.
+
+    Improvements and enhancements:
+    * Doxy function descriptions was corrected, clarified, extended,
+      and improved. Now it should be much easier to learn MHD just by
+      reading the headers.
+    * Completely rewritten reply header forming. New implementation is
+      more robust, simpler maintainable and expandable, and better
+      follows RFC HTTP specifications.
+    * Performance improvements: now HTTP version and request method are
+      decoded one time only (previously MHD used string comparison many
+      times during processing the data).
+    * Rewritten request chunked payload decoding. The new
+      implementation better conforms to the HTTP RFC, detects format
+      problems earlier, replies to the clients with description of
+      detected problems, handles untypical (but syntactically correct)
+      values properly.
+    * Added special replies for wrong/unsupported HTTP versions in
+      requests, broken HTTP chunked encoding in requests,
+    * As required by HTTP RFC, added automatic error replies if client
+      used broken chunked encoding, too large chunk size, too large
+      payload size, or broken Content-Length header.
+    * Optimized connection's memory pool handling.
+    * Changed timeout precision from one second to one millisecond.
+    * Added some checks for incorrect user data, reporting problems in
+      MHD log.
+    * Improved performance of hash calculations functions by using
+      compiler built-ins (if available).
+    * Implemented SHA-1 calculations (required for WebSockets).
+    * Added universal MSVC project that works with any (sufficiently
+      new) version of MSVC.
+    * Developed simple HTTP client to test MHD under very special
+      conditions.
+    * Implemented 45 new tests.
+    * Improved existing tests to test more aspects of MHD.
+    * Added check for correct results of system and libcurl functions.
+    * Response headers are checked during forming of responses.
+    * HTTPS tests were improved.
+    * Added rebuild on W32 of all required files if files are missing.
+    * Many internal optimisations and improvements.
+
+    Functionality changes:
+    * Keep-alive header is omitted by default for HTTP/1.1 connections.
+      Use of header can be enforced by response flag.
+    * Chunked encoding is used for HTTP/1.1 non-keep-alive connections
+      for responses with unknown size. Previously MHD used "indication
+      of the end of the response by closing connection" in such cases,
+      however it is not correct for HTTP/1.1 connections as per HTTP
+      RFC.
+    * As required by HTTP RFC, use HTTP/1.1 version instead of HTTP/1.0
+      in reply headers when client is HTTP/1.0 . HTTP/1.0 version can
+      be enforced by response flag.
+    * User response headers are used in replies in the same order as
+      was added by application.
+    * Allowed tab characters in response header values.
+    * All custom "Connection:" response headers are automatically
+      combined into single "Connection:" header.
+    * "keep-alive" token silently dropped from custom "Connection:"
+      response header. "Keep-alive" cannot be enforced and used
+      automatically if possible.
+    * Allow tab character in custom response header value.
+    * Disallow space character in custom response header value.
+    * Do not allow responses with 1xx codes for HTTP/1.0 requests.
+    * Detected and reported incorrect "Upgrade" responses.
+    * W32 targets are changed to Vista+ by default. XP is supported
+      still.
+
+    Fixes:
+    # Fixed short busy-waiting (up to one second) when connection is
+      going to be expired and closed.
+    # Fixed handling of errors during start of new connection, fixed
+      inability to accept new connections in thread-per-connection mode
+      due to the missing decrement of number of daemon's connections if
+      start of new thread is failed.
+    # Fixed incorrect parsing of LFLF, LFCR, CRCR, and bare CR as
+      single linefeed in request header and request chunked payload.
+      Now only CRLF or bare LF are recognized as linefeed.
+    # Fixed response chunked encoding handling. Now it works properly
+      with non-keep-alive connection, with fixed size replies (if
+      chunked was enforced by header), and in other situations.
+    # Other fixes for chunked replies.
+    # Fixed handling of custom connection timeout in thread-per-
+      connection mode.
+    # Fixed wrongly used MHD_REQUEST_TERMINATED_COMPLETED_OK code for
+      application notification when MHD_REQUEST_TERMINATED_WITH_ERROR
+      code must be used.
+    # Fixed code MHD_REQUEST_TERMINATED_READ_ERROR not reported (code
+      MHD_REQUEST_TERMINATED_WITH_ERROR was incorrectly used instead).
+    # Fixed handling of request chunked encoding with untypical
+      formatting.
+    # Fixed processing of last part of hex-encoded values under
+      certain conditions.
+    # Fixed value returned for MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE.
+    # Fixed returned value for MHD_FEATURE_AUTOSUPPRESS_SIGPIPE on W32,
+      now it is MHD_YES as W32 does not need SIGPIPE suppression.
+    # Fixed portability of bitwise NOT for enums values.
+    # Fixed SHA-256 and MD5 calculations with unaligned data.
+    # Fixed incorrect caseless matching for HTTP version.
+    # Fixed incorrect caseless matching for request method.
+    # Fixed compatibility with old GnuTLS versions.
+    # Fixed compiler warnings on 32-bits platforms.
+    # Fixed blocking sockets setting in tests and examples for W32.
+    # Fixed examples to really use libmagic if present.
+    # HTTPS tests were fixed.
+    # Fixed libcurl test with case-insensitive match for HTTP methods,
+      method names must use case-sensitive match.
+    # Fixed tests compatibility with old libcurl versions.
+    # Fixed build on W32 with llvm-dlltool (this tool is too 
+      oversimplified)
+
+    -- Evgeny Grin (Karlson2k)
+
+
+Sun 25 Apr 2021 14:00:00 MSK
+Released GNU libmicrohttpd 0.9.73
+
+    This release brings new features, improvements, and a few fixes.
+    The most important addition is the new function for vector-backed
+    responses, based on the patch contributed by NASA engineers.
+    Other changes include compatibility with autoconf 2.70+, improved
+    testsuite compatibility with CI systems, fixed and improved MSVC
+    builds, and implementation of ALPN support.
+
+    More detailed list of notable changes:
+
+    API changes:
+    + Added new function MHD_create_response_from_iovec(), based on the
+      patch provided by Lawrence Sebald and Damon N. Earp from NASA.
+    + Added MHD_OPTION_SIGPIPE_HANDLED_BY_APP daemon option.
+    + Added new function MHD_run_wait().
+    + Added MHD_OPTION_TLS_NO_ALPN to disable usage of ALPN even if
+      it is supported by TLS library.
+
+    New features:
+    + Added '--enable-heavy-tests' configure parameter (disabled by
+      default).
+    + Implemented support for ALPN.
+
+    Improvements and enhancements:
+    * Return timeout of zero also for connections awaiting cleanup.
+    * Compatibility with autoconf >=2.70, used new autoconf features.
+    * Warn user when custom logger option is not the first option.
+    * Added information to the header about minimal MHD version when
+      particular symbols were introduced.
+    * Updated test certificates to be compatible with modern browsers.
+    * Added on-fly detection of UNIX domain sockets and pipes, MHD does
+      not try to use TCP/IP-specific socket options on them.
+    * Report more detailed error description in the MHD log for send
+      and receive errors.
+    * Enabled bind port autodetection for MSVC builds.
+
+    Fixes:
+    # Fix PostProcessor to always properly stop iteration when
+      application callback tells it to do so.
+    # Fixed MD5 digest authorization broken when compiled without
+      variable length arrays support (notably with MSVC).
+    # Fixed detection of type of send errors on W32.
+
+    -- Evgeny Grin (Karlson2k)
+
+
+Mon 28 Dec 2020 21:36:00 MSK
+Released GNU libmicrohttpd 0.9.72
+
+    This release is mostly a bugfix release, with greatly improved
+    compatibility with various OSes/kernels, including FreeBSD, Windows,
+    OpenBSD, NetBSD, Darwin (macOS), Solaris. Performance is improved,
+    especially with HTTPS connections and stay-alive HTTP connections.
+
+    Notable changes since version 0.9.71:
+
+    API changes:
+    + New function MHD_create_response_from_pipe()
+
+    Improvements and enhancements:
+    * Fully rewritten code for buffering/pushing from kernel network buffers
+      for compatibility with various OSes. Reduced number of additional
+      sys-calls, network is better utilized, responses are delivered faster.
+    * Restored optimal sendfile() usage on FreeBSD.
+    * MHD now takes care about SIGPIPE handling by blocking it in internal
+      threads and avoiding functions (like sendfile()) that could generate
+      SIGPIPE when blocking of this signal is not possible.
+
+    Fixes:
+    # Fixed crash in PostProcessor.
+    # Fixed several resources leaks in corner cases.
+    # Improved thread sync, thread safety and fixed one use-after-free under
+      special conditions during stopping of daemon.
+    # Updated HTTP status codes, header names and methods from the
+      registries.
+    # Fixed functioning without listen socket and with internal threads.
+    # Fixed streaming of chunked responses for both HTTP and HTTPS.
+    # Various compatibility fixes.
+
+    -- Evgeny Grin (Karlson2k)
+
+
 Tue Jan  9 20:52:48 MST 2007
 	Project posted.
diff --git a/README b/README
index 6d92691..a330e19 100644
--- a/README
+++ b/README
@@ -7,39 +7,35 @@
 protocol.  The main application must still provide the application
 logic to generate the content.
 
-Additionally, a second, still very experimental library is provided
-for SPDY (the base for HTTP 2.0) support.  libmicrospdy provides a
-compact API and implementation of SPDY server. libmicrospdy currently
-only implements partially version 3 of SPDY.
+GNU libmicrohttpd is dual-licensed under the GNU Lesser General Public
+License (LGPLv2.1+) and the eCos License.  See COPYING for details.
+
+
+Joining GNU
+===========
+
+This is a GNU program, developed by the GNU Project and part of the
+GNU Operating System. If you are the author of an awesome program and
+want to join us in writing Free Software, please consider making it an
+official GNU program and become a GNU maintainer.  You can find
+instructions on how to do so at http://www.gnu.org/help/evaluation.
+We are looking forward to hacking with you!
 
 
 Installation
 ============
 
-If you are using Subversion, run "autoreconf -fi" to create configure.
+See INSTALL for generic installation instructions.
+
+If you are using Git, run "./bootstrap" to create configure.
 
 In order to run the testcases, you need a recent version of libcurl.
 libcurl is not required if you just want to install the library.
 
-Especially for development, do use the MHD_USE_DEBUG option to get
+Especially for development, do use the MHD_USE_ERROR_LOG option to get
 error messages.
 
 
-Requirements for libmicrospdy
-=============================
-
-The following packages are needed to build libmicrospdy:
-
-* zlib 
-* OpenSSL >= 1.0.1
-
-To run the test cases, involving requests, version of Spdylay, supporting
-SPDY v3, is required. Spdylay is still under development and can be
-found here:
-
-http://spdylay.sourceforge.net/
-
-
 Configure options
 =================
 
@@ -66,23 +62,20 @@
 least).  On other systems that may trigger a SIGPIPE on send/recv, the
 main application should install a signal handler to handle SIGPIPE.
 
-libmicrohttpd should work well on GNU/Linux, BSD, OS X, W32 and z/OS.
+libmicrohttpd should work well on GNU/Linux, W32, FreeBSD, Darwin,
+NetBSD, OpenBSD, Solaris/OpenIndiana, and z/OS.
 Note that HTTPS is not supported on z/OS (yet).  We also have reports
-of users using it on vxWorks and Symbian.  Note that on platforms
-where the compiler does not support the "constructor" attribute, you
-must call "MHD_init" before using any MHD functions and "MHD_fini"
-after you are done using MHD.
+of users using it on vxWorks.
 
 
 Development Status
 ==================
 
 This is a beta release for libmicrohttpd.  Before declaring the
-library stable, we should implement support for HTTP "Upgrade" 
-requests and have testcases for the following features:
+library stable, we should have testcases for the following features:
 
-- HTTP/1.1 pipelining (need to figure out how to ensure curl pipelines 
-  -- and it seems libcurl has issues with pipelining, 
+- HTTP/1.1 pipelining (need to figure out how to ensure curl pipelines
+  -- and it seems libcurl has issues with pipelining,
   see http://curl.haxx.se/mail/lib-2007-12/0248.html)
 - resource limit enforcement
 - client queuing early response, suppressing 100 CONTINUE
@@ -91,53 +84,14 @@
 - MHD basic and digest authentication
 
 In particular, the following functions are not covered by 'make check':
-- mhd_panic_std (daemon.c); special case (abort)
+- mhd_panic_std (mhd_panic.c); special case (abort)
 - parse_options (daemon.c)
-- MHD_set_panic_func (daemon.c)
 - MHD_get_version (daemon.c)
 
 
-This is an early alpha release for libmicrospdy.  The following things
-should be implemented (in order of importance) before we can claim to
-be reasonably complete:
-- 8 different output queues (one for each priority) have to be implemented
-together with a suitable algorithm for utilizing them. Otherwise, downloading
-a file will block all responses with same or smaller priority
-- SPDY RST_STREAM sending on each possible error (DONE?)
-- SPDY_close_session
-- Find the best way for closing still opened stream (new call or existing)
-- SPDY_is_stream_opened
-- SPDY PING (used often by browsers)
-- receiving SPDY WINDOW_UPDATE
-- SPDY Settings
-- SPDY PUSH
-- SPDY HEADERS
-- SPDY Credentials
-
-Additional ideas for features include:
-- Individual callbacks for each session
-- Individual timeout for each session
-
-Unimplemented API functions of libmicrospdy:
-- SPDY_settings_create ();
-- SPDY_settings_add (...);
-- SPDY_settings_lookup (...);
-- SPDY_settings_iterate (...);
-- SPDY_settings_destroy (...);
-- SPDY_close_session(...);
-- SPDY_send_ping(...);
-- SPDY_send_settings (...);
-
-In particular, we should write tests for:
-- Enqueueing responses while considering request priorities.
-- HTTP methods other than GET
-
-
-
-
-
-Missing documentation:
-======================
-
-- libmicrospdy manual:
-  * missing entirely
+Note that the working library is in src/microhttpd/ with the API in
+src/include/microhttpd.h.  An *experimental* (read: not yet working
+at all) newer implementation is in src/lib/, with the new API in
+src/include/microhttpd2.h.  The experimental code will need MUCH
+more testing and development, you are strongly advised to stick
+to microhttpd.h unless you are a MHD developer!
diff --git a/acinclude.m4 b/acinclude.m4
deleted file mode 100644
index 8b13789..0000000
--- a/acinclude.m4
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/aclocal.m4 b/aclocal.m4
deleted file mode 100644
index fdc4449..0000000
--- a/aclocal.m4
+++ /dev/null
@@ -1,1381 +0,0 @@
-# generated automatically by aclocal 1.14.1 -*- Autoconf -*-
-
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
-
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])])
-m4_ifndef([AC_AUTOCONF_VERSION],
-  [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
-m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],,
-[m4_warning([this file was generated for autoconf 2.69.
-You have another version of autoconf.  It may work, but is not guaranteed to.
-If you have problems, you may need to regenerate the build system entirely.
-To do so, use the procedure documented by the package, typically 'autoreconf'.])])
-
-# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
-# serial 1 (pkg-config-0.24)
-# 
-# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
-#
-# 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 2 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, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# PKG_PROG_PKG_CONFIG([MIN-VERSION])
-# ----------------------------------
-AC_DEFUN([PKG_PROG_PKG_CONFIG],
-[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
-m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
-m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
-AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
-AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
-AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
-
-if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
-	AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
-fi
-if test -n "$PKG_CONFIG"; then
-	_pkg_min_version=m4_default([$1], [0.9.0])
-	AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
-	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
-		AC_MSG_RESULT([yes])
-	else
-		AC_MSG_RESULT([no])
-		PKG_CONFIG=""
-	fi
-fi[]dnl
-])# PKG_PROG_PKG_CONFIG
-
-# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-#
-# Check to see whether a particular set of modules exists.  Similar
-# to PKG_CHECK_MODULES(), but does not set variables or print errors.
-#
-# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-# only at the first occurence in configure.ac, so if the first place
-# it's called might be skipped (such as if it is within an "if", you
-# have to call PKG_CHECK_EXISTS manually
-# --------------------------------------------------------------
-AC_DEFUN([PKG_CHECK_EXISTS],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-if test -n "$PKG_CONFIG" && \
-    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
-  m4_default([$2], [:])
-m4_ifvaln([$3], [else
-  $3])dnl
-fi])
-
-# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
-# ---------------------------------------------
-m4_define([_PKG_CONFIG],
-[if test -n "$$1"; then
-    pkg_cv_[]$1="$$1"
- elif test -n "$PKG_CONFIG"; then
-    PKG_CHECK_EXISTS([$3],
-                     [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes ],
-		     [pkg_failed=yes])
- else
-    pkg_failed=untried
-fi[]dnl
-])# _PKG_CONFIG
-
-# _PKG_SHORT_ERRORS_SUPPORTED
-# -----------------------------
-AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi[]dnl
-])# _PKG_SHORT_ERRORS_SUPPORTED
-
-
-# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
-# [ACTION-IF-NOT-FOUND])
-#
-#
-# Note that if there is a possibility the first call to
-# PKG_CHECK_MODULES might not happen, you should be sure to include an
-# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
-#
-#
-# --------------------------------------------------------------
-AC_DEFUN([PKG_CHECK_MODULES],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
-AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
-
-pkg_failed=no
-AC_MSG_CHECKING([for $1])
-
-_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
-_PKG_CONFIG([$1][_LIBS], [libs], [$2])
-
-m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
-and $1[]_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.])
-
-if test $pkg_failed = yes; then
-   	AC_MSG_RESULT([no])
-        _PKG_SHORT_ERRORS_SUPPORTED
-        if test $_pkg_short_errors_supported = yes; then
-	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
-        else 
-	        $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
-
-	m4_default([$4], [AC_MSG_ERROR(
-[Package requirements ($2) were not met:
-
-$$1_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-_PKG_TEXT])[]dnl
-        ])
-elif test $pkg_failed = untried; then
-     	AC_MSG_RESULT([no])
-	m4_default([$4], [AC_MSG_FAILURE(
-[The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-_PKG_TEXT
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl
-        ])
-else
-	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
-	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
-        AC_MSG_RESULT([yes])
-	$3
-fi[]dnl
-])# PKG_CHECK_MODULES
-
-
-# PKG_INSTALLDIR(DIRECTORY)
-# -------------------------
-# Substitutes the variable pkgconfigdir as the location where a module
-# should install pkg-config .pc files. By default the directory is
-# $libdir/pkgconfig, but the default can be changed by passing
-# DIRECTORY. The user can override through the --with-pkgconfigdir
-# parameter.
-AC_DEFUN([PKG_INSTALLDIR],
-[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
-m4_pushdef([pkg_description],
-    [pkg-config installation directory @<:@]pkg_default[@:>@])
-AC_ARG_WITH([pkgconfigdir],
-    [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
-    [with_pkgconfigdir=]pkg_default)
-AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
-m4_popdef([pkg_default])
-m4_popdef([pkg_description])
-]) dnl PKG_INSTALLDIR
-
-
-# PKG_NOARCH_INSTALLDIR(DIRECTORY)
-# -------------------------
-# Substitutes the variable noarch_pkgconfigdir as the location where a
-# module should install arch-independent pkg-config .pc files. By
-# default the directory is $datadir/pkgconfig, but the default can be
-# changed by passing DIRECTORY. The user can override through the
-# --with-noarch-pkgconfigdir parameter.
-AC_DEFUN([PKG_NOARCH_INSTALLDIR],
-[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
-m4_pushdef([pkg_description],
-    [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
-AC_ARG_WITH([noarch-pkgconfigdir],
-    [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
-    [with_noarch_pkgconfigdir=]pkg_default)
-AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
-m4_popdef([pkg_default])
-m4_popdef([pkg_description])
-]) dnl PKG_NOARCH_INSTALLDIR
-
-
-# PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
-# [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-# -------------------------------------------
-# Retrieves the value of the pkg-config variable for the given module.
-AC_DEFUN([PKG_CHECK_VAR],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
-
-_PKG_CONFIG([$1], [variable="][$3]["], [$2])
-AS_VAR_COPY([$1], [pkg_cv_][$1])
-
-AS_VAR_IF([$1], [""], [$5], [$4])dnl
-])# PKG_CHECK_VAR
-
-# Copyright (C) 2002-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_AUTOMAKE_VERSION(VERSION)
-# ----------------------------
-# Automake X.Y traces this macro to ensure aclocal.m4 has been
-# generated from the m4 files accompanying Automake X.Y.
-# (This private macro should not be called outside this file.)
-AC_DEFUN([AM_AUTOMAKE_VERSION],
-[am__api_version='1.14'
-dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
-dnl require some minimum version.  Point them to the right macro.
-m4_if([$1], [1.14.1], [],
-      [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
-])
-
-# _AM_AUTOCONF_VERSION(VERSION)
-# -----------------------------
-# aclocal traces this macro to find the Autoconf version.
-# This is a private macro too.  Using m4_define simplifies
-# the logic in aclocal, which can simply ignore this definition.
-m4_define([_AM_AUTOCONF_VERSION], [])
-
-# AM_SET_CURRENT_AUTOMAKE_VERSION
-# -------------------------------
-# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
-# This function is AC_REQUIREd by AM_INIT_AUTOMAKE.
-AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
-[AM_AUTOMAKE_VERSION([1.14.1])dnl
-m4_ifndef([AC_AUTOCONF_VERSION],
-  [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
-_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))])
-
-# AM_AUX_DIR_EXPAND                                         -*- Autoconf -*-
-
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
-# $ac_aux_dir to '$srcdir/foo'.  In other projects, it is set to
-# '$srcdir', '$srcdir/..', or '$srcdir/../..'.
-#
-# Of course, Automake must honor this variable whenever it calls a
-# tool from the auxiliary directory.  The problem is that $srcdir (and
-# therefore $ac_aux_dir as well) can be either absolute or relative,
-# depending on how configure is run.  This is pretty annoying, since
-# it makes $ac_aux_dir quite unusable in subdirectories: in the top
-# source directory, any form will work fine, but in subdirectories a
-# relative path needs to be adjusted first.
-#
-# $ac_aux_dir/missing
-#    fails when called from a subdirectory if $ac_aux_dir is relative
-# $top_srcdir/$ac_aux_dir/missing
-#    fails if $ac_aux_dir is absolute,
-#    fails when called from a subdirectory in a VPATH build with
-#          a relative $ac_aux_dir
-#
-# The reason of the latter failure is that $top_srcdir and $ac_aux_dir
-# are both prefixed by $srcdir.  In an in-source build this is usually
-# harmless because $srcdir is '.', but things will broke when you
-# start a VPATH build or use an absolute $srcdir.
-#
-# So we could use something similar to $top_srcdir/$ac_aux_dir/missing,
-# iff we strip the leading $srcdir from $ac_aux_dir.  That would be:
-#   am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"`
-# and then we would define $MISSING as
-#   MISSING="\${SHELL} $am_aux_dir/missing"
-# This will work as long as MISSING is not called from configure, because
-# unfortunately $(top_srcdir) has no meaning in configure.
-# However there are other variables, like CC, which are often used in
-# configure, and could therefore not use this "fixed" $ac_aux_dir.
-#
-# Another solution, used here, is to always expand $ac_aux_dir to an
-# absolute PATH.  The drawback is that using absolute paths prevent a
-# configured tree to be moved without reconfiguration.
-
-AC_DEFUN([AM_AUX_DIR_EXPAND],
-[AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
-# Expand $ac_aux_dir to an absolute path.
-am_aux_dir=`cd "$ac_aux_dir" && pwd`
-])
-
-# AM_CONDITIONAL                                            -*- Autoconf -*-
-
-# Copyright (C) 1997-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_CONDITIONAL(NAME, SHELL-CONDITION)
-# -------------------------------------
-# Define a conditional.
-AC_DEFUN([AM_CONDITIONAL],
-[AC_PREREQ([2.52])dnl
- m4_if([$1], [TRUE],  [AC_FATAL([$0: invalid condition: $1])],
-       [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl
-AC_SUBST([$1_TRUE])dnl
-AC_SUBST([$1_FALSE])dnl
-_AM_SUBST_NOTMAKE([$1_TRUE])dnl
-_AM_SUBST_NOTMAKE([$1_FALSE])dnl
-m4_define([_AM_COND_VALUE_$1], [$2])dnl
-if $2; then
-  $1_TRUE=
-  $1_FALSE='#'
-else
-  $1_TRUE='#'
-  $1_FALSE=
-fi
-AC_CONFIG_COMMANDS_PRE(
-[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then
-  AC_MSG_ERROR([[conditional "$1" was never defined.
-Usually this means the macro was only invoked conditionally.]])
-fi])])
-
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-
-# There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be
-# written in clear, in which case automake, when reading aclocal.m4,
-# will think it sees a *use*, and therefore will trigger all it's
-# C support machinery.  Also note that it means that autoscan, seeing
-# CC etc. in the Makefile, will ask for an AC_PROG_CC use...
-
-
-# _AM_DEPENDENCIES(NAME)
-# ----------------------
-# See how the compiler implements dependency checking.
-# NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC".
-# We try a few techniques and use that to set a single cache variable.
-#
-# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was
-# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular
-# dependency, and given that the user is not expected to run this macro,
-# just rely on AC_PROG_CC.
-AC_DEFUN([_AM_DEPENDENCIES],
-[AC_REQUIRE([AM_SET_DEPDIR])dnl
-AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl
-AC_REQUIRE([AM_MAKE_INCLUDE])dnl
-AC_REQUIRE([AM_DEP_TRACK])dnl
-
-m4_if([$1], [CC],   [depcc="$CC"   am_compiler_list=],
-      [$1], [CXX],  [depcc="$CXX"  am_compiler_list=],
-      [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'],
-      [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'],
-      [$1], [UPC],  [depcc="$UPC"  am_compiler_list=],
-      [$1], [GCJ],  [depcc="$GCJ"  am_compiler_list='gcc3 gcc'],
-                    [depcc="$$1"   am_compiler_list=])
-
-AC_CACHE_CHECK([dependency style of $depcc],
-               [am_cv_$1_dependencies_compiler_type],
-[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
-  # We make a subdir and do the tests there.  Otherwise we can end up
-  # making bogus files that we don't know about and never remove.  For
-  # instance it was reported that on HP-UX the gcc test will end up
-  # making a dummy file named 'D' -- because '-MD' means "put the output
-  # in D".
-  rm -rf conftest.dir
-  mkdir conftest.dir
-  # Copy depcomp to subdir because otherwise we won't find it if we're
-  # using a relative directory.
-  cp "$am_depcomp" conftest.dir
-  cd conftest.dir
-  # We will build objects and dependencies in a subdirectory because
-  # it helps to detect inapplicable dependency modes.  For instance
-  # both Tru64's cc and ICC support -MD to output dependencies as a
-  # side effect of compilation, but ICC will put the dependencies in
-  # the current directory while Tru64 will put them in the object
-  # directory.
-  mkdir sub
-
-  am_cv_$1_dependencies_compiler_type=none
-  if test "$am_compiler_list" = ""; then
-     am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp`
-  fi
-  am__universal=false
-  m4_case([$1], [CC],
-    [case " $depcc " in #(
-     *\ -arch\ *\ -arch\ *) am__universal=true ;;
-     esac],
-    [CXX],
-    [case " $depcc " in #(
-     *\ -arch\ *\ -arch\ *) am__universal=true ;;
-     esac])
-
-  for depmode in $am_compiler_list; do
-    # Setup a source with many dependencies, because some compilers
-    # like to wrap large dependency lists on column 80 (with \), and
-    # we should not choose a depcomp mode which is confused by this.
-    #
-    # We need to recreate these files for each test, as the compiler may
-    # overwrite some of them when testing with obscure command lines.
-    # This happens at least with the AIX C compiler.
-    : > sub/conftest.c
-    for i in 1 2 3 4 5 6; do
-      echo '#include "conftst'$i'.h"' >> sub/conftest.c
-      # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with
-      # Solaris 10 /bin/sh.
-      echo '/* dummy */' > sub/conftst$i.h
-    done
-    echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
-
-    # We check with '-c' and '-o' for the sake of the "dashmstdout"
-    # mode.  It turns out that the SunPro C++ compiler does not properly
-    # handle '-M -o', and we need to detect this.  Also, some Intel
-    # versions had trouble with output in subdirs.
-    am__obj=sub/conftest.${OBJEXT-o}
-    am__minus_obj="-o $am__obj"
-    case $depmode in
-    gcc)
-      # This depmode causes a compiler race in universal mode.
-      test "$am__universal" = false || continue
-      ;;
-    nosideeffect)
-      # After this tag, mechanisms are not by side-effect, so they'll
-      # only be used when explicitly requested.
-      if test "x$enable_dependency_tracking" = xyes; then
-	continue
-      else
-	break
-      fi
-      ;;
-    msvc7 | msvc7msys | msvisualcpp | msvcmsys)
-      # This compiler won't grok '-c -o', but also, the minuso test has
-      # not run yet.  These depmodes are late enough in the game, and
-      # so weak that their functioning should not be impacted.
-      am__obj=conftest.${OBJEXT-o}
-      am__minus_obj=
-      ;;
-    none) break ;;
-    esac
-    if depmode=$depmode \
-       source=sub/conftest.c object=$am__obj \
-       depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
-       $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \
-         >/dev/null 2>conftest.err &&
-       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
-       grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
-       grep $am__obj sub/conftest.Po > /dev/null 2>&1 &&
-       ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
-      # icc doesn't choke on unknown options, it will just issue warnings
-      # or remarks (even with -Werror).  So we grep stderr for any message
-      # that says an option was ignored or not supported.
-      # When given -MP, icc 7.0 and 7.1 complain thusly:
-      #   icc: Command line warning: ignoring option '-M'; no argument required
-      # The diagnosis changed in icc 8.0:
-      #   icc: Command line remark: option '-MP' not supported
-      if (grep 'ignoring option' conftest.err ||
-          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
-        am_cv_$1_dependencies_compiler_type=$depmode
-        break
-      fi
-    fi
-  done
-
-  cd ..
-  rm -rf conftest.dir
-else
-  am_cv_$1_dependencies_compiler_type=none
-fi
-])
-AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type])
-AM_CONDITIONAL([am__fastdep$1], [
-  test "x$enable_dependency_tracking" != xno \
-  && test "$am_cv_$1_dependencies_compiler_type" = gcc3])
-])
-
-
-# AM_SET_DEPDIR
-# -------------
-# Choose a directory name for dependency files.
-# This macro is AC_REQUIREd in _AM_DEPENDENCIES.
-AC_DEFUN([AM_SET_DEPDIR],
-[AC_REQUIRE([AM_SET_LEADING_DOT])dnl
-AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl
-])
-
-
-# AM_DEP_TRACK
-# ------------
-AC_DEFUN([AM_DEP_TRACK],
-[AC_ARG_ENABLE([dependency-tracking], [dnl
-AS_HELP_STRING(
-  [--enable-dependency-tracking],
-  [do not reject slow dependency extractors])
-AS_HELP_STRING(
-  [--disable-dependency-tracking],
-  [speeds up one-time build])])
-if test "x$enable_dependency_tracking" != xno; then
-  am_depcomp="$ac_aux_dir/depcomp"
-  AMDEPBACKSLASH='\'
-  am__nodep='_no'
-fi
-AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno])
-AC_SUBST([AMDEPBACKSLASH])dnl
-_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl
-AC_SUBST([am__nodep])dnl
-_AM_SUBST_NOTMAKE([am__nodep])dnl
-])
-
-# Generate code to set up dependency tracking.              -*- Autoconf -*-
-
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-
-# _AM_OUTPUT_DEPENDENCY_COMMANDS
-# ------------------------------
-AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS],
-[{
-  # Older Autoconf quotes --file arguments for eval, but not when files
-  # are listed without --file.  Let's play safe and only enable the eval
-  # if we detect the quoting.
-  case $CONFIG_FILES in
-  *\'*) eval set x "$CONFIG_FILES" ;;
-  *)   set x $CONFIG_FILES ;;
-  esac
-  shift
-  for mf
-  do
-    # Strip MF so we end up with the name of the file.
-    mf=`echo "$mf" | sed -e 's/:.*$//'`
-    # Check whether this is an Automake generated Makefile or not.
-    # We used to match only the files named 'Makefile.in', but
-    # some people rename them; so instead we look at the file content.
-    # Grep'ing the first line is not enough: some people post-process
-    # each Makefile.in and add a new line on top of each file to say so.
-    # Grep'ing the whole file is not good either: AIX grep has a line
-    # limit of 2048, but all sed's we know have understand at least 4000.
-    if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then
-      dirpart=`AS_DIRNAME("$mf")`
-    else
-      continue
-    fi
-    # Extract the definition of DEPDIR, am__include, and am__quote
-    # from the Makefile without running 'make'.
-    DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
-    test -z "$DEPDIR" && continue
-    am__include=`sed -n 's/^am__include = //p' < "$mf"`
-    test -z "$am__include" && continue
-    am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
-    # Find all dependency output files, they are included files with
-    # $(DEPDIR) in their names.  We invoke sed twice because it is the
-    # simplest approach to changing $(DEPDIR) to its actual value in the
-    # expansion.
-    for file in `sed -n "
-      s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
-	 sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do
-      # Make sure the directory exists.
-      test -f "$dirpart/$file" && continue
-      fdir=`AS_DIRNAME(["$file"])`
-      AS_MKDIR_P([$dirpart/$fdir])
-      # echo "creating $dirpart/$file"
-      echo '# dummy' > "$dirpart/$file"
-    done
-  done
-}
-])# _AM_OUTPUT_DEPENDENCY_COMMANDS
-
-
-# AM_OUTPUT_DEPENDENCY_COMMANDS
-# -----------------------------
-# This macro should only be invoked once -- use via AC_REQUIRE.
-#
-# This code is only required when automatic dependency tracking
-# is enabled.  FIXME.  This creates each '.P' file that we will
-# need in order to bootstrap the dependency handling code.
-AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
-[AC_CONFIG_COMMANDS([depfiles],
-     [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS],
-     [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"])
-])
-
-# Do all the work for Automake.                             -*- Autoconf -*-
-
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This macro actually does too much.  Some checks are only needed if
-# your package does certain things.  But this isn't really a big deal.
-
-dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O.
-m4_define([AC_PROG_CC],
-m4_defn([AC_PROG_CC])
-[_AM_PROG_CC_C_O
-])
-
-# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
-# AM_INIT_AUTOMAKE([OPTIONS])
-# -----------------------------------------------
-# The call with PACKAGE and VERSION arguments is the old style
-# call (pre autoconf-2.50), which is being phased out.  PACKAGE
-# and VERSION should now be passed to AC_INIT and removed from
-# the call to AM_INIT_AUTOMAKE.
-# We support both call styles for the transition.  After
-# the next Automake release, Autoconf can make the AC_INIT
-# arguments mandatory, and then we can depend on a new Autoconf
-# release and drop the old call support.
-AC_DEFUN([AM_INIT_AUTOMAKE],
-[AC_PREREQ([2.65])dnl
-dnl Autoconf wants to disallow AM_ names.  We explicitly allow
-dnl the ones we care about.
-m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl
-AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl
-AC_REQUIRE([AC_PROG_INSTALL])dnl
-if test "`cd $srcdir && pwd`" != "`pwd`"; then
-  # Use -I$(srcdir) only when $(srcdir) != ., so that make's output
-  # is not polluted with repeated "-I."
-  AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl
-  # test to see if srcdir already configured
-  if test -f $srcdir/config.status; then
-    AC_MSG_ERROR([source directory already configured; run "make distclean" there first])
-  fi
-fi
-
-# test whether we have cygpath
-if test -z "$CYGPATH_W"; then
-  if (cygpath --version) >/dev/null 2>/dev/null; then
-    CYGPATH_W='cygpath -w'
-  else
-    CYGPATH_W=echo
-  fi
-fi
-AC_SUBST([CYGPATH_W])
-
-# Define the identity of the package.
-dnl Distinguish between old-style and new-style calls.
-m4_ifval([$2],
-[AC_DIAGNOSE([obsolete],
-             [$0: two- and three-arguments forms are deprecated.])
-m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl
- AC_SUBST([PACKAGE], [$1])dnl
- AC_SUBST([VERSION], [$2])],
-[_AM_SET_OPTIONS([$1])dnl
-dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT.
-m4_if(
-  m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]),
-  [ok:ok],,
-  [m4_fatal([AC_INIT should be called with package and version arguments])])dnl
- AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl
- AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl
-
-_AM_IF_OPTION([no-define],,
-[AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package])
- AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl
-
-# Some tools Automake needs.
-AC_REQUIRE([AM_SANITY_CHECK])dnl
-AC_REQUIRE([AC_ARG_PROGRAM])dnl
-AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}])
-AM_MISSING_PROG([AUTOCONF], [autoconf])
-AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}])
-AM_MISSING_PROG([AUTOHEADER], [autoheader])
-AM_MISSING_PROG([MAKEINFO], [makeinfo])
-AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
-AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl
-AC_REQUIRE([AC_PROG_MKDIR_P])dnl
-# For better backward compatibility.  To be removed once Automake 1.9.x
-# dies out for good.  For more background, see:
-# <http://lists.gnu.org/archive/html/automake/2012-07/msg00001.html>
-# <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
-AC_SUBST([mkdir_p], ['$(MKDIR_P)'])
-# We need awk for the "check" target.  The system "awk" is bad on
-# some platforms.
-AC_REQUIRE([AC_PROG_AWK])dnl
-AC_REQUIRE([AC_PROG_MAKE_SET])dnl
-AC_REQUIRE([AM_SET_LEADING_DOT])dnl
-_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
-	      [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
-			     [_AM_PROG_TAR([v7])])])
-_AM_IF_OPTION([no-dependencies],,
-[AC_PROVIDE_IFELSE([AC_PROG_CC],
-		  [_AM_DEPENDENCIES([CC])],
-		  [m4_define([AC_PROG_CC],
-			     m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl
-AC_PROVIDE_IFELSE([AC_PROG_CXX],
-		  [_AM_DEPENDENCIES([CXX])],
-		  [m4_define([AC_PROG_CXX],
-			     m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl
-AC_PROVIDE_IFELSE([AC_PROG_OBJC],
-		  [_AM_DEPENDENCIES([OBJC])],
-		  [m4_define([AC_PROG_OBJC],
-			     m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl
-AC_PROVIDE_IFELSE([AC_PROG_OBJCXX],
-		  [_AM_DEPENDENCIES([OBJCXX])],
-		  [m4_define([AC_PROG_OBJCXX],
-			     m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl
-])
-AC_REQUIRE([AM_SILENT_RULES])dnl
-dnl The testsuite driver may need to know about EXEEXT, so add the
-dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen.  This
-dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below.
-AC_CONFIG_COMMANDS_PRE(dnl
-[m4_provide_if([_AM_COMPILER_EXEEXT],
-  [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl
-
-# POSIX will say in a future version that running "rm -f" with no argument
-# is OK; and we want to be able to make that assumption in our Makefile
-# recipes.  So use an aggressive probe to check that the usage we want is
-# actually supported "in the wild" to an acceptable degree.
-# See automake bug#10828.
-# To make any issue more visible, cause the running configure to be aborted
-# by default if the 'rm' program in use doesn't match our expectations; the
-# user can still override this though.
-if rm -f && rm -fr && rm -rf; then : OK; else
-  cat >&2 <<'END'
-Oops!
-
-Your 'rm' program seems unable to run without file operands specified
-on the command line, even when the '-f' option is present.  This is contrary
-to the behaviour of most rm programs out there, and not conforming with
-the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542>
-
-Please tell bug-automake@gnu.org about your system, including the value
-of your $PATH and any error possibly output before this message.  This
-can help us improve future automake versions.
-
-END
-  if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then
-    echo 'Configuration will proceed anyway, since you have set the' >&2
-    echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2
-    echo >&2
-  else
-    cat >&2 <<'END'
-Aborting the configuration process, to ensure you take notice of the issue.
-
-You can download and install GNU coreutils to get an 'rm' implementation
-that behaves properly: <http://www.gnu.org/software/coreutils/>.
-
-If you want to complete the configuration process using your problematic
-'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM
-to "yes", and re-run configure.
-
-END
-    AC_MSG_ERROR([Your 'rm' program is bad, sorry.])
-  fi
-fi
-])
-
-dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion.  Do not
-dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further
-dnl mangled by Autoconf and run in a shell conditional statement.
-m4_define([_AC_COMPILER_EXEEXT],
-m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])])
-
-# When config.status generates a header, we must update the stamp-h file.
-# This file resides in the same directory as the config header
-# that is generated.  The stamp files are numbered to have different names.
-
-# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the
-# loop where config.status creates the headers, so we can generate
-# our stamp files there.
-AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK],
-[# Compute $1's index in $config_headers.
-_am_arg=$1
-_am_stamp_count=1
-for _am_header in $config_headers :; do
-  case $_am_header in
-    $_am_arg | $_am_arg:* )
-      break ;;
-    * )
-      _am_stamp_count=`expr $_am_stamp_count + 1` ;;
-  esac
-done
-echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count])
-
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_PROG_INSTALL_SH
-# ------------------
-# Define $install_sh.
-AC_DEFUN([AM_PROG_INSTALL_SH],
-[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-if test x"${install_sh}" != xset; then
-  case $am_aux_dir in
-  *\ * | *\	*)
-    install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
-  *)
-    install_sh="\${SHELL} $am_aux_dir/install-sh"
-  esac
-fi
-AC_SUBST([install_sh])])
-
-# Copyright (C) 2003-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# Check whether the underlying file-system supports filenames
-# with a leading dot.  For instance MS-DOS doesn't.
-AC_DEFUN([AM_SET_LEADING_DOT],
-[rm -rf .tst 2>/dev/null
-mkdir .tst 2>/dev/null
-if test -d .tst; then
-  am__leading_dot=.
-else
-  am__leading_dot=_
-fi
-rmdir .tst 2>/dev/null
-AC_SUBST([am__leading_dot])])
-
-# Check to see how 'make' treats includes.	            -*- Autoconf -*-
-
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_MAKE_INCLUDE()
-# -----------------
-# Check to see how make treats includes.
-AC_DEFUN([AM_MAKE_INCLUDE],
-[am_make=${MAKE-make}
-cat > confinc << 'END'
-am__doit:
-	@echo this is the am__doit target
-.PHONY: am__doit
-END
-# If we don't find an include directive, just comment out the code.
-AC_MSG_CHECKING([for style of include used by $am_make])
-am__include="#"
-am__quote=
-_am_result=none
-# First try GNU make style include.
-echo "include confinc" > confmf
-# Ignore all kinds of additional output from 'make'.
-case `$am_make -s -f confmf 2> /dev/null` in #(
-*the\ am__doit\ target*)
-  am__include=include
-  am__quote=
-  _am_result=GNU
-  ;;
-esac
-# Now try BSD make style include.
-if test "$am__include" = "#"; then
-   echo '.include "confinc"' > confmf
-   case `$am_make -s -f confmf 2> /dev/null` in #(
-   *the\ am__doit\ target*)
-     am__include=.include
-     am__quote="\""
-     _am_result=BSD
-     ;;
-   esac
-fi
-AC_SUBST([am__include])
-AC_SUBST([am__quote])
-AC_MSG_RESULT([$_am_result])
-rm -f confinc confmf
-])
-
-# Fake the existence of programs that GNU maintainers use.  -*- Autoconf -*-
-
-# Copyright (C) 1997-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_MISSING_PROG(NAME, PROGRAM)
-# ------------------------------
-AC_DEFUN([AM_MISSING_PROG],
-[AC_REQUIRE([AM_MISSING_HAS_RUN])
-$1=${$1-"${am_missing_run}$2"}
-AC_SUBST($1)])
-
-# AM_MISSING_HAS_RUN
-# ------------------
-# Define MISSING if not defined so far and test if it is modern enough.
-# If it is, set am_missing_run to use it, otherwise, to nothing.
-AC_DEFUN([AM_MISSING_HAS_RUN],
-[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-AC_REQUIRE_AUX_FILE([missing])dnl
-if test x"${MISSING+set}" != xset; then
-  case $am_aux_dir in
-  *\ * | *\	*)
-    MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;;
-  *)
-    MISSING="\${SHELL} $am_aux_dir/missing" ;;
-  esac
-fi
-# Use eval to expand $SHELL
-if eval "$MISSING --is-lightweight"; then
-  am_missing_run="$MISSING "
-else
-  am_missing_run=
-  AC_MSG_WARN(['missing' script is too old or missing])
-fi
-])
-
-# Helper functions for option handling.                     -*- Autoconf -*-
-
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# _AM_MANGLE_OPTION(NAME)
-# -----------------------
-AC_DEFUN([_AM_MANGLE_OPTION],
-[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])])
-
-# _AM_SET_OPTION(NAME)
-# --------------------
-# Set option NAME.  Presently that only means defining a flag for this option.
-AC_DEFUN([_AM_SET_OPTION],
-[m4_define(_AM_MANGLE_OPTION([$1]), [1])])
-
-# _AM_SET_OPTIONS(OPTIONS)
-# ------------------------
-# OPTIONS is a space-separated list of Automake options.
-AC_DEFUN([_AM_SET_OPTIONS],
-[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
-
-# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET])
-# -------------------------------------------
-# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
-AC_DEFUN([_AM_IF_OPTION],
-[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
-
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# _AM_PROG_CC_C_O
-# ---------------
-# Like AC_PROG_CC_C_O, but changed for automake.  We rewrite AC_PROG_CC
-# to automatically call this.
-AC_DEFUN([_AM_PROG_CC_C_O],
-[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-AC_REQUIRE_AUX_FILE([compile])dnl
-AC_LANG_PUSH([C])dnl
-AC_CACHE_CHECK(
-  [whether $CC understands -c and -o together],
-  [am_cv_prog_cc_c_o],
-  [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])])
-  # Make sure it works both with $CC and with simple cc.
-  # Following AC_PROG_CC_C_O, we do the test twice because some
-  # compilers refuse to overwrite an existing .o file with -o,
-  # though they will create one.
-  am_cv_prog_cc_c_o=yes
-  for am_i in 1 2; do
-    if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \
-         && test -f conftest2.$ac_objext; then
-      : OK
-    else
-      am_cv_prog_cc_c_o=no
-      break
-    fi
-  done
-  rm -f core conftest*
-  unset am_i])
-if test "$am_cv_prog_cc_c_o" != yes; then
-   # Losing compiler, so override with the script.
-   # FIXME: It is wrong to rewrite CC.
-   # But if we don't then we get into trouble of one sort or another.
-   # A longer-term fix would be to have automake use am__CC in this case,
-   # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
-   CC="$am_aux_dir/compile $CC"
-fi
-AC_LANG_POP([C])])
-
-# For backward compatibility.
-AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])])
-
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_RUN_LOG(COMMAND)
-# -------------------
-# Run COMMAND, save the exit status in ac_status, and log it.
-# (This has been adapted from Autoconf's _AC_RUN_LOG macro.)
-AC_DEFUN([AM_RUN_LOG],
-[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD
-   ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD
-   ac_status=$?
-   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
-   (exit $ac_status); }])
-
-# Check to make sure that the build environment is sane.    -*- Autoconf -*-
-
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_SANITY_CHECK
-# ---------------
-AC_DEFUN([AM_SANITY_CHECK],
-[AC_MSG_CHECKING([whether build environment is sane])
-# Reject unsafe characters in $srcdir or the absolute working directory
-# name.  Accept space and tab only in the latter.
-am_lf='
-'
-case `pwd` in
-  *[[\\\"\#\$\&\'\`$am_lf]]*)
-    AC_MSG_ERROR([unsafe absolute working directory name]);;
-esac
-case $srcdir in
-  *[[\\\"\#\$\&\'\`$am_lf\ \	]]*)
-    AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);;
-esac
-
-# Do 'set' in a subshell so we don't clobber the current shell's
-# arguments.  Must try -L first in case configure is actually a
-# symlink; some systems play weird games with the mod time of symlinks
-# (eg FreeBSD returns the mod time of the symlink's containing
-# directory).
-if (
-   am_has_slept=no
-   for am_try in 1 2; do
-     echo "timestamp, slept: $am_has_slept" > conftest.file
-     set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null`
-     if test "$[*]" = "X"; then
-	# -L didn't work.
-	set X `ls -t "$srcdir/configure" conftest.file`
-     fi
-     if test "$[*]" != "X $srcdir/configure conftest.file" \
-	&& test "$[*]" != "X conftest.file $srcdir/configure"; then
-
-	# If neither matched, then we have a broken ls.  This can happen
-	# if, for instance, CONFIG_SHELL is bash and it inherits a
-	# broken ls alias from the environment.  This has actually
-	# happened.  Such a system could not be considered "sane".
-	AC_MSG_ERROR([ls -t appears to fail.  Make sure there is not a broken
-  alias in your environment])
-     fi
-     if test "$[2]" = conftest.file || test $am_try -eq 2; then
-       break
-     fi
-     # Just in case.
-     sleep 1
-     am_has_slept=yes
-   done
-   test "$[2]" = conftest.file
-   )
-then
-   # Ok.
-   :
-else
-   AC_MSG_ERROR([newly created file is older than distributed files!
-Check your system clock])
-fi
-AC_MSG_RESULT([yes])
-# If we didn't sleep, we still need to ensure time stamps of config.status and
-# generated files are strictly newer.
-am_sleep_pid=
-if grep 'slept: no' conftest.file >/dev/null 2>&1; then
-  ( sleep 1 ) &
-  am_sleep_pid=$!
-fi
-AC_CONFIG_COMMANDS_PRE(
-  [AC_MSG_CHECKING([that generated files are newer than configure])
-   if test -n "$am_sleep_pid"; then
-     # Hide warnings about reused PIDs.
-     wait $am_sleep_pid 2>/dev/null
-   fi
-   AC_MSG_RESULT([done])])
-rm -f conftest.file
-])
-
-# Copyright (C) 2009-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_SILENT_RULES([DEFAULT])
-# --------------------------
-# Enable less verbose build rules; with the default set to DEFAULT
-# ("yes" being less verbose, "no" or empty being verbose).
-AC_DEFUN([AM_SILENT_RULES],
-[AC_ARG_ENABLE([silent-rules], [dnl
-AS_HELP_STRING(
-  [--enable-silent-rules],
-  [less verbose build output (undo: "make V=1")])
-AS_HELP_STRING(
-  [--disable-silent-rules],
-  [verbose build output (undo: "make V=0")])dnl
-])
-case $enable_silent_rules in @%:@ (((
-  yes) AM_DEFAULT_VERBOSITY=0;;
-   no) AM_DEFAULT_VERBOSITY=1;;
-    *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);;
-esac
-dnl
-dnl A few 'make' implementations (e.g., NonStop OS and NextStep)
-dnl do not support nested variable expansions.
-dnl See automake bug#9928 and bug#10237.
-am_make=${MAKE-make}
-AC_CACHE_CHECK([whether $am_make supports nested variables],
-   [am_cv_make_support_nested_variables],
-   [if AS_ECHO([['TRUE=$(BAR$(V))
-BAR0=false
-BAR1=true
-V=1
-am__doit:
-	@$(TRUE)
-.PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then
-  am_cv_make_support_nested_variables=yes
-else
-  am_cv_make_support_nested_variables=no
-fi])
-if test $am_cv_make_support_nested_variables = yes; then
-  dnl Using '$V' instead of '$(V)' breaks IRIX make.
-  AM_V='$(V)'
-  AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)'
-else
-  AM_V=$AM_DEFAULT_VERBOSITY
-  AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY
-fi
-AC_SUBST([AM_V])dnl
-AM_SUBST_NOTMAKE([AM_V])dnl
-AC_SUBST([AM_DEFAULT_V])dnl
-AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl
-AC_SUBST([AM_DEFAULT_VERBOSITY])dnl
-AM_BACKSLASH='\'
-AC_SUBST([AM_BACKSLASH])dnl
-_AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl
-])
-
-# Copyright (C) 2001-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# AM_PROG_INSTALL_STRIP
-# ---------------------
-# One issue with vendor 'install' (even GNU) is that you can't
-# specify the program used to strip binaries.  This is especially
-# annoying in cross-compiling environments, where the build's strip
-# is unlikely to handle the host's binaries.
-# Fortunately install-sh will honor a STRIPPROG variable, so we
-# always use install-sh in "make install-strip", and initialize
-# STRIPPROG with the value of the STRIP variable (set by the user).
-AC_DEFUN([AM_PROG_INSTALL_STRIP],
-[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
-# Installed binaries are usually stripped using 'strip' when the user
-# run "make install-strip".  However 'strip' might not be the right
-# tool to use in cross-compilation environments, therefore Automake
-# will honor the 'STRIP' environment variable to overrule this program.
-dnl Don't test for $cross_compiling = yes, because it might be 'maybe'.
-if test "$cross_compiling" != no; then
-  AC_CHECK_TOOL([STRIP], [strip], :)
-fi
-INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
-AC_SUBST([INSTALL_STRIP_PROGRAM])])
-
-# Copyright (C) 2006-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# _AM_SUBST_NOTMAKE(VARIABLE)
-# ---------------------------
-# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in.
-# This macro is traced by Automake.
-AC_DEFUN([_AM_SUBST_NOTMAKE])
-
-# AM_SUBST_NOTMAKE(VARIABLE)
-# --------------------------
-# Public sister of _AM_SUBST_NOTMAKE.
-AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)])
-
-# Check how to create a tarball.                            -*- Autoconf -*-
-
-# Copyright (C) 2004-2013 Free Software Foundation, Inc.
-#
-# This file is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# _AM_PROG_TAR(FORMAT)
-# --------------------
-# Check how to create a tarball in format FORMAT.
-# FORMAT should be one of 'v7', 'ustar', or 'pax'.
-#
-# Substitute a variable $(am__tar) that is a command
-# writing to stdout a FORMAT-tarball containing the directory
-# $tardir.
-#     tardir=directory && $(am__tar) > result.tar
-#
-# Substitute a variable $(am__untar) that extract such
-# a tarball read from stdin.
-#     $(am__untar) < result.tar
-#
-AC_DEFUN([_AM_PROG_TAR],
-[# Always define AMTAR for backward compatibility.  Yes, it's still used
-# in the wild :-(  We should find a proper way to deprecate it ...
-AC_SUBST([AMTAR], ['$${TAR-tar}'])
-
-# We'll loop over all known methods to create a tar archive until one works.
-_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none'
-
-m4_if([$1], [v7],
-  [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'],
-
-  [m4_case([$1],
-    [ustar],
-     [# The POSIX 1988 'ustar' format is defined with fixed-size fields.
-      # There is notably a 21 bits limit for the UID and the GID.  In fact,
-      # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343
-      # and bug#13588).
-      am_max_uid=2097151 # 2^21 - 1
-      am_max_gid=$am_max_uid
-      # The $UID and $GID variables are not portable, so we need to resort
-      # to the POSIX-mandated id(1) utility.  Errors in the 'id' calls
-      # below are definitely unexpected, so allow the users to see them
-      # (that is, avoid stderr redirection).
-      am_uid=`id -u || echo unknown`
-      am_gid=`id -g || echo unknown`
-      AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format])
-      if test $am_uid -le $am_max_uid; then
-         AC_MSG_RESULT([yes])
-      else
-         AC_MSG_RESULT([no])
-         _am_tools=none
-      fi
-      AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format])
-      if test $am_gid -le $am_max_gid; then
-         AC_MSG_RESULT([yes])
-      else
-        AC_MSG_RESULT([no])
-        _am_tools=none
-      fi],
-
-  [pax],
-    [],
-
-  [m4_fatal([Unknown tar format])])
-
-  AC_MSG_CHECKING([how to create a $1 tar archive])
-
-  # Go ahead even if we have the value already cached.  We do so because we
-  # need to set the values for the 'am__tar' and 'am__untar' variables.
-  _am_tools=${am_cv_prog_tar_$1-$_am_tools}
-
-  for _am_tool in $_am_tools; do
-    case $_am_tool in
-    gnutar)
-      for _am_tar in tar gnutar gtar; do
-        AM_RUN_LOG([$_am_tar --version]) && break
-      done
-      am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"'
-      am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"'
-      am__untar="$_am_tar -xf -"
-      ;;
-    plaintar)
-      # Must skip GNU tar: if it does not support --format= it doesn't create
-      # ustar tarball either.
-      (tar --version) >/dev/null 2>&1 && continue
-      am__tar='tar chf - "$$tardir"'
-      am__tar_='tar chf - "$tardir"'
-      am__untar='tar xf -'
-      ;;
-    pax)
-      am__tar='pax -L -x $1 -w "$$tardir"'
-      am__tar_='pax -L -x $1 -w "$tardir"'
-      am__untar='pax -r'
-      ;;
-    cpio)
-      am__tar='find "$$tardir" -print | cpio -o -H $1 -L'
-      am__tar_='find "$tardir" -print | cpio -o -H $1 -L'
-      am__untar='cpio -i -H $1 -d'
-      ;;
-    none)
-      am__tar=false
-      am__tar_=false
-      am__untar=false
-      ;;
-    esac
-
-    # If the value was cached, stop now.  We just wanted to have am__tar
-    # and am__untar set.
-    test -n "${am_cv_prog_tar_$1}" && break
-
-    # tar/untar a dummy directory, and stop if the command works.
-    rm -rf conftest.dir
-    mkdir conftest.dir
-    echo GrepMe > conftest.dir/file
-    AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar])
-    rm -rf conftest.dir
-    if test -s conftest.tar; then
-      AM_RUN_LOG([$am__untar <conftest.tar])
-      AM_RUN_LOG([cat conftest.dir/file])
-      grep GrepMe conftest.dir/file >/dev/null 2>&1 && break
-    fi
-  done
-  rm -rf conftest.dir
-
-  AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool])
-  AC_MSG_RESULT([$am_cv_prog_tar_$1])])
-
-AC_SUBST([am__tar])
-AC_SUBST([am__untar])
-]) # _AM_PROG_TAR
-
-m4_include([m4/ax_append_compile_flags.m4])
-m4_include([m4/ax_append_flag.m4])
-m4_include([m4/ax_check_compile_flag.m4])
-m4_include([m4/ax_check_link_flag.m4])
-m4_include([m4/ax_check_openssl.m4])
-m4_include([m4/ax_count_cpus.m4])
-m4_include([m4/ax_have_epoll.m4])
-m4_include([m4/ax_pthread.m4])
-m4_include([m4/ax_require_defined.m4])
-m4_include([m4/libcurl.m4])
-m4_include([m4/libgcrypt.m4])
-m4_include([m4/libtool.m4])
-m4_include([m4/ltoptions.m4])
-m4_include([m4/ltsugar.m4])
-m4_include([m4/ltversion.m4])
-m4_include([m4/lt~obsolete.m4])
-m4_include([acinclude.m4])
diff --git a/autogen.sh b/autogen.sh
new file mode 100755
index 0000000..dd9ec6e
--- /dev/null
+++ b/autogen.sh
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+# This file was added for compatibility with some automated build systems.
+# It is recommended to use 'bootstrap' directly instead.
+
+ag_srcdir="${0%/*}" && ag_srcdir="${ag_srcdir}${ag_srcdir:+/}"
+"${ag_srcdir}./bootstrap" ${1+"$@"}
diff --git a/bootstrap b/bootstrap
new file mode 100755
index 0000000..8e1212f
--- /dev/null
+++ b/bootstrap
@@ -0,0 +1,74 @@
+#!/bin/sh
+
+# This is more portable than `which' but comes with
+# the caveat of not(?) properly working on busybox's ash:
+have_command()
+{
+    command -v "$1" >/dev/null 2>&1
+}
+
+unset bs_srcdir
+if test X"`dirname / 2>/dev/null`" = X"/"; then
+  bs_scrdir=`dirname $0`
+else
+  case $0 in
+    */*) bs_scrdir=`echo $0 | ${SED-sed} -n -e 's|/.*$||p'` ;;
+    *) bs_scrdir='.' ;;
+  esac
+fi
+
+test -n "$bs_scrdir" && cd "$bs_scrdir" || echo "Warning: cannot detect sources directory" 1>&2
+
+if test ! -f './configure.ac'; then
+  echo "Error: no 'configure.ac' found. Wrong sources directory?" 1>&2
+  exit 2
+fi
+if test ! -f './src/include/microhttpd.h'; then
+  echo "Error: src/include/libmicrohttpd.h not found. Wrong sources directory?" 1>&2
+  exit 2
+fi
+
+if have_command uncrustify; then
+    if test -f uncrustify.cfg; then
+      echo "Uncrustify configuration already exists, skipping installation from the upstream file."
+    else
+      echo "Installing configuration"
+      ln -s contrib/uncrustify.cfg uncrustify.cfg
+    fi
+    if test -d '.git'; then
+      if test -f .git/hooks/pre-commit; then
+        echo "Pre-commit git hook already exists, skipping installation from the upstream file."
+      else
+        echo "Installing uncrustify pre-commit git hook"
+        ln -s ../../contrib/uncrustify_precommit .git/hooks/pre-commit
+      fi
+    else
+      echo "No '.git' directory found, skipping installation of pre-commit git hook."
+    fi
+else
+    echo "Uncrustify not detected, hook not installed. Please install uncrustify if you plan on doing development."
+fi
+
+if have_command libtool || have_command libtoolize || have_command glibtoolize || have_command slibtool; then
+    echo "Running autotools..."
+    have_command libtoolize && \
+      aclocal -I m4 --install && \
+      libtoolize -c -i -v && \
+      autoconf && \
+      autoheader && \
+      automake -a -c --gnu
+    if test $? -ne 0 || ! test -x configure || ! test -f Makefile.in ; then
+        echo "Trying with autoreconf..."
+        if ! autoreconf -i ${1+"$@"} ; then
+            echo "Failed to autoreconf, retrying with force install..."
+            if ! autoreconf -i -f ${1+"$@"} ; then
+                echo "*** Failed to create 'configure' and other autotools generated files. ***" >&2
+                exit 1
+            fi
+        fi
+    fi
+    echo "The ${bs_scrdir-.}/configure is ready to run."
+else
+    echo "*** No libtoolize or libtool found, please install it ***" >&2;
+    exit 1
+fi
diff --git a/compile b/compile
deleted file mode 100755
index 531136b..0000000
--- a/compile
+++ /dev/null
@@ -1,347 +0,0 @@
-#! /bin/sh
-# Wrapper for compilers which do not understand '-c -o'.
-
-scriptversion=2012-10-14.11; # UTC
-
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
-# Written by Tom Tromey <tromey@cygnus.com>.
-#
-# 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 2, 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/>.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# This file is maintained in Automake, please report
-# bugs to <bug-automake@gnu.org> or send patches to
-# <automake-patches@gnu.org>.
-
-nl='
-'
-
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent tools from complaining about whitespace usage.
-IFS=" ""	$nl"
-
-file_conv=
-
-# func_file_conv build_file lazy
-# Convert a $build file to $host form and store it in $file
-# Currently only supports Windows hosts. If the determined conversion
-# type is listed in (the comma separated) LAZY, no conversion will
-# take place.
-func_file_conv ()
-{
-  file=$1
-  case $file in
-    / | /[!/]*) # absolute file, and not a UNC file
-      if test -z "$file_conv"; then
-	# lazily determine how to convert abs files
-	case `uname -s` in
-	  MINGW*)
-	    file_conv=mingw
-	    ;;
-	  CYGWIN*)
-	    file_conv=cygwin
-	    ;;
-	  *)
-	    file_conv=wine
-	    ;;
-	esac
-      fi
-      case $file_conv/,$2, in
-	*,$file_conv,*)
-	  ;;
-	mingw/*)
-	  file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
-	  ;;
-	cygwin/*)
-	  file=`cygpath -m "$file" || echo "$file"`
-	  ;;
-	wine/*)
-	  file=`winepath -w "$file" || echo "$file"`
-	  ;;
-      esac
-      ;;
-  esac
-}
-
-# func_cl_dashL linkdir
-# Make cl look for libraries in LINKDIR
-func_cl_dashL ()
-{
-  func_file_conv "$1"
-  if test -z "$lib_path"; then
-    lib_path=$file
-  else
-    lib_path="$lib_path;$file"
-  fi
-  linker_opts="$linker_opts -LIBPATH:$file"
-}
-
-# func_cl_dashl library
-# Do a library search-path lookup for cl
-func_cl_dashl ()
-{
-  lib=$1
-  found=no
-  save_IFS=$IFS
-  IFS=';'
-  for dir in $lib_path $LIB
-  do
-    IFS=$save_IFS
-    if $shared && test -f "$dir/$lib.dll.lib"; then
-      found=yes
-      lib=$dir/$lib.dll.lib
-      break
-    fi
-    if test -f "$dir/$lib.lib"; then
-      found=yes
-      lib=$dir/$lib.lib
-      break
-    fi
-    if test -f "$dir/lib$lib.a"; then
-      found=yes
-      lib=$dir/lib$lib.a
-      break
-    fi
-  done
-  IFS=$save_IFS
-
-  if test "$found" != yes; then
-    lib=$lib.lib
-  fi
-}
-
-# func_cl_wrapper cl arg...
-# Adjust compile command to suit cl
-func_cl_wrapper ()
-{
-  # Assume a capable shell
-  lib_path=
-  shared=:
-  linker_opts=
-  for arg
-  do
-    if test -n "$eat"; then
-      eat=
-    else
-      case $1 in
-	-o)
-	  # configure might choose to run compile as 'compile cc -o foo foo.c'.
-	  eat=1
-	  case $2 in
-	    *.o | *.[oO][bB][jJ])
-	      func_file_conv "$2"
-	      set x "$@" -Fo"$file"
-	      shift
-	      ;;
-	    *)
-	      func_file_conv "$2"
-	      set x "$@" -Fe"$file"
-	      shift
-	      ;;
-	  esac
-	  ;;
-	-I)
-	  eat=1
-	  func_file_conv "$2" mingw
-	  set x "$@" -I"$file"
-	  shift
-	  ;;
-	-I*)
-	  func_file_conv "${1#-I}" mingw
-	  set x "$@" -I"$file"
-	  shift
-	  ;;
-	-l)
-	  eat=1
-	  func_cl_dashl "$2"
-	  set x "$@" "$lib"
-	  shift
-	  ;;
-	-l*)
-	  func_cl_dashl "${1#-l}"
-	  set x "$@" "$lib"
-	  shift
-	  ;;
-	-L)
-	  eat=1
-	  func_cl_dashL "$2"
-	  ;;
-	-L*)
-	  func_cl_dashL "${1#-L}"
-	  ;;
-	-static)
-	  shared=false
-	  ;;
-	-Wl,*)
-	  arg=${1#-Wl,}
-	  save_ifs="$IFS"; IFS=','
-	  for flag in $arg; do
-	    IFS="$save_ifs"
-	    linker_opts="$linker_opts $flag"
-	  done
-	  IFS="$save_ifs"
-	  ;;
-	-Xlinker)
-	  eat=1
-	  linker_opts="$linker_opts $2"
-	  ;;
-	-*)
-	  set x "$@" "$1"
-	  shift
-	  ;;
-	*.cc | *.CC | *.cxx | *.CXX | *.[cC]++)
-	  func_file_conv "$1"
-	  set x "$@" -Tp"$file"
-	  shift
-	  ;;
-	*.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO])
-	  func_file_conv "$1" mingw
-	  set x "$@" "$file"
-	  shift
-	  ;;
-	*)
-	  set x "$@" "$1"
-	  shift
-	  ;;
-      esac
-    fi
-    shift
-  done
-  if test -n "$linker_opts"; then
-    linker_opts="-link$linker_opts"
-  fi
-  exec "$@" $linker_opts
-  exit 1
-}
-
-eat=
-
-case $1 in
-  '')
-     echo "$0: No command.  Try '$0 --help' for more information." 1>&2
-     exit 1;
-     ;;
-  -h | --h*)
-    cat <<\EOF
-Usage: compile [--help] [--version] PROGRAM [ARGS]
-
-Wrapper for compilers which do not understand '-c -o'.
-Remove '-o dest.o' from ARGS, run PROGRAM with the remaining
-arguments, and rename the output as expected.
-
-If you are trying to build a whole package this is not the
-right script to run: please start by reading the file 'INSTALL'.
-
-Report bugs to <bug-automake@gnu.org>.
-EOF
-    exit $?
-    ;;
-  -v | --v*)
-    echo "compile $scriptversion"
-    exit $?
-    ;;
-  cl | *[/\\]cl | cl.exe | *[/\\]cl.exe )
-    func_cl_wrapper "$@"      # Doesn't return...
-    ;;
-esac
-
-ofile=
-cfile=
-
-for arg
-do
-  if test -n "$eat"; then
-    eat=
-  else
-    case $1 in
-      -o)
-	# configure might choose to run compile as 'compile cc -o foo foo.c'.
-	# So we strip '-o arg' only if arg is an object.
-	eat=1
-	case $2 in
-	  *.o | *.obj)
-	    ofile=$2
-	    ;;
-	  *)
-	    set x "$@" -o "$2"
-	    shift
-	    ;;
-	esac
-	;;
-      *.c)
-	cfile=$1
-	set x "$@" "$1"
-	shift
-	;;
-      *)
-	set x "$@" "$1"
-	shift
-	;;
-    esac
-  fi
-  shift
-done
-
-if test -z "$ofile" || test -z "$cfile"; then
-  # If no '-o' option was seen then we might have been invoked from a
-  # pattern rule where we don't need one.  That is ok -- this is a
-  # normal compilation that the losing compiler can handle.  If no
-  # '.c' file was seen then we are probably linking.  That is also
-  # ok.
-  exec "$@"
-fi
-
-# Name of file we expect compiler to create.
-cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
-
-# Create the lock directory.
-# Note: use '[/\\:.-]' here to ensure that we don't use the same name
-# that we are using for the .o file.  Also, base the name on the expected
-# object file name, since that is what matters with a parallel build.
-lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
-while true; do
-  if mkdir "$lockdir" >/dev/null 2>&1; then
-    break
-  fi
-  sleep 1
-done
-# FIXME: race condition here if user kills between mkdir and trap.
-trap "rmdir '$lockdir'; exit 1" 1 2 15
-
-# Run the compile.
-"$@"
-ret=$?
-
-if test -f "$cofile"; then
-  test "$cofile" = "$ofile" || mv "$cofile" "$ofile"
-elif test -f "${cofile}bj"; then
-  test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile"
-fi
-
-rmdir "$lockdir"
-exit $ret
-
-# Local Variables:
-# mode: shell-script
-# sh-indentation: 2
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/config.guess b/config.guess
deleted file mode 100755
index 1f5c50c..0000000
--- a/config.guess
+++ /dev/null
@@ -1,1420 +0,0 @@
-#! /bin/sh
-# Attempt to guess a canonical system name.
-#   Copyright 1992-2014 Free Software Foundation, Inc.
-
-timestamp='2014-03-23'
-
-# This file 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/>.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that
-# program.  This Exception is an additional permission under section 7
-# of the GNU General Public License, version 3 ("GPLv3").
-#
-# Originally written by Per Bothner.
-#
-# You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
-#
-# Please send patches with a ChangeLog entry to config-patches@gnu.org.
-
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION]
-
-Output the configuration name of the system \`$me' is run on.
-
-Operation modes:
-  -h, --help         print this help, then exit
-  -t, --time-stamp   print date of last modification, then exit
-  -v, --version      print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.guess ($timestamp)
-
-Originally written by Per Bothner.
-Copyright 1992-2014 Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
-  case $1 in
-    --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit ;;
-    --version | -v )
-       echo "$version" ; exit ;;
-    --help | --h* | -h )
-       echo "$usage"; exit ;;
-    -- )     # Stop option processing
-       shift; break ;;
-    - )	# Use stdin as input.
-       break ;;
-    -* )
-       echo "$me: invalid option $1$help" >&2
-       exit 1 ;;
-    * )
-       break ;;
-  esac
-done
-
-if test $# != 0; then
-  echo "$me: too many arguments$help" >&2
-  exit 1
-fi
-
-trap 'exit 1' 1 2 15
-
-# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
-# compiler to aid in system detection is discouraged as it requires
-# temporary files to be created and, as you can see below, it is a
-# headache to deal with in a portable fashion.
-
-# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
-# use `HOST_CC' if defined, but it is deprecated.
-
-# Portable tmp directory creation inspired by the Autoconf team.
-
-set_cc_for_build='
-trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
-trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
-: ${TMPDIR=/tmp} ;
- { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
- { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
- { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
- { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
-dummy=$tmp/dummy ;
-tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
-case $CC_FOR_BUILD,$HOST_CC,$CC in
- ,,)    echo "int x;" > $dummy.c ;
-	for c in cc gcc c89 c99 ; do
-	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
-	     CC_FOR_BUILD="$c"; break ;
-	  fi ;
-	done ;
-	if test x"$CC_FOR_BUILD" = x ; then
-	  CC_FOR_BUILD=no_compiler_found ;
-	fi
-	;;
- ,,*)   CC_FOR_BUILD=$CC ;;
- ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
-esac ; set_cc_for_build= ;'
-
-# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
-# (ghazi@noc.rutgers.edu 1994-08-24)
-if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
-	PATH=$PATH:/.attbin ; export PATH
-fi
-
-UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
-UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
-UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
-UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
-
-case "${UNAME_SYSTEM}" in
-Linux|GNU|GNU/*)
-	# If the system lacks a compiler, then just pick glibc.
-	# We could probably try harder.
-	LIBC=gnu
-
-	eval $set_cc_for_build
-	cat <<-EOF > $dummy.c
-	#include <features.h>
-	#if defined(__UCLIBC__)
-	LIBC=uclibc
-	#elif defined(__dietlibc__)
-	LIBC=dietlibc
-	#else
-	LIBC=gnu
-	#endif
-	EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
-	;;
-esac
-
-# Note: order is significant - the case branches are not exclusive.
-
-case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
-    *:NetBSD:*:*)
-	# NetBSD (nbsd) targets should (where applicable) match one or
-	# more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
-	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
-	# switched to ELF, *-*-netbsd* would select the old
-	# object file format.  This provides both forward
-	# compatibility and a consistent mechanism for selecting the
-	# object file format.
-	#
-	# Note: NetBSD doesn't particularly care about the vendor
-	# portion of the name.  We always set it to "unknown".
-	sysctl="sysctl -n hw.machine_arch"
-	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
-	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
-	case "${UNAME_MACHINE_ARCH}" in
-	    armeb) machine=armeb-unknown ;;
-	    arm*) machine=arm-unknown ;;
-	    sh3el) machine=shl-unknown ;;
-	    sh3eb) machine=sh-unknown ;;
-	    sh5el) machine=sh5le-unknown ;;
-	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
-	esac
-	# The Operating System including object format, if it has switched
-	# to ELF recently, or will in the future.
-	case "${UNAME_MACHINE_ARCH}" in
-	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
-		eval $set_cc_for_build
-		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
-			| grep -q __ELF__
-		then
-		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
-		    # Return netbsd for either.  FIX?
-		    os=netbsd
-		else
-		    os=netbsdelf
-		fi
-		;;
-	    *)
-		os=netbsd
-		;;
-	esac
-	# The OS release
-	# Debian GNU/NetBSD machines have a different userland, and
-	# thus, need a distinct triplet. However, they do not need
-	# kernel version information, so it can be replaced with a
-	# suitable tag, in the style of linux-gnu.
-	case "${UNAME_VERSION}" in
-	    Debian*)
-		release='-gnu'
-		;;
-	    *)
-		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
-		;;
-	esac
-	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
-	# contains redundant information, the shorter form:
-	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
-	echo "${machine}-${os}${release}"
-	exit ;;
-    *:Bitrig:*:*)
-	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
-	echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}
-	exit ;;
-    *:OpenBSD:*:*)
-	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
-	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
-	exit ;;
-    *:ekkoBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
-	exit ;;
-    *:SolidBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
-	exit ;;
-    macppc:MirBSD:*:*)
-	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
-	exit ;;
-    *:MirBSD:*:*)
-	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
-	exit ;;
-    alpha:OSF1:*:*)
-	case $UNAME_RELEASE in
-	*4.0)
-		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
-		;;
-	*5.*)
-		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
-		;;
-	esac
-	# According to Compaq, /usr/sbin/psrinfo has been available on
-	# OSF/1 and Tru64 systems produced since 1995.  I hope that
-	# covers most systems running today.  This code pipes the CPU
-	# types through head -n 1, so we only detect the type of CPU 0.
-	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
-	case "$ALPHA_CPU_TYPE" in
-	    "EV4 (21064)")
-		UNAME_MACHINE="alpha" ;;
-	    "EV4.5 (21064)")
-		UNAME_MACHINE="alpha" ;;
-	    "LCA4 (21066/21068)")
-		UNAME_MACHINE="alpha" ;;
-	    "EV5 (21164)")
-		UNAME_MACHINE="alphaev5" ;;
-	    "EV5.6 (21164A)")
-		UNAME_MACHINE="alphaev56" ;;
-	    "EV5.6 (21164PC)")
-		UNAME_MACHINE="alphapca56" ;;
-	    "EV5.7 (21164PC)")
-		UNAME_MACHINE="alphapca57" ;;
-	    "EV6 (21264)")
-		UNAME_MACHINE="alphaev6" ;;
-	    "EV6.7 (21264A)")
-		UNAME_MACHINE="alphaev67" ;;
-	    "EV6.8CB (21264C)")
-		UNAME_MACHINE="alphaev68" ;;
-	    "EV6.8AL (21264B)")
-		UNAME_MACHINE="alphaev68" ;;
-	    "EV6.8CX (21264D)")
-		UNAME_MACHINE="alphaev68" ;;
-	    "EV6.9A (21264/EV69A)")
-		UNAME_MACHINE="alphaev69" ;;
-	    "EV7 (21364)")
-		UNAME_MACHINE="alphaev7" ;;
-	    "EV7.9 (21364A)")
-		UNAME_MACHINE="alphaev79" ;;
-	esac
-	# A Pn.n version is a patched version.
-	# A Vn.n version is a released version.
-	# A Tn.n version is a released field test version.
-	# A Xn.n version is an unreleased experimental baselevel.
-	# 1.2 uses "1.2" for uname -r.
-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
-	exitcode=$?
-	trap '' 0
-	exit $exitcode ;;
-    Alpha\ *:Windows_NT*:*)
-	# How do we know it's Interix rather than the generic POSIX subsystem?
-	# Should we change UNAME_MACHINE based on the output of uname instead
-	# of the specific Alpha model?
-	echo alpha-pc-interix
-	exit ;;
-    21064:Windows_NT:50:3)
-	echo alpha-dec-winnt3.5
-	exit ;;
-    Amiga*:UNIX_System_V:4.0:*)
-	echo m68k-unknown-sysv4
-	exit ;;
-    *:[Aa]miga[Oo][Ss]:*:*)
-	echo ${UNAME_MACHINE}-unknown-amigaos
-	exit ;;
-    *:[Mm]orph[Oo][Ss]:*:*)
-	echo ${UNAME_MACHINE}-unknown-morphos
-	exit ;;
-    *:OS/390:*:*)
-	echo i370-ibm-openedition
-	exit ;;
-    *:z/VM:*:*)
-	echo s390-ibm-zvmoe
-	exit ;;
-    *:OS400:*:*)
-	echo powerpc-ibm-os400
-	exit ;;
-    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
-	echo arm-acorn-riscix${UNAME_RELEASE}
-	exit ;;
-    arm*:riscos:*:*|arm*:RISCOS:*:*)
-	echo arm-unknown-riscos
-	exit ;;
-    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
-	echo hppa1.1-hitachi-hiuxmpp
-	exit ;;
-    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
-	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
-	if test "`(/bin/universe) 2>/dev/null`" = att ; then
-		echo pyramid-pyramid-sysv3
-	else
-		echo pyramid-pyramid-bsd
-	fi
-	exit ;;
-    NILE*:*:*:dcosx)
-	echo pyramid-pyramid-svr4
-	exit ;;
-    DRS?6000:unix:4.0:6*)
-	echo sparc-icl-nx6
-	exit ;;
-    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
-	case `/usr/bin/uname -p` in
-	    sparc) echo sparc-icl-nx7; exit ;;
-	esac ;;
-    s390x:SunOS:*:*)
-	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    sun4H:SunOS:5.*:*)
-	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
-	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
-	echo i386-pc-auroraux${UNAME_RELEASE}
-	exit ;;
-    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
-	eval $set_cc_for_build
-	SUN_ARCH="i386"
-	# If there is a compiler, see if it is configured for 64-bit objects.
-	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
-	# This test works for both compilers.
-	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
-		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		grep IS_64BIT_ARCH >/dev/null
-	    then
-		SUN_ARCH="x86_64"
-	    fi
-	fi
-	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    sun4*:SunOS:6*:*)
-	# According to config.sub, this is the proper way to canonicalize
-	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
-	# it's likely to be more like Solaris than SunOS4.
-	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    sun4*:SunOS:*:*)
-	case "`/usr/bin/arch -k`" in
-	    Series*|S4*)
-		UNAME_RELEASE=`uname -v`
-		;;
-	esac
-	# Japanese Language versions have a version number like `4.1.3-JL'.
-	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
-	exit ;;
-    sun3*:SunOS:*:*)
-	echo m68k-sun-sunos${UNAME_RELEASE}
-	exit ;;
-    sun*:*:4.2BSD:*)
-	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
-	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
-	case "`/bin/arch`" in
-	    sun3)
-		echo m68k-sun-sunos${UNAME_RELEASE}
-		;;
-	    sun4)
-		echo sparc-sun-sunos${UNAME_RELEASE}
-		;;
-	esac
-	exit ;;
-    aushp:SunOS:*:*)
-	echo sparc-auspex-sunos${UNAME_RELEASE}
-	exit ;;
-    # The situation for MiNT is a little confusing.  The machine name
-    # can be virtually everything (everything which is not
-    # "atarist" or "atariste" at least should have a processor
-    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
-    # to the lowercase version "mint" (or "freemint").  Finally
-    # the system name "TOS" denotes a system which is actually not
-    # MiNT.  But MiNT is downward compatible to TOS, so this should
-    # be no problem.
-    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
-	echo m68k-atari-mint${UNAME_RELEASE}
-	exit ;;
-    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
-	echo m68k-atari-mint${UNAME_RELEASE}
-	exit ;;
-    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
-	echo m68k-atari-mint${UNAME_RELEASE}
-	exit ;;
-    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
-	echo m68k-milan-mint${UNAME_RELEASE}
-	exit ;;
-    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
-	echo m68k-hades-mint${UNAME_RELEASE}
-	exit ;;
-    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
-	echo m68k-unknown-mint${UNAME_RELEASE}
-	exit ;;
-    m68k:machten:*:*)
-	echo m68k-apple-machten${UNAME_RELEASE}
-	exit ;;
-    powerpc:machten:*:*)
-	echo powerpc-apple-machten${UNAME_RELEASE}
-	exit ;;
-    RISC*:Mach:*:*)
-	echo mips-dec-mach_bsd4.3
-	exit ;;
-    RISC*:ULTRIX:*:*)
-	echo mips-dec-ultrix${UNAME_RELEASE}
-	exit ;;
-    VAX*:ULTRIX*:*:*)
-	echo vax-dec-ultrix${UNAME_RELEASE}
-	exit ;;
-    2020:CLIX:*:* | 2430:CLIX:*:*)
-	echo clipper-intergraph-clix${UNAME_RELEASE}
-	exit ;;
-    mips:*:*:UMIPS | mips:*:*:RISCos)
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-#ifdef __cplusplus
-#include <stdio.h>  /* for printf() prototype */
-	int main (int argc, char *argv[]) {
-#else
-	int main (argc, argv) int argc; char *argv[]; {
-#endif
-	#if defined (host_mips) && defined (MIPSEB)
-	#if defined (SYSTYPE_SYSV)
-	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
-	#endif
-	#if defined (SYSTYPE_SVR4)
-	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
-	#endif
-	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
-	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
-	#endif
-	#endif
-	  exit (-1);
-	}
-EOF
-	$CC_FOR_BUILD -o $dummy $dummy.c &&
-	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
-	  SYSTEM_NAME=`$dummy $dummyarg` &&
-	    { echo "$SYSTEM_NAME"; exit; }
-	echo mips-mips-riscos${UNAME_RELEASE}
-	exit ;;
-    Motorola:PowerMAX_OS:*:*)
-	echo powerpc-motorola-powermax
-	exit ;;
-    Motorola:*:4.3:PL8-*)
-	echo powerpc-harris-powermax
-	exit ;;
-    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
-	echo powerpc-harris-powermax
-	exit ;;
-    Night_Hawk:Power_UNIX:*:*)
-	echo powerpc-harris-powerunix
-	exit ;;
-    m88k:CX/UX:7*:*)
-	echo m88k-harris-cxux7
-	exit ;;
-    m88k:*:4*:R4*)
-	echo m88k-motorola-sysv4
-	exit ;;
-    m88k:*:3*:R3*)
-	echo m88k-motorola-sysv3
-	exit ;;
-    AViiON:dgux:*:*)
-	# DG/UX returns AViiON for all architectures
-	UNAME_PROCESSOR=`/usr/bin/uname -p`
-	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
-	then
-	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
-	       [ ${TARGET_BINARY_INTERFACE}x = x ]
-	    then
-		echo m88k-dg-dgux${UNAME_RELEASE}
-	    else
-		echo m88k-dg-dguxbcs${UNAME_RELEASE}
-	    fi
-	else
-	    echo i586-dg-dgux${UNAME_RELEASE}
-	fi
-	exit ;;
-    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
-	echo m88k-dolphin-sysv3
-	exit ;;
-    M88*:*:R3*:*)
-	# Delta 88k system running SVR3
-	echo m88k-motorola-sysv3
-	exit ;;
-    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
-	echo m88k-tektronix-sysv3
-	exit ;;
-    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
-	echo m68k-tektronix-bsd
-	exit ;;
-    *:IRIX*:*:*)
-	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
-	exit ;;
-    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
-	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
-	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
-    i*86:AIX:*:*)
-	echo i386-ibm-aix
-	exit ;;
-    ia64:AIX:*:*)
-	if [ -x /usr/bin/oslevel ] ; then
-		IBM_REV=`/usr/bin/oslevel`
-	else
-		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
-	fi
-	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
-	exit ;;
-    *:AIX:2:3)
-	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
-		eval $set_cc_for_build
-		sed 's/^		//' << EOF >$dummy.c
-		#include <sys/systemcfg.h>
-
-		main()
-			{
-			if (!__power_pc())
-				exit(1);
-			puts("powerpc-ibm-aix3.2.5");
-			exit(0);
-			}
-EOF
-		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
-		then
-			echo "$SYSTEM_NAME"
-		else
-			echo rs6000-ibm-aix3.2.5
-		fi
-	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
-		echo rs6000-ibm-aix3.2.4
-	else
-		echo rs6000-ibm-aix3.2
-	fi
-	exit ;;
-    *:AIX:*:[4567])
-	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
-	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
-		IBM_ARCH=rs6000
-	else
-		IBM_ARCH=powerpc
-	fi
-	if [ -x /usr/bin/oslevel ] ; then
-		IBM_REV=`/usr/bin/oslevel`
-	else
-		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
-	fi
-	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
-	exit ;;
-    *:AIX:*:*)
-	echo rs6000-ibm-aix
-	exit ;;
-    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
-	echo romp-ibm-bsd4.4
-	exit ;;
-    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
-	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
-	exit ;;                             # report: romp-ibm BSD 4.3
-    *:BOSX:*:*)
-	echo rs6000-bull-bosx
-	exit ;;
-    DPX/2?00:B.O.S.:*:*)
-	echo m68k-bull-sysv3
-	exit ;;
-    9000/[34]??:4.3bsd:1.*:*)
-	echo m68k-hp-bsd
-	exit ;;
-    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
-	echo m68k-hp-bsd4.4
-	exit ;;
-    9000/[34678]??:HP-UX:*:*)
-	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
-	case "${UNAME_MACHINE}" in
-	    9000/31? )            HP_ARCH=m68000 ;;
-	    9000/[34]?? )         HP_ARCH=m68k ;;
-	    9000/[678][0-9][0-9])
-		if [ -x /usr/bin/getconf ]; then
-		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
-		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
-		    case "${sc_cpu_version}" in
-		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
-		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
-		      532)                      # CPU_PA_RISC2_0
-			case "${sc_kernel_bits}" in
-			  32) HP_ARCH="hppa2.0n" ;;
-			  64) HP_ARCH="hppa2.0w" ;;
-			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
-			esac ;;
-		    esac
-		fi
-		if [ "${HP_ARCH}" = "" ]; then
-		    eval $set_cc_for_build
-		    sed 's/^		//' << EOF >$dummy.c
-
-		#define _HPUX_SOURCE
-		#include <stdlib.h>
-		#include <unistd.h>
-
-		int main ()
-		{
-		#if defined(_SC_KERNEL_BITS)
-		    long bits = sysconf(_SC_KERNEL_BITS);
-		#endif
-		    long cpu  = sysconf (_SC_CPU_VERSION);
-
-		    switch (cpu)
-			{
-			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
-			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
-			case CPU_PA_RISC2_0:
-		#if defined(_SC_KERNEL_BITS)
-			    switch (bits)
-				{
-				case 64: puts ("hppa2.0w"); break;
-				case 32: puts ("hppa2.0n"); break;
-				default: puts ("hppa2.0"); break;
-				} break;
-		#else  /* !defined(_SC_KERNEL_BITS) */
-			    puts ("hppa2.0"); break;
-		#endif
-			default: puts ("hppa1.0"); break;
-			}
-		    exit (0);
-		}
-EOF
-		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
-		    test -z "$HP_ARCH" && HP_ARCH=hppa
-		fi ;;
-	esac
-	if [ ${HP_ARCH} = "hppa2.0w" ]
-	then
-	    eval $set_cc_for_build
-
-	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
-	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
-	    # generating 64-bit code.  GNU and HP use different nomenclature:
-	    #
-	    # $ CC_FOR_BUILD=cc ./config.guess
-	    # => hppa2.0w-hp-hpux11.23
-	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
-	    # => hppa64-hp-hpux11.23
-
-	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
-		grep -q __LP64__
-	    then
-		HP_ARCH="hppa2.0w"
-	    else
-		HP_ARCH="hppa64"
-	    fi
-	fi
-	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
-	exit ;;
-    ia64:HP-UX:*:*)
-	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
-	echo ia64-hp-hpux${HPUX_REV}
-	exit ;;
-    3050*:HI-UX:*:*)
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#include <unistd.h>
-	int
-	main ()
-	{
-	  long cpu = sysconf (_SC_CPU_VERSION);
-	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
-	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
-	     results, however.  */
-	  if (CPU_IS_PA_RISC (cpu))
-	    {
-	      switch (cpu)
-		{
-		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
-		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
-		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
-		  default: puts ("hppa-hitachi-hiuxwe2"); break;
-		}
-	    }
-	  else if (CPU_IS_HP_MC68K (cpu))
-	    puts ("m68k-hitachi-hiuxwe2");
-	  else puts ("unknown-hitachi-hiuxwe2");
-	  exit (0);
-	}
-EOF
-	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
-		{ echo "$SYSTEM_NAME"; exit; }
-	echo unknown-hitachi-hiuxwe2
-	exit ;;
-    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
-	echo hppa1.1-hp-bsd
-	exit ;;
-    9000/8??:4.3bsd:*:*)
-	echo hppa1.0-hp-bsd
-	exit ;;
-    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
-	echo hppa1.0-hp-mpeix
-	exit ;;
-    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
-	echo hppa1.1-hp-osf
-	exit ;;
-    hp8??:OSF1:*:*)
-	echo hppa1.0-hp-osf
-	exit ;;
-    i*86:OSF1:*:*)
-	if [ -x /usr/sbin/sysversion ] ; then
-	    echo ${UNAME_MACHINE}-unknown-osf1mk
-	else
-	    echo ${UNAME_MACHINE}-unknown-osf1
-	fi
-	exit ;;
-    parisc*:Lites*:*:*)
-	echo hppa1.1-hp-lites
-	exit ;;
-    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
-	echo c1-convex-bsd
-	exit ;;
-    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
-	if getsysinfo -f scalar_acc
-	then echo c32-convex-bsd
-	else echo c2-convex-bsd
-	fi
-	exit ;;
-    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
-	echo c34-convex-bsd
-	exit ;;
-    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
-	echo c38-convex-bsd
-	exit ;;
-    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
-	echo c4-convex-bsd
-	exit ;;
-    CRAY*Y-MP:*:*:*)
-	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
-    CRAY*[A-Z]90:*:*:*)
-	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
-	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
-	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
-	      -e 's/\.[^.]*$/.X/'
-	exit ;;
-    CRAY*TS:*:*:*)
-	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
-    CRAY*T3E:*:*:*)
-	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
-    CRAY*SV1:*:*:*)
-	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
-    *:UNICOS/mp:*:*)
-	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
-	exit ;;
-    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
-	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
-	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
-	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
-	exit ;;
-    5000:UNIX_System_V:4.*:*)
-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
-	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
-	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
-	exit ;;
-    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
-	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
-	exit ;;
-    sparc*:BSD/OS:*:*)
-	echo sparc-unknown-bsdi${UNAME_RELEASE}
-	exit ;;
-    *:BSD/OS:*:*)
-	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
-	exit ;;
-    *:FreeBSD:*:*)
-	UNAME_PROCESSOR=`/usr/bin/uname -p`
-	case ${UNAME_PROCESSOR} in
-	    amd64)
-		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
-	    *)
-		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
-	esac
-	exit ;;
-    i*:CYGWIN*:*)
-	echo ${UNAME_MACHINE}-pc-cygwin
-	exit ;;
-    *:MINGW64*:*)
-	echo ${UNAME_MACHINE}-pc-mingw64
-	exit ;;
-    *:MINGW*:*)
-	echo ${UNAME_MACHINE}-pc-mingw32
-	exit ;;
-    *:MSYS*:*)
-	echo ${UNAME_MACHINE}-pc-msys
-	exit ;;
-    i*:windows32*:*)
-	# uname -m includes "-pc" on this system.
-	echo ${UNAME_MACHINE}-mingw32
-	exit ;;
-    i*:PW*:*)
-	echo ${UNAME_MACHINE}-pc-pw32
-	exit ;;
-    *:Interix*:*)
-	case ${UNAME_MACHINE} in
-	    x86)
-		echo i586-pc-interix${UNAME_RELEASE}
-		exit ;;
-	    authenticamd | genuineintel | EM64T)
-		echo x86_64-unknown-interix${UNAME_RELEASE}
-		exit ;;
-	    IA64)
-		echo ia64-unknown-interix${UNAME_RELEASE}
-		exit ;;
-	esac ;;
-    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
-	echo i${UNAME_MACHINE}-pc-mks
-	exit ;;
-    8664:Windows_NT:*)
-	echo x86_64-pc-mks
-	exit ;;
-    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
-	# How do we know it's Interix rather than the generic POSIX subsystem?
-	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
-	# UNAME_MACHINE based on the output of uname instead of i386?
-	echo i586-pc-interix
-	exit ;;
-    i*:UWIN*:*)
-	echo ${UNAME_MACHINE}-pc-uwin
-	exit ;;
-    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
-	echo x86_64-unknown-cygwin
-	exit ;;
-    p*:CYGWIN*:*)
-	echo powerpcle-unknown-cygwin
-	exit ;;
-    prep*:SunOS:5.*:*)
-	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
-	exit ;;
-    *:GNU:*:*)
-	# the GNU system
-	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
-	exit ;;
-    *:GNU/*:*:*)
-	# other systems with GNU libc and userland
-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
-	exit ;;
-    i*86:Minix:*:*)
-	echo ${UNAME_MACHINE}-pc-minix
-	exit ;;
-    aarch64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    aarch64_be:Linux:*:*)
-	UNAME_MACHINE=aarch64_be
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    alpha:Linux:*:*)
-	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
-	  EV5)   UNAME_MACHINE=alphaev5 ;;
-	  EV56)  UNAME_MACHINE=alphaev56 ;;
-	  PCA56) UNAME_MACHINE=alphapca56 ;;
-	  PCA57) UNAME_MACHINE=alphapca56 ;;
-	  EV6)   UNAME_MACHINE=alphaev6 ;;
-	  EV67)  UNAME_MACHINE=alphaev67 ;;
-	  EV68*) UNAME_MACHINE=alphaev68 ;;
-	esac
-	objdump --private-headers /bin/sh | grep -q ld.so.1
-	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    arc:Linux:*:* | arceb:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    arm*:Linux:*:*)
-	eval $set_cc_for_build
-	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
-	    | grep -q __ARM_EABI__
-	then
-	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	else
-	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
-		| grep -q __ARM_PCS_VFP
-	    then
-		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
-	    else
-		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
-	    fi
-	fi
-	exit ;;
-    avr32*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    cris:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
-	exit ;;
-    crisv32:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
-	exit ;;
-    frv:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    hexagon:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    i*86:Linux:*:*)
-	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
-	exit ;;
-    ia64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    m32r*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    m68*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    mips:Linux:*:* | mips64:Linux:*:*)
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#undef CPU
-	#undef ${UNAME_MACHINE}
-	#undef ${UNAME_MACHINE}el
-	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
-	CPU=${UNAME_MACHINE}el
-	#else
-	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
-	CPU=${UNAME_MACHINE}
-	#else
-	CPU=
-	#endif
-	#endif
-EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
-	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
-	;;
-    openrisc*:Linux:*:*)
-	echo or1k-unknown-linux-${LIBC}
-	exit ;;
-    or32:Linux:*:* | or1k*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    padre:Linux:*:*)
-	echo sparc-unknown-linux-${LIBC}
-	exit ;;
-    parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-${LIBC}
-	exit ;;
-    parisc:Linux:*:* | hppa:Linux:*:*)
-	# Look for CPU level
-	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
-	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
-	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
-	  *)    echo hppa-unknown-linux-${LIBC} ;;
-	esac
-	exit ;;
-    ppc64:Linux:*:*)
-	echo powerpc64-unknown-linux-${LIBC}
-	exit ;;
-    ppc:Linux:*:*)
-	echo powerpc-unknown-linux-${LIBC}
-	exit ;;
-    ppc64le:Linux:*:*)
-	echo powerpc64le-unknown-linux-${LIBC}
-	exit ;;
-    ppcle:Linux:*:*)
-	echo powerpcle-unknown-linux-${LIBC}
-	exit ;;
-    s390:Linux:*:* | s390x:Linux:*:*)
-	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
-	exit ;;
-    sh64*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    sh*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    sparc:Linux:*:* | sparc64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    tile*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    vax:Linux:*:*)
-	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
-	exit ;;
-    x86_64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    xtensa*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
-	exit ;;
-    i*86:DYNIX/ptx:4*:*)
-	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
-	# earlier versions are messed up and put the nodename in both
-	# sysname and nodename.
-	echo i386-sequent-sysv4
-	exit ;;
-    i*86:UNIX_SV:4.2MP:2.*)
-	# Unixware is an offshoot of SVR4, but it has its own version
-	# number series starting with 2...
-	# I am not positive that other SVR4 systems won't match this,
-	# I just have to hope.  -- rms.
-	# Use sysv4.2uw... so that sysv4* matches it.
-	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
-	exit ;;
-    i*86:OS/2:*:*)
-	# If we were able to find `uname', then EMX Unix compatibility
-	# is probably installed.
-	echo ${UNAME_MACHINE}-pc-os2-emx
-	exit ;;
-    i*86:XTS-300:*:STOP)
-	echo ${UNAME_MACHINE}-unknown-stop
-	exit ;;
-    i*86:atheos:*:*)
-	echo ${UNAME_MACHINE}-unknown-atheos
-	exit ;;
-    i*86:syllable:*:*)
-	echo ${UNAME_MACHINE}-pc-syllable
-	exit ;;
-    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
-	echo i386-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
-    i*86:*DOS:*:*)
-	echo ${UNAME_MACHINE}-pc-msdosdjgpp
-	exit ;;
-    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
-	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
-	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
-		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
-	else
-		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
-	fi
-	exit ;;
-    i*86:*:5:[678]*)
-	# UnixWare 7.x, OpenUNIX and OpenServer 6.
-	case `/bin/uname -X | grep "^Machine"` in
-	    *486*)	     UNAME_MACHINE=i486 ;;
-	    *Pentium)	     UNAME_MACHINE=i586 ;;
-	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
-	esac
-	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
-	exit ;;
-    i*86:*:3.2:*)
-	if test -f /usr/options/cb.name; then
-		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
-		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
-	elif /bin/uname -X 2>/dev/null >/dev/null ; then
-		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
-		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
-		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
-			&& UNAME_MACHINE=i586
-		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
-			&& UNAME_MACHINE=i686
-		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
-			&& UNAME_MACHINE=i686
-		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
-	else
-		echo ${UNAME_MACHINE}-pc-sysv32
-	fi
-	exit ;;
-    pc:*:*:*)
-	# Left here for compatibility:
-	# uname -m prints for DJGPP always 'pc', but it prints nothing about
-	# the processor, so we play safe by assuming i586.
-	# Note: whatever this is, it MUST be the same as what config.sub
-	# prints for the "djgpp" host, or else GDB configury will decide that
-	# this is a cross-build.
-	echo i586-pc-msdosdjgpp
-	exit ;;
-    Intel:Mach:3*:*)
-	echo i386-pc-mach3
-	exit ;;
-    paragon:*:*:*)
-	echo i860-intel-osf1
-	exit ;;
-    i860:*:4.*:*) # i860-SVR4
-	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
-	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
-	else # Add other i860-SVR4 vendors below as they are discovered.
-	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
-	fi
-	exit ;;
-    mini*:CTIX:SYS*5:*)
-	# "miniframe"
-	echo m68010-convergent-sysv
-	exit ;;
-    mc68k:UNIX:SYSTEM5:3.51m)
-	echo m68k-convergent-sysv
-	exit ;;
-    M680?0:D-NIX:5.3:*)
-	echo m68k-diab-dnix
-	exit ;;
-    M68*:*:R3V[5678]*:*)
-	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
-    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
-	OS_REL=''
-	test -r /etc/.relid \
-	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
-	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
-	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
-    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	  && { echo i486-ncr-sysv4; exit; } ;;
-    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
-	OS_REL='.3'
-	test -r /etc/.relid \
-	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
-	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
-	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
-	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
-	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
-	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
-    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
-	echo m68k-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
-    mc68030:UNIX_System_V:4.*:*)
-	echo m68k-atari-sysv4
-	exit ;;
-    TSUNAMI:LynxOS:2.*:*)
-	echo sparc-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
-    rs6000:LynxOS:2.*:*)
-	echo rs6000-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
-    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
-	echo powerpc-unknown-lynxos${UNAME_RELEASE}
-	exit ;;
-    SM[BE]S:UNIX_SV:*:*)
-	echo mips-dde-sysv${UNAME_RELEASE}
-	exit ;;
-    RM*:ReliantUNIX-*:*:*)
-	echo mips-sni-sysv4
-	exit ;;
-    RM*:SINIX-*:*:*)
-	echo mips-sni-sysv4
-	exit ;;
-    *:SINIX-*:*:*)
-	if uname -p 2>/dev/null >/dev/null ; then
-		UNAME_MACHINE=`(uname -p) 2>/dev/null`
-		echo ${UNAME_MACHINE}-sni-sysv4
-	else
-		echo ns32k-sni-sysv
-	fi
-	exit ;;
-    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort
-			# says <Richard.M.Bartel@ccMail.Census.GOV>
-	echo i586-unisys-sysv4
-	exit ;;
-    *:UNIX_System_V:4*:FTX*)
-	# From Gerald Hewes <hewes@openmarket.com>.
-	# How about differentiating between stratus architectures? -djm
-	echo hppa1.1-stratus-sysv4
-	exit ;;
-    *:*:*:FTX*)
-	# From seanf@swdc.stratus.com.
-	echo i860-stratus-sysv4
-	exit ;;
-    i*86:VOS:*:*)
-	# From Paul.Green@stratus.com.
-	echo ${UNAME_MACHINE}-stratus-vos
-	exit ;;
-    *:VOS:*:*)
-	# From Paul.Green@stratus.com.
-	echo hppa1.1-stratus-vos
-	exit ;;
-    mc68*:A/UX:*:*)
-	echo m68k-apple-aux${UNAME_RELEASE}
-	exit ;;
-    news*:NEWS-OS:6*:*)
-	echo mips-sony-newsos6
-	exit ;;
-    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
-	if [ -d /usr/nec ]; then
-		echo mips-nec-sysv${UNAME_RELEASE}
-	else
-		echo mips-unknown-sysv${UNAME_RELEASE}
-	fi
-	exit ;;
-    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
-	echo powerpc-be-beos
-	exit ;;
-    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
-	echo powerpc-apple-beos
-	exit ;;
-    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
-	echo i586-pc-beos
-	exit ;;
-    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
-	echo i586-pc-haiku
-	exit ;;
-    x86_64:Haiku:*:*)
-	echo x86_64-unknown-haiku
-	exit ;;
-    SX-4:SUPER-UX:*:*)
-	echo sx4-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-5:SUPER-UX:*:*)
-	echo sx5-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-6:SUPER-UX:*:*)
-	echo sx6-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-7:SUPER-UX:*:*)
-	echo sx7-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-8:SUPER-UX:*:*)
-	echo sx8-nec-superux${UNAME_RELEASE}
-	exit ;;
-    SX-8R:SUPER-UX:*:*)
-	echo sx8r-nec-superux${UNAME_RELEASE}
-	exit ;;
-    Power*:Rhapsody:*:*)
-	echo powerpc-apple-rhapsody${UNAME_RELEASE}
-	exit ;;
-    *:Rhapsody:*:*)
-	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
-	exit ;;
-    *:Darwin:*:*)
-	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
-	eval $set_cc_for_build
-	if test "$UNAME_PROCESSOR" = unknown ; then
-	    UNAME_PROCESSOR=powerpc
-	fi
-	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
-	    if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-		    (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		    grep IS_64BIT_ARCH >/dev/null
-		then
-		    case $UNAME_PROCESSOR in
-			i386) UNAME_PROCESSOR=x86_64 ;;
-			powerpc) UNAME_PROCESSOR=powerpc64 ;;
-		    esac
-		fi
-	    fi
-	elif test "$UNAME_PROCESSOR" = i386 ; then
-	    # Avoid executing cc on OS X 10.9, as it ships with a stub
-	    # that puts up a graphical alert prompting to install
-	    # developer tools.  Any system running Mac OS X 10.7 or
-	    # later (Darwin 11 and later) is required to have a 64-bit
-	    # processor. This is not true of the ARM version of Darwin
-	    # that Apple uses in portable devices.
-	    UNAME_PROCESSOR=x86_64
-	fi
-	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
-	exit ;;
-    *:procnto*:*:* | *:QNX:[0123456789]*:*)
-	UNAME_PROCESSOR=`uname -p`
-	if test "$UNAME_PROCESSOR" = "x86"; then
-		UNAME_PROCESSOR=i386
-		UNAME_MACHINE=pc
-	fi
-	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
-	exit ;;
-    *:QNX:*:4*)
-	echo i386-pc-qnx
-	exit ;;
-    NEO-?:NONSTOP_KERNEL:*:*)
-	echo neo-tandem-nsk${UNAME_RELEASE}
-	exit ;;
-    NSE-*:NONSTOP_KERNEL:*:*)
-	echo nse-tandem-nsk${UNAME_RELEASE}
-	exit ;;
-    NSR-?:NONSTOP_KERNEL:*:*)
-	echo nsr-tandem-nsk${UNAME_RELEASE}
-	exit ;;
-    *:NonStop-UX:*:*)
-	echo mips-compaq-nonstopux
-	exit ;;
-    BS2000:POSIX*:*:*)
-	echo bs2000-siemens-sysv
-	exit ;;
-    DS/*:UNIX_System_V:*:*)
-	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
-	exit ;;
-    *:Plan9:*:*)
-	# "uname -m" is not consistent, so use $cputype instead. 386
-	# is converted to i386 for consistency with other x86
-	# operating systems.
-	if test "$cputype" = "386"; then
-	    UNAME_MACHINE=i386
-	else
-	    UNAME_MACHINE="$cputype"
-	fi
-	echo ${UNAME_MACHINE}-unknown-plan9
-	exit ;;
-    *:TOPS-10:*:*)
-	echo pdp10-unknown-tops10
-	exit ;;
-    *:TENEX:*:*)
-	echo pdp10-unknown-tenex
-	exit ;;
-    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
-	echo pdp10-dec-tops20
-	exit ;;
-    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
-	echo pdp10-xkl-tops20
-	exit ;;
-    *:TOPS-20:*:*)
-	echo pdp10-unknown-tops20
-	exit ;;
-    *:ITS:*:*)
-	echo pdp10-unknown-its
-	exit ;;
-    SEI:*:*:SEIUX)
-	echo mips-sei-seiux${UNAME_RELEASE}
-	exit ;;
-    *:DragonFly:*:*)
-	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
-	exit ;;
-    *:*VMS:*:*)
-	UNAME_MACHINE=`(uname -p) 2>/dev/null`
-	case "${UNAME_MACHINE}" in
-	    A*) echo alpha-dec-vms ; exit ;;
-	    I*) echo ia64-dec-vms ; exit ;;
-	    V*) echo vax-dec-vms ; exit ;;
-	esac ;;
-    *:XENIX:*:SysV)
-	echo i386-pc-xenix
-	exit ;;
-    i*86:skyos:*:*)
-	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
-	exit ;;
-    i*86:rdos:*:*)
-	echo ${UNAME_MACHINE}-pc-rdos
-	exit ;;
-    i*86:AROS:*:*)
-	echo ${UNAME_MACHINE}-pc-aros
-	exit ;;
-    x86_64:VMkernel:*:*)
-	echo ${UNAME_MACHINE}-unknown-esx
-	exit ;;
-esac
-
-cat >&2 <<EOF
-$0: unable to guess system type
-
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
-
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
-and
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
-
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches@gnu.org> in order to provide the needed
-information to handle your system.
-
-config.guess timestamp = $timestamp
-
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
-
-hostinfo               = `(hostinfo) 2>/dev/null`
-/bin/universe          = `(/bin/universe) 2>/dev/null`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
-/bin/arch              = `(/bin/arch) 2>/dev/null`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
-
-UNAME_MACHINE = ${UNAME_MACHINE}
-UNAME_RELEASE = ${UNAME_RELEASE}
-UNAME_SYSTEM  = ${UNAME_SYSTEM}
-UNAME_VERSION = ${UNAME_VERSION}
-EOF
-
-exit 1
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/config.sub b/config.sub
deleted file mode 100755
index bba4efb..0000000
--- a/config.sub
+++ /dev/null
@@ -1,1799 +0,0 @@
-#! /bin/sh
-# Configuration validation subroutine script.
-#   Copyright 1992-2014 Free Software Foundation, Inc.
-
-timestamp='2014-09-11'
-
-# This file 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/>.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that
-# program.  This Exception is an additional permission under section 7
-# of the GNU General Public License, version 3 ("GPLv3").
-
-
-# Please send patches with a ChangeLog entry to config-patches@gnu.org.
-#
-# Configuration subroutine to validate and canonicalize a configuration type.
-# Supply the specified configuration type as an argument.
-# If it is invalid, we print an error message on stderr and exit with code 1.
-# Otherwise, we print the canonical config type on stdout and succeed.
-
-# You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
-
-# This file is supposed to be the same for all GNU packages
-# and recognize all the CPU types, system types and aliases
-# that are meaningful with *any* GNU software.
-# Each package is responsible for reporting which valid configurations
-# it does not support.  The user should be able to distinguish
-# a failure to support a valid configuration from a meaningless
-# configuration.
-
-# The goal of this file is to map all the various variations of a given
-# machine specification into a single specification in the form:
-#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
-# or in some cases, the newer four-part form:
-#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
-# It is wrong to echo any other type of specification.
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
-       $0 [OPTION] ALIAS
-
-Canonicalize a configuration name.
-
-Operation modes:
-  -h, --help         print this help, then exit
-  -t, --time-stamp   print date of last modification, then exit
-  -v, --version      print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.sub ($timestamp)
-
-Copyright 1992-2014 Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
-  case $1 in
-    --time-stamp | --time* | -t )
-       echo "$timestamp" ; exit ;;
-    --version | -v )
-       echo "$version" ; exit ;;
-    --help | --h* | -h )
-       echo "$usage"; exit ;;
-    -- )     # Stop option processing
-       shift; break ;;
-    - )	# Use stdin as input.
-       break ;;
-    -* )
-       echo "$me: invalid option $1$help"
-       exit 1 ;;
-
-    *local*)
-       # First pass through any local machine types.
-       echo $1
-       exit ;;
-
-    * )
-       break ;;
-  esac
-done
-
-case $# in
- 0) echo "$me: missing argument$help" >&2
-    exit 1;;
- 1) ;;
- *) echo "$me: too many arguments$help" >&2
-    exit 1;;
-esac
-
-# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
-# Here we must recognize all the valid KERNEL-OS combinations.
-maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
-case $maybe_os in
-  nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
-  linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
-  knetbsd*-gnu* | netbsd*-gnu* | \
-  kopensolaris*-gnu* | \
-  storm-chaos* | os2-emx* | rtmk-nova*)
-    os=-$maybe_os
-    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
-    ;;
-  android-linux)
-    os=-linux-android
-    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
-    ;;
-  *)
-    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
-    if [ $basic_machine != $1 ]
-    then os=`echo $1 | sed 's/.*-/-/'`
-    else os=; fi
-    ;;
-esac
-
-### Let's recognize common machines as not being operating systems so
-### that things like config.sub decstation-3100 work.  We also
-### recognize some manufacturers as not being operating systems, so we
-### can provide default operating systems below.
-case $os in
-	-sun*os*)
-		# Prevent following clause from handling this invalid input.
-		;;
-	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
-	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
-	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
-	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
-	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
-	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-	-apple | -axis | -knuth | -cray | -microblaze*)
-		os=
-		basic_machine=$1
-		;;
-	-bluegene*)
-		os=-cnk
-		;;
-	-sim | -cisco | -oki | -wec | -winbond)
-		os=
-		basic_machine=$1
-		;;
-	-scout)
-		;;
-	-wrs)
-		os=-vxworks
-		basic_machine=$1
-		;;
-	-chorusos*)
-		os=-chorusos
-		basic_machine=$1
-		;;
-	-chorusrdb)
-		os=-chorusrdb
-		basic_machine=$1
-		;;
-	-hiux*)
-		os=-hiuxwe2
-		;;
-	-sco6)
-		os=-sco5v6
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-sco5)
-		os=-sco3.2v5
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-sco4)
-		os=-sco3.2v4
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-sco3.2.[4-9]*)
-		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-sco3.2v[4-9]*)
-		# Don't forget version if it is 3.2v4 or newer.
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-sco5v6*)
-		# Don't forget version if it is 3.2v4 or newer.
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-sco*)
-		os=-sco3.2v2
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-udk*)
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-isc)
-		os=-isc2.2
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-clix*)
-		basic_machine=clipper-intergraph
-		;;
-	-isc*)
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
-		;;
-	-lynx*178)
-		os=-lynxos178
-		;;
-	-lynx*5)
-		os=-lynxos5
-		;;
-	-lynx*)
-		os=-lynxos
-		;;
-	-ptx*)
-		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
-		;;
-	-windowsnt*)
-		os=`echo $os | sed -e 's/windowsnt/winnt/'`
-		;;
-	-psos*)
-		os=-psos
-		;;
-	-mint | -mint[0-9]*)
-		basic_machine=m68k-atari
-		os=-mint
-		;;
-esac
-
-# Decode aliases for certain CPU-COMPANY combinations.
-case $basic_machine in
-	# Recognize the basic CPU types without company name.
-	# Some are omitted here because they have special meanings below.
-	1750a | 580 \
-	| a29k \
-	| aarch64 | aarch64_be \
-	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
-	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
-	| am33_2.0 \
-	| arc | arceb \
-	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
-	| avr | avr32 \
-	| be32 | be64 \
-	| bfin \
-	| c4x | c8051 | clipper \
-	| d10v | d30v | dlx | dsp16xx \
-	| epiphany \
-	| fido | fr30 | frv \
-	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
-	| hexagon \
-	| i370 | i860 | i960 | ia64 \
-	| ip2k | iq2000 \
-	| k1om \
-	| le32 | le64 \
-	| lm32 \
-	| m32c | m32r | m32rle | m68000 | m68k | m88k \
-	| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
-	| mips | mipsbe | mipseb | mipsel | mipsle \
-	| mips16 \
-	| mips64 | mips64el \
-	| mips64octeon | mips64octeonel \
-	| mips64orion | mips64orionel \
-	| mips64r5900 | mips64r5900el \
-	| mips64vr | mips64vrel \
-	| mips64vr4100 | mips64vr4100el \
-	| mips64vr4300 | mips64vr4300el \
-	| mips64vr5000 | mips64vr5000el \
-	| mips64vr5900 | mips64vr5900el \
-	| mipsisa32 | mipsisa32el \
-	| mipsisa32r2 | mipsisa32r2el \
-	| mipsisa32r6 | mipsisa32r6el \
-	| mipsisa64 | mipsisa64el \
-	| mipsisa64r2 | mipsisa64r2el \
-	| mipsisa64r6 | mipsisa64r6el \
-	| mipsisa64sb1 | mipsisa64sb1el \
-	| mipsisa64sr71k | mipsisa64sr71kel \
-	| mipsr5900 | mipsr5900el \
-	| mipstx39 | mipstx39el \
-	| mn10200 | mn10300 \
-	| moxie \
-	| mt \
-	| msp430 \
-	| nds32 | nds32le | nds32be \
-	| nios | nios2 | nios2eb | nios2el \
-	| ns16k | ns32k \
-	| open8 | or1k | or1knd | or32 \
-	| pdp10 | pdp11 | pj | pjl \
-	| powerpc | powerpc64 | powerpc64le | powerpcle \
-	| pyramid \
-	| riscv32 | riscv64 \
-	| rl78 | rx \
-	| score \
-	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
-	| sh64 | sh64le \
-	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
-	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
-	| spu \
-	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
-	| ubicom32 \
-	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
-	| we32k \
-	| x86 | xc16x | xstormy16 | xtensa \
-	| z8k | z80)
-		basic_machine=$basic_machine-unknown
-		;;
-	c54x)
-		basic_machine=tic54x-unknown
-		;;
-	c55x)
-		basic_machine=tic55x-unknown
-		;;
-	c6x)
-		basic_machine=tic6x-unknown
-		;;
-	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
-		basic_machine=$basic_machine-unknown
-		os=-none
-		;;
-	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
-		;;
-	ms1)
-		basic_machine=mt-unknown
-		;;
-
-	strongarm | thumb | xscale)
-		basic_machine=arm-unknown
-		;;
-	xgate)
-		basic_machine=$basic_machine-unknown
-		os=-none
-		;;
-	xscaleeb)
-		basic_machine=armeb-unknown
-		;;
-
-	xscaleel)
-		basic_machine=armel-unknown
-		;;
-
-	# We use `pc' rather than `unknown'
-	# because (1) that's what they normally are, and
-	# (2) the word "unknown" tends to confuse beginning users.
-	i*86 | x86_64)
-	  basic_machine=$basic_machine-pc
-	  ;;
-	# Object if more than one company name word.
-	*-*-*)
-		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
-		exit 1
-		;;
-	# Recognize the basic CPU types with company name.
-	580-* \
-	| a29k-* \
-	| aarch64-* | aarch64_be-* \
-	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
-	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
-	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
-	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
-	| avr-* | avr32-* \
-	| be32-* | be64-* \
-	| bfin-* | bs2000-* \
-	| c[123]* | c30-* | [cjt]90-* | c4x-* \
-	| c8051-* | clipper-* | craynv-* | cydra-* \
-	| d10v-* | d30v-* | dlx-* \
-	| elxsi-* \
-	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
-	| h8300-* | h8500-* \
-	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
-	| hexagon-* \
-	| i*86-* | i860-* | i960-* | ia64-* \
-	| ip2k-* | iq2000-* \
-	| k1om-* \
-	| le32-* | le64-* \
-	| lm32-* \
-	| m32c-* | m32r-* | m32rle-* \
-	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
-	| microblaze-* | microblazeel-* \
-	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
-	| mips16-* \
-	| mips64-* | mips64el-* \
-	| mips64octeon-* | mips64octeonel-* \
-	| mips64orion-* | mips64orionel-* \
-	| mips64r5900-* | mips64r5900el-* \
-	| mips64vr-* | mips64vrel-* \
-	| mips64vr4100-* | mips64vr4100el-* \
-	| mips64vr4300-* | mips64vr4300el-* \
-	| mips64vr5000-* | mips64vr5000el-* \
-	| mips64vr5900-* | mips64vr5900el-* \
-	| mipsisa32-* | mipsisa32el-* \
-	| mipsisa32r2-* | mipsisa32r2el-* \
-	| mipsisa32r6-* | mipsisa32r6el-* \
-	| mipsisa64-* | mipsisa64el-* \
-	| mipsisa64r2-* | mipsisa64r2el-* \
-	| mipsisa64r6-* | mipsisa64r6el-* \
-	| mipsisa64sb1-* | mipsisa64sb1el-* \
-	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
-	| mipsr5900-* | mipsr5900el-* \
-	| mipstx39-* | mipstx39el-* \
-	| mmix-* \
-	| mt-* \
-	| msp430-* \
-	| nds32-* | nds32le-* | nds32be-* \
-	| nios-* | nios2-* | nios2eb-* | nios2el-* \
-	| none-* | np1-* | ns16k-* | ns32k-* \
-	| open8-* \
-	| or1k*-* \
-	| orion-* \
-	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
-	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
-	| pyramid-* \
-	| rl78-* | romp-* | rs6000-* | rx-* \
-	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
-	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
-	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
-	| sparclite-* \
-	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
-	| tahoe-* \
-	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
-	| tile*-* \
-	| tron-* \
-	| ubicom32-* \
-	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
-	| vax-* \
-	| we32k-* \
-	| x86-* | x86_64-* | xc16x-* | xps100-* \
-	| xstormy16-* | xtensa*-* \
-	| ymp-* \
-	| z8k-* | z80-*)
-		;;
-	# Recognize the basic CPU types without company name, with glob match.
-	xtensa*)
-		basic_machine=$basic_machine-unknown
-		;;
-	# Recognize the various machine names and aliases which stand
-	# for a CPU type and a company and sometimes even an OS.
-	386bsd)
-		basic_machine=i386-unknown
-		os=-bsd
-		;;
-	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
-		basic_machine=m68000-att
-		;;
-	3b*)
-		basic_machine=we32k-att
-		;;
-	a29khif)
-		basic_machine=a29k-amd
-		os=-udi
-		;;
-	abacus)
-		basic_machine=abacus-unknown
-		;;
-	adobe68k)
-		basic_machine=m68010-adobe
-		os=-scout
-		;;
-	alliant | fx80)
-		basic_machine=fx80-alliant
-		;;
-	altos | altos3068)
-		basic_machine=m68k-altos
-		;;
-	am29k)
-		basic_machine=a29k-none
-		os=-bsd
-		;;
-	amd64)
-		basic_machine=x86_64-pc
-		;;
-	amd64-*)
-		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	amdahl)
-		basic_machine=580-amdahl
-		os=-sysv
-		;;
-	amiga | amiga-*)
-		basic_machine=m68k-unknown
-		;;
-	amigaos | amigados)
-		basic_machine=m68k-unknown
-		os=-amigaos
-		;;
-	amigaunix | amix)
-		basic_machine=m68k-unknown
-		os=-sysv4
-		;;
-	apollo68)
-		basic_machine=m68k-apollo
-		os=-sysv
-		;;
-	apollo68bsd)
-		basic_machine=m68k-apollo
-		os=-bsd
-		;;
-	aros)
-		basic_machine=i386-pc
-		os=-aros
-		;;
-	aux)
-		basic_machine=m68k-apple
-		os=-aux
-		;;
-	balance)
-		basic_machine=ns32k-sequent
-		os=-dynix
-		;;
-	blackfin)
-		basic_machine=bfin-unknown
-		os=-linux
-		;;
-	blackfin-*)
-		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
-		os=-linux
-		;;
-	bluegene*)
-		basic_machine=powerpc-ibm
-		os=-cnk
-		;;
-	c54x-*)
-		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	c55x-*)
-		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	c6x-*)
-		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	c90)
-		basic_machine=c90-cray
-		os=-unicos
-		;;
-	cegcc)
-		basic_machine=arm-unknown
-		os=-cegcc
-		;;
-	convex-c1)
-		basic_machine=c1-convex
-		os=-bsd
-		;;
-	convex-c2)
-		basic_machine=c2-convex
-		os=-bsd
-		;;
-	convex-c32)
-		basic_machine=c32-convex
-		os=-bsd
-		;;
-	convex-c34)
-		basic_machine=c34-convex
-		os=-bsd
-		;;
-	convex-c38)
-		basic_machine=c38-convex
-		os=-bsd
-		;;
-	cray | j90)
-		basic_machine=j90-cray
-		os=-unicos
-		;;
-	craynv)
-		basic_machine=craynv-cray
-		os=-unicosmp
-		;;
-	cr16 | cr16-*)
-		basic_machine=cr16-unknown
-		os=-elf
-		;;
-	crds | unos)
-		basic_machine=m68k-crds
-		;;
-	crisv32 | crisv32-* | etraxfs*)
-		basic_machine=crisv32-axis
-		;;
-	cris | cris-* | etrax*)
-		basic_machine=cris-axis
-		;;
-	crx)
-		basic_machine=crx-unknown
-		os=-elf
-		;;
-	da30 | da30-*)
-		basic_machine=m68k-da30
-		;;
-	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
-		basic_machine=mips-dec
-		;;
-	decsystem10* | dec10*)
-		basic_machine=pdp10-dec
-		os=-tops10
-		;;
-	decsystem20* | dec20*)
-		basic_machine=pdp10-dec
-		os=-tops20
-		;;
-	delta | 3300 | motorola-3300 | motorola-delta \
-	      | 3300-motorola | delta-motorola)
-		basic_machine=m68k-motorola
-		;;
-	delta88)
-		basic_machine=m88k-motorola
-		os=-sysv3
-		;;
-	dicos)
-		basic_machine=i686-pc
-		os=-dicos
-		;;
-	djgpp)
-		basic_machine=i586-pc
-		os=-msdosdjgpp
-		;;
-	dpx20 | dpx20-*)
-		basic_machine=rs6000-bull
-		os=-bosx
-		;;
-	dpx2* | dpx2*-bull)
-		basic_machine=m68k-bull
-		os=-sysv3
-		;;
-	ebmon29k)
-		basic_machine=a29k-amd
-		os=-ebmon
-		;;
-	elxsi)
-		basic_machine=elxsi-elxsi
-		os=-bsd
-		;;
-	encore | umax | mmax)
-		basic_machine=ns32k-encore
-		;;
-	es1800 | OSE68k | ose68k | ose | OSE)
-		basic_machine=m68k-ericsson
-		os=-ose
-		;;
-	fx2800)
-		basic_machine=i860-alliant
-		;;
-	genix)
-		basic_machine=ns32k-ns
-		;;
-	gmicro)
-		basic_machine=tron-gmicro
-		os=-sysv
-		;;
-	go32)
-		basic_machine=i386-pc
-		os=-go32
-		;;
-	h3050r* | hiux*)
-		basic_machine=hppa1.1-hitachi
-		os=-hiuxwe2
-		;;
-	h8300hms)
-		basic_machine=h8300-hitachi
-		os=-hms
-		;;
-	h8300xray)
-		basic_machine=h8300-hitachi
-		os=-xray
-		;;
-	h8500hms)
-		basic_machine=h8500-hitachi
-		os=-hms
-		;;
-	harris)
-		basic_machine=m88k-harris
-		os=-sysv3
-		;;
-	hp300-*)
-		basic_machine=m68k-hp
-		;;
-	hp300bsd)
-		basic_machine=m68k-hp
-		os=-bsd
-		;;
-	hp300hpux)
-		basic_machine=m68k-hp
-		os=-hpux
-		;;
-	hp3k9[0-9][0-9] | hp9[0-9][0-9])
-		basic_machine=hppa1.0-hp
-		;;
-	hp9k2[0-9][0-9] | hp9k31[0-9])
-		basic_machine=m68000-hp
-		;;
-	hp9k3[2-9][0-9])
-		basic_machine=m68k-hp
-		;;
-	hp9k6[0-9][0-9] | hp6[0-9][0-9])
-		basic_machine=hppa1.0-hp
-		;;
-	hp9k7[0-79][0-9] | hp7[0-79][0-9])
-		basic_machine=hppa1.1-hp
-		;;
-	hp9k78[0-9] | hp78[0-9])
-		# FIXME: really hppa2.0-hp
-		basic_machine=hppa1.1-hp
-		;;
-	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
-		# FIXME: really hppa2.0-hp
-		basic_machine=hppa1.1-hp
-		;;
-	hp9k8[0-9][13679] | hp8[0-9][13679])
-		basic_machine=hppa1.1-hp
-		;;
-	hp9k8[0-9][0-9] | hp8[0-9][0-9])
-		basic_machine=hppa1.0-hp
-		;;
-	hppa-next)
-		os=-nextstep3
-		;;
-	hppaosf)
-		basic_machine=hppa1.1-hp
-		os=-osf
-		;;
-	hppro)
-		basic_machine=hppa1.1-hp
-		os=-proelf
-		;;
-	i370-ibm* | ibm*)
-		basic_machine=i370-ibm
-		;;
-	i*86v32)
-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
-		os=-sysv32
-		;;
-	i*86v4*)
-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
-		os=-sysv4
-		;;
-	i*86v)
-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
-		os=-sysv
-		;;
-	i*86sol2)
-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
-		os=-solaris2
-		;;
-	i386mach)
-		basic_machine=i386-mach
-		os=-mach
-		;;
-	i386-vsta | vsta)
-		basic_machine=i386-unknown
-		os=-vsta
-		;;
-	iris | iris4d)
-		basic_machine=mips-sgi
-		case $os in
-		    -irix*)
-			;;
-		    *)
-			os=-irix4
-			;;
-		esac
-		;;
-	isi68 | isi)
-		basic_machine=m68k-isi
-		os=-sysv
-		;;
-	m68knommu)
-		basic_machine=m68k-unknown
-		os=-linux
-		;;
-	m68knommu-*)
-		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
-		os=-linux
-		;;
-	m88k-omron*)
-		basic_machine=m88k-omron
-		;;
-	magnum | m3230)
-		basic_machine=mips-mips
-		os=-sysv
-		;;
-	merlin)
-		basic_machine=ns32k-utek
-		os=-sysv
-		;;
-	microblaze*)
-		basic_machine=microblaze-xilinx
-		;;
-	mingw64)
-		basic_machine=x86_64-pc
-		os=-mingw64
-		;;
-	mingw32)
-		basic_machine=i686-pc
-		os=-mingw32
-		;;
-	mingw32ce)
-		basic_machine=arm-unknown
-		os=-mingw32ce
-		;;
-	miniframe)
-		basic_machine=m68000-convergent
-		;;
-	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
-		basic_machine=m68k-atari
-		os=-mint
-		;;
-	mips3*-*)
-		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
-		;;
-	mips3*)
-		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
-		;;
-	monitor)
-		basic_machine=m68k-rom68k
-		os=-coff
-		;;
-	morphos)
-		basic_machine=powerpc-unknown
-		os=-morphos
-		;;
-	moxiebox)
-		basic_machine=moxie-unknown
-		os=-moxiebox
-		;;
-	msdos)
-		basic_machine=i386-pc
-		os=-msdos
-		;;
-	ms1-*)
-		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
-		;;
-	msys)
-		basic_machine=i686-pc
-		os=-msys
-		;;
-	mvs)
-		basic_machine=i370-ibm
-		os=-mvs
-		;;
-	nacl)
-		basic_machine=le32-unknown
-		os=-nacl
-		;;
-	ncr3000)
-		basic_machine=i486-ncr
-		os=-sysv4
-		;;
-	netbsd386)
-		basic_machine=i386-unknown
-		os=-netbsd
-		;;
-	netwinder)
-		basic_machine=armv4l-rebel
-		os=-linux
-		;;
-	news | news700 | news800 | news900)
-		basic_machine=m68k-sony
-		os=-newsos
-		;;
-	news1000)
-		basic_machine=m68030-sony
-		os=-newsos
-		;;
-	news-3600 | risc-news)
-		basic_machine=mips-sony
-		os=-newsos
-		;;
-	necv70)
-		basic_machine=v70-nec
-		os=-sysv
-		;;
-	next | m*-next )
-		basic_machine=m68k-next
-		case $os in
-		    -nextstep* )
-			;;
-		    -ns2*)
-		      os=-nextstep2
-			;;
-		    *)
-		      os=-nextstep3
-			;;
-		esac
-		;;
-	nh3000)
-		basic_machine=m68k-harris
-		os=-cxux
-		;;
-	nh[45]000)
-		basic_machine=m88k-harris
-		os=-cxux
-		;;
-	nindy960)
-		basic_machine=i960-intel
-		os=-nindy
-		;;
-	mon960)
-		basic_machine=i960-intel
-		os=-mon960
-		;;
-	nonstopux)
-		basic_machine=mips-compaq
-		os=-nonstopux
-		;;
-	np1)
-		basic_machine=np1-gould
-		;;
-	neo-tandem)
-		basic_machine=neo-tandem
-		;;
-	nse-tandem)
-		basic_machine=nse-tandem
-		;;
-	nsr-tandem)
-		basic_machine=nsr-tandem
-		;;
-	op50n-* | op60c-*)
-		basic_machine=hppa1.1-oki
-		os=-proelf
-		;;
-	openrisc | openrisc-*)
-		basic_machine=or32-unknown
-		;;
-	os400)
-		basic_machine=powerpc-ibm
-		os=-os400
-		;;
-	OSE68000 | ose68000)
-		basic_machine=m68000-ericsson
-		os=-ose
-		;;
-	os68k)
-		basic_machine=m68k-none
-		os=-os68k
-		;;
-	pa-hitachi)
-		basic_machine=hppa1.1-hitachi
-		os=-hiuxwe2
-		;;
-	paragon)
-		basic_machine=i860-intel
-		os=-osf
-		;;
-	parisc)
-		basic_machine=hppa-unknown
-		os=-linux
-		;;
-	parisc-*)
-		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
-		os=-linux
-		;;
-	pbd)
-		basic_machine=sparc-tti
-		;;
-	pbb)
-		basic_machine=m68k-tti
-		;;
-	pc532 | pc532-*)
-		basic_machine=ns32k-pc532
-		;;
-	pc98)
-		basic_machine=i386-pc
-		;;
-	pc98-*)
-		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	pentium | p5 | k5 | k6 | nexgen | viac3)
-		basic_machine=i586-pc
-		;;
-	pentiumpro | p6 | 6x86 | athlon | athlon_*)
-		basic_machine=i686-pc
-		;;
-	pentiumii | pentium2 | pentiumiii | pentium3)
-		basic_machine=i686-pc
-		;;
-	pentium4)
-		basic_machine=i786-pc
-		;;
-	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
-		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	pentiumpro-* | p6-* | 6x86-* | athlon-*)
-		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
-		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	pentium4-*)
-		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	pn)
-		basic_machine=pn-gould
-		;;
-	power)	basic_machine=power-ibm
-		;;
-	ppc | ppcbe)	basic_machine=powerpc-unknown
-		;;
-	ppc-* | ppcbe-*)
-		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	ppcle | powerpclittle | ppc-le | powerpc-little)
-		basic_machine=powerpcle-unknown
-		;;
-	ppcle-* | powerpclittle-*)
-		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	ppc64)	basic_machine=powerpc64-unknown
-		;;
-	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
-		basic_machine=powerpc64le-unknown
-		;;
-	ppc64le-* | powerpc64little-*)
-		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	ps2)
-		basic_machine=i386-ibm
-		;;
-	pw32)
-		basic_machine=i586-unknown
-		os=-pw32
-		;;
-	rdos | rdos64)
-		basic_machine=x86_64-pc
-		os=-rdos
-		;;
-	rdos32)
-		basic_machine=i386-pc
-		os=-rdos
-		;;
-	rom68k)
-		basic_machine=m68k-rom68k
-		os=-coff
-		;;
-	rm[46]00)
-		basic_machine=mips-siemens
-		;;
-	rtpc | rtpc-*)
-		basic_machine=romp-ibm
-		;;
-	s390 | s390-*)
-		basic_machine=s390-ibm
-		;;
-	s390x | s390x-*)
-		basic_machine=s390x-ibm
-		;;
-	sa29200)
-		basic_machine=a29k-amd
-		os=-udi
-		;;
-	sb1)
-		basic_machine=mipsisa64sb1-unknown
-		;;
-	sb1el)
-		basic_machine=mipsisa64sb1el-unknown
-		;;
-	sde)
-		basic_machine=mipsisa32-sde
-		os=-elf
-		;;
-	sei)
-		basic_machine=mips-sei
-		os=-seiux
-		;;
-	sequent)
-		basic_machine=i386-sequent
-		;;
-	sh)
-		basic_machine=sh-hitachi
-		os=-hms
-		;;
-	sh5el)
-		basic_machine=sh5le-unknown
-		;;
-	sh64)
-		basic_machine=sh64-unknown
-		;;
-	sparclite-wrs | simso-wrs)
-		basic_machine=sparclite-wrs
-		os=-vxworks
-		;;
-	sps7)
-		basic_machine=m68k-bull
-		os=-sysv2
-		;;
-	spur)
-		basic_machine=spur-unknown
-		;;
-	st2000)
-		basic_machine=m68k-tandem
-		;;
-	stratus)
-		basic_machine=i860-stratus
-		os=-sysv4
-		;;
-	strongarm-* | thumb-*)
-		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
-		;;
-	sun2)
-		basic_machine=m68000-sun
-		;;
-	sun2os3)
-		basic_machine=m68000-sun
-		os=-sunos3
-		;;
-	sun2os4)
-		basic_machine=m68000-sun
-		os=-sunos4
-		;;
-	sun3os3)
-		basic_machine=m68k-sun
-		os=-sunos3
-		;;
-	sun3os4)
-		basic_machine=m68k-sun
-		os=-sunos4
-		;;
-	sun4os3)
-		basic_machine=sparc-sun
-		os=-sunos3
-		;;
-	sun4os4)
-		basic_machine=sparc-sun
-		os=-sunos4
-		;;
-	sun4sol2)
-		basic_machine=sparc-sun
-		os=-solaris2
-		;;
-	sun3 | sun3-*)
-		basic_machine=m68k-sun
-		;;
-	sun4)
-		basic_machine=sparc-sun
-		;;
-	sun386 | sun386i | roadrunner)
-		basic_machine=i386-sun
-		;;
-	sv1)
-		basic_machine=sv1-cray
-		os=-unicos
-		;;
-	symmetry)
-		basic_machine=i386-sequent
-		os=-dynix
-		;;
-	t3e)
-		basic_machine=alphaev5-cray
-		os=-unicos
-		;;
-	t90)
-		basic_machine=t90-cray
-		os=-unicos
-		;;
-	tile*)
-		basic_machine=$basic_machine-unknown
-		os=-linux-gnu
-		;;
-	tx39)
-		basic_machine=mipstx39-unknown
-		;;
-	tx39el)
-		basic_machine=mipstx39el-unknown
-		;;
-	toad1)
-		basic_machine=pdp10-xkl
-		os=-tops20
-		;;
-	tower | tower-32)
-		basic_machine=m68k-ncr
-		;;
-	tpf)
-		basic_machine=s390x-ibm
-		os=-tpf
-		;;
-	udi29k)
-		basic_machine=a29k-amd
-		os=-udi
-		;;
-	ultra3)
-		basic_machine=a29k-nyu
-		os=-sym1
-		;;
-	v810 | necv810)
-		basic_machine=v810-nec
-		os=-none
-		;;
-	vaxv)
-		basic_machine=vax-dec
-		os=-sysv
-		;;
-	vms)
-		basic_machine=vax-dec
-		os=-vms
-		;;
-	vpp*|vx|vx-*)
-		basic_machine=f301-fujitsu
-		;;
-	vxworks960)
-		basic_machine=i960-wrs
-		os=-vxworks
-		;;
-	vxworks68)
-		basic_machine=m68k-wrs
-		os=-vxworks
-		;;
-	vxworks29k)
-		basic_machine=a29k-wrs
-		os=-vxworks
-		;;
-	w65*)
-		basic_machine=w65-wdc
-		os=-none
-		;;
-	w89k-*)
-		basic_machine=hppa1.1-winbond
-		os=-proelf
-		;;
-	xbox)
-		basic_machine=i686-pc
-		os=-mingw32
-		;;
-	xps | xps100)
-		basic_machine=xps100-honeywell
-		;;
-	xscale-* | xscalee[bl]-*)
-		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
-		;;
-	ymp)
-		basic_machine=ymp-cray
-		os=-unicos
-		;;
-	z8k-*-coff)
-		basic_machine=z8k-unknown
-		os=-sim
-		;;
-	z80-*-coff)
-		basic_machine=z80-unknown
-		os=-sim
-		;;
-	none)
-		basic_machine=none-none
-		os=-none
-		;;
-
-# Here we handle the default manufacturer of certain CPU types.  It is in
-# some cases the only manufacturer, in others, it is the most popular.
-	w89k)
-		basic_machine=hppa1.1-winbond
-		;;
-	op50n)
-		basic_machine=hppa1.1-oki
-		;;
-	op60c)
-		basic_machine=hppa1.1-oki
-		;;
-	romp)
-		basic_machine=romp-ibm
-		;;
-	mmix)
-		basic_machine=mmix-knuth
-		;;
-	rs6000)
-		basic_machine=rs6000-ibm
-		;;
-	vax)
-		basic_machine=vax-dec
-		;;
-	pdp10)
-		# there are many clones, so DEC is not a safe bet
-		basic_machine=pdp10-unknown
-		;;
-	pdp11)
-		basic_machine=pdp11-dec
-		;;
-	we32k)
-		basic_machine=we32k-att
-		;;
-	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
-		basic_machine=sh-unknown
-		;;
-	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
-		basic_machine=sparc-sun
-		;;
-	cydra)
-		basic_machine=cydra-cydrome
-		;;
-	orion)
-		basic_machine=orion-highlevel
-		;;
-	orion105)
-		basic_machine=clipper-highlevel
-		;;
-	mac | mpw | mac-mpw)
-		basic_machine=m68k-apple
-		;;
-	pmac | pmac-mpw)
-		basic_machine=powerpc-apple
-		;;
-	*-unknown)
-		# Make sure to match an already-canonicalized machine name.
-		;;
-	*)
-		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
-		exit 1
-		;;
-esac
-
-# Here we canonicalize certain aliases for manufacturers.
-case $basic_machine in
-	*-digital*)
-		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
-		;;
-	*-commodore*)
-		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
-		;;
-	*)
-		;;
-esac
-
-# Decode manufacturer-specific aliases for certain operating systems.
-
-if [ x"$os" != x"" ]
-then
-case $os in
-	# First match some system type aliases
-	# that might get confused with valid system types.
-	# -solaris* is a basic system type, with this one exception.
-	-auroraux)
-		os=-auroraux
-		;;
-	-solaris1 | -solaris1.*)
-		os=`echo $os | sed -e 's|solaris1|sunos4|'`
-		;;
-	-solaris)
-		os=-solaris2
-		;;
-	-svr4*)
-		os=-sysv4
-		;;
-	-unixware*)
-		os=-sysv4.2uw
-		;;
-	-gnu/linux*)
-		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
-		;;
-	# First accept the basic system types.
-	# The portable systems comes first.
-	# Each alternative MUST END IN A *, to match a version number.
-	# -sysv* is not here because it comes later, after sysvr4.
-	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
-	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
-	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
-	      | -sym* | -kopensolaris* | -plan9* \
-	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-	      | -aos* | -aros* \
-	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
-	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
-	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
-	      | -bitrig* | -openbsd* | -solidbsd* \
-	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
-	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
-	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
-	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
-	      | -chorusos* | -chorusrdb* | -cegcc* \
-	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
-	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
-	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
-	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
-	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
-	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
-	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
-	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
-	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
-	# Remember, each alternative MUST END IN *, to match a version number.
-		;;
-	-qnx*)
-		case $basic_machine in
-		    x86-* | i*86-*)
-			;;
-		    *)
-			os=-nto$os
-			;;
-		esac
-		;;
-	-nto-qnx*)
-		;;
-	-nto*)
-		os=`echo $os | sed -e 's|nto|nto-qnx|'`
-		;;
-	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
-	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
-	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
-		;;
-	-mac*)
-		os=`echo $os | sed -e 's|mac|macos|'`
-		;;
-	-linux-dietlibc)
-		os=-linux-dietlibc
-		;;
-	-linux*)
-		os=`echo $os | sed -e 's|linux|linux-gnu|'`
-		;;
-	-sunos5*)
-		os=`echo $os | sed -e 's|sunos5|solaris2|'`
-		;;
-	-sunos6*)
-		os=`echo $os | sed -e 's|sunos6|solaris3|'`
-		;;
-	-opened*)
-		os=-openedition
-		;;
-	-os400*)
-		os=-os400
-		;;
-	-wince*)
-		os=-wince
-		;;
-	-osfrose*)
-		os=-osfrose
-		;;
-	-osf*)
-		os=-osf
-		;;
-	-utek*)
-		os=-bsd
-		;;
-	-dynix*)
-		os=-bsd
-		;;
-	-acis*)
-		os=-aos
-		;;
-	-atheos*)
-		os=-atheos
-		;;
-	-syllable*)
-		os=-syllable
-		;;
-	-386bsd)
-		os=-bsd
-		;;
-	-ctix* | -uts*)
-		os=-sysv
-		;;
-	-nova*)
-		os=-rtmk-nova
-		;;
-	-ns2 )
-		os=-nextstep2
-		;;
-	-nsk*)
-		os=-nsk
-		;;
-	# Preserve the version number of sinix5.
-	-sinix5.*)
-		os=`echo $os | sed -e 's|sinix|sysv|'`
-		;;
-	-sinix*)
-		os=-sysv4
-		;;
-	-tpf*)
-		os=-tpf
-		;;
-	-triton*)
-		os=-sysv3
-		;;
-	-oss*)
-		os=-sysv3
-		;;
-	-svr4)
-		os=-sysv4
-		;;
-	-svr3)
-		os=-sysv3
-		;;
-	-sysvr4)
-		os=-sysv4
-		;;
-	# This must come after -sysvr4.
-	-sysv*)
-		;;
-	-ose*)
-		os=-ose
-		;;
-	-es1800*)
-		os=-ose
-		;;
-	-xenix)
-		os=-xenix
-		;;
-	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
-		os=-mint
-		;;
-	-aros*)
-		os=-aros
-		;;
-	-zvmoe)
-		os=-zvmoe
-		;;
-	-dicos*)
-		os=-dicos
-		;;
-	-nacl*)
-		;;
-	-none)
-		;;
-	*)
-		# Get rid of the `-' at the beginning of $os.
-		os=`echo $os | sed 's/[^-]*-//'`
-		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
-		exit 1
-		;;
-esac
-else
-
-# Here we handle the default operating systems that come with various machines.
-# The value should be what the vendor currently ships out the door with their
-# machine or put another way, the most popular os provided with the machine.
-
-# Note that if you're going to try to match "-MANUFACTURER" here (say,
-# "-sun"), then you have to tell the case statement up towards the top
-# that MANUFACTURER isn't an operating system.  Otherwise, code above
-# will signal an error saying that MANUFACTURER isn't an operating
-# system, and we'll never get to this point.
-
-case $basic_machine in
-	score-*)
-		os=-elf
-		;;
-	spu-*)
-		os=-elf
-		;;
-	*-acorn)
-		os=-riscix1.2
-		;;
-	arm*-rebel)
-		os=-linux
-		;;
-	arm*-semi)
-		os=-aout
-		;;
-	c4x-* | tic4x-*)
-		os=-coff
-		;;
-	c8051-*)
-		os=-elf
-		;;
-	hexagon-*)
-		os=-elf
-		;;
-	tic54x-*)
-		os=-coff
-		;;
-	tic55x-*)
-		os=-coff
-		;;
-	tic6x-*)
-		os=-coff
-		;;
-	# This must come before the *-dec entry.
-	pdp10-*)
-		os=-tops20
-		;;
-	pdp11-*)
-		os=-none
-		;;
-	*-dec | vax-*)
-		os=-ultrix4.2
-		;;
-	m68*-apollo)
-		os=-domain
-		;;
-	i386-sun)
-		os=-sunos4.0.2
-		;;
-	m68000-sun)
-		os=-sunos3
-		;;
-	m68*-cisco)
-		os=-aout
-		;;
-	mep-*)
-		os=-elf
-		;;
-	mips*-cisco)
-		os=-elf
-		;;
-	mips*-*)
-		os=-elf
-		;;
-	or32-*)
-		os=-coff
-		;;
-	*-tti)	# must be before sparc entry or we get the wrong os.
-		os=-sysv3
-		;;
-	sparc-* | *-sun)
-		os=-sunos4.1.1
-		;;
-	*-be)
-		os=-beos
-		;;
-	*-haiku)
-		os=-haiku
-		;;
-	*-ibm)
-		os=-aix
-		;;
-	*-knuth)
-		os=-mmixware
-		;;
-	*-wec)
-		os=-proelf
-		;;
-	*-winbond)
-		os=-proelf
-		;;
-	*-oki)
-		os=-proelf
-		;;
-	*-hp)
-		os=-hpux
-		;;
-	*-hitachi)
-		os=-hiux
-		;;
-	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
-		os=-sysv
-		;;
-	*-cbm)
-		os=-amigaos
-		;;
-	*-dg)
-		os=-dgux
-		;;
-	*-dolphin)
-		os=-sysv3
-		;;
-	m68k-ccur)
-		os=-rtu
-		;;
-	m88k-omron*)
-		os=-luna
-		;;
-	*-next )
-		os=-nextstep
-		;;
-	*-sequent)
-		os=-ptx
-		;;
-	*-crds)
-		os=-unos
-		;;
-	*-ns)
-		os=-genix
-		;;
-	i370-*)
-		os=-mvs
-		;;
-	*-next)
-		os=-nextstep3
-		;;
-	*-gould)
-		os=-sysv
-		;;
-	*-highlevel)
-		os=-bsd
-		;;
-	*-encore)
-		os=-bsd
-		;;
-	*-sgi)
-		os=-irix
-		;;
-	*-siemens)
-		os=-sysv4
-		;;
-	*-masscomp)
-		os=-rtu
-		;;
-	f30[01]-fujitsu | f700-fujitsu)
-		os=-uxpv
-		;;
-	*-rom68k)
-		os=-coff
-		;;
-	*-*bug)
-		os=-coff
-		;;
-	*-apple)
-		os=-macos
-		;;
-	*-atari*)
-		os=-mint
-		;;
-	*)
-		os=-none
-		;;
-esac
-fi
-
-# Here we handle the case where we know the os, and the CPU type, but not the
-# manufacturer.  We pick the logical manufacturer.
-vendor=unknown
-case $basic_machine in
-	*-unknown)
-		case $os in
-			-riscix*)
-				vendor=acorn
-				;;
-			-sunos*)
-				vendor=sun
-				;;
-			-cnk*|-aix*)
-				vendor=ibm
-				;;
-			-beos*)
-				vendor=be
-				;;
-			-hpux*)
-				vendor=hp
-				;;
-			-mpeix*)
-				vendor=hp
-				;;
-			-hiux*)
-				vendor=hitachi
-				;;
-			-unos*)
-				vendor=crds
-				;;
-			-dgux*)
-				vendor=dg
-				;;
-			-luna*)
-				vendor=omron
-				;;
-			-genix*)
-				vendor=ns
-				;;
-			-mvs* | -opened*)
-				vendor=ibm
-				;;
-			-os400*)
-				vendor=ibm
-				;;
-			-ptx*)
-				vendor=sequent
-				;;
-			-tpf*)
-				vendor=ibm
-				;;
-			-vxsim* | -vxworks* | -windiss*)
-				vendor=wrs
-				;;
-			-aux*)
-				vendor=apple
-				;;
-			-hms*)
-				vendor=hitachi
-				;;
-			-mpw* | -macos*)
-				vendor=apple
-				;;
-			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
-				vendor=atari
-				;;
-			-vos*)
-				vendor=stratus
-				;;
-		esac
-		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
-		;;
-esac
-
-echo $basic_machine$os
-exit
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/configure b/configure
deleted file mode 100755
index a846be6..0000000
--- a/configure
+++ /dev/null
@@ -1,19561 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for libmicrohttpd 0.9.42.
-#
-# Report bugs to <libmicrohttpd@gnu.org>.
-#
-#
-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
-#
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-	expr "X$arg" : "X\\(.*\\)$as_nl";
-	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""	$as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# Use a proper internal environment variable to ensure we don't fall
-  # into an infinite loop, continuously re-executing ourselves.
-  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
-    _as_can_reexec=no; export _as_can_reexec;
-    # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
-  *v*x* | *x*v* ) as_opts=-vx ;;
-  *v* ) as_opts=-v ;;
-  *x* ) as_opts=-x ;;
-  * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-as_fn_exit 255
-  fi
-  # We don't want this to propagate to other subprocesses.
-          { _as_can_reexec=; unset _as_can_reexec;}
-if test "x$CONFIG_SHELL" = x; then
-  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '\${1+\"\$@\"}'='\"\$@\"'
-  setopt NO_GLOB_SUBST
-else
-  case \`(set -o) 2>/dev/null\` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-"
-  as_required="as_fn_return () { (exit \$1); }
-as_fn_success () { as_fn_return 0; }
-as_fn_failure () { as_fn_return 1; }
-as_fn_ret_success () { return 0; }
-as_fn_ret_failure () { return 1; }
-
-exitcode=0
-as_fn_success || { exitcode=1; echo as_fn_success failed.; }
-as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
-as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
-as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
-
-else
-  exitcode=1; echo positional parameters were not saved.
-fi
-test x\$exitcode = x0 || exit 1
-test -x / || exit 1"
-  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
-  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
-  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
-  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
-
-  test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || (
-    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-    ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO
-    ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO
-    PATH=/empty FPATH=/empty; export PATH FPATH
-    test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\
-      || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1
-test \$(( 1 + 1 )) = 2 || exit 1"
-  if (eval "$as_required") 2>/dev/null; then :
-  as_have_required=yes
-else
-  as_have_required=no
-fi
-  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
-
-else
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-as_found=false
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  as_found=:
-  case $as_dir in #(
-	 /*)
-	   for as_base in sh bash ksh sh5; do
-	     # Try only shells that exist, to save several forks.
-	     as_shell=$as_dir/$as_base
-	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
-  CONFIG_SHELL=$as_shell as_have_required=yes
-		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
-  break 2
-fi
-fi
-	   done;;
-       esac
-  as_found=false
-done
-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
-	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
-  CONFIG_SHELL=$SHELL as_have_required=yes
-fi; }
-IFS=$as_save_IFS
-
-
-      if test "x$CONFIG_SHELL" != x; then :
-  export CONFIG_SHELL
-             # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
-  *v*x* | *x*v* ) as_opts=-vx ;;
-  *v* ) as_opts=-v ;;
-  *x* ) as_opts=-x ;;
-  * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-exit 255
-fi
-
-    if test x$as_have_required = xno; then :
-  $as_echo "$0: This script requires a shell more modern than all"
-  $as_echo "$0: the shells that I found on your system."
-  if test x${ZSH_VERSION+set} = xset ; then
-    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
-    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
-  else
-    $as_echo "$0: Please tell bug-autoconf@gnu.org and
-$0: libmicrohttpd@gnu.org about your system, including any
-$0: error possibly output before this message. Then install
-$0: a modern shell, or manually run the script under such a
-$0: shell if you do have one."
-  fi
-  exit 1
-fi
-fi
-fi
-SHELL=${CONFIG_SHELL-/bin/sh}
-export SHELL
-# Unset more variables known to interfere with behavior of common tools.
-CLICOLOR_FORCE= GREP_OPTIONS=
-unset CLICOLOR_FORCE GREP_OPTIONS
-
-## --------------------- ##
-## M4sh Shell Functions. ##
-## --------------------- ##
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-
-  as_lineno_1=$LINENO as_lineno_1a=$LINENO
-  as_lineno_2=$LINENO as_lineno_2a=$LINENO
-  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
-  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
-  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
-    sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
-      N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
-      t loop
-      s/-\n.*//
-    ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
-
-  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
-  # already done that, so ensure we don't try to do so again and fall
-  # in an infinite loop.  This has already happened in practice.
-  _as_can_reexec=no; export _as_can_reexec
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensitive to this).
-  . "./$as_me.lineno"
-  # Exit status is that of the last command.
-  exit
-}
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='	';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-SHELL=${CONFIG_SHELL-/bin/sh}
-
-
-test -n "$DJDIR" || exec 7<&0 </dev/null
-exec 6>&1
-
-# Name of the host.
-# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_clean_files=
-ac_config_libobj_dir=.
-LIBOBJS=
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-
-# Identity of this package.
-PACKAGE_NAME='libmicrohttpd'
-PACKAGE_TARNAME='libmicrohttpd'
-PACKAGE_VERSION='0.9.42'
-PACKAGE_STRING='libmicrohttpd 0.9.42'
-PACKAGE_BUGREPORT='libmicrohttpd@gnu.org'
-PACKAGE_URL=''
-
-# Factoring default headers for most tests.
-ac_includes_default="\
-#include <stdio.h>
-#ifdef HAVE_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-#ifdef STDC_HEADERS
-# include <stdlib.h>
-# include <stddef.h>
-#else
-# ifdef HAVE_STDLIB_H
-#  include <stdlib.h>
-# endif
-#endif
-#ifdef HAVE_STRING_H
-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
-#  include <memory.h>
-# endif
-# include <string.h>
-#endif
-#ifdef HAVE_STRINGS_H
-# include <strings.h>
-#endif
-#ifdef HAVE_INTTYPES_H
-# include <inttypes.h>
-#endif
-#ifdef HAVE_STDINT_H
-# include <stdint.h>
-#endif
-#ifdef HAVE_UNISTD_H
-# include <unistd.h>
-#endif"
-
-ac_func_list=
-ac_subst_vars='am__EXEEXT_FALSE
-am__EXEEXT_TRUE
-LTLIBOBJS
-LIBOBJS
-MHD_LIBDEPS
-MHD_LIBDEPS_PKGCFG
-MHD_REQ_PRIVATE
-MHD_LIB_LDFLAGS
-MHD_LIB_CFLAGS
-MHD_LIB_CPPFLAGS
-CPU_COUNT
-USE_COVERAGE_FALSE
-USE_COVERAGE_TRUE
-ENABLE_DAUTH_FALSE
-ENABLE_DAUTH_TRUE
-ENABLE_BAUTH_FALSE
-ENABLE_BAUTH_TRUE
-ENABLE_HTTPS_FALSE
-ENABLE_HTTPS_TRUE
-GNUTLS_LDFLAGS
-GNUTLS_CPPFLAGS
-HAVE_GNUTLS_SNI_FALSE
-HAVE_GNUTLS_SNI_TRUE
-HAVE_GNUTLS_FALSE
-HAVE_GNUTLS_TRUE
-GNUTLS_LIBS
-GNUTLS_CFLAGS
-PKG_CONFIG_LIBDIR
-PKG_CONFIG_PATH
-LIBGCRYPT_LIBS
-LIBGCRYPT_CFLAGS
-LIBGCRYPT_CONFIG
-HAVE_SOCAT_FALSE
-HAVE_SOCAT_TRUE
-HAVE_ZZUF_FALSE
-HAVE_ZZUF_TRUE
-have_socat
-have_zzuf
-HAVE_POSTPROCESSOR_FALSE
-HAVE_POSTPROCESSOR_TRUE
-HAVE_SPDYLAY_FALSE
-HAVE_SPDYLAY_TRUE
-SPDY_LIBDEPS
-SPDY_LIB_CPPFLAGS
-SPDY_LIB_CFLAGS
-SPDY_LIB_LDFLAGS
-ENABLE_SPDY_FALSE
-ENABLE_SPDY_TRUE
-HAVE_OPENSSL_FALSE
-HAVE_OPENSSL_TRUE
-OPENSSL_LDFLAGS
-OPENSSL_LIBS
-OPENSSL_INCLUDES
-PKG_CONFIG
-HAVE_MAGIC_FALSE
-HAVE_MAGIC_TRUE
-HAVE_CURL_FALSE
-HAVE_CURL_TRUE
-LIBCURL
-LIBCURL_CPPFLAGS
-_libcurl_config
-HIDDEN_VISIBILITY_CFLAGS
-HAVE_TSEARCH_FALSE
-HAVE_TSEARCH_TRUE
-BUILD_EXAMPLES_FALSE
-BUILD_EXAMPLES_TRUE
-BUILD_DOC_FALSE
-BUILD_DOC_TRUE
-W32_STATIC_LIB_FALSE
-W32_STATIC_LIB_TRUE
-HAVE_MAKEINFO_BINARY_FALSE
-HAVE_MAKEINFO_BINARY_TRUE
-HAVE_MAKEINFO_BINARY
-HAVE_CURL_BINARY_FALSE
-HAVE_CURL_BINARY_TRUE
-HAVE_CURL_BINARY
-USE_MS_LIB_TOOL_FALSE
-USE_MS_LIB_TOOL_TRUE
-W32_SHARED_LIB_EXP_FALSE
-W32_SHARED_LIB_EXP_TRUE
-HAVE_W32_FALSE
-HAVE_W32_TRUE
-USE_W32_THREADS_FALSE
-USE_W32_THREADS_TRUE
-USE_POSIX_THREADS_FALSE
-USE_POSIX_THREADS_TRUE
-lt_cv_objdir
-MS_LIB_TOOL
-HAVE_POSIX_THREADS_FALSE
-HAVE_POSIX_THREADS_TRUE
-PTHREAD_CFLAGS
-PTHREAD_LIBS
-PTHREAD_CC
-ax_pthread_config
-PACKAGE_VERSION_SUBMINOR
-PACKAGE_VERSION_MINOR
-PACKAGE_VERSION_MAJOR
-RC
-CPP
-OTOOL64
-OTOOL
-LIPO
-NMEDIT
-DSYMUTIL
-MANIFEST_TOOL
-RANLIB
-ac_ct_AR
-AR
-NM
-ac_ct_DUMPBIN
-DUMPBIN
-LD
-FGREP
-EGREP
-GREP
-SED
-LIBTOOL
-OBJDUMP
-DLLTOOL
-AS
-am__fastdepCC_FALSE
-am__fastdepCC_TRUE
-CCDEPMODE
-am__nodep
-AMDEPBACKSLASH
-AMDEP_FALSE
-AMDEP_TRUE
-am__quote
-am__include
-DEPDIR
-OBJEXT
-EXEEXT
-ac_ct_CC
-CPPFLAGS
-LDFLAGS
-CFLAGS
-CC
-host_os
-host_vendor
-host_cpu
-host
-build_os
-build_vendor
-build_cpu
-build
-LN_S
-LIBSPDY_VERSION_AGE
-LIBSPDY_VERSION_REVISION
-LIBSPDY_VERSION_CURRENT
-LIB_VERSION_AGE
-LIB_VERSION_REVISION
-LIB_VERSION_CURRENT
-AM_BACKSLASH
-AM_DEFAULT_VERBOSITY
-AM_DEFAULT_V
-AM_V
-am__untar
-am__tar
-AMTAR
-am__leading_dot
-SET_MAKE
-AWK
-mkdir_p
-MKDIR_P
-INSTALL_STRIP_PROGRAM
-STRIP
-install_sh
-MAKEINFO
-AUTOHEADER
-AUTOMAKE
-AUTOCONF
-ACLOCAL
-VERSION
-PACKAGE
-CYGPATH_W
-am__isrc
-INSTALL_DATA
-INSTALL_SCRIPT
-INSTALL_PROGRAM
-target_alias
-host_alias
-build_alias
-LIBS
-ECHO_T
-ECHO_N
-ECHO_C
-DEFS
-mandir
-localedir
-libdir
-psdir
-pdfdir
-dvidir
-htmldir
-infodir
-docdir
-oldincludedir
-includedir
-localstatedir
-sharedstatedir
-sysconfdir
-datadir
-datarootdir
-libexecdir
-sbindir
-bindir
-program_transform_name
-prefix
-exec_prefix
-PACKAGE_URL
-PACKAGE_BUGREPORT
-PACKAGE_STRING
-PACKAGE_VERSION
-PACKAGE_TARNAME
-PACKAGE_NAME
-PATH_SEPARATOR
-SHELL'
-ac_subst_files=''
-ac_user_opts='
-enable_option_checking
-enable_silent_rules
-enable_dependency_tracking
-enable_shared
-enable_static
-with_pic
-enable_fast_install
-with_gnu_ld
-with_sysroot
-enable_libtool_lock
-with_threads
-enable_doc
-enable_examples
-enable_poll
-enable_epoll
-enable_socketpair
-enable_curl
-with_libcurl
-enable_spdy
-with_openssl
-enable_largefile
-enable_messages
-enable_postprocessor
-with_libgcrypt_prefix
-with_gnutls
-enable_https
-enable_bauth
-enable_dauth
-enable_coverage
-'
-      ac_precious_vars='build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-LIBS
-CPPFLAGS
-CPP
-PKG_CONFIG
-PKG_CONFIG_PATH
-PKG_CONFIG_LIBDIR
-GNUTLS_CFLAGS
-GNUTLS_LIBS'
-
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-ac_unrecognized_opts=
-ac_unrecognized_sep=
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-# (The list follows the same order as the GNU Coding Standards.)
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datarootdir='${prefix}/share'
-datadir='${datarootdir}'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
-infodir='${datarootdir}/info'
-htmldir='${docdir}'
-dvidir='${docdir}'
-pdfdir='${docdir}'
-psdir='${docdir}'
-libdir='${exec_prefix}/lib'
-localedir='${datarootdir}/locale'
-mandir='${datarootdir}/man'
-
-ac_prev=
-ac_dashdash=
-for ac_option
-do
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval $ac_prev=\$ac_option
-    ac_prev=
-    continue
-  fi
-
-  case $ac_option in
-  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
-  *=)   ac_optarg= ;;
-  *)    ac_optarg=yes ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case $ac_dashdash$ac_option in
-  --)
-    ac_dashdash=yes ;;
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir=$ac_optarg ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build_alias ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build_alias=$ac_optarg ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file=$ac_optarg ;;
-
-  --config-cache | -C)
-    cache_file=config.cache ;;
-
-  -datadir | --datadir | --datadi | --datad)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=*)
-    datadir=$ac_optarg ;;
-
-  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
-  | --dataroo | --dataro | --datar)
-    ac_prev=datarootdir ;;
-  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
-  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
-    datarootdir=$ac_optarg ;;
-
-  -disable-* | --disable-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"enable_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
-	 ac_unrecognized_sep=', ';;
-    esac
-    eval enable_$ac_useropt=no ;;
-
-  -docdir | --docdir | --docdi | --doc | --do)
-    ac_prev=docdir ;;
-  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
-    docdir=$ac_optarg ;;
-
-  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
-    ac_prev=dvidir ;;
-  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
-    dvidir=$ac_optarg ;;
-
-  -enable-* | --enable-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"enable_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
-	 ac_unrecognized_sep=', ';;
-    esac
-    eval enable_$ac_useropt=\$ac_optarg ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix=$ac_optarg ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he | -h)
-    ac_init_help=long ;;
-  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
-    ac_init_help=recursive ;;
-  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
-    ac_init_help=short ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host_alias ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host_alias=$ac_optarg ;;
-
-  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
-    ac_prev=htmldir ;;
-  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
-  | --ht=*)
-    htmldir=$ac_optarg ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir=$ac_optarg ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir=$ac_optarg ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir=$ac_optarg ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir=$ac_optarg ;;
-
-  -localedir | --localedir | --localedi | --localed | --locale)
-    ac_prev=localedir ;;
-  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
-    localedir=$ac_optarg ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst | --locals)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
-    localstatedir=$ac_optarg ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir=$ac_optarg ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c | -n)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir=$ac_optarg ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix=$ac_optarg ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix=$ac_optarg ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix=$ac_optarg ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name=$ac_optarg ;;
-
-  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
-    ac_prev=pdfdir ;;
-  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
-    pdfdir=$ac_optarg ;;
-
-  -psdir | --psdir | --psdi | --psd | --ps)
-    ac_prev=psdir ;;
-  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
-    psdir=$ac_optarg ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir=$ac_optarg ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir=$ac_optarg ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site=$ac_optarg ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir=$ac_optarg ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir=$ac_optarg ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target_alias ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target_alias=$ac_optarg ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers | -V)
-    ac_init_version=: ;;
-
-  -with-* | --with-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"with_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
-	 ac_unrecognized_sep=', ';;
-    esac
-    eval with_$ac_useropt=\$ac_optarg ;;
-
-  -without-* | --without-*)
-    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
-    ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
-    case $ac_user_opts in
-      *"
-"with_$ac_useropt"
-"*) ;;
-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
-	 ac_unrecognized_sep=', ';;
-    esac
-    eval with_$ac_useropt=no ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes=$ac_optarg ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries=$ac_optarg ;;
-
-  -*) as_fn_error $? "unrecognized option: \`$ac_option'
-Try \`$0 --help' for more information"
-    ;;
-
-  *=*)
-    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
-    # Reject names that are not valid shell variable names.
-    case $ac_envvar in #(
-      '' | [0-9]* | *[!_$as_cr_alnum]* )
-      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
-    esac
-    eval $ac_envvar=\$ac_optarg
-    export $ac_envvar ;;
-
-  *)
-    # FIXME: should be removed in autoconf 3.0.
-    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
-    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
-  as_fn_error $? "missing argument to $ac_option"
-fi
-
-if test -n "$ac_unrecognized_opts"; then
-  case $enable_option_checking in
-    no) ;;
-    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
-    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
-  esac
-fi
-
-# Check all directory arguments for consistency.
-for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
-		datadir sysconfdir sharedstatedir localstatedir includedir \
-		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-		libdir localedir mandir
-do
-  eval ac_val=\$$ac_var
-  # Remove trailing slashes.
-  case $ac_val in
-    */ )
-      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
-      eval $ac_var=\$ac_val;;
-  esac
-  # Be sure to have absolute directory names.
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* )  continue;;
-    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
-  esac
-  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
-  if test "x$build_alias" = x; then
-    cross_compiling=maybe
-  elif test "x$build_alias" != "x$host_alias"; then
-    cross_compiling=yes
-  fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-ac_pwd=`pwd` && test -n "$ac_pwd" &&
-ac_ls_di=`ls -di .` &&
-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
-  as_fn_error $? "working directory cannot be determined"
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
-  as_fn_error $? "pwd does not report name of working directory"
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then the parent directory.
-  ac_confdir=`$as_dirname -- "$as_myself" ||
-$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_myself" : 'X\(//\)[^/]' \| \
-	 X"$as_myself" : 'X\(//\)$' \| \
-	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_myself" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-  srcdir=$ac_confdir
-  if test ! -r "$srcdir/$ac_unique_file"; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r "$srcdir/$ac_unique_file"; then
-  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
-  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
-fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
-	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
-	pwd)`
-# When building in place, set srcdir=.
-if test "$ac_abs_confdir" = "$ac_pwd"; then
-  srcdir=.
-fi
-# Remove unnecessary trailing slashes from srcdir.
-# Double slashes in file names in object file debugging info
-# mess up M-x gdb in Emacs.
-case $srcdir in
-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
-esac
-for ac_var in $ac_precious_vars; do
-  eval ac_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_env_${ac_var}_value=\$${ac_var}
-  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_cv_env_${ac_var}_value=\$${ac_var}
-done
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
-  # Omit some internal or obsolete options to make the list less imposing.
-  # This message is too long to be a string in the A/UX 3.1 sh.
-  cat <<_ACEOF
-\`configure' configures libmicrohttpd 0.9.42 to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE.  See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
-  -h, --help              display this help and exit
-      --help=short        display options specific to this package
-      --help=recursive    display the short help of all the included packages
-  -V, --version           display version information and exit
-  -q, --quiet, --silent   do not print \`checking ...' messages
-      --cache-file=FILE   cache test results in FILE [disabled]
-  -C, --config-cache      alias for \`--cache-file=config.cache'
-  -n, --no-create         do not create output files
-      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
-
-Installation directories:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-                          [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-                          [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
-  --bindir=DIR            user executables [EPREFIX/bin]
-  --sbindir=DIR           system admin executables [EPREFIX/sbin]
-  --libexecdir=DIR        program executables [EPREFIX/libexec]
-  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
-  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
-  --libdir=DIR            object code libraries [EPREFIX/lib]
-  --includedir=DIR        C header files [PREFIX/include]
-  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
-  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
-  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
-  --infodir=DIR           info documentation [DATAROOTDIR/info]
-  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
-  --mandir=DIR            man documentation [DATAROOTDIR/man]
-  --docdir=DIR            documentation root [DATAROOTDIR/doc/libmicrohttpd]
-  --htmldir=DIR           html documentation [DOCDIR]
-  --dvidir=DIR            dvi documentation [DOCDIR]
-  --pdfdir=DIR            pdf documentation [DOCDIR]
-  --psdir=DIR             ps documentation [DOCDIR]
-_ACEOF
-
-  cat <<\_ACEOF
-
-Program names:
-  --program-prefix=PREFIX            prepend PREFIX to installed program names
-  --program-suffix=SUFFIX            append SUFFIX to installed program names
-  --program-transform-name=PROGRAM   run sed PROGRAM on installed program names
-
-System types:
-  --build=BUILD     configure for building on BUILD [guessed]
-  --host=HOST       cross-compile to build programs to run on HOST [BUILD]
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
-  case $ac_init_help in
-     short | recursive ) echo "Configuration of libmicrohttpd 0.9.42:";;
-   esac
-  cat <<\_ACEOF
-
-Optional Features:
-  --disable-option-checking  ignore unrecognized --enable/--with options
-  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
-  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
-  --enable-silent-rules   less verbose build output (undo: "make V=1")
-  --disable-silent-rules  verbose build output (undo: "make V=0")
-  --enable-dependency-tracking
-                          do not reject slow dependency extractors
-  --disable-dependency-tracking
-                          speeds up one-time build
-  --enable-shared[=PKGS]  build shared libraries [default=yes]
-  --enable-static[=PKGS]  build static libraries [default=yes]
-  --enable-fast-install[=PKGS]
-                          optimize for fast installation [default=yes]
-  --disable-libtool-lock  avoid locking (might break parallel builds)
-  --disable-doc           do not build any documentation
-  --disable-examples      do not build any examples
-  --enable-poll[=ARG]     enable poll support (yes, no, auto) [auto]
-  --enable-epoll[=ARG]    enable epoll support (yes, no, auto) [auto]
-  --enable-socketpair[=ARG]
-                          disable internal singalling by pipes and use socket
-                          pair instead (yes, no, try) [no]
-  --disable-curl          disable cURL based testcases
-  --enable-spdy           enable build libmicrospdy (yes, no, auto) [auto]
-  --disable-largefile     omit support for large files
-  --disable-messages      disable MHD error messages
-  --disable-postprocessor disable MHD PostProcessor functionality
-  --enable-https          enable HTTPS support (yes, no, auto)[auto]
-  --disable-bauth         disable HTTP basic Auth support
-  --disable-dauth         disable HTTP basic and digest Auth support
-  --enable-coverage       compile the library with code coverage support
-
-Optional Packages:
-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
-  --with-pic[=PKGS]       try to use only PIC/non-PIC objects [default=use
-                          both]
-  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
-  --with-sysroot=DIR Search for dependent libraries within DIR
-                        (or the compiler's sysroot if not specified).
-  --with-threads=LIB      choose threading library (posix, w32, auto) [auto]
-  --with-libcurl=PREFIX   look for the curl library in PREFIX/lib and headers
-                          in PREFIX/include
-  --with-openssl=DIR      root of the OpenSSL directory
-  --with-libgcrypt-prefix=PFX
-                          prefix where LIBGCRYPT is installed (optional)
-  --with-gnutls[=PFX]     use GnuTLS for HTTPS support, optional PFX overrides
-                          pkg-config data for GnuTLS headers (PFX/include) and
-                          libs (PFX/lib)
-
-Some influential environment variables:
-  CC          C compiler command
-  CFLAGS      C compiler flags
-  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
-              nonstandard directory <lib dir>
-  LIBS        libraries to pass to the linker, e.g. -l<library>
-  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
-              you have headers in a nonstandard directory <include dir>
-  CPP         C preprocessor
-  PKG_CONFIG  path to pkg-config utility
-  PKG_CONFIG_PATH
-              directories to add to pkg-config's search path
-  PKG_CONFIG_LIBDIR
-              path overriding pkg-config's built-in search path
-  GNUTLS_CFLAGS
-              C compiler flags for GNUTLS, overriding pkg-config
-  GNUTLS_LIBS linker flags for GNUTLS, overriding pkg-config
-
-Use these variables to override the choices made by `configure' or to help
-it to find libraries and programs with nonstandard names/locations.
-
-Report bugs to <libmicrohttpd@gnu.org>.
-_ACEOF
-ac_status=$?
-fi
-
-if test "$ac_init_help" = "recursive"; then
-  # If there are subdirs, report their specific --help.
-  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d "$ac_dir" ||
-      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
-      continue
-    ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-    cd "$ac_dir" || { ac_status=$?; continue; }
-    # Check for guested configure.
-    if test -f "$ac_srcdir/configure.gnu"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
-    elif test -f "$ac_srcdir/configure"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure" --help=recursive
-    else
-      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi || ac_status=$?
-    cd "$ac_pwd" || { ac_status=$?; break; }
-  done
-fi
-
-test -n "$ac_init_help" && exit $ac_status
-if $ac_init_version; then
-  cat <<\_ACEOF
-libmicrohttpd configure 0.9.42
-generated by GNU Autoconf 2.69
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
-  exit
-fi
-
-## ------------------------ ##
-## Autoconf initialization. ##
-## ------------------------ ##
-
-# ac_fn_c_try_compile LINENO
-# --------------------------
-# Try to compile conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_compile ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext
-  if { { ac_try="$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compile") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_compile
-
-# ac_fn_c_try_link LINENO
-# -----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_link ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext conftest$ac_exeext
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext && {
-	 test "$cross_compiling" = yes ||
-	 test -x conftest$ac_exeext
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_retval=1
-fi
-  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
-  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
-  # interfere with the next link command; also delete a directory that is
-  # left behind by Apple's compiler.  We do this before executing the actions.
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_link
-
-# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists and can be compiled using the include files in
-# INCLUDES, setting the cache variable VAR accordingly.
-ac_fn_c_check_header_compile ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_compile
-
-# ac_fn_c_try_cpp LINENO
-# ----------------------
-# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_cpp ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    grep -v '^ *+' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-    mv -f conftest.er1 conftest.err
-  fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } > conftest.i && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-    ac_retval=1
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_cpp
-
-# ac_fn_c_try_run LINENO
-# ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
-ac_fn_c_try_run ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: program exited with status $ac_status" >&5
-       $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=$ac_status
-fi
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_run
-
-# ac_fn_c_check_func LINENO FUNC VAR
-# ----------------------------------
-# Tests whether FUNC exists, setting the cache variable VAR accordingly
-ac_fn_c_check_func ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $2 innocuous_$2
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $2 (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $2
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $2 ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$2 || defined __stub___$2
-choke me
-#endif
-
-int
-main ()
-{
-return $2 ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_func
-
-# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists, giving a warning if it cannot be compiled using
-# the include files in INCLUDES and setting the cache variable VAR
-# accordingly.
-ac_fn_c_check_header_mongrel ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval \${$3+:} false; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
-$as_echo_n "checking $2 usability... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_header_compiler=yes
-else
-  ac_header_compiler=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
-$as_echo "$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
-$as_echo_n "checking $2 presence... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <$2>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  ac_header_preproc=yes
-else
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
-$as_echo "$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
-  yes:no: )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-  no:yes:* )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
-$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
-$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-( $as_echo "## ------------------------------------ ##
-## Report this to libmicrohttpd@gnu.org ##
-## ------------------------------------ ##"
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=\$ac_header_compiler"
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_mongrel
-
-# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES
-# ----------------------------------------------------
-# Tries to find if the field MEMBER exists in type AGGR, after including
-# INCLUDES, setting cache variable VAR accordingly.
-ac_fn_c_check_member ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5
-$as_echo_n "checking for $2.$3... " >&6; }
-if eval \${$4+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$5
-int
-main ()
-{
-static $2 ac_aggr;
-if (ac_aggr.$3)
-return 0;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$4=yes"
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$5
-int
-main ()
-{
-static $2 ac_aggr;
-if (sizeof ac_aggr.$3)
-return 0;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$4=yes"
-else
-  eval "$4=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$4
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_member
-
-# ac_fn_c_check_decl LINENO SYMBOL VAR INCLUDES
-# ---------------------------------------------
-# Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR
-# accordingly.
-ac_fn_c_check_decl ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  as_decl_name=`echo $2|sed 's/ *(.*//'`
-  as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'`
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5
-$as_echo_n "checking whether $as_decl_name is declared... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-int
-main ()
-{
-#ifndef $as_decl_name
-#ifdef __cplusplus
-  (void) $as_decl_use;
-#else
-  (void) $as_decl_name;
-#endif
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$3=yes"
-else
-  eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_decl
-cat >config.log <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by libmicrohttpd $as_me 0.9.42, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  $ $0 $@
-
-_ACEOF
-exec 5>>config.log
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
-
-/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    $as_echo "PATH: $as_dir"
-  done
-IFS=$as_save_IFS
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
-  for ac_arg
-  do
-    case $ac_arg in
-    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
-    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-    | -silent | --silent | --silen | --sile | --sil)
-      continue ;;
-    *\'*)
-      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    case $ac_pass in
-    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
-    2)
-      as_fn_append ac_configure_args1 " '$ac_arg'"
-      if test $ac_must_keep_next = true; then
-	ac_must_keep_next=false # Got value, back to normal.
-      else
-	case $ac_arg in
-	  *=* | --config-cache | -C | -disable-* | --disable-* \
-	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
-	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
-	  | -with-* | --with-* | -without-* | --without-* | --x)
-	    case "$ac_configure_args0 " in
-	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
-	    esac
-	    ;;
-	  -* ) ac_must_keep_next=true ;;
-	esac
-      fi
-      as_fn_append ac_configure_args " '$ac_arg'"
-      ;;
-    esac
-  done
-done
-{ ac_configure_args0=; unset ac_configure_args0;}
-{ ac_configure_args1=; unset ac_configure_args1;}
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log.  We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Use '\'' to represent an apostrophe within the trap.
-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
-trap 'exit_status=$?
-  # Save into config.log some information that might help in debugging.
-  {
-    echo
-
-    $as_echo "## ---------------- ##
-## Cache variables. ##
-## ---------------- ##"
-    echo
-    # The following way of writing the cache mishandles newlines in values,
-(
-  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
-      *) { eval $ac_var=; unset $ac_var;} ;;
-      esac ;;
-    esac
-  done
-  (set) 2>&1 |
-    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      sed -n \
-	"s/'\''/'\''\\\\'\'''\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
-      ;; #(
-    *)
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-)
-    echo
-
-    $as_echo "## ----------------- ##
-## Output variables. ##
-## ----------------- ##"
-    echo
-    for ac_var in $ac_subst_vars
-    do
-      eval ac_val=\$$ac_var
-      case $ac_val in
-      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-      esac
-      $as_echo "$ac_var='\''$ac_val'\''"
-    done | sort
-    echo
-
-    if test -n "$ac_subst_files"; then
-      $as_echo "## ------------------- ##
-## File substitutions. ##
-## ------------------- ##"
-      echo
-      for ac_var in $ac_subst_files
-      do
-	eval ac_val=\$$ac_var
-	case $ac_val in
-	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-	esac
-	$as_echo "$ac_var='\''$ac_val'\''"
-      done | sort
-      echo
-    fi
-
-    if test -s confdefs.h; then
-      $as_echo "## ----------- ##
-## confdefs.h. ##
-## ----------- ##"
-      echo
-      cat confdefs.h
-      echo
-    fi
-    test "$ac_signal" != 0 &&
-      $as_echo "$as_me: caught signal $ac_signal"
-    $as_echo "$as_me: exit $exit_status"
-  } >&5
-  rm -f core *.core core.conftest.* &&
-    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
-    exit $exit_status
-' 0
-for ac_signal in 1 2 13 15; do
-  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -f -r conftest* confdefs.h
-
-$as_echo "/* confdefs.h */" > confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_URL "$PACKAGE_URL"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer an explicitly selected file to automatically selected ones.
-ac_site_file1=NONE
-ac_site_file2=NONE
-if test -n "$CONFIG_SITE"; then
-  # We do not want a PATH search for config.site.
-  case $CONFIG_SITE in #((
-    -*)  ac_site_file1=./$CONFIG_SITE;;
-    */*) ac_site_file1=$CONFIG_SITE;;
-    *)   ac_site_file1=./$CONFIG_SITE;;
-  esac
-elif test "x$prefix" != xNONE; then
-  ac_site_file1=$prefix/share/config.site
-  ac_site_file2=$prefix/etc/config.site
-else
-  ac_site_file1=$ac_default_prefix/share/config.site
-  ac_site_file2=$ac_default_prefix/etc/config.site
-fi
-for ac_site_file in "$ac_site_file1" "$ac_site_file2"
-do
-  test "x$ac_site_file" = xNONE && continue
-  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
-$as_echo "$as_me: loading site script $ac_site_file" >&6;}
-    sed 's/^/| /' "$ac_site_file" >&5
-    . "$ac_site_file" \
-      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5; }
-  fi
-done
-
-if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special files
-  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
-  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
-$as_echo "$as_me: loading cache $cache_file" >&6;}
-    case $cache_file in
-      [\\/]* | ?:[\\/]* ) . "$cache_file";;
-      *)                      . "./$cache_file";;
-    esac
-  fi
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
-$as_echo "$as_me: creating cache $cache_file" >&6;}
-  >$cache_file
-fi
-
-as_fn_append ac_func_list " memmem"
-as_fn_append ac_func_list " accept4"
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in $ac_precious_vars; do
-  eval ac_old_set=\$ac_cv_env_${ac_var}_set
-  eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val=\$ac_cv_env_${ac_var}_value
-  eval ac_new_val=\$ac_env_${ac_var}_value
-  case $ac_old_set,$ac_new_set in
-    set,)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,set)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,);;
-    *)
-      if test "x$ac_old_val" != "x$ac_new_val"; then
-	# differences in whitespace do not lead to failure.
-	ac_old_val_w=`echo x $ac_old_val`
-	ac_new_val_w=`echo x $ac_new_val`
-	if test "$ac_old_val_w" != "$ac_new_val_w"; then
-	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-	  ac_cache_corrupted=:
-	else
-	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
-	  eval $ac_var=\$ac_old_val
-	fi
-	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
-$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
-	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
-$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
-      fi;;
-  esac
-  # Pass precious variables to config.status.
-  if test "$ac_new_set" = set; then
-    case $ac_new_val in
-    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
-    *) ac_arg=$ac_var=$ac_new_val ;;
-    esac
-    case " $ac_configure_args " in
-      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
-    esac
-  fi
-done
-if $ac_cache_corrupted; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
-fi
-## -------------------- ##
-## Main body of script. ##
-## -------------------- ##
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-am__api_version='1.14'
-
-ac_aux_dir=
-for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
-  if test -f "$ac_dir/install-sh"; then
-    ac_aux_dir=$ac_dir
-    ac_install_sh="$ac_aux_dir/install-sh -c"
-    break
-  elif test -f "$ac_dir/install.sh"; then
-    ac_aux_dir=$ac_dir
-    ac_install_sh="$ac_aux_dir/install.sh -c"
-    break
-  elif test -f "$ac_dir/shtool"; then
-    ac_aux_dir=$ac_dir
-    ac_install_sh="$ac_aux_dir/shtool install -c"
-    break
-  fi
-done
-if test -z "$ac_aux_dir"; then
-  as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5
-fi
-
-# These three variables are undocumented and unsupported,
-# and are intended to be withdrawn in a future Autoconf release.
-# They can cause serious problems if a builder's source tree is in a directory
-# whose full name contains unusual characters.
-ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
-ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
-ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
-
-
-# Find a good install program.  We prefer a C program (faster),
-# so one script is as good as another.  But avoid the broken or
-# incompatible versions:
-# SysV /etc/install, /usr/sbin/install
-# SunOS /usr/etc/install
-# IRIX /sbin/install
-# AIX /bin/install
-# AmigaOS /C/install, which installs bootblocks on floppy discs
-# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
-# AFS /usr/afsws/bin/install, which mishandles nonexistent args
-# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
-# OS/2's system install, which has a completely different semantic
-# ./install, which can be erroneously created by make from ./install.sh.
-# Reject install programs that cannot install multiple files.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5
-$as_echo_n "checking for a BSD-compatible install... " >&6; }
-if test -z "$INSTALL"; then
-if ${ac_cv_path_install+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    # Account for people who put trailing slashes in PATH elements.
-case $as_dir/ in #((
-  ./ | .// | /[cC]/* | \
-  /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
-  ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \
-  /usr/ucb/* ) ;;
-  *)
-    # OSF1 and SCO ODT 3.0 have their own names for install.
-    # Don't use installbsd from OSF since it installs stuff as root
-    # by default.
-    for ac_prog in ginstall scoinst install; do
-      for ac_exec_ext in '' $ac_executable_extensions; do
-	if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then
-	  if test $ac_prog = install &&
-	    grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
-	    # AIX install.  It has an incompatible calling convention.
-	    :
-	  elif test $ac_prog = install &&
-	    grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
-	    # program-specific install script used by HP pwplus--don't use.
-	    :
-	  else
-	    rm -rf conftest.one conftest.two conftest.dir
-	    echo one > conftest.one
-	    echo two > conftest.two
-	    mkdir conftest.dir
-	    if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" &&
-	      test -s conftest.one && test -s conftest.two &&
-	      test -s conftest.dir/conftest.one &&
-	      test -s conftest.dir/conftest.two
-	    then
-	      ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
-	      break 3
-	    fi
-	  fi
-	fi
-      done
-    done
-    ;;
-esac
-
-  done
-IFS=$as_save_IFS
-
-rm -rf conftest.one conftest.two conftest.dir
-
-fi
-  if test "${ac_cv_path_install+set}" = set; then
-    INSTALL=$ac_cv_path_install
-  else
-    # As a last resort, use the slow shell script.  Don't cache a
-    # value for INSTALL within a source directory, because that will
-    # break other packages using the cache if that directory is
-    # removed, or if the value is a relative name.
-    INSTALL=$ac_install_sh
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5
-$as_echo "$INSTALL" >&6; }
-
-# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
-# It thinks the first close brace ends the variable substitution.
-test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
-
-test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
-
-test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5
-$as_echo_n "checking whether build environment is sane... " >&6; }
-# Reject unsafe characters in $srcdir or the absolute working directory
-# name.  Accept space and tab only in the latter.
-am_lf='
-'
-case `pwd` in
-  *[\\\"\#\$\&\'\`$am_lf]*)
-    as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;;
-esac
-case $srcdir in
-  *[\\\"\#\$\&\'\`$am_lf\ \	]*)
-    as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;;
-esac
-
-# Do 'set' in a subshell so we don't clobber the current shell's
-# arguments.  Must try -L first in case configure is actually a
-# symlink; some systems play weird games with the mod time of symlinks
-# (eg FreeBSD returns the mod time of the symlink's containing
-# directory).
-if (
-   am_has_slept=no
-   for am_try in 1 2; do
-     echo "timestamp, slept: $am_has_slept" > conftest.file
-     set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null`
-     if test "$*" = "X"; then
-	# -L didn't work.
-	set X `ls -t "$srcdir/configure" conftest.file`
-     fi
-     if test "$*" != "X $srcdir/configure conftest.file" \
-	&& test "$*" != "X conftest.file $srcdir/configure"; then
-
-	# If neither matched, then we have a broken ls.  This can happen
-	# if, for instance, CONFIG_SHELL is bash and it inherits a
-	# broken ls alias from the environment.  This has actually
-	# happened.  Such a system could not be considered "sane".
-	as_fn_error $? "ls -t appears to fail.  Make sure there is not a broken
-  alias in your environment" "$LINENO" 5
-     fi
-     if test "$2" = conftest.file || test $am_try -eq 2; then
-       break
-     fi
-     # Just in case.
-     sleep 1
-     am_has_slept=yes
-   done
-   test "$2" = conftest.file
-   )
-then
-   # Ok.
-   :
-else
-   as_fn_error $? "newly created file is older than distributed files!
-Check your system clock" "$LINENO" 5
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-# If we didn't sleep, we still need to ensure time stamps of config.status and
-# generated files are strictly newer.
-am_sleep_pid=
-if grep 'slept: no' conftest.file >/dev/null 2>&1; then
-  ( sleep 1 ) &
-  am_sleep_pid=$!
-fi
-
-rm -f conftest.file
-
-test "$program_prefix" != NONE &&
-  program_transform_name="s&^&$program_prefix&;$program_transform_name"
-# Use a double $ so make ignores it.
-test "$program_suffix" != NONE &&
-  program_transform_name="s&\$&$program_suffix&;$program_transform_name"
-# Double any \ or $.
-# By default was `s,x,x', remove it if useless.
-ac_script='s/[\\$]/&&/g;s/;s,x,x,$//'
-program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"`
-
-# Expand $ac_aux_dir to an absolute path.
-am_aux_dir=`cd "$ac_aux_dir" && pwd`
-
-if test x"${MISSING+set}" != xset; then
-  case $am_aux_dir in
-  *\ * | *\	*)
-    MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;;
-  *)
-    MISSING="\${SHELL} $am_aux_dir/missing" ;;
-  esac
-fi
-# Use eval to expand $SHELL
-if eval "$MISSING --is-lightweight"; then
-  am_missing_run="$MISSING "
-else
-  am_missing_run=
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5
-$as_echo "$as_me: WARNING: 'missing' script is too old or missing" >&2;}
-fi
-
-if test x"${install_sh}" != xset; then
-  case $am_aux_dir in
-  *\ * | *\	*)
-    install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;;
-  *)
-    install_sh="\${SHELL} $am_aux_dir/install-sh"
-  esac
-fi
-
-# Installed binaries are usually stripped using 'strip' when the user
-# run "make install-strip".  However 'strip' might not be the right
-# tool to use in cross-compilation environments, therefore Automake
-# will honor the 'STRIP' environment variable to overrule this program.
-if test "$cross_compiling" != no; then
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
-set dummy ${ac_tool_prefix}strip; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_STRIP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_STRIP="${ac_tool_prefix}strip"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-STRIP=$ac_cv_prog_STRIP
-if test -n "$STRIP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
-$as_echo "$STRIP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_STRIP"; then
-  ac_ct_STRIP=$STRIP
-  # Extract the first word of "strip", so it can be a program name with args.
-set dummy strip; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_STRIP"; then
-  ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_STRIP="strip"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
-if test -n "$ac_ct_STRIP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
-$as_echo "$ac_ct_STRIP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_STRIP" = x; then
-    STRIP=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    STRIP=$ac_ct_STRIP
-  fi
-else
-  STRIP="$ac_cv_prog_STRIP"
-fi
-
-fi
-INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5
-$as_echo_n "checking for a thread-safe mkdir -p... " >&6; }
-if test -z "$MKDIR_P"; then
-  if ${ac_cv_path_mkdir+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in mkdir gmkdir; do
-	 for ac_exec_ext in '' $ac_executable_extensions; do
-	   as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue
-	   case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #(
-	     'mkdir (GNU coreutils) '* | \
-	     'mkdir (coreutils) '* | \
-	     'mkdir (fileutils) '4.1*)
-	       ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext
-	       break 3;;
-	   esac
-	 done
-       done
-  done
-IFS=$as_save_IFS
-
-fi
-
-  test -d ./--version && rmdir ./--version
-  if test "${ac_cv_path_mkdir+set}" = set; then
-    MKDIR_P="$ac_cv_path_mkdir -p"
-  else
-    # As a last resort, use the slow shell script.  Don't cache a
-    # value for MKDIR_P within a source directory, because that will
-    # break other packages using the cache if that directory is
-    # removed, or if the value is a relative name.
-    MKDIR_P="$ac_install_sh -d"
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5
-$as_echo "$MKDIR_P" >&6; }
-
-for ac_prog in gawk mawk nawk awk
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AWK+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$AWK"; then
-  ac_cv_prog_AWK="$AWK" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_AWK="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-AWK=$ac_cv_prog_AWK
-if test -n "$AWK"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5
-$as_echo "$AWK" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$AWK" && break
-done
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
-set x ${MAKE-make}
-ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
-if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat >conftest.make <<\_ACEOF
-SHELL = /bin/sh
-all:
-	@echo '@@@%%%=$(MAKE)=@@@%%%'
-_ACEOF
-# GNU make sometimes prints "make[1]: Entering ...", which would confuse us.
-case `${MAKE-make} -f conftest.make 2>/dev/null` in
-  *@@@%%%=?*=@@@%%%*)
-    eval ac_cv_prog_make_${ac_make}_set=yes;;
-  *)
-    eval ac_cv_prog_make_${ac_make}_set=no;;
-esac
-rm -f conftest.make
-fi
-if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-  SET_MAKE=
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-rm -rf .tst 2>/dev/null
-mkdir .tst 2>/dev/null
-if test -d .tst; then
-  am__leading_dot=.
-else
-  am__leading_dot=_
-fi
-rmdir .tst 2>/dev/null
-
-# Check whether --enable-silent-rules was given.
-if test "${enable_silent_rules+set}" = set; then :
-  enableval=$enable_silent_rules;
-fi
-
-case $enable_silent_rules in # (((
-  yes) AM_DEFAULT_VERBOSITY=0;;
-   no) AM_DEFAULT_VERBOSITY=1;;
-    *) AM_DEFAULT_VERBOSITY=1;;
-esac
-am_make=${MAKE-make}
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5
-$as_echo_n "checking whether $am_make supports nested variables... " >&6; }
-if ${am_cv_make_support_nested_variables+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if $as_echo 'TRUE=$(BAR$(V))
-BAR0=false
-BAR1=true
-V=1
-am__doit:
-	@$(TRUE)
-.PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then
-  am_cv_make_support_nested_variables=yes
-else
-  am_cv_make_support_nested_variables=no
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5
-$as_echo "$am_cv_make_support_nested_variables" >&6; }
-if test $am_cv_make_support_nested_variables = yes; then
-    AM_V='$(V)'
-  AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)'
-else
-  AM_V=$AM_DEFAULT_VERBOSITY
-  AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY
-fi
-AM_BACKSLASH='\'
-
-if test "`cd $srcdir && pwd`" != "`pwd`"; then
-  # Use -I$(srcdir) only when $(srcdir) != ., so that make's output
-  # is not polluted with repeated "-I."
-  am__isrc=' -I$(srcdir)'
-  # test to see if srcdir already configured
-  if test -f $srcdir/config.status; then
-    as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5
-  fi
-fi
-
-# test whether we have cygpath
-if test -z "$CYGPATH_W"; then
-  if (cygpath --version) >/dev/null 2>/dev/null; then
-    CYGPATH_W='cygpath -w'
-  else
-    CYGPATH_W=echo
-  fi
-fi
-
-
-# Define the identity of the package.
- PACKAGE='libmicrohttpd'
- VERSION='0.9.42'
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE "$PACKAGE"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define VERSION "$VERSION"
-_ACEOF
-
-# Some tools Automake needs.
-
-ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"}
-
-
-AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"}
-
-
-AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"}
-
-
-AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"}
-
-
-MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"}
-
-# For better backward compatibility.  To be removed once Automake 1.9.x
-# dies out for good.  For more background, see:
-# <http://lists.gnu.org/archive/html/automake/2012-07/msg00001.html>
-# <http://lists.gnu.org/archive/html/automake/2012-07/msg00014.html>
-mkdir_p='$(MKDIR_P)'
-
-# We need awk for the "check" target.  The system "awk" is bad on
-# some platforms.
-# Always define AMTAR for backward compatibility.  Yes, it's still used
-# in the wild :-(  We should find a proper way to deprecate it ...
-AMTAR='$${TAR-tar}'
-
-
-# We'll loop over all known methods to create a tar archive until one works.
-_am_tools='gnutar  pax cpio none'
-
-am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'
-
-
-
-
-
-
-# POSIX will say in a future version that running "rm -f" with no argument
-# is OK; and we want to be able to make that assumption in our Makefile
-# recipes.  So use an aggressive probe to check that the usage we want is
-# actually supported "in the wild" to an acceptable degree.
-# See automake bug#10828.
-# To make any issue more visible, cause the running configure to be aborted
-# by default if the 'rm' program in use doesn't match our expectations; the
-# user can still override this though.
-if rm -f && rm -fr && rm -rf; then : OK; else
-  cat >&2 <<'END'
-Oops!
-
-Your 'rm' program seems unable to run without file operands specified
-on the command line, even when the '-f' option is present.  This is contrary
-to the behaviour of most rm programs out there, and not conforming with
-the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542>
-
-Please tell bug-automake@gnu.org about your system, including the value
-of your $PATH and any error possibly output before this message.  This
-can help us improve future automake versions.
-
-END
-  if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then
-    echo 'Configuration will proceed anyway, since you have set the' >&2
-    echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2
-    echo >&2
-  else
-    cat >&2 <<'END'
-Aborting the configuration process, to ensure you take notice of the issue.
-
-You can download and install GNU coreutils to get an 'rm' implementation
-that behaves properly: <http://www.gnu.org/software/coreutils/>.
-
-If you want to complete the configuration process using your problematic
-'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM
-to "yes", and re-run configure.
-
-END
-    as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5
-  fi
-fi
-
-ac_config_headers="$ac_config_headers MHD_config.h"
-
-
-
-
-LIB_VERSION_CURRENT=42
-LIB_VERSION_REVISION=0
-LIB_VERSION_AGE=32
-
-
-
-
-LIBSPDY_VERSION_CURRENT=0
-LIBSPDY_VERSION_REVISION=0
-LIBSPDY_VERSION_AGE=0
-
-
-
-
-
-if test `uname -s` = "OS/390"
-then
-# configure binaries for z/OS
-  if test -z "$CC"
-  then
-    CC=`pwd`"/contrib/xcc"
-    chmod +x $CC || true
-  fi
-  if test -z "$CPP"
-  then
-    CPP="c89 -E"
-  fi
-  if test -z "$CXXCPP"
-  then
-    CXXCPP="c++ -E -+"
-  fi
-#  _CCC_CCMODE=1
-#  _C89_CCMODE=1
-fi
-
-# Checks for programs.
-for ac_prog in gawk mawk nawk awk
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AWK+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$AWK"; then
-  ac_cv_prog_AWK="$AWK" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_AWK="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-AWK=$ac_cv_prog_AWK
-if test -n "$AWK"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5
-$as_echo "$AWK" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$AWK" && break
-done
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5
-$as_echo_n "checking whether ln -s works... " >&6; }
-LN_S=$as_ln_s
-if test "$LN_S" = "ln -s"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5
-$as_echo "no, using $LN_S" >&6; }
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
-set x ${MAKE-make}
-ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
-if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat >conftest.make <<\_ACEOF
-SHELL = /bin/sh
-all:
-	@echo '@@@%%%=$(MAKE)=@@@%%%'
-_ACEOF
-# GNU make sometimes prints "make[1]: Entering ...", which would confuse us.
-case `${MAKE-make} -f conftest.make 2>/dev/null` in
-  *@@@%%%=?*=@@@%%%*)
-    eval ac_cv_prog_make_${ac_make}_set=yes;;
-  *)
-    eval ac_cv_prog_make_${ac_make}_set=no;;
-esac
-rm -f conftest.make
-fi
-if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-  SET_MAKE=
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-  SET_MAKE="MAKE=${MAKE-make}"
-fi
-
-# Make sure we can run config.sub.
-$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
-  as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
-$as_echo_n "checking build system type... " >&6; }
-if ${ac_cv_build+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_build_alias=$build_alias
-test "x$ac_build_alias" = x &&
-  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
-test "x$ac_build_alias" = x &&
-  as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
-ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
-  as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
-$as_echo "$ac_cv_build" >&6; }
-case $ac_cv_build in
-*-*-*) ;;
-*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
-esac
-build=$ac_cv_build
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_build
-shift
-build_cpu=$1
-build_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-build_os=$*
-IFS=$ac_save_IFS
-case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
-$as_echo_n "checking host system type... " >&6; }
-if ${ac_cv_host+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test "x$host_alias" = x; then
-  ac_cv_host=$ac_cv_build
-else
-  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
-    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
-$as_echo "$ac_cv_host" >&6; }
-case $ac_cv_host in
-*-*-*) ;;
-*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
-esac
-host=$ac_cv_host
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_host
-shift
-host_cpu=$1
-host_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-host_os=$*
-IFS=$ac_save_IFS
-case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
-
-
-DEPDIR="${am__leading_dot}deps"
-
-ac_config_commands="$ac_config_commands depfiles"
-
-
-am_make=${MAKE-make}
-cat > confinc << 'END'
-am__doit:
-	@echo this is the am__doit target
-.PHONY: am__doit
-END
-# If we don't find an include directive, just comment out the code.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5
-$as_echo_n "checking for style of include used by $am_make... " >&6; }
-am__include="#"
-am__quote=
-_am_result=none
-# First try GNU make style include.
-echo "include confinc" > confmf
-# Ignore all kinds of additional output from 'make'.
-case `$am_make -s -f confmf 2> /dev/null` in #(
-*the\ am__doit\ target*)
-  am__include=include
-  am__quote=
-  _am_result=GNU
-  ;;
-esac
-# Now try BSD make style include.
-if test "$am__include" = "#"; then
-   echo '.include "confinc"' > confmf
-   case `$am_make -s -f confmf 2> /dev/null` in #(
-   *the\ am__doit\ target*)
-     am__include=.include
-     am__quote="\""
-     _am_result=BSD
-     ;;
-   esac
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5
-$as_echo "$_am_result" >&6; }
-rm -f confinc confmf
-
-# Check whether --enable-dependency-tracking was given.
-if test "${enable_dependency_tracking+set}" = set; then :
-  enableval=$enable_dependency_tracking;
-fi
-
-if test "x$enable_dependency_tracking" != xno; then
-  am_depcomp="$ac_aux_dir/depcomp"
-  AMDEPBACKSLASH='\'
-  am__nodep='_no'
-fi
- if test "x$enable_dependency_tracking" != xno; then
-  AMDEP_TRUE=
-  AMDEP_FALSE='#'
-else
-  AMDEP_TRUE='#'
-  AMDEP_FALSE=
-fi
-
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
-  # Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
-else
-  CC="$ac_cv_prog_CC"
-fi
-
-if test -z "$CC"; then
-          if test -n "$ac_tool_prefix"; then
-    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="${ac_tool_prefix}cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  fi
-fi
-if test -z "$CC"; then
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-  ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
-       ac_prog_rejected=yes
-       continue
-     fi
-    ac_cv_prog_CC="cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-if test $ac_prog_rejected = yes; then
-  # We found a bogon in the path, so make sure we never use it.
-  set dummy $ac_cv_prog_CC
-  shift
-  if test $# != 0; then
-    # We chose a different compiler from the bogus one.
-    # However, it has the same basename, so the bogon will be chosen
-    # first if we set CC to just the basename; use the full file name.
-    shift
-    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
-  fi
-fi
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl.exe
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$CC"; then
-  ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-    test -n "$CC" && break
-  done
-fi
-if test -z "$CC"; then
-  ac_ct_CC=$CC
-  for ac_prog in cl.exe
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$ac_ct_CC" && break
-done
-
-  if test "x$ac_ct_CC" = x; then
-    CC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    CC=$ac_ct_CC
-  fi
-fi
-
-fi
-
-
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5; }
-
-# Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
-set X $ac_compile
-ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
-  { { ac_try="$ac_compiler $ac_option >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
-  ac_status=$?
-  if test -s conftest.err; then
-    sed '10a\
-... rest of stderr output deleted ...
-         10q' conftest.err >conftest.er1
-    cat conftest.er1 >&5
-  fi
-  rm -f conftest.er1 conftest.err
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-done
-
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
-$as_echo_n "checking whether the C compiler works... " >&6; }
-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-
-# The possible output files:
-ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
-
-ac_rmfiles=
-for ac_file in $ac_files
-do
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
-    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
-  esac
-done
-rm -f $ac_rmfiles
-
-if { { ac_try="$ac_link_default"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link_default") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
-# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
-# in a Makefile.  We should not override ac_cv_exeext if it was cached,
-# so that the user can short-circuit this test for compilers unknown to
-# Autoconf.
-for ac_file in $ac_files ''
-do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
-	;;
-    [ab].out )
-	# We found the default executable, but exeext='' is most
-	# certainly right.
-	break;;
-    *.* )
-	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
-	then :; else
-	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-	fi
-	# We set ac_cv_exeext here because the later test for it is not
-	# safe: cross compilers may not add the suffix if given an `-o'
-	# argument, so we may need to know it at that point already.
-	# Even if this section looks crufty: it has the advantage of
-	# actually working.
-	break;;
-    * )
-	break;;
-  esac
-done
-test "$ac_cv_exeext" = no && ac_cv_exeext=
-
-else
-  ac_file=''
-fi
-if test -z "$ac_file"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-$as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
-$as_echo_n "checking for C compiler default output file name... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
-$as_echo "$ac_file" >&6; }
-ac_exeext=$ac_cv_exeext
-
-rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
-$as_echo_n "checking for suffix of executables... " >&6; }
-if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  # If both `conftest.exe' and `conftest' are `present' (well, observable)
-# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
-# work properly (i.e., refer to `conftest.exe'), while it won't with
-# `rm'.
-for ac_file in conftest.exe conftest conftest.*; do
-  test -f "$ac_file" || continue
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
-    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-	  break;;
-    * ) break;;
-  esac
-done
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest conftest$ac_cv_exeext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
-$as_echo "$ac_cv_exeext" >&6; }
-
-rm -f conftest.$ac_ext
-EXEEXT=$ac_cv_exeext
-ac_exeext=$EXEEXT
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdio.h>
-int
-main ()
-{
-FILE *f = fopen ("conftest.out", "w");
- return ferror (f) || fclose (f) != 0;
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files="$ac_clean_files conftest.out"
-# Check that the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
-$as_echo_n "checking whether we are cross compiling... " >&6; }
-if test "$cross_compiling" != yes; then
-  { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-  if { ac_try='./conftest$ac_cv_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then
-    cross_compiling=no
-  else
-    if test "$cross_compiling" = maybe; then
-	cross_compiling=yes
-    else
-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5; }
-    fi
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
-$as_echo "$cross_compiling" >&6; }
-
-rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
-$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { { ac_try="$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_compile") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
-  for ac_file in conftest.o conftest.obj conftest.*; do
-  test -f "$ac_file" || continue;
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
-    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
-       break;;
-  esac
-done
-else
-  $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest.$ac_cv_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
-$as_echo "$ac_cv_objext" >&6; }
-OBJEXT=$ac_cv_objext
-ac_objext=$OBJEXT
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-#ifndef __GNUC__
-       choke me
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_compiler_gnu=yes
-else
-  ac_compiler_gnu=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_c_compiler_gnu=$ac_compiler_gnu
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
-if test $ac_compiler_gnu = yes; then
-  GCC=yes
-else
-  GCC=
-fi
-ac_test_CFLAGS=${CFLAGS+set}
-ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_save_c_werror_flag=$ac_c_werror_flag
-   ac_c_werror_flag=yes
-   ac_cv_prog_cc_g=no
-   CFLAGS="-g"
-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_g=yes
-else
-  CFLAGS=""
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  ac_c_werror_flag=$ac_save_c_werror_flag
-	 CFLAGS="-g"
-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_g=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-   ac_c_werror_flag=$ac_save_c_werror_flag
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
-  CFLAGS=$ac_save_CFLAGS
-elif test $ac_cv_prog_cc_g = yes; then
-  if test "$GCC" = yes; then
-    CFLAGS="-g -O2"
-  else
-    CFLAGS="-g"
-  fi
-else
-  if test "$GCC" = yes; then
-    CFLAGS="-O2"
-  else
-    CFLAGS=
-  fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_prog_cc_c89=no
-ac_save_CC=$CC
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdarg.h>
-#include <stdio.h>
-struct stat;
-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
-struct buf { int x; };
-FILE * (*rcsopen) (struct buf *, struct stat *, int);
-static char *e (p, i)
-     char **p;
-     int i;
-{
-  return p[i];
-}
-static char *f (char * (*g) (char **, int), char **p, ...)
-{
-  char *s;
-  va_list v;
-  va_start (v,p);
-  s = g (p, va_arg (v,int));
-  va_end (v);
-  return s;
-}
-
-/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
-   function prototypes and stuff, but not '\xHH' hex character constants.
-   These don't provoke an error unfortunately, instead are silently treated
-   as 'x'.  The following induces an error, until -std is added to get
-   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
-   array size at least.  It's necessary to write '\x00'==0 to get something
-   that's true only with -std.  */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
-
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
-   inside strings and character constants.  */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
-
-int test (int i, double x);
-struct s1 {int (*f) (int a);};
-struct s2 {int (*f) (double a);};
-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
-int argc;
-char **argv;
-int
-main ()
-{
-return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
-  ;
-  return 0;
-}
-_ACEOF
-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
-	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
-do
-  CC="$ac_save_CC $ac_arg"
-  if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_prog_cc_c89=$ac_arg
-fi
-rm -f core conftest.err conftest.$ac_objext
-  test "x$ac_cv_prog_cc_c89" != "xno" && break
-done
-rm -f conftest.$ac_ext
-CC=$ac_save_CC
-
-fi
-# AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
-  x)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
-  xno)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
-  *)
-    CC="$CC $ac_cv_prog_cc_c89"
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
-esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
-
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5
-$as_echo_n "checking whether $CC understands -c and -o together... " >&6; }
-if ${am_cv_prog_cc_c_o+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-  # Make sure it works both with $CC and with simple cc.
-  # Following AC_PROG_CC_C_O, we do the test twice because some
-  # compilers refuse to overwrite an existing .o file with -o,
-  # though they will create one.
-  am_cv_prog_cc_c_o=yes
-  for am_i in 1 2; do
-    if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5
-   ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5
-   ac_status=$?
-   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-   (exit $ac_status); } \
-         && test -f conftest2.$ac_objext; then
-      : OK
-    else
-      am_cv_prog_cc_c_o=no
-      break
-    fi
-  done
-  rm -f core conftest*
-  unset am_i
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5
-$as_echo "$am_cv_prog_cc_c_o" >&6; }
-if test "$am_cv_prog_cc_c_o" != yes; then
-   # Losing compiler, so override with the script.
-   # FIXME: It is wrong to rewrite CC.
-   # But if we don't then we get into trouble of one sort or another.
-   # A longer-term fix would be to have automake use am__CC in this case,
-   # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
-   CC="$am_aux_dir/compile $CC"
-fi
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-depcc="$CC"   am_compiler_list=
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5
-$as_echo_n "checking dependency style of $depcc... " >&6; }
-if ${am_cv_CC_dependencies_compiler_type+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
-  # We make a subdir and do the tests there.  Otherwise we can end up
-  # making bogus files that we don't know about and never remove.  For
-  # instance it was reported that on HP-UX the gcc test will end up
-  # making a dummy file named 'D' -- because '-MD' means "put the output
-  # in D".
-  rm -rf conftest.dir
-  mkdir conftest.dir
-  # Copy depcomp to subdir because otherwise we won't find it if we're
-  # using a relative directory.
-  cp "$am_depcomp" conftest.dir
-  cd conftest.dir
-  # We will build objects and dependencies in a subdirectory because
-  # it helps to detect inapplicable dependency modes.  For instance
-  # both Tru64's cc and ICC support -MD to output dependencies as a
-  # side effect of compilation, but ICC will put the dependencies in
-  # the current directory while Tru64 will put them in the object
-  # directory.
-  mkdir sub
-
-  am_cv_CC_dependencies_compiler_type=none
-  if test "$am_compiler_list" = ""; then
-     am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp`
-  fi
-  am__universal=false
-  case " $depcc " in #(
-     *\ -arch\ *\ -arch\ *) am__universal=true ;;
-     esac
-
-  for depmode in $am_compiler_list; do
-    # Setup a source with many dependencies, because some compilers
-    # like to wrap large dependency lists on column 80 (with \), and
-    # we should not choose a depcomp mode which is confused by this.
-    #
-    # We need to recreate these files for each test, as the compiler may
-    # overwrite some of them when testing with obscure command lines.
-    # This happens at least with the AIX C compiler.
-    : > sub/conftest.c
-    for i in 1 2 3 4 5 6; do
-      echo '#include "conftst'$i'.h"' >> sub/conftest.c
-      # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with
-      # Solaris 10 /bin/sh.
-      echo '/* dummy */' > sub/conftst$i.h
-    done
-    echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
-
-    # We check with '-c' and '-o' for the sake of the "dashmstdout"
-    # mode.  It turns out that the SunPro C++ compiler does not properly
-    # handle '-M -o', and we need to detect this.  Also, some Intel
-    # versions had trouble with output in subdirs.
-    am__obj=sub/conftest.${OBJEXT-o}
-    am__minus_obj="-o $am__obj"
-    case $depmode in
-    gcc)
-      # This depmode causes a compiler race in universal mode.
-      test "$am__universal" = false || continue
-      ;;
-    nosideeffect)
-      # After this tag, mechanisms are not by side-effect, so they'll
-      # only be used when explicitly requested.
-      if test "x$enable_dependency_tracking" = xyes; then
-	continue
-      else
-	break
-      fi
-      ;;
-    msvc7 | msvc7msys | msvisualcpp | msvcmsys)
-      # This compiler won't grok '-c -o', but also, the minuso test has
-      # not run yet.  These depmodes are late enough in the game, and
-      # so weak that their functioning should not be impacted.
-      am__obj=conftest.${OBJEXT-o}
-      am__minus_obj=
-      ;;
-    none) break ;;
-    esac
-    if depmode=$depmode \
-       source=sub/conftest.c object=$am__obj \
-       depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
-       $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \
-         >/dev/null 2>conftest.err &&
-       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
-       grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
-       grep $am__obj sub/conftest.Po > /dev/null 2>&1 &&
-       ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
-      # icc doesn't choke on unknown options, it will just issue warnings
-      # or remarks (even with -Werror).  So we grep stderr for any message
-      # that says an option was ignored or not supported.
-      # When given -MP, icc 7.0 and 7.1 complain thusly:
-      #   icc: Command line warning: ignoring option '-M'; no argument required
-      # The diagnosis changed in icc 8.0:
-      #   icc: Command line remark: option '-MP' not supported
-      if (grep 'ignoring option' conftest.err ||
-          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
-        am_cv_CC_dependencies_compiler_type=$depmode
-        break
-      fi
-    fi
-  done
-
-  cd ..
-  rm -rf conftest.dir
-else
-  am_cv_CC_dependencies_compiler_type=none
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5
-$as_echo "$am_cv_CC_dependencies_compiler_type" >&6; }
-CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type
-
- if
-  test "x$enable_dependency_tracking" != xno \
-  && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then
-  am__fastdepCC_TRUE=
-  am__fastdepCC_FALSE='#'
-else
-  am__fastdepCC_TRUE='#'
-  am__fastdepCC_FALSE=
-fi
-
-
-
-case `pwd` in
-  *\ * | *\	*)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5
-$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;;
-esac
-
-
-
-macro_version='2.4.2'
-macro_revision='1.3337'
-
-
-
-
-
-
-
-
-
-
-
-
-
-ltmain="$ac_aux_dir/ltmain.sh"
-
-# Backslashify metacharacters that are still active within
-# double-quoted strings.
-sed_quote_subst='s/\(["`$\\]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\(["`\\]\)/\\\1/g'
-
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
-
-# Sed substitution to delay expansion of an escaped single quote.
-delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
-
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst='s/\*/\\\*/g'
-
-ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5
-$as_echo_n "checking how to print strings... " >&6; }
-# Test print first, because it will be a builtin if present.
-if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
-   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='print -r --'
-elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='printf %s\n'
-else
-  # Use this function as a fallback that always works.
-  func_fallback_echo ()
-  {
-    eval 'cat <<_LTECHO_EOF
-$1
-_LTECHO_EOF'
-  }
-  ECHO='func_fallback_echo'
-fi
-
-# func_echo_all arg...
-# Invoke $ECHO with all args, space-separated.
-func_echo_all ()
-{
-    $ECHO ""
-}
-
-case "$ECHO" in
-  printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5
-$as_echo "printf" >&6; } ;;
-  print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5
-$as_echo "print -r" >&6; } ;;
-  *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5
-$as_echo "cat" >&6; } ;;
-esac
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
-$as_echo_n "checking for a sed that does not truncate output... " >&6; }
-if ${ac_cv_path_SED+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-            ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
-     for ac_i in 1 2 3 4 5 6 7; do
-       ac_script="$ac_script$as_nl$ac_script"
-     done
-     echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
-     { ac_script=; unset ac_script;}
-     if test -z "$SED"; then
-  ac_path_SED_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in sed gsed; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_SED="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_SED" || continue
-# Check for GNU ac_path_SED and select it if it is found.
-  # Check for GNU $ac_path_SED
-case `"$ac_path_SED" --version 2>&1` in
-*GNU*)
-  ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo '' >> "conftest.nl"
-    "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_SED_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_SED="$ac_path_SED"
-      ac_path_SED_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_SED_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_SED"; then
-    as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5
-  fi
-else
-  ac_cv_path_SED=$SED
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5
-$as_echo "$ac_cv_path_SED" >&6; }
- SED="$ac_cv_path_SED"
-  rm -f conftest.sed
-
-test -z "$SED" && SED=sed
-Xsed="$SED -e 1s/^X//"
-
-
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
-$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if ${ac_cv_path_GREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$GREP"; then
-  ac_path_GREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in grep ggrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_GREP" || continue
-# Check for GNU ac_path_GREP and select it if it is found.
-  # Check for GNU $ac_path_GREP
-case `"$ac_path_GREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'GREP' >> "conftest.nl"
-    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_GREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_GREP="$ac_path_GREP"
-      ac_path_GREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_GREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_GREP"; then
-    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_GREP=$GREP
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
-$as_echo "$ac_cv_path_GREP" >&6; }
- GREP="$ac_cv_path_GREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
-$as_echo_n "checking for egrep... " >&6; }
-if ${ac_cv_path_EGREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
-   then ac_cv_path_EGREP="$GREP -E"
-   else
-     if test -z "$EGREP"; then
-  ac_path_EGREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in egrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_EGREP" || continue
-# Check for GNU ac_path_EGREP and select it if it is found.
-  # Check for GNU $ac_path_EGREP
-case `"$ac_path_EGREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'EGREP' >> "conftest.nl"
-    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_EGREP="$ac_path_EGREP"
-      ac_path_EGREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_EGREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_EGREP"; then
-    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_EGREP=$EGREP
-fi
-
-   fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
-$as_echo "$ac_cv_path_EGREP" >&6; }
- EGREP="$ac_cv_path_EGREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
-$as_echo_n "checking for fgrep... " >&6; }
-if ${ac_cv_path_FGREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
-   then ac_cv_path_FGREP="$GREP -F"
-   else
-     if test -z "$FGREP"; then
-  ac_path_FGREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in fgrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_FGREP" || continue
-# Check for GNU ac_path_FGREP and select it if it is found.
-  # Check for GNU $ac_path_FGREP
-case `"$ac_path_FGREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'FGREP' >> "conftest.nl"
-    "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_FGREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_FGREP="$ac_path_FGREP"
-      ac_path_FGREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_FGREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_FGREP"; then
-    as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_FGREP=$FGREP
-fi
-
-   fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5
-$as_echo "$ac_cv_path_FGREP" >&6; }
- FGREP="$ac_cv_path_FGREP"
-
-
-test -z "$GREP" && GREP=grep
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-# Check whether --with-gnu-ld was given.
-if test "${with_gnu_ld+set}" = set; then :
-  withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes
-else
-  with_gnu_ld=no
-fi
-
-ac_prog=ld
-if test "$GCC" = yes; then
-  # Check if gcc -print-prog-name=ld gives a path.
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
-$as_echo_n "checking for ld used by $CC... " >&6; }
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [\\/]* | ?:[\\/]*)
-      re_direlt='/[^/][^/]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
-      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD="$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=ld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=unknown
-    ;;
-  esac
-elif test "$with_gnu_ld" = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
-$as_echo_n "checking for GNU ld... " >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
-$as_echo_n "checking for non-GNU ld... " >&6; }
-fi
-if ${lt_cv_path_LD+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
-	;;
-      *)
-	test "$with_gnu_ld" != yes && break
-	;;
-      esac
-    fi
-  done
-  IFS="$lt_save_ifs"
-else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
-fi
-fi
-
-LD="$lt_cv_path_LD"
-if test -n "$LD"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
-$as_echo "$LD" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5
-$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
-if ${lt_cv_prog_gnu_ld+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  # I'd rather use --version here, but apparently some GNU lds only accept -v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=yes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=no
-  ;;
-esac
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5
-$as_echo "$lt_cv_prog_gnu_ld" >&6; }
-with_gnu_ld=$lt_cv_prog_gnu_ld
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5
-$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; }
-if ${lt_cv_path_NM+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM="$NM"
-else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
-	  break
-	  ;;
-	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
-	  ;;
-	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
-  done
-  : ${lt_cv_path_NM=no}
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5
-$as_echo "$lt_cv_path_NM" >&6; }
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
-else
-  # Didn't find any BSD compatible name lister, look for dumpbin.
-  if test -n "$DUMPBIN"; then :
-    # Let the user override the test.
-  else
-    if test -n "$ac_tool_prefix"; then
-  for ac_prog in dumpbin "link -dump"
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_DUMPBIN+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$DUMPBIN"; then
-  ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-DUMPBIN=$ac_cv_prog_DUMPBIN
-if test -n "$DUMPBIN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5
-$as_echo "$DUMPBIN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-    test -n "$DUMPBIN" && break
-  done
-fi
-if test -z "$DUMPBIN"; then
-  ac_ct_DUMPBIN=$DUMPBIN
-  for ac_prog in dumpbin "link -dump"
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_DUMPBIN"; then
-  ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_DUMPBIN="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN
-if test -n "$ac_ct_DUMPBIN"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5
-$as_echo "$ac_ct_DUMPBIN" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$ac_ct_DUMPBIN" && break
-done
-
-  if test "x$ac_ct_DUMPBIN" = x; then
-    DUMPBIN=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    DUMPBIN=$ac_ct_DUMPBIN
-  fi
-fi
-
-    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
-    *COFF*)
-      DUMPBIN="$DUMPBIN -symbols"
-      ;;
-    *)
-      DUMPBIN=:
-      ;;
-    esac
-  fi
-
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
-  fi
-fi
-test -z "$NM" && NM=nm
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5
-$as_echo_n "checking the name lister ($NM) interface... " >&6; }
-if ${lt_cv_nm_interface+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_nm_interface="BSD nm"
-  echo "int some_variable = 0;" > conftest.$ac_ext
-  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5)
-  (eval "$ac_compile" 2>conftest.err)
-  cat conftest.err >&5
-  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
-  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
-  cat conftest.err >&5
-  (eval echo "\"\$as_me:$LINENO: output\"" >&5)
-  cat conftest.out >&5
-  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
-    lt_cv_nm_interface="MS dumpbin"
-  fi
-  rm -f conftest*
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5
-$as_echo "$lt_cv_nm_interface" >&6; }
-
-# find the maximum length of command line arguments
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5
-$as_echo_n "checking the maximum length of command line arguments... " >&6; }
-if ${lt_cv_sys_max_cmd_len+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-    i=0
-  teststring="ABCD"
-
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
-    ;;
-
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=-1;
-    ;;
-
-  cygwin* | mingw* | cegcc*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # Instead, let's just punt: use the minimum linelength reported by
-    # all of the supported platforms: 8192 (on NT/2K/XP).
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  mint*)
-    # On MiNT this can take a long time and run out of memory.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
-    ;;
-
-  os2*)
-    # The test takes a long time on OS/2.
-    lt_cv_sys_max_cmd_len=8192
-    ;;
-
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[	 ]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
-  *)
-    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
-    if test -n "$lt_cv_sys_max_cmd_len" && \
-	test undefined != "$lt_cv_sys_max_cmd_len"; then
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    else
-      # Make teststring a little bigger before we do anything with it.
-      # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
-        teststring=$teststring$teststring
-      done
-      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
-      # If test is not a shell built-in, we'll probably end up computing a
-      # maximum length that is only half of the actual maximum length, but
-      # we can't tell.
-      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
-	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
-	      test $i != 17 # 1/2 MB should be enough
-      do
-        i=`expr $i + 1`
-        teststring=$teststring$teststring
-      done
-      # Only check the string length outside the loop.
-      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
-      teststring=
-      # Add a significant safety factor because C++ compilers can tack on
-      # massive amounts of additional arguments before passing them to the
-      # linker.  It appears as though 1/2 is a usable value.
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
-    fi
-    ;;
-  esac
-
-fi
-
-if test -n $lt_cv_sys_max_cmd_len ; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5
-$as_echo "$lt_cv_sys_max_cmd_len" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
-$as_echo "none" >&6; }
-fi
-max_cmd_len=$lt_cv_sys_max_cmd_len
-
-
-
-
-
-
-: ${CP="cp -f"}
-: ${MV="mv -f"}
-: ${RM="rm -f"}
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5
-$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; }
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,b/c, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5
-$as_echo "$xsi_shell" >&6; }
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5
-$as_echo_n "checking whether the shell understands \"+=\"... " >&6; }
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5
-$as_echo "$lt_shell_append" >&6; }
-
-
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  lt_unset=unset
-else
-  lt_unset=false
-fi
-
-
-
-
-
-# test EBCDIC or ASCII
-case `echo X|tr X '\101'` in
- A) # ASCII based system
-    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
-  lt_SP2NL='tr \040 \012'
-  lt_NL2SP='tr \015\012 \040\040'
-  ;;
- *) # EBCDIC based system
-  lt_SP2NL='tr \100 \n'
-  lt_NL2SP='tr \r\n \100\100'
-  ;;
-esac
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5
-$as_echo_n "checking how to convert $build file names to $host format... " >&6; }
-if ${lt_cv_to_host_file_cmd+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
-        ;;
-    esac
-    ;;
-  *-*-cygwin* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_noop
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
-        ;;
-    esac
-    ;;
-  * ) # unhandled hosts (and "normal" native builds)
-    lt_cv_to_host_file_cmd=func_convert_file_noop
-    ;;
-esac
-
-fi
-
-to_host_file_cmd=$lt_cv_to_host_file_cmd
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5
-$as_echo "$lt_cv_to_host_file_cmd" >&6; }
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5
-$as_echo_n "checking how to convert $build file names to toolchain format... " >&6; }
-if ${lt_cv_to_tool_file_cmd+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  #assume ordinary cross tools, or native build.
-lt_cv_to_tool_file_cmd=func_convert_file_noop
-case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
-        ;;
-    esac
-    ;;
-esac
-
-fi
-
-to_tool_file_cmd=$lt_cv_to_tool_file_cmd
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5
-$as_echo "$lt_cv_to_tool_file_cmd" >&6; }
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5
-$as_echo_n "checking for $LD option to reload object files... " >&6; }
-if ${lt_cv_ld_reload_flag+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_ld_reload_flag='-r'
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5
-$as_echo "$lt_cv_ld_reload_flag" >&6; }
-reload_flag=$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=" $reload_flag" ;;
-esac
-reload_cmds='$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    if test "$GCC" != yes; then
-      reload_cmds=false
-    fi
-    ;;
-  darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
-    else
-      reload_cmds='$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
-
-
-
-
-
-
-
-
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
-set dummy ${ac_tool_prefix}objdump; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_OBJDUMP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$OBJDUMP"; then
-  ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-OBJDUMP=$ac_cv_prog_OBJDUMP
-if test -n "$OBJDUMP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5
-$as_echo "$OBJDUMP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_OBJDUMP"; then
-  ac_ct_OBJDUMP=$OBJDUMP
-  # Extract the first word of "objdump", so it can be a program name with args.
-set dummy objdump; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_OBJDUMP"; then
-  ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_OBJDUMP="objdump"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP
-if test -n "$ac_ct_OBJDUMP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5
-$as_echo "$ac_ct_OBJDUMP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_OBJDUMP" = x; then
-    OBJDUMP="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    OBJDUMP=$ac_ct_OBJDUMP
-  fi
-else
-  OBJDUMP="$ac_cv_prog_OBJDUMP"
-fi
-
-test -z "$OBJDUMP" && OBJDUMP=objdump
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5
-$as_echo_n "checking how to recognize dependent libraries... " >&6; }
-if ${lt_cv_deplibs_check_method+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_file_magic_cmd='$MAGIC_CMD'
-lt_cv_file_magic_test_file=
-lt_cv_deplibs_check_method='unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix[4-9]*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-beos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-bsdi[45]*)
-  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  ;;
-
-cygwin*)
-  # func_win32_libid is a shell function defined in ltmain.sh
-  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-  lt_cv_file_magic_cmd='func_win32_libid'
-  ;;
-
-mingw* | pw32*)
-  # Base MSYS/MinGW do not provide the 'file' command needed by
-  # func_win32_libid shell function, so use a weaker test based on 'objdump',
-  # unless we find 'file', for example because we are cross-compiling.
-  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
-  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
-    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-    lt_cv_file_magic_cmd='func_win32_libid'
-  else
-    # Keep this pattern in sync with the one in func_win32_libid.
-    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
-    lt_cv_file_magic_cmd='$OBJDUMP -f'
-  fi
-  ;;
-
-cegcc*)
-  # use the weaker test based on 'objdump'. See mingw*.
-  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
-  lt_cv_file_magic_cmd='$OBJDUMP -f'
-  ;;
-
-darwin* | rhapsody*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-freebsd* | dragonfly*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=/usr/bin/file
-      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=pass_all
-  fi
-  ;;
-
-haiku*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-hpux10.20* | hpux11*)
-  lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
-  ia64*)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64'
-    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
-    ;;
-  hppa*64*)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'
-    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
-    ;;
-  *)
-    lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library'
-    lt_cv_file_magic_test_file=/usr/lib/libc.sl
-    ;;
-  esac
-  ;;
-
-interix[3-9]*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$'
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $LD in
-  *-32|*"-32 ") libmagic=32-bit;;
-  *-n32|*"-n32 ") libmagic=N32;;
-  *-64|*"-64 ") libmagic=64-bit;;
-  *) libmagic=never-match;;
-  esac
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-netbsd* | netbsdelf*-gnu)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$'
-  fi
-  ;;
-
-newos6*)
-  lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=/usr/bin/file
-  lt_cv_file_magic_test_file=/usr/lib/libnls.so
-  ;;
-
-*nto* | *qnx*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$'
-  fi
-  ;;
-
-osf3* | osf4* | osf5*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-rdos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-solaris*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv4 | sysv4.3*)
-  case $host_vendor in
-  motorola)
-    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]'
-    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
-    ;;
-  ncr)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  sequent)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )'
-    ;;
-  sni)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib"
-    lt_cv_file_magic_test_file=/lib/libc.so
-    ;;
-  siemens)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  esac
-  ;;
-
-tpf*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-esac
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5
-$as_echo "$lt_cv_deplibs_check_method" >&6; }
-
-file_magic_glob=
-want_nocaseglob=no
-if test "$build" = "$host"; then
-  case $host_os in
-  mingw* | pw32*)
-    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
-      want_nocaseglob=yes
-    else
-      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"`
-    fi
-    ;;
-  esac
-fi
-
-file_magic_cmd=$lt_cv_file_magic_cmd
-deplibs_check_method=$lt_cv_deplibs_check_method
-test -z "$deplibs_check_method" && deplibs_check_method=unknown
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args.
-set dummy ${ac_tool_prefix}dlltool; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_DLLTOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$DLLTOOL"; then
-  ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-DLLTOOL=$ac_cv_prog_DLLTOOL
-if test -n "$DLLTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5
-$as_echo "$DLLTOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_DLLTOOL"; then
-  ac_ct_DLLTOOL=$DLLTOOL
-  # Extract the first word of "dlltool", so it can be a program name with args.
-set dummy dlltool; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_DLLTOOL"; then
-  ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_DLLTOOL="dlltool"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL
-if test -n "$ac_ct_DLLTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5
-$as_echo "$ac_ct_DLLTOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_DLLTOOL" = x; then
-    DLLTOOL="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    DLLTOOL=$ac_ct_DLLTOOL
-  fi
-else
-  DLLTOOL="$ac_cv_prog_DLLTOOL"
-fi
-
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5
-$as_echo_n "checking how to associate runtime and link libraries... " >&6; }
-if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_sharedlib_from_linklib_cmd='unknown'
-
-case $host_os in
-cygwin* | mingw* | pw32* | cegcc*)
-  # two different shell functions defined in ltmain.sh
-  # decide which to use based on capabilities of $DLLTOOL
-  case `$DLLTOOL --help 2>&1` in
-  *--identify-strict*)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
-    ;;
-  *)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
-    ;;
-  esac
-  ;;
-*)
-  # fallback: assume linklib IS sharedlib
-  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
-  ;;
-esac
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5
-$as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; }
-sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
-test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
-
-
-
-
-
-
-
-
-if test -n "$ac_tool_prefix"; then
-  for ac_prog in ar
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$AR"; then
-  ac_cv_prog_AR="$AR" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_AR="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-AR=$ac_cv_prog_AR
-if test -n "$AR"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
-$as_echo "$AR" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-    test -n "$AR" && break
-  done
-fi
-if test -z "$AR"; then
-  ac_ct_AR=$AR
-  for ac_prog in ar
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_AR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_AR"; then
-  ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_AR="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_AR=$ac_cv_prog_ac_ct_AR
-if test -n "$ac_ct_AR"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
-$as_echo "$ac_ct_AR" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$ac_ct_AR" && break
-done
-
-  if test "x$ac_ct_AR" = x; then
-    AR="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    AR=$ac_ct_AR
-  fi
-fi
-
-: ${AR=ar}
-: ${AR_FLAGS=cru}
-
-
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5
-$as_echo_n "checking for archiver @FILE support... " >&6; }
-if ${lt_cv_ar_at_file+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_ar_at_file=no
-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  echo conftest.$ac_objext > conftest.lst
-      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5'
-      { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
-  (eval $lt_ar_try) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-      if test "$ac_status" -eq 0; then
-	# Ensure the archiver fails upon bogus file names.
-	rm -f conftest.$ac_objext libconftest.a
-	{ { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
-  (eval $lt_ar_try) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-	if test "$ac_status" -ne 0; then
-          lt_cv_ar_at_file=@
-        fi
-      fi
-      rm -f conftest.* libconftest.a
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5
-$as_echo "$lt_cv_ar_at_file" >&6; }
-
-if test "x$lt_cv_ar_at_file" = xno; then
-  archiver_list_spec=
-else
-  archiver_list_spec=$lt_cv_ar_at_file
-fi
-
-
-
-
-
-
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
-set dummy ${ac_tool_prefix}strip; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_STRIP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_STRIP="${ac_tool_prefix}strip"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-STRIP=$ac_cv_prog_STRIP
-if test -n "$STRIP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
-$as_echo "$STRIP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_STRIP"; then
-  ac_ct_STRIP=$STRIP
-  # Extract the first word of "strip", so it can be a program name with args.
-set dummy strip; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_STRIP"; then
-  ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_STRIP="strip"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
-if test -n "$ac_ct_STRIP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
-$as_echo "$ac_ct_STRIP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_STRIP" = x; then
-    STRIP=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    STRIP=$ac_ct_STRIP
-  fi
-else
-  STRIP="$ac_cv_prog_STRIP"
-fi
-
-test -z "$STRIP" && STRIP=:
-
-
-
-
-
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_RANLIB" = x; then
-    RANLIB=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    RANLIB=$ac_ct_RANLIB
-  fi
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-test -z "$RANLIB" && RANLIB=:
-
-
-
-
-
-
-# Determine commands to create old-style static archives.
-old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
-old_postinstall_cmds='chmod 644 $oldlib'
-old_postuninstall_cmds=
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
-    ;;
-  *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
-    ;;
-  esac
-  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
-fi
-
-case $host_os in
-  darwin*)
-    lock_old_archive_extraction=yes ;;
-  *)
-    lock_old_archive_extraction=no ;;
-esac
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=$CC
-
-
-# Check for command to grab the raw symbol name followed by C symbol from nm.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5
-$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; }
-if ${lt_cv_sys_global_symbol_pipe+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode='[BCDEGRST]'
-
-# Regexp to match symbols that can be accessed directly from C.
-sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
-
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode='[BCDT]'
-  ;;
-cygwin* | mingw* | pw32* | cegcc*)
-  symcode='[ABCDGISTW]'
-  ;;
-hpux*)
-  if test "$host_cpu" = ia64; then
-    symcode='[ABCDEGRST]'
-  fi
-  ;;
-irix* | nonstopux*)
-  symcode='[BCDEGRST]'
-  ;;
-osf*)
-  symcode='[BCDEGQRST]'
-  ;;
-solaris*)
-  symcode='[BDRT]'
-  ;;
-sco3.2v5*)
-  symcode='[DT]'
-  ;;
-sysv4.2uw2*)
-  symcode='[DT]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode='[ABDT]'
-  ;;
-sysv4)
-  symcode='[DFNSTU]'
-  ;;
-esac
-
-# If we're using GNU nm, then use its standard symbol codes.
-case `$NM -V 2>&1` in
-*GNU* | *'with BFD'*)
-  symcode='[ABCDGIRSTW]' ;;
-esac
-
-# Transform an extracted symbol line into a proper C declaration.
-# Some systems (esp. on ia64) link data and code symbols differently,
-# so use this general approach.
-lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-
-# Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"\2\", (void *) \&\2},/p'"
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
-
-# Handle CRLF in mingw tool chain
-opt_cr=
-case $build_os in
-mingw*)
-  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
-  ;;
-esac
-
-# Try without a prefix underscore, then with it.
-for ac_symprfx in "" "_"; do
-
-  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
-  symxfrm="\\1 $ac_symprfx\\2 \\2"
-
-  # Write the raw and C identifiers.
-  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-    # Fake it for dumpbin and say T for any non-static function
-    # and D for any global variable.
-    # Also find C++ and __fastcall symbols from MSVC++,
-    # which start with @ or ?.
-    lt_cv_sys_global_symbol_pipe="$AWK '"\
-"     {last_section=section; section=\$ 3};"\
-"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
-"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
-"     \$ 0!~/External *\|/{next};"\
-"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
-"     {if(hide[section]) next};"\
-"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
-"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
-"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
-"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
-"     ' prfx=^$ac_symprfx"
-  else
-    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[	 ]\($symcode$symcode*\)[	 ][	 ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
-  fi
-  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
-
-  # Check to see that the pipe works correctly.
-  pipe_works=no
-
-  rm -f conftest*
-  cat > conftest.$ac_ext <<_LT_EOF
-#ifdef __cplusplus
-extern "C" {
-#endif
-char nm_test_var;
-void nm_test_func(void);
-void nm_test_func(void){}
-#ifdef __cplusplus
-}
-#endif
-int main(){nm_test_var='a';nm_test_func();return(0);}
-_LT_EOF
-
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-    # Now try to grab the symbols.
-    nlist=conftest.nm
-    if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5
-  (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s "$nlist"; then
-      # Try sorting and uniquifying the output.
-      if sort "$nlist" | uniq > "$nlist"T; then
-	mv -f "$nlist"T "$nlist"
-      else
-	rm -f "$nlist"T
-      fi
-
-      # Make sure that we snagged all the symbols we need.
-      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
-	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
-	  cat <<_LT_EOF > conftest.$ac_ext
-/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
-   relocations are performed -- see ld's documentation on pseudo-relocs.  */
-# define LT_DLSYM_CONST
-#elif defined(__osf__)
-/* This system does not cope well with relocations in const data.  */
-# define LT_DLSYM_CONST
-#else
-# define LT_DLSYM_CONST const
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-_LT_EOF
-	  # Now generate the symbol file.
-	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
-
-	  cat <<_LT_EOF >> conftest.$ac_ext
-
-/* The mapping between symbol names and symbols.  */
-LT_DLSYM_CONST struct {
-  const char *name;
-  void       *address;
-}
-lt__PROGRAM__LTX_preloaded_symbols[] =
-{
-  { "@PROGRAM@", (void *) 0 },
-_LT_EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
-	  cat <<\_LT_EOF >> conftest.$ac_ext
-  {0, (void *) 0}
-};
-
-/* This works around a problem in FreeBSD linker */
-#ifdef FREEBSD_WORKAROUND
-static const void *lt_preloaded_setup() {
-  return lt__PROGRAM__LTX_preloaded_symbols;
-}
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-_LT_EOF
-	  # Now try linking the two files.
-	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_globsym_save_LIBS=$LIBS
-	  lt_globsym_save_CFLAGS=$CFLAGS
-	  LIBS="conftstm.$ac_objext"
-	  CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag"
-	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext}; then
-	    pipe_works=yes
-	  fi
-	  LIBS=$lt_globsym_save_LIBS
-	  CFLAGS=$lt_globsym_save_CFLAGS
-	else
-	  echo "cannot find nm_test_func in $nlist" >&5
-	fi
-      else
-	echo "cannot find nm_test_var in $nlist" >&5
-      fi
-    else
-      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5
-    fi
-  else
-    echo "$progname: failed program was:" >&5
-    cat conftest.$ac_ext >&5
-  fi
-  rm -rf conftest* conftst*
-
-  # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" = yes; then
-    break
-  else
-    lt_cv_sys_global_symbol_pipe=
-  fi
-done
-
-fi
-
-if test -z "$lt_cv_sys_global_symbol_pipe"; then
-  lt_cv_sys_global_symbol_to_cdecl=
-fi
-if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5
-$as_echo "failed" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5
-$as_echo "ok" >&6; }
-fi
-
-# Response file support.
-if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-  nm_file_list_spec='@'
-elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then
-  nm_file_list_spec='@'
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5
-$as_echo_n "checking for sysroot... " >&6; }
-
-# Check whether --with-sysroot was given.
-if test "${with_sysroot+set}" = set; then :
-  withval=$with_sysroot;
-else
-  with_sysroot=no
-fi
-
-
-lt_sysroot=
-case ${with_sysroot} in #(
- yes)
-   if test "$GCC" = yes; then
-     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
-   fi
-   ;; #(
- /*)
-   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
-   ;; #(
- no|'')
-   ;; #(
- *)
-   { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5
-$as_echo "${with_sysroot}" >&6; }
-   as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5
-   ;;
-esac
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5
-$as_echo "${lt_sysroot:-no}" >&6; }
-
-
-
-
-
-# Check whether --enable-libtool-lock was given.
-if test "${enable_libtool_lock+set}" = set; then :
-  enableval=$enable_libtool_lock;
-fi
-
-test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
-
-# Some flags need to be propagated to the compiler or linker for good
-# libtool support.
-case $host in
-ia64-*-hpux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-    case `/usr/bin/file conftest.$ac_objext` in
-      *ELF-32*)
-	HPUX_IA64_MODE="32"
-	;;
-      *ELF-64*)
-	HPUX_IA64_MODE="64"
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-*-*-irix6*)
-  # Find out which ABI we are using.
-  echo '#line '$LINENO' "configure"' > conftest.$ac_ext
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-    if test "$lt_cv_prog_gnu_ld" = yes; then
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -melf32bsmip"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -melf32bmipn32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -melf64bmip"
-	;;
-      esac
-    else
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -32"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -n32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -64"
-	  ;;
-      esac
-    fi
-  fi
-  rm -rf conftest*
-  ;;
-
-x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \
-s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-    case `/usr/bin/file conftest.o` in
-      *32-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_i386_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    case `/usr/bin/file conftest.o` in
-	      *x86-64*)
-		LD="${LD-ld} -m elf32_x86_64"
-		;;
-	      *)
-		LD="${LD-ld} -m elf_i386"
-		;;
-	    esac
-	    ;;
-	  powerpc64le-*)
-	    LD="${LD-ld} -m elf32lppclinux"
-	    ;;
-	  powerpc64-*)
-	    LD="${LD-ld} -m elf32ppclinux"
-	    ;;
-	  s390x-*linux*)
-	    LD="${LD-ld} -m elf_s390"
-	    ;;
-	  sparc64-*linux*)
-	    LD="${LD-ld} -m elf32_sparc"
-	    ;;
-	esac
-	;;
-      *64-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_x86_64_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    LD="${LD-ld} -m elf_x86_64"
-	    ;;
-	  powerpcle-*)
-	    LD="${LD-ld} -m elf64lppc"
-	    ;;
-	  powerpc-*)
-	    LD="${LD-ld} -m elf64ppc"
-	    ;;
-	  s390*-*linux*|s390*-*tpf*)
-	    LD="${LD-ld} -m elf64_s390"
-	    ;;
-	  sparc*-*linux*)
-	    LD="${LD-ld} -m elf64_sparc"
-	    ;;
-	esac
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-*-*-sco3.2v5*)
-  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS -belf"
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5
-$as_echo_n "checking whether the C compiler needs -belf... " >&6; }
-if ${lt_cv_cc_needs_belf+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  lt_cv_cc_needs_belf=yes
-else
-  lt_cv_cc_needs_belf=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-     ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5
-$as_echo "$lt_cv_cc_needs_belf" >&6; }
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
-    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
-  fi
-  ;;
-*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*)
-        case $host in
-        i?86-*-solaris*)
-          LD="${LD-ld} -m elf_x86_64"
-          ;;
-        sparc*-*-solaris*)
-          LD="${LD-ld} -m elf64_sparc"
-          ;;
-        esac
-        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
-        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
-          LD="${LD-ld}_sol2"
-        fi
-        ;;
-      *)
-	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
-	  LD="${LD-ld} -64"
-	fi
-	;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-esac
-
-need_locks="$enable_libtool_lock"
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args.
-set dummy ${ac_tool_prefix}mt; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_MANIFEST_TOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$MANIFEST_TOOL"; then
-  ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL
-if test -n "$MANIFEST_TOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5
-$as_echo "$MANIFEST_TOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_MANIFEST_TOOL"; then
-  ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL
-  # Extract the first word of "mt", so it can be a program name with args.
-set dummy mt; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_MANIFEST_TOOL"; then
-  ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_MANIFEST_TOOL="mt"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL
-if test -n "$ac_ct_MANIFEST_TOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5
-$as_echo "$ac_ct_MANIFEST_TOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_MANIFEST_TOOL" = x; then
-    MANIFEST_TOOL=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL
-  fi
-else
-  MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL"
-fi
-
-test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5
-$as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; }
-if ${lt_cv_path_mainfest_tool+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_path_mainfest_tool=no
-  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5
-  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
-  cat conftest.err >&5
-  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
-    lt_cv_path_mainfest_tool=yes
-  fi
-  rm -f conftest*
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5
-$as_echo "$lt_cv_path_mainfest_tool" >&6; }
-if test "x$lt_cv_path_mainfest_tool" != xyes; then
-  MANIFEST_TOOL=:
-fi
-
-
-
-
-
-
-  case $host_os in
-    rhapsody* | darwin*)
-    if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args.
-set dummy ${ac_tool_prefix}dsymutil; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_DSYMUTIL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$DSYMUTIL"; then
-  ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-DSYMUTIL=$ac_cv_prog_DSYMUTIL
-if test -n "$DSYMUTIL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5
-$as_echo "$DSYMUTIL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_DSYMUTIL"; then
-  ac_ct_DSYMUTIL=$DSYMUTIL
-  # Extract the first word of "dsymutil", so it can be a program name with args.
-set dummy dsymutil; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_DSYMUTIL"; then
-  ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_DSYMUTIL="dsymutil"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL
-if test -n "$ac_ct_DSYMUTIL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5
-$as_echo "$ac_ct_DSYMUTIL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_DSYMUTIL" = x; then
-    DSYMUTIL=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    DSYMUTIL=$ac_ct_DSYMUTIL
-  fi
-else
-  DSYMUTIL="$ac_cv_prog_DSYMUTIL"
-fi
-
-    if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args.
-set dummy ${ac_tool_prefix}nmedit; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_NMEDIT+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$NMEDIT"; then
-  ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-NMEDIT=$ac_cv_prog_NMEDIT
-if test -n "$NMEDIT"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5
-$as_echo "$NMEDIT" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_NMEDIT"; then
-  ac_ct_NMEDIT=$NMEDIT
-  # Extract the first word of "nmedit", so it can be a program name with args.
-set dummy nmedit; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_NMEDIT"; then
-  ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_NMEDIT="nmedit"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT
-if test -n "$ac_ct_NMEDIT"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5
-$as_echo "$ac_ct_NMEDIT" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_NMEDIT" = x; then
-    NMEDIT=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    NMEDIT=$ac_ct_NMEDIT
-  fi
-else
-  NMEDIT="$ac_cv_prog_NMEDIT"
-fi
-
-    if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args.
-set dummy ${ac_tool_prefix}lipo; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_LIPO+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$LIPO"; then
-  ac_cv_prog_LIPO="$LIPO" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_LIPO="${ac_tool_prefix}lipo"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-LIPO=$ac_cv_prog_LIPO
-if test -n "$LIPO"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5
-$as_echo "$LIPO" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_LIPO"; then
-  ac_ct_LIPO=$LIPO
-  # Extract the first word of "lipo", so it can be a program name with args.
-set dummy lipo; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_LIPO+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_LIPO"; then
-  ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_LIPO="lipo"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO
-if test -n "$ac_ct_LIPO"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5
-$as_echo "$ac_ct_LIPO" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_LIPO" = x; then
-    LIPO=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    LIPO=$ac_ct_LIPO
-  fi
-else
-  LIPO="$ac_cv_prog_LIPO"
-fi
-
-    if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args.
-set dummy ${ac_tool_prefix}otool; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_OTOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$OTOOL"; then
-  ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_OTOOL="${ac_tool_prefix}otool"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-OTOOL=$ac_cv_prog_OTOOL
-if test -n "$OTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5
-$as_echo "$OTOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_OTOOL"; then
-  ac_ct_OTOOL=$OTOOL
-  # Extract the first word of "otool", so it can be a program name with args.
-set dummy otool; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_OTOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_OTOOL"; then
-  ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_OTOOL="otool"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL
-if test -n "$ac_ct_OTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5
-$as_echo "$ac_ct_OTOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_OTOOL" = x; then
-    OTOOL=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    OTOOL=$ac_ct_OTOOL
-  fi
-else
-  OTOOL="$ac_cv_prog_OTOOL"
-fi
-
-    if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args.
-set dummy ${ac_tool_prefix}otool64; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_OTOOL64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$OTOOL64"; then
-  ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-OTOOL64=$ac_cv_prog_OTOOL64
-if test -n "$OTOOL64"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5
-$as_echo "$OTOOL64" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_OTOOL64"; then
-  ac_ct_OTOOL64=$OTOOL64
-  # Extract the first word of "otool64", so it can be a program name with args.
-set dummy otool64; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_OTOOL64"; then
-  ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_OTOOL64="otool64"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64
-if test -n "$ac_ct_OTOOL64"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5
-$as_echo "$ac_ct_OTOOL64" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_OTOOL64" = x; then
-    OTOOL64=":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    OTOOL64=$ac_ct_OTOOL64
-  fi
-else
-  OTOOL64="$ac_cv_prog_OTOOL64"
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5
-$as_echo_n "checking for -single_module linker flag... " >&6; }
-if ${lt_cv_apple_cc_single_mod+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_apple_cc_single_mod=no
-      if test -z "${LT_MULTI_MODULE}"; then
-	# By default we will add the -single_module flag. You can override
-	# by either setting the environment variable LT_MULTI_MODULE
-	# non-empty at configure time, or by adding -multi_module to the
-	# link flags.
-	rm -rf libconftest.dylib*
-	echo "int foo(void){return 1;}" > conftest.c
-	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
--dynamiclib -Wl,-single_module conftest.c" >&5
-	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
-	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
-        _lt_result=$?
-	# If there is a non-empty error log, and "single_module"
-	# appears in it, assume the flag caused a linker warning
-        if test -s conftest.err && $GREP single_module conftest.err; then
-	  cat conftest.err >&5
-	# Otherwise, if the output was created with a 0 exit code from
-	# the compiler, it worked.
-	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
-	  lt_cv_apple_cc_single_mod=yes
-	else
-	  cat conftest.err >&5
-	fi
-	rm -rf libconftest.dylib*
-	rm -f conftest.*
-      fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5
-$as_echo "$lt_cv_apple_cc_single_mod" >&6; }
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5
-$as_echo_n "checking for -exported_symbols_list linker flag... " >&6; }
-if ${lt_cv_ld_exported_symbols_list+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_ld_exported_symbols_list=no
-      save_LDFLAGS=$LDFLAGS
-      echo "_main" > conftest.sym
-      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  lt_cv_ld_exported_symbols_list=yes
-else
-  lt_cv_ld_exported_symbols_list=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-	LDFLAGS="$save_LDFLAGS"
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5
-$as_echo "$lt_cv_ld_exported_symbols_list" >&6; }
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5
-$as_echo_n "checking for -force_load linker flag... " >&6; }
-if ${lt_cv_ld_force_load+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_ld_force_load=no
-      cat > conftest.c << _LT_EOF
-int forced_loaded() { return 2;}
-_LT_EOF
-      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5
-      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5
-      echo "$AR cru libconftest.a conftest.o" >&5
-      $AR cru libconftest.a conftest.o 2>&5
-      echo "$RANLIB libconftest.a" >&5
-      $RANLIB libconftest.a 2>&5
-      cat > conftest.c << _LT_EOF
-int main() { return 0;}
-_LT_EOF
-      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5
-      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
-      _lt_result=$?
-      if test -s conftest.err && $GREP force_load conftest.err; then
-	cat conftest.err >&5
-      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
-	lt_cv_ld_force_load=yes
-      else
-	cat conftest.err >&5
-      fi
-        rm -f conftest.err libconftest.a conftest conftest.c
-        rm -rf conftest.dSYM
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5
-$as_echo "$lt_cv_ld_force_load" >&6; }
-    case $host_os in
-    rhapsody* | darwin1.[012])
-      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
-    darwin1.*)
-      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-    darwin*) # darwin 5.x on
-      # if running on 10.5 or later, the deployment target defaults
-      # to the OS version, if on x86, and 10.4, the deployment
-      # target defaults to 10.4. Don't you love it?
-      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
-	10.0,*86*-darwin8*|10.0,*-darwin[91]*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-	10.[012]*)
-	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-	10.*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-      esac
-    ;;
-  esac
-    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
-      _lt_dar_single_mod='$single_module'
-    fi
-    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
-      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
-    else
-      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    fi
-    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
-      _lt_dsymutil='~$DSYMUTIL $lib || :'
-    else
-      _lt_dsymutil=
-    fi
-    ;;
-  esac
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
-  CPP=
-fi
-if test -z "$CPP"; then
-  if ${ac_cv_prog_CPP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
-    do
-      ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-  break
-fi
-
-    done
-    ac_cv_prog_CPP=$CPP
-
-fi
-  CPP=$ac_cv_prog_CPP
-else
-  ac_cv_prog_CPP=$CPP
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
-  # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  # Broken: success on invalid input.
-continue
-else
-  # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_header_stdc=yes
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then :
-  :
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ctype.h>
-#include <stdlib.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-		   (('a' <= (c) && (c) <= 'i') \
-		     || ('j' <= (c) && (c) <= 'r') \
-		     || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-	|| toupper (i) != TOUPPER (i))
-      return 2;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
-$as_echo "$ac_cv_header_stdc" >&6; }
-if test $ac_cv_header_stdc = yes; then
-
-$as_echo "#define STDC_HEADERS 1" >>confdefs.h
-
-fi
-
-# On IRIX 5.3, sys/types and inttypes.h are conflicting.
-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
-		  inttypes.h stdint.h unistd.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
-"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-for ac_header in dlfcn.h
-do :
-  ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default
-"
-if test "x$ac_cv_header_dlfcn_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DLFCN_H 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-
-# Set options
-enable_win32_dll=yes
-
-case $host in
-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args.
-set dummy ${ac_tool_prefix}as; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AS+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$AS"; then
-  ac_cv_prog_AS="$AS" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_AS="${ac_tool_prefix}as"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-AS=$ac_cv_prog_AS
-if test -n "$AS"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AS" >&5
-$as_echo "$AS" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_AS"; then
-  ac_ct_AS=$AS
-  # Extract the first word of "as", so it can be a program name with args.
-set dummy as; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_AS+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_AS"; then
-  ac_cv_prog_ac_ct_AS="$ac_ct_AS" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_AS="as"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_AS=$ac_cv_prog_ac_ct_AS
-if test -n "$ac_ct_AS"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AS" >&5
-$as_echo "$ac_ct_AS" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_AS" = x; then
-    AS="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    AS=$ac_ct_AS
-  fi
-else
-  AS="$ac_cv_prog_AS"
-fi
-
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args.
-set dummy ${ac_tool_prefix}dlltool; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_DLLTOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$DLLTOOL"; then
-  ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-DLLTOOL=$ac_cv_prog_DLLTOOL
-if test -n "$DLLTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5
-$as_echo "$DLLTOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_DLLTOOL"; then
-  ac_ct_DLLTOOL=$DLLTOOL
-  # Extract the first word of "dlltool", so it can be a program name with args.
-set dummy dlltool; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_DLLTOOL"; then
-  ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_DLLTOOL="dlltool"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL
-if test -n "$ac_ct_DLLTOOL"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5
-$as_echo "$ac_ct_DLLTOOL" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_DLLTOOL" = x; then
-    DLLTOOL="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    DLLTOOL=$ac_ct_DLLTOOL
-  fi
-else
-  DLLTOOL="$ac_cv_prog_DLLTOOL"
-fi
-
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
-set dummy ${ac_tool_prefix}objdump; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_OBJDUMP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$OBJDUMP"; then
-  ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-OBJDUMP=$ac_cv_prog_OBJDUMP
-if test -n "$OBJDUMP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5
-$as_echo "$OBJDUMP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_OBJDUMP"; then
-  ac_ct_OBJDUMP=$OBJDUMP
-  # Extract the first word of "objdump", so it can be a program name with args.
-set dummy objdump; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_OBJDUMP"; then
-  ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_OBJDUMP="objdump"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP
-if test -n "$ac_ct_OBJDUMP"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5
-$as_echo "$ac_ct_OBJDUMP" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_OBJDUMP" = x; then
-    OBJDUMP="false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    OBJDUMP=$ac_ct_OBJDUMP
-  fi
-else
-  OBJDUMP="$ac_cv_prog_OBJDUMP"
-fi
-
-  ;;
-esac
-
-test -z "$AS" && AS=as
-
-
-
-
-
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-
-
-
-
-
-test -z "$OBJDUMP" && OBJDUMP=objdump
-
-
-
-
-
-
-
-        enable_dlopen=no
-
-
-
-            # Check whether --enable-shared was given.
-if test "${enable_shared+set}" = set; then :
-  enableval=$enable_shared; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_shared=yes
-fi
-
-
-
-
-
-
-
-
-
-  # Check whether --enable-static was given.
-if test "${enable_static+set}" = set; then :
-  enableval=$enable_static; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=yes ;;
-    no) enable_static=no ;;
-    *)
-     enable_static=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_static=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_static=yes
-fi
-
-
-
-
-
-
-
-
-
-
-# Check whether --with-pic was given.
-if test "${with_pic+set}" = set; then :
-  withval=$with_pic; lt_p=${PACKAGE-default}
-    case $withval in
-    yes|no) pic_mode=$withval ;;
-    *)
-      pic_mode=default
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for lt_pkg in $withval; do
-	IFS="$lt_save_ifs"
-	if test "X$lt_pkg" = "X$lt_p"; then
-	  pic_mode=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  pic_mode=default
-fi
-
-
-test -z "$pic_mode" && pic_mode=default
-
-
-
-
-
-
-
-  # Check whether --enable-fast-install was given.
-if test "${enable_fast_install+set}" = set; then :
-  enableval=$enable_fast_install; p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_fast_install=yes ;;
-    no) enable_fast_install=no ;;
-    *)
-      enable_fast_install=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_fast_install=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_fast_install=yes
-fi
-
-
-
-
-
-
-
-
-
-
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ltmain"
-
-# Always use our own libtool.
-LIBTOOL='$(SHELL) $(top_builddir)/libtool'
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-test -z "$LN_S" && LN_S="ln -s"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-if test -n "${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5
-$as_echo_n "checking for objdir... " >&6; }
-if ${lt_cv_objdir+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  rm -f .libs 2>/dev/null
-mkdir .libs 2>/dev/null
-if test -d .libs; then
-  lt_cv_objdir=.libs
-else
-  # MS-DOS does not allow filenames that begin with a dot.
-  lt_cv_objdir=_libs
-fi
-rmdir .libs 2>/dev/null
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5
-$as_echo "$lt_cv_objdir" >&6; }
-objdir=$lt_cv_objdir
-
-
-
-
-
-cat >>confdefs.h <<_ACEOF
-#define LT_OBJDIR "$lt_cv_objdir/"
-_ACEOF
-
-
-
-
-case $host_os in
-aix3*)
-  # AIX sometimes has problems with the GCC collect2 program.  For some
-  # reason, if we set the COLLECT_NAMES environment variable, the problems
-  # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" != Xset; then
-    COLLECT_NAMES=
-    export COLLECT_NAMES
-  fi
-  ;;
-esac
-
-# Global variables:
-ofile=libtool
-can_build_shared=yes
-
-# All known linkers require a `.a' archive for static linking (except MSVC,
-# which needs '.lib').
-libext=a
-
-with_gnu_ld="$lt_cv_prog_gnu_ld"
-
-old_CC="$CC"
-old_CFLAGS="$CFLAGS"
-
-# Set sane defaults for various variables
-test -z "$CC" && CC=cc
-test -z "$LTCC" && LTCC=$CC
-test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
-test -z "$LD" && LD=ld
-test -z "$ac_objext" && ac_objext=o
-
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
-
-
-# Only perform the check for file, if the check method requires it
-test -z "$MAGIC_CMD" && MAGIC_CMD=file
-case $deplibs_check_method in
-file_magic*)
-  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5
-$as_echo_n "checking for ${ac_tool_prefix}file... " >&6; }
-if ${lt_cv_path_MAGIC_CMD+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $MAGIC_CMD in
-[\\/*] |  ?:[\\/]*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-*)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
-  for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/${ac_tool_prefix}file; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    $EGREP "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <<_LT_EOF 1>&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-_LT_EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
-  ;;
-esac
-fi
-
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
-$as_echo "$MAGIC_CMD" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-
-
-
-if test -z "$lt_cv_path_MAGIC_CMD"; then
-  if test -n "$ac_tool_prefix"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5
-$as_echo_n "checking for file... " >&6; }
-if ${lt_cv_path_MAGIC_CMD+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $MAGIC_CMD in
-[\\/*] |  ?:[\\/]*)
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-*)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  ac_dummy="/usr/bin$PATH_SEPARATOR$PATH"
-  for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/file; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/file"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    $EGREP "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <<_LT_EOF 1>&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-_LT_EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
-  ;;
-esac
-fi
-
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
-$as_echo "$MAGIC_CMD" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  else
-    MAGIC_CMD=:
-  fi
-fi
-
-  fi
-  ;;
-esac
-
-# Use C for the default configuration in the libtool script
-
-lt_save_CC="$CC"
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-# Source file extension for C test sources.
-ac_ext=c
-
-# Object file extension for compiled C test sources.
-objext=o
-objext=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="int some_variable = 0;"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='int main(){return(0);}'
-
-
-
-
-
-
-
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=$CC
-
-# Save the default compiler, since it gets overwritten when the other
-# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
-compiler_DEFAULT=$CC
-
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$RM conftest*
-
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$RM -r conftest*
-
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-
-lt_prog_compiler_no_builtin_flag=
-
-if test "$GCC" = yes; then
-  case $cc_basename in
-  nvcc*)
-    lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;;
-  *)
-    lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;;
-  esac
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
-$as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; }
-if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler_rtti_exceptions=no
-   ac_outfile=conftest.$ac_objext
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="-fno-rtti -fno-exceptions"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=$?
-   cat conftest.err >&5
-   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
-       lt_cv_prog_compiler_rtti_exceptions=yes
-     fi
-   fi
-   $RM conftest*
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
-$as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; }
-
-if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then
-    lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions"
-else
-    :
-fi
-
-fi
-
-
-
-
-
-
-  lt_prog_compiler_wl=
-lt_prog_compiler_pic=
-lt_prog_compiler_static=
-
-
-  if test "$GCC" = yes; then
-    lt_prog_compiler_wl='-Wl,'
-    lt_prog_compiler_static='-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            lt_prog_compiler_pic='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      lt_prog_compiler_pic='-DDLL_EXPORT'
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      lt_prog_compiler_pic='-fno-common'
-      ;;
-
-    haiku*)
-      # PIC is the default for Haiku.
-      # The "-static" flag exists, but is broken.
-      lt_prog_compiler_static=
-      ;;
-
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic='-fPIC'
-	;;
-      esac
-      ;;
-
-    interix[3-9]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared libraries
-      # on systems that don't support them.
-      lt_prog_compiler_can_build_shared=no
-      enable_shared=no
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      lt_prog_compiler_pic='-fPIC -shared'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	lt_prog_compiler_pic=-Kconform_pic
-      fi
-      ;;
-
-    *)
-      lt_prog_compiler_pic='-fPIC'
-      ;;
-    esac
-
-    case $cc_basename in
-    nvcc*) # Cuda Compiler Driver 2.2
-      lt_prog_compiler_wl='-Xlinker '
-      if test -n "$lt_prog_compiler_pic"; then
-        lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic"
-      fi
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compiler.
-    case $host_os in
-    aix*)
-      lt_prog_compiler_wl='-Wl,'
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static='-Bstatic'
-      else
-	lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      lt_prog_compiler_pic='-DDLL_EXPORT'
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      lt_prog_compiler_wl='-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic='+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      lt_prog_compiler_static='${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      lt_prog_compiler_wl='-Wl,'
-      # PIC (with -KPIC) is the default.
-      lt_prog_compiler_static='-non_shared'
-      ;;
-
-    linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-      case $cc_basename in
-      # old Intel for x86_64 which still supported -KPIC.
-      ecc*)
-	lt_prog_compiler_wl='-Wl,'
-	lt_prog_compiler_pic='-KPIC'
-	lt_prog_compiler_static='-static'
-        ;;
-      # icc used to be incompatible with GCC.
-      # ICC 10 doesn't accept -KPIC any more.
-      icc* | ifort*)
-	lt_prog_compiler_wl='-Wl,'
-	lt_prog_compiler_pic='-fPIC'
-	lt_prog_compiler_static='-static'
-        ;;
-      # Lahey Fortran 8.1.
-      lf95*)
-	lt_prog_compiler_wl='-Wl,'
-	lt_prog_compiler_pic='--shared'
-	lt_prog_compiler_static='--static'
-	;;
-      nagfor*)
-	# NAG Fortran compiler
-	lt_prog_compiler_wl='-Wl,-Wl,,'
-	lt_prog_compiler_pic='-PIC'
-	lt_prog_compiler_static='-Bstatic'
-	;;
-      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	lt_prog_compiler_wl='-Wl,'
-	lt_prog_compiler_pic='-fpic'
-	lt_prog_compiler_static='-Bstatic'
-        ;;
-      ccc*)
-        lt_prog_compiler_wl='-Wl,'
-        # All Alpha code is PIC.
-        lt_prog_compiler_static='-non_shared'
-        ;;
-      xl* | bgxl* | bgf* | mpixl*)
-	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
-	lt_prog_compiler_wl='-Wl,'
-	lt_prog_compiler_pic='-qpic'
-	lt_prog_compiler_static='-qstaticlink'
-	;;
-      *)
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*)
-	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
-	  lt_prog_compiler_pic='-KPIC'
-	  lt_prog_compiler_static='-Bstatic'
-	  lt_prog_compiler_wl=''
-	  ;;
-	*Sun\ F* | *Sun*Fortran*)
-	  lt_prog_compiler_pic='-KPIC'
-	  lt_prog_compiler_static='-Bstatic'
-	  lt_prog_compiler_wl='-Qoption ld '
-	  ;;
-	*Sun\ C*)
-	  # Sun C 5.9
-	  lt_prog_compiler_pic='-KPIC'
-	  lt_prog_compiler_static='-Bstatic'
-	  lt_prog_compiler_wl='-Wl,'
-	  ;;
-        *Intel*\ [CF]*Compiler*)
-	  lt_prog_compiler_wl='-Wl,'
-	  lt_prog_compiler_pic='-fPIC'
-	  lt_prog_compiler_static='-static'
-	  ;;
-	*Portland\ Group*)
-	  lt_prog_compiler_wl='-Wl,'
-	  lt_prog_compiler_pic='-fpic'
-	  lt_prog_compiler_static='-Bstatic'
-	  ;;
-	esac
-	;;
-      esac
-      ;;
-
-    newsos6)
-      lt_prog_compiler_pic='-KPIC'
-      lt_prog_compiler_static='-Bstatic'
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      lt_prog_compiler_pic='-fPIC -shared'
-      ;;
-
-    osf3* | osf4* | osf5*)
-      lt_prog_compiler_wl='-Wl,'
-      # All OSF/1 code is PIC.
-      lt_prog_compiler_static='-non_shared'
-      ;;
-
-    rdos*)
-      lt_prog_compiler_static='-non_shared'
-      ;;
-
-    solaris*)
-      lt_prog_compiler_pic='-KPIC'
-      lt_prog_compiler_static='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
-	lt_prog_compiler_wl='-Qoption ld ';;
-      *)
-	lt_prog_compiler_wl='-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      lt_prog_compiler_wl='-Qoption ld '
-      lt_prog_compiler_pic='-PIC'
-      lt_prog_compiler_static='-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      lt_prog_compiler_wl='-Wl,'
-      lt_prog_compiler_pic='-KPIC'
-      lt_prog_compiler_static='-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	lt_prog_compiler_pic='-Kconform_pic'
-	lt_prog_compiler_static='-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      lt_prog_compiler_wl='-Wl,'
-      lt_prog_compiler_pic='-KPIC'
-      lt_prog_compiler_static='-Bstatic'
-      ;;
-
-    unicos*)
-      lt_prog_compiler_wl='-Wl,'
-      lt_prog_compiler_can_build_shared=no
-      ;;
-
-    uts4*)
-      lt_prog_compiler_pic='-pic'
-      lt_prog_compiler_static='-Bstatic'
-      ;;
-
-    *)
-      lt_prog_compiler_can_build_shared=no
-      ;;
-    esac
-  fi
-
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    lt_prog_compiler_pic=
-    ;;
-  *)
-    lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC"
-    ;;
-esac
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5
-$as_echo_n "checking for $compiler option to produce PIC... " >&6; }
-if ${lt_cv_prog_compiler_pic+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler_pic=$lt_prog_compiler_pic
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5
-$as_echo "$lt_cv_prog_compiler_pic" >&6; }
-lt_prog_compiler_pic=$lt_cv_prog_compiler_pic
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$lt_prog_compiler_pic"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5
-$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; }
-if ${lt_cv_prog_compiler_pic_works+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler_pic_works=no
-   ac_outfile=conftest.$ac_objext
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$lt_prog_compiler_pic -DPIC"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=$?
-   cat conftest.err >&5
-   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
-       lt_cv_prog_compiler_pic_works=yes
-     fi
-   fi
-   $RM conftest*
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5
-$as_echo "$lt_cv_prog_compiler_pic_works" >&6; }
-
-if test x"$lt_cv_prog_compiler_pic_works" = xyes; then
-    case $lt_prog_compiler_pic in
-     "" | " "*) ;;
-     *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;;
-     esac
-else
-    lt_prog_compiler_pic=
-     lt_prog_compiler_can_build_shared=no
-fi
-
-fi
-
-
-
-
-
-
-
-
-
-
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5
-$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; }
-if ${lt_cv_prog_compiler_static_works+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler_static_works=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
-   echo "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_cv_prog_compiler_static_works=yes
-       fi
-     else
-       lt_cv_prog_compiler_static_works=yes
-     fi
-   fi
-   $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5
-$as_echo "$lt_cv_prog_compiler_static_works" >&6; }
-
-if test x"$lt_cv_prog_compiler_static_works" = xyes; then
-    :
-else
-    lt_prog_compiler_static=
-fi
-
-
-
-
-
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
-$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
-if ${lt_cv_prog_compiler_c_o+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler_c_o=no
-   $RM -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag="-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=$?
-   cat out/conftest.err >&5
-   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
-       lt_cv_prog_compiler_c_o=yes
-     fi
-   fi
-   chmod u+w . 2>&5
-   $RM conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
-   $RM out/* && rmdir out
-   cd ..
-   $RM -r conftest
-   $RM conftest*
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5
-$as_echo "$lt_cv_prog_compiler_c_o" >&6; }
-
-
-
-
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
-$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
-if ${lt_cv_prog_compiler_c_o+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler_c_o=no
-   $RM -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag="-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=$?
-   cat out/conftest.err >&5
-   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
-       lt_cv_prog_compiler_c_o=yes
-     fi
-   fi
-   chmod u+w . 2>&5
-   $RM conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
-   $RM out/* && rmdir out
-   cd ..
-   $RM -r conftest
-   $RM conftest*
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5
-$as_echo "$lt_cv_prog_compiler_c_o" >&6; }
-
-
-
-
-hard_links="nottested"
-if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then
-  # do not overwrite the value of need_locks provided by the user
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5
-$as_echo_n "checking if we can lock with hard links... " >&6; }
-  hard_links=yes
-  $RM conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=no
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5
-$as_echo "$hard_links" >&6; }
-  if test "$hard_links" = no; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5
-$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;}
-    need_locks=warn
-  fi
-else
-  need_locks=no
-fi
-
-
-
-
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5
-$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; }
-
-  runpath_var=
-  allow_undefined_flag=
-  always_export_symbols=no
-  archive_cmds=
-  archive_expsym_cmds=
-  compiler_needs_object=no
-  enable_shared_with_static_runtimes=no
-  export_dynamic_flag_spec=
-  export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  hardcode_automatic=no
-  hardcode_direct=no
-  hardcode_direct_absolute=no
-  hardcode_libdir_flag_spec=
-  hardcode_libdir_separator=
-  hardcode_minus_L=no
-  hardcode_shlibpath_var=unsupported
-  inherit_rpath=no
-  link_all_deplibs=unknown
-  module_cmds=
-  module_expsym_cmds=
-  old_archive_from_new_cmds=
-  old_archive_from_expsyms_cmds=
-  thread_safe_flag_spec=
-  whole_archive_flag_spec=
-  # include_expsyms should be a list of space-separated symbols to be *always*
-  # included in the symbol list
-  include_expsyms=
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
-  exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  # Exclude shared library initialization/finalization symbols.
-  extract_expsyms_cmds=
-
-  case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" != yes; then
-      with_gnu_ld=no
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
-  openbsd*)
-    with_gnu_ld=no
-    ;;
-  linux* | k*bsd*-gnu | gnu*)
-    link_all_deplibs=no
-    ;;
-  esac
-
-  ld_shlibs=yes
-
-  # On some targets, GNU ld is compatible enough with the native linker
-  # that we're better off using the native interface for both.
-  lt_use_gnu_ld_interface=no
-  if test "$with_gnu_ld" = yes; then
-    case $host_os in
-      aix*)
-	# The AIX port of GNU ld has always aspired to compatibility
-	# with the native linker.  However, as the warning in the GNU ld
-	# block says, versions before 2.19.5* couldn't really create working
-	# shared libraries, regardless of the interface used.
-	case `$LD -v 2>&1` in
-	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
-	  *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;;
-	  *\ \(GNU\ Binutils\)\ [3-9]*) ;;
-	  *)
-	    lt_use_gnu_ld_interface=yes
-	    ;;
-	esac
-	;;
-      *)
-	lt_use_gnu_ld_interface=yes
-	;;
-    esac
-  fi
-
-  if test "$lt_use_gnu_ld_interface" = yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-    export_dynamic_flag_spec='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
-      whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-    else
-      whole_archive_flag_spec=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>&1` in
-      *GNU\ gold*) supports_anon_versioning=yes ;;
-      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix[3-9]*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
-	ld_shlibs=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.19, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to install binutils
-*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
-*** You will then need to restart the configuration process.
-
-_LT_EOF
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            archive_expsym_cmds=''
-        ;;
-      m68k)
-            archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            hardcode_libdir_flag_spec='-L$libdir'
-            hardcode_minus_L=yes
-        ;;
-      esac
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	allow_undefined_flag=unsupported
-	# Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      else
-	ld_shlibs=no
-      fi
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
-      # as there is no search path for DLLs.
-      hardcode_libdir_flag_spec='-L$libdir'
-      export_dynamic_flag_spec='${wl}--export-all-symbols'
-      allow_undefined_flag=unsupported
-      always_export_symbols=no
-      enable_shared_with_static_runtimes=yes
-      export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols'
-      exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'
-
-      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-        archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	ld_shlibs=no
-      fi
-      ;;
-
-    haiku*)
-      archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      link_all_deplibs=yes
-      ;;
-
-    interix[3-9]*)
-      hardcode_direct=no
-      hardcode_shlibpath_var=no
-      hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-      export_dynamic_flag_spec='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
-      tmp_diet=no
-      if test "$host_os" = linux-dietlibc; then
-	case $cc_basename in
-	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
-	esac
-      fi
-      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
-	 && test "$tmp_diet" = no
-      then
-	tmp_addflag=' $pic_flag'
-	tmp_sharedflag='-shared'
-	case $cc_basename,$host_cpu in
-        pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95* | pgfortran*)
-					# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	lf95*)				# Lahey Fortran 8.1
-	  whole_archive_flag_spec=
-	  tmp_sharedflag='--shared' ;;
-	xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below)
-	  tmp_sharedflag='-qmkshrobj'
-	  tmp_addflag= ;;
-	nvcc*)	# Cuda Compiler Driver 2.2
-	  whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  compiler_needs_object=yes
-	  ;;
-	esac
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ C*)			# Sun C 5.9
-	  whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  compiler_needs_object=yes
-	  tmp_sharedflag='-G' ;;
-	*Sun\ F*)			# Sun Fortran 8.3
-	  tmp_sharedflag='-G' ;;
-	esac
-	archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-        if test "x$supports_anon_versioning" = xyes; then
-          archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~
-	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	    echo "local: *; };" >> $output_objdir/$libname.ver~
-	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-        fi
-
-	case $cc_basename in
-	xlf* | bgf* | bgxlf* | mpixlf*)
-	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
-	  whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive'
-	  hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-	  archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
-	  if test "x$supports_anon_versioning" = xyes; then
-	    archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~
-	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	      echo "local: *; };" >> $output_objdir/$libname.ver~
-	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
-	  fi
-	  ;;
-	esac
-      else
-        ld_shlibs=no
-      fi
-      ;;
-
-    netbsd* | netbsdelf*-gnu)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
-	wlarc=
-      else
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
-	ld_shlibs=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	ld_shlibs=no
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
-	ld_shlibs=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  # For security reasons, it is highly recommended that you always
-	  # use absolute paths for naming shared libraries, and exclude the
-	  # DT_RUNPATH tag from executables and libraries.  But doing so
-	  # requires that you compile everything twice, which is a pain.
-	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-	    archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-	  else
-	    ld_shlibs=no
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      wlarc=
-      hardcode_direct=yes
-      hardcode_shlibpath_var=no
-      ;;
-
-    *)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	ld_shlibs=no
-      fi
-      ;;
-    esac
-
-    if test "$ld_shlibs" = no; then
-      runpath_var=
-      hardcode_libdir_flag_spec=
-      export_dynamic_flag_spec=
-      whole_archive_flag_spec=
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      allow_undefined_flag=unsupported
-      always_export_symbols=yes
-      archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      hardcode_minus_L=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	hardcode_direct=unsupported
-      fi
-      ;;
-
-    aix[4-9]*)
-      if test "$host_cpu" = ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=no
-	exp_sym_flag='-Bexport'
-	no_entry_flag=""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	# Also, AIX nm treats weak defined symbols like other global
-	# defined symbols, whereas GNU nm marks them as "W".
-	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-	  export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-	else
-	  export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-	fi
-	aix_use_runtimelinking=no
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*)
-	  for ld_flag in $LDFLAGS; do
-	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
-	    aix_use_runtimelinking=yes
-	    break
-	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag='-bexport'
-	no_entry_flag='-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      archive_cmds=''
-      hardcode_direct=yes
-      hardcode_direct_absolute=yes
-      hardcode_libdir_separator=':'
-      link_all_deplibs=yes
-      file_list_spec='${wl}-f,'
-
-      if test "$GCC" = yes; then
-	case $host_os in aix4.[012]|aix4.[012].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	  # We have reworked collect2
-	  :
-	  else
-	  # We have old collect2
-	  hardcode_direct=unsupported
-	  # It fails to find uninstalled libraries when the uninstalled
-	  # path is not listed in the libpath.  Setting hardcode_minus_L
-	  # to unsupported forces relinking
-	  hardcode_minus_L=yes
-	  hardcode_libdir_flag_spec='-L$libdir'
-	  hardcode_libdir_separator=
-	  fi
-	  ;;
-	esac
-	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
-	fi
-	link_all_deplibs=no
-      else
-	# not using gcc
-	if test "$host_cpu" = ia64; then
-	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
-	  else
-	    shared_flag='${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      export_dynamic_flag_spec='${wl}-bexpall'
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to export.
-      always_export_symbols=yes
-      if test "$aix_use_runtimelinking" = yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	allow_undefined_flag='-berok'
-        # Determine the default libpath from the value encoded in an
-        # empty executable.
-        if test "${lt_cv_aix_libpath+set}" = set; then
-  aix_libpath=$lt_cv_aix_libpath
-else
-  if ${lt_cv_aix_libpath_+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-  lt_aix_libpath_sed='
-      /Import File Strings/,/^$/ {
-	  /^0/ {
-	      s/^0  *\([^ ]*\) *$/\1/
-	      p
-	  }
-      }'
-  lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  # Check for a 64-bit object if we didn't find anything.
-  if test -z "$lt_cv_aix_libpath_"; then
-    lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  fi
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  if test -z "$lt_cv_aix_libpath_"; then
-    lt_cv_aix_libpath_="/usr/lib:/lib"
-  fi
-
-fi
-
-  aix_libpath=$lt_cv_aix_libpath_
-fi
-
-        hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
-        archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-      else
-	if test "$host_cpu" = ia64; then
-	  hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib'
-	  allow_undefined_flag="-z nodefs"
-	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an
-	 # empty executable.
-	 if test "${lt_cv_aix_libpath+set}" = set; then
-  aix_libpath=$lt_cv_aix_libpath
-else
-  if ${lt_cv_aix_libpath_+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-  lt_aix_libpath_sed='
-      /Import File Strings/,/^$/ {
-	  /^0/ {
-	      s/^0  *\([^ ]*\) *$/\1/
-	      p
-	  }
-      }'
-  lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  # Check for a 64-bit object if we didn't find anything.
-  if test -z "$lt_cv_aix_libpath_"; then
-    lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  fi
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  if test -z "$lt_cv_aix_libpath_"; then
-    lt_cv_aix_libpath_="/usr/lib:/lib"
-  fi
-
-fi
-
-  aix_libpath=$lt_cv_aix_libpath_
-fi
-
-	 hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  no_undefined_flag=' ${wl}-bernotok'
-	  allow_undefined_flag=' ${wl}-berok'
-	  if test "$with_gnu_ld" = yes; then
-	    # We only use this code for GNU lds that support --whole-archive.
-	    whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	  else
-	    # Exported symbols can be pulled into shared objects from archives
-	    whole_archive_flag_spec='$convenience'
-	  fi
-	  archive_cmds_need_lc=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            archive_expsym_cmds=''
-        ;;
-      m68k)
-            archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            hardcode_libdir_flag_spec='-L$libdir'
-            hardcode_minus_L=yes
-        ;;
-      esac
-      ;;
-
-    bsdi[45]*)
-      export_dynamic_flag_spec=-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      case $cc_basename in
-      cl*)
-	# Native MSVC
-	hardcode_libdir_flag_spec=' '
-	allow_undefined_flag=unsupported
-	always_export_symbols=yes
-	file_list_spec='@'
-	# Tell ltmain to make .lib files, not .a files.
-	libext=lib
-	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
-	# FIXME: Setting linknames here is a bad hack.
-	archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	  else
-	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	  fi~
-	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	  linknames='
-	# The linker will not automatically build a static lib if we build a DLL.
-	# _LT_TAGVAR(old_archive_from_new_cmds, )='true'
-	enable_shared_with_static_runtimes=yes
-	exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
-	export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols'
-	# Don't use ranlib
-	old_postinstall_cmds='chmod 644 $oldlib'
-	postlink_cmds='lt_outputfile="@OUTPUT@"~
-	  lt_tool_outputfile="@TOOL_OUTPUT@"~
-	  case $lt_outputfile in
-	    *.exe|*.EXE) ;;
-	    *)
-	      lt_outputfile="$lt_outputfile.exe"
-	      lt_tool_outputfile="$lt_tool_outputfile.exe"
-	      ;;
-	  esac~
-	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	    $RM "$lt_outputfile.manifest";
-	  fi'
-	;;
-      *)
-	# Assume MSVC wrapper
-	hardcode_libdir_flag_spec=' '
-	allow_undefined_flag=unsupported
-	# Tell ltmain to make .lib files, not .a files.
-	libext=lib
-	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
-	# FIXME: Setting linknames here is a bad hack.
-	archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
-	# The linker will automatically build a .lib file if we build a DLL.
-	old_archive_from_new_cmds='true'
-	# FIXME: Should let the user specify the lib program.
-	old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs'
-	enable_shared_with_static_runtimes=yes
-	;;
-      esac
-      ;;
-
-    darwin* | rhapsody*)
-
-
-  archive_cmds_need_lc=no
-  hardcode_direct=no
-  hardcode_automatic=yes
-  hardcode_shlibpath_var=unsupported
-  if test "$lt_cv_ld_force_load" = "yes"; then
-    whole_archive_flag_spec='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
-
-  else
-    whole_archive_flag_spec=''
-  fi
-  link_all_deplibs=yes
-  allow_undefined_flag="$_lt_dar_allow_undefined"
-  case $cc_basename in
-     ifort*) _lt_dar_can_shared=yes ;;
-     *) _lt_dar_can_shared=$GCC ;;
-  esac
-  if test "$_lt_dar_can_shared" = "yes"; then
-    output_verbose_link_cmd=func_echo_all
-    archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-    module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
-    archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-    module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
-
-  else
-  ld_shlibs=no
-  fi
-
-      ;;
-
-    dgux*)
-      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_libdir_flag_spec='-L$libdir'
-      hardcode_shlibpath_var=no
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
-    # support.  Future versions do this automatically, but an explicit c++rt0.o
-    # does not break anything, and helps significantly (at the cost of a little
-    # extra space).
-    freebsd2.2*)
-      archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
-      hardcode_libdir_flag_spec='-R$libdir'
-      hardcode_direct=yes
-      hardcode_shlibpath_var=no
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2.*)
-      archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_direct=yes
-      hardcode_minus_L=yes
-      hardcode_shlibpath_var=no
-      ;;
-
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | dragonfly*)
-      archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-      hardcode_libdir_flag_spec='-R$libdir'
-      hardcode_direct=yes
-      hardcode_shlibpath_var=no
-      ;;
-
-    hpux9*)
-      if test "$GCC" = yes; then
-	archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      else
-	archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      fi
-      hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
-      hardcode_libdir_separator=:
-      hardcode_direct=yes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      hardcode_minus_L=yes
-      export_dynamic_flag_spec='${wl}-E'
-      ;;
-
-    hpux10*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator=:
-	hardcode_direct=yes
-	hardcode_direct_absolute=yes
-	export_dynamic_flag_spec='${wl}-E'
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	hardcode_minus_L=yes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-
-	  # Older versions of the 11.00 compiler do not understand -b yet
-	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
-	  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5
-$as_echo_n "checking if $CC understands -b... " >&6; }
-if ${lt_cv_prog_compiler__b+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_prog_compiler__b=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS -b"
-   echo "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_cv_prog_compiler__b=yes
-       fi
-     else
-       lt_cv_prog_compiler__b=yes
-     fi
-   fi
-   $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5
-$as_echo "$lt_cv_prog_compiler__b" >&6; }
-
-if test x"$lt_cv_prog_compiler__b" = xyes; then
-    archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-else
-    archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-fi
-
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" = no; then
-	hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  hardcode_direct=no
-	  hardcode_shlibpath_var=no
-	  ;;
-	*)
-	  hardcode_direct=yes
-	  hardcode_direct_absolute=yes
-	  export_dynamic_flag_spec='${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  hardcode_minus_L=yes
-	  ;;
-	esac
-      fi
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	# Try to use the -exported_symbol ld option, if it does not
-	# work, assume that -exports_file does not work either and
-	# implicitly export all symbols.
-	# This should be the same for all languages, so no per-tag cache variable.
-	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5
-$as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; }
-if ${lt_cv_irix_exported_symbol+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  save_LDFLAGS="$LDFLAGS"
-	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
-	   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int foo (void) { return 0; }
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  lt_cv_irix_exported_symbol=yes
-else
-  lt_cv_irix_exported_symbol=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-           LDFLAGS="$save_LDFLAGS"
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5
-$as_echo "$lt_cv_irix_exported_symbol" >&6; }
-	if test "$lt_cv_irix_exported_symbol" = yes; then
-          archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
-	fi
-      else
-	archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
-      fi
-      archive_cmds_need_lc='no'
-      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator=:
-      inherit_rpath=yes
-      link_all_deplibs=yes
-      ;;
-
-    netbsd* | netbsdelf*-gnu)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
-      else
-	archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
-      fi
-      hardcode_libdir_flag_spec='-R$libdir'
-      hardcode_direct=yes
-      hardcode_shlibpath_var=no
-      ;;
-
-    newsos6)
-      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_direct=yes
-      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator=:
-      hardcode_shlibpath_var=no
-      ;;
-
-    *nto* | *qnx*)
-      ;;
-
-    openbsd*)
-      if test -f /usr/libexec/ld.so; then
-	hardcode_direct=yes
-	hardcode_shlibpath_var=no
-	hardcode_direct_absolute=yes
-	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	  archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	  archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	  hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-	  export_dynamic_flag_spec='${wl}-E'
-	else
-	  case $host_os in
-	   openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
-	     archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	     hardcode_libdir_flag_spec='-R$libdir'
-	     ;;
-	   *)
-	     archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	     hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
-	     ;;
-	  esac
-	fi
-      else
-	ld_shlibs=no
-      fi
-      ;;
-
-    os2*)
-      hardcode_libdir_flag_spec='-L$libdir'
-      hardcode_minus_L=yes
-      allow_undefined_flag=unsupported
-      archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      if test "$GCC" = yes; then
-	allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	allow_undefined_flag=' -expect_unresolved \*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
-      archive_cmds_need_lc='no'
-      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator=:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" = yes; then
-	allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
-      else
-	allow_undefined_flag=' -expect_unresolved \*'
-	archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
-	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
-
-	# Both c and cxx compiler support -rpath directly
-	hardcode_libdir_flag_spec='-rpath $libdir'
-      fi
-      archive_cmds_need_lc='no'
-      hardcode_libdir_separator=:
-      ;;
-
-    solaris*)
-      no_undefined_flag=' -z defs'
-      if test "$GCC" = yes; then
-	wlarc='${wl}'
-	archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-      else
-	case `$CC -V 2>&1` in
-	*"Compilers 5.0"*)
-	  wlarc=''
-	  archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
-	  ;;
-	*)
-	  wlarc='${wl}'
-	  archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
-	  archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-	  ;;
-	esac
-      fi
-      hardcode_libdir_flag_spec='-R$libdir'
-      hardcode_shlibpath_var=no
-      case $host_os in
-      solaris2.[0-5] | solaris2.[0-5].*) ;;
-      *)
-	# The compiler driver will combine and reorder linker options,
-	# but understands `-z linker_flag'.  GCC discards it without `$wl',
-	# but is careful enough not to reorder.
-	# Supported since Solaris 2.6 (maybe 2.5.1?)
-	if test "$GCC" = yes; then
-	  whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-	else
-	  whole_archive_flag_spec='-z allextract$convenience -z defaultextract'
-	fi
-	;;
-      esac
-      link_all_deplibs=yes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" = xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      hardcode_libdir_flag_spec='-L$libdir'
-      hardcode_direct=yes
-      hardcode_minus_L=yes
-      hardcode_shlibpath_var=no
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  hardcode_direct=yes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  reload_cmds='$CC -r -o $output$reload_objs'
-	  hardcode_direct=no
-        ;;
-	motorola)
-	  archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  hardcode_direct=no #Motorola manual says yes, but my tests say they lie
-	;;
-      esac
-      runpath_var='LD_RUN_PATH'
-      hardcode_shlibpath_var=no
-      ;;
-
-    sysv4.3*)
-      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_shlibpath_var=no
-      export_dynamic_flag_spec='-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	hardcode_shlibpath_var=no
-	runpath_var=LD_RUN_PATH
-	hardcode_runpath_var=yes
-	ld_shlibs=yes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
-      no_undefined_flag='${wl}-z,text'
-      archive_cmds_need_lc=no
-      hardcode_shlibpath_var=no
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      no_undefined_flag='${wl}-z,text'
-      allow_undefined_flag='${wl}-z,nodefs'
-      archive_cmds_need_lc=no
-      hardcode_shlibpath_var=no
-      hardcode_libdir_flag_spec='${wl}-R,$libdir'
-      hardcode_libdir_separator=':'
-      link_all_deplibs=yes
-      export_dynamic_flag_spec='${wl}-Bexport'
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    uts4*)
-      archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      hardcode_libdir_flag_spec='-L$libdir'
-      hardcode_shlibpath_var=no
-      ;;
-
-    *)
-      ld_shlibs=no
-      ;;
-    esac
-
-    if test x$host_vendor = xsni; then
-      case $host in
-      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-	export_dynamic_flag_spec='${wl}-Blargedynsym'
-	;;
-      esac
-    fi
-  fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5
-$as_echo "$ld_shlibs" >&6; }
-test "$ld_shlibs" = no && can_build_shared=no
-
-with_gnu_ld=$with_gnu_ld
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$archive_cmds_need_lc" in
-x|xyes)
-  # Assume -lc should be added
-  archive_cmds_need_lc=yes
-
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
-    case $archive_cmds in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5
-$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; }
-if ${lt_cv_archive_cmds_need_lc+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  $RM conftest*
-	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-	if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
-  (eval $ac_compile) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } 2>conftest.err; then
-	  soname=conftest
-	  lib=conftest
-	  libobjs=conftest.$ac_objext
-	  deplibs=
-	  wl=$lt_prog_compiler_wl
-	  pic_flag=$lt_prog_compiler_pic
-	  compiler_flags=-v
-	  linker_flags=-v
-	  verstring=
-	  output_objdir=.
-	  libname=conftest
-	  lt_save_allow_undefined_flag=$allow_undefined_flag
-	  allow_undefined_flag=
-	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5
-  (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-	  then
-	    lt_cv_archive_cmds_need_lc=no
-	  else
-	    lt_cv_archive_cmds_need_lc=yes
-	  fi
-	  allow_undefined_flag=$lt_save_allow_undefined_flag
-	else
-	  cat conftest.err 1>&5
-	fi
-	$RM conftest*
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5
-$as_echo "$lt_cv_archive_cmds_need_lc" >&6; }
-      archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5
-$as_echo_n "checking dynamic linker characteristics... " >&6; }
-
-if test "$GCC" = yes; then
-  case $host_os in
-    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
-    *) lt_awk_arg="/^libraries:/" ;;
-  esac
-  case $host_os in
-    mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;;
-    *) lt_sed_strip_eq="s,=/,/,g" ;;
-  esac
-  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
-  case $lt_search_path_spec in
-  *\;*)
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that should
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
-    ;;
-  *)
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
-    ;;
-  esac
-  # Ok, now we have the path, separated by spaces, we can step through it
-  # and add multilib dir if necessary.
-  lt_tmp_lt_search_path_spec=
-  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
-  for lt_sys_path in $lt_search_path_spec; do
-    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
-      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
-    else
-      test -d "$lt_sys_path" && \
-	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
-    fi
-  done
-  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
-BEGIN {RS=" "; FS="/|\n";} {
-  lt_foo="";
-  lt_count=0;
-  for (lt_i = NF; lt_i > 0; lt_i--) {
-    if ($lt_i != "" && $lt_i != ".") {
-      if ($lt_i == "..") {
-        lt_count++;
-      } else {
-        if (lt_count == 0) {
-          lt_foo="/" $lt_i lt_foo;
-        } else {
-          lt_count--;
-        }
-      }
-    }
-  }
-  if (lt_foo != "") { lt_freq[lt_foo]++; }
-  if (lt_freq[lt_foo] == 1) { print lt_foo; }
-}'`
-  # AWK program above erroneously prepends '/' to C:/dos/paths
-  # for these hosts.
-  case $host_os in
-    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
-      $SED 's,/\([A-Za-z]:\),\1,g'` ;;
-  esac
-  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
-else
-  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
-fi
-library_names_spec=
-libname_spec='lib$name'
-soname_spec=
-shrext_cmds=".so"
-postinstall_cmds=
-postuninstall_cmds=
-finish_cmds=
-finish_eval=
-shlibpath_var=
-shlibpath_overrides_runpath=unknown
-version_type=none
-dynamic_linker="$host_os ld.so"
-sys_lib_dlsearch_path_spec="/lib /usr/lib"
-need_lib_prefix=unknown
-hardcode_into_libs=no
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=unknown
-
-case $host_os in
-aix3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
-  shlibpath_var=LIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
-  ;;
-
-aix[4-9]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
-    # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=LD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[01] | aix4.[01].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
-	:
-      else
-	can_build_shared=no
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=LIBPATH
-  fi
-  ;;
-
-amigaos*)
-  case $host_cpu in
-  powerpc)
-    # Since July 2007 AmigaOS4 officially supports .so libraries.
-    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    ;;
-  m68k)
-    library_names_spec='$libname.ixlibrary $libname.a'
-    # Create ${libname}_ixlibrary.a entries in /sys/libs.
-    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
-    ;;
-  esac
-  ;;
-
-beos*)
-  library_names_spec='${libname}${shared_ext}'
-  dynamic_linker="$host_os ld.so"
-  shlibpath_var=LIBRARY_PATH
-  ;;
-
-bsdi[45]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32* | cegcc*)
-  version_type=windows
-  shrext_cmds=".dll"
-  need_version=no
-  need_lib_prefix=no
-
-  case $GCC,$cc_basename in
-  yes,*)
-    # gcc
-    library_names_spec='$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname~
-      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
-        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
-      fi'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-
-      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"
-      ;;
-    mingw* | cegcc*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    dynamic_linker='Win32 ld.exe'
-    ;;
-
-  *,cl*)
-    # Native MSVC
-    libname_spec='$name'
-    soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-    library_names_spec='${libname}.dll.lib'
-
-    case $build_os in
-    mingw*)
-      sys_lib_search_path_spec=
-      lt_save_ifs=$IFS
-      IFS=';'
-      for lt_path in $LIB
-      do
-        IFS=$lt_save_ifs
-        # Let DOS variable expansion print the short 8.3 style file name.
-        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
-        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
-      done
-      IFS=$lt_save_ifs
-      # Convert to MSYS style.
-      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
-      ;;
-    cygwin*)
-      # Convert to unix form, then to dos form, then back to unix form
-      # but this time dos style (no spaces!) so that the unix form looks
-      # like /cygdrive/c/PROGRA~1:/cygdr...
-      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
-      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
-      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
-      ;;
-    *)
-      sys_lib_search_path_spec="$LIB"
-      if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then
-        # It is most probably a Windows format PATH.
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      # FIXME: find the short name or the path components, as spaces are
-      # common. (e.g. "Program Files" -> "PROGRA~1")
-      ;;
-    esac
-
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-    dynamic_linker='Win32 link.exe'
-    ;;
-
-  *)
-    # Assume MSVC wrapper
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib'
-    dynamic_linker='Win32 ld.exe'
-    ;;
-  esac
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=PATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker="$host_os dyld"
-  version_type=darwin
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=yes
-  shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
-
-  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"
-  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[23].*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
-  version_type=freebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=no
-      need_lib_prefix=no
-      ;;
-    freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
-      need_version=yes
-      ;;
-  esac
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_os in
-  freebsd2.*)
-    shlibpath_overrides_runpath=yes
-    ;;
-  freebsd3.[01]* | freebsdelf3.[01]*)
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=no
-    hardcode_into_libs=yes
-    ;;
-  *) # from 4.6 on, and DragonFly
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  esac
-  ;;
-
-haiku*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  dynamic_linker="$host_os runtime_loader"
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
-  hardcode_into_libs=yes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuses to
-  # link against other versions.
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  case $host_cpu in
-  ia64*)
-    shrext_cmds='.so'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.so"
-    shlibpath_var=LD_LIBRARY_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
-      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
-    else
-      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  hppa*64*)
-    shrext_cmds='.sl'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  *)
-    shrext_cmds='.sl'
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=SHLIB_PATH
-    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
-  postinstall_cmds='chmod 555 $lib'
-  # or fails outright, so override atomically:
-  install_override_mode=555
-  ;;
-
-interix[3-9]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux # correct to gnu/linux during the next big refactor
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-
-  # Some binutils ld are patched to set DT_RUNPATH
-  if ${lt_cv_shlibpath_overrides_runpath+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  lt_cv_shlibpath_overrides_runpath=no
-    save_LDFLAGS=$LDFLAGS
-    save_libdir=$libdir
-    eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \
-	 LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\""
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  if  ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then :
-  lt_cv_shlibpath_overrides_runpath=yes
-fi
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-    LDFLAGS=$save_LDFLAGS
-    libdir=$save_libdir
-
-fi
-
-  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
-
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
-
-netbsdelf*-gnu)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='NetBSD ld.elf_so'
-  ;;
-
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
-
-newsos6)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
-
-*nto* | *qnx*)
-  version_type=qnx
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='ldqnx.so'
-  ;;
-
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=yes
-  fi
-  ;;
-
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
-
-rdos*)
-  dynamic_linker=no
-  ;;
-
-solaris*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      runpath_var=LD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=no
-      ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux # correct to gnu/linux during the next big refactor
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
-tpf*)
-  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-uts4*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=no
-  ;;
-esac
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
-$as_echo "$dynamic_linker" >&6; }
-test "$dynamic_linker" = no && can_build_shared=no
-
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
-fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5
-$as_echo_n "checking how to hardcode library paths into programs... " >&6; }
-hardcode_action=
-if test -n "$hardcode_libdir_flag_spec" ||
-   test -n "$runpath_var" ||
-   test "X$hardcode_automatic" = "Xyes" ; then
-
-  # We can hardcode non-existent directories.
-  if test "$hardcode_direct" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no &&
-     test "$hardcode_minus_L" != no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action=unsupported
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5
-$as_echo "$hardcode_action" >&6; }
-
-if test "$hardcode_action" = relink ||
-   test "$inherit_rpath" = yes; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
-fi
-
-
-
-
-
-
-  if test "x$enable_dlopen" != xyes; then
-  enable_dlopen=unknown
-  enable_dlopen_self=unknown
-  enable_dlopen_self_static=unknown
-else
-  lt_cv_dlopen=no
-  lt_cv_dlopen_libs=
-
-  case $host_os in
-  beos*)
-    lt_cv_dlopen="load_add_on"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ;;
-
-  mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
-    lt_cv_dlopen_libs=
-    ;;
-
-  cygwin*)
-    lt_cv_dlopen="dlopen"
-    lt_cv_dlopen_libs=
-    ;;
-
-  darwin*)
-  # if libdl is installed we need to link against it
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
-$as_echo_n "checking for dlopen in -ldl... " >&6; }
-if ${ac_cv_lib_dl_dlopen+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dl_dlopen=yes
-else
-  ac_cv_lib_dl_dlopen=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
-$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
-if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
-else
-
-    lt_cv_dlopen="dyld"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-
-fi
-
-    ;;
-
-  *)
-    ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
-if test "x$ac_cv_func_shl_load" = xyes; then :
-  lt_cv_dlopen="shl_load"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
-$as_echo_n "checking for shl_load in -ldld... " >&6; }
-if ${ac_cv_lib_dld_shl_load+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldld  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char shl_load ();
-int
-main ()
-{
-return shl_load ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dld_shl_load=yes
-else
-  ac_cv_lib_dld_shl_load=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
-$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
-if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
-  lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"
-else
-  ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
-if test "x$ac_cv_func_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
-$as_echo_n "checking for dlopen in -ldl... " >&6; }
-if ${ac_cv_lib_dl_dlopen+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dl_dlopen=yes
-else
-  ac_cv_lib_dl_dlopen=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
-$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
-if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5
-$as_echo_n "checking for dlopen in -lsvld... " >&6; }
-if ${ac_cv_lib_svld_dlopen+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lsvld  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_svld_dlopen=yes
-else
-  ac_cv_lib_svld_dlopen=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5
-$as_echo "$ac_cv_lib_svld_dlopen" >&6; }
-if test "x$ac_cv_lib_svld_dlopen" = xyes; then :
-  lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5
-$as_echo_n "checking for dld_link in -ldld... " >&6; }
-if ${ac_cv_lib_dld_dld_link+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldld  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dld_link ();
-int
-main ()
-{
-return dld_link ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_dld_dld_link=yes
-else
-  ac_cv_lib_dld_dld_link=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5
-$as_echo "$ac_cv_lib_dld_dld_link" >&6; }
-if test "x$ac_cv_lib_dld_dld_link" = xyes; then :
-  lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"
-fi
-
-
-fi
-
-
-fi
-
-
-fi
-
-
-fi
-
-
-fi
-
-    ;;
-  esac
-
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
-    enable_dlopen=no
-  fi
-
-  case $lt_cv_dlopen in
-  dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
-
-    save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
-
-    save_LIBS="$LIBS"
-    LIBS="$lt_cv_dlopen_libs $LIBS"
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5
-$as_echo_n "checking whether a program can dlopen itself... " >&6; }
-if ${lt_cv_dlopen_self+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  	  if test "$cross_compiling" = yes; then :
-  lt_cv_dlopen_self=cross
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-#line $LINENO "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-/* When -fvisbility=hidden is used, assume the code has been annotated
-   correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
-int fnord () __attribute__((visibility("default")));
-#endif
-
-int fnord () { return 42; }
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else
-        {
-	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
-          else puts (dlerror ());
-	}
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}
-_LT_EOF
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&5 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;;
-      x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;;
-      x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;;
-    esac
-  else :
-    # compilation failed
-    lt_cv_dlopen_self=no
-  fi
-fi
-rm -fr conftest*
-
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
-$as_echo "$lt_cv_dlopen_self" >&6; }
-
-    if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5
-$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; }
-if ${lt_cv_dlopen_self_static+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  	  if test "$cross_compiling" = yes; then :
-  lt_cv_dlopen_self_static=cross
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-#line $LINENO "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-/* When -fvisbility=hidden is used, assume the code has been annotated
-   correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
-int fnord () __attribute__((visibility("default")));
-#endif
-
-int fnord () { return 42; }
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else
-        {
-	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
-          else puts (dlerror ());
-	}
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}
-_LT_EOF
-  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
-  (eval $ac_link) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&5 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;;
-      x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;;
-      x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;;
-    esac
-  else :
-    # compilation failed
-    lt_cv_dlopen_self_static=no
-  fi
-fi
-rm -fr conftest*
-
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5
-$as_echo "$lt_cv_dlopen_self_static" >&6; }
-    fi
-
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-    ;;
-  esac
-
-  case $lt_cv_dlopen_self in
-  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
-  *) enable_dlopen_self=unknown ;;
-  esac
-
-  case $lt_cv_dlopen_self_static in
-  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
-  *) enable_dlopen_self_static=unknown ;;
-  esac
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-striplib=
-old_striplib=
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5
-$as_echo_n "checking whether stripping libraries is possible... " >&6; }
-if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
-  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-  darwin*)
-    if test -n "$STRIP" ; then
-      striplib="$STRIP -x"
-      old_striplib="$STRIP -S"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-    else
-      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-    fi
-    ;;
-  *)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-    ;;
-  esac
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-  # Report which library types will actually be built
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5
-$as_echo_n "checking if libtool supports shared libraries... " >&6; }
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5
-$as_echo "$can_build_shared" >&6; }
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5
-$as_echo_n "checking whether to build shared libraries... " >&6; }
-  test "$can_build_shared" = "no" && enable_shared=no
-
-  # On AIX, shared libraries and static libraries use the same namespace, and
-  # are all built from PIC.
-  case $host_os in
-  aix3*)
-    test "$enable_shared" = yes && enable_static=no
-    if test -n "$RANLIB"; then
-      archive_cmds="$archive_cmds~\$RANLIB \$lib"
-      postinstall_cmds='$RANLIB $lib'
-    fi
-    ;;
-
-  aix[4-9]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
-    fi
-    ;;
-  esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5
-$as_echo "$enable_shared" >&6; }
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5
-$as_echo_n "checking whether to build static libraries... " >&6; }
-  # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5
-$as_echo "$enable_static" >&6; }
-
-
-
-
-fi
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-CC="$lt_save_CC"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-        ac_config_commands="$ac_config_commands libtool"
-
-
-
-
-# Only expand once:
-
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}windres", so it can be a program name with args.
-set dummy ${ac_tool_prefix}windres; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$RC"; then
-  ac_cv_prog_RC="$RC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RC="${ac_tool_prefix}windres"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-RC=$ac_cv_prog_RC
-if test -n "$RC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RC" >&5
-$as_echo "$RC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_RC"; then
-  ac_ct_RC=$RC
-  # Extract the first word of "windres", so it can be a program name with args.
-set dummy windres; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ac_ct_RC"; then
-  ac_cv_prog_ac_ct_RC="$ac_ct_RC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RC="windres"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_RC=$ac_cv_prog_ac_ct_RC
-if test -n "$ac_ct_RC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RC" >&5
-$as_echo "$ac_ct_RC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_RC" = x; then
-    RC=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    RC=$ac_ct_RC
-  fi
-else
-  RC="$ac_cv_prog_RC"
-fi
-
-
-
-
-# Source file extension for RC test sources.
-ac_ext=rc
-
-# Object file extension for compiled RC test sources.
-objext=o
-objext_RC=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
-
-# Code to be used in simple link tests
-lt_simple_link_test_code="$lt_simple_compile_test_code"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-
-
-
-
-
-
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=$CC
-
-
-# save warnings/boilerplate of simple test code
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$RM conftest*
-
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$RM -r conftest*
-
-
-# Allow CC to be a program name with arguments.
-lt_save_CC="$CC"
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=
-CC=${RC-"windres"}
-CFLAGS=
-compiler=$CC
-compiler_RC=$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
-
-lt_cv_prog_compiler_c_o_RC=yes
-
-if test -n "$compiler"; then
-  :
-
-
-
-fi
-
-GCC=$lt_save_GCC
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-
-
-PACKAGE_VERSION_MAJOR=${PACKAGE_VERSION%.*.*}
-PACKAGE_VERSION_MINOR=${PACKAGE_VERSION%.*}; PACKAGE_VERSION_MINOR=${PACKAGE_VERSION_MINOR#*.}
-PACKAGE_VERSION_SUBMINOR=${PACKAGE_VERSION#*.*.}
-
-
-
-ac_config_files="$ac_config_files src/microhttpd/microhttpd_dll_res.rc"
-
-
-MHD_LIB_CPPFLAGS=""
-MHD_LIB_CFLAGS=""
-MHD_LIB_LDFLAGS=""
-MHD_LIBDEPS=""
-
-
-# Check whether --with-threads was given.
-if test "${with_threads+set}" = set; then :
-  withval=$with_threads;
-else
-  with_threads='auto'
-fi
-
-test "x$with_threads" = "xwin32" && with_threads='w32'
-test "x$with_threads" = "xpthreads" && with_threads='posix'
-
-# Check for posix threads support
-
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-ax_pthread_ok=no
-
-# We used to check for pthread.h first, but this fails if pthread.h
-# requires special compiler flags (e.g. on True64 or Sequent).
-# It gets checked for in the link test anyway.
-
-# First of all, check if the user has set any of the PTHREAD_LIBS,
-# etcetera environment variables, and if threads linking works using
-# them:
-if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
-        save_CFLAGS="$CFLAGS"
-        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-        save_LIBS="$LIBS"
-        LIBS="$PTHREAD_LIBS $LIBS"
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS" >&5
-$as_echo_n "checking for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS... " >&6; }
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char pthread_join ();
-int
-main ()
-{
-return pthread_join ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ax_pthread_ok=yes
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_pthread_ok" >&5
-$as_echo "$ax_pthread_ok" >&6; }
-        if test x"$ax_pthread_ok" = xno; then
-                PTHREAD_LIBS=""
-                PTHREAD_CFLAGS=""
-        fi
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
-fi
-
-# We must check for the threads library under a number of different
-# names; the ordering is very important because some systems
-# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
-# libraries is broken (non-POSIX).
-
-# Create a list of thread flags to try.  Items starting with a "-" are
-# C compiler flags, and other items are library names, except for "none"
-# which indicates that we try without any flags at all, and "pthread-config"
-# which is a program returning the flags for the Pth emulation library.
-
-ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
-
-# The ordering *is* (sometimes) important.  Some notes on the
-# individual items follow:
-
-# pthreads: AIX (must check this before -lpthread)
-# none: in case threads are in libc; should be tried before -Kthread and
-#       other compiler flags to prevent continual compiler warnings
-# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
-# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
-# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
-# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
-# -pthreads: Solaris/gcc
-# -mthreads: Mingw32/gcc, Lynx/gcc
-# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
-#      doesn't hurt to check since this sometimes defines pthreads too;
-#      also defines -D_REENTRANT)
-#      ... -mt is also the pthreads flag for HP/aCC
-# pthread: Linux, etcetera
-# --thread-safe: KAI C++
-# pthread-config: use pthread-config program (for GNU Pth library)
-
-case ${host_os} in
-        solaris*)
-
-        # On Solaris (at least, for some versions), libc contains stubbed
-        # (non-functional) versions of the pthreads routines, so link-based
-        # tests will erroneously succeed.  (We need to link with -pthreads/-mt/
-        # -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
-        # a function called by this macro, so we could check for that, but
-        # who knows whether they'll stub that too in a future libc.)  So,
-        # we'll just look for -pthreads and -lpthread first:
-
-        ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags"
-        ;;
-
-        darwin*)
-        ax_pthread_flags="-pthread $ax_pthread_flags"
-        ;;
-esac
-
-# Clang doesn't consider unrecognized options an error unless we specify
-# -Werror. We throw in some extra Clang-specific options to ensure that
-# this doesn't happen for GCC, which also accepts -Werror.
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler needs -Werror to reject unknown flags" >&5
-$as_echo_n "checking if compiler needs -Werror to reject unknown flags... " >&6; }
-save_CFLAGS="$CFLAGS"
-ax_pthread_extra_flags="-Werror"
-CFLAGS="$CFLAGS $ax_pthread_extra_flags -Wunknown-warning-option -Wsizeof-array-argument"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int foo(void);
-int
-main ()
-{
-foo()
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
-  ax_pthread_extra_flags=
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-CFLAGS="$save_CFLAGS"
-
-if test x"$ax_pthread_ok" = xno; then
-for flag in $ax_pthread_flags; do
-
-        case $flag in
-                none)
-                { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads work without any flags" >&5
-$as_echo_n "checking whether pthreads work without any flags... " >&6; }
-                ;;
-
-                -*)
-                { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads work with $flag" >&5
-$as_echo_n "checking whether pthreads work with $flag... " >&6; }
-                PTHREAD_CFLAGS="$flag"
-                ;;
-
-                pthread-config)
-                # Extract the first word of "pthread-config", so it can be a program name with args.
-set dummy pthread-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ax_pthread_config+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$ax_pthread_config"; then
-  ac_cv_prog_ax_pthread_config="$ax_pthread_config" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ax_pthread_config="yes"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_prog_ax_pthread_config" && ac_cv_prog_ax_pthread_config="no"
-fi
-fi
-ax_pthread_config=$ac_cv_prog_ax_pthread_config
-if test -n "$ax_pthread_config"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_pthread_config" >&5
-$as_echo "$ax_pthread_config" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-                if test x"$ax_pthread_config" = xno; then continue; fi
-                PTHREAD_CFLAGS="`pthread-config --cflags`"
-                PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
-                ;;
-
-                *)
-                { $as_echo "$as_me:${as_lineno-$LINENO}: checking for the pthreads library -l$flag" >&5
-$as_echo_n "checking for the pthreads library -l$flag... " >&6; }
-                PTHREAD_LIBS="-l$flag"
-                ;;
-        esac
-
-        save_LIBS="$LIBS"
-        save_CFLAGS="$CFLAGS"
-        LIBS="$PTHREAD_LIBS $LIBS"
-        CFLAGS="$CFLAGS $PTHREAD_CFLAGS $ax_pthread_extra_flags"
-
-        # Check for various functions.  We must include pthread.h,
-        # since some functions may be macros.  (On the Sequent, we
-        # need a special flag -Kthread to make this header compile.)
-        # We check for pthread_join because it is in -lpthread on IRIX
-        # while pthread_create is in libc.  We check for pthread_attr_init
-        # due to DEC craziness with -lpthreads.  We check for
-        # pthread_cleanup_push because it is one of the few pthread
-        # functions on Solaris that doesn't have a non-functional libc stub.
-        # We try pthread_create on general principles.
-        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <pthread.h>
-                        static void routine(void *a) { a = 0; }
-                        static void *start_routine(void *a) { return a; }
-int
-main ()
-{
-pthread_t th; pthread_attr_t attr;
-                        pthread_create(&th, 0, start_routine, 0);
-                        pthread_join(th, 0);
-                        pthread_attr_init(&attr);
-                        pthread_cleanup_push(routine, 0);
-                        pthread_cleanup_pop(0) /* ; */
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ax_pthread_ok=yes
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_pthread_ok" >&5
-$as_echo "$ax_pthread_ok" >&6; }
-        if test "x$ax_pthread_ok" = xyes; then
-                break;
-        fi
-
-        PTHREAD_LIBS=""
-        PTHREAD_CFLAGS=""
-done
-fi
-
-# Various other checks:
-if test "x$ax_pthread_ok" = xyes; then
-        save_LIBS="$LIBS"
-        LIBS="$PTHREAD_LIBS $LIBS"
-        save_CFLAGS="$CFLAGS"
-        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-
-        # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for joinable pthread attribute" >&5
-$as_echo_n "checking for joinable pthread attribute... " >&6; }
-        attr_name=unknown
-        for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
-            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <pthread.h>
-int
-main ()
-{
-int attr = $attr; return attr /* ; */
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  attr_name=$attr; break
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-        done
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $attr_name" >&5
-$as_echo "$attr_name" >&6; }
-        if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
-
-cat >>confdefs.h <<_ACEOF
-#define PTHREAD_CREATE_JOINABLE $attr_name
-_ACEOF
-
-        fi
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking if more special flags are required for pthreads" >&5
-$as_echo_n "checking if more special flags are required for pthreads... " >&6; }
-        flag=no
-        case ${host_os} in
-            aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";;
-            osf* | hpux*) flag="-D_REENTRANT";;
-            solaris*)
-            if test "$GCC" = "yes"; then
-                flag="-D_REENTRANT"
-            else
-                # TODO: What about Clang on Solaris?
-                flag="-mt -D_REENTRANT"
-            fi
-            ;;
-        esac
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $flag" >&5
-$as_echo "$flag" >&6; }
-        if test "x$flag" != xno; then
-            PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
-        fi
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PTHREAD_PRIO_INHERIT" >&5
-$as_echo_n "checking for PTHREAD_PRIO_INHERIT... " >&6; }
-if ${ax_cv_PTHREAD_PRIO_INHERIT+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-                cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <pthread.h>
-int
-main ()
-{
-int i = PTHREAD_PRIO_INHERIT;
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ax_cv_PTHREAD_PRIO_INHERIT=yes
-else
-  ax_cv_PTHREAD_PRIO_INHERIT=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_PTHREAD_PRIO_INHERIT" >&5
-$as_echo "$ax_cv_PTHREAD_PRIO_INHERIT" >&6; }
-        if test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"; then :
-
-$as_echo "#define HAVE_PTHREAD_PRIO_INHERIT 1" >>confdefs.h
-
-fi
-
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
-
-        # More AIX lossage: compile with *_r variant
-        if test "x$GCC" != xyes; then
-            case $host_os in
-                aix*)
-                case "x/$CC" in #(
-  x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6) :
-    #handle absolute path differently from PATH based program lookup
-                   case "x$CC" in #(
-  x/*) :
-    if as_fn_executable_p ${CC}_r; then :
-  PTHREAD_CC="${CC}_r"
-fi ;; #(
-  *) :
-    for ac_prog in ${CC}_r
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_PTHREAD_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$PTHREAD_CC"; then
-  ac_cv_prog_PTHREAD_CC="$PTHREAD_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_PTHREAD_CC="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-PTHREAD_CC=$ac_cv_prog_PTHREAD_CC
-if test -n "$PTHREAD_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PTHREAD_CC" >&5
-$as_echo "$PTHREAD_CC" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$PTHREAD_CC" && break
-done
-test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
- ;;
-esac ;; #(
-  *) :
-     ;;
-esac
-                ;;
-            esac
-        fi
-fi
-
-test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
-
-
-
-
-
-# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
-if test x"$ax_pthread_ok" = xyes; then
-        HAVE_POSIX_THREADS='yes'
-        :
-else
-        ax_pthread_ok=no
-        HAVE_POSIX_THREADS='no'
-fi
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
- if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-  HAVE_POSIX_THREADS_TRUE=
-  HAVE_POSIX_THREADS_FALSE='#'
-else
-  HAVE_POSIX_THREADS_TRUE='#'
-  HAVE_POSIX_THREADS_FALSE=
-fi
-
-# Simple check for W32 threads support
-ac_fn_c_check_header_mongrel "$LINENO" "windows.h" "ac_cv_header_windows_h" "$ac_includes_default"
-if test "x$ac_cv_header_windows_h" = xyes; then :
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for CreateThread()" >&5
-$as_echo_n "checking for CreateThread()... " >&6; }
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <windows.h>
-int
-main ()
-{
- HANDLE h = CreateThread(NULL, 0, NULL, NULL, 0, NULL);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-        HAVE_W32_THREADS='yes'
-
-else
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-        HAVE_W32_THREADS='no'
-
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-else
-  HAVE_W32_THREADS='no'
-fi
-
-
-
-# for pkg-config
-MHD_LIBDEPS=""
-MHD_REQ_PRIVATE=''
-# Check system type
-case "$host_os" in
-*darwin* | *rhapsody* | *macosx*)
-
-cat >>confdefs.h <<_ACEOF
-#define OSX 1
-_ACEOF
-
-     CFLAGS="-no-cpp-precomp -fno-common $CFLAGS"
-     ;;
-freebsd*)
-
-cat >>confdefs.h <<_ACEOF
-#define SOMEBSD 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define FREEBSD 1
-_ACEOF
-
-     ;;
-openbsd*)
-
-cat >>confdefs.h <<_ACEOF
-#define SOMEBSD 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define OPENBSD 1
-_ACEOF
-
-     ;;
-netbsd*)
-
-cat >>confdefs.h <<_ACEOF
-#define SOMEBSD 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define NETBSD 1
-_ACEOF
-
-     ;;
-*solaris*)
-
-cat >>confdefs.h <<_ACEOF
-#define SOLARIS 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define _REENTRANT 1
-_ACEOF
-
-     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gethostbyname" >&5
-$as_echo_n "checking for library containing gethostbyname... " >&6; }
-if ${ac_cv_search_gethostbyname+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gethostbyname ();
-int
-main ()
-{
-return gethostbyname ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' nsl; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_gethostbyname=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_gethostbyname+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_gethostbyname+:} false; then :
-
-else
-  ac_cv_search_gethostbyname=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gethostbyname" >&5
-$as_echo "$ac_cv_search_gethostbyname" >&6; }
-ac_res=$ac_cv_search_gethostbyname
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing socket" >&5
-$as_echo_n "checking for library containing socket... " >&6; }
-if ${ac_cv_search_socket+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char socket ();
-int
-main ()
-{
-return socket ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' socket; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_socket=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_socket+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_socket+:} false; then :
-
-else
-  ac_cv_search_socket=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_socket" >&5
-$as_echo "$ac_cv_search_socket" >&6; }
-ac_res=$ac_cv_search_socket
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-     ;;
-*arm-linux*)
-
-cat >>confdefs.h <<_ACEOF
-#define LINUX 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_LISTEN_SHUTDOWN 1
-_ACEOF
-
-     CFLAGS="-fPIC -pipe $CFLAGS"
-     ;;
-*linux*)
-
-cat >>confdefs.h <<_ACEOF
-#define LINUX 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_LISTEN_SHUTDOWN 1
-_ACEOF
-
-     ;;
-*cygwin*)
-
-cat >>confdefs.h <<_ACEOF
-#define CYGWIN 1
-_ACEOF
-
-     os_is_windows=yes
-     ;;
-*mingw*)
-
-cat >>confdefs.h <<_ACEOF
-#define MINGW 1
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define WINDOWS 1
-_ACEOF
-
-     LIBS="$LIBS -lws2_32"
-     for ac_header in winsock2.h ws2tcpip.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-else
-  as_fn_error $? "Winsock2 headers are required for W32" "$LINENO" 5
-fi
-
-done
-
-     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for MS lib utility" >&5
-$as_echo_n "checking for MS lib utility... " >&6; }
-if ${ac_cv_use_ms_lib_tool+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  mslibcheck=`lib 2>&1`
-        if [[ $mslibcheck = "Microsoft (R) Library Manager"* ]]; then
-          ac_cv_use_ms_lib_tool=yes
-        else
-          ac_cv_use_ms_lib_tool=no
-        fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_use_ms_lib_tool" >&5
-$as_echo "$ac_cv_use_ms_lib_tool" >&6; }
-     if test "x$ac_cv_use_ms_lib_tool" = "xyes"; then
-       MS_LIB_TOOL=lib
-
-     fi
-
-     os_is_windows=yes
-     os_is_native_w32=yes
-     ;;
-*openedition*)
-
-cat >>confdefs.h <<_ACEOF
-#define OS390 1
-_ACEOF
-
-    ;;
-*)
-     { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unrecognised OS $host_os" >&5
-$as_echo "$as_me: WARNING: Unrecognised OS $host_os" >&2;}
-
-cat >>confdefs.h <<_ACEOF
-#define OTHEROS 1
-_ACEOF
-
-#    You might want to find out if your OS supports shutdown on listen sockets,
-#    and extend the switch statement; if we do not have 'HAVE_LISTEN_SHUTDOWN',
-#    pipes are used instead to signal 'select'.
-#    AC_DEFINE_UNQUOTED(HAVE_LISTEN_SHUTDOWN,1,[can use shutdown on listen sockets])
-;;
-esac
-
-if test "x$with_threads" = "xposix"; then
-# forced posix threads
-  if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-    USE_THREADS='posix'
-  else
-    if test "x$HAVE_W32_THREADS" = "xyes"; then
-      as_fn_error $? "Posix threads are not available. Try to configure --with-threads=auto" "$LINENO" 5
-    else
-      as_fn_error $? "Posix threads are not available" "$LINENO" 5
-    fi
-  fi
-elif test "x$with_threads" = "xw32"; then
-# forced w32 threads
-  if test "x$HAVE_W32_THREADS" = "xyes"; then
-    USE_THREADS='w32'
-  else
-    if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-      as_fn_error $? "W32 threads are not available. Try to configure --with-threads=auto" "$LINENO" 5
-    else
-      as_fn_error $? "W32 threads are not available" "$LINENO" 5
-    fi
-  fi
-else
-# automatic threads lib selection
-  if test "x$HAVE_POSIX_THREADS" = "xyes" && test "x$HAVE_W32_THREADS" = "xyes"; then
-    if test "x$os_is_native_w32" = "xyes"; then
-      USE_THREADS='w32'
-    else
-      USE_THREADS='posix'
-    fi
-  elif test "x$HAVE_POSIX_THREADS" = "xyes"; then
-    USE_THREADS='posix'
-  elif test "x$HAVE_W32_THREADS" = "xyes"; then
-    USE_THREADS='w32'
-  else
-    as_fn_error $? "No threading lib is available. Cosider installing pthreads" "$LINENO" 5
-  fi
-fi
-
-if test "x$USE_THREADS" = "xposix"; then
-  CC="$PTHREAD_CC"
-
-$as_echo "#define MHD_USE_POSIX_THREADS 1" >>confdefs.h
-
-  MHD_LIB_CFLAGS="$MHD_LIB_CFLAGS $PTHREAD_CFLAGS"
-  MHD_LIBDEPS="$PTHREAD_LIBS $MHD_LIBDEPS"
-elif test "x$USE_THREADS" = "xw32"; then
-
-$as_echo "#define MHD_USE_W32_THREADS 1" >>confdefs.h
-
-fi
- if test "x$USE_THREADS" = "xposix"; then
-  USE_POSIX_THREADS_TRUE=
-  USE_POSIX_THREADS_FALSE='#'
-else
-  USE_POSIX_THREADS_TRUE='#'
-  USE_POSIX_THREADS_FALSE=
-fi
-
- if test "x$USE_THREADS" = "xw32"; then
-  USE_W32_THREADS_TRUE=
-  USE_W32_THREADS_FALSE='#'
-else
-  USE_W32_THREADS_TRUE='#'
-  USE_W32_THREADS_FALSE=
-fi
-
-
-
- if test "x$os_is_native_w32" = "xyes"; then
-  HAVE_W32_TRUE=
-  HAVE_W32_FALSE='#'
-else
-  HAVE_W32_TRUE='#'
-  HAVE_W32_FALSE=
-fi
-
-w32_shared_lib_exp=no
-if test "x$enable_shared" = "xyes" && test "x$os_is_native_w32" = "xyes"; then
-  if test "x$ac_cv_use_ms_lib_tool" = "xyes" || test -n "$DLLTOOL"; then
-    w32_shared_lib_exp=yes
-  else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: GNU dlltool or MS lib.exe is required for creating shared library export on W32" >&5
-$as_echo "$as_me: WARNING: GNU dlltool or MS lib.exe is required for creating shared library export on W32" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Export library libmicrohttpd.lib will not be created" >&5
-$as_echo "$as_me: WARNING: Export library libmicrohttpd.lib will not be created" >&2;}
-  fi
-fi
- if test "x$w32_shared_lib_exp" = "xyes"; then
-  W32_SHARED_LIB_EXP_TRUE=
-  W32_SHARED_LIB_EXP_FALSE='#'
-else
-  W32_SHARED_LIB_EXP_TRUE='#'
-  W32_SHARED_LIB_EXP_FALSE=
-fi
-
- if test "x$ac_cv_use_ms_lib_tool" = "xyes"; then
-  USE_MS_LIB_TOOL_TRUE=
-  USE_MS_LIB_TOOL_FALSE='#'
-else
-  USE_MS_LIB_TOOL_TRUE='#'
-  USE_MS_LIB_TOOL_FALSE=
-fi
-
-
-# set GCC options
-# use '-fno-strict-aliasing', but only if the compiler
-# and linker can take it
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the linker accepts -fno-strict-aliasing" >&5
-$as_echo_n "checking whether the linker accepts -fno-strict-aliasing... " >&6; }
-if ${ax_cv_check_ldflags___fno_strict_aliasing+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-  ax_check_save_flags=$LDFLAGS
-  LDFLAGS="$LDFLAGS  -fno-strict-aliasing"
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ax_cv_check_ldflags___fno_strict_aliasing=yes
-else
-  ax_cv_check_ldflags___fno_strict_aliasing=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  LDFLAGS=$ax_check_save_flags
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_check_ldflags___fno_strict_aliasing" >&5
-$as_echo "$ax_cv_check_ldflags___fno_strict_aliasing" >&6; }
-if test x"$ax_cv_check_ldflags___fno_strict_aliasing" = xyes; then :
-
-
-
-
-for flag in -fno-strict-aliasing; do
-  as_CACHEVAR=`$as_echo "ax_cv_check_cflags__$flag" | $as_tr_sh`
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C compiler accepts $flag" >&5
-$as_echo_n "checking whether C compiler accepts $flag... " >&6; }
-if eval \${$as_CACHEVAR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-  ax_check_save_flags=$CFLAGS
-  CFLAGS="$CFLAGS  $flag"
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  eval "$as_CACHEVAR=yes"
-else
-  eval "$as_CACHEVAR=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  CFLAGS=$ax_check_save_flags
-fi
-eval ac_res=\$$as_CACHEVAR
-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-if test x"`eval 'as_val=${'$as_CACHEVAR'};$as_echo "$as_val"'`" = xyes; then :
-  if ${CFLAGS+:} false; then :
-  case " $CFLAGS " in
-    *" $flag "*)
-      { { $as_echo "$as_me:${as_lineno-$LINENO}: : CFLAGS already contains \$flag"; } >&5
-  (: CFLAGS already contains $flag) 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-      ;;
-    *)
-      { { $as_echo "$as_me:${as_lineno-$LINENO}: : CFLAGS=\"\$CFLAGS \$flag\""; } >&5
-  (: CFLAGS="$CFLAGS $flag") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }
-      CFLAGS="$CFLAGS $flag"
-      ;;
-   esac
-else
-  CFLAGS="$flag"
-fi
-
-else
-  :
-fi
-
-done
-
-else
-  :
-fi
-
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
-$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if ${ac_cv_c_bigendian+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_c_bigendian=unknown
-    # See if we're dealing with a universal compiler.
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#ifndef __APPLE_CC__
-	       not a universal capable compiler
-	     #endif
-	     typedef int dummy;
-
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-	# Check for potential -arch flags.  It is not universal unless
-	# there are at least two -arch flags with different values.
-	ac_arch=
-	ac_prev=
-	for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do
-	 if test -n "$ac_prev"; then
-	   case $ac_word in
-	     i?86 | x86_64 | ppc | ppc64)
-	       if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then
-		 ac_arch=$ac_word
-	       else
-		 ac_cv_c_bigendian=universal
-		 break
-	       fi
-	       ;;
-	   esac
-	   ac_prev=
-	 elif test "x$ac_word" = "x-arch"; then
-	   ac_prev=arch
-	 fi
-       done
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    if test $ac_cv_c_bigendian = unknown; then
-      # See if sys/param.h defines the BYTE_ORDER macro.
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
-	     #include <sys/param.h>
-
-int
-main ()
-{
-#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \
-		     && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \
-		     && LITTLE_ENDIAN)
-	      bogus endian macros
-	     #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  # It does; now see whether it defined to BIG_ENDIAN or not.
-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
-		#include <sys/param.h>
-
-int
-main ()
-{
-#if BYTE_ORDER != BIG_ENDIAN
-		 not big endian
-		#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_bigendian=yes
-else
-  ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    fi
-    if test $ac_cv_c_bigendian = unknown; then
-      # See if <limits.h> defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris).
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <limits.h>
-
-int
-main ()
-{
-#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN)
-	      bogus endian macros
-	     #endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  # It does; now see whether it defined to _BIG_ENDIAN or not.
-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <limits.h>
-
-int
-main ()
-{
-#ifndef _BIG_ENDIAN
-		 not big endian
-		#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_c_bigendian=yes
-else
-  ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-    fi
-    if test $ac_cv_c_bigendian = unknown; then
-      # Compile a test program.
-      if test "$cross_compiling" = yes; then :
-  # Try to guess by grepping values from an object file.
-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-short int ascii_mm[] =
-		  { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
-		short int ascii_ii[] =
-		  { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
-		int use_ascii (int i) {
-		  return ascii_mm[i] + ascii_ii[i];
-		}
-		short int ebcdic_ii[] =
-		  { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
-		short int ebcdic_mm[] =
-		  { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
-		int use_ebcdic (int i) {
-		  return ebcdic_mm[i] + ebcdic_ii[i];
-		}
-		extern int foo;
-
-int
-main ()
-{
-return use_ascii (foo) == use_ebcdic (foo);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then
-	      ac_cv_c_bigendian=yes
-	    fi
-	    if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then
-	      if test "$ac_cv_c_bigendian" = unknown; then
-		ac_cv_c_bigendian=no
-	      else
-		# finding both strings is unlikely to happen, but who knows?
-		ac_cv_c_bigendian=unknown
-	      fi
-	    fi
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-
-	     /* Are we little or big endian?  From Harbison&Steele.  */
-	     union
-	     {
-	       long int l;
-	       char c[sizeof (long int)];
-	     } u;
-	     u.l = 1;
-	     return u.c[sizeof (long int) - 1] == 1;
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  ac_cv_c_bigendian=no
-else
-  ac_cv_c_bigendian=yes
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-    fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5
-$as_echo "$ac_cv_c_bigendian" >&6; }
- case $ac_cv_c_bigendian in #(
-   yes)
-     $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h
-;; #(
-   no)
-      ;; #(
-   universal)
-
-$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
-
-     ;; #(
-   *)
-     as_fn_error $? "unknown endianness
- presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;;
- esac
-
-
-# Extract the first word of "curl", so it can be a program name with args.
-set dummy curl; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_HAVE_CURL_BINARY+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$HAVE_CURL_BINARY"; then
-  ac_cv_prog_HAVE_CURL_BINARY="$HAVE_CURL_BINARY" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_HAVE_CURL_BINARY="yes"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_prog_HAVE_CURL_BINARY" && ac_cv_prog_HAVE_CURL_BINARY="no"
-fi
-fi
-HAVE_CURL_BINARY=$ac_cv_prog_HAVE_CURL_BINARY
-if test -n "$HAVE_CURL_BINARY"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAVE_CURL_BINARY" >&5
-$as_echo "$HAVE_CURL_BINARY" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- if test "x$HAVE_CURL_BINARY" = "xyes"; then
-  HAVE_CURL_BINARY_TRUE=
-  HAVE_CURL_BINARY_FALSE='#'
-else
-  HAVE_CURL_BINARY_TRUE='#'
-  HAVE_CURL_BINARY_FALSE=
-fi
-
-# Extract the first word of "makeinfo", so it can be a program name with args.
-set dummy makeinfo; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_HAVE_MAKEINFO_BINARY+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$HAVE_MAKEINFO_BINARY"; then
-  ac_cv_prog_HAVE_MAKEINFO_BINARY="$HAVE_MAKEINFO_BINARY" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_HAVE_MAKEINFO_BINARY="yes"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_prog_HAVE_MAKEINFO_BINARY" && ac_cv_prog_HAVE_MAKEINFO_BINARY="no"
-fi
-fi
-HAVE_MAKEINFO_BINARY=$ac_cv_prog_HAVE_MAKEINFO_BINARY
-if test -n "$HAVE_MAKEINFO_BINARY"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAVE_MAKEINFO_BINARY" >&5
-$as_echo "$HAVE_MAKEINFO_BINARY" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- if test "x$HAVE_MAKEINFO_BINARY" = "xyes"; then
-  HAVE_MAKEINFO_BINARY_TRUE=
-  HAVE_MAKEINFO_BINARY_FALSE='#'
-else
-  HAVE_MAKEINFO_BINARY_TRUE='#'
-  HAVE_MAKEINFO_BINARY_FALSE=
-fi
-
- if test "x$os_is_native_w32" = "xyes"  && test "x$enable_static" = "xyes"; then
-  W32_STATIC_LIB_TRUE=
-  W32_STATIC_LIB_FALSE='#'
-else
-  W32_STATIC_LIB_TRUE='#'
-  W32_STATIC_LIB_FALSE=
-fi
-
-
-
-# Check whether --enable-doc was given.
-if test "${enable_doc+set}" = set; then :
-  enableval=$enable_doc;
-else
-  enable_doc=yes
-fi
-
-test "x$enable_doc" = "xno" || enable_doc=yes
- if test "x$enable_doc" = "xyes"; then
-  BUILD_DOC_TRUE=
-  BUILD_DOC_FALSE='#'
-else
-  BUILD_DOC_TRUE='#'
-  BUILD_DOC_FALSE=
-fi
-
-
-# Check whether --enable-examples was given.
-if test "${enable_examples+set}" = set; then :
-  enableval=$enable_examples;
-else
-  enable_examples=yes
-fi
-
-test "x$enable_examples" = "xno" || enable_examples=yes
- if test "x$enable_examples" = "xyes"; then
-  BUILD_EXAMPLES_TRUE=
-  BUILD_EXAMPLES_FALSE='#'
-else
-  BUILD_EXAMPLES_TRUE='#'
-  BUILD_EXAMPLES_FALSE=
-fi
-
-
-# Check whether --enable-poll was given.
-if test "${enable_poll+set}" = set; then :
-  enableval=$enable_poll; enable_poll=${enableval}
-else
-  enable_poll='auto'
-
-fi
-
-
-if test "$enable_poll" != "no"; then
-  if test "$os_is_native_w32" != "yes"; then
-    for ac_header in poll.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "poll.h" "ac_cv_header_poll_h" "$ac_includes_default"
-if test "x$ac_cv_header_poll_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_POLL_H 1
-_ACEOF
-
-        for ac_func in poll
-do :
-  ac_fn_c_check_func "$LINENO" "poll" "ac_cv_func_poll"
-if test "x$ac_cv_func_poll" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_POLL 1
-_ACEOF
- have_poll='yes'
-else
-  have_poll='no'
-fi
-done
-
-
-fi
-
-done
-
-  else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for WSAPoll()" >&5
-$as_echo_n "checking for WSAPoll()... " >&6; }
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-      #include <winsock2.h>
-int
-main ()
-{
-
-WSAPOLLFD fda[2];
-WSAPoll(fda, 2, 0);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-          have_poll='yes'
-          $as_echo "#define HAVE_POLL 1" >>confdefs.h
-
-
-else
-  have_poll='no'
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_poll" >&5
-$as_echo "$have_poll" >&6; }
-  fi
-  if test "$enable_poll" = "yes" && test "$have_poll" != "yes"; then
-    as_fn_error $? "Support for poll was explicitly requested but cannot be enabled on this platform." "$LINENO" 5
-  fi
-  enable_poll="$have_poll"
-fi
-
-# Check whether --enable-epoll was given.
-if test "${enable_epoll+set}" = set; then :
-  enableval=$enable_epoll; enable_epoll=${enableval}
-else
-  enable_epoll='auto'
-
-fi
-
-
-if test "$enable_epoll" != "no"; then
-    ax_have_epoll_cppflags="${CPPFLAGS}"
-  ac_fn_c_check_header_mongrel "$LINENO" "linux/version.h" "ac_cv_header_linux_version_h" "$ac_includes_default"
-if test "x$ac_cv_header_linux_version_h" = xyes; then :
-  CPPFLAGS="${CPPFLAGS} -DHAVE_LINUX_VERSION_H"
-fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Linux epoll(7) interface" >&5
-$as_echo_n "checking for Linux epoll(7) interface... " >&6; }
-  if ${ax_cv_have_epoll+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-      #include <sys/epoll.h>
-#ifdef HAVE_LINUX_VERSION_H
-#  include <linux/version.h>
-#  if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,45)
-#    error linux kernel version is too old to have epoll
-#  endif
-#endif
-
-int
-main ()
-{
-int fd, rc;
-struct epoll_event ev;
-fd = epoll_create(128);
-rc = epoll_wait(fd, &ev, 1, 0);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ax_cv_have_epoll=yes
-else
-  ax_cv_have_epoll=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-fi
-
-  CPPFLAGS="${ax_have_epoll_cppflags}"
-  if test "${ax_cv_have_epoll}" = "yes"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-fi
-
-  if test "${ax_cv_have_epoll}" = "yes"; then
-
-$as_echo "#define EPOLL_SUPPORT 1" >>confdefs.h
-
-    enable_epoll='yes'
-  else
-
-$as_echo "#define EPOLL_SUPPORT 0" >>confdefs.h
-
-    if test "$enable_epoll" = "yes"; then
-      as_fn_error $? "Support for epoll was explicitly requested but cannot be enabled on this platform." "$LINENO" 5
-    fi
-    enable_epoll='no'
-  fi
-fi
-
-if test "x$enable_epoll" = "xyes"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for epoll_create1()" >&5
-$as_echo_n "checking for epoll_create1()... " >&6; }
-if ${mhd_cv_have_epoll_create1+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-      #include <sys/epoll.h>
-int
-main ()
-{
-
-int fd;
-fd = epoll_create1(EPOLL_CLOEXEC);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  mhd_cv_have_epoll_create1=yes
-else
-  mhd_cv_have_epoll_create1=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mhd_cv_have_epoll_create1" >&5
-$as_echo "$mhd_cv_have_epoll_create1" >&6; }
-  if test "x$mhd_cv_have_epoll_create1" = "xyes"; then :
-
-
-$as_echo "#define HAVE_EPOLL_CREATE1 1" >>confdefs.h
-
-fi
-fi
-
-if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-  # Check for pthread_setname_np()
-  SAVE_LIBS="$LIBS"
-  SAVE_CFLAGS="$CFLAGS"
-  LIBS="$PTHREAD_LIBS $LIBS"
-  CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_setname_np" >&5
-$as_echo_n "checking for pthread_setname_np... " >&6; }
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <pthread.h>
-int
-main ()
-{
-  pthread_setname_np(pthread_self(), "name")
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-$as_echo "#define HAVE_PTHREAD_SETNAME_NP 1" >>confdefs.h
-
-     { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  LIBS="$SAVE_LIBS"
-  CFLAGS="$SAVE_CFLAGS"
-fi
-
-# Check for headers that are ALWAYS required
-for ac_header in fcntl.h math.h errno.h limits.h stdio.h locale.h sys/stat.h sys/types.h pthread.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-else
-  as_fn_error $? "Compiling libmicrohttpd requires standard UNIX headers files" "$LINENO" 5
-fi
-
-done
-
-
-# Check for optional headers
-for ac_header in sys/types.h sys/time.h sys/msg.h netdb.h netinet/in.h netinet/tcp.h time.h sys/socket.h sys/mman.h arpa/inet.h sys/select.h search.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
- if test "x$ac_cv_header_search_h" = "xyes"; then
-  HAVE_TSEARCH_TRUE=
-  HAVE_TSEARCH_FALSE='#'
-else
-  HAVE_TSEARCH_TRUE='#'
-  HAVE_TSEARCH_FALSE=
-fi
-
-
-ac_fn_c_check_member "$LINENO" "struct sockaddr_in" "sin_len" "ac_cv_member_struct_sockaddr_in_sin_len" "
-    #ifdef HAVE_SYS_TYPES_H
-      #include <sys/types.h>
-    #endif
-    #ifdef HAVE_SYS_SOCKET_H
-      #include <sys/socket.h>
-    #endif
-    #ifdef HAVE_NETINET_IN_H
-      #include <netinet/in.h>
-    #endif
-
-"
-if test "x$ac_cv_member_struct_sockaddr_in_sin_len" = xyes; then :
-
-$as_echo "#define HAVE_SOCKADDR_IN_SIN_LEN 1" >>confdefs.h
-
-
-fi
-
-
-
-# Check for pipe/socketpair signaling
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable signaling by socketpair" >&5
-$as_echo_n "checking whether to enable signaling by socketpair... " >&6; }
-
-# Check whether --enable-socketpair was given.
-if test "${enable_socketpair+set}" = set; then :
-  enableval=$enable_socketpair;
-else
-  if test "x$os_is_windows" = "xyes"; then :
-  enable_socketpair=yes
-else
-  enable_socketpair=no
-fi
-
-fi
-
-
-if test "x$enable_socketpair" != "xno"; then :
-  if test "x$os_is_windows" = "xyes"; then :
-   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, forced on W32" >&5
-$as_echo "yes, forced on W32" >&6; }
-else
-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-				#ifdef HAVE_SYS_TYPES_H
-				#include <sys/types.h>
-				#endif
-				#ifdef HAVE_SYS_SOCKET_H
-				#include <sys/socket.h>
-				#endif
-
-int
-main ()
-{
-
-				  int sv[2];
-				  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 1
-
-  ;
-  return 0;
-}
-
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, socketpair in available" >&5
-$as_echo "yes, socketpair in available" >&6; }
-else
-   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, socketpair in not available" >&5
-$as_echo "no, socketpair in not available" >&6; }
-              if test "x$enable_socketpair" = "xyes"; then :
-   as_fn_error $? "socketpair signalling cannot be enabled." "$LINENO" 5
-fi
-
-
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-
-fi
-
-else
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-        if test "x$os_is_windows" = "xyes"; then :
-   as_fn_error $? "socketpair must be enabled on W32" "$LINENO" 5
-fi
-
-
-fi
-if test "x$enable_socketpair" = "xyes"; then
-
-$as_echo "#define MHD_DONT_USE_PIPES 1" >>confdefs.h
-
-fi
-
-
-
-
-  for ac_func in $ac_func_list
-do :
-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gmtime_s" >&5
-$as_echo_n "checking for gmtime_s... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
- #include <time.h>
-int
-main ()
-{
-struct tm now; time_t t; time (&t); gmtime_s (&now, &t)
-  ;
-  return 0;
-}
-
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-
-$as_echo "#define HAVE_GMTIME_S 1" >>confdefs.h
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-
-ac_fn_c_check_decl "$LINENO" "SOCK_NONBLOCK" "ac_cv_have_decl_SOCK_NONBLOCK" "
-                    #if defined HAVE_SYS_TYPES_H
-                    #  include <sys/types.h>
-                    #endif
-                    #if defined HAVE_SYS_SOCKET_H
-                    #  include <sys/socket.h>
-                    #elif defined HAVE_WINSOCK2_H
-                    #  include <winsock2.h>
-                    #endif
-
-"
-if test "x$ac_cv_have_decl_SOCK_NONBLOCK" = xyes; then :
-  ac_have_decl=1
-else
-  ac_have_decl=0
-fi
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_SOCK_NONBLOCK $ac_have_decl
-_ACEOF
-if test $ac_have_decl = 1; then :
-
-$as_echo "#define HAVE_SOCK_NONBLOCK 1" >>confdefs.h
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing clock_gettime" >&5
-$as_echo_n "checking for library containing clock_gettime... " >&6; }
-if ${ac_cv_search_clock_gettime+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char clock_gettime ();
-int
-main ()
-{
-return clock_gettime ();
-  ;
-  return 0;
-}
-_ACEOF
-for ac_lib in '' rt; do
-  if test -z "$ac_lib"; then
-    ac_res="none required"
-  else
-    ac_res=-l$ac_lib
-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
-  fi
-  if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_search_clock_gettime=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext
-  if ${ac_cv_search_clock_gettime+:} false; then :
-  break
-fi
-done
-if ${ac_cv_search_clock_gettime+:} false; then :
-
-else
-  ac_cv_search_clock_gettime=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_clock_gettime" >&5
-$as_echo "$ac_cv_search_clock_gettime" >&6; }
-ac_res=$ac_cv_search_clock_gettime
-if test "$ac_res" != no; then :
-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-
-$as_echo "#define HAVE_CLOCK_GETTIME 1" >>confdefs.h
-
-
-fi
-
-
-# IPv6
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for IPv6" >&5
-$as_echo_n "checking for IPv6... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-#include <stdio.h>
-#if HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#if HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#if HAVE_WINSOCK2_H
-#include <winsock2.h>
-#endif
-#if HAVE_WS2TCPIP_H
-#include <ws2tcpip.h>
-#endif
-
-int
-main ()
-{
-
-int af=AF_INET6;
-int pf=PF_INET6;
-struct sockaddr_in6 sa;
-printf("%d %d %p\n", af, pf, &sa);
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-have_inet6=yes;
-
-$as_echo "#define HAVE_INET6 1" >>confdefs.h
-
-
-else
-
-have_inet6=no
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_inet6" >&5
-$as_echo "$have_inet6" >&6; }
-
-# TCP_CORK and TCP_NOPUSH
-ac_fn_c_check_decl "$LINENO" "TCP_CORK" "ac_cv_have_decl_TCP_CORK" "#include <netinet/tcp.h>
-"
-if test "x$ac_cv_have_decl_TCP_CORK" = xyes; then :
-  ac_have_decl=1
-else
-  ac_have_decl=0
-fi
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_TCP_CORK $ac_have_decl
-_ACEOF
-ac_fn_c_check_decl "$LINENO" "TCP_NOPUSH" "ac_cv_have_decl_TCP_NOPUSH" "#include <netinet/tcp.h>
-"
-if test "x$ac_cv_have_decl_TCP_NOPUSH" = xyes; then :
-  ac_have_decl=1
-else
-  ac_have_decl=0
-fi
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_TCP_NOPUSH $ac_have_decl
-_ACEOF
-
-
-HIDDEN_VISIBILITY_CFLAGS=""
-case "$host" in
-  *-*-mingw*)
-
-$as_echo "#define _MHD_EXTERN __attribute__((visibility(\"default\"))) __declspec(dllexport) extern" >>confdefs.h
-
-    HIDDEN_VISIBILITY_CFLAGS="-fvisibility=hidden"
-    ;;
-  *)
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the linker accepts -fvisibility=hidden" >&5
-$as_echo_n "checking whether the linker accepts -fvisibility=hidden... " >&6; }
-if ${ax_cv_check_ldflags___fvisibility_hidden+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-  ax_check_save_flags=$LDFLAGS
-  LDFLAGS="$LDFLAGS  -fvisibility=hidden"
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ax_cv_check_ldflags___fvisibility_hidden=yes
-else
-  ax_cv_check_ldflags___fvisibility_hidden=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  LDFLAGS=$ax_check_save_flags
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_check_ldflags___fvisibility_hidden" >&5
-$as_echo "$ax_cv_check_ldflags___fvisibility_hidden" >&6; }
-if test x"$ax_cv_check_ldflags___fvisibility_hidden" = xyes; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C compiler accepts -fvisibility=hidden" >&5
-$as_echo_n "checking whether C compiler accepts -fvisibility=hidden... " >&6; }
-if ${ax_cv_check_cflags___fvisibility_hidden+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-  ax_check_save_flags=$CFLAGS
-  CFLAGS="$CFLAGS  -fvisibility=hidden"
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ax_cv_check_cflags___fvisibility_hidden=yes
-else
-  ax_cv_check_cflags___fvisibility_hidden=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  CFLAGS=$ax_check_save_flags
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_check_cflags___fvisibility_hidden" >&5
-$as_echo "$ax_cv_check_cflags___fvisibility_hidden" >&6; }
-if test x"$ax_cv_check_cflags___fvisibility_hidden" = xyes; then :
-
-$as_echo "#define _MHD_EXTERN __attribute__((visibility(\"default\"))) extern" >>confdefs.h
-
-                            HIDDEN_VISIBILITY_CFLAGS="-fvisibility=hidden"
-else
-  :
-fi
-
-else
-  :
-fi
-
-    ;;
-esac
-
-
-# libcurl (required for testing)
-# Check whether --enable-curl was given.
-if test "${enable_curl+set}" = set; then :
-  enableval=$enable_curl; enable_curl=${enableval}
-fi
-
-curl=0
-if test "$enable_curl" != "no"
-then
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-# Check whether --with-libcurl was given.
-if test "${with_libcurl+set}" = set; then :
-  withval=$with_libcurl; _libcurl_with=$withval
-else
-  _libcurl_with=yes
-fi
-
-
-  if test "$_libcurl_with" != "no" ; then
-
-     for ac_prog in gawk mawk nawk awk
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AWK+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$AWK"; then
-  ac_cv_prog_AWK="$AWK" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_AWK="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-AWK=$ac_cv_prog_AWK
-if test -n "$AWK"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5
-$as_echo "$AWK" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$AWK" && break
-done
-
-
-     _libcurl_version_parse="eval $AWK '{split(\$NF,A,\".\"); X=256*256*A[1]+256*A[2]+A[3]; print X;}'"
-
-     _libcurl_try_link=yes
-
-     if test -d "$_libcurl_with" ; then
-        LIBCURL_CPPFLAGS="-I$withval/include"
-        _libcurl_ldflags="-L$withval/lib"
-        # Extract the first word of "curl-config", so it can be a program name with args.
-set dummy curl-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path__libcurl_config+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $_libcurl_config in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path__libcurl_config="$_libcurl_config" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in "$withval/bin"
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path__libcurl_config="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-_libcurl_config=$ac_cv_path__libcurl_config
-if test -n "$_libcurl_config"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_libcurl_config" >&5
-$as_echo "$_libcurl_config" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-     else
-        # Extract the first word of "curl-config", so it can be a program name with args.
-set dummy curl-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path__libcurl_config+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $_libcurl_config in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path__libcurl_config="$_libcurl_config" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path__libcurl_config="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-_libcurl_config=$ac_cv_path__libcurl_config
-if test -n "$_libcurl_config"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_libcurl_config" >&5
-$as_echo "$_libcurl_config" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-     fi
-
-     if test x$_libcurl_config != "x" ; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for the version of libcurl" >&5
-$as_echo_n "checking for the version of libcurl... " >&6; }
-if ${libcurl_cv_lib_curl_version+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  libcurl_cv_lib_curl_version=`$_libcurl_config --version | $AWK '{print $2}'`
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libcurl_cv_lib_curl_version" >&5
-$as_echo "$libcurl_cv_lib_curl_version" >&6; }
-
-        _libcurl_version=`echo $libcurl_cv_lib_curl_version | $_libcurl_version_parse`
-        _libcurl_wanted=`echo 7.16.4 | $_libcurl_version_parse`
-
-        if test $_libcurl_wanted -gt 0 ; then
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libcurl >= version 7.16.4" >&5
-$as_echo_n "checking for libcurl >= version 7.16.4... " >&6; }
-if ${libcurl_cv_lib_version_ok+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-              if test $_libcurl_version -ge $_libcurl_wanted ; then
-                 libcurl_cv_lib_version_ok=yes
-              else
-                 libcurl_cv_lib_version_ok=no
-              fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libcurl_cv_lib_version_ok" >&5
-$as_echo "$libcurl_cv_lib_version_ok" >&6; }
-        fi
-
-        if test $_libcurl_wanted -eq 0 || test x$libcurl_cv_lib_version_ok = xyes ; then
-           if test x"$LIBCURL_CPPFLAGS" = "x" ; then
-              LIBCURL_CPPFLAGS=`$_libcurl_config --cflags`
-           fi
-           if test x"$LIBCURL" = "x" ; then
-              LIBCURL=`$_libcurl_config --libs`
-
-              # This is so silly, but Apple actually has a bug in their
-              # curl-config script.  Fixed in Tiger, but there are still
-              # lots of Panther installs around.
-              case "${host}" in
-                 powerpc-apple-darwin7*)
-                    LIBCURL=`echo $LIBCURL | sed -e 's|-arch i386||g'`
-                 ;;
-              esac
-           fi
-
-           # All curl-config scripts support --feature
-           _libcurl_features=`$_libcurl_config --feature`
-
-           # Is it modern enough to have --protocols? (7.12.4)
-           if test $_libcurl_version -ge 461828 ; then
-              _libcurl_protocols=`$_libcurl_config --protocols`
-           fi
-        else
-           _libcurl_try_link=no
-        fi
-
-        unset _libcurl_wanted
-     fi
-
-     if test $_libcurl_try_link = yes ; then
-
-        # we didn't find curl-config, so let's see if the user-supplied
-        # link line (or failing that, "-lcurl") is enough.
-        LIBCURL=${LIBCURL-"$_libcurl_ldflags -lcurl"}
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether libcurl is usable" >&5
-$as_echo_n "checking whether libcurl is usable... " >&6; }
-if ${libcurl_cv_lib_curl_usable+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-
-           _libcurl_save_cppflags=$CPPFLAGS
-           CPPFLAGS="$LIBCURL_CPPFLAGS $CPPFLAGS"
-           _libcurl_save_libs=$LIBS
-           LIBS="$LIBCURL $LIBS"
-
-           cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <curl/curl.h>
-int
-main ()
-{
-
-/* Try and use a few common options to force a failure if we are
-   missing symbols or can't link. */
-int x;
-curl_easy_setopt(NULL,CURLOPT_URL,NULL);
-x=CURL_ERROR_SIZE;
-x=CURLOPT_WRITEFUNCTION;
-x=CURLOPT_FILE;
-x=CURLOPT_ERRORBUFFER;
-x=CURLOPT_STDERR;
-x=CURLOPT_VERBOSE;
-if (x) ;
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  libcurl_cv_lib_curl_usable=yes
-else
-  libcurl_cv_lib_curl_usable=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-           CPPFLAGS=$_libcurl_save_cppflags
-           LIBS=$_libcurl_save_libs
-           unset _libcurl_save_cppflags
-           unset _libcurl_save_libs
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libcurl_cv_lib_curl_usable" >&5
-$as_echo "$libcurl_cv_lib_curl_usable" >&6; }
-
-        if test $libcurl_cv_lib_curl_usable = yes ; then
-
-           # Does curl_free() exist in this version of libcurl?
-           # If not, fake it with free()
-
-           _libcurl_save_cppflags=$CPPFLAGS
-           CPPFLAGS="$CPPFLAGS $LIBCURL_CPPFLAGS"
-           _libcurl_save_libs=$LIBS
-           LIBS="$LIBS $LIBCURL"
-
-           ac_fn_c_check_func "$LINENO" "curl_free" "ac_cv_func_curl_free"
-if test "x$ac_cv_func_curl_free" = xyes; then :
-
-else
-
-$as_echo "#define curl_free free" >>confdefs.h
-
-fi
-
-
-           CPPFLAGS=$_libcurl_save_cppflags
-           LIBS=$_libcurl_save_libs
-           unset _libcurl_save_cppflags
-           unset _libcurl_save_libs
-
-
-$as_echo "#define HAVE_LIBCURL 1" >>confdefs.h
-
-
-
-
-           for _libcurl_feature in $_libcurl_features ; do
-              cat >>confdefs.h <<_ACEOF
-#define `$as_echo "libcurl_feature_$_libcurl_feature" | $as_tr_cpp` 1
-_ACEOF
-
-              eval `$as_echo "libcurl_feature_$_libcurl_feature" | $as_tr_sh`=yes
-           done
-
-           if test "x$_libcurl_protocols" = "x" ; then
-
-              # We don't have --protocols, so just assume that all
-              # protocols are available
-              _libcurl_protocols="HTTP FTP FILE TELNET LDAP DICT TFTP"
-
-              test -z "$_libcurl_version" && _libcurl_version=0
-
-              if test x$libcurl_feature_SSL = xyes ; then
-                 _libcurl_protocols="$_libcurl_protocols HTTPS"
-
-                 # FTPS wasn't standards-compliant until version
-                 # 7.11.0 (0x070b00 == 461568)
-                 if test $_libcurl_version -ge 461568; then
-                    _libcurl_protocols="$_libcurl_protocols FTPS"
-                 fi
-              fi
-
-              # RTSP, IMAP, POP3 and SMTP were added in
-              # 7.20.0 (0x071400 == 463872)
-              if test $_libcurl_version -ge 463872; then
-                 _libcurl_protocols="$_libcurl_protocols RTSP IMAP POP3 SMTP"
-              fi
-           fi
-
-           for _libcurl_protocol in $_libcurl_protocols ; do
-              cat >>confdefs.h <<_ACEOF
-#define `$as_echo "libcurl_protocol_$_libcurl_protocol" | $as_tr_cpp` 1
-_ACEOF
-
-              eval `$as_echo "libcurl_protocol_$_libcurl_protocol" | $as_tr_sh`=yes
-           done
-        else
-           unset LIBCURL
-           unset LIBCURL_CPPFLAGS
-        fi
-     fi
-
-     unset _libcurl_try_link
-     unset _libcurl_version_parse
-     unset _libcurl_config
-     unset _libcurl_feature
-     unset _libcurl_features
-     unset _libcurl_protocol
-     unset _libcurl_protocols
-     unset _libcurl_version
-     unset _libcurl_ldflags
-  fi
-
-  if test x$_libcurl_with = xno || test x$libcurl_cv_lib_curl_usable != xyes ; then
-     # This is the IF-NO path
-
-      if test "x$enable_curl" = "xyes"; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cURL-based tests cannot be enabled because libcurl is missing" >&5
-$as_echo "$as_me: WARNING: cURL-based tests cannot be enabled because libcurl is missing" >&2;}
-      fi
-      enable_curl=no
-
-  else
-     # This is the IF-YES path
-     enable_curl=yes
-  fi
-
-  unset _libcurl_with
-
-fi
-if test "$enable_curl" != "no"
-then
-# Lib cURL & cURL - OpenSSL versions
-
-$as_echo "#define MHD_REQ_CURL_VERSION \"7.16.4\"" >>confdefs.h
-
-
-$as_echo "#define MHD_REQ_CURL_OPENSSL_VERSION \"0.9.8\"" >>confdefs.h
-
-
-$as_echo "#define MHD_REQ_CURL_GNUTLS_VERSION \"2.8.6\"" >>confdefs.h
-
-
-$as_echo "#define MHD_REQ_CURL_NSS_VERSION \"3.12.0\"" >>confdefs.h
-
-fi
- if test "x$enable_curl" = "xyes"; then
-  HAVE_CURL_TRUE=
-  HAVE_CURL_FALSE='#'
-else
-  HAVE_CURL_TRUE='#'
-  HAVE_CURL_FALSE=
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for magic_open in -lmagic" >&5
-$as_echo_n "checking for magic_open in -lmagic... " >&6; }
-if ${ac_cv_lib_magic_magic_open+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lmagic  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char magic_open ();
-int
-main ()
-{
-return magic_open ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_magic_magic_open=yes
-else
-  ac_cv_lib_magic_magic_open=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_magic_magic_open" >&5
-$as_echo "$ac_cv_lib_magic_magic_open" >&6; }
-if test "x$ac_cv_lib_magic_magic_open" = xyes; then :
-  for ac_header in magic.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "magic.h" "ac_cv_header_magic_h" "$ac_includes_default"
-if test "x$ac_cv_header_magic_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_MAGIC_H 1
-_ACEOF
-  if true; then
-  HAVE_MAGIC_TRUE=
-  HAVE_MAGIC_FALSE='#'
-else
-  HAVE_MAGIC_TRUE='#'
-  HAVE_MAGIC_FALSE=
-fi
-
-else
-   if false; then
-  HAVE_MAGIC_TRUE=
-  HAVE_MAGIC_FALSE='#'
-else
-  HAVE_MAGIC_TRUE='#'
-  HAVE_MAGIC_FALSE=
-fi
-
-fi
-
-done
-
-else
-   if false; then
-  HAVE_MAGIC_TRUE=
-  HAVE_MAGIC_FALSE='#'
-else
-  HAVE_MAGIC_TRUE='#'
-  HAVE_MAGIC_FALSE=
-fi
-
-fi
-
-
-
-# optional: libmicrospdy support. Enabled by default if not on W32
-# Check whether --enable-spdy was given.
-if test "${enable_spdy+set}" = set; then :
-  enableval=$enable_spdy; enable_spdy=${enableval}
-else
-   if test "x$os_is_windows" = "xyes"; then :
-  enable_spdy=no
-fi
-fi
-
-
-if test "$enable_spdy" != "no"
-then
-
-    found=false
-
-# Check whether --with-openssl was given.
-if test "${with_openssl+set}" = set; then :
-  withval=$with_openssl;
-            case "$withval" in
-            "" | y | ye | yes | n | no)
-            as_fn_error $? "Invalid --with-openssl value" "$LINENO" 5
-              ;;
-            *) ssldirs="$withval"
-              ;;
-            esac
-
-else
-
-            # if pkg-config is installed and openssl has installed a .pc file,
-            # then use that information and don't search ssldirs
-            # Extract the first word of "pkg-config", so it can be a program name with args.
-set dummy pkg-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_PKG_CONFIG+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $PKG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-PKG_CONFIG=$ac_cv_path_PKG_CONFIG
-if test -n "$PKG_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
-$as_echo "$PKG_CONFIG" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-            if test x"$PKG_CONFIG" != x""; then
-                OPENSSL_LDFLAGS=`$PKG_CONFIG openssl --libs-only-L 2>/dev/null`
-                if test $? = 0; then
-                    OPENSSL_LIBS=`$PKG_CONFIG openssl --libs-only-l 2>/dev/null`
-                    OPENSSL_INCLUDES=`$PKG_CONFIG openssl --cflags-only-I 2>/dev/null`
-                    found=true
-                fi
-            fi
-
-            # no such luck; use some default ssldirs
-            if ! $found; then
-                ssldirs="/usr/local/ssl /usr/lib/ssl /usr/ssl /usr/pkg /usr/local /usr"
-            fi
-
-
-fi
-
-
-
-    # note that we #include <openssl/foo.h>, so the OpenSSL headers have to be in
-    # an 'openssl' subdirectory
-
-    if ! $found; then
-        OPENSSL_INCLUDES=
-        for ssldir in $ssldirs; do
-            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openssl/ssl.h in $ssldir" >&5
-$as_echo_n "checking for openssl/ssl.h in $ssldir... " >&6; }
-            if test -f "$ssldir/include/openssl/ssl.h"; then
-                OPENSSL_INCLUDES="-I$ssldir/include"
-                OPENSSL_LDFLAGS="-L$ssldir/lib"
-                OPENSSL_LIBS="-lssl -lcrypto"
-                found=true
-                { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-                break
-            else
-                { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-            fi
-        done
-
-        # if the file wasn't found, well, go ahead and try the link anyway -- maybe
-        # it will just work!
-    fi
-
-    # try the preprocessor and linker with our new flags,
-    # being careful not to pollute the global LIBS, LDFLAGS, and CPPFLAGS
-
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiling and linking against OpenSSL works" >&5
-$as_echo_n "checking whether compiling and linking against OpenSSL works... " >&6; }
-    echo "Trying link with OPENSSL_LDFLAGS=$OPENSSL_LDFLAGS;" \
-        "OPENSSL_LIBS=$OPENSSL_LIBS; OPENSSL_INCLUDES=$OPENSSL_INCLUDES" >&5
-
-    save_LIBS="$LIBS"
-    save_LDFLAGS="$LDFLAGS"
-    save_CPPFLAGS="$CPPFLAGS"
-    LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS"
-    LIBS="$OPENSSL_LIBS $LIBS"
-    CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS"
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <openssl/ssl.h>
-int
-main ()
-{
-SSL_new(NULL)
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-             have_openssl=yes
-
-else
-
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-             have_openssl=no
-
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-
-
-
-
-
-  if test "x$have_openssl" = "xyes"
-  then
-    # check OpenSSL headers
-    SAVE_CPP_FLAGS="$CPPFLAGS"
-    CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS"
-    for ac_header in openssl/evp.h openssl/rsa.h openssl/rand.h openssl/err.h openssl/sha.h openssl/pem.h openssl/engine.h
-do :
-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-  have_openssl=yes
-else
-   have_openssl=no
-fi
-
-done
-
-    if test "x$have_openssl" = "xyes"
-    then
-      # check OpenSSL libs
-      SAVE_LIBS="$LIBS"
-      SAVE_LD_FLAGS="$LDFLAGS"
-      LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS"
-      LIBS="$OPENSSL_LIBS $LIBS"
-      ac_fn_c_check_func "$LINENO" "SSL_CTX_set_next_protos_advertised_cb" "ac_cv_func_SSL_CTX_set_next_protos_advertised_cb"
-if test "x$ac_cv_func_SSL_CTX_set_next_protos_advertised_cb" = xyes; then :
-
-          ac_fn_c_check_func "$LINENO" "SSL_library_init" "ac_cv_func_SSL_library_init"
-if test "x$ac_cv_func_SSL_library_init" = xyes; then :
-   have_openssl=yes
-else
-   have_openssl=no
-fi
-
-
-else
-   have_openssl=no
-fi
-
-      LIBS="$SAVE_LIBS"
-      LDFLAGS="$SAVE_LD_FLAGS"
-    fi
-    CPPFLAGS="$SAVE_CPP_FLAGS"
-  fi
-  if test "x$have_openssl" = "xyes"
-  then
-    enable_spdy=yes
-  else
-    if test "x$enable_spdy" = "xyes" ; then :
-  as_fn_error $? "libmicrospdy cannot be enabled without OpenSSL." "$LINENO" 5
-fi
-    have_openssl=no
-    enable_spdy=no
-  fi
-else
-  # OpenSSL is used only for libmicrospdy
-  have_openssl=no
-fi
- if test "x$have_openssl" = "xyes"; then
-  HAVE_OPENSSL_TRUE=
-  HAVE_OPENSSL_FALSE='#'
-else
-  HAVE_OPENSSL_TRUE='#'
-  HAVE_OPENSSL_FALSE=
-fi
-
-
-if test "$enable_spdy" = "yes"
-then
-
-$as_echo "#define SPDY_SUPPORT 1" >>confdefs.h
-
-else
-
-$as_echo "#define SPDY_SUPPORT 0" >>confdefs.h
-
-fi
- if test "x$enable_spdy" != "xno"; then
-  ENABLE_SPDY_TRUE=
-  ENABLE_SPDY_FALSE='#'
-else
-  ENABLE_SPDY_TRUE='#'
-  ENABLE_SPDY_FALSE=
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we have OpenSSL and thus can support libmicrospdy" >&5
-$as_echo_n "checking whether we have OpenSSL and thus can support libmicrospdy... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_spdy" >&5
-$as_echo "$enable_spdy" >&6; }
-
-# for pkg-config
-SPDY_LIBDEPS="$OPENSSL_LIBS"
-
-SPDY_LIB_LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS"
-SPDY_LIB_CFLAGS="$CFLAGS"
-SPDY_LIB_CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS"
-
-
-
-# for pkg-config
-
-
-for ac_header in spdylay/spdylay.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "spdylay/spdylay.h" "ac_cv_header_spdylay_spdylay_h" "$ac_includes_default"
-if test "x$ac_cv_header_spdylay_spdylay_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_SPDYLAY_SPDYLAY_H 1
-_ACEOF
-  have_spdylay="yes"
-else
-  have_spdylay="no"
-fi
-
-done
-
- if test "x$have_spdylay" = "xyes"; then
-  HAVE_SPDYLAY_TRUE=
-  HAVE_SPDYLAY_FALSE='#'
-else
-  HAVE_SPDYLAY_TRUE='#'
-  HAVE_SPDYLAY_FALSE=
-fi
-
-
-# large file support (> 4 GB)
-# Check whether --enable-largefile was given.
-if test "${enable_largefile+set}" = set; then :
-  enableval=$enable_largefile;
-fi
-
-if test "$enable_largefile" != no; then
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5
-$as_echo_n "checking for special C compiler options needed for large files... " >&6; }
-if ${ac_cv_sys_largefile_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_sys_largefile_CC=no
-     if test "$GCC" != yes; then
-       ac_save_CC=$CC
-       while :; do
-	 # IRIX 6.2 and later do not support large files by default,
-	 # so use the C compiler's -n32 option if that helps.
-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
-		       && LARGE_OFF_T % 2147483647 == 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-	 if ac_fn_c_try_compile "$LINENO"; then :
-  break
-fi
-rm -f core conftest.err conftest.$ac_objext
-	 CC="$CC -n32"
-	 if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_sys_largefile_CC=' -n32'; break
-fi
-rm -f core conftest.err conftest.$ac_objext
-	 break
-       done
-       CC=$ac_save_CC
-       rm -f conftest.$ac_ext
-    fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5
-$as_echo "$ac_cv_sys_largefile_CC" >&6; }
-  if test "$ac_cv_sys_largefile_CC" != no; then
-    CC=$CC$ac_cv_sys_largefile_CC
-  fi
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5
-$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; }
-if ${ac_cv_sys_file_offset_bits+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  while :; do
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
-		       && LARGE_OFF_T % 2147483647 == 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_sys_file_offset_bits=no; break
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#define _FILE_OFFSET_BITS 64
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
-		       && LARGE_OFF_T % 2147483647 == 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_sys_file_offset_bits=64; break
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_cv_sys_file_offset_bits=unknown
-  break
-done
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5
-$as_echo "$ac_cv_sys_file_offset_bits" >&6; }
-case $ac_cv_sys_file_offset_bits in #(
-  no | unknown) ;;
-  *)
-cat >>confdefs.h <<_ACEOF
-#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits
-_ACEOF
-;;
-esac
-rm -rf conftest*
-  if test $ac_cv_sys_file_offset_bits = unknown; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5
-$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; }
-if ${ac_cv_sys_large_files+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  while :; do
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
-		       && LARGE_OFF_T % 2147483647 == 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_sys_large_files=no; break
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#define _LARGE_FILES 1
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
-		       && LARGE_OFF_T % 2147483647 == 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_sys_large_files=1; break
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_cv_sys_large_files=unknown
-  break
-done
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5
-$as_echo "$ac_cv_sys_large_files" >&6; }
-case $ac_cv_sys_large_files in #(
-  no | unknown) ;;
-  *)
-cat >>confdefs.h <<_ACEOF
-#define _LARGE_FILES $ac_cv_sys_large_files
-_ACEOF
-;;
-esac
-rm -rf conftest*
-  fi
-
-
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGEFILE_SOURCE value needed for large files" >&5
-$as_echo_n "checking for _LARGEFILE_SOURCE value needed for large files... " >&6; }
-if ${ac_cv_sys_largefile_source+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  while :; do
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <sys/types.h> /* for off_t */
-     #include <stdio.h>
-int
-main ()
-{
-int (*fp) (FILE *, off_t, int) = fseeko;
-     return fseeko (stdin, 0, 0) && fp (stdin, 0, 0);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_sys_largefile_source=no; break
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#define _LARGEFILE_SOURCE 1
-#include <sys/types.h> /* for off_t */
-     #include <stdio.h>
-int
-main ()
-{
-int (*fp) (FILE *, off_t, int) = fseeko;
-     return fseeko (stdin, 0, 0) && fp (stdin, 0, 0);
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_sys_largefile_source=1; break
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-  ac_cv_sys_largefile_source=unknown
-  break
-done
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_source" >&5
-$as_echo "$ac_cv_sys_largefile_source" >&6; }
-case $ac_cv_sys_largefile_source in #(
-  no | unknown) ;;
-  *)
-cat >>confdefs.h <<_ACEOF
-#define _LARGEFILE_SOURCE $ac_cv_sys_largefile_source
-_ACEOF
-;;
-esac
-rm -rf conftest*
-
-# We used to try defining _XOPEN_SOURCE=500 too, to work around a bug
-# in glibc 2.1.3, but that breaks too many other things.
-# If you want fseeko and ftello with glibc, upgrade to a fixed glibc.
-if test $ac_cv_sys_largefile_source != unknown; then
-
-$as_echo "#define HAVE_FSEEKO 1" >>confdefs.h
-
-fi
-
-
-# optional: have error messages ?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to generate error messages" >&5
-$as_echo_n "checking whether to generate error messages... " >&6; }
-# Check whether --enable-messages was given.
-if test "${enable_messages+set}" = set; then :
-  enableval=$enable_messages; enable_messages=${enableval}
-else
-  enable_messages=yes
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_messages" >&5
-$as_echo "$enable_messages" >&6; }
-if test "$enable_messages" = "yes"
-then
-
-$as_echo "#define HAVE_MESSAGES 1" >>confdefs.h
-
-else
-
-$as_echo "#define HAVE_MESSAGES 0" >>confdefs.h
-
-fi
-
-
-# optional: have postprocessor?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable postprocessor" >&5
-$as_echo_n "checking whether to enable postprocessor... " >&6; }
-# Check whether --enable-postprocessor was given.
-if test "${enable_postprocessor+set}" = set; then :
-  enableval=$enable_postprocessor; enable_postprocessor=${enableval}
-else
-  enable_postprocessor=yes
-fi
-
-test "x$enable_postprocessor" = "xno" || enable_postprocessor=yes
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_postprocessor" >&5
-$as_echo "$enable_postprocessor" >&6; }
- if test "x$enable_postprocessor" != "xno"; then
-  HAVE_POSTPROCESSOR_TRUE=
-  HAVE_POSTPROCESSOR_FALSE='#'
-else
-  HAVE_POSTPROCESSOR_TRUE='#'
-  HAVE_POSTPROCESSOR_FALSE=
-fi
-
-if test "x$enable_postprocessor" != "xno"
-then
-
-$as_echo "#define HAVE_POSTPROCESSOR 1" >>confdefs.h
-
-fi
-
-
-# optional: have zzuf, socat?
-# Extract the first word of "zzuf", so it can be a program name with args.
-set dummy zzuf; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_have_zzuf+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$have_zzuf"; then
-  ac_cv_prog_have_zzuf="$have_zzuf" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_have_zzuf="yes"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_prog_have_zzuf" && ac_cv_prog_have_zzuf="no"
-fi
-fi
-have_zzuf=$ac_cv_prog_have_zzuf
-if test -n "$have_zzuf"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_zzuf" >&5
-$as_echo "$have_zzuf" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-# Extract the first word of "socat", so it can be a program name with args.
-set dummy socat; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_have_socat+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$have_socat"; then
-  ac_cv_prog_have_socat="$have_socat" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_have_socat="yes"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  test -z "$ac_cv_prog_have_socat" && ac_cv_prog_have_socat="no"
-fi
-fi
-have_socat=$ac_cv_prog_have_socat
-if test -n "$have_socat"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_socat" >&5
-$as_echo "$have_socat" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- if test "x$have_zzuf" = "xyes"; then
-  HAVE_ZZUF_TRUE=
-  HAVE_ZZUF_FALSE='#'
-else
-  HAVE_ZZUF_TRUE='#'
-  HAVE_ZZUF_FALSE=
-fi
-
- if test "x$have_socat" = "xyes"; then
-  HAVE_SOCAT_TRUE=
-  HAVE_SOCAT_FALSE='#'
-else
-  HAVE_SOCAT_TRUE='#'
-  HAVE_SOCAT_FALSE=
-fi
-
-
-
-# libgcrypt linkage: required for HTTPS support
-
-
-
-
-# Check whether --with-libgcrypt-prefix was given.
-if test "${with_libgcrypt_prefix+set}" = set; then :
-  withval=$with_libgcrypt_prefix; libgcrypt_config_prefix="$withval"
-else
-  libgcrypt_config_prefix=""
-fi
-
-  if test x$libgcrypt_config_prefix != x ; then
-     if test x${LIBGCRYPT_CONFIG+set} != xset ; then
-        LIBGCRYPT_CONFIG=$libgcrypt_config_prefix/bin/libgcrypt-config
-     fi
-  fi
-
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}libgcrypt-config", so it can be a program name with args.
-set dummy ${ac_tool_prefix}libgcrypt-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_LIBGCRYPT_CONFIG+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $LIBGCRYPT_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_LIBGCRYPT_CONFIG="$LIBGCRYPT_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_LIBGCRYPT_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-LIBGCRYPT_CONFIG=$ac_cv_path_LIBGCRYPT_CONFIG
-if test -n "$LIBGCRYPT_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBGCRYPT_CONFIG" >&5
-$as_echo "$LIBGCRYPT_CONFIG" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_path_LIBGCRYPT_CONFIG"; then
-  ac_pt_LIBGCRYPT_CONFIG=$LIBGCRYPT_CONFIG
-  # Extract the first word of "libgcrypt-config", so it can be a program name with args.
-set dummy libgcrypt-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_ac_pt_LIBGCRYPT_CONFIG+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $ac_pt_LIBGCRYPT_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_ac_pt_LIBGCRYPT_CONFIG="$ac_pt_LIBGCRYPT_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_ac_pt_LIBGCRYPT_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-ac_pt_LIBGCRYPT_CONFIG=$ac_cv_path_ac_pt_LIBGCRYPT_CONFIG
-if test -n "$ac_pt_LIBGCRYPT_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_LIBGCRYPT_CONFIG" >&5
-$as_echo "$ac_pt_LIBGCRYPT_CONFIG" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_pt_LIBGCRYPT_CONFIG" = x; then
-    LIBGCRYPT_CONFIG="no"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    LIBGCRYPT_CONFIG=$ac_pt_LIBGCRYPT_CONFIG
-  fi
-else
-  LIBGCRYPT_CONFIG="$ac_cv_path_LIBGCRYPT_CONFIG"
-fi
-
-  tmp=1.2.2
-  if echo "$tmp" | $GREP ':' >/dev/null 2>/dev/null ; then
-     req_libgcrypt_api=`echo "$tmp"     | $SED 's/\(.*\):\(.*\)/\1/'`
-     min_libgcrypt_version=`echo "$tmp" | $SED 's/\(.*\):\(.*\)/\2/'`
-  else
-     req_libgcrypt_api=0
-     min_libgcrypt_version="$tmp"
-  fi
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for LIBGCRYPT - version >= $min_libgcrypt_version" >&5
-$as_echo_n "checking for LIBGCRYPT - version >= $min_libgcrypt_version... " >&6; }
-  ok=no
-  if test "$LIBGCRYPT_CONFIG" != "no" ; then
-    req_major=`echo $min_libgcrypt_version | \
-               $SED 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\1/'`
-    req_minor=`echo $min_libgcrypt_version | \
-               $SED 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\2/'`
-    req_micro=`echo $min_libgcrypt_version | \
-               $SED 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\3/'`
-    libgcrypt_config_version=`$LIBGCRYPT_CONFIG --version`
-    major=`echo $libgcrypt_config_version | \
-               $SED 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'`
-    minor=`echo $libgcrypt_config_version | \
-               $SED 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'`
-    micro=`echo $libgcrypt_config_version | \
-               $SED 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\3/'`
-    if test "$major" -gt "$req_major"; then
-        ok=yes
-    else
-        if test "$major" -eq "$req_major"; then
-            if test "$minor" -gt "$req_minor"; then
-               ok=yes
-            else
-               if test "$minor" -eq "$req_minor"; then
-                   if test "$micro" -ge "$req_micro"; then
-                     ok=yes
-                   fi
-               fi
-            fi
-        fi
-    fi
-  fi
-  if test $ok = yes; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes ($libgcrypt_config_version)" >&5
-$as_echo "yes ($libgcrypt_config_version)" >&6; }
-  else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-  fi
-  if test $ok = yes; then
-     # If we have a recent libgcrypt, we should also check that the
-     # API is compatible
-     if test "$req_libgcrypt_api" -gt 0 ; then
-        tmp=`$LIBGCRYPT_CONFIG --api-version 2>/dev/null || echo 0`
-        if test "$tmp" -gt 0 ; then
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking LIBGCRYPT API version" >&5
-$as_echo_n "checking LIBGCRYPT API version... " >&6; }
-           if test "$req_libgcrypt_api" -eq "$tmp" ; then
-             { $as_echo "$as_me:${as_lineno-$LINENO}: result: okay" >&5
-$as_echo "okay" >&6; }
-           else
-             ok=no
-             { $as_echo "$as_me:${as_lineno-$LINENO}: result: does not match. want=$req_libgcrypt_api got=$tmp" >&5
-$as_echo "does not match. want=$req_libgcrypt_api got=$tmp" >&6; }
-           fi
-        fi
-     fi
-  fi
-  if test $ok = yes; then
-    LIBGCRYPT_CFLAGS=`$LIBGCRYPT_CONFIG --cflags`
-    LIBGCRYPT_LIBS=`$LIBGCRYPT_CONFIG --libs`
-    have_gcrypt=yes
-    libgcrypt_config_host=`$LIBGCRYPT_CONFIG --host 2>/dev/null || echo none`
-    if test x"$libgcrypt_config_host" != xnone ; then
-      if test x"$libgcrypt_config_host" != x"$host" ; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING:
-***
-*** The config script $LIBGCRYPT_CONFIG was
-*** built for $libgcrypt_config_host and thus may not match the
-*** used host $host.
-*** You may want to use the configure option --with-libgcrypt-prefix
-*** to specify a matching config script.
-***" >&5
-$as_echo "$as_me: WARNING:
-***
-*** The config script $LIBGCRYPT_CONFIG was
-*** built for $libgcrypt_config_host and thus may not match the
-*** used host $host.
-*** You may want to use the configure option --with-libgcrypt-prefix
-*** to specify a matching config script.
-***" >&2;}
-      fi
-    fi
-  else
-    LIBGCRYPT_CFLAGS=""
-    LIBGCRYPT_LIBS=""
-    have_gcrypt=no
-  fi
-
-
-
-if test "x$have_gcrypt" = "xyes"
-then
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS $LIBGCRYPT_CFLAGS"
-  # LIBGCRYPT_CFLAGS can be actually a CPPFLAGS, so check them both
-  SAVE_CPPFLAGS="$CPPFLAGS"
-  CPPFLAGS="$CPPFLAGS $LIBGCRYPT_CFLAGS"
-  for ac_header in gcrypt.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "gcrypt.h" "ac_cv_header_gcrypt_h" "$ac_includes_default"
-if test "x$ac_cv_header_gcrypt_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GCRYPT_H 1
-_ACEOF
-
-else
-  have_gcrypt=no
-fi
-
-done
-
-  CFLAGS="$SAVE_CFLAGS"
-  CPPFLAGS="$SAVE_CPPFLAGS"
-fi
-
-# gnutls
-GNUTLS_CPPFLAGS=""
-GNUTLS_LDFLAGS=""
-have_gnutls=no
-have_gnutls_sni=no
-have_gnutls_pkgcfg=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to find GnuTLS library" >&5
-$as_echo_n "checking how to find GnuTLS library... " >&6; }
-
-# Check whether --with-gnutls was given.
-if test "${with_gnutls+set}" = set; then :
-  withval=$with_gnutls;
-    case $with_gnutls in
-      no)
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: GnuTLS disabled" >&5
-$as_echo "GnuTLS disabled" >&6; }
-        ;;
-      yes)
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: automatically, forced" >&5
-$as_echo "automatically, forced" >&6; }
-        ;;
-      *)
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: -I$with_gnutls/include -L$with_gnutls/lib -lgnutls" >&5
-$as_echo "-I$with_gnutls/include -L$with_gnutls/lib -lgnutls" >&6; }
-        SAVE_LDFLAGS="$LDFLAGS"
-        SAVE_CPPFLAGS="$CPPFLAGS"
-        LDFLAGS="-L$with_gnutls/lib $LDFLAGS"
-        CPPFLAGS="-I$with_gnutls/include $CPPFLAGS"
-        have_gnutls_pkgcfg=no
-          for ac_header in gnutls/gnutls.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "gnutls/gnutls.h" "ac_cv_header_gnutls_gnutls_h" "$ac_includes_default"
-if test "x$ac_cv_header_gnutls_gnutls_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GNUTLS_GNUTLS_H 1
-_ACEOF
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_priority_set in -lgnutls" >&5
-$as_echo_n "checking for gnutls_priority_set in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_priority_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_priority_set ();
-int
-main ()
-{
-return gnutls_priority_set ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_priority_set=yes
-else
-  ac_cv_lib_gnutls_gnutls_priority_set=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_priority_set" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_priority_set" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_priority_set" = xyes; then :
-
-                GNUTLS_CPPFLAGS="-I$with_gnutls/include"
-                GNUTLS_LDFLAGS="-L$with_gnutls/lib"
-                GNUTLS_LIBS="-lgnutls"
-                { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_load_file in -lgnutls" >&5
-$as_echo_n "checking for gnutls_load_file in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_load_file+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_load_file ();
-int
-main ()
-{
-return gnutls_load_file ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_load_file=yes
-else
-  ac_cv_lib_gnutls_gnutls_load_file=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_load_file" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_load_file" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_load_file" = xyes; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_privkey_import_x509_raw in -lgnutls" >&5
-$as_echo_n "checking for gnutls_privkey_import_x509_raw in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_privkey_import_x509_raw ();
-int
-main ()
-{
-return gnutls_privkey_import_x509_raw ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw=yes
-else
-  ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" = xyes; then :
-  have_gnutls_sni=yes
-fi
-
-fi
-
-                have_gnutls=yes
-
-fi
-
-fi
-
-done
-
-        if test "x$have_gnutls" != "xyes"; then :
-  as_fn_error $? "can't find usable libgnutls at specified prefix $with_gnutls" "$LINENO" 5
-fi
-        LDFLAGS="$SAVE_LDFLAGS"
-        CPPFLAGS="$SAVE_CPPFLAGS"
-        ;;
-    esac
-
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: automatically" >&5
-$as_echo "automatically" >&6; }
-
-fi
-
-
-
-
-
-
-
-
-
-if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
-	if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args.
-set dummy ${ac_tool_prefix}pkg-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_PKG_CONFIG+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $PKG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-PKG_CONFIG=$ac_cv_path_PKG_CONFIG
-if test -n "$PKG_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
-$as_echo "$PKG_CONFIG" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_path_PKG_CONFIG"; then
-  ac_pt_PKG_CONFIG=$PKG_CONFIG
-  # Extract the first word of "pkg-config", so it can be a program name with args.
-set dummy pkg-config; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  case $ac_pt_PKG_CONFIG in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG
-if test -n "$ac_pt_PKG_CONFIG"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5
-$as_echo "$ac_pt_PKG_CONFIG" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_pt_PKG_CONFIG" = x; then
-    PKG_CONFIG=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    PKG_CONFIG=$ac_pt_PKG_CONFIG
-  fi
-else
-  PKG_CONFIG="$ac_cv_path_PKG_CONFIG"
-fi
-
-fi
-if test -n "$PKG_CONFIG"; then
-	_pkg_min_version=0.9.0
-	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5
-$as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; }
-	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
-		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-	else
-		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-		PKG_CONFIG=""
-	fi
-fi
-if test "x$with_gnutls" != "xno" && test "x$have_gnutls" != "xyes"; then :
-
-
-pkg_failed=no
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNUTLS" >&5
-$as_echo_n "checking for GNUTLS... " >&6; }
-
-if test -n "$GNUTLS_CFLAGS"; then
-    pkg_cv_GNUTLS_CFLAGS="$GNUTLS_CFLAGS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"gnutls\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "gnutls") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_GNUTLS_CFLAGS=`$PKG_CONFIG --cflags "gnutls" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-if test -n "$GNUTLS_LIBS"; then
-    pkg_cv_GNUTLS_LIBS="$GNUTLS_LIBS"
- elif test -n "$PKG_CONFIG"; then
-    if test -n "$PKG_CONFIG" && \
-    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"gnutls\""; } >&5
-  ($PKG_CONFIG --exists --print-errors "gnutls") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then
-  pkg_cv_GNUTLS_LIBS=`$PKG_CONFIG --libs "gnutls" 2>/dev/null`
-		      test "x$?" != "x0" && pkg_failed=yes
-else
-  pkg_failed=yes
-fi
- else
-    pkg_failed=untried
-fi
-
-
-
-if test $pkg_failed = yes; then
-   	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi
-        if test $_pkg_short_errors_supported = yes; then
-	        GNUTLS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "gnutls" 2>&1`
-        else
-	        GNUTLS_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "gnutls" 2>&1`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$GNUTLS_PKG_ERRORS" >&5
-
-
-       have_gnutls_pkgcfg='no'
-       for ac_header in gnutls/gnutls.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "gnutls/gnutls.h" "ac_cv_header_gnutls_gnutls_h" "$ac_includes_default"
-if test "x$ac_cv_header_gnutls_gnutls_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GNUTLS_GNUTLS_H 1
-_ACEOF
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_priority_set in -lgnutls" >&5
-$as_echo_n "checking for gnutls_priority_set in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_priority_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_priority_set ();
-int
-main ()
-{
-return gnutls_priority_set ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_priority_set=yes
-else
-  ac_cv_lib_gnutls_gnutls_priority_set=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_priority_set" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_priority_set" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_priority_set" = xyes; then :
-
-            GNUTLS_LIBS="-lgnutls"
-            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_load_file in -lgnutls" >&5
-$as_echo_n "checking for gnutls_load_file in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_load_file+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_load_file ();
-int
-main ()
-{
-return gnutls_load_file ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_load_file=yes
-else
-  ac_cv_lib_gnutls_gnutls_load_file=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_load_file" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_load_file" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_load_file" = xyes; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_privkey_import_x509_raw in -lgnutls" >&5
-$as_echo_n "checking for gnutls_privkey_import_x509_raw in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_privkey_import_x509_raw ();
-int
-main ()
-{
-return gnutls_privkey_import_x509_raw ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw=yes
-else
-  ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" = xyes; then :
-  have_gnutls_sni=yes
-fi
-
-fi
-
-            have_gnutls=yes
-
-fi
-
-fi
-
-done
-
-
-elif test $pkg_failed = untried; then
-     	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-       have_gnutls_pkgcfg='no'
-       for ac_header in gnutls/gnutls.h
-do :
-  ac_fn_c_check_header_mongrel "$LINENO" "gnutls/gnutls.h" "ac_cv_header_gnutls_gnutls_h" "$ac_includes_default"
-if test "x$ac_cv_header_gnutls_gnutls_h" = xyes; then :
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_GNUTLS_GNUTLS_H 1
-_ACEOF
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_priority_set in -lgnutls" >&5
-$as_echo_n "checking for gnutls_priority_set in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_priority_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_priority_set ();
-int
-main ()
-{
-return gnutls_priority_set ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_priority_set=yes
-else
-  ac_cv_lib_gnutls_gnutls_priority_set=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_priority_set" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_priority_set" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_priority_set" = xyes; then :
-
-            GNUTLS_LIBS="-lgnutls"
-            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_load_file in -lgnutls" >&5
-$as_echo_n "checking for gnutls_load_file in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_load_file+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_load_file ();
-int
-main ()
-{
-return gnutls_load_file ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_load_file=yes
-else
-  ac_cv_lib_gnutls_gnutls_load_file=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_load_file" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_load_file" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_load_file" = xyes; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_privkey_import_x509_raw in -lgnutls" >&5
-$as_echo_n "checking for gnutls_privkey_import_x509_raw in -lgnutls... " >&6; }
-if ${ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgnutls  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gnutls_privkey_import_x509_raw ();
-int
-main ()
-{
-return gnutls_privkey_import_x509_raw ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw=yes
-else
-  ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" >&5
-$as_echo "$ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" >&6; }
-if test "x$ac_cv_lib_gnutls_gnutls_privkey_import_x509_raw" = xyes; then :
-  have_gnutls_sni=yes
-fi
-
-fi
-
-            have_gnutls=yes
-
-fi
-
-fi
-
-done
-
-
-else
-	GNUTLS_CFLAGS=$pkg_cv_GNUTLS_CFLAGS
-	GNUTLS_LIBS=$pkg_cv_GNUTLS_LIBS
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-
-       have_gnutls_pkgcfg='yes'
-       SAVE_CPPFLAGS="$CPPFLAGS"
-       SAVE_CFLAGS="$CFLAGS"
-       SAVE_LDFLAGS="$LDFLAGS"
-       SAVE_LIBS="$LIBS"
-       CPPFLAGS="$GNUTLS_CFLAGS $CPPFLAGS"
-       CFLAGS="$GNUTLS_CFLAGS $CFLAGS"
-       LDFLAGS="$GNUTLS_LIBS $LDFLAGS"
-       LIBS="$LIBS $GNUTLS_LIBS"
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether GnuTLS is usable" >&5
-$as_echo_n "checking whether GnuTLS is usable... " >&6; }
-       cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-         #include <gnutls/gnutls.h>
-int
-main ()
-{
-
-                gnutls_session_t session;
-                gnutls_priority_t priorities;
-                gnutls_global_init();
-                gnutls_priority_init(&priorities, "NORMAL", NULL);
-                gnutls_init(&session, GNUTLS_SERVER);
-                gnutls_priority_set(session, priorities);
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-           have_gnutls=yes
-           GNUTLS_CPPLAGS="$GNUTLS_CFLAGS"
-           GNUTLS_LDFLAGS="$GNUTLS_LIBS"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gnutls_privkey_import_x509_raw()" >&5
-$as_echo_n "checking for gnutls_privkey_import_x509_raw()... " >&6; }
-           cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-             #include <gnutls/gnutls.h>
-int
-main ()
-{
-
-                    gnutls_datum_t data;
-                    gnutls_privkey_t key;
-                    gnutls_load_file("key.pem", &data);
-                    gnutls_privkey_import_x509_raw(key, &data, GNUTLS_X509_FMT_PEM, NULL, 0);
-                    gnutls_free(data.data);
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  have_gnutls_sni=yes
-else
-  have_gnutls_sni=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_gnutls_sni" >&5
-$as_echo "$have_gnutls_sni" >&6; }
-
-else
-
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-           have_gnutls=no
-
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-
-       if test "x$have_gnutls" != "xyes"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: pkg-config reports that GnuTLS is present, but GnuTLS can't be used" >&5
-$as_echo "$as_me: WARNING: pkg-config reports that GnuTLS is present, but GnuTLS can't be used" >&2;}
-fi
-       CPPFLAGS="$SAVE_CPPFLAGS"
-       CFLAGS="$SAVE_CFLAGS"
-       LDFLAGS="$SAVE_LDFLAGS"
-       LIBS="$SAVE_LIBS"
-
-fi
-
-fi
-
-if test "x$have_gnutls" != "xyes" && test "x$with_gnutls" = "xyes"; then :
-  as_fn_error $? "can't find usable libgnutls" "$LINENO" 5
-fi
-
- if test "x$have_gnutls" = "xyes"; then
-  HAVE_GNUTLS_TRUE=
-  HAVE_GNUTLS_FALSE='#'
-else
-  HAVE_GNUTLS_TRUE='#'
-  HAVE_GNUTLS_FALSE=
-fi
-
- if test "x$have_gnutls_sni" = "xyes"; then
-  HAVE_GNUTLS_SNI_TRUE=
-  HAVE_GNUTLS_SNI_FALSE='#'
-else
-  HAVE_GNUTLS_SNI_TRUE='#'
-  HAVE_GNUTLS_SNI_FALSE=
-fi
-
-
-
-
-
-
-
-# optional: HTTPS support.  Enabled by default
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to support HTTPS" >&5
-$as_echo_n "checking whether to support HTTPS... " >&6; }
-# Check whether --enable-https was given.
-if test "${enable_https+set}" = set; then :
-  enableval=$enable_https; enable_https=${enableval}
-fi
-
-if test "x$enable_https" != "xno"
-then
-  if test "x$have_gnutls" = "xyes" && test "x$have_gcrypt" = "xyes"; then :
-
-
-$as_echo "#define HTTPS_SUPPORT 1" >>confdefs.h
-
-          MHD_LIB_CPPFLAGS="$MHD_LIB_CPPFLAGS $LIBGCRYPT_CFLAGS $GNUTLS_CPPFLAGS"
-          MHD_LIB_CFLAGS="$MHD_LIB_CFLAGS $LIBGCRYPT_CFLAGS $GNUTLS_CFLAGS"
-          MHD_LIB_LDFLAGS="$MHD_LIB_LDFLAGS $GNUTLS_LDFLAGS"
-          MHD_LIBDEPS="$GNUTLS_LIBS $LIBGCRYPT_LIBS $MHD_LIBDEPS"
-          enable_https=yes
-          MSG_HTTPS="yes (using libgnutls and libgcrypt)"
-
-else
-
-          if test "x$have_gnutls" = "xyes"; then :
-  crypt_missing="libgrypt"
-elif test "x$have_gcrypt" = "xyes"; then :
-  crypt_missing="libgnutls"
-else
-  crypt_missing="libgrypt and libgnutls"
-fi
-          if test "x$enable_https" = "xyes" ; then :
-  as_fn_error $? "HTTPS support cannot be enabled without $crypt_missing." "$LINENO" 5
-fi
-
-$as_echo "#define HTTPS_SUPPORT 0" >>confdefs.h
-
-          enable_https=no
-          MSG_HTTPS="no (lacking $crypt_missing)"
-
-fi
-else
-
-$as_echo "#define HTTPS_SUPPORT 0" >>confdefs.h
-
-  MSG_HTTPS="no (disabled)"
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSG_HTTPS" >&5
-$as_echo "$MSG_HTTPS" >&6; }
-
- if test "x$enable_https" = "xyes"; then
-  ENABLE_HTTPS_TRUE=
-  ENABLE_HTTPS_FALSE='#'
-else
-  ENABLE_HTTPS_TRUE='#'
-  ENABLE_HTTPS_FALSE=
-fi
-
-
-# optional: HTTP Basic Auth support. Enabled by default
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to support HTTP basic authentication" >&5
-$as_echo_n "checking whether to support HTTP basic authentication... " >&6; }
-# Check whether --enable-bauth was given.
-if test "${enable_bauth+set}" = set; then :
-  enableval=$enable_bauth; enable_bauth=${enableval}
-else
-  enable_bauth=yes
-fi
-
-if test "x$enable_bauth" != "xno"
-then
- enable_bauth=yes
-
-$as_echo "#define BAUTH_SUPPORT 1" >>confdefs.h
-
-else
-
-$as_echo "#define BAUTH_SUPPORT 0" >>confdefs.h
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_bauth" >&5
-$as_echo "$enable_bauth" >&6; }
- if test "x$enable_bauth" != "xno"; then
-  ENABLE_BAUTH_TRUE=
-  ENABLE_BAUTH_FALSE='#'
-else
-  ENABLE_BAUTH_TRUE='#'
-  ENABLE_BAUTH_FALSE=
-fi
-
-
-# optional: HTTP Digest Auth support. Enabled by default
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to support HTTP digest authentication" >&5
-$as_echo_n "checking whether to support HTTP digest authentication... " >&6; }
-# Check whether --enable-dauth was given.
-if test "${enable_dauth+set}" = set; then :
-  enableval=$enable_dauth; enable_dauth=${enableval}
-else
-  enable_dauth=yes
-fi
-
-if test "x$enable_dauth" != "xno"
-then
- enable_dauth=yes
-
-$as_echo "#define DAUTH_SUPPORT 1" >>confdefs.h
-
-else
-
-$as_echo "#define DAUTH_SUPPORT 0" >>confdefs.h
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_dauth" >&5
-$as_echo "$enable_dauth" >&6; }
- if test "x$enable_dauth" != "xno"; then
-  ENABLE_DAUTH_TRUE=
-  ENABLE_DAUTH_FALSE='#'
-else
-  ENABLE_DAUTH_TRUE='#'
-  ENABLE_DAUTH_FALSE=
-fi
-
-
-
-
-MHD_LIB_LDFLAGS="$MHD_LIB_LDFLAGS -export-dynamic -no-undefined"
-
-# gcov compilation
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to compile with support for code coverage analysis" >&5
-$as_echo_n "checking whether to compile with support for code coverage analysis... " >&6; }
-# Check whether --enable-coverage was given.
-if test "${enable_coverage+set}" = set; then :
-  enableval=$enable_coverage; use_gcov=${enableval}
-else
-  use_gcov=no
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $use_gcov" >&5
-$as_echo "$use_gcov" >&6; }
- if test "x$use_gcov" = "xyes"; then
-  USE_COVERAGE_TRUE=
-  USE_COVERAGE_FALSE='#'
-else
-  USE_COVERAGE_TRUE='#'
-  USE_COVERAGE_FALSE=
-fi
-
-
-
-
-
-      { $as_echo "$as_me:${as_lineno-$LINENO}: checking the number of available CPUs" >&5
-$as_echo_n "checking the number of available CPUs... " >&6; }
-      CPU_COUNT="0"
-
-      case $host_os in #(
-
-        *darwin*) :
-
-        if test -x /usr/sbin/sysctl; then :
-
-          sysctl_a=`/usr/sbin/sysctl -a 2>/dev/null| grep -c hw.cpu`
-          if test sysctl_a; then :
-
-            CPU_COUNT=`/usr/sbin/sysctl -n hw.ncpu`
-
-fi
-
-fi ;; #(
-
-        *linux*) :
-
-        if test "x$CPU_COUNT" = "x0" -a -e /proc/cpuinfo; then :
-
-          if test "x$CPU_COUNT" = "x0" -a -e /proc/cpuinfo; then :
-
-            CPU_COUNT=`$EGREP -c '^processor' /proc/cpuinfo`
-
-fi
-
-fi ;; #(
-
-        *mingw*) :
-
-        if test -n "$NUMBER_OF_PROCESSORS"; then :
-
-          CPU_COUNT="$NUMBER_OF_PROCESSORS"
-
-fi ;; #(
-
-        *cygwin*) :
-
-        if test -n "$NUMBER_OF_PROCESSORS"; then :
-
-          CPU_COUNT="$NUMBER_OF_PROCESSORS"
-
-fi
-         ;; #(
-  *) :
-     ;;
-esac
-
-      if test "x$CPU_COUNT" = "x0"; then :
-
-        CPU_COUNT="1"
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: unable to detect (assuming 1) " >&5
-$as_echo "unable to detect (assuming 1) " >&6; }
-
-else
-
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPU_COUNT " >&5
-$as_echo "$CPU_COUNT " >&6; }
-
-fi
-
-
-
-
-
-
-
-# for pkg-config
-if test "x$enable_https" = "xyes" && test "x$have_gnutls_pkgcfg" = "xyes" ; then :
-   # remove GnuTLS from private libs in .pc file as it defined in Requires.private
-   MHD_REQ_PRIVATE='gnutls'
-   MHD_LIBDEPS_PKGCFG="${MHD_LIBDEPS//$GNUTLS_LIBS/}"
-
-else
-
-   MHD_REQ_PRIVATE=''
-   MHD_LIBDEPS_PKGCFG="$MHD_LIBDEPS"
-
-fi
-
-
-
-
-
-
-
-
-ac_config_files="$ac_config_files libmicrohttpd.pc libmicrospdy.pc w32/VS2013/microhttpd_dll_res_vc.rc Makefile contrib/Makefile doc/Makefile doc/doxygen/Makefile doc/examples/Makefile m4/Makefile src/Makefile src/include/Makefile src/platform/Makefile src/microhttpd/Makefile src/microspdy/Makefile src/spdy2http/Makefile src/examples/Makefile src/testcurl/Makefile src/testcurl/https/Makefile src/testspdy/Makefile src/testzzuf/Makefile"
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems.  If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, we kill variables containing newlines.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(
-  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
-      *) { eval $ac_var=; unset $ac_var;} ;;
-      esac ;;
-    esac
-  done
-
-  (set) 2>&1 |
-    case $as_nl`(ac_space=' '; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      # `set' does not quote correctly, so add quotes: double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \.
-      sed -n \
-	"s/'/'\\\\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;; #(
-    *)
-      # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-) |
-  sed '
-     /^ac_cv_env_/b end
-     t clear
-     :clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
-     t end
-     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     :end' >>confcache
-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
-  if test -w "$cache_file"; then
-    if test "x$cache_file" != "x/dev/null"; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
-$as_echo "$as_me: updating cache $cache_file" >&6;}
-      if test ! -f "$cache_file" || test -h "$cache_file"; then
-	cat confcache >"$cache_file"
-      else
-        case $cache_file in #(
-        */* | ?:*)
-	  mv -f confcache "$cache_file"$$ &&
-	  mv -f "$cache_file"$$ "$cache_file" ;; #(
-        *)
-	  mv -f confcache "$cache_file" ;;
-	esac
-      fi
-    fi
-  else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
-  fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-DEFS=-DHAVE_CONFIG_H
-
-ac_libobjs=
-ac_ltlibobjs=
-U=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
-  # 1. Remove the extension, and $U if already installed.
-  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
-  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
-  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
-  #    will be set to the directory where LIBOBJS objects are built.
-  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
-  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5
-$as_echo_n "checking that generated files are newer than configure... " >&6; }
-   if test -n "$am_sleep_pid"; then
-     # Hide warnings about reused PIDs.
-     wait $am_sleep_pid 2>/dev/null
-   fi
-   { $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5
-$as_echo "done" >&6; }
- if test -n "$EXEEXT"; then
-  am__EXEEXT_TRUE=
-  am__EXEEXT_FALSE='#'
-else
-  am__EXEEXT_TRUE='#'
-  am__EXEEXT_FALSE=
-fi
-
-if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then
-  as_fn_error $? "conditional \"AMDEP\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then
-  as_fn_error $? "conditional \"am__fastdepCC\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_POSIX_THREADS_TRUE}" && test -z "${HAVE_POSIX_THREADS_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_POSIX_THREADS\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${USE_POSIX_THREADS_TRUE}" && test -z "${USE_POSIX_THREADS_FALSE}"; then
-  as_fn_error $? "conditional \"USE_POSIX_THREADS\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${USE_W32_THREADS_TRUE}" && test -z "${USE_W32_THREADS_FALSE}"; then
-  as_fn_error $? "conditional \"USE_W32_THREADS\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_W32_TRUE}" && test -z "${HAVE_W32_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_W32\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${W32_SHARED_LIB_EXP_TRUE}" && test -z "${W32_SHARED_LIB_EXP_FALSE}"; then
-  as_fn_error $? "conditional \"W32_SHARED_LIB_EXP\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${USE_MS_LIB_TOOL_TRUE}" && test -z "${USE_MS_LIB_TOOL_FALSE}"; then
-  as_fn_error $? "conditional \"USE_MS_LIB_TOOL\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-
-if test -z "${HAVE_CURL_BINARY_TRUE}" && test -z "${HAVE_CURL_BINARY_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_CURL_BINARY\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_MAKEINFO_BINARY_TRUE}" && test -z "${HAVE_MAKEINFO_BINARY_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_MAKEINFO_BINARY\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${W32_STATIC_LIB_TRUE}" && test -z "${W32_STATIC_LIB_FALSE}"; then
-  as_fn_error $? "conditional \"W32_STATIC_LIB\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${BUILD_DOC_TRUE}" && test -z "${BUILD_DOC_FALSE}"; then
-  as_fn_error $? "conditional \"BUILD_DOC\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${BUILD_EXAMPLES_TRUE}" && test -z "${BUILD_EXAMPLES_FALSE}"; then
-  as_fn_error $? "conditional \"BUILD_EXAMPLES\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_TSEARCH_TRUE}" && test -z "${HAVE_TSEARCH_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_TSEARCH\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_CURL_TRUE}" && test -z "${HAVE_CURL_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_CURL\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_MAGIC_TRUE}" && test -z "${HAVE_MAGIC_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_MAGIC\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_MAGIC_TRUE}" && test -z "${HAVE_MAGIC_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_MAGIC\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_MAGIC_TRUE}" && test -z "${HAVE_MAGIC_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_MAGIC\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_OPENSSL_TRUE}" && test -z "${HAVE_OPENSSL_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_OPENSSL\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${ENABLE_SPDY_TRUE}" && test -z "${ENABLE_SPDY_FALSE}"; then
-  as_fn_error $? "conditional \"ENABLE_SPDY\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_SPDYLAY_TRUE}" && test -z "${HAVE_SPDYLAY_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_SPDYLAY\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_POSTPROCESSOR_TRUE}" && test -z "${HAVE_POSTPROCESSOR_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_POSTPROCESSOR\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_ZZUF_TRUE}" && test -z "${HAVE_ZZUF_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_ZZUF\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_SOCAT_TRUE}" && test -z "${HAVE_SOCAT_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_SOCAT\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_GNUTLS_TRUE}" && test -z "${HAVE_GNUTLS_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_GNUTLS\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${HAVE_GNUTLS_SNI_TRUE}" && test -z "${HAVE_GNUTLS_SNI_FALSE}"; then
-  as_fn_error $? "conditional \"HAVE_GNUTLS_SNI\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${ENABLE_HTTPS_TRUE}" && test -z "${ENABLE_HTTPS_FALSE}"; then
-  as_fn_error $? "conditional \"ENABLE_HTTPS\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${ENABLE_BAUTH_TRUE}" && test -z "${ENABLE_BAUTH_FALSE}"; then
-  as_fn_error $? "conditional \"ENABLE_BAUTH\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${ENABLE_DAUTH_TRUE}" && test -z "${ENABLE_DAUTH_FALSE}"; then
-  as_fn_error $? "conditional \"ENABLE_DAUTH\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-if test -z "${USE_COVERAGE_TRUE}" && test -z "${USE_COVERAGE_FALSE}"; then
-  as_fn_error $? "conditional \"USE_COVERAGE\" was never defined.
-Usually this means the macro was only invoked conditionally." "$LINENO" 5
-fi
-
-: "${CONFIG_STATUS=./config.status}"
-ac_write_fail=0
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
-as_write_fail=0
-cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in #(
-  *posix*) :
-    set -o posix ;; #(
-  *) :
-     ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-	expr "X$arg" : "X\\(.*\\)$as_nl";
-	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  PATH_SEPARATOR=:
-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
-      PATH_SEPARATOR=';'
-  }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""	$as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-  done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
-  as_status=$1; test $as_status -eq 0 && as_status=1
-  if test "$4"; then
-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
-  fi
-  $as_echo "$as_me: error: $2" >&2
-  as_fn_exit $as_status
-} # as_fn_error
-
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
-  return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
-  set +e
-  as_fn_set_status $1
-  exit $1
-} # as_fn_exit
-
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
-  { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
-  eval 'as_fn_append ()
-  {
-    eval $1+=\$2
-  }'
-else
-  as_fn_append ()
-  {
-    eval $1=\$$1\$2
-  }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
-  eval 'as_fn_arith ()
-  {
-    as_val=$(( $* ))
-  }'
-else
-  as_fn_arith ()
-  {
-    as_val=`expr "$@" || test $? -eq 1`
-  }
-fi # as_fn_arith
-
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
-  case `echo 'xy\c'` in
-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
-  xy)  ECHO_C='\c';;
-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
-       ECHO_T='	';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
-  if ln -s conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s='ln -s'
-    # ... but there are two gotchas:
-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -pR'.
-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -pR'
-  elif ln conf$$.file conf$$ 2>/dev/null; then
-    as_ln_s=ln
-  else
-    as_ln_s='cp -pR'
-  fi
-else
-  as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || eval $as_mkdir_p || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p='mkdir -p "$as_dir"'
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
-  test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-## ----------------------------------- ##
-## Main body of $CONFIG_STATUS script. ##
-## ----------------------------------- ##
-_ASEOF
-test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# Save the log message, to keep $0 and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by libmicrohttpd $as_me 0.9.42, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
-
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-_ACEOF
-
-case $ac_config_files in *"
-"*) set x $ac_config_files; shift; ac_config_files=$*;;
-esac
-
-case $ac_config_headers in *"
-"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
-esac
-
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-# Files that config.status was made for.
-config_files="$ac_config_files"
-config_headers="$ac_config_headers"
-config_commands="$ac_config_commands"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-ac_cs_usage="\
-\`$as_me' instantiates files and other configuration actions
-from templates according to the current configuration.  Unless the files
-and actions are specified as TAGs, all are instantiated by default.
-
-Usage: $0 [OPTION]... [TAG]...
-
-  -h, --help       print this help, then exit
-  -V, --version    print version number and configuration settings, then exit
-      --config     print configuration, then exit
-  -q, --quiet, --silent
-                   do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-      --file=FILE[:TEMPLATE]
-                   instantiate the configuration file FILE
-      --header=FILE[:TEMPLATE]
-                   instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Configuration commands:
-$config_commands
-
-Report bugs to <libmicrohttpd@gnu.org>."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
-ac_cs_version="\\
-libmicrohttpd config.status 0.9.42
-configured by $0, generated by GNU Autoconf 2.69,
-  with options \\"\$ac_cs_config\\"
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='$ac_pwd'
-srcdir='$srcdir'
-INSTALL='$INSTALL'
-MKDIR_P='$MKDIR_P'
-AWK='$AWK'
-test -n "\$AWK" || AWK=awk
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# The default lists apply if the user does not specify any file.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=?*)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  --*=)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=
-    ac_shift=:
-    ;;
-  *)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  esac
-
-  case $ac_option in
-  # Handling of the options.
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    $as_echo "$ac_cs_version"; exit ;;
-  --config | --confi | --conf | --con | --co | --c )
-    $as_echo "$ac_cs_config"; exit ;;
-  --debug | --debu | --deb | --de | --d | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    '') as_fn_error $? "missing file argument" ;;
-    esac
-    as_fn_append CONFIG_FILES " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --header | --heade | --head | --hea )
-    $ac_shift
-    case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
-    ac_need_defaults=false;;
-  --he | --h)
-    # Conflict between --help and --header
-    as_fn_error $? "ambiguous option: \`$1'
-Try \`$0 --help' for more information.";;
-  --help | --hel | -h )
-    $as_echo "$ac_cs_usage"; exit ;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
-
-  # This is an error.
-  -*) as_fn_error $? "unrecognized option: \`$1'
-Try \`$0 --help' for more information." ;;
-
-  *) as_fn_append ac_config_targets " $1"
-     ac_need_defaults=false ;;
-
-  esac
-  shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-if \$ac_cs_recheck; then
-  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
-  shift
-  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
-  CONFIG_SHELL='$SHELL'
-  export CONFIG_SHELL
-  exec "\$@"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-  $as_echo "$ac_log"
-} >&5
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-#
-# INIT-COMMANDS
-#
-AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"
-
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-sed_quote_subst='$sed_quote_subst'
-double_quote_subst='$double_quote_subst'
-delay_variable_subst='$delay_variable_subst'
-macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`'
-macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`'
-AS='`$ECHO "$AS" | $SED "$delay_single_quote_subst"`'
-DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`'
-OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`'
-enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`'
-enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`'
-pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`'
-enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`'
-SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`'
-ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`'
-PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`'
-host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`'
-host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`'
-host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`'
-build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`'
-build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`'
-build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`'
-SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`'
-Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`'
-GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`'
-EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`'
-FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`'
-LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`'
-NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`'
-LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`'
-max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`'
-ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`'
-exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`'
-lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`'
-lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`'
-lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`'
-lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`'
-lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`'
-reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`'
-reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`'
-deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`'
-file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`'
-file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`'
-want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`'
-sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`'
-AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`'
-AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`'
-archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`'
-STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`'
-RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`'
-old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`'
-old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`'
-old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`'
-lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`'
-CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`'
-CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`'
-compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`'
-GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`'
-lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`'
-lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`'
-lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`'
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`'
-nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`'
-lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`'
-objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`'
-MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`'
-lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`'
-need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`'
-MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`'
-DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`'
-NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`'
-LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`'
-OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`'
-OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`'
-libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`'
-shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`'
-extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`'
-archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`'
-enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`'
-export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`'
-whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`'
-compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`'
-old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`'
-old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`'
-archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`'
-archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`'
-module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`'
-module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`'
-with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`'
-allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`'
-no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`'
-hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`'
-hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`'
-hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`'
-hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`'
-hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`'
-hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`'
-hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`'
-inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`'
-link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`'
-always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`'
-export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`'
-exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`'
-include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`'
-prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`'
-postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`'
-file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`'
-variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`'
-need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`'
-need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`'
-version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`'
-runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`'
-shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`'
-shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`'
-libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`'
-library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`'
-soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`'
-install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`'
-postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`'
-postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`'
-finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`'
-finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`'
-hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`'
-sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`'
-sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`'
-hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`'
-enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`'
-enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`'
-enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`'
-old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`'
-striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`'
-LD_RC='`$ECHO "$LD_RC" | $SED "$delay_single_quote_subst"`'
-reload_flag_RC='`$ECHO "$reload_flag_RC" | $SED "$delay_single_quote_subst"`'
-reload_cmds_RC='`$ECHO "$reload_cmds_RC" | $SED "$delay_single_quote_subst"`'
-old_archive_cmds_RC='`$ECHO "$old_archive_cmds_RC" | $SED "$delay_single_quote_subst"`'
-compiler_RC='`$ECHO "$compiler_RC" | $SED "$delay_single_quote_subst"`'
-GCC_RC='`$ECHO "$GCC_RC" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_no_builtin_flag_RC='`$ECHO "$lt_prog_compiler_no_builtin_flag_RC" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_pic_RC='`$ECHO "$lt_prog_compiler_pic_RC" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_wl_RC='`$ECHO "$lt_prog_compiler_wl_RC" | $SED "$delay_single_quote_subst"`'
-lt_prog_compiler_static_RC='`$ECHO "$lt_prog_compiler_static_RC" | $SED "$delay_single_quote_subst"`'
-lt_cv_prog_compiler_c_o_RC='`$ECHO "$lt_cv_prog_compiler_c_o_RC" | $SED "$delay_single_quote_subst"`'
-archive_cmds_need_lc_RC='`$ECHO "$archive_cmds_need_lc_RC" | $SED "$delay_single_quote_subst"`'
-enable_shared_with_static_runtimes_RC='`$ECHO "$enable_shared_with_static_runtimes_RC" | $SED "$delay_single_quote_subst"`'
-export_dynamic_flag_spec_RC='`$ECHO "$export_dynamic_flag_spec_RC" | $SED "$delay_single_quote_subst"`'
-whole_archive_flag_spec_RC='`$ECHO "$whole_archive_flag_spec_RC" | $SED "$delay_single_quote_subst"`'
-compiler_needs_object_RC='`$ECHO "$compiler_needs_object_RC" | $SED "$delay_single_quote_subst"`'
-old_archive_from_new_cmds_RC='`$ECHO "$old_archive_from_new_cmds_RC" | $SED "$delay_single_quote_subst"`'
-old_archive_from_expsyms_cmds_RC='`$ECHO "$old_archive_from_expsyms_cmds_RC" | $SED "$delay_single_quote_subst"`'
-archive_cmds_RC='`$ECHO "$archive_cmds_RC" | $SED "$delay_single_quote_subst"`'
-archive_expsym_cmds_RC='`$ECHO "$archive_expsym_cmds_RC" | $SED "$delay_single_quote_subst"`'
-module_cmds_RC='`$ECHO "$module_cmds_RC" | $SED "$delay_single_quote_subst"`'
-module_expsym_cmds_RC='`$ECHO "$module_expsym_cmds_RC" | $SED "$delay_single_quote_subst"`'
-with_gnu_ld_RC='`$ECHO "$with_gnu_ld_RC" | $SED "$delay_single_quote_subst"`'
-allow_undefined_flag_RC='`$ECHO "$allow_undefined_flag_RC" | $SED "$delay_single_quote_subst"`'
-no_undefined_flag_RC='`$ECHO "$no_undefined_flag_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_libdir_flag_spec_RC='`$ECHO "$hardcode_libdir_flag_spec_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_libdir_separator_RC='`$ECHO "$hardcode_libdir_separator_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_direct_RC='`$ECHO "$hardcode_direct_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_direct_absolute_RC='`$ECHO "$hardcode_direct_absolute_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_minus_L_RC='`$ECHO "$hardcode_minus_L_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_shlibpath_var_RC='`$ECHO "$hardcode_shlibpath_var_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_automatic_RC='`$ECHO "$hardcode_automatic_RC" | $SED "$delay_single_quote_subst"`'
-inherit_rpath_RC='`$ECHO "$inherit_rpath_RC" | $SED "$delay_single_quote_subst"`'
-link_all_deplibs_RC='`$ECHO "$link_all_deplibs_RC" | $SED "$delay_single_quote_subst"`'
-always_export_symbols_RC='`$ECHO "$always_export_symbols_RC" | $SED "$delay_single_quote_subst"`'
-export_symbols_cmds_RC='`$ECHO "$export_symbols_cmds_RC" | $SED "$delay_single_quote_subst"`'
-exclude_expsyms_RC='`$ECHO "$exclude_expsyms_RC" | $SED "$delay_single_quote_subst"`'
-include_expsyms_RC='`$ECHO "$include_expsyms_RC" | $SED "$delay_single_quote_subst"`'
-prelink_cmds_RC='`$ECHO "$prelink_cmds_RC" | $SED "$delay_single_quote_subst"`'
-postlink_cmds_RC='`$ECHO "$postlink_cmds_RC" | $SED "$delay_single_quote_subst"`'
-file_list_spec_RC='`$ECHO "$file_list_spec_RC" | $SED "$delay_single_quote_subst"`'
-hardcode_action_RC='`$ECHO "$hardcode_action_RC" | $SED "$delay_single_quote_subst"`'
-
-LTCC='$LTCC'
-LTCFLAGS='$LTCFLAGS'
-compiler='$compiler_DEFAULT'
-
-# A function that is used when there is no print builtin or printf.
-func_fallback_echo ()
-{
-  eval 'cat <<_LTECHO_EOF
-\$1
-_LTECHO_EOF'
-}
-
-# Quote evaled strings.
-for var in AS \
-DLLTOOL \
-OBJDUMP \
-SHELL \
-ECHO \
-PATH_SEPARATOR \
-SED \
-GREP \
-EGREP \
-FGREP \
-LD \
-NM \
-LN_S \
-lt_SP2NL \
-lt_NL2SP \
-reload_flag \
-deplibs_check_method \
-file_magic_cmd \
-file_magic_glob \
-want_nocaseglob \
-sharedlib_from_linklib_cmd \
-AR \
-AR_FLAGS \
-archiver_list_spec \
-STRIP \
-RANLIB \
-CC \
-CFLAGS \
-compiler \
-lt_cv_sys_global_symbol_pipe \
-lt_cv_sys_global_symbol_to_cdecl \
-lt_cv_sys_global_symbol_to_c_name_address \
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \
-nm_file_list_spec \
-lt_prog_compiler_no_builtin_flag \
-lt_prog_compiler_pic \
-lt_prog_compiler_wl \
-lt_prog_compiler_static \
-lt_cv_prog_compiler_c_o \
-need_locks \
-MANIFEST_TOOL \
-DSYMUTIL \
-NMEDIT \
-LIPO \
-OTOOL \
-OTOOL64 \
-shrext_cmds \
-export_dynamic_flag_spec \
-whole_archive_flag_spec \
-compiler_needs_object \
-with_gnu_ld \
-allow_undefined_flag \
-no_undefined_flag \
-hardcode_libdir_flag_spec \
-hardcode_libdir_separator \
-exclude_expsyms \
-include_expsyms \
-file_list_spec \
-variables_saved_for_relink \
-libname_spec \
-library_names_spec \
-soname_spec \
-install_override_mode \
-finish_eval \
-old_striplib \
-striplib \
-LD_RC \
-reload_flag_RC \
-compiler_RC \
-lt_prog_compiler_no_builtin_flag_RC \
-lt_prog_compiler_pic_RC \
-lt_prog_compiler_wl_RC \
-lt_prog_compiler_static_RC \
-lt_cv_prog_compiler_c_o_RC \
-export_dynamic_flag_spec_RC \
-whole_archive_flag_spec_RC \
-compiler_needs_object_RC \
-with_gnu_ld_RC \
-allow_undefined_flag_RC \
-no_undefined_flag_RC \
-hardcode_libdir_flag_spec_RC \
-hardcode_libdir_separator_RC \
-exclude_expsyms_RC \
-include_expsyms_RC \
-file_list_spec_RC; do
-    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
-    *[\\\\\\\`\\"\\\$]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-# Double-quote double-evaled strings.
-for var in reload_cmds \
-old_postinstall_cmds \
-old_postuninstall_cmds \
-old_archive_cmds \
-extract_expsyms_cmds \
-old_archive_from_new_cmds \
-old_archive_from_expsyms_cmds \
-archive_cmds \
-archive_expsym_cmds \
-module_cmds \
-module_expsym_cmds \
-export_symbols_cmds \
-prelink_cmds \
-postlink_cmds \
-postinstall_cmds \
-postuninstall_cmds \
-finish_cmds \
-sys_lib_search_path_spec \
-sys_lib_dlsearch_path_spec \
-reload_cmds_RC \
-old_archive_cmds_RC \
-old_archive_from_new_cmds_RC \
-old_archive_from_expsyms_cmds_RC \
-archive_cmds_RC \
-archive_expsym_cmds_RC \
-module_cmds_RC \
-module_expsym_cmds_RC \
-export_symbols_cmds_RC \
-prelink_cmds_RC \
-postlink_cmds_RC; do
-    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
-    *[\\\\\\\`\\"\\\$]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-ac_aux_dir='$ac_aux_dir'
-xsi_shell='$xsi_shell'
-lt_shell_append='$lt_shell_append'
-
-# See if we are running on zsh, and set the options which allow our
-# commands through without removal of \ escapes INIT.
-if test -n "\${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-
-
-    PACKAGE='$PACKAGE'
-    VERSION='$VERSION'
-    TIMESTAMP='$TIMESTAMP'
-    RM='$RM'
-    ofile='$ofile'
-
-
-
-
-
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
-  case $ac_config_target in
-    "MHD_config.h") CONFIG_HEADERS="$CONFIG_HEADERS MHD_config.h" ;;
-    "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
-    "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;;
-    "src/microhttpd/microhttpd_dll_res.rc") CONFIG_FILES="$CONFIG_FILES src/microhttpd/microhttpd_dll_res.rc" ;;
-    "libmicrohttpd.pc") CONFIG_FILES="$CONFIG_FILES libmicrohttpd.pc" ;;
-    "libmicrospdy.pc") CONFIG_FILES="$CONFIG_FILES libmicrospdy.pc" ;;
-    "w32/VS2013/microhttpd_dll_res_vc.rc") CONFIG_FILES="$CONFIG_FILES w32/VS2013/microhttpd_dll_res_vc.rc" ;;
-    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-    "contrib/Makefile") CONFIG_FILES="$CONFIG_FILES contrib/Makefile" ;;
-    "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;;
-    "doc/doxygen/Makefile") CONFIG_FILES="$CONFIG_FILES doc/doxygen/Makefile" ;;
-    "doc/examples/Makefile") CONFIG_FILES="$CONFIG_FILES doc/examples/Makefile" ;;
-    "m4/Makefile") CONFIG_FILES="$CONFIG_FILES m4/Makefile" ;;
-    "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
-    "src/include/Makefile") CONFIG_FILES="$CONFIG_FILES src/include/Makefile" ;;
-    "src/platform/Makefile") CONFIG_FILES="$CONFIG_FILES src/platform/Makefile" ;;
-    "src/microhttpd/Makefile") CONFIG_FILES="$CONFIG_FILES src/microhttpd/Makefile" ;;
-    "src/microspdy/Makefile") CONFIG_FILES="$CONFIG_FILES src/microspdy/Makefile" ;;
-    "src/spdy2http/Makefile") CONFIG_FILES="$CONFIG_FILES src/spdy2http/Makefile" ;;
-    "src/examples/Makefile") CONFIG_FILES="$CONFIG_FILES src/examples/Makefile" ;;
-    "src/testcurl/Makefile") CONFIG_FILES="$CONFIG_FILES src/testcurl/Makefile" ;;
-    "src/testcurl/https/Makefile") CONFIG_FILES="$CONFIG_FILES src/testcurl/https/Makefile" ;;
-    "src/testspdy/Makefile") CONFIG_FILES="$CONFIG_FILES src/testspdy/Makefile" ;;
-    "src/testzzuf/Makefile") CONFIG_FILES="$CONFIG_FILES src/testzzuf/Makefile" ;;
-
-  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
-  esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
-  test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
-fi
-
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
-  tmp= ac_tmp=
-  trap 'exit_status=$?
-  : "${ac_tmp:=$tmp}"
-  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
-' 0
-  trap 'as_fn_exit 1' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -d "$tmp"
-}  ||
-{
-  tmp=./conf$$-$RANDOM
-  (umask 077 && mkdir "$tmp")
-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
-
-# Set up the scripts for CONFIG_FILES section.
-# No need to generate them if there are no CONFIG_FILES.
-# This happens for instance with `./config.status config.h'.
-if test -n "$CONFIG_FILES"; then
-
-
-ac_cr=`echo X | tr X '\015'`
-# On cygwin, bash can eat \r inside `` if the user requested igncr.
-# But we know of no other shell where ac_cr would be empty at this
-# point, so we can use a bashism as a fallback.
-if test "x$ac_cr" = x; then
-  eval ac_cr=\$\'\\r\'
-fi
-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
-  ac_cs_awk_cr='\\r'
-else
-  ac_cs_awk_cr=$ac_cr
-fi
-
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
-_ACEOF
-
-
-{
-  echo "cat >conf$$subs.awk <<_ACEOF" &&
-  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
-  echo "_ACEOF"
-} >conf$$subs.sh ||
-  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
-  . ./conf$$subs.sh ||
-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-
-  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
-  if test $ac_delim_n = $ac_delim_num; then
-    break
-  elif $ac_last_try; then
-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-rm -f conf$$subs.sh
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
-_ACEOF
-sed -n '
-h
-s/^/S["/; s/!.*/"]=/
-p
-g
-s/^[^!]*!//
-:repl
-t repl
-s/'"$ac_delim"'$//
-t delim
-:nl
-h
-s/\(.\{148\}\)..*/\1/
-t more1
-s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
-p
-n
-b repl
-:more1
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t nl
-:delim
-h
-s/\(.\{148\}\)..*/\1/
-t more2
-s/["\\]/\\&/g; s/^/"/; s/$/"/
-p
-b
-:more2
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t delim
-' <conf$$subs.awk | sed '
-/^[^""]/{
-  N
-  s/\n//
-}
-' >>$CONFIG_STATUS || ac_write_fail=1
-rm -f conf$$subs.awk
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACAWK
-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
-  for (key in S) S_is_set[key] = 1
-  FS = ""
-
-}
-{
-  line = $ 0
-  nfields = split(line, field, "@")
-  substed = 0
-  len = length(field[1])
-  for (i = 2; i < nfields; i++) {
-    key = field[i]
-    keylen = length(key)
-    if (S_is_set[key]) {
-      value = S[key]
-      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
-      len += length(value) + length(field[++i])
-      substed = 1
-    } else
-      len += 1 + keylen
-  }
-
-  print line
-}
-
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
-  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
-else
-  cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
-  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
-_ACEOF
-
-# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
-# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{
-h
-s///
-s/^/:/
-s/[	 ]*$/:/
-s/:\$(srcdir):/:/g
-s/:\${srcdir}:/:/g
-s/:@srcdir@:/:/g
-s/^:*//
-s/:*$//
-x
-s/\(=[	 ]*\).*/\1/
-G
-s/\n//
-s/^[^=]*=[	 ]*$//
-}'
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-fi # test -n "$CONFIG_FILES"
-
-# Set up the scripts for CONFIG_HEADERS section.
-# No need to generate them if there are no CONFIG_HEADERS.
-# This happens for instance with `./config.status Makefile'.
-if test -n "$CONFIG_HEADERS"; then
-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
-BEGIN {
-_ACEOF
-
-# Transform confdefs.h into an awk script `defines.awk', embedded as
-# here-document in config.status, that substitutes the proper values into
-# config.h.in to produce config.h.
-
-# Create a delimiter string that does not exist in confdefs.h, to ease
-# handling of long lines.
-ac_delim='%!_!# '
-for ac_last_try in false false :; do
-  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
-  if test -z "$ac_tt"; then
-    break
-  elif $ac_last_try; then
-    as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-
-# For the awk script, D is an array of macro values keyed by name,
-# likewise P contains macro parameters if any.  Preserve backslash
-# newline sequences.
-
-ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
-sed -n '
-s/.\{148\}/&'"$ac_delim"'/g
-t rset
-:rset
-s/^[	 ]*#[	 ]*define[	 ][	 ]*/ /
-t def
-d
-:def
-s/\\$//
-t bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3"/p
-s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2"/p
-d
-:bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3\\\\\\n"\\/p
-t cont
-s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
-t cont
-d
-:cont
-n
-s/.\{148\}/&'"$ac_delim"'/g
-t clear
-:clear
-s/\\$//
-t bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/"/p
-d
-:bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
-b cont
-' <confdefs.h | sed '
-s/'"$ac_delim"'/"\\\
-"/g' >>$CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-  for (key in D) D_is_set[key] = 1
-  FS = ""
-}
-/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
-  line = \$ 0
-  split(line, arg, " ")
-  if (arg[1] == "#") {
-    defundef = arg[2]
-    mac1 = arg[3]
-  } else {
-    defundef = substr(arg[1], 2)
-    mac1 = arg[2]
-  }
-  split(mac1, mac2, "(") #)
-  macro = mac2[1]
-  prefix = substr(line, 1, index(line, defundef) - 1)
-  if (D_is_set[macro]) {
-    # Preserve the white space surrounding the "#".
-    print prefix "define", macro P[macro] D[macro]
-    next
-  } else {
-    # Replace #undef with comments.  This is necessary, for example,
-    # in the case of _POSIX_SOURCE, which is predefined and required
-    # on some systems where configure will not decide to define it.
-    if (defundef == "undef") {
-      print "/*", prefix defundef, macro, "*/"
-      next
-    }
-  }
-}
-{ print }
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
-fi # test -n "$CONFIG_HEADERS"
-
-
-eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    :C $CONFIG_COMMANDS"
-shift
-for ac_tag
-do
-  case $ac_tag in
-  :[FHLC]) ac_mode=$ac_tag; continue;;
-  esac
-  case $ac_mode$ac_tag in
-  :[FHL]*:*);;
-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
-  :[FH]-) ac_tag=-:-;;
-  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
-  esac
-  ac_save_IFS=$IFS
-  IFS=:
-  set x $ac_tag
-  IFS=$ac_save_IFS
-  shift
-  ac_file=$1
-  shift
-
-  case $ac_mode in
-  :L) ac_source=$1;;
-  :[FH])
-    ac_file_inputs=
-    for ac_f
-    do
-      case $ac_f in
-      -) ac_f="$ac_tmp/stdin";;
-      *) # Look for the file first in the build tree, then in the source tree
-	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
-	 # because $ac_f cannot contain `:'.
-	 test -f "$ac_f" ||
-	   case $ac_f in
-	   [\\/$]*) false;;
-	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
-	   esac ||
-	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
-      esac
-      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
-      as_fn_append ac_file_inputs " '$ac_f'"
-    done
-
-    # Let's still pretend it is `configure' which instantiates (i.e., don't
-    # use $as_me), people would be surprised to read:
-    #    /* config.h.  Generated by config.status.  */
-    configure_input='Generated from '`
-	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
-	`' by configure.'
-    if test x"$ac_file" != x-; then
-      configure_input="$ac_file.  $configure_input"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
-    fi
-    # Neutralize special characters interpreted by sed in replacement strings.
-    case $configure_input in #(
-    *\&* | *\|* | *\\* )
-       ac_sed_conf_input=`$as_echo "$configure_input" |
-       sed 's/[\\\\&|]/\\\\&/g'`;; #(
-    *) ac_sed_conf_input=$configure_input;;
-    esac
-
-    case $ac_tag in
-    *:-:* | *:-) cat >"$ac_tmp/stdin" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
-    esac
-    ;;
-  esac
-
-  ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$ac_file" : 'X\(//\)[^/]' \| \
-	 X"$ac_file" : 'X\(//\)$' \| \
-	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-  as_dir="$ac_dir"; as_fn_mkdir_p
-  ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
-  case $ac_mode in
-  :F)
-  #
-  # CONFIG_FILE
-  #
-
-  case $INSTALL in
-  [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
-  *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
-  esac
-  ac_MKDIR_P=$MKDIR_P
-  case $MKDIR_P in
-  [\\/$]* | ?:[\\/]* ) ;;
-  */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;;
-  esac
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-ac_sed_dataroot='
-/datarootdir/ {
-  p
-  q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p'
-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-  ac_datarootdir_hack='
-  s&@datadir@&$datadir&g
-  s&@docdir@&$docdir&g
-  s&@infodir@&$infodir&g
-  s&@localedir@&$localedir&g
-  s&@mandir@&$mandir&g
-  s&\\\${datarootdir}&$datarootdir&g' ;;
-esac
-_ACEOF
-
-# Neutralize VPATH when `$srcdir' = `.'.
-# Shell code in configure.ac might set extrasub.
-# FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_sed_extra="$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s|@configure_input@|$ac_sed_conf_input|;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@top_build_prefix@&$ac_top_build_prefix&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-s&@INSTALL@&$ac_INSTALL&;t t
-s&@MKDIR_P@&$ac_MKDIR_P&;t t
-$ac_datarootdir_hack
-"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
-  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
-      "$ac_tmp/out"`; test -z "$ac_out"; } &&
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined" >&2;}
-
-  rm -f "$ac_tmp/stdin"
-  case $ac_file in
-  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
-  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
-  esac \
-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- ;;
-  :H)
-  #
-  # CONFIG_HEADER
-  #
-  if test x"$ac_file" != x-; then
-    {
-      $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
-    } >"$ac_tmp/config.h" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
-$as_echo "$as_me: $ac_file is unchanged" >&6;}
-    else
-      rm -f "$ac_file"
-      mv "$ac_tmp/config.h" "$ac_file" \
-	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    fi
-  else
-    $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
-      || as_fn_error $? "could not create -" "$LINENO" 5
-  fi
-# Compute "$ac_file"'s index in $config_headers.
-_am_arg="$ac_file"
-_am_stamp_count=1
-for _am_header in $config_headers :; do
-  case $_am_header in
-    $_am_arg | $_am_arg:* )
-      break ;;
-    * )
-      _am_stamp_count=`expr $_am_stamp_count + 1` ;;
-  esac
-done
-echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" ||
-$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$_am_arg" : 'X\(//\)[^/]' \| \
-	 X"$_am_arg" : 'X\(//\)$' \| \
-	 X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$_am_arg" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`/stamp-h$_am_stamp_count
- ;;
-
-  :C)  { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5
-$as_echo "$as_me: executing $ac_file commands" >&6;}
- ;;
-  esac
-
-
-  case $ac_file$ac_mode in
-    "depfiles":C) test x"$AMDEP_TRUE" != x"" || {
-  # Older Autoconf quotes --file arguments for eval, but not when files
-  # are listed without --file.  Let's play safe and only enable the eval
-  # if we detect the quoting.
-  case $CONFIG_FILES in
-  *\'*) eval set x "$CONFIG_FILES" ;;
-  *)   set x $CONFIG_FILES ;;
-  esac
-  shift
-  for mf
-  do
-    # Strip MF so we end up with the name of the file.
-    mf=`echo "$mf" | sed -e 's/:.*$//'`
-    # Check whether this is an Automake generated Makefile or not.
-    # We used to match only the files named 'Makefile.in', but
-    # some people rename them; so instead we look at the file content.
-    # Grep'ing the first line is not enough: some people post-process
-    # each Makefile.in and add a new line on top of each file to say so.
-    # Grep'ing the whole file is not good either: AIX grep has a line
-    # limit of 2048, but all sed's we know have understand at least 4000.
-    if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then
-      dirpart=`$as_dirname -- "$mf" ||
-$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$mf" : 'X\(//\)[^/]' \| \
-	 X"$mf" : 'X\(//\)$' \| \
-	 X"$mf" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$mf" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-    else
-      continue
-    fi
-    # Extract the definition of DEPDIR, am__include, and am__quote
-    # from the Makefile without running 'make'.
-    DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
-    test -z "$DEPDIR" && continue
-    am__include=`sed -n 's/^am__include = //p' < "$mf"`
-    test -z "$am__include" && continue
-    am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
-    # Find all dependency output files, they are included files with
-    # $(DEPDIR) in their names.  We invoke sed twice because it is the
-    # simplest approach to changing $(DEPDIR) to its actual value in the
-    # expansion.
-    for file in `sed -n "
-      s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
-	 sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do
-      # Make sure the directory exists.
-      test -f "$dirpart/$file" && continue
-      fdir=`$as_dirname -- "$file" ||
-$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$file" : 'X\(//\)[^/]' \| \
-	 X"$file" : 'X\(//\)$' \| \
-	 X"$file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-      as_dir=$dirpart/$fdir; as_fn_mkdir_p
-      # echo "creating $dirpart/$file"
-      echo '# dummy' > "$dirpart/$file"
-    done
-  done
-}
- ;;
-    "libtool":C)
-
-    # See if we are running on zsh, and set the options which allow our
-    # commands through without removal of \ escapes.
-    if test -n "${ZSH_VERSION+set}" ; then
-      setopt NO_GLOB_SUBST
-    fi
-
-    cfgfile="${ofile}T"
-    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
-    $RM "$cfgfile"
-
-    cat <<_LT_EOF >> "$cfgfile"
-#! $SHELL
-
-# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
-# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
-# NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-#   This file is part of GNU Libtool.
-#
-# GNU Libtool 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 2 of
-# the License, or (at your option) any later version.
-#
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
-#
-# GNU Libtool 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 GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
-# obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
-
-# The names of the tagged configurations supported by this script.
-available_tags="RC "
-
-# ### BEGIN LIBTOOL CONFIG
-
-# Which release of libtool.m4 was used?
-macro_version=$macro_version
-macro_revision=$macro_revision
-
-# Assembler program.
-AS=$lt_AS
-
-# DLL creation program.
-DLLTOOL=$lt_DLLTOOL
-
-# Object dumper program.
-OBJDUMP=$lt_OBJDUMP
-
-# Whether or not to build shared libraries.
-build_libtool_libs=$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=$enable_static
-
-# What type of objects to build.
-pic_mode=$pic_mode
-
-# Whether or not to optimize for fast installation.
-fast_install=$enable_fast_install
-
-# Shell to use when invoking shell scripts.
-SHELL=$lt_SHELL
-
-# An echo program that protects backslashes.
-ECHO=$lt_ECHO
-
-# The PATH separator for the build system.
-PATH_SEPARATOR=$lt_PATH_SEPARATOR
-
-# The host system.
-host_alias=$host_alias
-host=$host
-host_os=$host_os
-
-# The build system.
-build_alias=$build_alias
-build=$build
-build_os=$build_os
-
-# A sed program that does not truncate output.
-SED=$lt_SED
-
-# Sed that helps us avoid accidentally triggering echo(1) options like -n.
-Xsed="\$SED -e 1s/^X//"
-
-# A grep program that handles long lines.
-GREP=$lt_GREP
-
-# An ERE matcher.
-EGREP=$lt_EGREP
-
-# A literal string matcher.
-FGREP=$lt_FGREP
-
-# A BSD- or MS-compatible name lister.
-NM=$lt_NM
-
-# Whether we need soft or hard links.
-LN_S=$lt_LN_S
-
-# What is the maximum length of a command?
-max_cmd_len=$max_cmd_len
-
-# Object file suffix (normally "o").
-objext=$ac_objext
-
-# Executable file suffix (normally "").
-exeext=$exeext
-
-# whether the shell understands "unset".
-lt_unset=$lt_unset
-
-# turn spaces into newlines.
-SP2NL=$lt_lt_SP2NL
-
-# turn newlines into spaces.
-NL2SP=$lt_lt_NL2SP
-
-# convert \$build file names to \$host format.
-to_host_file_cmd=$lt_cv_to_host_file_cmd
-
-# convert \$build files to toolchain format.
-to_tool_file_cmd=$lt_cv_to_tool_file_cmd
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method = "file_magic".
-file_magic_cmd=$lt_file_magic_cmd
-
-# How to find potential files when deplibs_check_method = "file_magic".
-file_magic_glob=$lt_file_magic_glob
-
-# Find potential files using nocaseglob when deplibs_check_method = "file_magic".
-want_nocaseglob=$lt_want_nocaseglob
-
-# Command to associate shared and link libraries.
-sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd
-
-# The archiver.
-AR=$lt_AR
-
-# Flags to create an archive.
-AR_FLAGS=$lt_AR_FLAGS
-
-# How to feed a file listing to the archiver.
-archiver_list_spec=$lt_archiver_list_spec
-
-# A symbol stripping program.
-STRIP=$lt_STRIP
-
-# Commands used to install an old-style archive.
-RANLIB=$lt_RANLIB
-old_postinstall_cmds=$lt_old_postinstall_cmds
-old_postuninstall_cmds=$lt_old_postuninstall_cmds
-
-# Whether to use a lock for old archive extraction.
-lock_old_archive_extraction=$lock_old_archive_extraction
-
-# A C compiler.
-LTCC=$lt_CC
-
-# LTCC compiler flags.
-LTCFLAGS=$lt_CFLAGS
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration.
-global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair.
-global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address
-
-# Transform the output of nm in a C name address pair when lib prefix is needed.
-global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix
-
-# Specify filename containing input files for \$NM.
-nm_file_list_spec=$lt_nm_file_list_spec
-
-# The root where to search for dependent libraries,and in which our libraries should be installed.
-lt_sysroot=$lt_sysroot
-
-# The name of the directory that contains temporary libtool files.
-objdir=$objdir
-
-# Used to examine libraries when file_magic_cmd begins with "file".
-MAGIC_CMD=$MAGIC_CMD
-
-# Must we lock files when doing compilation?
-need_locks=$lt_need_locks
-
-# Manifest tool.
-MANIFEST_TOOL=$lt_MANIFEST_TOOL
-
-# Tool to manipulate archived DWARF debug symbol files on Mac OS X.
-DSYMUTIL=$lt_DSYMUTIL
-
-# Tool to change global to local symbols on Mac OS X.
-NMEDIT=$lt_NMEDIT
-
-# Tool to manipulate fat objects and archives on Mac OS X.
-LIPO=$lt_LIPO
-
-# ldd/readelf like tool for Mach-O binaries on Mac OS X.
-OTOOL=$lt_OTOOL
-
-# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4.
-OTOOL64=$lt_OTOOL64
-
-# Old archive suffix (normally "a").
-libext=$libext
-
-# Shared library suffix (normally ".so").
-shrext_cmds=$lt_shrext_cmds
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=$lt_extract_expsyms_cmds
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at link time.
-variables_saved_for_relink=$lt_variables_saved_for_relink
-
-# Do we need the "lib" prefix for modules?
-need_lib_prefix=$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=$need_version
-
-# Library versioning type.
-version_type=$version_type
-
-# Shared library runtime path variable.
-runpath_var=$runpath_var
-
-# Shared library path variable.
-shlibpath_var=$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=$shlibpath_overrides_runpath
-
-# Format of library name prefix.
-libname_spec=$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME
-library_names_spec=$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=$lt_soname_spec
-
-# Permission mode override for installation of shared libraries.
-install_override_mode=$lt_install_override_mode
-
-# Command to use after installation of a shared archive.
-postinstall_cmds=$lt_postinstall_cmds
-
-# Command to use after uninstallation of a shared archive.
-postuninstall_cmds=$lt_postuninstall_cmds
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=$lt_finish_cmds
-
-# As "finish_cmds", except a single script fragment to be evaled but
-# not shown.
-finish_eval=$lt_finish_eval
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=$hardcode_into_libs
-
-# Compile-time system search path for libraries.
-sys_lib_search_path_spec=$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries.
-sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec
-
-# Whether dlopen is supported.
-dlopen_support=$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=$enable_dlopen_self_static
-
-# Commands to strip libraries.
-old_striplib=$lt_old_striplib
-striplib=$lt_striplib
-
-
-# The linker used to build libraries.
-LD=$lt_LD
-
-# How to create reloadable object files.
-reload_flag=$lt_reload_flag
-reload_cmds=$lt_reload_cmds
-
-# Commands used to build an old-style archive.
-old_archive_cmds=$lt_old_archive_cmds
-
-# A language specific compiler.
-CC=$lt_compiler
-
-# Is the compiler the GNU compiler?
-with_gcc=$GCC
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag
-
-# Additional compiler flags for building library objects.
-pic_flag=$lt_lt_prog_compiler_pic
-
-# How to pass a linker flag through the compiler.
-wl=$lt_lt_prog_compiler_wl
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=$lt_lt_prog_compiler_static
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=$lt_lt_cv_prog_compiler_c_o
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=$archive_cmds_need_lc
-
-# Whether or not to disallow shared libs when runtime libs are static.
-allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=$lt_export_dynamic_flag_spec
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=$lt_whole_archive_flag_spec
-
-# Whether the compiler copes with passing no objects directly.
-compiler_needs_object=$lt_compiler_needs_object
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=$lt_old_archive_from_new_cmds
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds
-
-# Commands used to build a shared archive.
-archive_cmds=$lt_archive_cmds
-archive_expsym_cmds=$lt_archive_expsym_cmds
-
-# Commands used to build a loadable module if different from building
-# a shared archive.
-module_cmds=$lt_module_cmds
-module_expsym_cmds=$lt_module_expsym_cmds
-
-# Whether we are building with GNU ld or not.
-with_gnu_ld=$lt_with_gnu_ld
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=$lt_allow_undefined_flag
-
-# Flag that enforces no undefined symbols.
-no_undefined_flag=$lt_no_undefined_flag
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist
-hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec
-
-# Whether we need a single "-rpath" flag with a separated argument.
-hardcode_libdir_separator=$lt_hardcode_libdir_separator
-
-# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
-# DIR into the resulting binary.
-hardcode_direct=$hardcode_direct
-
-# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
-# DIR into the resulting binary and the resulting library dependency is
-# "absolute",i.e impossible to change by setting \${shlibpath_var} if the
-# library is relocated.
-hardcode_direct_absolute=$hardcode_direct_absolute
-
-# Set to "yes" if using the -LDIR flag during linking hardcodes DIR
-# into the resulting binary.
-hardcode_minus_L=$hardcode_minus_L
-
-# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
-# into the resulting binary.
-hardcode_shlibpath_var=$hardcode_shlibpath_var
-
-# Set to "yes" if building a shared library automatically hardcodes DIR
-# into the library and all subsequent libraries and executables linked
-# against it.
-hardcode_automatic=$hardcode_automatic
-
-# Set to yes if linker adds runtime paths of dependent libraries
-# to runtime path list.
-inherit_rpath=$inherit_rpath
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=$link_all_deplibs
-
-# Set to "yes" if exported symbols are required.
-always_export_symbols=$always_export_symbols
-
-# The commands to list exported symbols.
-export_symbols_cmds=$lt_export_symbols_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=$lt_exclude_expsyms
-
-# Symbols that must always be exported.
-include_expsyms=$lt_include_expsyms
-
-# Commands necessary for linking programs (against libraries) with templates.
-prelink_cmds=$lt_prelink_cmds
-
-# Commands necessary for finishing linking programs.
-postlink_cmds=$lt_postlink_cmds
-
-# Specify filename containing input files.
-file_list_spec=$lt_file_list_spec
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=$hardcode_action
-
-# ### END LIBTOOL CONFIG
-
-_LT_EOF
-
-  case $host_os in
-  aix3*)
-    cat <<\_LT_EOF >> "$cfgfile"
-# AIX sometimes has problems with the GCC collect2 program.  For some
-# reason, if we set the COLLECT_NAMES environment variable, the problems
-# vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" != Xset; then
-  COLLECT_NAMES=
-  export COLLECT_NAMES
-fi
-_LT_EOF
-    ;;
-  esac
-
-
-ltmain="$ac_aux_dir/ltmain.sh"
-
-
-  # We use sed instead of cat because bash on DJGPP gets confused if
-  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
-  # text mode, it properly converts lines to CR/LF.  This bash problem
-  # is reportedly fixed, but why not run on old versions too?
-  sed '$q' "$ltmain" >> "$cfgfile" \
-     || (rm -f "$cfgfile"; exit 1)
-
-  if test x"$xsi_shell" = xyes; then
-  sed -e '/^func_dirname ()$/,/^} # func_dirname /c\
-func_dirname ()\
-{\
-\    case ${1} in\
-\      */*) func_dirname_result="${1%/*}${2}" ;;\
-\      *  ) func_dirname_result="${3}" ;;\
-\    esac\
-} # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_basename ()$/,/^} # func_basename /c\
-func_basename ()\
-{\
-\    func_basename_result="${1##*/}"\
-} # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\
-func_dirname_and_basename ()\
-{\
-\    case ${1} in\
-\      */*) func_dirname_result="${1%/*}${2}" ;;\
-\      *  ) func_dirname_result="${3}" ;;\
-\    esac\
-\    func_basename_result="${1##*/}"\
-} # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_stripname ()$/,/^} # func_stripname /c\
-func_stripname ()\
-{\
-\    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\
-\    # positional parameters, so assign one to ordinary parameter first.\
-\    func_stripname_result=${3}\
-\    func_stripname_result=${func_stripname_result#"${1}"}\
-\    func_stripname_result=${func_stripname_result%"${2}"}\
-} # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\
-func_split_long_opt ()\
-{\
-\    func_split_long_opt_name=${1%%=*}\
-\    func_split_long_opt_arg=${1#*=}\
-} # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\
-func_split_short_opt ()\
-{\
-\    func_split_short_opt_arg=${1#??}\
-\    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\
-} # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\
-func_lo2o ()\
-{\
-\    case ${1} in\
-\      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\
-\      *)    func_lo2o_result=${1} ;;\
-\    esac\
-} # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_xform ()$/,/^} # func_xform /c\
-func_xform ()\
-{\
-    func_xform_result=${1%.*}.lo\
-} # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_arith ()$/,/^} # func_arith /c\
-func_arith ()\
-{\
-    func_arith_result=$(( $* ))\
-} # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_len ()$/,/^} # func_len /c\
-func_len ()\
-{\
-    func_len_result=${#1}\
-} # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-fi
-
-if test x"$lt_shell_append" = xyes; then
-  sed -e '/^func_append ()$/,/^} # func_append /c\
-func_append ()\
-{\
-    eval "${1}+=\\${2}"\
-} # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\
-func_append_quoted ()\
-{\
-\    func_quote_for_eval "${2}"\
-\    eval "${1}+=\\\\ \\$func_quote_for_eval_result"\
-} # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-
-
-  # Save a `func_append' function call where possible by direct use of '+='
-  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-else
-  # Save a `func_append' function call even when '+=' is not available
-  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-fi
-
-if test x"$_lt_function_replace_fail" = x":"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5
-$as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;}
-fi
-
-
-   mv -f "$cfgfile" "$ofile" ||
-    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
-  chmod +x "$ofile"
-
-
-    cat <<_LT_EOF >> "$ofile"
-
-# ### BEGIN LIBTOOL TAG CONFIG: RC
-
-# The linker used to build libraries.
-LD=$lt_LD_RC
-
-# How to create reloadable object files.
-reload_flag=$lt_reload_flag_RC
-reload_cmds=$lt_reload_cmds_RC
-
-# Commands used to build an old-style archive.
-old_archive_cmds=$lt_old_archive_cmds_RC
-
-# A language specific compiler.
-CC=$lt_compiler_RC
-
-# Is the compiler the GNU compiler?
-with_gcc=$GCC_RC
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_RC
-
-# Additional compiler flags for building library objects.
-pic_flag=$lt_lt_prog_compiler_pic_RC
-
-# How to pass a linker flag through the compiler.
-wl=$lt_lt_prog_compiler_wl_RC
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=$lt_lt_prog_compiler_static_RC
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=$lt_lt_cv_prog_compiler_c_o_RC
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=$archive_cmds_need_lc_RC
-
-# Whether or not to disallow shared libs when runtime libs are static.
-allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_RC
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_RC
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=$lt_whole_archive_flag_spec_RC
-
-# Whether the compiler copes with passing no objects directly.
-compiler_needs_object=$lt_compiler_needs_object_RC
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_RC
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_RC
-
-# Commands used to build a shared archive.
-archive_cmds=$lt_archive_cmds_RC
-archive_expsym_cmds=$lt_archive_expsym_cmds_RC
-
-# Commands used to build a loadable module if different from building
-# a shared archive.
-module_cmds=$lt_module_cmds_RC
-module_expsym_cmds=$lt_module_expsym_cmds_RC
-
-# Whether we are building with GNU ld or not.
-with_gnu_ld=$lt_with_gnu_ld_RC
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=$lt_allow_undefined_flag_RC
-
-# Flag that enforces no undefined symbols.
-no_undefined_flag=$lt_no_undefined_flag_RC
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist
-hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_RC
-
-# Whether we need a single "-rpath" flag with a separated argument.
-hardcode_libdir_separator=$lt_hardcode_libdir_separator_RC
-
-# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
-# DIR into the resulting binary.
-hardcode_direct=$hardcode_direct_RC
-
-# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
-# DIR into the resulting binary and the resulting library dependency is
-# "absolute",i.e impossible to change by setting \${shlibpath_var} if the
-# library is relocated.
-hardcode_direct_absolute=$hardcode_direct_absolute_RC
-
-# Set to "yes" if using the -LDIR flag during linking hardcodes DIR
-# into the resulting binary.
-hardcode_minus_L=$hardcode_minus_L_RC
-
-# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
-# into the resulting binary.
-hardcode_shlibpath_var=$hardcode_shlibpath_var_RC
-
-# Set to "yes" if building a shared library automatically hardcodes DIR
-# into the library and all subsequent libraries and executables linked
-# against it.
-hardcode_automatic=$hardcode_automatic_RC
-
-# Set to yes if linker adds runtime paths of dependent libraries
-# to runtime path list.
-inherit_rpath=$inherit_rpath_RC
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=$link_all_deplibs_RC
-
-# Set to "yes" if exported symbols are required.
-always_export_symbols=$always_export_symbols_RC
-
-# The commands to list exported symbols.
-export_symbols_cmds=$lt_export_symbols_cmds_RC
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=$lt_exclude_expsyms_RC
-
-# Symbols that must always be exported.
-include_expsyms=$lt_include_expsyms_RC
-
-# Commands necessary for linking programs (against libraries) with templates.
-prelink_cmds=$lt_prelink_cmds_RC
-
-# Commands necessary for finishing linking programs.
-postlink_cmds=$lt_postlink_cmds_RC
-
-# Specify filename containing input files.
-file_list_spec=$lt_file_list_spec_RC
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=$hardcode_action_RC
-
-# ### END LIBTOOL TAG CONFIG: RC
-_LT_EOF
-
- ;;
-
-  esac
-done # for ac_tag
-
-
-as_fn_exit 0
-_ACEOF
-ac_clean_files=$ac_clean_files_save
-
-test $ac_write_fail = 0 ||
-  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded.  So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status.  When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
-  ac_cs_success=:
-  ac_config_status_args=
-  test "$silent" = yes &&
-    ac_config_status_args="$ac_config_status_args --quiet"
-  exec 5>/dev/null
-  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
-  exec 5>>config.log
-  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
-  # would make configure fail if this is the last instruction.
-  $ac_cs_success || as_fn_exit 1
-fi
-if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
-fi
-
-
-# Finally: summary
-if test "x$enable_curl" != "xyes"; then
- MSG_CURL="no, many unit tests will not run"
-else
- MSG_CURL="yes"
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: Configuration Summary:
-  Operating System:  ${host_os}
-  Threading lib:     ${USE_THREADS}
-  libcurl (testing): ${MSG_CURL}
-  Target directory:  ${prefix}
-  Messages:          ${enable_messages}
-  Basic auth.:       ${enable_bauth}
-  Digest auth.:      ${enable_dauth}
-  Postproc:          ${enable_postprocessor}
-  HTTPS support:     ${MSG_HTTPS}
-  poll support:      ${enable_poll=no}
-  epoll support:     ${enable_epoll=no}
-  build docs:        ${enable_doc}
-  build examples:    ${enable_examples}
-  libmicrospdy:      ${enable_spdy}
-  spdylay (testing): ${have_spdylay}
-" >&5
-$as_echo "$as_me: Configuration Summary:
-  Operating System:  ${host_os}
-  Threading lib:     ${USE_THREADS}
-  libcurl (testing): ${MSG_CURL}
-  Target directory:  ${prefix}
-  Messages:          ${enable_messages}
-  Basic auth.:       ${enable_bauth}
-  Digest auth.:      ${enable_dauth}
-  Postproc:          ${enable_postprocessor}
-  HTTPS support:     ${MSG_HTTPS}
-  poll support:      ${enable_poll=no}
-  epoll support:     ${enable_epoll=no}
-  build docs:        ${enable_doc}
-  build examples:    ${enable_examples}
-  libmicrospdy:      ${enable_spdy}
-  spdylay (testing): ${have_spdylay}
-" >&6;}
-
-if test "x$enable_https" = "xyes"
-then
- { $as_echo "$as_me:${as_lineno-$LINENO}: HTTPS subsystem configuration:
-  License         :  LGPL only
- " >&5
-$as_echo "$as_me: HTTPS subsystem configuration:
-  License         :  LGPL only
- " >&6;}
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}:
-  License         :  LGPL or eCos
-" >&5
-$as_echo "$as_me:
-  License         :  LGPL or eCos
-" >&6;}
-fi
-
-if test "x$enable_bauth" != "xyes" -o \
-        "x$enable_dauth" != "xyes" -o \
-        "x$enable_postprocessor" != "xyes"
-then
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: This will be a custom build with missing symbols. Do NOT use this build in a distribution. Building with these kinds of configure options is only for custom builds for embedded systems." >&5
-$as_echo "$as_me: WARNING: This will be a custom build with missing symbols. Do NOT use this build in a distribution. Building with these kinds of configure options is only for custom builds for embedded systems." >&6;}
-fi
diff --git a/configure.ac b/configure.ac
index 3f7fb8f..44ac85c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,5 +1,6 @@
 # This file is part of libmicrohttpd.
-# (C) 2006-2015 Christian Grothoff (and other contributing authors)
+# (C) 2006-2021 Christian Grothoff (and other contributing authors)
+# (C) 2014-2023 Evgeny Grin (Karlson2k)
 #
 # libmicrohttpd is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published
@@ -13,249 +14,1717 @@
 #
 # You should have received a copy of the GNU General Public License
 # along with libmicrohttpd; see the file COPYING.  If not, write to the
-# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-# Boston, MA 02111-1307, USA.
+# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
 #
 #
 # Process this file with autoconf to produce a configure script.
 #
 #
-AC_PREREQ([2.60])
+AC_PREREQ([2.64])
 LT_PREREQ([2.4.0])
-AC_INIT([libmicrohttpd],[0.9.42],[libmicrohttpd@gnu.org])
-AM_INIT_AUTOMAKE([silent-rules] [subdir-objects])
+AC_INIT([GNU libmicrohttpd],[0.9.76],[libmicrohttpd@gnu.org])
+AC_CONFIG_AUX_DIR([build-aux])
+MHD_AUX_DIR='build-aux' # Must be set to the same value as in the previous line
 AC_CONFIG_HEADERS([MHD_config.h])
 AC_CONFIG_MACRO_DIR([m4])
-AH_TOP([#define _GNU_SOURCE  1])
+m4_pattern_forbid([^_?MHD_[A-Z_]+_CC_])dnl
 
-LIB_VERSION_CURRENT=42
+LIB_VERSION_CURRENT=73
 LIB_VERSION_REVISION=0
-LIB_VERSION_AGE=32
-AC_SUBST(LIB_VERSION_CURRENT)
-AC_SUBST(LIB_VERSION_REVISION)
-AC_SUBST(LIB_VERSION_AGE)
-
-LIBSPDY_VERSION_CURRENT=0
-LIBSPDY_VERSION_REVISION=0
-LIBSPDY_VERSION_AGE=0
-AC_SUBST(LIBSPDY_VERSION_CURRENT)
-AC_SUBST(LIBSPDY_VERSION_REVISION)
-AC_SUBST(LIBSPDY_VERSION_AGE)
+LIB_VERSION_AGE=61
+AC_SUBST([LIB_VERSION_CURRENT])
+AC_SUBST([LIB_VERSION_REVISION])
+AC_SUBST([LIB_VERSION_AGE])
 
 
-if test `uname -s` = "OS/390"
-then
-# configure binaries for z/OS
-  if test -z "$CC"
-  then
-    CC=`pwd`"/contrib/xcc"
-    chmod +x $CC || true
-  fi
-  if test -z "$CPP"
-  then
-    CPP="c89 -E"
-  fi
-  if test -z "$CXXCPP"
-  then
-    CXXCPP="c++ -E -+"
-  fi
-#  _CCC_CCMODE=1
-#  _C89_CCMODE=1
-fi
-
-# Checks for programs.
-AC_PROG_AWK
-AC_PROG_INSTALL
-AC_PROG_LN_S
-AC_PROG_MAKE_SET
-AC_CANONICAL_HOST
-AM_PROG_CC_C_O
-LT_INIT([win32-dll])
-LT_LANG([Windows Resource])
-
-PACKAGE_VERSION_MAJOR=${PACKAGE_VERSION%.*.*}
-PACKAGE_VERSION_MINOR=${PACKAGE_VERSION%.*}; PACKAGE_VERSION_MINOR=${PACKAGE_VERSION_MINOR#*.}
-PACKAGE_VERSION_SUBMINOR=${PACKAGE_VERSION#*.*.}
+PACKAGE_VERSION_MAJOR='m4_car(m4_unquote(m4_split(AC_PACKAGE_VERSION, [\.])))'
+PACKAGE_VERSION_MINOR='m4_argn(2, m4_unquote(m4_split(AC_PACKAGE_VERSION, [\.])))'
+PACKAGE_VERSION_SUBMINOR='m4_argn(3, m4_unquote(m4_split(AC_PACKAGE_VERSION, [\.])))'
+AS_VAR_ARITH([MHD_W32_DLL_SUFF],[[$LIB_VERSION_CURRENT - $LIB_VERSION_AGE]])
 AC_SUBST([PACKAGE_VERSION_MAJOR])
 AC_SUBST([PACKAGE_VERSION_MINOR])
 AC_SUBST([PACKAGE_VERSION_SUBMINOR])
+AC_SUBST([MHD_W32_DLL_SUFF])
 AC_CONFIG_FILES([src/microhttpd/microhttpd_dll_res.rc])
 
 MHD_LIB_CPPFLAGS=""
 MHD_LIB_CFLAGS=""
 MHD_LIB_LDFLAGS=""
 MHD_LIBDEPS=""
+# for pkg-config
+MHD_REQ_PRIVATE=''
+MHD_LIBDEPS_PKGCFG=''
 
-AC_ARG_WITH([threads],
-   [AC_HELP_STRING([--with-threads=LIB],[choose threading library (posix, w32, auto) [auto]])],
-   [], [with_threads='auto'])
-test "x$with_threads" = "xwin32" && with_threads='w32'
-test "x$with_threads" = "xpthreads" && with_threads='posix'
+AS_IF([test -z "$CC" && test -z "$CPP"], [
+  AC_MSG_CHECKING([[whether z/OS special settings are required]])
+  AS_IF([test `uname -s` = "OS/390"],
+    [
+      # configure binaries for z/OS
+      AS_IF([test -z "$CC"],
+            [CC=`pwd`"/contrib/xcc"
+             chmod +x $CC || true])
+      AS_IF([test -z "$CPP"],
+            CPP="c89 -E")
+      AC_MSG_RESULT([[yes]])
+    ],
+    [AC_MSG_RESULT([[no]])]
+  )
+])
 
-# Check for posix threads support
-AX_PTHREAD([HAVE_POSIX_THREADS='yes'],[HAVE_POSIX_THREADS='no'])
-AM_CONDITIONAL([HAVE_POSIX_THREADS],[test "x$HAVE_POSIX_THREADS" = "xyes"])
-# Simple check for W32 threads support
-AC_CHECK_HEADER([windows.h],
+
+AC_MSG_CHECKING([for build type])
+AC_ARG_ENABLE([build-type],
+  [AS_HELP_STRING([[--enable-build-type=TYPE]],
+  [enable build TYPE, a set of configuration parameters; individual settings ]
+  [(asserts, sanitizers, compiler and linker flags) can be overridden by ]
+  [additional configure parameters (debug, debugger, neutral, release, release-compact, ]
+  [release-hardened) [neutral]])],
+  [], [enable_build_type=neutral])
+AS_IF([test "x${enable_build_type}" = "x"], [enable_build_type="neutral"])
+AS_VAR_IF([enable_build_type], ["no"], [enable_build_type="neutral"])
+AS_VAR_IF([enable_build_type], ["yes"], [AC_MSG_ERROR([[Missing TYPE for --enable-build-type=]])])
+AS_CASE([${enable_build_type}],
+  [debug], [AC_MSG_RESULT([debug. Defaults: enable asserts, sanitizers (if any supported), debug information, compiler optimisation for debugging])],
+  [debugger], [AC_MSG_RESULT([debugger. Defaults: enable asserts, disable sanitizers, debug information, no compiler optimisation, static lib])],
+  [neutral], [AC_MSG_RESULT([neutral. Defaults: use only user-specified compiler and linker flags])],
+  [release], [AC_MSG_RESULT([release. Defaults: disable asserts, enable compiler optimisations])],
+  [release-compact], [AC_MSG_RESULT([release-compact. Defaults: disable asserts, enable compiler optimisations for size, enable compact code])],
+  [release-hardened], [AC_MSG_RESULT([release-hardened. Defaults: disable asserts, enable compiler optimisations, enable linker and compiler hardening])],
+  [AC_MSG_ERROR([[Unknown build type: ${enable_build_type}]])]
+)
+AS_VAR_IF([enable_build_type], ["neutral"], [:],
   [
-    AC_MSG_CHECKING([for CreateThread()])
-    AC_LINK_IFELSE(
-      [AC_LANG_PROGRAM([#include <windows.h>], [ HANDLE h = CreateThread(NULL, 0, NULL, NULL, 0, NULL);])],
+    # For all non-neutral build types do not use automatic "-g -O2" for CFLAGS
+    AS_IF([test -z "${CFLAGS}"], [CFLAGS=""])
+  ]
+)
+AS_VAR_IF([enable_build_type], ["debugger"],
+  [ # Build only static version unless something else is specified by the user
+    AS_IF([test -z "${enable_static}" || test "x${enable_static}" = "xyes"],
       [
-        AC_MSG_RESULT([yes])
-        HAVE_W32_THREADS='yes'
+        AS_IF([test -z "${enable_shared}"],
+          [
+            enable_shared="no"
+            enable_static="yes"
+          ]
+        )
       ],
       [
-        AC_MSG_RESULT([no])
-        HAVE_W32_THREADS='no'
-      ])
-  ],
-  [HAVE_W32_THREADS='no'])
+        AS_CASE([${enable_static}],[*libmicrohttpd*],
+          [AS_IF([test -z "${enable_shared}"], [enable_shared="no"])],
+        )
+      ]
+    )
+  ]
+)
+AS_CASE([${enable_build_type}],[debug|debugger],
+  [ AS_IF([test -z "${enable_silent_rules}"], [ enable_silent_rules="yes" ])]
+)
 
-# for pkg-config
-MHD_LIBDEPS=""
-MHD_REQ_PRIVATE=''
+AM_INIT_AUTOMAKE([gnu] [check-news] [filename-length-max=99] [tar-v7] [silent-rules] [subdir-objects])
+
+# Checks for programs.
+AC_PROG_AWK
+AC_PROG_GREP
+AC_PROG_FGREP
+AC_PROG_INSTALL
+AC_PROG_LN_S
+AC_PROG_MAKE_SET
+AC_CANONICAL_HOST
+m4_version_prereq([2.70],
+  [
+# Find C compiler and compiler options to support
+# the latest C standard (C11). Fallback to C99 and C89
+# if later C versions are not supported.
+AC_PROG_CC
+  ],
+  [
+# Find C compiler and compiler options to support
+# the latest C standard (C99). Fallback to C89
+# if later C versions are not supported.
+AC_PROG_CC_STDC
+  ]
+)
+
+# Workaround for libgcrypt
+AS_IF([[test "x$lt_sysroot" != "x" && test "x$SYSROOT" = "x"]], [[SYSROOT="$lt_sysroot"]])
+user_CFLAGS="$CFLAGS"
+user_LDFLAGS="$LDFLAGS"
+user_CPPFLAGS="$CPPFLAGS"
+
+CFLAGS_ac=""
+LDFLAGS_ac=""
+CPPFLAGS_ac=""
+
+MHD_SYS_EXT([CPPFLAGS_ac])
+CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+LT_INIT([win32-dll])
+LT_LANG([Windows Resource])
+
+AC_ARG_ENABLE([compact-code],
+  [AS_HELP_STRING([[--enable-compact-code]],
+  [enable use of a reduced size version of the code, resulting in smaller ]
+  [binaries with a slight performance hit [auto]])],
+  [], [enable_compact_code=auto])
+AS_IF([test "x${enable_compact_code}" = "x"], [enable_compact_code="auto"])
+AH_TEMPLATE([[MHD_FAVOR_SMALL_CODE]], [Define to '1' to use compact code version])
+AH_TEMPLATE([[MHD_FAVOR_FAST_CODE]], [Define to '1' to use fast (and larger) code version])
+AS_UNSET([compact_code_MSG])
+AS_CASE([${enable_compact_code}], [auto],
+  [
+    # Parameter not set.
+    # Check preprocessor macros
+    AC_CHECK_DECL([MHD_FAVOR_SMALL_CODE],
+      [
+        enable_compact_code="yes"
+        compact_code_MSG="enabled by preprocessor macro"
+      ],
+      [],[/* no includes */]
+    )
+    AC_CHECK_DECL([MHD_FAVOR_FAST_CODE],
+      [
+        AS_VAR_IF([enable_compact_code],["yes"],
+          [AC_MSG_ERROR([Both MHD_FAVOR_SMALL_CODE and MHD_FAVOR_FAST_CODE macros are defined])]
+        )
+        enable_compact_code="no"
+        compact_code_MSG="set by preprocessor macro"
+      ],[],[/* no includes */]
+    )
+
+    AS_VAR_IF([enable_compact_code], ["auto"],
+      [
+        # No preference by preprocessor macros
+        AC_CACHE_CHECK([whether compiler is configured to optimize for size],
+          [mhd_cv_cc_optim_size],
+          [
+            AC_COMPILE_IFELSE(
+              [
+                AC_LANG_PROGRAM([[
+#ifndef __OPTIMIZE_SIZE__
+#error Looks like compiler does not optimize for size
+choke me now
+#endif
+              ]],[])
+              ],
+              [mhd_cv_cc_optim_size="yes"],[mhd_cv_cc_optim_size="no"]
+            )
+          ]
+        )
+        AS_VAR_IF([mhd_cv_cc_optim_size], ["yes"],
+          [
+            enable_compact_code="yes"
+            compact_code_MSG="enabled automatically as compiler optimizes for size"
+            AC_DEFINE([MHD_FAVOR_SMALL_CODE],[1])
+          ]
+        )
+      ]
+    )
+
+    AS_VAR_IF([enable_compact_code], ["auto"],
+      [
+        # No preference by preprocessor macros and compiler flags
+        AS_CASE([${enable_build_type}],[*-compact],
+          [
+            enable_compact_code="yes"
+            compact_code_MSG="enabled by --enable-build-type=${enable_build_type}"
+            AC_DEFINE([MHD_FAVOR_SMALL_CODE],[1])
+          ]
+        )
+      ]
+    )
+
+    AS_VAR_IF([enable_compact_code], ["auto"],
+      [
+        # No preference
+        enable_compact_code="no"
+        compact_code_MSG="by default"
+        AC_DEFINE([MHD_FAVOR_FAST_CODE],[1])
+      ]
+    )
+  ],
+  [yes],
+  [
+    compact_code_MSG="enabled by configure parameter"
+    AC_CHECK_DECL([MHD_FAVOR_SMALL_CODE],
+      [],
+      [AC_DEFINE([MHD_FAVOR_SMALL_CODE],[1])],[/* no includes */]
+    )
+    AC_CHECK_DECL([MHD_FAVOR_FAST_CODE],
+      [AC_MSG_ERROR([MHD_FAVOR_FAST_CODE macro is defined, --enable-compact-code could not be used])
+      ],
+      [],[/* no includes */]
+    )
+  ],
+  [no],
+  [
+    compact_code_MSG="disabled by configure parameter"
+    AC_CHECK_DECL([MHD_FAVOR_FAST_CODE],
+      [],
+      [AC_DEFINE([MHD_FAVOR_FAST_CODE],[1])],[/* no includes */]
+    )
+    AC_CHECK_DECL([MHD_FAVOR_SMALL_CODE],
+      [AC_MSG_ERROR([MHD_FAVOR_SMALL_CODE macro is defined, --disable-compact-code could not be used])
+      ],
+      [],[/* no includes */]
+    )
+  ],
+  [AC_MSG_ERROR([[Unknown parameter value: --enable-compact-code=${enable_compact_code}]])]
+)
+
+AC_MSG_CHECKING([whether to use a reduced size version of the code])
+AC_MSG_RESULT([${enable_compact_code} (${compact_code_MSG})])
+
+
+CFLAGS="${user_CFLAGS}"
+# Compiler options to always enable (if supported)
+MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-fno-strict-aliasing], [-qnoansialias])
+# '-qlonglong' is XLC option for C89, not used with C99 or later
+MHD_CHECK_ADD_CC_CFLAG([-qlonglong], [CFLAGS_ac])
+
+# Set basic optimisation flags
+AS_VAR_IF([enable_build_type],["neutral"],[],
+  [ # Any non-neutral build types
+    AC_CACHE_CHECK([whether workarounds for clang or clang-based compiler are required],
+      [mhd_cv_cc_clang_based],
+      [
+        AC_COMPILE_IFELSE([AC_LANG_SOURCE([[
+#if ! defined(__clang__) && ! defined(__llvm__)
+#error Compiler is not clang-based
+choke me now
+#endif
+              ]]
+            )
+          ],
+          [mhd_cv_cc_clang_based="yes"],[mhd_cv_cc_clang_based="no"]
+        )
+      ]
+    )
+  ]
+)
+AS_CASE([${enable_build_type}],[debug|debugger],
+  [ # Debug build or build for walking with debugger
+    CFLAGS="${user_CFLAGS}"
+    AS_VAR_IF([enable_build_type],["debug"],
+      [
+        # Clang has ASAN (pointer compare) broken when '-Og' optimisations are used
+        AS_IF([test "x${enable_sanitizers}" != "xno" && test "x${mhd_cv_cc_clang_based}" = "xyes"],
+          [MHD_CHECK_ADD_CC_CFLAG([-O0], [CFLAGS_ac])],
+          [MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-Og], [-O0])]
+        )
+      ],
+      [MHD_CHECK_ADD_CC_CFLAG([-O0], [CFLAGS_ac])]
+    )
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+  ]
+)
+AS_CASE([${enable_build_type}],[release|release-*],
+  [ # All release types
+    AS_VAR_IF([enable_build_type],["release-compact"],
+      [
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+        AC_CHECK_DECL([MHD_FAVOR_SMALL_CODE],[],
+          [AC_CHECK_DECL([MHD_FAVOR_FAST_CODE],[],
+            [MHD_APPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-DMHD_FAVOR_SMALL_CODE=1])],
+            [/* no includes */])],[/* no includes */])
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+        CFLAGS="${user_CFLAGS}"
+        MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-Oz], [-Os], [-O])
+	    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+      ],
+      [ # All non-compact release types
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+        AC_CHECK_DECL([MHD_FAVOR_SMALL_CODE],[],
+          [AC_CHECK_DECL([MHD_FAVOR_FAST_CODE],[],
+            [MHD_APPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-DMHD_FAVOR_FAST_CODE=1])],
+            [/* no includes */])],[/* no includes */])
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+        CFLAGS="${user_CFLAGS}"
+        MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-O2], [-O])
+	    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+      ]
+    )
+  ]
+)
+
+AS_VAR_IF([enable_build_type],["neutral"],[],
+  [ # Any non-neutral build types
+    MHD_CHECK_ADD_CC_CFLAGS([-Wall -Wnull-dereference], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wdeclaration-after-statement -Wimplicit -Wnested-externs], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wredundant-decls -Wtrampolines -Wunsafe-loop-optimizations], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wpoison-system-directories], [CFLAGS_ac])
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    LDFLAGS="${user_LDFLAGS}"
+    MHD_CHECK_ADD_CC_LDFLAG([-Wl,--warn-common], [LDFLAGS_ac])
+    LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+  ]
+)
+AS_CASE([${enable_build_type}],[debug|debugger],
+  [ # Debug build or build for walking with debugger
+    CFLAGS="${user_CFLAGS}"
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-ggdb3], [-g3], [-ggdb], [-g])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wextra -Wdouble-promotion], [CFLAGS_ac])
+    MHD_FIND_ADD_CC_CFLAG_IFELSE(
+      [
+        # clang produce warning when string pointer is used as a format specifier for v*printf() function
+        AS_VAR_IF([mhd_cv_cc_clang_based],["yes"],[MHD_CHECK_ADD_CC_CFLAG([-Wno-format-nonliteral], [CFLAGS_ac])])
+      ],[],
+      [CFLAGS_ac], [-Wformat=2], [-Wformat]
+    )
+    MHD_CHECK_ADD_CC_CFLAGS([-Wformat-overflow -Wformat-truncation -Wformat-security -Wformat-signedness], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wmissing-include-dirs -Wshift-overflow=2 -Wstringop-overflow=4 -Walloc-zero], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wduplicated-branches -Wduplicated-cond -Wfloat-equal -Wshadow -Wpointer-arith], [CFLAGS_ac])
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-Wshadow-all], [-Wshadow])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wbad-function-cast -Wcast-qual -Wwrite-strings -Wconversion], [CFLAGS_ac])
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-Wcast-align=strict], [-Wcast-align])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wjump-misses-init -Wlogical-op -Waggregate-return -Wstrict-prototypes], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wold-style-definition -Wmissing-declarations -Wmissing-prototypes], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wuninitialized -Winit-self -Wshift-negative-value -Wswitch-enum], [CFLAGS_ac])
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-Wstrict-overflow=4], [-Wstrict-overflow])
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac], [-Wnormalized=nfkc], [-Wnormalized])
+    MHD_CHECK_ADD_CC_CFLAGS([-Walloca -Wbidi-chars=any -Warray-bounds -Wpacked -Wvariadic-macros], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wundef], [CFLAGS_ac])
+
+    MHD_CHECK_ADD_CC_CFLAGS([-Wanon-enum-enum-conversion -Warray-bounds-pointer-arithmetic -Wassign-enum], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wbit-int-extension -Wbitfield-enum-conversion -Wparentheses -Wbool-operation], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wcast-function-type -Wcomma -Wcomment -Wcompound-token-split], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wconditional-uninitialized -Wdeprecated], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wdocumentation-pedantic -Wempty-init-stmt -Wenum-conversion -Wexpansion-to-defined], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wflexible-array-extensions -Wloop-analysis -Wformat-pedantic], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wformat-type-confusion -Wfour-char-constants], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wgcc-compat -Wgnu-anonymous-struct -Wgnu-compound-literal-initializer], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wgnu-conditional-omitted-operand -Wgnu-designator -Wgnu-empty-initializer], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wgnu-empty-struct -Wgnu-flexible-array-initializer -Wgnu-folding-constant], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wgnu-null-pointer-arithmetic -Wgnu-pointer-arith -Wgnu-redeclared-enum], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wgnu-union-cast -Wgnu-variable-sized-type-not-at-end -Widiomatic-parentheses], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wmissing-noreturn -Wmissing-variable-declarations -Wnested-anon-types], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wnewline-eof -Wover-aligned -Wredundant-parens], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wshift-sign-overflow -Wtautological-compare -Wunaligned-access], [CFLAGS_ac])
+    MHD_CHECK_ADD_CC_CFLAGS([-Wunused -Wzero-as-null-pointer-constant -Wzero-length-array], [CFLAGS_ac])
+    MHD_CHECK_CC_CFLAG([-Wused-but-marked-unused],[CFLAGS_ac],
+      [
+        AC_CACHE_CHECK([whether $[]CC -Wused-but-marked-unused works with system headers],
+          [mhd_cv_wused_but_marked_unused_sys_header],
+          [
+            SAVE_ac_c_werror_flag="$ac_c_werror_flag"
+            ac_c_werror_flag="yes"
+            CFLAGS="${CFLAGS_ac} -Wused-but-marked-unused ${user_CFLAGS}"
+            AC_COMPILE_IFELSE(
+              [
+                AC_LANG_SOURCE([[
+#include <stdio.h>
+
+int main(void)
+{
+  char buf[16];
+  return (int) snprintf(buf, 16, "test");
+}
+                  ]]
+                )
+              ],
+              [mhd_cv_wused_but_marked_unused_sys_header="yes"],
+              [mhd_cv_wused_but_marked_unused_sys_header="no"]
+            )
+            ac_c_werror_flag="$SAVE_ac_c_werror_flag"
+          ]
+        )
+        AS_VAR_IF([mhd_cv_wused_but_marked_unused_sys_header],["yes"],
+          [MHD_APPEND_FLAG_TO_VAR([CFLAGS_ac],[-Wused-but-marked-unused])]
+        )
+      ]
+    )
+    #
+    # Removed flags:
+    #
+    # -Wdisabled-macro-expansion - warns about macros from system headers
+
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    LDFLAGS="${user_LDFLAGS}"
+    MHD_CHECK_ADD_CC_LDFLAG([-Wl,--enable-long-section-names], [LDFLAGS_ac])
+    LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+  ]
+)
+AS_CASE([${enable_build_type}],[release|release-*],
+  [ # All release types
+    CFLAGS="${user_CFLAGS}"
+    AS_VAR_IF([enable_build_type],["release-compact"],
+      [],
+      [ # All non-compact release types
+        MHD_CHECK_ADD_CC_CFLAGS([-fsched-pressure -fira-loop-pressure -fmerge-all-constants], [CFLAGS_ac]) # These flags may improve size, recheck with LTO and linker garbage collection
+        MHD_CHECK_ADD_CC_CFLAGS([-ftree-partial-pre -fgcse-after-reload -fipa-pta], [CFLAGS_ac])
+        MHD_CHECK_ADD_CC_CFLAGS([-fisolate-erroneous-paths-attribute -ffinite-loops -floop-nest-optimize], [CFLAGS_ac])
+        MHD_CHECK_ADD_CC_CFLAGS([-fpredictive-commoning -frename-registers], [CFLAGS_ac])
+        MHD_CHECK_ADD_CC_CFLAGS([-ftree-loop-distribute-patterns -fpeel-loops -fsplit-loops -ftree-vectorize], [CFLAGS_ac])
+      ]
+    )
+
+    AS_VAR_IF([enable_build_type],["release-hardened"],
+      [
+        MHD_CHECK_ADD_CC_CFLAGS([-Wformat-security -Wstack-protector], [CFLAGS_ac])
+        MHD_CHECK_ADD_CC_CFLAGS([-Wuninitialized -Winit-self -Walloc-zero -Wbidi-chars=any], [CFLAGS_ac])
+      ]
+    )
+    AS_VAR_IF([enable_build_type],["release"],
+      [ # Flags are not suitable for 'compact' and for 'hardened'
+        MHD_CHECK_ADD_CC_CFLAGS([-ffast-math -fno-trapping-math], [CFLAGS_ac])
+      ]
+    )
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    # W32-specific
+    LDFLAGS="${user_LDFLAGS}"
+    MHD_CHECK_ADD_CC_LDFLAG([-Wl,--disable-long-section-names], [LDFLAGS_ac])
+    LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+  ]
+)
+CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+# Additional flags are checked and added at the end of 'configure'
+
+# Check for headers that are ALWAYS required
+AC_CHECK_HEADERS_ONCE([stdio.h string.h stdint.h errno.h limits.h fcntl.h], [],
+  [AC_MSG_ERROR([Compiling libmicrohttpd requires standard POSIX headers files])], [AC_INCLUDES_DEFAULT])
+
+# Check for basic optional headers
+AC_CHECK_HEADERS([stddef.h stdlib.h inttypes.h sys/types.h sys/stat.h unistd.h \
+                  sys/uio.h], [], [], [AC_INCLUDES_DEFAULT])
+
+# Check for clock-specific optional headers
+AC_CHECK_HEADERS([sys/time.h time.h], [], [], [AC_INCLUDES_DEFAULT])
+
+# Check for system information and parameters optional headers
+AC_CHECK_HEADERS([endian.h machine/endian.h sys/endian.h sys/byteorder.h \
+                  sys/machine.h machine/param.h sys/param.h sys/isa_defs.h \
+                  sys/ioctl.h], [], [], [AC_INCLUDES_DEFAULT])
+
+# Check for network and sockets optional headers
+AC_CHECK_HEADERS([sys/socket.h sys/select.h netinet/in_systm.h netinet/in.h \
+                  arpa/inet.h netinet/ip.h netinet/tcp.h net/if.h \
+                  netdb.h sockLib.h inetLib.h], [], [],
+  [AC_INCLUDES_DEFAULT
+   [
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif /* HAVE_INTTYPES_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+#ifdef HAVE_NETINET_IN_SYSTM_H
+#include <netinet/in_systm.h>
+#endif /* HAVE_NETINET_IN_SYSTM_H */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif /* HAVE_NETINET_IN_H */
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+#ifdef HAVE_NETINET_TCP_H
+#include <netinet/tcp.h>
+#endif /* HAVE_NETINET_TCP_H */
+  ]]
+)
+
+# Check for other optional headers
+AC_CHECK_HEADERS([sys/msg.h sys/mman.h signal.h], [], [], [AC_INCLUDES_DEFAULT])
+
+AC_CHECK_HEADER([[search.h]],
+  [
+    MHD_CHECK_LINK_RUN([[for proper tsearch(), tfind() and tdelete()]],[[mhd_cv_sys_tsearch_usable]],
+	  [
+	    AS_CASE([$host_os],
+	      [openbsd*],
+	      [[ # Some OpenBSD versions have wrong return value for tdelete()
+	        mhd_cv_sys_tsearch_usable='assuming no'
+	      ]],
+	      [netbsd*],
+	      [[ # NetBSD had leaked root node for years
+	        mhd_cv_sys_tsearch_usable='assuming no'
+	      ]],
+	      [[mhd_cv_sys_tsearch_usable='assuming yes']]
+	    )
+	  ],
+	  [
+	    AC_LANG_SOURCE(
+	      [[
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif /* HAVE_STDDEF_H */
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+
+#include <stdio.h>
+#include <search.h>
+
+static int cmp_func(const void *p1, const void *p2)
+{
+  return (*((const int *)p1)) - (*((const int *)p2));
+}
+
+int main(void)
+{
+  int ret = 0;
+  void *root_ptr = NULL;
+  int element1 = 1;
+  int **element_ptr_ptr1;
+  int **element_ptr_ptr2;
+
+  element_ptr_ptr1 =
+    (int **) tsearch ((void*) &element1, &root_ptr, &cmp_func);
+  if (NULL == element_ptr_ptr1)
+  {
+    fprintf (stderr, "NULL pointer has been returned when tsearch() called for the first time.\n");
+    return ++ret;
+  }
+  if (*element_ptr_ptr1 != &element1)
+  {
+    fprintf (stderr, "Wrong pointer has been returned when tsearch() called for the first time.\n");
+    return ++ret;
+  }
+  if (NULL == root_ptr)
+  {
+    fprintf (stderr, "Root pointer has not been set by tsearch().\n");
+    return ++ret;
+  }
+
+  element_ptr_ptr2 =
+    (int **) tsearch ((void*) &element1, &root_ptr, &cmp_func);
+  if (NULL == element_ptr_ptr2)
+  {
+    fprintf (stderr, "NULL pointer has been returned when tsearch() called for the second time.\n");
+    return ++ret;
+  }
+  if (*element_ptr_ptr2 != &element1)
+  {
+    fprintf (stderr, "Wrong pointer has been returned when tsearch() called for the second time.\n");
+    ++ret;
+  }
+  if (element_ptr_ptr2 != element_ptr_ptr1)
+  {
+    fprintf (stderr, "Wrong element has been returned when tsearch() called for the second time.\n");
+    ++ret;
+  }
+
+  element_ptr_ptr2 =
+    (int **) tfind ((void*) &element1, &root_ptr, &cmp_func);
+  if (NULL == element_ptr_ptr2)
+  {
+    fprintf (stderr, "NULL pointer has been returned by tfind().\n");
+    ++ret;
+  }
+  if (*element_ptr_ptr2 != &element1)
+  {
+    fprintf (stderr, "Wrong pointer has been returned when by tfind().\n");
+    ++ret;
+  }
+  if (element_ptr_ptr2 != element_ptr_ptr1)
+  {
+    fprintf (stderr, "Wrong element has been returned when tsearch() called for the second time.\n");
+    ++ret;
+  }
+
+  element_ptr_ptr1 =
+    (int **) tdelete ((void*) &element1, &root_ptr, &cmp_func);
+  if (NULL == element_ptr_ptr1)
+  {
+    fprintf (stderr, "NULL pointer has been returned by tdelete().\n");
+    ++ret;
+  }
+  if (NULL != root_ptr)
+  {
+    fprintf (stderr, "Root pointer has not been set to NULL by tdelete().\n");
+    ++ret;
+  }
+
+  return ret;
+}
+	      ]]
+	    )
+	  ],
+	  [AC_DEFINE([[MHD_USE_SYS_TSEARCH]], [[1]], [Define to 1 if you have properly working tsearch(), tfind() and tdelete() functions.])]
+	)
+  ],
+  [], [AC_INCLUDES_DEFAULT]
+)
+AM_CONDITIONAL([MHD_USE_SYS_TSEARCH], [[test "x$mhd_cv_sys_tsearch_usable" = "xyes" || test "x$mhd_cv_sys_tsearch_usable" = "xassuming yes"]])
+
+# Optional headers used for tests
+AC_CHECK_HEADERS([sys/sysctl.h netinet/ip_icmp.h netinet/icmp_var.h], [], [],
+  [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif /* HAVE_SYS_SYSCTL_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+#ifdef HAVE_NETINET_IN_SYSTM_H
+#include <netinet/in_systm.h>
+#endif /* HAVE_NETINET_IN_SYSTM_H */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif /* HAVE_NETINET_IN_H */
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+#ifdef HAVE_NETINET_IP_ICMP_H
+#include <netinet/ip_icmp.h>
+#endif /* HAVE_NETINET_IP_ICMP_H */
+  ]]
+)
+
+AC_ARG_ENABLE([compiler-hardening],
+  [AS_HELP_STRING([--enable-compiler-hardening], [enable compiler security checks])],
+  [],
+  [AS_CASE([${enable_build_type}],[*-hardened],
+    [enable_compiler_hardening='yes'],[enable_compiler_hardening='no'])]
+)
+AS_VAR_IF([enable_compiler_hardening],["yes"],
+  [
+    CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+    AC_CHECK_DECL([_FORTIFY_SOURCE],
+      [MHD_APPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-U_FORTIFY_SOURCE])],
+      [],[/* no includes */])
+    MHD_APPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-D_FORTIFY_SOURCE=2])
+    CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+    CFLAGS="${user_CFLAGS}"
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac],[-fstack-protector-strong],[-fstack-protector-all],[-fstack-protector])
+    MHD_CHECK_ADD_CC_CFLAGS([-fstack-clash-protection],[CFLAGS_ac])
+    MHD_FIND_ADD_CC_CFLAG([CFLAGS_ac],[-ftrivial-auto-var-init=pattern],[-ftrivial-auto-var-init=zero])
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    AS_IF([test "x${enable_static}" = "xyes" && test "x${pic_mode}" != "xyes"],
+      [
+        # PIE static lib can be used within non-PIE application, but
+        # PIE static lib cannot be used in non-PIE shared lib. Let's assume
+        # that static lib will not be used in shared lib
+        # All "pie" flags will be used automatically by libtool only
+        # for static library objects.
+        CFLAGS="${user_CFLAGS}"
+        # Perform tests here with "-pie" enabled
+        LDFLAGS="${LDFLAGS_ac} -pie ${user_LDFLAGS}"
+        MHD_CHECK_ADD_CC_CFLAG([-fPIE],[CFLAGS_ac],
+          [
+            MHD_APPEND_FLAG_TO_VAR([LDFLAGS_ac],[-pie])
+          ],
+          [
+            MHD_CHECK_ADD_CC_CFLAG([-fpie],[CFLAGS_ac],
+              [
+                MHD_APPEND_FLAG_TO_VAR([LDFLAGS_ac],[-pie])
+              ]
+            )
+          ]
+        )
+        CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+        LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+      ]
+    )
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+  ]
+)
+
+# Linker hardening options
+# Currently these options are ELF specific, they don't work on Darwin and W32
+AC_ARG_ENABLE([linker-hardening],
+  [AS_HELP_STRING([--enable-linker-hardening], [enable linker security fixups])],
+  [],
+  [AS_CASE([${enable_build_type}],[*-hardened],
+    [enable_linker_hardening='yes'],[enable_linker_hardening='no'])]
+)
+AS_VAR_IF([enable_linker_hardening],["yes"],
+  [
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    LDFLAGS="${user_LDFLAGS}"
+    MHD_CHECK_ADD_CC_LDFLAG([-Wl,-z,relro],[LDFLAGS_ac],
+      [MHD_CHECK_ADD_CC_LDFLAG([-Wl,-z,now],[LDFLAGS_ac])])
+    # Actually should be "noexec" by default, but let's try to enforce it.
+    MHD_CHECK_ADD_CC_LDFLAG([-Wl,-z,noexecstack],[LDFLAGS_ac])
+    # W32-specific. Some are enabled by default, but they will be enfored to be sure.
+    MHD_CHECK_ADD_CC_LDFLAGS([-Wl,--large-address-aware -Wl,--enable-auto-image-base],[LDFLAGS_ac])
+    MHD_CHECK_ADD_CC_LDFLAGS([-Wl,--dynamicbase -Wl,--nxcompat -Wl,--high-entropy-va],[LDFLAGS_ac])
+    LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+  ]
+)
+
+
+AH_TEMPLATE([[HAVE_STDBOOL_H]], [Define to 1 if you have the <stdbool.h> header file and <stdbool.h> defines 'bool' type.])
+AH_TEMPLATE([[HAVE_BUILTIN_TYPE_BOOL]], [Define to 1 if you have the real boolean type.])
+AH_TEMPLATE([[bool]], [Define to type name which will be used as boolean type.])
+AC_CHECK_HEADER([stdbool.h],
+  [
+   AC_CHECK_TYPE([bool],
+     [
+      AC_DEFINE([[HAVE_STDBOOL_H]], [[1]])
+      AC_DEFINE([[HAVE_BUILTIN_TYPE_BOOL]], [[1]])
+     ],
+     [
+      AC_MSG_WARN([[Header <stdbool.h> is present, but "bool" type cannot be detected. Check compiler flags.]])
+      AC_DEFINE([[bool]], [[int]])
+     ], [
+#include <stdbool.h>
+        ]
+   )
+  ],
+  [
+   AC_CHECK_TYPE([bool],
+     [AC_DEFINE([[HAVE_BUILTIN_TYPE_BOOL]], [[1]])],
+     [
+      AC_CHECK_TYPE([_Bool],
+        [
+         AC_DEFINE([[HAVE_BUILTIN_TYPE_BOOL]], [[1]])
+         AC_DEFINE([[bool]], [[_Bool]])
+        ],
+        [
+         AC_DEFINE([[bool]], [[int]])
+        ], []
+      )
+     ], []
+   )
+  ],
+  [AC_INCLUDES_DEFAULT]
+)
+
+AC_CACHE_CHECK([[whether "true" is defined or builtin]], [[mhd_cv_macro_true_defined]],
+  [AC_COMPILE_IFELSE(
+     [AC_LANG_PROGRAM(
+        [[
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+        ]], [[
+#if defined(true)
+    /* dummy */
+#else
+    (void)true;
+#endif
+        ]])
+     ], [[mhd_cv_macro_true_defined='yes']], [[mhd_cv_macro_true_defined='no']])
+  ])
+AS_VAR_IF([[mhd_cv_macro_true_defined]], [["yes"]], [[:]],
+  [AC_DEFINE([[true]],[[(!0)]], [Define to value interpreted by compiler as boolean "true", if "true" is not defined by system headers.])])
+
+AC_CACHE_CHECK([[whether "false" is defined or builtin]], [[mhd_cv_macro_false_defined]],
+  [AC_COMPILE_IFELSE(
+     [AC_LANG_PROGRAM(
+        [[
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+        ]], [[
+#if !defined(false)
+    (void)false;
+#else
+    /* dummy */
+#endif
+        ]])
+     ], [[mhd_cv_macro_false_defined='yes']], [[mhd_cv_macro_false_defined='no']])
+  ])
+AS_VAR_IF([[mhd_cv_macro_false_defined]], [["yes"]], [[:]],
+  [AC_DEFINE([[false]],[[0]], [Define to value interpreted by compiler as boolean "false", if "false" is not defined by system headers.])])
+
+AC_CACHE_CHECK([[whether "true" and "false" could be used]], [[mhd_cv_macro_true_false_valid]],
+  [AC_COMPILE_IFELSE(
+     [AC_LANG_PROGRAM(
+        [[
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+        ]], [[
+          int var1[true ? 1 : -1] = { 1 };
+          int var2[false ? -1 : 1] = { 2 };
+          int var3[!true ? -1 : 1] = { 3 };
+          int var4[!false ? 1 : -1] = { 4 };
+          if (var1[0] == var2[0] || var3[0] == var4[0])
+            return 1;
+        ]])
+     ], [[mhd_cv_macro_true_false_valid='yes']], [[mhd_cv_macro_true_false_valid='no']])
+  ])
+AS_VAR_IF([[mhd_cv_macro_true_false_valid]], [["yes"]], [[:]],
+  [AC_MSG_ERROR([[Value of "true" or value of "false" is not valid. Check config.log for details.]])])
+
+
+AX_CHECK_COMPILE_FLAG([[-Werror=attributes]],
+  [
+   AC_MSG_CHECKING([[whether -Werror=attributes actually works]])
+   CFLAGS="${CFLAGS_ac} ${user_CFLAGS} -Werror=attributes"
+   AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+       [[__attribute__((non_existing_attrb_dummy)) static int SimpleFunc(void) {return 3;}]],
+       [[int r = SimpleFunc(); if (r) return r;]])],
+     [
+       AC_MSG_RESULT([[no]])
+       errattr_CFLAGS=""
+     ], [
+       AC_MSG_RESULT([[yes]])
+       errattr_CFLAGS="-Werror=attributes"
+     ])
+   CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+  ],
+                      [[errattr_CFLAGS=""]], [], [])
+
+AC_MSG_CHECKING([[for function inline keywords supported by $CC]])
+CFLAGS="${CFLAGS_ac} ${user_CFLAGS} $errattr_CFLAGS"
+inln_prfx="none"
+# Prefer always inline functions
+for inln_prfx_chk in InlineWithAttr __forceinline inline __inline__ __inline _inline _Inline
+do
+  # Try to link to avoid "symbol undefined" problems at build time
+  AS_IF([[test "x$inln_prfx_chk" = "xInlineWithAttr"]],
+    [
+     AS_IF([[test "x$errattr_CFLAGS" = "x"]],
+       [[ # Skip test with attribute as negative result can't be detected
+          inln_prfx_chk="__forceinline" # use next value
+       ]],[[inln_prfx_chk="inline __attribute__((always_inline))"]])
+    ])
+  AC_LINK_IFELSE(
+    [
+     AC_LANG_PROGRAM(
+       [[
+#ifdef __cplusplus
+#error This test is only for C.
+choke me
+#endif
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+         static $inln_prfx_chk bool cmpfn(int x, int y)
+         { return x > y; }
+         static $inln_prfx_chk int sumfn(int x, int y)
+         { return x + y; }
+       ]],[[
+       int a = 1, b = 100, c;
+       if (cmpfn(a, b))
+         c = sumfn(a, b);
+       else
+         c = 0 - sumfn(a, b);
+       if (c)
+         return 0;
+       ]])
+    ],
+    [[ inln_prfx="$inln_prfx_chk" ]])
+  test "x$inln_prfx" != "xnone" && break
+done
+AS_IF([[test "x$inln_prfx" != "xnone"]],
+      [
+       AC_DEFINE([INLINE_FUNC],[1],[Define to 1 if your C compiler supports inline functions.])
+       AC_DEFINE_UNQUOTED([_MHD_static_inline],[static $inln_prfx],[Define to prefix which will be used with MHD static inline functions.])
+      ], [
+       AC_DEFINE([_MHD_static_inline],[static],[Define to prefix which will be used with MHD static inline functions.])
+      ])
+AC_MSG_RESULT([[$inln_prfx]])
+CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+
+AC_CHECK_HEADERS([stdalign.h], [], [], [AC_INCLUDES_DEFAULT])
+AC_CACHE_CHECK([[for C11 'alignof()' support]], [[mhd_cv_c_alignof]],
+  [AC_COMPILE_IFELSE(
+     [AC_LANG_PROGRAM(
+        [[
+#ifdef HAVE_STDALIGN_H
+#include <stdalign.h>
+#endif
+        ]], [[
+          int var1[(alignof(int) >= 2) ? 1 : -1];
+          int var2[alignof(unsigned int) - 1];
+          int var3[(alignof(char) > 0) ? 1 : -1];
+          int var4[(alignof(long) >= 4) ? 1 : -1];
+
+          /* Mute compiler warnings */
+          var1[0] = var2[0] = var3[0] = 0;
+          var4[0] = 1;
+          if (var1[0] + var2[0] + var3[0] == var4[0])
+            return 1;
+        ]])
+     ], [
+          AC_COMPILE_IFELSE(
+		    [AC_LANG_PROGRAM(
+		        [[
+#ifdef HAVE_STDALIGN_H
+#include <stdalign.h>
+#endif
+		        ]], [[
+		          /* Should fail if 'alignof()' works */
+		          int var1[alignof(nonexisting_type) - 1];
+
+		          /* Mute compiler warnings */
+		          var1[0] = 1;
+		          if (var1[0] + 1 == 1)
+		            return 1;
+		        ]])
+		    ], [[mhd_cv_c_alignof='no']], [[mhd_cv_c_alignof='yes']])
+        ], [[mhd_cv_c_alignof='no']])
+  ])
+AS_VAR_IF([mhd_cv_c_alignof], ["yes"],
+  [AC_DEFINE([[HAVE_C_ALIGNOF]], [1], [Define to 1 if your compiler supports 'alignof()'])])
+
+
 # Check system type
-case "$host_os" in
-*darwin* | *rhapsody* | *macosx*)
-     AC_DEFINE_UNQUOTED(OSX,1,[This is an OS X system])
-     CFLAGS="-no-cpp-precomp -fno-common $CFLAGS"
-     ;;
-freebsd*)
-     AC_DEFINE_UNQUOTED(SOMEBSD,1,[This is a BSD system])
-     AC_DEFINE_UNQUOTED(FREEBSD,1,[This is a FreeBSD system])
-     ;;
-openbsd*)
-     AC_DEFINE_UNQUOTED(SOMEBSD,1,[This is a BSD system])
-     AC_DEFINE_UNQUOTED(OPENBSD,1,[This is an OpenBSD system])
-     ;;
-netbsd*)
-     AC_DEFINE_UNQUOTED(SOMEBSD,1,[This is a BSD system])
-     AC_DEFINE_UNQUOTED(NETBSD,1,[This is a NetBSD system])
-     ;;
-*solaris*)
-     AC_DEFINE_UNQUOTED(SOLARIS,1,[This is a Solaris system])
-     AC_DEFINE_UNQUOTED(_REENTRANT,1,[Need with solaris or errno doesnt work])
-     AC_SEARCH_LIBS(gethostbyname, nsl)
-     AC_SEARCH_LIBS(socket, socket)
-     ;;
-*arm-linux*)
-     AC_DEFINE_UNQUOTED(LINUX,1,[This is a Linux kernel])
-     AC_DEFINE_UNQUOTED(HAVE_LISTEN_SHUTDOWN,1,[can use shutdown on listen sockets])
-     CFLAGS="-fPIC -pipe $CFLAGS"
-     ;;
-*linux*)
-     AC_DEFINE_UNQUOTED(LINUX,1,[This is a Linux kernel])
-     AC_DEFINE_UNQUOTED(HAVE_LISTEN_SHUTDOWN,1,[can use shutdown on listen sockets])
-     ;;
-*cygwin*)
-     AC_DEFINE_UNQUOTED(CYGWIN,1,[This is a Cygwin system])
-     os_is_windows=yes
-     ;;
-*mingw*)
-     AC_DEFINE_UNQUOTED(MINGW,1,[This is a MinGW system])
-     AC_DEFINE_UNQUOTED(WINDOWS,1,[This is a Windows system])
-     LIBS="$LIBS -lws2_32"
-     AC_CHECK_HEADERS([winsock2.h ws2tcpip.h],, AC_MSG_ERROR([[Winsock2 headers are required for W32]]))
+AC_MSG_CHECKING([[for target host OS]])
+AS_CASE(["$host_os"],
+ [*darwin* | *rhapsody* | *macosx*],
+ [AC_DEFINE([OSX],[1],[This is an OS X system])
+     mhd_host_os='Darwin'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+ [kfreebsd*-gnu],
+ [AC_DEFINE([SOMEBSD],[1],[This is a BSD system])
+     AC_DEFINE([FREEBSD],[1],[This is a FreeBSD system])
+     mhd_host_os='FreeBSD kernel with GNU userland'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+ [freebsd*],
+ [AC_DEFINE([SOMEBSD],[1],[This is a BSD system])
+     AC_DEFINE([FREEBSD],[1],[This is a FreeBSD system])
+     mhd_host_os='FreeBSD'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+ [openbsd*],
+ [AC_DEFINE([SOMEBSD],[1],[This is a BSD system])
+     AC_DEFINE([OPENBSD],[1],[This is an OpenBSD system])
+     mhd_host_os='OpenBSD'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+ [netbsd*],
+ [AC_DEFINE([SOMEBSD],[1],[This is a BSD system])
+     AC_DEFINE([NETBSD],[1],[This is a NetBSD system])
+     mhd_host_os='NetBSD'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+ [*solaris*],
+ [AC_DEFINE([SOLARIS],[1],[This is a Solaris system])
+     AC_DEFINE([_REENTRANT],[1],[Need with solaris or errno does not work])
+     mhd_host_os='Solaris'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+  [*linux*],
+  [AC_DEFINE([LINUX],[1],[This is a Linux kernel])
+     mhd_host_os='Linux'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+  [*cygwin*],
+  [AC_DEFINE([CYGWIN],[1],[This is a Cygwin system])
+     mhd_host_os='Windows/Cygwin'
+     AC_MSG_RESULT([[$mhd_host_os]])
+     os_is_windows=yes],
+  [*mingw*],
+  [
+    AC_DEFINE([MINGW],[1],[This is a MinGW system])
+     AC_DEFINE([WINDOWS],[1],[This is a Windows system])
+     mhd_host_os='Windows/MinGW'
+     AC_MSG_RESULT([[$mhd_host_os]])
+     AC_CHECK_HEADERS([winsock2.h ws2tcpip.h], [], [AC_MSG_ERROR([[Winsock2 headers are required for W32]])], [AC_INCLUDES_DEFAULT])
      AC_CACHE_CHECK([for MS lib utility], [ac_cv_use_ms_lib_tool],
-       [[mslibcheck=`lib 2>&1`
-        if [[ $mslibcheck = "Microsoft (R) Library Manager"* ]]; then
-          ac_cv_use_ms_lib_tool=yes
-        else
-          ac_cv_use_ms_lib_tool=no
-        fi
-         ]])
-     if test "x$ac_cv_use_ms_lib_tool" = "xyes"; then
-       AC_SUBST([MS_LIB_TOOL], [[lib]])
-     fi
+       [mslibcheck=`lib 2>&1`
+        AS_IF([echo "$mslibcheck" | $GREP -e '^Microsoft (R) Library Manager' - >/dev/null],
+          [ac_cv_use_ms_lib_tool=yes],
+          [ac_cv_use_ms_lib_tool=no])
+         ])
+     AS_IF([test "x$ac_cv_use_ms_lib_tool" = "xyes"],
+       [AC_SUBST([MS_LIB_TOOL], [[lib]])])
      AC_SUBST([lt_cv_objdir])
      os_is_windows=yes
      os_is_native_w32=yes
-     ;;
-*openedition*)
-     AC_DEFINE_UNQUOTED(OS390,1,[This is a OS/390 system])
-    ;;
-*)
+   ],
+   [*openedition*],
+   [AC_DEFINE([OS390],[1],[This is a OS/390 system])
+     mhd_host_os='OS/390'
+     AC_MSG_RESULT([[$mhd_host_os]])],
+   [gnu*],
+   [AC_DEFINE([[GNU_HURD]], [[1]], [Define to `1' if host machine runs on GNU Hurd.])
+     mhd_host_os='GNU Hurd'
+     AC_MSG_RESULT([[$mhd_host_os]])
+    ],
+    [
+     AC_MSG_RESULT([unrecognised OS])
+     mhd_host_os="${host_os}"
      AC_MSG_WARN([Unrecognised OS $host_os])
-     AC_DEFINE_UNQUOTED(OTHEROS,1,[Some strange OS])
-#    You might want to find out if your OS supports shutdown on listen sockets,
-#    and extend the switch statement; if we do not have 'HAVE_LISTEN_SHUTDOWN',
-#    pipes are used instead to signal 'select'.
-#    AC_DEFINE_UNQUOTED(HAVE_LISTEN_SHUTDOWN,1,[can use shutdown on listen sockets])
-;;
-esac
+     AC_DEFINE([OTHEROS],1,[Some strange OS])
+ ])
 
-if test "x$with_threads" = "xposix"; then
-# forced posix threads
-  if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-    USE_THREADS='posix'
-  else
-    if test "x$HAVE_W32_THREADS" = "xyes"; then
-      AC_MSG_ERROR([[Posix threads are not available. Try to configure --with-threads=auto]])
-    else
-      AC_MSG_ERROR([[Posix threads are not available]])
-    fi
-  fi
-elif test "x$with_threads" = "xw32"; then
-# forced w32 threads
-  if test "x$HAVE_W32_THREADS" = "xyes"; then
-    USE_THREADS='w32'
-  else
-    if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-      AC_MSG_ERROR([[W32 threads are not available. Try to configure --with-threads=auto]])
-    else
-      AC_MSG_ERROR([[W32 threads are not available]])
-    fi
-  fi
-else
-# automatic threads lib selection
-  if test "x$HAVE_POSIX_THREADS" = "xyes" && test "x$HAVE_W32_THREADS" = "xyes"; then
-    if test "x$os_is_native_w32" = "xyes"; then
-      USE_THREADS='w32'
-    else
-      USE_THREADS='posix'
-    fi
-  elif test "x$HAVE_POSIX_THREADS" = "xyes"; then
-    USE_THREADS='posix'
-  elif test "x$HAVE_W32_THREADS" = "xyes"; then
-    USE_THREADS='w32'
-  else
-    AC_MSG_ERROR([[No threading lib is available. Cosider installing pthreads]])
-  fi
-fi
+AM_CONDITIONAL([CYGWIN_TARGET], [[test "x$os_is_windows" = "xyes" && \
+                                  test "x${os_is_native_w32}" != "xyes"]])
 
-if test "x$USE_THREADS" = "xposix"; then
-  CC="$PTHREAD_CC"
+AS_VAR_IF([os_is_windows], ["yes"],
+  [
+    AC_MSG_CHECKING([[whether target W32 version is specified by precompiler defines]])
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+/* Note: check logic is reversed for easy log reading */
+#ifdef WINVER
+#error WINVER is defined
+choke me now;
+#endif
+#ifdef _WIN32_WINNT
+#error _WIN32_WINNT is defined
+choke me now;
+#endif
+#ifdef NTDDI
+#error NTDDI is defined
+choke me now;
+#endif
+        ]],[[(void)0]])
+      ], [[mhd_w32_ver_preselect=no]], [[mhd_w32_ver_preselect=yes]]
+    )
+    AC_MSG_RESULT([[${mhd_w32_ver_preselect}]])
+    AC_CHECK_HEADERS([windows.h sdkddkver.h], [], [], [AC_INCLUDES_DEFAULT])
+    AS_VAR_IF([mhd_w32_ver_preselect],["yes"],
+     [
+       AC_MSG_CHECKING([[for specified target W32 version]])
+       AS_UNSET([[mhd_w32_ver]])
+       AS_UNSET([[mhd_w32_ver_msg]])
+       AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#if _WIN32_WINNT+0 < 0x0501
+/* Check before headers inclusion */
+#error _WIN32_WINNT is less than 0x0501
+choke me now;
+#endif
+
+#ifdef HAVE_SDKDDKVER_H
+#include <sdkddkver.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#if _WIN32_WINNT+0 < 0x0501
+#error _WIN32_WINNT is less than 0x0501
+choke me now;
+#endif
+           ]],[[(void)0]])
+         ], [], [
+           AC_MSG_RESULT([[pre-WinXP]])
+           AC_MSG_ERROR([[libmicrohttpd cannot be compiled for Windows version before Windows XP]])
+         ]
+       )
+       AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#ifdef HAVE_SDKDDKVER_H
+#include <sdkddkver.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#if _WIN32_WINNT+0 == 0x0501
+#error _WIN32_WINNT is 0x0501
+choke me now;
+#endif
+#if _WIN32_WINNT+0 == 0x0502
+#error _WIN32_WINNT is 0x0502
+choke me now;
+#endif
+           ]],[[(void)0]])
+         ], [], [
+           mhd_w32_ver="WinXP"
+           mhd_w32_ver_msg="WinXP (selected by precompiler flags)"
+         ]
+       )
+       AS_VAR_SET_IF([mhd_w32_ver], [],
+         [
+           AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#ifdef HAVE_SDKDDKVER_H
+#include <sdkddkver.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#if _WIN32_WINNT+0 < 0x0600
+#error _WIN32_WINNT is less than 0x0600 but greater than 0x0502
+choke me now;
+#endif
+                ]],[[(void)0]])
+             ], [], [
+               AC_MSG_ERROR([[_WIN32_WINNT value is wrong (less than 0x0600 but greater than 0x0502)]])
+             ]
+           )
+
+           AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#ifdef HAVE_SDKDDKVER_H
+#include <sdkddkver.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#if _WIN32_WINNT+0 == 0x0600
+#error _WIN32_WINNT is 0x0600
+choke me now;
+#endif
+                ]],[[(void)0]])
+             ], [], [
+               mhd_w32_ver="Vista"
+               mhd_w32_ver_msg="Vista (selected by precompiler flags)"
+             ]
+           )
+         ]
+       )
+
+       AS_VAR_SET_IF([mhd_w32_ver], [],
+         [
+           AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#ifdef HAVE_SDKDDKVER_H
+#include <sdkddkver.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#if _WIN32_WINNT+0 > 0x0600
+#error _WIN32_WINNT is greater than 0x0600
+choke me now;
+#endif
+                ]],[[(void)0]])
+             ], [
+               mhd_w32_ver="unknown"
+               mhd_w32_ver_msg="unknown (cannot be detected)"
+             ], [
+               mhd_w32_ver="newer than Vista"
+               mhd_w32_ver_msg="newer than Vista (selected by precompiler flags)"
+             ]
+           )
+         ]
+       )
+       AC_MSG_RESULT([[${mhd_w32_ver}]])
+     ], [
+       mhd_w32_ver="Vista"
+       mhd_w32_ver_msg="Vista (default, override by CPPFLAGS=-D_WIN32_WINNT=0xNNNN)"
+       CPPFLAGS_ac="${CPPFLAGS_ac} -D_WIN32_WINNT=0x0600"
+       CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+       AC_MSG_CHECKING([[whether headers accept _WIN32_WINNT=0x0600]])
+       AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#ifdef HAVE_SDKDDKVER_H
+#include <sdkddkver.h>
+#endif
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+#include <stdio.h>
+            ]],[[(void)0]])
+         ], [
+           AC_MSG_RESULT([[yes]])
+         ], [
+           AC_MSG_RESULT([[no]])
+           AC_MSG_ERROR([Headers do not accept _WIN32_WINNT=0x0600. Consider override target W32 version by CPPFLAGS=-D_WIN32_WINNT=0xNNNN])
+         ]
+       )
+     ]
+    )
+  ]
+)
+
+AS_IF([test "x${os_is_windows}" = "xyes" && test "x${os_is_native_w32}" = "xyes"],
+  [
+    AC_CACHE_CHECK([W32 run-time library type], [mhd_cv_wctr_type],
+      [
+        AC_EGREP_CPP([MHDMARKER: UCRT run-time library in use!], [
+#include <stdio.h>
+#if defined(_UCRT)
+#define CRT_STR "MHDMARKER: UCRT run-time library in use!"
+#endif
+#if defined(__MSVCRT_VERSION__)
+#if (__MSVCRT_VERSION__ >= 0xE00) && (__MSVCRT_VERSION__ < 0x1000)
+#define CRT_STR "MHDMARKER: UCRT run-time library in use!"
+#endif
+#if (__MSVCRT_VERSION__ > 0x1400)
+#define CRT_STR "MHDMARKER: UCRT run-time library in use!"
+#endif
+#endif
+
+#ifndef CRT_STR
+#define CRT_STR "MHDMARKER: MSVCRT run-time library in use!"
+#endif
+
+int main(void)
+{
+  printf ("%\n", CRT_STR);
+  return 0;
+}
+          ],
+          [mhd_cv_wctr_type="ucrt"], [mhd_cv_wctr_type="msvcrt"])
+      ]
+    )
+    mhd_host_os="${mhd_host_os}-${mhd_cv_wctr_type}"
+    AS_VAR_IF([mhd_cv_wctr_type], ["msvcrt"],
+      [
+        # Use CFLAGS here to override user-supplied wrong CPPFLAGS. Durty trick, but choice is limited.
+        AX_APPEND_COMPILE_FLAGS([-U__USE_MINGW_ANSI_STDIO -D__USE_MINGW_ANSI_STDIO=0], [CFLAGS_ac])
+        AC_SUBST([W32CRT], [MSVCRT])
+      ], [AC_SUBST([W32CRT], [UCRT])]
+    )
+
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+    LDFLAGS="${user_LDFLAGS}"
+    AS_CASE([$mhd_w32_ver],
+      [WinXP],
+      [MHD_CHECK_ADD_CC_LDFLAG([-Wl,--major-subsystem-version,5,--minor-subsystem-version,1],[LDFLAGS_ac])],
+      [Vista],
+      [MHD_CHECK_ADD_CC_LDFLAG([-Wl,--major-subsystem-version,6,--minor-subsystem-version,0],[LDFLAGS_ac])]
+    )
+    LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+  ]
+)
+CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+
+
+AC_ARG_WITH([threads],
+   [AS_HELP_STRING([--with-threads=LIB],[choose threading library (posix, w32, auto, none) [auto]])],
+   [], [with_threads='auto'])
+AS_CASE([[$with_threads]],
+  [[win32]], [[with_threads='w32']],
+  [[pthreads]], [[with_threads='posix']],
+  [[posix]], [[:]],
+  [[w32]], [[:]],
+  [[none]], [[with_threads='none']],
+  [[no]], [[with_threads='none']],
+  [[auto]], [[:]],
+    [AC_MSG_ERROR([[incorrect parameter "$with_threads" specified for --with-threads]])]
+)
+
+# Check for posix threads support, regardless of configure parameters as
+# testsuite uses only posix threads.
+AX_PTHREAD(
+  [
+    mhd_have_posix_threads='yes'
+    AC_DEFINE([[HAVE_PTHREAD_H]],[[1]],[Define to 1 if you have the <pthread.h> header file.])
+	AC_CACHE_CHECK([[whether pthread_sigmask(3) is available]],
+	  [[mhd_cv_func_pthread_sigmask]], [dnl
+	  save_LIBS="$LIBS"
+	  LIBS="$PTHREAD_LIBS $LIBS"
+  	  CFLAGS="${CFLAGS_ac} ${PTHREAD_CFLAGS} ${user_CFLAGS}"
+	  AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <signal.h>]],
+	    [[
+	      sigset_t nset, oset;
+	      sigemptyset (&nset);
+	      sigaddset (&nset, SIGPIPE);
+	      if (0 != pthread_sigmask(SIG_BLOCK, &nset, &oset)) return 1;
+	    ]])],
+	    [[mhd_cv_func_pthread_sigmask="yes"]],[[mhd_cv_func_pthread_sigmask="no"]])
+	  LIBS="${save_LIBS}"
+      CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+	])
+	AS_VAR_IF([mhd_cv_func_pthread_sigmask],["yes"],
+	  [AC_DEFINE([[HAVE_PTHREAD_SIGMASK]],[[1]],[Define to 1 if you have the pthread_sigmask(3) function.])])
+  ],[[mhd_have_posix_threads='no']])
+AM_CONDITIONAL([HAVE_POSIX_THREADS],[test "x$mhd_have_posix_threads" = "xyes"])
+
+mhd_have_w32_threads='no'
+AS_IF([[test "x$with_threads" = "xauto"]],
+ [
+ AS_IF([[test "x$os_is_windows" = "xyes"]],
+   [
+    AC_MSG_CHECKING([[for W32 threads]])
+    AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM([[
+#include <windows.h>
+         ]], [ HANDLE h = CreateThread(NULL, 0, NULL, NULL, 0, NULL);])]
+      , [[mhd_have_w32_threads='yes']], [[mhd_have_w32_threads='no']]
+      )
+    AC_MSG_RESULT([[$mhd_have_w32_threads]])
+   ])
+ ]
+)
+
+AC_MSG_CHECKING([[for threading lib to use with libmicrohttpd ($with_threads)]])
+AS_IF([test "x$with_threads" = "xposix"],
+  [ # forced posix threads
+    AS_IF([test "x$mhd_have_posix_threads" = "xyes"], [USE_THREADS='posix'],
+      [ AS_IF([[test "x$os_is_windows" = "xyes"]] ,
+          [ AC_MSG_ERROR([[Posix threads are not available. Try to configure --with-threads=auto]])],
+          [ AC_MSG_ERROR([[No threading lib is available. Consider installing pthreads]])] )
+      ])
+    ])
+AS_IF([test "x$with_threads" = "xw32"],
+  [ # forced w32 threads
+    AS_IF([[test "x$mhd_have_w32_threads" = "xyes"]],
+      [[ USE_THREADS='w32' ]],
+      [ AC_MSG_ERROR([[W32 threads are not available. Try to configure --with-threads=auto]])])
+    ])
+AS_IF([test "x$with_threads" = "xauto"],
+      [# automatic threads lib selection
+       AS_IF([[test "x$os_is_native_w32" = "xyes" && test "x$mhd_have_w32_threads" = "xyes"]] ,
+        [[ USE_THREADS='w32' ]] ,
+        [[ test "x$mhd_have_posix_threads" = "xyes" ]], [[ USE_THREADS='posix' ]],
+        [[ test "x$mhd_have_w32_threads" = "xyes" ]], [[ USE_THREADS='w32' ]],
+        [ AC_MSG_ERROR([[No threading lib is available. Consider installing pthreads]]) ]
+        )])
+AS_IF([test "x$with_threads" = "xnone"],
+   [USE_THREADS='none'])
+
+AS_IF([test "x$USE_THREADS" = "xposix"],
+  [CC="$PTHREAD_CC"
   AC_DEFINE([MHD_USE_POSIX_THREADS],[1],[define to use pthreads])
   MHD_LIB_CFLAGS="$MHD_LIB_CFLAGS $PTHREAD_CFLAGS"
   MHD_LIBDEPS="$PTHREAD_LIBS $MHD_LIBDEPS"
-elif test "x$USE_THREADS" = "xw32"; then
-  AC_DEFINE([MHD_USE_W32_THREADS],[1],[define to use W32 threads])
-fi
+  MHD_LIBDEPS_PKGCFG="$PTHREAD_LIBS $MHD_LIBDEPS_PKGCFG"],
+  [AS_IF([test "x$USE_THREADS" = "xw32"],
+   [AC_DEFINE([MHD_USE_W32_THREADS],[1],[define to use W32 threads])])])
 AM_CONDITIONAL([USE_POSIX_THREADS], [test "x$USE_THREADS" = "xposix"])
 AM_CONDITIONAL([USE_W32_THREADS], [test "x$USE_THREADS" = "xw32"])
+AM_CONDITIONAL([USE_THREADS], [test "x$USE_THREADS" != "xnone"])
+AM_CONDITIONAL([DISABLE_THREADS], [test "x$USE_THREADS" = "xnone"])
+AC_MSG_RESULT([$USE_THREADS])
 
+AC_ARG_ENABLE([[thread-names]],
+   [AS_HELP_STRING([--disable-thread-names],[do not set names on MHD generated threads [auto]])],
+   [], [enable_thread_names='auto'])
+
+AS_IF([test "x$enable_thread_names" != "xno" && test "x$USE_THREADS" = "xposix"],[
+  # Check for thread name function
+  HAVE_THREAD_NAME_FUNC="no"
+  SAVE_LIBS="$LIBS"
+  LIBS="$PTHREAD_LIBS $LIBS"
+  CFLAGS="${CFLAGS_ac} $PTHREAD_CFLAGS ${user_CFLAGS}"
+  AC_CHECK_HEADERS([pthread_np.h],[],[],
+    [
+AC_INCLUDES_DEFAULT
+      [
+#include <pthread.h>
+      ]
+    ])
+
+  # Try to find how to set thread name by thread attributes.
+  # If pthread_attr_setname_np(3) is not declared, it's not possible to detect
+  # form of pthread_attr_setname_np(3) due to C "feature" "implicit declaration".
+  AC_CHECK_DECL([[pthread_attr_setname_np]],[],[],[[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]])
+
+  AS_IF([[test "x$ac_cv_have_decl_pthread_attr_setname_np" = "xyes"]],
+    [AC_MSG_CHECKING([[for pthread_attr_setname_np(3) in NetBSD or OSF1 form]])
+     AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM([[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]], [[
+      pthread_attr_t thr_attr;
+      pthread_attr_init(&thr_attr);
+      pthread_attr_setname_np(&thr_attr, "name", 0);
+      pthread_attr_destroy(&thr_attr);
+        ]])],
+        [AC_DEFINE([[HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD]], [[1]], [Define if you have NetBSD form (or OSF1 form) of pthread_attr_setname_np(3) function.])
+         HAVE_THREAD_NAME_FUNC="yes"
+         AC_MSG_RESULT([[yes]])],
+        [AC_MSG_RESULT([[no]])]
+        )
+    ])
+
+  AS_IF([[test "x$HAVE_THREAD_NAME_FUNC" != "xyes" && test "x$ac_cv_have_decl_pthread_attr_setname_np" = "xyes"]],
+    [AC_MSG_CHECKING([[for pthread_attr_setname_np(3) in IBM i or Solaris form]])
+     AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM([[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]], [[
+      pthread_attr_t thr_attr;
+      pthread_attr_init(&thr_attr);
+      pthread_attr_setname_np(&thr_attr, "name");
+      pthread_attr_destroy(&thr_attr);
+        ]])],
+        [AC_DEFINE([[HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI]], [[1]], [Define if you have IBM i form (or Solaris form) of pthread_attr_setname_np(3) function.])
+         HAVE_THREAD_NAME_FUNC="yes"
+         AC_MSG_RESULT([[yes]])],
+        [AC_MSG_RESULT([[no]])]
+        )
+    ])
+
+  # Try to find how to set thread name for started thread - less convenient
+  # than setting name by attributes.
+  # If pthread_setname_np(3) is not declared, it's not possible to detect
+  # form of pthread_setname_np(3) due to C "feature" "implicit declaration".
+  AS_IF([[test "x$HAVE_THREAD_NAME_FUNC" != "xyes"]],
+    [AC_CHECK_DECL([[pthread_setname_np]],[],[],[[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+       ]])
+    ])
+
+  AS_IF([[test "x$HAVE_THREAD_NAME_FUNC" != "xyes" && test "x$ac_cv_have_decl_pthread_setname_np" = "xyes"]],
+    [AC_MSG_CHECKING([[for pthread_setname_np(3) in NetBSD or OSF1 form]])
+     AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM([[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]], [[int res = pthread_setname_np(pthread_self(), "name", 0); if (res) return res;]])],
+        [AC_DEFINE([[HAVE_PTHREAD_SETNAME_NP_NETBSD]], [[1]], [Define if you have NetBSD form (or OSF1 form) of pthread_setname_np(3) function.])
+         HAVE_THREAD_NAME_FUNC="yes"
+         AC_MSG_RESULT([[yes]])],
+        [AC_MSG_RESULT([[no]])]
+        )
+    ])
+
+  AS_IF([[test "x$HAVE_THREAD_NAME_FUNC" != "xyes" && test "x$ac_cv_have_decl_pthread_setname_np" = "xyes"]],
+    [AC_MSG_CHECKING([[for pthread_setname_np(3) in GNU/Linux form]])
+     AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM([[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]], [[int res = pthread_setname_np(pthread_self(), "name"); if (res) return res;]])],
+        [AC_DEFINE([[HAVE_PTHREAD_SETNAME_NP_GNU]], [[1]], [Define if you have GNU/Linux form of pthread_setname_np(3) function.])
+         HAVE_THREAD_NAME_FUNC="yes"
+         AC_MSG_RESULT([[yes]])],
+        [AC_MSG_RESULT([[no]])]
+        )
+    ])
+
+  AS_IF([[test "x$HAVE_THREAD_NAME_FUNC" != "xyes" && test "x$ac_cv_have_decl_pthread_setname_np" = "xyes"]],
+    [AC_MSG_CHECKING([[for pthread_setname_np(3) in Darwin form]])
+     AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM([[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]], [[int res = pthread_setname_np("name"); if (res) return res;]])],
+        [AC_DEFINE([[HAVE_PTHREAD_SETNAME_NP_DARWIN]], [[1]], [Define if you have Darwin form of pthread_setname_np(3) function.])
+         HAVE_THREAD_NAME_FUNC="yes"
+         AC_MSG_RESULT([[yes]])],
+        [AC_MSG_RESULT([[no]])]
+        )
+    ])
+
+  AS_IF([[test "x$HAVE_THREAD_NAME_FUNC" != "xyes"]],
+    [
+     AC_CHECK_DECL([[pthread_set_name_np]],
+       [
+        AC_MSG_CHECKING([[for pthread_set_name_np(3) in FreeBSD form]])
+        AC_LINK_IFELSE(
+          [AC_LANG_PROGRAM([[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+]], [[pthread_set_name_np(pthread_self(), "name");]])],
+          [AC_DEFINE([[HAVE_PTHREAD_SET_NAME_NP_FREEBSD]], [[1]], [Define if you have FreeBSD form of pthread_set_name_np(3) function.])
+           HAVE_THREAD_NAME_FUNC="yes"
+           AC_MSG_RESULT([[yes]])],
+          [AC_MSG_RESULT([[no]])]
+          )
+       ],[],[[
+#include <pthread.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif
+       ]]
+     )
+    ])
+
+  LIBS="$SAVE_LIBS"
+  CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+])
+
+AS_IF([[test "x$enable_thread_names" != "xno"]],
+  [
+    AC_MSG_CHECKING([[whether to enable thread names]])
+    AC_COMPILE_IFELSE(
+     [AC_LANG_PROGRAM([], [[
+#ifdef MHD_NO_THREAD_NAMES
+#error Thread names are disabled.
+choke me
+#endif
+
+/* Keep in sync with mhd_threads.h */
+#if defined(MHD_USE_POSIX_THREADS) && (defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) || \
+    defined(HAVE_PTHREAD_SETNAME_NP_GNU) || defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) || defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) || \
+    defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) )
+(void) 0; /* no-op */
+#elif defined(MHD_USE_W32_THREADS) && defined(_MSC_FULL_VER)
+(void) 0; /* no-op */
+#else
+#error No thread name function is available.
+choke me
+#endif
+       ]])
+     ], [
+       enable_thread_names='yes'
+     ], [
+       AS_IF([[test "x$enable_thread_names" = "xyes"]],
+         [
+           AC_MSG_RESULT([[no]])
+           AC_MSG_ERROR([[thread names was explicitly requested, but thread name function is not available]])
+         ])
+       enable_thread_names='no'
+     ])
+  AC_MSG_RESULT([[$enable_thread_names]])
+  ])
+
+AS_IF([[test "x$enable_thread_names" = "xno"]],
+  [AC_DEFINE([[MHD_NO_THREAD_NAMES]], [[1]], [Define to 1 to disable setting name on generated threads])])
 
 AM_CONDITIONAL(HAVE_W32, [test "x$os_is_native_w32" = "xyes"])
 w32_shared_lib_exp=no
-if test "x$enable_shared" = "xyes" && test "x$os_is_native_w32" = "xyes"; then
-  if test "x$ac_cv_use_ms_lib_tool" = "xyes" || test -n "$DLLTOOL"; then
-    w32_shared_lib_exp=yes
-  else
-    AC_MSG_WARN([[GNU dlltool or MS lib.exe is required for creating shared library export on W32]])
-    AC_MSG_WARN([[Export library libmicrohttpd.lib will not be created]])
-  fi
-fi
-AM_CONDITIONAL(W32_SHARED_LIB_EXP, [test "x$w32_shared_lib_exp" = "xyes"])
-AM_CONDITIONAL(USE_MS_LIB_TOOL, [test "x$ac_cv_use_ms_lib_tool" = "xyes"])
+AS_IF([test "x$enable_shared" = "xyes" && test "x$os_is_native_w32" = "xyes"],
+  [
+    AS_IF([test "x$ac_cv_use_ms_lib_tool" = "xyes" || test -n "$DLLTOOL"],
+      [
+        w32_shared_lib_exp=yes
+        use_expfile="no"
+        AS_VAR_IF([ac_cv_use_ms_lib_tool], ["yes"], [use_expfile="yes"],
+          [
+            AC_CACHE_CHECK([whether $DLLTOOL supports export file generation], [mhd_cv_dlltool_expfile],
+              [
+                AS_IF([AC_RUN_LOG([$DLLTOOL -e conftest.exp >&2 ])],
+                  [
+                    AS_IF([test -f conftest.exp], [mhd_cv_dlltool_expfile="yes"], [mhd_cv_dlltool_expfile="no"])
+                  ], [mhd_cv_dlltool_expfile="no"]
+                )
+                rm -f conftest.exp
+              ]
+            )
+            use_expfile="${mhd_cv_dlltool_expfile}"
+          ]
+        )
+      ],
+      [
+        AC_MSG_WARN([[GNU dlltool or MS lib.exe is required for creating shared library export on W32]])
+        AC_MSG_WARN([[Export library libmicrohttpd.lib will not be created]])
+      ]
+    )
+  ]
+)
+AM_CONDITIONAL([W32_SHARED_LIB_EXP], [test "x$w32_shared_lib_exp" = "xyes"])
+AM_CONDITIONAL([USE_MS_LIB_TOOL], [test "x$ac_cv_use_ms_lib_tool" = "xyes"])
+AM_CONDITIONAL([USE_EXPORT_FILE], [test "x$use_expfile" = "xyes"])
 
-# set GCC options
-# use '-fno-strict-aliasing', but only if the compiler
-# and linker can take it
-AX_CHECK_LINK_FLAG([-fno-strict-aliasing],
-  [AX_APPEND_COMPILE_FLAGS([-fno-strict-aliasing])])
+dnl gethostbyname() is not really needed
+dnl AC_SEARCH_LIBS([gethostbyname], [nsl])
+MHD_FIND_LIB([socket],
+  [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_SOCKLIB_H
+#include <sockLib.h>
+#endif
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#include <winsock2.h>
+#endif
+  ]],
+  [(void)socket(0, 0, 0);],
+  [socket ws2_32 xnet],
+  [
+    AS_VAR_IF([[mhd_cv_find_lib_socket]],[["none required"]], [],
+      [
+       MHD_LIBDEPS_PKGCFG="${mhd_cv_find_lib_socket} $MHD_LIBDEPS_PKGCFG"
+      ]
+    )
+  ],
+  [AC_MSG_ERROR([[cannot find header or library required for function socket()]])]
+)
+
+MHD_CHECK_SOCKET_SHUTDOWN_TRIGGER([AC_DEFINE([HAVE_LISTEN_SHUTDOWN],[1],[can use shutdown on listen sockets])])
+AM_CONDITIONAL([HAVE_LISTEN_SHUTDOWN], [test "x$mhd_cv_host_shtdwn_trgr_select" = "xyes"])
+
+MHD_CHECK_FUNC([writev],
+  [[#include <sys/uio.h>]],
+  [[
+    struct iovec iov[2];
+    char some_str[4] = "OK\n";
+    iov[0].iov_base = (void *) some_str;
+    iov[0].iov_len = 3;
+    i][f (0 > writev(1, iov, 1))
+      return 2;
+  ]]
+)
+MHD_FIND_LIB([sendmsg],
+  [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_SOCKLIB_H
+#include <sockLib.h>
+#endif
+#ifdef HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+  ]],
+  [[
+    struct msghdr msg;
+    struct iovec iov;
+    unsigned int i;
+    char some_str[5] = "test";
+
+    iov.iov_base = (void*)some_str;
+    iov.iov_len = 4;
+
+    for (i = 0; i < (unsigned int) sizeof(msg); i++)
+    {
+      *(((unsigned char *)&msg) + i) = 0;
+    }
+    msg.msg_iov = &iov;
+    msg.msg_iovlen = 1;
+
+    i][f (0 > sendmsg(1, &msg, 0))
+      return -1;
+  ]],
+  [socket],
+  [
+    AC_DEFINE([HAVE_SENDMSG],[1],[Define to '1' if your have sendmsg() function])
+    AS_VAR_IF([[mhd_cv_find_lib_sendmsg]],[["none required"]], [],
+      [
+        MHD_LIBDEPS_PKGCFG="${mhd_cv_find_lib_sendmsg} $MHD_LIBDEPS_PKGCFG"
+      ]
+    )
+  ],[],
+  [MHD_LIBDEPS]
+)
 
 AC_C_BIGENDIAN
+AC_C_VARARRAYS
+
+AC_CACHE_CHECK([[whether __func__ magic-macro is available]],
+  [[mhd_cv_macro___func___avail]], [dnl
+  AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stddef.h>]],[[const char *funcname = __func__ ; if (NULL == funcname) return 1;]])],
+    [[mhd_cv_macro___func___avail="yes"]],[[mhd_cv_macro___func___avail="no"]])
+])
+AS_VAR_IF([mhd_cv_macro___func___avail], ["yes"],
+  [AC_DEFINE([HAVE___FUNC__], [1], [Define to 1 if your compiler supports __func__ magic-macro.])],
+  [
+    AC_CACHE_CHECK([[whether __FUNCTION__ magic-macro is available]],
+      [[mhd_cv_macro___function___avail]], [dnl
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stddef.h>]],[[const char *funcname = __FUNCTION__ ; if (NULL == funcname) return 1;]])],
+        [[mhd_cv_macro___function___avail="yes"]],[[mhd_cv_macro___function___avail="no"]])
+    ])
+    AS_VAR_IF([mhd_cv_macro___function___avail], ["yes"],
+      [AC_DEFINE([HAVE___FUNCTION__], [1], [Define to 1 if your compiler supports __FUNCTION__ magic-macro.])],
+      [
+        AC_CACHE_CHECK([[whether __PRETTY_FUNCTION__ magic-macro is available]],
+          [[mhd_cv_macro___pretty_function___avail]], [dnl
+          AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stddef.h>]],[[const char *funcname = __PRETTY_FUNCTION__ ; if (NULL == funcname) return 1;]])],
+            [[mhd_cv_macro___pretty_function___avail="yes"]],[[mhd_cv_macro___pretty_function___avail="no"]])
+        ])
+        AS_VAR_IF([mhd_cv_macro___pretty_function___avail], ["yes"],
+          [AC_DEFINE([HAVE___PRETTY_FUNCTION__], [1], [Define to 1 if your compiler supports __PRETTY_FUNCTION__ magic-macro.])],
+        )
+      ]
+    )
+  ]
+)
+AC_CACHE_CHECK([[whether __builtin_bswap32() is available]],
+  [[mhd_cv_func___builtin_bswap32_avail]], [dnl
+  AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include<stdint.h>]], [[uint32_t a = 1; uint32_t b = __builtin_bswap32(a); a = b; (void) a;]])],
+    [[mhd_cv_func___builtin_bswap32_avail="yes"]],[[mhd_cv_func___builtin_bswap32_avail="no"]])
+])
+AS_IF([[test "x$mhd_cv_func___builtin_bswap32_avail" = "xyes"]],
+  [AC_DEFINE([[MHD_HAVE___BUILTIN_BSWAP32]], [[1]], [Define to 1 if you have __builtin_bswap32() builtin function])])
+AC_CACHE_CHECK([[whether __builtin_bswap64() is available]],
+  [[mhd_cv_func___builtin_bswap64_avail]], [dnl
+  AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include<stdint.h>]], [[uint64_t a = 1; uint64_t b = __builtin_bswap64(a); a = b; (void) a;]])],
+    [[mhd_cv_func___builtin_bswap64_avail="yes"]], [[mhd_cv_func___builtin_bswap64_avail="no"]])
+])
+AS_IF([[test "x$mhd_cv_func___builtin_bswap64_avail" = "xyes"]],
+  [AC_DEFINE([[MHD_HAVE___BUILTIN_BSWAP64]], [[1]], [Define to 1 if you have __builtin_bswap64() builtin function])])
 
 AC_CHECK_PROG([HAVE_CURL_BINARY],[curl],[yes],[no])
 AM_CONDITIONAL([HAVE_CURL_BINARY],[test "x$HAVE_CURL_BINARY" = "xyes"])
@@ -276,35 +1745,103 @@
 test "x$enable_examples" = "xno" || enable_examples=yes
 AM_CONDITIONAL([BUILD_EXAMPLES], [test "x$enable_examples" = "xyes"])
 
+AC_ARG_ENABLE([[heavy-tests]],
+  [AS_HELP_STRING([[--enable-heavy-tests[=SCOPE]]], [use SCOPE of heavy tests in test-suite. WARNING:]
+  [a dedicated host with minimal number of background processes and no network]
+  [activity is recommended to enable. (basic, full)])], [],
+    [enable_heavy_tests=no])
+use_heavy_tests="no"
+use_vheavy_tests="no"
+use_heavy_tests_MSG="no"
+AS_CASE([${enable_heavy_tests}],
+  [yes|basic],
+  [
+  	enable_heavy_tests="basic"
+    use_heavy_tests="yes"
+    use_vheavy_tests="no"
+    use_heavy_tests_MSG="yes, basic heavy tests (a dedicated host is recommended)"
+  ],
+  [all|full],
+  [
+  	enable_heavy_tests="full"
+    use_heavy_tests="yes"
+    use_vheavy_tests="yes"
+    use_heavy_tests_MSG="yes, full set of heavy tests (a dedicated host is recommended)"
+  ],
+  [no],
+  [
+    use_heavy_tests="no"
+    use_vheavy_tests="no"
+    use_heavy_tests_MSG="no"
+  ],
+  [AC_MSG_ERROR([[Unknown parameter value: --enable-heavy-tests=${enable_heavy_tests}]])]
+)
+AS_VAR_IF([use_heavy_tests], ["yes"],
+  [
+    HEAVY_TESTS_NOTPARALLEL='.NOTPARALLEL:'
+    AC_DEFINE([_MHD_HEAVY_TESTS], [1], [Define to 1 to enable "heavy" test paths.])
+    AS_VAR_IF([use_vheavy_tests], ["yes"],
+      [AC_DEFINE([_MHD_VHEAVY_TESTS], [1], [Define to 1 to enable "very heavy" test paths.])]
+    )
+  ],
+  [
+    HEAVY_TESTS_NOTPARALLEL=" "
+  ]
+)
+AM_CONDITIONAL([HEAVY_TESTS],[test "x$use_heavy_tests" = "xyes"])
+AM_CONDITIONAL([TESTS_STRESS_OS],[false])
+
 AC_ARG_ENABLE([[poll]],
   [AS_HELP_STRING([[--enable-poll[=ARG]]], [enable poll support (yes, no, auto) [auto]])],
     [enable_poll=${enableval}],
     [enable_poll='auto']
   )
 
-if test "$enable_poll" != "no"; then
-  if test "$os_is_native_w32" != "yes"; then
-    AC_CHECK_HEADERS([poll.h],
+AS_IF([test "$enable_poll" != "no"],
+  [
+    AS_IF([test "$os_is_native_w32" != "yes"],
       [
-        AC_CHECK_FUNCS([poll], [have_poll='yes'], [have_poll='no'])
-      ])
-  else
-    AC_MSG_CHECKING([for WSAPoll()])
-    AC_LINK_IFELSE([
-      AC_LANG_PROGRAM([[#include <winsock2.h>]], [[
-WSAPOLLFD fda[2];
-WSAPoll(fda, 2, 0);]])],
-        [
-          have_poll='yes'
-          AC_DEFINE([HAVE_POLL],[1])
-        ], [have_poll='no'])
-    AC_MSG_RESULT([$have_poll])
-  fi
-  if test "$enable_poll" = "yes" && test "$have_poll" != "yes"; then
-    AC_MSG_ERROR([[Support for poll was explicitly requested but cannot be enabled on this platform.]])
-  fi
-  enable_poll="$have_poll"
-fi
+        AC_CHECK_HEADERS([poll.h],
+          [
+            MHD_CHECK_FUNC([poll],
+              [[
+#include <poll.h>
+              ]],
+              [[
+  struct pollfd fds[2];
+
+  fds[0].fd = 0;
+  fds[0].events = POLLIN;
+  if (0 > poll(fds, 1, 0))
+    return 2;
+              ]],
+              [have_poll='yes'], [have_poll='no']
+            )
+          ], [], [AC_INCLUDES_DEFAULT]
+        )
+      ],
+      [
+        MHD_CHECK_FUNC([WSAPoll],
+          [[
+#include <winsock2.h>
+          ]],
+          [[
+  WSAPOLLFD fda[2];
+  WSAPoll(fda, 2, 0);
+          ]],
+          [
+            have_poll='yes'
+            AC_DEFINE([HAVE_POLL],[1])
+          ],
+          [have_poll='no']
+        )
+      ]
+    )
+    AS_IF([test "$enable_poll" = "yes" && test "$have_poll" != "yes"],
+      [AC_MSG_ERROR([[Support for poll was explicitly requested but cannot be enabled on this platform.]])])
+    enable_poll="$have_poll"
+  ]
+)
 
 AC_ARG_ENABLE([[epoll]],
   [AS_HELP_STRING([[--enable-epoll[=ARG]]], [enable epoll support (yes, no, auto) [auto]])],
@@ -312,414 +1849,1366 @@
     [enable_epoll='auto']
   )
 
-if test "$enable_epoll" != "no"; then
-  AX_HAVE_EPOLL
-  if test "${ax_cv_have_epoll}" = "yes"; then
-    AC_DEFINE([EPOLL_SUPPORT],[1],[define to 1 to enable epoll support])
-    enable_epoll='yes'
-  else
-    AC_DEFINE([EPOLL_SUPPORT],[0],[define to 0 to disable epoll support])
-    if test "$enable_epoll" = "yes"; then
-      AC_MSG_ERROR([[Support for epoll was explicitly requested but cannot be enabled on this platform.]])
-    fi
-    enable_epoll='no'
-  fi
-fi
-
-if test "x$enable_epoll" = "xyes"; then
-  AC_CACHE_CHECK([for epoll_create1()], [mhd_cv_have_epoll_create1], [
-    AC_LINK_IFELSE([
-      AC_LANG_PROGRAM([[#include <sys/epoll.h>]], [[
-int fd;
-fd = epoll_create1(EPOLL_CLOEXEC);]])],
-      [mhd_cv_have_epoll_create1=yes],
-      [mhd_cv_have_epoll_create1=no])])
-  AS_IF([test "x$mhd_cv_have_epoll_create1" = "xyes"],[
-    AC_DEFINE([[HAVE_EPOLL_CREATE1]], [[1]], [Define if you have epoll_create1 function.])])
-fi
-
-if test "x$HAVE_POSIX_THREADS" = "xyes"; then
-  # Check for pthread_setname_np()
-  SAVE_LIBS="$LIBS"
-  SAVE_CFLAGS="$CFLAGS"
-  LIBS="$PTHREAD_LIBS $LIBS"
-  CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-  AC_MSG_CHECKING([[for pthread_setname_np]])
-  AC_LINK_IFELSE(
-    [AC_LANG_PROGRAM([[#include <pthread.h>]], [[  pthread_setname_np(pthread_self(), "name")]])],
-    [AC_DEFINE([[HAVE_PTHREAD_SETNAME_NP]], [[1]], [Define if you have pthread_setname_np function.])
-     AC_MSG_RESULT([[yes]])],
-    [AC_MSG_RESULT([[no]])] )
-  LIBS="$SAVE_LIBS"
-  CFLAGS="$SAVE_CFLAGS"
-fi
-
-# Check for headers that are ALWAYS required
-AC_CHECK_HEADERS([fcntl.h math.h errno.h limits.h stdio.h locale.h sys/stat.h sys/types.h pthread.h],,AC_MSG_ERROR([Compiling libmicrohttpd requires standard UNIX headers files]))
-
-# Check for optional headers
-AC_CHECK_HEADERS([sys/types.h sys/time.h sys/msg.h netdb.h netinet/in.h netinet/tcp.h time.h sys/socket.h sys/mman.h arpa/inet.h sys/select.h search.h])
-AM_CONDITIONAL([HAVE_TSEARCH], [test "x$ac_cv_header_search_h" = "xyes"])
-
-AC_CHECK_MEMBER([struct sockaddr_in.sin_len],
-   [ AC_DEFINE(HAVE_SOCKADDR_IN_SIN_LEN, 1, [Do we have sockaddr_in.sin_len?])
-   ],
-   [],
-   [
-    #ifdef HAVE_SYS_TYPES_H
-      #include <sys/types.h>
-    #endif
-    #ifdef HAVE_SYS_SOCKET_H
-      #include <sys/socket.h>
-    #endif
-    #ifdef HAVE_NETINET_IN_H
-      #include <netinet/in.h>
-    #endif
-   ])
-
-
-# Check for pipe/socketpair signaling
-AC_MSG_CHECKING([[whether to enable signaling by socketpair]])
-
-AC_ARG_ENABLE([[socketpair]],
-	[AS_HELP_STRING([[--enable-socketpair[=ARG]]], [disable internal singalling by pipes and use socket pair instead (yes, no, try) [no]])], ,
-	[AS_IF([[test "x$os_is_windows" = "xyes"]], [enable_socketpair=yes], [enable_socketpair=no])]
-  )
-
-AS_IF(
-       [[test "x$enable_socketpair" != "xno"]],
-         [AS_IF([[test "x$os_is_windows" = "xyes"]],
-           [ AC_MSG_RESULT([[yes, forced on W32]]) ],
-           [ AC_LINK_IFELSE(
-             [ AC_LANG_PROGRAM([[
-				#ifdef HAVE_SYS_TYPES_H
-				#include <sys/types.h>
-				#endif
-				#ifdef HAVE_SYS_SOCKET_H
-				#include <sys/socket.h>
-				#endif
-				]],[[
-				  int sv[2];
-				  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 1
-				]])
-             ],
-             [ AC_MSG_RESULT([[yes, socketpair in available]]) ],
-             [ AC_MSG_RESULT([[no, socketpair in not available]])
-              AS_IF([[test "x$enable_socketpair" = "xyes"]], [ AC_MSG_ERROR([[socketpair signalling cannot be enabled.]]) ])
-             ]
-             )
-           ]
-          )
-         ],
-       [
-        AC_MSG_RESULT([[no]])
-        AS_IF([[test "x$os_is_windows" = "xyes"]], [ AC_MSG_ERROR([[socketpair must be enabled on W32]]) ])
-       ]
-     )
-if test "x$enable_socketpair" = "xyes"; then
-	AC_DEFINE([[MHD_DONT_USE_PIPES]], [[1]], [Define to use pair of sockets instead of pipes for signaling])
-fi
-
-AC_CHECK_FUNCS_ONCE([memmem accept4])
-AC_MSG_CHECKING([[for gmtime_s]])
-AC_LINK_IFELSE(
-  [AC_LANG_PROGRAM(
-    [[ #include <time.h>]], [[struct tm now; time_t t; time (&t); gmtime_s (&now, &t)]])
-  ],
+AS_IF([test "$enable_epoll" != "no"],
   [
-    AC_DEFINE([HAVE_GMTIME_S], [1], [Define to 1 if you have `gmtime_s' function (only for W32).])
-    AC_MSG_RESULT([[yes]])
-  ],
-  [AC_MSG_RESULT([[no]])
-  ])
+    AX_HAVE_EPOLL
+    AS_IF([test "${ax_cv_have_epoll}" = "yes"],
+      [
+        AC_DEFINE([[EPOLL_SUPPORT]],[[1]],[Define to 1 to enable epoll support])
+        enable_epoll='yes'
+      ],
+      [
+        AS_IF([test "$enable_epoll" = "yes"],
+          [AC_MSG_ERROR([[Support for epoll was explicitly requested but cannot be enabled on this platform.]])]
+        )
+        enable_epoll='no'
+      ]
+    )
+  ]
+)
 
+AM_CONDITIONAL([MHD_HAVE_EPOLL], [[test "x$enable_epoll" = xyes]])
 
-AC_CHECK_DECLS([SOCK_NONBLOCK], [AC_DEFINE([HAVE_SOCK_NONBLOCK], [1], [SOCK_NONBLOCK is defined in a socket header])], [],
-                   [
-                    #if defined HAVE_SYS_TYPES_H
-                    #  include <sys/types.h>
-                    #endif
-                    #if defined HAVE_SYS_SOCKET_H
-                    #  include <sys/socket.h>
-                    #elif defined HAVE_WINSOCK2_H
-                    #  include <winsock2.h>
-                    #endif
-                   ])
+AS_IF([test "x$enable_epoll" = "xyes"],
+  [
+    MHD_CHECK_FUNC([epoll_create1],
+      [[
+#include <sys/epoll.h>
+      ]],
+      [[
+  i][f (0 > epoll_create1(EPOLL_CLOEXEC))
+    return 3;
+      ]]
+    )
+  ]
+)
 
-
-AC_SEARCH_LIBS([clock_gettime], [rt], [
-				AC_DEFINE(HAVE_CLOCK_GETTIME, 1, [Have clock_gettime])
-])
-
-# IPv6
-AC_MSG_CHECKING(for IPv6)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
-#include <stdio.h>
-#if HAVE_NETINET_IN_H
-#include <netinet/in.h>
+AC_CACHE_CHECK([for supported 'noreturn' keyword], [mhd_cv_decl_noreturn],
+  [
+    mhd_cv_decl_noreturn="none"
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS} ${errattr_CFLAGS}"
+    for decl_noret in '_Noreturn' '__attribute__((__noreturn__))' '__declspec(noreturn)'
+    do
+      AC_LINK_IFELSE([AC_LANG_SOURCE(
+          [[
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
 #endif
-#if HAVE_SYS_SOCKET_H
+
+${decl_noret} static void myexitfunc(int code)
+{
+#ifdef HAVE_STDLIB_H
+  exit (code);
+#else
+  (void)code;
+#endif
+}
+
+int main (int argc, char *const *argv)
+{
+  (void) argv;
+  if (argc > 2)
+    myexitfunc (2);
+  return 0;
+}
+          ]]
+        )], [mhd_cv_decl_noreturn="${decl_noret}"]
+      )
+      AS_IF([test "x${mhd_cv_decl_noreturn}" != "xnone"], [break])
+    done
+   CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+  ]
+)
+AS_VAR_IF([mhd_cv_decl_noreturn], ["none"],
+  [AC_DEFINE([_MHD_NORETURN], [], [Define to supported 'noreturn' function declaration])],
+  [AC_DEFINE_UNQUOTED([_MHD_NORETURN], [${mhd_cv_decl_noreturn}], [Define to supported 'noreturn' function declaration])]
+)
+
+# Check for types sizes
+# Types sizes are used as an indirect indication of maximum allowed values for types
+# which is used to exclude by preprocessor some compiler checks for values clips
+# Assuming no staffing or uniform staffing for integer types
+AC_CACHE_CHECK([size of tv_sec member of struct timeval], [mhd_cv_size_timeval_tv_sec],
+  [
+    AC_COMPUTE_INT([mhd_cv_size_timeval_tv_sec], [((long int)sizeof(test_var.tv_sec))],
+      [[
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+#if HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+struct timeval test_var;
+      ]],
+      [
+        # The size is used only to exclude additional checks/comparison in code
+        # to avoid compiler warnings. With larger size MHD code will use
+        # additional checks which ensure that value will fit but it may produce
+        # a harmless compiler warning.
+        AC_MSG_WARN([The size cannot be determined, assuming 8.])
+        mhd_cv_size_timeval_tv_sec=8
+      ]
+    )
+  ]
+)
+AC_DEFINE_UNQUOTED([SIZEOF_STRUCT_TIMEVAL_TV_SEC], [$mhd_cv_size_timeval_tv_sec],
+  [The size of `tv_sec' member of `struct timeval', as computed by sizeof])
+AC_CHECK_SIZEOF([int64_t], [], [[#include <stdint.h>]])
+AC_CHECK_SIZEOF([uint64_t], [], [[#include <stdint.h>]])
+AC_CHECK_SIZEOF([int], [], [[#include <stdint.h>]])
+AC_CHECK_SIZEOF([unsigned int], [], [[#include <stdint.h>]])
+AC_CHECK_SIZEOF([unsigned long long], [], [[#include <stdint.h>]])
+AC_CHECK_SIZEOF([size_t], [],
+  [[
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif /* HAVE_STDDEF_H */
+#include <stdio.h>
+  ]]
+)
+
+AC_CHECK_HEADERS([dlfcn.h],[have_tlsplugin=yes],[have_tlsplugin=no], [AC_INCLUDES_DEFAULT])
+AM_CONDITIONAL([MHD_HAVE_TLS_PLUGIN], [[test "x$have_tlsplugin" = xyes]])
+
+AC_CHECK_HEADERS([zlib.h],[have_zlib=yes],[have_zlib=no], [AC_INCLUDES_DEFAULT])
+AM_CONDITIONAL([HAVE_ZLIB], [[test "x$have_zlib" = xyes]])
+
+# Check for generic functions
+MHD_CHECK_FUNC([random],
+  [
+AC_INCLUDES_DEFAULT
+[#include <stdlib.h>
+  ]],
+  [[long int r = random(); (void)r;]],
+  [],
+  [
+    MHD_CHECK_FUNC([rand],
+      [
+AC_INCLUDES_DEFAULT
+[#include <stdlib.h>
+      ]],
+      [[int r = rand(); (void)r;]],
+	)
+  ]
+)
+
+AC_CHECK_MEMBERS([struct sockaddr_in.sin_len, struct sockaddr_in6.sin6_len,
+                  struct sockaddr_storage.ss_len],
+   [], [],
+   [
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-#if HAVE_WINSOCK2_H
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+   ])
+
+MHD_CHECK_LINK_RUN([[f][or working getsockname()]],[[mhd_cv_getsockname_usable]],
+  [[mhd_cv_getsockname_usable='assuming yes']],
+  [
+    AC_LANG_SOURCE(
+      [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
 #include <winsock2.h>
 #endif
-#if HAVE_WS2TCPIP_H
+#ifdef HAVE_WS2TCPIP_H
 #include <ws2tcpip.h>
 #endif
-]], [[
-int af=AF_INET6;
-int pf=PF_INET6;
-struct sockaddr_in6 sa;
-printf("%d %d %p\n", af, pf, &sa);
-]])],[
-have_inet6=yes;
-AC_DEFINE([HAVE_INET6], [1], [Provides IPv6 headers])
-],[
-have_inet6=no
-])
-AC_MSG_RESULT($have_inet6)
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
 
-# TCP_CORK and TCP_NOPUSH
-AC_CHECK_DECLS([TCP_CORK, TCP_NOPUSH], [], [], [[#include <netinet/tcp.h>]])
+
+static void zr_mem(void *ptr, socklen_t size)
+{ char *mem = ptr; while(size--) {mem[0] = 0; mem++;} }
+
+int main(void)
+{
+  const socklen_t c_addr_size = (socklen_t)sizeof(struct sockaddr_in);
+  struct sockaddr_in sa;
+  socklen_t addr_size;
+  int ret = 1;
+#if !defined(_WIN32) || defined(__CYGWIN__)
+  int sckt;
+  const int invld_sckt = -1;
+#else
+  SOCKET sckt;
+  const SOCKET invld_sckt = INVALID_SOCKET;
+  WSADATA wsa_data;
+
+  if (0 != WSAStartup(MAKEWORD(2, 2), &wsa_data) || MAKEWORD(2, 2) != wsa_data.wVersion)
+    return 20;
+#endif
+
+  sckt = socket (PF_INET, SOCK_STREAM, 0);
+  if (invld_sckt != sckt)
+  {
+    zr_mem(&sa, c_addr_size);
+    sa.sin_family = AF_INET;
+#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+    sa.sin_len = c_addr_size;
+#endif
+    if (0 == bind (sckt, (struct sockaddr *)&sa, c_addr_size))
+    {
+      if (0 == listen (sckt, 1))
+      {
+        addr_size = c_addr_size;
+        if (0 == getsockname (sckt, (struct sockaddr  *)&sa, &addr_size))
+        {
+          if (c_addr_size >= addr_size)
+          {
+            if (0 != ntohs(sa.sin_port))
+            { ret = 0;
+            } else ret = 7;
+          } else ret = 6;
+        } else ret = 5;
+      } else ret = 4;
+    } else ret = 3;
+  } else ret = 2;
+#if !defined(_WIN32) || defined(__CYGWIN__)
+  close (sckt);
+#else
+  closesocket (sckt);
+  WSACleanup();
+#endif
+  return ret;
+}
+      ]]
+    )
+  ],
+  [AC_DEFINE([[MHD_USE_GETSOCKNAME]], [[1]], [Define if you have usable `getsockname' function.])]
+)
+
+AC_CACHE_CHECK([for usable PAGESIZE macro], [mhd_cv_macro_pagesize_usable],
+  [
+    AC_LINK_IFELSE(
+      [
+        AC_LANG_PROGRAM(
+          [[
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifndef PAGESIZE
+#error No PAGESIZE macro defined
+choke me now
+#endif
+          ]],
+          [[
+            long pgsz = PAGESIZE + 0;
+            if (1 > pgsz) return 1;
+          ]]
+        )
+      ],
+      [[mhd_cv_macro_pagesize_usable="yes"]], [[mhd_cv_macro_pagesize_usable="no"]]
+    )
+  ]
+)
+AS_VAR_IF([[mhd_cv_macro_pagesize_usable]], [["yes"]],
+  [
+    AC_DEFINE([[MHD_USE_PAGESIZE_MACRO]],[[1]],[Define if you have usable PAGESIZE macro])
+    AC_CACHE_CHECK([whether PAGESIZE macro could be used for static init], [mhd_cv_macro_pagesize_usable_static],
+      [
+        AC_LINK_IFELSE(
+          [
+            AC_LANG_PROGRAM(
+              [[
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifndef PAGESIZE
+#error No PAGESIZE macro defined
+choke me now
+#endif
+static long ac_pgsz = PAGESIZE + 0;
+              ]],
+              [[
+                if (1 > ac_pgsz) return 1;
+              ]]
+            )
+          ],
+          [[mhd_cv_macro_pagesize_usable_static="yes"]], [[mhd_cv_macro_pagesize_usable_static="no"]]
+        )
+      ]
+    )
+    AS_VAR_IF([[mhd_cv_macro_pagesize_usable_static]], [["yes"]],
+      [AC_DEFINE([[MHD_USE_PAGESIZE_MACRO_STATIC]],[[1]],[Define if you have PAGESIZE macro usable for static init])]
+    )
+  ],
+  [
+    AC_CACHE_CHECK([for usable PAGE_SIZE macro], [mhd_cv_macro_page_size_usable],
+      [
+        AC_LINK_IFELSE(
+          [
+            AC_LANG_PROGRAM(
+              [[
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifndef PAGE_SIZE
+#error No PAGE_SIZE macro defined
+choke me now
+#endif
+              ]],
+              [[
+                long pgsz = PAGE_SIZE + 0;
+                if (1 > pgsz) return 1;
+              ]]
+            )
+          ],
+          [[mhd_cv_macro_page_size_usable="yes"]], [[mhd_cv_macro_page_size_usable="no"]]
+        )
+      ]
+    )
+    AS_VAR_IF([[mhd_cv_macro_page_size_usable]], [["yes"]],
+      [
+        AC_DEFINE([[MHD_USE_PAGE_SIZE_MACRO]],[[1]],[Define if you have usable PAGE_SIZE macro])
+        AC_CACHE_CHECK([whether PAGE_SIZE macro could be used for static init], [mhd_cv_macro_page_size_usable_static],
+          [
+            AC_LINK_IFELSE(
+              [
+                AC_LANG_PROGRAM(
+                  [[
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifndef PAGE_SIZE
+#error No PAGE_SIZE macro defined
+choke me now
+#endif
+static long ac_pgsz = PAGE_SIZE + 0;
+                  ]],
+                  [[
+                    if (1 > ac_pgsz) return 1;
+                  ]]
+                )
+              ],
+              [[mhd_cv_macro_page_size_usable_static="yes"]], [[mhd_cv_macro_page_size_usable_static="no"]]
+            )
+          ]
+        )
+        AS_VAR_IF([[mhd_cv_macro_page_size_usable_static]], [["yes"]],
+          [AC_DEFINE([[MHD_USE_PAGE_SIZE_MACRO_STATIC]],[[1]],[Define if you have PAGE_SIZE macro usable for static init])]
+        )
+      ]
+    )
+  ]
+)
+
+# Check for inter-thread signaling type
+AC_ARG_ENABLE([[itc]],
+  [AS_HELP_STRING([[--enable-itc=TYPE]], [use TYPE of inter-thread communication (pipe, socketpair, eventfd) [auto]])], [],
+  [[enable_itc='auto']]
+)
+
+AS_CASE([[$enable_itc]],
+  [[pipe]], [[:]],
+  [[socketpair]], [[:]],
+  [[eventfd]], [[:]],
+  [[auto]], [AS_VAR_IF([[os_is_windows]], [["yes"]], [[enable_itc='socketpair']])],
+  [[eventFD]], [[enable_itc='eventfd']],
+  [[socket]], [[enable_itc='socketpair']],
+  [[no]], [AC_MSG_ERROR([[inter-thread communication cannot be disabled]])],
+    [AC_MSG_ERROR([[unrecognized type "$enable_itc" of inter-thread communication specified by "--enable-itc=$enable_itc"]])]
+)
+AS_UNSET([[use_itc]])
+
+AS_IF([[test "x$enable_itc" = "xeventfd" || test "x$enable_itc" = "xauto"]],
+  [
+    MHD_CHECK_LINK_RUN([[f][or working eventfd(2)]],[[mhd_cv_eventfd_usable]],[[mhd_cv_eventfd_usable='assuming no']],
+      [
+        AC_LANG_SOURCE([[
+#include <sys/eventfd.h>
+#include <unistd.h>
+
+int main(void)
+{
+  unsigned char buf[8];
+  int ret;
+  int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+  if (0 > efd)
+    return 2;
+  ret = 0;
+  buf[3] = 1;
+  if (8 != write(efd, buf, 8))
+    ret = 3;
+  else
+  {
+    if (8 != read(efd, buf, 8))
+      ret = 4;
+  }
+  close(efd);
+  return ret;
+}
+          ]]
+        )
+      ],
+      [
+        use_itc='eventfd'
+        enable_itc="$use_itc"
+        AC_DEFINE([[_MHD_ITC_EVENTFD]], [[1]], [Define to use eventFD for inter-thread communication])
+      ],
+      [
+        AS_VAR_IF([[enable_itc]], [["eventfd"]], [AC_MSG_ERROR([[eventfd(2) is not usable, consider using other type of inter-thread communication]])])
+      ]
+    )
+    AS_VAR_IF([mhd_cv_eventfd_usable],["assuming no"],
+      [AC_MSG_WARN([if you have 'eventfd' support enabled on your target system consider overriding test result by "mhd_cv_eventfd_usable=yes" configure parameter])]
+    )
+  ]
+)
+
+AS_IF([[test "x$enable_itc" = "xpipe" || test "x$enable_itc" = "xauto"]], [
+  AS_VAR_IF([[os_is_native_w32]], [["yes"]], [], [
+    AC_CACHE_CHECK([[whether pipe(3) is usable]], [[mhd_cv_pipe_usable]], [
+      AC_LINK_IFELSE([
+        AC_LANG_PROGRAM([
+AC_INCLUDES_DEFAULT
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+        ], [[
+          int arr[2];
+          int res;
+          res = pipe(arr);
+          if (res != 0) return 33;
+          close (arr[0]);
+          close (arr[1]);
+        ]])
+      ], [[mhd_cv_pipe_usable='yes']], [[mhd_cv_pipe_usable='no']])
+    ])
+    AS_VAR_IF([[mhd_cv_pipe_usable]], [["yes"]], [
+      use_itc='pipe'
+      enable_itc="$use_itc"
+      AC_DEFINE([[_MHD_ITC_PIPE]], [[1]], [Define to use pipe for inter-thread communication])
+      MHD_CHECK_LINK_RUN([[whether pipe2(2) is usable]],[[mhd_cv_pipe2_usable]],
+        [
+          # Cross-compiling
+          AS_CASE([${host_os}], [kfreebsd*-gnu], [[mhd_cv_pipe2_usable='assuming no']],
+            [[mhd_cv_pipe2_usable='assuming yes']])
+        ],
+        [
+          AC_LANG_PROGRAM([
+AC_INCLUDES_DEFAULT
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+            ], [[
+              int arr[2];
+              int res;
+              res = pipe2(arr, O_CLOEXEC | O_NONBLOCK);
+              if (res != 0) return 33;
+              close (arr[0]);
+              close (arr[1]);
+            ]]
+          )
+        ],
+        [AC_DEFINE([[HAVE_PIPE2_FUNC]], [[1]], [Define if you have usable pipe2(2) function])]
+      )
+    ], [
+      AS_VAR_IF([[enable_itc]], [["pipe"]], [AC_MSG_ERROR([[pipe(3) is not usable, consider using other type of inter-thread communication]])])
+    ])
+  ])
+])
+
+AS_IF([[test "x$enable_itc" = "xsocketpair" || test "x$enable_itc" = "xauto"]], [
+  AS_VAR_IF([[os_is_native_w32]], [["yes"]], [[mhd_cv_socketpair_usable='yes']], [
+    AC_CACHE_CHECK([[whether socketpair(3) is usable]], [[mhd_cv_socketpair_usable]], [
+      AC_LINK_IFELSE([
+        AC_LANG_PROGRAM([
+AC_INCLUDES_DEFAULT
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+        ], [[
+          int arr[2];
+          int res;
+#if defined(AF_LOCAL)
+          res = socketpair(AF_LOCAL, SOCK_STREAM, 0, arr);
+#elif defined(AF_UNIX)
+          res = socketpair(AF_UNIX, SOCK_STREAM, 0, arr);
+#else
+#error AF_LOCAL and AF_UNIX are both undefined
+          choke me now;
+#endif
+          if (res != 0) return 1
+        ]])
+      ], [[mhd_cv_socketpair_usable='yes']], [[mhd_cv_socketpair_usable='no']])
+    ])
+  ])
+  AS_VAR_IF([[mhd_cv_socketpair_usable]], [["yes"]], [
+    use_itc='socketpair'
+    enable_itc="$use_itc"
+    AC_DEFINE([[_MHD_ITC_SOCKETPAIR]], [[1]], [Define to use socketpair for inter-thread communication])
+  ], [
+    AS_VAR_IF([[enable_itc]], [["socketpair"]], [AC_MSG_ERROR([[socketpair(3) is not usable, consider using other type of inter-thread communication]])])
+  ])
+])
+
+AS_IF([[test -z "$use_itc"]], [AC_MSG_ERROR([[cannot find usable type of inter-thread communication]])])
+
+
+MHD_CHECK_FUNC([accept4],
+  [[
+#if defined(HAVE_SYS_TYPES_H)
+#  include <sys/types.h>
+#endif
+#include <sys/socket.h>
+  ]],
+  [[
+  struct sockaddr sk_addr;
+  socklen_t addr_size;
+  i][f (0 > accept4(0, &sk_addr, &addr_size, 0))
+    return 3;
+  ]]
+)
+MHD_CHECK_FUNC([gmtime_r],
+  [[
+#if defined(HAVE_SYS_TYPES_H)
+#  include <sys/types.h>
+#endif
+#include <time.h>
+  ]],
+  [[
+  time_t timer = (time_t) 0;
+  struct tm res;
+
+  i][f (&res != gmtime_r(&timer, &res))
+    return 3;
+  ]]
+)
+MHD_CHECK_FUNC([memmem],
+  [[
+#if defined(HAVE_STDDEF_H)
+#  include <stddef.h>
+#elif defined(HAVE_STDLIB_H)
+#  include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#include <string.h>
+  ]],
+  [[
+  const char *haystack = "abc";
+  size_t hslen = 3;
+  const char *needle = "b";
+  size_t needlelen = 1;
+
+  i][f ((haystack + 1) != memmem(haystack, hslen, needle, needlelen))
+    return 3;
+  ]]
+)
+MHD_CHECK_FUNC([snprintf],
+  [[
+#include <stdio.h>
+  ]],
+  [[
+  char buf[2];
+
+  i][f (1 != snprintf(buf, 2, "a"))
+    return 3;
+  /* Do not use the next check to avoid compiler warning */
+  /* i][f (4 != snprintf(buf, 2, "abcd"))
+    return 4; */
+  ]]
+)
+AC_CHECK_DECL([gmtime_s],
+  [
+    AC_MSG_CHECKING([[whether gmtime_s is in C11 form]])
+    AC_LINK_IFELSE(
+        [ AC_LANG_PROGRAM(
+          [[
+#define __STDC_WANT_LIB_EXT1__ 1
+#include <time.h>
+#ifdef __cplusplus
+extern "C"
+#endif
+             struct tm* gmtime_s(const time_t* time, struct tm* result);
+           ]], [[
+             struct tm res;
+             time_t t;
+             gmtime_s (&t, &res);
+          ]])
+        ],
+        [
+          AC_DEFINE([HAVE_C11_GMTIME_S], [1], [Define to 1 if you have the `gmtime_s' function in C11 form.])
+          AC_MSG_RESULT([[yes]])
+        ],
+        [
+          AC_MSG_RESULT([[no]])
+          AC_MSG_CHECKING([[whether gmtime_s is in W32 form]])
+          AC_LINK_IFELSE(
+            [ AC_LANG_PROGRAM(
+              [[
+#include <time.h>
+#ifdef __cplusplus
+extern "C"
+#endif
+errno_t gmtime_s(struct tm* _tm, const time_t* time);
+              ]], [[
+                 struct tm res;
+                 time_t t;
+                 gmtime_s (&res, &t);
+              ]])
+            ],
+            [
+              AC_DEFINE([HAVE_W32_GMTIME_S], [1], [Define to 1 if you have the `gmtime_s' function in W32 form.])
+              AC_MSG_RESULT([[yes]])
+            ],
+            [AC_MSG_RESULT([[no]])
+            ])
+        ])
+  ], [],
+  [[#define __STDC_WANT_LIB_EXT1__ 1
+#include <time.h>]])
+
+
+AC_CHECK_DECL([SOCK_NONBLOCK], [AC_DEFINE([HAVE_SOCK_NONBLOCK], [1], [SOCK_NONBLOCK is defined in a socket header])], [],
+  [[
+#if defined(HAVE_SYS_TYPES_H)
+#  include <sys/types.h>
+#endif
+#if defined(HAVE_SYS_SOCKET_H)
+#  include <sys/socket.h>
+#elif defined(HAVE_WINSOCK2_H)
+#  include <winsock2.h>
+#endif
+  ]]
+)
+
+MHD_FIND_LIB([clock_gettime],[[#include <time.h>]],
+  [[
+    struct timespec tp;
+    i][f (0 > clock_gettime(CLOCK_REALTIME, &tp))
+      return 3;
+  ]],
+  [rt],
+  [
+    AC_DEFINE([HAVE_CLOCK_GETTIME], [1], [Define to '1' if you have clock_gettime() function])
+    AS_VAR_IF([[mhd_cv_find_lib_clock_gettime]],[["none required"]], [],
+      [
+        MHD_LIBDEPS_PKGCFG="${mhd_cv_find_lib_clock_gettime} $MHD_LIBDEPS_PKGCFG"
+      ]
+    )
+  ],[],
+  [MHD_LIBDEPS]
+)
+
+MHD_CHECK_FUNC([clock_get_time],
+  [[
+#include <mach/clock.h>
+#include <mach/mach.h>
+  ]],
+  [[
+    clock_serv_t cs;
+    mach_timespec_t mt;
+    host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cs);
+    clock_get_time(cs, &mt);
+    mach_port_deallocate(mach_task_self(), cs);
+  ]]
+)
+
+MHD_CHECK_FUNC([gethrtime],
+  [[
+#ifdef HAVE_SYS_TIME_H
+/* Solaris define gethrtime() in sys/time.h */
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+#ifdef HAVE_TIME_H
+/* HP-UX define gethrtime() in time.h */
+#include <time.h>
+#endif /* HAVE_TIME_H */
+  ]],
+  [[
+    hrtime_t hrt = gethrtime();
+    i][f (0 == hrt)
+      return 3;
+  ]]
+)
+
+AS_VAR_IF([ac_cv_header_time_h], ["yes"],
+  [
+    MHD_CHECK_FUNC([timespec_get],
+      [[
+#include <time.h>
+
+#ifndef TIME_UTC
+#error TIME_UTC must be defined to use timespec_get()
+choke me now
+#endif
+      ]],
+      [[
+  struct timespec ts;
+  i][f (TIME_UTC != timespec_get (&ts, TIME_UTC))
+    return 3;
+      ]]
+    )
+  ]
+)
+
+MHD_CHECK_FUNC_GETTIMEOFDAY
+
+# IPv6
+AC_CACHE_CHECK([for IPv6],[mhd_cv_have_inet6],
+  [
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#include <stdio.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+          ]], [[
+  int af=AF_INET6;
+  int pf=PF_INET6;
+  struct sockaddr_in6 sa;
+  printf("%d %d %p\n", af, pf, (void*) &sa);
+          ]]
+        )
+      ],
+      [AS_VAR_SET([mhd_cv_have_inet6],["yes"])],
+      [AS_VAR_SET([mhd_cv_have_inet6],["no"])]
+    )
+  ]
+)
+AS_VAR_IF([mhd_cv_have_inet6],["yes"],
+  [AC_DEFINE([HAVE_INET6], [1], [Define to '1' if you have IPv6 headers])]
+)
+
+MHD_CHECK_FUNC([[sysconf]], [[#include <unistd.h>]], [[long a = sysconf(0); if (a) return 1;]])
+
+MHD_CHECK_FUNC([[sysctl]], [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif
+#if defined(HAVE_STDDEF_H)
+#include <stddef.h>
+#elif defined(HAVE_STDLIB_H)
+#include <stdlib.h>
+#endif
+  ]], [[
+      int mib[2] = {0, 0}; /* Avoid any platform-specific values */
+      i][f (sysctl(mib, 2, NULL, NULL, NULL, 0)) return 1;
+  ]],
+  [
+    AC_CHECK_DECLS([CTL_NET,PF_INET,IPPROTO_ICMP,ICMPCTL_ICMPLIM],[],[],
+      [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif /* HAVE_SYS_SYSCTL_H */
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif /* HAVE_SYS_SYSCTL_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+#ifdef HAVE_NETINET_IN_SYSTM_H
+#include <netinet/in_systm.h>
+#endif /* HAVE_NETINET_IN_SYSTM_H */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif /* HAVE_NETINET_IN_H */
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+#ifdef HAVE_NETINET_IP_ICMP_H
+#include <netinet/ip_icmp.h>
+#endif /* HAVE_NETINET_IP_ICMP_H */
+#ifdef HAVE_NETINET_ICMP_VAR_H
+#include <netinet/icmp_var.h>
+#endif /* HAVE_NETINET_ICMP_VAR_H */
+      ]]
+    )
+  ]
+)
+
+MHD_CHECK_FUNC([[sysctlbyname]], [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif
+#if defined(HAVE_STDDEF_H)
+#include <stddef.h>
+#elif defined(HAVE_STDLIB_H)
+#include <stdlib.h>
+#endif
+  ]], [[sysctlbyname("test", NULL, NULL, NULL, 0);]]
+)
+
+MHD_CHECK_FUNC([[usleep]], [[#include <unistd.h>]], [[usleep(100000);]])
+MHD_CHECK_FUNC([[nanosleep]], [[#include <time.h>]], [[struct timespec ts2, ts1 = {0, 0}; nanosleep(&ts1, &ts2);]])
 
 HIDDEN_VISIBILITY_CFLAGS=""
-case "$host" in
-  *-*-mingw*)
-    dnl on mingw32 we do -fvisibility=hidden and __declspec(dllexport)
-    AC_DEFINE([_MHD_EXTERN], [__attribute__((visibility("default"))) __declspec(dllexport) extern],
-              [defines how to decorate public symbols while building])
-    HIDDEN_VISIBILITY_CFLAGS="-fvisibility=hidden"
-    ;;
-  *)
-    dnl on other compilers, check if we can do -fvisibility=hidden
-    AX_CHECK_LINK_FLAG([-fvisibility=hidden],
-      [AX_CHECK_COMPILE_FLAG([-fvisibility=hidden],
-                           [AC_DEFINE([_MHD_EXTERN], [__attribute__((visibility("default"))) extern],
-                                       [defines how to decorate public symbols while building])
-                            HIDDEN_VISIBILITY_CFLAGS="-fvisibility=hidden"])])
-    ;;
-esac
-AC_SUBST(HIDDEN_VISIBILITY_CFLAGS)
+AH_TEMPLATE([_MHD_EXTERN],[defines how to decorate public symbols w][hile building the library])
+CFLAGS="${user_CFLAGS}"
+MHD_CHECK_CC_CFLAG([-fvisibility=hidden],[CFLAGS_ac],
+  [
+    # NOTE: require setting of errattr_CFLAGS above
+    CFLAGS="${CFLAGS_ac} -fvisibility=hidden ${user_CFLAGS} ${errattr_CFLAGS}"
+    AC_CACHE_CHECK([whether $CC supports __attribute__((visibility("default")))],[mhd_cv_cc_attr_visibility],
+      [
+        AC_COMPILE_IFELSE([AC_LANG_SOURCE([[
+extern __attribute__((visibility("default"))) int test_extrn_func(void);
+
+int test_extrn_func(void) {return 0;}
+              ]])
+          ],
+          [mhd_cv_cc_attr_visibility="yes"],[mhd_cv_cc_attr_visibility="no"]
+        )
+      ]
+    )
+    AS_VAR_IF([mhd_cv_cc_attr_visibility],["yes"],
+      [
+        HIDDEN_VISIBILITY_CFLAGS="-fvisibility=hidden"
+        AS_IF([test "x$os_is_native_w32" = "xyes" && test "x$enable_shared" = "xyes"],
+          [AC_DEFINE([_MHD_EXTERN], [__attribute__((visibility("default"))) __declspec(dllexport) extern])],
+          [AC_DEFINE([_MHD_EXTERN], [__attribute__((visibility("default"))) extern])]
+        )
+      ],
+      [
+        AC_MSG_WARN([$CC supports -fvisibility, but does not support __attribute__((visibility("default"))). Check compiler and compiler flags.])
+        AC_DEFINE([_MHD_EXTERN], [extern])
+      ]
+    )
+  ],[AC_DEFINE([_MHD_EXTERN], [extern])]
+)
+CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+AC_SUBST([HIDDEN_VISIBILITY_CFLAGS])
 
 # libcurl (required for testing)
 AC_ARG_ENABLE([curl],
   [AS_HELP_STRING([--disable-curl],[disable cURL based testcases])],
   [enable_curl=${enableval}])
 curl=0
-if test "$enable_curl" != "no"
-then
-  LIBCURL_CHECK_CONFIG([yes],[7.16.4],[enable_curl=yes],
+AS_IF([test "$enable_curl" != "no"],
+ [LIBCURL_CHECK_CONFIG([yes],[7.16.4],[enable_curl=yes],
     [
-      if test "x$enable_curl" = "xyes"; then
-        AC_MSG_WARN([[cURL-based tests cannot be enabled because libcurl is missing]])
-      fi
+      AS_IF([test "x$enable_curl" = "xyes"],
+       [AC_MSG_WARN([[cURL-based tests cannot be enabled because libcurl is missing]])])
       enable_curl=no
     ])
-fi
-if test "$enable_curl" != "no"
-then
-# Lib cURL & cURL - OpenSSL versions
-  AC_DEFINE([MHD_REQ_CURL_VERSION], ["7.16.4"], [required cURL version to run tests])
-  AC_DEFINE([MHD_REQ_CURL_OPENSSL_VERSION], ["0.9.8"], [required cURL SSL version to run tests])
-  AC_DEFINE([MHD_REQ_CURL_GNUTLS_VERSION], ["2.8.6"], [gnuTLS lib version - used in conjunction with cURL])
-  AC_DEFINE([MHD_REQ_CURL_NSS_VERSION], ["3.12.0"], [NSS lib version - used in conjunction with cURL])
-fi
-AM_CONDITIONAL([HAVE_CURL], [test "x$enable_curl" = "xyes"])
+])
+AM_CONDITIONAL([RUN_LIBCURL_TESTS], [test "x$enable_curl" = "xyes"])
+AS_IF([test "x$enable_curl" = "xyes"],
+  [MSG_CURL="yes"],
+  [MSG_CURL="no, many unit tests will not run"]
+)
 
-AC_CHECK_LIB([[magic]], [[magic_open]],
-  [AC_CHECK_HEADERS([magic.h],
-   AM_CONDITIONAL(HAVE_MAGIC, true),
-   AM_CONDITIONAL(HAVE_MAGIC, false))],
-  AM_CONDITIONAL(HAVE_MAGIC, false))
-
-
-# optional: libmicrospdy support. Enabled by default if not on W32
-AC_ARG_ENABLE([spdy],
-		AS_HELP_STRING([--enable-spdy],
-			[enable build libmicrospdy (yes, no, auto) [auto]]),
-		[enable_spdy=${enableval}],
-		[ AS_IF([[test "x$os_is_windows" = "xyes"]], [enable_spdy=no]) ])
-
-if test "$enable_spdy" != "no"
-then
-  AX_CHECK_OPENSSL([ have_openssl=yes ],[ have_openssl=no ])
-  if test "x$have_openssl" = "xyes"
-  then
-    # check OpenSSL headers
-    SAVE_CPP_FLAGS="$CPPFLAGS"
-    CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS"
-    AC_CHECK_HEADERS([openssl/evp.h openssl/rsa.h openssl/rand.h openssl/err.h openssl/sha.h openssl/pem.h openssl/engine.h], [ have_openssl=yes ],[ have_openssl=no ])
-    if test "x$have_openssl" = "xyes"
-    then
-      # check OpenSSL libs
-      SAVE_LIBS="$LIBS"
-      SAVE_LD_FLAGS="$LDFLAGS"
-      LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS"
-      LIBS="$OPENSSL_LIBS $LIBS"
-      AC_CHECK_FUNC([SSL_CTX_set_next_protos_advertised_cb],
-        [
-          AC_CHECK_FUNC([SSL_library_init], [ have_openssl=yes ],[ have_openssl=no ])
-        ],[ have_openssl=no ])
-      LIBS="$SAVE_LIBS"
-      LDFLAGS="$SAVE_LD_FLAGS"
-    fi
-    CPPFLAGS="$SAVE_CPP_FLAGS"
-  fi
-  if test "x$have_openssl" = "xyes"
-  then
-    enable_spdy=yes
-  else
-    AS_IF([[test "x$enable_spdy" = "xyes" ]], [AC_MSG_ERROR([[libmicrospdy cannot be enabled without OpenSSL.]])])
-    have_openssl=no
-    enable_spdy=no
-  fi
-else
-  # OpenSSL is used only for libmicrospdy
-  have_openssl=no
-fi
-AM_CONDITIONAL([HAVE_OPENSSL], [test "x$have_openssl" = "xyes"])
-
-if test "$enable_spdy" = "yes"
-then
- AC_DEFINE([SPDY_SUPPORT],[1],[include libmicrospdy support])
-else
- AC_DEFINE([SPDY_SUPPORT],[0],[disable libmicrospdy support])
-fi
-AM_CONDITIONAL(ENABLE_SPDY, [test "x$enable_spdy" != "xno"])
-AC_MSG_CHECKING(whether we have OpenSSL and thus can support libmicrospdy)
-AC_MSG_RESULT($enable_spdy)
-
-# for pkg-config
-SPDY_LIBDEPS="$OPENSSL_LIBS"
-
-SPDY_LIB_LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS"
-SPDY_LIB_CFLAGS="$CFLAGS"
-SPDY_LIB_CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS"
-AC_SUBST(SPDY_LIB_LDFLAGS)
-AC_SUBST(SPDY_LIB_CFLAGS)
-AC_SUBST(SPDY_LIB_CPPFLAGS)
-# for pkg-config
-AC_SUBST(SPDY_LIBDEPS)
-
-AC_CHECK_HEADERS([spdylay/spdylay.h], [ have_spdylay="yes" ], [have_spdylay="no"])
-AM_CONDITIONAL(HAVE_SPDYLAY, [test "x$have_spdylay" = "xyes"])
+MHD_CHECK_FUNC([magic_open],
+  [[
+#include <magic.h>
+  ]],
+  [[
+    char var_data[256];
+    const char *var_mime;
+    magic_t var_magic = magic_open (MAGIC_MIME_TYPE);
+    (void)magic_load (var_magic, "filename");
+    var_data[0] = 0;
+    var_mime = magic_buffer (var_magic, var_data, 1);
+    i][f (! var_mime)
+      return 1;
+    magic_close (var_magic);
+  ]],
+  [AC_DEFINE([MHD_HAVE_LIBMAGIC], [1], [Define to 1 if you have suitable libmagic.])],
+  [],
+  [-lmagic]
+)
+AM_CONDITIONAL([MHD_HAVE_LIBMAGIC], [[test "x$mhd_cv_func_magic_open" = "xyes"]])
 
 # large file support (> 4 GB)
 AC_SYS_LARGEFILE
 AC_FUNC_FSEEKO
+MHD_CHECK_FUNC([lseek64],
+  [[
+#if defined(HAVE_SYS_TYPES_H)
+#  include <sys/types.h>
+#endif
+#include <unistd.h>
+  ]],
+  [[
+  i][f (((off64_t) -1) == lseek64(0, (off64_t) 0, SEEK_SET))
+    return 3;
+  ]]
+)
+MHD_CHECK_FUNC([pread64],
+  [[
+#if defined(HAVE_SYS_TYPES_H)
+#  include <sys/types.h>
+#endif
+#include <unistd.h>
+  ]],
+  [[
+  char buf[5];
+  i][f (0 > pread64(0, (void *) buf, 1, (off64_t) 0))
+    return 3;
+  ]]
+)
+MHD_CHECK_FUNC([pread],
+  [[
+#if defined(HAVE_SYS_TYPES_H)
+#  include <sys/types.h>
+#endif
+#include <unistd.h>
+  ]],
+  [[
+  char buf[5];
+  i][f (0 > pread(0, (void *) buf, 1, 0))
+    return 3;
+  ]]
+)
+
+
+# check for various sendfile functions
+AC_ARG_ENABLE([sendfile],
+   [AS_HELP_STRING([--disable-sendfile],
+               [disable usage of sendfile() for HTTP connections [auto]])],
+   [],
+   [enable_sendfile="auto"])
+AS_CASE([$enable_sendfile],
+  [[auto | yes]],[[found_sendfile="no"]],
+  [[no]],[[found_sendfile="disabled"]],
+  [AC_MSG_ERROR([[unknown value specified: --enable-sendfile=$enable_sendfile]])]
+)
+AS_VAR_IF([[found_sendfile]], [["no"]],
+  [
+    AC_MSG_CHECKING([[for Linux-style sendfile(2)]])
+    AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM(
+        [[
+#include <sys/sendfile.h>
+
+static void empty_func(void)
+{
+/* Check for declaration */
+  (void)sendfile;
+}
+/* Declare again to check form match */
+ssize_t sendfile(int, int, off_t*, size_t);
+        ]],
+        [[
+          int fd1=0, fd2=2;
+          off_t o = 0;
+          size_t s = 5;
+          ssize_t r;
+          r = sendfile (fd1, fd2, &o, s);
+          if (r)
+            empty_func();
+        ]]
+       )
+      ],
+      [
+        AC_DEFINE([HAVE_LINUX_SENDFILE], [1], [Define to 1 if you have linux-style sendfile(2).])
+        found_sendfile="yes, Linux-style"
+        AC_MSG_RESULT([[yes]])
+        MHD_CHECK_FUNC([sendfile64],
+          [[
+#include <sys/sendfile.h>
+          ]],
+          [[
+  off64_t f_offset = (off64_t) 0;
+  if (0 > sendfile64 (0, 1, &f_offset, 1))
+    return 3;
+          ]]
+        )
+      ],
+      [AC_MSG_RESULT([[no]])
+      ]
+    )
+  ]
+)
+AS_VAR_IF([[found_sendfile]], [["no"]],
+  [
+   AC_MSG_CHECKING([[for FreeBSD-style sendfile(2)]])
+   AC_LINK_IFELSE(
+     [AC_LANG_PROGRAM(
+       [[
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+
+static void empty_func(void)
+{
+/* Check for declaration */
+  (void)sendfile;
+}
+/* Declare again to check form match */
+int sendfile(int, int, off_t, size_t,
+             struct sf_hdtr*, off_t*, int);
+       ]],
+       [[
+         int fd1=0, fd2=1;
+         off_t o = 0;
+         size_t s = 5;
+         off_t r1;
+         int r2;
+         r2 = sendfile (fd1, fd2, o, s, (void*)0, &r1, 0);
+         if (r2)
+           empty_func();
+       ]]
+      )
+     ],
+     [
+       AC_DEFINE([HAVE_FREEBSD_SENDFILE], [1], [Define to 1 if you have FreeBSD-style sendfile(2).])
+       found_sendfile="yes, FreeBSD-style"
+       AC_MSG_RESULT([[yes]])
+     ],
+     [AC_MSG_RESULT([[no]])
+     ]
+   )
+  ]
+)
+AS_VAR_IF([[found_sendfile]], [["no"]],
+  [
+   AC_MSG_CHECKING([[for Darwin-style sendfile(2)]])
+   AC_LINK_IFELSE(
+     [AC_LANG_PROGRAM(
+       [[
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+
+static void empty_func(void)
+{
+/* Check for declaration */
+  (void)sendfile;
+}
+/* Declare again to check form match */
+int sendfile(int, int, off_t, off_t*,
+             struct sf_hdtr *, int);
+       ]],
+       [[
+         int fd=0, s=1;
+         off_t o = 0;
+         off_t l = 5;
+         int r;
+         r = sendfile (fd, s, o, &l, (void*)0, 0);
+         if (r)
+           empty_func();
+       ]]
+      )
+     ],
+     [
+       AC_DEFINE([HAVE_DARWIN_SENDFILE], [1], [Define to 1 if you have Darwin-style sendfile(2).])
+       found_sendfile="yes, Darwin-style"
+       AC_MSG_RESULT([[yes]])
+     ],
+     [AC_MSG_RESULT([[no]])
+     ]
+   )
+  ]
+)
+
+AS_VAR_IF([[found_sendfile]], [["no"]],
+  [
+   AC_MSG_CHECKING([[for Solaris-style sendfile(3)]])
+   SAVE_LIBS="$LIBS"
+   LIBS="-lsendfile $LIBS"
+   AC_LINK_IFELSE(
+     [AC_LANG_PROGRAM(
+       [[
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sendfile.h>
+
+static void empty_func(void)
+{
+/* Check for declaration */
+  (void)sendfile;
+}
+/* Declare again to check form match */
+ssize_t sendfile(int out_fd, int in_fd,
+                 off_t *off, size_t len);
+       ]],
+       [[
+         int fd1=0, fd2=1;
+         off_t o = 0;
+         size_t l = 5;
+         ssize_t r;
+         r = sendfile (fd1, fd2, &o, l);
+         if (r)
+           empty_func();
+       ]]
+      )
+     ],
+     [
+       AC_DEFINE([HAVE_SOLARIS_SENDFILE], [1], [Define to 1 if you have Solaris-style sendfile(3).])
+       found_sendfile="yes, Solaris-style"
+       MHD_LIBDEPS="-lsendfile $MHD_LIBDEPS"
+       MHD_LIBDEPS_PKGCFG="-lsendfile $MHD_LIBDEPS_PKGCFG"
+       AC_MSG_RESULT([[yes]])
+       MHD_CHECK_FUNC([sendfile64],
+         [[
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sendfile.h>
+         ]],
+         [[
+  off64_t f_offset = (off64_t) 0;
+  if (0 > sendfile64 (0, 1, &f_offset, 1))
+    return 3;
+         ]]
+       )
+     ],
+     [AC_MSG_RESULT([[no]])
+     ]
+   )
+   LIBS="$SAVE_LIBS"
+  ]
+)
+AS_IF([[test "x$found_sendfile" = "xno" && test "x$enable_sendfile" = "xyes"]],
+  [AC_MSG_ERROR([[sendfile() usage was requested by configure parameter, but no usable sendfile() function is detected]])]
+)
 
 # optional: have error messages ?
-AC_MSG_CHECKING(whether to generate error messages)
+AC_MSG_CHECKING([[whether to generate error messages]])
 AC_ARG_ENABLE([messages],
    [AS_HELP_STRING([--disable-messages],
                [disable MHD error messages])],
    [enable_messages=${enableval}],
    [enable_messages=yes])
-AC_MSG_RESULT($enable_messages)
-if test "$enable_messages" = "yes"
-then
- AC_DEFINE([HAVE_MESSAGES],[1],[Include error messages])
-else
- AC_DEFINE([HAVE_MESSAGES],[0],[Disable error messages])
-fi
+AS_IF([[test "x$enable_messages" = "xyes"]],
+  [ AC_DEFINE([HAVE_MESSAGES],[1],[Define to 1 to enable support for error messages.]) ],
+  [[ enable_messages=no ]])
+AC_MSG_RESULT([[$enable_messages]])
 
 
 # optional: have postprocessor?
-AC_MSG_CHECKING(whether to enable postprocessor)
+AC_MSG_CHECKING([[whether to enable postprocessor]])
 AC_ARG_ENABLE([postprocessor],
    [AS_HELP_STRING([--disable-postprocessor],
                [disable MHD PostProcessor functionality])],
    [enable_postprocessor=${enableval}],
    [enable_postprocessor=yes])
-test "x$enable_postprocessor" = "xno" || enable_postprocessor=yes
+AS_IF([[test "x$enable_postprocessor" != "xno"]],
+  [ enable_postprocessor=yes
+    AC_DEFINE([HAVE_POSTPROCESSOR],[1],[Define to 1 if libmicrohttpd is compiled with postprocessor support.]) ])
+AM_CONDITIONAL([HAVE_POSTPROCESSOR], [test "x$enable_postprocessor" != "xno"])
 AC_MSG_RESULT([[$enable_postprocessor]])
-AM_CONDITIONAL([HAVE_POSTPROCESSOR],test "x$enable_postprocessor" != "xno")
-if test "x$enable_postprocessor" != "xno"
-then
- AC_DEFINE([HAVE_POSTPROCESSOR],[1],[define to 1 if MHD was build with postprocessor.c])
-fi
 
 
 # optional: have zzuf, socat?
-AC_CHECK_PROG([have_zzuf],[zzuf], [yes], [no])
-AC_CHECK_PROG([have_socat],[socat], [yes], [no])
-AM_CONDITIONAL([HAVE_ZZUF], [test "x$have_zzuf" = "xyes"])
-AM_CONDITIONAL([HAVE_SOCAT], [test "x$have_socat" = "xyes"])
+run_zzuf_tests="no"
+AS_VAR_IF([use_heavy_tests],["yes"],
+  [
+    AS_VAR_IF([enable_curl],["yes"],
+      [
+        AC_CHECK_PROG([have_zzuf],[zzuf],[yes],[no])
+        AS_VAR_IF([have_zzuf],["yes"],
+          [
+            AC_CHECK_PROG([have_socat],[socat],[yes],[no])
+            AS_VAR_IF([have_socat],["yes"],
+              [
+                run_zzuf_tests="yes"
+                run_zzuf_tests_MSG="yes"
+              ],
+              [
+                run_zzuf_tests="no"
+                run_zzuf_tests_MSG="no, socat tool not found"
+              ]
+            )
+          ],
+          [
+            run_zzuf_tests="no"
+            run_zzuf_tests_MSG="no, zzuf tool not found"
+          ]
+        )
+      ],
+      [
+        run_zzuf_tests="no"
+        run_zzuf_tests_MSG="no, tests with libcurl are not enabled"
+      ]
+    )
+  ],
+  [
+    run_zzuf_tests="no"
+    run_zzuf_tests_MSG="no, heavy tests are not enabled"
+  ]
+)
+AM_CONDITIONAL([RUN_ZZUF_TESTS],[test "x$run_zzuf_tests" = "xyes"])
 
-
-# libgcrypt linkage: required for HTTPS support
-AM_PATH_LIBGCRYPT([1.2.2], [have_gcrypt=yes], [have_gcrypt=no])
-if test "x$have_gcrypt" = "xyes"
-then
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS $LIBGCRYPT_CFLAGS"
-  # LIBGCRYPT_CFLAGS can be actually a CPPFLAGS, so check them both
-  SAVE_CPPFLAGS="$CPPFLAGS"
-  CPPFLAGS="$CPPFLAGS $LIBGCRYPT_CFLAGS"
-  AC_CHECK_HEADERS([gcrypt.h], [], [have_gcrypt=no])
-  CFLAGS="$SAVE_CFLAGS"
-  CPPFLAGS="$SAVE_CPPFLAGS"
-fi
-
-# gnutls
-GNUTLS_CPPFLAGS=""
-GNUTLS_LDFLAGS=""
 have_gnutls=no
 have_gnutls_sni=no
+have_gcrypt=no
+AS_UNSET([GNUTLS_CPPFLAGS])
+AS_UNSET([GNUTLS_LDFLAGS])
+
+# optional: HTTPS support.  Enabled by default
+AC_ARG_ENABLE([https],
+   [AS_HELP_STRING([--enable-https],
+               [enable HTTPS support (yes, no, auto)[auto]])],
+   [enable_https=${enableval}])
+AS_IF([test "x$enable_https" != "xno"],[
+#
+# Next block is large unindented block
+#
+
+# gnutls
 have_gnutls_pkgcfg=no
 AC_MSG_CHECKING([[how to find GnuTLS library]])
 AC_ARG_WITH([[gnutls]],
-   [AC_HELP_STRING([[--with-gnutls[=PFX]]],[use GnuTLS for HTTPS support, optional PFX overrides pkg-config data for GnuTLS headers (PFX/include) and libs (PFX/lib)])],
+   [AS_HELP_STRING([[--with-gnutls[=PFX]]],[use GnuTLS for HTTPS support, optional PFX overrides pkg-config data for GnuTLS headers (PFX/include) and libs (PFX/lib)])],
    [
-    case $with_gnutls in
-      no)
+    AS_CASE([$with_gnutls],
+     [no],[
         AC_MSG_RESULT([[GnuTLS disabled]])
-        ;;
-      yes)
+        AS_UNSET([GNUTLS_CPPFLAGS])
+        AS_UNSET([GNUTLS_CFLAGS])
+        AS_UNSET([GNUTLS_LDFLAGS])
+        AS_UNSET([GNUTLS_LIBS])
+      ],
+      [yes],[
         AC_MSG_RESULT([[automatically, forced]])
-        ;;
-      *)
+      ],
+      [
         AC_MSG_RESULT([[-I$with_gnutls/include -L$with_gnutls/lib -lgnutls]])
-        SAVE_LDFLAGS="$LDFLAGS"
-        SAVE_CPPFLAGS="$CPPFLAGS"
-        LDFLAGS="-L$with_gnutls/lib $LDFLAGS"
-        CPPFLAGS="-I$with_gnutls/include $CPPFLAGS"
+        SAVE_LIBS="$LIBS"
+        LDFLAGS="${LDFLAGS_ac} -L$with_gnutls/lib ${user_LDFLAGS}"
+        CPPFLAGS="${CPPFLAGS_ac} -I$with_gnutls/include ${user_CPPFLAGS}"
         have_gnutls_pkgcfg=no
-          AC_CHECK_HEADERS([gnutls/gnutls.h],
-            [AC_CHECK_LIB([gnutls], [gnutls_priority_set],
-              [
-                GNUTLS_CPPFLAGS="-I$with_gnutls/include"
-                GNUTLS_LDFLAGS="-L$with_gnutls/lib"
-                GNUTLS_LIBS="-lgnutls"
-                AC_CHECK_LIB([gnutls], [gnutls_load_file], [AC_CHECK_LIB([gnutls], [gnutls_privkey_import_x509_raw], [have_gnutls_sni=yes])])
-                have_gnutls=yes
-              ])])
-        AS_IF([test "x$have_gnutls" != "xyes"], [AC_MSG_ERROR([can't find usable libgnutls at specified prefix $with_gnutls])])
-        LDFLAGS="$SAVE_LDFLAGS"
-        CPPFLAGS="$SAVE_CPPFLAGS"
-        ;;
-    esac
+        MHD_CHECK_FUNC([gnutls_check_version],[[#include <gnutls/gnutls.h>]],
+          [
+           if(!gnutls_check_version("2.0.0"))
+             return 3;
+          ],
+          [
+            GNUTLS_CPPFLAGS="-I$with_gnutls/include"
+            GNUTLS_LDFLAGS="-L$with_gnutls/lib"
+            GNUTLS_LIBS="-lgnutls"
+            have_gnutls=yes
+          ],
+          [AC_MSG_ERROR([can't find usable libgnutls at specified prefix $with_gnutls])],
+          [-lgnutls]
+        )
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+        CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+        LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+        LIBS="$SAVE_LIBS"
+      ])
    ],
    [AC_MSG_RESULT([[automatically]])
    ])
 
 AS_IF([test "x$with_gnutls" != "xno" && test "x$have_gnutls" != "xyes"],
   [
+    AC_CACHE_CHECK([[whether to add pkg-config special search directories]], [mhd_cv_pkgconf_add_dirs],
+     [
+      AS_IF([[test "x$host_os" = "xsolaris2.11" && test "x$cross_compiling" = "xno"]],
+       [
+        AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+char size_chk[7-sizeof(char*)];
+#if defined(_LP64) || defined(__LP64__) || defined(__x86_64) || defined(__x86_64__)
+#error This is 64-bit target.
+choke me now
+#endif
+#if defined(__amd64) || defined(__amd64__) || defined(__sparcv9) || defined(__sparc_v9__)
+#error This is 64-bit target.
+choke me now
+#endif
+           ]], [[]]
+          )
+         ],
+         [
+          mhd_cv_pkgconf_add_dirs='/usr/lib/pkgconfig/gnutls-3'
+         ],
+         [
+          AS_IF([[test "x$host_cpu" = "xx86_64" || test "x$host_cpu" = "xi386"]],
+                  [[mhd_cv_pkgconf_add_dirs='/usr/lib/amd64/pkgconfig/gnutls-3:/usr/lib/amd64/pkgconfig']],
+                [[test "x$host_cpu" = "xsparc"]],
+                  [[mhd_cv_pkgconf_add_dirs='/usr/lib/sparkv9/pkgconfig/gnutls-3:/usr/lib/sparkv9/pkgconfig']],
+                  [[mhd_cv_pkgconf_add_dirs='/usr/lib/64/pkgconfig/gnutls-3:/usr/lib/64/pkgconfig']]
+          )
+         ]
+        )
+       ],
+       [[ mhd_cv_pkgconf_add_dirs='no' ]]
+      )
+     ]
+    )
+    AS_IF([[test "x$mhd_cv_pkgconf_add_dirs" != "xno"]],
+     [
+      test "x$PKG_CONFIG_PATH" = "x" || PKG_CONFIG_PATH="${PKG_CONFIG_PATH}${PATH_SEPARATOR}"
+      PKG_CONFIG_PATH="${PKG_CONFIG_PATH}${mhd_cv_pkgconf_add_dirs}"
+      export PKG_CONFIG_PATH
+     ]
+    )
     PKG_CHECK_MODULES(GNUTLS, [[gnutls]],
       [
        have_gnutls_pkgcfg='yes'
-       SAVE_CPPFLAGS="$CPPFLAGS"
-       SAVE_CFLAGS="$CFLAGS"
-       SAVE_LDFLAGS="$LDFLAGS"
        SAVE_LIBS="$LIBS"
-       CPPFLAGS="$GNUTLS_CFLAGS $CPPFLAGS"
-       CFLAGS="$GNUTLS_CFLAGS $CFLAGS"
-       LDFLAGS="$GNUTLS_LIBS $LDFLAGS"
-       LIBS="$LIBS $GNUTLS_LIBS"
+       CFLAGS="${CFLAGS_ac} $GNUTLS_CFLAGS ${user_CFLAGS}"
+       LIBS="$GNUTLS_LIBS $LIBS"
        AC_MSG_CHECKING([[whether GnuTLS is usable]])
        AC_LINK_IFELSE([
-         AC_LANG_PROGRAM([[#include <gnutls/gnutls.h>]], [[
+         AC_LANG_PROGRAM([[
+#include <gnutls/gnutls.h>
+          ]], [[
                 gnutls_session_t session;
                 gnutls_priority_t priorities;
                 gnutls_global_init();
@@ -730,122 +3219,775 @@
           [
            AC_MSG_RESULT([[yes]])
            have_gnutls=yes
-           GNUTLS_CPPLAGS="$GNUTLS_CFLAGS"
+           # GNUTLS_CFLAGS is actually CPPFLAGS
+           GNUTLS_CPPFLAGS="$GNUTLS_CFLAGS"
+           # GNUTLS_LDFLAGS is a combination of LDFLAGS and LIBS
            GNUTLS_LDFLAGS="$GNUTLS_LIBS"
-           AC_MSG_CHECKING([[for gnutls_privkey_import_x509_raw()]])
-           AC_LINK_IFELSE([
-             AC_LANG_PROGRAM([[#include <gnutls/gnutls.h>]], [[
-                    gnutls_datum_t data;
-                    gnutls_privkey_t key;
-                    gnutls_load_file("key.pem", &data);
-                    gnutls_privkey_import_x509_raw(key, &data, GNUTLS_X509_FMT_PEM, NULL, 0);
-                    gnutls_free(data.data);
-                  ]])], [[have_gnutls_sni=yes]], [[have_gnutls_sni=no]])
-           AC_MSG_RESULT([[$have_gnutls_sni]])
           ],
           [
            AC_MSG_RESULT([[no]])
            have_gnutls=no
           ])
 
-       AS_IF([test "x$have_gnutls" != "xyes"], [AC_MSG_WARN([pkg-config reports that GnuTLS is present, but GnuTLS can't be used])])
-       CPPFLAGS="$SAVE_CPPFLAGS"
-       CFLAGS="$SAVE_CFLAGS"
-       LDFLAGS="$SAVE_LDFLAGS"
+       AS_IF([test "x$have_gnutls" != "xyes"],
+         [
+          AC_MSG_WARN([pkg-config reports that GnuTLS is present, but GnuTLS can't be used])
+          AS_UNSET([GNUTLS_CPPFLAGS])
+          AS_UNSET([GNUTLS_CFLAGS])
+          AS_UNSET([GNUTLS_LDFLAGS])
+          AS_UNSET([GNUTLS_LIBS])
+         ]
+       )
+       CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+       CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+       LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
        LIBS="$SAVE_LIBS"
       ],
       [
+       # check for GnuTLS at default paths
        have_gnutls_pkgcfg='no'
        AC_CHECK_HEADERS([gnutls/gnutls.h],
         [AC_CHECK_LIB([gnutls], [gnutls_priority_set],
           [
             GNUTLS_LIBS="-lgnutls"
-            AC_CHECK_LIB([gnutls], [gnutls_load_file], [AC_CHECK_LIB([gnutls], [gnutls_privkey_import_x509_raw], [have_gnutls_sni=yes])])
             have_gnutls=yes
-          ])])
+          ])], [], [AC_INCLUDES_DEFAULT])
       ])
   ])
 
-AS_IF([test "x$have_gnutls" != "xyes" && test "x$with_gnutls" = "xyes"], [AC_MSG_ERROR([[can't find usable libgnutls]])])
+have_gcrypt='unknown'
+AS_IF([test "x$with_gnutls" != "xno" && test "x$have_gnutls" != "xyes"],
+  [
+   AM_PATH_LIBGCRYPT([1.2.2], [have_gcrypt=yes], [have_gcrypt=no])
+   AS_IF([[test "x$have_gcrypt" = "xyes"]],
+     [
+       SAVE_LIBS="$LIBS"
+       CFLAGS="${CFLAGS_ac} $LIBGCRYPT_CFLAGS ${user_CFLAGS}"
+       # LIBGCRYPT_CFLAGS can be actually a CPPFLAGS, so check them both
+       CPPFLAGS="${CPPFLAGS_ac} $LIBGCRYPT_CFLAGS ${user_CPPFLAGS}"
+       AC_CHECK_HEADERS([gcrypt.h], [], [have_gcrypt=no], [AC_INCLUDES_DEFAULT])
+       # Check for GnuTLS with gcrypt flags
+       LDFLAGS="${LDFLAGS_ac} ${LIBGCRYPT_LIBS} ${user_LDFLAGS}"
+       # A bit of hack: unset cache variable to force recheck
+       AS_UNSET([ac_cv_header_gnutls_gnutls_h])
+       AC_CHECK_HEADERS([gnutls/gnutls.h],
+        [AS_UNSET([ac_cv_lib_gnutls_gnutls_priority_set]) # A bit of hack: unset cache variable to force recheck
+         AC_CHECK_LIB([gnutls], [gnutls_priority_set],
+          [
+            GNUTLS_CPPFLAGS="$LIBGCRYPT_CFLAGS"
+            GNUTLS_CFLAGS="$LIBGCRYPT_CFLAGS"
+            GNUTLS_LDFLAGS="$LIBGCRYPT_LIBS"
+            GNUTLS_LIBS="-lgnutls"
+            have_gnutls=yes
+          ])], [], [AC_INCLUDES_DEFAULT])
+       CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+       CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+       LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+       LIBS="$SAVE_LIBS"
+     ]
+   )
+  ]
+)
+AS_IF([test "x$have_gnutls" != "xyes" && test "x$with_gnutls" = "xyes"],
+      [AC_MSG_ERROR([[can't find usable libgnutls]])])
 
-AM_CONDITIONAL(HAVE_GNUTLS, test "x$have_gnutls" = "xyes")
-AM_CONDITIONAL([HAVE_GNUTLS_SNI], [test "x$have_gnutls_sni" = "xyes"])
+  AS_IF([test "x$have_gnutls" = "xyes"],
+    [
+     SAVE_LIBS="$LIBS"
+     CPPFLAGS="${CPPFLAGS_ac} ${GNUTLS_CPPFLAGS} ${user_CPPFLAGS}"
+     CFLAGS="${CFLAGS_ac} ${GNUTLS_CFLAGS} ${user_CFLAGS}"
+     LDFLAGS="${LDFLAGS_ac} ${GNUTLS_LDFLAGS} ${user_LDFLAGS}"
+     LIBS="$GNUTLS_LIBS $LIBS"
+     AC_MSG_CHECKING([[for gnutls_privkey_import_x509_raw()]])
+     AC_LINK_IFELSE([
+       AC_LANG_PROGRAM([[
+#include <gnutls/gnutls.h>
+#include <gnutls/abstract.h>
+          ]], [[
+            gnutls_datum_t data;
+            gnutls_privkey_t key = 0;
+#ifndef gnutls_load_file
+            (void)gnutls_load_file; /* Check for declaration. */
+#endif
+#ifndef gnutls_privkey_import_x509_raw
+            (void)gnutls_privkey_import_x509_raw; /* Check for declaration. */
+#endif
+            gnutls_load_file("key.pem", &data);
+            gnutls_privkey_import_x509_raw(key, &data, GNUTLS_X509_FMT_PEM, NULL, 0);
+            gnutls_free(data.data);
+          ]])], [[have_gnutls_sni=yes]], [[have_gnutls_sni=no]])
+     AC_MSG_RESULT([[$have_gnutls_sni]])
+     AC_CACHE_CHECK([[whether GnuTLS require libgcrypt initialisation]], [mhd_cv_gcrypt_required],
+       [
+        AC_COMPILE_IFELSE(
+          [
+           AC_LANG_PROGRAM(
+             [
+#include <gnutls/gnutls.h>
+             ],
+             [
+#if !defined(GNUTLS_VERSION_NUMBER) || GNUTLS_VERSION_NUMBER+0 <= 0x020c14
+#error Old versions of GnuTLS require libgcript initialisation
+choke me now
+#endif
+             ]
+           )
+          ],
+          [[mhd_cv_gcrypt_required='no']], [[mhd_cv_gcrypt_required='yes']]
+        )
+       ]
+     )
+     CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+     CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+     LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+     LIBS="$SAVE_LIBS"
+    ],
+    [
+     AS_UNSET([GNUTLS_CPPFLAGS])
+     AS_UNSET([GNUTLS_LDFLAGS])
+    ]
+  )
 
+  AS_IF([[test "x$mhd_cv_gcrypt_required" = "xyes" && test "x$have_gcrypt" = "xunknown"]],
+    [
+     AM_PATH_LIBGCRYPT([1.2.2], [have_gcrypt=yes], [have_gcrypt=no])
+     AS_IF([[test "x$have_gcrypt" = "xyes"]],
+       [
+         CFLAGS="${CFLAGS_ac} ${LIBGCRYPT_CFLAGS} ${user_CFLAGS}"
+         # LIBGCRYPT_CFLAGS can be actually a CPPFLAGS, so check them both
+         CPPFLAGS="${CPPFLAGS_ac} ${LIBGCRYPT_CFLAGS} ${user_CPPFLAGS}"
+         AC_CHECK_HEADERS([gcrypt.h], [], [have_gcrypt=no], [AC_INCLUDES_DEFAULT])
+         CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+         CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+       ]
+     )
+    ]
+  )
+
+  AS_UNSET([[crypt_missing]])
+  AS_IF([[test "x$have_gnutls" = "xyes"]],
+    [
+     AS_IF([[test "x$mhd_cv_gcrypt_required" = "xyes" && test "x$have_gcrypt" != "xyes"]],
+       [
+        crypt_missing="required libgcrypt"
+        AS_IF([[test "x$enable_https" = "xyes" ]], [AC_MSG_ERROR([[HTTPS support cannot be enabled without $crypt_missing.]])])
+        enable_https=no
+        MSG_HTTPS="no (lacking $crypt_missing)"
+        AS_UNSET([LIBGCRYPT_CFLAGS])
+        AS_UNSET([LIBGCRYPT_LIBS])
+        AS_UNSET([GNUTLS_CPPFLAGS])
+        AS_UNSET([GNUTLS_CFLAGS])
+        AS_UNSET([GNUTLS_LDFLAGS])
+        AS_UNSET([GNUTLS_LIBS])
+       ],
+         [
+          AC_DEFINE([[HTTPS_SUPPORT]],[[1]],[Define to 1 if libmicrohttpd is compiled with HTTPS support.])
+          enable_https=yes
+          AS_IF([[test "x$mhd_cv_gcrypt_required" = "xyes"]],
+            [
+             MSG_HTTPS="yes (using libgnutls and libgcrypt)"
+	         MHD_TLS_LIB_CPPFLAGS="$LIBGCRYPT_CFLAGS $GNUTLS_CPPFLAGS"
+             MHD_TLS_LIB_CFLAGS="$LIBGCRYPT_CFLAGS $GNUTLS_CFLAGS"
+             MHD_TLS_LIB_LDFLAGS="$GNUTLS_LDFLAGS"
+             MHD_TLS_LIBDEPS="$GNUTLS_LIBS $LIBGCRYPT_LIBS"
+             AC_DEFINE([[MHD_HTTPS_REQUIRE_GCRYPT]], [[1]], [Define to `1' if HTTPS require initialisation of libgcrypt])
+            ],
+            [
+             MSG_HTTPS="yes (using libgnutls)"
+             AS_UNSET([LIBGCRYPT_CFLAGS])
+             AS_UNSET([LIBGCRYPT_LIBS])
+             MHD_TLS_LIB_CPPFLAGS="$GNUTLS_CPPFLAGS"
+             MHD_TLS_LIB_CFLAGS="$GNUTLS_CFLAGS"
+             MHD_TLS_LIB_LDFLAGS="$GNUTLS_LDFLAGS"
+             MHD_TLS_LIBDEPS="$GNUTLS_LIBS"
+            ]
+          )
+          AS_IF([[ test "x$have_gnutls_pkgcfg" = "xyes" ]],
+            [ # remove GnuTLS from private libs in .pc file as it defined in Requires.private
+              MHD_REQ_PRIVATE='gnutls'
+              AS_IF([[test "x$mhd_cv_gcrypt_required" = "xyes"]],
+                [[MHD_LIBDEPS_PKGCFG="$LIBGCRYPT_LIBS $MHD_LIBDEPS_PKGCFG"]]
+              )
+            ],
+            [
+              MHD_REQ_PRIVATE=''
+              AS_IF([[test "x$mhd_cv_gcrypt_required" = "xyes"]],
+                [[MHD_LIBDEPS_PKGCFG="$LIBGCRYPT_LIBS $MHD_LIBDEPS_PKGCFG"]]
+              )
+              MHD_LIBDEPS_PKGCFG="$GNUTLS_LIBS $MHD_LIBDEPS_PKGCFG"
+          ])
+         ]
+     )
+    ],
+    [
+     crypt_missing="libgnutls"
+     AS_IF([[test "x$enable_https" = "xyes" ]], [AC_MSG_ERROR([[HTTPS support cannot be enabled without $crypt_missing.]])])
+     enable_https=no
+     MSG_HTTPS="no (lacking $crypt_missing)"
+     AS_UNSET([LIBGCRYPT_CFLAGS])
+     AS_UNSET([LIBGCRYPT_LIBS])
+     AS_UNSET([GNUTLS_CPPFLAGS])
+     AS_UNSET([GNUTLS_CFLAGS])
+     AS_UNSET([GNUTLS_LDFLAGS])
+     AS_UNSET([GNUTLS_LIBS])
+    ]
+  )
+],[
+  MSG_HTTPS="no (disabled)"
+])
+
+#
+# End of large unindented block
+#
+
+
+AC_MSG_CHECKING(whether to support HTTPS)
+AC_MSG_RESULT([$MSG_HTTPS])
+
+AM_CONDITIONAL([HAVE_GNUTLS], [[test "x$have_gnutls" = "xyes"]])
+AM_CONDITIONAL([HAVE_GNUTLS_SNI], [[test "x$have_gnutls_sni" = "xyes"]])
+AM_CONDITIONAL([ENABLE_HTTPS], [test "x$enable_https" = "xyes"])
+AM_CONDITIONAL([HTTPS_REQUIRE_GCRYPT], [[test "x$enable_https" = "xyes" && test "x$mhd_cv_gcrypt_required" = "xyes"]])
 AC_SUBST([GNUTLS_CPPFLAGS])
 AC_SUBST([GNUTLS_CFLAGS])
 AC_SUBST([GNUTLS_LDFLAGS])
 AC_SUBST([GNUTLS_LIBS])
 
-# optional: HTTPS support.  Enabled by default
-AC_MSG_CHECKING(whether to support HTTPS)
-AC_ARG_ENABLE([https],
-   [AS_HELP_STRING([--enable-https],
-               [enable HTTPS support (yes, no, auto)[auto]])],
-   [enable_https=${enableval}])
-if test "x$enable_https" != "xno"
-then
-  AS_IF([test "x$have_gnutls" = "xyes" && test "x$have_gcrypt" = "xyes"], [
-          AC_DEFINE([HTTPS_SUPPORT],[1],[include HTTPS support])
-          MHD_LIB_CPPFLAGS="$MHD_LIB_CPPFLAGS $LIBGCRYPT_CFLAGS $GNUTLS_CPPFLAGS"
-          MHD_LIB_CFLAGS="$MHD_LIB_CFLAGS $LIBGCRYPT_CFLAGS $GNUTLS_CFLAGS"
-          MHD_LIB_LDFLAGS="$MHD_LIB_LDFLAGS $GNUTLS_LDFLAGS"
-          MHD_LIBDEPS="$GNUTLS_LIBS $LIBGCRYPT_LIBS $MHD_LIBDEPS"
-          enable_https=yes
-          MSG_HTTPS="yes (using libgnutls and libgcrypt)"
-        ], [
-          AS_IF([test "x$have_gnutls" = "xyes"], [crypt_missing="libgrypt"],
-                [test "x$have_gcrypt" = "xyes"], [crypt_missing="libgnutls"],
-                                                 [crypt_missing="libgrypt and libgnutls"])
-          AS_IF([[test "x$enable_https" = "xyes" ]], [AC_MSG_ERROR([[HTTPS support cannot be enabled without $crypt_missing.]])])
-          AC_DEFINE([HTTPS_SUPPORT],[0],[no libgcrypt or libgnutls])
-          enable_https=no
-          MSG_HTTPS="no (lacking $crypt_missing)"
-        ])
-else
-  AC_DEFINE([HTTPS_SUPPORT],[0],[disable HTTPS support])
-  MSG_HTTPS="no (disabled)"
-fi
-AC_MSG_RESULT([$MSG_HTTPS])
-
-AM_CONDITIONAL([ENABLE_HTTPS], [test "x$enable_https" = "xyes"])
+AS_VAR_IF([have_gnutls], ["yes"],
+  [
+    AC_CACHE_CHECK([for GnuTLS quirks], [mhd_cv_gnutls_mthread_broken],
+      [
+        mhd_cv_gnutls_mthread_broken="no"
+        AS_IF([test -r /etc/redhat-release],
+          [
+            AS_IF([$FGREP ' release 6.' /etc/redhat-release >/dev/null || $FGREP '(Santiago)' /etc/redhat-release >/dev/null],
+              [mhd_cv_gnutls_mthread_broken="found"],
+            )
+          ]
+        )
+        AS_VAR_IF([mhd_cv_gnutls_mthread_broken], ["no"],
+          [
+            AS_IF([command -v rpm >/dev/null],
+              [
+                AS_IF([test "r`rpm -E '%{rhel}' 2>/dev/null`" = "r6"],
+                  [mhd_cv_gnutls_mthread_broken="found"],
+                )
+              ]
+            )
+          ]
+        )
+      ]
+    )
+    AC_CACHE_CHECK([for gnutls-cli binary], [mhd_cv_gnutls_cli],
+      [
+        mhd_cv_gnutls_cli="no"
+        AS_IF([command -v gnutls-cli >/dev/null 2>&1],
+          [AS_IF([AC_RUN_LOG([gnutls-cli --version >&2])], [mhd_cv_gnutls_cli="yes"])]
+        )
+      ]
+    )
+  ]
+)
+AM_CONDITIONAL([HAVE_GNUTLS_MTHREAD_BROKEN], [[test "x${mhd_cv_gnutls_mthread_broken}" = "xfound"]])
+AM_CONDITIONAL([USE_UPGRADE_TLS_TESTS], [[test "x${mhd_cv_gnutls_mthread_broken}" = "xno" || test "x${mhd_cv_gnutls_cli}" = "xyes"]])
 
 # optional: HTTP Basic Auth support. Enabled by default
-AC_MSG_CHECKING(whether to support HTTP basic authentication)
+AC_MSG_CHECKING([[whether to support HTTP Basic authentication]])
 AC_ARG_ENABLE([bauth],
-		AS_HELP_STRING([--disable-bauth],
-			[disable HTTP basic Auth support]),
+		[AS_HELP_STRING([--disable-bauth],[disable HTTP Basic Authentication support])],
 		[enable_bauth=${enableval}],
 		[enable_bauth=yes])
-if test "x$enable_bauth" != "xno"
-then
- enable_bauth=yes
- AC_DEFINE([BAUTH_SUPPORT],[1],[include basic Auth support])
-else
- AC_DEFINE([BAUTH_SUPPORT],[0],[disable basic Auth support])
-fi
-AC_MSG_RESULT($enable_bauth)
-AM_CONDITIONAL(ENABLE_BAUTH, [test "x$enable_bauth" != "xno"])
+AS_IF([[test "x$enable_bauth" != "xno"]],
+  [ enable_bauth=yes
+    AC_DEFINE([BAUTH_SUPPORT],[1],[Define to 1 if libmicrohttpd is compiled with Basic Auth support.]) ])
+AM_CONDITIONAL([ENABLE_BAUTH], [test "x$enable_bauth" != "xno"])
+AC_MSG_RESULT([[$enable_bauth]])
 
 # optional: HTTP Digest Auth support. Enabled by default
-AC_MSG_CHECKING(whether to support HTTP digest authentication)
+AC_MSG_CHECKING([[whether to support HTTP Digest authentication]])
 AC_ARG_ENABLE([dauth],
-		AS_HELP_STRING([--disable-dauth],
-			[disable HTTP basic and digest Auth support]),
-		[enable_dauth=${enableval}],
-		[enable_dauth=yes])
-if test "x$enable_dauth" != "xno"
-then
- enable_dauth=yes
- AC_DEFINE([DAUTH_SUPPORT],[1],[include digest Auth support])
-else
- AC_DEFINE([DAUTH_SUPPORT],[0],[disable digest Auth support])
-fi
-AC_MSG_RESULT($enable_dauth)
-AM_CONDITIONAL(ENABLE_DAUTH, [test "x$enable_dauth" != "xno"])
+		[AS_HELP_STRING([--disable-dauth], [disable HTTP Digest Authentication support])],
+		[enable_dauth="${enableval}"],
+		[enable_dauth="yes"])
+AS_IF([[test "x$enable_dauth" != "xno"]],
+  [ enable_dauth=yes
+    AC_DEFINE([DAUTH_SUPPORT],[1],[Define to 1 if libmicrohttpd is compiled with Digest Auth support.]) ])
+AM_CONDITIONAL([ENABLE_DAUTH], [test "x$enable_dauth" != "xno"])
+AC_MSG_RESULT([[$enable_dauth]])
+
+AM_CONDITIONAL([HAVE_ANYAUTH],[test "x$enable_bauth" != "xno" || test "x$enable_dauth" != "xno"])
+
+# optional: HTTP "Upgrade" support. Enabled by default
+AC_MSG_CHECKING([[whether to support HTTP "Upgrade"]])
+AC_ARG_ENABLE([[httpupgrade]],
+    [AS_HELP_STRING([[--disable-httpupgrade]], [disable HTTP "Upgrade" support])],
+    [AS_VAR_IF([[enable_httpupgrade]],[["no"]],[],[[enable_httpupgrade='yes']])],
+    [[enable_httpupgrade='yes']])
+AS_VAR_IF([[enable_httpupgrade]],[["yes"]],
+  [
+   AC_DEFINE([[UPGRADE_SUPPORT]],[[1]],[Define to 1 if libmicrohttpd is compiled with HTTP Upgrade support.]) ])
+AM_CONDITIONAL([ENABLE_UPGRADE], [[test "x$enable_httpupgrade" = "xyes"]])
+AC_MSG_RESULT([[$enable_httpupgrade]])
+
+# optional: HTTP cookie parsing support. Enabled by default
+AC_MSG_CHECKING([[whether to support HTTP cookie parsing]])
+AC_ARG_ENABLE([[cookie]],
+    [AS_HELP_STRING([[--disable-cookie]], [disable HTTP cookie parsing support])],
+    [AS_VAR_IF([[enable_cookie]],[["no"]],[],[[enable_cookie='yes']])],
+    [[enable_cookie='yes']])
+AS_VAR_IF([[enable_cookie]],[["yes"]],
+  [
+   AC_DEFINE([[COOKIE_SUPPORT]],[[1]],[Define to 1 if libmicrohttpd is compiled with HTTP cookie parsing support.]) ])
+AM_CONDITIONAL([ENABLE_COOKIE], [[test "x$enable_cookie" = "xyes"]])
+AC_MSG_RESULT([[$enable_cookie]])
+
+# optional: MD5 support for Digest Auth. Enabled by default.
+AC_ARG_ENABLE([[md5]],
+  [AS_HELP_STRING([[--enable-md5=TYPE]],
+    [enable TYPE of MD5 hashing code (yes, no, builtin, tlslib) [yes if dauth enabled]])],
+  [
+    AS_VAR_IF([enable_md5],["internal"],[enable_md5='builtin'])
+    AS_VAR_IF([enable_md5],["built-in"],[enable_md5='builtin'])
+    AS_VAR_IF([enable_dauth],["yes"],[],
+      [
+        AS_VAR_IF([enable_md5],["no"],[],
+          [
+            AC_MSG_WARN([The parameter --enable-md5=${enable_md5} is ignored as Digest Authentication is disabled])
+            enable_md5='no'
+          ]
+        )
+      ]
+    )
+  ], [[enable_md5="${enable_dauth}"]]
+)
+AS_CASE([${enable_md5}],[yes|tlslib],
+  [
+    AS_IF([test "x${enable_compact_code}" != "xno" || test "x$enable_md5" = "xtlslib"],
+      [
+        AS_IF([test "x$enable_https" = "xyes"],
+          [
+            AC_CACHE_CHECK([whether GnuTLS supports MD5 hashing],[mhd_cv_gnutls_md5],
+              [
+                CFLAGS="${CFLAGS_ac} ${GNUTLS_CFLAGS} ${user_CFLAGS}"
+                CPPFLAGS="${CPPFLAGS_ac} ${MHD_TLS_LIB_CPPFLAGS} ${user_CPPFLAGS}"
+                CFLAGS="${CFLAGS_ac} ${MHD_TLS_LIB_CFLAGS} ${user_CFLAGS}"
+                LDFLAGS="${LDFLAGS_ac} ${MHD_TLS_LIB_LDFLAGS} ${user_LDFLAGS}"
+                save_LIBS="$LIBS"
+                LIBS="${MHD_TLS_LIBDEPS} ${LIBS}"
+                AC_LINK_IFELSE(
+                  [
+                    AC_LANG_PROGRAM(
+                      [[
+#include <gnutls/crypto.h>
+                      ]],
+                      [[
+    gnutls_hash_hd_t hash_handle;
+    unsigned char digest[16];
+    int exit_code;
+
+    if (0 == gnutls_hash_init(&hash_handle, GNUTLS_DIG_MD5))
+    {
+      if (0 == gnutls_hash(hash_handle, "", 1))
+      {
+        gnutls_hash_output(hash_handle, digest);
+        if (0x93 == digest[0])
+          exit_code = 0;
+        else
+          exit_code = 7;
+      }
+      else
+        exit_code = 5;
+      gnutls_hash_deinit(hash_handle, (void *)0);
+    }
+    else
+      exit_code = 2;
+    if (exit_code)
+      return exit_code;
+                      ]]
+                    )
+                  ],
+                  [mhd_cv_gnutls_md5='yes'],[mhd_cv_gnutls_md5='no']
+                )
+                LIBS="${save_LIBS}"
+                CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+                CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+                CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+                LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+              ]
+            )
+            AS_VAR_IF([mhd_cv_gnutls_md5],["no"],
+              [
+                AS_VAR_IF([enable_md5],["tlslib"],
+                  [AC_MSG_FAILURE([TLS library MD5 implementation is not available])]
+                )
+                enable_md5="builtin"
+              ],
+              [enable_md5="tlslib"]
+            )
+          ],
+          [
+            AS_VAR_IF([enable_md5],["tlslib"],
+              [AC_MSG_ERROR([HTTPS is not enabled, TLS library MD5 implementation cannot be used])]
+            )
+            enable_md5="builtin"
+          ]
+        )
+      ],
+      [
+        enable_md5="builtin"
+      ]
+    )
+  ]
+)
+AC_MSG_CHECKING([[whether to support MD5]])
+AS_UNSET([enable_md5_MSG])
+AS_CASE([${enable_md5}],
+  [builtin],[enable_md5_MSG='yes, built-in'],
+  [tlslib],[enable_md5_MSG='yes, external (TLS library)'],
+  [no],[enable_md5_MSG='no'],
+  [yes],[AC_MSG_ERROR([configure internal error: unexpected variable value])],
+  [AC_MSG_ERROR([Unrecognized parameter --enable-md5=${enable_md5}])]
+)
+AS_IF([test "x${enable_md5}" = "xbuiltin" || test "x${enable_md5}" = "xtlslib" ],
+  [
+    AC_DEFINE([[MHD_MD5_SUPPORT]],[[1]],
+      [Define to 1 if libmicrohttpd is compiled with MD5 hashing support.])
+  ]
+)
+AS_IF([test "x${enable_md5}" = "xtlslib" ],
+  [
+    AC_DEFINE([[MHD_MD5_TLSLIB]],[[1]],
+      [Define to 1 if libmicrohttpd is compiled with MD5 hashing by TLS library.])
+  ]
+)
+AM_CONDITIONAL([ENABLE_MD5], [[test "x${enable_md5}" = "xbuiltin" || test "x${enable_md5}" = "xtlslib" ]])
+AM_CONDITIONAL([ENABLE_MD5_EXT], [[test "x${enable_md5}" = "xtlslib" ]])
+AC_MSG_RESULT([[${enable_md5_MSG}]])
+
+# optional: SHA-256 support for Digest Auth. Enabled by default.
+AC_ARG_ENABLE([[sha256]],
+  [AS_HELP_STRING([[--enable-sha256=TYPE]],
+    [enable TYPE of SHA-256 hashing code (yes, no, builtin, tlslib) [yes if dauth enabled]])],
+  [
+    AS_VAR_IF([enable_sha256],["internal"],[enable_sha256='builtin'])
+    AS_VAR_IF([enable_sha256],["built-in"],[enable_sha256='builtin'])
+    AS_VAR_IF([enable_dauth],["yes"],[],
+      [
+        AS_VAR_IF([enable_sha256],["no"],[],
+          [
+            AC_MSG_WARN([The parameter --enable-sha256=${enable_sha256} is ignored as Digest Authentication is disabled])
+            enable_sha256='no'
+          ]
+        )
+      ]
+    )
+  ], [[enable_sha256="${enable_dauth}"]]
+)
+AS_CASE([${enable_sha256}],[yes|tlslib],
+  [
+    AS_IF([test "x${enable_compact_code}" != "xno" || test "x$enable_sha256" = "xtlslib"],
+      [
+        AS_IF([test "x$enable_https" = "xyes"],
+          [
+            AC_CACHE_CHECK([whether GnuTLS supports sha256 hashing],[mhd_cv_gnutls_sha256],
+              [
+                CFLAGS="${CFLAGS_ac} ${GNUTLS_CFLAGS} ${user_CFLAGS}"
+                CPPFLAGS="${CPPFLAGS_ac} ${MHD_TLS_LIB_CPPFLAGS} ${user_CPPFLAGS}"
+                CFLAGS="${CFLAGS_ac} ${MHD_TLS_LIB_CFLAGS} ${user_CFLAGS}"
+                LDFLAGS="${LDFLAGS_ac} ${MHD_TLS_LIB_LDFLAGS} ${user_LDFLAGS}"
+                save_LIBS="$LIBS"
+                LIBS="${MHD_TLS_LIBDEPS} ${LIBS}"
+                AC_LINK_IFELSE(
+                  [
+                    AC_LANG_PROGRAM(
+                      [[
+#include <gnutls/crypto.h>
+                      ]],
+                      [[
+    gnutls_hash_hd_t hash_handle;
+    unsigned char digest[32];
+    int exit_code;
+
+    if (0 == gnutls_hash_init(&hash_handle, GNUTLS_DIG_SHA256))
+    {
+      if (0 == gnutls_hash(hash_handle, "", 1))
+      {
+        gnutls_hash_output(hash_handle, digest);
+        if (0x6e == digest[0])
+          exit_code = 0;
+        else
+          exit_code = 7;
+      }
+      else
+        exit_code = 5;
+      gnutls_hash_deinit(hash_handle, (void *)0);
+    }
+    else
+      exit_code = 2;
+    if (exit_code)
+      return exit_code;
+                      ]]
+                    )
+                  ],
+                  [mhd_cv_gnutls_sha256='yes'],[mhd_cv_gnutls_sha256='no']
+                )
+                LIBS="${save_LIBS}"
+                CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+                CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+                CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+                LDFLAGS="${LDFLAGS_ac} ${user_LDFLAGS}"
+              ]
+            )
+            AS_VAR_IF([mhd_cv_gnutls_sha256],["no"],
+              [
+                AS_VAR_IF([enable_sha256],["tlslib"],
+                  [AC_MSG_FAILURE([TLS library SHA-256 implementation is not available])]
+                )
+                enable_sha256="builtin"
+              ],
+              [enable_sha256="tlslib"]
+            )
+          ],
+          [
+            AS_VAR_IF([enable_sha256],["tlslib"],
+              [AC_MSG_ERROR([HTTPS is not enabled, TLS library SHA-256 implementation cannot be used])]
+            )
+            enable_sha256="builtin"
+          ]
+        )
+      ],
+      [
+        enable_sha256="builtin"
+      ]
+    )
+  ]
+)
+AC_MSG_CHECKING([[whether to support SHA-256]])
+AS_UNSET([enable_sha256_MSG])
+AS_CASE([${enable_sha256}],
+  [builtin],[enable_sha256_MSG='yes, built-in'],
+  [tlslib],[enable_sha256_MSG='yes, external (TLS library)'],
+  [no],[enable_sha256_MSG='no'],
+  [yes],[AC_MSG_ERROR([configure internal error: unexpected variable value])],
+  [AC_MSG_ERROR([Unrecognized parameter --enable-sha256=${enable_sha256}])]
+)
+AS_IF([test "x${enable_sha256}" = "xbuiltin" || test "x${enable_sha256}" = "xtlslib" ],
+  [
+    AC_DEFINE([[MHD_SHA256_SUPPORT]],[[1]],
+      [Define to 1 if libmicrohttpd is compiled with SHA-256 hashing support.])
+  ]
+)
+AS_IF([test "x${enable_sha256}" = "xtlslib" ],
+  [
+    AC_DEFINE([[MHD_SHA256_TLSLIB]],[[1]],
+      [Define to 1 if libmicrohttpd is compiled with SHA-256 hashing by TLS library.])
+  ]
+)
+AM_CONDITIONAL([ENABLE_SHA256], [[test "x${enable_sha256}" = "xbuiltin" || test "x${enable_sha256}" = "xtlslib" ]])
+AM_CONDITIONAL([ENABLE_SHA256_EXT], [[test "x${enable_sha256}" = "xtlslib" ]])
+AC_MSG_RESULT([[${enable_sha256_MSG}]])
+
+# optional: SHA-512/256 support for Digest Auth. Enabled by default.
+AC_ARG_ENABLE([[sha512-256]],
+  [AS_HELP_STRING([[--disable-sha512-256]],
+    [disable SHA-512/256 hashing support for Digest Authentication])],
+  [
+    AS_VAR_IF([[enable_sha512_256]],[["yes"]],
+      [
+        AS_VAR_IF([enable_dauth],["yes"],[],
+          [
+            AC_MSG_WARN([The parameter --enable-sha512-256 is ignored as Digest Authentication is disabled])
+            enable_sha512_256='no'
+          ]
+        )
+      ],[[enable_sha512_256='no']]
+    )
+  ], [[enable_sha512_256="${enable_dauth}"]]
+)
+AC_MSG_CHECKING([[whether to support SHA-512/256]])
+AS_UNSET([enable_sha512_256_MSG])
+AS_CASE([${enable_sha512_256}],
+  [yes],[enable_sha512_256_MSG='yes, built-in'],
+  [no],[enable_sha512_256_MSG='no'],
+  [AC_MSG_ERROR([Unrecognized parameter --enable-sha512-256=${enable_sha512_256}])]
+)
+AS_VAR_IF([[enable_sha512_256]],[["yes"]],
+  [
+   AC_DEFINE([[MHD_SHA512_256_SUPPORT]],[[1]],
+     [Define to 1 if libmicrohttpd is compiled with SHA-512/256 hashing support.])
+  ]
+)
+AM_CONDITIONAL([ENABLE_SHA512_256], [[test "x${enable_sha512_256}" = "xyes"]])
+AC_MSG_RESULT([[${enable_sha512_256_MSG}]])
+
+AS_IF([test "x$enable_dauth" != "xno"],
+  [
+    AS_IF([test "x${enable_md5}" = "xno" &&  test "x${enable_sha256}" = "xno" && test "x${enable_sha512_256}" != "xyes"],
+      [AC_MSG_ERROR([At least one hashing algorithm must be enabled if Digest Auth is enabled])]
+    )
+  ]
+)
 
 
+AC_CACHE_CHECK([[for calloc()]], [[mhd_cv_have_func_calloc]],
+  [
+   AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+#include <stdlib.h>
+       ]],[[void * ptr = calloc(1, 2); if (ptr) return 1;]])
+     ],
+     [[mhd_cv_have_func_calloc='yes']],
+     [[mhd_cv_have_func_calloc='no']]
+   )
+  ]
+)
+AS_VAR_IF([[mhd_cv_have_func_calloc]], [["yes"]],
+  [AC_DEFINE([[HAVE_CALLOC]], [[1]], [Define to 1 if you have the usable `calloc' function.])])
 
-MHD_LIB_LDFLAGS="$MHD_LIB_LDFLAGS -export-dynamic -no-undefined"
+# Some systems have IPv6 disabled in kernel at run-time
+AS_IF([[test "x${mhd_cv_have_inet6}" = "xyes" && test "x${cross_compiling}" = "xno"]],
+ [
+   AC_CACHE_CHECK([whether IPv6 could be used for testing],[mhd_cv_ipv6_for_testing],
+     [
+       AC_RUN_IFELSE(
+         [
+           AC_LANG_SOURCE([[
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_WINSOCK2_H
+#include <winsock2.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_NETINET_TCP_H
+#include <netinet/tcp.h>
+#endif
+
+static void zr_mem(void *ptr, socklen_t size)
+{ char *mem = ptr; while(size--) {mem[0] = 0; mem++;} }
+
+int main(void)
+{
+  int ret = 30;
+  struct sockaddr_in6 sa;
+#if !defined(_WIN32) || defined(__CYGWIN__)
+  int sckt;
+  const int invld_sckt = -1;
+#else
+  SOCKET sckt;
+  const SOCKET invld_sckt = INVALID_SOCKET;
+  WSADATA wsa_data;
+
+  WSAStartup(MAKEWORD(2, 2), &wsa_data);
+#endif
+  zr_mem(&sa, sizeof(sa));
+  sa.sin6_family = AF_INET6;
+  sa.sin6_port = 0;
+  sa.sin6_addr = in6addr_loopback;
+#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+  sa.sin6_len = sizeof(sa);
+#endif
+  sckt = socket (PF_INET6, SOCK_STREAM, 0);
+  if (invld_sckt != sckt)
+  {
+    if (0 == bind (sckt, (struct sockaddr *)&sa, sizeof(sa)))
+    {
+      if (0 == listen (sckt, 1))
+        ret = 0;
+      else
+        ret = 1; /* listen() failed */
+    } else ret = 2; /* bind() failed */
+#if !defined(_WIN32) || defined(__CYGWIN__)
+    close (sckt);
+#else
+    closesocket (sckt);
+#endif
+  } else ret = 3; /* socket() failed */
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  WSACleanup();
+#endif
+  return ret;
+}
+           ]])
+         ], [[mhd_cv_ipv6_for_testing="yes"]], [[mhd_cv_ipv6_for_testing="no"]], [[mhd_cv_ipv6_for_testing="no"]]
+       )
+     ]
+   )
+ ]
+)
+AS_VAR_IF([mhd_cv_ipv6_for_testing],["yes"],
+	[AC_DEFINE([[USE_IPV6_TESTING]], [[1]], [Define to 1 if your kernel supports IPv6 and IPv6 is enabled and useful for testing.])]
+)
+
+
+# Check for fork() and waitpid(). They are used for tests.
+AC_MSG_CHECKING([[for fork()]])
+mhd_have_fork_waitpid='no'
+AC_LINK_IFELSE(
+  [
+   AC_LANG_PROGRAM(
+     [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+     ]], [[
+  pid_t p = fork ();
+  if (0 == p)
+    return 1;
+     ]])
+  ], [
+   AC_DEFINE([[HAVE_FORK]], [[1]], [Define to 1 if you have the usable `fork' function.])
+   AC_MSG_RESULT([[yes]])
+
+   AC_MSG_CHECKING([[for waitpid()]])
+   AC_LINK_IFELSE(
+     [
+      AC_LANG_PROGRAM(
+        [[
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <sys/wait.h>
+        ]], [[
+     pid_t p = fork ();
+     if (0 == p)
+       return 1;
+     waitpid (p, (void*)0, 0)
+        ]])
+     ], [
+      AC_DEFINE([[HAVE_WAITPID]], [[1]], [Define to 1 if you have the usable `waitpid' function.])
+      AC_MSG_RESULT([[yes]])
+      mhd_have_fork_waitpid='yes'
+    ],[
+       AC_MSG_RESULT([[no]])
+    ])
+],[
+   AC_MSG_RESULT([[no]])
+])
+
+AM_CONDITIONAL([HAVE_FORK_WAITPID], [test "x$mhd_have_fork_waitpid" = "xyes"])
 
 # gcov compilation
 AC_MSG_CHECKING(whether to compile with support for code coverage analysis)
@@ -858,92 +4000,1083 @@
 AM_CONDITIONAL([USE_COVERAGE], [test "x$use_gcov" = "xyes"])
 
 AX_COUNT_CPUS
-AC_SUBST([CPU_COUNT])
+AC_MSG_CHECKING([for number of CPU cores to use in tests])
+AS_VAR_IF([use_heavy_tests], ["yes"],
+  [
+    # Enable usage of many core if heavy tests are enabled
+    AS_IF([[test "$CPU_COUNT" -gt "32"]], [[CPU_COUNT="32"]])dnl Limit resource usage
+  ],
+  [
+    # Limit usage to just a few cores if heavy tests are not enabled
+    AS_IF([[test "$CPU_COUNT" -gt "6"]], [[CPU_COUNT="6"]])
+    AS_IF([[test "$CPU_COUNT" -lt "2"]], [[CPU_COUNT="2"]])
+  ]
+)
+AC_MSG_RESULT([$CPU_COUNT])
 
+
+AC_ARG_ENABLE([[asserts]],
+  [AS_HELP_STRING([[--enable-asserts]],
+    [enable test build with debug asserts])],
+  [],
+  [enable_asserts='auto']
+)
+AS_UNSET([use_asserts_MSG])
+AC_CACHE_CHECK([[whether NDEBUG macro is defined]], [mhd_cv_macro_ndebug_def],
+  [
+    AC_LINK_IFELSE(
+      [
+        AC_LANG_SOURCE([[
+#ifndef NDEBUG
+#error NDEBUG is NOT defined
+chome me now
+#endif
+
+int main(void)
+{
+  return 0;
+}
+          ]]
+        )
+      ],
+      [[mhd_cv_macro_ndebug_def='yes']],
+      [[mhd_cv_macro_ndebug_def='no']]
+    )
+  ]
+)
+AS_VAR_IF([enable_asserts],["yes"],
+  [
+    AS_VAR_IF([mhd_cv_macro_ndebug_def],["yes"],
+      [
+        AC_MSG_FAILURE([Parameter --enable-asserts is specified, but NDEBUG macro is defined as well])
+      ]
+    )
+    use_asserts_MSG="yes, enabled by configure parameter"
+  ]
+)
+AC_CACHE_CHECK([[whether _DEBUG macro is defined]], [mhd_cv_macro__debug_def],
+  [
+    AC_LINK_IFELSE(
+      [
+        AC_LANG_SOURCE([[
+#ifndef _DEBUG
+#error _DEBUG is NOT defined
+chome me now
+#endif
+
+int main(void)
+{
+  return 0;
+}
+          ]]
+        )
+      ],
+      [[mhd_cv_macro__debug_def='yes']],
+      [[mhd_cv_macro__debug_def='no']]
+    )
+  ]
+)
+AS_VAR_IF([enable_asserts],["no"],
+  [
+    AS_VAR_IF([mhd_cv_macro__debug_def],["yes"],
+      [
+        AC_MSG_FAILURE([Parameter --disable-asserts is specified, but _DEBUG macro is defined as well])
+      ]
+    )
+    use_asserts_MSG="no, set by configure parameter"
+  ]
+)
+AS_IF([test "x${mhd_cv_macro_ndebug_def}" = "xyes" && test "x${mhd_cv_macro__debug_def}" = "xyes"],
+  [AC_MSG_FAILURE([Both NDEBUG and _DEBUG macros are defined])]
+)
+AS_VAR_IF([enable_asserts],["auto"],
+  [
+    AS_VAR_IF([mhd_cv_macro_ndebug_def],["yes"],
+      [
+        enable_asserts="no"
+        use_asserts_MSG="no, set by NDEBUG preprocessor macro"
+      ]
+    )
+  ]
+)
+AS_VAR_IF([enable_asserts],["auto"],
+  [
+    AS_VAR_IF([mhd_cv_macro__debug_def],["yes"],
+      [
+        enable_asserts="yes"
+        use_asserts_MSG="yes, enabled by _DEBUG preprocessor macro"
+      ]
+    )
+  ]
+)
+AS_VAR_IF([enable_asserts],["auto"],
+  [
+    AC_CACHE_CHECK([[whether DEBUG macro is defined]], [mhd_cv_macro_debug_def],
+      [
+        AC_LINK_IFELSE(
+          [
+            AC_LANG_SOURCE([[
+#ifndef DEBUG
+#error DEBUG is NOT defined
+chome me now
+#endif
+
+int main(void)
+{
+  return 0;
+}
+              ]]
+            )
+          ],
+          [[mhd_cv_macro_debug_def='yes']],
+          [[mhd_cv_macro_debug_def='no']]
+        )
+      ]
+    )
+    AS_VAR_IF([mhd_cv_macro_debug_def],["yes"],
+      [
+        enable_asserts="yes"
+        use_asserts_MSG="yes, enabled by DEBUG preprocessor macro"
+      ]
+    )
+  ]
+)
+AC_MSG_CHECKING([[whether to enable debug asserts]])
+AS_VAR_IF([enable_asserts],["auto"],
+  [
+    AS_CASE([${enable_build_type}],
+      [debug|debugger],
+      [
+        enable_asserts="yes"
+        use_asserts_MSG="yes, enabled by --enable-bulid-type=${enable_build_type}"
+      ],
+      [
+        enable_asserts="no"
+        use_asserts_MSG="no"
+      ]
+    )
+  ]
+)
+AS_CASE([[$enable_asserts]], [[yes]], [[:]], [[no]], [[:]], [[enable_asserts='no']])
+AC_MSG_RESULT([[${use_asserts_MSG=no}]])
+
+AS_VAR_IF([[enable_asserts]], [["yes"]],
+  [
+    AS_VAR_IF([[mhd_cv_macro__debug_def]], [["yes"]], [:],
+      [
+        MHD_PREPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-D_DEBUG=1])
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+      ]
+    )
+    AC_CACHE_CHECK([[whether system assert() is available]], [mhd_cv_sys_assert_avail],
+      [
+        AC_LINK_IFELSE(
+          [
+            AC_LANG_SOURCE([[
+#include <assert.h>
+
+static int pos_val(void) {return 5;}
+static int neg_val(void) {return -5;}
+int main(void)
+{
+  int pos_var = pos_val(), neg_var = neg_val();
+  assert(neg_var > pos_var); /* Must trigger assert. */
+  return pos_var + neg_var;
+}
+            ]])
+          ],
+          [[mhd_cv_sys_assert_avail='yes']],
+          [[mhd_cv_sys_assert_avail='no']]
+        )
+      ]
+    )
+    AS_VAR_IF([[mhd_cv_sys_assert_avail]], [["no"]], [],
+      [AC_DEFINE([[HAVE_ASSERT]], [[1]], [Define if you have usable assert() and assert.h])])
+  ],
+  [
+    AS_VAR_IF([[mhd_cv_macro_ndebug_def]], [["yes"]], [:],
+      [
+        MHD_PREPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-DNDEBUG=1])
+        CPPFLAGS="${CPPFLAGS_ac} ${user_CPPFLAGS}"
+      ]
+    )
+  ]
+)
+
+AS_UNSET([enabled_sanitizers])
+TESTS_ENVIRONMENT_ac=""
+AM_ASAN_OPTIONS=""
+AM_UBSAN_OPTIONS=""
+AM_LSAN_OPTIONS=""
+AS_UNSET([ASAN_OPTIONS])
+AS_UNSET([UBSAN_OPTIONS])
+AS_UNSET([LSAN_OPTIONS])
+
+AC_MSG_CHECKING([whether to enable run-time sanitizers])
+AC_ARG_ENABLE([sanitizers],
+  [AS_HELP_STRING([[--enable-sanitizers[=address,undefined,leak,user-poison]]],
+  [enable run-time sanitizers, specify the list of types of sanitizers to enable, ]
+  [leave the list empty (or set to "auto") to enable all supported and available ]
+  [sanitizers, or specify "auto-fallback" to use sanitizers even without ]
+  [installed sanitizer run-time library])],
+  [], [AS_CASE([${enable_build_type}],[debug],
+    [enable_sanitizers='auto-optional'],[enable_sanitizers='no'])]
+)
+AS_IF([test "x${enable_sanitizers}" = "x"], [enable_sanitizers="auto"])
+AS_VAR_IF([enable_sanitizers], ["yes"], [enable_sanitizers="auto"])
+AS_VAR_IF([enable_sanitizers], ["autofallback"], [enable_sanitizers="auto-fallback"])
+AS_VAR_IF([enable_sanitizers], ["autooptional"], [enable_sanitizers="auto-optional"])
+AS_IF([test "x${enable_sanitizers}" = "xno"],
+  [
+    enable_sanitizers="no"
+    enable_san_address="no"
+    enable_san_undef="no"
+    enable_san_leak="no"
+    enable_san_upoison="no"
+  ],
+  [test "x${enable_sanitizers}" = "xauto" || test "x${enable_sanitizers}" = "xauto-optional"],
+  [
+    AS_VAR_IF([enable_compiler_hardening],["yes"],
+      [
+        AS_VAR_IF([enable_sanitizers],["auto"],
+          [AC_MSG_ERROR([sanitizers cannot be enabled with compiler hardnening])],
+          [AC_MSG_WARN([sanitizers cannot be enabled with compiler hardnening])]
+        )
+        enable_sanitizers="no"
+        enable_san_address="no"
+        enable_san_undef="no"
+        enable_san_leak="no"
+        enable_san_upoison="no"
+      ],
+      [
+        enable_san_address="auto"
+        enable_san_undef="auto"
+        enable_san_leak="auto"
+        enable_san_upoison="auto"
+      ]
+    )
+  ],
+  [test "x${enable_sanitizers}" = "xauto-fallback"],
+  [
+    enable_san_address="auto"
+    enable_san_undef="auto-fallback"
+    enable_san_leak="auto"
+    enable_san_upoison="auto"
+  ],
+  [
+    AS_UNSET([san])
+    enable_san_address="no"
+    enable_san_undef="no"
+    enable_san_leak="no"
+    enable_san_upoison="no"
+    f][or san in `AS_ECHO([${enable_sanitizers}]) | tr ',' ' '`
+    do
+      AS_CASE([$san],
+        [address], [enable_san_address="yes"],
+        [undefined], [enable_san_undef="yes"],
+        [leak], [enable_san_leak="yes"],
+        [user-poison|user_poison], [enable_san_upoison="yes"],
+        [no|yes|auto|auto-fallback|autofallback], [AC_MSG_ERROR(["$san" cannot be used with other options for --enable-sanitizers=])],
+        [AC_MSG_ERROR([Unknown parameter "$san" for --enable-sanitizers=])]
+      )
+    done
+    AS_IF([test "x${enable_san_upoison}" = "xyes" && test "x${enable_san_address}" = "xno"],
+      [AC_MSG_ERROR([User memory poisoning cannot be used without address sanitizer])]
+    )
+    enable_sanitizers="selected"
+  ]
+)
+AS_CASE([${enable_sanitizers}],
+  [selected], [AC_MSG_RESULT([selected])],
+  [auto], [AC_MSG_RESULT([yes, detect and use supported sanitizers])],
+  [auto-fallback], [AC_MSG_RESULT([yes, detect and use supported sanitizers even without run-time lib])],
+  [auto-optional], [AC_MSG_RESULT([yes, detect and use supported sanitizers if any])],
+  [AC_MSG_RESULT([no])]
+)
+AS_VAR_IF([enable_sanitizers], ["no"], [:],
+ [
+   AS_UNSET([san_FLAGS]) # the sanitizer flags to be added to both CFLAGS and LDFLAGS
+   AS_UNSET([san_CFLAGS]) # the sanitizer flags to be added to CFLAGS
+   AC_CACHE_CHECK([whether '-fsanitize=' works for $CC],
+     [mhd_cv_cc_sanitizer_works],
+     [
+       CFLAGS="${CFLAGS_ac} -fsanitize=wrongFeatureName ${user_CFLAGS}"
+       AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],
+         [mhd_cv_cc_sanitizer_works=no], [mhd_cv_cc_sanitizer_works=yes])
+     ]
+   )
+   AS_VAR_IF([mhd_cv_cc_sanitizer_works], ["yes"],
+     [
+       AS_VAR_IF([enable_san_address], ["no"], [:],
+         [
+           AC_CACHE_CHECK([for address sanitizer], [mhd_cv_cc_sanitizer_address],
+             [
+               CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} -fsanitize=address ${user_CFLAGS}"
+               AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+                [mhd_cv_cc_sanitizer_address=yes], [mhd_cv_cc_sanitizer_address=no])
+             ]
+           )
+           AS_VAR_IF([mhd_cv_cc_sanitizer_address],["yes"],
+             [
+               AC_DEFINE([MHD_ASAN_ACTIVE], [1], [Define to '1' if you have address sanitizer enabled])
+               AX_APPEND_FLAG([-fsanitize=address], [san_FLAGS])
+               enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }address"
+               AS_VAR_IF([enable_san_leak], ["no"], [:],
+                 [
+                   AC_CACHE_CHECK([whether leak detect is not rejected by address sanitizer], [mhd_cv_cc_sanitizer_address_leak],
+                     [
+                       CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} ${user_CFLAGS}"
+                       ASAN_OPTIONS="exitcode=88:detect_leaks=1:halt_on_error=1"
+                       export ASAN_OPTIONS
+                       AC_RUN_IFELSE([AC_LANG_PROGRAM([],[])],
+                         [mhd_cv_cc_sanitizer_address_leak=yes], [mhd_cv_cc_sanitizer_address_leak=no],
+                         [
+                           # Cross-compiling with sanitizers?
+                           mhd_cv_cc_sanitizer_address_leak='assuming no'
+                         ]
+                       )
+                       AS_UNSET([ASAN_OPTIONS])
+                     ]
+                   )
+                 ]
+               )
+               AC_CACHE_CHECK([for pointer compare sanitizer], [mhd_cv_cc_sanitizer_pointer_compare],
+                 [
+                   CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} -fsanitize=pointer-compare ${user_CFLAGS}"
+                   AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+                    [mhd_cv_cc_sanitizer_pointer_compare=yes], [mhd_cv_cc_sanitizer_pointer_compare=no])
+                 ]
+               )
+               AS_VAR_IF([mhd_cv_cc_sanitizer_pointer_compare],["yes"],
+                 [
+                   AX_APPEND_FLAG([-fsanitize=pointer-compare], [san_FLAGS])
+                   enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }pointer compare"
+                 ]
+               )
+               AC_CACHE_CHECK([for pointer subtract sanitizer], [mhd_cv_cc_sanitizer_pointer_subtract],
+                 [
+                   CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} -fsanitize=pointer-subtract ${user_CFLAGS}"
+                   AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+                    [mhd_cv_cc_sanitizer_pointer_subtract=yes], [mhd_cv_cc_sanitizer_pointer_subtract=no])
+                 ]
+               )
+               AS_VAR_IF([mhd_cv_cc_sanitizer_pointer_subtract],["yes"],
+                 [
+                   AX_APPEND_FLAG([-fsanitize=pointer-subtract], [san_FLAGS])
+                   enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }pointer subtract"
+                 ]
+               )
+               AS_VAR_IF([enable_san_upoison], ["no"], [:],
+                 [
+                   AC_CHECK_HEADERS([sanitizer/asan_interface.h], [], [], [AC_INCLUDES_DEFAULT])
+                   AS_VAR_IF([ac_cv_header_sanitizer_asan_interface_h],["yes"],
+                     [
+                       CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} ${errattr_CFLAGS} ${user_CFLAGS}"
+                       MHD_CHECK_FUNC([__asan_address_is_poisoned],[[#include <sanitizer/asan_interface.h>]],
+                         [[int a_var=1; i][f(__asan_address_is_poisoned((void*) &a_var)) return 3;]]
+                       )
+                       MHD_CHECK_FUNC([__asan_region_is_poisoned],[[#include <sanitizer/asan_interface.h>]],
+                         [[int a_var=1; i][f(((void*) 0) != __asan_region_is_poisoned((void*) &a_var, sizeof(a_var))) return 3;]]
+                       )
+                       AC_CACHE_CHECK([whether special function attribute is needed for user-poison], [mhd_cv_func_u_p_attribute_needed],
+                         [
+                           ASAN_OPTIONS="exitcode=88:detect_invalid_pointer_pairs=3:halt_on_error=1"
+                           export ASAN_OPTIONS
+                           CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} ${errattr_CFLAGS} ${user_CFLAGS}"
+                           AC_RUN_IFELSE(
+                             [
+                               AC_LANG_SOURCE(
+                                 [[
+#include <stdint.h>
+#include <stdlib.h>
+#include <sanitizer/asan_interface.h>
+
+static const size_t first_pos = 0;
+static const size_t mid_pos = 64;
+static const size_t last_pos = 128;
+static const size_t zone_size = 16;
+static const size_t buf_size = 128 + 16;
+
+static int ptr_compare(void *ptr1, uint8_t *ptr2)
+{
+  if ((((uintptr_t) (uint8_t *)ptr1) >= ((uintptr_t)ptr2)))
+    return ((char *) ptr1)[0] < ((char *) ptr2)[0];
+  return ((char *) ptr1)[0] > ((char *) ptr2)[0];
+}
+
+static int ptr_subtract(void *ptr1, uint8_t *ptr2)
+{
+  return ((size_t)(((uintptr_t)(uint8_t*)ptr1) - ((uintptr_t)ptr2))) <= last_pos;
+}
+
+int main(int argc, char *argv[])
+{
+  char *buf = (char*) malloc (buf_size);
+  char *a;
+  char *b;
+  int ret;
+
+  (void) argv;
+  if (NULL == buf)
+    return 10;
+  ASAN_POISON_MEMORY_REGION (buf + first_pos + zone_size, mid_pos - first_pos - zone_size);
+  ASAN_POISON_MEMORY_REGION (buf + mid_pos + zone_size, last_pos - mid_pos - zone_size);
+
+  if (0 < argc)
+    a = buf + last_pos;
+  else
+    a = buf + first_pos;
+  b = buf + mid_pos;
+
+  *a = '0';
+  *b = '9';
+
+  if (ptr_compare((void *)a, (uint8_t*) b))
+  {
+    if (ptr_subtract((void *)a, (uint8_t*) b))
+      ret = 0;
+    else
+      ret = 10;
+  }
+  else
+    ret = 5;
+  ASAN_UNPOISON_MEMORY_REGION (buf, buf_size);
+  free (buf);
+
+  return ret;
+}
+                                 ]]
+                               )
+                             ],
+                             [mhd_cv_func_u_p_attribute_needed="no"], [mhd_cv_func_u_p_attribute_needed="yes"],
+                             [
+                               # Cross-compiling with sanitizers??
+                               mhd_cv_func_up_attribute_needed='assuming no'
+                             ]
+                           )
+                           AS_UNSET([ASAN_OPTIONS])
+                         ]
+                       )
+                     ]
+                   )
+                   AS_VAR_IF([mhd_cv_func_u_p_attribute_needed],["yes"],[:],
+                     [
+                       AC_DEFINE([FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS],[1],[Define to '1' if cast to 'uintptr_t' works for safely processing user-poisoned pointer])
+                     ]
+                   )
+                   AS_IF([test "x${mhd_cv_func_u_p_attribute_needed}" = "xyes" && test "x${ac_cv_header_sanitizer_asan_interface_h}" = "xyes"],
+                     [
+                       AC_CACHE_CHECK([whether '__attribute__((no_sanitize("pointer-compare")))' and '__attribute__((no_sanitize("pointer-subtract")))' work],
+                         [mhd_cv_func_attribute_nosanitize_ptr],
+                         [
+                           ASAN_OPTIONS="exitcode=88:detect_invalid_pointer_pairs=3:halt_on_error=1"
+                           export ASAN_OPTIONS
+                           CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} ${errattr_CFLAGS} ${user_CFLAGS}"
+                           AC_RUN_IFELSE(
+                             [
+                               AC_LANG_SOURCE(
+                                 [[
+#include <stdint.h>
+#include <stdlib.h>
+#include <sanitizer/asan_interface.h>
+
+static const size_t first_pos = 0;
+static const size_t mid_pos = 64;
+static const size_t last_pos = 128;
+static const size_t zone_size = 16;
+static const size_t buf_size = 128 + 16;
+
+__attribute__((no_sanitize("pointer-compare")))
+static int ptr_compare(void *ptr1, uint8_t *ptr2)
+{
+  if ((((const uint8_t*)ptr1) >= ((const uint8_t*)ptr2)))
+    return ((char *) ptr1)[0] < ((char *) ptr2)[0];
+  return ((char *) ptr1)[0] > ((char *) ptr2)[0];
+}
+
+__attribute__((no_sanitize("pointer-subtract")))
+static int ptr_subtract(void *ptr1, uint8_t *ptr2)
+{
+  return ((size_t)(((const uint8_t*)ptr1) - \
+          ((const uint8_t*)ptr2))) <= last_pos;
+}
+
+int main(int argc, char *argv[])
+{
+  char *buf = (char*) malloc (buf_size);
+  char *a;
+  char *b;
+  int ret;
+
+  (void) argv;
+  if (NULL == buf)
+    return 10;
+  ASAN_POISON_MEMORY_REGION (buf + first_pos + zone_size, mid_pos - first_pos - zone_size);
+  ASAN_POISON_MEMORY_REGION (buf + mid_pos + zone_size, last_pos - mid_pos - zone_size);
+
+  if (0 < argc)
+    a = buf + last_pos;
+  else
+    a = buf + first_pos;
+  b = buf + mid_pos;
+
+  *a = '0';
+  *b = '9';
+
+  if (ptr_compare((void *)a, (uint8_t*) b))
+  {
+    if (ptr_subtract((void *)a, (uint8_t*) b))
+      ret = 0;
+    else
+      ret = 10;
+  }
+  else
+    ret = 5;
+  ASAN_UNPOISON_MEMORY_REGION (buf, buf_size);
+  free (buf);
+
+  return ret;
+}
+                                 ]]
+                               )
+                             ],
+                             [mhd_cv_func_attribute_nosanitize_ptr=yes], [mhd_cv_func_attribute_nosanitize_ptr=no],
+                             [
+                               # Cross-compiling with sanitizers??
+                               mhd_cv_func_attribute_nosanitize_ptr='assuming no'
+                             ]
+                           )
+                           AS_UNSET([ASAN_OPTIONS])
+                         ]
+                       )
+                       AS_VAR_IF([mhd_cv_func_attribute_nosanitize_ptr], ["yes"],
+                         [
+                           AC_DEFINE([FUNC_ATTR_PTRCOMPARE_WORKS],[1],[Define to '1' if '__attribute__((no_sanitize("pointer-compare")))' works])
+                           AC_DEFINE([FUNC_ATTR_PTRSUBTRACT_WORKS],[1],[Define to '1' if '__attribute__((no_sanitize("pointer-subtract")))' works])
+                         ],
+                         [
+                           AC_CACHE_CHECK([whether '__attribute__((no_sanitize("address")))' works for pointers compare], [mhd_cv_func_attribute_nosanitize_addr],
+                             [
+                               ASAN_OPTIONS="exitcode=88:detect_invalid_pointer_pairs=3:halt_on_error=1"
+                               export ASAN_OPTIONS
+                               CFLAGS="${CFLAGS_ac} ${san_CFLAGS} ${san_FLAGS} ${errattr_CFLAGS} ${user_CFLAGS}"
+                               AC_RUN_IFELSE(
+                                 [
+                                   AC_LANG_SOURCE(
+                                     [[
+#include <stdint.h>
+#include <stdlib.h>
+#include <sanitizer/asan_interface.h>
+
+static const size_t first_pos = 0;
+static const size_t mid_pos = 64;
+static const size_t last_pos = 128;
+static const size_t zone_size = 16;
+static const size_t buf_size = 128 + 16;
+
+__attribute__((no_sanitize("address")))
+static int ptr_compare(void *ptr1, uint8_t *ptr2)
+{
+  if ((((const uint8_t*)ptr1) >= ((const uint8_t*)ptr2)))
+    return ((char *) ptr1)[0] < ((char *) ptr2)[0];
+  return ((char *) ptr1)[0] > ((char *) ptr2)[0];
+}
+
+__attribute__((no_sanitize("address")))
+static int ptr_subtract(void *ptr1, uint8_t *ptr2)
+{
+  return ((size_t)(((const uint8_t*)ptr1) - \
+          ((const uint8_t*)ptr2))) <= last_pos;
+}
+
+int main(int argc, char *argv[])
+{
+  char *buf = (char*) malloc (buf_size);
+  char *a;
+  char *b;
+  int ret;
+
+  (void) argv;
+  if (NULL == buf)
+    return 10;
+  ASAN_POISON_MEMORY_REGION (buf + first_pos + zone_size, mid_pos - first_pos - zone_size);
+  ASAN_POISON_MEMORY_REGION (buf + mid_pos + zone_size, last_pos - mid_pos - zone_size);
+
+  if (0 < argc)
+    a = buf + last_pos;
+  else
+    a = buf + first_pos;
+  b = buf + mid_pos;
+
+  *a = '0';
+  *b = '9';
+
+  if (ptr_compare((void *)a, (uint8_t*) b))
+  {
+    if (ptr_subtract((void *)a, (uint8_t*) b))
+      ret = 0;
+    else
+      ret = 10;
+  }
+  else
+    ret = 5;
+  ASAN_UNPOISON_MEMORY_REGION (buf, buf_size);
+  free (buf);
+
+  return ret;
+}
+                                     ]]
+                                   )
+                                 ],
+                                 [mhd_cv_func_attribute_nosanitize_addr=yes], [mhd_cv_func_attribute_nosanitize_addr=no],
+                                 [
+                                   # Cross-compiling with sanitizers??
+                                   mhd_cv_func_attribute_nosanitize_addr='assuming no'
+                                 ]
+                               )
+                               AS_UNSET([ASAN_OPTIONS])
+                             ]
+                           )
+                           AS_VAR_IF([mhd_cv_func_attribute_nosanitize_addr], ["yes"],
+                             [AC_DEFINE([FUNC_ATTR_NOSANITIZE_WORKS],[1],[Define to '1' if '__attribute__((no_sanitize("address")))' works for pointers compare])]
+                           )
+                         ]
+                       )
+                     ]
+                   )
+                 ]
+               )
+             ]
+           )
+           AS_IF([test "x${enable_san_address}" = "xyes" && test "x${mhd_cv_cc_sanitizer_address}" != "xyes"],
+             [AC_MSG_ERROR([Address sanitizer cannot be enabled])]
+           )
+           enable_san_address="${mhd_cv_cc_sanitizer_address}"
+         ]
+       )
+       AS_VAR_IF([enable_san_undef], ["no"], [:],
+         [
+           dnl Ensure that '#' will be processed correctly
+           [
+            test_undf_prog='
+#include <stdio.h>
+
+static void func_out_b(char *arr)
+{
+  arr[0] = 0;
+  arr[16] = 2;
+}
+
+static unsigned int int_deref(void *ptr)
+{
+  return (*((unsigned int*)ptr)) + 2;
+}
+
+static int func1(void)
+{
+  char chr[16];
+  func_out_b (chr);
+  return (int) (int_deref(chr + 1) + int_deref(chr + 2));
+}
+
+int main(void)
+{
+  unsigned long ulvar;
+  signed char ch1;
+  ulvar = -1 * func1();
+  ch1 = ulvar * 6UL;
+  printf("%lu\n", ulvar + ch1);
+  return 0;
+}
+            '
+           ]
+           AC_CACHE_CHECK([for undefined behavior sanitizer], [mhd_cv_cc_sanitizer_undefined],
+             [
+               CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} -fsanitize=undefined ${user_CFLAGS}"
+               AC_LINK_IFELSE([AC_LANG_SOURCE([${test_undf_prog}])],
+                [mhd_cv_cc_sanitizer_undefined=yes], [mhd_cv_cc_sanitizer_undefined=no])
+             ]
+           )
+           AS_VAR_IF([mhd_cv_cc_sanitizer_undefined],["yes"],
+             [
+               AX_APPEND_FLAG([-fsanitize=undefined], [san_FLAGS])
+               enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }undefined"
+             ],
+             [
+               AS_CASE([${enable_san_undef}], [yes|auto-fallback],
+                 [
+                   AC_CACHE_CHECK([for undefined behavior sanitizer with '-fsanitize-undefined-trap-on-error'], [mhd_cv_cc_sanitizer_undefined_trap],
+                     [
+                       CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} -fsanitize=undefined -fsanitize-undefined-trap-on-error ${user_CFLAGS}"
+                       AC_LINK_IFELSE([AC_LANG_SOURCE([${test_undf_prog}])],
+                        [mhd_cv_cc_sanitizer_undefined_trap=yes], [mhd_cv_cc_sanitizer_undefined_trap=no])
+                     ]
+                   )
+                   AS_VAR_IF([mhd_cv_cc_sanitizer_undefined_trap], ["yes"],
+                     [
+                       AX_APPEND_FLAG([-fsanitize=undefined], [san_FLAGS])
+                       AX_APPEND_FLAG([-fsanitize-undefined-trap-on-error], [san_FLAGS])
+                       enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }undefined"
+                       AC_MSG_WARN([Enabled sanitizer without run-time library, error reporting will be limited])
+                     ],
+                     [
+                       AS_IF([test -z "${enabled_sanitizers}"],
+                         [
+                           # Last resort
+                           AC_CACHE_CHECK([for undefined behavior sanitizer with '-fsanitize-trap=all'], [mhd_cv_cc_sanitizer_undefined_trap_all],
+                             [
+                               CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} -fsanitize=undefined -fsanitize-trap=all ${user_CFLAGS}"
+                               AC_LINK_IFELSE([AC_LANG_SOURCE([${test_undf_prog}])],
+                                [mhd_cv_cc_sanitizer_undefined_trap_all=yes], [mhd_cv_cc_sanitizer_undefined_trap_all=no])
+                             ]
+                           )
+                           AS_VAR_IF([mhd_cv_cc_sanitizer_undefined_trap_all],["yes"],
+                             [
+                               AX_APPEND_FLAG([-fsanitize=undefined], [san_FLAGS])
+                               AX_APPEND_FLAG([-fsanitize-trap=all], [san_FLAGS])
+                               CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} -fsanitize=undefined -fsanitize-trap=all ${user_CFLAGS}"
+                               enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }undefined"
+                               AC_MSG_WARN([Enabled sanitizer without run-time library, error reporting will be limited])
+                             ]
+                           )
+                         ]
+                       )
+                     ]
+                   )
+                   AS_CASE(["$enabled_sanitizers"], [*undefined],
+                     [
+                       AS_VAR_IF([mhd_cv_cc_sanitizer_undefined], ["yes"],[],
+                         [
+                           # A workaround for broken clang which is trying to use UBSan lib
+                           # even when instructed to not use it
+                           CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} ${user_CFLAGS}"
+                           AX_APPEND_LINK_FLAGS([-fsanitize-trap=implicit-conversion],
+                             [san_FLAGS], [], [AC_LANG_SOURCE([${test_undf_prog}])])
+                         ]
+                       )
+                     ]
+                   )
+                 ]
+               )
+             ]
+           )
+           AS_CASE(["$enabled_sanitizers"], [*undefined],
+             [
+               CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} ${user_CFLAGS}"
+               AX_APPEND_LINK_FLAGS([-fsanitize=bounds-strict -fsanitize=local-bounds -fsanitize=implicit-conversion -fsanitize=nullability-arg],
+                 [san_CFLAGS], [], [AC_LANG_SOURCE([${test_undf_prog}])])
+             ]
+           )
+           AS_UNSET([test_undf_prog])
+           AS_CASE(["$enabled_sanitizers"],
+             [*undefined], [enable_san_undef="yes"],
+             [
+               AS_VAR_IF([enable_san_undef], [yes], [AC_MSG_ERROR([Undefined behavior sanitizer cannot be enabled])])
+               enable_san_undef="no"
+             ]
+           )
+         ]
+       )
+       AS_VAR_IF([enable_san_leak], ["no"], [:],
+         [
+           AC_CACHE_CHECK([for leak sanitizer], [mhd_cv_cc_sanitizer_leak],
+             [
+               CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} -fsanitize=leak ${user_CFLAGS}"
+               AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+                [mhd_cv_cc_sanitizer_leak=yes], [mhd_cv_cc_sanitizer_leak=no])
+             ]
+           )
+           AS_VAR_IF([mhd_cv_cc_sanitizer_leak],["yes"],
+             [
+               AX_APPEND_FLAG([-fsanitize=leak], [san_FLAGS])
+               enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }leak"
+             ]
+           )
+           AS_IF([test "x${enable_san_leak}" = "xyes" && test "x${mhd_cv_cc_sanitizer_leak}" != "xyes"],
+             [AC_MSG_ERROR([User poison cannot be enabled])]
+           )
+           enable_san_leak="${mhd_cv_cc_sanitizer_leak}"
+         ]
+       )
+       AS_IF([test -z "${enabled_sanitizers}"],
+         [
+           AS_VAR_IF([enable_sanitizers], ["auto-optional"],
+             [
+               san_FLAGS=""
+               san_CFLAGS=""
+             ],
+             [
+               AC_MSG_ERROR([cannot find any sanitizer supported by $CC])
+             ]
+           )
+         ],
+         [
+           AS_VAR_IF([enable_san_upoison], ["no"], [:],
+             [
+               AC_MSG_CHECKING([whether to enable user memory poisoning])
+               AS_IF([test "x${mhd_cv_cc_sanitizer_address}" = "xyes" && test "x${ac_cv_header_sanitizer_asan_interface_h}" = "xyes" && \
+                 (test "x${mhd_cv_func_u_p_attribute_needed}" != "xyes" || test "x${mhd_cv_func_attribute_nosanitize_ptr}" = "xyes" || \
+                  test "x${mhd_cv_func_attribute_nosanitize_addr}" = "xyes")],
+                 [
+                   AC_DEFINE([MHD_ASAN_POISON_ACTIVE], [1], [Define to '1' if user memory poison is used])
+                   enabled_sanitizers="${enabled_sanitizers}${enabled_sanitizers:+, }user-poison"
+                   enable_san_upoison="yes"
+                   AC_MSG_RESULT([yes])
+                 ],
+                 [
+                   AC_MSG_RESULT([no])
+                   AS_VAR_IF([enable_san_upoison], ["yes"],
+                     [AC_MSG_ERROR([User memory poisoning cannot be enabled])])
+                   enable_san_upoison="no"
+                 ]
+               )
+             ]
+           )
+           AS_VAR_IF([enable_san_address], ["yes"],
+             [
+               CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} ${user_CFLAGS}"
+               AC_CHECK_DECL([_FORTIFY_SOURCE],
+                 [MHD_APPEND_FLAG_TO_VAR([CPPFLAGS_ac],[-U_FORTIFY_SOURCE])],
+                 [],[/* no includes */])
+               AX_APPEND_FLAG([-D_FORTIFY_SOURCE=0], [san_CFLAGS])
+             ],
+             [
+               AS_CASE([$enable_sanitizers], [auto|auto-fallback],
+                 [AC_MSG_WARN([$CC does not support address sanitizer])])
+             ]
+           )
+           CFLAGS="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS} ${user_CFLAGS}"
+           # Always stop on sanitizer error
+           AX_APPEND_COMPILE_FLAGS([-fno-sanitize-recover=all], [san_CFLAGS])
+           # Get a better output for sanitizers error reporting
+           AX_APPEND_COMPILE_FLAGS([-fno-omit-frame-pointer -fno-optimize-sibling-calls],
+             [san_CFLAGS])
+           AS_VAR_IF([enable_san_address], ["yes"],
+             [
+               AM_ASAN_OPTIONS="exitcode=88:strict_string_checks=1:detect_stack_use_after_return=1"
+               AM_ASAN_OPTIONS="${AM_ASAN_OPTIONS}:check_initialization_order=1:strict_init_order=1:redzone=64"
+               AM_ASAN_OPTIONS="${AM_ASAN_OPTIONS}:max_free_fill_size=1024:detect_invalid_pointer_pairs=3"
+               AM_ASAN_OPTIONS="${AM_ASAN_OPTIONS}:handle_ioctl=1:halt_on_error=1"
+               AS_VAR_IF([enable_san_upoison], ["yes"], [AM_ASAN_OPTIONS="${AM_ASAN_OPTIONS}:allow_user_poisoning=1"])
+               AS_VAR_IF([enable_san_leak], ["yes"],
+                 [AS_VAR_IF([mhd_cv_cc_sanitizer_address_leak], ["yes"],
+                   [AM_ASAN_OPTIONS="${AM_ASAN_OPTIONS}:detect_leaks=1"])
+                 ], [AM_ASAN_OPTIONS="${AM_ASAN_OPTIONS}:detect_leaks=0"]
+               )
+             ]
+           )
+           AS_VAR_IF([enable_san_undef], [yes],
+             [AM_UBSAN_OPTIONS="exitcode=87:print_stacktrace=1:halt_on_error=1"])
+           AS_VAR_IF([enable_san_leak], ["yes"],
+             [AM_LSAN_OPTIONS="use_unaligned=1"]
+           )
+           TESTS_ENVIRONMENT_ac='\
+    ASAN_OPTIONS="$(AM_ASAN_OPTIONS)" ; export ASAN_OPTIONS ; \
+    UBSAN_OPTIONS="$(AM_UBSAN_OPTIONS)" ; export UBSAN_OPTIONS ; \
+    LSAN_OPTIONS="$(AM_LSAN_OPTIONS)" ; export LSAN_OPTIONS ;'
+         ]
+       )
+     ]
+   )
+   CFLAGS_ac="${CFLAGS_ac} ${san_FLAGS} ${san_CFLAGS}"
+   CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+ ]
+)
+
+# Final flags that may interfere with autoconf detections
+AS_CASE([${enable_build_type}],[debug|debugger],
+  [ # Debug build or build for walking with debugger
+    CFLAGS="${user_CFLAGS}"
+    MHD_CHECK_ADD_CC_CFLAGS([-Wextra-semi -Wextra-semi-stmt], [CFLAGS_ac])
+    CFLAGS="${CFLAGS_ac} ${user_CFLAGS}"
+  ]
+)
+
+AM_CONDITIONAL([USE_SANITIZERS],
+  [test -n "$enabled_sanitizers" && test "x$mhd_cv_cc_sanitizer_works" = "xyes"])
+AC_SUBST([AM_ASAN_OPTIONS])
+AC_SUBST([AM_UBSAN_OPTIONS])
+AC_SUBST([AM_LSAN_OPTIONS])
+AC_SUBST([TESTS_ENVIRONMENT_ac])
+
+MHD_LIB_LDFLAGS="$MHD_LIB_LDFLAGS"
+
+AC_SUBST([CPU_COUNT])
+AC_SUBST([HEAVY_TESTS_NOTPARALLEL])
+AM_SUBST_NOTMAKE([HEAVY_TESTS_NOTPARALLEL])
 AC_SUBST(MHD_LIB_CPPFLAGS)
 AC_SUBST(MHD_LIB_CFLAGS)
 AC_SUBST(MHD_LIB_LDFLAGS)
+AC_SUBST(MHD_LIBDEPS)
+AC_SUBST(MHD_TLS_LIB_CPPFLAGS)
+AC_SUBST(MHD_TLS_LIB_CFLAGS)
+AC_SUBST(MHD_TLS_LIB_LDFLAGS)
+AC_SUBST(MHD_TLS_LIBDEPS)
 
 # for pkg-config
-AS_IF([[test "x$enable_https" = "xyes" && test "x$have_gnutls_pkgcfg" = "xyes" ]],
- [ # remove GnuTLS from private libs in .pc file as it defined in Requires.private
-   MHD_REQ_PRIVATE='gnutls'
-   MHD_LIBDEPS_PKGCFG="${MHD_LIBDEPS//$GNUTLS_LIBS/}"
- ],
- [
-   MHD_REQ_PRIVATE=''
-   MHD_LIBDEPS_PKGCFG="$MHD_LIBDEPS"
- ])
 AC_SUBST([MHD_REQ_PRIVATE])
 AC_SUBST([MHD_LIBDEPS_PKGCFG])
-AC_SUBST(MHD_LIBDEPS)
 
-AC_SUBST(CPPFLAGS)
-AC_SUBST(LIBS)
-AC_SUBST(LDFLAGS)
+# Restore flags as set by the user
+CFLAGS="${user_CFLAGS}"
+LDFLAGS="${user_LDFLAGS}"
+CPPFLAGS="${user_CPPFLAGS}"
+AC_SUBST([CFLAGS])
+AC_SUBST([LDFLAGS])
+AC_SUBST([CPPFLAGS])
+AC_SUBST([LIBS])
 
-AC_CONFIG_FILES([
-libmicrohttpd.pc
-libmicrospdy.pc
-w32/VS2013/microhttpd_dll_res_vc.rc
+# Configure-defined flags
+AC_SUBST([CFLAGS_ac])
+AC_SUBST([LDFLAGS_ac])
+AC_SUBST([CPPFLAGS_ac])
+
+# Used for 'po' directory staff
+AC_SUBST([ac_configure_args])
+AC_SUBST([EMPTY_VAR],[])
+AC_SUBST([MHD_AUX_DIR])
+AC_CONFIG_FILES([po/po-configure.ac])
+AC_CONFIG_COMMANDS([po/Makefile.in],
+  [
+    echo "Skipping update of po/Makefile.in"
+    echo "Real update of po/Makefile.in for 'make dist' is performed by po-config.status"
+  ]
+)
+AC_CONFIG_COMMANDS([po-directories],
+  [
+    echo "Skipping po-directories command."
+    echo "Real po-directories command for 'make dist' is implemented in po-config.status"
+  ]
+)
+
+# We define the paths here, because MinGW/GCC expands paths
+# passed through the command line ("-DDIR=..."). This would
+# lead to hard-coded paths ("C:\mingw\mingw\bin...") that do
+# not contain the actual installation.
+AC_DEFINE_DIR([MHD_PLUGIN_INSTALL_PREFIX], [libdir/libmicrohttpd], [tls plugins])
+
+
+# should experimental code be compiled (code that may not yet compile)?
+AC_MSG_CHECKING(whether to compile experimental code)
+AC_ARG_ENABLE([experimental],
+   [AS_HELP_STRING([--enable-experimental], [enable compiling experimental code])],
+   [enable_experimental=${enableval}],
+   [enable_experimental=no])
+AC_MSG_RESULT($enable_experimental)
+AM_CONDITIONAL([HAVE_EXPERIMENTAL], [test "x$enable_experimental" = "xyes"])
+
+
+AC_CONFIG_FILES([libmicrohttpd.pc
+w32/common/microhttpd_dll_res_vc.rc
 Makefile
 contrib/Makefile
 doc/Makefile
+doc/doxygen/libmicrohttpd.doxy
 doc/doxygen/Makefile
 doc/examples/Makefile
 m4/Makefile
 src/Makefile
 src/include/Makefile
-src/platform/Makefile
+src/lib/Makefile
 src/microhttpd/Makefile
-src/microspdy/Makefile
-src/spdy2http/Makefile
+src/microhttpd_ws/Makefile
 src/examples/Makefile
 src/testcurl/Makefile
 src/testcurl/https/Makefile
-src/testspdy/Makefile
 src/testzzuf/Makefile])
 AC_OUTPUT
 
 # Finally: summary
-if test "x$enable_curl" != "xyes"; then
- MSG_CURL="no, many unit tests will not run"
-else
- MSG_CURL="yes"
-fi
+# Format flags without extra spaces for visual beauty
+fin_CPPFLAGS="$user_CPPFLAGS"
+fin_CFLAGS="$user_CFLAGS"
+fin_LDFLAGS="$user_LDFLAGS"
+MHD_PREPEND_FLAG_TO_VAR([fin_CPPFLAGS],[$CPPFLAGS_ac])
+MHD_PREPEND_FLAG_TO_VAR([fin_CFLAGS],[$CFLAGS_ac])
+MHD_PREPEND_FLAG_TO_VAR([fin_LDFLAGS],[$LDFLAGS_ac])
+fin_lib_CPPFLAGS="$user_CPPFLAGS"
+fin_lib_CFLAGS="$user_CFLAGS"
+fin_lib_LDFLAGS="$user_LDFLAGS"
+MHD_PREPEND_FLAG_TO_VAR([fin_lib_CPPFLAGS],[$MHD_LIB_CPPFLAGS])
+MHD_PREPEND_FLAG_TO_VAR([fin_lib_CFLAGS],[$MHD_LIB_CFLAGS])
+MHD_PREPEND_FLAG_TO_VAR([fin_lib_LDFLAGS],[$MHD_LIB_LDFLAGS])
+MHD_PREPEND_FLAG_TO_VAR([fin_lib_CPPFLAGS],[$CPPFLAGS_ac])
+MHD_PREPEND_FLAG_TO_VAR([fin_lib_CFLAGS],[$CFLAGS_ac])
+MHD_PREPEND_FLAG_TO_VAR([fin_lib_LDFLAGS],[$LDFLAGS_ac])
+AC_MSG_NOTICE([Toolchain settings:
+  CC=$CC
+  User/system/default flags:
+    CPPFLAGS="$user_CPPFLAGS"
+    CFLAGS=  "$user_CFLAGS"
+    LDFLAGS= "$user_LDFLAGS"
+  Final set of the flags for tests and examples:
+    CPPFLAGS="$fin_CPPFLAGS"
+    CFLAGS=  "$fin_CFLAGS"
+    LDFLAGS= "$fin_LDFLAGS"
+  Final set of the flags for ${PACKAGE_NAME} library:
+    CPPFLAGS="$fin_lib_CPPFLAGS"
+    CFLAGS=  "$fin_lib_CFLAGS"
+    LDFLAGS= "$fin_lib_LDFLAGS"
+])
+AS_UNSET([fin_CPPFLAGS])
+AS_UNSET([fin_CFLAGS])
+AS_UNSET([fin_LDFLAGS])
+AS_UNSET([fin_lib_CPPFLAGS])
+AS_UNSET([fin_lib_CFLAGS])
+AS_UNSET([fin_lib_LDFLAGS])
 
-AC_MSG_NOTICE([Configuration Summary:
-  Operating System:  ${host_os}
-  Threading lib:     ${USE_THREADS}
-  libcurl (testing): ${MSG_CURL}
+AS_VAR_IF([os_is_windows], ["yes"],
+  [os_ver_msg="
+  Target W32 ver:    ${mhd_w32_ver_msg}"], [AS_UNSET([[os_ver_msg]])])
+
+
+AC_MSG_NOTICE([GNU libmicrohttpd ${PACKAGE_VERSION} Configuration Summary:
   Target directory:  ${prefix}
+  Cross-compiling:   ${cross_compiling}
+  Operating System:  ${mhd_host_os}${os_ver_msg}
   Messages:          ${enable_messages}
+  Cookie parsing:    ${enable_cookie}
+  Postproc:          ${enable_postprocessor}
+  HTTP "Upgrade":    ${enable_httpupgrade}
   Basic auth.:       ${enable_bauth}
   Digest auth.:      ${enable_dauth}
-  Postproc:          ${enable_postprocessor}
-  HTTPS support:     ${MSG_HTTPS}
+  MD5:               ${enable_md5_MSG}
+  SHA-256:           ${enable_sha256_MSG}
+  SHA-512/256:       ${enable_sha512_256_MSG}
+  Shutdown of listening socket triggers select: ${mhd_cv_host_shtdwn_trgr_select}
+  Inter-thread comm: ${use_itc}
+  Threading lib:     ${USE_THREADS}
   poll support:      ${enable_poll=no}
   epoll support:     ${enable_epoll=no}
-  build docs:        ${enable_doc}
-  build examples:    ${enable_examples}
-  libmicrospdy:      ${enable_spdy}
-  spdylay (testing): ${have_spdylay}
+  sendfile used:     ${found_sendfile}
+  HTTPS support:     ${MSG_HTTPS}
+  Compact code:      ${enable_compact_code} (${compact_code_MSG})
+  Use thread names:  ${enable_thread_names}
+  Use debug asserts: ${use_asserts_MSG=no}
+  Use sanitizers:    ${enabled_sanitizers:=no}
+  Build docs:        ${enable_doc}
+  Build examples:    ${enable_examples}
+  Build static lib:  ${enable_static}
+  Build shared lib:  ${enable_shared}
+  Test with libcurl: ${MSG_CURL}
+  Heavy tests:       ${use_heavy_tests_MSG}
+  Fuzzing tests:     ${run_zzuf_tests_MSG=no}
 ])
 
-if test "x$enable_https" = "xyes"
-then
- AC_MSG_NOTICE([HTTPS subsystem configuration:
-  License         :  LGPL only
- ])
-else
- AC_MSG_NOTICE([
-  License         :  LGPL or eCos
-])
-fi
+AS_IF([test "x$enable_https" = "xyes"],
+ [AC_MSG_NOTICE([HTTPS subsystem configuration:
+  License         :  LGPL version 2.1 or any later version
+ ])],
+ [AC_MSG_NOTICE([
+  License         :  LGPLv2.1+ or eCos
+ ])])
 
-if test "x$enable_bauth" != "xyes" -o \
-        "x$enable_dauth" != "xyes" -o \
-        "x$enable_postprocessor" != "xyes"
-then
- AC_MSG_NOTICE([WARNING: This will be a custom build with missing symbols. Do NOT use this build in a distribution. Building with these kinds of configure options is only for custom builds for embedded systems.])
-fi
+AS_IF([test "x$enable_bauth" != "xyes" || \
+   test "x$enable_dauth" != "xyes" || \
+   test "x${enable_md5}" = "xno" || \
+   test "x${enable_sha256}" = "xno" || \
+   test "x${enable_sha512_256}" != "xyes" || \
+   test "x$enable_httpupgrade" != "xyes" || \
+   test "x$enable_cookie" != "xyes" || \
+   test "x$enable_postprocessor" != "xyes"],
+   [AC_MSG_NOTICE([WARNING: This will be a custom build with missing symbols. Do NOT use this build in a distribution. Building with these kinds of configure options is only for custom builds for embedded systems.])])
diff --git a/contrib/Makefile.in b/contrib/Makefile.in
deleted file mode 100644
index 12f8fc4..0000000
--- a/contrib/Makefile.in
+++ /dev/null
@@ -1,483 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-subdir = contrib
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-EXTRA_DIST = xcc ascebc mhd.png mhd.svg mhd_logo.png
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu contrib/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu contrib/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-tags TAGS:
-
-ctags CTAGS:
-
-cscope cscopelist:
-
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-am
-all-am: Makefile
-installdirs:
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-	cscopelist-am ctags-am distclean distclean-generic \
-	distclean-libtool distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	maintainer-clean maintainer-clean-generic mostlyclean \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags-am uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/contrib/coverage.sh b/contrib/coverage.sh
new file mode 100755
index 0000000..7cf74b6
--- /dev/null
+++ b/contrib/coverage.sh
@@ -0,0 +1,14 @@
+#!/bin/sh
+# make sure configure was run with coverage enabled...
+lcov --directory . --zerocounters
+make check
+rm `find * -name "*_test.gc??"`  `find src/testcurl -name "*.gc??"` `find src/testzzuf -name "*.gc??"` `find src/examples -name "*.gc??"`
+for n in `find * -name "*.gc*" | grep libs`
+do
+  cd `dirname $n`
+  mv `basename $n` ..
+  cd -
+done
+lcov --directory . --capture --output-file app.info
+mkdir /tmp/coverage
+genhtml -o /tmp/coverage app.info
diff --git a/contrib/fixes-autoconf/apply-all.sh b/contrib/fixes-autoconf/apply-all.sh
new file mode 100755
index 0000000..1a9d725
--- /dev/null
+++ b/contrib/fixes-autoconf/apply-all.sh
@@ -0,0 +1,53 @@
+#!/bin/bash
+
+#
+# This file applies optional Autoconf patches for better MSys2 and new
+# compiler compatibility.
+#
+# Based on Debian SID baseline files as of April 2023.
+#
+
+patchesdir=$(dirname $BASH_SOURCE) || exit 2
+test -n "$patchesdir" || exit 2
+cd "$patchesdir" || exit 2
+patchesdir=$(pwd) || exit 2
+
+patches=(
+ # No patches currently
+)
+
+failed=( )
+
+cd "${patchesdir}/../.." || exit 1
+
+patch_params="-Nf -p1 --no-backup-if-mismatch -r - --read-only=fail"
+
+for patch in ${patches[@]}; do
+  patchfile="${patchesdir}/${patch}"
+  echo "*** Applying $patch..."
+  if echo "$patch_data" | patch $patch_params -i "$patchfile"
+  then
+    echo "** $patch successfully applied."
+  else
+    echo "** $patch failed."
+    failed+=("$patch")
+  fi
+  unset patch_data
+done
+
+
+addl_file="c_backported.m4"
+echo "*** Copying $addl_file"
+cp -fT "${patchesdir}/$addl_file" "m4/$addl_file" || exit 2
+echo "$addl_file copied."
+
+echo ''
+
+if [[ -n "${failed[@]}" ]]; then
+  printf '* Failed patch: %s\n' "${failed[@]}" >&2
+  exit 2
+else
+  echo "* All patches have been successfully applied."
+fi
+
+exit 0
diff --git a/contrib/fixes-autoconf/c_backported.m4 b/contrib/fixes-autoconf/c_backported.m4
new file mode 100644
index 0000000..0cac1dc
--- /dev/null
+++ b/contrib/fixes-autoconf/c_backported.m4
@@ -0,0 +1,567 @@
+# Backported macros from autoconf git master + a few custom patches
+
+# This file is part of Autoconf.			-*- Autoconf -*-
+# Programming languages support.
+# Copyright (C) 2001-2017, 2020-2023 Free Software Foundation, Inc.
+
+# This file is part of Autoconf.  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.
+#
+# Under Section 7 of GPL version 3, you are granted additional
+# permissions described in the Autoconf Configure Script Exception,
+# version 3.0, as published by the Free Software Foundation.
+#
+# You should have received a copy of the GNU General Public License
+# and a copy of the Autoconf Configure Script Exception along with
+# this program; see the files COPYINGv3 and COPYING.EXCEPTION
+# respectively.  If not, see <https://www.gnu.org/licenses/>.
+
+# Written by David MacKenzie, with help from
+# Akim Demaille, Paul Eggert,
+# François Pinard, Karl Berry, Richard Pixley, Ian Lance Taylor,
+# Roland McGrath, Noah Friedman, david d zuhn, and many others.
+
+# ---- Backported macros only ----
+
+AC_DEFUN([_AC_C_C89_TEST_GLOBALS],
+[m4_divert_text([INIT_PREPARE],
+[[# Test code for whether the C compiler supports C89 (global declarations)
+ac_c_conftest_c89_globals='
+/* Does the compiler advertise C89 conformance?
+   Do not test the value of __STDC__, because some compilers set it to 0
+   while being otherwise adequately conformant. */
+#if !defined __STDC__
+# error "Compiler does not advertise C89 conformance"
+#endif
+
+#include <stddef.h>
+#include <stdarg.h>
+struct stat;
+/* Most of the following tests are stolen from RCS 5.7 src/conf.sh.  */
+struct buf { int x; };
+struct buf * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (char **p, int i)
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* C89 style stringification. */
+#define noexpand_stringify(a) #a
+const char *stringified = noexpand_stringify(arbitrary+token=sequence);
+
+/* C89 style token pasting.  Exercises some of the corner cases that
+   e.g. old MSVC gets wrong, but not very hard. */
+#define noexpand_concat(a,b) a##b
+#define expand_concat(a,b) noexpand_concat(a,b)
+extern int vA;
+extern int vbee;
+#define aye A
+#define bee B
+int *pvA = &expand_concat(v,aye);
+int *pvbee = &noexpand_concat(v,bee);
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not \xHH hex character constants.
+   These do not provoke an error unfortunately, instead are silently treated
+   as an "x".  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously \x00 != x always comes out true, for an
+   array size at least.  It is necessary to write \x00 == 0 to get something
+   that is true only with -std.  */
+int osf4_cc_array ['\''\x00'\'' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) '\''x'\''
+int xlc6_cc_array[FOO(a) == '\''x'\'' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, int *(*)(struct buf *, struct stat *, int),
+               int, int);'
+]])])
+
+
+AC_DEFUN([_AC_C_C99_TEST_GLOBALS],
+[m4_divert_text([INIT_PREPARE],
+[[# Test code for whether the C compiler supports C99 (global declarations)
+ac_c_conftest_c99_globals='
+// Does the compiler advertise C99 conformance?
+#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L
+# error "Compiler does not advertise C99 conformance"
+#endif
+
+#include <stdbool.h>
+extern int puts (const char *);
+extern int printf (const char *, ...);
+extern int dprintf (int, const char *, ...);
+extern void *malloc (size_t);
+extern void free (void *);
+
+// Check varargs macros.  These examples are taken from C99 6.10.3.5.
+// dprintf is used instead of fprintf to avoid needing to declare
+// FILE and stderr.
+#define debug(...) dprintf (2, __VA_ARGS__)
+#define showlist(...) puts (#__VA_ARGS__)
+#define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__))
+static void
+test_varargs_macros (void)
+{
+  int x = 1234;
+  int y = 5678;
+  debug ("Flag");
+  debug ("X = %d\n", x);
+  showlist (The first, second, and third items.);
+  report (x>y, "x is %d but y is %d", x, y);
+}
+
+// Check long long types.
+#define BIG64 18446744073709551615ull
+#define BIG32 4294967295ul
+#define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0)
+#if !BIG_OK
+  #error "your preprocessor is broken"
+#endif
+#if BIG_OK
+#else
+  #error "your preprocessor is broken"
+#endif
+static long long int bignum = -9223372036854775807LL;
+static unsigned long long int ubignum = BIG64;
+
+struct incomplete_array
+{
+  int datasize;
+  double data[];
+};
+
+struct named_init {
+  int number;
+  const wchar_t *name;
+  double average;
+};
+
+typedef const char *ccp;
+
+static inline int
+test_restrict (ccp restrict text)
+{
+  // See if C++-style comments work.
+  // Iterate through items via the restricted pointer.
+  // Also check for declarations in for loops.
+  for (unsigned int i = 0; *(text+i) != '\''\0'\''; ++i)
+    continue;
+  return 0;
+}
+
+// Check varargs and va_copy.
+static bool
+test_varargs (const char *format, ...)
+{
+  va_list args;
+  va_start (args, format);
+  va_list args_copy;
+  va_copy (args_copy, args);
+
+  const char *str = "";
+  int number = 0;
+  float fnumber = 0;
+
+  while (*format)
+    {
+      switch (*format++)
+	{
+	case '\''s'\'': // string
+	  str = va_arg (args_copy, const char *);
+	  break;
+	case '\''d'\'': // int
+	  number = va_arg (args_copy, int);
+	  break;
+	case '\''f'\'': // float
+	  fnumber = va_arg (args_copy, double);
+	  break;
+	default:
+	  break;
+	}
+    }
+  va_end (args_copy);
+  va_end (args);
+
+  return *str && number && fnumber;
+}
+'
+]])])
+
+
+AC_DEFUN([_AC_C_C11_TEST_GLOBALS],
+[m4_divert_text([INIT_PREPARE],
+[[# Test code for whether the C compiler supports C11 (global declarations)
+ac_c_conftest_c11_globals='
+// Does the compiler advertise C11 conformance?
+#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112L
+# error "Compiler does not advertise C11 conformance"
+#endif
+
+// Check _Alignas.
+char _Alignas (double) aligned_as_double;
+char _Alignas (0) no_special_alignment;
+extern char aligned_as_int;
+char _Alignas (0) _Alignas (int) aligned_as_int;
+
+// Check _Alignof.
+enum
+{
+  int_alignment = _Alignof (int),
+  int_array_alignment = _Alignof (int[100]),
+  char_alignment = _Alignof (char)
+};
+_Static_assert (0 < -_Alignof (int), "_Alignof is signed");
+
+// Check _Noreturn.
+_Noreturn int does_not_return (void) { for (;;) continue; }
+
+// Check _Static_assert.
+struct test_static_assert
+{
+  int x;
+  _Static_assert (sizeof (int) <= sizeof (long int),
+                  "_Static_assert does not work in struct");
+  long int y;
+};
+
+// Check UTF-8 literals.
+#define u8 syntax error!
+char const utf8_literal[] = u8"happens to be ASCII" "another string";
+
+// Check duplicate typedefs.
+typedef long *long_ptr;
+typedef long int *long_ptr;
+typedef long_ptr long_ptr;
+
+// Anonymous structures and unions -- taken from C11 6.7.2.1 Example 1.
+struct anonymous
+{
+  union {
+    struct { int i; int j; };
+    struct { int k; long int l; } w;
+  };
+  int m;
+} v1;
+'
+]])])
+
+
+# AC_LANG_CALL(C)(PROLOGUE, FUNCTION)
+# -----------------------------------
+# Avoid conflicting decl of main.
+m4_define([AC_LANG_CALL(C)],
+[AC_LANG_PROGRAM([$1
+m4_if([$2], [main], ,
+[/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.
+   The 'extern "C"' is for builds by C++ compilers;
+   although this is not generally supported in C code supporting it here
+   has little cost and some practical benefit (sr 110532).  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $2 (void);])], [return $2 ();])])
+
+
+# AC_LANG_FUNC_LINK_TRY(C)(FUNCTION)
+# ----------------------------------
+# Don't include <ctype.h> because on OSF/1 3.0 it includes
+# <sys/types.h> which includes <sys/select.h> which contains a
+# prototype for select.  Similarly for bzero.
+#
+# This test used to merely assign f=$1 in main(), but that was
+# optimized away by HP unbundled cc A.05.36 for ia64 under +O3,
+# presumably on the basis that there's no need to do that store if the
+# program is about to exit.  Conversely, the AIX linker optimizes an
+# unused external declaration that initializes f=$1.  So this test
+# program has both an external initialization of f, and a use of f in
+# main that affects the exit status.
+#
+m4_define([AC_LANG_FUNC_LINK_TRY(C)],
+[AC_LANG_PROGRAM(
+[/* Define $1 to an innocuous variant, in case <limits.h> declares $1.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define $1 innocuous_$1
+
+/* System header to define __stub macros and hopefully few prototypes,
+   which can conflict with char $1 (void); below.  */
+
+#include <limits.h>
+#undef $1
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $1 (void);
+/* The GNU C library defines this for functions which it implements
+    to always fail with ENOSYS.  Some functions are actually named
+    something starting with __ and the normal name is an alias.  */
+#if defined __stub_$1 || defined __stub___$1
+choke me
+#endif
+], [return $1 ();])])
+
+
+# AC_C_BIGENDIAN ([ACTION-IF-TRUE], [ACTION-IF-FALSE], [ACTION-IF-UNKNOWN],
+#                 [ACTION-IF-UNIVERSAL])
+# -------------------------------------------------------------------------
+AC_DEFUN([AC_C_BIGENDIAN],
+[AH_VERBATIM([WORDS_BIGENDIAN],
+[/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+   significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+#  define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+#  undef WORDS_BIGENDIAN
+# endif
+#endif])dnl
+ AC_CACHE_CHECK([whether byte ordering is bigendian], [ac_cv_c_bigendian],
+   [ac_cv_c_bigendian=unknown
+    # See if we're dealing with a universal compiler.
+    AC_COMPILE_IFELSE(
+	 [AC_LANG_SOURCE(
+	    [[#ifndef __APPLE_CC__
+	       not a universal capable compiler
+	     #endif
+	     typedef int dummy;
+	    ]])],
+	 [
+	# Check for potential -arch flags.  It is not universal unless
+	# there are at least two -arch flags with different values.
+	ac_arch=
+	ac_prev=
+	for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do
+	 if test -n "$ac_prev"; then
+	   case $ac_word in
+	     i?86 | x86_64 | ppc | ppc64)
+	       if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then
+		 ac_arch=$ac_word
+	       else
+		 ac_cv_c_bigendian=universal
+		 break
+	       fi
+	       ;;
+	   esac
+	   ac_prev=
+	 elif test "x$ac_word" = "x-arch"; then
+	   ac_prev=arch
+	 fi
+       done])
+    if test $ac_cv_c_bigendian = unknown; then
+      # See if sys/param.h defines the BYTE_ORDER macro.
+      AC_COMPILE_IFELSE(
+	[AC_LANG_PROGRAM(
+	   [[#include <sys/types.h>
+	     #include <sys/param.h>
+	   ]],
+	   [[#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \\
+		     && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \\
+		     && LITTLE_ENDIAN)
+	      bogus endian macros
+	     #endif
+	   ]])],
+	[# It does; now see whether it defined to BIG_ENDIAN or not.
+	 AC_COMPILE_IFELSE(
+	   [AC_LANG_PROGRAM(
+	      [[#include <sys/types.h>
+		#include <sys/param.h>
+	      ]],
+	      [[#if BYTE_ORDER != BIG_ENDIAN
+		 not big endian
+		#endif
+	      ]])],
+	   [ac_cv_c_bigendian=yes],
+	   [ac_cv_c_bigendian=no])])
+    fi
+    if test $ac_cv_c_bigendian = unknown; then
+      # See if <limits.h> defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris).
+      AC_COMPILE_IFELSE(
+	[AC_LANG_PROGRAM(
+	   [[#include <limits.h>
+	   ]],
+	   [[#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN)
+	      bogus endian macros
+	     #endif
+	   ]])],
+	[# It does; now see whether it defined to _BIG_ENDIAN or not.
+	 AC_COMPILE_IFELSE(
+	   [AC_LANG_PROGRAM(
+	      [[#include <limits.h>
+	      ]],
+	      [[#ifndef _BIG_ENDIAN
+		 not big endian
+		#endif
+	      ]])],
+	   [ac_cv_c_bigendian=yes],
+	   [ac_cv_c_bigendian=no])])
+    fi
+    if test $ac_cv_c_bigendian = unknown; then
+      # Compile a test program.
+      AC_RUN_IFELSE(
+	[AC_LANG_PROGRAM([AC_INCLUDES_DEFAULT],
+	   [[
+	     /* Are we little or big endian?  From Harbison&Steele.  */
+	     union
+	     {
+	       long int l;
+	       char c[sizeof (long int)];
+	     } u;
+	     u.l = 1;
+	     return u.c[sizeof (long int) - 1] == 1;
+	   ]])],
+	[ac_cv_c_bigendian=no],
+	[ac_cv_c_bigendian=yes],
+	[# Try to guess by grepping values from an object file.
+	 AC_LINK_IFELSE(
+	   [AC_LANG_SOURCE(
+	      [[unsigned short int ascii_mm[] =
+		  { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
+		unsigned short int ascii_ii[] =
+		  { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
+		int use_ascii (int i) {
+		  return ascii_mm[i] + ascii_ii[i];
+		}
+		unsigned short int ebcdic_ii[] =
+		  { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
+		unsigned short int ebcdic_mm[] =
+		  { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
+		int use_ebcdic (int i) {
+		  return ebcdic_mm[i] + ebcdic_ii[i];
+		}
+		int
+		main (int argc, char **argv)
+		{
+		  /* Intimidate the compiler so that it does not
+		     optimize the arrays away.  */
+		  char *p = argv[0];
+		  ascii_mm[1] = *p++; ebcdic_mm[1] = *p++;
+		  ascii_ii[1] = *p++; ebcdic_ii[1] = *p++;
+		  return use_ascii (argc) == use_ebcdic (*p);
+		}]])],
+	   [if grep BIGenDianSyS conftest$ac_exeext >/dev/null; then
+	      ac_cv_c_bigendian=yes
+	    fi
+	    if grep LiTTleEnDian conftest$ac_exeext >/dev/null ; then
+	      if test "$ac_cv_c_bigendian" = unknown; then
+		ac_cv_c_bigendian=no
+	      else
+		# finding both strings is unlikely to happen, but who knows?
+		ac_cv_c_bigendian=unknown
+	      fi
+	    fi])])
+    fi])
+ case $ac_cv_c_bigendian in #(
+   yes)
+     m4_default([$1],
+       [AC_DEFINE([WORDS_BIGENDIAN], 1)]);; #(
+   no)
+     $2 ;; #(
+   universal)
+dnl Note that AC_APPLE_UNIVERSAL_BUILD sorts less than WORDS_BIGENDIAN;
+dnl this is a necessity for proper config header operation.  Warn if
+dnl the user did not specify a config header but is relying on the
+dnl default behavior for universal builds.
+     m4_default([$4],
+       [AC_CONFIG_COMMANDS_PRE([m4_ifset([AH_HEADER], [],
+	 [m4_warn([obsolete],
+	   [AC_C_BIGENDIAN should be used with AC_CONFIG_HEADERS])])])dnl
+	AC_DEFINE([AC_APPLE_UNIVERSAL_BUILD],1,
+	  [Define if building universal (internal helper macro)])])
+     ;; #(
+   *)
+     m4_default([$3],
+       [AC_MSG_ERROR([unknown endianness
+ presetting ac_cv_c_bigendian=no (or yes) will help])]) ;;
+ esac
+])# AC_C_BIGENDIAN
+
+
+# AC_C_VARARRAYS
+# --------------
+# Check whether the C compiler supports variable-length arrays.
+AC_DEFUN([AC_C_VARARRAYS],
+[
+  AC_CACHE_CHECK([for variable-length arrays],
+    ac_cv_c_vararrays,
+    [AC_COMPILE_IFELSE([AC_LANG_SOURCE(
+[[	#ifndef __STDC_NO_VLA__
+	#error __STDC_NO_VLA__ not defined
+	choke me now
+	#endif
+]])],
+       [ac_cv_c_vararrays='no: __STDC_NO_VLA__ is defined'],
+       [AC_COMPILE_IFELSE(
+	  [AC_LANG_PROGRAM(
+	     [[/* Test for VLA support.  This test is partly inspired
+		  from examples in the C standard.  Use at least two VLA
+		  functions to detect the GCC 3.4.3 bug described in:
+		  https://lists.gnu.org/archive/html/bug-gnulib/2014-08/msg00014.html
+		  */
+	       #ifdef __STDC_NO_VLA__
+		syntax error;
+	       #else
+		 extern int n;
+		 static int B[100];
+		 int fvla (int m, int C[m][m]);
+
+		 static int
+		 simple (int count, int all[static count])
+		 {
+		   return all[count - 1];
+		 }
+
+		 int
+		 fvla (int m, int C[m][m])
+		 {
+		   typedef int VLA[m][m];
+		   VLA x;
+		   int D[m];
+		   static int (*q)[m] = &B;
+		   int (*s)[n] = q;
+		   (void) simple;
+		   return C && &x[0][0] == &D[0] && &D[0] == s[0];
+		 }
+	       #endif
+	       ]])],
+	  [ac_cv_c_vararrays=yes],
+	  [ac_cv_c_vararrays=no])])])
+  if test "$ac_cv_c_vararrays" = yes; then
+    dnl This is for compatibility with Autoconf 2.61-2.69.
+    AC_DEFINE([HAVE_C_VARARRAYS], 1,
+      [Define to 1 if C supports variable-length arrays.])
+  elif test "$ac_cv_c_vararrays" = no; then
+    AC_DEFINE([__STDC_NO_VLA__], 1,
+      [Define to 1 if C does not support variable-length arrays, and
+       if the compiler does not already define this.])
+  fi
+])
+
diff --git a/contrib/fixes-libtool/0003-Pass-various-runtime-library-flags-to-GCC.mingw.mod.patch b/contrib/fixes-libtool/0003-Pass-various-runtime-library-flags-to-GCC.mingw.mod.patch
new file mode 100644
index 0000000..4207374
--- /dev/null
+++ b/contrib/fixes-libtool/0003-Pass-various-runtime-library-flags-to-GCC.mingw.mod.patch
@@ -0,0 +1,31 @@
+The patch below was modified to work on top of Debian patches
+
+[PATCH 3/6] Pass various runtime library flags to GCC.
+* build-aux/ltmain.in (func_mode_link): Pass the
+-shared-libgcc and -static-lib* flags along to GCC.
+
+diff -urN libtool-2.4.7/build-aux/ltmain.in.orig libtool-2.4.7/build-aux/ltmain.in
+--- libtool-2.4.7/build-aux/ltmain.in.orig	2022-05-25 13:57:50.311734300 +0200
++++ libtool-2.4.7/build-aux/ltmain.in	2022-05-25 14:01:54.621866600 +0200
+@@ -7559,15 +7559,19 @@
+       # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
+       # -specs=*             GCC specs files
+       # -stdlib=*            select c++ std lib with clang
++      # -{shared,static}-libgcc, -static-{libgfortran|libstdc++}
++      #                      link against specified runtime library
+       # -fsanitize=*         Clang/GCC memory and address sanitizer
+       # -fuse-ld=*           Linker select flags for GCC
+-      # -static-*            direct GCC to link specific libraries statically
+       # -fcilkplus           Cilk Plus language extension features for C/C++
+       # -Wa,*                Pass flags directly to the assembler
+       -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
+       -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
+       -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \
+-      -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus|-Wa,*)
++      -specs=*|-fsanitize=*|-fuse-ld=*|-Wa,*|-ftree-parallelize-loops=*| \
++      -fcilkplus|-fgnu-tm|-ffast-math|-funsafe-math-optimizations| \
++      -fvtable-verify*|-shared-libgcc|-static-libgcc|-static-libgfortran| \
++      -static-libstdc++)
+         func_quote_arg pretty "$arg"
+ 	arg=$func_quote_arg_result
+         func_append compile_command " $arg"
diff --git a/contrib/fixes-libtool/0006-Fix-strict-ansi-vs-posix.patch b/contrib/fixes-libtool/0006-Fix-strict-ansi-vs-posix.patch
new file mode 100644
index 0000000..486ad76
--- /dev/null
+++ b/contrib/fixes-libtool/0006-Fix-strict-ansi-vs-posix.patch
@@ -0,0 +1,22 @@
+[PATCH 6/6] Fix STRICT_ANSI vs POSIX
+* build-aux/ltmain.in (func_mode_link): Also check for _POSIX
+as well as __STRICT_ANSI__ to avoid re-definitions.
+---
+ build-aux/ltmain.in |    4 +++-
+ 1 files changed, 1 insertions(+), 1 deletions(-)
+
+diff --git a/build-aux/ltmain.in b/build-aux/ltmain.in
+index af46cb8..244bb5b 100644
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -3382,7 +3382,7 @@
+ 
+ /* declarations of non-ANSI functions */
+ #if defined __MINGW32__
+-# ifdef __STRICT_ANSI__
++# if defined(__STRICT_ANSI__) && !defined(__MINGW64_VERSION_MAJOR) || defined(_POSIX_)
+ int _putenv (const char *);
+ # endif
+ #elif defined __CYGWIN__
+-- 
+1.7.0.2.msysgit.0
\ No newline at end of file
diff --git a/contrib/fixes-libtool/0009-libtool-2.4.2.418-msysize.patch b/contrib/fixes-libtool/0009-libtool-2.4.2.418-msysize.patch
new file mode 100644
index 0000000..1997342
--- /dev/null
+++ b/contrib/fixes-libtool/0009-libtool-2.4.2.418-msysize.patch
@@ -0,0 +1,1403 @@
+diff -urN libtool-2.4.7/build-aux/config.guess.orig libtool-2.4.7/build-aux/config.guess
+--- libtool-2.4.7/build-aux/config.guess.orig	2022-05-25 14:18:47.388587800 +0200
++++ libtool-2.4.7/build-aux/config.guess	2022-05-25 14:21:50.720326000 +0200
+@@ -950,6 +950,9 @@
+     amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+ 	GUESS=x86_64-pc-cygwin
+ 	;;
++    amd64:MSYS*:*:* | x86_64:MSYS*:*:*)
++	GUESS=x86_64-pc-msys
++	;;
+     prep*:SunOS:5.*:*)
+ 	SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`
+ 	GUESS=powerpcle-unknown-solaris2$SUN_REL
+
+diff -Naur libtool-2.4.3-orig/build-aux/ltmain.in libtool-2.4.3/build-aux/ltmain.in
+--- libtool-2.4.3-orig/build-aux/ltmain.in	2014-09-02 09:54:56.481600000 +0400
++++ libtool-2.4.3/build-aux/ltmain.in	2014-09-02 10:14:04.809600000 +0400
+@@ -497,7 +497,7 @@
+     case $host in
+       # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452
+       # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788
+-      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)
++      *cygwin* | *msys* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)
+         # don't eliminate duplications in $postdeps and $predeps
+         opt_duplicate_compiler_generated_deps=:
+         ;;
+@@ -1510,7 +1510,7 @@
+ 
+     # On Cygwin there's no "real" PIC flag so we must build both object types
+     case $host_os in
+-    cygwin* | mingw* | pw32* | os2* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | os2* | cegcc*)
+       pic_mode=default
+       ;;
+     esac
+@@ -2383,7 +2383,7 @@
+ 	      'exit $?'
+ 	  tstripme=$stripme
+ 	  case $host_os in
+-	  cygwin* | mingw* | pw32* | cegcc*)
++	  cygwin* | msys* | mingw* | pw32* | cegcc*)
+ 	    case $realname in
+ 	    *.dll.a)
+ 	      tstripme=
+@@ -2489,7 +2489,7 @@
+ 
+ 	# Do a test to see if this is really a libtool program.
+ 	case $host in
+-	*cygwin* | *mingw*)
++	*cygwin* | *msys* | *mingw*)
+ 	    if func_ltwrapper_executable_p "$file"; then
+ 	      func_ltwrapper_scriptname "$file"
+ 	      wrapper=$func_ltwrapper_scriptname_result
+@@ -2564,7 +2564,7 @@
+ 	# remove .exe since cygwin /usr/bin/install will append another
+ 	# one anyway
+ 	case $install_prog,$host in
+-	*/usr/bin/install*,*cygwin*)
++	*/usr/bin/install*,*cygwin*|*/usr/bin/install*,*msys*)
+ 	  case $file:$destfile in
+ 	  *.exe:*.exe)
+ 	    # this is ok
+@@ -2717,7 +2717,7 @@
+ 	      $RM $export_symbols
+ 	      eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+ 	      case $host in
+-	      *cygwin* | *mingw* | *cegcc* )
++	      *cygwin* | *msys* | *mingw* | *cegcc* )
+                 eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+                 eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+ 	        ;;
+@@ -2729,7 +2729,7 @@
+ 	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+ 	      eval '$MV "$nlist"T "$nlist"'
+ 	      case $host in
+-	        *cygwin* | *mingw* | *cegcc* )
++	        *cygwin* | *msys* | *mingw* | *cegcc* )
+ 	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ 	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+ 	          ;;
+@@ -2743,7 +2743,7 @@
+ 	  func_basename "$dlprefile"
+ 	  name=$func_basename_result
+           case $host in
+-	    *cygwin* | *mingw* | *cegcc* )
++	    *cygwin* | *msys* | *mingw* | *cegcc* )
+ 	      # if an import library, we need to obtain dlname
+ 	      if func_win32_import_lib_p "$dlprefile"; then
+ 	        func_tr_sh "$dlprefile"
+@@ -2918,7 +2918,7 @@
+ 	# Transform the symbol file into the correct name.
+ 	symfileobj=$output_objdir/${my_outputname}S.$objext
+ 	case $host in
+-	*cygwin* | *mingw* | *cegcc* )
++	*cygwin* | *msys* | *mingw* | *cegcc* )
+ 	  if test -f "$output_objdir/$my_outputname.def"; then
+ 	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+ 	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+@@ -3811,7 +3811,7 @@
+ 	{
+ EOF
+ 	    case $host in
+-	      *mingw* | *cygwin* )
++	      *mingw* | *cygwin* | *msys* )
+ 		# make stdout use "unix" line endings
+ 		echo "          setmode(1,_O_BINARY);"
+ 		;;
+@@ -4567,7 +4567,7 @@
+     $debug_cmd
+ 
+     case $host in
+-    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
++    *-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+       # It is impossible to link a dll without this setting, and
+       # we shouldn't force the makefile maintainer to figure out
+       # what system we are compiling for in order to pass an extra
+@@ -5060,7 +5060,7 @@
+ 	  ;;
+ 	esac
+ 	case $host in
+-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
++	*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+ 	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
+ 	  case :$dllsearchpath: in
+ 	  *":$dir:"*) ;;
+@@ -5080,7 +5080,7 @@
+       -l*)
+ 	if test X-lc = "X$arg" || test X-lm = "X$arg"; then
+ 	  case $host in
+-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
++	  *-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
+ 	    # These systems don't actually have a C or math library (as such)
+ 	    continue
+ 	    ;;
+@@ -5163,7 +5163,7 @@
+ 
+       -no-install)
+ 	case $host in
+-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
++	*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
+ 	  # The PATH hackery in wrapper scripts is required on Windows
+ 	  # and Darwin in order for the loader to find any dlls it needs.
+ 	  func_warning "'-no-install' is ignored for $host"
+@@ -6034,7 +6034,7 @@
+ 	  fi
+ 	  case $host in
+ 	    # special handling for platforms with PE-DLLs.
+-	    *cygwin* | *mingw* | *cegcc* )
++	    *cygwin* | *msys* | *mingw* | *cegcc* )
+ 	      # Linker will automatically link against shared library if both
+ 	      # static and shared are present.  Therefore, ensure we extract
+ 	      # symbols from the import library if a shared library is present
+@@ -6178,7 +6178,7 @@
+ 	if test -n "$library_names" &&
+ 	   { test no = "$use_static_libs" || test -z "$old_library"; }; then
+ 	  case $host in
+-	  *cygwin* | *mingw* | *cegcc* | *os2*)
++	  *cygwin* | *msys* | *mingw* | *cegcc* | *os2*)
+ 	      # No point in relinking DLLs because paths are not encoded
+ 	      func_append notinst_deplibs " $lib"
+ 	      need_relink=no
+@@ -6248,7 +6248,7 @@
+ 	    elif test -n "$soname_spec"; then
+ 	      # bleh windows
+ 	      case $host in
+-	      *cygwin* | mingw* | *cegcc* | *os2*)
++	      *cygwin* | *msys* | mingw* | *cegcc* | *os2*)
+ 	        func_arith $current - $age
+ 		major=$func_arith_result
+ 		versuffix=-$major
+@@ -7123,7 +7123,7 @@
+       if test yes = "$build_libtool_libs"; then
+ 	if test -n "$rpath"; then
+ 	  case $host in
+-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
++	  *-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
+ 	    # these systems don't actually have a c library (as such)!
+ 	    ;;
+ 	  *-*-rhapsody* | *-*-darwin1.[012])
+@@ -7637,7 +7637,7 @@
+ 
+ 	orig_export_symbols=
+ 	case $host_os in
+-	cygwin* | mingw* | cegcc*)
++	cygwin* | msys* | mingw* | cegcc*)
+ 	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
+ 	    # exporting using user supplied symfile
+ 	    func_dll_def_p "$export_symbols" || {
+@@ -8194,7 +8194,7 @@
+ 
+     prog)
+       case $host in
+-	*cygwin*) func_stripname '' '.exe' "$output"
++	*cygwin* | *msys*) func_stripname '' '.exe' "$output"
+ 	          output=$func_stripname_result.exe;;
+       esac
+       test -n "$vinfo" && \
+@@ -8305,7 +8305,7 @@
+ 	  esac
+ 	fi
+ 	case $host in
+-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
++	*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+ 	  testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'`
+ 	  case :$dllsearchpath: in
+ 	  *":$libdir:"*) ;;
+@@ -8383,7 +8383,7 @@
+         # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+         wrappers_required=false
+         ;;
+-      *cygwin* | *mingw* )
++      *cygwin* | *msys* | *mingw* )
+         test yes = "$build_libtool_libs" || wrappers_required=false
+         ;;
+       *)
+@@ -8529,14 +8529,14 @@
+ 	esac
+ 	# test for cygwin because mv fails w/o .exe extensions
+ 	case $host in
+-	  *cygwin*)
++	  *cygwin* | *msys*)
+ 	    exeext=.exe
+ 	    func_stripname '' '.exe' "$outputname"
+ 	    outputname=$func_stripname_result ;;
+ 	  *) exeext= ;;
+ 	esac
+ 	case $host in
+-	  *cygwin* | *mingw* )
++	  *cygwin* | *msys* | *mingw* )
+ 	    func_dirname_and_basename "$output" "" "."
+ 	    output_name=$func_basename_result
+ 	    output_path=$func_dirname_result
+@@ -8878,7 +8878,7 @@
+ 	  # tests/bindir.at for full details.
+ 	  tdlname=$dlname
+ 	  case $host,$output,$installed,$module,$dlname in
+-	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
++	    *cygwin*,*lai,yes,no,*.dll | *msys*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+ 	      # If a -bindir argument was supplied, place the dll there.
+ 	      if test -n "$bindir"; then
+ 		func_relative_path "$install_libdir" "$bindir"
+
+diff -Naur libtool-2.4.2.418-orig/build-aux/ltmain.sh libtool-2.4.2.418/build-aux/ltmain.sh
+--- libtool-2.4.2.418-orig/build-aux/ltmain.sh	2013-10-27 02:53:58.000000000 +0400
++++ libtool-2.4.2.418/build-aux/ltmain.sh	2014-09-02 10:29:08.840800000 +0400
+@@ -2315,7 +2315,7 @@
+     case $host in
+       # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452
+       # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788
+-      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)
++      *cygwin* | *msys* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)
+         # don't eliminate duplications in $postdeps and $predeps
+         opt_duplicate_compiler_generated_deps=:
+         ;;
+@@ -3328,7 +3328,7 @@
+ 
+     # On Cygwin there's no "real" PIC flag so we must build both object types
+     case $host_os in
+-    cygwin* | mingw* | pw32* | os2* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | os2* | cegcc*)
+       pic_mode=default
+       ;;
+     esac
+@@ -4201,7 +4201,7 @@
+ 	      'exit $?'
+ 	  tstripme=$stripme
+ 	  case $host_os in
+-	  cygwin* | mingw* | pw32* | cegcc*)
++	  cygwin* | msys* | mingw* | pw32* | cegcc*)
+ 	    case $realname in
+ 	    *.dll.a)
+ 	      tstripme=
+@@ -4307,7 +4307,7 @@
+ 
+ 	# Do a test to see if this is really a libtool program.
+ 	case $host in
+-	*cygwin* | *mingw*)
++	*cygwin* | *msys* | *mingw*)
+ 	    if func_ltwrapper_executable_p "$file"; then
+ 	      func_ltwrapper_scriptname "$file"
+ 	      wrapper=$func_ltwrapper_scriptname_result
+@@ -4382,7 +4382,7 @@
+ 	# remove .exe since cygwin /usr/bin/install will append another
+ 	# one anyway
+ 	case $install_prog,$host in
+-	*/usr/bin/install*,*cygwin*)
++	*/usr/bin/install*,*cygwin* | */usr/bin/install*,*msys*)
+ 	  case $file:$destfile in
+ 	  *.exe:*.exe)
+ 	    # this is ok
+@@ -4535,7 +4535,7 @@
+ 	      $RM $export_symbols
+ 	      eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
+ 	      case $host in
+-	      *cygwin* | *mingw* | *cegcc* )
++	      *cygwin* | *msys* | *mingw* | *cegcc* )
+                 eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+                 eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
+ 	        ;;
+@@ -4547,7 +4547,7 @@
+ 	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
+ 	      eval '$MV "$nlist"T "$nlist"'
+ 	      case $host in
+-	        *cygwin* | *mingw* | *cegcc* )
++	        *cygwin* | *msys* | *mingw* | *cegcc* )
+ 	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+ 	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+ 	          ;;
+@@ -4561,7 +4561,7 @@
+ 	  func_basename "$dlprefile"
+ 	  name=$func_basename_result
+           case $host in
+-	    *cygwin* | *mingw* | *cegcc* )
++	    *cygwin* | *msys* | *mingw* | *cegcc* )
+ 	      # if an import library, we need to obtain dlname
+ 	      if func_win32_import_lib_p "$dlprefile"; then
+ 	        func_tr_sh "$dlprefile"
+@@ -4736,7 +4736,7 @@
+ 	# Transform the symbol file into the correct name.
+ 	symfileobj=$output_objdir/${my_outputname}S.$objext
+ 	case $host in
+-	*cygwin* | *mingw* | *cegcc* )
++	*cygwin* | *msys* | *mingw* | *cegcc* )
+ 	  if test -f "$output_objdir/$my_outputname.def"; then
+ 	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+ 	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
+@@ -5629,7 +5629,7 @@
+ 	{
+ EOF
+ 	    case $host in
+-	      *mingw* | *cygwin* )
++	      *mingw* | *cygwin* | *msys* )
+ 		# make stdout use "unix" line endings
+ 		echo "          setmode(1,_O_BINARY);"
+ 		;;
+@@ -6350,7 +6350,7 @@
+     $debug_cmd
+ 
+     case $host in
+-    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
++    *-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+       # It is impossible to link a dll without this setting, and
+       # we shouldn't force the makefile maintainer to figure out
+       # what system we are compiling for in order to pass an extra
+@@ -6843,7 +6843,7 @@
+ 	  ;;
+ 	esac
+ 	case $host in
+-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
++	*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+ 	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
+ 	  case :$dllsearchpath: in
+ 	  *":$dir:"*) ;;
+@@ -6863,7 +6863,7 @@
+       -l*)
+ 	if test X-lc = "X$arg" || test X-lm = "X$arg"; then
+ 	  case $host in
+-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
++	  *-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
+ 	    # These systems don't actually have a C or math library (as such)
+ 	    continue
+ 	    ;;
+@@ -6946,7 +6946,7 @@
+ 
+       -no-install)
+ 	case $host in
+-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
++	*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
+ 	  # The PATH hackery in wrapper scripts is required on Windows
+ 	  # and Darwin in order for the loader to find any dlls it needs.
+ 	  func_warning "'-no-install' is ignored for $host"
+@@ -7812,7 +7812,7 @@
+ 	  fi
+ 	  case $host in
+ 	    # special handling for platforms with PE-DLLs.
+-	    *cygwin* | *mingw* | *cegcc* )
++	    *cygwin* | *msys* | *mingw* | *cegcc* )
+ 	      # Linker will automatically link against shared library if both
+ 	      # static and shared are present.  Therefore, ensure we extract
+ 	      # symbols from the import library if a shared library is present
+@@ -7956,7 +7956,7 @@
+ 	if test -n "$library_names" &&
+ 	   { test no = "$use_static_libs" || test -z "$old_library"; }; then
+ 	  case $host in
+-	  *cygwin* | *mingw* | *cegcc* | *os2*)
++	  *cygwin* | *msys* | *mingw* | *cegcc* | *os2*)
+ 	      # No point in relinking DLLs because paths are not encoded
+ 	      func_append notinst_deplibs " $lib"
+ 	      need_relink=no
+@@ -8026,7 +8026,7 @@
+ 	    elif test -n "$soname_spec"; then
+ 	      # bleh windows
+ 	      case $host in
+-	      *cygwin* | mingw* | *cegcc* | *os2*)
++	      *cygwin* | *msys* | mingw* | *cegcc* | *os2*)
+ 	        func_arith $current - $age
+ 		major=$func_arith_result
+ 		versuffix=-$major
+@@ -8899,7 +8899,7 @@
+       if test yes = "$build_libtool_libs"; then
+ 	if test -n "$rpath"; then
+ 	  case $host in
+-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
++	  *-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
+ 	    # these systems don't actually have a c library (as such)!
+ 	    ;;
+ 	  *-*-rhapsody* | *-*-darwin1.[012])
+@@ -9413,7 +9413,7 @@
+ 
+ 	orig_export_symbols=
+ 	case $host_os in
+-	cygwin* | mingw* | cegcc*)
++	cygwin* | *msys* | mingw* | cegcc*)
+ 	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
+ 	    # exporting using user supplied symfile
+ 	    func_dll_def_p "$export_symbols" || {
+@@ -9970,7 +9970,7 @@
+ 
+     prog)
+       case $host in
+-	*cygwin*) func_stripname '' '.exe' "$output"
++	*cygwin* | *msys*) func_stripname '' '.exe' "$output"
+ 	          output=$func_stripname_result.exe;;
+       esac
+       test -n "$vinfo" && \
+@@ -10081,7 +10081,7 @@
+ 	  esac
+ 	fi
+ 	case $host in
+-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
++	*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+ 	  testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'`
+ 	  case :$dllsearchpath: in
+ 	  *":$libdir:"*) ;;
+@@ -10159,7 +10159,7 @@
+         # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
+         wrappers_required=false
+         ;;
+-      *cygwin* | *mingw* )
++      *cygwin* | *msys* | *mingw* )
+         test yes = "$build_libtool_libs" || wrappers_required=false
+         ;;
+       *)
+@@ -10305,14 +10305,14 @@
+ 	esac
+ 	# test for cygwin because mv fails w/o .exe extensions
+ 	case $host in
+-	  *cygwin*)
++	  *cygwin* | *msys*)
+ 	    exeext=.exe
+ 	    func_stripname '' '.exe' "$outputname"
+ 	    outputname=$func_stripname_result ;;
+ 	  *) exeext= ;;
+ 	esac
+ 	case $host in
+-	  *cygwin* | *mingw* )
++	  *cygwin* | *msys* | *mingw* )
+ 	    func_dirname_and_basename "$output" "" "."
+ 	    output_name=$func_basename_result
+ 	    output_path=$func_dirname_result
+@@ -10644,7 +10644,7 @@
+ 	  # tests/bindir.at for full details.
+ 	  tdlname=$dlname
+ 	  case $host,$output,$installed,$module,$dlname in
+-	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
++	    *cygwin*,*lai,yes,no,*.dll | *msys*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
+ 	      # If a -bindir argument was supplied, place the dll there.
+ 	      if test -n "$bindir"; then
+ 		func_relative_path "$install_libdir" "$bindir"
+--- libtool-2.4.7/configure.orig	2022-05-25 14:05:58.332605400 +0200
++++ libtool-2.4.7/configure	2022-05-25 14:11:29.613646200 +0200
+@@ -5988,7 +5988,7 @@
+     lt_cv_sys_max_cmd_len=-1;
+     ;;
+ 
+-  cygwin* | mingw* | cegcc*)
++  cygwin* | msys* | mingw* | cegcc*)
+     # On Win9x/ME, this test blows up -- it succeeds, but takes
+     # about 5 minutes as the teststring grows exponentially.
+     # Worse, since 9x/ME are not pre-emptively multitasking,
+@@ -6154,7 +6154,7 @@
+       *-*-mingw* ) # actually msys
+         lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+         ;;
+-      *-*-cygwin* )
++      *-*-cygwin* | *-*-msys* )
+         lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+         ;;
+       * ) # otherwise, assume *nix
+@@ -6162,12 +6162,12 @@
+         ;;
+     esac
+     ;;
+-  *-*-cygwin* )
++  *-*-cygwin* | *-*-msys* )
+     case $build in
+       *-*-mingw* ) # actually msys
+         lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+         ;;
+-      *-*-cygwin* )
++      *-*-cygwin* | *-*-msys* )
+         lt_cv_to_host_file_cmd=func_convert_file_noop
+         ;;
+       * ) # otherwise, assume *nix
+@@ -6233,7 +6233,7 @@
+ esac
+ reload_cmds='$LD$reload_flag -o $output$reload_objs'
+ case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     if test yes != "$GCC"; then
+       reload_cmds=false
+     fi
+@@ -6486,7 +6486,7 @@
+   lt_cv_file_magic_test_file=/shlib/libc.so
+   ;;
+ 
+-cygwin*)
++cygwin* | msys*)
+   # func_win32_libid is a shell function defined in ltmain.sh
+   lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+   lt_cv_file_magic_cmd='func_win32_libid'
+@@ -6802,7 +6802,7 @@
+   lt_cv_sharedlib_from_linklib_cmd='unknown'
+ 
+ case $host_os in
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   # two different shell functions defined in ltmain.sh;
+   # decide which one to use based on capabilities of $DLLTOOL
+   case `$DLLTOOL --help 2>&1` in
+@@ -7310,7 +7310,7 @@
+ aix*)
+   symcode='[BCDT]'
+   ;;
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   symcode='[ABCDGISTW]'
+   ;;
+ hpux*)
+@@ -8912,7 +8912,7 @@
+ enable_win32_dll=yes
+ 
+ case $host in
+-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
++*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
+   if test -n "$ac_tool_prefix"; then
+   # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args.
+ set dummy ${ac_tool_prefix}as; ac_word=$2
+@@ -9813,7 +9813,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -9916,7 +9916,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       lt_prog_compiler_pic='-DDLL_EXPORT'
+@@ -10418,7 +10418,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -10533,7 +10533,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
+       # as there is no search path for DLLs.
+       hardcode_libdir_flag_spec='-L$libdir'
+@@ -11074,7 +11074,7 @@
+       export_dynamic_flag_spec=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+@@ -12110,7 +12110,7 @@
+   # libtool to hard-code these into programs
+   ;;
+ 
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   version_type=windows
+   shrext_cmds=.dll
+   need_version=no
+@@ -12136,9 +12136,9 @@
+     shlibpath_overrides_runpath=yes
+ 
+     case $host_os in
+-    cygwin*)
++    cygwin* | msys*)
+       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+-      soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
++      soname_spec='`echo $libname | $SED -e 's/^lib/msys-/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
+ 
+       sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"
+       ;;
+@@ -12176,7 +12176,7 @@
+       # Convert to MSYS style.
+       sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+       ;;
+-    cygwin*)
++    cygwin* | msys*)
+       # Convert to unix form, then to dos form, then back to unix form
+       # but this time dos style (no spaces!) so that the unix form looks
+       # like /cygdrive/c/PROGRA~1:/cygdr...
+@@ -12878,7 +12878,7 @@
+     lt_cv_dlopen_libs=
+     ;;
+ 
+-  cygwin*)
++  cygwin* | msys*)
+     lt_cv_dlopen=dlopen
+     lt_cv_dlopen_libs=
+     ;;
+@@ -13827,7 +13827,7 @@
+ beos*)
+   LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la"
+   ;;
+-cygwin* | mingw* | pw32*)
++cygwin* | msys* | mingw* | pw32*)
+   ac_fn_c_check_decl "$LINENO" "cygwin_conv_path" "ac_cv_have_decl_cygwin_conv_path" "#include <sys/cygwin.h>
+ "
+ if test "x$ac_cv_have_decl_cygwin_conv_path" = xyes; then :
+@@ -14242,7 +14242,7 @@
+   $as_echo_n "(cached) " >&6
+ else
+   case $host_os in #(
+-	 *cygwin*)
++	 *cygwin* | *msys*)
+ 	   lt_cv_sys_argz_works=no
+ 	   if test no != "$cross_compiling"; then
+ 	     lt_cv_sys_argz_works="guessing no"
+@@ -15517,7 +15517,7 @@
+         esac
+         ;;
+ 
+-      cygwin* | mingw* | pw32* | cegcc*)
++      cygwin* | msys* | mingw* | pw32* | cegcc*)
+ 	case $GXX,$cc_basename in
+ 	,cl* | no,cl* | ,icl* | no,icl*)
+ 	  # Native MSVC or ICC
+@@ -16528,7 +16528,7 @@
+     beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+       # PIC is the default for these OSes.
+       ;;
+-    mingw* | cygwin* | os2* | pw32* | cegcc*)
++    mingw* | cygwin* | msys* | os2* | pw32* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -16603,7 +16603,7 @@
+ 	  ;;
+ 	esac
+ 	;;
+-      mingw* | cygwin* | os2* | pw32* | cegcc*)
++      mingw* | cygwin* | msys* | os2* | pw32* | cegcc*)
+ 	# This hack is so that the source file can tell whether it is being
+ 	# built for inclusion in a dll (and should export symbols for example).
+ 	lt_prog_compiler_pic_CXX='-DDLL_EXPORT'
+@@ -17092,7 +17092,7 @@
+   pw32*)
+     export_symbols_cmds_CXX=$ltdll_cmds
+     ;;
+-  cygwin* | mingw* | cegcc*)
++  cygwin* | msys* | mingw* | cegcc*)
+     case $cc_basename in
+     cl* | icl*)
+       exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+@@ -17413,7 +17413,7 @@
+   # libtool to hard-code these into programs
+   ;;
+ 
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   version_type=windows
+   shrext_cmds=.dll
+   need_version=no
+@@ -17439,7 +17439,7 @@
+     shlibpath_overrides_runpath=yes
+ 
+     case $host_os in
+-    cygwin*)
++    cygwin* | msys*)
+       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+-      soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
++      soname_spec='`echo $libname | $SED -e 's/^lib/msys-/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
+ 
+@@ -17478,7 +17478,7 @@
+       # Convert to MSYS style.
+       sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+       ;;
+-    cygwin*)
++    cygwin* | msys*)
+       # Convert to unix form, then to dos form, then back to unix form
+       # but this time dos style (no spaces!) so that the unix form looks
+       # like /cygdrive/c/PROGRA~1:/cygdr...
+@@ -18519,7 +18519,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -18622,7 +18622,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       lt_prog_compiler_pic_F77='-DDLL_EXPORT'
+@@ -19109,7 +19109,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -19224,7 +19224,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningless,
+       # as there is no search path for DLLs.
+       hardcode_libdir_flag_spec_F77='-L$libdir'
+@@ -19753,7 +19753,7 @@
+       export_dynamic_flag_spec_F77=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+@@ -20581,7 +20581,7 @@
+   # libtool to hard-code these into programs
+   ;;
+ 
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   version_type=windows
+   shrext_cmds=.dll
+   need_version=no
+@@ -20607,9 +20607,9 @@
+     shlibpath_overrides_runpath=yes
+ 
+     case $host_os in
+-    cygwin*)
++    cygwin* | msys*)
+       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+-      soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
++      soname_spec='`echo $libname | $SED -e 's/^lib/msys-/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
+ 
+       ;;
+     mingw* | cegcc*)
+@@ -20646,7 +20646,7 @@
+       # Convert to MSYS style.
+       sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+       ;;
+-    cygwin*)
++    cygwin* | msys*)
+       # Convert to unix form, then to dos form, then back to unix form
+       # but this time dos style (no spaces!) so that the unix form looks
+       # like /cygdrive/c/PROGRA~1:/cygdr...
+@@ -21822,7 +21822,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -21925,7 +21925,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       lt_prog_compiler_pic_FC='-DDLL_EXPORT'
+@@ -22412,7 +22412,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -22527,7 +22527,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, FC) is actually meaningless,
+       # as there is no search path for DLLs.
+       hardcode_libdir_flag_spec_FC='-L$libdir'
+@@ -23056,7 +23056,7 @@
+       export_dynamic_flag_spec_FC=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+@@ -23884,7 +23884,7 @@
+   # libtool to hard-code these into programs
+   ;;
+ 
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   version_type=windows
+   shrext_cmds=.dll
+   need_version=no
+@@ -23910,9 +23910,9 @@
+     shlibpath_overrides_runpath=yes
+ 
+     case $host_os in
+-    cygwin*)
++    cygwin* | msys*)
+       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+-      soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
++      soname_spec='`echo $libname | $SED -e 's/^lib/msys-/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
+ 
+       ;;
+     mingw* | cegcc*)
+@@ -23949,7 +23949,7 @@
+       # Convert to MSYS style.
+       sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+       ;;
+-    cygwin*)
++    cygwin* | msys*)
+       # Convert to unix form, then to dos form, then back to unix form
+       # but this time dos style (no spaces!) so that the unix form looks
+       # like /cygdrive/c/PROGRA~1:/cygdr...
+@@ -24844,7 +24844,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -24947,7 +24947,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       lt_prog_compiler_pic_GO='-DDLL_EXPORT'
+@@ -25434,7 +25434,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -25549,7 +25549,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, GO) is actually meaningless,
+       # as there is no search path for DLLs.
+       hardcode_libdir_flag_spec_GO='-L$libdir'
+@@ -26090,7 +26090,7 @@
+       export_dynamic_flag_spec_GO=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+@@ -27073,7 +27073,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -27176,7 +27176,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+ 
+@@ -27663,7 +27663,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -27778,7 +27778,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, GCJ) is actually meaningless,
+       # as there is no search path for DLLs.
+       hardcode_libdir_flag_spec_GCJ='-L$libdir'
+@@ -28319,7 +28319,7 @@
+       export_dynamic_flag_spec_GCJ=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+
+diff -urN libtool-2.4.7/libltdl/configure.orig libtool-2.4.7/libltdl/configure
+--- libtool-2.4.7/libltdl/configure.orig	2022-05-25 14:29:13.245182300 +0200
++++ libtool-2.4.7/libltdl/configure	2022-05-25 14:30:03.920944200 +0200
+@@ -4774,7 +4774,7 @@
+     lt_cv_sys_max_cmd_len=-1;
+     ;;
+ 
+-  cygwin* | mingw* | cegcc*)
++  cygwin* | msys* | mingw* | cegcc*)
+     # On Win9x/ME, this test blows up -- it succeeds, but takes
+     # about 5 minutes as the teststring grows exponentially.
+     # Worse, since 9x/ME are not pre-emptively multitasking,
+@@ -4940,7 +4940,7 @@
+       *-*-mingw* ) # actually msys
+         lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+         ;;
+-      *-*-cygwin* )
++      *-*-cygwin* | *-*-msys* )
+         lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+         ;;
+       * ) # otherwise, assume *nix
+@@ -4948,12 +4948,12 @@
+         ;;
+     esac
+     ;;
+-  *-*-cygwin* )
++  *-*-cygwin* | *-*-msys* )
+     case $build in
+       *-*-mingw* ) # actually msys
+         lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+         ;;
+-      *-*-cygwin* )
++      *-*-cygwin* | *-*-msys* )
+         lt_cv_to_host_file_cmd=func_convert_file_noop
+         ;;
+       * ) # otherwise, assume *nix
+@@ -5019,7 +5019,7 @@
+ esac
+ reload_cmds='$LD$reload_flag -o $output$reload_objs'
+ case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     if test yes != "$GCC"; then
+       reload_cmds=false
+     fi
+@@ -5272,7 +5272,7 @@
+   lt_cv_file_magic_test_file=/shlib/libc.so
+   ;;
+ 
+-cygwin*)
++cygwin* | msys*)
+   # func_win32_libid is a shell function defined in ltmain.sh
+   lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+   lt_cv_file_magic_cmd='func_win32_libid'
+@@ -5588,7 +5588,7 @@
+   lt_cv_sharedlib_from_linklib_cmd='unknown'
+ 
+ case $host_os in
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   # two different shell functions defined in ltmain.sh;
+   # decide which one to use based on capabilities of $DLLTOOL
+   case `$DLLTOOL --help 2>&1` in
+@@ -6097,7 +6097,7 @@
+ aix*)
+   symcode='[BCDT]'
+   ;;
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   symcode='[ABCDGISTW]'
+   ;;
+ hpux*)
+@@ -7837,7 +7837,7 @@
+ enable_win32_dll=yes
+ 
+ case $host in
+-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
++*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
+   if test -n "$ac_tool_prefix"; then
+   # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args.
+ set dummy ${ac_tool_prefix}as; ac_word=$2
+@@ -8738,7 +8738,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -8841,7 +8841,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       lt_prog_compiler_pic='-DDLL_EXPORT'
+@@ -9343,7 +9343,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -9458,7 +9458,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
+       # as there is no search path for DLLs.
+       hardcode_libdir_flag_spec='-L$libdir'
+@@ -9999,7 +9999,7 @@
+       export_dynamic_flag_spec=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+@@ -11035,7 +11035,7 @@
+   # libtool to hard-code these into programs
+   ;;
+ 
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   version_type=windows
+   shrext_cmds=.dll
+   need_version=no
+@@ -11067,6 +11067,12 @@
+ 
+       sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"
+       ;;
++    msys*)
++      # MSYS DLLs use 'msys-' prefix rather than 'lib'
++      soname_spec='`echo $libname | sed -e 's/^lib/msys-/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
++
++      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"
++      ;;
+     mingw* | cegcc*)
+       # MinGW DLLs use traditional 'lib' prefix
+       soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext'
+@@ -11101,7 +11107,7 @@
+       # Convert to MSYS style.
+       sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+       ;;
+-    cygwin*)
++    cygwin* | msys*)
+       # Convert to unix form, then to dos form, then back to unix form
+       # but this time dos style (no spaces!) so that the unix form looks
+       # like /cygdrive/c/PROGRA~1:/cygdr...
+@@ -11803,7 +11809,7 @@
+     lt_cv_dlopen_libs=
+     ;;
+ 
+-  cygwin*)
++  cygwin* | msys*)
+     lt_cv_dlopen=dlopen
+     lt_cv_dlopen_libs=
+     ;;
+@@ -12751,7 +12757,7 @@
+ beos*)
+   LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la"
+   ;;
+-cygwin* | mingw* | pw32*)
++cygwin* | msys* | mingw* | pw32*)
+   ac_fn_c_check_decl "$LINENO" "cygwin_conv_path" "ac_cv_have_decl_cygwin_conv_path" "#include <sys/cygwin.h>
+ "
+ if test "x$ac_cv_have_decl_cygwin_conv_path" = xyes; then :
+@@ -13166,7 +13172,7 @@
+   $as_echo_n "(cached) " >&6
+ else
+   case $host_os in #(
+-	 *cygwin*)
++	 *cygwin* | *msys*)
+ 	   lt_cv_sys_argz_works=no
+ 	   if test no != "$cross_compiling"; then
+ 	     lt_cv_sys_argz_works="guessing no"
+
+diff -urN libtool-2.4.7/m4/libtool.m4.orig libtool-2.4.7/m4/libtool.m4
+--- libtool-2.4.7/m4/libtool.m4.orig	2022-03-17 03:43:39.000000000 +0100
++++ libtool-2.4.7/m4/libtool.m4	2022-05-25 14:26:59.035745300 +0200
+@@ -1703,7 +1703,7 @@
+     lt_cv_sys_max_cmd_len=-1;
+     ;;
+ 
+-  cygwin* | mingw* | cegcc*)
++  cygwin* | msys* | mingw* | cegcc*)
+     # On Win9x/ME, this test blows up -- it succeeds, but takes
+     # about 5 minutes as the teststring grows exponentially.
+     # Worse, since 9x/ME are not pre-emptively multitasking,
+@@ -1951,7 +1951,7 @@
+     lt_cv_dlopen_libs=
+     ;;
+ 
+-  cygwin*)
++  cygwin* | msys*)
+     lt_cv_dlopen=dlopen
+     lt_cv_dlopen_libs=
+     ;;
+@@ -2541,7 +2541,7 @@
+   # libtool to hard-code these into programs
+   ;;
+ 
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   version_type=windows
+   shrext_cmds=.dll
+   need_version=no
+@@ -2567,9 +2567,9 @@
+     shlibpath_overrides_runpath=yes
+ 
+     case $host_os in
+-    cygwin*)
++    cygwin* | msys*)
+       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+-      soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext'
++      soname_spec='`echo $libname | $SED -e 's/^lib/msys-/'``echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext'
+ m4_if([$1], [],[
+       sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
+       ;;
+@@ -2607,7 +2607,7 @@
+       # Convert to MSYS style.
+       sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
+       ;;
+-    cygwin*)
++    cygwin* | msys*)
+       # Convert to unix form, then to dos form, then back to unix form
+       # but this time dos style (no spaces!) so that the unix form looks
+       # like /cygdrive/c/PROGRA~1:/cygdr...
+@@ -3385,7 +3385,7 @@
+ esac
+ reload_cmds='$LD$reload_flag -o $output$reload_objs'
+ case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     if test yes != "$GCC"; then
+       reload_cmds=false
+     fi
+@@ -3478,7 +3478,7 @@
+   lt_cv_file_magic_test_file=/shlib/libc.so
+   ;;
+ 
+-cygwin*)
++cygwin* | msys*)
+   # func_win32_libid is a shell function defined in ltmain.sh
+   lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+   lt_cv_file_magic_cmd='func_win32_libid'
+@@ -3791,7 +3791,7 @@
+ [lt_cv_sharedlib_from_linklib_cmd='unknown'
+ 
+ case $host_os in
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   # two different shell functions defined in ltmain.sh;
+   # decide which one to use based on capabilities of $DLLTOOL
+   case `$DLLTOOL --help 2>&1` in
+@@ -3861,7 +3861,7 @@
+ [AC_REQUIRE([AC_CANONICAL_HOST])dnl
+ LIBM=
+ case $host in
+-*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
++*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-msys* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
+   # These system don't have libm, or don't need it
+   ;;
+ *-ncr-sysv4.3*)
+@@ -3936,7 +3936,7 @@
+ aix*)
+   symcode='[[BCDT]]'
+   ;;
+-cygwin* | mingw* | pw32* | cegcc*)
++cygwin* | msys* | mingw* | pw32* | cegcc*)
+   symcode='[[ABCDGISTW]]'
+   ;;
+ hpux*)
+@@ -4242,7 +4242,7 @@
+     beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+       # PIC is the default for these OSes.
+       ;;
+-    mingw* | cygwin* | os2* | pw32* | cegcc*)
++    mingw* | cygwin* | msys* | os2* | pw32* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -4318,7 +4318,7 @@
+ 	  ;;
+ 	esac
+ 	;;
+-      mingw* | cygwin* | os2* | pw32* | cegcc*)
++      mingw* | cygwin* | msys* | os2* | pw32* | cegcc*)
+ 	# This hack is so that the source file can tell whether it is being
+ 	# built for inclusion in a dll (and should export symbols for example).
+ 	m4_if([$1], [GCJ], [],
+@@ -4566,7 +4566,7 @@
+       # PIC is the default for these OSes.
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       # Although the cygwin gcc ignores -fPIC, still need this for old-style
+@@ -4670,7 +4670,7 @@
+       esac
+       ;;
+ 
+-    mingw* | cygwin* | pw32* | os2* | cegcc*)
++    mingw* | cygwin* | msys* | pw32* | os2* | cegcc*)
+       # This hack is so that the source file can tell whether it is being
+       # built for inclusion in a dll (and should export symbols for example).
+       m4_if([$1], [GCJ], [],
+@@ -4945,7 +4945,7 @@
+   pw32*)
+     _LT_TAGVAR(export_symbols_cmds, $1)=$ltdll_cmds
+     ;;
+-  cygwin* | mingw* | cegcc*)
++  cygwin* | msys* | mingw* | cegcc*)
+     case $cc_basename in
+     cl* | icl*)
+       _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
+@@ -5003,7 +5003,7 @@
+   extract_expsyms_cmds=
+ 
+   case $host_os in
+-  cygwin* | mingw* | pw32* | cegcc*)
++  cygwin* | msys* | mingw* | pw32* | cegcc*)
+     # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time
+     # When not using gcc, we currently assume that we are using
+     # Microsoft Visual C++ or Intel C++ Compiler.
+@@ -5118,7 +5118,7 @@
+       fi
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+       # as there is no search path for DLLs.
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+@@ -5575,7 +5575,7 @@
+       _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+       ;;
+ 
+-    cygwin* | mingw* | pw32* | cegcc*)
++    cygwin* | msys* | mingw* | pw32* | cegcc*)
+       # When not using gcc, we currently assume that we are using
+       # Microsoft Visual C++ or Intel C++ Compiler.
+       # hardcode_libdir_flag_spec is actually meaningless, as there is
+@@ -6651,7 +6651,7 @@
+         esac
+         ;;
+ 
+-      cygwin* | mingw* | pw32* | cegcc*)
++      cygwin* | msys* | mingw* | pw32* | cegcc*)
+ 	case $GXX,$cc_basename in
+ 	,cl* | no,cl* | ,icl* | no,icl*)
+ 	  # Native MSVC or ICC
+@@ -8348,7 +8348,7 @@
+       *-*-mingw* ) # actually msys
+         lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
+         ;;
+-      *-*-cygwin* )
++      *-*-cygwin* | *-*-msys* )
+         lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
+         ;;
+       * ) # otherwise, assume *nix
+@@ -8356,12 +8356,12 @@
+         ;;
+     esac
+     ;;
+-  *-*-cygwin* )
++  *-*-cygwin* | *-*-msys* )
+     case $build in
+       *-*-mingw* ) # actually msys
+         lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
+         ;;
+-      *-*-cygwin* )
++      *-*-cygwin* | *-*-msys* )
+         lt_cv_to_host_file_cmd=func_convert_file_noop
+         ;;
+       * ) # otherwise, assume *nix
+
+diff -Naur libtool-2.4.2.418-orig/m4/ltdl.m4 libtool-2.4.2.418/m4/ltdl.m4
+--- libtool-2.4.2.418-orig/m4/ltdl.m4	2013-10-26 03:37:46.000000000 +0400
++++ libtool-2.4.2.418/m4/ltdl.m4	2014-09-02 10:19:58.102800000 +0400
+@@ -706,7 +706,7 @@
+ beos*)
+   LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la"
+   ;;
+-cygwin* | mingw* | pw32*)
++cygwin* | msys* | mingw* | pw32*)
+   AC_CHECK_DECLS([cygwin_conv_path], [], [], [[#include <sys/cygwin.h>]])
+   LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}loadlibrary.la"
+   ;;
+
+diff -Naur libtool-2.4.2.418-orig/m4/ltoptions.m4 libtool-2.4.2.418/m4/ltoptions.m4
+--- libtool-2.4.2.418-orig/m4/ltoptions.m4	2013-10-26 03:37:46.000000000 +0400
++++ libtool-2.4.2.418/m4/ltoptions.m4	2014-09-02 10:20:19.069200000 +0400
+@@ -126,7 +126,7 @@
+ [enable_win32_dll=yes
+ 
+ case $host in
+-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
++*-*-cygwin* | *-*-msys* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
+   AC_CHECK_TOOL(AS, as, false)
+   AC_CHECK_TOOL(DLLTOOL, dlltool, false)
+   AC_CHECK_TOOL(OBJDUMP, objdump, false)
+
+diff -Naur libtool-2.4.2.418-orig/tests/bindir.at libtool-2.4.2.418/tests/bindir.at
+--- libtool-2.4.2.418-orig/tests/bindir.at	2013-01-26 08:19:10.000000000 +0400
++++ libtool-2.4.2.418/tests/bindir.at	2014-09-02 10:21:21.999600000 +0400
+@@ -65,7 +65,7 @@
+ 
+ bindirneeded=:
+ case $host_os in
+-  cygwin*|mingw*|cegcc*)
++  cygwin*|msys*|mingw*|cegcc*)
+     ;;
+   *)
+     bindirneeded=false
+@@ -174,7 +174,7 @@
+ 
+ bindirneeded=:
+ case $host_os in
+-  cygwin*|mingw*|cegcc*)
++  cygwin*|msys*|mingw*|cegcc*)
+     ;;
+   *)
+     bindirneeded=false
+
+diff -Naur libtool-2.4.2.418-orig/tests/lt_dladvise.at libtool-2.4.2.418/tests/lt_dladvise.at
+--- libtool-2.4.2.418-orig/tests/lt_dladvise.at	2013-01-01 21:36:01.000000000 +0400
++++ libtool-2.4.2.418/tests/lt_dladvise.at	2014-09-02 10:20:51.298800000 +0400
+@@ -332,7 +332,7 @@
+ $LIBTOOL --features | grep 'enable shared libraries' >/dev/null && have_shared=:
+ 
+ case $host_os,$have_shared in
+-cygwin* | mingw* | cegcc* | *,false)
++cygwin* | msys* | mingw* | cegcc* | *,false)
+   # These hosts do not support linking without -no-undefined
+   CPPFLAGS="$CPPFLAGS -DHAVE_UNDEFINED_SYMBOLS=0"
+   ;;
diff --git a/contrib/fixes-libtool/0010-libtool-2.4.2-include-process-h.patch b/contrib/fixes-libtool/0010-libtool-2.4.2-include-process-h.patch
new file mode 100644
index 0000000..82ecf52
--- /dev/null
+++ b/contrib/fixes-libtool/0010-libtool-2.4.2-include-process-h.patch
@@ -0,0 +1,24 @@
+diff --git a/build-aux/ltmain.in b/build-aux/ltmain.in
+index 0418007..91276c2 100644
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -4163,6 +4163,7 @@
+ # include <unistd.h>
+ # include <stdint.h>
+ # ifdef __CYGWIN__
++#  include <process.h>
+ #  include <io.h>
+ # endif
+ #endif
+diff --git a/build-aux/ltmain.sh b/build-aux/ltmain.sh
+index 0418007..91276c2 100644
+--- a/build-aux/ltmain.sh
++++ b/build-aux/ltmain.sh
+@@ -4163,6 +4163,7 @@
+ # include <unistd.h>
+ # include <stdint.h>
+ # ifdef __CYGWIN__
++#  include <process.h>
+ #  include <io.h>
+ # endif
+ #endif
diff --git a/contrib/fixes-libtool/0011-Pick-up-clang_rt-static-archives-compiler-internal-l.patch b/contrib/fixes-libtool/0011-Pick-up-clang_rt-static-archives-compiler-internal-l.patch
new file mode 100644
index 0000000..49cc070
--- /dev/null
+++ b/contrib/fixes-libtool/0011-Pick-up-clang_rt-static-archives-compiler-internal-l.patch
@@ -0,0 +1,33 @@
+From a18473ed4e5574dab899db640b8efeff78939b54 Mon Sep 17 00:00:00 2001
+From: Manoj Gupta <manojgupta@chromium.org>
+Date: Wed, 10 Oct 2018 10:50:23 +0300
+Subject: [PATCH 1/2] Pick up clang_rt static archives compiler internal
+ libraries
+
+Libtool checks only for libraries linked as -l* when trying to
+find internal compiler libraries. Clang, however uses the absolute
+path to link its internal libraries e.g. compiler_rt. This patch
+handles clang's statically linked libraries when finding internal
+compiler libraries.
+https://crbug.com/749263
+https://debbugs.gnu.org/cgi/bugreport.cgi?bug=27866
+---
+ m4/libtool.m4 | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/m4/libtool.m4 b/m4/libtool.m4
+index b55a6e5..d9322d0 100644
+--- a/m4/libtool.m4
++++ b/m4/libtool.m4
+@@ -7556,7 +7556,7 @@ if AC_TRY_EVAL(ac_compile); then
+   for p in `eval "$output_verbose_link_cmd"`; do
+     case $prev$p in
+ 
+-    -L* | -R* | -l*)
++    -L* | -R* | -l* | */libclang_rt.*.a)
+        # Some compilers place space between "-{L,R}" and the path.
+        # Remove the space.
+        if test x-L = "$p" ||
+-- 
+2.7.4
+
diff --git a/contrib/fixes-libtool/0012-Prefer-response-files-over-linker-scripts-for-mingw-.patch b/contrib/fixes-libtool/0012-Prefer-response-files-over-linker-scripts-for-mingw-.patch
new file mode 100644
index 0000000..7bdb62d
--- /dev/null
+++ b/contrib/fixes-libtool/0012-Prefer-response-files-over-linker-scripts-for-mingw-.patch
@@ -0,0 +1,83 @@
+From ec15841963ca3aab3bc88fb0932c014337284bfc Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Martin=20Storsj=C3=B6?= <martin@martin.st>
+Date: Wed, 10 Oct 2018 10:47:21 +0300
+Subject: [PATCH 2/2] Prefer response files over linker scripts for mingw tools
+
+The GCC/binutils tools support response files just fine, while
+lld (impersonating GNU ld) only supports response files, not
+linker scripts. Using a linker script as input just to pass a
+list of files is overkill for cases when a response file is enough.
+---
+ build-aux/ltmain.in | 28 ++++++++++++++--------------
+ m4/libtool.m4       |  2 ++
+ 2 files changed, 16 insertions(+), 14 deletions(-)
+
+diff --git a/build-aux/ltmain.in b/build-aux/ltmain.in
+index e2fb263..db5d590 100644
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -7932,20 +7932,7 @@ EOF
+ 	  last_robj=
+ 	  k=1
+ 
+-	  if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then
+-	    output=$output_objdir/$output_la.lnkscript
+-	    func_verbose "creating GNU ld script: $output"
+-	    echo 'INPUT (' > $output
+-	    for obj in $save_libobjs
+-	    do
+-	      func_to_tool_file "$obj"
+-	      $ECHO "$func_to_tool_file_result" >> $output
+-	    done
+-	    echo ')' >> $output
+-	    func_append delfiles " $output"
+-	    func_to_tool_file "$output"
+-	    output=$func_to_tool_file_result
+-	  elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then
++	  if test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then
+ 	    output=$output_objdir/$output_la.lnk
+ 	    func_verbose "creating linker input file list: $output"
+ 	    : > $output
+@@ -7964,6 +7951,19 @@ EOF
+ 	    func_append delfiles " $output"
+ 	    func_to_tool_file "$output"
+ 	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
++	  elif test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then
++	    output=$output_objdir/$output_la.lnkscript
++	    func_verbose "creating GNU ld script: $output"
++	    echo 'INPUT (' > $output
++	    for obj in $save_libobjs
++	    do
++	      func_to_tool_file "$obj"
++	      $ECHO "$func_to_tool_file_result" >> $output
++	    done
++	    echo ')' >> $output
++	    func_append delfiles " $output"
++	    func_to_tool_file "$output"
++	    output=$func_to_tool_file_result
+ 	  else
+ 	    if test -n "$save_libobjs"; then
+ 	      func_verbose "creating reloadable object files..."
+diff --git a/m4/libtool.m4 b/m4/libtool.m4
+index d9322d0..9046a84 100644
+--- a/m4/libtool.m4
++++ b/m4/libtool.m4
+@@ -5130,6 +5130,7 @@ _LT_EOF
+       _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+       _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+       _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
++      _LT_TAGVAR(file_list_spec, $1)='@'
+ 
+       if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+@@ -6706,6 +6707,7 @@ if test yes != "$_lt_caught_CXX_error"; then
+ 	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+ 	  _LT_TAGVAR(always_export_symbols, $1)=no
+ 	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
++	  _LT_TAGVAR(file_list_spec, $1)='@'
+ 
+ 	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+ 	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+-- 
+2.7.4
+
diff --git a/contrib/fixes-libtool/0013-Allow-statically-linking-compiler-support-libraries-.patch b/contrib/fixes-libtool/0013-Allow-statically-linking-compiler-support-libraries-.patch
new file mode 100644
index 0000000..b75b191
--- /dev/null
+++ b/contrib/fixes-libtool/0013-Allow-statically-linking-compiler-support-libraries-.patch
@@ -0,0 +1,38 @@
+From b9f77cae8cfbe850e58cac686fcb4d246b5bfc51 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Martin=20Storsj=C3=B6?= <martin@martin.st>
+Date: Mon, 19 Aug 2019 13:34:51 +0300
+Subject: [PATCH] Allow statically linking compiler support libraries when
+ linking a library
+
+For cases with deplibs_check_method="file_magic ..." (as it is for mingw),
+there were previously no way that a static library could be accepted
+here.
+---
+ build-aux/ltmain.in | 11 +++++++++--
+ 1 file changed, 9 insertions(+), 2 deletions(-)
+
+diff --git a/build-aux/ltmain.in b/build-aux/ltmain.in
+index e2fb2633..db4d775c 100644
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -5870,8 +5870,15 @@ func_mode_link ()
+ 	  fi
+ 	  case $linkmode in
+ 	  lib)
+-	    # Linking convenience modules into shared libraries is allowed,
+-	    # but linking other static libraries is non-portable.
++	    # Linking convenience modules and compiler provided static libraries
++	    # into shared libraries is allowed, but linking other static
++	    # libraries is non-portable.
++	    case $deplib in
++	      */libgcc*.$libext | */libclang_rt*.$libext)
++		deplibs="$deplib $deplibs"
++		continue
++	      ;;
++	    esac
+ 	    case " $dlpreconveniencelibs " in
+ 	    *" $deplib "*) ;;
+ 	    *)
+-- 
+2.17.1
+
diff --git a/contrib/fixes-libtool/0014-Support-llvm-objdump-f-output.patch b/contrib/fixes-libtool/0014-Support-llvm-objdump-f-output.patch
new file mode 100644
index 0000000..d657050
--- /dev/null
+++ b/contrib/fixes-libtool/0014-Support-llvm-objdump-f-output.patch
@@ -0,0 +1,39 @@
+From 03dabb6a70847761e65572a2a7b770a3b1b9f123 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= <mati865@gmail.com>
+Date: Mon, 12 Apr 2021 23:44:10 +0200
+Subject: [PATCH] Support llvm-objdump -f output
+
+---
+ build-aux/ltmain.in | 2 +-
+ m4/libtool.m4       | 2 +-
+ 2 files changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/build-aux/ltmain.in b/build-aux/ltmain.in
+index a9f070a..4a434cc 100644
+--- a/build-aux/ltmain.in
++++ b/build-aux/ltmain.in
+@@ -3019,7 +3019,7 @@ func_win32_libid ()
+   *ar\ archive*) # could be an import, or static
+     # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
+     if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
+-       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
++       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64|coff-arm|coff-arm64|coff-i386|coff-x86-64)' >/dev/null; then
+       case $nm_interface in
+       "MS dumpbin")
+ 	if func_cygming_ms_implib_p "$1" ||
+diff --git a/m4/libtool.m4 b/m4/libtool.m4
+index 21a7d60..594be9c 100644
+--- a/m4/libtool.m4
++++ b/m4/libtool.m4
+@@ -3473,7 +3473,7 @@ mingw* | pw32*)
+     lt_cv_file_magic_cmd='func_win32_libid'
+   else
+     # Keep this pattern in sync with the one in func_win32_libid.
+-    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
++    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64|coff-arm|coff-arm64|coff-i386|coff-x86-64)'
+     lt_cv_file_magic_cmd='$OBJDUMP -f'
+   fi
+   ;;
+-- 
+2.31.1
+
diff --git a/contrib/fixes-libtool/apply-all.sh b/contrib/fixes-libtool/apply-all.sh
new file mode 100755
index 0000000..7df5f8c
--- /dev/null
+++ b/contrib/fixes-libtool/apply-all.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+
+#
+# This file applies optional libtool patches mainly for better MSys2 compatibility,
+# especially for MSys2/Clang{64,32} toolchains.
+# It's a pity that these patches haven't been sent upstream.
+#
+# Based on Debian SID baseline files as of April 2023.
+#
+
+patchesdir=$(dirname $BASH_SOURCE) || exit 2
+test -n "$patchesdir" || exit 2
+cd "$patchesdir" || exit 2
+patchesdir=$(pwd) || exit 2
+
+patches=(
+  0003-Pass-various-runtime-library-flags-to-GCC.mingw.mod.patch
+  0006-Fix-strict-ansi-vs-posix.patch
+  0009-libtool-2.4.2.418-msysize.patch
+  0010-libtool-2.4.2-include-process-h.patch
+  0011-Pick-up-clang_rt-static-archives-compiler-internal-l.patch
+  0012-Prefer-response-files-over-linker-scripts-for-mingw-.patch
+  0013-Allow-statically-linking-compiler-support-libraries-.patch
+  0014-Support-llvm-objdump-f-output.patch
+)
+
+failed=( )
+
+cd "${patchesdir}/../.." || exit 1
+
+patch_params="-Nf -p1 --no-backup-if-mismatch -r - --read-only=fail"
+
+for patch in ${patches[@]}; do
+  patchfile="${patchesdir}/${patch}"
+  # Load patch into memory for simplicity
+  # Patches should not be very large
+  if grep -Eq -e '^--- .*\/ltmain\.in(\.orig)?([[:space:]]|$)' "$patchfile" && grep -Eq -e '^--- .*\/ltmain\.sh(\.orig)?([[:space:]]|$)' "$patchfile"
+  then
+    patch_data=$(awk '/^diff .*\/ltmain\.in(\.orig)?$/||(/^--- / && $2 ~ /\/ltmain\.in(\.orig)?$/){h=1;s=1;next}/^-- ?$/{h=0;s=0}/^[^-+@ ]/{h||s=0}/^\+\+\+ /{h=0}!s' "$patchfile") || exit 2
+  else
+    patch_data=$(cat "$patchfile") || exit 2
+  fi
+  patch_data=$(echo "$patch_data" | sed -E -e '/^(diff|---|\+\+\+) / s|/ltmain\.in|/ltmain.sh|g' -) || exit 2
+  patch_data=$(echo "$patch_data" | awk '(/^diff / && !/.*\/(ltmain\.sh|config\.guess|libtool\.m4|ltoptions\.m4)$/)||(/^--- / && $2 !~ /\/(ltmain\.sh|config\.guess|libtool\.m4|ltoptions\.m4)(\.orig)?$/){h=1;s=1;next}/^-- ?$/{h=0;s=0}/^[^-+@ ]/{h||s=0}/^\+\+\+ /{h=0}!s' -) || exit 2
+  echo "*** Applying $patch..."
+  if echo "$patch_data" | patch $patch_params -i -
+  then
+    echo "** $patch successfully applied."
+  else
+    echo "** $patch failed."
+    failed+=("$patch")
+  fi
+  unset patch_data
+done
+
+echo ''
+
+if [[ -n "${failed[@]}" ]]; then
+  printf '* Failed patch: %s\n' "${failed[@]}" >&2
+  exit 2
+else
+  echo "* All patches have been successfully applied."
+fi
+
+exit 0
diff --git a/contrib/gen_http_headers_insert.sh b/contrib/gen_http_headers_insert.sh
new file mode 100755
index 0000000..d373045
--- /dev/null
+++ b/contrib/gen_http_headers_insert.sh
@@ -0,0 +1,133 @@
+#!/bin/bash
+
+#
+#   Generate header insert for HTTP headers
+#
+
+#   Copyright (c) 2015-2021 Karlson2k (Evgeny Grin) <k2k@yandex.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+wget -nv https://www.iana.org/assignments/http-fields/field-names.csv -O perm-headers.csv || exit
+echo Generating...
+echo '/**
+ * @defgroup headers HTTP headers
+ * These are the standard headers found in HTTP requests and responses.
+ * See: https://www.iana.org/assignments/http-fields/http-fields.xhtml
+ * Registry export date: '"$(date -u +%Y-%m-%d)"'
+ * @{
+ */
+
+/* Main HTTP headers. */' > header_insert_headers.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+    gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+    field_name = $1
+    status = $3
+    ref = $4
+    comment = $5
+    if ("RFC-ietf-httpbis" == substr(ref, 1, 16))
+    {
+      gsub(/\]\[/, "; ", ref)
+      if (length(status) == 0)
+      { status = "No category" }
+      else
+      { sub(/^./, toupper(substr(status, 1, 1)), status) }
+      field_name = gensub(/\*/, "ASTERISK", "g", field_name)
+      field_name = gensub(/[^a-zA-Z0-9_]/, "_", "g", field_name)
+      printf ("/* %-14.14s %s */\n", status ".", ref)
+      printf ("#define MHD_HTTP_HEADER_%-12s \"%s\"\n", toupper(field_name), $1)
+    }
+}' perm-headers.csv >> header_insert_headers.h && \
+echo '
+/* Additional HTTP headers. */' >> header_insert_headers.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+    gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+    field_name = $1
+    status = $3
+    ref = $4
+    comment = $5
+    if ("RFC-ietf-httpbis" != substr(ref, 1, 16) && status == "permanent")
+    {
+      gsub(/\]\[/, "; ", ref)
+      sub(/^./, toupper(substr(status, 1, 1)), status)
+      field_name = gensub(/\*/, "ASTERISK", "g", field_name)
+      field_name = gensub(/[^a-zA-Z0-9_]/, "_", "g", field_name)
+      printf ("/* %-14.14s %s */\n", status ".", ref)
+      printf ("#define MHD_HTTP_HEADER_%-12s \"%s\"\n", toupper(field_name), $1)
+    }
+}' perm-headers.csv >> header_insert_headers.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+    gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+    field_name = $1
+    status = $3
+    ref = $4
+    comment = $5
+    if ("RFC-ietf-httpbis" != substr(ref, 1, 16) && status == "provisional")
+    {
+      gsub(/\]\[/, "; ", ref)
+      sub(/^./, toupper(substr(status, 1, 1)), status)
+      field_name = gensub(/\*/, "ASTERISK", "g", field_name)
+      field_name = gensub(/[^a-zA-Z0-9_]/, "_", "g", field_name)
+      printf ("/* %-14.14s %s */\n", status ".", ref)
+      printf ("#define MHD_HTTP_HEADER_%-12s \"%s\"\n", toupper(field_name), $1)
+    }
+}' perm-headers.csv >> header_insert_headers.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+    gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+    field_name = $1
+    status = $3
+    ref = $4
+    comment = $5
+    if ("RFC-ietf-httpbis" != substr(ref, 1, 16) && length(status) == 0)
+    {
+      gsub(/\]\[/, "; ", ref)
+      status = "No category"
+      field_name = gensub(/\*/, "ASTERISK", "g", field_name)
+      field_name = gensub(/[^a-zA-Z0-9_]/, "_", "g", field_name)
+      printf ("/* %-14.14s %s */\n", status ".", ref)
+      printf ("#define MHD_HTTP_HEADER_%-12s \"%s\"\n", toupper(field_name), $1)
+    }
+}' perm-headers.csv >> header_insert_headers.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+    gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+    field_name = $1
+    status = $3
+    ref = $4
+    comment = $5
+    if ("RFC-ietf-httpbis" != substr(ref, 1, 16) && status == "deprecated")
+    {
+      gsub(/\]\[/, "; ", ref)
+      sub(/^./, toupper(substr(status, 1, 1)), status)
+      field_name = gensub(/\*/, "ASTERISK", "g", field_name)
+      field_name = gensub(/[^a-zA-Z0-9_]/, "_", "g", field_name)
+      printf ("/* %-14.14s %s */\n", status ".", ref)
+      printf ("#define MHD_HTTP_HEADER_%-12s \"%s\"\n", toupper(field_name), $1)
+    }
+}' perm-headers.csv >> header_insert_headers.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+    gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+    field_name = $1
+    status = $3
+    ref = $4
+    comment = $5
+    if ("RFC-ietf-httpbis" != substr(ref, 1, 16) && status == "obsoleted")
+    {
+      gsub(/\]\[/, "; ", ref)
+      sub(/^./, toupper(substr(status, 1, 1)), status)
+      field_name = gensub(/\*/, "ASTERISK", "g", field_name)
+      field_name = gensub(/[^a-zA-Z0-9_]/, "_", "g", field_name)
+      printf ("/* %-14.14s %s */\n", status ".", ref)
+      printf ("#define MHD_HTTP_HEADER_%-12s \"%s\"\n", toupper(field_name), $1)
+    }
+}' perm-headers.csv >> header_insert_headers.h && \
+echo OK && \
+rm perm-headers.csv || exit
diff --git a/contrib/gen_http_methods_insert.sh b/contrib/gen_http_methods_insert.sh
new file mode 100755
index 0000000..6507608
--- /dev/null
+++ b/contrib/gen_http_methods_insert.sh
@@ -0,0 +1,66 @@
+#!/bin/bash
+
+#
+#   Generate header insert for HTTP methods
+#
+
+#   Copyright (c) 2015-2021 Karlson2k (Evgeny Grin) <k2k@yandex.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+wget -nv http://www.iana.org/assignments/http-methods/methods.csv -O methods.csv || exit
+echo Generating...
+echo '/**
+ * @defgroup methods HTTP methods
+ * HTTP methods (as strings).
+ * See: http://www.iana.org/assignments/http-methods/http-methods.xml
+ * Registry export date: '"$(date -u +%Y-%m-%d)"'
+ * @{
+ */
+
+/* Main HTTP methods. */' > header_insert_methods.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+  gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+  gsub(/\]\[/, "; ", $4)
+  if (substr($4, 1, 26) == "RFC-ietf-httpbis-semantics") {
+    if ($2 == "yes")
+    { safe_m = "Safe.    " }
+    else
+    { safe_m = "Not safe." }
+    if ($3 == "yes")
+    { indem_m = "Idempotent.    " }
+    else
+    { indem_m = "Not idempotent." }
+    print "/* " safe_m " " indem_m " " $4 ". */"
+    mthd = gensub(/\*/, "ASTERISK", "g", $1)
+    mthd = gensub(/[^a-zA-Z0-9_]/, "_", "g", mthd)
+    printf ("%-32s \"%s\"\n", "#define MHD_HTTP_METHOD_" toupper(mthd), $1)
+  }
+}' methods.csv >> header_insert_methods.h && \
+echo '
+/* Additional HTTP methods. */' >> header_insert_methods.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+  gsub(/^\[|^"\[|\]"$|\]$/, "", $4)
+  gsub(/\]\[/, "; ", $4)
+  if (substr($4, 1, 26) != "RFC-ietf-httpbis-semantics") {
+    if ($2 == "yes")
+    { safe_m = "Safe.    " }
+    else
+    { safe_m = "Not safe." }
+    if ($3 == "yes")
+    { indem_m = "Idempotent.    " }
+    else
+    { indem_m = "Not idempotent." }
+    print "/* " safe_m " " indem_m " " $4 ". */"
+    mthd = gensub(/\*/, "ASTERISK", "g", $1)
+    mthd = gensub(/[^a-zA-Z0-9_]/, "_", "g", mthd)
+    printf ("%-38s \"%s\"\n", "#define MHD_HTTP_METHOD_" toupper(mthd), $1)
+  }
+}' methods.csv >> header_insert_methods.h && \
+echo OK && \
+rm methods.csv || exit
diff --git a/contrib/gen_http_statuses_inserts.sh b/contrib/gen_http_statuses_inserts.sh
new file mode 100755
index 0000000..a4f2bb0
--- /dev/null
+++ b/contrib/gen_http_statuses_inserts.sh
@@ -0,0 +1,101 @@
+#!/bin/bash
+
+#
+#   Generate code and header inserts for HTTP statues
+#
+
+#   Copyright (c) 2019-2021 Karlson2k (Evgeny Grin) <k2k@yandex.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+wget -nv https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv -O http-status-codes-1.csv || exit
+echo Generating...
+echo '/**
+ * @defgroup httpcode HTTP response codes.
+ * These are the status codes defined for HTTP responses.
+ * See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
+ * Registry export date: '"$(date -u +%Y-%m-%d)"'
+ * @{
+ */
+' > header_insert_statuses.h && \
+gawk -e 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"}
+FNR > 1 {
+  gsub(/^\[|^"\[|\]"$|\]$/, "", $3)
+  gsub(/\]\[/, "; ", $3)
+  if ($1 == 306) {
+    $2 = "Switch Proxy"
+    $3 = "Not used! " $3
+  }
+  if ($2 != "Unassigned" && $2 != "(Unused)") {
+    printf ("/* %s %-22s %s. */\n", $1, "\"" $2 "\".", $3)
+    printf ("#define MHD_HTTP_%-27s %s\n", toupper(gensub(/[^A-Za-z0-0]/, "_", "g", $2)), $1)
+  } else {
+    print ""
+  }
+}' http-status-codes-1.csv >> header_insert_statuses.h && \
+echo '
+/* Not registered non-standard codes */
+/* 449 "Reply With".          MS IIS extension. */
+#define MHD_HTTP_RETRY_WITH                  449
+
+/* 450 "Blocked by Windows Parental Controls". MS extension. */
+#define MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450
+
+/* 509 "Bandwidth Limit Exceeded". Apache extension. */
+#define MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED    509
+' >> header_insert_statuses.h && \
+gawk -e 'BEGIN {
+  FPAT = "([^,]*)|(\"[^\"]+\")"
+  hundreds[1]="one"
+  hundreds[2]="two"
+  hundreds[3]="three"
+  hundreds[4]="four"
+  hundreds[5]="five"
+  hundreds[6]="six"
+  prev_num=0
+  prev_reason=""
+  prev_desc=""
+  num=0
+  reason=""
+  desc=""
+}
+FNR > 1 {
+  gsub(/^\[|^"\[|\]"$|\]$/, "", $3)
+  gsub(/\]\[/, "; ", $3)
+  num = $1
+  reason = $2
+  desc = $3
+  if (num % 100 == 0) {
+    if (num != 100) {
+      printf ("  /* %s */ %-36s /* %s */\n};\n\n", prev_num, "_MHD_S_STR_W_LEN (\""prev_reason"\")", prev_desc)
+    }
+    prev_num = num;
+    print "static const struct _MHD_str_w_len " hundreds[$1/100] "_hundred[] = {"
+  }
+  if (num == 306) { 
+    reason = "Switch Proxy"
+    desc = "Not used! " desc
+  }
+  if (reason == "Unassigned" || reason == "(Unused)") next
+  if (prev_num != num)
+    printf ("  /* %s */ %-36s /* %s */\n", prev_num, "_MHD_S_STR_W_LEN (\""prev_reason"\"),", prev_desc)
+  while(++prev_num < num) {
+    if (prev_num == 449) {prev_reason="Reply With"; prev_desc="MS IIS extension";}
+    else if (prev_num == 450) {prev_reason="Blocked by Windows Parental Controls"; prev_desc="MS extension";}
+    else if (prev_num == 509) {prev_reason="Bandwidth Limit Exceeded"; prev_desc="Apache extension";}
+    else {prev_reason="Unknown"; prev_desc="Not used";}
+    if (prev_reason=="Unknown") printf ("  /* %s */ %-36s /* %s */\n", prev_num, "{\""prev_reason"\", 0},", prev_desc)
+    else printf ("  /* %s */ %-36s /* %s */\n", prev_num, "_MHD_S_STR_W_LEN (\""prev_reason"\"),", prev_desc)
+  }
+  prev_num = num
+  prev_reason = reason
+  prev_desc = desc
+}
+END {
+  printf ("  /* %s */ %-36s /* %s */\n};\n", prev_num, "_MHD_S_STR_W_LEN (\""prev_reason"\")", prev_desc)
+}' http-status-codes-1.csv > code_insert_statuses.c && \
+echo OK && \
+rm http-status-codes-1.csv || exit
diff --git a/contrib/make-dist.sh b/contrib/make-dist.sh
new file mode 100755
index 0000000..47d580a
--- /dev/null
+++ b/contrib/make-dist.sh
@@ -0,0 +1,107 @@
+#!/bin/bash
+
+#
+# This file creates dist tarball.
+# Optional autotools patches are applied for better toolchains
+# compatibility.
+#
+# Based on Debian SID baseline files as of April 2023.
+#
+
+if ! grep -Eq -e '^PRETTY_NAME="Debian GNU/Linux 12 \(bookworm\)"$' /etc/os-release
+then
+  echo "Only Debian 'bookworm' is supported by this script." >&2
+  exit 1
+fi
+
+if ! autoconf --version | head -1 | grep -Eq -e ' 2\.71$' -
+then
+  echo "The only supported autoconf version is 2.71." >&2
+  exit 1
+fi
+
+
+tooldir=$(dirname $BASH_SOURCE) || exit 2
+test -n "$tooldir" || exit 2
+cd "$tooldir" || exit 2
+tooldir="$PWD" || exit 2
+cd "${tooldir}/.." || exit 2
+rootsrcdir="$PWD" || exit 2
+
+# Cleanup sources
+echo ''
+echo '*** Performing initial cleanup...'
+echo ''
+if [[ ! -f 'Makefile' ]] || ! make maintainer-clean
+then
+  # Makefile needed for initial cleanup
+  if [[ ! -f 'Makefile.in' ]] || [[ ! -f 'configure' ]] || ! ./configure || ! make maintainer-clean
+  then
+    rm -f po/Makefile || exit 3
+    # Build 'configure' to build Makefile for initial cleanup
+    autoreconf -fvi || exit 3
+    ./configure || exit 3
+    make maintainer-clean || exit 3
+  fi
+fi
+echo ''
+echo '** Initial cleanup completed.'
+echo ''
+
+# Copy latest autotools files
+echo ''
+echo '*** Copying autotools files...'
+echo ''
+autoreconf -fvi || exit 4
+echo ''
+echo '*** Performing intermediate cleanup...'
+echo ''
+./configure || exit 4
+make distclean || exit 4
+rm -f ./configure ./aclocal.m4 || exit 4
+rm -rf ./autom4te.cache || exit 4
+echo ''
+echo '** Intermediate cleanup completed.'
+echo ''
+
+# Patching local autotools files
+echo ''
+echo '*** Performing patching of local autotools files...'
+echo ''
+"$tooldir/fixes-libtool/apply-all.sh" || exit 5
+"$tooldir/fixes-autoconf/apply-all.sh" || exit 5
+echo ''
+echo '** Local autotools files patched.'
+echo ''
+
+# Build the configure and the related files with patches
+echo ''
+echo '*** Building patched configure and related files...'
+echo ''
+autoreconf -v || exit 6
+echo ''
+echo '** Patched build system ready.'
+echo ''
+
+# Build the configure and the related files with patches
+
+have_command()
+{
+    command -v "$1" >/dev/null 2>&1
+}
+
+echo ''
+echo '*** Building dist tarball...'
+echo ''
+./configure || exit 7
+if have_command zopfli; then
+    make dist-custm2 'ARC_CMD=zopfli -v --gzip --i15' 'ARC_EXT=tar.gz' || exit 7
+else
+    make dist || exit 7
+    echo '* zopfli is not installed, tarball size is suboptimal.'
+fi
+echo ''
+echo '** Dist tarball ready.'
+echo ''
+
+exit 0
diff --git a/contrib/pogen.sh b/contrib/pogen.sh
new file mode 100755
index 0000000..87c90ad
--- /dev/null
+++ b/contrib/pogen.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+find src -name "*.c" | grep -v \# | grep -v /test_ | grep -v /perf_  | grep -v _old | grep -v chat | grep -v .libs/ | sort  > po/POTFILES.in
+grep -l _\( `find src -name "*.h"` | grep -v "platform.h" | grep -v _old | grep -v chat | sort >> po/POTFILES.in
+
diff --git a/contrib/uncrustify.cfg b/contrib/uncrustify.cfg
new file mode 100644
index 0000000..8b4cf3d
--- /dev/null
+++ b/contrib/uncrustify.cfg
@@ -0,0 +1,115 @@
+input_tab_size = 2
+output_tab_size = 2
+
+indent_columns = 2
+indent_with_tabs = 0
+indent_case_brace = 2
+indent_label=-16
+
+code_width=80
+#cmd_width=80
+
+# Leave most comments alone for now
+cmt_indent_multi=false
+sp_cmt_cpp_start=add
+
+sp_not=add
+
+sp_func_call_user_paren_paren=remove
+sp_inside_fparen=remove
+sp_after_cast=add
+
+ls_for_split_full=true
+ls_func_split_full=true
+ls_code_width=true
+
+# Arithmetic operations in wrapped expressions should be at the start
+# of the line.
+pos_arith=lead
+
+# Fully parenthesize boolean exprs
+mod_full_paren_if_bool=true
+
+# Braces should be on their own line
+nl_fdef_brace=add
+nl_enum_brace=add
+nl_struct_brace=add
+nl_union_brace=add
+nl_if_brace=add
+nl_brace_else=add
+nl_elseif_brace=add
+nl_while_brace=add
+nl_switch_brace=add
+
+# no newline between "else" and "if"
+nl_else_if=remove
+
+nl_func_paren=remove
+nl_assign_brace=remove
+
+# No extra newlines that cause noisy diffs
+nl_start_of_file=remove
+nl_after_func_proto = 2
+nl_after_func_body = 3
+# If there's no new line, it's not a text file!
+nl_end_of_file=add
+nl_max_blank_in_func = 3
+nl_max = 3
+
+sp_inside_paren = remove
+
+sp_arith = add
+sp_arith_additive = add
+
+# We want spaces before and after "="
+sp_before_assign = add
+sp_after_assign = add
+
+# we want "char *foo;"
+sp_before_ptr_star = add
+sp_after_ptr_star = remove
+sp_between_ptr_star = remove
+
+# we want "if (foo) { ... }"
+sp_before_sparen = add
+
+sp_inside_fparen = remove
+sp_inside_sparen = remove
+
+# Add or remove space around compare operator '<', '>', '==', etc
+sp_compare                                = add    # ignore/add/remove/force
+
+# add space before function call and decl: "foo (x)"
+sp_func_call_paren = add
+sp_func_proto_paren = add
+sp_func_proto_paren_empty = add
+sp_func_def_paren = add
+sp_func_def_paren_empty = add
+
+# We'd want it for "if ( (foo) || (bar) )", but not for "if (m())",
+# so as uncrustify doesn't give exactly what we want => ignore
+sp_paren_paren = ignore
+sp_inside_paren = remove
+sp_bool = force
+
+nl_func_type_name = force
+#nl_branch_else = add
+nl_else_brace = add
+nl_elseif_brace = add
+nl_for_brace = add
+
+# Whether to ignore the '#define' body while formatting.
+pp_ignore_define_body           = true    # true/false
+
+# Add or remove space between #else or #endif and a trailing comment.
+sp_endif_cmt                    = add   # ignore/add/remove/force
+
+# The span for aligning comments that end lines.
+#
+# 0: Don't align (default).
+align_right_cmt_span            = 3        # unsigned number
+
+# Minimum number of columns between preceding text and a trailing comment in
+# order for the comment to qualify for being aligned. Must be non-zero to have
+# an effect.
+align_right_cmt_gap             = 2        # unsigned number
diff --git a/contrib/uncrustify.sh b/contrib/uncrustify.sh
new file mode 100755
index 0000000..e8e05d3
--- /dev/null
+++ b/contrib/uncrustify.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+
+set -eu
+
+DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
+
+if ! uncrustify --version >/dev/null; then
+  echo "you need to install uncrustify for indentation"
+  exit 1
+fi
+
+find "$DIR/../src" \( -name "*.cpp" -o -name "*.c" -o -name "*.h" \) \
+  -exec uncrustify -c "$DIR/uncrustify.cfg" --replace --no-backup {} + \
+  || true
diff --git a/contrib/uncrustify_precommit b/contrib/uncrustify_precommit
new file mode 100755
index 0000000..2487333
--- /dev/null
+++ b/contrib/uncrustify_precommit
@@ -0,0 +1,35 @@
+#!/bin/sh
+
+# use as .git/hooks/pre-commit
+
+exec 1>&2
+
+RET=0
+changed=$(git diff --cached --name-only)
+crustified=""
+
+for f in $changed;
+do
+ if echo $f | grep \\.[c,h]\$ > /dev/null
+ then
+    # compare result of uncrustify with changes
+    #
+    # only change any of the invocations here if
+    # they are portable across all cmp and shell
+    # implementations !
+    uncrustify -q -c uncrustify.cfg -f $f | cmp -s $f -
+    if test $? = 1 ;
+    then
+      crustified=" $crustified $f"
+      RET=1
+    fi
+  fi
+done
+
+if [ $RET = 1 ];
+then
+  echo "Run"
+  echo "uncrustify --no-backup -c uncrustify.cfg ${crustified}"
+  echo "before committing."
+fi
+exit $RET
diff --git a/depcomp b/depcomp
deleted file mode 100755
index 4ebd5b3..0000000
--- a/depcomp
+++ /dev/null
@@ -1,791 +0,0 @@
-#! /bin/sh
-# depcomp - compile a program generating dependencies as side-effects
-
-scriptversion=2013-05-30.07; # UTC
-
-# Copyright (C) 1999-2013 Free Software Foundation, Inc.
-
-# 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 2, 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/>.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
-
-case $1 in
-  '')
-    echo "$0: No command.  Try '$0 --help' for more information." 1>&2
-    exit 1;
-    ;;
-  -h | --h*)
-    cat <<\EOF
-Usage: depcomp [--help] [--version] PROGRAM [ARGS]
-
-Run PROGRAMS ARGS to compile a file, generating dependencies
-as side-effects.
-
-Environment variables:
-  depmode     Dependency tracking mode.
-  source      Source file read by 'PROGRAMS ARGS'.
-  object      Object file output by 'PROGRAMS ARGS'.
-  DEPDIR      directory where to store dependencies.
-  depfile     Dependency file to output.
-  tmpdepfile  Temporary file to use when outputting dependencies.
-  libtool     Whether libtool is used (yes/no).
-
-Report bugs to <bug-automake@gnu.org>.
-EOF
-    exit $?
-    ;;
-  -v | --v*)
-    echo "depcomp $scriptversion"
-    exit $?
-    ;;
-esac
-
-# Get the directory component of the given path, and save it in the
-# global variables '$dir'.  Note that this directory component will
-# be either empty or ending with a '/' character.  This is deliberate.
-set_dir_from ()
-{
-  case $1 in
-    */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;;
-      *) dir=;;
-  esac
-}
-
-# Get the suffix-stripped basename of the given path, and save it the
-# global variable '$base'.
-set_base_from ()
-{
-  base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'`
-}
-
-# If no dependency file was actually created by the compiler invocation,
-# we still have to create a dummy depfile, to avoid errors with the
-# Makefile "include basename.Plo" scheme.
-make_dummy_depfile ()
-{
-  echo "#dummy" > "$depfile"
-}
-
-# Factor out some common post-processing of the generated depfile.
-# Requires the auxiliary global variable '$tmpdepfile' to be set.
-aix_post_process_depfile ()
-{
-  # If the compiler actually managed to produce a dependency file,
-  # post-process it.
-  if test -f "$tmpdepfile"; then
-    # Each line is of the form 'foo.o: dependency.h'.
-    # Do two passes, one to just change these to
-    #   $object: dependency.h
-    # and one to simply output
-    #   dependency.h:
-    # which is needed to avoid the deleted-header problem.
-    { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile"
-      sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile"
-    } > "$depfile"
-    rm -f "$tmpdepfile"
-  else
-    make_dummy_depfile
-  fi
-}
-
-# A tabulation character.
-tab='	'
-# A newline character.
-nl='
-'
-# Character ranges might be problematic outside the C locale.
-# These definitions help.
-upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
-lower=abcdefghijklmnopqrstuvwxyz
-digits=0123456789
-alpha=${upper}${lower}
-
-if test -z "$depmode" || test -z "$source" || test -z "$object"; then
-  echo "depcomp: Variables source, object and depmode must be set" 1>&2
-  exit 1
-fi
-
-# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
-depfile=${depfile-`echo "$object" |
-  sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
-tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
-
-rm -f "$tmpdepfile"
-
-# Avoid interferences from the environment.
-gccflag= dashmflag=
-
-# Some modes work just like other modes, but use different flags.  We
-# parameterize here, but still list the modes in the big case below,
-# to make depend.m4 easier to write.  Note that we *cannot* use a case
-# here, because this file can only contain one case statement.
-if test "$depmode" = hp; then
-  # HP compiler uses -M and no extra arg.
-  gccflag=-M
-  depmode=gcc
-fi
-
-if test "$depmode" = dashXmstdout; then
-  # This is just like dashmstdout with a different argument.
-  dashmflag=-xM
-  depmode=dashmstdout
-fi
-
-cygpath_u="cygpath -u -f -"
-if test "$depmode" = msvcmsys; then
-  # This is just like msvisualcpp but w/o cygpath translation.
-  # Just convert the backslash-escaped backslashes to single forward
-  # slashes to satisfy depend.m4
-  cygpath_u='sed s,\\\\,/,g'
-  depmode=msvisualcpp
-fi
-
-if test "$depmode" = msvc7msys; then
-  # This is just like msvc7 but w/o cygpath translation.
-  # Just convert the backslash-escaped backslashes to single forward
-  # slashes to satisfy depend.m4
-  cygpath_u='sed s,\\\\,/,g'
-  depmode=msvc7
-fi
-
-if test "$depmode" = xlc; then
-  # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information.
-  gccflag=-qmakedep=gcc,-MF
-  depmode=gcc
-fi
-
-case "$depmode" in
-gcc3)
-## gcc 3 implements dependency tracking that does exactly what
-## we want.  Yay!  Note: for some reason libtool 1.4 doesn't like
-## it if -MD -MP comes after the -MF stuff.  Hmm.
-## Unfortunately, FreeBSD c89 acceptance of flags depends upon
-## the command line argument order; so add the flags where they
-## appear in depend2.am.  Note that the slowdown incurred here
-## affects only configure: in makefiles, %FASTDEP% shortcuts this.
-  for arg
-  do
-    case $arg in
-    -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
-    *)  set fnord "$@" "$arg" ;;
-    esac
-    shift # fnord
-    shift # $arg
-  done
-  "$@"
-  stat=$?
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile"
-    exit $stat
-  fi
-  mv "$tmpdepfile" "$depfile"
-  ;;
-
-gcc)
-## Note that this doesn't just cater to obsosete pre-3.x GCC compilers.
-## but also to in-use compilers like IMB xlc/xlC and the HP C compiler.
-## (see the conditional assignment to $gccflag above).
-## There are various ways to get dependency output from gcc.  Here's
-## why we pick this rather obscure method:
-## - Don't want to use -MD because we'd like the dependencies to end
-##   up in a subdir.  Having to rename by hand is ugly.
-##   (We might end up doing this anyway to support other compilers.)
-## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
-##   -MM, not -M (despite what the docs say).  Also, it might not be
-##   supported by the other compilers which use the 'gcc' depmode.
-## - Using -M directly means running the compiler twice (even worse
-##   than renaming).
-  if test -z "$gccflag"; then
-    gccflag=-MD,
-  fi
-  "$@" -Wp,"$gccflag$tmpdepfile"
-  stat=$?
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile"
-    exit $stat
-  fi
-  rm -f "$depfile"
-  echo "$object : \\" > "$depfile"
-  # The second -e expression handles DOS-style file names with drive
-  # letters.
-  sed -e 's/^[^:]*: / /' \
-      -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
-## This next piece of magic avoids the "deleted header file" problem.
-## The problem is that when a header file which appears in a .P file
-## is deleted, the dependency causes make to die (because there is
-## typically no way to rebuild the header).  We avoid this by adding
-## dummy dependencies for each header file.  Too bad gcc doesn't do
-## this for us directly.
-## Some versions of gcc put a space before the ':'.  On the theory
-## that the space means something, we add a space to the output as
-## well.  hp depmode also adds that space, but also prefixes the VPATH
-## to the object.  Take care to not repeat it in the output.
-## Some versions of the HPUX 10.20 sed can't process this invocation
-## correctly.  Breaking it into two sed invocations is a workaround.
-  tr ' ' "$nl" < "$tmpdepfile" \
-    | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \
-    | sed -e 's/$/ :/' >> "$depfile"
-  rm -f "$tmpdepfile"
-  ;;
-
-hp)
-  # This case exists only to let depend.m4 do its work.  It works by
-  # looking at the text of this script.  This case will never be run,
-  # since it is checked for above.
-  exit 1
-  ;;
-
-sgi)
-  if test "$libtool" = yes; then
-    "$@" "-Wp,-MDupdate,$tmpdepfile"
-  else
-    "$@" -MDupdate "$tmpdepfile"
-  fi
-  stat=$?
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile"
-    exit $stat
-  fi
-  rm -f "$depfile"
-
-  if test -f "$tmpdepfile"; then  # yes, the sourcefile depend on other files
-    echo "$object : \\" > "$depfile"
-    # Clip off the initial element (the dependent).  Don't try to be
-    # clever and replace this with sed code, as IRIX sed won't handle
-    # lines with more than a fixed number of characters (4096 in
-    # IRIX 6.2 sed, 8192 in IRIX 6.5).  We also remove comment lines;
-    # the IRIX cc adds comments like '#:fec' to the end of the
-    # dependency line.
-    tr ' ' "$nl" < "$tmpdepfile" \
-      | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \
-      | tr "$nl" ' ' >> "$depfile"
-    echo >> "$depfile"
-    # The second pass generates a dummy entry for each header file.
-    tr ' ' "$nl" < "$tmpdepfile" \
-      | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
-      >> "$depfile"
-  else
-    make_dummy_depfile
-  fi
-  rm -f "$tmpdepfile"
-  ;;
-
-xlc)
-  # This case exists only to let depend.m4 do its work.  It works by
-  # looking at the text of this script.  This case will never be run,
-  # since it is checked for above.
-  exit 1
-  ;;
-
-aix)
-  # The C for AIX Compiler uses -M and outputs the dependencies
-  # in a .u file.  In older versions, this file always lives in the
-  # current directory.  Also, the AIX compiler puts '$object:' at the
-  # start of each line; $object doesn't have directory information.
-  # Version 6 uses the directory in both cases.
-  set_dir_from "$object"
-  set_base_from "$object"
-  if test "$libtool" = yes; then
-    tmpdepfile1=$dir$base.u
-    tmpdepfile2=$base.u
-    tmpdepfile3=$dir.libs/$base.u
-    "$@" -Wc,-M
-  else
-    tmpdepfile1=$dir$base.u
-    tmpdepfile2=$dir$base.u
-    tmpdepfile3=$dir$base.u
-    "$@" -M
-  fi
-  stat=$?
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
-    exit $stat
-  fi
-
-  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
-  do
-    test -f "$tmpdepfile" && break
-  done
-  aix_post_process_depfile
-  ;;
-
-tcc)
-  # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26
-  # FIXME: That version still under development at the moment of writing.
-  #        Make that this statement remains true also for stable, released
-  #        versions.
-  # It will wrap lines (doesn't matter whether long or short) with a
-  # trailing '\', as in:
-  #
-  #   foo.o : \
-  #    foo.c \
-  #    foo.h \
-  #
-  # It will put a trailing '\' even on the last line, and will use leading
-  # spaces rather than leading tabs (at least since its commit 0394caf7
-  # "Emit spaces for -MD").
-  "$@" -MD -MF "$tmpdepfile"
-  stat=$?
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile"
-    exit $stat
-  fi
-  rm -f "$depfile"
-  # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'.
-  # We have to change lines of the first kind to '$object: \'.
-  sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile"
-  # And for each line of the second kind, we have to emit a 'dep.h:'
-  # dummy dependency, to avoid the deleted-header problem.
-  sed -n -e 's|^  *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile"
-  rm -f "$tmpdepfile"
-  ;;
-
-## The order of this option in the case statement is important, since the
-## shell code in configure will try each of these formats in the order
-## listed in this file.  A plain '-MD' option would be understood by many
-## compilers, so we must ensure this comes after the gcc and icc options.
-pgcc)
-  # Portland's C compiler understands '-MD'.
-  # Will always output deps to 'file.d' where file is the root name of the
-  # source file under compilation, even if file resides in a subdirectory.
-  # The object file name does not affect the name of the '.d' file.
-  # pgcc 10.2 will output
-  #    foo.o: sub/foo.c sub/foo.h
-  # and will wrap long lines using '\' :
-  #    foo.o: sub/foo.c ... \
-  #     sub/foo.h ... \
-  #     ...
-  set_dir_from "$object"
-  # Use the source, not the object, to determine the base name, since
-  # that's sadly what pgcc will do too.
-  set_base_from "$source"
-  tmpdepfile=$base.d
-
-  # For projects that build the same source file twice into different object
-  # files, the pgcc approach of using the *source* file root name can cause
-  # problems in parallel builds.  Use a locking strategy to avoid stomping on
-  # the same $tmpdepfile.
-  lockdir=$base.d-lock
-  trap "
-    echo '$0: caught signal, cleaning up...' >&2
-    rmdir '$lockdir'
-    exit 1
-  " 1 2 13 15
-  numtries=100
-  i=$numtries
-  while test $i -gt 0; do
-    # mkdir is a portable test-and-set.
-    if mkdir "$lockdir" 2>/dev/null; then
-      # This process acquired the lock.
-      "$@" -MD
-      stat=$?
-      # Release the lock.
-      rmdir "$lockdir"
-      break
-    else
-      # If the lock is being held by a different process, wait
-      # until the winning process is done or we timeout.
-      while test -d "$lockdir" && test $i -gt 0; do
-        sleep 1
-        i=`expr $i - 1`
-      done
-    fi
-    i=`expr $i - 1`
-  done
-  trap - 1 2 13 15
-  if test $i -le 0; then
-    echo "$0: failed to acquire lock after $numtries attempts" >&2
-    echo "$0: check lockdir '$lockdir'" >&2
-    exit 1
-  fi
-
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile"
-    exit $stat
-  fi
-  rm -f "$depfile"
-  # Each line is of the form `foo.o: dependent.h',
-  # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
-  # Do two passes, one to just change these to
-  # `$object: dependent.h' and one to simply `dependent.h:'.
-  sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
-  # Some versions of the HPUX 10.20 sed can't process this invocation
-  # correctly.  Breaking it into two sed invocations is a workaround.
-  sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \
-    | sed -e 's/$/ :/' >> "$depfile"
-  rm -f "$tmpdepfile"
-  ;;
-
-hp2)
-  # The "hp" stanza above does not work with aCC (C++) and HP's ia64
-  # compilers, which have integrated preprocessors.  The correct option
-  # to use with these is +Maked; it writes dependencies to a file named
-  # 'foo.d', which lands next to the object file, wherever that
-  # happens to be.
-  # Much of this is similar to the tru64 case; see comments there.
-  set_dir_from  "$object"
-  set_base_from "$object"
-  if test "$libtool" = yes; then
-    tmpdepfile1=$dir$base.d
-    tmpdepfile2=$dir.libs/$base.d
-    "$@" -Wc,+Maked
-  else
-    tmpdepfile1=$dir$base.d
-    tmpdepfile2=$dir$base.d
-    "$@" +Maked
-  fi
-  stat=$?
-  if test $stat -ne 0; then
-     rm -f "$tmpdepfile1" "$tmpdepfile2"
-     exit $stat
-  fi
-
-  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
-  do
-    test -f "$tmpdepfile" && break
-  done
-  if test -f "$tmpdepfile"; then
-    sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile"
-    # Add 'dependent.h:' lines.
-    sed -ne '2,${
-               s/^ *//
-               s/ \\*$//
-               s/$/:/
-               p
-             }' "$tmpdepfile" >> "$depfile"
-  else
-    make_dummy_depfile
-  fi
-  rm -f "$tmpdepfile" "$tmpdepfile2"
-  ;;
-
-tru64)
-  # The Tru64 compiler uses -MD to generate dependencies as a side
-  # effect.  'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'.
-  # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
-  # dependencies in 'foo.d' instead, so we check for that too.
-  # Subdirectories are respected.
-  set_dir_from  "$object"
-  set_base_from "$object"
-
-  if test "$libtool" = yes; then
-    # Libtool generates 2 separate objects for the 2 libraries.  These
-    # two compilations output dependencies in $dir.libs/$base.o.d and
-    # in $dir$base.o.d.  We have to check for both files, because
-    # one of the two compilations can be disabled.  We should prefer
-    # $dir$base.o.d over $dir.libs/$base.o.d because the latter is
-    # automatically cleaned when .libs/ is deleted, while ignoring
-    # the former would cause a distcleancheck panic.
-    tmpdepfile1=$dir$base.o.d          # libtool 1.5
-    tmpdepfile2=$dir.libs/$base.o.d    # Likewise.
-    tmpdepfile3=$dir.libs/$base.d      # Compaq CCC V6.2-504
-    "$@" -Wc,-MD
-  else
-    tmpdepfile1=$dir$base.d
-    tmpdepfile2=$dir$base.d
-    tmpdepfile3=$dir$base.d
-    "$@" -MD
-  fi
-
-  stat=$?
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
-    exit $stat
-  fi
-
-  for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
-  do
-    test -f "$tmpdepfile" && break
-  done
-  # Same post-processing that is required for AIX mode.
-  aix_post_process_depfile
-  ;;
-
-msvc7)
-  if test "$libtool" = yes; then
-    showIncludes=-Wc,-showIncludes
-  else
-    showIncludes=-showIncludes
-  fi
-  "$@" $showIncludes > "$tmpdepfile"
-  stat=$?
-  grep -v '^Note: including file: ' "$tmpdepfile"
-  if test $stat -ne 0; then
-    rm -f "$tmpdepfile"
-    exit $stat
-  fi
-  rm -f "$depfile"
-  echo "$object : \\" > "$depfile"
-  # The first sed program below extracts the file names and escapes
-  # backslashes for cygpath.  The second sed program outputs the file
-  # name when reading, but also accumulates all include files in the
-  # hold buffer in order to output them again at the end.  This only
-  # works with sed implementations that can handle large buffers.
-  sed < "$tmpdepfile" -n '
-/^Note: including file:  *\(.*\)/ {
-  s//\1/
-  s/\\/\\\\/g
-  p
-}' | $cygpath_u | sort -u | sed -n '
-s/ /\\ /g
-s/\(.*\)/'"$tab"'\1 \\/p
-s/.\(.*\) \\/\1:/
-H
-$ {
-  s/.*/'"$tab"'/
-  G
-  p
-}' >> "$depfile"
-  echo >> "$depfile" # make sure the fragment doesn't end with a backslash
-  rm -f "$tmpdepfile"
-  ;;
-
-msvc7msys)
-  # This case exists only to let depend.m4 do its work.  It works by
-  # looking at the text of this script.  This case will never be run,
-  # since it is checked for above.
-  exit 1
-  ;;
-
-#nosideeffect)
-  # This comment above is used by automake to tell side-effect
-  # dependency tracking mechanisms from slower ones.
-
-dashmstdout)
-  # Important note: in order to support this mode, a compiler *must*
-  # always write the preprocessed file to stdout, regardless of -o.
-  "$@" || exit $?
-
-  # Remove the call to Libtool.
-  if test "$libtool" = yes; then
-    while test "X$1" != 'X--mode=compile'; do
-      shift
-    done
-    shift
-  fi
-
-  # Remove '-o $object'.
-  IFS=" "
-  for arg
-  do
-    case $arg in
-    -o)
-      shift
-      ;;
-    $object)
-      shift
-      ;;
-    *)
-      set fnord "$@" "$arg"
-      shift # fnord
-      shift # $arg
-      ;;
-    esac
-  done
-
-  test -z "$dashmflag" && dashmflag=-M
-  # Require at least two characters before searching for ':'
-  # in the target name.  This is to cope with DOS-style filenames:
-  # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise.
-  "$@" $dashmflag |
-    sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile"
-  rm -f "$depfile"
-  cat < "$tmpdepfile" > "$depfile"
-  # Some versions of the HPUX 10.20 sed can't process this sed invocation
-  # correctly.  Breaking it into two sed invocations is a workaround.
-  tr ' ' "$nl" < "$tmpdepfile" \
-    | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
-    | sed -e 's/$/ :/' >> "$depfile"
-  rm -f "$tmpdepfile"
-  ;;
-
-dashXmstdout)
-  # This case only exists to satisfy depend.m4.  It is never actually
-  # run, as this mode is specially recognized in the preamble.
-  exit 1
-  ;;
-
-makedepend)
-  "$@" || exit $?
-  # Remove any Libtool call
-  if test "$libtool" = yes; then
-    while test "X$1" != 'X--mode=compile'; do
-      shift
-    done
-    shift
-  fi
-  # X makedepend
-  shift
-  cleared=no eat=no
-  for arg
-  do
-    case $cleared in
-    no)
-      set ""; shift
-      cleared=yes ;;
-    esac
-    if test $eat = yes; then
-      eat=no
-      continue
-    fi
-    case "$arg" in
-    -D*|-I*)
-      set fnord "$@" "$arg"; shift ;;
-    # Strip any option that makedepend may not understand.  Remove
-    # the object too, otherwise makedepend will parse it as a source file.
-    -arch)
-      eat=yes ;;
-    -*|$object)
-      ;;
-    *)
-      set fnord "$@" "$arg"; shift ;;
-    esac
-  done
-  obj_suffix=`echo "$object" | sed 's/^.*\././'`
-  touch "$tmpdepfile"
-  ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
-  rm -f "$depfile"
-  # makedepend may prepend the VPATH from the source file name to the object.
-  # No need to regex-escape $object, excess matching of '.' is harmless.
-  sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile"
-  # Some versions of the HPUX 10.20 sed can't process the last invocation
-  # correctly.  Breaking it into two sed invocations is a workaround.
-  sed '1,2d' "$tmpdepfile" \
-    | tr ' ' "$nl" \
-    | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
-    | sed -e 's/$/ :/' >> "$depfile"
-  rm -f "$tmpdepfile" "$tmpdepfile".bak
-  ;;
-
-cpp)
-  # Important note: in order to support this mode, a compiler *must*
-  # always write the preprocessed file to stdout.
-  "$@" || exit $?
-
-  # Remove the call to Libtool.
-  if test "$libtool" = yes; then
-    while test "X$1" != 'X--mode=compile'; do
-      shift
-    done
-    shift
-  fi
-
-  # Remove '-o $object'.
-  IFS=" "
-  for arg
-  do
-    case $arg in
-    -o)
-      shift
-      ;;
-    $object)
-      shift
-      ;;
-    *)
-      set fnord "$@" "$arg"
-      shift # fnord
-      shift # $arg
-      ;;
-    esac
-  done
-
-  "$@" -E \
-    | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-             -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-    | sed '$ s: \\$::' > "$tmpdepfile"
-  rm -f "$depfile"
-  echo "$object : \\" > "$depfile"
-  cat < "$tmpdepfile" >> "$depfile"
-  sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
-  rm -f "$tmpdepfile"
-  ;;
-
-msvisualcpp)
-  # Important note: in order to support this mode, a compiler *must*
-  # always write the preprocessed file to stdout.
-  "$@" || exit $?
-
-  # Remove the call to Libtool.
-  if test "$libtool" = yes; then
-    while test "X$1" != 'X--mode=compile'; do
-      shift
-    done
-    shift
-  fi
-
-  IFS=" "
-  for arg
-  do
-    case "$arg" in
-    -o)
-      shift
-      ;;
-    $object)
-      shift
-      ;;
-    "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
-        set fnord "$@"
-        shift
-        shift
-        ;;
-    *)
-        set fnord "$@" "$arg"
-        shift
-        shift
-        ;;
-    esac
-  done
-  "$@" -E 2>/dev/null |
-  sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
-  rm -f "$depfile"
-  echo "$object : \\" > "$depfile"
-  sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile"
-  echo "$tab" >> "$depfile"
-  sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
-  rm -f "$tmpdepfile"
-  ;;
-
-msvcmsys)
-  # This case exists only to let depend.m4 do its work.  It works by
-  # looking at the text of this script.  This case will never be run,
-  # since it is checked for above.
-  exit 1
-  ;;
-
-none)
-  exec "$@"
-  ;;
-
-*)
-  echo "Unknown depmode $depmode" 1>&2
-  exit 1
-  ;;
-esac
-
-exit 0
-
-# Local Variables:
-# mode: shell-script
-# sh-indentation: 2
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/doc/.gitignore b/doc/.gitignore
new file mode 100644
index 0000000..b904aac
--- /dev/null
+++ b/doc/.gitignore
@@ -0,0 +1,64 @@
+/libmicrohttpd.vr
+/libmicrohttpd.tps
+/libmicrohttpd.tp
+/libmicrohttpd.toc
+/libmicrohttpd.pg
+/libmicrohttpd.ky
+/libmicrohttpd.fns
+/libmicrohttpd.fn
+/libmicrohttpd.cps
+/libmicrohttpd.cp
+/libmicrohttpd.aux
+/texinfo.tex
+/libmicrohttpd-tutorial.info
+/libmicrohttpd.info
+/libmicrohttpd.html
+/microhttpd-tutorial.vr
+/microhttpd-tutorial.tp
+/microhttpd-tutorial.toc
+/microhttpd-tutorial.pg
+/microhttpd-tutorial.pdf
+/microhttpd-tutorial.log
+/microhttpd-tutorial.ky
+/microhttpd-tutorial.info
+/microhttpd-tutorial.html
+/microhttpd-tutorial.fn
+/microhttpd-tutorial.cp
+/microhttpd-tutorial.aux
+/libmicrohttpd-tutorial.vr
+/libmicrohttpd-tutorial.tp
+/libmicrohttpd-tutorial.pg
+/libmicrohttpd-tutorial.pdf
+/libmicrohttpd-tutorial.log
+/libmicrohttpd-tutorial.ky
+/libmicrohttpd-tutorial.html
+/libmicrohttpd-tutorial.fn
+/libmicrohttpd-tutorial.cp
+/libmicrohttpd-tutorial.cps
+/microhttpd.html
+/version.texi.orig
+/libmicrohttpd-tutorial.toc
+/libmicrohttpd-tutorial.aux
+/stamp-vti.orig
+/microhttpd.info.orig
+/microhttpd.vr
+/microhttpd.tps
+/microhttpd.tp
+/microhttpd.toc
+/microhttpd.pg
+/microhttpd.pdf
+/microhttpd.log
+/microhttpd.ky
+/microhttpd.fns
+/microhttpd.fn
+/microhttpd.cps
+/microhttpd.cp
+/microhttpd.aux
+/tutorial
+/microhttpd
+/libmicrohttpdtutorial
+/version.texi
+/stamp-vti
+/microhttpd.info
+/mdate-sh
+/doxygen
diff --git a/doc/Makefile.am b/doc/Makefile.am
index 287514d..3a236cc 100644
--- a/doc/Makefile.am
+++ b/doc/Makefile.am
@@ -1,17 +1,27 @@
 # This Makefile.am is in the public domain
-man_MANS = libmicrohttpd.3
+dist_man_MANS = libmicrohttpd.3
 
-SUBDIRS = . examples doxygen
+SUBDIRS = . doxygen
+
+if BUILD_EXAMPLES
+SUBDIRS += examples
+endif
 
 DISTCLEANFILES = \
   libmicrohttpd.cps \
   libmicrohttpd.dvi \
   libmicrohttpd-tutorial.cps \
   libmicrohttpd-tutorial.dvi
+
 info_TEXINFOS = \
   libmicrohttpd.texi \
   libmicrohttpd-tutorial.texi
 microhttpd_TEXINFOS = \
+  lgpl.texi \
+  ecos.texi \
+  gpl-2.0.texi \
+  fdl-1.3.texi
+microhttpd_tutorial_TEXINFOS = \
   chapters/basicauthentication.inc \
   chapters/bibliography.inc \
   chapters/exploringrequests.inc \
@@ -22,9 +32,36 @@
   chapters/responseheaders.inc \
   chapters/tlsauthentication.inc \
   chapters/sessions.inc \
-  fdl-1.3.texi \
-  lgpl.texi \
-  ecos.texi
+  chapters/websocket.inc
 
-EXTRA_DIST = $(man_MANS) $(microhttpd_TEXINFOS) performance_data.png performance_data.eps
+EXTRA_DIST = \
+  $(microhttpd_TEXINFOS) $(microhttpd_tutorial_TEXINFOS) \
+  libmicrohttpd_performance_data.png \
+  libmicrohttpd_performance_data.eps
+
+install-info-local:
+	@echo " $(MKDIR_P) '$(DESTDIR)$(infodir)'"; \
+	$(MKDIR_P) "$(DESTDIR)$(infodir)" || exit 1; \
+	echo " $(INSTALL_DATA) libmicrohttpd_performance_data.png '$(DESTDIR)$(infodir)'"; \
+	$(INSTALL_DATA) '$(srcdir)/libmicrohttpd_performance_data.png' "$(DESTDIR)$(infodir)" || exit 1;
+
+install-html-local:
+	@if test -n "$(htmldir)"; then \
+	  echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)/libmicrohttpd.html'"; \
+	  $(MKDIR_P) "$(DESTDIR)$(htmldir)/libmicrohttpd.html" || exit 1; \
+	  echo " $(INSTALL_DATA) libmicrohttpd_performance_data.png '$(DESTDIR)$(htmldir)/libmicrohttpd.html'"; \
+	  $(INSTALL_DATA) '$(srcdir)/libmicrohttpd_performance_data.png' "$(DESTDIR)$(htmldir)/libmicrohttpd.html" || exit 1; \
+	else : ; fi
+
+uninstall-local:
+	@if test -d "$(DESTDIR)$(infodir)"; then \
+	  echo " rm -f '$(DESTDIR)$(infodir)/libmicrohttpd_performance_data.png'"; \
+	  rm -f "$(DESTDIR)$(infodir)/libmicrohttpd_performance_data.png" \
+	else : ; fi
+
+update-stamp:
+	@rm -f '$(srcdir)/stamp-vti' '$(srcdir)/version.texi' && \
+	  $(MAKE) $(AM_MAKEFLAGS) '$(srcdir)/version.texi'
+
+.PHONY: update-stamp
 
diff --git a/doc/Makefile.in b/doc/Makefile.in
deleted file mode 100644
index adf9d93..0000000
--- a/doc/Makefile.in
+++ /dev/null
@@ -1,1086 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-subdir = doc
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am mdate-sh \
-	$(srcdir)/version.texi $(srcdir)/stamp-vti texinfo.tex
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-AM_V_DVIPS = $(am__v_DVIPS_@AM_V@)
-am__v_DVIPS_ = $(am__v_DVIPS_@AM_DEFAULT_V@)
-am__v_DVIPS_0 = @echo "  DVIPS   " $@;
-am__v_DVIPS_1 = 
-AM_V_MAKEINFO = $(am__v_MAKEINFO_@AM_V@)
-am__v_MAKEINFO_ = $(am__v_MAKEINFO_@AM_DEFAULT_V@)
-am__v_MAKEINFO_0 = @echo "  MAKEINFO" $@;
-am__v_MAKEINFO_1 = 
-AM_V_INFOHTML = $(am__v_INFOHTML_@AM_V@)
-am__v_INFOHTML_ = $(am__v_INFOHTML_@AM_DEFAULT_V@)
-am__v_INFOHTML_0 = @echo "  INFOHTML" $@;
-am__v_INFOHTML_1 = 
-AM_V_TEXI2DVI = $(am__v_TEXI2DVI_@AM_V@)
-am__v_TEXI2DVI_ = $(am__v_TEXI2DVI_@AM_DEFAULT_V@)
-am__v_TEXI2DVI_0 = @echo "  TEXI2DVI" $@;
-am__v_TEXI2DVI_1 = 
-AM_V_TEXI2PDF = $(am__v_TEXI2PDF_@AM_V@)
-am__v_TEXI2PDF_ = $(am__v_TEXI2PDF_@AM_DEFAULT_V@)
-am__v_TEXI2PDF_0 = @echo "  TEXI2PDF" $@;
-am__v_TEXI2PDF_1 = 
-AM_V_texinfo = $(am__v_texinfo_@AM_V@)
-am__v_texinfo_ = $(am__v_texinfo_@AM_DEFAULT_V@)
-am__v_texinfo_0 = -q
-am__v_texinfo_1 = 
-AM_V_texidevnull = $(am__v_texidevnull_@AM_V@)
-am__v_texidevnull_ = $(am__v_texidevnull_@AM_DEFAULT_V@)
-am__v_texidevnull_0 = > /dev/null
-am__v_texidevnull_1 = 
-INFO_DEPS = $(srcdir)/libmicrohttpd.info \
-	$(srcdir)/libmicrohttpd-tutorial.info
-am__TEXINFO_TEX_DIR = $(srcdir)
-DVIS = libmicrohttpd.dvi libmicrohttpd-tutorial.dvi
-PDFS = libmicrohttpd.pdf libmicrohttpd-tutorial.pdf
-PSS = libmicrohttpd.ps libmicrohttpd-tutorial.ps
-HTMLS = libmicrohttpd.html libmicrohttpd-tutorial.html
-TEXINFOS = libmicrohttpd.texi libmicrohttpd-tutorial.texi
-TEXI2DVI = texi2dvi
-TEXI2PDF = $(TEXI2DVI) --pdf --batch
-MAKEINFOHTML = $(MAKEINFO) --html
-AM_MAKEINFOHTMLFLAGS = $(AM_MAKEINFOFLAGS)
-DVIPS = dvips
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__installdirs = "$(DESTDIR)$(infodir)" "$(DESTDIR)$(man3dir)"
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-man3dir = $(mandir)/man3
-NROFF = nroff
-MANS = $(man_MANS)
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-man_MANS = libmicrohttpd.3
-SUBDIRS = . examples doxygen
-DISTCLEANFILES = \
-  libmicrohttpd.cps \
-  libmicrohttpd.dvi \
-  libmicrohttpd-tutorial.cps \
-  libmicrohttpd-tutorial.dvi
-
-info_TEXINFOS = \
-  libmicrohttpd.texi \
-  libmicrohttpd-tutorial.texi
-
-microhttpd_TEXINFOS = \
-  chapters/basicauthentication.inc \
-  chapters/bibliography.inc \
-  chapters/exploringrequests.inc \
-  chapters/hellobrowser.inc \
-  chapters/introduction.inc \
-  chapters/largerpost.inc \
-  chapters/processingpost.inc \
-  chapters/responseheaders.inc \
-  chapters/tlsauthentication.inc \
-  chapters/sessions.inc \
-  fdl-1.3.texi \
-  lgpl.texi \
-  ecos.texi
-
-EXTRA_DIST = $(man_MANS) $(microhttpd_TEXINFOS) performance_data.png performance_data.eps
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .dvi .html .info .pdf .ps .texi
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu doc/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-.texi.info:
-	$(AM_V_MAKEINFO)restore=: && backupdir="$(am__leading_dot)am$$$$" && \
-	am__cwd=`pwd` && $(am__cd) $(srcdir) && \
-	rm -rf $$backupdir && mkdir $$backupdir && \
-	if ($(MAKEINFO) --version) >/dev/null 2>&1; then \
-	  for f in $@ $@-[0-9] $@-[0-9][0-9] $(@:.info=).i[0-9] $(@:.info=).i[0-9][0-9]; do \
-	    if test -f $$f; then mv $$f $$backupdir; restore=mv; else :; fi; \
-	  done; \
-	else :; fi && \
-	cd "$$am__cwd"; \
-	if $(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir) \
-	 -o $@ $<; \
-	then \
-	  rc=0; \
-	  $(am__cd) $(srcdir); \
-	else \
-	  rc=$$?; \
-	  $(am__cd) $(srcdir) && \
-	  $$restore $$backupdir/* `echo "./$@" | sed 's|[^/]*$$||'`; \
-	fi; \
-	rm -rf $$backupdir; exit $$rc
-
-.texi.dvi:
-	$(AM_V_TEXI2DVI)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \
-	MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir)' \
-	$(TEXI2DVI) $(AM_V_texinfo) --build-dir=$(@:.dvi=.t2d) -o $@ $(AM_V_texidevnull) \
-	$<
-
-.texi.pdf:
-	$(AM_V_TEXI2PDF)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \
-	MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir)' \
-	$(TEXI2PDF) $(AM_V_texinfo) --build-dir=$(@:.pdf=.t2p) -o $@ $(AM_V_texidevnull) \
-	$<
-
-.texi.html:
-	$(AM_V_MAKEINFO)rm -rf $(@:.html=.htp)
-	$(AM_V_at)if $(MAKEINFOHTML) $(AM_MAKEINFOHTMLFLAGS) $(MAKEINFOFLAGS) -I $(srcdir) \
-	 -o $(@:.html=.htp) $<; \
-	then \
-	  rm -rf $@ && mv $(@:.html=.htp) $@; \
-	else \
-	  rm -rf $(@:.html=.htp); exit 1; \
-	fi
-$(srcdir)/libmicrohttpd.info: libmicrohttpd.texi $(srcdir)/version.texi
-libmicrohttpd.dvi: libmicrohttpd.texi $(srcdir)/version.texi
-libmicrohttpd.pdf: libmicrohttpd.texi $(srcdir)/version.texi
-libmicrohttpd.html: libmicrohttpd.texi $(srcdir)/version.texi
-$(srcdir)/version.texi:  $(srcdir)/stamp-vti
-$(srcdir)/stamp-vti: libmicrohttpd.texi $(top_srcdir)/configure
-	@(dir=.; test -f ./libmicrohttpd.texi || dir=$(srcdir); \
-	set `$(SHELL) $(srcdir)/mdate-sh $$dir/libmicrohttpd.texi`; \
-	echo "@set UPDATED $$1 $$2 $$3"; \
-	echo "@set UPDATED-MONTH $$2 $$3"; \
-	echo "@set EDITION $(VERSION)"; \
-	echo "@set VERSION $(VERSION)") > vti.tmp
-	@cmp -s vti.tmp $(srcdir)/version.texi \
-	  || (echo "Updating $(srcdir)/version.texi"; \
-	      cp vti.tmp $(srcdir)/version.texi)
-	-@rm -f vti.tmp
-	@cp $(srcdir)/version.texi $@
-
-mostlyclean-vti:
-	-rm -f vti.tmp
-
-maintainer-clean-vti:
-	-rm -f $(srcdir)/stamp-vti $(srcdir)/version.texi
-$(srcdir)/libmicrohttpd-tutorial.info: libmicrohttpd-tutorial.texi 
-libmicrohttpd-tutorial.dvi: libmicrohttpd-tutorial.texi 
-libmicrohttpd-tutorial.pdf: libmicrohttpd-tutorial.texi 
-libmicrohttpd-tutorial.html: libmicrohttpd-tutorial.texi 
-.dvi.ps:
-	$(AM_V_DVIPS)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \
-	$(DVIPS) $(AM_V_texinfo) -o $@ $<
-
-uninstall-dvi-am:
-	@$(NORMAL_UNINSTALL)
-	@list='$(DVIS)'; test -n "$(dvidir)" || list=; \
-	for p in $$list; do \
-	  $(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(dvidir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(dvidir)/$$f"; \
-	done
-
-uninstall-html-am:
-	@$(NORMAL_UNINSTALL)
-	@list='$(HTMLS)'; test -n "$(htmldir)" || list=; \
-	for p in $$list; do \
-	  $(am__strip_dir) \
-	  echo " rm -rf '$(DESTDIR)$(htmldir)/$$f'"; \
-	  rm -rf "$(DESTDIR)$(htmldir)/$$f"; \
-	done
-
-uninstall-info-am:
-	@$(PRE_UNINSTALL)
-	@if test -d '$(DESTDIR)$(infodir)' && $(am__can_run_installinfo); then \
-	  list='$(INFO_DEPS)'; \
-	  for file in $$list; do \
-	    relfile=`echo "$$file" | sed 's|^.*/||'`; \
-	    echo " install-info --info-dir='$(DESTDIR)$(infodir)' --remove '$(DESTDIR)$(infodir)/$$relfile'"; \
-	    if install-info --info-dir="$(DESTDIR)$(infodir)" --remove "$(DESTDIR)$(infodir)/$$relfile"; \
-	    then :; else test ! -f "$(DESTDIR)$(infodir)/$$relfile" || exit 1; fi; \
-	  done; \
-	else :; fi
-	@$(NORMAL_UNINSTALL)
-	@list='$(INFO_DEPS)'; \
-	for file in $$list; do \
-	  relfile=`echo "$$file" | sed 's|^.*/||'`; \
-	  relfile_i=`echo "$$relfile" | sed 's|\.info$$||;s|$$|.i|'`; \
-	  (if test -d "$(DESTDIR)$(infodir)" && cd "$(DESTDIR)$(infodir)"; then \
-	     echo " cd '$(DESTDIR)$(infodir)' && rm -f $$relfile $$relfile-[0-9] $$relfile-[0-9][0-9] $$relfile_i[0-9] $$relfile_i[0-9][0-9]"; \
-	     rm -f $$relfile $$relfile-[0-9] $$relfile-[0-9][0-9] $$relfile_i[0-9] $$relfile_i[0-9][0-9]; \
-	   else :; fi); \
-	done
-
-uninstall-pdf-am:
-	@$(NORMAL_UNINSTALL)
-	@list='$(PDFS)'; test -n "$(pdfdir)" || list=; \
-	for p in $$list; do \
-	  $(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(pdfdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(pdfdir)/$$f"; \
-	done
-
-uninstall-ps-am:
-	@$(NORMAL_UNINSTALL)
-	@list='$(PSS)'; test -n "$(psdir)" || list=; \
-	for p in $$list; do \
-	  $(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(psdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(psdir)/$$f"; \
-	done
-
-dist-info: $(INFO_DEPS)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
-	list='$(INFO_DEPS)'; \
-	for base in $$list; do \
-	  case $$base in \
-	    $(srcdir)/*) base=`echo "$$base" | sed "s|^$$srcdirstrip/||"`;; \
-	  esac; \
-	  if test -f $$base; then d=.; else d=$(srcdir); fi; \
-	  base_i=`echo "$$base" | sed 's|\.info$$||;s|$$|.i|'`; \
-	  for file in $$d/$$base $$d/$$base-[0-9] $$d/$$base-[0-9][0-9] $$d/$$base_i[0-9] $$d/$$base_i[0-9][0-9]; do \
-	    if test -f $$file; then \
-	      relfile=`expr "$$file" : "$$d/\(.*\)"`; \
-	      test -f "$(distdir)/$$relfile" || \
-		cp -p $$file "$(distdir)/$$relfile"; \
-	    else :; fi; \
-	  done; \
-	done
-
-mostlyclean-aminfo:
-	-rm -rf libmicrohttpd.t2d libmicrohttpd.t2p libmicrohttpd-tutorial.t2d \
-	  libmicrohttpd-tutorial.t2p
-
-clean-aminfo:
-	-test -z "libmicrohttpd.dvi libmicrohttpd.pdf libmicrohttpd.ps \
-	  libmicrohttpd.html libmicrohttpd-tutorial.dvi \
-	  libmicrohttpd-tutorial.pdf libmicrohttpd-tutorial.ps \
-	  libmicrohttpd-tutorial.html" \
-	|| rm -rf libmicrohttpd.dvi libmicrohttpd.pdf libmicrohttpd.ps \
-	  libmicrohttpd.html libmicrohttpd-tutorial.dvi \
-	  libmicrohttpd-tutorial.pdf libmicrohttpd-tutorial.ps \
-	  libmicrohttpd-tutorial.html
-
-maintainer-clean-aminfo:
-	@list='$(INFO_DEPS)'; for i in $$list; do \
-	  i_i=`echo "$$i" | sed 's|\.info$$||;s|$$|.i|'`; \
-	  echo " rm -f $$i $$i-[0-9] $$i-[0-9][0-9] $$i_i[0-9] $$i_i[0-9][0-9]"; \
-	  rm -f $$i $$i-[0-9] $$i-[0-9][0-9] $$i_i[0-9] $$i_i[0-9][0-9]; \
-	done
-install-man3: $(man_MANS)
-	@$(NORMAL_INSTALL)
-	@list1=''; \
-	list2='$(man_MANS)'; \
-	test -n "$(man3dir)" \
-	  && test -n "`echo $$list1$$list2`" \
-	  || exit 0; \
-	echo " $(MKDIR_P) '$(DESTDIR)$(man3dir)'"; \
-	$(MKDIR_P) "$(DESTDIR)$(man3dir)" || exit 1; \
-	{ for i in $$list1; do echo "$$i"; done;  \
-	if test -n "$$list2"; then \
-	  for i in $$list2; do echo "$$i"; done \
-	    | sed -n '/\.3[a-z]*$$/p'; \
-	fi; \
-	} | while read p; do \
-	  if test -f $$p; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; echo "$$p"; \
-	done | \
-	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
-	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
-	sed 'N;N;s,\n, ,g' | { \
-	list=; while read file base inst; do \
-	  if test "$$base" = "$$inst"; then list="$$list $$file"; else \
-	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
-	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
-	  fi; \
-	done; \
-	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
-	while read files; do \
-	  test -z "$$files" || { \
-	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
-	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
-	done; }
-
-uninstall-man3:
-	@$(NORMAL_UNINSTALL)
-	@list=''; test -n "$(man3dir)" || exit 0; \
-	files=`{ for i in $$list; do echo "$$i"; done; \
-	l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
-	  sed -n '/\.3[a-z]*$$/p'; \
-	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
-	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
-	dir='$(DESTDIR)$(man3dir)'; $(am__uninstall_files_from_dir)
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-	$(MAKE) $(AM_MAKEFLAGS) \
-	  top_distdir="$(top_distdir)" distdir="$(distdir)" \
-	  dist-info
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(INFO_DEPS) $(MANS)
-installdirs: installdirs-recursive
-installdirs-am:
-	for dir in "$(DESTDIR)$(infodir)" "$(DESTDIR)$(man3dir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-	-test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-aminfo clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am: $(DVIS)
-
-html: html-recursive
-
-html-am: $(HTMLS)
-
-info: info-recursive
-
-info-am: $(INFO_DEPS)
-
-install-data-am: install-info-am install-man
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am: $(DVIS)
-	@$(NORMAL_INSTALL)
-	@list='$(DVIS)'; test -n "$(dvidir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(dvidir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(dvidir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(dvidir)'"; \
-	  $(INSTALL_DATA) $$files "$(DESTDIR)$(dvidir)" || exit $$?; \
-	done
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am: $(HTMLS)
-	@$(NORMAL_INSTALL)
-	@list='$(HTMLS)'; list2=; test -n "$(htmldir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(htmldir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p" || test -d "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  $(am__strip_dir) \
-	  d2=$$d$$p; \
-	  if test -d "$$d2"; then \
-	    echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)/$$f'"; \
-	    $(MKDIR_P) "$(DESTDIR)$(htmldir)/$$f" || exit 1; \
-	    echo " $(INSTALL_DATA) '$$d2'/* '$(DESTDIR)$(htmldir)/$$f'"; \
-	    $(INSTALL_DATA) "$$d2"/* "$(DESTDIR)$(htmldir)/$$f" || exit $$?; \
-	  else \
-	    list2="$$list2 $$d2"; \
-	  fi; \
-	done; \
-	test -z "$$list2" || { echo "$$list2" | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldir)'"; \
-	  $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldir)" || exit $$?; \
-	done; }
-install-info: install-info-recursive
-
-install-info-am: $(INFO_DEPS)
-	@$(NORMAL_INSTALL)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
-	list='$(INFO_DEPS)'; test -n "$(infodir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(infodir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(infodir)" || exit 1; \
-	fi; \
-	for file in $$list; do \
-	  case $$file in \
-	    $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
-	  esac; \
-	  if test -f $$file; then d=.; else d=$(srcdir); fi; \
-	  file_i=`echo "$$file" | sed 's|\.info$$||;s|$$|.i|'`; \
-	  for ifile in $$d/$$file $$d/$$file-[0-9] $$d/$$file-[0-9][0-9] \
-	               $$d/$$file_i[0-9] $$d/$$file_i[0-9][0-9] ; do \
-	    if test -f $$ifile; then \
-	      echo "$$ifile"; \
-	    else : ; fi; \
-	  done; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(infodir)'"; \
-	  $(INSTALL_DATA) $$files "$(DESTDIR)$(infodir)" || exit $$?; done
-	@$(POST_INSTALL)
-	@if $(am__can_run_installinfo); then \
-	  list='$(INFO_DEPS)'; test -n "$(infodir)" || list=; \
-	  for file in $$list; do \
-	    relfile=`echo "$$file" | sed 's|^.*/||'`; \
-	    echo " install-info --info-dir='$(DESTDIR)$(infodir)' '$(DESTDIR)$(infodir)/$$relfile'";\
-	    install-info --info-dir="$(DESTDIR)$(infodir)" "$(DESTDIR)$(infodir)/$$relfile" || :;\
-	  done; \
-	else : ; fi
-install-man: install-man3
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am: $(PDFS)
-	@$(NORMAL_INSTALL)
-	@list='$(PDFS)'; test -n "$(pdfdir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(pdfdir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(pdfdir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pdfdir)'"; \
-	  $(INSTALL_DATA) $$files "$(DESTDIR)$(pdfdir)" || exit $$?; done
-install-ps: install-ps-recursive
-
-install-ps-am: $(PSS)
-	@$(NORMAL_INSTALL)
-	@list='$(PSS)'; test -n "$(psdir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(psdir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(psdir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(psdir)'"; \
-	  $(INSTALL_DATA) $$files "$(DESTDIR)$(psdir)" || exit $$?; done
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-aminfo \
-	maintainer-clean-generic maintainer-clean-vti
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-aminfo mostlyclean-generic \
-	mostlyclean-libtool mostlyclean-vti
-
-pdf: pdf-recursive
-
-pdf-am: $(PDFS)
-
-ps: ps-recursive
-
-ps-am: $(PSS)
-
-uninstall-am: uninstall-dvi-am uninstall-html-am uninstall-info-am \
-	uninstall-man uninstall-pdf-am uninstall-ps-am
-
-uninstall-man: uninstall-man3
-
-.MAKE: $(am__recursive_targets) install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-am clean clean-aminfo clean-generic clean-libtool \
-	cscopelist-am ctags ctags-am dist-info distclean \
-	distclean-generic distclean-libtool distclean-tags distdir dvi \
-	dvi-am html html-am info info-am install install-am \
-	install-data install-data-am install-dvi install-dvi-am \
-	install-exec install-exec-am install-html install-html-am \
-	install-info install-info-am install-man install-man3 \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-aminfo \
-	maintainer-clean-generic maintainer-clean-vti mostlyclean \
-	mostlyclean-aminfo mostlyclean-generic mostlyclean-libtool \
-	mostlyclean-vti pdf pdf-am ps ps-am tags tags-am uninstall \
-	uninstall-am uninstall-dvi-am uninstall-html-am \
-	uninstall-info-am uninstall-man uninstall-man3 \
-	uninstall-pdf-am uninstall-ps-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/doc/chapters/basicauthentication.inc b/doc/chapters/basicauthentication.inc
index bbdd364..ec0dd38 100644
--- a/doc/chapters/basicauthentication.inc
+++ b/doc/chapters/basicauthentication.inc
@@ -1,7 +1,7 @@
-With the small exception of IP address based access control, 
+With the small exception of IP address based access control,
 requests from all connecting clients where served equally until now.
 This chapter discusses a first method of client's authentication and
-its limits. 
+its limits.
 
 A very simple approach feasible with the means already discussed would
 be to expect the password in the @emph{URI} string before granting access to
@@ -12,115 +12,160 @@
 @end verbatim
 @noindent
 
-In the rare situation where the client is customized enough and the connection occurs
-through secured lines (e.g., a embedded device directly attached to another via wire)
-and where the ability to embedd a password in the URI or to pass on a URI with a
-password are desired, this can be a reasonable choice. 
+In the rare situation where the client is customized enough and the connection
+occurs through secured lines (e.g., a embedded device directly attached to
+another via wire) and where the ability to embed a password in the URI or to
+pass on a URI with a password are desired, this can be a reasonable choice.
 
-But when it is assumed that the user connecting does so with an ordinary Internet browser,
-this implementation brings some problems about. For example, the URI including the password
-stays in the address field or at least in the history of the browser for anybody near enough to see. 
-It will also be inconvenient to add the password manually to any new URI when the browser does
+But when it is assumed that the user connecting does so with an ordinary
+Internet browser, this implementation brings some problems about. For example,
+the URI including the password stays in the address field or at least in the
+history of the browser for anybody near enough to see.  It will also be
+inconvenient to add the password manually to any new URI when the browser does
 not know how to compose this automatically.
 
-At least the convenience issue can be addressed by employing the simplest built-in password
-facilities of HTTP compliant browsers, hence we want to start there. It will however turn out
-to have still severe weaknesses in terms of security which need consideration.
+At least the convenience issue can be addressed by employing the simplest
+built-in password facilities of HTTP compliant browsers, hence we want to
+start there. It will, however, turn out to have still severe weaknesses in
+terms of security which need consideration.
 
-Before we will start implementing @emph{Basic Authentication} as described in @emph{RFC 2617},
-we should finally abandon the bad practice of responding every request the first time our callback
-is called for a given connection. This is becoming more important now because the client and 
-the server will have to talk in a more bi-directional way than before to 
+Before we will start implementing @emph{Basic Authentication} as described in
+@emph{RFC 2617}, we will also abandon the simplistic and generally
+problematic practice of responding every request the first time our callback
+is called for a given connection. Queuing a response upon the first request
+is akin to generating an error response (even if it is a "200 OK" reply!).
+The reason is that MHD usually calls the callback in three phases:
 
-But how can we tell whether the callback has been called before for the particular connection?
-Initially, the pointer this parameter references is set by @emph{MHD} in the callback. But it will 
-also be "remembered" on the next call (for the same connection).
-Thus, we will generate no response until the parameter is non-null---implying the callback was
-called before at least once. We do not need to share information between different calls of the callback,
-so we can set the parameter to any adress that is assured to be not null. The pointer to the 
-@code{connection} structure will be pointing to a legal address, so we take this.
+@enumerate
+@item
+First, to initially tell the application about the connection and inquire whether
+it is OK to proceed. This call typically happens before the client could upload
+the request body, and can be used to tell the client to not proceed with the
+upload (if the client requested "Expect: 100 Continue"). Applications may queue
+a reply at this point, but it will force the connection to be closed and thus
+prevent keep-alive / pipelining, which is generally a bad idea. Applications
+wanting to proceed with the request throughout the other phases should just return
+"MHD_YES" and not queue any response.  Note that when an application suspends
+a connection in this callback, the phase does not advance and the application
+will be called again in this first phase.
+@item
+Next, to tell the application about upload data provided by the client.
+In this phase, the application may not queue replies, and trying to do so
+will result in MHD returning an error code from @code{MHD_queue_response}.
+If there is no upload data, this phase is skipped.
+@item
+Finally, to obtain a regular response from the application. This can be
+almost any type of response, including ones indicating failures. The
+one exception is a "100 Continue" response, which applications must never
+generate: MHD generates that response automatically when necessary in the
+first phase.  If the application does not queue a response, MHD may call
+the callback repeatedly (depending a bit on the threading model, the
+application should suspend the connection).
+@end enumerate
+
+But how can we tell whether the callback has been called before for the
+particular request?  Initially, the pointer this parameter references is
+set by @emph{MHD} in the callback. But it will also be "remembered" on the
+next call (for the same request).  Thus, we can use the @code{req_cls}
+location to keep track of the request state.  For now, we will simply
+generate no response until the parameter is non-null---implying the callback
+was called before at least once. We do not need to share information between
+different calls of the callback, so we can set the parameter to any address
+that is assured to be not null. The pointer to the @code{connection} structure
+will be pointing to a legal address, so we take this.
 
 The first time @code{answer_to_connection} is called, we will not even look at the headers.
 
 @verbatim
-static int 
+static int
 answer_to_connection (void *cls, struct MHD_Connection *connection,
-                      const char *url, const char *method, const char *version, 
+                      const char *url, const char *method, const char *version,
                       const char *upload_data, size_t *upload_data_size,
-                      void **con_cls)
+                      void **req_cls)
 {
   if (0 != strcmp(method, "GET")) return MHD_NO;
-  if (NULL == *con_cls) {*con_cls = connection; return MHD_YES;}
+  if (NULL == *req_cls) {*req_cls = connection; return MHD_YES;}
 
-  ... 
+  ...
   /* else respond accordingly */
   ...
 }
 @end verbatim
 @noindent
 
-Note how we lop off the connection on the first condition (no "GET" request), but return asking for more on 
-the other one with @code{MHD_YES}.
-With this minor change, we can proceed to implement the actual authentication process.
+Note how we lop off the connection on the first condition (no "GET" request),
+but return asking for more on the other one with @code{MHD_YES}.  With this
+minor change, we can proceed to implement the actual authentication process.
 
-@heading Request for authentication 
+@heading Request for authentication
 
-Let us assume we had only files not intended to be handed out without the correct username/password,
-so every "GET" request will be challenged.
-@emph{RFC 2617} describes how the server shall ask for authentication by adding a
-@emph{WWW-Authenticate} response header with the name of the @emph{realm} protected.
-MHD can generate and queue such a failure response for you using
-the @code{MHD_queue_basic_auth_fail_response} API.  The only thing you need to do
-is construct a response with the error page to be shown to the user
-if he aborts basic authentication.  But first, you should check if the
-proper credentials were already supplied using the
+Let us assume we had only files not intended to be handed out without the
+correct username/password, so every "GET" request will be challenged.
+@emph{RFC 7617} describes how the server shall ask for authentication by
+adding a @emph{WWW-Authenticate} response header with the name of the
+@emph{realm} protected.  MHD can generate and queue such a failure response
+for you using the @code{MHD_queue_basic_auth_fail_response} API.  The only
+thing you need to do is construct a response with the error page to be shown
+to the user if he aborts basic authentication.  But first, you should check if
+the proper credentials were already supplied using the
 @code{MHD_basic_auth_get_username_password} call.
 
 Your code would then look like this:
 @verbatim
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
-  char *user;
-  char *pass;
-  int fail;
+  struct MHD_BasicAuthInfo *auth_info;
+  enum MHD_Result ret;
   struct MHD_Response *response;
 
-  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+  if (0 != strcmp (method, "GET"))
     return MHD_NO;
-  if (NULL == *con_cls)
-    {
-      *con_cls = connection;
-      return MHD_YES;
-    }
-  pass = NULL;
-  user = MHD_basic_auth_get_username_password (connection, &pass);
-  fail = ( (user == NULL) ||
-	   (0 != strcmp (user, "root")) ||
-	   (0 != strcmp (pass, "pa$$w0rd") ) );  
-  if (user != NULL) free (user);
-  if (pass != NULL) free (pass);
-  if (fail)
-    {
-      const char *page = "<html><body>Go away.</body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (page), (void *) page, 
-				       MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_basic_auth_fail_response (connection,
-						"my realm",
-						response);
-    }
+  if (NULL == *req_cls)
+  {
+    *req_cls = connection;
+    return MHD_YES;
+  }
+  auth_info = MHD_basic_auth_get_username_password3 (connection);
+  if (NULL == auth_info)
+  {
+    static const char *page =
+      "<html><body>Authorization required</body></html>";
+    response = MHD_create_response_from_buffer_static (strlen (page), page);
+    ret = MHD_queue_basic_auth_fail_response3 (connection,
+                                               "admins",
+                                               MHD_YES,
+                                               response);
+  }
+  else if ((strlen ("root") != auth_info->username_len) ||
+           (0 != memcmp (auth_info->username, "root",
+                         auth_info->username_len)) ||
+           /* The next check against NULL is optional,
+            * if 'password' is NULL then 'password_len' is always zero. */
+           (NULL == auth_info->password) ||
+           (strlen ("pa$$w0rd") != auth_info->password_len) ||
+           (0 != memcmp (auth_info->password, "pa$$w0rd",
+                         auth_info->password_len)))
+  {
+    static const char *page =
+      "<html><body>Wrong username or password</body></html>";
+    response = MHD_create_response_from_buffer_static (strlen (page), page);
+    ret = MHD_queue_basic_auth_fail_response3 (connection,
+                                               "admins",
+                                               MHD_YES,
+                                               response);
+  }
   else
-    {
-      const char *page = "<html><body>A secret.</body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (page), (void *) page, 
-				       MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-    }
+  {
+    static const char *page = "<html><body>A secret.</body></html>";
+    response = MHD_create_response_from_buffer_static (strlen (page), page);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  }
+  if (NULL != auth_info)
+    MHD_free (auth_info);
   MHD_destroy_response (response);
   return ret;
 }
@@ -129,9 +174,9 @@
 See the @code{examples} directory for the complete example file.
 
 @heading Remarks
-For a proper server, the conditional statements leading to a return of @code{MHD_NO} should yield a 
+For a proper server, the conditional statements leading to a return of @code{MHD_NO} should yield a
 response with a more precise status code instead of silently closing the connection. For example,
-failures of memory allocation are best reported as @emph{internal server error} and unexpected 
+failures of memory allocation are best reported as @emph{internal server error} and unexpected
 authentication methods as @emph{400 bad request}.
 
 @heading Exercises
@@ -141,7 +186,7 @@
 @emph{401 unauthorized} status code. If the client still does not authenticate correctly within the
 same connection, close it and store the client's IP address for a certain time. (It is OK to check for
 expiration not until the main thread wakes up again on the next connection.) If the client fails
-authenticating three times during this period, add it to another list for which the 
+authenticating three times during this period, add it to another list for which the
 @code{AcceptPolicyCallback} function denies connection (temporally).
 
 @item
@@ -155,5 +200,3 @@
 and see how both the user's name and password could be completely restored.
 
 @end itemize
-
-
diff --git a/doc/chapters/bibliography.inc b/doc/chapters/bibliography.inc
index cc288bc..bdaa618 100644
--- a/doc/chapters/bibliography.inc
+++ b/doc/chapters/bibliography.inc
@@ -16,6 +16,9 @@
 @emph{RFC 2617}: Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P.,
 Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", RFC 2617, June 1999.
 
+@item
+@emph{RFC 6455}: Fette, I., Melnikov, A., "The WebSocket Protocol", RFC 6455, December 2011.
+
 
 @item 
 A well--structured @emph{HTML} reference can be found on
diff --git a/doc/chapters/exploringrequests.inc b/doc/chapters/exploringrequests.inc
index 2e43c38..8237c9b 100644
--- a/doc/chapters/exploringrequests.inc
+++ b/doc/chapters/exploringrequests.inc
@@ -14,7 +14,7 @@
                       const char *url, 
 		      const char *method, const char *version, 
 		      const char *upload_data, 
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
   ...  
   return MHD_NO;
diff --git a/doc/chapters/hellobrowser.inc b/doc/chapters/hellobrowser.inc
index 5859778..6ca37df 100644
--- a/doc/chapters/hellobrowser.inc
+++ b/doc/chapters/hellobrowser.inc
@@ -1,13 +1,13 @@
 The most basic task for a HTTP server is to deliver a static text message to any client connecting to it.
 Given that this is also easy to implement, it is an excellent problem to start with.
 
-For now, the particular URI the client asks for shall have no effect on the message that will 
+For now, the particular URI the client asks for shall have no effect on the message that will
 be returned. In addition, the server shall end the connection after the message has been sent so that
 the client will know there is nothing more to expect.
 
 The C program @code{hellobrowser.c}, which is to be found in the examples section, does just that.
 If you are very eager, you can compile and start it right away but it is advisable to type the
-lines in by yourself as they will be discussed and explained in detail. 
+lines in by yourself as they will be discussed and explained in detail.
 
 After the necessary includes and the definition of the port which our server should listen on
 @verbatim
@@ -23,13 +23,13 @@
 @noindent
 the desired behaviour of our server when HTTP request arrive has to be implemented. We already have
 agreed that it should not care about the particular details of the request, such as who is requesting
-what. The server will respond merely with the same small HTML page to every request. 
+what. The server will respond merely with the same small HTML page to every request.
 
 The function we are going to write now will be called by @emph{GNU libmicrohttpd} every time an
 appropriate request comes in. While the name of this callback function is arbitrary, its parameter
 list has to follow a certain layout. So please, ignore the lot of parameters for now, they will be
 explained at the point they are needed. We have to use only one of them,
-@code{struct MHD_Connection *connection}, for the minimalistic functionality we want to archive at the moment.
+@code{struct MHD_Connection *connection}, for the minimalistic functionality we want to achieve at the moment.
 
 This parameter is set by the @emph{libmicrohttpd} daemon and holds the necessary information to
 relate the call with a certain connection. Keep in mind that a server might have to satisfy hundreds
@@ -39,11 +39,11 @@
 
 Talking about the reply, it is defined as a string right after the function header
 @verbatim
-int answer_to_connection (void *cls, struct MHD_Connection *connection, 
-                          const char *url, 
-                          const char *method, const char *version, 
-                          const char *upload_data, 
-                          size_t *upload_data_size, void **con_cls)
+int answer_to_connection (void *cls, struct MHD_Connection *connection,
+                          const char *url,
+                          const char *method, const char *version,
+                          const char *upload_data,
+                          size_t *upload_data_size, void **req_cls)
 {
   const char *page  = "<html><body>Hello, browser!</body></html>";
 
@@ -53,7 +53,7 @@
 HTTP is a rather strict protocol and the client would certainly consider it "inappropriate" if we
 just sent the answer string "as is". Instead, it has to be wrapped with additional information stored in so-called headers and footers.  Most of the work in this area is done by the library for us---we
 just have to ask. Our reply string packed in the necessary layers will be called a "response".
-To obtain such a response we hand our data (the reply--string) and its size over to the 
+To obtain such a response we hand our data (the reply--string) and its size over to the
 @code{MHD_create_response_from_buffer} function. The last two parameters basically tell @emph{MHD}
 that we do not want it to dispose the message data for us when it has been sent and there also needs
 no internal copy to be done because the @emph{constant} string won't change anyway.
@@ -68,11 +68,11 @@
 @end verbatim
 
 @noindent
-Now that the the response has been laced up, it is ready for delivery and can be queued for sending. 
+Now that the the response has been laced up, it is ready for delivery and can be queued for sending.
 This is done by passing it to another @emph{GNU libmicrohttpd} function. As all our work was done in
 the scope of one function, the recipient is without doubt the one associated with the
-local variable @code{connection} and consequently this variable is given to the queue function. 
-Every HTTP response is accompanied by a status code, here "OK", so that the client knows 
+local variable @code{connection} and consequently this variable is given to the queue function.
+Every HTTP response is accompanied by a status code, here "OK", so that the client knows
 this response is the intended result of his request and not due to some error or malfunction.
 
 Finally, the packet is destroyed and the return value from the queue returned,
@@ -88,14 +88,14 @@
 @end verbatim
 
 @noindent
-With the primary task of our server implemented, we can start the actual server daemon which will listen 
+With the primary task of our server implemented, we can start the actual server daemon which will listen
 on @code{PORT} for connections. This is done in the main function.
 @verbatim
 int main ()
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL, 
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
                              &answer_to_connection, NULL, MHD_OPTION_END);
   if (NULL == daemon) return 1;
 
@@ -108,20 +108,20 @@
 example, where the reply is already known and therefore the request is served quickly, this poses no problem.
 
 We will allow all clients to connect regardless of their name or location, therefore we do not check
-them on connection and set the forth and fifth parameter to NULL.
+them on connection and set the third and fourth parameter to NULL.
 
-Parameter six is the address of the function we want to be called whenever a new connection has been
+Parameter five is the address of the function we want to be called whenever a new connection has been
 established. Our @code{answer_to_connection} knows best what the client wants and needs no additional
-information (which could be passed via the next parameter) so the next parameter is NULL. Likewise,
+information (which could be passed via the next parameter) so the next (sixth) parameter is NULL. Likewise,
 we do not need to pass extra options to the daemon so we just write the MHD_OPTION_END as the last parameter.
 
 As the server daemon runs in the background in its own thread, the execution flow in our main
-function will contine right after the call. Because of this, we must delay the execution flow in the
+function will continue right after the call. Because of this, we must delay the execution flow in the
 main thread or else the program will terminate prematurely. We let it pause in a processing-time
 friendly manner by waiting for the enter key to be pressed. In the end, we stop the daemon so it can
 do its cleanup tasks.
 @verbatim
-  getchar (); 
+  getchar ();
 
   MHD_stop_daemon (daemon);
   return 0;
@@ -132,9 +132,9 @@
 @noindent
 The first example is now complete.
 
-Compile it with 
+Compile it with
 @verbatim
-cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES 
+cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES
   -L$PATH_TO_LIBMHD_LIBS -lmicrohttpd
 @end verbatim
 with the two paths set accordingly and run it.
@@ -145,7 +145,7 @@
 
 @heading Remarks
 To keep this first example as small as possible, some drastic shortcuts were taken and are to be
-discussed now. 
+discussed now.
 
 Firstly, there is no distinction made between the kinds of requests a client could send. We implied
 that the client sends a GET request, that means, that he actually asked for some data. Even when
@@ -161,23 +161,23 @@
 disables HTTP pipelining.  The correct approach is to simply not queue a message on the first
 callback unless there is an error.  The @code{void**} argument to the callback provides a location
 for storing information about the history of the connection; for the first call, the pointer
-will point to NULL.  A simplistic way to differenciate the first call from others is to check
+will point to NULL.  A simplistic way to differentiate the first call from others is to check
 if the pointer is NULL and set it to a non-NULL value during the first call.
 
 Both of these issues you will find addressed in the official @code{minimal_example.c} residing in
 the @code{src/examples} directory of the @emph{MHD} package.  The source code of this
 program should look very familiar to you by now and easy to understand.
 
-For our example, the @code{must_copy} and @code{must_free} parameter at the response construction
-function could be set to @code{MHD_NO}. In the usual case, responses cannot be sent immediately
+For our example, we create the response from a static (persistent) buffer in memory and thus pass @code{MHD_RESPMEM_PERSISTENT} to the response construction
+function. In the usual case, responses are not transmitted immediately
 after being queued. For example, there might be other data on the system that needs to be sent with
 a higher priority. Nevertheless, the queue function will return successfully---raising the problem
 that the data we have pointed to may be invalid by the time it is about being sent. This is not an
 issue here because we can expect the @code{page} string, which is a constant @emph{string literal}
-here, to be static. That means it will be present and unchanged for as long as the program runs. 
-For dynamic data, one could choose to either have @emph{MHD} free the memory @code{page} points 
-to itself when it is not longer needed or, alternatively, have the library to make and manage 
-its own copy of it.
+here, to be static. That means it will be present and unchanged for as long as the program runs.
+For dynamic data, one could choose to either have @emph{MHD} free the memory @code{page} points
+to itself when it is not longer needed (by passing @code{MHD_RESPMEM_MUST_FREE}) or, alternatively, have the library to make and manage
+its own copy of it (by passing @code{MHD_RESPMEM_MUST_COPY}).  Naturally, this last option is the most expensive.
 
 @heading Exercises
 @itemize @bullet
@@ -191,7 +191,7 @@
 @end verbatim
 @noindent
 and see what the server returns to you.
-     
+
 
 @item
 Also, try other requests, like POST, and see how our server does not mind and why.
@@ -214,7 +214,7 @@
 
 
 @item
-@emph{Demanding:} Write a separate function returning a string containing some useful information, 
+@emph{Demanding:} Write a separate function returning a string containing some useful information,
 for example, the time. Pass the function's address as the sixth parameter and evaluate this function
 on every request anew in @code{answer_to_connection}. Remember to free the memory of the string
 every time after satisfying the request.
diff --git a/doc/chapters/introduction.inc b/doc/chapters/introduction.inc
index 95caf9a..2845d35 100644
--- a/doc/chapters/introduction.inc
+++ b/doc/chapters/introduction.inc
@@ -19,5 +19,5 @@
 @section History
 
 This tutorial was originally written by Sebastian Gerhardt for MHD
-0.4.0.  It was slighly polished and updated to MHD 0.9.0 by Christian
+0.4.0.  It was slightly polished and updated to MHD 0.9.0 by Christian
 Grothoff.
\ No newline at end of file
diff --git a/doc/chapters/largerpost.inc b/doc/chapters/largerpost.inc
index 1f60028..681550c 100644
--- a/doc/chapters/largerpost.inc
+++ b/doc/chapters/largerpost.inc
@@ -49,7 +49,7 @@
 adequately. 
 @verbatim
 const char* servererrorpage 
-  = "<html><body>An internal server error has occured.</body></html>";
+  = "<html><body>An internal server error has occurred.</body></html>";
 const char* fileexistspage
   = "<html><body>This file already exists.</body></html>";
 @end verbatim
@@ -95,9 +95,9 @@
 		      const char *url, 
                       const char *method, const char *version, 
 		      const char *upload_data, 
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
-  if (NULL == *con_cls) 
+  if (NULL == *req_cls) 
     {
       struct connection_info_struct *con_info;
 
@@ -120,7 +120,7 @@
         } 
       else con_info->connectiontype = GET;
 
-      *con_cls = (void*) con_info;
+      *req_cls = (void*) con_info;
  
       return MHD_YES;
     }
@@ -179,7 +179,7 @@
 @verbatim
   if (0 == strcmp (method, "POST")) 
     {
-      struct connection_info_struct *con_info = *con_cls;
+      struct connection_info_struct *con_info = *req_cls;
        
       if (0 != *upload_data_size) 
         { 
@@ -284,10 +284,10 @@
 on destroying the postprocessor when the request is completed.
 @verbatim
 void request_completed (void *cls, struct MHD_Connection *connection, 
-     		        void **con_cls,
+     		        void **req_cls,
                         enum MHD_RequestTerminationCode toe)
 {
-  struct connection_info_struct *con_info = *con_cls;
+  struct connection_info_struct *con_info = *req_cls;
 
   if (NULL == con_info) return;
 
@@ -303,7 +303,7 @@
     }
 
   free (con_info);
-  *con_cls = NULL;      
+  *req_cls = NULL;      
 }
 @end verbatim
 @noindent
diff --git a/doc/chapters/processingpost.inc b/doc/chapters/processingpost.inc
index 92f93f5..8f0dc7d 100644
--- a/doc/chapters/processingpost.inc
+++ b/doc/chapters/processingpost.inc
@@ -111,10 +111,10 @@
 
 @verbatim
 void request_completed (void *cls, struct MHD_Connection *connection, 
-     		        void **con_cls,
+     		        void **req_cls,
                         enum MHD_RequestTerminationCode toe)
 {
-  struct connection_info_struct *con_info = *con_cls;
+  struct connection_info_struct *con_info = *req_cls;
 
   if (NULL == con_info) return;
   if (con_info->connectiontype == POST)
@@ -124,7 +124,7 @@
     }
   
   free (con_info);
-  *con_cls = NULL;   
+  *req_cls = NULL;   
 }
 @end verbatim
 @noindent
@@ -134,7 +134,7 @@
 
 @verbatim
 ...
-daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
                            &answer_to_connection, NULL, 
 			   MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL,
 			   MHD_OPTION_END);
@@ -155,9 +155,9 @@
 		      const char *url, 
                       const char *method, const char *version, 
 		      const char *upload_data, 
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
-  if(NULL == *con_cls) 
+  if(NULL == *req_cls) 
     {
       struct connection_info_struct *con_info;
 
@@ -190,7 +190,7 @@
 The address of our structure will both serve as the indicator for successive iterations and to remember
 the particular details about the connection.
 @verbatim
-      *con_cls = (void*) con_info; 
+      *req_cls = (void*) con_info; 
       return MHD_YES;
     }
 @end verbatim
@@ -212,7 +212,7 @@
 @verbatim
   if (0 == strcmp (method, "POST")) 
     {
-      struct connection_info_struct *con_info = *con_cls;
+      struct connection_info_struct *con_info = *req_cls;
 
       if (*upload_data_size != 0) 
         {
diff --git a/doc/chapters/responseheaders.inc b/doc/chapters/responseheaders.inc
index ece7ce1..cd33e25 100644
--- a/doc/chapters/responseheaders.inc
+++ b/doc/chapters/responseheaders.inc
@@ -28,7 +28,7 @@
 		      const char *url, 
                       const char *method, const char *version, 
 		      const char *upload_data, 
-              	      size_t *upload_data_size, void **con_cls)
+              	      size_t *upload_data_size, void **req_cls)
 {
   unsigned char *buffer = NULL;
   struct MHD_Response *response;
@@ -60,7 +60,7 @@
       /* error accessing file */
      if (fd != -1) close (fd);
       const char *errorstr =
-        "<html><body>An internal server error has occured!\
+        "<html><body>An internal server error has occurred!\
                               </body></html>";
       response =
 	MHD_create_response_from_buffer (strlen (errorstr), 
@@ -79,7 +79,7 @@
         return MHD_NO;
   if (!ret) 
     {
-      const char *errorstr = "<html><body>An internal server error has occured!\
+      const char *errorstr = "<html><body>An internal server error has occurred!\
                               </body></html>";
 
       if (buffer) free(buffer);
@@ -120,7 +120,7 @@
 @end verbatim
 @noindent
 
-Note that the response object will take care of closing the file desciptor for us.
+Note that the response object will take care of closing the file descriptor for us.
 
 Up to this point, there was little new. The actual novelty is that we enhance the header with the
 meta data about the content. Aware of the field's name we want to add, it is as easy as that:
diff --git a/doc/chapters/sessions.inc b/doc/chapters/sessions.inc
index e4ee91d..ee48e58 100644
--- a/doc/chapters/sessions.inc
+++ b/doc/chapters/sessions.inc
@@ -16,10 +16,14 @@
 is straightforward:
 
 @verbatim
-FIXME.
+const char *value;
+
+value = MHD_lookup_connection_value (connection,
+                                     MHD_COOKIE_KIND,
+                                     "KEY");
 @end verbatim
 
-Here, FIXME is the name we chose for our session cookie.
+Here, "KEY" is the name we chose for our session cookie.
 
 
 @heading Setting the cookie header
@@ -29,14 +33,27 @@
 64-character text string to be used as the value of the cookie:
 
 @verbatim
-FIXME.
+char value[128];
+char raw_value[65];
+
+for (unsigned int i=0;i<sizeof (raw_value);i++)
+  raw_value = 'A' + (rand () % 26); /* bad PRNG! */
+raw_value[64] = '\0';
+snprintf (value, sizeof (value),
+          "%s=%s",
+          "KEY",
+          raw_value);
 @end verbatim
 
-Given this cookie value, we can then set the cookie header in our HTTP response 
+Given this cookie value, we can then set the cookie header in our HTTP response
 as follows:
 
 @verbatim
-FIXME.
+assert (MHD_YES ==
+        MHD_set_connection_value (connection,
+                                  MHD_HEADER_KIND,
+                                  MHD_HTTP_HEADER_SET_COOKIE,
+                                  value));
 @end verbatim
 
 
diff --git a/doc/chapters/tlsauthentication.inc b/doc/chapters/tlsauthentication.inc
index c1b6673..db3a4cc 100644
--- a/doc/chapters/tlsauthentication.inc
+++ b/doc/chapters/tlsauthentication.inc
@@ -65,10 +65,10 @@
 @end verbatim
 @noindent
 
-and then we point the @emph{MHD} daemon to it upon initalization.
+and then we point the @emph{MHD} daemon to it upon initialization.
 @verbatim
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL,
   	   		     PORT, NULL, NULL,
                              &answer_to_connection, NULL,
                              MHD_OPTION_HTTPS_MEM_KEY, key_pem,
@@ -138,7 +138,7 @@
 Next, when you start the MHD daemon, you must specify the root CA that you're
 willing to trust:
 @verbatim
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL,
   	   		     PORT, NULL, NULL,
                              &answer_to_connection, NULL,
                              MHD_OPTION_HTTPS_MEM_KEY, key_pem,
@@ -161,7 +161,7 @@
 
 ci = MHD_get_connection_info (connection,
                               MHD_CONNECTION_INFO_GNUTLS_SESSION);
-tls_session = ci->tls_session;
+tls_session = (gnutls_session_t) ci->tls_session;
 @end verbatim
 
 You can then extract the client certificate:
@@ -187,6 +187,13 @@
   if (gnutls_certificate_verify_peers2(tls_session,
 				       &client_cert_status))
     return NULL;
+  if (0 != client_cert_status)
+  {
+    fprintf (stderr,
+            "Failed client certificate invalid: %d\n",
+            client_cert_status);
+    return NULL;
+  }
   pcert = gnutls_certificate_get_peers(tls_session,
 				       &listsize);
   if ( (pcert == NULL) ||
@@ -229,7 +236,7 @@
  * 			to the dn if found
  */
 char *
-cert_auth_get_dn(gnutls_x509_crt_c client_cert)
+cert_auth_get_dn(gnutls_x509_crt_t client_cert)
 {
   char* buf;
   size_t lbuf;
@@ -326,7 +333,7 @@
 and certificate.  For example, when you start the MHD daemon, you could
 do this:
 @verbatim
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SSL,
   	   		     PORT, NULL, NULL,
                              &answer_to_connection, NULL,
                              MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback,
@@ -421,7 +428,7 @@
 point.
 
 The @code{hosts} list can be initialized by loading the private keys and X.509
-certificats from disk as follows:
+certificates from disk as follows:
 
 @verbatim
 static void
diff --git a/doc/chapters/websocket.inc b/doc/chapters/websocket.inc
new file mode 100644
index 0000000..a091bfa
--- /dev/null
+++ b/doc/chapters/websocket.inc
@@ -0,0 +1,886 @@
+Websockets are a genuine way to implement push notifications,
+where the server initiates the communication while the client can be idle.
+Usually a HTTP communication is half-duplex and always requested by the client,
+but websockets are full-duplex and only initialized by the client.
+In the further communication both sites can use the websocket at any time
+to send data to the other site.
+
+To initialize a websocket connection the client sends a special HTTP request
+to the server and initializes
+a handshake between client and server which switches from the HTTP protocol
+to the websocket protocol.
+Thus both the server as well as the client must support websockets.
+If proxys are used, they must support websockets too.
+In this chapter we take a look on server and client, but with a focus on
+the server with @emph{libmicrohttpd}.
+
+Since version 0.9.52 @emph{libmicrohttpd} supports upgrading requests,
+which is required for switching from the HTTP protocol.
+Since version 0.9.74 the library @emph{libmicrohttpd_ws} has been added
+to support the websocket protocol.
+
+@heading Upgrading connections with libmicrohttpd
+
+To support websockets we need to enable upgrading of HTTP connections first.
+This is done by passing the flag @code{MHD_ALLOW_UPGRADE} to
+@code{MHD_start_daemon()}.
+
+
+@verbatim
+daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD |
+                           MHD_USE_THREAD_PER_CONNECTION |
+                           MHD_ALLOW_UPGRADE |
+                           MHD_USE_ERROR_LOG,
+                           PORT, NULL, NULL,
+                           &access_handler, NULL,
+                           MHD_OPTION_END);
+@end verbatim
+@noindent
+
+
+The next step is to turn a specific request into an upgraded connection.
+This done in our @code{access_handler} by calling
+@code{MHD_create_response_for_upgrade()}.
+An @code{upgrade_handler} will be passed to perform the low-level actions
+on the socket.
+
+@emph{Please note that the socket here is just a regular socket as provided
+by the operating system.
+To use it as a websocket, some more steps from the following
+chapters are required.}
+
+
+@verbatim
+static enum MHD_Result
+access_handler (void *cls,
+                struct MHD_Connection *connection,
+                const char *url,
+                const char *method,
+                const char *version,
+                const char *upload_data,
+                size_t *upload_data_size,
+                void **ptr)
+{
+  /* ... */
+  /* some code to decide whether to upgrade or not */
+  /* ... */
+
+  /* create the response for upgrade */
+  response = MHD_create_response_for_upgrade (&upgrade_handler,
+                                              NULL);
+
+  /* ... */
+  /* additional headers, etc. */
+  /* ... */
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_SWITCHING_PROTOCOLS,
+                            response);
+  MHD_destroy_response (response);
+
+  return ret;
+}
+@end verbatim
+@noindent
+
+
+In the @code{upgrade_handler} we receive the low-level socket,
+which is used for the communication with the specific client.
+In addition to the low-level socket we get:
+@itemize @bullet
+@item
+Some data, which has been read too much while @emph{libmicrohttpd} was
+switching the protocols.
+This value is usually empty, because it would mean that the client
+has sent data before the handshake was complete.
+
+@item
+A @code{struct MHD_UpgradeResponseHandle} which is used to perform
+special actions like closing, corking or uncorking the socket.
+These commands are executed by passing the handle
+to @code{MHD_upgrade_action()}.
+
+
+@end itemize
+
+Depending of the flags specified while calling @code{MHD_start_deamon()}
+our @code{upgrade_handler} is either executed in the same thread
+as our daemon or in a thread specific for each connection.
+If it is executed in the same thread then @code{upgrade_handler} is
+a blocking call for our webserver and
+we should finish it as fast as possible (i. e. by creating a thread and
+passing the information there).
+If @code{MHD_USE_THREAD_PER_CONNECTION} was passed to
+@code{MHD_start_daemon()} then a separate thread is used and
+thus our @code{upgrade_handler} needs not to start a separate thread.
+
+An @code{upgrade_handler}, which is called with a separate thread
+per connection, could look like this:
+
+
+@verbatim
+static void
+upgrade_handler (void *cls,
+                 struct MHD_Connection *connection,
+                 void *req_cls,
+                 const char *extra_in,
+                 size_t extra_in_size,
+                 MHD_socket fd,
+                 struct MHD_UpgradeResponseHandle *urh)
+{
+  /* ... */
+  /* do something with the socket `fd` like `recv()` or `send()` */
+  /* ... */
+
+  /* close the socket when it is not needed anymore */
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+}
+@end verbatim
+@noindent
+
+
+This is all you need to know for upgrading connections
+with @emph{libmicrohttpd}.
+The next chapters focus on using the websocket protocol
+with @emph{libmicrohttpd_ws}.
+
+
+@heading Websocket handshake with libmicrohttpd_ws
+
+To request a websocket connection the client must send
+the following information with the HTTP request:
+
+@itemize @bullet
+@item
+A @code{GET} request must be sent.
+
+@item
+The version of the HTTP protocol must be 1.1 or higher.
+
+@item
+A @code{Host} header field must be sent
+
+@item
+A @code{Upgrade} header field containing the keyword "websocket"
+(case-insensitive).
+Please note that the client could pass multiple protocols separated by comma.
+
+@item
+A @code{Connection} header field that includes the token "Upgrade"
+(case-insensitive).
+Please note that the client could pass multiple tokens separated by comma.
+
+@item
+A @code{Sec-WebSocket-Key} header field with a base64-encoded value.
+The decoded the value is 16 bytes long
+and has been generated randomly by the client.
+
+@item
+A @code{Sec-WebSocket-Version} header field with the value "13".
+
+@end itemize
+
+
+Optionally the client can also send the following information:
+
+
+@itemize @bullet
+@item
+A @code{Origin} header field can be used to determine the source
+of the client (i. e. the website).
+
+@item
+A @code{Sec-WebSocket-Protocol} header field can contain a list
+of supported protocols by the client, which can be sent over the websocket.
+
+@item
+A @code{Sec-WebSocket-Extensions} header field which may contain extensions
+to the websocket protocol. The extensions must be registered by IANA.
+
+@end itemize
+
+
+A valid example request from the client could look like this:
+
+
+@verbatim
+GET /chat HTTP/1.1
+Host: server.example.com
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
+Sec-WebSocket-Version: 13
+@end verbatim
+@noindent
+
+
+To complete the handshake the server must respond with
+some specific response headers:
+
+@itemize @bullet
+@item
+The HTTP response code @code{101 Switching Protocols} must be answered.
+
+@item
+An @code{Upgrade} header field containing the value "websocket" must be sent.
+
+@item
+A @code{Connection} header field containing the value "Upgrade" must be sent.
+
+@item
+A @code{Sec-WebSocket-Accept} header field containing a value, which
+has been calculated from the @code{Sec-WebSocket-Key} request header field,
+must be sent.
+
+@end itemize
+
+
+Optionally the server may send following headers:
+
+
+@itemize @bullet
+@item
+A @code{Sec-WebSocket-Protocol} header field containing a protocol
+of the list specified in the corresponding request header field.
+
+@item
+A @code{Sec-WebSocket-Extension} header field containing all used extensions
+of the list specified in the corresponding request header field.
+
+@end itemize
+
+
+A valid websocket HTTP response could look like this:
+
+@verbatim
+HTTP/1.1 101 Switching Protocols
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
+@end verbatim
+@noindent
+
+
+To upgrade a connection to a websocket the @emph{libmicrohttpd_ws} provides
+some helper functions for the @code{access_handler} callback function:
+
+@itemize @bullet
+@item
+@code{MHD_websocket_check_http_version()} checks whether the HTTP version
+is 1.1 or above.
+
+@item
+@code{MHD_websocket_check_connection_header()} checks whether the value
+of the @code{Connection} request header field contains
+an "Upgrade" token (case-insensitive).
+
+@item
+@code{MHD_websocket_check_upgrade_header()} checks whether the value
+of the @code{Upgrade} request header field contains
+the "websocket" keyword (case-insensitive).
+
+@item
+@code{MHD_websocket_check_version_header()} checks whether the value
+of the @code{Sec-WebSocket-Version} request header field is "13".
+
+@item
+@code{MHD_websocket_create_accept_header()} takes the value from
+the @code{Sec-WebSocket-Key} request header and calculates the value
+for the @code{Sec-WebSocket-Accept} response header field.
+
+@end itemize
+
+
+The @code{access_handler} example of the previous chapter can now be
+extended with these helper functions to perform the websocket handshake:
+
+@verbatim
+static enum MHD_Result
+access_handler (void *cls,
+                struct MHD_Connection *connection,
+                const char *url,
+                const char *method,
+                const char *version,
+                const char *upload_data,
+                size_t *upload_data_size,
+                void **ptr)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  int ret;
+
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *ptr)
+  {
+    /* do never respond on first call */
+    *ptr = &aptr;
+    return MHD_YES;
+  }
+  *ptr = NULL;                  /* reset when done */
+
+  if (0 == strcmp (url, "/"))
+  {
+    /* Default page for visiting the server */
+    struct MHD_Response *response = MHD_create_response_from_buffer (
+                                      strlen (PAGE),
+                                      PAGE,
+                                      MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else if (0 == strcmp (url, "/chat"))
+  {
+    char is_valid = 1;
+    const char* value = NULL;
+    char sec_websocket_accept[29];
+
+    if (0 != MHD_websocket_check_http_version (version))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_CONNECTION);
+    if (0 != MHD_websocket_check_connection_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_UPGRADE);
+    if (0 != MHD_websocket_check_upgrade_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION);
+    if (0 != MHD_websocket_check_version_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY);
+    if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept))
+    {
+      is_valid = 0;
+    }
+
+    if (1 == is_valid)
+    {
+      /* upgrade the connection */
+      response = MHD_create_response_for_upgrade (&upgrade_handler,
+                                                  NULL);
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_CONNECTION,
+                               "Upgrade");
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_UPGRADE,
+                               "websocket");
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT,
+                               sec_websocket_accept);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_SWITCHING_PROTOCOLS,
+                                response);
+      MHD_destroy_response (response);
+    }
+    else
+    {
+      /* return error page */
+      struct MHD_Response*response = MHD_create_response_from_buffer (
+                                       strlen (PAGE_INVALID_WEBSOCKET_REQUEST),
+                                       PAGE_INVALID_WEBSOCKET_REQUEST,
+                                       MHD_RESPMEM_PERSISTENT);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_BAD_REQUEST,
+                                response);
+      MHD_destroy_response (response);
+    }
+  }
+  else
+  {
+    struct MHD_Response*response = MHD_create_response_from_buffer (
+                                     strlen (PAGE_NOT_FOUND),
+                                     PAGE_NOT_FOUND,
+                                     MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_NOT_FOUND,
+                              response);
+    MHD_destroy_response (response);
+  }
+
+  return ret;
+}
+@end verbatim
+@noindent
+
+Please note that we skipped the check of the Host header field here,
+because we don't know the host for this example.
+
+@heading Decoding/encoding the websocket protocol with libmicrohttpd_ws
+
+Once the websocket connection is established you can receive/send frame data
+with the low-level socket functions @code{recv()} and @code{send()}.
+The frame data which goes over the low-level socket is encoded according
+to the websocket protocol.
+To use received payload data, you need to decode the frame data first.
+To send payload data, you need to encode it into frame data first.
+
+@emph{libmicrohttpd_ws} provides several functions for encoding of
+payload data and decoding of frame data:
+
+@itemize @bullet
+@item
+@code{MHD_websocket_decode()} decodes received frame data.
+The payload data may be of any kind, depending upon what the client has sent.
+So this decode function is used for all kind of frames and returns
+the frame type along with the payload data.
+
+@item
+@code{MHD_websocket_encode_text()} encodes text.
+The text must be encoded with UTF-8.
+
+@item
+@code{MHD_websocket_encode_binary()} encodes binary data.
+
+@item
+@code{MHD_websocket_encode_ping()} encodes a ping request to
+check whether the websocket is still valid and to test latency.
+
+@item
+@code{MHD_websocket_encode_ping()} encodes a pong response to
+answer a received ping request.
+
+@item
+@code{MHD_websocket_encode_close()} encodes a close request.
+
+@item
+@code{MHD_websocket_free()} frees data returned by the encode/decode functions.
+
+@end itemize
+
+Since you could receive or send fragmented data (i. e. due to a too
+small buffer passed to @code{recv}) all of these encode/decode
+functions require a pointer to a @code{struct MHD_WebSocketStream} passed
+as argument.
+In this structure @emph{libmicrohttpd_ws} stores information
+about encoding/decoding of the particular websocket.
+For each websocket you need a unique @code{struct MHD_WebSocketStream}
+to encode/decode with this library.
+
+To create or destroy @code{struct MHD_WebSocketStream}
+we have additional functions:
+
+@itemize @bullet
+@item
+@code{MHD_websocket_stream_init()} allocates and initializes
+a new @code{struct MHD_WebSocketStream}.
+You can specify some options here to alter the behavior of the websocket stream.
+
+@item
+@code{MHD_websocket_stream_free()} frees a previously allocated
+@code{struct MHD_WebSocketStream}.
+
+@end itemize
+
+With these encode/decode functions we can improve our @code{upgrade_handler}
+callback function from an earlier example to a working websocket:
+
+
+@verbatim
+static void
+upgrade_handler (void *cls,
+                 struct MHD_Connection *connection,
+                 void *req_cls,
+                 const char *extra_in,
+                 size_t extra_in_size,
+                 MHD_socket fd,
+                 struct MHD_UpgradeResponseHandle *urh)
+{
+  /* make the socket blocking (operating-system-dependent code) */
+  make_blocking (fd);
+
+  /* create a websocket stream for this connection */
+  struct MHD_WebSocketStream* ws;
+  int result = MHD_websocket_stream_init (&ws,
+                                          0,
+                                          0);
+  if (0 != result)
+  {
+    /* Couldn't create the websocket stream.
+     * So we close the socket and leave
+     */
+    MHD_upgrade_action (urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+    return;
+  }
+
+  /* Let's wait for incoming data */
+  const size_t buf_len = 256;
+  char buf[buf_len];
+  ssize_t got;
+  while (MHD_WEBSOCKET_VALIDITY_VALID == MHD_websocket_stream_is_valid (ws))
+  {
+    got = recv (fd,
+                buf,
+                buf_len,
+                0);
+    if (0 >= got)
+    {
+      /* the TCP/IP socket has been closed */
+      break;
+    }
+
+    /* parse the entire received data */
+    size_t buf_offset = 0;
+    while (buf_offset < (size_t) got)
+    {
+      size_t new_offset = 0;
+      char *frame_data = NULL;
+      size_t frame_len  = 0;
+      int status = MHD_websocket_decode (ws,
+                                         buf + buf_offset,
+                                         ((size_t) got) - buf_offset,
+                                         &new_offset,
+                                         &frame_data,
+                                         &frame_len);
+      if (0 > status)
+      {
+        /* an error occurred and the connection must be closed */
+        if (NULL != frame_data)
+        {
+          MHD_websocket_free (ws, frame_data);
+        }
+        break;
+      }
+      else
+      {
+        buf_offset += new_offset;
+        if (0 < status)
+        {
+          /* the frame is complete */
+          switch (status)
+          {
+          case MHD_WEBSOCKET_STATUS_TEXT_FRAME:
+            /* The client has sent some text.
+             * We will display it and answer with a text frame.
+             */
+            if (NULL != frame_data)
+            {
+              printf ("Received message: %s\n", frame_data);
+              MHD_websocket_free (ws, frame_data);
+              frame_data = NULL;
+            }
+            result = MHD_websocket_encode_text (ws,
+                                                "Hello",
+                                                5,  /* length of "Hello" */
+                                                0,
+                                                &frame_data,
+                                                &frame_len,
+                                                NULL);
+            if (0 == result)
+            {
+              send_all (fd,
+                        frame_data,
+                        frame_len);
+            }
+            break;
+
+          case MHD_WEBSOCKET_STATUS_CLOSE_FRAME:
+            /* if we receive a close frame, we will respond with one */
+            MHD_websocket_free (ws,
+                                frame_data);
+            frame_data = NULL;
+
+            result = MHD_websocket_encode_close (ws,
+                                                 0,
+                                                 NULL,
+                                                 0,
+                                                 &frame_data,
+                                                 &frame_len);
+            if (0 == result)
+            {
+              send_all (fd,
+                        frame_data,
+                        frame_len);
+            }
+            break;
+
+          case MHD_WEBSOCKET_STATUS_PING_FRAME:
+            /* if we receive a ping frame, we will respond */
+            /* with the corresponding pong frame */
+            {
+              char *pong = NULL;
+              size_t pong_len = 0;
+              result = MHD_websocket_encode_pong (ws,
+                                                  frame_data,
+                                                  frame_len,
+                                                  &pong,
+                                                  &pong_len);
+              if (0 == result)
+              {
+                send_all (fd,
+                          pong,
+                          pong_len);
+              }
+              MHD_websocket_free (ws,
+                                  pong);
+            }
+            break;
+
+          default:
+            /* Other frame types are ignored
+             * in this minimal example.
+             * This is valid, because they become
+             * automatically skipped if we receive them unexpectedly
+             */
+            break;
+          }
+        }
+        if (NULL != frame_data)
+        {
+          MHD_websocket_free (ws, frame_data);
+        }
+      }
+    }
+  }
+
+  /* free the websocket stream */
+  MHD_websocket_stream_free (ws);
+
+  /* close the socket when it is not needed anymore */
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+}
+
+/* This helper function is used for the case that
+ * we need to resend some data
+ */
+static void
+send_all (MHD_socket fd,
+          const char *buf,
+          size_t len)
+{
+  ssize_t ret;
+  size_t off;
+
+  for (off = 0; off < len; off += ret)
+  {
+    ret = send (fd,
+                &buf[off],
+                (int) (len - off),
+                0);
+    if (0 > ret)
+    {
+      if (EAGAIN == errno)
+      {
+        ret = 0;
+        continue;
+      }
+      break;
+    }
+    if (0 == ret)
+      break;
+  }
+}
+
+/* This helper function contains operating-system-dependent code and
+ * is used to make a socket blocking.
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    return;
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      abort ();
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  ioctlsocket (fd, FIONBIO, &flags);
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+@end verbatim
+@noindent
+
+
+Please note that the websocket in this example is only half-duplex.
+It waits until the blocking @code{recv()} call returns and
+only does then something.
+In this example all frame types are decoded by @emph{libmicrohttpd_ws},
+but we only do something when a text, ping or close frame is received.
+Binary and pong frames are ignored in our code.
+This is legit, because the server is only required to implement at
+least support for ping frame or close frame (the other frame types
+could be skipped in theory, because they don't require an answer).
+The pong frame doesn't require an answer and whether text frames or
+binary frames get an answer simply belongs to your server application.
+So this is a valid minimal example.
+
+Until this point you've learned everything you need to basically
+use websockets with @emph{libmicrohttpd} and @emph{libmicrohttpd_ws}.
+These libraries offer much more functions for some specific cases.
+
+
+The further chapters of this tutorial focus on some specific problems
+and the client site programming.
+
+
+@heading Using full-duplex websockets
+
+To use full-duplex websockets you can simply create two threads
+per websocket connection.
+One of these threads is used for receiving data with
+a blocking @code{recv()} call and the other thread is triggered
+by the application internal codes and sends the data.
+
+A full-duplex websocket example is implemented in the example file
+@code{websocket_chatserver_example.c}.
+
+@heading Error handling
+
+The most functions of @emph{libmicrohttpd_ws} return a value
+of @code{enum MHD_WEBSOCKET_STATUS}.
+The values of this enumeration can be converted into an integer
+and have an easy interpretation:
+
+@itemize @bullet
+@item
+If the value is less than zero an error occurred and the call has failed.
+Check the enumeration values for more specific information.
+
+@item
+If the value is equal to zero, the call succeeded.
+
+@item
+If the value is greater than zero, the call succeeded and the value
+specifies the decoded frame type.
+Currently positive values are only returned by @code{MHD_websocket_decode()}
+(of the functions with this return enumeration type).
+
+@end itemize
+
+A websocket stream can also get broken when invalid frame data is received.
+Also the other site could send a close frame which puts the stream into
+a state where it may not be used for regular communication.
+Whether a stream has become broken, can be checked with
+@code{MHD_websocket_stream_is_valid()}.
+
+
+@heading Fragmentation
+
+In addition to the regular TCP/IP fragmentation the websocket protocol also
+supports fragmentation.
+Fragmentation could be used for continuous payload data such as video data
+from a webcam.
+Whether or not you want to receive fragmentation is specified upon
+initialization of the websocket stream.
+If you pass @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS} in the flags parameter
+of @code{MHD_websocket_stream_init()} then you can receive fragments.
+If you don't pass this flag (in the most cases you just pass zero as flags)
+then you don't want to handle fragments on your own.
+@emph{libmicrohttpd_ws} removes then the fragmentation for you
+in the background.
+You only get the completely assembled frames.
+
+Upon encoding you specify whether or not you want to create a fragmented frame
+by passing a flag to the corresponding encode function.
+Only @code{MHD_websocket_encode_text()} and @code{MHD_websocket_encode_binary()}
+can be used for fragmentation, because the other frame types may
+not be fragmented.
+Encoding fragmented frames is independent of
+the @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS} flag upon initialization.
+
+@heading Quick guide to websockets in JavaScript
+
+Websockets are supported in all modern web browsers.
+You initialize a websocket connection by creating an instance of
+the @code{WebSocket} class provided by the web browser.
+
+There are some simple rules for using websockets in the browser:
+
+@itemize @bullet
+@item
+When you initialize the instance of the websocket class you must pass an URL.
+The URL must either start with @code{ws://}
+(for not encrypted websocket protocol) or @code{wss://}
+(for TLS-encrypted websocket protocol).
+
+@strong{IMPORTANT:} If your website is accessed via @code{https://}
+then you are in a security context, which means that you are only allowed to
+access other secure protocols.
+So you can only use @code{wss://} for websocket connections then.
+If you try to @code{ws://} instead then your websocket connection will
+automatically fail.
+
+@item
+The WebSocket class uses events to handle the receiving of data.
+JavaScript is per definition a single-threaded language so
+the receiving events will never overlap.
+Sending is done directly by calling a method of the instance of
+the WebSocket class.
+
+@end itemize
+
+
+Here is a short example for receiving/sending data to the same host
+as the website is running on:
+
+@verbatim
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8">
+<title>Websocket Demo</title>
+<script>
+
+let url = 'ws' + (window.location.protocol === 'https:' ? 's' : '') + '://' +
+          window.location.host + '/chat';
+let socket = null;
+
+window.onload = function(event) {
+  socket = new WebSocket(url);
+  socket.onopen = function(event) {
+    document.write('The websocket connection has been established.<br>');
+
+    // Send some text
+    socket.send('Hello from JavaScript!');
+  }
+
+  socket.onclose = function(event) {
+    document.write('The websocket connection has been closed.<br>');
+  }
+
+  socket.onerror = function(event) {
+    document.write('An error occurred during the websocket communication.<br>');
+  }
+
+  socket.onmessage = function(event) {
+    document.write('Websocket message received: ' + event.data + '<br>');
+  }
+}
+
+</script>
+</head>
+<body>
+</body>
+</html>
+
+@end verbatim
+@noindent
diff --git a/doc/doxygen/Makefile.am b/doc/doxygen/Makefile.am
index 6f132dd..52da05b 100644
--- a/doc/doxygen/Makefile.am
+++ b/doc/doxygen/Makefile.am
@@ -1,7 +1,7 @@
 # This Makefile.am is in the public domain
 all:
 	@echo -e \
-"Generate documentation:\n" \
+"Generate doxygen additional documentation:\n" \
 "\tmake full - full documentation with dependency graphs (slow)\n" \
 "\tmake fast - fast mode without dependency graphs"
 
diff --git a/doc/doxygen/Makefile.in b/doc/doxygen/Makefile.in
deleted file mode 100644
index aaeb894..0000000
--- a/doc/doxygen/Makefile.in
+++ /dev/null
@@ -1,495 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-subdir = doc/doxygen
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-EXTRA_DIST = libmicrohttpd.doxy
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/doxygen/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu doc/doxygen/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-tags TAGS:
-
-ctags CTAGS:
-
-cscope cscopelist:
-
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-am
-all-am: Makefile
-installdirs:
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-	cscopelist-am ctags-am distclean distclean-generic \
-	distclean-libtool distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	maintainer-clean maintainer-clean-generic mostlyclean \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags-am uninstall uninstall-am
-
-
-# This Makefile.am is in the public domain
-all:
-	@echo -e \
-"Generate documentation:\n" \
-"\tmake full - full documentation with dependency graphs (slow)\n" \
-"\tmake fast - fast mode without dependency graphs"
-
-full: libmicrohttpd.doxy
-	doxygen $<
-
-fast: libmicrohttpd.doxy
-	sed 's/\(HAVE_DOT.*=\).*/\1 NO/' $< | doxygen -
-
-clean:
-	rm -rf html
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/doc/doxygen/libmicrohttpd.doxy b/doc/doxygen/libmicrohttpd.doxy
deleted file mode 100644
index 3830161..0000000
--- a/doc/doxygen/libmicrohttpd.doxy
+++ /dev/null
@@ -1,248 +0,0 @@
-# Doxyfile 1.5.5
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-DOXYFILE_ENCODING      = UTF-8
-PROJECT_NAME           = "GNU libmicrohttpd"
-PROJECT_NUMBER         = 0.9.29
-OUTPUT_DIRECTORY       = .
-CREATE_SUBDIRS         = YES
-OUTPUT_LANGUAGE        = English
-BRIEF_MEMBER_DESC      = YES
-REPEAT_BRIEF           = YES
-ABBREVIATE_BRIEF       = "The $name class" \
-                         "The $name widget" \
-                         "The $name file" \
-                         is \
-                         provides \
-                         specifies \
-                         contains \
-                         represents \
-                         a \
-                         an \
-                         the
-ALWAYS_DETAILED_SEC    = NO
-INLINE_INHERITED_MEMB  = NO
-FULL_PATH_NAMES        = YES
-STRIP_FROM_PATH        = ../..
-STRIP_FROM_INC_PATH    = ../../src/include \
-		         src/include
-SHORT_NAMES            = NO
-JAVADOC_AUTOBRIEF      = NO
-QT_AUTOBRIEF           = NO
-MULTILINE_CPP_IS_BRIEF = NO
-INHERIT_DOCS           = NO
-SEPARATE_MEMBER_PAGES  = NO
-TAB_SIZE               = 8
-ALIASES                = 
-OPTIMIZE_OUTPUT_FOR_C  = YES
-OPTIMIZE_OUTPUT_JAVA   = NO
-OPTIMIZE_FOR_FORTRAN   = NO
-OPTIMIZE_OUTPUT_VHDL   = NO
-BUILTIN_STL_SUPPORT    = NO
-CPP_CLI_SUPPORT        = NO
-SIP_SUPPORT            = NO
-DISTRIBUTE_GROUP_DOC   = NO
-SUBGROUPING            = YES
-TYPEDEF_HIDES_STRUCT   = NO
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-EXTRACT_ALL            = YES
-EXTRACT_PRIVATE        = NO
-EXTRACT_STATIC         = YES
-EXTRACT_LOCAL_CLASSES  = NO
-EXTRACT_LOCAL_METHODS  = YES
-EXTRACT_ANON_NSPACES   = NO
-HIDE_UNDOC_MEMBERS     = NO
-HIDE_UNDOC_CLASSES     = NO
-HIDE_FRIEND_COMPOUNDS  = NO
-HIDE_IN_BODY_DOCS      = NO
-INTERNAL_DOCS          = NO
-CASE_SENSE_NAMES       = YES
-HIDE_SCOPE_NAMES       = NO
-SHOW_INCLUDE_FILES     = YES
-INLINE_INFO            = YES
-SORT_MEMBER_DOCS       = YES
-SORT_BRIEF_DOCS        = NO
-SORT_GROUP_NAMES       = NO
-SORT_BY_SCOPE_NAME     = NO
-GENERATE_TODOLIST      = NO
-GENERATE_TESTLIST      = NO
-GENERATE_BUGLIST       = NO
-GENERATE_DEPRECATEDLIST= NO
-ENABLED_SECTIONS       = 
-MAX_INITIALIZER_LINES  = 30
-SHOW_USED_FILES        = YES
-FILE_VERSION_FILTER    = 
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-QUIET                  = NO
-WARNINGS               = YES
-WARN_IF_UNDOCUMENTED   = YES
-WARN_IF_DOC_ERROR      = YES
-WARN_NO_PARAMDOC       = NO
-WARN_FORMAT            = "$file:$line: $text"
-WARN_LOGFILE           = 
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-INPUT                  = ../..
-INPUT_ENCODING         = UTF-8
-FILE_PATTERNS          = *.c \
-                         *.h
-RECURSIVE              = YES
-EXCLUDE                = 
-EXCLUDE_SYMLINKS       = NO
-EXCLUDE_PATTERNS       = */test_* */.svn/* */perf_* */tls_test_*  */examples/* */testcurl/* */testspdy/* */testzzuf/* */platform/* */symbian/* MHD_config.h
-EXCLUDE_SYMBOLS        = MHD_DLOG
-EXAMPLE_PATH           = 
-EXAMPLE_PATTERNS       = *
-EXAMPLE_RECURSIVE      = NO
-IMAGE_PATH             = 
-INPUT_FILTER           = 
-FILTER_PATTERNS        = 
-FILTER_SOURCE_FILES    = NO
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-SOURCE_BROWSER         = YES
-INLINE_SOURCES         = NO
-STRIP_CODE_COMMENTS    = YES
-REFERENCED_BY_RELATION = YES
-REFERENCES_RELATION    = YES
-REFERENCES_LINK_SOURCE = YES
-USE_HTAGS              = NO
-VERBATIM_HEADERS       = NO
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-ALPHABETICAL_INDEX     = YES
-COLS_IN_ALPHA_INDEX    = 5
-IGNORE_PREFIX          = 
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-GENERATE_HTML          = YES
-HTML_OUTPUT            = html
-HTML_FILE_EXTENSION    = .html
-HTML_HEADER            = 
-HTML_FOOTER            = 
-HTML_STYLESHEET        = 
-GENERATE_HTMLHELP      = NO
-GENERATE_DOCSET        = NO
-DOCSET_FEEDNAME        = "Doxygen generated docs"
-DOCSET_BUNDLE_ID       = org.doxygen.Project
-HTML_DYNAMIC_SECTIONS  = NO
-CHM_FILE               = 
-HHC_LOCATION           = 
-GENERATE_CHI           = NO
-BINARY_TOC             = NO
-TOC_EXPAND             = NO
-DISABLE_INDEX          = NO
-ENUM_VALUES_PER_LINE   = 4
-GENERATE_TREEVIEW      = YES
-TREEVIEW_WIDTH         = 250
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-GENERATE_LATEX         = NO
-LATEX_OUTPUT           = latex
-LATEX_CMD_NAME         = latex
-MAKEINDEX_CMD_NAME     = makeindex
-COMPACT_LATEX          = NO
-PAPER_TYPE             = a4wide
-EXTRA_PACKAGES         = 
-LATEX_HEADER           = 
-PDF_HYPERLINKS         = YES
-USE_PDFLATEX           = YES
-LATEX_BATCHMODE        = NO
-LATEX_HIDE_INDICES     = NO
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-GENERATE_RTF           = NO
-RTF_OUTPUT             = rtf
-COMPACT_RTF            = NO
-RTF_HYPERLINKS         = NO
-RTF_STYLESHEET_FILE    = 
-RTF_EXTENSIONS_FILE    = 
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-GENERATE_MAN           = NO
-MAN_OUTPUT             = man
-MAN_EXTENSION          = .3
-MAN_LINKS              = NO
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-GENERATE_XML           = NO
-XML_OUTPUT             = xml
-XML_SCHEMA             = 
-XML_DTD                = 
-XML_PROGRAMLISTING     = YES
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-GENERATE_AUTOGEN_DEF   = NO
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-GENERATE_PERLMOD       = NO
-PERLMOD_LATEX          = NO
-PERLMOD_PRETTY         = YES
-PERLMOD_MAKEVAR_PREFIX = 
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor   
-#---------------------------------------------------------------------------
-ENABLE_PREPROCESSING   = YES
-MACRO_EXPANSION        = NO
-EXPAND_ONLY_PREDEF     = NO
-SEARCH_INCLUDES        = YES
-INCLUDE_PATH           = 
-INCLUDE_FILE_PATTERNS  = 
-PREDEFINED             = 
-EXPAND_AS_DEFINED      = 
-SKIP_FUNCTION_MACROS   = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references   
-#---------------------------------------------------------------------------
-TAGFILES               = 
-GENERATE_TAGFILE       = 
-ALLEXTERNALS           = NO
-EXTERNAL_GROUPS        = YES
-PERL_PATH              = /usr/bin/perl
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool   
-#---------------------------------------------------------------------------
-CLASS_DIAGRAMS         = YES
-MSCGEN_PATH            = 
-HIDE_UNDOC_RELATIONS   = YES
-HAVE_DOT               = YES
-CLASS_GRAPH            = NO
-COLLABORATION_GRAPH    = NO
-GROUP_GRAPHS           = NO
-UML_LOOK               = NO
-TEMPLATE_RELATIONS     = NO
-INCLUDE_GRAPH          = YES
-INCLUDED_BY_GRAPH      = YES
-CALL_GRAPH             = YES
-CALLER_GRAPH           = YES
-GRAPHICAL_HIERARCHY    = NO
-DIRECTORY_GRAPH        = YES
-DOT_IMAGE_FORMAT       = png
-DOT_PATH               = 
-DOTFILE_DIRS           = 
-DOT_GRAPH_MAX_NODES    = 25
-MAX_DOT_GRAPH_DEPTH    = 2
-DOT_TRANSPARENT        = YES
-DOT_MULTI_TARGETS      = NO
-GENERATE_LEGEND        = YES
-DOT_CLEANUP            = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to the search engine   
-#---------------------------------------------------------------------------
-SEARCHENGINE           = YES
diff --git a/doc/doxygen/libmicrohttpd.doxy.in b/doc/doxygen/libmicrohttpd.doxy.in
new file mode 100644
index 0000000..ccad07c
--- /dev/null
+++ b/doc/doxygen/libmicrohttpd.doxy.in
@@ -0,0 +1,2464 @@
+# Doxyfile 1.8.13
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single 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.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = "GNU libmicrohttpd"
+
+# 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         = @PACKAGE_VERSION@
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
+# in the documentation. The maximum height of the logo should not exceed 55
+# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
+# the logo to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. 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       = .
+
+# 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 causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS         = YES
+
+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
+# characters to appear in the names of generated files. If set to NO, non-ASCII
+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
+# U+3044.
+# The default value is: NO.
+
+ALLOW_UNICODE_NAMES    = 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.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES, 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.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES, 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.
+# The default value is: YES.
+
+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 and 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.
+# The default value is: NO.
+
+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.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES, 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
+# The default value is: YES.
+
+FULL_PATH_NAMES        = YES
+
+# 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.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+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 list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    = ../../src/include \
+                         src/include
+
+# 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.
+# The default value is: NO.
+
+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-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF      = NO
+
+# 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 Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+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 behavior. 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 behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS           = NO
+
+# 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.
+# The default value is: NO.
+
+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.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 8
+
+# This tag can be used to specify a number of aliases that act 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                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# 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.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C  = YES
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+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.
+# The default value is: NO.
+
+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 (fixed format Fortran:
+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
+# Fortran. In the later case the parser tries to guess whether the code is fixed
+# or free formatted code, this is the default for Fortran type files), VHDL. 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: For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
+# to that level are automatically included in the table of contents, even if
+# they do not have an id attribute.
+# Note: This feature currently applies only to Markdown headings.
+# Minimum value: 0, maximum value: 99, default value: 0.
+# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
+
+TOC_INCLUDE_HEADINGS   = 0
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by putting a % sign in front of the word or
+# globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# 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);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) 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.
+# The default value is: NO.
+
+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 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.
+# The default value is: YES.
+
+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.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# If one adds a struct or class to a group and this option is enabled, then also
+# any nested class or struct is added to the same group. By default this option
+# is disabled and one has to add nested compounds explicitly via \ingroup.
+# The default value is: NO.
+
+GROUP_NESTED_COMPOUNDS = NO
+
+# Set the SUBGROUPING tag to YES 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.
+# The default value is: YES.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag 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.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_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 respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC         = YES
+
+# 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. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES  = NO
+
+# This flag is only useful for Objective-C code. If 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, only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS  = YES
+
+# 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.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO 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.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# 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, these classes will be included in the various overviews. This option
+# has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO, these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+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, these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+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 then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+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.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES       = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES, the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
+# append additional text to a page's title, such as Class Reference. If set to
+# YES the compound reference will be hidden.
+# The default value is: NO.
+
+HIDE_COMPOUND_REFERENCE= NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES 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.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO, the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
+
+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 constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: 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 group names will
+# appear in their defined order.
+# The default value is: NO.
+
+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 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.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = 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.
+# The default value is: YES.
+
+GENERATE_TODOLIST      = NO
+
+# 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.
+# The default value is: YES.
+
+GENERATE_TESTLIST      = NO
+
+# 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.
+# The default value is: YES.
+
+GENERATE_BUGLIST       = NO
+
+# 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.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= NO
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have 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 value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+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.
+# The default value is: YES.
+
+SHOW_USED_FILES        = YES
+
+# 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 value 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 value 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. For an example see the documentation.
+
+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. To 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.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. See also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS               = YES
+
+# If the WARN_IF_UNDOCUMENTED tag 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.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If the WARN_IF_DOC_ERROR tag 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.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO, doxygen will only warn about wrong or incomplete
+# parameter documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC       = NO
+
+# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
+# a warning is encountered.
+# The default value is: NO.
+
+WARN_AS_ERROR          = 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)
+# The default value is: $file:$line: $text.
+
+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 standard
+# error (stderr).
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is 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. See also FILE_PATTERNS and EXTENSION_MAPPING
+# Note: If this tag is empty the current directory is searched.
+
+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. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+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 patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# read by doxygen.
+#
+# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
+# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
+# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
+# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,
+# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf.
+
+FILE_PATTERNS          = *.c \
+                         *.h
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE              = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# 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.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+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       = */test_* \
+                         */.svn/* \
+                         */perf_* \
+                         */tls_test_* \
+                         */examples/* \
+                         */testcurl/* \
+                         */testzzuf/* \
+                         */platform/* \
+                         */symbian/* \
+                         MHD_config.h \
+                         microhttpd2.h
+
+
+# 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
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        = MHD_DLOG
+
+# 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.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be 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.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# properly processed by doxygen.
+
+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 information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+#
+# Note that for custom extensions or not directly supported extensions you also
+# need to set EXTENSION_MAPPING for the extension otherwise the files are not
+# properly processed by doxygen.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# 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 that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER         = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+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.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = YES
+
+# 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.
+# The default value is: NO.
+
+REFERENCES_RELATION    = YES
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES 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.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = 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.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set the YES 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.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS       = NO
+
+# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
+# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
+# cost of reduced performance. This can be particularly helpful with template
+# rich C++ code for which doxygen's built-in parser lacks the necessary type
+# information.
+# Note: The availability of this option depends on whether or not doxygen was
+# generated with the -Duse-libclang=ON option for CMake.
+# The default value is: NO.
+
+CLANG_ASSISTED_PARSING = NO
+
+# If clang assisted parsing is enabled you can provide the compiler with command
+# line options that you would normally use when invoking the compiler. Note that
+# the include paths will already be set by doxygen for the files and directories
+# specified with INPUT and INCLUDE_PATH.
+# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
+
+CLANG_OPTIONS          =
+
+#---------------------------------------------------------------------------
+# 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.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX     = YES
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+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 a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML          = YES
+
+# 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.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+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).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+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 left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# cascading style sheets that are included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefore more robust against future updates.
+# Doxygen will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list). For an example see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the style sheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to YES can help to show when doxygen was last run and thus if the
+# documentation is up to date.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = NO
+
+# 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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# 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 (see: http://developer.apple.com/tools/xcode/), 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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET        = NO
+
+# This tag determines the name of the docset 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.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# 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.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP      = NO
+
+# 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.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               =
+
+# 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.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           =
+
+# 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).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI           = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     =
+
+# 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. Furthermore it
+# enables the Previous and Next buttons.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+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.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# 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.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX          = NO
+
+# 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. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = YES
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# 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.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH         = 250
+
+# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. 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.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled 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), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
+# setting. When disabled, doxygen will generate a PHP script for searching and
+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
+# and searching needs to be provided by external tools. See the section
+# "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer (doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX         = NO
+
+# 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.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+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 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4wide
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. The package can be specified just
+# by its name or with the correct syntax as to be used with the LaTeX
+# \usepackage command. To get the times font for instance you can specify :
+# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
+# To use the option intlimits with the amsmath package you can specify:
+# EXTRA_PACKAGES=[intlimits]{amsmath}
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+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. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
+# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
+# string, for the replacement values of the other commands the user is referred
+# to HTML_HEADER.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer. See
+# LATEX_HEADER for more information on how to generate a default footer and what
+# special commands can be used inside the footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# LaTeX style sheets that are included after the standard style sheets created
+# by doxygen. Using this option one can overrule certain style aspects. Doxygen
+# will copy the style sheet files to the output directory.
+# Note: The order of the extra style sheet files is of importance (e.g. the last
+# style sheet in the list overrules the setting of the previous ones in the
+# list).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_STYLESHEET =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). 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.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES, to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE        = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES     = NO
+
+# If the LATEX_SOURCE_CODE tag 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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_TIMESTAMP        = 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 too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+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.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+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 some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+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.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    =
+
+# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
+# with syntax highlighting in the RTF output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_SOURCE_CODE        = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN           = NO
+
+# 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. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION          = .3
+
+# The MAN_SUBDIR tag determines the name of the directory created within
+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
+# MAN_EXTENSION with the initial . removed.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_SUBDIR             =
+
+# 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 value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+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.
+# The default value is: NO.
+
+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.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT             = xml
+
+# 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.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
+# program listings (including syntax highlighting and cross-referencing
+# information) to the DOCBOOK output. Note that enabling this will significantly
+# increase the size of the DOCBOOK output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_PROGRAMLISTING = NO
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
+# AutoGen Definitions (see http://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.
+# The default value is: NO.
+
+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.
+# The default value is: NO.
+
+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.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+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.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+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.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+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, only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set 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.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES, the include files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+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.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+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.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+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 e.g.
+# 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.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             =
+
+# 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 that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to 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.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. 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. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: 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. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
+# the class index. If set to NO, only the inherited external classes will be
+# listed.
+# The default value is: NO.
+
+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.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+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            =
+
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_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.
+# The default value is: YES.
+
+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 (see:
+# http://www.graphviz.org/), 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 value is: YES.
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font in the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You 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.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH tag is 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 CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = NO
+
+# If the COLLABORATION_GRAPH tag is 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.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = NO
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = NO
+
+# 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.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES 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.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH          = YES
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES 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.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH tag is 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. Disabling a call graph can be
+# accomplished by means of the command \hidecallgraph.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = YES
+
+# If the CALLER_GRAPH tag is 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. Disabling a caller graph can be
+# accomplished by means of the command \hidecallergraph.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = YES
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY    = NO
+
+# If the DIRECTORY_GRAPH tag is 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.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. For an explanation of the image formats see the section
+# output formats in the documentation of the dot tool (Graphviz (see:
+# http://www.graphviz.org/)).
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd,
+# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo,
+# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo,
+# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
+# png:gdiplus:gdiplus.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag 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.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+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).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
+# path where java can find the plantuml.jar file. If left blank, it is assumed
+# PlantUML is not used or called during a preprocessing step. Doxygen will
+# generate a warning when it encounters a \startuml command in this case and
+# will not generate output for the diagram.
+
+PLANTUML_JAR_PATH      =
+
+# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
+# configuration file for plantuml.
+
+PLANTUML_CFG_FILE      =
+
+# When using plantuml, the specified paths are searched for files specified by
+# the !include statement in a plantuml block.
+
+PLANTUML_INCLUDE_PATH  =
+
+# 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.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 25
+
+# 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.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH    = 2
+
+# 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).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT        = YES
+
+# Set the DOT_MULTI_TARGETS tag to YES to 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.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP            = YES
diff --git a/doc/ecos.texi b/doc/ecos.texi
index 00fad74..395c419 100644
--- a/doc/ecos.texi
+++ b/doc/ecos.texi
@@ -1,405 +1,26 @@
-@cindex GPL, GNU General Public License
 @cindex eCos, GNU General Public License with eCos Extension
-@center Version 2, June 1991
 
-@display
-Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
-59 Temple Place -- Suite 330, Boston, MA 02111-1307, USA
+GNU libmicrohttpd 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 2 or (at your option) any later version.
 
-Everyone is permitted to copy and distribute verbatim copies
-of this license document, but changing it is not allowed.
-@end display
+GNU libmicrohttpd 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
+GNU libmicrohttpd; if not, write to the Free Software Foundation, Inc., 51
+Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
+As a special exception, if other files instantiate templates or use macros or
+inline functions from this file, or you compile this file and link it with
+other works to produce a work based on this file, this file does not by itself
+cause the resulting work to be covered by the GNU General Public
+License. However the source code for this file must still be made available in
+accordance with section (3) of the GNU General Public License v2.
 
-
-@subheading Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software---to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-@iftex
-@subheading TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-@end iftex
-@ifinfo
-@center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-@end ifinfo
-
-@enumerate
-@item
-This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The ``Program'', below,
-refers to any such program or work, and a ``work based on the Program''
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term ``modification''.)  Each licensee is addressed as ``you''.
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-@item
-You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-@item
-You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-@enumerate a
-@item
-You must cause the modified files to carry prominent notices
-stating that you changed the files and the date of any change.
-
-@item
-You must cause any work that you distribute or publish, that in
-whole or in part contains or is derived from the Program or any
-part thereof, to be licensed as a whole at no charge to all third
-parties under the terms of this License.
-
-@item
-If the modified program normally reads commands interactively
-when run, you must cause it, when started running for such
-interactive use in the most ordinary way, to print or display an
-announcement including an appropriate copyright notice and a
-notice that there is no warranty (or else, saying that you provide
-a warranty) and that users may redistribute the program under
-these conditions, and telling the user how to view a copy of this
-License.  (Exception: if the Program itself is interactive but
-does not normally print such an announcement, your work based on
-the Program is not required to print an announcement.)
-@end enumerate
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-@item
-You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-@enumerate a
-@item
-Accompany it with the complete corresponding machine-readable
-source code, which must be distributed under the terms of Sections
-1 and 2 above on a medium customarily used for software interchange; or,
-
-@item
-Accompany it with a written offer, valid for at least three
-years, to give any third party, for a charge no more than your
-cost of physically performing source distribution, a complete
-machine-readable copy of the corresponding source code, to be
-distributed under the terms of Sections 1 and 2 above on a medium
-customarily used for software interchange; or,
-
-@item
-Accompany it with the information you received as to the offer
-to distribute corresponding source code.  (This alternative is
-allowed only for noncommercial distribution and only if you
-received the program in object code or executable form with such
-an offer, in accord with Subsection b above.)
-@end enumerate
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-@item
-You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-@item
-You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-@item
-Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-@item
-If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-@item
-If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-@item
-The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and ``any
-later version'', you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-@item
-If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-@center @b{NO WARRANTY}
-
-@item
-BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-@item
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-@center @b{ECOS EXTENSION}
-
-
-@item
-As a special exception, if other files instantiate templates or use
-macros or inline functions from this file, or you compile this file
-and link it with other works to produce a work based on this file,
-this file does not by itself cause the resulting work to be covered by
-the GNU General Public License. However the source code for this file
-must still be made available in accordance with section (3) of the GNU
-General Public License v2.
-
-This exception does not invalidate any other reasons why a work based
-on this file might be covered by the GNU General Public License.
-
-@end enumerate
-
-
-@subheading END OF TERMS AND CONDITIONS
-
-@page
-@unnumberedsec How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the ``copyright'' line and a pointer to where the full notice is found.
-
-@smallexample
-@var{one line to give the program's name and an idea of what it does.}
-Copyright (C) 19@var{yy}  @var{name of author}
-
-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 2
-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, write to the Free Software Foundation, Inc.,
-59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-@end smallexample
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-@smallexample
-Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
-Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
-type `show w'.  This is free software, and you are welcome
-to redistribute it under certain conditions; type `show c' 
-for details.
-@end smallexample
-
-The hypothetical commands @samp{show w} and @samp{show c} should show
-the appropriate parts of the General Public License.  Of course, the
-commands you use may be called something other than @samp{show w} and
-@samp{show c}; they could even be mouse-clicks or menu items---whatever
-suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a ``copyright disclaimer'' for the program, if
-necessary.  Here is a sample; alter the names:
-
-@smallexample
-@group
-Yoyodyne, Inc., hereby disclaims all copyright
-interest in the program `Gnomovision'
-(which makes passes at compilers) written 
-by James Hacker.
+This exception does not invalidate any other reasons why a work based on this
+file might be covered by the GNU General Public License.
 
-@var{signature of Ty Coon}, 1 April 1989
-Ty Coon, President of Vice
-@end group
-@end smallexample
 
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff --git a/doc/examples/.gitignore b/doc/examples/.gitignore
new file mode 100644
index 0000000..bffda70
--- /dev/null
+++ b/doc/examples/.gitignore
@@ -0,0 +1,12 @@
+/tlsauthentication
+/simplepost
+/sessions
+/responseheaders
+/logging
+/largepost
+/hellobrowser
+/basicauthentication
+*.exe
+*.o
+*.lo
+*.la
diff --git a/doc/examples/Makefile.am b/doc/examples/Makefile.am
index 7bb02da..67302b2 100644
--- a/doc/examples/Makefile.am
+++ b/doc/examples/Makefile.am
@@ -2,20 +2,33 @@
 SUBDIRS  = .
 
 AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include
+  -I$(top_srcdir)/src/include \
+  $(CPPFLAGS_ac)
 
-AM_CFLAGS = @LIBGCRYPT_CFLAGS@
+AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@
+
+AM_LDFLAGS = $(LDFLAGS_ac)
+
+AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac)
 
 if USE_COVERAGE
   AM_CFLAGS += --coverage
 endif
 
+$(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile
+	@echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \
+	$(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la
+
 # example programs
 noinst_PROGRAMS = \
-  basicauthentication \
   hellobrowser \
   logging \
-  responseheaders 
+  responseheaders
+  
+if ENABLE_BAUTH
+noinst_PROGRAMS += \
+  basicauthentication
+endif
 
 if ENABLE_HTTPS
 noinst_PROGRAMS += \
@@ -29,6 +42,10 @@
 AM_CPPFLAGS += -DWINDOWS
 endif
 
+if HAVE_EXPERIMENTAL
+noinst_PROGRAMS += websocket
+endif
+
 basicauthentication_SOURCES = \
  basicauthentication.c 
 basicauthentication_LDADD = \
@@ -69,3 +86,8 @@
 largepost_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la 
 
+websocket_SOURCES = \
+ websocket.c
+websocket_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la \
+ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la
diff --git a/doc/examples/Makefile.in b/doc/examples/Makefile.in
deleted file mode 100644
index a39cd32..0000000
--- a/doc/examples/Makefile.in
+++ /dev/null
@@ -1,880 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@USE_COVERAGE_TRUE@am__append_1 = --coverage
-noinst_PROGRAMS = basicauthentication$(EXEEXT) hellobrowser$(EXEEXT) \
-	logging$(EXEEXT) responseheaders$(EXEEXT) $(am__EXEEXT_1) \
-	$(am__EXEEXT_2)
-@ENABLE_HTTPS_TRUE@am__append_2 = \
-@ENABLE_HTTPS_TRUE@  tlsauthentication
-
-@HAVE_POSTPROCESSOR_TRUE@am__append_3 = simplepost largepost sessions 
-@HAVE_W32_TRUE@am__append_4 = -DWINDOWS
-subdir = doc/examples
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-@ENABLE_HTTPS_TRUE@am__EXEEXT_1 = tlsauthentication$(EXEEXT)
-@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_2 = simplepost$(EXEEXT) \
-@HAVE_POSTPROCESSOR_TRUE@	largepost$(EXEEXT) sessions$(EXEEXT)
-PROGRAMS = $(noinst_PROGRAMS)
-am_basicauthentication_OBJECTS = basicauthentication.$(OBJEXT)
-basicauthentication_OBJECTS = $(am_basicauthentication_OBJECTS)
-basicauthentication_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-am_hellobrowser_OBJECTS = hellobrowser.$(OBJEXT)
-hellobrowser_OBJECTS = $(am_hellobrowser_OBJECTS)
-hellobrowser_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_largepost_OBJECTS = largepost.$(OBJEXT)
-largepost_OBJECTS = $(am_largepost_OBJECTS)
-largepost_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_logging_OBJECTS = logging.$(OBJEXT)
-logging_OBJECTS = $(am_logging_OBJECTS)
-logging_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_responseheaders_OBJECTS = responseheaders.$(OBJEXT)
-responseheaders_OBJECTS = $(am_responseheaders_OBJECTS)
-responseheaders_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_sessions_OBJECTS = sessions.$(OBJEXT)
-sessions_OBJECTS = $(am_sessions_OBJECTS)
-sessions_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_simplepost_OBJECTS = simplepost.$(OBJEXT)
-simplepost_OBJECTS = $(am_simplepost_OBJECTS)
-simplepost_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_tlsauthentication_OBJECTS = tlsauthentication.$(OBJEXT)
-tlsauthentication_OBJECTS = $(am_tlsauthentication_OBJECTS)
-tlsauthentication_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(basicauthentication_SOURCES) $(hellobrowser_SOURCES) \
-	$(largepost_SOURCES) $(logging_SOURCES) \
-	$(responseheaders_SOURCES) $(sessions_SOURCES) \
-	$(simplepost_SOURCES) $(tlsauthentication_SOURCES)
-DIST_SOURCES = $(basicauthentication_SOURCES) $(hellobrowser_SOURCES) \
-	$(largepost_SOURCES) $(logging_SOURCES) \
-	$(responseheaders_SOURCES) $(sessions_SOURCES) \
-	$(simplepost_SOURCES) $(tlsauthentication_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-AM_CPPFLAGS = -I$(top_srcdir)/src/include $(am__append_4)
-AM_CFLAGS = @LIBGCRYPT_CFLAGS@ $(am__append_1)
-basicauthentication_SOURCES = \
- basicauthentication.c 
-
-basicauthentication_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-hellobrowser_SOURCES = \
- hellobrowser.c 
-
-hellobrowser_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-logging_SOURCES = \
- logging.c 
-
-logging_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-responseheaders_SOURCES = \
- responseheaders.c 
-
-responseheaders_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-sessions_SOURCES = \
- sessions.c 
-
-sessions_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-tlsauthentication_SOURCES = \
- tlsauthentication.c 
-
-tlsauthentication_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-simplepost_SOURCES = \
- simplepost.c 
-
-simplepost_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-largepost_SOURCES = \
- largepost.c 
-
-largepost_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la 
-
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/examples/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu doc/examples/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-noinstPROGRAMS:
-	@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-basicauthentication$(EXEEXT): $(basicauthentication_OBJECTS) $(basicauthentication_DEPENDENCIES) $(EXTRA_basicauthentication_DEPENDENCIES) 
-	@rm -f basicauthentication$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(basicauthentication_OBJECTS) $(basicauthentication_LDADD) $(LIBS)
-
-hellobrowser$(EXEEXT): $(hellobrowser_OBJECTS) $(hellobrowser_DEPENDENCIES) $(EXTRA_hellobrowser_DEPENDENCIES) 
-	@rm -f hellobrowser$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(hellobrowser_OBJECTS) $(hellobrowser_LDADD) $(LIBS)
-
-largepost$(EXEEXT): $(largepost_OBJECTS) $(largepost_DEPENDENCIES) $(EXTRA_largepost_DEPENDENCIES) 
-	@rm -f largepost$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(largepost_OBJECTS) $(largepost_LDADD) $(LIBS)
-
-logging$(EXEEXT): $(logging_OBJECTS) $(logging_DEPENDENCIES) $(EXTRA_logging_DEPENDENCIES) 
-	@rm -f logging$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(logging_OBJECTS) $(logging_LDADD) $(LIBS)
-
-responseheaders$(EXEEXT): $(responseheaders_OBJECTS) $(responseheaders_DEPENDENCIES) $(EXTRA_responseheaders_DEPENDENCIES) 
-	@rm -f responseheaders$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(responseheaders_OBJECTS) $(responseheaders_LDADD) $(LIBS)
-
-sessions$(EXEEXT): $(sessions_OBJECTS) $(sessions_DEPENDENCIES) $(EXTRA_sessions_DEPENDENCIES) 
-	@rm -f sessions$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(sessions_OBJECTS) $(sessions_LDADD) $(LIBS)
-
-simplepost$(EXEEXT): $(simplepost_OBJECTS) $(simplepost_DEPENDENCIES) $(EXTRA_simplepost_DEPENDENCIES) 
-	@rm -f simplepost$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(simplepost_OBJECTS) $(simplepost_LDADD) $(LIBS)
-
-tlsauthentication$(EXEEXT): $(tlsauthentication_OBJECTS) $(tlsauthentication_DEPENDENCIES) $(EXTRA_tlsauthentication_DEPENDENCIES) 
-	@rm -f tlsauthentication$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(tlsauthentication_OBJECTS) $(tlsauthentication_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/basicauthentication.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hellobrowser.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/largepost.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/logging.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/responseheaders.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sessions.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/simplepost.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tlsauthentication.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(PROGRAMS)
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \
-	mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-am clean clean-generic clean-libtool \
-	clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
-	uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/doc/examples/basicauthentication.c b/doc/examples/basicauthentication.c
index 407738b..6e1493a 100644
--- a/doc/examples/basicauthentication.c
+++ b/doc/examples/basicauthentication.c
@@ -17,61 +17,76 @@
 #define PORT 8888
 
 
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
-  char *user;
-  char *pass;
-  int fail;
-  int ret;
+  struct MHD_BasicAuthInfo *auth_info;
+  enum MHD_Result ret;
   struct MHD_Response *response;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;
-  if (NULL == *con_cls)
-    {
-      *con_cls = connection;
-      return MHD_YES;
-    }
-  pass = NULL;
-  user = MHD_basic_auth_get_username_password (connection, &pass);
-  fail = ( (user == NULL) ||
-	   (0 != strcmp (user, "root")) ||
-	   (0 != strcmp (pass, "pa$$w0rd") ) );  
-  if (user != NULL) free (user);
-  if (pass != NULL) free (pass);
-  if (fail)
-    {
-      const char *page = "<html><body>Go away.</body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (page), (void *) page,
-					 MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_basic_auth_fail_response (connection,
-						"my realm",
-						response);
-    }
+  if (NULL == *req_cls)
+  {
+    *req_cls = connection;
+    return MHD_YES;
+  }
+  auth_info = MHD_basic_auth_get_username_password3 (connection);
+  if (NULL == auth_info)
+  {
+    static const char *page =
+      "<html><body>Authorization required</body></html>";
+    response = MHD_create_response_from_buffer_static (strlen (page), page);
+    ret = MHD_queue_basic_auth_fail_response3 (connection,
+                                               "admins",
+                                               MHD_YES,
+                                               response);
+  }
+  else if ((strlen ("root") != auth_info->username_len) ||
+           (0 != memcmp (auth_info->username, "root",
+                         auth_info->username_len)) ||
+           /* The next check against NULL is optional,
+            * if 'password' is NULL then 'password_len' is always zero. */
+           (NULL == auth_info->password) ||
+           (strlen ("pa$$w0rd") != auth_info->password_len) ||
+           (0 != memcmp (auth_info->password, "pa$$w0rd",
+                         auth_info->password_len)))
+  {
+    static const char *page =
+      "<html><body>Wrong username or password</body></html>";
+    response = MHD_create_response_from_buffer_static (strlen (page), page);
+    ret = MHD_queue_basic_auth_fail_response3 (connection,
+                                               "admins",
+                                               MHD_YES,
+                                               response);
+  }
   else
-    {
-      const char *page = "<html><body>A secret.</body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (page), (void *) page,
-					 MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-    }
+  {
+    static const char *page = "<html><body>A secret.</body></html>";
+    response = MHD_create_response_from_buffer_static (strlen (page), page);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  }
+  if (NULL != auth_info)
+    MHD_free (auth_info);
   MHD_destroy_response (response);
   return ret;
 }
 
 
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
                              &answer_to_connection, NULL, MHD_OPTION_END);
   if (NULL == daemon)
     return 1;
diff --git a/doc/examples/hellobrowser.c b/doc/examples/hellobrowser.c
index df38e72..0b7d907 100644
--- a/doc/examples/hellobrowser.c
+++ b/doc/examples/hellobrowser.c
@@ -14,19 +14,24 @@
 
 #define PORT 8888
 
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
   const char *page = "<html><body>Hello, browser!</body></html>";
   struct MHD_Response *response;
-  int ret;
-  
-  response =
-    MHD_create_response_from_buffer (strlen (page), (void *) page, 
-				     MHD_RESPMEM_PERSISTENT);
+  enum MHD_Result ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) method;            /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+  (void) req_cls;           /* Unused. Silent compiler warning. */
+
+  response = MHD_create_response_from_buffer_static (strlen (page), page);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
 
@@ -35,11 +40,12 @@
 
 
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+  daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                             PORT, NULL, NULL,
                              &answer_to_connection, NULL, MHD_OPTION_END);
   if (NULL == daemon)
     return 1;
diff --git a/doc/examples/largepost.c b/doc/examples/largepost.c
index 0b9de2d..45c4ad0 100644
--- a/doc/examples/largepost.c
+++ b/doc/examples/largepost.c
@@ -13,229 +13,331 @@
 #include <string.h>
 #include <microhttpd.h>
 
+#if defined(_MSC_VER) && _MSC_VER + 0 <= 1800
+/* Substitution is OK while return value is not used */
+#define snprintf _snprintf
+#endif
+
 #define PORT            8888
 #define POSTBUFFERSIZE  512
 #define MAXCLIENTS      2
 
-#define GET             0
-#define POST            1
+enum ConnectionType
+{
+  GET = 0,
+  POST = 1
+};
 
 static unsigned int nr_of_uploading_clients = 0;
 
+
+/**
+ * Information we keep per connection.
+ */
 struct connection_info_struct
 {
-  int connectiontype;
+  enum ConnectionType connectiontype;
+
+  /**
+   * Handle to the POST processing state.
+   */
   struct MHD_PostProcessor *postprocessor;
+
+  /**
+   * File handle where we write uploaded data.
+   */
   FILE *fp;
+
+  /**
+   * HTTP response body we will return, NULL if not yet known.
+   */
   const char *answerstring;
-  int answercode;
+
+  /**
+   * HTTP status code we will return, 0 for undecided.
+   */
+  unsigned int answercode;
 };
 
-const char *askpage = "<html><body>\n\
-                       Upload a file, please!<br>\n\
-                       There are %u clients uploading at the moment.<br>\n\
-                       <form action=\"/filepost\" method=\"post\" enctype=\"multipart/form-data\">\n\
-                       <input name=\"file\" type=\"file\">\n\
-                       <input type=\"submit\" value=\" Send \"></form>\n\
-                       </body></html>";
 
-const char *busypage =
+#define ASKPAGE \
+  "<html><body>\n" \
+  "Upload a file, please!<br>\n" \
+  "There are %u clients uploading at the moment.<br>\n" \
+  "<form action=\"/filepost\" method=\"post\" enctype=\"multipart/form-data\">\n" \
+  "<input name=\"file\" type=\"file\">\n" \
+  "<input type=\"submit\" value=\" Send \"></form>\n" \
+  "</body></html>"
+static const char *busypage =
   "<html><body>This server is busy, please try again later.</body></html>";
-
-const char *completepage =
+static const char *completepage =
   "<html><body>The upload has been completed.</body></html>";
-
-const char *errorpage =
+static const char *errorpage =
   "<html><body>This doesn't seem to be right.</body></html>";
-const char *servererrorpage =
-  "<html><body>An internal server error has occured.</body></html>";
-const char *fileexistspage =
+static const char *servererrorpage =
+  "<html><body>Invalid request.</body></html>";
+static const char *fileexistspage =
   "<html><body>This file already exists.</body></html>";
+static const char *fileioerror =
+  "<html><body>IO error writing to disk.</body></html>";
+static const char *const postprocerror =
+  "<html><head><title>Error</title></head><body>Error processing POST data</body></html>";
 
 
-static int
-send_page (struct MHD_Connection *connection, const char *page,
-           int status_code)
+static enum MHD_Result
+send_page (struct MHD_Connection *connection,
+           const char *page,
+           unsigned int status_code)
 {
-  int ret;
+  enum MHD_Result ret;
   struct MHD_Response *response;
 
-  response =
-    MHD_create_response_from_buffer (strlen (page), (void *) page,
-				     MHD_RESPMEM_MUST_COPY);
-  if (!response)
+  response = MHD_create_response_from_buffer_static (strlen (page), page);
+  if (! response)
     return MHD_NO;
-  MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html");
-  ret = MHD_queue_response (connection, status_code, response);
+  MHD_add_response_header (response,
+                           MHD_HTTP_HEADER_CONTENT_TYPE,
+                           "text/html");
+  ret = MHD_queue_response (connection,
+                            status_code,
+                            response);
   MHD_destroy_response (response);
 
   return ret;
 }
 
 
-static int
-iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key,
-              const char *filename, const char *content_type,
-              const char *transfer_encoding, const char *data, uint64_t off,
+static enum MHD_Result
+iterate_post (void *coninfo_cls,
+              enum MHD_ValueKind kind,
+              const char *key,
+              const char *filename,
+              const char *content_type,
+              const char *transfer_encoding,
+              const char *data,
+              uint64_t off,
               size_t size)
 {
   struct connection_info_struct *con_info = coninfo_cls;
   FILE *fp;
-
-  con_info->answerstring = servererrorpage;
-  con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR;
+  (void) kind;               /* Unused. Silent compiler warning. */
+  (void) content_type;       /* Unused. Silent compiler warning. */
+  (void) transfer_encoding;  /* Unused. Silent compiler warning. */
+  (void) off;                /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (key, "file"))
-    return MHD_NO;
+  {
+    con_info->answerstring = servererrorpage;
+    con_info->answercode = MHD_HTTP_BAD_REQUEST;
+    return MHD_YES;
+  }
 
-  if (!con_info->fp)
+  if (! con_info->fp)
+  {
+    if (0 != con_info->answercode)   /* something went wrong */
+      return MHD_YES;
+    if (NULL != (fp = fopen (filename, "rb")))
     {
-      if (NULL != (fp = fopen (filename, "rb")))
-        {
-          fclose (fp);
-          con_info->answerstring = fileexistspage;
-          con_info->answercode = MHD_HTTP_FORBIDDEN;
-          return MHD_NO;
-        }
-
-      con_info->fp = fopen (filename, "ab");
-      if (!con_info->fp)
-        return MHD_NO;
+      fclose (fp);
+      con_info->answerstring = fileexistspage;
+      con_info->answercode = MHD_HTTP_FORBIDDEN;
+      return MHD_YES;
     }
+    /* NOTE: This is technically a race with the 'fopen()' above,
+       but there is no easy fix, short of moving to open(O_EXCL)
+       instead of using fopen(). For the example, we do not care. */
+    con_info->fp = fopen (filename, "ab");
+    if (! con_info->fp)
+    {
+      con_info->answerstring = fileioerror;
+      con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR;
+      return MHD_YES;
+    }
+  }
 
   if (size > 0)
+  {
+    if (! fwrite (data, sizeof (char), size, con_info->fp))
     {
-      if (!fwrite (data, size, sizeof (char), con_info->fp))
-        return MHD_NO;
+      con_info->answerstring = fileioerror;
+      con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR;
+      return MHD_YES;
     }
-
-  con_info->answerstring = completepage;
-  con_info->answercode = MHD_HTTP_OK;
+  }
 
   return MHD_YES;
 }
 
 
 static void
-request_completed (void *cls, struct MHD_Connection *connection,
-                   void **con_cls, enum MHD_RequestTerminationCode toe)
+request_completed (void *cls,
+                   struct MHD_Connection *connection,
+                   void **req_cls,
+                   enum MHD_RequestTerminationCode toe)
 {
-  struct connection_info_struct *con_info = *con_cls;
+  struct connection_info_struct *con_info = *req_cls;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == con_info)
     return;
 
   if (con_info->connectiontype == POST)
+  {
+    if (NULL != con_info->postprocessor)
     {
-      if (NULL != con_info->postprocessor)
-        {
-          MHD_destroy_post_processor (con_info->postprocessor);
-          nr_of_uploading_clients--;
-        }
-
-      if (con_info->fp)
-        fclose (con_info->fp);
+      MHD_destroy_post_processor (con_info->postprocessor);
+      nr_of_uploading_clients--;
     }
 
+    if (con_info->fp)
+      fclose (con_info->fp);
+  }
+
   free (con_info);
-  *con_cls = NULL;
+  *req_cls = NULL;
 }
 
 
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-                      const char *url, const char *method,
-                      const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+static enum MHD_Result
+answer_to_connection (void *cls,
+                      struct MHD_Connection *connection,
+                      const char *url,
+                      const char *method,
+                      const char *version,
+                      const char *upload_data,
+                      size_t *upload_data_size,
+                      void **req_cls)
 {
-  if (NULL == *con_cls)
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+
+  if (NULL == *req_cls)
+  {
+    /* First call, setup data structures */
+    struct connection_info_struct *con_info;
+
+    if (nr_of_uploading_clients >= MAXCLIENTS)
+      return send_page (connection,
+                        busypage,
+                        MHD_HTTP_SERVICE_UNAVAILABLE);
+
+    con_info = malloc (sizeof (struct connection_info_struct));
+    if (NULL == con_info)
+      return MHD_NO;
+    con_info->answercode = 0;   /* none yet */
+    con_info->fp = NULL;
+
+    if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
     {
-      struct connection_info_struct *con_info;
+      con_info->postprocessor =
+        MHD_create_post_processor (connection,
+                                   POSTBUFFERSIZE,
+                                   &iterate_post,
+                                   (void *) con_info);
 
-      if (nr_of_uploading_clients >= MAXCLIENTS)
-        return send_page (connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE);
-
-      con_info = malloc (sizeof (struct connection_info_struct));
-      if (NULL == con_info)
+      if (NULL == con_info->postprocessor)
+      {
+        free (con_info);
         return MHD_NO;
+      }
 
-      con_info->fp = NULL;
+      nr_of_uploading_clients++;
 
-      if (0 == strcmp (method, "POST"))
-        {
-          con_info->postprocessor =
-            MHD_create_post_processor (connection, POSTBUFFERSIZE,
-                                       iterate_post, (void *) con_info);
+      con_info->connectiontype = POST;
+    }
+    else
+    {
+      con_info->connectiontype = GET;
+    }
 
-          if (NULL == con_info->postprocessor)
-            {
-              free (con_info);
-              return MHD_NO;
-            }
+    *req_cls = (void *) con_info;
 
-          nr_of_uploading_clients++;
+    return MHD_YES;
+  }
 
-          con_info->connectiontype = POST;
-          con_info->answercode = MHD_HTTP_OK;
-          con_info->answerstring = completepage;
-        }
-      else
-        con_info->connectiontype = GET;
+  if (0 == strcmp (method, MHD_HTTP_METHOD_GET))
+  {
+    /* We just return the standard form for uploads on all GET requests */
+    char buffer[1024];
 
-      *con_cls = (void *) con_info;
+    snprintf (buffer,
+              sizeof (buffer),
+              ASKPAGE,
+              nr_of_uploading_clients);
+    return send_page (connection,
+                      buffer,
+                      MHD_HTTP_OK);
+  }
+
+  if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
+  {
+    struct connection_info_struct *con_info = *req_cls;
+
+    if (0 != *upload_data_size)
+    {
+      /* Upload not yet done */
+      if (0 != con_info->answercode)
+      {
+        /* we already know the answer, skip rest of upload */
+        *upload_data_size = 0;
+        return MHD_YES;
+      }
+      if (MHD_YES !=
+          MHD_post_process (con_info->postprocessor,
+                            upload_data,
+                            *upload_data_size))
+      {
+        con_info->answerstring = postprocerror;
+        con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR;
+      }
+      *upload_data_size = 0;
 
       return MHD_YES;
     }
-
-  if (0 == strcmp (method, "GET"))
+    /* Upload finished */
+    if (NULL != con_info->fp)
     {
-      char buffer[1024];
-
-      snprintf (buffer, sizeof (buffer), askpage, nr_of_uploading_clients);
-      return send_page (connection, buffer, MHD_HTTP_OK);
+      fclose (con_info->fp);
+      con_info->fp = NULL;
     }
-
-  if (0 == strcmp (method, "POST"))
+    if (0 == con_info->answercode)
     {
-      struct connection_info_struct *con_info = *con_cls;
-
-      if (0 != *upload_data_size)
-        {
-          MHD_post_process (con_info->postprocessor, upload_data,
-                            *upload_data_size);
-          *upload_data_size = 0;
-
-          return MHD_YES;
-        }
-      else
-	{
-	  if (NULL != con_info->fp)
-	  {
-	    fclose (con_info->fp);
-	    con_info->fp = NULL;
-	  }
-	  /* Now it is safe to open and inspect the file before calling send_page with a response */
-	  return send_page (connection, con_info->answerstring,
-			    con_info->answercode);
-	}
-
+      /* No errors encountered, declare success */
+      con_info->answerstring = completepage;
+      con_info->answercode = MHD_HTTP_OK;
     }
+    return send_page (connection,
+                      con_info->answerstring,
+                      con_info->answercode);
+  }
 
-  return send_page (connection, errorpage, MHD_HTTP_BAD_REQUEST);
+  /* Note a GET or a POST, generate error */
+  return send_page (connection,
+                    errorpage,
+                    MHD_HTTP_BAD_REQUEST);
 }
 
 
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD,
+                             PORT, NULL, NULL,
                              &answer_to_connection, NULL,
-                             MHD_OPTION_NOTIFY_COMPLETED, request_completed,
-                             NULL, MHD_OPTION_END);
+                             MHD_OPTION_NOTIFY_COMPLETED, &request_completed,
+                             NULL,
+                             MHD_OPTION_END);
   if (NULL == daemon)
+  {
+    fprintf (stderr,
+             "Failed to start daemon.\n");
     return 1;
+  }
   (void) getchar ();
   MHD_stop_daemon (daemon);
   return 0;
diff --git a/doc/examples/logging.c b/doc/examples/logging.c
index c896a7d..2c2a3c3 100644
--- a/doc/examples/logging.c
+++ b/doc/examples/logging.c
@@ -14,21 +14,28 @@
 #define PORT 8888
 
 
-static int
+static enum MHD_Result
 print_out_key (void *cls, enum MHD_ValueKind kind, const char *key,
                const char *value)
 {
+  (void) cls;    /* Unused. Silent compiler warning. */
+  (void) kind;   /* Unused. Silent compiler warning. */
   printf ("%s: %s\n", key, value);
   return MHD_YES;
 }
 
 
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+  (void) req_cls;           /* Unused. Silent compiler warning. */
   printf ("New %s request for %s using version %s\n", method, url, version);
 
   MHD_get_connection_values (connection, MHD_HEADER_KIND, print_out_key,
@@ -39,11 +46,11 @@
 
 
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
                              &answer_to_connection, NULL, MHD_OPTION_END);
   if (NULL == daemon)
     return 1;
diff --git a/doc/examples/responseheaders.c b/doc/examples/responseheaders.c
index 25cca43..30ac459 100644
--- a/doc/examples/responseheaders.c
+++ b/doc/examples/responseheaders.c
@@ -19,47 +19,51 @@
 #define FILENAME "picture.png"
 #define MIMETYPE "image/png"
 
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
   struct MHD_Response *response;
   int fd;
-  int ret;
+  enum MHD_Result ret;
   struct stat sbuf;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+  (void) req_cls;           /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;
 
   if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
        (0 != fstat (fd, &sbuf)) )
-    {
-      /* error accessing file */
-      if (fd != -1)
-	(void) close (fd);
-      const char *errorstr =
-        "<html><body>An internal server error has occured!\
+  {
+    const char *errorstr =
+      "<html><body>An internal server error has occurred!\
                               </body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (errorstr), 
-					 (void *) errorstr, 
-					 MHD_RESPMEM_PERSISTENT);
-      if (NULL != response)
-        {
-          ret =
-            MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
-                                response);
-          MHD_destroy_response (response);
+    /* error accessing file */
+    if (fd != -1)
+      (void) close (fd);
+    response =
+      MHD_create_response_from_buffer_static (strlen (errorstr), errorstr);
+    if (NULL != response)
+    {
+      ret =
+        MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
+                            response);
+      MHD_destroy_response (response);
 
-          return ret;
-        }
-      else
-        return MHD_NO;
+      return ret;
     }
+    else
+      return MHD_NO;
+  }
   response =
-    MHD_create_response_from_fd_at_offset (sbuf.st_size, fd, 0);
+    MHD_create_response_from_fd_at_offset64 ((size_t) sbuf.st_size, fd, 0);
   MHD_add_response_header (response, "Content-Type", MIMETYPE);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
@@ -69,11 +73,11 @@
 
 
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
                              &answer_to_connection, NULL, MHD_OPTION_END);
   if (NULL == daemon)
     return 1;
diff --git a/doc/examples/sessions.c b/doc/examples/sessions.c
index 0fd2766..3f60c29 100644
--- a/doc/examples/sessions.c
+++ b/doc/examples/sessions.c
@@ -1,9 +1,6 @@
 /* Feel free to use this example code in any way
    you see fit (Public Domain) */
 
-/* needed for asprintf */
-#define _GNU_SOURCE
-
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -11,75 +8,45 @@
 #include <time.h>
 #include <microhttpd.h>
 
-#if defined _WIN32 && !defined(__MINGW64_VERSION_MAJOR)
-static int
-asprintf (char **resultp, const char *format, ...)
-{
-  va_list argptr;
-  char *result = NULL;
-  int len = 0;
-
-  if (format == NULL)
-    return -1;
-
-  va_start (argptr, format);
-
-  len = _vscprintf ((char *) format, argptr);
-  if (len >= 0)
-  {
-    len += 1;
-    result = (char *) malloc (sizeof (char *) * len);
-    if (result != NULL)
-    {
-      int len2 = _vscprintf ((char *) format, argptr);
-      if (len2 != len - 1 || len2 <= 0)
-      {
-        free (result);
-        result = NULL;
-        len = -1;
-      }
-      else
-      {
-        len = len2;
-        if (resultp)
-          *resultp = result;
-      }
-    }
-  }
-  va_end (argptr);
-  return len;
-}
-#endif
-
 /**
  * Invalid method page.
  */
-#define METHOD_ERROR "<html><head><title>Illegal request</title></head><body>Go away.</body></html>"
+#define METHOD_ERROR \
+  "<html><head><title>Illegal request</title></head><body>Go away.</body></html>"
 
 /**
  * Invalid URL page.
  */
-#define NOT_FOUND_ERROR "<html><head><title>Not found</title></head><body>Go away.</body></html>"
+#define NOT_FOUND_ERROR \
+  "<html><head><title>Not found</title></head><body>Go away.</body></html>"
 
 /**
  * Front page. (/)
  */
-#define MAIN_PAGE "<html><head><title>Welcome</title></head><body><form action=\"/2\" method=\"post\">What is your name? <input type=\"text\" name=\"v1\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
+#define MAIN_PAGE \
+  "<html><head><title>Welcome</title></head><body><form action=\"/2\" method=\"post\">What is your name? <input type=\"text\" name=\"v1\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
+
+#define FORM_V1 MAIN_PAGE
 
 /**
  * Second page. (/2)
  */
-#define SECOND_PAGE "<html><head><title>Tell me more</title></head><body><a href=\"/\">previous</a> <form action=\"/S\" method=\"post\">%s, what is your job? <input type=\"text\" name=\"v2\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
+#define SECOND_PAGE \
+  "<html><head><title>Tell me more</title></head><body><a href=\"/\">previous</a> <form action=\"/S\" method=\"post\">%s, what is your job? <input type=\"text\" name=\"v2\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
+
+#define FORM_V1_V2 SECOND_PAGE
 
 /**
  * Second page (/S)
  */
-#define SUBMIT_PAGE "<html><head><title>Ready to submit?</title></head><body><form action=\"/F\" method=\"post\"><a href=\"/2\">previous </a> <input type=\"hidden\" name=\"DONE\" value=\"yes\" /><input type=\"submit\" value=\"Submit\" /></body></html>"
+#define SUBMIT_PAGE \
+  "<html><head><title>Ready to submit?</title></head><body><form action=\"/F\" method=\"post\"><a href=\"/2\">previous </a> <input type=\"hidden\" name=\"DONE\" value=\"yes\" /><input type=\"submit\" value=\"Submit\" /></body></html>"
 
 /**
  * Last page.
  */
-#define LAST_PAGE "<html><head><title>Thank you</title></head><body>Thank you.</body></html>"
+#define LAST_PAGE \
+  "<html><head><title>Thank you</title></head><body>Thank you.</body></html>"
 
 /**
  * Name of our cookie.
@@ -98,7 +65,7 @@
   struct Session *next;
 
   /**
-   * Unique ID for this session. 
+   * Unique ID for this session.
    */
   char sid[33];
 
@@ -144,7 +111,7 @@
   struct MHD_PostProcessor *pp;
 
   /**
-   * URL to serve in response to this POST (if this request 
+   * URL to serve in response to this POST (if this request
    * was a 'POST')
    */
   const char *post_url;
@@ -159,10 +126,8 @@
 static struct Session *sessions;
 
 
-
-
 /**
- * Return the session handle for this connection, or 
+ * Return the session handle for this connection, or
  * create one if this is a new user.
  */
 static struct Session *
@@ -172,41 +137,41 @@
   const char *cookie;
 
   cookie = MHD_lookup_connection_value (connection,
-					MHD_COOKIE_KIND,
-					COOKIE_NAME);
+                                        MHD_COOKIE_KIND,
+                                        COOKIE_NAME);
   if (cookie != NULL)
+  {
+    /* find existing session */
+    ret = sessions;
+    while (NULL != ret)
     {
-      /* find existing session */
-      ret = sessions;
-      while (NULL != ret)
-	{
-	  if (0 == strcmp (cookie, ret->sid))
-	    break;
-	  ret = ret->next;
-	}
-      if (NULL != ret)
-	{
-	  ret->rc++;
-	  return ret;
-	}
+      if (0 == strcmp (cookie, ret->sid))
+        break;
+      ret = ret->next;
     }
+    if (NULL != ret)
+    {
+      ret->rc++;
+      return ret;
+    }
+  }
   /* create fresh session */
   ret = calloc (1, sizeof (struct Session));
   if (NULL == ret)
-    {						
-      fprintf (stderr, "calloc error: %s\n", strerror (errno));
-      return NULL; 
-    }
+  {
+    fprintf (stderr, "calloc error: %s\n", strerror (errno));
+    return NULL;
+  }
   /* not a super-secure way to generate a random session ID,
      but should do for a simple example... */
   snprintf (ret->sid,
-	    sizeof (ret->sid),
-	    "%X%X%X%X",
-	    (unsigned int) rand (),
-	    (unsigned int) rand (),
-	    (unsigned int) rand (),
-	    (unsigned int) rand ());
-  ret->rc++;  
+            sizeof (ret->sid),
+            "%X%X%X%X",
+            (unsigned int) rand (),
+            (unsigned int) rand (),
+            (unsigned int) rand (),
+            (unsigned int) rand ());
+  ret->rc++;
   ret->start = time (NULL);
   ret->next = sessions;
   sessions = ret;
@@ -221,17 +186,17 @@
  * @param mime mime type to use
  * @param session session information
  * @param connection connection to process
- * @param MHD_YES on success, MHD_NO on failure
+ * @param #MHD_YES on success, #MHD_NO on failure
  */
-typedef int (*PageHandler)(const void *cls,
-			   const char *mime,
-			   struct Session *session,
-			   struct MHD_Connection *connection);
+typedef enum MHD_Result (*PageHandler)(const void *cls,
+                                       const char *mime,
+                                       struct Session *session,
+                                       struct MHD_Connection *connection);
 
 
 /**
  * Entry we generate for each page served.
- */ 
+ */
 struct Page
 {
   /**
@@ -251,7 +216,7 @@
 
   /**
    * Extra argument to handler.
-   */ 
+   */
   const void *handler_cls;
 };
 
@@ -261,25 +226,25 @@
  *
  * @param session session to use
  * @param response response to modify
- */ 
+ */
 static void
 add_session_cookie (struct Session *session,
-		    struct MHD_Response *response)
+                    struct MHD_Response *response)
 {
   char cstr[256];
   snprintf (cstr,
-	    sizeof (cstr),
-	    "%s=%s",
-	    COOKIE_NAME,
-	    session->sid);
-  if (MHD_NO == 
+            sizeof (cstr),
+            "%s=%s",
+            COOKIE_NAME,
+            session->sid);
+  if (MHD_NO ==
       MHD_add_response_header (response,
-			       MHD_HTTP_HEADER_SET_COOKIE,
-			       cstr))
-    {
-      fprintf (stderr, 
-	       "Failed to set session cookie header!\n");
-    }
+                               MHD_HTTP_HEADER_SET_COOKIE,
+                               cstr))
+  {
+    fprintf (stderr,
+             "Failed to set session cookie header!\n");
+  }
 }
 
 
@@ -289,30 +254,28 @@
  *
  * @param cls a 'const char *' with the HTML webpage to return
  * @param mime mime type to use
- * @param session session handle 
+ * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 serve_simple_form (const void *cls,
-		   const char *mime,
-		   struct Session *session,
-		   struct MHD_Connection *connection)
+                   const char *mime,
+                   struct Session *session,
+                   struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
   const char *form = cls;
   struct MHD_Response *response;
 
   /* return static form */
-  response = MHD_create_response_from_buffer (strlen (form),
-					      (void *) form,
-					      MHD_RESPMEM_PERSISTENT);
+  response = MHD_create_response_from_buffer_static (strlen (form), form);
   add_session_cookie (session, response);
   MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
-  ret = MHD_queue_response (connection, 
-			    MHD_HTTP_OK, 
-			    response);
+                           MHD_HTTP_HEADER_CONTENT_ENCODING,
+                           mime);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
@@ -323,39 +286,60 @@
  *
  * @param cls a 'const char *' with the HTML webpage to return
  * @param mime mime type to use
- * @param session session handle 
+ * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 fill_v1_form (const void *cls,
-	      const char *mime,
-	      struct Session *session,
-	      struct MHD_Connection *connection)
+              const char *mime,
+              struct Session *session,
+              struct MHD_Connection *connection)
 {
-  int ret;
-  const char *form = cls;
+  enum MHD_Result ret;
   char *reply;
   struct MHD_Response *response;
+  int reply_len;
+  (void) cls; /* Unused */
 
-  if (-1 == asprintf (&reply,
-		      form,
-		      session->value_1))
-    {
-      /* oops */
-      return MHD_NO;
-    }
+  /* Emulate 'asprintf' */
+  reply_len = snprintf (NULL, 0, FORM_V1, session->value_1);
+  if (0 > reply_len)
+    return MHD_NO; /* Internal error */
+
+  reply = (char *) malloc (reply_len + 1);
+  if (NULL == reply)
+    return MHD_NO; /* Out-of-memory error */
+
+  if (reply_len != snprintf (reply,
+                             ((size_t) reply_len) + 1,
+                             FORM_V1,
+                             session->value_1))
+  {
+    free (reply);
+    return MHD_NO; /* printf error */
+  }
+
   /* return static form */
-  response = MHD_create_response_from_buffer (strlen (reply),
-					      (void *) reply,
-					      MHD_RESPMEM_MUST_FREE);
-  add_session_cookie (session, response);
-  MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
-  ret = MHD_queue_response (connection, 
-			    MHD_HTTP_OK, 
-			    response);
-  MHD_destroy_response (response);
+  response =
+    MHD_create_response_from_buffer_with_free_callback ((size_t) reply_len,
+                                                        (void *) reply,
+                                                        &free);
+  if (NULL != response)
+  {
+    add_session_cookie (session, response);
+    MHD_add_response_header (response,
+                             MHD_HTTP_HEADER_CONTENT_ENCODING,
+                             mime);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else
+  {
+    free (reply);
+    ret = MHD_NO;
+  }
   return ret;
 }
 
@@ -365,40 +349,62 @@
  *
  * @param cls a 'const char *' with the HTML webpage to return
  * @param mime mime type to use
- * @param session session handle 
+ * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 fill_v1_v2_form (const void *cls,
-		 const char *mime,
-		 struct Session *session,
-		 struct MHD_Connection *connection)
+                 const char *mime,
+                 struct Session *session,
+                 struct MHD_Connection *connection)
 {
-  int ret;
-  const char *form = cls;
+  enum MHD_Result ret;
   char *reply;
   struct MHD_Response *response;
+  int reply_len;
+  (void) cls; /* Unused */
 
-  if (-1 == asprintf (&reply,
-		      form,
-		      session->value_1,
-		      session->value_2))
-    {
-      /* oops */
-      return MHD_NO;
-    }
+  /* Emulate 'asprintf' */
+  reply_len = snprintf (NULL, 0, FORM_V1_V2, session->value_1,
+                        session->value_2);
+  if (0 > reply_len)
+    return MHD_NO; /* Internal error */
+
+  reply = (char *) malloc (reply_len + 1);
+  if (NULL == reply)
+    return MHD_NO; /* Out-of-memory error */
+
+  if (reply_len == snprintf (reply,
+                             ((size_t) reply_len) + 1,
+                             FORM_V1_V2,
+                             session->value_1,
+                             session->value_2))
+  {
+    free (reply);
+    return MHD_NO; /* printf error */
+  }
+
   /* return static form */
-  response = MHD_create_response_from_buffer (strlen (reply),
-					      (void *) reply,
-					      MHD_RESPMEM_MUST_FREE);
-  add_session_cookie (session, response);
-  MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
-  ret = MHD_queue_response (connection, 
-			    MHD_HTTP_OK, 
-			    response);
-  MHD_destroy_response (response);
+  response =
+    MHD_create_response_from_buffer_with_free_callback ((size_t) reply_len,
+                                                        (void *) reply,
+                                                        &free);
+  if (NULL != response)
+  {
+    add_session_cookie (session, response);
+    MHD_add_response_header (response,
+                             MHD_HTTP_HEADER_CONTENT_ENCODING,
+                             mime);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else
+  {
+    free (reply);
+    ret = MHD_NO;
+  }
   return ret;
 }
 
@@ -408,28 +414,29 @@
  *
  * @param cls a 'const char *' with the HTML webpage to return
  * @param mime mime type to use
- * @param session session handle 
+ * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 not_found_page (const void *cls,
-		const char *mime,
-		struct Session *session,
-		struct MHD_Connection *connection)
+                const char *mime,
+                struct Session *session,
+                struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
   struct MHD_Response *response;
+  (void) cls;     /* Unused. Silent compiler warning. */
+  (void) session; /* Unused. Silent compiler warning. */
 
   /* unsupported HTTP method */
-  response = MHD_create_response_from_buffer (strlen (NOT_FOUND_ERROR),
-					      (void *) NOT_FOUND_ERROR,
-					      MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response (connection, 
-			    MHD_HTTP_NOT_FOUND, 
-			    response);
+  response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR),
+                                                     NOT_FOUND_ERROR);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_NOT_FOUND,
+                            response);
   MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
+                           MHD_HTTP_HEADER_CONTENT_ENCODING,
+                           mime);
   MHD_destroy_response (response);
   return ret;
 }
@@ -438,15 +445,13 @@
 /**
  * List of all pages served by this HTTP server.
  */
-static struct Page pages[] = 
-  {
-    { "/", "text/html",  &fill_v1_form, MAIN_PAGE },
-    { "/2", "text/html", &fill_v1_v2_form, SECOND_PAGE },
-    { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE },
-    { "/F", "text/html", &serve_simple_form, LAST_PAGE },
-    { NULL, NULL, &not_found_page, NULL } /* 404 */
-  };
-
+static const struct Page pages[] = {
+  { "/", "text/html",  &fill_v1_form, NULL },
+  { "/2", "text/html", &fill_v1_v2_form, NULL },
+  { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE },
+  { "/F", "text/html", &serve_simple_form, LAST_PAGE },
+  { NULL, NULL, &not_found_page, NULL }   /* 404 */
+};
 
 
 /**
@@ -468,49 +473,53 @@
  * @return MHD_YES to continue iterating,
  *         MHD_NO to abort the iteration
  */
-static int
+static enum MHD_Result
 post_iterator (void *cls,
-	       enum MHD_ValueKind kind,
-	       const char *key,
-	       const char *filename,
-	       const char *content_type,
-	       const char *transfer_encoding,
-	       const char *data, uint64_t off, size_t size)
+               enum MHD_ValueKind kind,
+               const char *key,
+               const char *filename,
+               const char *content_type,
+               const char *transfer_encoding,
+               const char *data, uint64_t off, size_t size)
 {
   struct Request *request = cls;
   struct Session *session = request->session;
+  (void) kind;               /* Unused. Silent compiler warning. */
+  (void) filename;           /* Unused. Silent compiler warning. */
+  (void) content_type;       /* Unused. Silent compiler warning. */
+  (void) transfer_encoding;  /* Unused. Silent compiler warning. */
 
   if (0 == strcmp ("DONE", key))
-    {
-      fprintf (stdout,
-	       "Session `%s' submitted `%s', `%s'\n",
-	       session->sid,
-	       session->value_1,
-	       session->value_2);
-      return MHD_YES;
-    }
+  {
+    fprintf (stdout,
+             "Session `%s' submitted `%s', `%s'\n",
+             session->sid,
+             session->value_1,
+             session->value_2);
+    return MHD_YES;
+  }
   if (0 == strcmp ("v1", key))
-    {
-      if (size + off > sizeof(session->value_1))
-	size = sizeof (session->value_1) - off;
-      memcpy (&session->value_1[off],
-	      data,
-	      size);
-      if (size + off < sizeof (session->value_1))
-	session->value_1[size+off] = '\0';
-      return MHD_YES;
-    }
+  {
+    if (size + off > sizeof(session->value_1))
+      size = sizeof (session->value_1) - off;
+    memcpy (&session->value_1[off],
+            data,
+            size);
+    if (size + off < sizeof (session->value_1))
+      session->value_1[size + off] = '\0';
+    return MHD_YES;
+  }
   if (0 == strcmp ("v2", key))
-    {
-      if (size + off > sizeof(session->value_2))
-	size = sizeof (session->value_2) - off;
-      memcpy (&session->value_2[off],
-	      data,
-	      size);
-      if (size + off < sizeof (session->value_2))
-	session->value_2[size+off] = '\0';
-      return MHD_YES;
-    }
+  {
+    if (size + off > sizeof(session->value_2))
+      size = sizeof (session->value_2) - off;
+    memcpy (&session->value_2[off],
+            data,
+            size);
+    if (size + off < sizeof (session->value_2))
+      session->value_2[size + off] = '\0';
+    return MHD_YES;
+  }
   fprintf (stderr, "Unsupported form value `%s'\n", key);
   return MHD_YES;
 }
@@ -536,7 +545,7 @@
  * @param upload_data_size set initially to the size of the
  *        upload_data provided; the method must update this
  *        value to the number of bytes NOT processed;
- * @param ptr pointer that the callback can set to some
+ * @param req_cls pointer that the callback can set to some
  *        address and that will be preserved by MHD for future
  *        calls for this request; since the access handler may
  *        be called many times (i.e., for a PUT/POST operation
@@ -545,104 +554,105 @@
  *        If necessary, this state can be cleaned up in the
  *        global "MHD_RequestCompleted" callback (which
  *        can be set with the MHD_OPTION_NOTIFY_COMPLETED).
- *        Initially, <tt>*con_cls</tt> will be NULL.
+ *        Initially, <tt>*req_cls</tt> will be NULL.
  * @return MHS_YES if the connection was handled successfully,
- *         MHS_NO if the socket must be closed due to a serios
+ *         MHS_NO if the socket must be closed due to a serious
  *         error while handling the request
  */
-static int
+static enum MHD_Result
 create_response (void *cls,
-		 struct MHD_Connection *connection,
-		 const char *url,
-		 const char *method,
-		 const char *version,
-		 const char *upload_data, 
-		 size_t *upload_data_size,
-		 void **ptr)
+                 struct MHD_Connection *connection,
+                 const char *url,
+                 const char *method,
+                 const char *version,
+                 const char *upload_data,
+                 size_t *upload_data_size,
+                 void **req_cls)
 {
   struct MHD_Response *response;
   struct Request *request;
   struct Session *session;
-  int ret;
+  enum MHD_Result ret;
   unsigned int i;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
 
-  request = *ptr;
+  request = *req_cls;
   if (NULL == request)
+  {
+    request = calloc (1, sizeof (struct Request));
+    if (NULL == request)
     {
-      request = calloc (1, sizeof (struct Request));
-      if (NULL == request)
-	{
-	  fprintf (stderr, "calloc error: %s\n", strerror (errno));
-	  return MHD_NO;
-	}
-      *ptr = request;
-      if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-	{
-	  request->pp = MHD_create_post_processor (connection, 1024,
-						   &post_iterator, request);
-	  if (NULL == request->pp)
-	    {
-	      fprintf (stderr, "Failed to setup post processor for `%s'\n",
-		       url);
-	      return MHD_NO; /* internal error */
-	    }
-	}
-      return MHD_YES;
+      fprintf (stderr, "calloc error: %s\n", strerror (errno));
+      return MHD_NO;
     }
+    *req_cls = request;
+    if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
+    {
+      request->pp = MHD_create_post_processor (connection, 1024,
+                                               &post_iterator, request);
+      if (NULL == request->pp)
+      {
+        fprintf (stderr, "Failed to setup post processor for `%s'\n",
+                 url);
+        return MHD_NO; /* internal error */
+      }
+    }
+    return MHD_YES;
+  }
   if (NULL == request->session)
+  {
+    request->session = get_session (connection);
+    if (NULL == request->session)
     {
-      request->session = get_session (connection);
-      if (NULL == request->session)
-	{
-	  fprintf (stderr, "Failed to setup session for `%s'\n",
-		   url);
-	  return MHD_NO; /* internal error */
-	}
+      fprintf (stderr, "Failed to setup session for `%s'\n",
+               url);
+      return MHD_NO; /* internal error */
     }
+  }
   session = request->session;
   session->start = time (NULL);
   if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-    {      
-      /* evaluate POST data */
-      MHD_post_process (request->pp,
-			upload_data,
-			*upload_data_size);
-      if (0 != *upload_data_size)
-	{
-	  *upload_data_size = 0;
-	  return MHD_YES;
-	}
-      /* done with POST data, serve response */
-      MHD_destroy_post_processor (request->pp);
-      request->pp = NULL;
-      method = MHD_HTTP_METHOD_GET; /* fake 'GET' */
-      if (NULL != request->post_url)
-	url = request->post_url;
+  {
+    /* evaluate POST data */
+    MHD_post_process (request->pp,
+                      upload_data,
+                      *upload_data_size);
+    if (0 != *upload_data_size)
+    {
+      *upload_data_size = 0;
+      return MHD_YES;
     }
+    /* done with POST data, serve response */
+    MHD_destroy_post_processor (request->pp);
+    request->pp = NULL;
+    method = MHD_HTTP_METHOD_GET;   /* fake 'GET' */
+    if (NULL != request->post_url)
+      url = request->post_url;
+  }
 
   if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) ||
        (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) )
-    {
-      /* find out which page to serve */
-      i=0;
-      while ( (pages[i].url != NULL) &&
-	      (0 != strcmp (pages[i].url, url)) )
-	i++;
-      ret = pages[i].handler (pages[i].handler_cls, 
-			      pages[i].mime,
-			      session, connection);
-      if (ret != MHD_YES)
-	fprintf (stderr, "Failed to create page for `%s'\n",
-		 url);
-      return ret;
-    }
+  {
+    /* find out which page to serve */
+    i = 0;
+    while ( (pages[i].url != NULL) &&
+            (0 != strcmp (pages[i].url, url)) )
+      i++;
+    ret = pages[i].handler (pages[i].handler_cls,
+                            pages[i].mime,
+                            session, connection);
+    if (ret != MHD_YES)
+      fprintf (stderr, "Failed to create page for `%s'\n",
+               url);
+    return ret;
+  }
   /* unsupported HTTP method */
-  response = MHD_create_response_from_buffer (strlen (METHOD_ERROR),
-					      (void *) METHOD_ERROR,
-					      MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response (connection, 
-			    MHD_HTTP_METHOD_NOT_ACCEPTABLE, 
-			    response);
+  response = MHD_create_response_from_buffer_static (strlen (METHOD_ERROR),
+                                                     METHOD_ERROR);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_NOT_ACCEPTABLE,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
@@ -654,16 +664,19 @@
  *
  * @param cls not used
  * @param connection connection that completed
- * @param con_cls session handle
+ * @param req_cls session handle
  * @param toe status code
  */
 static void
 request_completed_callback (void *cls,
-			    struct MHD_Connection *connection,
-			    void **con_cls,
-			    enum MHD_RequestTerminationCode toe)
+                            struct MHD_Connection *connection,
+                            void **req_cls,
+                            enum MHD_RequestTerminationCode toe)
 {
-  struct Request *request = *con_cls;
+  struct Request *request = *req_cls;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == request)
     return;
@@ -680,7 +693,7 @@
  * too long.
  */
 static void
-expire_sessions ()
+expire_sessions (void)
 {
   struct Session *pos;
   struct Session *prev;
@@ -691,21 +704,21 @@
   prev = NULL;
   pos = sessions;
   while (NULL != pos)
+  {
+    next = pos->next;
+    if (now - pos->start > 60 * 60)
     {
-      next = pos->next;
-      if (now - pos->start > 60 * 60)
-	{
-	  /* expire sessions after 1h */
-	  if (NULL == prev)
-	    sessions = pos->next;
-	  else
-	    prev->next = next;
-	  free (pos);
-	}
+      /* expire sessions after 1h */
+      if (NULL == prev)
+        sessions = pos->next;
       else
-        prev = pos;
-      pos = next;
-    }      
+        prev->next = next;
+      free (pos);
+    }
+    else
+      prev = pos;
+    pos = next;
+  }
 }
 
 
@@ -722,53 +735,66 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  int max;
-  MHD_UNSIGNED_LONG_LONG mhd_timeout;
+  MHD_socket max;
+  uint64_t mhd_timeout;
+  unsigned int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  if ( (1 != sscanf (argv[1], "%u", &port)) ||
+       (0 == port) || (65535 < port) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+
   /* initialize PRNG */
   srand ((unsigned int) time (NULL));
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, 
-			&create_response, NULL, 
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15,
-			MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL,
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL,
+                        &create_response, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15,
+                        MHD_OPTION_NOTIFY_COMPLETED,
+                        &request_completed_callback, NULL,
+                        MHD_OPTION_END);
   if (NULL == d)
     return 1;
   while (1)
+  {
+    expire_sessions ();
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      break; /* fatal internal error */
+    if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES)
     {
-      expire_sessions ();
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-	break; /* fatal internal error */
-      if (MHD_get_timeout (d, &mhd_timeout) == MHD_YES)	
-	{
-	  tv.tv_sec = mhd_timeout / 1000;
-	  tv.tv_usec = (mhd_timeout - (tv.tv_sec * 1000)) * 1000;
-	  tvp = &tv;	  
-	}
-      else
-	tvp = NULL;
-      if (-1 == select (max + 1, &rs, &ws, &es, tvp))
-	{
-	  if (EINTR != errno)
-	    fprintf (stderr, 
-		     "Aborting due to error during select: %s\n",
-		     strerror (errno));
-	  break;
-	}
-      MHD_run (d);
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+      tv.tv_sec = (time_t) (mhd_timeout / 1000);
+#else  /* Native W32 */
+      tv.tv_sec = (long) (mhd_timeout / 1000);
+#endif /* Native W32 */
+      tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000;
+      tvp = &tv;
     }
+    else
+      tvp = NULL;
+    if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp))
+    {
+      if (EINTR != errno)
+        fprintf (stderr,
+                 "Aborting due to error during select: %s\n",
+                 strerror (errno));
+      break;
+    }
+    MHD_run (d);
+  }
   MHD_stop_daemon (d);
   return 0;
 }
-
diff --git a/doc/examples/simplepost.c b/doc/examples/simplepost.c
index c623cba..4d42b9a 100644
--- a/doc/examples/simplepost.c
+++ b/doc/examples/simplepost.c
@@ -13,6 +13,11 @@
 #include <string.h>
 #include <stdlib.h>
 
+#if defined(_MSC_VER) && _MSC_VER + 0 <= 1800
+/* Substitution is OK while return value is not used */
+#define snprintf _snprintf
+#endif
+
 #define PORT            8888
 #define POSTBUFFERSIZE  512
 #define MAXNAMESIZE     20
@@ -28,31 +33,30 @@
   struct MHD_PostProcessor *postprocessor;
 };
 
-const char *askpage = "<html><body>\
-                       What's your name, Sir?<br>\
-                       <form action=\"/namepost\" method=\"post\">\
-                       <input name=\"name\" type=\"text\"\
-                       <input type=\"submit\" value=\" Send \"></form>\
-                       </body></html>";
+static const char *askpage =
+  "<html><body>\n"
+  "What's your name, Sir?<br>\n"
+  "<form action=\"/namepost\" method=\"post\">\n"
+  "<input name=\"name\" type=\"text\">\n"
+  "<input type=\"submit\" value=\" Send \"></form>\n"
+  "</body></html>";
 
-const char *greetingpage =
-  "<html><body><h1>Welcome, %s!</center></h1></body></html>";
+#define GREETINGPAGE \
+  "<html><body><h1>Welcome, %s!</center></h1></body></html>"
 
-const char *errorpage =
+static const char *errorpage =
   "<html><body>This doesn't seem to be right.</body></html>";
 
 
-static int
+static enum MHD_Result
 send_page (struct MHD_Connection *connection, const char *page)
 {
-  int ret;
+  enum MHD_Result ret;
   struct MHD_Response *response;
 
 
-  response =
-    MHD_create_response_from_buffer (strlen (page), (void *) page,
-				     MHD_RESPMEM_PERSISTENT);
-  if (!response)
+  response = MHD_create_response_from_buffer_static (strlen (page), page);
+  if (! response)
     return MHD_NO;
 
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
@@ -62,123 +66,138 @@
 }
 
 
-static int
+static enum MHD_Result
 iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key,
               const char *filename, const char *content_type,
               const char *transfer_encoding, const char *data, uint64_t off,
               size_t size)
 {
   struct connection_info_struct *con_info = coninfo_cls;
+  (void) kind;               /* Unused. Silent compiler warning. */
+  (void) filename;           /* Unused. Silent compiler warning. */
+  (void) content_type;       /* Unused. Silent compiler warning. */
+  (void) transfer_encoding;  /* Unused. Silent compiler warning. */
+  (void) off;                /* Unused. Silent compiler warning. */
 
   if (0 == strcmp (key, "name"))
+  {
+    if ((size > 0) && (size <= MAXNAMESIZE))
     {
-      if ((size > 0) && (size <= MAXNAMESIZE))
-        {
-          char *answerstring;
-          answerstring = malloc (MAXANSWERSIZE);
-          if (!answerstring)
-            return MHD_NO;
+      char *answerstring;
+      answerstring = malloc (MAXANSWERSIZE);
+      if (! answerstring)
+        return MHD_NO;
 
-          snprintf (answerstring, MAXANSWERSIZE, greetingpage, data);
-          con_info->answerstring = answerstring;
-        }
-      else
-        con_info->answerstring = NULL;
-
-      return MHD_NO;
+      snprintf (answerstring, MAXANSWERSIZE, GREETINGPAGE, data);
+      con_info->answerstring = answerstring;
     }
+    else
+      con_info->answerstring = NULL;
+
+    return MHD_NO;
+  }
 
   return MHD_YES;
 }
 
+
 static void
 request_completed (void *cls, struct MHD_Connection *connection,
-                   void **con_cls, enum MHD_RequestTerminationCode toe)
+                   void **req_cls, enum MHD_RequestTerminationCode toe)
 {
-  struct connection_info_struct *con_info = *con_cls;
+  struct connection_info_struct *con_info = *req_cls;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == con_info)
     return;
 
   if (con_info->connectiontype == POST)
-    {
-      MHD_destroy_post_processor (con_info->postprocessor);
-      if (con_info->answerstring)
-        free (con_info->answerstring);
-    }
+  {
+    MHD_destroy_post_processor (con_info->postprocessor);
+    if (con_info->answerstring)
+      free (con_info->answerstring);
+  }
 
   free (con_info);
-  *con_cls = NULL;
+  *req_cls = NULL;
 }
 
 
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
-  if (NULL == *con_cls)
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+
+  if (NULL == *req_cls)
+  {
+    struct connection_info_struct *con_info;
+
+    con_info = malloc (sizeof (struct connection_info_struct));
+    if (NULL == con_info)
+      return MHD_NO;
+    con_info->answerstring = NULL;
+
+    if (0 == strcmp (method, "POST"))
     {
-      struct connection_info_struct *con_info;
+      con_info->postprocessor =
+        MHD_create_post_processor (connection, POSTBUFFERSIZE,
+                                   iterate_post, (void *) con_info);
 
-      con_info = malloc (sizeof (struct connection_info_struct));
-      if (NULL == con_info)
+      if (NULL == con_info->postprocessor)
+      {
+        free (con_info);
         return MHD_NO;
-      con_info->answerstring = NULL;
+      }
 
-      if (0 == strcmp (method, "POST"))
-        {
-          con_info->postprocessor =
-            MHD_create_post_processor (connection, POSTBUFFERSIZE,
-                                       iterate_post, (void *) con_info);
+      con_info->connectiontype = POST;
+    }
+    else
+      con_info->connectiontype = GET;
 
-          if (NULL == con_info->postprocessor)
-            {
-              free (con_info);
-              return MHD_NO;
-            }
+    *req_cls = (void *) con_info;
 
-          con_info->connectiontype = POST;
-        }
-      else
-        con_info->connectiontype = GET;
+    return MHD_YES;
+  }
 
-      *con_cls = (void *) con_info;
+  if (0 == strcmp (method, "GET"))
+  {
+    return send_page (connection, askpage);
+  }
+
+  if (0 == strcmp (method, "POST"))
+  {
+    struct connection_info_struct *con_info = *req_cls;
+
+    if (*upload_data_size != 0)
+    {
+      MHD_post_process (con_info->postprocessor, upload_data,
+                        *upload_data_size);
+      *upload_data_size = 0;
 
       return MHD_YES;
     }
-
-  if (0 == strcmp (method, "GET"))
-    {
-      return send_page (connection, askpage);
-    }
-
-  if (0 == strcmp (method, "POST"))
-    {
-      struct connection_info_struct *con_info = *con_cls;
-
-      if (*upload_data_size != 0)
-        {
-          MHD_post_process (con_info->postprocessor, upload_data,
-                            *upload_data_size);
-          *upload_data_size = 0;
-
-          return MHD_YES;
-        }
-      else if (NULL != con_info->answerstring)
-        return send_page (connection, con_info->answerstring);
-    }
+    else if (NULL != con_info->answerstring)
+      return send_page (connection, con_info->answerstring);
+  }
 
   return send_page (connection, errorpage);
 }
 
+
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
 
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
+  daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                             PORT, NULL, NULL,
                              &answer_to_connection, NULL,
                              MHD_OPTION_NOTIFY_COMPLETED, request_completed,
                              NULL, MHD_OPTION_END);
diff --git a/doc/examples/tlsauthentication.c b/doc/examples/tlsauthentication.c
index 4d616b6..0cd6c4e 100644
--- a/doc/examples/tlsauthentication.c
+++ b/doc/examples/tlsauthentication.c
@@ -15,7 +15,7 @@
 
 #define PORT 8888
 
-#define REALM     "\"Maintenance\""
+#define REALM     "Maintenance"
 #define USER      "a legitimate user"
 #define PASSWORD  "and his password"
 
@@ -23,183 +23,116 @@
 #define SERVERCERTFILE "server.pem"
 
 
-static char *
-string_to_base64 (const char *message)
-{
-  const char *lookup =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-  unsigned long l;
-  int i;
-  char *tmp;
-  size_t length = strlen (message);
-
-  tmp = malloc (length * 2);
-  if (NULL == tmp)
-    return tmp;
-
-  tmp[0] = 0;
-
-  for (i = 0; i < length; i += 3)
-    {
-      l = (((unsigned long) message[i]) << 16)
-        | (((i + 1) < length) ? (((unsigned long) message[i + 1]) << 8) : 0)
-        | (((i + 2) < length) ? ((unsigned long) message[i + 2]) : 0);
-
-
-      strncat (tmp, &lookup[(l >> 18) & 0x3F], 1);
-      strncat (tmp, &lookup[(l >> 12) & 0x3F], 1);
-
-      if (i + 1 < length)
-        strncat (tmp, &lookup[(l >> 6) & 0x3F], 1);
-      if (i + 2 < length)
-        strncat (tmp, &lookup[l & 0x3F], 1);
-    }
-
-  if (length % 3)
-    strncat (tmp, "===", 3 - length % 3);
-
-  return tmp;
-}
-
-
-static long
+static size_t
 get_file_size (const char *filename)
 {
   FILE *fp;
 
   fp = fopen (filename, "rb");
   if (fp)
-    {
-      long size;
+  {
+    long size;
 
-      if ((0 != fseek (fp, 0, SEEK_END)) || (-1 == (size = ftell (fp))))
-        size = 0;
+    if ((0 != fseek (fp, 0, SEEK_END)) || (-1 == (size = ftell (fp))))
+      size = 0;
 
-      fclose (fp);
+    fclose (fp);
 
-      return size;
-    }
+    return (size_t) size;
+  }
   else
     return 0;
 }
 
+
 static char *
 load_file (const char *filename)
 {
   FILE *fp;
   char *buffer;
-  long size;
+  size_t size;
 
   size = get_file_size (filename);
-  if (size == 0)
+  if (0 == size)
     return NULL;
 
   fp = fopen (filename, "rb");
-  if (!fp)
+  if (! fp)
     return NULL;
 
-  buffer = malloc (size);
-  if (!buffer)
-    {
-      fclose (fp);
-      return NULL;
-    }
+  buffer = malloc (size + 1);
+  if (! buffer)
+  {
+    fclose (fp);
+    return NULL;
+  }
+  buffer[size] = '\0';
 
   if (size != fread (buffer, 1, size, fp))
-    {
-      free (buffer);
-      buffer = NULL;
-    }
+  {
+    free (buffer);
+    buffer = NULL;
+  }
 
   fclose (fp);
   return buffer;
 }
 
-static int
+
+static enum MHD_Result
 ask_for_authentication (struct MHD_Connection *connection, const char *realm)
 {
-  int ret;
+  enum MHD_Result ret;
   struct MHD_Response *response;
-  char *headervalue;
-  const char *strbase = "Basic realm=";
 
-  response = MHD_create_response_from_buffer (0, NULL, 
-					      MHD_RESPMEM_PERSISTENT);
-  if (!response)
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  if (! response)
     return MHD_NO;
 
-  headervalue = malloc (strlen (strbase) + strlen (realm) + 1);
-  if (!headervalue)
-    return MHD_NO;
-
-  strcpy (headervalue, strbase);
-  strcat (headervalue, realm);
-
-  ret = MHD_add_response_header (response, "WWW-Authenticate", headervalue);
-  free (headervalue);
-  if (!ret)
-    {
-      MHD_destroy_response (response);
-      return MHD_NO;
-    }
-
-  ret = MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response);
-
+  ret = MHD_queue_basic_auth_fail_response3 (connection,
+                                             realm,
+                                             MHD_YES,
+                                             response);
   MHD_destroy_response (response);
-
   return ret;
 }
 
+
 static int
 is_authenticated (struct MHD_Connection *connection,
-                  const char *username, const char *password)
+                  const char *username,
+                  const char *password)
 {
-  const char *headervalue;
-  char *expected_b64, *expected;
-  const char *strbase = "Basic ";
+  struct MHD_BasicAuthInfo *auth_info;
   int authenticated;
 
-  headervalue =
-    MHD_lookup_connection_value (connection, MHD_HEADER_KIND,
-                                 "Authorization");
-  if (NULL == headervalue)
+  auth_info = MHD_basic_auth_get_username_password3 (connection);
+  if (NULL == auth_info)
     return 0;
-  if (0 != strncmp (headervalue, strbase, strlen (strbase)))
-    return 0;
-
-  expected = malloc (strlen (username) + 1 + strlen (password) + 1);
-  if (NULL == expected)
-    return 0;
-
-  strcpy (expected, username);
-  strcat (expected, ":");
-  strcat (expected, password);
-
-  expected_b64 = string_to_base64 (expected);
-  free (expected);
-  if (NULL == expected_b64)
-    return 0;
-
   authenticated =
-    (strcmp (headervalue + strlen (strbase), expected_b64) == 0);
+    ( (strlen (username) == auth_info->username_len) &&
+      (0 == memcmp (auth_info->username, username, auth_info->username_len)) &&
+      /* The next check against NULL is optional,
+       * if 'password' is NULL then 'password_len' is always zero. */
+      (NULL != auth_info->password) &&
+      (strlen (password) == auth_info->password_len) &&
+      (0 == memcmp (auth_info->password, password, auth_info->password_len)) );
 
-  free (expected_b64);
+  MHD_free (auth_info);
 
   return authenticated;
 }
 
 
-static int
+static enum MHD_Result
 secret_page (struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
   struct MHD_Response *response;
   const char *page = "<html><body>A secret.</body></html>";
 
-  response =
-    MHD_create_response_from_buffer (strlen (page), (void *) page, 
-				     MHD_RESPMEM_PERSISTENT);
-  if (!response)
+  response = MHD_create_response_from_buffer_static (strlen (page), page);
+  if (! response)
     return MHD_NO;
 
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
@@ -209,21 +142,27 @@
 }
 
 
-static int
+static enum MHD_Result
 answer_to_connection (void *cls, struct MHD_Connection *connection,
                       const char *url, const char *method,
                       const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
+                      size_t *upload_data_size, void **req_cls)
 {
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
   if (0 != strcmp (method, "GET"))
     return MHD_NO;
-  if (NULL == *con_cls)
-    {
-      *con_cls = connection;
-      return MHD_YES;
-    }
+  if (NULL == *req_cls)
+  {
+    *req_cls = connection;
+    return MHD_YES;
+  }
 
-  if (!is_authenticated (connection, USER, PASSWORD))
+  if (! is_authenticated (connection, USER, PASSWORD))
     return ask_for_authentication (connection, REALM);
 
   return secret_page (connection);
@@ -231,7 +170,7 @@
 
 
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
   char *key_pem;
@@ -241,25 +180,29 @@
   cert_pem = load_file (SERVERCERTFILE);
 
   if ((key_pem == NULL) || (cert_pem == NULL))
-    {
-      printf ("The key/certificate files could not be read.\n");
-      return 1;
-    }
+  {
+    printf ("The key/certificate files could not be read.\n");
+    if (NULL != key_pem)
+      free (key_pem);
+    if (NULL != cert_pem)
+      free (cert_pem);
+    return 1;
+  }
 
   daemon =
-    MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL, PORT, NULL,
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL,
                       NULL, &answer_to_connection, NULL,
                       MHD_OPTION_HTTPS_MEM_KEY, key_pem,
                       MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END);
   if (NULL == daemon)
-    {
-      printf ("%s\n", cert_pem);
+  {
+    printf ("%s\n", cert_pem);
 
-      free (key_pem);
-      free (cert_pem);
+    free (key_pem);
+    free (cert_pem);
 
-      return 1;
-    }
+    return 1;
+  }
 
   (void) getchar ();
 
diff --git a/doc/examples/websocket.c b/doc/examples/websocket.c
new file mode 100644
index 0000000..1d25fe5
--- /dev/null
+++ b/doc/examples/websocket.c
@@ -0,0 +1,449 @@
+/* Feel free to use this example code in any way
+   you see fit (Public Domain) */
+
+#include <sys/types.h>
+#ifndef _WIN32
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <fcntl.h>
+#else
+#include <winsock2.h>
+#endif
+#include <microhttpd.h>
+#include <microhttpd_ws.h>
+#include <time.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+
+#define PORT 80
+
+#define PAGE \
+  "<!DOCTYPE html>\n" \
+  "<html>\n" \
+  "<head>\n" \
+  "<meta charset=\"UTF-8\">\n" \
+  "<title>Websocket Demo</title>\n" \
+  "<script>\n" \
+  "\n" \
+  "let url = 'ws' + (window.location.protocol === 'https:' ? 's' : '')" \
+    "  + ':/" "/' +\n" \
+  "          window.location.host + '/chat';\n" \
+  "let socket = null;\n" \
+  "\n" \
+  "window.onload = function(event) {\n" \
+  "  socket = new WebSocket(url);\n" \
+  "  socket.onopen = function(event) {\n" \
+  "    document.write('The websocket connection has been " \
+    "established.<br>');\n" \
+  "\n" \
+  "    /" "/ Send some text\n" \
+  "    socket.send('Hello from JavaScript!');\n" \
+  "  }\n" \
+  "\n" \
+  "  socket.onclose = function(event) {\n" \
+  "    document.write('The websocket connection has been closed.<br>');\n" \
+  "  }\n" \
+  "\n" \
+  "  socket.onerror = function(event) {\n" \
+  "    document.write('An error occurred during the websocket " \
+    "communication.<br>');\n" \
+  "  }\n" \
+  "\n" \
+  "  socket.onmessage = function(event) {\n" \
+  "    document.write('Websocket message received: ' + " \
+    "event.data + '<br>');\n" \
+  "  }\n" \
+  "}\n" \
+  "\n" \
+  "</script>\n" \
+  "</head>\n" \
+  "<body>\n" \
+  "</body>\n" \
+  "</html>"
+
+#define PAGE_NOT_FOUND \
+  "404 Not Found"
+
+#define PAGE_INVALID_WEBSOCKET_REQUEST \
+  "Invalid WebSocket request!"
+
+static void
+send_all (MHD_socket fd,
+          const char *buf,
+          size_t len);
+
+static void
+make_blocking (MHD_socket fd);
+
+static void
+upgrade_handler (void *cls,
+                 struct MHD_Connection *connection,
+                 void *req_cls,
+                 const char *extra_in,
+                 size_t extra_in_size,
+                 MHD_socket fd,
+                 struct MHD_UpgradeResponseHandle *urh)
+{
+  /* make the socket blocking (operating-system-dependent code) */
+  make_blocking (fd);
+
+  /* create a websocket stream for this connection */
+  struct MHD_WebSocketStream *ws;
+  int result = MHD_websocket_stream_init (&ws,
+                                          0,
+                                          0);
+  if (0 != result)
+  {
+    /* Couldn't create the websocket stream.
+     * So we close the socket and leave
+     */
+    MHD_upgrade_action (urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+    return;
+  }
+
+  /* Let's wait for incoming data */
+  const size_t buf_len = 256;
+  char buf[buf_len];
+  ssize_t got;
+  while (MHD_WEBSOCKET_VALIDITY_VALID == MHD_websocket_stream_is_valid (ws))
+  {
+    got = recv (fd,
+                buf,
+                buf_len,
+                0);
+    if (0 >= got)
+    {
+      /* the TCP/IP socket has been closed */
+      break;
+    }
+
+    /* parse the entire received data */
+    size_t buf_offset = 0;
+    while (buf_offset < (size_t) got)
+    {
+      size_t new_offset = 0;
+      char *frame_data = NULL;
+      size_t frame_len  = 0;
+      int status = MHD_websocket_decode (ws,
+                                         buf + buf_offset,
+                                         ((size_t) got) - buf_offset,
+                                         &new_offset,
+                                         &frame_data,
+                                         &frame_len);
+      if (0 > status)
+      {
+        /* an error occurred and the connection must be closed */
+        if (NULL != frame_data)
+        {
+          MHD_websocket_free (ws, frame_data);
+        }
+        break;
+      }
+      else
+      {
+        buf_offset += new_offset;
+        if (0 < status)
+        {
+          /* the frame is complete */
+          switch (status)
+          {
+          case MHD_WEBSOCKET_STATUS_TEXT_FRAME:
+            /* The client has sent some text.
+             * We will display it and answer with a text frame.
+             */
+            if (NULL != frame_data)
+            {
+              printf ("Received message: %s\n", frame_data);
+              MHD_websocket_free (ws, frame_data);
+              frame_data = NULL;
+            }
+            result = MHD_websocket_encode_text (ws,
+                                                "Hello",
+                                                5,  /* length of "Hello" */
+                                                0,
+                                                &frame_data,
+                                                &frame_len,
+                                                NULL);
+            if (0 == result)
+            {
+              send_all (fd,
+                        frame_data,
+                        frame_len);
+            }
+            break;
+
+          case MHD_WEBSOCKET_STATUS_CLOSE_FRAME:
+            /* if we receive a close frame, we will respond with one */
+            MHD_websocket_free (ws,
+                                frame_data);
+            frame_data = NULL;
+
+            result = MHD_websocket_encode_close (ws,
+                                                 0,
+                                                 NULL,
+                                                 0,
+                                                 &frame_data,
+                                                 &frame_len);
+            if (0 == result)
+            {
+              send_all (fd,
+                        frame_data,
+                        frame_len);
+            }
+            break;
+
+          case MHD_WEBSOCKET_STATUS_PING_FRAME:
+            /* if we receive a ping frame, we will respond */
+            /* with the corresponding pong frame */
+            {
+              char *pong = NULL;
+              size_t pong_len = 0;
+              result = MHD_websocket_encode_pong (ws,
+                                                  frame_data,
+                                                  frame_len,
+                                                  &pong,
+                                                  &pong_len);
+              if (0 == result)
+              {
+                send_all (fd,
+                          pong,
+                          pong_len);
+              }
+              MHD_websocket_free (ws,
+                                  pong);
+            }
+            break;
+
+          default:
+            /* Other frame types are ignored
+             * in this minimal example.
+             * This is valid, because they become
+             * automatically skipped if we receive them unexpectedly
+             */
+            break;
+          }
+        }
+        if (NULL != frame_data)
+        {
+          MHD_websocket_free (ws, frame_data);
+        }
+      }
+    }
+  }
+
+  /* free the websocket stream */
+  MHD_websocket_stream_free (ws);
+
+  /* close the socket when it is not needed anymore */
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+}
+
+
+/* This helper function is used for the case that
+ * we need to resend some data
+ */
+static void
+send_all (MHD_socket fd,
+          const char *buf,
+          size_t len)
+{
+  ssize_t ret;
+  size_t off;
+
+  for (off = 0; off < len; off += ret)
+  {
+    ret = send (fd,
+                &buf[off],
+                (int) (len - off),
+                0);
+    if (0 > ret)
+    {
+      if (EAGAIN == errno)
+      {
+        ret = 0;
+        continue;
+      }
+      break;
+    }
+    if (0 == ret)
+      break;
+  }
+}
+
+
+/* This helper function contains operating-system-dependent code and
+ * is used to make a socket blocking.
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#ifndef _WIN32
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    abort ();
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      abort ();
+#else  /* _WIN32 */
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    abort ();
+#endif /* _WIN32 */
+}
+
+
+static enum MHD_Result
+access_handler (void *cls,
+                struct MHD_Connection *connection,
+                const char *url,
+                const char *method,
+                const char *version,
+                const char *upload_data,
+                size_t *upload_data_size,
+                void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  int ret;
+
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+
+  if (0 == strcmp (url, "/"))
+  {
+    /* Default page for visiting the server */
+    struct MHD_Response *response;
+    response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                       PAGE);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else if (0 == strcmp (url, "/chat"))
+  {
+    char is_valid = 1;
+    const char *value = NULL;
+    char sec_websocket_accept[29];
+
+    if (0 != MHD_websocket_check_http_version (version))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_CONNECTION);
+    if (0 != MHD_websocket_check_connection_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_UPGRADE);
+    if (0 != MHD_websocket_check_upgrade_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION);
+    if (0 != MHD_websocket_check_version_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY);
+    if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept))
+    {
+      is_valid = 0;
+    }
+
+    if (1 == is_valid)
+    {
+      /* upgrade the connection */
+      response = MHD_create_response_for_upgrade (&upgrade_handler,
+                                                  NULL);
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_UPGRADE,
+                               "websocket");
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT,
+                               sec_websocket_accept);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_SWITCHING_PROTOCOLS,
+                                response);
+      MHD_destroy_response (response);
+    }
+    else
+    {
+      /* return error page */
+      struct MHD_Response *response;
+      response =
+        MHD_create_response_from_buffer_static (strlen (
+                                                  PAGE_INVALID_WEBSOCKET_REQUEST),
+                                                PAGE_INVALID_WEBSOCKET_REQUEST);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_BAD_REQUEST,
+                                response);
+      MHD_destroy_response (response);
+    }
+  }
+  else
+  {
+    struct MHD_Response *response;
+    response =
+      MHD_create_response_from_buffer_static (strlen (PAGE_NOT_FOUND),
+                                              PAGE_NOT_FOUND);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_NOT_FOUND,
+                              response);
+    MHD_destroy_response (response);
+  }
+
+  return ret;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  (void) argc;               /* Unused. Silent compiler warning. */
+  (void) argv;               /* Unused. Silent compiler warning. */
+  struct MHD_Daemon *daemon;
+
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                             | MHD_USE_THREAD_PER_CONNECTION
+                             | MHD_ALLOW_UPGRADE
+                             | MHD_USE_ERROR_LOG,
+                             PORT, NULL, NULL,
+                             &access_handler, NULL,
+                             MHD_OPTION_END);
+
+  if (NULL == daemon)
+    return 1;
+  (void) getc (stdin);
+
+  MHD_stop_daemon (daemon);
+
+  return 0;
+}
diff --git a/doc/gendocs.sh b/doc/gendocs.sh
new file mode 100755
index 0000000..c293f96
--- /dev/null
+++ b/doc/gendocs.sh
@@ -0,0 +1,392 @@
+#!/bin/sh -e
+# gendocs.sh -- generate a GNU manual in many formats.  This script is
+#   mentioned in maintain.texi.  See the help message below for usage details.
+
+scriptversion=2012-09-02.17
+
+# Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
+# Free Software Foundation, Inc.
+#
+# 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/>.
+#
+# Original author: Mohit Agarwal.
+# Send bug reports and any other correspondence to bug-texinfo@gnu.org.
+#
+# The latest version of this script, and the companion template, is
+# available from Texinfo CVS:
+# http://savannah.gnu.org/cgi-bin/viewcvs/texinfo/texinfo/util/gendocs.sh
+# http://savannah.gnu.org/cgi-bin/viewcvs/texinfo/texinfo/util/gendocs_template
+#
+# An up-to-date copy is also maintained in Gnulib (gnu.org/software/gnulib).
+
+prog=`basename "$0"`
+srcdir=`pwd`
+
+scripturl="http://savannah.gnu.org/cgi-bin/viewcvs/~checkout~/texinfo/texinfo/util/gendocs.sh"
+templateurl="http://savannah.gnu.org/cgi-bin/viewcvs/~checkout~/texinfo/texinfo/util/gendocs_template"
+
+: ${SETLANG="env LANG= LC_MESSAGES= LC_ALL= LANGUAGE="}
+: ${MAKEINFO="makeinfo"}
+: ${TEXI2DVI="texi2dvi -t @finalout"}
+: ${DVIPS="dvips"}
+: ${DOCBOOK2HTML="docbook2html"}
+: ${DOCBOOK2PDF="docbook2pdf"}
+: ${DOCBOOK2PS="docbook2ps"}
+: ${DOCBOOK2TXT="docbook2txt"}
+: ${GENDOCS_TEMPLATE_DIR="."}
+: ${TEXI2HTML="texi2html"}
+unset CDPATH
+unset use_texi2html
+
+version="gendocs.sh $scriptversion
+
+Copyright 2012 Free Software Foundation, Inc.
+There is NO warranty.  You may redistribute this software
+under the terms of the GNU General Public License.
+For more information about these matters, see the files named COPYING."
+
+usage="Usage: $prog [OPTION]... PACKAGE MANUAL-TITLE
+
+Generate output in various formats from PACKAGE.texinfo (or .texi or
+.txi) source.  See the GNU Maintainers document for a more extensive
+discussion:
+  http://www.gnu.org/prep/maintain_toc.html
+
+Options:
+  -s SRCFILE  read Texinfo from SRCFILE, instead of PACKAGE.{texinfo|texi|txi}
+  -o OUTDIR   write files into OUTDIR, instead of manual/.
+  --email ADR use ADR as contact in generated web pages.
+  --docbook   convert to DocBook too (xml, txt, html, pdf and ps).
+  --html ARG  pass indicated ARG to makeinfo or texi2html for HTML targets.
+  --info ARG  pass indicated ARG to makeinfo for Info, instead of --no-split.
+  --texi2html use texi2html to generate HTML targets.
+  --help      display this help and exit successfully.
+  --version   display version information and exit successfully.
+
+Simple example: $prog --email bug-gnu-emacs@gnu.org emacs \"GNU Emacs Manual\"
+
+Typical sequence:
+  cd PACKAGESOURCE/doc
+  wget \"$scripturl\"
+  wget \"$templateurl\"
+  $prog --email BUGLIST MANUAL \"GNU MANUAL - One-line description\"
+
+Output will be in a new subdirectory \"manual\" (by default;
+use -o OUTDIR to override).  Move all the new files into your web CVS
+tree, as explained in the Web Pages node of maintain.texi.
+
+Please do use the --email ADDRESS option to specify your bug-reporting
+address in the generated HTML pages.
+
+MANUAL-TITLE is included as part of the HTML <title> of the overall
+manual/index.html file.  It should include the name of the package being
+documented.  manual/index.html is created by substitution from the file
+$GENDOCS_TEMPLATE_DIR/gendocs_template.  (Feel free to modify the
+generic template for your own purposes.)
+
+If you have several manuals, you'll need to run this script several
+times with different MANUAL values, specifying a different output
+directory with -o each time.  Then write (by hand) an overall index.html
+with links to them all.
+
+If a manual's Texinfo sources are spread across several directories,
+first copy or symlink all Texinfo sources into a single directory.
+(Part of the script's work is to make a tar.gz of the sources.)
+
+As implied above, by default monolithic Info files are generated.
+If you want split Info, or other Info options, use --info to override.
+
+You can set the environment variables MAKEINFO, TEXI2DVI, TEXI2HTML, and
+DVIPS to control the programs that get executed, and
+GENDOCS_TEMPLATE_DIR to control where the gendocs_template file is
+looked for.  With --docbook, the environment variables DOCBOOK2HTML,
+DOCBOOK2PDF, DOCBOOK2PS, and DOCBOOK2TXT are also respected.
+
+By default, makeinfo and texi2dvi are run in the default (English)
+locale, since that's the language of most Texinfo manuals.  If you
+happen to have a non-English manual and non-English web site, see the
+SETLANG setting in the source.
+
+Email bug reports or enhancement requests to bug-texinfo@gnu.org.
+"
+
+calcsize()
+{
+  size=`ls -ksl $1 | awk '{print $1}'`
+  echo $size
+}
+
+MANUAL_TITLE=
+PACKAGE=
+EMAIL=webmasters@gnu.org  # please override with --email
+htmlarg=
+infoarg=--no-split
+outdir=manual
+srcfile=
+
+while test $# -gt 0; do
+  case $1 in
+    --email) shift; EMAIL=$1;;
+    --help) echo "$usage"; exit 0;;
+    --version) echo "$version"; exit 0;;
+    -s) shift; srcfile=$1;;
+    -o) shift; outdir=$1;;
+    --docbook) docbook=yes;;
+    --html) shift; htmlarg=$1;;
+    --info) shift; infoarg=$1;;
+    --texi2html) use_texi2html=1;;
+    -*)
+      echo "$0: Unknown option \`$1'." >&2
+      echo "$0: Try \`--help' for more information." >&2
+      exit 1;;
+    *)
+      if test -z "$PACKAGE"; then
+        PACKAGE=$1
+      elif test -z "$MANUAL_TITLE"; then
+        MANUAL_TITLE=$1
+      else
+        echo "$0: extra non-option argument \`$1'." >&2
+        exit 1
+      fi;;
+  esac
+  shift
+done
+
+# For most of the following, the base name is just $PACKAGE
+base=$PACKAGE
+
+if test -n "$srcfile"; then
+  # but here, we use the basename of $srcfile
+  base=`basename "$srcfile"`
+  case $base in
+    *.txi|*.texi|*.texinfo) base=`echo "$base"|sed 's/\.[texinfo]*$//'`;;
+  esac
+  PACKAGE=$base
+elif test -s "$srcdir/$PACKAGE.texinfo"; then
+  srcfile=$srcdir/$PACKAGE.texinfo
+elif test -s "$srcdir/$PACKAGE.texi"; then
+  srcfile=$srcdir/$PACKAGE.texi
+elif test -s "$srcdir/$PACKAGE.txi"; then
+  srcfile=$srcdir/$PACKAGE.txi
+else
+  echo "$0: cannot find .texinfo or .texi or .txi for $PACKAGE in $srcdir." >&2
+  exit 1
+fi
+
+if test ! -r $GENDOCS_TEMPLATE_DIR/gendocs_template; then
+  echo "$0: cannot read $GENDOCS_TEMPLATE_DIR/gendocs_template." >&2
+  echo "$0: it is available from $templateurl." >&2
+  exit 1
+fi
+
+case $outdir in
+  /*) abs_outdir=$outdir;;
+  *)  abs_outdir=$srcdir/$outdir;;
+esac
+
+echo "Generating output formats for $srcfile"
+
+cmd="$SETLANG $MAKEINFO -o $PACKAGE.info $infoarg \"$srcfile\""
+echo "Generating info file(s)... ($cmd)"
+eval "$cmd"
+mkdir -p "$outdir/"
+tar czf "$outdir/$PACKAGE.info.tar.gz" $PACKAGE.info*
+info_tgz_size=`calcsize "$outdir/$PACKAGE.info.tar.gz"`
+# do not mv the info files, there's no point in having them available
+# separately on the web.
+
+cmd="$SETLANG ${TEXI2DVI} \"$srcfile\""
+echo "Generating dvi ... ($cmd)"
+eval "$cmd"
+
+# now, before we compress dvi:
+echo "Generating postscript..."
+${DVIPS} $PACKAGE -o
+gzip -f -9 $PACKAGE.ps
+ps_gz_size=`calcsize $PACKAGE.ps.gz`
+mv $PACKAGE.ps.gz "$outdir/"
+
+# compress/finish dvi:
+gzip -f -9 $PACKAGE.dvi
+dvi_gz_size=`calcsize $PACKAGE.dvi.gz`
+mv $PACKAGE.dvi.gz "$outdir/"
+
+cmd="$SETLANG ${TEXI2DVI} --pdf \"$srcfile\""
+echo "Generating pdf ... ($cmd)"
+eval "$cmd"
+pdf_size=`calcsize $PACKAGE.pdf`
+mv $PACKAGE.pdf "$outdir/"
+
+cmd="$SETLANG $MAKEINFO -o $PACKAGE.txt --no-split --no-headers \"$srcfile\""
+echo "Generating ASCII... ($cmd)"
+eval "$cmd"
+ascii_size=`calcsize $PACKAGE.txt`
+gzip -f -9 -c $PACKAGE.txt >"$outdir/$PACKAGE.txt.gz"
+ascii_gz_size=`calcsize "$outdir/$PACKAGE.txt.gz"`
+mv $PACKAGE.txt "$outdir/"
+
+html_split()
+{
+  opt="--split=$1 $htmlarg --node-files"
+  cmd="$SETLANG $TEXI2HTML --output $PACKAGE.html $opt \"$srcfile\""
+  echo "Generating html by $1... ($cmd)"
+  eval "$cmd"
+  split_html_dir=$PACKAGE.html
+  (
+    cd ${split_html_dir} || exit 1
+    ln -sf ${PACKAGE}.html index.html
+    tar -czf "$abs_outdir/${PACKAGE}.html_$1.tar.gz" -- *.html
+  )
+  eval html_$1_tgz_size=`calcsize "$outdir/${PACKAGE}.html_$1.tar.gz"`
+  rm -f "$outdir"/html_$1/*.html
+  mkdir -p "$outdir/html_$1/"
+  mv ${split_html_dir}/*.html "$outdir/html_$1/"
+  rmdir ${split_html_dir}
+}
+
+if test -z "$use_texi2html"; then
+  opt="--no-split --html -o $PACKAGE.html $htmlarg"
+  cmd="$SETLANG $MAKEINFO $opt \"$srcfile\""
+  echo "Generating monolithic html... ($cmd)"
+  rm -rf $PACKAGE.html  # in case a directory is left over
+  eval "$cmd"
+  html_mono_size=`calcsize $PACKAGE.html`
+  gzip -f -9 -c $PACKAGE.html >"$outdir/$PACKAGE.html.gz"
+  html_mono_gz_size=`calcsize "$outdir/$PACKAGE.html.gz"`
+  mv $PACKAGE.html "$outdir/"
+
+  cmd="$SETLANG $MAKEINFO --html -o $PACKAGE.html $htmlarg \"$srcfile\""
+  echo "Generating html by node... ($cmd)"
+  eval "$cmd"
+  split_html_dir=$PACKAGE.html
+  (
+   cd ${split_html_dir} || exit 1
+   tar -czf "$abs_outdir/${PACKAGE}.html_node.tar.gz" -- *.html
+  )
+  html_node_tgz_size=`calcsize "$outdir/${PACKAGE}.html_node.tar.gz"`
+  rm -f "$outdir"/html_node/*.html
+  mkdir -p "$outdir/html_node/"
+  mv ${split_html_dir}/*.html "$outdir/html_node/"
+  rmdir ${split_html_dir}
+else
+  cmd="$SETLANG $TEXI2HTML --output $PACKAGE.html $htmlarg \"$srcfile\""
+  echo "Generating monolithic html... ($cmd)"
+  rm -rf $PACKAGE.html  # in case a directory is left over
+  eval "$cmd"
+  html_mono_size=`calcsize $PACKAGE.html`
+  gzip -f -9 -c $PACKAGE.html >"$outdir/$PACKAGE.html.gz"
+  html_mono_gz_size=`calcsize "$outdir/$PACKAGE.html.gz"`
+  mv $PACKAGE.html "$outdir/"
+
+  html_split node
+  html_split chapter
+  html_split section
+fi
+
+echo Making .tar.gz for sources...
+d=`dirname $srcfile`
+(
+  cd "$d"
+  srcfiles=`ls *.texinfo *.texi *.txi *.eps 2>/dev/null` || true
+  tar cvzfh "$abs_outdir/$PACKAGE.texi.tar.gz" $srcfiles
+)
+texi_tgz_size=`calcsize "$outdir/$PACKAGE.texi.tar.gz"`
+
+if test -n "$docbook"; then
+  cmd="$SETLANG $MAKEINFO -o - --docbook \"$srcfile\" > ${srcdir}/$PACKAGE-db.xml"
+  echo "Generating docbook XML... ($cmd)"
+  eval "$cmd"
+  docbook_xml_size=`calcsize $PACKAGE-db.xml`
+  gzip -f -9 -c $PACKAGE-db.xml >"$outdir/$PACKAGE-db.xml.gz"
+  docbook_xml_gz_size=`calcsize "$outdir/$PACKAGE-db.xml.gz"`
+  mv $PACKAGE-db.xml "$outdir/"
+
+  split_html_db_dir=html_node_db
+  cmd="${DOCBOOK2HTML} -o $split_html_db_dir \"${outdir}/$PACKAGE-db.xml\""
+  echo "Generating docbook HTML... ($cmd)"
+  eval "$cmd"
+  (
+    cd ${split_html_db_dir} || exit 1
+    tar -czf "$abs_outdir/${PACKAGE}.html_node_db.tar.gz" -- *.html
+  )
+  html_node_db_tgz_size=`calcsize "$outdir/${PACKAGE}.html_node_db.tar.gz"`
+  rm -f "$outdir"/html_node_db/*.html
+  mkdir -p "$outdir/html_node_db"
+  mv ${split_html_db_dir}/*.html "$outdir/html_node_db/"
+  rmdir ${split_html_db_dir}
+
+  cmd="${DOCBOOK2TXT} \"${outdir}/$PACKAGE-db.xml\""
+  echo "Generating docbook ASCII... ($cmd)"
+  eval "$cmd"
+  docbook_ascii_size=`calcsize $PACKAGE-db.txt`
+  mv $PACKAGE-db.txt "$outdir/"
+
+  cmd="${DOCBOOK2PS} \"${outdir}/$PACKAGE-db.xml\""
+  echo "Generating docbook PS... ($cmd)"
+  eval "$cmd"
+  gzip -f -9 -c $PACKAGE-db.ps >"$outdir/$PACKAGE-db.ps.gz"
+  docbook_ps_gz_size=`calcsize "$outdir/$PACKAGE-db.ps.gz"`
+  mv $PACKAGE-db.ps "$outdir/"
+
+  cmd="${DOCBOOK2PDF} \"${outdir}/$PACKAGE-db.xml\""
+  echo "Generating docbook PDF... ($cmd)"
+  eval "$cmd"
+  docbook_pdf_size=`calcsize $PACKAGE-db.pdf`
+  mv $PACKAGE-db.pdf "$outdir/"
+fi
+
+echo "Writing index file..."
+if test -z "$use_texi2html"; then
+   CONDS="/%%IF  *HTML_SECTION%%/,/%%ENDIF  *HTML_SECTION%%/d;\
+          /%%IF  *HTML_CHAPTER%%/,/%%ENDIF  *HTML_CHAPTER%%/d"
+else
+   CONDS="/%%ENDIF.*%%/d;/%%IF  *HTML_SECTION%%/d;/%%IF  *HTML_CHAPTER%%/d"
+fi
+curdate=`$SETLANG date '+%B %d, %Y'`
+sed \
+   -e "s!%%TITLE%%!$MANUAL_TITLE!g" \
+   -e "s!%%EMAIL%%!$EMAIL!g" \
+   -e "s!%%PACKAGE%%!$PACKAGE!g" \
+   -e "s!%%DATE%%!$curdate!g" \
+   -e "s!%%HTML_MONO_SIZE%%!$html_mono_size!g" \
+   -e "s!%%HTML_MONO_GZ_SIZE%%!$html_mono_gz_size!g" \
+   -e "s!%%HTML_NODE_TGZ_SIZE%%!$html_node_tgz_size!g" \
+   -e "s!%%HTML_SECTION_TGZ_SIZE%%!$html_section_tgz_size!g" \
+   -e "s!%%HTML_CHAPTER_TGZ_SIZE%%!$html_chapter_tgz_size!g" \
+   -e "s!%%INFO_TGZ_SIZE%%!$info_tgz_size!g" \
+   -e "s!%%DVI_GZ_SIZE%%!$dvi_gz_size!g" \
+   -e "s!%%PDF_SIZE%%!$pdf_size!g" \
+   -e "s!%%PS_GZ_SIZE%%!$ps_gz_size!g" \
+   -e "s!%%ASCII_SIZE%%!$ascii_size!g" \
+   -e "s!%%ASCII_GZ_SIZE%%!$ascii_gz_size!g" \
+   -e "s!%%TEXI_TGZ_SIZE%%!$texi_tgz_size!g" \
+   -e "s!%%DOCBOOK_HTML_NODE_TGZ_SIZE%%!$html_node_db_tgz_size!g" \
+   -e "s!%%DOCBOOK_ASCII_SIZE%%!$docbook_ascii_size!g" \
+   -e "s!%%DOCBOOK_PS_GZ_SIZE%%!$docbook_ps_gz_size!g" \
+   -e "s!%%DOCBOOK_PDF_SIZE%%!$docbook_pdf_size!g" \
+   -e "s!%%DOCBOOK_XML_SIZE%%!$docbook_xml_size!g" \
+   -e "s!%%DOCBOOK_XML_GZ_SIZE%%!$docbook_xml_gz_size!g" \
+   -e "s,%%SCRIPTURL%%,$scripturl,g" \
+   -e "s!%%SCRIPTNAME%%!$prog!g" \
+   -e "$CONDS" \
+$GENDOCS_TEMPLATE_DIR/gendocs_template >"$outdir/index.html"
+
+echo "Done, see $outdir/ subdirectory for new files."
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-end: "$"
+# End:
diff --git a/doc/gendocs_template b/doc/gendocs_template
new file mode 100644
index 0000000..63fbe53
--- /dev/null
+++ b/doc/gendocs_template
@@ -0,0 +1,87 @@
+<!--#include virtual="/server/header.html" -->
+<title>%%TITLE%% - GNU Project - Free Software Foundation (FSF)</title>
+<!--#include virtual="/server/banner.html" -->
+<h2>%%TITLE%%</h2>
+
+<address>Free Software Foundation</address>
+<address>last updated %%DATE%%</address>
+
+<p>This manual (%%PACKAGE%%) is available in the following formats:</p>
+
+<ul>
+<li><a href="%%PACKAGE%%.html">HTML
+    (%%HTML_MONO_SIZE%%K bytes)</a> - entirely on one web page.</li>
+<li><a href="html_node/index.html">HTML</a> - with one web page per
+    node.</li>
+%%IF HTML_SECTION%%
+<li><a href="html_section/index.html">HTML</a> - with one web page per
+    section.</li>
+%%ENDIF HTML_SECTION%%
+%%IF HTML_CHAPTER%%
+<li><a href="html_chapter/index.html">HTML</a> - with one web page per
+    chapter.</li>
+%%ENDIF HTML_CHAPTER%%
+<li><a href="%%PACKAGE%%.html.gz">HTML compressed
+    (%%HTML_MONO_GZ_SIZE%%K gzipped characters)</a> - entirely on
+    one web page.</li>
+<li><a href="%%PACKAGE%%.html_node.tar.gz">HTML compressed
+    (%%HTML_NODE_TGZ_SIZE%%K gzipped tar file)</a> -
+    with one web page per node.</li>
+%%IF HTML_SECTION%%
+<li><a href="%%PACKAGE%%.html_section.tar.gz">HTML compressed
+    (%%HTML_SECTION_TGZ_SIZE%%K gzipped tar file)</a> -
+    with one web page per section.</li>
+%%ENDIF HTML_SECTION%%
+%%IF HTML_CHAPTER%%
+<li><a href="%%PACKAGE%%.html_chapter.tar.gz">HTML compressed
+    (%%HTML_CHAPTER_TGZ_SIZE%%K gzipped tar file)</a> -
+    with one web page per chapter.</li>
+%%ENDIF HTML_CHAPTER%%
+<li><a href="%%PACKAGE%%.info.tar.gz">Info document
+    (%%INFO_TGZ_SIZE%%K bytes gzipped tar file)</a>.</li>
+<li><a href="%%PACKAGE%%.txt">ASCII text
+    (%%ASCII_SIZE%%K bytes)</a>.</li>
+<li><a href="%%PACKAGE%%.txt.gz">ASCII text compressed
+    (%%ASCII_GZ_SIZE%%K bytes gzipped)</a>.</li>
+<li><a href="%%PACKAGE%%.dvi.gz">TeX dvi file
+    (%%DVI_GZ_SIZE%%K bytes gzipped)</a>.</li>
+<li><a href="%%PACKAGE%%.pdf">PDF file
+    (%%PDF_SIZE%%K bytes)</a>.</li>
+<li><a href="%%PACKAGE%%.texi.tar.gz">Texinfo source
+    (%%TEXI_TGZ_SIZE%%K bytes gzipped tar file).</a></li>
+</ul>
+
+<p>You can <a href="http://shop.fsf.org/">buy printed copies of
+some manuals</a> (among other items) from the Free Software Foundation;
+this helps support FSF activities.</p>
+
+<p>(This page generated by the <a href="%%SCRIPTURL%%">%%SCRIPTNAME%%
+script</a>.)</p>
+
+<!-- If needed, change the copyright block at the bottom. In general,
+     all pages on the GNU web server should have the section about
+     verbatim copying.  Please do NOT remove this without talking
+     with the webmasters first.
+     Please make sure the copyright date is consistent with the document
+     and that it is like this: "2001, 2002", not this: "2001-2002". -->
+</div><!-- for id="content", starts in the include above -->
+<!--#include virtual="/server/footer.html" -->
+<div id="footer">
+
+<p>Please send general FSF &amp; GNU inquiries to
+<a href="mailto:gnu@gnu.org">&lt;gnu@gnu.org&gt;</a>.
+There are also <a href="/contact/">other ways to contact</a>
+the FSF.<br />
+Please send broken links and other corrections or suggestions to
+<a href="mailto:%%EMAIL%%">&lt;%%EMAIL%%&gt;</a>.</p>
+
+<p>Copyright &copy; 2013 Free Software Foundation, Inc.</p>
+
+<p>Verbatim copying and distribution of this entire article are
+permitted worldwide, without royalty, in any medium, provided this
+notice, and the copyright notice, are preserved.</p>
+
+</div>
+</div>
+</body>
+</html>
diff --git a/doc/gpl-2.0.texi b/doc/gpl-2.0.texi
new file mode 100644
index 0000000..38aa918
--- /dev/null
+++ b/doc/gpl-2.0.texi
@@ -0,0 +1,389 @@
+@c The GNU General Public License.
+@center Version 2, June 1991
+
+@c This file is intended to be included within another document,
+@c hence no sectioning command or @node.
+
+@display
+Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
+
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+@end display
+
+@heading Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software---to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+@heading TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+@enumerate 0
+@item
+This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The ``Program'', below,
+refers to any such program or work, and a ``work based on the Program''
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term ``modification''.)  Each licensee is addressed as ``you''.
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+@item
+You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+@item
+You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+@enumerate a
+@item
+You must cause the modified files to carry prominent notices
+stating that you changed the files and the date of any change.
+
+@item
+You must cause any work that you distribute or publish, that in
+whole or in part contains or is derived from the Program or any
+part thereof, to be licensed as a whole at no charge to all third
+parties under the terms of this License.
+
+@item
+If the modified program normally reads commands interactively
+when run, you must cause it, when started running for such
+interactive use in the most ordinary way, to print or display an
+announcement including an appropriate copyright notice and a
+notice that there is no warranty (or else, saying that you provide
+a warranty) and that users may redistribute the program under
+these conditions, and telling the user how to view a copy of this
+License.  (Exception: if the Program itself is interactive but
+does not normally print such an announcement, your work based on
+the Program is not required to print an announcement.)
+@end enumerate
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+@item
+You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+@enumerate a
+@item
+Accompany it with the complete corresponding machine-readable
+source code, which must be distributed under the terms of Sections
+1 and 2 above on a medium customarily used for software interchange; or,
+
+@item
+Accompany it with a written offer, valid for at least three
+years, to give any third party, for a charge no more than your
+cost of physically performing source distribution, a complete
+machine-readable copy of the corresponding source code, to be
+distributed under the terms of Sections 1 and 2 above on a medium
+customarily used for software interchange; or,
+
+@item
+Accompany it with the information you received as to the offer
+to distribute corresponding source code.  (This alternative is
+allowed only for noncommercial distribution and only if you
+received the program in object code or executable form with such
+an offer, in accord with Subsection b above.)
+@end enumerate
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+@item
+You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+@item
+You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+@item
+Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+@item
+If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+@item
+If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+@item
+The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and ``any
+later version'', you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+@item
+If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+@iftex
+@heading NO WARRANTY
+@end iftex
+@ifinfo
+@center NO WARRANTY
+
+@end ifinfo
+
+@item
+BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+@item
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+@end enumerate
+
+@iftex
+@heading END OF TERMS AND CONDITIONS
+@end iftex
+@ifinfo
+@center END OF TERMS AND CONDITIONS
+
+@end ifinfo
+
+@page
+@heading Appendix: How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the ``copyright'' line and a pointer to where the full notice is found.
+
+@smallexample
+@var{one line to give the program's name and a brief idea of what it does.}
+Copyright (C) @var{yyyy}  @var{name of author}
+
+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 2 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, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+@end smallexample
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+@smallexample
+Gnomovision version 69, Copyright (C) @var{year} @var{name of author}
+Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+This is free software, and you are welcome to redistribute it
+under certain conditions; type `show c' for details.
+@end smallexample
+
+The hypothetical commands @samp{show w} and @samp{show c} should show
+the appropriate parts of the General Public License.  Of course, the
+commands you use may be called something other than @samp{show w} and
+@samp{show c}; they could even be mouse-clicks or menu items---whatever
+suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a ``copyright disclaimer'' for the program, if
+necessary.  Here is a sample; alter the names:
+
+@example
+Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+`Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+@var{signature of Ty Coon}, 1 April 1989
+Ty Coon, President of Vice
+@end example
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/doc/libmicrohttpd-tutorial.info b/doc/libmicrohttpd-tutorial.info
deleted file mode 100644
index 79632a4..0000000
--- a/doc/libmicrohttpd-tutorial.info
+++ /dev/null
@@ -1,4231 +0,0 @@
-This is libmicrohttpd-tutorial.info, produced by makeinfo version 4.13
-from libmicrohttpd-tutorial.texi.
-
-INFO-DIR-SECTION Software libraries
-START-INFO-DIR-ENTRY
-* libmicrohttpdtutorial: (libmicrohttpd).       A tutorial for GNU libmicrohttpd.
-END-INFO-DIR-ENTRY
-
-   This tutorial documents GNU libmicrohttpd version 0.9.23, last
-updated 17 November 2013.
-
-   Copyright (c)  2008  Sebastian Gerhardt.
-
-   Copyright (c)  2010, 2011, 2012, 2013  Christian Grothoff.
-
-     Permission is granted to copy, distribute and/or modify this
-     document under the terms of the GNU Free Documentation License,
-     Version 1.3 or any later version published by the Free Software
-     Foundation; with no Invariant Sections, no Front-Cover Texts, and
-     no Back-Cover Texts.  A copy of the license is included in the
-     section entitled "GNU Free Documentation License".
-
-
-File: libmicrohttpd-tutorial.info,  Node: Top,  Next: Introduction,  Up: (dir)
-
-A Tutorial for GNU libmicrohttpd
-********************************
-
-This tutorial documents GNU libmicrohttpd version 0.9.23, last updated
-17 November 2013.
-
-   Copyright (c)  2008  Sebastian Gerhardt.
-
-   Copyright (c)  2010, 2011, 2012, 2013  Christian Grothoff.
-
-     Permission is granted to copy, distribute and/or modify this
-     document under the terms of the GNU Free Documentation License,
-     Version 1.3 or any later version published by the Free Software
-     Foundation; with no Invariant Sections, no Front-Cover Texts, and
-     no Back-Cover Texts.  A copy of the license is included in the
-     section entitled "GNU Free Documentation License".
-
-* Menu:
-
-* Introduction::
-* Hello browser example::
-* Exploring requests::
-* Response headers::
-* Supporting basic authentication::
-* Processing POST data::
-* Improved processing of POST data::
-* Session management::
-* Adding a layer of security::
-* Bibliography::
-* License text::
-* Example programs::
-
-
-File: libmicrohttpd-tutorial.info,  Node: Introduction,  Next: Hello browser example,  Prev: Top,  Up: Top
-
-1 Introduction
-**************
-
-This tutorial is for developers who want to learn how they can add HTTP
-serving capabilities to their applications with the _GNU libmicrohttpd_
-library, abbreviated _MHD_.  The reader will learn how to implement
-basic HTTP functions from simple executable sample programs that
-implement various features.
-
-   The text is supposed to be a supplement to the API reference manual
-of _GNU libmicrohttpd_ and for that reason does not explain many of the
-parameters.  Therefore, the reader should always consult the manual to
-find the exact meaning of the functions used in the tutorial.
-Furthermore, the reader is encouraged to study the relevant _RFCs_,
-which document the HTTP standard.
-
-   _GNU libmicrohttpd_ is assumed to be already installed.  This
-tutorial is written for version 0.9.23.  At the time being, this
-tutorial has only been tested on _GNU/Linux_ machines even though
-efforts were made not to rely on anything that would prevent the
-samples from being built on similar systems.
-
-1.1 History
-===========
-
-This tutorial was originally written by Sebastian Gerhardt for MHD
-0.4.0.  It was slighly polished and updated to MHD 0.9.0 by Christian
-Grothoff.
-
-
-File: libmicrohttpd-tutorial.info,  Node: Hello browser example,  Next: Exploring requests,  Prev: Introduction,  Up: Top
-
-2 Hello browser example
-***********************
-
-The most basic task for a HTTP server is to deliver a static text
-message to any client connecting to it.  Given that this is also easy
-to implement, it is an excellent problem to start with.
-
-   For now, the particular URI the client asks for shall have no effect
-on the message that will be returned. In addition, the server shall end
-the connection after the message has been sent so that the client will
-know there is nothing more to expect.
-
-   The C program `hellobrowser.c', which is to be found in the examples
-section, does just that.  If you are very eager, you can compile and
-start it right away but it is advisable to type the lines in by
-yourself as they will be discussed and explained in detail.
-
-   After the necessary includes and the definition of the port which
-our server should listen on
-#include <sys/types.h>
-#include <sys/select.h>
-#include <sys/socket.h>
-#include <microhttpd.h>
-
-#define PORT 8888
-
-the desired behaviour of our server when HTTP request arrive has to be
-implemented. We already have agreed that it should not care about the
-particular details of the request, such as who is requesting what. The
-server will respond merely with the same small HTML page to every
-request.
-
-   The function we are going to write now will be called by _GNU
-libmicrohttpd_ every time an appropriate request comes in. While the
-name of this callback function is arbitrary, its parameter list has to
-follow a certain layout. So please, ignore the lot of parameters for
-now, they will be explained at the point they are needed. We have to
-use only one of them, `struct MHD_Connection *connection', for the
-minimalistic functionality we want to archive at the moment.
-
-   This parameter is set by the _libmicrohttpd_ daemon and holds the
-necessary information to relate the call with a certain connection.
-Keep in mind that a server might have to satisfy hundreds of concurrent
-connections and we have to make sure that the correct data is sent to
-the destined client. Therefore, this variable is a means to refer to a
-particular connection if we ask the daemon to sent the reply.
-
-   Talking about the reply, it is defined as a string right after the
-function header
-int answer_to_connection (void *cls, struct MHD_Connection *connection,
-                          const char *url,
-                          const char *method, const char *version,
-                          const char *upload_data,
-                          size_t *upload_data_size, void **con_cls)
-{
-  const char *page  = "<html><body>Hello, browser!</body></html>";
-
-HTTP is a rather strict protocol and the client would certainly
-consider it "inappropriate" if we just sent the answer string "as is".
-Instead, it has to be wrapped with additional information stored in
-so-called headers and footers.  Most of the work in this area is done
-by the library for us--we just have to ask. Our reply string packed in
-the necessary layers will be called a "response".  To obtain such a
-response we hand our data (the reply-string) and its size over to the
-`MHD_create_response_from_buffer' function. The last two parameters
-basically tell _MHD_ that we do not want it to dispose the message data
-for us when it has been sent and there also needs no internal copy to
-be done because the _constant_ string won't change anyway.
-
-  struct MHD_Response *response;
-  int ret;
-
-  response = MHD_create_response_from_buffer (strlen (page),
-                                            (void*) page, MHD_RESPMEM_PERSISTENT);
-
-Now that the the response has been laced up, it is ready for delivery
-and can be queued for sending.  This is done by passing it to another
-_GNU libmicrohttpd_ function. As all our work was done in the scope of
-one function, the recipient is without doubt the one associated with the
-local variable `connection' and consequently this variable is given to
-the queue function.  Every HTTP response is accompanied by a status
-code, here "OK", so that the client knows this response is the intended
-result of his request and not due to some error or malfunction.
-
-   Finally, the packet is destroyed and the return value from the queue
-returned, already being set at this point to either MHD_YES or MHD_NO
-in case of success or failure.
-
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-  MHD_destroy_response (response);
-
-  return ret;
-}
-
-With the primary task of our server implemented, we can start the
-actual server daemon which will listen on `PORT' for connections. This
-is done in the main function.
-int main ()
-{
-  struct MHD_Daemon *daemon;
-
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                             &answer_to_connection, NULL, MHD_OPTION_END);
-  if (NULL == daemon) return 1;
-
-The first parameter is one of three possible modes of operation. Here
-we want the daemon to run in a separate thread and to manage all
-incoming connections in the same thread. This means that while
-producing the response for one connection, the other connections will
-be put on hold. In this example, where the reply is already known and
-therefore the request is served quickly, this poses no problem.
-
-   We will allow all clients to connect regardless of their name or
-location, therefore we do not check them on connection and set the
-forth and fifth parameter to NULL.
-
-   Parameter six is the address of the function we want to be called
-whenever a new connection has been established. Our
-`answer_to_connection' knows best what the client wants and needs no
-additional information (which could be passed via the next parameter)
-so the next parameter is NULL. Likewise, we do not need to pass extra
-options to the daemon so we just write the MHD_OPTION_END as the last
-parameter.
-
-   As the server daemon runs in the background in its own thread, the
-execution flow in our main function will contine right after the call.
-Because of this, we must delay the execution flow in the main thread or
-else the program will terminate prematurely. We let it pause in a
-processing-time friendly manner by waiting for the enter key to be
-pressed. In the end, we stop the daemon so it can do its cleanup tasks.
-  getchar ();
-
-  MHD_stop_daemon (daemon);
-  return 0;
-}
-
-The first example is now complete.
-
-   Compile it with
-cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES
-  -L$PATH_TO_LIBMHD_LIBS -lmicrohttpd
- with the two paths set accordingly and run it.
-
-   Now open your favorite Internet browser and go to the address
-`http://localhost:8888/', provided that 8888 is the port you chose. If
-everything works as expected, the browser will present the message of
-the static HTML page it got from our minimal server.
-
-Remarks
-=======
-
-To keep this first example as small as possible, some drastic shortcuts
-were taken and are to be discussed now.
-
-   Firstly, there is no distinction made between the kinds of requests
-a client could send. We implied that the client sends a GET request,
-that means, that he actually asked for some data. Even when it is not
-intended to accept POST requests, a good server should at least
-recognize that this request does not constitute a legal request and
-answer with an error code. This can be easily implemented by checking
-if the parameter `method' equals the string "GET" and returning a
-`MHD_NO' if not so.
-
-   Secondly, the above practice of queuing a response upon the first
-call of the callback function brings with it some limitations.  This is
-because the content of the message body will not be received if a
-response is queued in the first iteration.  Furthermore, the connection
-will be closed right after the response has been transferred then.
-This is typically not what you want as it disables HTTP pipelining.
-The correct approach is to simply not queue a message on the first
-callback unless there is an error.  The `void**' argument to the
-callback provides a location for storing information about the history
-of the connection; for the first call, the pointer will point to NULL.
-A simplistic way to differenciate the first call from others is to check
-if the pointer is NULL and set it to a non-NULL value during the first
-call.
-
-   Both of these issues you will find addressed in the official
-`minimal_example.c' residing in the `src/examples' directory of the
-_MHD_ package.  The source code of this program should look very
-familiar to you by now and easy to understand.
-
-   For our example, the `must_copy' and `must_free' parameter at the
-response construction function could be set to `MHD_NO'. In the usual
-case, responses cannot be sent immediately after being queued. For
-example, there might be other data on the system that needs to be sent
-with a higher priority. Nevertheless, the queue function will return
-successfully--raising the problem that the data we have pointed to may
-be invalid by the time it is about being sent. This is not an issue
-here because we can expect the `page' string, which is a constant
-_string literal_ here, to be static. That means it will be present and
-unchanged for as long as the program runs.  For dynamic data, one could
-choose to either have _MHD_ free the memory `page' points to itself
-when it is not longer needed or, alternatively, have the library to
-make and manage its own copy of it.
-
-Exercises
-=========
-
-   * While the server is running, use a program like `telnet' or
-     `netcat' to connect to it. Try to form a valid HTTP 1.1 request
-     yourself like GET /dontcare HTTP/1.1
-     Host: itsme
-     <enter>
-      and see what the server returns to you.
-
-   * Also, try other requests, like POST, and see how our server does
-     not mind and why.  How far in malforming a request can you go
-     before the builtin functionality of _MHD_ intervenes and an
-     altered response is sent? Make sure you read about the status
-     codes in the _RFC_.
-
-   * Add the option `MHD_USE_PEDANTIC_CHECKS' to the start function of
-     the daemon in `main'.  Mind the special format of the parameter
-     list here which is described in the manual. How indulgent is the
-     server now to your input?
-
-   * Let the main function take a string as the first command line
-     argument and pass `argv[1]' to the `MHD_start_daemon' function as
-     the sixth parameter. The address of this string will be passed to
-     the callback function via the `cls' variable. Decorate the text
-     given at the command line when the server is started with proper
-     HTML tags and send it as the response instead of the former static
-     string.
-
-   * _Demanding:_ Write a separate function returning a string
-     containing some useful information, for example, the time. Pass
-     the function's address as the sixth parameter and evaluate this
-     function on every request anew in `answer_to_connection'. Remember
-     to free the memory of the string every time after satisfying the
-     request.
-
-
-
-File: libmicrohttpd-tutorial.info,  Node: Exploring requests,  Next: Response headers,  Prev: Hello browser example,  Up: Top
-
-3 Exploring requests
-********************
-
-This chapter will deal with the information which the client sends to
-the server at every request. We are going to examine the most useful
-fields of such an request and print them out in a readable manner. This
-could be useful for logging facilities.
-
-   The starting point is the _hellobrowser_ program with the former
-response removed.
-
-   This time, we just want to collect information in the callback
-function, thus we will just return MHD_NO after we have probed the
-request. This way, the connection is closed without much ado by the
-server.
-
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-                      const char *url,
-		      const char *method, const char *version,
-		      const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
-{
-  ...
-  return MHD_NO;
-}
- The ellipsis marks the position where the following instructions shall
-be inserted.
-
-   We begin with the most obvious information available to the server,
-the request line. You should already have noted that a request consists
-of a command (or "HTTP method") and a URI (e.g. a filename).  It also
-contains a string for the version of the protocol which can be found in
-`version'.  To call it a "new request" is justified because we return
-only `MHD_NO', thus ensuring the function will not be called again for
-this connection.
-printf ("New %s request for %s using version %s\n", method, url, version);
- The rest of the information is a bit more hidden. Nevertheless, there
-is lot of it sent from common Internet browsers. It is stored in
-"key-value" pairs and we want to list what we find in the header.  As
-there is no mandatory set of keys a client has to send, each key-value
-pair is printed out one by one until there are no more left. We do this
-by writing a separate function which will be called for each pair just
-like the above function is called for each HTTP request.  It can then
-print out the content of this pair.
-int print_out_key (void *cls, enum MHD_ValueKind kind,
-                   const char *key, const char *value)
-{
-  printf ("%s: %s\n", key, value);
-  return MHD_YES;
-}
- To start the iteration process that calls our new function for every
-key, the line
-MHD_get_connection_values (connection, MHD_HEADER_KIND, &print_out_key, NULL);
- needs to be inserted in the connection callback function too. The
-second parameter tells the function that we are only interested in keys
-from the general HTTP header of the request. Our iterating function
-`print_out_key' does not rely on any additional information to fulfill
-its duties so the last parameter can be NULL.
-
-   All in all, this constitutes the complete `logging.c' program for
-this chapter which can be found in the `examples' section.
-
-   Connecting with any modern Internet browser should yield a handful
-of keys. You should try to interpret them with the aid of _RFC 2616_.
-Especially worth mentioning is the "Host" key which is often used to
-serve several different websites hosted under one single IP address but
-reachable by different domain names (this is called virtual hosting).
-
-Conclusion
-==========
-
-The introduced capabilities to itemize the content of a simple GET
-request--especially the URI--should already allow the server to satisfy
-clients' requests for small specific resources (e.g. files) or even
-induce alteration of server state. However, the latter is not
-recommended as the GET method (including its header data) is by
-convention considered a "safe" operation, which should not change the
-server's state in a significant way.  By convention, GET operations can
-thus be performed by crawlers and other automatic software.  Naturally
-actions like searching for a passed string are fine.
-
-   Of course, no transmission can occur while the return value is still
-set to `MHD_NO' in the callback function.
-
-Exercises
-=========
-
-   * By parsing the `url' string and delivering responses accordingly,
-     implement a small server for "virtual" files. When asked for
-     `/index.htm{l}', let the response consist of a HTML page
-     containing a link to `/another.html' page which is also to be
-     created "on the fly" in case of being requested. If neither of
-     these two pages are requested, `MHD_HTTP_NOT_FOUND' shall be
-     returned accompanied by an informative message.
-
-   * A very interesting information has still been ignored by our
-     logger--the client's IP address.  Implement a callback function static int on_client_connect (void *cls,
-                                   const struct sockaddr *addr,
-     			      socklen_t addrlen)
-      that prints out the IP address in an appropriate format. You
-     might want to use the POSIX function `inet_ntoa' but bear in mind
-     that `addr' is actually just a structure containing other
-     substructures and is _not_ the variable this function expects.
-     Make sure to return `MHD_YES' so that the library knows the client
-     is allowed to connect (and to then process the request). If one
-     wanted to limit access basing on IP addresses, this would be the
-     place to do it. The address of your `on_client_connect' function
-     must be passed as the third parameter to the `MHD_start_daemon'
-     call.
-
-
-
-File: libmicrohttpd-tutorial.info,  Node: Response headers,  Next: Supporting basic authentication,  Prev: Exploring requests,  Up: Top
-
-4 Response headers
-******************
-
-Now that we are able to inspect the incoming request in great detail,
-this chapter discusses the means to enrich the outgoing responses
-likewise.
-
-   As you have learned in the _Hello, Browser_ chapter, some obligatory
-header fields are added and set automatically for simple responses by
-the library itself but if more advanced features are desired,
-additional fields have to be created.  One of the possible fields is
-the content type field and an example will be developed around it.
-This will lead to an application capable of correctly serving different
-types of files.
-
-   When we responded with HTML page packed in the static string
-previously, the client had no choice but guessing about how to handle
-the response, because the server had not told him.  What if we had sent
-a picture or a sound file?  Would the message have been understood or
-merely been displayed as an endless stream of random characters in the
-browser?  This is what the mime content types are for. The header of
-the response is extended by certain information about how the data is
-to be interpreted.
-
-   To introduce the concept, a picture of the format _PNG_ will be sent
-to the client and labeled accordingly with `image/png'.  Once again, we
-can base the new example on the `hellobrowser' program.
-
-#define FILENAME "picture.png"
-#define MIMETYPE "image/png"
-
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-		      const char *url,
-                      const char *method, const char *version,
-		      const char *upload_data,
-              	      size_t *upload_data_size, void **con_cls)
-{
-  unsigned char *buffer = NULL;
-  struct MHD_Response *response;
- We want the program to open the file for reading and determine its
-size:
-  int fd;
-  int ret;
-  struct stat sbuf;
-
-  if (0 != strcmp (method, "GET"))
-    return MHD_NO;
-  if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
-       (0 != fstat (fd, &sbuf)) )
-    {
-     /* error accessing file */
-      /* ... (see below) */
-    }
- /* ... (see below) */
- When dealing with files, there is a lot that could go wrong on the
-server side and if so, the client should be informed with
-`MHD_HTTP_INTERNAL_SERVER_ERROR'.
-
-      /* error accessing file */
-     if (fd != -1) close (fd);
-      const char *errorstr =
-        "<html><body>An internal server error has occured!\
-                              </body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (errorstr),
-				         (void *) errorstr,
-				         MHD_RESPMEM_PERSISTENT);
-      if (response)
-        {
-          ret =
-            MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
-                                response);
-          MHD_destroy_response (response);
-
-          return MHD_YES;
-        }
-      else
-        return MHD_NO;
-  if (!ret)
-    {
-      const char *errorstr = "<html><body>An internal server error has occured!\
-                              </body></html>";
-
-      if (buffer) free(buffer);
-
-      response = MHD_create_response_from_buffer (strlen(errorstr), (void*) errorstr,
-                                                  MHD_RESPMEM_PERSISTENT);
-
-      if (response)
-        {
-          ret = MHD_queue_response (connection,
-	      			    MHD_HTTP_INTERNAL_SERVER_ERROR,
-				    response);
-          MHD_destroy_response (response);
-
-          return MHD_YES;
-        }
-      else return MHD_NO;
-    }
- Note that we nevertheless have to create a response object even for
-sending a simple error code.  Otherwise, the connection would just be
-closed without comment, leaving the client curious about what has
-happened.
-
-   But in the case of success a response will be constructed directly
-from the file descriptor:
-
-     /* error accessing file */
-     /* ... (see above) */
-    }
-
-  response =
-    MHD_create_response_from_fd_at_offset (sbuf.st_size, fd, 0);
-  MHD_add_response_header (response, "Content-Type", MIMETYPE);
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-  MHD_destroy_response (response);
- Note that the response object will take care of closing the file
-desciptor for us.
-
-   Up to this point, there was little new. The actual novelty is that
-we enhance the header with the meta data about the content. Aware of
-the field's name we want to add, it is as easy as that:
-MHD_add_response_header(response, "Content-Type", MIMETYPE);
- We do not have to append a colon expected by the protocol behind the
-first field--_GNU libhttpdmicro_ will take care of this.
-
-   The function finishes with the well-known lines
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-  MHD_destroy_response (response);
-  return ret;
-}
- The complete program `responseheaders.c' is in the `examples' section
-as usual.  Find a _PNG_ file you like and save it to the directory the
-example is run from under the name `picture.png'. You should find the
-image displayed on your browser if everything worked well.
-
-Remarks
-=======
-
-The include file of the _MHD_ library comes with the header types
-mentioned in _RFC 2616_ already defined as macros. Thus, we could have
-written `MHD_HTTP_HEADER_CONTENT_TYPE' instead of `"Content-Type"' as
-well. However, one is not limited to these standard headers and could
-add custom response headers without violating the protocol. Whether,
-and how, the client would react to these custom header is up to the
-receiver. Likewise, the client is allowed to send custom request
-headers to the server as well, opening up yet more possibilities how
-client and server could communicate with each other.
-
-   The method of creating the response from a file on disk only works
-for static content.  Serving dynamically created responses will be a
-topic of a future chapter.
-
-Exercises
-=========
-
-   * Remember that the original program was written under a few
-     assumptions--a static response using a local file being one of
-     them. In order to simulate a very large or hard to reach file that
-     cannot be provided instantly, postpone the queuing in the callback
-     with the `sleep' function for 30 seconds _if_ the file `/big.png'
-     is requested (but deliver the same as above). A request for
-     `/picture.png' should provide just the same but without any
-     artificial delays.
-
-     Now start two instances of your browser (or even use two machines)
-     and see how the second client is put on hold while the first waits
-     for his request on the slow file to be fulfilled.
-
-     Finally, change the sourcecode to use
-     `MHD_USE_THREAD_PER_CONNECTION' when the daemon is started and try
-     again.
-
-   * Did you succeed in implementing the clock exercise yet? This time,
-     let the server save the program's start time `t' and implement a
-     response simulating a countdown that reaches 0 at `t+60'.
-     Returning a message saying on which point the countdown is, the
-     response should ultimately be to reply "Done" if the program has
-     been running long enough,
-
-     An unofficial, but widely understood, response header line is
-     `Refresh: DELAY; url=URL' with the uppercase words substituted to
-     tell the client it should request the given resource after the
-     given delay again. Improve your program in that the browser (any
-     modern browser should work) automatically reconnects and asks for
-     the status again every 5 seconds or so. The URL would have to be
-     composed so that it begins with "http://", followed by the _URI_
-     the server is reachable from the client's point of view.
-
-     Maybe you want also to visualize the countdown as a status bar by
-     creating a `<table>' consisting of one row and `n' columns whose
-     fields contain small images of either a red or a green light.
-
-
-
-File: libmicrohttpd-tutorial.info,  Node: Supporting basic authentication,  Next: Processing POST data,  Prev: Response headers,  Up: Top
-
-5 Supporting basic authentication
-*********************************
-
-With the small exception of IP address based access control, requests
-from all connecting clients where served equally until now.  This
-chapter discusses a first method of client's authentication and its
-limits.
-
-   A very simple approach feasible with the means already discussed
-would be to expect the password in the _URI_ string before granting
-access to the secured areas. The password could be separated from the
-actual resource identifier by a certain character, thus the request
-line might look like
-GET /picture.png?mypassword
- In the rare situation where the client is customized enough and the
-connection occurs through secured lines (e.g., a embedded device
-directly attached to another via wire) and where the ability to embedd
-a password in the URI or to pass on a URI with a password are desired,
-this can be a reasonable choice.
-
-   But when it is assumed that the user connecting does so with an
-ordinary Internet browser, this implementation brings some problems
-about. For example, the URI including the password stays in the address
-field or at least in the history of the browser for anybody near enough
-to see.  It will also be inconvenient to add the password manually to
-any new URI when the browser does not know how to compose this
-automatically.
-
-   At least the convenience issue can be addressed by employing the
-simplest built-in password facilities of HTTP compliant browsers, hence
-we want to start there. It will however turn out to have still severe
-weaknesses in terms of security which need consideration.
-
-   Before we will start implementing _Basic Authentication_ as
-described in _RFC 2617_, we should finally abandon the bad practice of
-responding every request the first time our callback is called for a
-given connection. This is becoming more important now because the
-client and the server will have to talk in a more bi-directional way
-than before to
-
-   But how can we tell whether the callback has been called before for
-the particular connection?  Initially, the pointer this parameter
-references is set by _MHD_ in the callback. But it will also be
-"remembered" on the next call (for the same connection).  Thus, we will
-generate no response until the parameter is non-null--implying the
-callback was called before at least once. We do not need to share
-information between different calls of the callback, so we can set the
-parameter to any adress that is assured to be not null. The pointer to
-the `connection' structure will be pointing to a legal address, so we
-take this.
-
-   The first time `answer_to_connection' is called, we will not even
-look at the headers.
-
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-                      const char *url, const char *method, const char *version,
-                      const char *upload_data, size_t *upload_data_size,
-                      void **con_cls)
-{
-  if (0 != strcmp(method, "GET")) return MHD_NO;
-  if (NULL == *con_cls) {*con_cls = connection; return MHD_YES;}
-
-  ...
-  /* else respond accordingly */
-  ...
-}
- Note how we lop off the connection on the first condition (no "GET"
-request), but return asking for more on the other one with `MHD_YES'.
-With this minor change, we can proceed to implement the actual
-authentication process.
-
-Request for authentication
-==========================
-
-Let us assume we had only files not intended to be handed out without
-the correct username/password, so every "GET" request will be
-challenged.  _RFC 2617_ describes how the server shall ask for
-authentication by adding a _WWW-Authenticate_ response header with the
-name of the _realm_ protected.  MHD can generate and queue such a
-failure response for you using the `MHD_queue_basic_auth_fail_response'
-API.  The only thing you need to do is construct a response with the
-error page to be shown to the user if he aborts basic authentication.
-But first, you should check if the proper credentials were already
-supplied using the `MHD_basic_auth_get_username_password' call.
-
-   Your code would then look like this:
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-                      const char *url, const char *method,
-                      const char *version, const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
-{
-  char *user;
-  char *pass;
-  int fail;
-  struct MHD_Response *response;
-
-  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
-    return MHD_NO;
-  if (NULL == *con_cls)
-    {
-      *con_cls = connection;
-      return MHD_YES;
-    }
-  pass = NULL;
-  user = MHD_basic_auth_get_username_password (connection, &pass);
-  fail = ( (user == NULL) ||
-	   (0 != strcmp (user, "root")) ||
-	   (0 != strcmp (pass, "pa$$w0rd") ) );
-  if (user != NULL) free (user);
-  if (pass != NULL) free (pass);
-  if (fail)
-    {
-      const char *page = "<html><body>Go away.</body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (page), (void *) page,
-				       MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_basic_auth_fail_response (connection,
-						"my realm",
-						response);
-    }
-  else
-    {
-      const char *page = "<html><body>A secret.</body></html>";
-      response =
-	MHD_create_response_from_buffer (strlen (page), (void *) page,
-				       MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-    }
-  MHD_destroy_response (response);
-  return ret;
-}
-
-   See the `examples' directory for the complete example file.
-
-Remarks
-=======
-
-For a proper server, the conditional statements leading to a return of
-`MHD_NO' should yield a response with a more precise status code
-instead of silently closing the connection. For example, failures of
-memory allocation are best reported as _internal server error_ and
-unexpected authentication methods as _400 bad request_.
-
-Exercises
-=========
-
-   * Make the server respond to wrong credentials (but otherwise
-     well-formed requests) with the recommended _401 unauthorized_
-     status code. If the client still does not authenticate correctly
-     within the same connection, close it and store the client's IP
-     address for a certain time. (It is OK to check for expiration not
-     until the main thread wakes up again on the next connection.) If
-     the client fails authenticating three times during this period,
-     add it to another list for which the `AcceptPolicyCallback'
-     function denies connection (temporally).
-
-   * With the network utility `netcat' connect and log the response of
-     a "GET" request as you did in the exercise of the first example,
-     this time to a file. Now stop the server and let _netcat_ listen
-     on the same port the server used to listen on and have it fake
-     being the proper server by giving the file's content as the
-     response (e.g. `cat log | nc -l -p 8888'). Pretending to think
-     your were connecting to the actual server, browse to the
-     eavesdropper and give the correct credentials.
-
-     Copy and paste the encoded string you see in `netcat''s output to
-     some of the Base64 decode tools available online and see how both
-     the user's name and password could be completely restored.
-
-
-
-File: libmicrohttpd-tutorial.info,  Node: Processing POST data,  Next: Improved processing of POST data,  Prev: Supporting basic authentication,  Up: Top
-
-6 Processing POST data
-**********************
-
-The previous chapters already have demonstrated a variety of
-possibilities to send information to the HTTP server, but it is not
-recommended that the _GET_ method is used to alter the way the server
-operates. To induce changes on the server, the _POST_ method is
-preferred over and is much more powerful than _GET_ and will be
-introduced in this chapter.
-
-   We are going to write an application that asks for the visitor's
-name and, after the user has posted it, composes an individual response
-text. Even though it was not mandatory to use the _POST_ method here,
-as there is no permanent change caused by the POST, it is an
-illustrative example on how to share data between different functions
-for the same connection. Furthermore, the reader should be able to
-extend it easily.
-
-GET request
-===========
-
-When the first _GET_ request arrives, the server shall respond with a
-HTML page containing an edit field for the name.
-
-const char* askpage = "<html><body>\
-                       What's your name, Sir?<br>\
-                       <form action=\"/namepost\" method=\"post\">\
-                       <input name=\"name\" type=\"text\"\
-                       <input type=\"submit\" value=\" Send \"></form>\
-                       </body></html>";
- The `action' entry is the _URI_ to be called by the browser when
-posting, and the `name' will be used later to be sure it is the
-editbox's content that has been posted.
-
-   We also prepare the answer page, where the name is to be filled in
-later, and an error page as the response for anything but proper _GET_
-and _POST_ requests:
-
-const char* greatingpage="<html><body><h1>Welcome, %s!</center></h1></body></html>";
-
-const char* errorpage="<html><body>This doesn't seem to be right.</body></html>";
- Whenever we need to send a page, we use an extra function `int
-send_page(struct MHD_Connection *connection, const char* page)' for
-this, which does not contain anything new and whose implementation is
-therefore not discussed further in the tutorial.
-
-POST request
-============
-
-Posted data can be of arbitrary and considerable size; for example, if
-a user uploads a big image to the server. Similar to the case of the
-header fields, there may also be different streams of posted data, such
-as one containing the text of an editbox and another the state of a
-button.  Likewise, we will have to register an iterator function that
-is going to be called maybe several times not only if there are
-different POSTs but also if one POST has only been received partly yet
-and needs processing before another chunk can be received.
-
-   Such an iterator function is called by a _postprocessor_, which must
-be created upon arriving of the post request.  We want the iterator
-function to read the first post data which is tagged `name' and to
-create an individual greeting string based on the template and the name.
-But in order to pass this string to other functions and still be able
-to differentiate different connections, we must first define a
-structure to share the information, holding the most import entries.
-
-struct connection_info_struct
-{
-  int connectiontype;
-  char *answerstring;
-  struct MHD_PostProcessor *postprocessor;
-};
- With these information available to the iterator function, it is able
-to fulfill its task.  Once it has composed the greeting string, it
-returns `MHD_NO' to inform the post processor that it does not need to
-be called again. Note that this function does not handle processing of
-data for the same `key'. If we were to expect that the name will be
-posted in several chunks, we had to expand the namestring dynamically
-as additional parts of it with the same `key' came in. But in this
-example, the name is assumed to fit entirely inside one single packet.
-
-static int
-iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key,
-              const char *filename, const char *content_type,
-              const char *transfer_encoding, const char *data,
-	      uint64_t off, size_t size)
-{
-  struct connection_info_struct *con_info = coninfo_cls;
-
-  if (0 == strcmp (key, "name"))
-    {
-      if ((size > 0) && (size <= MAXNAMESIZE))
-        {
-          char *answerstring;
-          answerstring = malloc (MAXANSWERSIZE);
-          if (!answerstring) return MHD_NO;
-
-          snprintf (answerstring, MAXANSWERSIZE, greatingpage, data);
-          con_info->answerstring = answerstring;
-        }
-      else con_info->answerstring = NULL;
-
-      return MHD_NO;
-    }
-
-  return MHD_YES;
-}
- Once a connection has been established, it can be terminated for many
-reasons. As these reasons include unexpected events, we have to
-register another function that cleans up any resources that might have
-been allocated for that connection by us, namely the post processor and
-the greetings string. This cleanup function must take into account that
-it will also be called for finished requests other than _POST_ requests.
-
-void request_completed (void *cls, struct MHD_Connection *connection,
-     		        void **con_cls,
-                        enum MHD_RequestTerminationCode toe)
-{
-  struct connection_info_struct *con_info = *con_cls;
-
-  if (NULL == con_info) return;
-  if (con_info->connectiontype == POST)
-    {
-      MHD_destroy_post_processor (con_info->postprocessor);
-      if (con_info->answerstring) free (con_info->answerstring);
-    }
-
-  free (con_info);
-  *con_cls = NULL;
-}
- _GNU libmicrohttpd_ is informed that it shall call the above function
-when the daemon is started in the main function.
-
-...
-daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                           &answer_to_connection, NULL,
-			   MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL,
-			   MHD_OPTION_END);
-...
-
-Request handling
-================
-
-With all other functions prepared, we can now discuss the actual
-request handling.
-
-   On the first iteration for a new request, we start by allocating a
-new instance of a `struct connection_info_struct' structure, which will
-store all necessary information for later iterations and other
-functions.
-
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-		      const char *url,
-                      const char *method, const char *version,
-		      const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
-{
-  if(NULL == *con_cls)
-    {
-      struct connection_info_struct *con_info;
-
-      con_info = malloc (sizeof (struct connection_info_struct));
-      if (NULL == con_info) return MHD_NO;
-      con_info->answerstring = NULL;
- If the new request is a _POST_, the postprocessor must be created now.
-In addition, the type of the request is stored for convenience.
-      if (0 == strcmp (method, "POST"))
-        {
-          con_info->postprocessor
-	    = MHD_create_post_processor (connection, POSTBUFFERSIZE,
-                                         iterate_post, (void*) con_info);
-
-          if (NULL == con_info->postprocessor)
-            {
-              free (con_info);
-              return MHD_NO;
-            }
-          con_info->connectiontype = POST;
-        }
-      else con_info->connectiontype = GET;
- The address of our structure will both serve as the indicator for
-successive iterations and to remember the particular details about the
-connection.
-      *con_cls = (void*) con_info;
-      return MHD_YES;
-    }
- The rest of the function will not be executed on the first iteration.
-A _GET_ request is easily satisfied by sending the question form.
-  if (0 == strcmp (method, "GET"))
-    {
-      return send_page (connection, askpage);
-    }
- In case of _POST_, we invoke the post processor for as long as data
-keeps incoming, setting `*upload_data_size' to zero in order to
-indicate that we have processed--or at least have considered--all of it.
-  if (0 == strcmp (method, "POST"))
-    {
-      struct connection_info_struct *con_info = *con_cls;
-
-      if (*upload_data_size != 0)
-        {
-          MHD_post_process (con_info->postprocessor, upload_data,
-	                    *upload_data_size);
-          *upload_data_size = 0;
-
-          return MHD_YES;
-        }
-      else if (NULL != con_info->answerstring)
-        return send_page (connection, con_info->answerstring);
-    }
- Finally, if they are neither _GET_ nor _POST_ requests, the error page
-is returned.
-  return send_page(connection, errorpage);
-}
- These were the important parts of the program `simplepost.c'.
-
-
-File: libmicrohttpd-tutorial.info,  Node: Improved processing of POST data,  Next: Session management,  Prev: Processing POST data,  Up: Top
-
-7 Improved processing of POST data
-**********************************
-
-The previous chapter introduced a way to upload data to the server, but
-the developed example program has some shortcomings, such as not being
-able to handle larger chunks of data. In this chapter, we are going to
-discuss a more advanced server program that allows clients to upload a
-file in order to have it stored on the server's filesystem. The server
-shall also watch and limit the number of clients concurrently
-uploading, responding with a proper busy message if necessary.
-
-Prepared answers
-================
-
-We choose to operate the server with the `SELECT_INTERNALLY' method.
-This makes it easier to synchronize the global states at the cost of
-possible delays for other connections if the processing of a request is
-too slow. One of these variables that needs to be shared for all
-connections is the total number of clients that are uploading.
-
-#define MAXCLIENTS      2
-static unsigned int    nr_of_uploading_clients = 0;
- If there are too many clients uploading, we want the server to respond
-to all requests with a busy message.
-const char* busypage =
-  "<html><body>This server is busy, please try again later.</body></html>";
- Otherwise, the server will send a _form_ that informs the user of the
-current number of uploading clients, and ask her to pick a file on her
-local filesystem which is to be uploaded.
-const char* askpage = "<html><body>\n\
-                       Upload a file, please!<br>\n\
-                       There are %u clients uploading at the moment.<br>\n\
-                       <form action=\"/filepost\" method=\"post\" \
-                         enctype=\"multipart/form-data\">\n\
-                       <input name=\"file\" type=\"file\">\n\
-                       <input type=\"submit\" value=\" Send \"></form>\n\
-                       </body></html>";
- If the upload has succeeded, the server will respond with a message
-saying so.
-const char* completepage = "<html><body>The upload has been completed.</body></html>";
- We want the server to report internal errors, such as memory shortage
-or file access problems, adequately.
-const char* servererrorpage
-  = "<html><body>An internal server error has occured.</body></html>";
-const char* fileexistspage
-  = "<html><body>This file already exists.</body></html>";
- It would be tolerable to send all these responses undifferentiated
-with a `200 HTTP_OK' status code but in order to improve the `HTTP'
-conformance of our server a bit, we extend the `send_page' function so
-that it accepts individual status codes.
-
-static int
-send_page (struct MHD_Connection *connection,
-	   const char* page, int status_code)
-{
-  int ret;
-  struct MHD_Response *response;
-
-  response = MHD_create_response_from_buffer (strlen (page), (void*) page,
-  	     				      MHD_RESPMEM_MUST_COPY);
-  if (!response) return MHD_NO;
-
-  ret = MHD_queue_response (connection, status_code, response);
-  MHD_destroy_response (response);
-
-  return ret;
-}
- Note how we ask _MHD_ to make its own copy of the message data. The
-reason behind this will become clear later.
-
-Connection cycle
-================
-
-The decision whether the server is busy or not is made right at the
-beginning of the connection. To do that at this stage is especially
-important for _POST_ requests because if no response is queued at this
-point, and `MHD_YES' returned, _MHD_ will not sent any queued messages
-until a postprocessor has been created and the post iterator is called
-at least once.
-
-static int
-answer_to_connection (void *cls, struct MHD_Connection *connection,
-		      const char *url,
-                      const char *method, const char *version,
-		      const char *upload_data,
-                      size_t *upload_data_size, void **con_cls)
-{
-  if (NULL == *con_cls)
-    {
-      struct connection_info_struct *con_info;
-
-      if (nr_of_uploading_clients >= MAXCLIENTS)
-        return send_page(connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE);
- If the server is not busy, the `connection_info' structure is
-initialized as usual, with the addition of a filepointer for each
-connection.
-
-      con_info = malloc (sizeof (struct connection_info_struct));
-      if (NULL == con_info) return MHD_NO;
-      con_info->fp = 0;
-
-      if (0 == strcmp (method, "POST"))
-        {
-          ...
-        }
-      else con_info->connectiontype = GET;
-
-      *con_cls = (void*) con_info;
-
-      return MHD_YES;
-    }
- For _POST_ requests, the postprocessor is created and we register a
-new uploading client. From this point on, there are many possible
-places for errors to occur that make it necessary to interrupt the
-uploading process. We need a means of having the proper response
-message ready at all times.  Therefore, the `connection_info' structure
-is extended to hold the most current response message so that whenever
-a response is sent, the client will get the most informative message.
-Here, the structure is initialized to "no error".
-      if (0 == strcmp (method, "POST"))
-        {
-          con_info->postprocessor
-	    = MHD_create_post_processor (connection, POSTBUFFERSIZE,
-                                         iterate_post, (void*) con_info);
-
-          if (NULL == con_info->postprocessor)
-            {
-              free (con_info);
-              return MHD_NO;
-            }
-
-          nr_of_uploading_clients++;
-
-          con_info->connectiontype = POST;
-          con_info->answercode = MHD_HTTP_OK;
-          con_info->answerstring = completepage;
-        }
-      else con_info->connectiontype = GET;
- If the connection handler is called for the second time, _GET_
-requests will be answered with the _form_. We can keep the buffer under
-function scope, because we asked _MHD_ to make its own copy of it for
-as long as it is needed.
-  if (0 == strcmp (method, "GET"))
-    {
-      int ret;
-      char buffer[1024];
-
-      sprintf (buffer, askpage, nr_of_uploading_clients);
-      return send_page (connection, buffer, MHD_HTTP_OK);
-    }
- The rest of the `answer_to_connection' function is very similar to the
-`simplepost.c' example, except the more flexible content of the
-responses. The _POST_ data is processed until there is none left and
-the execution falls through to return an error page if the connection
-constituted no expected request method.
-  if (0 == strcmp (method, "POST"))
-    {
-      struct connection_info_struct *con_info = *con_cls;
-
-      if (0 != *upload_data_size)
-        {
-          MHD_post_process (con_info->postprocessor,
-	                    upload_data, *upload_data_size);
-          *upload_data_size = 0;
-
-          return MHD_YES;
-        }
-      else
-        return send_page (connection, con_info->answerstring,
-	       		  con_info->answercode);
-    }
-
-  return send_page(connection, errorpage, MHD_HTTP_BAD_REQUEST);
-}
-
-Storing to data
-===============
-
-Unlike the `simplepost.c' example, here it is to be expected that post
-iterator will be called several times now. This means that for any
-given connection (there might be several concurrent of them) the posted
-data has to be written to the correct file. That is why we store a file
-handle in every `connection_info', so that the it is preserved between
-successive iterations.
-static int
-iterate_post (void *coninfo_cls, enum MHD_ValueKind kind,
-	      const char *key,
-	      const char *filename, const char *content_type,
-              const char *transfer_encoding, const char *data,
-	      uint64_t off, size_t size)
-{
-  struct connection_info_struct *con_info = coninfo_cls;
- Because the following actions depend heavily on correct file
-processing, which might be error prone, we default to reporting
-internal errors in case anything will go wrong.
-
-con_info->answerstring = servererrorpage;
-con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR;
- In the "askpage" _form_, we told the client to label its post data
-with the "file" key. Anything else would be an error.
-
-  if (0 != strcmp (key, "file")) return MHD_NO;
- If the iterator is called for the first time, no file will have been
-opened yet. The `filename' string contains the name of the file
-(without any paths) the user selected on his system. We want to take
-this as the name the file will be stored on the server and make sure no
-file of that name exists (or is being uploaded) before we create one
-(note that the code below technically contains a race between the two
-"fopen" calls, but we will overlook this for portability sake).
-  if (!con_info->fp)
-    {
-      if (NULL != (fp = fopen (filename, "rb")) )
-        {
-          fclose (fp);
-          con_info->answerstring = fileexistspage;
-          con_info->answercode = MHD_HTTP_FORBIDDEN;
-          return MHD_NO;
-        }
-
-      con_info->fp = fopen (filename, "ab");
-      if (!con_info->fp) return MHD_NO;
-    }
- Occasionally, the iterator function will be called even when there are
-0 new bytes to process. The server only needs to write data to the file
-if there is some.
-if (size > 0)
-    {
-      if (!fwrite (data, size, sizeof(char), con_info->fp))
-        return MHD_NO;
-    }
- If this point has been reached, everything worked well for this
-iteration and the response can be set to success again. If the upload
-has finished, this iterator function will not be called again.
-  con_info->answerstring = completepage;
-  con_info->answercode = MHD_HTTP_OK;
-
-  return MHD_YES;
-}
- The new client was registered when the postprocessor was created.
-Likewise, we unregister the client on destroying the postprocessor when
-the request is completed.
-void request_completed (void *cls, struct MHD_Connection *connection,
-     		        void **con_cls,
-                        enum MHD_RequestTerminationCode toe)
-{
-  struct connection_info_struct *con_info = *con_cls;
-
-  if (NULL == con_info) return;
-
-  if (con_info->connectiontype == POST)
-    {
-      if (NULL != con_info->postprocessor)
-        {
-          MHD_destroy_post_processor (con_info->postprocessor);
-          nr_of_uploading_clients--;
-        }
-
-      if (con_info->fp) fclose (con_info->fp);
-    }
-
-  free (con_info);
-  *con_cls = NULL;
-}
- This is essentially the whole example `largepost.c'.
-
-Remarks
-=======
-
-Now that the clients are able to create files on the server, security
-aspects are becoming even more important than before. Aside from proper
-client authentication, the server should always make sure explicitly
-that no files will be created outside of a dedicated upload directory.
-In particular, filenames must be checked to not contain strings like
-"../".
-
-
-File: libmicrohttpd-tutorial.info,  Node: Session management,  Next: Adding a layer of security,  Prev: Improved processing of POST data,  Up: Top
-
-8 Session management
-********************
-
-This chapter discusses how one should manage sessions, that is, share
-state between multiple HTTP requests from the same user.  We use a
-simple example where the user submits multiple forms and the server is
-supposed to accumulate state from all of these forms.  Naturally, as
-this is a network protocol, our session mechanism must support having
-many users with many concurrent sessions at the same time.
-
-   In order to track users, we use a simple session cookie.  A session
-cookie expires when the user closes the browser.  Changing from session
-cookies to persistent cookies only requires adding an expiration time
-to the cookie.  The server creates a fresh session cookie whenever a
-request without a cookie is received, or if the supplied session cookie
-is not known to the server.
-
-Looking up the cookie
-=====================
-
-Since MHD parses the HTTP cookie header for us, looking up an existing
-cookie is straightforward:
-
-FIXME.
-
-   Here, FIXME is the name we chose for our session cookie.
-
-Setting the cookie header
-=========================
-
-MHD requires the user to provide the full cookie format string in order
-to set cookies.  In order to generate a unique cookie, our example
-creates a random 64-character text string to be used as the value of
-the cookie:
-
-FIXME.
-
-   Given this cookie value, we can then set the cookie header in our
-HTTP response as follows:
-
-FIXME.
-
-Remark: Session expiration
-==========================
-
-It is of course possible that clients stop their interaction with the
-server at any time.  In order to avoid using too much storage, the
-server must thus discard inactive sessions at some point.  Our example
-implements this by discarding inactive sessions after a certain amount
-of time.  Alternatively, the implementation may limit the total number
-of active sessions.  Which bounds are used for idle sessions or the
-total number of sessions obviously depends largely on the type of the
-application and available server resources.
-
-Example code
-============
-
-A sample application implementing a website with multiple forms (which
-are dynamically created using values from previous POST requests from
-the same session) is available as the example `sessions.c'.
-
-   Note that the example uses a simple, $O(n)$ linked list traversal to
-look up sessions and to expire old sessions.  Using a hash table and a
-heap would be more appropriate if a large number of concurrent sessions
-is expected.
-
-Remarks
-=======
-
-Naturally, it is quite conceivable to store session data in a database
-instead of in memory.  Still, having mechanisms to expire data
-associated with long-time idle sessions (where the business process has
-still not finished) is likely a good idea.
-
-
-File: libmicrohttpd-tutorial.info,  Node: Adding a layer of security,  Next: Bibliography,  Prev: Session management,  Up: Top
-
-9 Adding a layer of security
-****************************
-
-We left the basic authentication chapter with the unsatisfactory
-conclusion that any traffic, including the credentials, could be
-intercepted by anyone between the browser client and the server.
-Protecting the data while it is sent over unsecured lines will be the
-goal of this chapter.
-
-   Since version 0.4, the _MHD_ library includes support for encrypting
-the traffic by employing SSL/TSL. If _GNU libmicrohttpd_ has been
-configured to support these, encryption and decryption can be applied
-transparently on the data being sent, with only minimal changes to the
-actual source code of the example.
-
-Preparation
-===========
-
-First, a private key for the server will be generated. With this key,
-the server will later be able to authenticate itself to the
-client--preventing anyone else from stealing the password by faking its
-identity. The _OpenSSL_ suite, which is available on many operating
-systems, can generate such a key. For the scope of this tutorial, we
-will be content with a 1024 bit key:
-> openssl genrsa -out server.key 1024
- In addition to the key, a certificate describing the server in human
-readable tokens is also needed. This certificate will be attested with
-our aforementioned key. In this way, we obtain a self-signed
-certificate, valid for one year.
-
-> openssl req -days 365 -out server.pem -new -x509 -key server.key
- To avoid unnecessary error messages in the browser, the certificate
-needs to have a name that matches the _URI_, for example, "localhost"
-or the domain.  If you plan to have a publicly reachable server, you
-will need to ask a trusted third party, called _Certificate Authority_,
-or _CA_, to attest the certificate for you. This way, any visitor can
-make sure the server's identity is real.
-
-   Whether the server's certificate is signed by us or a third party,
-once it has been accepted by the client, both sides will be
-communicating over encrypted channels. From this point on, it is the
-client's turn to authenticate itself. But this has already been
-implemented in the basic authentication scheme.
-
-Changing the source code
-========================
-
-We merely have to extend the server program so that it loads the two
-files into memory,
-
-int
-main ()
-{
-  struct MHD_Daemon *daemon;
-  char *key_pem;
-  char *cert_pem;
-
-  key_pem = load_file (SERVERKEYFILE);
-  cert_pem = load_file (SERVERCERTFILE);
-
-  if ((key_pem == NULL) || (cert_pem == NULL))
-  {
-    printf ("The key/certificate files could not be read.\n");
-    return 1;
-  }
- and then we point the _MHD_ daemon to it upon initalization.
-
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL,
-  	   		     PORT, NULL, NULL,
-                             &answer_to_connection, NULL,
-                             MHD_OPTION_HTTPS_MEM_KEY, key_pem,
-                             MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
-                             MHD_OPTION_END);
-
-  if (NULL == daemon)
-    {
-      printf ("%s\n", cert_pem);
-
-      free (key_pem);
-      free (cert_pem);
-
-      return 1;
-    }
- The rest consists of little new besides some additional memory
-cleanups.
-
-  getchar ();
-
-  MHD_stop_daemon (daemon);
-  free (key_pem);
-  free (cert_pem);
-
-  return 0;
-}
- The rather unexciting file loader can be found in the complete example
-`tlsauthentication.c'.
-
-Remarks
-=======
-
-   * While the standard _HTTP_ port is 80, it is 443 for _HTTPS_. The
-     common internet browsers assume standard _HTTP_ if they are asked
-     to access other ports than these. Therefore, you will have to type
-     `https://localhost:8888' explicitly when you test the example, or
-     the browser will not know how to handle the answer properly.
-
-   * The remaining weak point is the question how the server will be
-     trusted initially. Either a _CA_ signs the certificate or the
-     client obtains the key over secure means. Anyway, the clients have
-     to be aware (or configured) that they should not accept
-     certificates of unknown origin.
-
-   * The introduced method of certificates makes it mandatory to set an
-     expiration date--making it less feasible to hardcode certificates
-     in embedded devices.
-
-   * The cryptographic facilities consume memory space and computing
-     time. For this reason, websites usually consists both of
-     uncritically _HTTP_ parts and secured _HTTPS_.
-
-
-Client authentication
-=====================
-
-You can also use MHD to authenticate the client via SSL/TLS certificates
-(as an alternative to using the password-based Basic or Digest
-authentication).  To do this, you will need to link your application
-against _gnutls_.  Next, when you start the MHD daemon, you must
-specify the root CA that you're willing to trust:
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL,
-  	   		     PORT, NULL, NULL,
-                             &answer_to_connection, NULL,
-                             MHD_OPTION_HTTPS_MEM_KEY, key_pem,
-                             MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
-			     MHD_OPTION_HTTPS_MEM_TRUST, root_ca_pem,
-                             MHD_OPTION_END);
-
-   With this, you can then obtain client certificates for each session.
-In order to obtain the identity of the client, you first need to obtain
-the raw GnuTLS session handle from _MHD_ using
-`MHD_get_connection_info'.
-
-#include <gnutls/gnutls.h>
-#include <gnutls/x509.h>
-
-gnutls_session_t tls_session;
-union MHD_ConnectionInfo *ci;
-
-ci = MHD_get_connection_info (connection,
-                              MHD_CONNECTION_INFO_GNUTLS_SESSION);
-tls_session = ci->tls_session;
-
-   You can then extract the client certificate:
-
-/**
- * Get the client's certificate
- *
- * @param tls_session the TLS session
- * @return NULL if no valid client certificate could be found, a pointer
- *  	to the certificate if found
- */
-static gnutls_x509_crt_t
-get_client_certificate (gnutls_session_t tls_session)
-{
-  unsigned int listsize;
-  const gnutls_datum_t * pcert;
-  gnutls_certificate_status_t client_cert_status;
-  gnutls_x509_crt_t client_cert;
-
-  if (tls_session == NULL)
-    return NULL;
-  if (gnutls_certificate_verify_peers2(tls_session,
-				       &client_cert_status))
-    return NULL;
-  pcert = gnutls_certificate_get_peers(tls_session,
-				       &listsize);
-  if ( (pcert == NULL) ||
-       (listsize == 0))
-    {
-      fprintf (stderr,
-	       "Failed to retrieve client certificate chain\n");
-      return NULL;
-    }
-  if (gnutls_x509_crt_init(&client_cert))
-    {
-      fprintf (stderr,
-	       "Failed to initialize client certificate\n");
-      return NULL;
-    }
-  /* Note that by passing values between 0 and listsize here, you
-     can get access to the CA's certs */
-  if (gnutls_x509_crt_import(client_cert,
-			     &pcert[0],
-			     GNUTLS_X509_FMT_DER))
-    {
-      fprintf (stderr,
-	       "Failed to import client certificate\n");
-      gnutls_x509_crt_deinit(client_cert);
-      return NULL;
-    }
-  return client_cert;
-}
-
-   Using the client certificate, you can then get the client's
-distinguished name and alternative names:
-
-/**
- * Get the distinguished name from the client's certificate
- *
- * @param client_cert the client certificate
- * @return NULL if no dn or certificate could be found, a pointer
- * 			to the dn if found
- */
-char *
-cert_auth_get_dn(gnutls_x509_crt_c client_cert)
-{
-  char* buf;
-  size_t lbuf;
-
-  lbuf = 0;
-  gnutls_x509_crt_get_dn(client_cert, NULL, &lbuf);
-  buf = malloc(lbuf);
-  if (buf == NULL)
-    {
-      fprintf (stderr,
-	       "Failed to allocate memory for certificate dn\n");
-      return NULL;
-    }
-  gnutls_x509_crt_get_dn(client_cert, buf, &lbuf);
-  return buf;
-}
-
-
-/**
- * Get the alternative name of specified type from the client's certificate
- *
- * @param client_cert the client certificate
- * @param nametype The requested name type
- * @param index The position of the alternative name if multiple names are
- * 			matching the requested type, 0 for the first matching name
- * @return NULL if no matching alternative name could be found, a pointer
- * 			to the alternative name if found
- */
-char *
-MHD_cert_auth_get_alt_name(gnutls_x509_crt_t client_cert,
-			   int nametype,
-			   unsigned int index)
-{
-  char* buf;
-  size_t lbuf;
-  unsigned int seq;
-  unsigned int subseq;
-  unsigned int type;
-  int result;
-
-  subseq = 0;
-  for (seq=0;;seq++)
-    {
-      lbuf = 0;
-      result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, NULL, &lbuf,
-						     &type, NULL);
-      if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
-	return NULL;
-      if (nametype != (int) type)
-	continue;
-      if (subseq == index)
-	break;
-      subseq++;
-    }
-  buf = malloc(lbuf);
-  if (buf == NULL)
-    {
-      fprintf (stderr,
-	       "Failed to allocate memory for certificate alt name\n");
-      return NULL;
-    }
-  result = gnutls_x509_crt_get_subject_alt_name2(client_cert,
-						 seq,
-						 buf,
-						 &lbuf,
-						 NULL, NULL);
-  if (result != nametype)
-    {
-      fprintf (stderr,
-	       "Unexpected return value from gnutls: %d\n",
-	       result);
-      free (buf);
-      return NULL;
-    }
-  return buf;
-}
-
-   Finally, you should release the memory associated with the client
-certificate:
-
-gnutls_x509_crt_deinit (client_cert);
-
-Using TLS Server Name Indication (SNI)
-======================================
-
-SNI enables hosting multiple domains under one IP address with TLS.  So
-SNI is the TLS-equivalent of virtual hosting.  To use SNI with MHD, you
-need at least GnuTLS 3.0.  The main change compared to the simple
-hosting of one domain is that you need to provide a callback instead of
-the key and certificate.  For example, when you start the MHD daemon,
-you could do this:
-  daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL,
-  	   		     PORT, NULL, NULL,
-                             &answer_to_connection, NULL,
-                             MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback,
-                             MHD_OPTION_END);
- Here, `sni_callback' is the name of a function that you will have to
-implement to retrieve the X.509 certificate for an incoming connection.
-The callback has type `gnutls_certificate_retrieve_function2' and is
-documented in the GnuTLS API for the
-`gnutls_certificate_set_retrieve_function2' as follows:
-
- -- Function Pointer: int *gnutls_certificate_retrieve_function2
-          (gnutls_session_t, const gnutls_datum_t* req_ca_dn, int
-          nreqs, const gnutls_pk_algorithm_t* pk_algos, int
-          pk_algos_length, gnutls_pcert_st** pcert, unsigned int
-          *pcert_length, gnutls_privkey_t * pkey)
-    REQ_CA_CERT
-          is only used in X.509 certificates. Contains a list with the
-          CA names that the server considers trusted. Normally we
-          should send a certificate that is signed by one of these CAs.
-          These names are DER encoded. To get a more meaningful value
-          use the function `gnutls_x509_rdn_get()'.
-
-    PK_ALGOS
-          contains a list with server’s acceptable signature
-          algorithms. The certificate returned should support the
-          server’s given algorithms.
-
-    PCERT
-          should contain a single certificate and public or a list of
-          them.
-
-    PCERT_LENGTH
-          is the size of the previous list.
-
-    PKEY
-          is the private key.
-
-   A possible implementation of this callback would look like this:
-
-struct Hosts
-{
-  struct Hosts *next;
-  const char *hostname;
-  gnutls_pcert_st pcrt;
-  gnutls_privkey_t key;
-};
-
-static struct Hosts *hosts;
-
-int
-sni_callback (gnutls_session_t session,
-              const gnutls_datum_t* req_ca_dn,
-              int nreqs,
-              const gnutls_pk_algorithm_t* pk_algos,
-              int pk_algos_length,
-              gnutls_pcert_st** pcert,
-              unsigned int *pcert_length,
-              gnutls_privkey_t * pkey)
-{
-  char name[256];
-  size_t name_len;
-  struct Hosts *host;
-  unsigned int type;
-
-  name_len = sizeof (name);
-  if (GNUTLS_E_SUCCESS !=
-      gnutls_server_name_get (session,
-                              name,
-                              &name_len,
-                              &type,
-                              0 /* index */))
-    return -1;
-  for (host = hosts; NULL != host; host = host->next)
-    if (0 == strncmp (name, host->hostname, name_len))
-      break;
-  if (NULL == host)
-    {
-      fprintf (stderr,
-               "Need certificate for %.*s\n",
-               (int) name_len,
-               name);
-      return -1;
-    }
-  fprintf (stderr,
-           "Returning certificate for %.*s\n",
-           (int) name_len,
-           name);
-  *pkey = host->key;
-  *pcert_length = 1;
-  *pcert = &host->pcrt;
-  return 0;
-}
-
-   Note that MHD cannot offer passing a closure or any other additional
-information to this callback, as the GnuTLS API unfortunately does not
-permit this at this point.
-
-   The `hosts' list can be initialized by loading the private keys and
-X.509 certificats from disk as follows:
-
-static void
-load_keys(const char *hostname,
-          const char *CERT_FILE,
-          const char *KEY_FILE)
-{
-  int ret;
-  gnutls_datum_t data;
-  struct Hosts *host;
-
-  host = malloc (sizeof (struct Hosts));
-  host->hostname = hostname;
-  host->next = hosts;
-  hosts = host;
-
-  ret = gnutls_load_file (CERT_FILE, &data);
-  if (ret < 0)
-  {
-    fprintf (stderr,
-             "*** Error loading certificate file %s.\n",
-             CERT_FILE);
-    exit(1);
-  }
-  ret =
-    gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM,
-                                  0);
-  if (ret < 0)
-  {
-    fprintf(stderr,
-            "*** Error loading certificate file: %s\n",
-            gnutls_strerror (ret));
-    exit(1);
-  }
-  gnutls_free (data.data);
-
-  ret = gnutls_load_file (KEY_FILE, &data);
-  if (ret < 0)
-  {
-    fprintf (stderr,
-             "*** Error loading key file %s.\n",
-             KEY_FILE);
-    exit(1);
-  }
-
-  gnutls_privkey_init (&host->key);
-  ret =
-    gnutls_privkey_import_x509_raw (host->key,
-                                    &data, GNUTLS_X509_FMT_PEM,
-                                    NULL, 0);
-  if (ret < 0)
-  {
-    fprintf (stderr,
-             "*** Error loading key file: %s\n",
-             gnutls_strerror (ret));
-    exit(1);
-  }
-  gnutls_free (data.data);
-}
-
-   The code above was largely lifted from GnuTLS.  You can find other
-methods for initializing certificates and keys in the GnuTLS manual and
-source code.
-
-
-File: libmicrohttpd-tutorial.info,  Node: Bibliography,  Next: License text,  Prev: Adding a layer of security,  Up: Top
-
-Appendix A Bibliography
-***********************
-
-API reference
-=============
-
-   * The _GNU libmicrohttpd_ manual by Marco Maggi and Christian
-     Grothoff 2008 `http://gnunet.org/libmicrohttpd/microhttpd.html'
-
-   * All referenced RFCs can be found on the website of _The Internet
-     Engineering Task Force_ `http://www.ietf.org/'
-
-   * _RFC 2616_: Fielding, R., Gettys, J., Mogul, J., Frystyk, H., and
-     T. Berners-Lee, "Hypertext Transfer Protocol - HTTP/1.1", RFC
-     2016, January 1997.
-
-   * _RFC 2617_: Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence,
-     S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication:
-     Basic and Digest Access Authentication", RFC 2617, June 1999.
-
-   * A well-structured _HTML_ reference can be found on
-     `http://www.echoecho.com/html.htm'
-
-     For those readers understanding German or French, there is an
-     excellent document both for learning _HTML_ and for reference,
-     whose English version unfortunately has been discontinued.
-     `http://de.selfhtml.org/' and `http://fr.selfhtml.org/'
-
-
-
-File: libmicrohttpd-tutorial.info,  Node: License text,  Next: Example programs,  Prev: Bibliography,  Up: Top
-
-Appendix B GNU Free Documentation License
-*****************************************
-
-                     Version 1.3, 3 November 2008
-
-     Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.
-     `http://fsf.org/'
-
-     Everyone is permitted to copy and distribute verbatim copies
-     of this license document, but changing it is not allowed.
-
-  0. PREAMBLE
-
-     The purpose of this License is to make a manual, textbook, or other
-     functional and useful document "free" in the sense of freedom: to
-     assure everyone the effective freedom to copy and redistribute it,
-     with or without modifying it, either commercially or
-     noncommercially.  Secondarily, this License preserves for the
-     author and publisher a way to get credit for their work, while not
-     being considered responsible for modifications made by others.
-
-     This License is a kind of "copyleft", which means that derivative
-     works of the document must themselves be free in the same sense.
-     It complements the GNU General Public License, which is a copyleft
-     license designed for free software.
-
-     We have designed this License in order to use it for manuals for
-     free software, because free software needs free documentation: a
-     free program should come with manuals providing the same freedoms
-     that the software does.  But this License is not limited to
-     software manuals; it can be used for any textual work, regardless
-     of subject matter or whether it is published as a printed book.
-     We recommend this License principally for works whose purpose is
-     instruction or reference.
-
-  1. APPLICABILITY AND DEFINITIONS
-
-     This License applies to any manual or other work, in any medium,
-     that contains a notice placed by the copyright holder saying it
-     can be distributed under the terms of this License.  Such a notice
-     grants a world-wide, royalty-free license, unlimited in duration,
-     to use that work under the conditions stated herein.  The
-     "Document", below, refers to any such manual or work.  Any member
-     of the public is a licensee, and is addressed as "you".  You
-     accept the license if you copy, modify or distribute the work in a
-     way requiring permission under copyright law.
-
-     A "Modified Version" of the Document means any work containing the
-     Document or a portion of it, either copied verbatim, or with
-     modifications and/or translated into another language.
-
-     A "Secondary Section" is a named appendix or a front-matter section
-     of the Document that deals exclusively with the relationship of the
-     publishers or authors of the Document to the Document's overall
-     subject (or to related matters) and contains nothing that could
-     fall directly within that overall subject.  (Thus, if the Document
-     is in part a textbook of mathematics, a Secondary Section may not
-     explain any mathematics.)  The relationship could be a matter of
-     historical connection with the subject or with related matters, or
-     of legal, commercial, philosophical, ethical or political position
-     regarding them.
-
-     The "Invariant Sections" are certain Secondary Sections whose
-     titles are designated, as being those of Invariant Sections, in
-     the notice that says that the Document is released under this
-     License.  If a section does not fit the above definition of
-     Secondary then it is not allowed to be designated as Invariant.
-     The Document may contain zero Invariant Sections.  If the Document
-     does not identify any Invariant Sections then there are none.
-
-     The "Cover Texts" are certain short passages of text that are
-     listed, as Front-Cover Texts or Back-Cover Texts, in the notice
-     that says that the Document is released under this License.  A
-     Front-Cover Text may be at most 5 words, and a Back-Cover Text may
-     be at most 25 words.
-
-     A "Transparent" copy of the Document means a machine-readable copy,
-     represented in a format whose specification is available to the
-     general public, that is suitable for revising the document
-     straightforwardly with generic text editors or (for images
-     composed of pixels) generic paint programs or (for drawings) some
-     widely available drawing editor, and that is suitable for input to
-     text formatters or for automatic translation to a variety of
-     formats suitable for input to text formatters.  A copy made in an
-     otherwise Transparent file format whose markup, or absence of
-     markup, has been arranged to thwart or discourage subsequent
-     modification by readers is not Transparent.  An image format is
-     not Transparent if used for any substantial amount of text.  A
-     copy that is not "Transparent" is called "Opaque".
-
-     Examples of suitable formats for Transparent copies include plain
-     ASCII without markup, Texinfo input format, LaTeX input format,
-     SGML or XML using a publicly available DTD, and
-     standard-conforming simple HTML, PostScript or PDF designed for
-     human modification.  Examples of transparent image formats include
-     PNG, XCF and JPG.  Opaque formats include proprietary formats that
-     can be read and edited only by proprietary word processors, SGML or
-     XML for which the DTD and/or processing tools are not generally
-     available, and the machine-generated HTML, PostScript or PDF
-     produced by some word processors for output purposes only.
-
-     The "Title Page" means, for a printed book, the title page itself,
-     plus such following pages as are needed to hold, legibly, the
-     material this License requires to appear in the title page.  For
-     works in formats which do not have any title page as such, "Title
-     Page" means the text near the most prominent appearance of the
-     work's title, preceding the beginning of the body of the text.
-
-     The "publisher" means any person or entity that distributes copies
-     of the Document to the public.
-
-     A section "Entitled XYZ" means a named subunit of the Document
-     whose title either is precisely XYZ or contains XYZ in parentheses
-     following text that translates XYZ in another language.  (Here XYZ
-     stands for a specific section name mentioned below, such as
-     "Acknowledgements", "Dedications", "Endorsements", or "History".)
-     To "Preserve the Title" of such a section when you modify the
-     Document means that it remains a section "Entitled XYZ" according
-     to this definition.
-
-     The Document may include Warranty Disclaimers next to the notice
-     which states that this License applies to the Document.  These
-     Warranty Disclaimers are considered to be included by reference in
-     this License, but only as regards disclaiming warranties: any other
-     implication that these Warranty Disclaimers may have is void and
-     has no effect on the meaning of this License.
-
-  2. VERBATIM COPYING
-
-     You may copy and distribute the Document in any medium, either
-     commercially or noncommercially, provided that this License, the
-     copyright notices, and the license notice saying this License
-     applies to the Document are reproduced in all copies, and that you
-     add no other conditions whatsoever to those of this License.  You
-     may not use technical measures to obstruct or control the reading
-     or further copying of the copies you make or distribute.  However,
-     you may accept compensation in exchange for copies.  If you
-     distribute a large enough number of copies you must also follow
-     the conditions in section 3.
-
-     You may also lend copies, under the same conditions stated above,
-     and you may publicly display copies.
-
-  3. COPYING IN QUANTITY
-
-     If you publish printed copies (or copies in media that commonly
-     have printed covers) of the Document, numbering more than 100, and
-     the Document's license notice requires Cover Texts, you must
-     enclose the copies in covers that carry, clearly and legibly, all
-     these Cover Texts: Front-Cover Texts on the front cover, and
-     Back-Cover Texts on the back cover.  Both covers must also clearly
-     and legibly identify you as the publisher of these copies.  The
-     front cover must present the full title with all words of the
-     title equally prominent and visible.  You may add other material
-     on the covers in addition.  Copying with changes limited to the
-     covers, as long as they preserve the title of the Document and
-     satisfy these conditions, can be treated as verbatim copying in
-     other respects.
-
-     If the required texts for either cover are too voluminous to fit
-     legibly, you should put the first ones listed (as many as fit
-     reasonably) on the actual cover, and continue the rest onto
-     adjacent pages.
-
-     If you publish or distribute Opaque copies of the Document
-     numbering more than 100, you must either include a
-     machine-readable Transparent copy along with each Opaque copy, or
-     state in or with each Opaque copy a computer-network location from
-     which the general network-using public has access to download
-     using public-standard network protocols a complete Transparent
-     copy of the Document, free of added material.  If you use the
-     latter option, you must take reasonably prudent steps, when you
-     begin distribution of Opaque copies in quantity, to ensure that
-     this Transparent copy will remain thus accessible at the stated
-     location until at least one year after the last time you
-     distribute an Opaque copy (directly or through your agents or
-     retailers) of that edition to the public.
-
-     It is requested, but not required, that you contact the authors of
-     the Document well before redistributing any large number of
-     copies, to give them a chance to provide you with an updated
-     version of the Document.
-
-  4. MODIFICATIONS
-
-     You may copy and distribute a Modified Version of the Document
-     under the conditions of sections 2 and 3 above, provided that you
-     release the Modified Version under precisely this License, with
-     the Modified Version filling the role of the Document, thus
-     licensing distribution and modification of the Modified Version to
-     whoever possesses a copy of it.  In addition, you must do these
-     things in the Modified Version:
-
-       A. Use in the Title Page (and on the covers, if any) a title
-          distinct from that of the Document, and from those of
-          previous versions (which should, if there were any, be listed
-          in the History section of the Document).  You may use the
-          same title as a previous version if the original publisher of
-          that version gives permission.
-
-       B. List on the Title Page, as authors, one or more persons or
-          entities responsible for authorship of the modifications in
-          the Modified Version, together with at least five of the
-          principal authors of the Document (all of its principal
-          authors, if it has fewer than five), unless they release you
-          from this requirement.
-
-       C. State on the Title page the name of the publisher of the
-          Modified Version, as the publisher.
-
-       D. Preserve all the copyright notices of the Document.
-
-       E. Add an appropriate copyright notice for your modifications
-          adjacent to the other copyright notices.
-
-       F. Include, immediately after the copyright notices, a license
-          notice giving the public permission to use the Modified
-          Version under the terms of this License, in the form shown in
-          the Addendum below.
-
-       G. Preserve in that license notice the full lists of Invariant
-          Sections and required Cover Texts given in the Document's
-          license notice.
-
-       H. Include an unaltered copy of this License.
-
-       I. Preserve the section Entitled "History", Preserve its Title,
-          and add to it an item stating at least the title, year, new
-          authors, and publisher of the Modified Version as given on
-          the Title Page.  If there is no section Entitled "History" in
-          the Document, create one stating the title, year, authors,
-          and publisher of the Document as given on its Title Page,
-          then add an item describing the Modified Version as stated in
-          the previous sentence.
-
-       J. Preserve the network location, if any, given in the Document
-          for public access to a Transparent copy of the Document, and
-          likewise the network locations given in the Document for
-          previous versions it was based on.  These may be placed in
-          the "History" section.  You may omit a network location for a
-          work that was published at least four years before the
-          Document itself, or if the original publisher of the version
-          it refers to gives permission.
-
-       K. For any section Entitled "Acknowledgements" or "Dedications",
-          Preserve the Title of the section, and preserve in the
-          section all the substance and tone of each of the contributor
-          acknowledgements and/or dedications given therein.
-
-       L. Preserve all the Invariant Sections of the Document,
-          unaltered in their text and in their titles.  Section numbers
-          or the equivalent are not considered part of the section
-          titles.
-
-       M. Delete any section Entitled "Endorsements".  Such a section
-          may not be included in the Modified Version.
-
-       N. Do not retitle any existing section to be Entitled
-          "Endorsements" or to conflict in title with any Invariant
-          Section.
-
-       O. Preserve any Warranty Disclaimers.
-
-     If the Modified Version includes new front-matter sections or
-     appendices that qualify as Secondary Sections and contain no
-     material copied from the Document, you may at your option
-     designate some or all of these sections as invariant.  To do this,
-     add their titles to the list of Invariant Sections in the Modified
-     Version's license notice.  These titles must be distinct from any
-     other section titles.
-
-     You may add a section Entitled "Endorsements", provided it contains
-     nothing but endorsements of your Modified Version by various
-     parties--for example, statements of peer review or that the text
-     has been approved by an organization as the authoritative
-     definition of a standard.
-
-     You may add a passage of up to five words as a Front-Cover Text,
-     and a passage of up to 25 words as a Back-Cover Text, to the end
-     of the list of Cover Texts in the Modified Version.  Only one
-     passage of Front-Cover Text and one of Back-Cover Text may be
-     added by (or through arrangements made by) any one entity.  If the
-     Document already includes a cover text for the same cover,
-     previously added by you or by arrangement made by the same entity
-     you are acting on behalf of, you may not add another; but you may
-     replace the old one, on explicit permission from the previous
-     publisher that added the old one.
-
-     The author(s) and publisher(s) of the Document do not by this
-     License give permission to use their names for publicity for or to
-     assert or imply endorsement of any Modified Version.
-
-  5. COMBINING DOCUMENTS
-
-     You may combine the Document with other documents released under
-     this License, under the terms defined in section 4 above for
-     modified versions, provided that you include in the combination
-     all of the Invariant Sections of all of the original documents,
-     unmodified, and list them all as Invariant Sections of your
-     combined work in its license notice, and that you preserve all
-     their Warranty Disclaimers.
-
-     The combined work need only contain one copy of this License, and
-     multiple identical Invariant Sections may be replaced with a single
-     copy.  If there are multiple Invariant Sections with the same name
-     but different contents, make the title of each such section unique
-     by adding at the end of it, in parentheses, the name of the
-     original author or publisher of that section if known, or else a
-     unique number.  Make the same adjustment to the section titles in
-     the list of Invariant Sections in the license notice of the
-     combined work.
-
-     In the combination, you must combine any sections Entitled
-     "History" in the various original documents, forming one section
-     Entitled "History"; likewise combine any sections Entitled
-     "Acknowledgements", and any sections Entitled "Dedications".  You
-     must delete all sections Entitled "Endorsements."
-
-  6. COLLECTIONS OF DOCUMENTS
-
-     You may make a collection consisting of the Document and other
-     documents released under this License, and replace the individual
-     copies of this License in the various documents with a single copy
-     that is included in the collection, provided that you follow the
-     rules of this License for verbatim copying of each of the
-     documents in all other respects.
-
-     You may extract a single document from such a collection, and
-     distribute it individually under this License, provided you insert
-     a copy of this License into the extracted document, and follow
-     this License in all other respects regarding verbatim copying of
-     that document.
-
-  7. AGGREGATION WITH INDEPENDENT WORKS
-
-     A compilation of the Document or its derivatives with other
-     separate and independent documents or works, in or on a volume of
-     a storage or distribution medium, is called an "aggregate" if the
-     copyright resulting from the compilation is not used to limit the
-     legal rights of the compilation's users beyond what the individual
-     works permit.  When the Document is included in an aggregate, this
-     License does not apply to the other works in the aggregate which
-     are not themselves derivative works of the Document.
-
-     If the Cover Text requirement of section 3 is applicable to these
-     copies of the Document, then if the Document is less than one half
-     of the entire aggregate, the Document's Cover Texts may be placed
-     on covers that bracket the Document within the aggregate, or the
-     electronic equivalent of covers if the Document is in electronic
-     form.  Otherwise they must appear on printed covers that bracket
-     the whole aggregate.
-
-  8. TRANSLATION
-
-     Translation is considered a kind of modification, so you may
-     distribute translations of the Document under the terms of section
-     4.  Replacing Invariant Sections with translations requires special
-     permission from their copyright holders, but you may include
-     translations of some or all Invariant Sections in addition to the
-     original versions of these Invariant Sections.  You may include a
-     translation of this License, and all the license notices in the
-     Document, and any Warranty Disclaimers, provided that you also
-     include the original English version of this License and the
-     original versions of those notices and disclaimers.  In case of a
-     disagreement between the translation and the original version of
-     this License or a notice or disclaimer, the original version will
-     prevail.
-
-     If a section in the Document is Entitled "Acknowledgements",
-     "Dedications", or "History", the requirement (section 4) to
-     Preserve its Title (section 1) will typically require changing the
-     actual title.
-
-  9. TERMINATION
-
-     You may not copy, modify, sublicense, or distribute the Document
-     except as expressly provided under this License.  Any attempt
-     otherwise to copy, modify, sublicense, or distribute it is void,
-     and will automatically terminate your rights under this License.
-
-     However, if you cease all violation of this License, then your
-     license from a particular copyright holder is reinstated (a)
-     provisionally, unless and until the copyright holder explicitly
-     and finally terminates your license, and (b) permanently, if the
-     copyright holder fails to notify you of the violation by some
-     reasonable means prior to 60 days after the cessation.
-
-     Moreover, your license from a particular copyright holder is
-     reinstated permanently if the copyright holder notifies you of the
-     violation by some reasonable means, this is the first time you have
-     received notice of violation of this License (for any work) from
-     that copyright holder, and you cure the violation prior to 30 days
-     after your receipt of the notice.
-
-     Termination of your rights under this section does not terminate
-     the licenses of parties who have received copies or rights from
-     you under this License.  If your rights have been terminated and
-     not permanently reinstated, receipt of a copy of some or all of
-     the same material does not give you any rights to use it.
-
- 10. FUTURE REVISIONS OF THIS LICENSE
-
-     The Free Software Foundation may publish new, revised versions of
-     the GNU Free Documentation License from time to time.  Such new
-     versions will be similar in spirit to the present version, but may
-     differ in detail to address new problems or concerns.  See
-     `http://www.gnu.org/copyleft/'.
-
-     Each version of the License is given a distinguishing version
-     number.  If the Document specifies that a particular numbered
-     version of this License "or any later version" applies to it, you
-     have the option of following the terms and conditions either of
-     that specified version or of any later version that has been
-     published (not as a draft) by the Free Software Foundation.  If
-     the Document does not specify a version number of this License,
-     you may choose any version ever published (not as a draft) by the
-     Free Software Foundation.  If the Document specifies that a proxy
-     can decide which future versions of this License can be used, that
-     proxy's public statement of acceptance of a version permanently
-     authorizes you to choose that version for the Document.
-
- 11. RELICENSING
-
-     "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
-     World Wide Web server that publishes copyrightable works and also
-     provides prominent facilities for anybody to edit those works.  A
-     public wiki that anybody can edit is an example of such a server.
-     A "Massive Multiauthor Collaboration" (or "MMC") contained in the
-     site means any set of copyrightable works thus published on the MMC
-     site.
-
-     "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
-     license published by Creative Commons Corporation, a not-for-profit
-     corporation with a principal place of business in San Francisco,
-     California, as well as future copyleft versions of that license
-     published by that same organization.
-
-     "Incorporate" means to publish or republish a Document, in whole or
-     in part, as part of another Document.
-
-     An MMC is "eligible for relicensing" if it is licensed under this
-     License, and if all works that were first published under this
-     License somewhere other than this MMC, and subsequently
-     incorporated in whole or in part into the MMC, (1) had no cover
-     texts or invariant sections, and (2) were thus incorporated prior
-     to November 1, 2008.
-
-     The operator of an MMC Site may republish an MMC contained in the
-     site under CC-BY-SA on the same site at any time before August 1,
-     2009, provided the MMC is eligible for relicensing.
-
-
-ADDENDUM: How to use this License for your documents
-====================================================
-
-To use this License in a document you have written, include a copy of
-the License in the document and put the following copyright and license
-notices just after the title page:
-
-       Copyright (C)  YEAR  YOUR NAME.
-       Permission is granted to copy, distribute and/or modify this document
-       under the terms of the GNU Free Documentation License, Version 1.3
-       or any later version published by the Free Software Foundation;
-       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
-       Texts.  A copy of the license is included in the section entitled ``GNU
-       Free Documentation License''.
-
-   If you have Invariant Sections, Front-Cover Texts and Back-Cover
-Texts, replace the "with...Texts." line with this:
-
-         with the Invariant Sections being LIST THEIR TITLES, with
-         the Front-Cover Texts being LIST, and with the Back-Cover Texts
-         being LIST.
-
-   If you have Invariant Sections without Cover Texts, or some other
-combination of the three, merge those two alternatives to suit the
-situation.
-
-   If your document contains nontrivial examples of program code, we
-recommend releasing these examples in parallel under your choice of
-free software license, such as the GNU General Public License, to
-permit their use in free software.
-
-
-File: libmicrohttpd-tutorial.info,  Node: Example programs,  Prev: License text,  Up: Top
-
-Appendix C Example programs
-***************************
-
-* Menu:
-
-* hellobrowser.c::
-* logging.c::
-* responseheaders.c::
-* basicauthentication.c::
-* simplepost.c::
-* largepost.c::
-* sessions.c::
-* tlsauthentication.c::
-
-
-File: libmicrohttpd-tutorial.info,  Node: hellobrowser.c,  Next: logging.c,  Up: Example programs
-
-C.1 hellobrowser.c
-==================
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <string.h>
-     #include <microhttpd.h>
-     #include <stdio.h>
-
-     #define PORT 8888
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       const char *page = "<html><body>Hello, browser!</body></html>";
-       struct MHD_Response *response;
-       int ret;
-
-       response =
-         MHD_create_response_from_buffer (strlen (page), (void *) page,
-     				     MHD_RESPMEM_PERSISTENT);
-       ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-       MHD_destroy_response (response);
-
-       return ret;
-     }
-
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-
-       daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                                  &answer_to_connection, NULL, MHD_OPTION_END);
-       if (NULL == daemon)
-         return 1;
-
-       (void) getchar ();
-
-       MHD_stop_daemon (daemon);
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: logging.c,  Next: responseheaders.c,  Prev: hellobrowser.c,  Up: Example programs
-
-C.2 logging.c
-=============
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <microhttpd.h>
-     #include <stdio.h>
-
-     #define PORT 8888
-
-
-     static int
-     print_out_key (void *cls, enum MHD_ValueKind kind, const char *key,
-                    const char *value)
-     {
-       printf ("%s: %s\n", key, value);
-       return MHD_YES;
-     }
-
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       printf ("New %s request for %s using version %s\n", method, url, version);
-
-       MHD_get_connection_values (connection, MHD_HEADER_KIND, print_out_key,
-                                  NULL);
-
-       return MHD_NO;
-     }
-
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-
-       daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                                  &answer_to_connection, NULL, MHD_OPTION_END);
-       if (NULL == daemon)
-         return 1;
-
-       (void) getchar ();
-
-       MHD_stop_daemon (daemon);
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: responseheaders.c,  Next: basicauthentication.c,  Prev: logging.c,  Up: Example programs
-
-C.3 responseheaders.c
-=====================
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <microhttpd.h>
-     #include <time.h>
-     #include <sys/stat.h>
-     #include <fcntl.h>
-     #include <string.h>
-     #include <stdio.h>
-
-     #define PORT 8888
-     #define FILENAME "picture.png"
-     #define MIMETYPE "image/png"
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       struct MHD_Response *response;
-       int fd;
-       int ret;
-       struct stat sbuf;
-
-       if (0 != strcmp (method, "GET"))
-         return MHD_NO;
-
-       if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
-            (0 != fstat (fd, &sbuf)) )
-         {
-           /* error accessing file */
-           if (fd != -1)
-     	(void) close (fd);
-           const char *errorstr =
-             "<html><body>An internal server error has occured!\
-                                   </body></html>";
-           response =
-     	MHD_create_response_from_buffer (strlen (errorstr),
-     					 (void *) errorstr,
-     					 MHD_RESPMEM_PERSISTENT);
-           if (NULL != response)
-             {
-               ret =
-                 MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
-                                     response);
-               MHD_destroy_response (response);
-
-               return ret;
-             }
-           else
-             return MHD_NO;
-         }
-       response =
-         MHD_create_response_from_fd_at_offset (sbuf.st_size, fd, 0);
-       MHD_add_response_header (response, "Content-Type", MIMETYPE);
-       ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-       MHD_destroy_response (response);
-
-       return ret;
-     }
-
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-
-       daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                                  &answer_to_connection, NULL, MHD_OPTION_END);
-       if (NULL == daemon)
-         return 1;
-
-       (void) getchar ();
-
-       MHD_stop_daemon (daemon);
-
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: basicauthentication.c,  Next: simplepost.c,  Prev: responseheaders.c,  Up: Example programs
-
-C.4 basicauthentication.c
-=========================
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <microhttpd.h>
-     #include <time.h>
-     #include <string.h>
-     #include <stdlib.h>
-     #include <stdio.h>
-
-     #define PORT 8888
-
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       char *user;
-       char *pass;
-       int fail;
-       int ret;
-       struct MHD_Response *response;
-
-       if (0 != strcmp (method, "GET"))
-         return MHD_NO;
-       if (NULL == *con_cls)
-         {
-           *con_cls = connection;
-           return MHD_YES;
-         }
-       pass = NULL;
-       user = MHD_basic_auth_get_username_password (connection, &pass);
-       fail = ( (user == NULL) ||
-     	   (0 != strcmp (user, "root")) ||
-     	   (0 != strcmp (pass, "pa$$w0rd") ) );
-       if (user != NULL) free (user);
-       if (pass != NULL) free (pass);
-       if (fail)
-         {
-           const char *page = "<html><body>Go away.</body></html>";
-           response =
-     	MHD_create_response_from_buffer (strlen (page), (void *) page,
-     					 MHD_RESPMEM_PERSISTENT);
-           ret = MHD_queue_basic_auth_fail_response (connection,
-     						"my realm",
-     						response);
-         }
-       else
-         {
-           const char *page = "<html><body>A secret.</body></html>";
-           response =
-     	MHD_create_response_from_buffer (strlen (page), (void *) page,
-     					 MHD_RESPMEM_PERSISTENT);
-           ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-         }
-       MHD_destroy_response (response);
-       return ret;
-     }
-
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-
-       daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                                  &answer_to_connection, NULL, MHD_OPTION_END);
-       if (NULL == daemon)
-         return 1;
-
-       (void) getchar ();
-
-       MHD_stop_daemon (daemon);
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: simplepost.c,  Next: largepost.c,  Prev: basicauthentication.c,  Up: Example programs
-
-C.5 simplepost.c
-================
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <microhttpd.h>
-     #include <stdio.h>
-     #include <string.h>
-     #include <stdlib.h>
-
-     #define PORT            8888
-     #define POSTBUFFERSIZE  512
-     #define MAXNAMESIZE     20
-     #define MAXANSWERSIZE   512
-
-     #define GET             0
-     #define POST            1
-
-     struct connection_info_struct
-     {
-       int connectiontype;
-       char *answerstring;
-       struct MHD_PostProcessor *postprocessor;
-     };
-
-     const char *askpage = "<html><body>\
-                            What's your name, Sir?<br>\
-                            <form action=\"/namepost\" method=\"post\">\
-                            <input name=\"name\" type=\"text\"\
-                            <input type=\"submit\" value=\" Send \"></form>\
-                            </body></html>";
-
-     const char *greetingpage =
-       "<html><body><h1>Welcome, %s!</center></h1></body></html>";
-
-     const char *errorpage =
-       "<html><body>This doesn't seem to be right.</body></html>";
-
-
-     static int
-     send_page (struct MHD_Connection *connection, const char *page)
-     {
-       int ret;
-       struct MHD_Response *response;
-
-
-       response =
-         MHD_create_response_from_buffer (strlen (page), (void *) page,
-     				     MHD_RESPMEM_PERSISTENT);
-       if (!response)
-         return MHD_NO;
-
-       ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-       MHD_destroy_response (response);
-
-       return ret;
-     }
-
-
-     static int
-     iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key,
-                   const char *filename, const char *content_type,
-                   const char *transfer_encoding, const char *data, uint64_t off,
-                   size_t size)
-     {
-       struct connection_info_struct *con_info = coninfo_cls;
-
-       if (0 == strcmp (key, "name"))
-         {
-           if ((size > 0) && (size <= MAXNAMESIZE))
-             {
-               char *answerstring;
-               answerstring = malloc (MAXANSWERSIZE);
-               if (!answerstring)
-                 return MHD_NO;
-
-               snprintf (answerstring, MAXANSWERSIZE, greetingpage, data);
-               con_info->answerstring = answerstring;
-             }
-           else
-             con_info->answerstring = NULL;
-
-           return MHD_NO;
-         }
-
-       return MHD_YES;
-     }
-
-     static void
-     request_completed (void *cls, struct MHD_Connection *connection,
-                        void **con_cls, enum MHD_RequestTerminationCode toe)
-     {
-       struct connection_info_struct *con_info = *con_cls;
-
-       if (NULL == con_info)
-         return;
-
-       if (con_info->connectiontype == POST)
-         {
-           MHD_destroy_post_processor (con_info->postprocessor);
-           if (con_info->answerstring)
-             free (con_info->answerstring);
-         }
-
-       free (con_info);
-       *con_cls = NULL;
-     }
-
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       if (NULL == *con_cls)
-         {
-           struct connection_info_struct *con_info;
-
-           con_info = malloc (sizeof (struct connection_info_struct));
-           if (NULL == con_info)
-             return MHD_NO;
-           con_info->answerstring = NULL;
-
-           if (0 == strcmp (method, "POST"))
-             {
-               con_info->postprocessor =
-                 MHD_create_post_processor (connection, POSTBUFFERSIZE,
-                                            iterate_post, (void *) con_info);
-
-               if (NULL == con_info->postprocessor)
-                 {
-                   free (con_info);
-                   return MHD_NO;
-                 }
-
-               con_info->connectiontype = POST;
-             }
-           else
-             con_info->connectiontype = GET;
-
-           *con_cls = (void *) con_info;
-
-           return MHD_YES;
-         }
-
-       if (0 == strcmp (method, "GET"))
-         {
-           return send_page (connection, askpage);
-         }
-
-       if (0 == strcmp (method, "POST"))
-         {
-           struct connection_info_struct *con_info = *con_cls;
-
-           if (*upload_data_size != 0)
-             {
-               MHD_post_process (con_info->postprocessor, upload_data,
-                                 *upload_data_size);
-               *upload_data_size = 0;
-
-               return MHD_YES;
-             }
-           else if (NULL != con_info->answerstring)
-             return send_page (connection, con_info->answerstring);
-         }
-
-       return send_page (connection, errorpage);
-     }
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-
-       daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                                  &answer_to_connection, NULL,
-                                  MHD_OPTION_NOTIFY_COMPLETED, request_completed,
-                                  NULL, MHD_OPTION_END);
-       if (NULL == daemon)
-         return 1;
-
-       (void) getchar ();
-
-       MHD_stop_daemon (daemon);
-
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: largepost.c,  Next: sessions.c,  Prev: simplepost.c,  Up: Example programs
-
-C.6 largepost.c
-===============
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <stdio.h>
-     #include <stdlib.h>
-     #include <string.h>
-     #include <microhttpd.h>
-
-     #define PORT            8888
-     #define POSTBUFFERSIZE  512
-     #define MAXCLIENTS      2
-
-     #define GET             0
-     #define POST            1
-
-     static unsigned int nr_of_uploading_clients = 0;
-
-     struct connection_info_struct
-     {
-       int connectiontype;
-       struct MHD_PostProcessor *postprocessor;
-       FILE *fp;
-       const char *answerstring;
-       int answercode;
-     };
-
-     const char *askpage = "<html><body>\n\
-                            Upload a file, please!<br>\n\
-                            There are %u clients uploading at the moment.<br>\n\
-                            <form action=\"/filepost\" method=\"post\" enctype=\"multipart/form-data\">\n\
-                            <input name=\"file\" type=\"file\">\n\
-                            <input type=\"submit\" value=\" Send \"></form>\n\
-                            </body></html>";
-
-     const char *busypage =
-       "<html><body>This server is busy, please try again later.</body></html>";
-
-     const char *completepage =
-       "<html><body>The upload has been completed.</body></html>";
-
-     const char *errorpage =
-       "<html><body>This doesn't seem to be right.</body></html>";
-     const char *servererrorpage =
-       "<html><body>An internal server error has occured.</body></html>";
-     const char *fileexistspage =
-       "<html><body>This file already exists.</body></html>";
-
-
-     static int
-     send_page (struct MHD_Connection *connection, const char *page,
-                int status_code)
-     {
-       int ret;
-       struct MHD_Response *response;
-
-       response =
-         MHD_create_response_from_buffer (strlen (page), (void *) page,
-     				     MHD_RESPMEM_MUST_COPY);
-       if (!response)
-         return MHD_NO;
-       MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html");
-       ret = MHD_queue_response (connection, status_code, response);
-       MHD_destroy_response (response);
-
-       return ret;
-     }
-
-
-     static int
-     iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key,
-                   const char *filename, const char *content_type,
-                   const char *transfer_encoding, const char *data, uint64_t off,
-                   size_t size)
-     {
-       struct connection_info_struct *con_info = coninfo_cls;
-       FILE *fp;
-
-       con_info->answerstring = servererrorpage;
-       con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR;
-
-       if (0 != strcmp (key, "file"))
-         return MHD_NO;
-
-       if (!con_info->fp)
-         {
-           if (NULL != (fp = fopen (filename, "rb")))
-             {
-               fclose (fp);
-               con_info->answerstring = fileexistspage;
-               con_info->answercode = MHD_HTTP_FORBIDDEN;
-               return MHD_NO;
-             }
-
-           con_info->fp = fopen (filename, "ab");
-           if (!con_info->fp)
-             return MHD_NO;
-         }
-
-       if (size > 0)
-         {
-           if (!fwrite (data, size, sizeof (char), con_info->fp))
-             return MHD_NO;
-         }
-
-       con_info->answerstring = completepage;
-       con_info->answercode = MHD_HTTP_OK;
-
-       return MHD_YES;
-     }
-
-
-     static void
-     request_completed (void *cls, struct MHD_Connection *connection,
-                        void **con_cls, enum MHD_RequestTerminationCode toe)
-     {
-       struct connection_info_struct *con_info = *con_cls;
-
-       if (NULL == con_info)
-         return;
-
-       if (con_info->connectiontype == POST)
-         {
-           if (NULL != con_info->postprocessor)
-             {
-               MHD_destroy_post_processor (con_info->postprocessor);
-               nr_of_uploading_clients--;
-             }
-
-           if (con_info->fp)
-             fclose (con_info->fp);
-         }
-
-       free (con_info);
-       *con_cls = NULL;
-     }
-
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       if (NULL == *con_cls)
-         {
-           struct connection_info_struct *con_info;
-
-           if (nr_of_uploading_clients >= MAXCLIENTS)
-             return send_page (connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE);
-
-           con_info = malloc (sizeof (struct connection_info_struct));
-           if (NULL == con_info)
-             return MHD_NO;
-
-           con_info->fp = NULL;
-
-           if (0 == strcmp (method, "POST"))
-             {
-               con_info->postprocessor =
-                 MHD_create_post_processor (connection, POSTBUFFERSIZE,
-                                            iterate_post, (void *) con_info);
-
-               if (NULL == con_info->postprocessor)
-                 {
-                   free (con_info);
-                   return MHD_NO;
-                 }
-
-               nr_of_uploading_clients++;
-
-               con_info->connectiontype = POST;
-               con_info->answercode = MHD_HTTP_OK;
-               con_info->answerstring = completepage;
-             }
-           else
-             con_info->connectiontype = GET;
-
-           *con_cls = (void *) con_info;
-
-           return MHD_YES;
-         }
-
-       if (0 == strcmp (method, "GET"))
-         {
-           char buffer[1024];
-
-           snprintf (buffer, sizeof (buffer), askpage, nr_of_uploading_clients);
-           return send_page (connection, buffer, MHD_HTTP_OK);
-         }
-
-       if (0 == strcmp (method, "POST"))
-         {
-           struct connection_info_struct *con_info = *con_cls;
-
-           if (0 != *upload_data_size)
-             {
-               MHD_post_process (con_info->postprocessor, upload_data,
-                                 *upload_data_size);
-               *upload_data_size = 0;
-
-               return MHD_YES;
-             }
-           else
-     	{
-     	  if (NULL != con_info->fp)
-     	  {
-     	    fclose (con_info->fp);
-     	    con_info->fp = NULL;
-     	  }
-     	  /* Now it is safe to open and inspect the file before calling send_page with a response */
-     	  return send_page (connection, con_info->answerstring,
-     			    con_info->answercode);
-     	}
-
-         }
-
-       return send_page (connection, errorpage, MHD_HTTP_BAD_REQUEST);
-     }
-
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-
-       daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
-                                  &answer_to_connection, NULL,
-                                  MHD_OPTION_NOTIFY_COMPLETED, request_completed,
-                                  NULL, MHD_OPTION_END);
-       if (NULL == daemon)
-         return 1;
-       (void) getchar ();
-       MHD_stop_daemon (daemon);
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: sessions.c,  Next: tlsauthentication.c,  Prev: largepost.c,  Up: Example programs
-
-C.7 sessions.c
-==============
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     /* needed for asprintf */
-     #define _GNU_SOURCE
-
-     #include <stdlib.h>
-     #include <string.h>
-     #include <stdio.h>
-     #include <errno.h>
-     #include <time.h>
-     #include <microhttpd.h>
-
-     #if defined _WIN32 && !defined(__MINGW64_VERSION_MAJOR)
-     static int
-     asprintf (char **resultp, const char *format, ...)
-     {
-       va_list argptr;
-       char *result = NULL;
-       int len = 0;
-
-       if (format == NULL)
-         return -1;
-
-       va_start (argptr, format);
-
-       len = _vscprintf ((char *) format, argptr);
-       if (len >= 0)
-       {
-         len += 1;
-         result = (char *) malloc (sizeof (char *) * len);
-         if (result != NULL)
-         {
-           int len2 = _vscprintf ((char *) format, argptr);
-           if (len2 != len - 1 || len2 <= 0)
-           {
-             free (result);
-             result = NULL;
-             len = -1;
-           }
-           else
-           {
-             len = len2;
-             if (resultp)
-               *resultp = result;
-           }
-         }
-       }
-       va_end (argptr);
-       return len;
-     }
-     #endif
-
-     /**
-      * Invalid method page.
-      */
-     #define METHOD_ERROR "<html><head><title>Illegal request</title></head><body>Go away.</body></html>"
-
-     /**
-      * Invalid URL page.
-      */
-     #define NOT_FOUND_ERROR "<html><head><title>Not found</title></head><body>Go away.</body></html>"
-
-     /**
-      * Front page. (/)
-      */
-     #define MAIN_PAGE "<html><head><title>Welcome</title></head><body><form action=\"/2\" method=\"post\">What is your name? <input type=\"text\" name=\"v1\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
-
-     /**
-      * Second page. (/2)
-      */
-     #define SECOND_PAGE "<html><head><title>Tell me more</title></head><body><a href=\"/\">previous</a> <form action=\"/S\" method=\"post\">%s, what is your job? <input type=\"text\" name=\"v2\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
-
-     /**
-      * Second page (/S)
-      */
-     #define SUBMIT_PAGE "<html><head><title>Ready to submit?</title></head><body><form action=\"/F\" method=\"post\"><a href=\"/2\">previous </a> <input type=\"hidden\" name=\"DONE\" value=\"yes\" /><input type=\"submit\" value=\"Submit\" /></body></html>"
-
-     /**
-      * Last page.
-      */
-     #define LAST_PAGE "<html><head><title>Thank you</title></head><body>Thank you.</body></html>"
-
-     /**
-      * Name of our cookie.
-      */
-     #define COOKIE_NAME "session"
-
-
-     /**
-      * State we keep for each user/session/browser.
-      */
-     struct Session
-     {
-       /**
-        * We keep all sessions in a linked list.
-        */
-       struct Session *next;
-
-       /**
-        * Unique ID for this session.
-        */
-       char sid[33];
-
-       /**
-        * Reference counter giving the number of connections
-        * currently using this session.
-        */
-       unsigned int rc;
-
-       /**
-        * Time when this session was last active.
-        */
-       time_t start;
-
-       /**
-        * String submitted via form.
-        */
-       char value_1[64];
-
-       /**
-        * Another value submitted via form.
-        */
-       char value_2[64];
-
-     };
-
-
-     /**
-      * Data kept per request.
-      */
-     struct Request
-     {
-
-       /**
-        * Associated session.
-        */
-       struct Session *session;
-
-       /**
-        * Post processor handling form data (IF this is
-        * a POST request).
-        */
-       struct MHD_PostProcessor *pp;
-
-       /**
-        * URL to serve in response to this POST (if this request
-        * was a 'POST')
-        */
-       const char *post_url;
-
-     };
-
-
-     /**
-      * Linked list of all active sessions.  Yes, O(n) but a
-      * hash table would be overkill for a simple example...
-      */
-     static struct Session *sessions;
-
-
-
-
-     /**
-      * Return the session handle for this connection, or
-      * create one if this is a new user.
-      */
-     static struct Session *
-     get_session (struct MHD_Connection *connection)
-     {
-       struct Session *ret;
-       const char *cookie;
-
-       cookie = MHD_lookup_connection_value (connection,
-     					MHD_COOKIE_KIND,
-     					COOKIE_NAME);
-       if (cookie != NULL)
-         {
-           /* find existing session */
-           ret = sessions;
-           while (NULL != ret)
-     	{
-     	  if (0 == strcmp (cookie, ret->sid))
-     	    break;
-     	  ret = ret->next;
-     	}
-           if (NULL != ret)
-     	{
-     	  ret->rc++;
-     	  return ret;
-     	}
-         }
-       /* create fresh session */
-       ret = calloc (1, sizeof (struct Session));
-       if (NULL == ret)
-         {
-           fprintf (stderr, "calloc error: %s\n", strerror (errno));
-           return NULL;
-         }
-       /* not a super-secure way to generate a random session ID,
-          but should do for a simple example... */
-       snprintf (ret->sid,
-     	    sizeof (ret->sid),
-     	    "%X%X%X%X",
-     	    (unsigned int) rand (),
-     	    (unsigned int) rand (),
-     	    (unsigned int) rand (),
-     	    (unsigned int) rand ());
-       ret->rc++;
-       ret->start = time (NULL);
-       ret->next = sessions;
-       sessions = ret;
-       return ret;
-     }
-
-
-     /**
-      * Type of handler that generates a reply.
-      *
-      * @param cls content for the page (handler-specific)
-      * @param mime mime type to use
-      * @param session session information
-      * @param connection connection to process
-      * @param MHD_YES on success, MHD_NO on failure
-      */
-     typedef int (*PageHandler)(const void *cls,
-     			   const char *mime,
-     			   struct Session *session,
-     			   struct MHD_Connection *connection);
-
-
-     /**
-      * Entry we generate for each page served.
-      */
-     struct Page
-     {
-       /**
-        * Acceptable URL for this page.
-        */
-       const char *url;
-
-       /**
-        * Mime type to set for the page.
-        */
-       const char *mime;
-
-       /**
-        * Handler to call to generate response.
-        */
-       PageHandler handler;
-
-       /**
-        * Extra argument to handler.
-        */
-       const void *handler_cls;
-     };
-
-
-     /**
-      * Add header to response to set a session cookie.
-      *
-      * @param session session to use
-      * @param response response to modify
-      */
-     static void
-     add_session_cookie (struct Session *session,
-     		    struct MHD_Response *response)
-     {
-       char cstr[256];
-       snprintf (cstr,
-     	    sizeof (cstr),
-     	    "%s=%s",
-     	    COOKIE_NAME,
-     	    session->sid);
-       if (MHD_NO ==
-           MHD_add_response_header (response,
-     			       MHD_HTTP_HEADER_SET_COOKIE,
-     			       cstr))
-         {
-           fprintf (stderr,
-     	       "Failed to set session cookie header!\n");
-         }
-     }
-
-
-     /**
-      * Handler that returns a simple static HTTP page that
-      * is passed in via 'cls'.
-      *
-      * @param cls a 'const char *' with the HTML webpage to return
-      * @param mime mime type to use
-      * @param session session handle
-      * @param connection connection to use
-      */
-     static int
-     serve_simple_form (const void *cls,
-     		   const char *mime,
-     		   struct Session *session,
-     		   struct MHD_Connection *connection)
-     {
-       int ret;
-       const char *form = cls;
-       struct MHD_Response *response;
-
-       /* return static form */
-       response = MHD_create_response_from_buffer (strlen (form),
-     					      (void *) form,
-     					      MHD_RESPMEM_PERSISTENT);
-       add_session_cookie (session, response);
-       MHD_add_response_header (response,
-     			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-     			   mime);
-       ret = MHD_queue_response (connection,
-     			    MHD_HTTP_OK,
-     			    response);
-       MHD_destroy_response (response);
-       return ret;
-     }
-
-
-     /**
-      * Handler that adds the 'v1' value to the given HTML code.
-      *
-      * @param cls a 'const char *' with the HTML webpage to return
-      * @param mime mime type to use
-      * @param session session handle
-      * @param connection connection to use
-      */
-     static int
-     fill_v1_form (const void *cls,
-     	      const char *mime,
-     	      struct Session *session,
-     	      struct MHD_Connection *connection)
-     {
-       int ret;
-       const char *form = cls;
-       char *reply;
-       struct MHD_Response *response;
-
-       if (-1 == asprintf (&reply,
-     		      form,
-     		      session->value_1))
-         {
-           /* oops */
-           return MHD_NO;
-         }
-       /* return static form */
-       response = MHD_create_response_from_buffer (strlen (reply),
-     					      (void *) reply,
-     					      MHD_RESPMEM_MUST_FREE);
-       add_session_cookie (session, response);
-       MHD_add_response_header (response,
-     			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-     			   mime);
-       ret = MHD_queue_response (connection,
-     			    MHD_HTTP_OK,
-     			    response);
-       MHD_destroy_response (response);
-       return ret;
-     }
-
-
-     /**
-      * Handler that adds the 'v1' and 'v2' values to the given HTML code.
-      *
-      * @param cls a 'const char *' with the HTML webpage to return
-      * @param mime mime type to use
-      * @param session session handle
-      * @param connection connection to use
-      */
-     static int
-     fill_v1_v2_form (const void *cls,
-     		 const char *mime,
-     		 struct Session *session,
-     		 struct MHD_Connection *connection)
-     {
-       int ret;
-       const char *form = cls;
-       char *reply;
-       struct MHD_Response *response;
-
-       if (-1 == asprintf (&reply,
-     		      form,
-     		      session->value_1,
-     		      session->value_2))
-         {
-           /* oops */
-           return MHD_NO;
-         }
-       /* return static form */
-       response = MHD_create_response_from_buffer (strlen (reply),
-     					      (void *) reply,
-     					      MHD_RESPMEM_MUST_FREE);
-       add_session_cookie (session, response);
-       MHD_add_response_header (response,
-     			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-     			   mime);
-       ret = MHD_queue_response (connection,
-     			    MHD_HTTP_OK,
-     			    response);
-       MHD_destroy_response (response);
-       return ret;
-     }
-
-
-     /**
-      * Handler used to generate a 404 reply.
-      *
-      * @param cls a 'const char *' with the HTML webpage to return
-      * @param mime mime type to use
-      * @param session session handle
-      * @param connection connection to use
-      */
-     static int
-     not_found_page (const void *cls,
-     		const char *mime,
-     		struct Session *session,
-     		struct MHD_Connection *connection)
-     {
-       int ret;
-       struct MHD_Response *response;
-
-       /* unsupported HTTP method */
-       response = MHD_create_response_from_buffer (strlen (NOT_FOUND_ERROR),
-     					      (void *) NOT_FOUND_ERROR,
-     					      MHD_RESPMEM_PERSISTENT);
-       ret = MHD_queue_response (connection,
-     			    MHD_HTTP_NOT_FOUND,
-     			    response);
-       MHD_add_response_header (response,
-     			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-     			   mime);
-       MHD_destroy_response (response);
-       return ret;
-     }
-
-
-     /**
-      * List of all pages served by this HTTP server.
-      */
-     static struct Page pages[] =
-       {
-         { "/", "text/html",  &fill_v1_form, MAIN_PAGE },
-         { "/2", "text/html", &fill_v1_v2_form, SECOND_PAGE },
-         { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE },
-         { "/F", "text/html", &serve_simple_form, LAST_PAGE },
-         { NULL, NULL, &not_found_page, NULL } /* 404 */
-       };
-
-
-
-     /**
-      * Iterator over key-value pairs where the value
-      * maybe made available in increments and/or may
-      * not be zero-terminated.  Used for processing
-      * POST data.
-      *
-      * @param cls user-specified closure
-      * @param kind type of the value
-      * @param key 0-terminated key for the value
-      * @param filename name of the uploaded file, NULL if not known
-      * @param content_type mime-type of the data, NULL if not known
-      * @param transfer_encoding encoding of the data, NULL if not known
-      * @param data pointer to size bytes of data at the
-      *              specified offset
-      * @param off offset of data in the overall value
-      * @param size number of bytes in data available
-      * @return MHD_YES to continue iterating,
-      *         MHD_NO to abort the iteration
-      */
-     static int
-     post_iterator (void *cls,
-     	       enum MHD_ValueKind kind,
-     	       const char *key,
-     	       const char *filename,
-     	       const char *content_type,
-     	       const char *transfer_encoding,
-     	       const char *data, uint64_t off, size_t size)
-     {
-       struct Request *request = cls;
-       struct Session *session = request->session;
-
-       if (0 == strcmp ("DONE", key))
-         {
-           fprintf (stdout,
-     	       "Session `%s' submitted `%s', `%s'\n",
-     	       session->sid,
-     	       session->value_1,
-     	       session->value_2);
-           return MHD_YES;
-         }
-       if (0 == strcmp ("v1", key))
-         {
-           if (size + off > sizeof(session->value_1))
-     	size = sizeof (session->value_1) - off;
-           memcpy (&session->value_1[off],
-     	      data,
-     	      size);
-           if (size + off < sizeof (session->value_1))
-     	session->value_1[size+off] = '\0';
-           return MHD_YES;
-         }
-       if (0 == strcmp ("v2", key))
-         {
-           if (size + off > sizeof(session->value_2))
-     	size = sizeof (session->value_2) - off;
-           memcpy (&session->value_2[off],
-     	      data,
-     	      size);
-           if (size + off < sizeof (session->value_2))
-     	session->value_2[size+off] = '\0';
-           return MHD_YES;
-         }
-       fprintf (stderr, "Unsupported form value `%s'\n", key);
-       return MHD_YES;
-     }
-
-
-     /**
-      * Main MHD callback for handling requests.
-      *
-      *
-      * @param cls argument given together with the function
-      *        pointer when the handler was registered with MHD
-      * @param connection handle to connection which is being processed
-      * @param url the requested url
-      * @param method the HTTP method used ("GET", "PUT", etc.)
-      * @param version the HTTP version string (i.e. "HTTP/1.1")
-      * @param upload_data the data being uploaded (excluding HEADERS,
-      *        for a POST that fits into memory and that is encoded
-      *        with a supported encoding, the POST data will NOT be
-      *        given in upload_data and is instead available as
-      *        part of MHD_get_connection_values; very large POST
-      *        data *will* be made available incrementally in
-      *        upload_data)
-      * @param upload_data_size set initially to the size of the
-      *        upload_data provided; the method must update this
-      *        value to the number of bytes NOT processed;
-      * @param ptr pointer that the callback can set to some
-      *        address and that will be preserved by MHD for future
-      *        calls for this request; since the access handler may
-      *        be called many times (i.e., for a PUT/POST operation
-      *        with plenty of upload data) this allows the application
-      *        to easily associate some request-specific state.
-      *        If necessary, this state can be cleaned up in the
-      *        global "MHD_RequestCompleted" callback (which
-      *        can be set with the MHD_OPTION_NOTIFY_COMPLETED).
-      *        Initially, <tt>*con_cls</tt> will be NULL.
-      * @return MHS_YES if the connection was handled successfully,
-      *         MHS_NO if the socket must be closed due to a serios
-      *         error while handling the request
-      */
-     static int
-     create_response (void *cls,
-     		 struct MHD_Connection *connection,
-     		 const char *url,
-     		 const char *method,
-     		 const char *version,
-     		 const char *upload_data,
-     		 size_t *upload_data_size,
-     		 void **ptr)
-     {
-       struct MHD_Response *response;
-       struct Request *request;
-       struct Session *session;
-       int ret;
-       unsigned int i;
-
-       request = *ptr;
-       if (NULL == request)
-         {
-           request = calloc (1, sizeof (struct Request));
-           if (NULL == request)
-     	{
-     	  fprintf (stderr, "calloc error: %s\n", strerror (errno));
-     	  return MHD_NO;
-     	}
-           *ptr = request;
-           if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-     	{
-     	  request->pp = MHD_create_post_processor (connection, 1024,
-     						   &post_iterator, request);
-     	  if (NULL == request->pp)
-     	    {
-     	      fprintf (stderr, "Failed to setup post processor for `%s'\n",
-     		       url);
-     	      return MHD_NO; /* internal error */
-     	    }
-     	}
-           return MHD_YES;
-         }
-       if (NULL == request->session)
-         {
-           request->session = get_session (connection);
-           if (NULL == request->session)
-     	{
-     	  fprintf (stderr, "Failed to setup session for `%s'\n",
-     		   url);
-     	  return MHD_NO; /* internal error */
-     	}
-         }
-       session = request->session;
-       session->start = time (NULL);
-       if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-         {
-           /* evaluate POST data */
-           MHD_post_process (request->pp,
-     			upload_data,
-     			*upload_data_size);
-           if (0 != *upload_data_size)
-     	{
-     	  *upload_data_size = 0;
-     	  return MHD_YES;
-     	}
-           /* done with POST data, serve response */
-           MHD_destroy_post_processor (request->pp);
-           request->pp = NULL;
-           method = MHD_HTTP_METHOD_GET; /* fake 'GET' */
-           if (NULL != request->post_url)
-     	url = request->post_url;
-         }
-
-       if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) ||
-            (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) )
-         {
-           /* find out which page to serve */
-           i=0;
-           while ( (pages[i].url != NULL) &&
-     	      (0 != strcmp (pages[i].url, url)) )
-     	i++;
-           ret = pages[i].handler (pages[i].handler_cls,
-     			      pages[i].mime,
-     			      session, connection);
-           if (ret != MHD_YES)
-     	fprintf (stderr, "Failed to create page for `%s'\n",
-     		 url);
-           return ret;
-         }
-       /* unsupported HTTP method */
-       response = MHD_create_response_from_buffer (strlen (METHOD_ERROR),
-     					      (void *) METHOD_ERROR,
-     					      MHD_RESPMEM_PERSISTENT);
-       ret = MHD_queue_response (connection,
-     			    MHD_HTTP_METHOD_NOT_ACCEPTABLE,
-     			    response);
-       MHD_destroy_response (response);
-       return ret;
-     }
-
-
-     /**
-      * Callback called upon completion of a request.
-      * Decrements session reference counter.
-      *
-      * @param cls not used
-      * @param connection connection that completed
-      * @param con_cls session handle
-      * @param toe status code
-      */
-     static void
-     request_completed_callback (void *cls,
-     			    struct MHD_Connection *connection,
-     			    void **con_cls,
-     			    enum MHD_RequestTerminationCode toe)
-     {
-       struct Request *request = *con_cls;
-
-       if (NULL == request)
-         return;
-       if (NULL != request->session)
-         request->session->rc--;
-       if (NULL != request->pp)
-         MHD_destroy_post_processor (request->pp);
-       free (request);
-     }
-
-
-     /**
-      * Clean up handles of sessions that have been idle for
-      * too long.
-      */
-     static void
-     expire_sessions ()
-     {
-       struct Session *pos;
-       struct Session *prev;
-       struct Session *next;
-       time_t now;
-
-       now = time (NULL);
-       prev = NULL;
-       pos = sessions;
-       while (NULL != pos)
-         {
-           next = pos->next;
-           if (now - pos->start > 60 * 60)
-     	{
-     	  /* expire sessions after 1h */
-     	  if (NULL == prev)
-     	    sessions = pos->next;
-     	  else
-     	    prev->next = next;
-     	  free (pos);
-     	}
-           else
-             prev = pos;
-           pos = next;
-         }
-     }
-
-
-     /**
-      * Call with the port number as the only argument.
-      * Never terminates (other than by signals, such as CTRL-C).
-      */
-     int
-     main (int argc, char *const *argv)
-     {
-       struct MHD_Daemon *d;
-       struct timeval tv;
-       struct timeval *tvp;
-       fd_set rs;
-       fd_set ws;
-       fd_set es;
-       int max;
-       MHD_UNSIGNED_LONG_LONG mhd_timeout;
-
-       if (argc != 2)
-         {
-           printf ("%s PORT\n", argv[0]);
-           return 1;
-         }
-       /* initialize PRNG */
-       srand ((unsigned int) time (NULL));
-       d = MHD_start_daemon (MHD_USE_DEBUG,
-                             atoi (argv[1]),
-                             NULL, NULL,
-     			&create_response, NULL,
-     			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15,
-     			MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL,
-     			MHD_OPTION_END);
-       if (NULL == d)
-         return 1;
-       while (1)
-         {
-           expire_sessions ();
-           max = 0;
-           FD_ZERO (&rs);
-           FD_ZERO (&ws);
-           FD_ZERO (&es);
-           if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-     	break; /* fatal internal error */
-           if (MHD_get_timeout (d, &mhd_timeout) == MHD_YES)
-     	{
-     	  tv.tv_sec = mhd_timeout / 1000;
-     	  tv.tv_usec = (mhd_timeout - (tv.tv_sec * 1000)) * 1000;
-     	  tvp = &tv;
-     	}
-           else
-     	tvp = NULL;
-           if (-1 == select (max + 1, &rs, &ws, &es, tvp))
-     	{
-     	  if (EINTR != errno)
-     	    fprintf (stderr,
-     		     "Aborting due to error during select: %s\n",
-     		     strerror (errno));
-     	  break;
-     	}
-           MHD_run (d);
-         }
-       MHD_stop_daemon (d);
-       return 0;
-     }
-
-
-File: libmicrohttpd-tutorial.info,  Node: tlsauthentication.c,  Prev: sessions.c,  Up: Example programs
-
-C.8 tlsauthentication.c
-=======================
-
-     /* Feel free to use this example code in any way
-        you see fit (Public Domain) */
-
-     #include <sys/types.h>
-     #ifndef _WIN32
-     #include <sys/select.h>
-     #include <sys/socket.h>
-     #else
-     #include <winsock2.h>
-     #endif
-     #include <microhttpd.h>
-     #include <string.h>
-     #include <stdio.h>
-     #include <stdlib.h>
-
-     #define PORT 8888
-
-     #define REALM     "\"Maintenance\""
-     #define USER      "a legitimate user"
-     #define PASSWORD  "and his password"
-
-     #define SERVERKEYFILE "server.key"
-     #define SERVERCERTFILE "server.pem"
-
-
-     static char *
-     string_to_base64 (const char *message)
-     {
-       const char *lookup =
-         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-       unsigned long l;
-       int i;
-       char *tmp;
-       size_t length = strlen (message);
-
-       tmp = malloc (length * 2);
-       if (NULL == tmp)
-         return tmp;
-
-       tmp[0] = 0;
-
-       for (i = 0; i < length; i += 3)
-         {
-           l = (((unsigned long) message[i]) << 16)
-             | (((i + 1) < length) ? (((unsigned long) message[i + 1]) << 8) : 0)
-             | (((i + 2) < length) ? ((unsigned long) message[i + 2]) : 0);
-
-
-           strncat (tmp, &lookup[(l >> 18) & 0x3F], 1);
-           strncat (tmp, &lookup[(l >> 12) & 0x3F], 1);
-
-           if (i + 1 < length)
-             strncat (tmp, &lookup[(l >> 6) & 0x3F], 1);
-           if (i + 2 < length)
-             strncat (tmp, &lookup[l & 0x3F], 1);
-         }
-
-       if (length % 3)
-         strncat (tmp, "===", 3 - length % 3);
-
-       return tmp;
-     }
-
-
-     static long
-     get_file_size (const char *filename)
-     {
-       FILE *fp;
-
-       fp = fopen (filename, "rb");
-       if (fp)
-         {
-           long size;
-
-           if ((0 != fseek (fp, 0, SEEK_END)) || (-1 == (size = ftell (fp))))
-             size = 0;
-
-           fclose (fp);
-
-           return size;
-         }
-       else
-         return 0;
-     }
-
-     static char *
-     load_file (const char *filename)
-     {
-       FILE *fp;
-       char *buffer;
-       long size;
-
-       size = get_file_size (filename);
-       if (size == 0)
-         return NULL;
-
-       fp = fopen (filename, "rb");
-       if (!fp)
-         return NULL;
-
-       buffer = malloc (size);
-       if (!buffer)
-         {
-           fclose (fp);
-           return NULL;
-         }
-
-       if (size != fread (buffer, 1, size, fp))
-         {
-           free (buffer);
-           buffer = NULL;
-         }
-
-       fclose (fp);
-       return buffer;
-     }
-
-     static int
-     ask_for_authentication (struct MHD_Connection *connection, const char *realm)
-     {
-       int ret;
-       struct MHD_Response *response;
-       char *headervalue;
-       const char *strbase = "Basic realm=";
-
-       response = MHD_create_response_from_buffer (0, NULL,
-     					      MHD_RESPMEM_PERSISTENT);
-       if (!response)
-         return MHD_NO;
-
-       headervalue = malloc (strlen (strbase) + strlen (realm) + 1);
-       if (!headervalue)
-         return MHD_NO;
-
-       strcpy (headervalue, strbase);
-       strcat (headervalue, realm);
-
-       ret = MHD_add_response_header (response, "WWW-Authenticate", headervalue);
-       free (headervalue);
-       if (!ret)
-         {
-           MHD_destroy_response (response);
-           return MHD_NO;
-         }
-
-       ret = MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response);
-
-       MHD_destroy_response (response);
-
-       return ret;
-     }
-
-     static int
-     is_authenticated (struct MHD_Connection *connection,
-                       const char *username, const char *password)
-     {
-       const char *headervalue;
-       char *expected_b64, *expected;
-       const char *strbase = "Basic ";
-       int authenticated;
-
-       headervalue =
-         MHD_lookup_connection_value (connection, MHD_HEADER_KIND,
-                                      "Authorization");
-       if (NULL == headervalue)
-         return 0;
-       if (0 != strncmp (headervalue, strbase, strlen (strbase)))
-         return 0;
-
-       expected = malloc (strlen (username) + 1 + strlen (password) + 1);
-       if (NULL == expected)
-         return 0;
-
-       strcpy (expected, username);
-       strcat (expected, ":");
-       strcat (expected, password);
-
-       expected_b64 = string_to_base64 (expected);
-       free (expected);
-       if (NULL == expected_b64)
-         return 0;
-
-       authenticated =
-         (strcmp (headervalue + strlen (strbase), expected_b64) == 0);
-
-       free (expected_b64);
-
-       return authenticated;
-     }
-
-
-     static int
-     secret_page (struct MHD_Connection *connection)
-     {
-       int ret;
-       struct MHD_Response *response;
-       const char *page = "<html><body>A secret.</body></html>";
-
-       response =
-         MHD_create_response_from_buffer (strlen (page), (void *) page,
-     				     MHD_RESPMEM_PERSISTENT);
-       if (!response)
-         return MHD_NO;
-
-       ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-       MHD_destroy_response (response);
-
-       return ret;
-     }
-
-
-     static int
-     answer_to_connection (void *cls, struct MHD_Connection *connection,
-                           const char *url, const char *method,
-                           const char *version, const char *upload_data,
-                           size_t *upload_data_size, void **con_cls)
-     {
-       if (0 != strcmp (method, "GET"))
-         return MHD_NO;
-       if (NULL == *con_cls)
-         {
-           *con_cls = connection;
-           return MHD_YES;
-         }
-
-       if (!is_authenticated (connection, USER, PASSWORD))
-         return ask_for_authentication (connection, REALM);
-
-       return secret_page (connection);
-     }
-
-
-     int
-     main ()
-     {
-       struct MHD_Daemon *daemon;
-       char *key_pem;
-       char *cert_pem;
-
-       key_pem = load_file (SERVERKEYFILE);
-       cert_pem = load_file (SERVERCERTFILE);
-
-       if ((key_pem == NULL) || (cert_pem == NULL))
-         {
-           printf ("The key/certificate files could not be read.\n");
-           return 1;
-         }
-
-       daemon =
-         MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL, PORT, NULL,
-                           NULL, &answer_to_connection, NULL,
-                           MHD_OPTION_HTTPS_MEM_KEY, key_pem,
-                           MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END);
-       if (NULL == daemon)
-         {
-           printf ("%s\n", cert_pem);
-
-           free (key_pem);
-           free (cert_pem);
-
-           return 1;
-         }
-
-       (void) getchar ();
-
-       MHD_stop_daemon (daemon);
-       free (key_pem);
-       free (cert_pem);
-
-       return 0;
-     }
-
-
-
-Tag Table:
-Node: Top866
-Node: Introduction1917
-Node: Hello browser example3223
-Node: Exploring requests14247
-Node: Response headers19643
-Node: Supporting basic authentication27522
-Node: Processing POST data34913
-Node: Improved processing of POST data43534
-Node: Session management54177
-Node: Adding a layer of security57072
-Node: Bibliography71602
-Node: License text72797
-Node: Example programs97972
-Node: hellobrowser.c98285
-Node: logging.c99828
-Node: responseheaders.c101411
-Node: basicauthentication.c104035
-Node: simplepost.c106574
-Node: largepost.c112254
-Node: sessions.c119619
-Node: tlsauthentication.c141964
-
-End Tag Table
diff --git a/doc/libmicrohttpd-tutorial.texi b/doc/libmicrohttpd-tutorial.texi
index 104f00c..7d3cd23 100644
--- a/doc/libmicrohttpd-tutorial.texi
+++ b/doc/libmicrohttpd-tutorial.texi
@@ -1,10 +1,10 @@
 \input texinfo  @c -*-texinfo-*-
 @finalout
 @setfilename libmicrohttpd-tutorial.info
-@set UPDATED 17 November 2013
-@set UPDATED-MONTH November 2013
-@set EDITION 0.9.23
-@set VERSION 0.9.23
+@set UPDATED 2 April 2016
+@set UPDATED-MONTH April 2016
+@set EDITION 0.9.48
+@set VERSION 0.9.48
 @settitle A tutorial for GNU libmicrohttpd
 @c Unify all the indices into concept index.
 @syncodeindex fn cp
@@ -24,7 +24,7 @@
 
 Copyright (c)  2008  Sebastian Gerhardt.
 
-Copyright (c)  2010, 2011, 2012, 2013  Christian Grothoff.
+Copyright (c)  2010, 2011, 2012, 2013, 2016, 2021  Christian Grothoff.
 @quotation
 Permission is granted to copy, distribute and/or modify this document
 under the terms of the GNU Free Documentation License, Version 1.3
@@ -68,6 +68,7 @@
 * Improved processing of POST data::
 * Session management::
 * Adding a layer of security::
+* Websockets::
 * Bibliography::
 * License text::
 * Example programs::
@@ -109,6 +110,10 @@
 @chapter Adding a layer of security
 @include chapters/tlsauthentication.inc
 
+@node Websockets
+@chapter Websockets
+@include chapters/websocket.inc
+
 @node Bibliography
 @appendix Bibliography
 @include chapters/bibliography.inc
@@ -128,6 +133,7 @@
 * largepost.c::
 * sessions.c::
 * tlsauthentication.c::
+* websocket.c::
 @end menu
 
 @node hellobrowser.c
@@ -178,4 +184,10 @@
 @verbatiminclude examples/tlsauthentication.c
 @end smalldisplay
 
+@node websocket.c
+@section websocket.c
+@smalldisplay
+@verbatiminclude examples/websocket.c
+@end smalldisplay
+
 @bye
diff --git a/doc/libmicrohttpd.3 b/doc/libmicrohttpd.3
index 13fcdcd..cfa0762 100644
--- a/doc/libmicrohttpd.3
+++ b/doc/libmicrohttpd.3
@@ -1,35 +1,45 @@
-.TH LIBMICROHTTPD "3" "21 Jun 2013 "libmicrohttpd"
-.SH "NAME"
-GNU libmicrohttpd \- library for embedding HTTP servers
-.SH "SYNOPSIS"
-
- \fB#include <microhttpd.h>
-
-.SH "DESCRIPTION"
-.P
+.Dd June 21, 2013
+.Dt LIBMICROHTTPD 3
+.Os
+.Sh NAME
+.Nm libmicrohttpd
+.Nd library for embedding HTTP servers
+.Sh LIBRARY
+.Lb libmicrohttpd
+.Sh SYNOPSIS
+.In microhttpd.h
+.Sh DESCRIPTION
 GNU libmicrohttpd (short MHD) allows applications to easily integrate the functionality of a simple HTTP server.  MHD is a GNU package.
-.P
-The details of the API are described in comments in the header file, a detailed reference documentation, a tutorial, and in brief on the MHD webpage.
-.P
-.SH "SEE ALSO"
-\fBcurl\fP(1), \fBlibcurl\fP(3)
-
-.SH "LEGAL NOTICE"
-libmicrohttpd is released under both the LGPL Version 2.1 or higher and the GNU GPL with eCos extension.  For details on both licenses please read the respective appendix in the manual.
-
-.SH "FILES"
-.TP
-microhttpd.h
+.sp
+The details of the API are described in comments in the header file, a detailed reference documentation in Texinfo, a tutorial, and in brief on the MHD webpage.
+.Sh LEGAL NOTICE
+libmicrohttpd is released under both the LGPL Version 2.1 or higher and the GNU GPL with eCos extension.  For details on both licenses please read the respective appendix in the Texinfo manual.
+.Sh FILES
+.Bl -tag -width /etc/ttys -compact
+.It Pa microhttpd.h
 libmicrohttpd include file
-.TP
-libmicrohttpd.so
+.It Pa libmicrohttpd.so
 libmicrohttpd library
-
-.SH "REPORTING BUGS"
-Report bugs by using mantis <https://gnunet.org/bugs/>.
-
-.SH "AUTHORS"
-GNU libmicrohttpd was originally designed by Christian Grothoff <christian@grothoff.org> and Chris GauthierDickey <chrisg@cs.du.edu>.  The original implementation was done by Daniel Pittman <depittman@gmail.com> and Christian Grothoff.  SSL/TLS support was added by Sagie Amir using code from GnuTLS.  See the AUTHORS file in the distribution for a more detailed list of contributors.
-
-.SH "AVAILABILITY"
-You can obtain the latest version from http://www.gnu.org/software/libmicrohttpd/.
+.El
+.Sh SEE ALSO
+.Xr curl 1 ,
+.Xr libcurl 3 ,
+info libmicrohttpd
+.Sh AUTHORS
+GNU
+.Nm
+was originally designed by
+.An -nosplit
+.An Christian Grothoff Aq Mt christian@grothoff.org
+and
+.An Chris GauthierDickey Aq Mt chrisg@cs.du.edu Ns .
+The original implementation was done by
+.An Daniel Pittman Aq Mt depittman@gmail.com
+and Christian Grothoff.
+SSL/TLS support was added by Sagie Amir using code from GnuTLS.  See the AUTHORS file in the distribution for a more detailed list of contributors.
+.Sh AVAILABILITY
+You can obtain the latest version from
+.Lk https://www.gnu.org/software/libmicrohttpd/ Ns .
+.Sh BUGS
+Report bugs by using
+.Lk https://gnunet.org/bugs/ "Mantis" Ns .
diff --git a/doc/libmicrohttpd.info b/doc/libmicrohttpd.info
deleted file mode 100644
index 7db83c7..0000000
--- a/doc/libmicrohttpd.info
+++ /dev/null
Binary files differ
diff --git a/doc/libmicrohttpd.texi b/doc/libmicrohttpd.texi
index 7e13a27..e1fc05b 100644
--- a/doc/libmicrohttpd.texi
+++ b/doc/libmicrohttpd.texi
@@ -1,5 +1,6 @@
 \input texinfo
 @setfilename libmicrohttpd.info
+@documentencoding UTF-8
 @include version.texi
 @settitle The GNU libmicrohttpd Reference Manual
 @c Unify all the indices into concept index.
@@ -11,7 +12,7 @@
 (version @value{VERSION}, @value{UPDATED}), a library for embedding
 an HTTP(S) server into C applications.
 
-Copyright @copyright{} 2007--2013 Christian Grothoff
+Copyright @copyright{} 2007--2019 Christian Grothoff
 
 @quotation
 Permission is granted to copy, distribute and/or modify this document
@@ -66,13 +67,14 @@
 * microhttpd-post::             Adding a @code{POST} processor.
 * microhttpd-info::             Obtaining and modifying status information.
 * microhttpd-util::             Utilities.
+* microhttpd-websocket::        Websockets.
 
 Appendices
 
-* GNU-LGPL::                     The GNU Lesser General Public License says how you
+* GNU-LGPL::                    The GNU Lesser General Public License says how you
                                  can copy and share almost all of `libmicrohttpd'.
-* GNU GPL with eCos Extension::  The GNU General Public License with eCos extension says how you
-                                 can copy and share some parts of `libmicrohttpd'.
+* eCos License::                The eCos License says how you can copy and share some parts of `libmicrohttpd'.
+* GNU-GPL::                     The GNU General Public License (with eCos extension) says how you can copy and share some parts of `libmicrohttpd'.
 * GNU-FDL::                     The GNU Free Documentation License says how you
                                 can copy and share the documentation of `libmicrohttpd'.
 
@@ -100,13 +102,26 @@
 
 The library is supposed to handle everything that it must handle
 (because the API would not allow clients to do this), such as basic
-connection management; however, detailed interpretations of headers ---
-such as range requests --- and HTTP methods are left to clients.  The
-library does understand @code{HEAD} and will only send the headers of
-the response and not the body, even if the client supplied a body.  The
-library also understands headers that control connection management
-(specifically, @code{Connection: close} and @code{Expect: 100 continue}
-are understood and handled automatically).
+connection management. However, detailed interpretations of headers,
+such as range requests, are left to the main application.  In
+particular, if an application developer wants to support range
+requests, he needs to explicitly indicate support in responses and
+also explicitly parse the range header and generate a response (for
+example, using the @code{MHD_create_response_from_fd_at_offset} call
+to serve ranges from a file).  MHD does understands headers that
+control connection management (specifically, @code{Connection: close}
+and @code{Expect: 100 continue} are understood and handled
+automatically).  @code{Connection: upgrade} is supported by passing
+control over the socket (or something that behaves like the real
+socket in the case of TLS) to the application (after sending the
+desired HTTP response header).
+
+MHD largely ignores the semantics of the different HTTP methods,
+so clients are left to handle those.  One exception is that MHD does
+understand @code{HEAD} and will only send the headers of the response
+and not the body, even if the client supplied a body.  (In fact,
+clients do need to construct a response with the correct length, even
+for @code{HEAD} request.)
 
 MHD understands @code{POST} data and is able to decode certain
 formats (at the moment only @code{application/x-www-form-urlencoded}
@@ -148,20 +163,20 @@
 @cindex select
 
 MHD supports four basic thread modes and up to three event loop
-styes.
+styles.
 
-The four basic thread modes are external (MHD creates no threads,
-event loop is fully managed by the application), internal (MHD creates
-one thread for all connections), thread pool (MHD creates a thread
-pool which is used to process all connections) and
-thread-per-connection (MHD creates one listen thread and then one
-thread per accepted connection).
+The four basic thread modes are external sockets polling (MHD creates
+no threads, event loop is fully managed by the application), internal
+polling (MHD creates one thread for all connections), polling in
+thread pool (MHD creates a thread pool which is used to process all
+connections) and thread-per-connection (MHD creates one thread for
+listen sockets and then one thread per accepted connection).
 
-These thread modes are then combined with the event loop styles.
-MHD support select, poll and epoll.  epoll is only available on
-Linux, poll may not be available on some platforms.  Note that
-it is possible to combine MHD using epoll with an external
-select-based event loop.
+These thread modes are then combined with the evet loop styles
+(polling function type).  MHD support select, poll and epoll. select
+is available on all platforms, epoll and poll may not be available on
+some platforms.  Note that it is possible to combine MHD using epoll
+with an external select-based event loop.
 
 The default (if no other option is passed) is ``external select''.
 The highest performance can typically be obtained with a thread pool
@@ -178,7 +193,7 @@
 
 
 @float Figure,fig:performance
-@image{performance_data,400pt,300pt,Data,.png}
+@image{libmicrohttpd_performance_data,400pt,300pt,Data,.png}
 @caption{Performance measurements for select vs. epoll (with thread-pool).}
 @end float
 
@@ -186,15 +201,15 @@
 Not all combinations of thread modes and event loop styles are
 supported.  This is partially to keep the API simple, and partially
 because some combinations simply make no sense as others are strictly
-superior.  Note that the choice of style depends fist of all on the
+superior.  Note that the choice of style depends first of all on the
 application logic, and then on the performance requirements.
 Applications that perform a blocking operation while handling a
 request within the callbacks from MHD must use a thread per
 connection.  This is typically rather costly.  Applications that do
 not support threads or that must run on embedded devices without
 thread-support must use the external mode.  Using @code{epoll} is only
-supported on Linux, thus portable applications must at least have a
-fallback option available.  @ref{tbl:supported} lists the sane
+supported on some platform, thus portable applications must at least
+have a fallback option available.  @ref{tbl:supported} lists the sane
 combinations.
 
 @float Table,tbl:supported
@@ -254,21 +269,36 @@
 @item ``--disable-dauth''
 do not include the authentication APIs (results in binary incompatibility)
 
-@item ``--disable-epoll
-do not include epoll support, even on Linux (minimally smaller binary size, good for testing portability to non-Linux systems)
+@item ``--disable-httpupgrade''
+do not build code for HTTP ``Upgrade'' (smaller binary size, binary incompatible library)
+
+@item ``--disable-epoll''
+do not include epoll support, even if it supported (minimally smaller binary size, good for portability testing)
 
 @item ``--enable-coverage''
 set flags for analysis of code-coverage with gcc/gcov (results in slow, large binaries)
 
+@item ``--with-threads=posix,w32,none,auto''
+sets threading library to use. With use ``none'' to not support threads. In this case, MHD will only support the ``external'' threading modes and not perform any locking of data structures! Use @code{MHD_is_feature_supported(MHD_FEATURE_THREADS)} to test if threads are available. Default is ``auto''.
+
 @item ``--with-gcrypt=PATH''
 specifies path to libgcrypt installation
 
 @item ``--with-gnutls=PATH''
 specifies path to libgnutls installation
 
-
 @end table
 
+To cross-compile MHD for Android, install the Android NDK and use:
+@verbatim
+./configure --target=arm-linux-androideabi --host=arm-linux-androideabi --disable-doc --disable-examples
+make
+@end verbatim
+
+Similar build commands should work for cross-compilation to other platforms.
+Note that you may have to first cross-compile GnuTLS to get MHD with TLS support.
+
+
 @section Validity of pointers
 
 MHD will give applications access to its internal data structures
@@ -302,11 +332,13 @@
 @cindex microhttpd.h
 
 Ideally, before including "microhttpd.h" you should add the necessary
-includes to define the @code{uint64_t}, @code{size_t}, @code{fd_set},
-@code{socklen_t} and @code{struct sockaddr} data types.  Which
-specific headers are needed may depend on your platform and your build
-system might include some tests to provide you with the necessary
-conditional operations.  For possible suggestions consult
+includes to define the @code{va_list}, @code{size_t}, @code{ssize_t},
+@code{intptr_t}, @code{off_t}, @code{uint8_t}, @code{uint16_t},
+@code{int32_t}, @code{uint32_t}, @code{int64_t}, @code{uint64_t},
+@code{fd_set}, @code{socklen_t} and @code{struct sockaddr} data types.
+Which specific headers are needed may depend on your platform and your
+build system might include some tests to provide you with the
+necessary conditional operations.  For possible suggestions consult
 @code{platform.h} and @code{configure.ac} in the MHD distribution.
 
 Once you have ensured that you manually (!) included the right headers
@@ -321,17 +353,18 @@
 
 @section SIGPIPE
 @cindex signals
-MHD does not install a signal handler for SIGPIPE.  On platforms
-where this is possible (such as GNU/Linux), it disables SIGPIPE for
-its I/O operations (by passing MSG_NOSIGNAL).  On other platforms,
-SIGPIPE signals may be generated from network operations by
-MHD and will cause the process to die unless the developer
-explicitly installs a signal handler for SIGPIPE.
+MHD does not install a signal handler for SIGPIPE.  On platforms where
+this is possible (such as GNU/Linux), it disables SIGPIPE for its I/O
+operations (by passing MSG_NOSIGNAL or similar).  On other platforms,
+SIGPIPE signals may be generated from network operations by MHD and
+will cause the process to die unless the developer explicitly installs
+a signal handler for SIGPIPE.
 
 Hence portable code using MHD must install a SIGPIPE handler or
-explicitly block the SIGPIPE signal.  MHD does not do so in order
-to avoid messing with other parts of the application that may
-need to handle SIGPIPE in a particular way.  You can make your application handle SIGPIPE by calling the following function in @code{main}:
+explicitly block the SIGPIPE signal.  MHD does not do so in order to
+avoid messing with other parts of the application that may need to
+handle SIGPIPE in a particular way.  You can make your application
+handle SIGPIPE by calling the following function in @code{main}:
 
 @verbatim
 static void
@@ -422,40 +455,42 @@
 @deftp {Enumeration} MHD_FLAG
 Options for the MHD daemon.
 
-Note that if neither @code{MHD_USE_THREAD_PER_CONNECTION} nor
-@code{MHD_USE_SELECT_INTERNALLY} is used, the client wants control over
-the process and will call the appropriate microhttpd callbacks.
+Note that MHD will run automatically in background thread(s) only if
+@code{MHD_USE_INTERNAL_POLLING_THREAD} is used. Otherwise caller
+(application) must use @code{MHD_run} or @code{MHD_run_from_select} to
+have MHD processed network connections and data.
 
 Starting the daemon may also fail if a particular option is not
-implemented or not supported on the target platform (i.e. no support for
-@acronym{SSL}, threads or IPv6).  SSL support generally depends on
-options given during MHD compilation.  Threaded operations
-(including @code{MHD_USE_SELECT_INTERNALLY}) are not supported on
-Symbian.
+implemented or not supported on the target platform (i.e. no support
+for @acronym{TLS}, threads or IPv6). TLS support generally depends on
+options given during MHD compilation.
 
 @table @code
 @item MHD_NO_FLAG
 No options selected.
 
+@item MHD_USE_ERROR_LOG
+If this flag is used, the library should print error messages and
+warnings to stderr (or to custom error printer if it's specified by
+options).  Note that for this run-time option to have any effect, MHD
+needs to be compiled with messages enabled. This is done by default
+except you ran configure with the @code{--disable-messages} flag set.
+
 @item MHD_USE_DEBUG
 @cindex debugging
-Run in debug mode.  If this flag is used, the library should print error
-messages and warnings to stderr.  Note that for this
-run-time option to have any effect, MHD needs to be
-compiled with messages enabled. This is done by default except you ran
-configure with the @code{--disable-messages} flag set.
+Currently the same as @code{MHD_USE_ERROR_LOG}.
 
-@item MHD_USE_SSL
+@item MHD_USE_TLS
 @cindex TLS
 @cindex SSL
-Run in HTTPS-mode.  If you specify @code{MHD_USE_SSL} and MHD was
+Run in HTTPS-mode.  If you specify @code{MHD_USE_TLS} and MHD was
 compiled without SSL support, @code{MHD_start_daemon} will return
 NULL.
 
 @item MHD_USE_THREAD_PER_CONNECTION
 Run using one thread per connection.
 
-@item MHD_USE_SELECT_INTERNALLY
+@item MHD_USE_INTERNAL_POLLING_THREAD
 Run using an internal thread doing @code{SELECT}.
 
 @item MHD_USE_IPv6
@@ -475,7 +510,9 @@
 (the 'struct sockaddr_in6' format will be used for IPv4 and IPv6).
 
 @item MHD_USE_PEDANTIC_CHECKS
-Be pedantic about the protocol (as opposed to as tolerant as possible).
+@cindex deprecated
+Deprecated (use @code{MHD_OPTION_STRICT_FOR_CLIENT}).
+Be pedantic about the protocol.
 Specifically, at the moment, this flag causes MHD to reject HTTP
 1.1 connections without a @code{Host} header.  This is required by the
 standard, but of course in violation of the ``be as liberal as possible
@@ -487,29 +524,45 @@
 @cindex FD_SETSIZE
 @cindex poll
 @cindex select
-Use poll instead of select. This allows sockets with descriptors
-@code{>= FD_SETSIZE}.  This option currently only works in conjunction
-with @code{MHD_USE_THREAD_PER_CONNECTION} or
-@code{MHD_USE_INTERNAL_SELECT} (at this point).  If you specify
-@code{MHD_USE_POLL} and the local platform does not support it,
-@code{MHD_start_daemon} will return NULL.
+Use @code{poll()} instead of @code{select()}. This allows sockets with
+descriptors @code{>= FD_SETSIZE}.  This option currently only works in
+conjunction with @code{MHD_USE_INTERNAL_POLLING_THREAD} (at this point).
+If you specify @code{MHD_USE_POLL} and the local platform does not
+support it, @code{MHD_start_daemon} will return NULL.
 
-@item MHD_USE_EPOLL_LINUX_ONLY
+@item MHD_USE_EPOLL
 @cindex FD_SETSIZE
 @cindex epoll
 @cindex select
-Use epoll instead of poll or select. This allows sockets with
-descriptors @code{>= FD_SETSIZE}.  This option is only available on
-Linux systems and only works in conjunction with
+Use @code{epoll()} instead of @code{poll()} or @code{select()}. This
+allows sockets with descriptors @code{>= FD_SETSIZE}.  This option is
+only available on some systems and does not work in conjunction with
 @code{MHD_USE_THREAD_PER_CONNECTION} (at this point).  If you specify
-@code{MHD_USE_EPOLL_LINUX_ONLY} and the local platform does not
-support it, @code{MHD_start_daemon} will return NULL.  Using epoll
-instead of select or poll can in some situations result in significantly
-higher performance as the system call has fundamentally lower complexity
-(O(1) for epoll vs. O(n) for select/poll where n is the number of
-open connections).
+@code{MHD_USE_EPOLL} and the local platform does not support it,
+@code{MHD_start_daemon} will return NULL.  Using @code{epoll()}
+instead of @code{select()} or @code{poll()} can in some situations
+result in significantly higher performance as the system call has
+fundamentally lower complexity (O(1) for @code{epoll()} vs. O(n) for
+@code{select()}/@code{poll()} where n is the number of open
+connections).
 
-@item MHD_SUPPRESS_DATE_NO_CLOCK
+@item MHD_USE_TURBO
+@cindex performance
+Enable optimizations to aggressively improve performance.
+
+Currently, the optimizations this option enables are based on
+opportunistic reads and writes.  Basically, MHD will simply try to
+read or write or accept on a socket before checking that the socket is
+ready for IO using the event loop mechanism.  As the sockets are
+non-blocking, this may fail (at a loss of performance), but generally
+MHD does this in situations where the operation is likely to succeed,
+in which case performance is improved.  Setting the flag should generally
+be safe (even though the code is slightly more experimental).  You may
+want to benchmark your application to see if this makes any difference
+for you.
+
+
+@item MHD_USE_SUPPRESS_DATE_NO_CLOCK
 @cindex date
 @cindex clock
 @cindex embedded systems
@@ -529,11 +582,12 @@
 with using a thread pool; if it is used,
 @code{MHD_OPTION_THREAD_POOL_SIZE} is ignored.
 
-@item MHD_USE_PIPE_FOR_SHUTDOWN
+
+@item MHD_USE_ITC
 @cindex quiesce
-Force MHD to use a signal pipe to notify the event loop (of threads)
-of our shutdown.  This is required if an appliction uses
-@code{MHD_USE_INTERNAL_SELECT} or @code{MHD_USE_THREAD_PER_CONNECTION}
+Force MHD to use a signal inter-thread communication channel to notify
+the event loop (of threads) of our shutdown and other events.  This is
+required if an application uses @code{MHD_USE_INTERNAL_POLLING_THREAD}
 and then performs @code{MHD_quiesce_daemon} (which eliminates our
 ability to signal termination via the listen socket).  In these modes,
 @code{MHD_quiesce_daemon} will fail if this option was not set.  Also,
@@ -541,11 +595,15 @@
 specify it), if @code{MHD_USE_NO_LISTEN_SOCKET} is specified.  In
 "external" select mode, this option is always simply ignored.
 
-@item MHD_USE_SUSPEND_RESUME
+Using this option also guarantees that MHD will not call
+@code{shutdown()} on the listen socket, which means a parent
+process can continue to use the socket.
+
+@item MHD_ALLOW_SUSPEND_RESUME
 Enables using @code{MHD_suspend_connection} and
 @code{MHD_resume_connection}, as performing these calls requires some
-additional pipes to be created, and code not using these calls should
-not pay the cost.
+additional inter-thred communication channels to be created, and code
+not using these calls should not pay the cost.
 
 @item MHD_USE_TCP_FASTOPEN
 @cindex listen
@@ -553,6 +611,42 @@
 supported on Linux >= 3.6.  On other systems using this option with
 cause @code{MHD_start_daemon} to fail.
 
+
+@item MHD_ALLOW_UPGRADE
+@cindex upgrade
+This option must be set if you want to upgrade connections
+(via ``101 Switching Protocols'' responses).  This requires MHD to
+allocate additional resources, and hence we require this
+special flag so we only use the resources that are really needed.
+
+
+@item MHD_USE_AUTO
+Automatically select best event loop style (polling function)
+depending on requested mode by other MHD flags and functions available
+on platform.  If application doesn't have requirements for any
+specific polling function, it's recommended to use this flag.  This
+flag is very convenient for multiplatform applications.
+
+@item MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT
+Tell the TLS library to support post handshake client authentication.
+Only useful in combination with @code{MHD_USE_TLS}.
+
+This option will only work if the underlying TLS library
+supports it (i.e. GnuTLS after 3.6.3). If the TLS library
+does not support it, MHD may ignore the option and proceed
+without supporting this features.
+
+@item MHD_USE_INSECURE_TLS_EARLY_DATA
+Tell the TLS library to support TLS v1.3 early data (0-RTT) with the
+resulting security drawbacks. Only enable this if you really know what
+you are doing. MHD currently does NOT enforce that this only affects
+GET requests! You have been warned.
+
+This option will only work if the underlying TLS library
+supports it (i.e. GnuTLS after 3.6.3). If the TLS library
+does not support it, MHD may ignore the option and proceed
+without supporting this features.
+
 @end table
 @end deftp
 
@@ -592,6 +686,15 @@
 four for @code{stdin}, @code{stdout}, @code{stderr} and the server
 socket).  In other words, the default is as large as possible.
 
+If the connection limit is reached, MHD's behavior depends a bit on
+other options.  If @code{MHD_USE_ITC} was given, MHD
+will stop accepting connections on the listen socket.  This will cause
+the operating system to queue connections (up to the @code{listen()}
+limit) above the connection limit.  Those connections will be held
+until MHD is done processing at least one of the active connections.
+If @code{MHD_USE_ITC} is not set, then MHD will continue
+to @code{accept()} and immediately @code{close()} these connections.
+
 Note that if you set a low connection limit, you can easily get into
 trouble with browsers doing request pipelining.  For example, if your
 connection limit is ``1'', a browser may open a first connection to
@@ -633,18 +736,15 @@
 
 @item MHD_OPTION_NOTIFY_CONNECTION
 Register a function that should be called when the TCP connection to a
-client is opened or closed.  Note that
-@code{MHD_OPTION_NOTIFY_COMPLETED} and the @code{con_cls} argument to
-the @code{MHD_AccessHandlerCallback} are per HTTP request (and there
-can be multiple HTTP requests per TCP connection).  The registered
-callback is called twice per TCP connection, with
-@code{MHD_CONNECTION_NOTIFY_STARTED} and
-@code{MHD_CONNECTION_NOTIFY_CLOSED} respectively.  An additional
+client is opened or closed. The registered callback is called twice per
+TCP connection, with @code{MHD_CONNECTION_NOTIFY_STARTED} and
+@code{MHD_CONNECTION_NOTIFY_CLOSED} respectively. An additional
 argument can be used to store TCP connection specific information,
 which can be retrieved using @code{MHD_CONNECTION_INFO_SOCKET_CONTEXT}
-during the lifetime of the TCP connection.  The respective location is
-not the same as the HTTP-request-specific @code{con_cls} from the
-@code{MHD_AccessHandlerCallback}.
+during the lifetime of the TCP connection. 
+Note @code{MHD_OPTION_NOTIFY_COMPLETED} and the @code{req_cls} argument
+to the @code{MHD_AccessHandlerCallback} are per HTTP request (and there
+can be multiple HTTP requests per TCP connection). 
 
 This option should be followed by @strong{TWO} pointers.  First a
 pointer to a function of type @code{MHD_NotifyConnectionCallback()}
@@ -661,6 +761,40 @@
 zero, which means no limit on the number of connections
 from the same IP address.
 
+@item MHD_OPTION_LISTEN_BACKLOG_SIZE
+Set the size of the @code{listen()} back log queue of the TCP socket.
+Takes an @code{unsigned int} as the argument.  Default is the
+platform-specific value of @code{SOMAXCONN}.
+
+@item MHD_OPTION_STRICT_FOR_CLIENT
+Specify how strict we should enforce the HTTP protocol.
+Takes an @code{int} as the argument.  Default is zero.
+
+If set to 1, MHD will be strict about the protocol.  Specifically, at
+the moment, this flag uses MHD to reject HTTP 1.1 connections without
+a "Host" header.  This is required by the standard, but of course in
+violation of the "be as liberal as possible in what you accept" norm.
+It is recommended to set this to 1 if you are testing clients against
+MHD, and 0 in production.
+
+If set to -1 MHD will be permissive about the protocol, allowing
+slight deviations that are technically not allowed by the
+RFC. Specifically, at the moment, this flag causes MHD to allow spaces
+in header field names. This is disallowed by the standard.
+
+It is not recommended to set it to -1 on publicly available servers as
+it may potentially lower level of protection.
+
+@item MHD_OPTION_SERVER_INSANITY
+@cindex testing
+Allows the application to disable certain sanity precautions in MHD. With
+these, the client can break the HTTP protocol, so this should never be used in
+production. The options are, however, useful for testing HTTP clients against
+"broken" server implementations.  This argument must be followed by an
+@code{unsigned int}, corresponding to an @code{enum MHD_DisableSanityCheck}.
+
+Right now, no sanity checks can be disabled.
+
 @item MHD_OPTION_SOCK_ADDR
 @cindex bind, restricting bind
 Bind daemon to the supplied socket address. This option should be followed by a
@@ -685,12 +819,12 @@
  void * my_logger(void * cls, const char * uri, struct MHD_Connection *con)
 @end example
 where the return value will be passed as
-@code{*con_cls} in calls to the @code{MHD_AccessHandlerCallback}
+@code{*req_cls} in calls to the @code{MHD_AccessHandlerCallback}
 when this request is processed later; returning a
 value of @code{NULL} has no special significance; (however,
 note that if you return non-@code{NULL}, you can no longer
 rely on the first call to the access handler having
-@code{NULL == *con_cls} on entry)
+@code{NULL == *req_cls} on entry)
 @code{cls} will be set to the second argument following
 MHD_OPTION_URI_LOG_CALLBACK.  Finally, @code{uri} will
 be the 0-terminated URI of the request.
@@ -776,6 +910,29 @@
 using gnutls_server_name_get().  Using this option requires GnuTLS 3.0
 or higher.
 
+@item MHD_OPTION_HTTPS_CERT_CALLBACK2
+@cindex SSL
+@cindex TLS
+@cindex SNI
+@cindex OCSP
+Use a callback to determine which X.509 certificate should be
+used for a given HTTPS connection.  This option should be
+followed by a argument of type `gnutls_certificate_retrieve_function3 *`.
+This option provides an
+alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK.
+You must use this version if you want to use OCSP stapling.
+Using this option requires GnuTLS 3.6.3 or higher.
+
+@item MHD_OPTION_GNUTLS_PSK_CRED_HANDLER
+@cindex SSL
+@cindex TLS
+@cindex PSK
+Use pre-shared key for TLS credentials.
+Pass a pointer to callback of type
+@code{MHD_PskServerCredentialsCallback} and a closure.
+The function will be called to
+retrieve the shared key for a given username.
+
 @item MHD_OPTION_DIGEST_AUTH_RANDOM
 @cindex digest auth
 @cindex random
@@ -828,17 +985,17 @@
 be passed as the "arg" argument to "fun".
 
 Note that MHD will not generate any log messages without
-the MHD_USE_DEBUG flag set and if MHD was compiled
+the MHD_USE_ERROR_LOG flag set and if MHD was compiled
 with the "--disable-messages" flag.
 
 @item MHD_OPTION_THREAD_POOL_SIZE
 @cindex performance
 Number (unsigned int) of threads in thread pool. Enable
 thread pooling by setting this value to to something
-greater than 1. Currently, thread model must be
-MHD_USE_SELECT_INTERNALLY if thread pooling is enabled
+greater than 1. Currently, thread mode must be
+MHD_USE_INTERNAL_POLLING_THREAD if thread pooling is enabled
 (@code{MHD_start_daemon} returns @code{NULL} for an unsupported thread
-model).
+mode).
 
 @item MHD_OPTION_ARRAY
 @cindex options
@@ -926,9 +1083,8 @@
 platforms, and @code{SO_REUSEADDR} on Windows).  If a false (zero) parameter is
 given, disallow reusing the the address:port of the listening socket (this
 usually requires no special action, but @code{SO_EXCLUSIVEADDRUSE} is needed on
-Windows).  If this option is not present, default behaviour is undefined
-(currently, @code{SO_REUSEADDR} is used on all platforms, which disallows
-address:port reusing with the exception of Windows).
+Windows).  If this option is not present @code{SO_REUSEADDR} is used on all
+platforms except Windows so reusing of address:port is disallowed.
 
 @end table
 @end deftp
@@ -954,9 +1110,6 @@
 the HTTP protocol.
 
 @table @code
-@item MHD_RESPONSE_HEADER_KIND
-Response header.
-
 @item MHD_HEADER_KIND
 HTTP header.
 
@@ -1045,6 +1198,38 @@
 do not (automatically) sent "Connection" headers and always
 close the connection after generating the response.
 
+By default, MHD will respond using the same HTTP version which
+was set in the request. You can also set the
+@code{MHD_RF_HTTP_VERSION_1_0_RESPONSE} flag to force version 1.0
+in the response.
+
+@item MHD_RF_HTTP_VERSION_1_0_RESPONSE
+Only respond in HTTP 1.0-mode. Contrary to the
+@code{MHD_RF_HTTP_VERSION_1_0_ONLY} flag, the response's HTTP version will
+always be set to 1.0 and ``Connection'' headers are still supported.
+
+You can even combine this option with MHD_RF_HTTP_VERSION_1_0_ONLY to
+change the response's HTTP version while maintaining strict compliance
+with HTTP 1.0 regarding connection management.
+
+This solution is not perfect as this flag is set on the response which
+is created after header processing. So MHD will behave as a HTTP 1.1
+server until the response is queued. It means that an invalid HTTP 1.1
+request will fail even if the response is sent with HTTP 1.0 and the
+request would be valid if interpreted with this version. For example,
+this request will fail in strict mode:
+
+@verbatim
+GET / HTTP/1.1
+@end verbatim
+
+as the ``Host'' header is missing and is mandatory in HTTP 1.1, but it
+should succeed when interpreted with HTTP 1.0.
+
+@item MHD_RF_INSANITY_HEADER_CONTENT_LENGTH
+Disable sanity check preventing clients from manually
+setting the HTTP content length option.
+
 @end table
 @end deftp
 
@@ -1061,6 +1246,493 @@
 @end deftp
 
 
+@deftp {Enumeration} MHD_WEBSOCKET_FLAG
+@cindex websocket
+Options for the MHD websocket stream.
+
+This is used for initialization of a websocket stream when calling
+@code{MHD_websocket_stream_init} or @code{MHD_websocket_stream_init2} and
+alters the behavior of the websocket stream.
+
+Note that websocket streams are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@table @code
+@item MHD_WEBSOCKET_FLAG_SERVER
+The websocket stream is initialized in server mode (default).
+Thus all outgoing payload will not be masked.
+All incoming payload must be masked.
+
+This flag cannot be used together with @code{MHD_WEBSOCKET_FLAG_CLIENT}.
+
+@item MHD_WEBSOCKET_FLAG_CLIENT
+The websocket stream is initialized in client mode.
+You will usually never use that mode in combination with @emph{libmicrohttpd},
+because @emph{libmicrohttpd} provides a server and not a client.
+In client mode all outgoing payload will be masked
+(XOR-ed with random values).
+All incoming payload must be unmasked.
+If you use this mode, you must always call @code{MHD_websocket_stream_init2}
+instead of @code{MHD_websocket_stream_init}, because you need
+to pass a random number generator callback function for masking.
+
+This flag cannot be used together with @code{MHD_WEBSOCKET_FLAG_SERVER}.
+
+@item MHD_WEBSOCKET_FLAG_NO_FRAGMENTS
+You don't want to get fragmented data while decoding (default).
+Fragmented frames will be internally put together until
+they are complete.
+Whether or not data is fragmented is decided
+by the sender of the data during encoding.
+
+This cannot be used together with @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS}.
+
+@item MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+You want fragmented data, if it appears while decoding.
+You will receive the content of the fragmented frame,
+but if you are decoding text, you will never get an unfinished
+UTF-8 sequence (if the sequence appears between two fragments).
+Instead the text will end before the unfinished UTF-8 sequence.
+With the next fragment, which finishes the UTF-8 sequence,
+you will get the complete UTF-8 sequence.
+
+This cannot be used together with @code{MHD_WEBSOCKET_FLAG_NO_FRAGMENTS}.
+
+@item MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR
+If the websocket stream becomes invalid during decoding due to
+protocol errors, a matching close frame will automatically
+be generated.
+The close frame will be returned via the parameters
+@code{payload} and @code{payload_len} of @code{MHD_websocket_decode} and
+the return value is negative (a value of @code{enum MHD_WEBSOCKET_STATUS}).
+
+The generated close frame must be freed by the caller
+with @code{MHD_websocket_free}.
+
+@end table
+@end deftp
+
+
+@deftp {Enumeration} MHD_WEBSOCKET_FRAGMENTATION
+@cindex websocket
+This enumeration is used to specify the fragmentation behavior
+when encoding of data (text/binary) for a websocket stream.
+This is used with @code{MHD_websocket_encode_text} or
+@code{MHD_websocket_encode_binary}.
+
+Note that websocket streams are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@table @code
+@item MHD_WEBSOCKET_FRAGMENTATION_NONE
+You don't want to use fragmentation.
+The encoded frame consists of only one frame.
+
+@item MHD_WEBSOCKET_FRAGMENTATION_FIRST
+You want to use fragmentation.
+The encoded frame is the first frame of
+a series of data frames of the same type
+(text or binary).
+You may send control frames (ping, pong or close)
+between these data frames.
+
+@item MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING
+You want to use fragmentation.
+The encoded frame is not the first frame of
+the series of data frames, but also not the last one.
+You may send control frames (ping, pong or close)
+between these data frames.
+
+@item MHD_WEBSOCKET_FRAGMENTATION_LAST
+You want to use fragmentation.
+The encoded frame is the last frame of
+the series of data frames, but also not the first one.
+After this frame, you may send all types of frames again.
+
+@end table
+@end deftp
+
+
+@deftp {Enumeration} MHD_WEBSOCKET_STATUS
+@cindex websocket
+This enumeration is used for the return value of almost
+every websocket stream function.
+Errors are negative and values equal to or above zero mean a success.
+Positive values are only used by @code{MHD_websocket_decode}.
+
+Note that websocket streams are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@table @code
+@item MHD_WEBSOCKET_STATUS_OK
+The call succeeded.
+Especially for @code{MHD_websocket_decode} this means that no error occurred,
+but also no frame has been completed yet.
+For other functions this means simply a success.
+
+@item MHD_WEBSOCKET_STATUS_TEXT_FRAME
+@code{MHD_websocket_decode} has decoded a text frame.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded text (if any).
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_BINARY_FRAME
+@code{MHD_websocket_decode} has decoded a binary frame.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded binary data (if any).
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_CLOSE_FRAME
+@code{MHD_websocket_decode} has decoded a close frame.
+This means you must close the socket using @code{MHD_upgrade_action}
+with @code{MHD_UPGRADE_ACTION_CLOSE}.
+You may respond with a close frame before closing.
+The parameters @code{payload} and @code{payload_len} are filled with
+the close reason (if any).
+The close reason starts with a two byte sequence of close code
+in network byte order (see @code{enum MHD_WEBSOCKET_CLOSEREASON}).
+After these two bytes a UTF-8 encoded close reason may follow.
+You can call @code{MHD_websocket_split_close_reason} to split that
+close reason.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_PING_FRAME
+@code{MHD_websocket_decode} has decoded a ping frame.
+You should respond to this with a pong frame.
+The pong frame must contain the same binary data as
+the corresponding ping frame (if it had any).
+The parameters @code{payload} and @code{payload_len} are filled with
+the binary ping data (if any).
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_PONG_FRAME
+@code{MHD_websocket_decode} has decoded a pong frame.
+You should usually only receive pong frames if you sent
+a ping frame before.
+The binary data should be equal to your ping frame and can be
+used to distinguish the response if you sent multiple ping frames.
+The parameters @code{payload} and @code{payload_len} are filled with
+the binary pong data (if any).
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT
+@code{MHD_websocket_decode} has decoded a text frame fragment.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded text (if any).
+This is like @code{MHD_WEBSOCKET_STATUS_TEXT_FRAME}, but it can only
+appear if you specified @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS} during
+the call of @code{MHD_websocket_stream_init} or
+@code{MHD_websocket_stream_init2}.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT
+@code{MHD_websocket_decode} has decoded a binary frame fragment.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded binary data (if any).
+This is like @code{MHD_WEBSOCKET_STATUS_BINARY_FRAME}, but it can only
+appear if you specified @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS} during
+the call of @code{MHD_websocket_stream_init} or
+@code{MHD_websocket_stream_init2}.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_TEXT_NEXT_FRAGMENT
+@code{MHD_websocket_decode} has decoded the next text frame fragment.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded text (if any).
+This is like @code{MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT}, but it appears
+only after the first and before the last fragment of a series of fragments.
+It can only appear if you specified @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS}
+during the call of @code{MHD_websocket_stream_init} or
+@code{MHD_websocket_stream_init2}.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT
+@code{MHD_websocket_decode} has decoded the next binary frame fragment.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded binary data (if any).
+This is like @code{MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT}, but it appears
+only after the first and before the last fragment of a series of fragments.
+It can only appear if you specified @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS}
+during the call of @code{MHD_websocket_stream_init} or
+@code{MHD_websocket_stream_init2}.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT
+@code{MHD_websocket_decode} has decoded the last text frame fragment.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded text (if any).
+This is like @code{MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT}, but it appears
+only for the last fragment of a series of fragments.
+It can only appear if you specified @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS}
+during the call of @code{MHD_websocket_stream_init} or
+@code{MHD_websocket_stream_init2}.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT
+@code{MHD_websocket_decode} has decoded the last binary frame fragment.
+The parameters @code{payload} and @code{payload_len} are filled with
+the decoded binary data (if any).
+This is like @code{MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT}, but it appears
+only for the last fragment of a series of fragments.
+It can only appear if you specified @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS}
+during the call of @code{MHD_websocket_stream_init} or
+@code{MHD_websocket_stream_init2}.
+You must free the returned @code{payload} after use with
+@code{MHD_websocket_free}.
+
+@item MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR
+The call failed and the stream is invalid now for decoding.
+You must close the websocket now using @code{MHD_upgrade_action}
+with @code{MHD_UPGRADE_ACTION_CLOSE}.
+You may send a close frame before closing.
+This is only used by @code{MHD_websocket_decode} and happens
+if the stream contains errors (i. e. invalid byte data).
+
+@item MHD_WEBSOCKET_STATUS_STREAM_BROKEN
+You tried to decode something, but the stream has already
+been marked invalid.
+You must close the websocket now using @code{MHD_upgrade_action}
+with @code{MHD_UPGRADE_ACTION_CLOSE}.
+You may send a close frame before closing.
+This is only used by @code{MHD_websocket_decode} and happens
+if you call @code{MDM_websocket_decode} again after
+has been invalidated.
+You can call @code{MHD_websocket_stream_is_valid} at any time
+to check whether a stream is invalid or not.
+
+@item MHD_WEBSOCKET_STATUS_MEMORY_ERROR
+A memory allocation failed. The stream remains valid.
+If this occurred while decoding, the decoding could be
+possible later if enough memory is available.
+This could happen while decoding if you received a too big data frame.
+You could try to specify max_payload_size during the call of
+@code{MHD_websocket_stream_init} or @code{MHD_websocket_stream_init2} to
+avoid this and close the websocket instead.
+
+@item MHD_WEBSOCKET_STATUS_PARAMETER_ERROR
+You passed invalid parameters during the function call
+(i. e. a NULL pointer for a required parameter).
+The stream remains valid.
+
+@item MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED
+The maximum payload size has been exceeded.
+If you got this return code from @code{MHD_websocket_decode} then
+the stream becomes invalid and the websocket must be closed
+using @code{MHD_upgrade_action} with @code{MHD_UPGRADE_ACTION_CLOSE}.
+You may send a close frame before closing.
+The maximum payload size is specified during the call of
+@code{MHD_websocket_stream_init} or @code{MHD_websocket_stream_init2}.
+This can also appear if you specified 0 as maximum payload size
+when the message is greater than the maximum allocatable memory size
+(i. e. more than 4 GiB on 32 bit systems).
+If you got this return code from @code{MHD_websocket_encode_close},
+@code{MHD_websocket_encode_ping} or @code{MHD_websocket_encode_pong} then
+you passed to much payload data. The stream remains valid then.
+
+@item MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR
+An UTF-8 sequence is invalid.
+If you got this return code from @code{MHD_websocket_decode} then
+the stream becomes invalid and you must close the websocket
+using @code{MHD_upgrade_action} with @code{MHD_UPGRADE_ACTION_CLOSE}.
+You may send a close frame before closing.
+If you got this from @code{MHD_websocket_encode_text} or
+@code{MHD_websocket_encode_close} then you passed invalid UTF-8 text.
+The stream remains valid then.
+
+@item MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER
+A check routine for the HTTP headers came to the conclusion that
+the header value isn't valid for a websocket handshake request.
+This value can only be returned from the following functions:
+@code{MHD_websocket_check_http_version},
+@code{MHD_websocket_check_connection_header},
+@code{MHD_websocket_check_upgrade_header},
+@code{MHD_websocket_check_version_header},
+@code{MHD_websocket_create_accept_header}
+
+@end table
+@end deftp
+
+
+@deftp {Enumeration} MHD_WEBSOCKET_CLOSEREASON
+@cindex websocket
+Enumeration of possible close reasons for websocket close frames.
+
+The possible values are specified in RFC 6455 7.4.1
+These close reasons here are the default set specified by RFC 6455,
+but also other close reasons could be used.
+
+The definition is for short:
+@itemize @bullet
+@item 0-999 are never used (if you pass 0 in
+@code{MHD_websocket_encode_close} then no close reason is used).
+@item 1000-2999 are specified by RFC 6455.
+@item 3000-3999 are specified by libraries, etc. but must be registered by IANA.
+@item 4000-4999 are reserved for private use.
+@end itemize
+
+Note that websocket streams are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@table @code
+@item MHD_WEBSOCKET_CLOSEREASON_NO_REASON
+This value is used as placeholder for @code{MHD_websocket_encode_close}
+to tell that you don't want to specify any reason.
+If you use this value then no reason text may be used.
+This value cannot be a result of decoding, because this value
+is not a valid close reason for the websocket protocol.
+
+@item MHD_WEBSOCKET_CLOSEREASON_REGULAR
+You close the websocket because it fulfilled its purpose and shall
+now be closed in a normal, planned way.
+
+@item MHD_WEBSOCKET_CLOSEREASON_GOING_AWAY
+You close the websocket because you are shutting down the server or
+something similar.
+
+@item MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR
+You close the websocket because a protocol error occurred
+during decoding (i. e. invalid byte data).
+
+@item MHD_WEBSOCKET_CLOSEREASON_UNSUPPORTED_DATATYPE
+You close the websocket because you received data which you don't accept.
+For example if you received a binary frame,
+but your application only expects text frames.
+
+@item MHD_WEBSOCKET_CLOSEREASON_MALFORMED_UTF8
+You close the websocket because it contains malformed UTF-8.
+The UTF-8 validity is automatically checked by @code{MHD_websocket_decode},
+so you don't need to check it on your own.
+UTF-8 is specified in RFC 3629.
+
+@item MHD_WEBSOCKET_CLOSEREASON_POLICY_VIOLATED
+You close the websocket because you received a frame which is too big
+to process.
+You can specify the maximum allowed payload size during the call of
+@code{MHD_websocket_stream_init} or @code{MHD_websocket_stream_init2}.
+
+@item MHD_WEBSOCKET_CLOSEREASON_MISSING_EXTENSION
+This status code can be sent by the client if it
+expected a specific extension, but this extension hasn't been negotiated.
+
+@item MHD_WEBSOCKET_CLOSEREASON_UNEXPECTED_CONDITION
+The server closes the websocket because it encountered
+an unexpected condition that prevented it from fulfilling the request.
+
+@end table
+@end deftp
+
+
+@deftp {Enumeration} MHD_WEBSOCKET_UTF8STEP
+@cindex websocket
+Enumeration of possible UTF-8 check steps for websocket functions
+
+These values are used during the encoding of fragmented text frames
+or for error analysis while encoding text frames.
+Its values specify the next step of the UTF-8 check.
+UTF-8 sequences consist of one to four bytes.
+This enumeration just says how long the current UTF-8 sequence is
+and what is the next expected byte.
+
+Note that websocket streams are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@table @code
+@item MHD_WEBSOCKET_UTF8STEP_NORMAL
+There is no open UTF-8 sequence.
+The next byte must be 0x00-0x7F or 0xC2-0xF4.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1
+The second byte of a two byte UTF-8 sequence.
+The first byte was 0xC2-0xDF.
+The next byte must be 0x80-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2
+The second byte of a three byte UTF-8 sequence.
+The first byte was 0xE0.
+The next byte must be 0xA0-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2
+The second byte of a three byte UTF-8 sequence.
+The first byte was 0xED.
+The next byte must by 0x80-0x9F.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2
+The second byte of a three byte UTF-8 sequence.
+The first byte was 0xE1-0xEC or 0xEE-0xEF.
+The next byte must be 0x80-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2
+The third byte of a three byte UTF-8 sequence.
+The next byte must be 0x80-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3
+The second byte of a four byte UTF-8 sequence.
+The first byte was 0xF0.
+The next byte must be 0x90-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3
+The second byte of a four byte UTF-8 sequence.
+The first byte was 0xF4.
+The next byte must be 0x80-0x8F.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3
+The second byte of a four byte UTF-8 sequence.
+The first byte was 0xF1-0xF3.
+The next byte must be 0x80-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3
+The third byte of a four byte UTF-8 sequence.
+The next byte must be 0x80-0xBF.
+
+@item MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3
+The fourth byte of a four byte UTF-8 sequence.
+The next byte must be 0x80-0xBF.
+
+@end table
+@end deftp
+
+
+@deftp {Enumeration} MHD_WEBSOCKET_VALIDITY
+@cindex websocket
+Enumeration of validity values of a websocket stream
+
+These values are used for @code{MHD_websocket_stream_is_valid}
+and specify the validity status.
+
+Note that websocket streams are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@table @code
+@item MHD_WEBSOCKET_VALIDITY_INVALID
+The stream is invalid.
+It cannot be used for decoding anymore.
+
+@item MHD_WEBSOCKET_VALIDITY_VALID
+The stream is valid.
+Decoding works as expected.
+
+@item MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES
+The stream has received a close frame and
+is partly invalid.
+You can still use the stream for decoding,
+but if a data frame is received an error will be reported.
+After a close frame has been sent, no data frames
+may follow from the sender of the close frame.
+
+@end table
+@end deftp
+
+
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 @c ------------------------------------------------------------
@@ -1085,6 +1757,11 @@
 @end deftp
 
 
+@deftp {C Struct} MHD_IoVec
+An element of an array of memory buffers.
+@end deftp
+
+
 @deftp {C Struct} MHD_PostProcessor
 @cindex POST method
 Handle for @code{POST} processing.
@@ -1101,6 +1778,12 @@
 @end deftp
 
 
+@deftp {C Struct} MHD_WebSocketStream
+@cindex websocket
+Information about a MHD websocket stream.
+@end deftp
+
+
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 @c ------------------------------------------------------------
@@ -1108,7 +1791,7 @@
 @chapter Callback functions definition
 
 
-@deftypefn {Function Pointer} int {*MHD_AcceptPolicyCallback} (void *cls, const struct sockaddr * addr, socklen_t addrlen)
+@deftypefn {Function Pointer} enum MHD_Result {*MHD_AcceptPolicyCallback} (void *cls, const struct sockaddr * addr, socklen_t addrlen)
 Invoked in the context of a connection to allow or deny a client to
 connect.  This callback return @code{MHD_YES} if connection is allowed,
 @code{MHD_NO} if not.
@@ -1124,7 +1807,7 @@
 @end deftypefn
 
 
-@deftypefn {Function Pointer} int {*MHD_AccessHandlerCallback} (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls)
+@deftypefn {Function Pointer} enum MHD_Result {*MHD_AccessHandlerCallback} (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls)
 Invoked in the context of a connection to answer a request from the
 client.  This callback must call MHD functions (example: the
 @code{MHD_Response} ones) to provide content to give back to the client
@@ -1190,7 +1873,7 @@
 avoid this, clients must be able to process upload data incrementally
 and reduce the value of @code{upload_data_size}.
 
-@item con_cls
+@item req_cls
 reference to a pointer, initially set to @code{NULL}, that this callback can
 set to some address and that will be preserved by MHD for future
 calls for this request;
@@ -1206,7 +1889,7 @@
 @end deftypefn
 
 
-@deftypefn {Function Pointer} void {*MHD_RequestCompletedCallback} (void *cls, struct MHD_Connectionconnection, void **con_cls, enum MHD_RequestTerminationCode toe)
+@deftypefn {Function Pointer} void {*MHD_RequestCompletedCallback} (void *cls, struct MHD_Connectionconnection, void **req_cls, enum MHD_RequestTerminationCode toe)
 Signature of the callback used by MHD to notify the application about
 completed requests.
 
@@ -1217,7 +1900,7 @@
 @item connection
 connection handle;
 
-@item con_cls
+@item req_cls
 value as set by the last call to the
 @code{MHD_AccessHandlerCallback};
 
@@ -1227,7 +1910,7 @@
 @end deftypefn
 
 
-@deftypefn {Function Pointer} int {*MHD_KeyValueIterator} (void *cls, enum MHD_ValueKind kind, const char *key, const char *value)
+@deftypefn {Function Pointer} enum MHD_Result {*MHD_KeyValueIterator} (void *cls, enum MHD_ValueKind kind, const char *key, const char *value, size_t value_size)
 Iterator over key-value pairs.  This iterator can be used to iterate
 over all of the cookies, headers, or @code{POST}-data fields of a
 request, and also to iterate over the headers that have been added to a
@@ -1246,6 +1929,17 @@
 @item value
 value corresponding value, can be NULL
 
+@item value_size
+number of bytes in @code{value}. This argument was introduced in
+@code{MHD_VERSION} 0x00096301 to allow applications to use binary
+zeros in values.  Applications using this argument must ensure that
+they are using a sufficiently recent version of MHD, i.e. by testing
+@code{MHD_get_version()} for values above or equal to 0.9.64.
+Applications that do not need zeros in values and that want to compile
+without warnings against newer versions of MHD should not declare this
+argument and cast the function pointer argument to
+@code{MHD_KeyValueIterator}.
+
 @end table
 
 Return @code{MHD_YES} to continue iterating, @code{MHD_NO} to abort the
@@ -1253,7 +1947,7 @@
 @end deftypefn
 
 
-@deftypefn {Function Pointer} int {*MHD_ContentReaderCallback} (void *cls, uint64_t pos, char *buf, size_t max)
+@deftypefn {Function Pointer} ssize_t {*MHD_ContentReaderCallback} (void *cls, uint64_t pos, char *buf, size_t max)
 Callback used by MHD in order to obtain content.  The callback has to
 copy at most @var{max} bytes of content into @var{buf}.  The total
 number of bytes that has been placed into @var{buf} should be returned.
@@ -1309,7 +2003,7 @@
 @end deftypefn
 
 
-@deftypefn {Function Pointer} int {*MHD_PostDataIterator} (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size)
+@deftypefn {Function Pointer} enum MHD_Result {*MHD_PostDataIterator} (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size)
 Iterator over key-value pairs where the value maybe made available in
 increments and/or may not be zero-terminated.  Used for processing
 @code{POST} data.
@@ -1348,6 +2042,95 @@
 @end deftypefn
 
 
+@deftypefn {Function Pointer} void* {*MHD_WebSocketMallocCallback} (size_t buf_len)
+@cindex websocket
+This callback function is used internally by many websocket functions
+for allocating data.
+By default @code{malloc} is used.
+You can use your own allocation function with @code{MHD_websocket_stream_init2}
+if you wish to.
+This can be useful for operating systems like Windows
+where @code{malloc}, @code{realloc} and @code{free} are compiler-dependent.
+You can call the associated @code{malloc} callback of
+a websocket stream with @code{MHD_websocket_malloc}.
+
+@table @var
+@item buf_len
+size of the buffer to allocate in bytes.
+@end table
+
+Return the pointer of the allocated buffer or @code{NULL} on failure.
+@end deftypefn
+
+
+@deftypefn {Function Pointer} void* {*MHD_WebSocketReallocCallback} (void *buf, size_t new_buf_len)
+@cindex websocket
+This callback function is used internally by many websocket
+functions for reallocating data.
+By default @code{realloc} is used.
+You can use your own reallocation function with
+@code{MHD_websocket_stream_init2} if you wish to.
+This can be useful for operating systems like Windows
+where @code{malloc}, @code{realloc} and @code{free} are compiler-dependent.
+You can call the associated @code{realloc} callback of
+a websocket stream with @code{MHD_websocket_realloc}.
+
+@table @var
+@item buf
+current buffer, may be @code{NULL};
+
+@item new_buf_len
+new size of the buffer in bytes.
+@end table
+
+Return the pointer of the reallocated buffer or @code{NULL} on failure.
+On failure the old pointer must remain valid.
+@end deftypefn
+
+
+@deftypefn {Function Pointer} void {*MHD_WebSocketFreeCallback} (void *buf)
+@cindex websocket
+This callback function is used internally by many websocket
+functions for freeing data.
+By default @code{free} is used.
+You can use your own free function with
+@code{MHD_websocket_stream_init2} if you wish to.
+This can be useful for operating systems like Windows
+where @code{malloc}, @code{realloc} and @code{free} are compiler-dependent.
+You can call the associated @code{free} callback of
+a websocket stream with @code{MHD_websocket_free}.
+
+@table @var
+@item cls
+current buffer to free, this may be @code{NULL} then nothing happens.
+@end table
+@end deftypefn
+
+
+@deftypefn {Function Pointer} size_t {*MHD_WebSocketRandomNumberGenerator} (void *cls, void* buf, size_t buf_len)
+@cindex websocket
+This callback function is used for generating random numbers
+for masking payload data in client mode.
+If you use websockets in server mode with @emph{libmicrohttpd} then
+you don't need a random number generator, because
+the server doesn't mask its outgoing messages.
+However if you wish to use a websocket stream in client mode,
+you must pass this callback function to @code{MHD_websocket_stream_init2}.
+
+@table @var
+@item cls
+closure specified in @code{MHD_websocket_stream_init2};
+@item buf
+buffer to fill with random values;
+@item buf_len
+size of buffer in bytes.
+@end table
+
+Return the number of generated random bytes.
+The return value should usually equal to buf_len.
+@end deftypefn
+
+
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 @c ------------------------------------------------------------
@@ -1400,7 +2183,7 @@
 @end deftypefun
 
 
-@deftypefun int MHD_quiesce_daemon (struct MHD_Daemon *daemon)
+@deftypefun MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon)
 @cindex quiesce
 Stop accepting connections from the listening socket.  Allows clients
 to continue processing, but stops accepting new connections.  Note
@@ -1426,7 +2209,7 @@
 @end deftypefun
 
 
-@deftypefun int MHD_run (struct MHD_Daemon *daemon)
+@deftypefun enum MHD_Result MHD_run (struct MHD_Daemon *daemon)
 Run webserver operations (without blocking unless in client callbacks).
 This method should be called by clients in combination with
 @code{MHD_get_fdset()} if the client-controlled @code{select}-method is used.
@@ -1447,7 +2230,7 @@
 @end deftypefun
 
 
-@deftypefun int MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set)
+@deftypefun enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set)
 Run webserver operations given sets of ready socket handles.
 @cindex select
 
@@ -1489,7 +2272,7 @@
 HTTP client, or if you are building a proxy.
 
 If you use this API in conjunction with a internal select or a thread
-pool, you must set the option @code{MHD_USE_PIPE_FOR_SHUTDOWN} to
+pool, you must set the option @code{MHD_USE_ITC} to
 ensure that the freshly added connection is immediately processed by
 MHD.
 
@@ -1523,12 +2306,21 @@
 @chapter Implementing external @code{select}
 
 
-@deftypefun int MHD_get_fdset (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd)
+@deftypefun enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd)
 Obtain the @code{select()} sets for this daemon. The daemon's socket
 is added to @var{read_fd_set}. The list of currently existent
 connections is scanned and their file descriptors added to the correct
 set.
 
+When calling this function, FD_SETSIZE is assumed to be platform's
+default.  If you changed FD_SETSIZE for your application,
+you should use @code{MHD_get_fdset2()} instead.
+
+This function should only be called in when MHD is configured to use
+external select with @code{select()} or with @code{epoll()}.  In
+the latter case, it will only add the single @code{epoll()} file
+descriptor used by MHD to the sets.
+
 After the call completed successfully: the variable referenced by
 @var{max_fd} references the file descriptor with highest integer
 identifier. The variable must be set to zero before invoking this
@@ -1540,7 +2332,12 @@
 @end deftypefun
 
 
-@deftypefun int MHD_get_timeout (struct MHD_Daemon *daemon, unsigned long long *timeout)
+@deftypefun enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd, unsigned int fd_setsize)
+Like @code{MHD_get_fdset()}, except that you can manually specify the value of FD_SETSIZE used by your application.
+@end deftypefun
+
+
+@deftypefun enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, unsigned long long *timeout)
 @cindex timeout
 Obtain timeout value for select for this daemon (only needed if
 connection timeout is used).  The returned value is how many
@@ -1549,7 +2346,7 @@
 @code{MHD_USE_THREAD_PER_CONNECTION} mode is in use (since then it is
 not meaningful to ask for a timeout, after all, there is concurrenct
 activity).  The function must also not be called by user-code if
-@code{MHD_USE_INTERNAL_SELECT} is in use.  In the latter case, the
+@code{MHD_USE_INTERNAL_POLLING_THREAD} is in use.  In the latter case, the
 behavior is undefined.
 
 @table @var
@@ -1560,7 +2357,7 @@
 @end table
 
 Return @code{MHD_YES} on success, @code{MHD_NO} if timeouts are not used
-(or no connections exist that would necessiate the use of a timeout
+(or no connections exist that would necessitate the use of a timeout
 right now).
 @end deftypefun
 
@@ -1573,7 +2370,9 @@
 
 
 @deftypefun int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls)
-Get all the headers matching @var{kind} from the request.
+Get all the headers matching @var{kind} from the request.  The @var{kind}
+argument can be a bitmask, ORing the various header kinds that are
+requested.
 
 The @var{iterator} callback is invoked once for each header, with
 @var{iterator_cls} as first argument.  After version 0.9.19, the
@@ -1599,7 +2398,7 @@
 @end deftypefun
 
 
-@deftypefun int MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char * key, const char * value)
+@deftypefun enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value)
 This function can be used to append an entry to
 the list of HTTP headers of a connection (so that the
 @code{MHD_get_connection_values function} will return
@@ -1634,12 +2433,18 @@
 @var{kind}, return one of them (the ``first'', whatever that means).
 @var{key} must reference a zero-terminated ASCII-coded string
 representing the header to look for: it is compared against the
-headers using @code{strcasecmp()}, so case is ignored.  A value of
-@code{NULL} for @var{key} can be used to lookup 'trailing' values without a
-key, for example if a URI is of the form
-``http://example.com/?trailer'', a @var{key} of @code{NULL} can be used to
-access ``tailer" The function returns @code{NULL} if no matching item
-was found.
+headers using (basically) @code{strcasecmp()}, so case is ignored.
+@end deftypefun
+
+@deftypefun {const char *} MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr)
+Get a particular header value.  If multiple values match the
+@var{kind}, return one of them (the ``first'', whatever that means).
+@var{key} must reference an ASCII-coded string
+representing the header to look for: it is compared against the
+headers using (basically) @code{strncasecmp()}, so case is ignored.
+The @var{value_ptr} is set to the address of the value found,
+and @var{value_size_ptr} is set to the number of bytes in the
+value.
 @end deftypefun
 
 
@@ -1671,6 +2476,7 @@
 * microhttpd-response headers:: Adding headers to a response.
 * microhttpd-response options:: Setting response options.
 * microhttpd-response inspect:: Inspecting a response object.
+* microhttpd-response upgrade:: Creating a response for protocol upgrades.
 @end menu
 
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -1680,7 +2486,7 @@
 @section Enqueuing a response
 
 
-@deftypefun int MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response)
+@deftypefun enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response)
 Queue a response to be transmitted to the client as soon as possible
 but only after MHD_AccessHandlerCallback returns.  This function
 checks that it is legal to queue a response at this time for the
@@ -1808,6 +2614,21 @@
 @end deftypefun
 
 
+@deftypefun {struct MHD_Response *} MHD_create_response_from_pipe (uint64_t size, int fd)
+Create a response object.  The response object can be extended with
+header information and then it can be used ONLY ONCE.
+
+@table @var
+@item fd
+file descriptor of the read-end of the pipe; will be
+closed when response is destroyed.
+The descriptor should be in blocking-IO mode.
+@end table
+
+Return @code{NULL} on error (i.e. out of memory).
+@end deftypefun
+
+
 @deftypefun {struct MHD_Response *} MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset)
 Create a response object.  The response object can be extended with
 header information and then it can be used any number of times.
@@ -1877,6 +2698,24 @@
 @end deftypefun
 
 
+@deftypefun {struct MHD_Response *} MHD_create_response_from_buffer_with_free_callback (size_t size, void *data,  MHD_ContentReaderFreeCallback crfc)
+Create a response object.  The buffer at the end must be free'd
+by calling the @var{crfc} function.
+
+@table @var
+@item size
+size of the data portion of the response;
+
+@item buffer
+the data itself;
+
+@item crfc
+function to call at the end to free memory allocated at @var{buffer}.
+@end table
+
+Return @code{NULL} on error (i.e. invalid arguments, out of memory).
+@end deftypefun
+
 @deftypefun {struct MHD_Response *} MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy)
 Create a response object.  The response object can be extended with
 header information and then it can be used any number of times.
@@ -1918,6 +2757,28 @@
 @end example
 
 
+@deftypefun {struct MHD_Response *} MHD_create_response_from_iovec (const struct MHD_IoVec *iov, int iovcnt, MHD_ContentReaderFreeCallback crfc, void *cls)
+Create a response object from an array of memory buffers.
+The response object can be extended with header information and then be used
+any number of times.
+@table @var
+@item iov
+the array for response data buffers, an internal copy of this will be made; however, note that the data pointed to by the @var{iov} is not copied and must be preserved unchanged at the given locations until the response is no longer in use and the @var{crfc} is called;
+
+@item iovcnt
+the number of elements in @var{iov};
+
+@item crfc
+the callback to call to free resources associated with @var{iov};
+
+@item cls
+the argument to @var{crfc};
+@end table
+
+Return @code{NULL} on error (i.e. invalid arguments, out of memory).
+@end deftypefun
+
+
 
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
@@ -1926,7 +2787,7 @@
 @section Adding headers to a response
 
 
-@deftypefun int MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content)
+@deftypefun enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content)
 Add a header line to the response. The strings referenced by
 @var{header} and @var{content} must be zero-terminated and they are
 duplicated into memory blocks embedded in @var{response}.
@@ -1934,12 +2795,23 @@
 Notice that the strings must not hold newlines, carriage returns or tab
 chars.
 
+MHD_add_response_header() prevents applications from setting a
+``Transfer-Encoding'' header to values other than ``identity'' or
+``chunked'' as other transfer encodings are not supported by MHD. Note
+that usually MHD will pick the transfer encoding correctly
+automatically, but applications can use the header to force a
+particular behavior.
+
+MHD_add_response_header() also prevents applications from setting a
+``Content-Length'' header. MHD will automatically set a correct
+``Content-Length'' header if it is possible and allowed.
+
 Return @code{MHD_NO} on error (i.e. invalid header or content format or
 memory allocation error).
 @end deftypefun
 
 
-@deftypefun int MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content)
+@deftypefun enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content)
 Add a footer line to the response. The strings referenced by
 @var{footer} and @var{content} must be zero-terminated and they are
 duplicated into memory blocks embedded in @var{response}.
@@ -1957,7 +2829,7 @@
 
 
 
-@deftypefun int MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content)
+@deftypefun enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content)
 Delete a header (or footer) line from the response.  Return @code{MHD_NO} on error
 (arguments are invalid or no such header known).
 @end deftypefun
@@ -1968,7 +2840,7 @@
 @section Setting response options
 
 
-@deftypefun int MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...)
+@deftypefun enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...)
 Set special flags and options for a response.
 
 Calling this functions sets the given flags and options for the response.
@@ -2021,6 +2893,104 @@
 @end deftypefun
 
 
+@c ------------------------------------------------------------
+@node microhttpd-response upgrade
+@section Creating a response for protocol upgrades
+@cindex WebSockets
+@cindex Upgrade
+@cindex HTTP2
+@cindex RFC2817
+
+With RFC 2817 a mechanism to switch protocols within HTTP was
+introduced.  Here, a client sends a request with a ``Connection:
+Upgrade'' header.  The server responds with a ``101 Switching
+Protocols'' response header, after which the two parties begin to
+speak a different (non-HTTP) protocol over the TCP connection.
+
+This mechanism is used for upgrading HTTP 1.1 connections to HTTP2 or
+HTTPS, as well as for implementing WebSockets.  Which protocol
+upgrade is performed is negotiated between server and client in
+additional headers, in particular the ``Upgrade'' header.
+
+MHD supports switching protocols using this mechanism only if the
+@code{MHD_ALLOW_SUSPEND_RESUME} flag has been set when starting
+the daemon.  If this flag has been set, applications can upgrade
+a connection by queueing a response (using the
+@code{MHD_HTTP_SWITCHING_PROTOCOLS} status code) which must
+have been created with the following function:
+
+
+@deftypefun enum MHD_Result MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls)
+Create a response suitable for switching protocols.  Returns @code{MHD_YES} on success.  @code{upgrade_handler} must not be @code{NULL}.
+
+When creating this type of response, the ``Connection: Upgrade''
+header will be set automatically for you.  MHD requires that you
+additionally set an ``Upgrade:'' header.  The ``Upgrade'' header
+must simply exist, the specific value is completely up to the
+application.
+
+@end deftypefun
+
+The @code{upgrade_handler} argument to the above has the following type:
+
+
+@deftypefn {Function Pointer} void {*MHD_UpgradeHandler} (void *cls, struct MHD_Connection *connection, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh)
+This function will be called once MHD has transmitted the header of the response to the connection that is being upgraded.  At this point, the application is expected to take over the socket @code{sock} and speak the non-HTTP protocol to which the connection was upgraded.  MHD will no longer use the socket; this includes handling timeouts.  The application must call @code{MHD_upgrade_action} with an upgrade action of @code{MHD_UPGRADE_ACTION_CLOSE} when it is done processing the connection to close the socket.  The application must not call @code{MHD_stop_daemon} on the respective daemon as long as it is still handling the connection.  The arguments given to the @code{upgrade_handler} have the following meaning:
+
+@table @var
+@item cls
+matches the @code{upgrade_handler_cls} that was given to @code{MHD_create_response_for_upgrade}
+@item connection
+identifies the connection that is being upgraded;
+
+@item req_cls
+last value left in `*req_cls` in the `MHD_AccessHandlerCallback`
+
+@item extra_in
+buffer of bytes MHD read ``by accident'' from the socket already.  This can happen if the client eagerly transmits more than just the HTTP request.   The application should treat these as if it had read them from the socket.
+
+@item extra_in_size
+number of bytes in @code{extra_in}
+
+@item sock
+the socket which the application can now use directly for some bi-directional communication with the client. The application can henceforth use @code{recv()} and @code{send()} or @code{read()} and @code{write()} system calls on the socket.  However, @code{ioctl()} and @code{setsockopt()} functions will not work as expected when using HTTPS.  Such operations may be supported in the future via @code{MHD_upgrade_action}.   Most importantly, the application must never call @code{close()} on this socket.  Closing the socket must be done using @code{MHD_upgrade_action}.  However, while close is forbidden, the application may call @code{shutdown()} on the socket.
+
+@item urh
+argument for calls to @code{MHD_upgrade_action}.  Applications must eventually use this function to perform the @code{close()} action on the socket.
+@end table
+
+@end deftypefn
+
+@deftypefun enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...)
+Perform special operations related to upgraded connections.
+
+@table @var
+@item urh
+identifies the upgraded connection to perform an action on
+
+@item action
+specifies the action to perform; further arguments to the function depend on the specifics of the action.
+@end table
+
+@end deftypefun
+
+
+@deftp {Enumeration} MHD_UpgradeAction
+Set of actions to be performed on upgraded connections.  Passed as an argument to
+@code{MHD_upgrade_action()}.
+
+@table @code
+@item MHD_UPGRADE_ACTION_CLOSE
+Closes the connection.  Must be called once the application is done with the client.  Takes no additional arguments.
+@item MHD_UPGRADE_ACTION_CORK_ON
+Enable corking on the underlying socket.
+@item MHD_UPGRADE_ACTION_CORK_OFF
+Disable corking on the underlying socket.
+
+@end table
+@end deftp
+
+
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 @c ------------------------------------------------------------
@@ -2043,14 +3013,14 @@
 @code{MHD_USE_THREAD_PER_CONNECTION} should use the
 following functions to perform flow control.
 
-@deftypefun int MHD_suspend_connection (struct MHD_Connection *connection)
+@deftypefun enum MHD_Result MHD_suspend_connection (struct MHD_Connection *connection)
 Suspend handling of network data for a given connection.  This can
 be used to dequeue a connection from MHD's event loop (external
 select, internal select or thread pool; not applicable to
 thread-per-connection!) for a while.
 
 If you use this API in conjunction with a internal select or a
-thread pool, you must set the option @code{MHD_USE_SUSPEND_RESUME} to
+thread pool, you must set the option @code{MHD_ALLOW_SUSPEND_RESUME} to
 ensure that a resumed connection is immediately processed by MHD.
 
 Suspended connections continue to count against the total number of
@@ -2061,7 +3031,15 @@
 client.
 
 The only safe time to suspend a connection is from the
-@code{MHD_AccessHandlerCallback}.
+@code{MHD_AccessHandlerCallback} or from the respective
+@code{MHD_ContentReaderCallback} (but in this case the
+response object must not be shared among multiple
+connections).
+
+When suspending from the @code{MHD_AccessHandlerCallback}
+you MUST afterwards return @code{MHD_YES} from the access handler
+callback (as MHD_NO would imply to both close and suspend
+the connection, which is not allowed).
 
 Finally, it is an API violation to call @code{MHD_stop_daemon} while
 having suspended connections (this will at least create memory and
@@ -2074,12 +3052,22 @@
 @end table
 @end deftypefun
 
-@deftypefun int MHD_resume_connection (struct MHD_Connection *connection)
+@deftypefun enum MHD_Result MHD_resume_connection (struct MHD_Connection *connection)
 Resume handling of network data for suspended connection.  It is safe
 to resume a suspended connection at any time.  Calling this function
 on a connection that was not previously suspended will result in
 undefined behavior.
 
+If you are using this function in ``external'' select mode, you must
+make sure to run @code{MHD_run} afterwards (before again calling
+@code{MHD_get_fdset}), as otherwise the change may not be reflected in
+the set returned by @code{MHD_get_fdset} and you may end up with a
+connection that is stuck until the next network activity.
+
+You can check whether a connection is currently suspended using
+@code{MHD_get_connection_info} by querying for
+@code{MHD_CONNECTION_INFO_CONNECTION_SUSPENDED}.
+
 @table @var
 @item connection
 the connection to resume
@@ -2119,8 +3107,8 @@
 client certificates is presented in the MHD tutorial.
 
 @menu
-* microhttpd-dauth basic:: Using Basic Authentication.
-* microhttpd-dauth digest:: Using Digest Authentication.
+* microhttpd-dauth basic::      Using Basic Authentication.
+* microhttpd-dauth digest::     Using Digest Authentication.
 @end menu
 
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -2129,21 +3117,28 @@
 @node microhttpd-dauth basic
 @section Using Basic Authentication
 
-@deftypefun {char *} MHD_basic_auth_get_username_password (struct MHD_Connection *connection, char** password)
-Get the username and password from the basic authorization header sent by the client.
-Return @code{NULL} if no username could be found, a pointer to the username if found.
-If returned value is not @code{NULL}, the value must be @code{free()}'ed.
-
-@var{password} reference a buffer to store the password. It can be @code{NULL}.
-If returned value is not @code{NULL}, the value must be @code{free()}'ed.
+@deftypefun {void} MHD_free (void *ptr)
+Free the memory given at @code{ptr}.  Used to free data structures allocated by MHD. Calls @code{free(ptr)}.
 @end deftypefun
 
-@deftypefun {int} MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection, const char *realm, struct MHD_Response *response)
+@deftypefun {char *} MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection)
+Get the username and password from the basic authorization header sent by the client.
+Return @code{NULL} if no Basic Authorization header set by the client or if Base64
+encoding is invalid; a pointer to the structure with username and password
+if found values set by the client.
+If returned value is not @code{NULL}, the value must be @code{MHD_free()}'ed.
+@end deftypefun
+
+@deftypefun {enum MHD_Result} MHD_queue_basic_auth_fail_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response)
 Queues a response to request basic authentication from the client.
 Return @code{MHD_YES} if successful, otherwise @code{MHD_NO}.
 
 @var{realm} must reference to a zero-terminated string representing the realm.
 
+@var{prefer_utf8} if set to @code{MHD_YES} then parameter @code{charset} with value
+@code{UTF-8} will be added to the response authentication header which indicates
+that UTF-8 encoding is preferred for username and password.
+
 @var{response} a response structure to specify what shall be presented to the
 client with a 401 HTTP status.
 @end deftypefun
@@ -2154,13 +3149,88 @@
 @node microhttpd-dauth digest
 @section Using Digest Authentication
 
+MHD supports MD5 (deprecated by IETF) and SHA-256 hash algorithms
+for digest authentication. The @code{MHD_DigestAuthAlgorithm} enumeration
+is used to specify which algorithm should be used.
+
+@deftp {Enumeration} MHD_DigestAuthAlgorithm
+Which digest algorithm should be used. Must be used consistently.
+
+@table @code
+@item MHD_DIGEST_ALG_AUTO
+Have MHD pick an algorithm currently considered secure.  For now defaults to SHA-256.
+
+@item MHD_DIGEST_ALG_MD5
+Force use of (deprecated, ancient, insecure) MD5.
+
+@item MHD_DIGEST_ALG_SHA256
+Force use of SHA-256.
+
+@end table
+@end deftp
+
+@deftp {Enumeration} MHD_DigestAuthResult
+The result of digest authentication of the client.
+
+@table @code
+@item MHD_DAUTH_OK
+Authentication OK.
+
+@item MHD_DAUTH_ERROR
+General error, like ``out of memory''.
+
+@item MHD_DAUTH_WRONG_HEADER
+No ``Authorization'' header or wrong format of the header.
+
+@item MHD_DAUTH_WRONG_USERNAME
+Wrong ``username''.
+
+@item MHD_DAUTH_WRONG_REALM
+Wrong ``realm''.
+
+@item MHD_DAUTH_WRONG_URI
+Wrong ``URI'' (or URI parameters).
+
+@item MHD_DAUTH_NONCE_STALE
+The ``nonce'' is too old. Suggest the client to retry with the same username and
+password to get the fresh ``nonce''.
+The validity of the ``nonce'' may not be checked.
+
+@item MHD_DAUTH_NONCE_WRONG
+The ``nonce'' is wrong. May indicate an attack attempt.
+
+@item MHD_DAUTH_RESPONSE_WRONG
+The ``response'' is wrong. May indicate an attack attempt.
+
+@end table
+@end deftp
+
+
 @deftypefun {char *} MHD_digest_auth_get_username (struct MHD_Connection *connection)
 Find and return a pointer to the username value from the request header.
 Return @code{NULL} if the value is not found or header does not exist.
-If returned value is not @code{NULL}, the value must be @code{free()}'ed.
+If returned value is not @code{NULL}, the value must be @code{MHD_free()}'ed.
 @end deftypefun
 
-@deftypefun int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout)
+@deftypefun enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo)
+Checks if the provided values in the WWW-Authenticate header are valid
+and sound according to RFC7616. If valid return @code{MHD_DAUTH_OK}, otherwise return the error code.
+
+@var{realm} must reference to a zero-terminated string representing the realm.
+
+@var{username} must reference to a zero-terminated string representing the username,
+it is usually the returned value from MHD_digest_auth_get_username.
+
+@var{password} must reference to a zero-terminated string representing the password,
+most probably it will be the result of a lookup of the username against a local database.
+
+@var{nonce_timeout} the nonce validity duration in seconds.
+Most of the time it is sound to specify 300 seconds as its values.
+
+@var{algo} which digest algorithm should we use.
+@end deftypefun
+
+@deftypefun int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo)
 Checks if the provided values in the WWW-Authenticate header are valid
 and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}.
 
@@ -2174,9 +3244,109 @@
 
 @var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid.
 Most of the time it is sound to specify 300 seconds as its values.
+
+@var{algo} which digest algorithm should we use.
 @end deftypefun
 
-@deftypefun int MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale)
+
+@deftypefun int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout)
+Checks if the provided values in the WWW-Authenticate header are valid
+and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}.
+Deprecated, use @code{MHD_digest_auth_check2} instead.
+
+
+@var{realm} must reference to a zero-terminated string representing the realm.
+
+@var{username} must reference to a zero-terminated string representing the username,
+it is usually the returned value from MHD_digest_auth_get_username.
+
+@var{password} must reference to a zero-terminated string representing the password,
+most probably it will be the result of a lookup of the username against a local database.
+
+@var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid.
+Most of the time it is sound to specify 300 seconds as its values.
+@end deftypefun
+
+
+
+@deftypefun enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo)
+Checks if the provided values in the WWW-Authenticate header are valid
+and sound according to RFC7616. If valid return @code{MHD_DAUTH_OK}, otherwise return the error code.
+
+@var{realm} must reference to a zero-terminated string representing the realm.
+
+@var{username} must reference to a zero-terminated string representing the username,
+it is usually the returned value from MHD_digest_auth_get_username.
+
+@var{digest} the pointer to the binary digest for the precalculated hash value ``username:realm:password'' with specified @var{algo}.
+
+@var{digest_size} the number of bytes in @var{digest} (the size must match @var{algo}!)
+
+@var{nonce_timeout} the nonce validity duration in seconds.
+Most of the time it is sound to specify 300 seconds as its values.
+
+@var{algo} digest authentication algorithm to use.
+@end deftypefun
+
+@deftypefun int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo)
+Checks if the provided values in the WWW-Authenticate header are valid
+and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}.
+
+@var{realm} must reference to a zero-terminated string representing the realm.
+
+@var{username} must reference to a zero-terminated string representing the username,
+it is usually the returned value from MHD_digest_auth_get_username.
+
+@var{digest} pointer to the binary MD5 sum for the precalculated hash value ``userame:realm:password''. The size must match the selected @var{algo}!
+
+@var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid.
+Most of the time it is sound to specify 300 seconds as its values.
+
+@var{algo} digest authentication algorithm to use.
+@end deftypefun
+
+@deftypefun int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const unsigned char digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout)
+Checks if the provided values in the WWW-Authenticate header are valid
+and sound according to RFC2716. If valid return @code{MHD_YES}, otherwise return @code{MHD_NO}.
+Deprecated, use @code{MHD_digest_auth_check_digest2} instead.
+
+@var{realm} must reference to a zero-terminated string representing the realm.
+
+@var{username} must reference to a zero-terminated string representing the username,
+it is usually the returned value from MHD_digest_auth_get_username.
+
+@var{digest} pointer to the binary MD5 sum for the precalculated hash value ``userame:realm:password'' of @code{MHD_MD5_DIGEST_SIZE} bytes.
+
+@var{nonce_timeout} is the amount of time in seconds for a nonce to be invalid.
+Most of the time it is sound to specify 300 seconds as its values.
+@end deftypefun
+
+
+@deftypefun enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo)
+Queues a response to request authentication from the client,
+return @code{MHD_YES} if successful, otherwise @code{MHD_NO}.
+
+@var{realm} must reference to a zero-terminated string representing the realm.
+
+@var{opaque} must reference to a zero-terminated string representing a value
+that gets passed to the client and expected to be passed again to the server
+as-is. This value can be a hexadecimal or base64 string.
+
+@var{response} a response structure to specify what shall be presented to the
+client with a 401 HTTP status.
+
+@var{signal_stale} a value that signals "stale=true" in the response header to
+indicate the invalidity of the nonce and no need to ask for authentication
+parameters and only a new nonce gets generated. @code{MHD_YES} to generate a new
+nonce, @code{MHD_NO} to ask for authentication parameters.
+
+@var{algo} which digest algorithm should we use.  The same algorithm
+must then be selected when checking digests received from clients!
+
+@end deftypefun
+
+
+@deftypefun enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale)
 Queues a response to request authentication from the client,
 return @code{MHD_YES} if successful, otherwise @code{MHD_NO}.
 
@@ -2215,25 +3385,37 @@
   const char *password = "testpass";
   const char *realm = "test@@example.com";
   int ret;
+  static int already_called_marker;
 
-  username = MHD_digest_auth_get_username(connection);
+  if (&already_called_marker != *req_cls)
+    @{ /* Called for the first time, request not fully read yet */
+      *req_cls = &already_called_marker;
+      /* Wait for complete request */
+      return MHD_YES;
+    @}
+
+  username = MHD_digest_auth_get_username (connection);
   if (username == NULL)
     @{
       response = MHD_create_response_from_buffer(strlen (DENIED),
 					         DENIED,
 					         MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 OPAQUE,
-					 response,
-					 MHD_NO);
+      ret = MHD_queue_auth_fail_response2 (connection,
+                                           realm,
+					   OPAQUE,
+					   response,
+					   MHD_NO,
+                                           MHD_DIGEST_ALG_SHA256);
       MHD_destroy_response(response);
       return ret;
     @}
-  ret = MHD_digest_auth_check(connection, realm,
-			      username,
-			      password,
-			      300);
-  free(username);
+  ret = MHD_digest_auth_check2 (connection,
+                                realm,
+			        username,
+			        password,
+			        300,
+                                MHD_DIGEST_ALG_SHA256);
+  MHD_free(username);
   if ( (ret == MHD_INVALID_NONCE) ||
        (ret == MHD_NO) )
     @{
@@ -2242,16 +3424,21 @@
 					         MHD_RESPMEM_PERSISTENT);
       if (NULL == response)
 	return MHD_NO;
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 OPAQUE,
-					 response,
-					 (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO);
+      ret = MHD_queue_auth_fail_response2 (connection,
+                                           realm,
+					   OPAQUE,
+					   response,
+					   (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO,
+                                           MHD_DIGEST_ALG_SHA256);
       MHD_destroy_response(response);
       return ret;
     @}
-  response = MHD_create_response_from_buffer (strlen(PAGE), PAGE,
+  response = MHD_create_response_from_buffer (strlen(PAGE),
+                                              PAGE,
  					      MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response(response);
   return ret;
 @}
@@ -2278,15 +3465,15 @@
 be processed. The arguments @var{upload_data} and @var{upload_data_size}
 are used to reference the chunk of data.
 
-When @code{MHD_AccessHandlerCallback} is invoked for a new connection:
-its @code{*@var{con_cls}} argument is set to @code{NULL}. When @code{POST}
+When @code{MHD_AccessHandlerCallback} is invoked for a new request:
+its @code{*@var{req_cls}} argument is set to @code{NULL}. When @code{POST}
 data comes in the upload buffer it is @strong{mandatory} to use the
-@var{con_cls} to store a reference to per-connection data.  The fact
+@var{req_cls} to store a reference to per-request data.  The fact
 that the pointer was initially @code{NULL} can be used to detect that
 this is a new request.
 
-One method to detect that a new connection was established is
-to set @code{*con_cls} to an unused integer:
+One method to detect that a new request was started is
+to set @code{*req_cls} to an unused integer:
 
 @example
 int
@@ -2295,15 +3482,15 @@
                 const char *url,
                 const char *method, const char *version,
                 const char *upload_data, size_t *upload_data_size,
-                void **con_cls)
+                void **req_cls)
 @{
   static int old_connection_marker;
-  int new_connection = (NULL == *con_cls);
+  int new_connection = (NULL == *req_cls);
 
   if (new_connection)
     @{
       /* new connection with POST */
-      *con_cls = &old_connection_marker;
+      *req_cls = &old_connection_marker;
     @}
 
   ...
@@ -2312,7 +3499,7 @@
 
 @noindent
 In contrast to the previous example, for @code{POST} requests in particular,
-it is more common to use the value of @code{*con_cls} to keep track of
+it is more common to use the value of @code{*req_cls} to keep track of
 actual state used during processing, such as the post processor (or a
 struct containing a post processor):
 
@@ -2323,14 +3510,14 @@
                 const char *url,
                 const char *method, const char *version,
                 const char *upload_data, size_t *upload_data_size,
-                void **con_cls)
+                void **req_cls)
 @{
-  struct MHD_PostProcessor * pp = *con_cls;
+  struct MHD_PostProcessor * pp = *req_cls;
 
   if (pp == NULL)
     @{
       pp = MHD_create_post_processor(connection, ...);
-      *con_cls = pp;
+      *req_cls = pp;
       return MHD_YES;
     @}
   if (*upload_data_size)
@@ -2388,7 +3575,7 @@
 @end deftypefun
 
 
-@deftypefun int MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len)
+@deftypefun enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len)
 Parse and process @code{POST} data.  Call this function when @code{POST}
 data is available (usually during an @code{MHD_AccessHandlerCallback})
 with the @var{upload_data} and @var{upload_data_size}.  Whenever
@@ -2411,7 +3598,7 @@
 @end deftypefun
 
 
-@deftypefun int MHD_destroy_post_processor (struct MHD_PostProcessor *pp)
+@deftypefun enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp)
 Release PostProcessor resources.  After this function is being called,
 the PostProcessor is guaranteed to no longer call its iterator.  There
 is no special call to the iterator to indicate the end of the post processing
@@ -2436,9 +3623,9 @@
 
 
 @menu
-* microhttpd-info daemon::        State information about an MHD daemon
-* microhttpd-info conn::          State information about a connection
-* microhttpd-option conn::        Modify per-connection options
+* microhttpd-info daemon::      State information about an MHD daemon
+* microhttpd-info conn::        State information about a connection
+* microhttpd-option conn::      Modify per-connection options
 @end menu
 
 
@@ -2493,13 +3680,13 @@
 is actually being used by MHD.
 No extra arguments should be passed.
 
-@item MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY
+@item MHD_DAEMON_INFO_EPOLL_FD
 @cindex epoll
 Request the file-descriptor number that MHD is using for epoll.  If
 the build is not supporting epoll, NULL is returned; if we are using a
 thread pool or this daemon was not started with
-@code{MHD_USE_EPOLL_LINUX_ONLY}, (a pointer to) -1 is returned.  If we are
-using @code{MHD_USE_SELECT_INTERNALLY} or are in 'external' select mode, the
+@code{MHD_USE_EPOLL}, (a pointer to) -1 is returned.  If we are
+using @code{MHD_USE_INTERNAL_POLLING_THREAD} or are in 'external' select mode, the
 internal epoll FD is returned.  This function must be used in external
 select mode with epoll to obtain the FD to call epoll on.  No extra
 arguments should be passed.
@@ -2528,7 +3715,7 @@
 @section Obtaining state information about a connection
 
 
-@deftypefun {const union MHD_ConnectionInfo *} MHD_get_connection_info (struct MHD_Connection *daemon, enum MHD_ConnectionInfoType infoType, ...)
+@deftypefun {const union MHD_ConnectionInfo *} MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType infoType, ...)
 Obtain information about the given connection.
 
 @table @var
@@ -2557,26 +3744,33 @@
 
 @item MHD_CONNECTION_INFO_CIPHER_ALGO
 What cipher algorithm is being used (HTTPS connections only).
-Takes no extra arguments.
 @code{NULL} is returned for non-HTTPS connections.
 
+Takes no extra arguments.
+
 @item MHD_CONNECTION_INFO_PROTOCOL,
-Takes no extra arguments.   Allows finding out the TLS/SSL protocol used
+Allows finding out the TLS/SSL protocol used
 (HTTPS connections only).
 @code{NULL} is returned for non-HTTPS connections.
 
+Takes no extra arguments.
+
 @item MHD_CONNECTION_INFO_CLIENT_ADDRESS
 Returns information about the address of the client.  Returns
 essentially a @code{struct sockaddr **} (since the API returns
 a @code{union MHD_ConnectionInfo *} and that union contains
 a @code{struct sockaddr *}).
 
+Takes no extra arguments.
+
 @item MHD_CONNECTION_INFO_GNUTLS_SESSION,
 Takes no extra arguments.  Allows access to the underlying GNUtls session,
 including access to the underlying GNUtls client certificate
 (HTTPS connections only).  Takes no extra arguments.
 @code{NULL} is returned for non-HTTPS connections.
 
+Takes no extra arguments.
+
 @item MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT,
 Dysfunctional (never implemented, deprecated).  Use
 MHD_CONNECTION_INFO_GNUTLS_SESSION to get the @code{gnutls_session_t}
@@ -2586,6 +3780,8 @@
 Returns information about @code{struct MHD_Daemon} which manages
 this connection.
 
+Takes no extra arguments.
+
 @item MHD_CONNECTION_INFO_CONNECTION_FD
 Returns the file descriptor (usually a TCP socket) associated with
 this connection (in the ``connect-fd'' member of the returned struct).
@@ -2598,14 +3794,48 @@
 callbacks are invoked in between, those might be used to set different
 values for TCP-CORK and TCP-NODELAY in the meantime.
 
+Takes no extra arguments.
+
+@item MHD_CONNECTION_INFO_CONNECTION_SUSPENDED
+Returns pointer to an integer that is @code{MHD_YES} if the connection
+is currently suspended (and thus can be safely resumed) and
+@code{MHD_NO} otherwise.
+
+Takes no extra arguments.
+
 @item MHD_CONNECTION_INFO_SOCKET_CONTEXT
 Returns the client-specific pointer to a @code{void *} that was
 (possibly) set during a @code{MHD_NotifyConnectionCallback} when the
 socket was first accepted.  Note that this is NOT the same as the
-@code{con_cls} argument of the @code{MHD_AccessHandlerCallback}.  The
-@code{con_cls} is fresh for each HTTP request, while the
+@code{req_cls} argument of the @code{MHD_AccessHandlerCallback}.  The
+@code{req_cls} is fresh for each HTTP request, while the
 @code{socket_context} is fresh for each socket.
 
+Takes no extra arguments.
+
+@item MHD_CONNECTION_INFO_CONNECTION_TIMEOUT
+Returns pointer to an @code{unsigned int} that is the current timeout
+used for the connection (in seconds, 0 for no timeout).  Note that
+while suspended connections will not timeout, the timeout value
+returned for suspended connections will be the timeout that the
+connection will use after it is resumed, and thus might not be zero.
+
+Takes no extra arguments.
+
+@item MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE
+@cindex performance
+Returns pointer to an @code{size_t} that represents the size of the
+HTTP header received from the client. Only valid after the first callback
+to the access handler.
+
+Takes no extra arguments.
+
+@item MHD_CONNECTION_INFO_HTTP_STATUS
+Returns the HTTP status code of the response that was
+queued. Returns NULL if no response was queued yet.
+
+Takes no extra arguments.
+
 @end table
 @end deftp
 
@@ -2661,8 +3891,8 @@
 
 
 @menu
-* microhttpd-util feature::       Test supported MHD features
-* microhttpd-util unescape::      Unescape strings
+* microhttpd-util feature::     Test supported MHD features
+* microhttpd-util unescape::    Unescape strings
 @end menu
 
 
@@ -2706,13 +3936,13 @@
 
 @item MHD_FEATURE_EPOLL
 Get whether @code{epoll()} is supported. If supported then Flags
-MHD_USE_EPOLL_LINUX_ONLY and
-MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY can be used.
+MHD_USE_EPOLL and
+MHD_USE_EPOLL_INTERNAL_THREAD can be used.
 
 @item MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET
 Get whether shutdown on listen socket to signal other
 threads is supported. If not supported flag
-MHD_USE_PIPE_FOR_SHUTDOWN is automatically forced.
+MHD_USE_ITC is automatically forced.
 
 @item MHD_FEATURE_SOCKETPAIR
 Get whether a @code{socketpair()} is used internally instead of
@@ -2740,6 +3970,9 @@
 @code{MHD_post_process()}, @code{MHD_destroy_post_processor()}
 can be used.
 
+@item MHD_FEATURE_SENDFILE
+Get whether @code{sendfile()} is supported.
+
 @end table
 @end deftp
 
@@ -2784,6 +4017,704 @@
 
 
 
+
+@c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+@c ------------------------------------------------------------
+@node microhttpd-websocket
+@chapter Websocket functions.
+
+@noindent
+Websocket functions provide what you need to use an upgraded connection
+as a websocket.
+These functions are only available if you include the header file
+@code{microhttpd_ws.h} and compiled @emph{libmicrohttpd} with websockets.
+
+@menu
+* microhttpd-websocket handshake::    Websocket handshake functions
+* microhttpd-websocket stream::       Websocket stream functions
+* microhttpd-websocket decode::       Websocket decode functions
+* microhttpd-websocket encode::       Websocket encode functions
+* microhttpd-websocket memory::       Websocket memory functions
+@end menu
+
+@c ------------------------------------------------------------
+@node microhttpd-websocket handshake
+@section Websocket handshake functions
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_check_http_version (const char* http_version)
+@cindex websocket
+Checks the HTTP version of the incoming request.
+Websocket requests are only allowed for HTTP/1.1 or above.
+
+@table @var
+@item http_version
+The value of the @code{version} parameter of your
+@code{access_handler} callback.
+If you pass @code{NULL} then this is handled like a not
+matching HTTP version.
+@end table
+
+Returns 0 when the HTTP version is
+valid for a websocket request and
+a value less than zero when the HTTP version isn't
+valid for a websocket request.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_check_connection_header (const char* connection_header)
+@cindex websocket
+Checks the value of the @code{Connection} HTTP request header.
+Websocket requests require the token @code{Upgrade} in
+the @code{Connection} HTTP request header.
+
+@table @var
+@item connection_header
+Value of the @code{Connection} request header.
+You can get this request header value by passing
+@code{MHD_HTTP_HEADER_CONNECTION} to
+@code{MHD_lookup_connection_value()}.
+If you pass @code{NULL} then this is handled like a not
+matching @code{Connection} header value.
+@end table
+
+Returns 0 when the @code{Connection} header is
+valid for a websocket request and
+a value less than zero when the @code{Connection} header isn't
+valid for a websocket request.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_check_upgrade_header (const char* upgrade_header)
+@cindex websocket
+Checks the value of the @code{Upgrade} HTTP request header.
+Websocket requests require the value @code{websocket} in
+the @code{Upgrade} HTTP request header.
+
+@table @var
+@item upgrade_header
+Value of the @code{Upgrade} request header.
+You can get this request header value by passing
+@code{MHD_HTTP_HEADER_UPGRADE} to
+@code{MHD_lookup_connection_value()}.
+If you pass @code{NULL} then this is handled like a not
+matching @code{Upgrade} header value.
+@end table
+
+Returns 0 when the @code{Upgrade} header is
+valid for a websocket request and
+a value less than zero when the @code{Upgrade} header isn't
+valid for a websocket request.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_check_version_header (const char* version_header)
+@cindex websocket
+Checks the value of the @code{Sec-WebSocket-Version} HTTP request header.
+Websocket requests require the value @code{13} in
+the @code{Sec-WebSocket-Version} HTTP request header.
+
+@table @var
+@item version_header
+Value of the @code{Sec-WebSocket-Version} request header.
+You can get this request header value by passing
+@code{MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION} to
+@code{MHD_lookup_connection_value()}.
+If you pass @code{NULL} then this is handled like a not
+matching @code{Sec-WebSocket-Version} header value.
+@end table
+
+Returns 0 when the @code{Sec-WebSocket-Version} header is
+valid for a websocket request and
+a value less than zero when the @code{Sec-WebSocket-Version} header isn't
+valid for a websocket request.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_create_accept_header (const char* sec_websocket_key, char* sec_websocket_accept)
+@cindex websocket
+Checks the value of the @code{Sec-WebSocket-Key}
+HTTP request header and generates the value for
+the @code{Sec-WebSocket-Accept} HTTP response header.
+The generated value must be sent to the client.
+
+@table @var
+@item sec_websocket_key
+Value of the @code{Sec-WebSocket-Key} request header.
+You can get this request header value by passing
+@code{MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY} to
+@code{MHD_lookup_connection_value()}.
+If you pass @code{NULL} then this is handled like a not
+matching @code{Sec-WebSocket-Key} header value.
+
+@item sec_websocket_accept
+Response buffer, which will receive
+the generated value for the @code{Sec-WebSocket-Accept}
+HTTP response header.
+This buffer must be at least 29 bytes long and
+will contain the response value plus a terminating @code{NUL}
+character on success.
+Must not be @code{NULL}.
+You can add this HTTP header to your response by passing
+@code{MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT} to
+@code{MHD_add_response_header()}.
+@end table
+
+Returns 0 when the @code{Sec-WebSocket-Key} header was
+not empty and a result value for the @code{Sec-WebSocket-Accept}
+was calculated.
+A value less than zero is returned when the @code{Sec-WebSocket-Key}
+header isn't valid for a websocket request or when any
+error occurred.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@c ------------------------------------------------------------
+@node microhttpd-websocket stream
+@section Websocket stream functions
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_stream_init (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size)
+@cindex websocket
+Creates a new websocket stream, used for decoding/encoding.
+
+@table @var
+@item ws
+pointer a variable to fill with the newly created
+@code{struct MHD_WebSocketStream},
+receives @code{NULL} on error. May not be @code{NULL}.
+
+If not required anymore, free the created websocket stream with
+@code{MHD_websocket_stream_free()}.
+
+@item flags
+combination of @code{enum MHD_WEBSOCKET_FLAG} values to
+modify the behavior of the websocket stream.
+
+@item max_payload_size
+maximum size for incoming payload data in bytes. Use 0 to allow each size.
+@end table
+
+Returns 0 on success, negative values on error.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_stream_init2 (struct MHD_WebSocketStream **ws, int flags, size_t max_payload_size, MHD_WebSocketMallocCallback callback_malloc, MHD_WebSocketReallocCallback callback_realloc, MHD_WebSocketFreeCallback callback_free, void* cls_rng, MHD_WebSocketRandomNumberGenerator callback_rng)
+@cindex websocket
+Creates a new websocket stream, used for decoding/encoding,
+but with custom memory functions for malloc, realloc and free.
+Also a random number generator can be specified for client mode.
+
+@table @var
+@item ws
+pointer a variable to fill with the newly created
+@code{struct MHD_WebSocketStream},
+receives @code{NULL} on error. Must not be @code{NULL}.
+
+If not required anymore, free the created websocket stream with
+@code{MHD_websocket_stream_free}.
+
+@item flags
+combination of @code{enum MHD_WEBSOCKET_FLAG} values to
+modify the behavior of the websocket stream.
+
+@item max_payload_size
+maximum size for incoming payload data in bytes. Use 0 to allow each size.
+
+@item callback_malloc
+callback function for allocating memory. Must not be @code{NULL}.
+The shorter @code{MHD_websocket_stream_init()} passes a reference to @code{malloc} here.
+
+@item callback_realloc
+callback function for reallocating memory. Must not be @code{NULL}.
+The shorter @code{MHD_websocket_stream_init()} passes a reference to @code{realloc} here.
+
+@item callback_free
+callback function for freeing memory. Must not be @code{NULL}.
+The shorter @code{MHD_websocket_stream_init()} passes a reference to @code{free} here.
+
+@item cls_rng
+closure for the random number generator.
+This is only required when
+@code{MHD_WEBSOCKET_FLAG_CLIENT} is passed in @code{flags}.
+The given value is passed to the random number generator callback.
+May be @code{NULL} if not needed.
+Should be @code{NULL} when you are not using @code{MHD_WEBSOCKET_FLAG_CLIENT}.
+The shorter @code{MHD_websocket_stream_init} passes @code{NULL} here.
+
+@item callback_rng
+callback function for a secure random number generator.
+This is only required when @code{MHD_WEBSOCKET_FLAG_CLIENT} is
+passed in @code{flags} and must not be @code{NULL} then.
+Should be @code{NULL} otherwise.
+The shorter @code{MHD_websocket_stream_init()} passes @code{NULL} here.
+@end table
+
+Returns 0 on success, negative values on error.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_stream_free (struct MHD_WebSocketStream *ws)
+@cindex websocket
+Frees a previously allocated websocket stream
+
+@table @var
+@item ws
+websocket stream to free, this value may be @code{NULL}.
+@end table
+
+Returns 0 on success, negative values on error.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_stream_invalidate (struct MHD_WebSocketStream *ws)
+@cindex websocket
+Invalidates a websocket stream.
+After invalidation a websocket stream cannot be used for decoding anymore.
+Encoding is still possible.
+
+@table @var
+@item ws
+websocket stream to invalidate.
+@end table
+
+Returns 0 on success, negative values on error.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_VALIDITY} MHD_websocket_stream_is_valid (struct MHD_WebSocketStream *ws)
+@cindex websocket
+Queries whether a websocket stream is valid.
+Invalidated websocket streams cannot be used for decoding anymore.
+Encoding is still possible.
+
+@table @var
+@item ws
+websocket stream to invalidate.
+@end table
+
+Returns 0 if invalid, 1 if valid for all types or
+2 if valid only for control frames.
+Can be compared with @code{enum MHD_WEBSOCKET_VALIDITY}.
+@end deftypefun
+
+
+@c ------------------------------------------------------------
+@node microhttpd-websocket decode
+@section Websocket decode functions
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_decode (struct MHD_WebSocketStream* ws, const char* streambuf, size_t streambuf_len, size_t* streambuf_read_len, char** payload, size_t* payload_len)
+@cindex websocket
+Decodes a byte sequence for a websocket stream.
+Decoding is done until either a frame is complete or
+the end of the byte sequence is reached.
+
+@table @var
+@item ws
+websocket stream for decoding.
+
+@item streambuf
+byte sequence for decoding.
+This is what you typically received via @code{recv()}.
+
+@item streambuf_len
+length of the byte sequence in parameter @code{streambuf}.
+
+@item streambuf_read_len
+pointer to a variable, which receives the number of bytes,
+that has been processed by this call.
+This value may be less than the value of @code{streambuf_len} when
+a frame is decoded before the end of the buffer is reached.
+The remaining bytes of @code{buf} must be passed to
+the next call of this function.
+
+@item payload
+pointer to a variable, which receives the allocated buffer with the payload
+data of the decoded frame. Must not be @code{NULL}.
+If no decoded data is available or an error occurred @code{NULL} is returned.
+When the returned value is not @code{NULL} then the buffer contains always
+@code{payload_len} bytes plus one terminating @code{NUL} character
+(regardless of the frame type).
+
+The caller must free this buffer using @code{MHD_websocket_free()}.
+
+If you passed the flag @code{MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR}
+upon creation of the websocket stream and a decoding error occurred
+(function return value less than 0), then this buffer contains
+a generated close frame, which must be sent via the socket to the recipient.
+
+If you passed the flag @code{MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS}
+upon creation of the websocket stream then
+this payload may only be a part of the complete message.
+Only complete UTF-8 sequences are returned for fragmented text frames.
+If necessary the UTF-8 sequence will be completed with the next text fragment.
+
+@item payload_len
+pointer to a variable, which receives length of the result
+@code{payload} buffer in bytes.
+Must not be @code{NULL}.
+This receives 0 when no data is available, when the decoded payload
+has a length of zero or when an error occurred.
+@end table
+
+Returns a value greater than zero when a frame is complete.
+Compare with @code{enum MHD_WEBSOCKET_STATUS} to distinguish the frame type.
+Returns 0 when the call succeeded, but no frame is available.
+Returns a value less than zero on errors.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_split_close_reason (const char* payload, size_t payload_len, unsigned short* reason_code, const char** reason_utf8, size_t* reason_utf8_len)
+@cindex websocket
+Splits the payload of a decoded close frame.
+
+@table @var
+@item payload
+payload of the close frame.
+This parameter may only be @code{NULL} if @code{payload_len} is 0.
+
+@item payload_len
+length of @code{payload}.
+
+@item reason_code
+pointer to a variable, which receives the numeric close reason.
+If there was no close reason, this is 0.
+This value can be compared with @code{enum MHD_WEBSOCKET_CLOSEREASON}.
+May be @code{NULL}.
+
+@item reason_utf8
+pointer to a variable, which receives the literal close reason.
+If there was no literal close reason, this will be @code{NULL}.
+May be @code{NULL}.
+
+Please note that no memory is allocated in this function.
+If not @code{NULL} the returned value of this parameter
+points to a position in the specified @code{payload}.
+
+@item reason_utf8_len
+pointer to a variable, which receives the length of the literal close reason.
+If there was no literal close reason, this is 0.
+May be @code{NULL}.
+@end table
+
+Returns 0 on success or a value less than zero on errors.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@c ------------------------------------------------------------
+@node microhttpd-websocket encode
+@section Websocket encode functions
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_encode_text (struct MHD_WebSocketStream* ws, const char* payload_utf8, size_t payload_utf8_len, int fragmentation, char** frame, size_t* frame_len, int* utf8_step)
+@cindex websocket
+Encodes an UTF-8 encoded text into websocket text frame
+
+@table @var
+@item ws
+websocket stream;
+
+@item payload_utf8
+text to send. This must be UTF-8 encoded.
+If you don't want UTF-8 then send a binary frame
+with @code{MHD_websocket_encode_binary()} instead.
+May be be @code{NULL} if @code{payload_utf8_len} is 0,
+must not be @code{NULL} otherwise.
+
+@item payload_utf8_len
+length of @code{payload_utf8} in bytes.
+
+@item fragmentation
+A value of @code{enum MHD_WEBSOCKET_FRAGMENTATION}
+to specify the fragmentation behavior.
+Specify @code{MHD_WEBSOCKET_FRAGMENTATION_NONE} or just 0
+if you don't want to use fragmentation (default).
+
+@item frame
+pointer to a variable, which receives a buffer with the encoded text frame.
+Must not be @code{NULL}.
+The buffer contains what you typically send via @code{send()} to the recipient.
+If no encoded data is available the variable receives @code{NULL}.
+
+If the variable is not @code{NULL} then the buffer contains always
+@code{frame_len} bytes plus one terminating @code{NUL} character.
+The caller must free this buffer using @code{MHD_websocket_free()}.
+
+@item frame_len
+pointer to a variable, which receives the length of the encoded frame in bytes.
+Must not be @code{NULL}.
+
+@item utf8_step
+If fragmentation is used (the parameter @code{fragmentation} is not 0)
+then is parameter is required and must not be @code{NULL}.
+If no fragmentation is used, this parameter is optional and
+should be @code{NULL}.
+
+This parameter is a pointer to a variable which contains the last check status
+of the UTF-8 sequence. It is required to continue a previous
+UTF-8 sequence check when fragmentation is used, because a UTF-8 sequence
+could be split upon fragments.
+
+@code{enum MHD_WEBSOCKET_UTF8STEP} is used for this value.
+If you start a new fragment using
+@code{MHD_WEBSOCKET_FRAGMENTATION_NONE} or
+@code{MHD_WEBSOCKET_FRAGMENTATION_FIRST} the old value of this variable
+will be discarded and the value of this variable will be initialized
+to @code{MHD_WEBSOCKET_UTF8STEP_NORMAL}.
+On all other fragmentation modes the previous value of the pointed variable
+will be used to continue the UTF-8 sequence check.
+@end table
+
+Returns 0 on success or a value less than zero on errors.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_encode_binary (struct MHD_WebSocketStream* ws, const char* payload, size_t payload_len, int fragmentation, char** frame, size_t* frame_len)
+@cindex websocket
+Encodes binary data into websocket binary frame
+
+@table @var
+@item ws
+websocket stream;
+
+@item payload
+binary data to send.
+May be be @code{NULL} if @code{payload_len} is 0,
+must not be @code{NULL} otherwise.
+
+@item payload_len
+length of @code{payload} in bytes.
+
+@item fragmentation
+A value of @code{enum MHD_WEBSOCKET_FRAGMENTATION}
+to specify the fragmentation behavior.
+Specify @code{MHD_WEBSOCKET_FRAGMENTATION_NONE} or just 0
+if you don't want to use fragmentation (default).
+
+@item frame
+pointer to a variable, which receives a buffer with the encoded binary frame.
+Must not be @code{NULL}.
+The buffer contains what you typically send via @code{send()} to the recipient.
+If no encoded data is available the variable receives @code{NULL}.
+
+If the variable is not @code{NULL} then the buffer contains always
+@code{frame_len} bytes plus one terminating @code{NUL} character.
+The caller must free this buffer using @code{MHD_websocket_free()}.
+
+@item frame_len
+pointer to a variable, which receives the length of the encoded frame in bytes.
+Must not be @code{NULL}.
+@end table
+
+Returns 0 on success or a value less than zero on errors.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_encode_ping (struct MHD_WebSocketStream* ws, const char* payload, size_t payload_len, char** frame, size_t* frame_len)
+@cindex websocket
+Encodes a websocket ping frame.
+Ping frames are used to check whether a recipient is still available
+and what latency the websocket connection has.
+
+@table @var
+@item ws
+websocket stream;
+
+@item payload
+binary ping data to send.
+May be @code{NULL} if @code{payload_len} is 0.
+
+@item payload_len
+length of @code{payload} in bytes.
+This may not exceed 125 bytes.
+
+@item frame
+pointer to a variable, which receives a buffer with the encoded ping frame.
+Must not be @code{NULL}.
+The buffer contains what you typically send via @code{send()} to the recipient.
+If no encoded data is available the variable receives @code{NULL}.
+
+If the variable is not @code{NULL} then the buffer contains always
+@code{frame_len} bytes plus one terminating @code{NUL} character.
+The caller must free this buffer using @code{MHD_websocket_free()}.
+
+@item frame_len
+pointer to a variable, which receives the length of the encoded frame in bytes.
+Must not be @code{NULL}.
+@end table
+
+Returns 0 on success or a value less than zero on errors.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_encode_pong (struct MHD_WebSocketStream* ws, const char* payload, size_t payload_len, char** frame, size_t* frame_len)
+@cindex websocket
+Encodes a websocket pong frame.
+Pong frames are used to answer a previously received websocket ping frame.
+
+@table @var
+@item ws
+websocket stream;
+
+@item payload
+binary pong data to send, which should be
+the decoded payload from the received ping frame.
+May be @code{NULL} if @code{payload_len} is 0.
+
+@item payload_len
+length of @code{payload} in bytes.
+This may not exceed 125 bytes.
+
+@item frame
+pointer to a variable, which receives a buffer with the encoded pong frame.
+Must not be @code{NULL}.
+The buffer contains what you typically send via @code{send()} to the recipient.
+If no encoded data is available the variable receives @code{NULL}.
+
+If the variable is not @code{NULL} then the buffer contains always
+@code{frame_len} bytes plus one terminating @code{NUL} character.
+The caller must free this buffer using @code{MHD_websocket_free()}.
+
+@item frame_len
+pointer to a variable, which receives the length of the encoded frame in bytes.
+Must not be @code{NULL}.
+@end table
+
+Returns 0 on success or a value less than zero on errors.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@deftypefun {enum MHD_WEBSOCKET_STATUS} MHD_websocket_encode_close (struct MHD_WebSocketStream* ws, unsigned short reason_code, const char* reason_utf8, size_t reason_utf8_len, char** frame, size_t* frame_len)
+@cindex websocket
+Encodes a websocket close frame.
+Close frames are used to close a websocket connection in a formal way.
+
+@table @var
+@item ws
+websocket stream;
+
+@item reason_code
+reason for close.
+You can use @code{enum MHD_WEBSOCKET_CLOSEREASON} for typical reasons,
+but you are not limited to these values.
+The allowed values are specified in RFC 6455 7.4.
+If you don't want to enter a reason, you can specify
+@code{MHD_WEBSOCKET_CLOSEREASON_NO_REASON} (or just 0) then
+no reason is encoded.
+
+@item reason_utf8
+An UTF-8 encoded text reason why the connection is closed.
+This may be @code{NULL} if @code{reason_utf8_len} is 0.
+This must be @code{NULL} if @code{reason_code} equals to zero
+(@code{MHD_WEBSOCKET_CLOSEREASON_NO_REASON}).
+
+@item reason_utf8_len
+length of the UTF-8 encoded text reason in bytes.
+This may not exceed 123 bytes.
+
+@item frame
+pointer to a variable, which receives a buffer with the encoded close frame.
+Must not be @code{NULL}.
+The buffer contains what you typically send via @code{send()} to the recipient.
+If no encoded data is available the variable receives @code{NULL}.
+
+If the variable is not @code{NULL} then the buffer contains always
+@code{frame_len} bytes plus one terminating @code{NUL} character.
+The caller must free this buffer using @code{MHD_websocket_free()}.
+
+@item frame_len
+pointer to a variable, which receives the length of the encoded frame in bytes.
+Must not be @code{NULL}.
+@end table
+
+Returns 0 on success or a value less than zero on errors.
+Can be compared with @code{enum MHD_WEBSOCKET_STATUS}.
+@end deftypefun
+
+
+@c ------------------------------------------------------------
+@node microhttpd-websocket memory
+@section Websocket memory functions
+
+
+@deftypefun {void*} MHD_websocket_malloc (struct MHD_WebSocketStream* ws, size_t buf_len)
+@cindex websocket
+Allocates memory with the associated @code{malloc()} function
+of the websocket stream.
+The memory allocation function could be different for a websocket stream if
+@code{MHD_websocket_stream_init2()} has been used for initialization.
+
+@table @var
+@item ws
+websocket stream;
+
+@item buf_len
+size of the buffer to allocate in bytes.
+@end table
+
+Returns the pointer of the allocated buffer or @code{NULL} on failure.
+@end deftypefun
+
+
+@deftypefun {void*} MHD_websocket_realloc (struct MHD_WebSocketStream* ws, void* buf, size_t new_buf_len)
+@cindex websocket
+Reallocates memory with the associated @code{realloc()} function
+of the websocket stream.
+The memory reallocation function could be different for a websocket stream if
+@code{MHD_websocket_stream_init2()} has been used for initialization.
+
+@table @var
+@item ws
+websocket stream;
+
+@item buf
+current buffer, may be @code{NULL};
+
+@item new_buf_len
+new size of the buffer in bytes.
+@end table
+
+Return the pointer of the reallocated buffer or @code{NULL} on failure.
+On failure the old pointer remains valid.
+@end deftypefun
+
+
+@deftypefun {void} MHD_websocket_free (struct MHD_WebSocketStream* ws, void* buf)
+@cindex websocket
+Frees memory with the associated @code{free()} function
+of the websocket stream.
+The memory free function could be different for a websocket stream if
+@code{MHD_websocket_stream_init2()} has been used for initialization.
+
+@table @var
+@item ws
+websocket stream;
+
+@item buf
+buffer to free, this may be @code{NULL} then nothing happens.
+@end table
+
+@end deftypefun
+
+
+
+
+
 @c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 
@@ -2796,11 +4727,16 @@
 @cindex license
 @include lgpl.texi
 
-@node GNU GPL with eCos Extension
-@unnumbered GNU GPL with eCos Extension
+@node eCos License
+@unnumbered eCos License
 @cindex license
 @include ecos.texi
 
+@node GNU-GPL
+@unnumbered GNU General Public License
+@cindex license
+@include gpl-2.0.texi
+
 @node GNU-FDL
 @unnumbered GNU-FDL
 @cindex license
diff --git a/doc/performance_data.eps b/doc/libmicrohttpd_performance_data.eps
similarity index 99%
rename from doc/performance_data.eps
rename to doc/libmicrohttpd_performance_data.eps
index 7da198d..6014f9f 100644
--- a/doc/performance_data.eps
+++ b/doc/libmicrohttpd_performance_data.eps
@@ -1,6 +1,6 @@
 %!PS-Adobe-3.0 EPSF-3.0
 %%Creator: (ImageMagick)
-%%Title: (performance_data.eps)
+%%Title: (libmicrohttpd_performance_data.eps)
 %%CreationDate: (2014-02-19T07:16:22+01:00)
 %%BoundingBox: -0 -0 640 480
 %%HiResBoundingBox: 0 0 640 480
diff --git a/doc/performance_data.png b/doc/libmicrohttpd_performance_data.png
similarity index 100%
rename from doc/performance_data.png
rename to doc/libmicrohttpd_performance_data.png
Binary files differ
diff --git a/doc/mdate-sh b/doc/mdate-sh
deleted file mode 100755
index b3719cf..0000000
--- a/doc/mdate-sh
+++ /dev/null
@@ -1,224 +0,0 @@
-#!/bin/sh
-# Get modification time of a file or directory and pretty-print it.
-
-scriptversion=2010-08-21.06; # UTC
-
-# Copyright (C) 1995-2013 Free Software Foundation, Inc.
-# written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, June 1995
-#
-# 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 2, 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/>.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# This file is maintained in Automake, please report
-# bugs to <bug-automake@gnu.org> or send patches to
-# <automake-patches@gnu.org>.
-
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-fi
-
-case $1 in
-  '')
-     echo "$0: No file.  Try '$0 --help' for more information." 1>&2
-     exit 1;
-     ;;
-  -h | --h*)
-    cat <<\EOF
-Usage: mdate-sh [--help] [--version] FILE
-
-Pretty-print the modification day of FILE, in the format:
-1 January 1970
-
-Report bugs to <bug-automake@gnu.org>.
-EOF
-    exit $?
-    ;;
-  -v | --v*)
-    echo "mdate-sh $scriptversion"
-    exit $?
-    ;;
-esac
-
-error ()
-{
-  echo "$0: $1" >&2
-  exit 1
-}
-
-
-# Prevent date giving response in another language.
-LANG=C
-export LANG
-LC_ALL=C
-export LC_ALL
-LC_TIME=C
-export LC_TIME
-
-# GNU ls changes its time format in response to the TIME_STYLE
-# variable.  Since we cannot assume 'unset' works, revert this
-# variable to its documented default.
-if test "${TIME_STYLE+set}" = set; then
-  TIME_STYLE=posix-long-iso
-  export TIME_STYLE
-fi
-
-save_arg1=$1
-
-# Find out how to get the extended ls output of a file or directory.
-if ls -L /dev/null 1>/dev/null 2>&1; then
-  ls_command='ls -L -l -d'
-else
-  ls_command='ls -l -d'
-fi
-# Avoid user/group names that might have spaces, when possible.
-if ls -n /dev/null 1>/dev/null 2>&1; then
-  ls_command="$ls_command -n"
-fi
-
-# A 'ls -l' line looks as follows on OS/2.
-#  drwxrwx---        0 Aug 11  2001 foo
-# This differs from Unix, which adds ownership information.
-#  drwxrwx---   2 root  root      4096 Aug 11  2001 foo
-#
-# To find the date, we split the line on spaces and iterate on words
-# until we find a month.  This cannot work with files whose owner is a
-# user named "Jan", or "Feb", etc.  However, it's unlikely that '/'
-# will be owned by a user whose name is a month.  So we first look at
-# the extended ls output of the root directory to decide how many
-# words should be skipped to get the date.
-
-# On HPUX /bin/sh, "set" interprets "-rw-r--r--" as options, so the "x" below.
-set x`$ls_command /`
-
-# Find which argument is the month.
-month=
-command=
-until test $month
-do
-  test $# -gt 0 || error "failed parsing '$ls_command /' output"
-  shift
-  # Add another shift to the command.
-  command="$command shift;"
-  case $1 in
-    Jan) month=January; nummonth=1;;
-    Feb) month=February; nummonth=2;;
-    Mar) month=March; nummonth=3;;
-    Apr) month=April; nummonth=4;;
-    May) month=May; nummonth=5;;
-    Jun) month=June; nummonth=6;;
-    Jul) month=July; nummonth=7;;
-    Aug) month=August; nummonth=8;;
-    Sep) month=September; nummonth=9;;
-    Oct) month=October; nummonth=10;;
-    Nov) month=November; nummonth=11;;
-    Dec) month=December; nummonth=12;;
-  esac
-done
-
-test -n "$month" || error "failed parsing '$ls_command /' output"
-
-# Get the extended ls output of the file or directory.
-set dummy x`eval "$ls_command \"\\\$save_arg1\""`
-
-# Remove all preceding arguments
-eval $command
-
-# Because of the dummy argument above, month is in $2.
-#
-# On a POSIX system, we should have
-#
-# $# = 5
-# $1 = file size
-# $2 = month
-# $3 = day
-# $4 = year or time
-# $5 = filename
-#
-# On Darwin 7.7.0 and 7.6.0, we have
-#
-# $# = 4
-# $1 = day
-# $2 = month
-# $3 = year or time
-# $4 = filename
-
-# Get the month.
-case $2 in
-  Jan) month=January; nummonth=1;;
-  Feb) month=February; nummonth=2;;
-  Mar) month=March; nummonth=3;;
-  Apr) month=April; nummonth=4;;
-  May) month=May; nummonth=5;;
-  Jun) month=June; nummonth=6;;
-  Jul) month=July; nummonth=7;;
-  Aug) month=August; nummonth=8;;
-  Sep) month=September; nummonth=9;;
-  Oct) month=October; nummonth=10;;
-  Nov) month=November; nummonth=11;;
-  Dec) month=December; nummonth=12;;
-esac
-
-case $3 in
-  ???*) day=$1;;
-  *) day=$3; shift;;
-esac
-
-# Here we have to deal with the problem that the ls output gives either
-# the time of day or the year.
-case $3 in
-  *:*) set `date`; eval year=\$$#
-       case $2 in
-	 Jan) nummonthtod=1;;
-	 Feb) nummonthtod=2;;
-	 Mar) nummonthtod=3;;
-	 Apr) nummonthtod=4;;
-	 May) nummonthtod=5;;
-	 Jun) nummonthtod=6;;
-	 Jul) nummonthtod=7;;
-	 Aug) nummonthtod=8;;
-	 Sep) nummonthtod=9;;
-	 Oct) nummonthtod=10;;
-	 Nov) nummonthtod=11;;
-	 Dec) nummonthtod=12;;
-       esac
-       # For the first six month of the year the time notation can also
-       # be used for files modified in the last year.
-       if (expr $nummonth \> $nummonthtod) > /dev/null;
-       then
-	 year=`expr $year - 1`
-       fi;;
-  *) year=$3;;
-esac
-
-# The result.
-echo $day $month $year
-
-# Local Variables:
-# mode: shell-script
-# sh-indentation: 2
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/doc/run-gendocs.sh b/doc/run-gendocs.sh
new file mode 100644
index 0000000..1832b2a
--- /dev/null
+++ b/doc/run-gendocs.sh
@@ -0,0 +1 @@
+./gendocs.sh --email libmicrohttpd@gnu.org libmicrohttpd "GNU libmicrohttpd manual"
diff --git a/doc/stamp-vti b/doc/stamp-vti
deleted file mode 100644
index c8c24ba..0000000
--- a/doc/stamp-vti
+++ /dev/null
@@ -1,4 +0,0 @@
-@set UPDATED 3 April 2015
-@set UPDATED-MONTH April 2015
-@set EDITION 0.9.42
-@set VERSION 0.9.42
diff --git a/doc/texinfo.tex b/doc/texinfo.tex
deleted file mode 100644
index 85f184c..0000000
--- a/doc/texinfo.tex
+++ /dev/null
@@ -1,10079 +0,0 @@
-% texinfo.tex -- TeX macros to handle Texinfo files.
-% 
-% Load plain if necessary, i.e., if running under initex.
-\expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi
-%
-\def\texinfoversion{2013-02-01.11}
-%
-% Copyright 1985, 1986, 1988, 1990, 1991, 1992, 1993, 1994, 1995,
-% 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
-% 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
-%
-% This texinfo.tex file 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 texinfo.tex file 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/>.
-%
-% As a special exception, when this file is read by TeX when processing
-% a Texinfo source document, you may use the result without
-% restriction. This Exception is an additional permission under section 7
-% of the GNU General Public License, version 3 ("GPLv3").
-%
-% Please try the latest version of texinfo.tex before submitting bug
-% reports; you can get the latest version from:
-%   http://ftp.gnu.org/gnu/texinfo/ (the Texinfo release area), or
-%   http://ftpmirror.gnu.org/texinfo/ (same, via a mirror), or
-%   http://www.gnu.org/software/texinfo/ (the Texinfo home page)
-% The texinfo.tex in any given distribution could well be out
-% of date, so if that's what you're using, please check.
-%
-% Send bug reports to bug-texinfo@gnu.org.  Please include including a
-% complete document in each bug report with which we can reproduce the
-% problem.  Patches are, of course, greatly appreciated.
-%
-% To process a Texinfo manual with TeX, it's most reliable to use the
-% texi2dvi shell script that comes with the distribution.  For a simple
-% manual foo.texi, however, you can get away with this:
-%   tex foo.texi
-%   texindex foo.??
-%   tex foo.texi
-%   tex foo.texi
-%   dvips foo.dvi -o  # or whatever; this makes foo.ps.
-% The extra TeX runs get the cross-reference information correct.
-% Sometimes one run after texindex suffices, and sometimes you need more
-% than two; texi2dvi does it as many times as necessary.
-%
-% It is possible to adapt texinfo.tex for other languages, to some
-% extent.  You can get the existing language-specific files from the
-% full Texinfo distribution.
-%
-% The GNU Texinfo home page is http://www.gnu.org/software/texinfo.
-
-
-\message{Loading texinfo [version \texinfoversion]:}
-
-% If in a .fmt file, print the version number
-% and turn on active characters that we couldn't do earlier because
-% they might have appeared in the input file name.
-\everyjob{\message{[Texinfo version \texinfoversion]}%
-  \catcode`+=\active \catcode`\_=\active}
-
-\chardef\other=12
-
-% We never want plain's \outer definition of \+ in Texinfo.
-% For @tex, we can use \tabalign.
-\let\+ = \relax
-
-% Save some plain tex macros whose names we will redefine.
-\let\ptexb=\b
-\let\ptexbullet=\bullet
-\let\ptexc=\c
-\let\ptexcomma=\,
-\let\ptexdot=\.
-\let\ptexdots=\dots
-\let\ptexend=\end
-\let\ptexequiv=\equiv
-\let\ptexexclam=\!
-\let\ptexfootnote=\footnote
-\let\ptexgtr=>
-\let\ptexhat=^
-\let\ptexi=\i
-\let\ptexindent=\indent
-\let\ptexinsert=\insert
-\let\ptexlbrace=\{
-\let\ptexless=<
-\let\ptexnewwrite\newwrite
-\let\ptexnoindent=\noindent
-\let\ptexplus=+
-\let\ptexraggedright=\raggedright
-\let\ptexrbrace=\}
-\let\ptexslash=\/
-\let\ptexstar=\*
-\let\ptext=\t
-\let\ptextop=\top
-{\catcode`\'=\active \global\let\ptexquoteright'}% active in plain's math mode
-
-% If this character appears in an error message or help string, it
-% starts a new line in the output.
-\newlinechar = `^^J
-
-% Use TeX 3.0's \inputlineno to get the line number, for better error
-% messages, but if we're using an old version of TeX, don't do anything.
-%
-\ifx\inputlineno\thisisundefined
-  \let\linenumber = \empty % Pre-3.0.
-\else
-  \def\linenumber{l.\the\inputlineno:\space}
-\fi
-
-% Set up fixed words for English if not already set.
-\ifx\putwordAppendix\undefined  \gdef\putwordAppendix{Appendix}\fi
-\ifx\putwordChapter\undefined   \gdef\putwordChapter{Chapter}\fi
-\ifx\putworderror\undefined     \gdef\putworderror{error}\fi
-\ifx\putwordfile\undefined      \gdef\putwordfile{file}\fi
-\ifx\putwordin\undefined        \gdef\putwordin{in}\fi
-\ifx\putwordIndexIsEmpty\undefined       \gdef\putwordIndexIsEmpty{(Index is empty)}\fi
-\ifx\putwordIndexNonexistent\undefined   \gdef\putwordIndexNonexistent{(Index is nonexistent)}\fi
-\ifx\putwordInfo\undefined      \gdef\putwordInfo{Info}\fi
-\ifx\putwordInstanceVariableof\undefined \gdef\putwordInstanceVariableof{Instance Variable of}\fi
-\ifx\putwordMethodon\undefined  \gdef\putwordMethodon{Method on}\fi
-\ifx\putwordNoTitle\undefined   \gdef\putwordNoTitle{No Title}\fi
-\ifx\putwordof\undefined        \gdef\putwordof{of}\fi
-\ifx\putwordon\undefined        \gdef\putwordon{on}\fi
-\ifx\putwordpage\undefined      \gdef\putwordpage{page}\fi
-\ifx\putwordsection\undefined   \gdef\putwordsection{section}\fi
-\ifx\putwordSection\undefined   \gdef\putwordSection{Section}\fi
-\ifx\putwordsee\undefined       \gdef\putwordsee{see}\fi
-\ifx\putwordSee\undefined       \gdef\putwordSee{See}\fi
-\ifx\putwordShortTOC\undefined  \gdef\putwordShortTOC{Short Contents}\fi
-\ifx\putwordTOC\undefined       \gdef\putwordTOC{Table of Contents}\fi
-%
-\ifx\putwordMJan\undefined \gdef\putwordMJan{January}\fi
-\ifx\putwordMFeb\undefined \gdef\putwordMFeb{February}\fi
-\ifx\putwordMMar\undefined \gdef\putwordMMar{March}\fi
-\ifx\putwordMApr\undefined \gdef\putwordMApr{April}\fi
-\ifx\putwordMMay\undefined \gdef\putwordMMay{May}\fi
-\ifx\putwordMJun\undefined \gdef\putwordMJun{June}\fi
-\ifx\putwordMJul\undefined \gdef\putwordMJul{July}\fi
-\ifx\putwordMAug\undefined \gdef\putwordMAug{August}\fi
-\ifx\putwordMSep\undefined \gdef\putwordMSep{September}\fi
-\ifx\putwordMOct\undefined \gdef\putwordMOct{October}\fi
-\ifx\putwordMNov\undefined \gdef\putwordMNov{November}\fi
-\ifx\putwordMDec\undefined \gdef\putwordMDec{December}\fi
-%
-\ifx\putwordDefmac\undefined    \gdef\putwordDefmac{Macro}\fi
-\ifx\putwordDefspec\undefined   \gdef\putwordDefspec{Special Form}\fi
-\ifx\putwordDefvar\undefined    \gdef\putwordDefvar{Variable}\fi
-\ifx\putwordDefopt\undefined    \gdef\putwordDefopt{User Option}\fi
-\ifx\putwordDeffunc\undefined   \gdef\putwordDeffunc{Function}\fi
-
-% Since the category of space is not known, we have to be careful.
-\chardef\spacecat = 10
-\def\spaceisspace{\catcode`\ =\spacecat}
-
-% sometimes characters are active, so we need control sequences.
-\chardef\ampChar   = `\&
-\chardef\colonChar = `\:
-\chardef\commaChar = `\,
-\chardef\dashChar  = `\-
-\chardef\dotChar   = `\.
-\chardef\exclamChar= `\!
-\chardef\hashChar  = `\#
-\chardef\lquoteChar= `\`
-\chardef\questChar = `\?
-\chardef\rquoteChar= `\'
-\chardef\semiChar  = `\;
-\chardef\slashChar = `\/
-\chardef\underChar = `\_
-
-% Ignore a token.
-%
-\def\gobble#1{}
-
-% The following is used inside several \edef's.
-\def\makecsname#1{\expandafter\noexpand\csname#1\endcsname}
-
-% Hyphenation fixes.
-\hyphenation{
-  Flor-i-da Ghost-script Ghost-view Mac-OS Post-Script
-  ap-pen-dix bit-map bit-maps
-  data-base data-bases eshell fall-ing half-way long-est man-u-script
-  man-u-scripts mini-buf-fer mini-buf-fers over-view par-a-digm
-  par-a-digms rath-er rec-tan-gu-lar ro-bot-ics se-vere-ly set-up spa-ces
-  spell-ing spell-ings
-  stand-alone strong-est time-stamp time-stamps which-ever white-space
-  wide-spread wrap-around
-}
-
-% Margin to add to right of even pages, to left of odd pages.
-\newdimen\bindingoffset
-\newdimen\normaloffset
-\newdimen\pagewidth \newdimen\pageheight
-
-% For a final copy, take out the rectangles
-% that mark overfull boxes (in case you have decided
-% that the text looks ok even though it passes the margin).
-%
-\def\finalout{\overfullrule=0pt }
-
-% Sometimes it is convenient to have everything in the transcript file
-% and nothing on the terminal.  We don't just call \tracingall here,
-% since that produces some useless output on the terminal.  We also make
-% some effort to order the tracing commands to reduce output in the log
-% file; cf. trace.sty in LaTeX.
-%
-\def\gloggingall{\begingroup \globaldefs = 1 \loggingall \endgroup}%
-\def\loggingall{%
-  \tracingstats2
-  \tracingpages1
-  \tracinglostchars2  % 2 gives us more in etex
-  \tracingparagraphs1
-  \tracingoutput1
-  \tracingmacros2
-  \tracingrestores1
-  \showboxbreadth\maxdimen \showboxdepth\maxdimen
-  \ifx\eTeXversion\thisisundefined\else % etex gives us more logging
-    \tracingscantokens1
-    \tracingifs1
-    \tracinggroups1
-    \tracingnesting2
-    \tracingassigns1
-  \fi
-  \tracingcommands3  % 3 gives us more in etex
-  \errorcontextlines16
-}%
-
-% @errormsg{MSG}.  Do the index-like expansions on MSG, but if things
-% aren't perfect, it's not the end of the world, being an error message,
-% after all.
-% 
-\def\errormsg{\begingroup \indexnofonts \doerrormsg}
-\def\doerrormsg#1{\errmessage{#1}}
-
-% add check for \lastpenalty to plain's definitions.  If the last thing
-% we did was a \nobreak, we don't want to insert more space.
-%
-\def\smallbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\smallskipamount
-  \removelastskip\penalty-50\smallskip\fi\fi}
-\def\medbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\medskipamount
-  \removelastskip\penalty-100\medskip\fi\fi}
-\def\bigbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\bigskipamount
-  \removelastskip\penalty-200\bigskip\fi\fi}
-
-% Do @cropmarks to get crop marks.
-%
-\newif\ifcropmarks
-\let\cropmarks = \cropmarkstrue
-%
-% Dimensions to add cropmarks at corners.
-% Added by P. A. MacKay, 12 Nov. 1986
-%
-\newdimen\outerhsize \newdimen\outervsize % set by the paper size routines
-\newdimen\cornerlong  \cornerlong=1pc
-\newdimen\cornerthick \cornerthick=.3pt
-\newdimen\topandbottommargin \topandbottommargin=.75in
-
-% Output a mark which sets \thischapter, \thissection and \thiscolor.
-% We dump everything together because we only have one kind of mark.
-% This works because we only use \botmark / \topmark, not \firstmark.
-%
-% A mark contains a subexpression of the \ifcase ... \fi construct.
-% \get*marks macros below extract the needed part using \ifcase.
-%
-% Another complication is to let the user choose whether \thischapter
-% (\thissection) refers to the chapter (section) in effect at the top
-% of a page, or that at the bottom of a page.  The solution is
-% described on page 260 of The TeXbook.  It involves outputting two
-% marks for the sectioning macros, one before the section break, and
-% one after.  I won't pretend I can describe this better than DEK...
-\def\domark{%
-  \toks0=\expandafter{\lastchapterdefs}%
-  \toks2=\expandafter{\lastsectiondefs}%
-  \toks4=\expandafter{\prevchapterdefs}%
-  \toks6=\expandafter{\prevsectiondefs}%
-  \toks8=\expandafter{\lastcolordefs}%
-  \mark{%
-                   \the\toks0 \the\toks2
-      \noexpand\or \the\toks4 \the\toks6
-    \noexpand\else \the\toks8
-  }%
-}
-% \topmark doesn't work for the very first chapter (after the title
-% page or the contents), so we use \firstmark there -- this gets us
-% the mark with the chapter defs, unless the user sneaks in, e.g.,
-% @setcolor (or @url, or @link, etc.) between @contents and the very
-% first @chapter.
-\def\gettopheadingmarks{%
-  \ifcase0\topmark\fi
-  \ifx\thischapter\empty \ifcase0\firstmark\fi \fi
-}
-\def\getbottomheadingmarks{\ifcase1\botmark\fi}
-\def\getcolormarks{\ifcase2\topmark\fi}
-
-% Avoid "undefined control sequence" errors.
-\def\lastchapterdefs{}
-\def\lastsectiondefs{}
-\def\prevchapterdefs{}
-\def\prevsectiondefs{}
-\def\lastcolordefs{}
-
-% Main output routine.
-\chardef\PAGE = 255
-\output = {\onepageout{\pagecontents\PAGE}}
-
-\newbox\headlinebox
-\newbox\footlinebox
-
-% \onepageout takes a vbox as an argument.  Note that \pagecontents
-% does insertions, but you have to call it yourself.
-\def\onepageout#1{%
-  \ifcropmarks \hoffset=0pt \else \hoffset=\normaloffset \fi
-  %
-  \ifodd\pageno  \advance\hoffset by \bindingoffset
-  \else \advance\hoffset by -\bindingoffset\fi
-  %
-  % Do this outside of the \shipout so @code etc. will be expanded in
-  % the headline as they should be, not taken literally (outputting ''code).
-  \ifodd\pageno \getoddheadingmarks \else \getevenheadingmarks \fi
-  \setbox\headlinebox = \vbox{\let\hsize=\pagewidth \makeheadline}%
-  \ifodd\pageno \getoddfootingmarks \else \getevenfootingmarks \fi
-  \setbox\footlinebox = \vbox{\let\hsize=\pagewidth \makefootline}%
-  %
-  {%
-    % Have to do this stuff outside the \shipout because we want it to
-    % take effect in \write's, yet the group defined by the \vbox ends
-    % before the \shipout runs.
-    %
-    \indexdummies         % don't expand commands in the output.
-    \normalturnoffactive  % \ in index entries must not stay \, e.g., if
-               % the page break happens to be in the middle of an example.
-               % We don't want .vr (or whatever) entries like this:
-               % \entry{{\tt \indexbackslash }acronym}{32}{\code {\acronym}}
-               % "\acronym" won't work when it's read back in;
-               % it needs to be
-               % {\code {{\tt \backslashcurfont }acronym}
-    \shipout\vbox{%
-      % Do this early so pdf references go to the beginning of the page.
-      \ifpdfmakepagedest \pdfdest name{\the\pageno} xyz\fi
-      %
-      \ifcropmarks \vbox to \outervsize\bgroup
-        \hsize = \outerhsize
-        \vskip-\topandbottommargin
-        \vtop to0pt{%
-          \line{\ewtop\hfil\ewtop}%
-          \nointerlineskip
-          \line{%
-            \vbox{\moveleft\cornerthick\nstop}%
-            \hfill
-            \vbox{\moveright\cornerthick\nstop}%
-          }%
-          \vss}%
-        \vskip\topandbottommargin
-        \line\bgroup
-          \hfil % center the page within the outer (page) hsize.
-          \ifodd\pageno\hskip\bindingoffset\fi
-          \vbox\bgroup
-      \fi
-      %
-      \unvbox\headlinebox
-      \pagebody{#1}%
-      \ifdim\ht\footlinebox > 0pt
-        % Only leave this space if the footline is nonempty.
-        % (We lessened \vsize for it in \oddfootingyyy.)
-        % The \baselineskip=24pt in plain's \makefootline has no effect.
-        \vskip 24pt
-        \unvbox\footlinebox
-      \fi
-      %
-      \ifcropmarks
-          \egroup % end of \vbox\bgroup
-        \hfil\egroup % end of (centering) \line\bgroup
-        \vskip\topandbottommargin plus1fill minus1fill
-        \boxmaxdepth = \cornerthick
-        \vbox to0pt{\vss
-          \line{%
-            \vbox{\moveleft\cornerthick\nsbot}%
-            \hfill
-            \vbox{\moveright\cornerthick\nsbot}%
-          }%
-          \nointerlineskip
-          \line{\ewbot\hfil\ewbot}%
-        }%
-      \egroup % \vbox from first cropmarks clause
-      \fi
-    }% end of \shipout\vbox
-  }% end of group with \indexdummies
-  \advancepageno
-  \ifnum\outputpenalty>-20000 \else\dosupereject\fi
-}
-
-\newinsert\margin \dimen\margin=\maxdimen
-
-\def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}}
-{\catcode`\@ =11
-\gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi
-% marginal hacks, juha@viisa.uucp (Juha Takala)
-\ifvoid\margin\else % marginal info is present
-  \rlap{\kern\hsize\vbox to\z@{\kern1pt\box\margin \vss}}\fi
-\dimen@=\dp#1\relax \unvbox#1\relax
-\ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi
-\ifr@ggedbottom \kern-\dimen@ \vfil \fi}
-}
-
-% Here are the rules for the cropmarks.  Note that they are
-% offset so that the space between them is truly \outerhsize or \outervsize
-% (P. A. MacKay, 12 November, 1986)
-%
-\def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong}
-\def\nstop{\vbox
-  {\hrule height\cornerthick depth\cornerlong width\cornerthick}}
-\def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong}
-\def\nsbot{\vbox
-  {\hrule height\cornerlong depth\cornerthick width\cornerthick}}
-
-% Parse an argument, then pass it to #1.  The argument is the rest of
-% the input line (except we remove a trailing comment).  #1 should be a
-% macro which expects an ordinary undelimited TeX argument.
-%
-\def\parsearg{\parseargusing{}}
-\def\parseargusing#1#2{%
-  \def\argtorun{#2}%
-  \begingroup
-    \obeylines
-    \spaceisspace
-    #1%
-    \parseargline\empty% Insert the \empty token, see \finishparsearg below.
-}
-
-{\obeylines %
-  \gdef\parseargline#1^^M{%
-    \endgroup % End of the group started in \parsearg.
-    \argremovecomment #1\comment\ArgTerm%
-  }%
-}
-
-% First remove any @comment, then any @c comment.
-\def\argremovecomment#1\comment#2\ArgTerm{\argremovec #1\c\ArgTerm}
-\def\argremovec#1\c#2\ArgTerm{\argcheckspaces#1\^^M\ArgTerm}
-
-% Each occurrence of `\^^M' or `<space>\^^M' is replaced by a single space.
-%
-% \argremovec might leave us with trailing space, e.g.,
-%    @end itemize  @c foo
-% This space token undergoes the same procedure and is eventually removed
-% by \finishparsearg.
-%
-\def\argcheckspaces#1\^^M{\argcheckspacesX#1\^^M \^^M}
-\def\argcheckspacesX#1 \^^M{\argcheckspacesY#1\^^M}
-\def\argcheckspacesY#1\^^M#2\^^M#3\ArgTerm{%
-  \def\temp{#3}%
-  \ifx\temp\empty
-    % Do not use \next, perhaps the caller of \parsearg uses it; reuse \temp:
-    \let\temp\finishparsearg
-  \else
-    \let\temp\argcheckspaces
-  \fi
-  % Put the space token in:
-  \temp#1 #3\ArgTerm
-}
-
-% If a _delimited_ argument is enclosed in braces, they get stripped; so
-% to get _exactly_ the rest of the line, we had to prevent such situation.
-% We prepended an \empty token at the very beginning and we expand it now,
-% just before passing the control to \argtorun.
-% (Similarly, we have to think about #3 of \argcheckspacesY above: it is
-% either the null string, or it ends with \^^M---thus there is no danger
-% that a pair of braces would be stripped.
-%
-% But first, we have to remove the trailing space token.
-%
-\def\finishparsearg#1 \ArgTerm{\expandafter\argtorun\expandafter{#1}}
-
-% \parseargdef\foo{...}
-%	is roughly equivalent to
-% \def\foo{\parsearg\Xfoo}
-% \def\Xfoo#1{...}
-%
-% Actually, I use \csname\string\foo\endcsname, ie. \\foo, as it is my
-% favourite TeX trick.  --kasal, 16nov03
-
-\def\parseargdef#1{%
-  \expandafter \doparseargdef \csname\string#1\endcsname #1%
-}
-\def\doparseargdef#1#2{%
-  \def#2{\parsearg#1}%
-  \def#1##1%
-}
-
-% Several utility definitions with active space:
-{
-  \obeyspaces
-  \gdef\obeyedspace{ }
-
-  % Make each space character in the input produce a normal interword
-  % space in the output.  Don't allow a line break at this space, as this
-  % is used only in environments like @example, where each line of input
-  % should produce a line of output anyway.
-  %
-  \gdef\sepspaces{\obeyspaces\let =\tie}
-
-  % If an index command is used in an @example environment, any spaces
-  % therein should become regular spaces in the raw index file, not the
-  % expansion of \tie (\leavevmode \penalty \@M \ ).
-  \gdef\unsepspaces{\let =\space}
-}
-
-
-\def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next}
-
-% Define the framework for environments in texinfo.tex.  It's used like this:
-%
-%   \envdef\foo{...}
-%   \def\Efoo{...}
-%
-% It's the responsibility of \envdef to insert \begingroup before the
-% actual body; @end closes the group after calling \Efoo.  \envdef also
-% defines \thisenv, so the current environment is known; @end checks
-% whether the environment name matches.  The \checkenv macro can also be
-% used to check whether the current environment is the one expected.
-%
-% Non-false conditionals (@iftex, @ifset) don't fit into this, so they
-% are not treated as environments; they don't open a group.  (The
-% implementation of @end takes care not to call \endgroup in this
-% special case.)
-
-
-% At run-time, environments start with this:
-\def\startenvironment#1{\begingroup\def\thisenv{#1}}
-% initialize
-\let\thisenv\empty
-
-% ... but they get defined via ``\envdef\foo{...}'':
-\long\def\envdef#1#2{\def#1{\startenvironment#1#2}}
-\def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}}
-
-% Check whether we're in the right environment:
-\def\checkenv#1{%
-  \def\temp{#1}%
-  \ifx\thisenv\temp
-  \else
-    \badenverr
-  \fi
-}
-
-% Environment mismatch, #1 expected:
-\def\badenverr{%
-  \errhelp = \EMsimple
-  \errmessage{This command can appear only \inenvironment\temp,
-    not \inenvironment\thisenv}%
-}
-\def\inenvironment#1{%
-  \ifx#1\empty
-    outside of any environment%
-  \else
-    in environment \expandafter\string#1%
-  \fi
-}
-
-% @end foo executes the definition of \Efoo.
-% But first, it executes a specialized version of \checkenv
-%
-\parseargdef\end{%
-  \if 1\csname iscond.#1\endcsname
-  \else
-    % The general wording of \badenverr may not be ideal.
-    \expandafter\checkenv\csname#1\endcsname
-    \csname E#1\endcsname
-    \endgroup
-  \fi
-}
-
-\newhelp\EMsimple{Press RETURN to continue.}
-
-
-% Be sure we're in horizontal mode when doing a tie, since we make space
-% equivalent to this in @example-like environments. Otherwise, a space
-% at the beginning of a line will start with \penalty -- and
-% since \penalty is valid in vertical mode, we'd end up putting the
-% penalty on the vertical list instead of in the new paragraph.
-{\catcode`@ = 11
- % Avoid using \@M directly, because that causes trouble
- % if the definition is written into an index file.
- \global\let\tiepenalty = \@M
- \gdef\tie{\leavevmode\penalty\tiepenalty\ }
-}
-
-% @: forces normal size whitespace following.
-\def\:{\spacefactor=1000 }
-
-% @* forces a line break.
-\def\*{\unskip\hfil\break\hbox{}\ignorespaces}
-
-% @/ allows a line break.
-\let\/=\allowbreak
-
-% @. is an end-of-sentence period.
-\def\.{.\spacefactor=\endofsentencespacefactor\space}
-
-% @! is an end-of-sentence bang.
-\def\!{!\spacefactor=\endofsentencespacefactor\space}
-
-% @? is an end-of-sentence query.
-\def\?{?\spacefactor=\endofsentencespacefactor\space}
-
-% @frenchspacing on|off  says whether to put extra space after punctuation.
-%
-\def\onword{on}
-\def\offword{off}
-%
-\parseargdef\frenchspacing{%
-  \def\temp{#1}%
-  \ifx\temp\onword \plainfrenchspacing
-  \else\ifx\temp\offword \plainnonfrenchspacing
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @frenchspacing option `\temp', must be on|off}%
-  \fi\fi
-}
-
-% @w prevents a word break.  Without the \leavevmode, @w at the
-% beginning of a paragraph, when TeX is still in vertical mode, would
-% produce a whole line of output instead of starting the paragraph.
-\def\w#1{\leavevmode\hbox{#1}}
-
-% @group ... @end group forces ... to be all on one page, by enclosing
-% it in a TeX vbox.  We use \vtop instead of \vbox to construct the box
-% to keep its height that of a normal line.  According to the rules for
-% \topskip (p.114 of the TeXbook), the glue inserted is
-% max (\topskip - \ht (first item), 0).  If that height is large,
-% therefore, no glue is inserted, and the space between the headline and
-% the text is small, which looks bad.
-%
-% Another complication is that the group might be very large.  This can
-% cause the glue on the previous page to be unduly stretched, because it
-% does not have much material.  In this case, it's better to add an
-% explicit \vfill so that the extra space is at the bottom.  The
-% threshold for doing this is if the group is more than \vfilllimit
-% percent of a page (\vfilllimit can be changed inside of @tex).
-%
-\newbox\groupbox
-\def\vfilllimit{0.7}
-%
-\envdef\group{%
-  \ifnum\catcode`\^^M=\active \else
-    \errhelp = \groupinvalidhelp
-    \errmessage{@group invalid in context where filling is enabled}%
-  \fi
-  \startsavinginserts
-  %
-  \setbox\groupbox = \vtop\bgroup
-    % Do @comment since we are called inside an environment such as
-    % @example, where each end-of-line in the input causes an
-    % end-of-line in the output.  We don't want the end-of-line after
-    % the `@group' to put extra space in the output.  Since @group
-    % should appear on a line by itself (according to the Texinfo
-    % manual), we don't worry about eating any user text.
-    \comment
-}
-%
-% The \vtop produces a box with normal height and large depth; thus, TeX puts
-% \baselineskip glue before it, and (when the next line of text is done)
-% \lineskip glue after it.  Thus, space below is not quite equal to space
-% above.  But it's pretty close.
-\def\Egroup{%
-    % To get correct interline space between the last line of the group
-    % and the first line afterwards, we have to propagate \prevdepth.
-    \endgraf % Not \par, as it may have been set to \lisppar.
-    \global\dimen1 = \prevdepth
-  \egroup           % End the \vtop.
-  % \dimen0 is the vertical size of the group's box.
-  \dimen0 = \ht\groupbox  \advance\dimen0 by \dp\groupbox
-  % \dimen2 is how much space is left on the page (more or less).
-  \dimen2 = \pageheight   \advance\dimen2 by -\pagetotal
-  % if the group doesn't fit on the current page, and it's a big big
-  % group, force a page break.
-  \ifdim \dimen0 > \dimen2
-    \ifdim \pagetotal < \vfilllimit\pageheight
-      \page
-    \fi
-  \fi
-  \box\groupbox
-  \prevdepth = \dimen1
-  \checkinserts
-}
-%
-% TeX puts in an \escapechar (i.e., `@') at the beginning of the help
-% message, so this ends up printing `@group can only ...'.
-%
-\newhelp\groupinvalidhelp{%
-group can only be used in environments such as @example,^^J%
-where each line of input produces a line of output.}
-
-% @need space-in-mils
-% forces a page break if there is not space-in-mils remaining.
-
-\newdimen\mil  \mil=0.001in
-
-\parseargdef\need{%
-  % Ensure vertical mode, so we don't make a big box in the middle of a
-  % paragraph.
-  \par
-  %
-  % If the @need value is less than one line space, it's useless.
-  \dimen0 = #1\mil
-  \dimen2 = \ht\strutbox
-  \advance\dimen2 by \dp\strutbox
-  \ifdim\dimen0 > \dimen2
-    %
-    % Do a \strut just to make the height of this box be normal, so the
-    % normal leading is inserted relative to the preceding line.
-    % And a page break here is fine.
-    \vtop to #1\mil{\strut\vfil}%
-    %
-    % TeX does not even consider page breaks if a penalty added to the
-    % main vertical list is 10000 or more.  But in order to see if the
-    % empty box we just added fits on the page, we must make it consider
-    % page breaks.  On the other hand, we don't want to actually break the
-    % page after the empty box.  So we use a penalty of 9999.
-    %
-    % There is an extremely small chance that TeX will actually break the
-    % page at this \penalty, if there are no other feasible breakpoints in
-    % sight.  (If the user is using lots of big @group commands, which
-    % almost-but-not-quite fill up a page, TeX will have a hard time doing
-    % good page breaking, for example.)  However, I could not construct an
-    % example where a page broke at this \penalty; if it happens in a real
-    % document, then we can reconsider our strategy.
-    \penalty9999
-    %
-    % Back up by the size of the box, whether we did a page break or not.
-    \kern -#1\mil
-    %
-    % Do not allow a page break right after this kern.
-    \nobreak
-  \fi
-}
-
-% @br   forces paragraph break (and is undocumented).
-
-\let\br = \par
-
-% @page forces the start of a new page.
-%
-\def\page{\par\vfill\supereject}
-
-% @exdent text....
-% outputs text on separate line in roman font, starting at standard page margin
-
-% This records the amount of indent in the innermost environment.
-% That's how much \exdent should take out.
-\newskip\exdentamount
-
-% This defn is used inside fill environments such as @defun.
-\parseargdef\exdent{\hfil\break\hbox{\kern -\exdentamount{\rm#1}}\hfil\break}
-
-% This defn is used inside nofill environments such as @example.
-\parseargdef\nofillexdent{{\advance \leftskip by -\exdentamount
-  \leftline{\hskip\leftskip{\rm#1}}}}
-
-% @inmargin{WHICH}{TEXT} puts TEXT in the WHICH margin next to the current
-% paragraph.  For more general purposes, use the \margin insertion
-% class.  WHICH is `l' or `r'.  Not documented, written for gawk manual.
-%
-\newskip\inmarginspacing \inmarginspacing=1cm
-\def\strutdepth{\dp\strutbox}
-%
-\def\doinmargin#1#2{\strut\vadjust{%
-  \nobreak
-  \kern-\strutdepth
-  \vtop to \strutdepth{%
-    \baselineskip=\strutdepth
-    \vss
-    % if you have multiple lines of stuff to put here, you'll need to
-    % make the vbox yourself of the appropriate size.
-    \ifx#1l%
-      \llap{\ignorespaces #2\hskip\inmarginspacing}%
-    \else
-      \rlap{\hskip\hsize \hskip\inmarginspacing \ignorespaces #2}%
-    \fi
-    \null
-  }%
-}}
-\def\inleftmargin{\doinmargin l}
-\def\inrightmargin{\doinmargin r}
-%
-% @inmargin{TEXT [, RIGHT-TEXT]}
-% (if RIGHT-TEXT is given, use TEXT for left page, RIGHT-TEXT for right;
-% else use TEXT for both).
-%
-\def\inmargin#1{\parseinmargin #1,,\finish}
-\def\parseinmargin#1,#2,#3\finish{% not perfect, but better than nothing.
-  \setbox0 = \hbox{\ignorespaces #2}%
-  \ifdim\wd0 > 0pt
-    \def\lefttext{#1}%  have both texts
-    \def\righttext{#2}%
-  \else
-    \def\lefttext{#1}%  have only one text
-    \def\righttext{#1}%
-  \fi
-  %
-  \ifodd\pageno
-    \def\temp{\inrightmargin\righttext}% odd page -> outside is right margin
-  \else
-    \def\temp{\inleftmargin\lefttext}%
-  \fi
-  \temp
-}
-
-% @| inserts a changebar to the left of the current line.  It should
-% surround any changed text.  This approach does *not* work if the
-% change spans more than two lines of output.  To handle that, we would
-% have adopt a much more difficult approach (putting marks into the main
-% vertical list for the beginning and end of each change).  This command
-% is not documented, not supported, and doesn't work.
-%
-\def\|{%
-  % \vadjust can only be used in horizontal mode.
-  \leavevmode
-  %
-  % Append this vertical mode material after the current line in the output.
-  \vadjust{%
-    % We want to insert a rule with the height and depth of the current
-    % leading; that is exactly what \strutbox is supposed to record.
-    \vskip-\baselineskip
-    %
-    % \vadjust-items are inserted at the left edge of the type.  So
-    % the \llap here moves out into the left-hand margin.
-    \llap{%
-      %
-      % For a thicker or thinner bar, change the `1pt'.
-      \vrule height\baselineskip width1pt
-      %
-      % This is the space between the bar and the text.
-      \hskip 12pt
-    }%
-  }%
-}
-
-% @include FILE -- \input text of FILE.
-%
-\def\include{\parseargusing\filenamecatcodes\includezzz}
-\def\includezzz#1{%
-  \pushthisfilestack
-  \def\thisfile{#1}%
-  {%
-    \makevalueexpandable  % we want to expand any @value in FILE.
-    \turnoffactive        % and allow special characters in the expansion
-    \indexnofonts         % Allow `@@' and other weird things in file names.
-    \wlog{texinfo.tex: doing @include of #1^^J}%
-    \edef\temp{\noexpand\input #1 }%
-    %
-    % This trickery is to read FILE outside of a group, in case it makes
-    % definitions, etc.
-    \expandafter
-  }\temp
-  \popthisfilestack
-}
-\def\filenamecatcodes{%
-  \catcode`\\=\other
-  \catcode`~=\other
-  \catcode`^=\other
-  \catcode`_=\other
-  \catcode`|=\other
-  \catcode`<=\other
-  \catcode`>=\other
-  \catcode`+=\other
-  \catcode`-=\other
-  \catcode`\`=\other
-  \catcode`\'=\other
-}
-
-\def\pushthisfilestack{%
-  \expandafter\pushthisfilestackX\popthisfilestack\StackTerm
-}
-\def\pushthisfilestackX{%
-  \expandafter\pushthisfilestackY\thisfile\StackTerm
-}
-\def\pushthisfilestackY #1\StackTerm #2\StackTerm {%
-  \gdef\popthisfilestack{\gdef\thisfile{#1}\gdef\popthisfilestack{#2}}%
-}
-
-\def\popthisfilestack{\errthisfilestackempty}
-\def\errthisfilestackempty{\errmessage{Internal error:
-  the stack of filenames is empty.}}
-%
-\def\thisfile{}
-
-% @center line
-% outputs that line, centered.
-%
-\parseargdef\center{%
-  \ifhmode
-    \let\centersub\centerH
-  \else
-    \let\centersub\centerV
-  \fi
-  \centersub{\hfil \ignorespaces#1\unskip \hfil}%
-  \let\centersub\relax % don't let the definition persist, just in case
-}
-\def\centerH#1{{%
-  \hfil\break
-  \advance\hsize by -\leftskip
-  \advance\hsize by -\rightskip
-  \line{#1}%
-  \break
-}}
-%
-\newcount\centerpenalty
-\def\centerV#1{%
-  % The idea here is the same as in \startdefun, \cartouche, etc.: if
-  % @center is the first thing after a section heading, we need to wipe
-  % out the negative parskip inserted by \sectionheading, but still
-  % prevent a page break here.
-  \centerpenalty = \lastpenalty
-  \ifnum\centerpenalty>10000 \vskip\parskip \fi
-  \ifnum\centerpenalty>9999 \penalty\centerpenalty \fi
-  \line{\kern\leftskip #1\kern\rightskip}%
-}
-
-% @sp n   outputs n lines of vertical space
-%
-\parseargdef\sp{\vskip #1\baselineskip}
-
-% @comment ...line which is ignored...
-% @c is the same as @comment
-% @ignore ... @end ignore  is another way to write a comment
-%
-\def\comment{\begingroup \catcode`\^^M=\other%
-\catcode`\@=\other \catcode`\{=\other \catcode`\}=\other%
-\commentxxx}
-{\catcode`\^^M=\other \gdef\commentxxx#1^^M{\endgroup}}
-%
-\let\c=\comment
-
-% @paragraphindent NCHARS
-% We'll use ems for NCHARS, close enough.
-% NCHARS can also be the word `asis' or `none'.
-% We cannot feasibly implement @paragraphindent asis, though.
-%
-\def\asisword{asis} % no translation, these are keywords
-\def\noneword{none}
-%
-\parseargdef\paragraphindent{%
-  \def\temp{#1}%
-  \ifx\temp\asisword
-  \else
-    \ifx\temp\noneword
-      \defaultparindent = 0pt
-    \else
-      \defaultparindent = #1em
-    \fi
-  \fi
-  \parindent = \defaultparindent
-}
-
-% @exampleindent NCHARS
-% We'll use ems for NCHARS like @paragraphindent.
-% It seems @exampleindent asis isn't necessary, but
-% I preserve it to make it similar to @paragraphindent.
-\parseargdef\exampleindent{%
-  \def\temp{#1}%
-  \ifx\temp\asisword
-  \else
-    \ifx\temp\noneword
-      \lispnarrowing = 0pt
-    \else
-      \lispnarrowing = #1em
-    \fi
-  \fi
-}
-
-% @firstparagraphindent WORD
-% If WORD is `none', then suppress indentation of the first paragraph
-% after a section heading.  If WORD is `insert', then do indent at such
-% paragraphs.
-%
-% The paragraph indentation is suppressed or not by calling
-% \suppressfirstparagraphindent, which the sectioning commands do.
-% We switch the definition of this back and forth according to WORD.
-% By default, we suppress indentation.
-%
-\def\suppressfirstparagraphindent{\dosuppressfirstparagraphindent}
-\def\insertword{insert}
-%
-\parseargdef\firstparagraphindent{%
-  \def\temp{#1}%
-  \ifx\temp\noneword
-    \let\suppressfirstparagraphindent = \dosuppressfirstparagraphindent
-  \else\ifx\temp\insertword
-    \let\suppressfirstparagraphindent = \relax
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @firstparagraphindent option `\temp'}%
-  \fi\fi
-}
-
-% Here is how we actually suppress indentation.  Redefine \everypar to
-% \kern backwards by \parindent, and then reset itself to empty.
-%
-% We also make \indent itself not actually do anything until the next
-% paragraph.
-%
-\gdef\dosuppressfirstparagraphindent{%
-  \gdef\indent{%
-    \restorefirstparagraphindent
-    \indent
-  }%
-  \gdef\noindent{%
-    \restorefirstparagraphindent
-    \noindent
-  }%
-  \global\everypar = {%
-    \kern -\parindent
-    \restorefirstparagraphindent
-  }%
-}
-
-\gdef\restorefirstparagraphindent{%
-  \global \let \indent = \ptexindent
-  \global \let \noindent = \ptexnoindent
-  \global \everypar = {}%
-}
-
-
-% @refill is a no-op.
-\let\refill=\relax
-
-% If working on a large document in chapters, it is convenient to
-% be able to disable indexing, cross-referencing, and contents, for test runs.
-% This is done with @novalidate (before @setfilename).
-%
-\newif\iflinks \linkstrue % by default we want the aux files.
-\let\novalidate = \linksfalse
-
-% @setfilename is done at the beginning of every texinfo file.
-% So open here the files we need to have open while reading the input.
-% This makes it possible to make a .fmt file for texinfo.
-\def\setfilename{%
-   \fixbackslash  % Turn off hack to swallow `\input texinfo'.
-   \iflinks
-     \tryauxfile
-     % Open the new aux file.  TeX will close it automatically at exit.
-     \immediate\openout\auxfile=\jobname.aux
-   \fi % \openindices needs to do some work in any case.
-   \openindices
-   \let\setfilename=\comment % Ignore extra @setfilename cmds.
-   %
-   % If texinfo.cnf is present on the system, read it.
-   % Useful for site-wide @afourpaper, etc.
-   \openin 1 texinfo.cnf
-   \ifeof 1 \else \input texinfo.cnf \fi
-   \closein 1
-   %
-   \comment % Ignore the actual filename.
-}
-
-% Called from \setfilename.
-%
-\def\openindices{%
-  \newindex{cp}%
-  \newcodeindex{fn}%
-  \newcodeindex{vr}%
-  \newcodeindex{tp}%
-  \newcodeindex{ky}%
-  \newcodeindex{pg}%
-}
-
-% @bye.
-\outer\def\bye{\pagealignmacro\tracingstats=1\ptexend}
-
-
-\message{pdf,}
-% adobe `portable' document format
-\newcount\tempnum
-\newcount\lnkcount
-\newtoks\filename
-\newcount\filenamelength
-\newcount\pgn
-\newtoks\toksA
-\newtoks\toksB
-\newtoks\toksC
-\newtoks\toksD
-\newbox\boxA
-\newcount\countA
-\newif\ifpdf
-\newif\ifpdfmakepagedest
-
-% when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1
-% can be set).  So we test for \relax and 0 as well as being undefined.
-\ifx\pdfoutput\thisisundefined
-\else
-  \ifx\pdfoutput\relax
-  \else
-    \ifcase\pdfoutput
-    \else
-      \pdftrue
-    \fi
-  \fi
-\fi
-
-% PDF uses PostScript string constants for the names of xref targets,
-% for display in the outlines, and in other places.  Thus, we have to
-% double any backslashes.  Otherwise, a name like "\node" will be
-% interpreted as a newline (\n), followed by o, d, e.  Not good.
-% 
-% See http://www.ntg.nl/pipermail/ntg-pdftex/2004-July/000654.html and
-% related messages.  The final outcome is that it is up to the TeX user
-% to double the backslashes and otherwise make the string valid, so
-% that's what we do.  pdftex 1.30.0 (ca.2005) introduced a primitive to
-% do this reliably, so we use it.
-
-% #1 is a control sequence in which to do the replacements,
-% which we \xdef.
-\def\txiescapepdf#1{%
-  \ifx\pdfescapestring\thisisundefined
-    % No primitive available; should we give a warning or log?
-    % Many times it won't matter.
-  \else
-    % The expandable \pdfescapestring primitive escapes parentheses,
-    % backslashes, and other special chars.
-    \xdef#1{\pdfescapestring{#1}}%
-  \fi
-}
-
-\newhelp\nopdfimagehelp{Texinfo supports .png, .jpg, .jpeg, and .pdf images
-with PDF output, and none of those formats could be found.  (.eps cannot
-be supported due to the design of the PDF format; use regular TeX (DVI
-output) for that.)}
-
-\ifpdf
-  %
-  % Color manipulation macros based on pdfcolor.tex,
-  % except using rgb instead of cmyk; the latter is said to render as a
-  % very dark gray on-screen and a very dark halftone in print, instead
-  % of actual black.
-  \def\rgbDarkRed{0.50 0.09 0.12}
-  \def\rgbBlack{0 0 0}
-  %
-  % k sets the color for filling (usual text, etc.);
-  % K sets the color for stroking (thin rules, e.g., normal _'s).
-  \def\pdfsetcolor#1{\pdfliteral{#1 rg  #1 RG}}
-  %
-  % Set color, and create a mark which defines \thiscolor accordingly,
-  % so that \makeheadline knows which color to restore.
-  \def\setcolor#1{%
-    \xdef\lastcolordefs{\gdef\noexpand\thiscolor{#1}}%
-    \domark
-    \pdfsetcolor{#1}%
-  }
-  %
-  \def\maincolor{\rgbBlack}
-  \pdfsetcolor{\maincolor}
-  \edef\thiscolor{\maincolor}
-  \def\lastcolordefs{}
-  %
-  \def\makefootline{%
-    \baselineskip24pt
-    \line{\pdfsetcolor{\maincolor}\the\footline}%
-  }
-  %
-  \def\makeheadline{%
-    \vbox to 0pt{%
-      \vskip-22.5pt
-      \line{%
-        \vbox to8.5pt{}%
-        % Extract \thiscolor definition from the marks.
-        \getcolormarks
-        % Typeset the headline with \maincolor, then restore the color.
-        \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}%
-      }%
-      \vss
-    }%
-    \nointerlineskip
-  }
-  %
-  %
-  \pdfcatalog{/PageMode /UseOutlines}
-  %
-  % #1 is image name, #2 width (might be empty/whitespace), #3 height (ditto).
-  \def\dopdfimage#1#2#3{%
-    \def\pdfimagewidth{#2}\setbox0 = \hbox{\ignorespaces #2}%
-    \def\pdfimageheight{#3}\setbox2 = \hbox{\ignorespaces #3}%
-    %
-    % pdftex (and the PDF format) support .pdf, .png, .jpg (among
-    % others).  Let's try in that order, PDF first since if
-    % someone has a scalable image, presumably better to use that than a
-    % bitmap.
-    \let\pdfimgext=\empty
-    \begingroup
-      \openin 1 #1.pdf \ifeof 1
-        \openin 1 #1.PDF \ifeof 1
-          \openin 1 #1.png \ifeof 1
-            \openin 1 #1.jpg \ifeof 1
-              \openin 1 #1.jpeg \ifeof 1
-                \openin 1 #1.JPG \ifeof 1
-                  \errhelp = \nopdfimagehelp
-                  \errmessage{Could not find image file #1 for pdf}%
-                \else \gdef\pdfimgext{JPG}%
-                \fi
-              \else \gdef\pdfimgext{jpeg}%
-              \fi
-            \else \gdef\pdfimgext{jpg}%
-            \fi
-          \else \gdef\pdfimgext{png}%
-          \fi
-        \else \gdef\pdfimgext{PDF}%
-        \fi
-      \else \gdef\pdfimgext{pdf}%
-      \fi
-      \closein 1
-    \endgroup
-    %
-    % without \immediate, ancient pdftex seg faults when the same image is
-    % included twice.  (Version 3.14159-pre-1.0-unofficial-20010704.)
-    \ifnum\pdftexversion < 14
-      \immediate\pdfimage
-    \else
-      \immediate\pdfximage
-    \fi
-      \ifdim \wd0 >0pt width \pdfimagewidth \fi
-      \ifdim \wd2 >0pt height \pdfimageheight \fi
-      \ifnum\pdftexversion<13
-         #1.\pdfimgext
-       \else
-         {#1.\pdfimgext}%
-       \fi
-    \ifnum\pdftexversion < 14 \else
-      \pdfrefximage \pdflastximage
-    \fi}
-  %
-  \def\pdfmkdest#1{{%
-    % We have to set dummies so commands such as @code, and characters
-    % such as \, aren't expanded when present in a section title.
-    \indexnofonts
-    \turnoffactive
-    \makevalueexpandable
-    \def\pdfdestname{#1}%
-    \txiescapepdf\pdfdestname
-    \safewhatsit{\pdfdest name{\pdfdestname} xyz}%
-  }}
-  %
-  % used to mark target names; must be expandable.
-  \def\pdfmkpgn#1{#1}
-  %
-  % by default, use a color that is dark enough to print on paper as
-  % nearly black, but still distinguishable for online viewing.
-  \def\urlcolor{\rgbDarkRed}
-  \def\linkcolor{\rgbDarkRed}
-  \def\endlink{\setcolor{\maincolor}\pdfendlink}
-  %
-  % Adding outlines to PDF; macros for calculating structure of outlines
-  % come from Petr Olsak
-  \def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0%
-    \else \csname#1\endcsname \fi}
-  \def\advancenumber#1{\tempnum=\expnumber{#1}\relax
-    \advance\tempnum by 1
-    \expandafter\xdef\csname#1\endcsname{\the\tempnum}}
-  %
-  % #1 is the section text, which is what will be displayed in the
-  % outline by the pdf viewer.  #2 is the pdf expression for the number
-  % of subentries (or empty, for subsubsections).  #3 is the node text,
-  % which might be empty if this toc entry had no corresponding node.
-  % #4 is the page number
-  %
-  \def\dopdfoutline#1#2#3#4{%
-    % Generate a link to the node text if that exists; else, use the
-    % page number.  We could generate a destination for the section
-    % text in the case where a section has no node, but it doesn't
-    % seem worth the trouble, since most documents are normally structured.
-    \edef\pdfoutlinedest{#3}%
-    \ifx\pdfoutlinedest\empty
-      \def\pdfoutlinedest{#4}%
-    \else
-      \txiescapepdf\pdfoutlinedest
-    \fi
-    %
-    % Also escape PDF chars in the display string.
-    \edef\pdfoutlinetext{#1}%
-    \txiescapepdf\pdfoutlinetext
-    %
-    \pdfoutline goto name{\pdfmkpgn{\pdfoutlinedest}}#2{\pdfoutlinetext}%
-  }
-  %
-  \def\pdfmakeoutlines{%
-    \begingroup
-      % Read toc silently, to get counts of subentries for \pdfoutline.
-      \def\partentry##1##2##3##4{}% ignore parts in the outlines
-      \def\numchapentry##1##2##3##4{%
-	\def\thischapnum{##2}%
-	\def\thissecnum{0}%
-	\def\thissubsecnum{0}%
-      }%
-      \def\numsecentry##1##2##3##4{%
-	\advancenumber{chap\thischapnum}%
-	\def\thissecnum{##2}%
-	\def\thissubsecnum{0}%
-      }%
-      \def\numsubsecentry##1##2##3##4{%
-	\advancenumber{sec\thissecnum}%
-	\def\thissubsecnum{##2}%
-      }%
-      \def\numsubsubsecentry##1##2##3##4{%
-	\advancenumber{subsec\thissubsecnum}%
-      }%
-      \def\thischapnum{0}%
-      \def\thissecnum{0}%
-      \def\thissubsecnum{0}%
-      %
-      % use \def rather than \let here because we redefine \chapentry et
-      % al. a second time, below.
-      \def\appentry{\numchapentry}%
-      \def\appsecentry{\numsecentry}%
-      \def\appsubsecentry{\numsubsecentry}%
-      \def\appsubsubsecentry{\numsubsubsecentry}%
-      \def\unnchapentry{\numchapentry}%
-      \def\unnsecentry{\numsecentry}%
-      \def\unnsubsecentry{\numsubsecentry}%
-      \def\unnsubsubsecentry{\numsubsubsecentry}%
-      \readdatafile{toc}%
-      %
-      % Read toc second time, this time actually producing the outlines.
-      % The `-' means take the \expnumber as the absolute number of
-      % subentries, which we calculated on our first read of the .toc above.
-      %
-      % We use the node names as the destinations.
-      \def\numchapentry##1##2##3##4{%
-        \dopdfoutline{##1}{count-\expnumber{chap##2}}{##3}{##4}}%
-      \def\numsecentry##1##2##3##4{%
-        \dopdfoutline{##1}{count-\expnumber{sec##2}}{##3}{##4}}%
-      \def\numsubsecentry##1##2##3##4{%
-        \dopdfoutline{##1}{count-\expnumber{subsec##2}}{##3}{##4}}%
-      \def\numsubsubsecentry##1##2##3##4{% count is always zero
-        \dopdfoutline{##1}{}{##3}{##4}}%
-      %
-      % PDF outlines are displayed using system fonts, instead of
-      % document fonts.  Therefore we cannot use special characters,
-      % since the encoding is unknown.  For example, the eogonek from
-      % Latin 2 (0xea) gets translated to a | character.  Info from
-      % Staszek Wawrykiewicz, 19 Jan 2004 04:09:24 +0100.
-      %
-      % TODO this right, we have to translate 8-bit characters to
-      % their "best" equivalent, based on the @documentencoding.  Too
-      % much work for too little return.  Just use the ASCII equivalents
-      % we use for the index sort strings.
-      % 
-      \indexnofonts
-      \setupdatafile
-      % We can have normal brace characters in the PDF outlines, unlike
-      % Texinfo index files.  So set that up.
-      \def\{{\lbracecharliteral}%
-      \def\}{\rbracecharliteral}%
-      \catcode`\\=\active \otherbackslash
-      \input \tocreadfilename
-    \endgroup
-  }
-  {\catcode`[=1 \catcode`]=2
-   \catcode`{=\other \catcode`}=\other
-   \gdef\lbracecharliteral[{]%
-   \gdef\rbracecharliteral[}]%
-  ]
-  %
-  \def\skipspaces#1{\def\PP{#1}\def\D{|}%
-    \ifx\PP\D\let\nextsp\relax
-    \else\let\nextsp\skipspaces
-      \addtokens{\filename}{\PP}%
-      \advance\filenamelength by 1
-    \fi
-    \nextsp}
-  \def\getfilename#1{%
-    \filenamelength=0
-    % If we don't expand the argument now, \skipspaces will get
-    % snagged on things like "@value{foo}".
-    \edef\temp{#1}%
-    \expandafter\skipspaces\temp|\relax
-  }
-  \ifnum\pdftexversion < 14
-    \let \startlink \pdfannotlink
-  \else
-    \let \startlink \pdfstartlink
-  \fi
-  % make a live url in pdf output.
-  \def\pdfurl#1{%
-    \begingroup
-      % it seems we really need yet another set of dummies; have not
-      % tried to figure out what each command should do in the context
-      % of @url.  for now, just make @/ a no-op, that's the only one
-      % people have actually reported a problem with.
-      %
-      \normalturnoffactive
-      \def\@{@}%
-      \let\/=\empty
-      \makevalueexpandable
-      % do we want to go so far as to use \indexnofonts instead of just
-      % special-casing \var here?
-      \def\var##1{##1}%
-      %
-      \leavevmode\setcolor{\urlcolor}%
-      \startlink attr{/Border [0 0 0]}%
-        user{/Subtype /Link /A << /S /URI /URI (#1) >>}%
-    \endgroup}
-  \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}}
-  \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks}
-  \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks}
-  \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}}
-  \def\maketoks{%
-    \expandafter\poptoks\the\toksA|ENDTOKS|\relax
-    \ifx\first0\adn0
-    \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3
-    \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6
-    \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9
-    \else
-      \ifnum0=\countA\else\makelink\fi
-      \ifx\first.\let\next=\done\else
-        \let\next=\maketoks
-        \addtokens{\toksB}{\the\toksD}
-        \ifx\first,\addtokens{\toksB}{\space}\fi
-      \fi
-    \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
-    \next}
-  \def\makelink{\addtokens{\toksB}%
-    {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0}
-  \def\pdflink#1{%
-    \startlink attr{/Border [0 0 0]} goto name{\pdfmkpgn{#1}}
-    \setcolor{\linkcolor}#1\endlink}
-  \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st}
-\else
-  % non-pdf mode
-  \let\pdfmkdest = \gobble
-  \let\pdfurl = \gobble
-  \let\endlink = \relax
-  \let\setcolor = \gobble
-  \let\pdfsetcolor = \gobble
-  \let\pdfmakeoutlines = \relax
-\fi  % \ifx\pdfoutput
-
-
-\message{fonts,}
-
-% Change the current font style to #1, remembering it in \curfontstyle.
-% For now, we do not accumulate font styles: @b{@i{foo}} prints foo in
-% italics, not bold italics.
-%
-\def\setfontstyle#1{%
-  \def\curfontstyle{#1}% not as a control sequence, because we are \edef'd.
-  \csname ten#1\endcsname  % change the current font
-}
-
-% Select #1 fonts with the current style.
-%
-\def\selectfonts#1{\csname #1fonts\endcsname \csname\curfontstyle\endcsname}
-
-\def\rm{\fam=0 \setfontstyle{rm}}
-\def\it{\fam=\itfam \setfontstyle{it}}
-\def\sl{\fam=\slfam \setfontstyle{sl}}
-\def\bf{\fam=\bffam \setfontstyle{bf}}\def\bfstylename{bf}
-\def\tt{\fam=\ttfam \setfontstyle{tt}}
-
-% Unfortunately, we have to override this for titles and the like, since
-% in those cases "rm" is bold.  Sigh.
-\def\rmisbold{\rm\def\curfontstyle{bf}}
-
-% Texinfo sort of supports the sans serif font style, which plain TeX does not.
-% So we set up a \sf.
-\newfam\sffam
-\def\sf{\fam=\sffam \setfontstyle{sf}}
-\let\li = \sf % Sometimes we call it \li, not \sf.
-
-% We don't need math for this font style.
-\def\ttsl{\setfontstyle{ttsl}}
-
-
-% Set the baselineskip to #1, and the lineskip and strut size
-% correspondingly.  There is no deep meaning behind these magic numbers
-% used as factors; they just match (closely enough) what Knuth defined.
-%
-\def\lineskipfactor{.08333}
-\def\strutheightpercent{.70833}
-\def\strutdepthpercent {.29167}
-%
-% can get a sort of poor man's double spacing by redefining this.
-\def\baselinefactor{1}
-%
-\newdimen\textleading
-\def\setleading#1{%
-  \dimen0 = #1\relax
-  \normalbaselineskip = \baselinefactor\dimen0
-  \normallineskip = \lineskipfactor\normalbaselineskip
-  \normalbaselines
-  \setbox\strutbox =\hbox{%
-    \vrule width0pt height\strutheightpercent\baselineskip
-                    depth \strutdepthpercent \baselineskip
-  }%
-}
-
-% PDF CMaps.  See also LaTeX's t1.cmap.
-%
-% do nothing with this by default.
-\expandafter\let\csname cmapOT1\endcsname\gobble
-\expandafter\let\csname cmapOT1IT\endcsname\gobble
-\expandafter\let\csname cmapOT1TT\endcsname\gobble
-
-% if we are producing pdf, and we have \pdffontattr, then define cmaps.
-% (\pdffontattr was introduced many years ago, but people still run
-% older pdftex's; it's easy to conditionalize, so we do.)
-\ifpdf \ifx\pdffontattr\thisisundefined \else
-  \begingroup
-    \catcode`\^^M=\active \def^^M{^^J}% Output line endings as the ^^J char.
-    \catcode`\%=12 \immediate\pdfobj stream {%!PS-Adobe-3.0 Resource-CMap
-%%DocumentNeededResources: ProcSet (CIDInit)
-%%IncludeResource: ProcSet (CIDInit)
-%%BeginResource: CMap (TeX-OT1-0)
-%%Title: (TeX-OT1-0 TeX OT1 0)
-%%Version: 1.000
-%%EndComments
-/CIDInit /ProcSet findresource begin
-12 dict begin
-begincmap
-/CIDSystemInfo
-<< /Registry (TeX)
-/Ordering (OT1)
-/Supplement 0
->> def
-/CMapName /TeX-OT1-0 def
-/CMapType 2 def
-1 begincodespacerange
-<00> <7F>
-endcodespacerange
-8 beginbfrange
-<00> <01> <0393>
-<09> <0A> <03A8>
-<23> <26> <0023>
-<28> <3B> <0028>
-<3F> <5B> <003F>
-<5D> <5E> <005D>
-<61> <7A> <0061>
-<7B> <7C> <2013>
-endbfrange
-40 beginbfchar
-<02> <0398>
-<03> <039B>
-<04> <039E>
-<05> <03A0>
-<06> <03A3>
-<07> <03D2>
-<08> <03A6>
-<0B> <00660066>
-<0C> <00660069>
-<0D> <0066006C>
-<0E> <006600660069>
-<0F> <00660066006C>
-<10> <0131>
-<11> <0237>
-<12> <0060>
-<13> <00B4>
-<14> <02C7>
-<15> <02D8>
-<16> <00AF>
-<17> <02DA>
-<18> <00B8>
-<19> <00DF>
-<1A> <00E6>
-<1B> <0153>
-<1C> <00F8>
-<1D> <00C6>
-<1E> <0152>
-<1F> <00D8>
-<21> <0021>
-<22> <201D>
-<27> <2019>
-<3C> <00A1>
-<3D> <003D>
-<3E> <00BF>
-<5C> <201C>
-<5F> <02D9>
-<60> <2018>
-<7D> <02DD>
-<7E> <007E>
-<7F> <00A8>
-endbfchar
-endcmap
-CMapName currentdict /CMap defineresource pop
-end
-end
-%%EndResource
-%%EOF
-    }\endgroup
-  \expandafter\edef\csname cmapOT1\endcsname#1{%
-    \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}%
-  }%
-%
-% \cmapOT1IT
-  \begingroup
-    \catcode`\^^M=\active \def^^M{^^J}% Output line endings as the ^^J char.
-    \catcode`\%=12 \immediate\pdfobj stream {%!PS-Adobe-3.0 Resource-CMap
-%%DocumentNeededResources: ProcSet (CIDInit)
-%%IncludeResource: ProcSet (CIDInit)
-%%BeginResource: CMap (TeX-OT1IT-0)
-%%Title: (TeX-OT1IT-0 TeX OT1IT 0)
-%%Version: 1.000
-%%EndComments
-/CIDInit /ProcSet findresource begin
-12 dict begin
-begincmap
-/CIDSystemInfo
-<< /Registry (TeX)
-/Ordering (OT1IT)
-/Supplement 0
->> def
-/CMapName /TeX-OT1IT-0 def
-/CMapType 2 def
-1 begincodespacerange
-<00> <7F>
-endcodespacerange
-8 beginbfrange
-<00> <01> <0393>
-<09> <0A> <03A8>
-<25> <26> <0025>
-<28> <3B> <0028>
-<3F> <5B> <003F>
-<5D> <5E> <005D>
-<61> <7A> <0061>
-<7B> <7C> <2013>
-endbfrange
-42 beginbfchar
-<02> <0398>
-<03> <039B>
-<04> <039E>
-<05> <03A0>
-<06> <03A3>
-<07> <03D2>
-<08> <03A6>
-<0B> <00660066>
-<0C> <00660069>
-<0D> <0066006C>
-<0E> <006600660069>
-<0F> <00660066006C>
-<10> <0131>
-<11> <0237>
-<12> <0060>
-<13> <00B4>
-<14> <02C7>
-<15> <02D8>
-<16> <00AF>
-<17> <02DA>
-<18> <00B8>
-<19> <00DF>
-<1A> <00E6>
-<1B> <0153>
-<1C> <00F8>
-<1D> <00C6>
-<1E> <0152>
-<1F> <00D8>
-<21> <0021>
-<22> <201D>
-<23> <0023>
-<24> <00A3>
-<27> <2019>
-<3C> <00A1>
-<3D> <003D>
-<3E> <00BF>
-<5C> <201C>
-<5F> <02D9>
-<60> <2018>
-<7D> <02DD>
-<7E> <007E>
-<7F> <00A8>
-endbfchar
-endcmap
-CMapName currentdict /CMap defineresource pop
-end
-end
-%%EndResource
-%%EOF
-    }\endgroup
-  \expandafter\edef\csname cmapOT1IT\endcsname#1{%
-    \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}%
-  }%
-%
-% \cmapOT1TT
-  \begingroup
-    \catcode`\^^M=\active \def^^M{^^J}% Output line endings as the ^^J char.
-    \catcode`\%=12 \immediate\pdfobj stream {%!PS-Adobe-3.0 Resource-CMap
-%%DocumentNeededResources: ProcSet (CIDInit)
-%%IncludeResource: ProcSet (CIDInit)
-%%BeginResource: CMap (TeX-OT1TT-0)
-%%Title: (TeX-OT1TT-0 TeX OT1TT 0)
-%%Version: 1.000
-%%EndComments
-/CIDInit /ProcSet findresource begin
-12 dict begin
-begincmap
-/CIDSystemInfo
-<< /Registry (TeX)
-/Ordering (OT1TT)
-/Supplement 0
->> def
-/CMapName /TeX-OT1TT-0 def
-/CMapType 2 def
-1 begincodespacerange
-<00> <7F>
-endcodespacerange
-5 beginbfrange
-<00> <01> <0393>
-<09> <0A> <03A8>
-<21> <26> <0021>
-<28> <5F> <0028>
-<61> <7E> <0061>
-endbfrange
-32 beginbfchar
-<02> <0398>
-<03> <039B>
-<04> <039E>
-<05> <03A0>
-<06> <03A3>
-<07> <03D2>
-<08> <03A6>
-<0B> <2191>
-<0C> <2193>
-<0D> <0027>
-<0E> <00A1>
-<0F> <00BF>
-<10> <0131>
-<11> <0237>
-<12> <0060>
-<13> <00B4>
-<14> <02C7>
-<15> <02D8>
-<16> <00AF>
-<17> <02DA>
-<18> <00B8>
-<19> <00DF>
-<1A> <00E6>
-<1B> <0153>
-<1C> <00F8>
-<1D> <00C6>
-<1E> <0152>
-<1F> <00D8>
-<20> <2423>
-<27> <2019>
-<60> <2018>
-<7F> <00A8>
-endbfchar
-endcmap
-CMapName currentdict /CMap defineresource pop
-end
-end
-%%EndResource
-%%EOF
-    }\endgroup
-  \expandafter\edef\csname cmapOT1TT\endcsname#1{%
-    \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}%
-  }%
-\fi\fi
-
-
-% Set the font macro #1 to the font named \fontprefix#2.
-% #3 is the font's design size, #4 is a scale factor, #5 is the CMap
-% encoding (only OT1, OT1IT and OT1TT are allowed, or empty to omit).
-% Example:
-% #1 = \textrm
-% #2 = \rmshape
-% #3 = 10
-% #4 = \mainmagstep
-% #5 = OT1
-%
-\def\setfont#1#2#3#4#5{%
-  \font#1=\fontprefix#2#3 scaled #4
-  \csname cmap#5\endcsname#1%
-}
-% This is what gets called when #5 of \setfont is empty.
-\let\cmap\gobble
-%
-% (end of cmaps)
-
-% Use cm as the default font prefix.
-% To specify the font prefix, you must define \fontprefix
-% before you read in texinfo.tex.
-\ifx\fontprefix\thisisundefined
-\def\fontprefix{cm}
-\fi
-% Support font families that don't use the same naming scheme as CM.
-\def\rmshape{r}
-\def\rmbshape{bx}               % where the normal face is bold
-\def\bfshape{b}
-\def\bxshape{bx}
-\def\ttshape{tt}
-\def\ttbshape{tt}
-\def\ttslshape{sltt}
-\def\itshape{ti}
-\def\itbshape{bxti}
-\def\slshape{sl}
-\def\slbshape{bxsl}
-\def\sfshape{ss}
-\def\sfbshape{ss}
-\def\scshape{csc}
-\def\scbshape{csc}
-
-% Definitions for a main text size of 11pt.  (The default in Texinfo.)
-%
-\def\definetextfontsizexi{%
-% Text fonts (11.2pt, magstep1).
-\def\textnominalsize{11pt}
-\edef\mainmagstep{\magstephalf}
-\setfont\textrm\rmshape{10}{\mainmagstep}{OT1}
-\setfont\texttt\ttshape{10}{\mainmagstep}{OT1TT}
-\setfont\textbf\bfshape{10}{\mainmagstep}{OT1}
-\setfont\textit\itshape{10}{\mainmagstep}{OT1IT}
-\setfont\textsl\slshape{10}{\mainmagstep}{OT1}
-\setfont\textsf\sfshape{10}{\mainmagstep}{OT1}
-\setfont\textsc\scshape{10}{\mainmagstep}{OT1}
-\setfont\textttsl\ttslshape{10}{\mainmagstep}{OT1TT}
-\font\texti=cmmi10 scaled \mainmagstep
-\font\textsy=cmsy10 scaled \mainmagstep
-\def\textecsize{1095}
-
-% A few fonts for @defun names and args.
-\setfont\defbf\bfshape{10}{\magstep1}{OT1}
-\setfont\deftt\ttshape{10}{\magstep1}{OT1TT}
-\setfont\defttsl\ttslshape{10}{\magstep1}{OT1TT}
-\def\df{\let\tentt=\deftt \let\tenbf = \defbf \let\tenttsl=\defttsl \bf}
-
-% Fonts for indices, footnotes, small examples (9pt).
-\def\smallnominalsize{9pt}
-\setfont\smallrm\rmshape{9}{1000}{OT1}
-\setfont\smalltt\ttshape{9}{1000}{OT1TT}
-\setfont\smallbf\bfshape{10}{900}{OT1}
-\setfont\smallit\itshape{9}{1000}{OT1IT}
-\setfont\smallsl\slshape{9}{1000}{OT1}
-\setfont\smallsf\sfshape{9}{1000}{OT1}
-\setfont\smallsc\scshape{10}{900}{OT1}
-\setfont\smallttsl\ttslshape{10}{900}{OT1TT}
-\font\smalli=cmmi9
-\font\smallsy=cmsy9
-\def\smallecsize{0900}
-
-% Fonts for small examples (8pt).
-\def\smallernominalsize{8pt}
-\setfont\smallerrm\rmshape{8}{1000}{OT1}
-\setfont\smallertt\ttshape{8}{1000}{OT1TT}
-\setfont\smallerbf\bfshape{10}{800}{OT1}
-\setfont\smallerit\itshape{8}{1000}{OT1IT}
-\setfont\smallersl\slshape{8}{1000}{OT1}
-\setfont\smallersf\sfshape{8}{1000}{OT1}
-\setfont\smallersc\scshape{10}{800}{OT1}
-\setfont\smallerttsl\ttslshape{10}{800}{OT1TT}
-\font\smalleri=cmmi8
-\font\smallersy=cmsy8
-\def\smallerecsize{0800}
-
-% Fonts for title page (20.4pt):
-\def\titlenominalsize{20pt}
-\setfont\titlerm\rmbshape{12}{\magstep3}{OT1}
-\setfont\titleit\itbshape{10}{\magstep4}{OT1IT}
-\setfont\titlesl\slbshape{10}{\magstep4}{OT1}
-\setfont\titlett\ttbshape{12}{\magstep3}{OT1TT}
-\setfont\titlettsl\ttslshape{10}{\magstep4}{OT1TT}
-\setfont\titlesf\sfbshape{17}{\magstep1}{OT1}
-\let\titlebf=\titlerm
-\setfont\titlesc\scbshape{10}{\magstep4}{OT1}
-\font\titlei=cmmi12 scaled \magstep3
-\font\titlesy=cmsy10 scaled \magstep4
-\def\titleecsize{2074}
-
-% Chapter (and unnumbered) fonts (17.28pt).
-\def\chapnominalsize{17pt}
-\setfont\chaprm\rmbshape{12}{\magstep2}{OT1}
-\setfont\chapit\itbshape{10}{\magstep3}{OT1IT}
-\setfont\chapsl\slbshape{10}{\magstep3}{OT1}
-\setfont\chaptt\ttbshape{12}{\magstep2}{OT1TT}
-\setfont\chapttsl\ttslshape{10}{\magstep3}{OT1TT}
-\setfont\chapsf\sfbshape{17}{1000}{OT1}
-\let\chapbf=\chaprm
-\setfont\chapsc\scbshape{10}{\magstep3}{OT1}
-\font\chapi=cmmi12 scaled \magstep2
-\font\chapsy=cmsy10 scaled \magstep3
-\def\chapecsize{1728}
-
-% Section fonts (14.4pt).
-\def\secnominalsize{14pt}
-\setfont\secrm\rmbshape{12}{\magstep1}{OT1}
-\setfont\secit\itbshape{10}{\magstep2}{OT1IT}
-\setfont\secsl\slbshape{10}{\magstep2}{OT1}
-\setfont\sectt\ttbshape{12}{\magstep1}{OT1TT}
-\setfont\secttsl\ttslshape{10}{\magstep2}{OT1TT}
-\setfont\secsf\sfbshape{12}{\magstep1}{OT1}
-\let\secbf\secrm
-\setfont\secsc\scbshape{10}{\magstep2}{OT1}
-\font\seci=cmmi12 scaled \magstep1
-\font\secsy=cmsy10 scaled \magstep2
-\def\sececsize{1440}
-
-% Subsection fonts (13.15pt).
-\def\ssecnominalsize{13pt}
-\setfont\ssecrm\rmbshape{12}{\magstephalf}{OT1}
-\setfont\ssecit\itbshape{10}{1315}{OT1IT}
-\setfont\ssecsl\slbshape{10}{1315}{OT1}
-\setfont\ssectt\ttbshape{12}{\magstephalf}{OT1TT}
-\setfont\ssecttsl\ttslshape{10}{1315}{OT1TT}
-\setfont\ssecsf\sfbshape{12}{\magstephalf}{OT1}
-\let\ssecbf\ssecrm
-\setfont\ssecsc\scbshape{10}{1315}{OT1}
-\font\sseci=cmmi12 scaled \magstephalf
-\font\ssecsy=cmsy10 scaled 1315
-\def\ssececsize{1200}
-
-% Reduced fonts for @acro in text (10pt).
-\def\reducednominalsize{10pt}
-\setfont\reducedrm\rmshape{10}{1000}{OT1}
-\setfont\reducedtt\ttshape{10}{1000}{OT1TT}
-\setfont\reducedbf\bfshape{10}{1000}{OT1}
-\setfont\reducedit\itshape{10}{1000}{OT1IT}
-\setfont\reducedsl\slshape{10}{1000}{OT1}
-\setfont\reducedsf\sfshape{10}{1000}{OT1}
-\setfont\reducedsc\scshape{10}{1000}{OT1}
-\setfont\reducedttsl\ttslshape{10}{1000}{OT1TT}
-\font\reducedi=cmmi10
-\font\reducedsy=cmsy10
-\def\reducedecsize{1000}
-
-\textleading = 13.2pt % line spacing for 11pt CM
-\textfonts            % reset the current fonts
-\rm
-} % end of 11pt text font size definitions, \definetextfontsizexi
-
-
-% Definitions to make the main text be 10pt Computer Modern, with
-% section, chapter, etc., sizes following suit.  This is for the GNU
-% Press printing of the Emacs 22 manual.  Maybe other manuals in the
-% future.  Used with @smallbook, which sets the leading to 12pt.
-%
-\def\definetextfontsizex{%
-% Text fonts (10pt).
-\def\textnominalsize{10pt}
-\edef\mainmagstep{1000}
-\setfont\textrm\rmshape{10}{\mainmagstep}{OT1}
-\setfont\texttt\ttshape{10}{\mainmagstep}{OT1TT}
-\setfont\textbf\bfshape{10}{\mainmagstep}{OT1}
-\setfont\textit\itshape{10}{\mainmagstep}{OT1IT}
-\setfont\textsl\slshape{10}{\mainmagstep}{OT1}
-\setfont\textsf\sfshape{10}{\mainmagstep}{OT1}
-\setfont\textsc\scshape{10}{\mainmagstep}{OT1}
-\setfont\textttsl\ttslshape{10}{\mainmagstep}{OT1TT}
-\font\texti=cmmi10 scaled \mainmagstep
-\font\textsy=cmsy10 scaled \mainmagstep
-\def\textecsize{1000}
-
-% A few fonts for @defun names and args.
-\setfont\defbf\bfshape{10}{\magstephalf}{OT1}
-\setfont\deftt\ttshape{10}{\magstephalf}{OT1TT}
-\setfont\defttsl\ttslshape{10}{\magstephalf}{OT1TT}
-\def\df{\let\tentt=\deftt \let\tenbf = \defbf \let\tenttsl=\defttsl \bf}
-
-% Fonts for indices, footnotes, small examples (9pt).
-\def\smallnominalsize{9pt}
-\setfont\smallrm\rmshape{9}{1000}{OT1}
-\setfont\smalltt\ttshape{9}{1000}{OT1TT}
-\setfont\smallbf\bfshape{10}{900}{OT1}
-\setfont\smallit\itshape{9}{1000}{OT1IT}
-\setfont\smallsl\slshape{9}{1000}{OT1}
-\setfont\smallsf\sfshape{9}{1000}{OT1}
-\setfont\smallsc\scshape{10}{900}{OT1}
-\setfont\smallttsl\ttslshape{10}{900}{OT1TT}
-\font\smalli=cmmi9
-\font\smallsy=cmsy9
-\def\smallecsize{0900}
-
-% Fonts for small examples (8pt).
-\def\smallernominalsize{8pt}
-\setfont\smallerrm\rmshape{8}{1000}{OT1}
-\setfont\smallertt\ttshape{8}{1000}{OT1TT}
-\setfont\smallerbf\bfshape{10}{800}{OT1}
-\setfont\smallerit\itshape{8}{1000}{OT1IT}
-\setfont\smallersl\slshape{8}{1000}{OT1}
-\setfont\smallersf\sfshape{8}{1000}{OT1}
-\setfont\smallersc\scshape{10}{800}{OT1}
-\setfont\smallerttsl\ttslshape{10}{800}{OT1TT}
-\font\smalleri=cmmi8
-\font\smallersy=cmsy8
-\def\smallerecsize{0800}
-
-% Fonts for title page (20.4pt):
-\def\titlenominalsize{20pt}
-\setfont\titlerm\rmbshape{12}{\magstep3}{OT1}
-\setfont\titleit\itbshape{10}{\magstep4}{OT1IT}
-\setfont\titlesl\slbshape{10}{\magstep4}{OT1}
-\setfont\titlett\ttbshape{12}{\magstep3}{OT1TT}
-\setfont\titlettsl\ttslshape{10}{\magstep4}{OT1TT}
-\setfont\titlesf\sfbshape{17}{\magstep1}{OT1}
-\let\titlebf=\titlerm
-\setfont\titlesc\scbshape{10}{\magstep4}{OT1}
-\font\titlei=cmmi12 scaled \magstep3
-\font\titlesy=cmsy10 scaled \magstep4
-\def\titleecsize{2074}
-
-% Chapter fonts (14.4pt).
-\def\chapnominalsize{14pt}
-\setfont\chaprm\rmbshape{12}{\magstep1}{OT1}
-\setfont\chapit\itbshape{10}{\magstep2}{OT1IT}
-\setfont\chapsl\slbshape{10}{\magstep2}{OT1}
-\setfont\chaptt\ttbshape{12}{\magstep1}{OT1TT}
-\setfont\chapttsl\ttslshape{10}{\magstep2}{OT1TT}
-\setfont\chapsf\sfbshape{12}{\magstep1}{OT1}
-\let\chapbf\chaprm
-\setfont\chapsc\scbshape{10}{\magstep2}{OT1}
-\font\chapi=cmmi12 scaled \magstep1
-\font\chapsy=cmsy10 scaled \magstep2
-\def\chapecsize{1440}
-
-% Section fonts (12pt).
-\def\secnominalsize{12pt}
-\setfont\secrm\rmbshape{12}{1000}{OT1}
-\setfont\secit\itbshape{10}{\magstep1}{OT1IT}
-\setfont\secsl\slbshape{10}{\magstep1}{OT1}
-\setfont\sectt\ttbshape{12}{1000}{OT1TT}
-\setfont\secttsl\ttslshape{10}{\magstep1}{OT1TT}
-\setfont\secsf\sfbshape{12}{1000}{OT1}
-\let\secbf\secrm
-\setfont\secsc\scbshape{10}{\magstep1}{OT1}
-\font\seci=cmmi12
-\font\secsy=cmsy10 scaled \magstep1
-\def\sececsize{1200}
-
-% Subsection fonts (10pt).
-\def\ssecnominalsize{10pt}
-\setfont\ssecrm\rmbshape{10}{1000}{OT1}
-\setfont\ssecit\itbshape{10}{1000}{OT1IT}
-\setfont\ssecsl\slbshape{10}{1000}{OT1}
-\setfont\ssectt\ttbshape{10}{1000}{OT1TT}
-\setfont\ssecttsl\ttslshape{10}{1000}{OT1TT}
-\setfont\ssecsf\sfbshape{10}{1000}{OT1}
-\let\ssecbf\ssecrm
-\setfont\ssecsc\scbshape{10}{1000}{OT1}
-\font\sseci=cmmi10
-\font\ssecsy=cmsy10
-\def\ssececsize{1000}
-
-% Reduced fonts for @acro in text (9pt).
-\def\reducednominalsize{9pt}
-\setfont\reducedrm\rmshape{9}{1000}{OT1}
-\setfont\reducedtt\ttshape{9}{1000}{OT1TT}
-\setfont\reducedbf\bfshape{10}{900}{OT1}
-\setfont\reducedit\itshape{9}{1000}{OT1IT}
-\setfont\reducedsl\slshape{9}{1000}{OT1}
-\setfont\reducedsf\sfshape{9}{1000}{OT1}
-\setfont\reducedsc\scshape{10}{900}{OT1}
-\setfont\reducedttsl\ttslshape{10}{900}{OT1TT}
-\font\reducedi=cmmi9
-\font\reducedsy=cmsy9
-\def\reducedecsize{0900}
-
-\divide\parskip by 2  % reduce space between paragraphs
-\textleading = 12pt   % line spacing for 10pt CM
-\textfonts            % reset the current fonts
-\rm
-} % end of 10pt text font size definitions, \definetextfontsizex
-
-
-% We provide the user-level command
-%   @fonttextsize 10
-% (or 11) to redefine the text font size.  pt is assumed.
-%
-\def\xiword{11}
-\def\xword{10}
-\def\xwordpt{10pt}
-%
-\parseargdef\fonttextsize{%
-  \def\textsizearg{#1}%
-  %\wlog{doing @fonttextsize \textsizearg}%
-  %
-  % Set \globaldefs so that documents can use this inside @tex, since
-  % makeinfo 4.8 does not support it, but we need it nonetheless.
-  %
- \begingroup \globaldefs=1
-  \ifx\textsizearg\xword \definetextfontsizex
-  \else \ifx\textsizearg\xiword \definetextfontsizexi
-  \else
-    \errhelp=\EMsimple
-    \errmessage{@fonttextsize only supports `10' or `11', not `\textsizearg'}
-  \fi\fi
- \endgroup
-}
-
-
-% In order for the font changes to affect most math symbols and letters,
-% we have to define the \textfont of the standard families.  Since
-% texinfo doesn't allow for producing subscripts and superscripts except
-% in the main text, we don't bother to reset \scriptfont and
-% \scriptscriptfont (which would also require loading a lot more fonts).
-%
-\def\resetmathfonts{%
-  \textfont0=\tenrm \textfont1=\teni \textfont2=\tensy
-  \textfont\itfam=\tenit \textfont\slfam=\tensl \textfont\bffam=\tenbf
-  \textfont\ttfam=\tentt \textfont\sffam=\tensf
-}
-
-% The font-changing commands redefine the meanings of \tenSTYLE, instead
-% of just \STYLE.  We do this because \STYLE needs to also set the
-% current \fam for math mode.  Our \STYLE (e.g., \rm) commands hardwire
-% \tenSTYLE to set the current font.
-%
-% Each font-changing command also sets the names \lsize (one size lower)
-% and \lllsize (three sizes lower).  These relative commands are used in
-% the LaTeX logo and acronyms.
-%
-% This all needs generalizing, badly.
-%
-\def\textfonts{%
-  \let\tenrm=\textrm \let\tenit=\textit \let\tensl=\textsl
-  \let\tenbf=\textbf \let\tentt=\texttt \let\smallcaps=\textsc
-  \let\tensf=\textsf \let\teni=\texti \let\tensy=\textsy
-  \let\tenttsl=\textttsl
-  \def\curfontsize{text}%
-  \def\lsize{reduced}\def\lllsize{smaller}%
-  \resetmathfonts \setleading{\textleading}}
-\def\titlefonts{%
-  \let\tenrm=\titlerm \let\tenit=\titleit \let\tensl=\titlesl
-  \let\tenbf=\titlebf \let\tentt=\titlett \let\smallcaps=\titlesc
-  \let\tensf=\titlesf \let\teni=\titlei \let\tensy=\titlesy
-  \let\tenttsl=\titlettsl
-  \def\curfontsize{title}%
-  \def\lsize{chap}\def\lllsize{subsec}%
-  \resetmathfonts \setleading{27pt}}
-\def\titlefont#1{{\titlefonts\rmisbold #1}}
-\def\chapfonts{%
-  \let\tenrm=\chaprm \let\tenit=\chapit \let\tensl=\chapsl
-  \let\tenbf=\chapbf \let\tentt=\chaptt \let\smallcaps=\chapsc
-  \let\tensf=\chapsf \let\teni=\chapi \let\tensy=\chapsy
-  \let\tenttsl=\chapttsl
-  \def\curfontsize{chap}%
-  \def\lsize{sec}\def\lllsize{text}%
-  \resetmathfonts \setleading{19pt}}
-\def\secfonts{%
-  \let\tenrm=\secrm \let\tenit=\secit \let\tensl=\secsl
-  \let\tenbf=\secbf \let\tentt=\sectt \let\smallcaps=\secsc
-  \let\tensf=\secsf \let\teni=\seci \let\tensy=\secsy
-  \let\tenttsl=\secttsl
-  \def\curfontsize{sec}%
-  \def\lsize{subsec}\def\lllsize{reduced}%
-  \resetmathfonts \setleading{16pt}}
-\def\subsecfonts{%
-  \let\tenrm=\ssecrm \let\tenit=\ssecit \let\tensl=\ssecsl
-  \let\tenbf=\ssecbf \let\tentt=\ssectt \let\smallcaps=\ssecsc
-  \let\tensf=\ssecsf \let\teni=\sseci \let\tensy=\ssecsy
-  \let\tenttsl=\ssecttsl
-  \def\curfontsize{ssec}%
-  \def\lsize{text}\def\lllsize{small}%
-  \resetmathfonts \setleading{15pt}}
-\let\subsubsecfonts = \subsecfonts
-\def\reducedfonts{%
-  \let\tenrm=\reducedrm \let\tenit=\reducedit \let\tensl=\reducedsl
-  \let\tenbf=\reducedbf \let\tentt=\reducedtt \let\reducedcaps=\reducedsc
-  \let\tensf=\reducedsf \let\teni=\reducedi \let\tensy=\reducedsy
-  \let\tenttsl=\reducedttsl
-  \def\curfontsize{reduced}%
-  \def\lsize{small}\def\lllsize{smaller}%
-  \resetmathfonts \setleading{10.5pt}}
-\def\smallfonts{%
-  \let\tenrm=\smallrm \let\tenit=\smallit \let\tensl=\smallsl
-  \let\tenbf=\smallbf \let\tentt=\smalltt \let\smallcaps=\smallsc
-  \let\tensf=\smallsf \let\teni=\smalli \let\tensy=\smallsy
-  \let\tenttsl=\smallttsl
-  \def\curfontsize{small}%
-  \def\lsize{smaller}\def\lllsize{smaller}%
-  \resetmathfonts \setleading{10.5pt}}
-\def\smallerfonts{%
-  \let\tenrm=\smallerrm \let\tenit=\smallerit \let\tensl=\smallersl
-  \let\tenbf=\smallerbf \let\tentt=\smallertt \let\smallcaps=\smallersc
-  \let\tensf=\smallersf \let\teni=\smalleri \let\tensy=\smallersy
-  \let\tenttsl=\smallerttsl
-  \def\curfontsize{smaller}%
-  \def\lsize{smaller}\def\lllsize{smaller}%
-  \resetmathfonts \setleading{9.5pt}}
-
-% Fonts for short table of contents.
-\setfont\shortcontrm\rmshape{12}{1000}{OT1}
-\setfont\shortcontbf\bfshape{10}{\magstep1}{OT1}  % no cmb12
-\setfont\shortcontsl\slshape{12}{1000}{OT1}
-\setfont\shortconttt\ttshape{12}{1000}{OT1TT}
-
-% Define these just so they can be easily changed for other fonts.
-\def\angleleft{$\langle$}
-\def\angleright{$\rangle$}
-
-% Set the fonts to use with the @small... environments.
-\let\smallexamplefonts = \smallfonts
-
-% About \smallexamplefonts.  If we use \smallfonts (9pt), @smallexample
-% can fit this many characters:
-%   8.5x11=86   smallbook=72  a4=90  a5=69
-% If we use \scriptfonts (8pt), then we can fit this many characters:
-%   8.5x11=90+  smallbook=80  a4=90+  a5=77
-% For me, subjectively, the few extra characters that fit aren't worth
-% the additional smallness of 8pt.  So I'm making the default 9pt.
-%
-% By the way, for comparison, here's what fits with @example (10pt):
-%   8.5x11=71  smallbook=60  a4=75  a5=58
-% --karl, 24jan03.
-
-% Set up the default fonts, so we can use them for creating boxes.
-%
-\definetextfontsizexi
-
-
-\message{markup,}
-
-% Check if we are currently using a typewriter font.  Since all the
-% Computer Modern typewriter fonts have zero interword stretch (and
-% shrink), and it is reasonable to expect all typewriter fonts to have
-% this property, we can check that font parameter.
-%
-\def\ifmonospace{\ifdim\fontdimen3\font=0pt }
-
-% Markup style infrastructure.  \defmarkupstylesetup\INITMACRO will
-% define and register \INITMACRO to be called on markup style changes.
-% \INITMACRO can check \currentmarkupstyle for the innermost
-% style and the set of \ifmarkupSTYLE switches for all styles
-% currently in effect.
-\newif\ifmarkupvar
-\newif\ifmarkupsamp
-\newif\ifmarkupkey
-%\newif\ifmarkupfile % @file == @samp.
-%\newif\ifmarkupoption % @option == @samp.
-\newif\ifmarkupcode
-\newif\ifmarkupkbd
-%\newif\ifmarkupenv % @env == @code.
-%\newif\ifmarkupcommand % @command == @code.
-\newif\ifmarkuptex % @tex (and part of @math, for now).
-\newif\ifmarkupexample
-\newif\ifmarkupverb
-\newif\ifmarkupverbatim
-
-\let\currentmarkupstyle\empty
-
-\def\setupmarkupstyle#1{%
-  \csname markup#1true\endcsname
-  \def\currentmarkupstyle{#1}%
-  \markupstylesetup
-}
-
-\let\markupstylesetup\empty
-
-\def\defmarkupstylesetup#1{%
-  \expandafter\def\expandafter\markupstylesetup
-    \expandafter{\markupstylesetup #1}%
-  \def#1%
-}
-
-% Markup style setup for left and right quotes.
-\defmarkupstylesetup\markupsetuplq{%
-  \expandafter\let\expandafter \temp
-    \csname markupsetuplq\currentmarkupstyle\endcsname
-  \ifx\temp\relax \markupsetuplqdefault \else \temp \fi
-}
-
-\defmarkupstylesetup\markupsetuprq{%
-  \expandafter\let\expandafter \temp
-    \csname markupsetuprq\currentmarkupstyle\endcsname
-  \ifx\temp\relax \markupsetuprqdefault \else \temp \fi
-}
-
-{
-\catcode`\'=\active
-\catcode`\`=\active
-
-\gdef\markupsetuplqdefault{\let`\lq}
-\gdef\markupsetuprqdefault{\let'\rq}
-
-\gdef\markupsetcodequoteleft{\let`\codequoteleft}
-\gdef\markupsetcodequoteright{\let'\codequoteright}
-}
-
-\let\markupsetuplqcode \markupsetcodequoteleft
-\let\markupsetuprqcode \markupsetcodequoteright
-%
-\let\markupsetuplqexample \markupsetcodequoteleft
-\let\markupsetuprqexample \markupsetcodequoteright
-%
-\let\markupsetuplqkbd     \markupsetcodequoteleft
-\let\markupsetuprqkbd     \markupsetcodequoteright
-%
-\let\markupsetuplqsamp \markupsetcodequoteleft
-\let\markupsetuprqsamp \markupsetcodequoteright
-%
-\let\markupsetuplqverb \markupsetcodequoteleft
-\let\markupsetuprqverb \markupsetcodequoteright
-%
-\let\markupsetuplqverbatim \markupsetcodequoteleft
-\let\markupsetuprqverbatim \markupsetcodequoteright
-
-% Allow an option to not use regular directed right quote/apostrophe
-% (char 0x27), but instead the undirected quote from cmtt (char 0x0d).
-% The undirected quote is ugly, so don't make it the default, but it
-% works for pasting with more pdf viewers (at least evince), the
-% lilypond developers report.  xpdf does work with the regular 0x27.
-%
-\def\codequoteright{%
-  \expandafter\ifx\csname SETtxicodequoteundirected\endcsname\relax
-    \expandafter\ifx\csname SETcodequoteundirected\endcsname\relax
-      '%
-    \else \char'15 \fi
-  \else \char'15 \fi
-}
-%
-% and a similar option for the left quote char vs. a grave accent.
-% Modern fonts display ASCII 0x60 as a grave accent, so some people like
-% the code environments to do likewise.
-%
-\def\codequoteleft{%
-  \expandafter\ifx\csname SETtxicodequotebacktick\endcsname\relax
-    \expandafter\ifx\csname SETcodequotebacktick\endcsname\relax
-      % [Knuth] pp. 380,381,391
-      % \relax disables Spanish ligatures ?` and !` of \tt font.
-      \relax`%
-    \else \char'22 \fi
-  \else \char'22 \fi
-}
-
-% Commands to set the quote options.
-% 
-\parseargdef\codequoteundirected{%
-  \def\temp{#1}%
-  \ifx\temp\onword
-    \expandafter\let\csname SETtxicodequoteundirected\endcsname
-      = t%
-  \else\ifx\temp\offword
-    \expandafter\let\csname SETtxicodequoteundirected\endcsname
-      = \relax
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @codequoteundirected value `\temp', must be on|off}%
-  \fi\fi
-}
-%
-\parseargdef\codequotebacktick{%
-  \def\temp{#1}%
-  \ifx\temp\onword
-    \expandafter\let\csname SETtxicodequotebacktick\endcsname
-      = t%
-  \else\ifx\temp\offword
-    \expandafter\let\csname SETtxicodequotebacktick\endcsname
-      = \relax
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @codequotebacktick value `\temp', must be on|off}%
-  \fi\fi
-}
-
-% [Knuth] pp. 380,381,391, disable Spanish ligatures ?` and !` of \tt font.
-\def\noligaturesquoteleft{\relax\lq}
-
-% Count depth in font-changes, for error checks
-\newcount\fontdepth \fontdepth=0
-
-% Font commands.
-
-% #1 is the font command (\sl or \it), #2 is the text to slant.
-% If we are in a monospaced environment, however, 1) always use \ttsl,
-% and 2) do not add an italic correction.
-\def\dosmartslant#1#2{%
-  \ifusingtt 
-    {{\ttsl #2}\let\next=\relax}%
-    {\def\next{{#1#2}\futurelet\next\smartitaliccorrection}}%
-  \next
-}
-\def\smartslanted{\dosmartslant\sl}
-\def\smartitalic{\dosmartslant\it}
-
-% Output an italic correction unless \next (presumed to be the following
-% character) is such as not to need one.
-\def\smartitaliccorrection{%
-  \ifx\next,%
-  \else\ifx\next-%
-  \else\ifx\next.%
-  \else\ptexslash
-  \fi\fi\fi
-  \aftersmartic
-}
-
-% Unconditional use \ttsl, and no ic.  @var is set to this for defuns.
-\def\ttslanted#1{{\ttsl #1}}
-
-% @cite is like \smartslanted except unconditionally use \sl.  We never want
-% ttsl for book titles, do we?
-\def\cite#1{{\sl #1}\futurelet\next\smartitaliccorrection}
-
-\def\aftersmartic{}
-\def\var#1{%
-  \let\saveaftersmartic = \aftersmartic
-  \def\aftersmartic{\null\let\aftersmartic=\saveaftersmartic}%
-  \smartslanted{#1}%
-}
-
-\let\i=\smartitalic
-\let\slanted=\smartslanted
-\let\dfn=\smartslanted
-\let\emph=\smartitalic
-
-% Explicit font changes: @r, @sc, undocumented @ii.
-\def\r#1{{\rm #1}}              % roman font
-\def\sc#1{{\smallcaps#1}}       % smallcaps font
-\def\ii#1{{\it #1}}             % italic font
-
-% @b, explicit bold.  Also @strong.
-\def\b#1{{\bf #1}}
-\let\strong=\b
-
-% @sansserif, explicit sans.
-\def\sansserif#1{{\sf #1}}
-
-% We can't just use \exhyphenpenalty, because that only has effect at
-% the end of a paragraph.  Restore normal hyphenation at the end of the
-% group within which \nohyphenation is presumably called.
-%
-\def\nohyphenation{\hyphenchar\font = -1  \aftergroup\restorehyphenation}
-\def\restorehyphenation{\hyphenchar\font = `- }
-
-% Set sfcode to normal for the chars that usually have another value.
-% Can't use plain's \frenchspacing because it uses the `\x notation, and
-% sometimes \x has an active definition that messes things up.
-%
-\catcode`@=11
-  \def\plainfrenchspacing{%
-    \sfcode\dotChar  =\@m \sfcode\questChar=\@m \sfcode\exclamChar=\@m
-    \sfcode\colonChar=\@m \sfcode\semiChar =\@m \sfcode\commaChar =\@m
-    \def\endofsentencespacefactor{1000}% for @. and friends
-  }
-  \def\plainnonfrenchspacing{%
-    \sfcode`\.3000\sfcode`\?3000\sfcode`\!3000
-    \sfcode`\:2000\sfcode`\;1500\sfcode`\,1250
-    \def\endofsentencespacefactor{3000}% for @. and friends
-  }
-\catcode`@=\other
-\def\endofsentencespacefactor{3000}% default
-
-% @t, explicit typewriter.
-\def\t#1{%
-  {\tt \rawbackslash \plainfrenchspacing #1}%
-  \null
-}
-
-% @samp.
-\def\samp#1{{\setupmarkupstyle{samp}\lq\tclose{#1}\rq\null}}
-
-% @indicateurl is \samp, that is, with quotes.
-\let\indicateurl=\samp
-
-% @code (and similar) prints in typewriter, but with spaces the same
-% size as normal in the surrounding text, without hyphenation, etc.
-% This is a subroutine for that.
-\def\tclose#1{%
-  {%
-    % Change normal interword space to be same as for the current font.
-    \spaceskip = \fontdimen2\font
-    %
-    % Switch to typewriter.
-    \tt
-    %
-    % But `\ ' produces the large typewriter interword space.
-    \def\ {{\spaceskip = 0pt{} }}%
-    %
-    % Turn off hyphenation.
-    \nohyphenation
-    %
-    \rawbackslash
-    \plainfrenchspacing
-    #1%
-  }%
-  \null % reset spacefactor to 1000
-}
-
-% We *must* turn on hyphenation at `-' and `_' in @code.
-% Otherwise, it is too hard to avoid overfull hboxes
-% in the Emacs manual, the Library manual, etc.
-%
-% Unfortunately, TeX uses one parameter (\hyphenchar) to control
-% both hyphenation at - and hyphenation within words.
-% We must therefore turn them both off (\tclose does that)
-% and arrange explicitly to hyphenate at a dash.
-%  -- rms.
-{
-  \catcode`\-=\active \catcode`\_=\active
-  \catcode`\'=\active \catcode`\`=\active
-  \global\let'=\rq \global\let`=\lq  % default definitions
-  %
-  \global\def\code{\begingroup
-    \setupmarkupstyle{code}%
-    % The following should really be moved into \setupmarkupstyle handlers.
-    \catcode\dashChar=\active  \catcode\underChar=\active
-    \ifallowcodebreaks
-     \let-\codedash
-     \let_\codeunder
-    \else
-     \let-\normaldash
-     \let_\realunder
-    \fi
-    \codex
-  }
-}
-
-\def\codex #1{\tclose{#1}\endgroup}
-
-\def\normaldash{-}
-\def\codedash{-\discretionary{}{}{}}
-\def\codeunder{%
-  % this is all so @math{@code{var_name}+1} can work.  In math mode, _
-  % is "active" (mathcode"8000) and \normalunderscore (or \char95, etc.)
-  % will therefore expand the active definition of _, which is us
-  % (inside @code that is), therefore an endless loop.
-  \ifusingtt{\ifmmode
-               \mathchar"075F % class 0=ordinary, family 7=ttfam, pos 0x5F=_.
-             \else\normalunderscore \fi
-             \discretionary{}{}{}}%
-            {\_}%
-}
-
-% An additional complication: the above will allow breaks after, e.g.,
-% each of the four underscores in __typeof__.  This is bad.
-% @allowcodebreaks provides a document-level way to turn breaking at -
-% and _ on and off.
-%
-\newif\ifallowcodebreaks  \allowcodebreakstrue
-
-\def\keywordtrue{true}
-\def\keywordfalse{false}
-
-\parseargdef\allowcodebreaks{%
-  \def\txiarg{#1}%
-  \ifx\txiarg\keywordtrue
-    \allowcodebreakstrue
-  \else\ifx\txiarg\keywordfalse
-    \allowcodebreaksfalse
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @allowcodebreaks option `\txiarg', must be true|false}%
-  \fi\fi
-}
-
-% For @command, @env, @file, @option quotes seem unnecessary,
-% so use \code rather than \samp.
-\let\command=\code
-\let\env=\code
-\let\file=\code
-\let\option=\code
-
-% @uref (abbreviation for `urlref') takes an optional (comma-separated)
-% second argument specifying the text to display and an optional third
-% arg as text to display instead of (rather than in addition to) the url
-% itself.  First (mandatory) arg is the url.
-% (This \urefnobreak definition isn't used now, leaving it for a while
-% for comparison.)
-\def\urefnobreak#1{\dourefnobreak #1,,,\finish}
-\def\dourefnobreak#1,#2,#3,#4\finish{\begingroup
-  \unsepspaces
-  \pdfurl{#1}%
-  \setbox0 = \hbox{\ignorespaces #3}%
-  \ifdim\wd0 > 0pt
-    \unhbox0 % third arg given, show only that
-  \else
-    \setbox0 = \hbox{\ignorespaces #2}%
-    \ifdim\wd0 > 0pt
-      \ifpdf
-        \unhbox0             % PDF: 2nd arg given, show only it
-      \else
-        \unhbox0\ (\code{#1})% DVI: 2nd arg given, show both it and url
-      \fi
-    \else
-      \code{#1}% only url given, so show it
-    \fi
-  \fi
-  \endlink
-\endgroup}
-
-% This \urefbreak definition is the active one.
-\def\urefbreak{\begingroup \urefcatcodes \dourefbreak}
-\let\uref=\urefbreak
-\def\dourefbreak#1{\urefbreakfinish #1,,,\finish}
-\def\urefbreakfinish#1,#2,#3,#4\finish{% doesn't work in @example
-  \unsepspaces
-  \pdfurl{#1}%
-  \setbox0 = \hbox{\ignorespaces #3}%
-  \ifdim\wd0 > 0pt
-    \unhbox0 % third arg given, show only that
-  \else
-    \setbox0 = \hbox{\ignorespaces #2}%
-    \ifdim\wd0 > 0pt
-      \ifpdf
-        \unhbox0             % PDF: 2nd arg given, show only it
-      \else
-        \unhbox0\ (\urefcode{#1})% DVI: 2nd arg given, show both it and url
-      \fi
-    \else
-      \urefcode{#1}% only url given, so show it
-    \fi
-  \fi
-  \endlink
-\endgroup}
-
-% Allow line breaks around only a few characters (only).
-\def\urefcatcodes{%
-  \catcode\ampChar=\active   \catcode\dotChar=\active
-  \catcode\hashChar=\active  \catcode\questChar=\active
-  \catcode\slashChar=\active
-}
-{
-  \urefcatcodes
-  %
-  \global\def\urefcode{\begingroup
-    \setupmarkupstyle{code}%
-    \urefcatcodes
-    \let&\urefcodeamp
-    \let.\urefcodedot
-    \let#\urefcodehash
-    \let?\urefcodequest
-    \let/\urefcodeslash
-    \codex
-  }
-  %
-  % By default, they are just regular characters.
-  \global\def&{\normalamp}
-  \global\def.{\normaldot}
-  \global\def#{\normalhash}
-  \global\def?{\normalquest}
-  \global\def/{\normalslash}
-}
-
-% we put a little stretch before and after the breakable chars, to help
-% line breaking of long url's.  The unequal skips make look better in
-% cmtt at least, especially for dots.
-\def\urefprestretch{\urefprebreak \hskip0pt plus.13em }
-\def\urefpoststretch{\urefpostbreak \hskip0pt plus.1em }
-%
-\def\urefcodeamp{\urefprestretch \&\urefpoststretch}
-\def\urefcodedot{\urefprestretch .\urefpoststretch}
-\def\urefcodehash{\urefprestretch \#\urefpoststretch}
-\def\urefcodequest{\urefprestretch ?\urefpoststretch}
-\def\urefcodeslash{\futurelet\next\urefcodeslashfinish}
-{
-  \catcode`\/=\active
-  \global\def\urefcodeslashfinish{%
-    \urefprestretch \slashChar
-    % Allow line break only after the final / in a sequence of
-    % slashes, to avoid line break between the slashes in http://.
-    \ifx\next/\else \urefpoststretch \fi
-  }
-}
-
-% One more complication: by default we'll break after the special
-% characters, but some people like to break before the special chars, so
-% allow that.  Also allow no breaking at all, for manual control.
-% 
-\parseargdef\urefbreakstyle{%
-  \def\txiarg{#1}%
-  \ifx\txiarg\wordnone
-    \def\urefprebreak{\nobreak}\def\urefpostbreak{\nobreak}
-  \else\ifx\txiarg\wordbefore
-    \def\urefprebreak{\allowbreak}\def\urefpostbreak{\nobreak}
-  \else\ifx\txiarg\wordafter
-    \def\urefprebreak{\nobreak}\def\urefpostbreak{\allowbreak}
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @urefbreakstyle setting `\txiarg'}%
-  \fi\fi\fi
-}
-\def\wordafter{after}
-\def\wordbefore{before}
-\def\wordnone{none}
-
-\urefbreakstyle after
-
-% @url synonym for @uref, since that's how everyone uses it.
-%
-\let\url=\uref
-
-% rms does not like angle brackets --karl, 17may97.
-% So now @email is just like @uref, unless we are pdf.
-%
-%\def\email#1{\angleleft{\tt #1}\angleright}
-\ifpdf
-  \def\email#1{\doemail#1,,\finish}
-  \def\doemail#1,#2,#3\finish{\begingroup
-    \unsepspaces
-    \pdfurl{mailto:#1}%
-    \setbox0 = \hbox{\ignorespaces #2}%
-    \ifdim\wd0>0pt\unhbox0\else\code{#1}\fi
-    \endlink
-  \endgroup}
-\else
-  \let\email=\uref
-\fi
-
-% @kbdinputstyle -- arg is `distinct' (@kbd uses slanted tty font always),
-%   `example' (@kbd uses ttsl only inside of @example and friends),
-%   or `code' (@kbd uses normal tty font always).
-\parseargdef\kbdinputstyle{%
-  \def\txiarg{#1}%
-  \ifx\txiarg\worddistinct
-    \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl}%
-  \else\ifx\txiarg\wordexample
-    \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\tt}%
-  \else\ifx\txiarg\wordcode
-    \gdef\kbdexamplefont{\tt}\gdef\kbdfont{\tt}%
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @kbdinputstyle setting `\txiarg'}%
-  \fi\fi\fi
-}
-\def\worddistinct{distinct}
-\def\wordexample{example}
-\def\wordcode{code}
-
-% Default is `distinct'.
-\kbdinputstyle distinct
-
-% @kbd is like @code, except that if the argument is just one @key command,
-% then @kbd has no effect.
-\def\kbd#1{{\def\look{#1}\expandafter\kbdsub\look??\par}}
-
-\def\xkey{\key}
-\def\kbdsub#1#2#3\par{%
-  \def\one{#1}\def\three{#3}\def\threex{??}%
-  \ifx\one\xkey\ifx\threex\three \key{#2}%
-  \else{\tclose{\kbdfont\setupmarkupstyle{kbd}\look}}\fi
-  \else{\tclose{\kbdfont\setupmarkupstyle{kbd}\look}}\fi
-}
-
-% definition of @key that produces a lozenge.  Doesn't adjust to text size.
-%\setfont\keyrm\rmshape{8}{1000}{OT1}
-%\font\keysy=cmsy9
-%\def\key#1{{\keyrm\textfont2=\keysy \leavevmode\hbox{%
-%  \raise0.4pt\hbox{\angleleft}\kern-.08em\vtop{%
-%    \vbox{\hrule\kern-0.4pt
-%     \hbox{\raise0.4pt\hbox{\vphantom{\angleleft}}#1}}%
-%    \kern-0.4pt\hrule}%
-%  \kern-.06em\raise0.4pt\hbox{\angleright}}}}
-
-% definition of @key with no lozenge.  If the current font is already
-% monospace, don't change it; that way, we respect @kbdinputstyle.  But
-% if it isn't monospace, then use \tt.
-%
-\def\key#1{{\setupmarkupstyle{key}%
-  \nohyphenation
-  \ifmonospace\else\tt\fi
-  #1}\null}
-
-% @clicksequence{File @click{} Open ...}
-\def\clicksequence#1{\begingroup #1\endgroup}
-
-% @clickstyle @arrow   (by default)
-\parseargdef\clickstyle{\def\click{#1}}
-\def\click{\arrow}
-
-% Typeset a dimension, e.g., `in' or `pt'.  The only reason for the
-% argument is to make the input look right: @dmn{pt} instead of @dmn{}pt.
-%
-\def\dmn#1{\thinspace #1}
-
-% @l was never documented to mean ``switch to the Lisp font'',
-% and it is not used as such in any manual I can find.  We need it for
-% Polish suppressed-l.  --karl, 22sep96.
-%\def\l#1{{\li #1}\null}
-
-% @acronym for "FBI", "NATO", and the like.
-% We print this one point size smaller, since it's intended for
-% all-uppercase.
-%
-\def\acronym#1{\doacronym #1,,\finish}
-\def\doacronym#1,#2,#3\finish{%
-  {\selectfonts\lsize #1}%
-  \def\temp{#2}%
-  \ifx\temp\empty \else
-    \space ({\unsepspaces \ignorespaces \temp \unskip})%
-  \fi
-  \null % reset \spacefactor=1000
-}
-
-% @abbr for "Comput. J." and the like.
-% No font change, but don't do end-of-sentence spacing.
-%
-\def\abbr#1{\doabbr #1,,\finish}
-\def\doabbr#1,#2,#3\finish{%
-  {\plainfrenchspacing #1}%
-  \def\temp{#2}%
-  \ifx\temp\empty \else
-    \space ({\unsepspaces \ignorespaces \temp \unskip})%
-  \fi
-  \null % reset \spacefactor=1000
-}
-
-% @asis just yields its argument.  Used with @table, for example.
-%
-\def\asis#1{#1}
-
-% @math outputs its argument in math mode.
-%
-% One complication: _ usually means subscripts, but it could also mean
-% an actual _ character, as in @math{@var{some_variable} + 1}.  So make
-% _ active, and distinguish by seeing if the current family is \slfam,
-% which is what @var uses.
-{
-  \catcode`\_ = \active
-  \gdef\mathunderscore{%
-    \catcode`\_=\active
-    \def_{\ifnum\fam=\slfam \_\else\sb\fi}%
-  }
-}
-% Another complication: we want \\ (and @\) to output a math (or tt) \.
-% FYI, plain.tex uses \\ as a temporary control sequence (for no
-% particular reason), but this is not advertised and we don't care.
-%
-% The \mathchar is class=0=ordinary, family=7=ttfam, position=5C=\.
-\def\mathbackslash{\ifnum\fam=\ttfam \mathchar"075C \else\backslash \fi}
-%
-\def\math{%
-  \tex
-  \mathunderscore
-  \let\\ = \mathbackslash
-  \mathactive
-  % make the texinfo accent commands work in math mode
-  \let\"=\ddot
-  \let\'=\acute
-  \let\==\bar
-  \let\^=\hat
-  \let\`=\grave
-  \let\u=\breve
-  \let\v=\check
-  \let\~=\tilde
-  \let\dotaccent=\dot
-  $\finishmath
-}
-\def\finishmath#1{#1$\endgroup}  % Close the group opened by \tex.
-
-% Some active characters (such as <) are spaced differently in math.
-% We have to reset their definitions in case the @math was an argument
-% to a command which sets the catcodes (such as @item or @section).
-%
-{
-  \catcode`^ = \active
-  \catcode`< = \active
-  \catcode`> = \active
-  \catcode`+ = \active
-  \catcode`' = \active
-  \gdef\mathactive{%
-    \let^ = \ptexhat
-    \let< = \ptexless
-    \let> = \ptexgtr
-    \let+ = \ptexplus
-    \let' = \ptexquoteright
-  }
-}
-
-% ctrl is no longer a Texinfo command, but leave this definition for fun.
-\def\ctrl #1{{\tt \rawbackslash \hat}#1}
-
-% @inlinefmt{FMTNAME,PROCESSED-TEXT} and @inlineraw{FMTNAME,RAW-TEXT}.
-% Ignore unless FMTNAME == tex; then it is like @iftex and @tex,
-% except specified as a normal braced arg, so no newlines to worry about.
-% 
-\def\outfmtnametex{tex}
-%
-\long\def\inlinefmt#1{\doinlinefmt #1,\finish}
-\long\def\doinlinefmt#1,#2,\finish{%
-  \def\inlinefmtname{#1}%
-  \ifx\inlinefmtname\outfmtnametex \ignorespaces #2\fi
-}
-% For raw, must switch into @tex before parsing the argument, to avoid
-% setting catcodes prematurely.  Doing it this way means that, for
-% example, @inlineraw{html, foo{bar} gets a parse error instead of being
-% ignored.  But this isn't important because if people want a literal
-% *right* brace they would have to use a command anyway, so they may as
-% well use a command to get a left brace too.  We could re-use the
-% delimiter character idea from \verb, but it seems like overkill.
-% 
-\long\def\inlineraw{\tex \doinlineraw}
-\long\def\doinlineraw#1{\doinlinerawtwo #1,\finish}
-\def\doinlinerawtwo#1,#2,\finish{%
-  \def\inlinerawname{#1}%
-  \ifx\inlinerawname\outfmtnametex \ignorespaces #2\fi
-  \endgroup % close group opened by \tex.
-}
-
-
-\message{glyphs,}
-% and logos.
-
-% @@ prints an @, as does @atchar{}.
-\def\@{\char64 }
-\let\atchar=\@
-
-% @{ @} @lbracechar{} @rbracechar{} all generate brace characters.
-% Unless we're in typewriter, use \ecfont because the CM text fonts do
-% not have braces, and we don't want to switch into math.
-\def\mylbrace{{\ifmonospace\else\ecfont\fi \char123}}
-\def\myrbrace{{\ifmonospace\else\ecfont\fi \char125}}
-\let\{=\mylbrace \let\lbracechar=\{
-\let\}=\myrbrace \let\rbracechar=\}
-\begingroup
-  % Definitions to produce \{ and \} commands for indices,
-  % and @{ and @} for the aux/toc files.
-  \catcode`\{ = \other \catcode`\} = \other
-  \catcode`\[ = 1 \catcode`\] = 2
-  \catcode`\! = 0 \catcode`\\ = \other
-  !gdef!lbracecmd[\{]%
-  !gdef!rbracecmd[\}]%
-  !gdef!lbraceatcmd[@{]%
-  !gdef!rbraceatcmd[@}]%
-!endgroup
-
-% @comma{} to avoid , parsing problems.
-\let\comma = ,
-
-% Accents: @, @dotaccent @ringaccent @ubaraccent @udotaccent
-% Others are defined by plain TeX: @` @' @" @^ @~ @= @u @v @H.
-\let\, = \ptexc
-\let\dotaccent = \ptexdot
-\def\ringaccent#1{{\accent23 #1}}
-\let\tieaccent = \ptext
-\let\ubaraccent = \ptexb
-\let\udotaccent = \d
-
-% Other special characters: @questiondown @exclamdown @ordf @ordm
-% Plain TeX defines: @AA @AE @O @OE @L (plus lowercase versions) @ss.
-\def\questiondown{?`}
-\def\exclamdown{!`}
-\def\ordf{\leavevmode\raise1ex\hbox{\selectfonts\lllsize \underbar{a}}}
-\def\ordm{\leavevmode\raise1ex\hbox{\selectfonts\lllsize \underbar{o}}}
-
-% Dotless i and dotless j, used for accents.
-\def\imacro{i}
-\def\jmacro{j}
-\def\dotless#1{%
-  \def\temp{#1}%
-  \ifx\temp\imacro \ifmmode\imath \else\ptexi \fi
-  \else\ifx\temp\jmacro \ifmmode\jmath \else\j \fi
-  \else \errmessage{@dotless can be used only with i or j}%
-  \fi\fi
-}
-
-% The \TeX{} logo, as in plain, but resetting the spacing so that a
-% period following counts as ending a sentence.  (Idea found in latex.)
-%
-\edef\TeX{\TeX \spacefactor=1000 }
-
-% @LaTeX{} logo.  Not quite the same results as the definition in
-% latex.ltx, since we use a different font for the raised A; it's most
-% convenient for us to use an explicitly smaller font, rather than using
-% the \scriptstyle font (since we don't reset \scriptstyle and
-% \scriptscriptstyle).
-%
-\def\LaTeX{%
-  L\kern-.36em
-  {\setbox0=\hbox{T}%
-   \vbox to \ht0{\hbox{%
-     \ifx\textnominalsize\xwordpt
-       % for 10pt running text, \lllsize (8pt) is too small for the A in LaTeX.
-       % Revert to plain's \scriptsize, which is 7pt.
-       \count255=\the\fam $\fam\count255 \scriptstyle A$%
-     \else
-       % For 11pt, we can use our lllsize.
-       \selectfonts\lllsize A%
-     \fi
-     }%
-     \vss
-  }}%
-  \kern-.15em
-  \TeX
-}
-
-% Some math mode symbols.
-\def\bullet{$\ptexbullet$}
-\def\geq{\ifmmode \ge\else $\ge$\fi}
-\def\leq{\ifmmode \le\else $\le$\fi}
-\def\minus{\ifmmode -\else $-$\fi}
-
-% @dots{} outputs an ellipsis using the current font.
-% We do .5em per period so that it has the same spacing in the cm
-% typewriter fonts as three actual period characters; on the other hand,
-% in other typewriter fonts three periods are wider than 1.5em.  So do
-% whichever is larger.
-%
-\def\dots{%
-  \leavevmode
-  \setbox0=\hbox{...}% get width of three periods
-  \ifdim\wd0 > 1.5em
-    \dimen0 = \wd0
-  \else
-    \dimen0 = 1.5em
-  \fi
-  \hbox to \dimen0{%
-    \hskip 0pt plus.25fil
-    .\hskip 0pt plus1fil
-    .\hskip 0pt plus1fil
-    .\hskip 0pt plus.5fil
-  }%
-}
-
-% @enddots{} is an end-of-sentence ellipsis.
-%
-\def\enddots{%
-  \dots
-  \spacefactor=\endofsentencespacefactor
-}
-
-% @point{}, @result{}, @expansion{}, @print{}, @equiv{}.
-%
-% Since these characters are used in examples, they should be an even number of
-% \tt widths. Each \tt character is 1en, so two makes it 1em.
-%
-\def\point{$\star$}
-\def\arrow{\leavevmode\raise.05ex\hbox to 1em{\hfil$\rightarrow$\hfil}}
-\def\result{\leavevmode\raise.05ex\hbox to 1em{\hfil$\Rightarrow$\hfil}}
-\def\expansion{\leavevmode\hbox to 1em{\hfil$\mapsto$\hfil}}
-\def\print{\leavevmode\lower.1ex\hbox to 1em{\hfil$\dashv$\hfil}}
-\def\equiv{\leavevmode\hbox to 1em{\hfil$\ptexequiv$\hfil}}
-
-% The @error{} command.
-% Adapted from the TeXbook's \boxit.
-%
-\newbox\errorbox
-%
-{\tentt \global\dimen0 = 3em}% Width of the box.
-\dimen2 = .55pt % Thickness of rules
-% The text. (`r' is open on the right, `e' somewhat less so on the left.)
-\setbox0 = \hbox{\kern-.75pt \reducedsf \putworderror\kern-1.5pt}
-%
-\setbox\errorbox=\hbox to \dimen0{\hfil
-   \hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right.
-   \advance\hsize by -2\dimen2 % Rules.
-   \vbox{%
-      \hrule height\dimen2
-      \hbox{\vrule width\dimen2 \kern3pt          % Space to left of text.
-         \vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below.
-         \kern3pt\vrule width\dimen2}% Space to right.
-      \hrule height\dimen2}
-    \hfil}
-%
-\def\error{\leavevmode\lower.7ex\copy\errorbox}
-
-% @pounds{} is a sterling sign, which Knuth put in the CM italic font.
-%
-\def\pounds{{\it\$}}
-
-% @euro{} comes from a separate font, depending on the current style.
-% We use the free feym* fonts from the eurosym package by Henrik
-% Theiling, which support regular, slanted, bold and bold slanted (and
-% "outlined" (blackboard board, sort of) versions, which we don't need).
-% It is available from http://www.ctan.org/tex-archive/fonts/eurosym.
-%
-% Although only regular is the truly official Euro symbol, we ignore
-% that.  The Euro is designed to be slightly taller than the regular
-% font height.
-%
-% feymr - regular
-% feymo - slanted
-% feybr - bold
-% feybo - bold slanted
-%
-% There is no good (free) typewriter version, to my knowledge.
-% A feymr10 euro is ~7.3pt wide, while a normal cmtt10 char is ~5.25pt wide.
-% Hmm.
-%
-% Also doesn't work in math.  Do we need to do math with euro symbols?
-% Hope not.
-%
-%
-\def\euro{{\eurofont e}}
-\def\eurofont{%
-  % We set the font at each command, rather than predefining it in
-  % \textfonts and the other font-switching commands, so that
-  % installations which never need the symbol don't have to have the
-  % font installed.
-  %
-  % There is only one designed size (nominal 10pt), so we always scale
-  % that to the current nominal size.
-  %
-  % By the way, simply using "at 1em" works for cmr10 and the like, but
-  % does not work for cmbx10 and other extended/shrunken fonts.
-  %
-  \def\eurosize{\csname\curfontsize nominalsize\endcsname}%
-  %
-  \ifx\curfontstyle\bfstylename
-    % bold:
-    \font\thiseurofont = \ifusingit{feybo10}{feybr10} at \eurosize
-  \else
-    % regular:
-    \font\thiseurofont = \ifusingit{feymo10}{feymr10} at \eurosize
-  \fi
-  \thiseurofont
-}
-
-% Glyphs from the EC fonts.  We don't use \let for the aliases, because
-% sometimes we redefine the original macro, and the alias should reflect
-% the redefinition.
-%
-% Use LaTeX names for the Icelandic letters.
-\def\DH{{\ecfont \char"D0}} % Eth
-\def\dh{{\ecfont \char"F0}} % eth
-\def\TH{{\ecfont \char"DE}} % Thorn
-\def\th{{\ecfont \char"FE}} % thorn
-%
-\def\guillemetleft{{\ecfont \char"13}}
-\def\guillemotleft{\guillemetleft}
-\def\guillemetright{{\ecfont \char"14}}
-\def\guillemotright{\guillemetright}
-\def\guilsinglleft{{\ecfont \char"0E}}
-\def\guilsinglright{{\ecfont \char"0F}}
-\def\quotedblbase{{\ecfont \char"12}}
-\def\quotesinglbase{{\ecfont \char"0D}}
-%
-% This positioning is not perfect (see the ogonek LaTeX package), but
-% we have the precomposed glyphs for the most common cases.  We put the
-% tests to use those glyphs in the single \ogonek macro so we have fewer
-% dummy definitions to worry about for index entries, etc.
-%
-% ogonek is also used with other letters in Lithuanian (IOU), but using
-% the precomposed glyphs for those is not so easy since they aren't in
-% the same EC font.
-\def\ogonek#1{{%
-  \def\temp{#1}%
-  \ifx\temp\macrocharA\Aogonek
-  \else\ifx\temp\macrochara\aogonek
-  \else\ifx\temp\macrocharE\Eogonek
-  \else\ifx\temp\macrochare\eogonek
-  \else
-    \ecfont \setbox0=\hbox{#1}%
-    \ifdim\ht0=1ex\accent"0C #1%
-    \else\ooalign{\unhbox0\crcr\hidewidth\char"0C \hidewidth}%
-    \fi
-  \fi\fi\fi\fi
-  }%
-}
-\def\Aogonek{{\ecfont \char"81}}\def\macrocharA{A}
-\def\aogonek{{\ecfont \char"A1}}\def\macrochara{a}
-\def\Eogonek{{\ecfont \char"86}}\def\macrocharE{E}
-\def\eogonek{{\ecfont \char"A6}}\def\macrochare{e}
-%
-% Use the ec* fonts (cm-super in outline format) for non-CM glyphs.
-\def\ecfont{%
-  % We can't distinguish serif/sans and italic/slanted, but this
-  % is used for crude hacks anyway (like adding French and German
-  % quotes to documents typeset with CM, where we lose kerning), so
-  % hopefully nobody will notice/care.
-  \edef\ecsize{\csname\curfontsize ecsize\endcsname}%
-  \edef\nominalsize{\csname\curfontsize nominalsize\endcsname}%
-  \ifmonospace
-    % typewriter:
-    \font\thisecfont = ectt\ecsize \space at \nominalsize
-  \else
-    \ifx\curfontstyle\bfstylename
-      % bold:
-      \font\thisecfont = ecb\ifusingit{i}{x}\ecsize \space at \nominalsize
-    \else
-      % regular:
-      \font\thisecfont = ec\ifusingit{ti}{rm}\ecsize \space at \nominalsize
-    \fi
-  \fi
-  \thisecfont
-}
-
-% @registeredsymbol - R in a circle.  The font for the R should really
-% be smaller yet, but lllsize is the best we can do for now.
-% Adapted from the plain.tex definition of \copyright.
-%
-\def\registeredsymbol{%
-  $^{{\ooalign{\hfil\raise.07ex\hbox{\selectfonts\lllsize R}%
-               \hfil\crcr\Orb}}%
-    }$%
-}
-
-% @textdegree - the normal degrees sign.
-%
-\def\textdegree{$^\circ$}
-
-% Laurent Siebenmann reports \Orb undefined with:
-%  Textures 1.7.7 (preloaded format=plain 93.10.14)  (68K)  16 APR 2004 02:38
-% so we'll define it if necessary.
-%
-\ifx\Orb\thisisundefined
-\def\Orb{\mathhexbox20D}
-\fi
-
-% Quotes.
-\chardef\quotedblleft="5C
-\chardef\quotedblright=`\"
-\chardef\quoteleft=`\`
-\chardef\quoteright=`\'
-
-
-\message{page headings,}
-
-\newskip\titlepagetopglue \titlepagetopglue = 1.5in
-\newskip\titlepagebottomglue \titlepagebottomglue = 2pc
-
-% First the title page.  Must do @settitle before @titlepage.
-\newif\ifseenauthor
-\newif\iffinishedtitlepage
-
-% Do an implicit @contents or @shortcontents after @end titlepage if the
-% user says @setcontentsaftertitlepage or @setshortcontentsaftertitlepage.
-%
-\newif\ifsetcontentsaftertitlepage
- \let\setcontentsaftertitlepage = \setcontentsaftertitlepagetrue
-\newif\ifsetshortcontentsaftertitlepage
- \let\setshortcontentsaftertitlepage = \setshortcontentsaftertitlepagetrue
-
-\parseargdef\shorttitlepage{%
-  \begingroup \hbox{}\vskip 1.5in \chaprm \centerline{#1}%
-  \endgroup\page\hbox{}\page}
-
-\envdef\titlepage{%
-  % Open one extra group, as we want to close it in the middle of \Etitlepage.
-  \begingroup
-    \parindent=0pt \textfonts
-    % Leave some space at the very top of the page.
-    \vglue\titlepagetopglue
-    % No rule at page bottom unless we print one at the top with @title.
-    \finishedtitlepagetrue
-    %
-    % Most title ``pages'' are actually two pages long, with space
-    % at the top of the second.  We don't want the ragged left on the second.
-    \let\oldpage = \page
-    \def\page{%
-      \iffinishedtitlepage\else
-	 \finishtitlepage
-      \fi
-      \let\page = \oldpage
-      \page
-      \null
-    }%
-}
-
-\def\Etitlepage{%
-    \iffinishedtitlepage\else
-	\finishtitlepage
-    \fi
-    % It is important to do the page break before ending the group,
-    % because the headline and footline are only empty inside the group.
-    % If we use the new definition of \page, we always get a blank page
-    % after the title page, which we certainly don't want.
-    \oldpage
-  \endgroup
-  %
-  % Need this before the \...aftertitlepage checks so that if they are
-  % in effect the toc pages will come out with page numbers.
-  \HEADINGSon
-  %
-  % If they want short, they certainly want long too.
-  \ifsetshortcontentsaftertitlepage
-    \shortcontents
-    \contents
-    \global\let\shortcontents = \relax
-    \global\let\contents = \relax
-  \fi
-  %
-  \ifsetcontentsaftertitlepage
-    \contents
-    \global\let\contents = \relax
-    \global\let\shortcontents = \relax
-  \fi
-}
-
-\def\finishtitlepage{%
-  \vskip4pt \hrule height 2pt width \hsize
-  \vskip\titlepagebottomglue
-  \finishedtitlepagetrue
-}
-
-% Settings used for typesetting titles: no hyphenation, no indentation,
-% don't worry much about spacing, ragged right.  This should be used
-% inside a \vbox, and fonts need to be set appropriately first.  Because
-% it is always used for titles, nothing else, we call \rmisbold.  \par
-% should be specified before the end of the \vbox, since a vbox is a group.
-% 
-\def\raggedtitlesettings{%
-  \rmisbold
-  \hyphenpenalty=10000
-  \parindent=0pt
-  \tolerance=5000
-  \ptexraggedright
-}
-
-% Macros to be used within @titlepage:
-
-\let\subtitlerm=\tenrm
-\def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines}
-
-\parseargdef\title{%
-  \checkenv\titlepage
-  \vbox{\titlefonts \raggedtitlesettings #1\par}%
-  % print a rule at the page bottom also.
-  \finishedtitlepagefalse
-  \vskip4pt \hrule height 4pt width \hsize \vskip4pt
-}
-
-\parseargdef\subtitle{%
-  \checkenv\titlepage
-  {\subtitlefont \rightline{#1}}%
-}
-
-% @author should come last, but may come many times.
-% It can also be used inside @quotation.
-%
-\parseargdef\author{%
-  \def\temp{\quotation}%
-  \ifx\thisenv\temp
-    \def\quotationauthor{#1}% printed in \Equotation.
-  \else
-    \checkenv\titlepage
-    \ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi
-    {\secfonts\rmisbold \leftline{#1}}%
-  \fi
-}
-
-
-% Set up page headings and footings.
-
-\let\thispage=\folio
-
-\newtoks\evenheadline    % headline on even pages
-\newtoks\oddheadline     % headline on odd pages
-\newtoks\evenfootline    % footline on even pages
-\newtoks\oddfootline     % footline on odd pages
-
-% Now make TeX use those variables
-\headline={{\textfonts\rm \ifodd\pageno \the\oddheadline
-                            \else \the\evenheadline \fi}}
-\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline
-                            \else \the\evenfootline \fi}\HEADINGShook}
-\let\HEADINGShook=\relax
-
-% Commands to set those variables.
-% For example, this is what  @headings on  does
-% @evenheading @thistitle|@thispage|@thischapter
-% @oddheading @thischapter|@thispage|@thistitle
-% @evenfooting @thisfile||
-% @oddfooting ||@thisfile
-
-
-\def\evenheading{\parsearg\evenheadingxxx}
-\def\evenheadingxxx #1{\evenheadingyyy #1\|\|\|\|\finish}
-\def\evenheadingyyy #1\|#2\|#3\|#4\finish{%
-\global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
-
-\def\oddheading{\parsearg\oddheadingxxx}
-\def\oddheadingxxx #1{\oddheadingyyy #1\|\|\|\|\finish}
-\def\oddheadingyyy #1\|#2\|#3\|#4\finish{%
-\global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
-
-\parseargdef\everyheading{\oddheadingxxx{#1}\evenheadingxxx{#1}}%
-
-\def\evenfooting{\parsearg\evenfootingxxx}
-\def\evenfootingxxx #1{\evenfootingyyy #1\|\|\|\|\finish}
-\def\evenfootingyyy #1\|#2\|#3\|#4\finish{%
-\global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
-
-\def\oddfooting{\parsearg\oddfootingxxx}
-\def\oddfootingxxx #1{\oddfootingyyy #1\|\|\|\|\finish}
-\def\oddfootingyyy #1\|#2\|#3\|#4\finish{%
-  \global\oddfootline = {\rlap{\centerline{#2}}\line{#1\hfil#3}}%
-  %
-  % Leave some space for the footline.  Hopefully ok to assume
-  % @evenfooting will not be used by itself.
-  \global\advance\pageheight by -12pt
-  \global\advance\vsize by -12pt
-}
-
-\parseargdef\everyfooting{\oddfootingxxx{#1}\evenfootingxxx{#1}}
-
-% @evenheadingmarks top     \thischapter <- chapter at the top of a page
-% @evenheadingmarks bottom  \thischapter <- chapter at the bottom of a page
-%
-% The same set of arguments for:
-%
-% @oddheadingmarks
-% @evenfootingmarks
-% @oddfootingmarks
-% @everyheadingmarks
-% @everyfootingmarks
-
-\def\evenheadingmarks{\headingmarks{even}{heading}}
-\def\oddheadingmarks{\headingmarks{odd}{heading}}
-\def\evenfootingmarks{\headingmarks{even}{footing}}
-\def\oddfootingmarks{\headingmarks{odd}{footing}}
-\def\everyheadingmarks#1 {\headingmarks{even}{heading}{#1}
-                          \headingmarks{odd}{heading}{#1} }
-\def\everyfootingmarks#1 {\headingmarks{even}{footing}{#1}
-                          \headingmarks{odd}{footing}{#1} }
-% #1 = even/odd, #2 = heading/footing, #3 = top/bottom.
-\def\headingmarks#1#2#3 {%
-  \expandafter\let\expandafter\temp \csname get#3headingmarks\endcsname
-  \global\expandafter\let\csname get#1#2marks\endcsname \temp
-}
-
-\everyheadingmarks bottom
-\everyfootingmarks bottom
-
-% @headings double      turns headings on for double-sided printing.
-% @headings single      turns headings on for single-sided printing.
-% @headings off         turns them off.
-% @headings on          same as @headings double, retained for compatibility.
-% @headings after       turns on double-sided headings after this page.
-% @headings doubleafter turns on double-sided headings after this page.
-% @headings singleafter turns on single-sided headings after this page.
-% By default, they are off at the start of a document,
-% and turned `on' after @end titlepage.
-
-\def\headings #1 {\csname HEADINGS#1\endcsname}
-
-\def\headingsoff{% non-global headings elimination
-  \evenheadline={\hfil}\evenfootline={\hfil}%
-   \oddheadline={\hfil}\oddfootline={\hfil}%
-}
-
-\def\HEADINGSoff{{\globaldefs=1 \headingsoff}} % global setting
-\HEADINGSoff  % it's the default
-
-% When we turn headings on, set the page number to 1.
-% For double-sided printing, put current file name in lower left corner,
-% chapter name on inside top of right hand pages, document
-% title on inside top of left hand pages, and page numbers on outside top
-% edge of all pages.
-\def\HEADINGSdouble{%
-\global\pageno=1
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\folio\hfil\thistitle}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chapoddpage
-}
-\let\contentsalignmacro = \chappager
-
-% For single-sided printing, chapter title goes across top left of page,
-% page number on top right.
-\def\HEADINGSsingle{%
-\global\pageno=1
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\thischapter\hfil\folio}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chappager
-}
-\def\HEADINGSon{\HEADINGSdouble}
-
-\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex}
-\let\HEADINGSdoubleafter=\HEADINGSafter
-\def\HEADINGSdoublex{%
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\folio\hfil\thistitle}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chapoddpage
-}
-
-\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex}
-\def\HEADINGSsinglex{%
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\thischapter\hfil\folio}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chappager
-}
-
-% Subroutines used in generating headings
-% This produces Day Month Year style of output.
-% Only define if not already defined, in case a txi-??.tex file has set
-% up a different format (e.g., txi-cs.tex does this).
-\ifx\today\thisisundefined
-\def\today{%
-  \number\day\space
-  \ifcase\month
-  \or\putwordMJan\or\putwordMFeb\or\putwordMMar\or\putwordMApr
-  \or\putwordMMay\or\putwordMJun\or\putwordMJul\or\putwordMAug
-  \or\putwordMSep\or\putwordMOct\or\putwordMNov\or\putwordMDec
-  \fi
-  \space\number\year}
-\fi
-
-% @settitle line...  specifies the title of the document, for headings.
-% It generates no output of its own.
-\def\thistitle{\putwordNoTitle}
-\def\settitle{\parsearg{\gdef\thistitle}}
-
-
-\message{tables,}
-% Tables -- @table, @ftable, @vtable, @item(x).
-
-% default indentation of table text
-\newdimen\tableindent \tableindent=.8in
-% default indentation of @itemize and @enumerate text
-\newdimen\itemindent  \itemindent=.3in
-% margin between end of table item and start of table text.
-\newdimen\itemmargin  \itemmargin=.1in
-
-% used internally for \itemindent minus \itemmargin
-\newdimen\itemmax
-
-% Note @table, @ftable, and @vtable define @item, @itemx, etc., with
-% these defs.
-% They also define \itemindex
-% to index the item name in whatever manner is desired (perhaps none).
-
-\newif\ifitemxneedsnegativevskip
-
-\def\itemxpar{\par\ifitemxneedsnegativevskip\nobreak\vskip-\parskip\nobreak\fi}
-
-\def\internalBitem{\smallbreak \parsearg\itemzzz}
-\def\internalBitemx{\itemxpar \parsearg\itemzzz}
-
-\def\itemzzz #1{\begingroup %
-  \advance\hsize by -\rightskip
-  \advance\hsize by -\tableindent
-  \setbox0=\hbox{\itemindicate{#1}}%
-  \itemindex{#1}%
-  \nobreak % This prevents a break before @itemx.
-  %
-  % If the item text does not fit in the space we have, put it on a line
-  % by itself, and do not allow a page break either before or after that
-  % line.  We do not start a paragraph here because then if the next
-  % command is, e.g., @kindex, the whatsit would get put into the
-  % horizontal list on a line by itself, resulting in extra blank space.
-  \ifdim \wd0>\itemmax
-    %
-    % Make this a paragraph so we get the \parskip glue and wrapping,
-    % but leave it ragged-right.
-    \begingroup
-      \advance\leftskip by-\tableindent
-      \advance\hsize by\tableindent
-      \advance\rightskip by0pt plus1fil\relax
-      \leavevmode\unhbox0\par
-    \endgroup
-    %
-    % We're going to be starting a paragraph, but we don't want the
-    % \parskip glue -- logically it's part of the @item we just started.
-    \nobreak \vskip-\parskip
-    %
-    % Stop a page break at the \parskip glue coming up.  However, if
-    % what follows is an environment such as @example, there will be no
-    % \parskip glue; then the negative vskip we just inserted would
-    % cause the example and the item to crash together.  So we use this
-    % bizarre value of 10001 as a signal to \aboveenvbreak to insert
-    % \parskip glue after all.  Section titles are handled this way also.
-    %
-    \penalty 10001
-    \endgroup
-    \itemxneedsnegativevskipfalse
-  \else
-    % The item text fits into the space.  Start a paragraph, so that the
-    % following text (if any) will end up on the same line.
-    \noindent
-    % Do this with kerns and \unhbox so that if there is a footnote in
-    % the item text, it can migrate to the main vertical list and
-    % eventually be printed.
-    \nobreak\kern-\tableindent
-    \dimen0 = \itemmax  \advance\dimen0 by \itemmargin \advance\dimen0 by -\wd0
-    \unhbox0
-    \nobreak\kern\dimen0
-    \endgroup
-    \itemxneedsnegativevskiptrue
-  \fi
-}
-
-\def\item{\errmessage{@item while not in a list environment}}
-\def\itemx{\errmessage{@itemx while not in a list environment}}
-
-% @table, @ftable, @vtable.
-\envdef\table{%
-  \let\itemindex\gobble
-  \tablecheck{table}%
-}
-\envdef\ftable{%
-  \def\itemindex ##1{\doind {fn}{\code{##1}}}%
-  \tablecheck{ftable}%
-}
-\envdef\vtable{%
-  \def\itemindex ##1{\doind {vr}{\code{##1}}}%
-  \tablecheck{vtable}%
-}
-\def\tablecheck#1{%
-  \ifnum \the\catcode`\^^M=\active
-    \endgroup
-    \errmessage{This command won't work in this context; perhaps the problem is
-      that we are \inenvironment\thisenv}%
-    \def\next{\doignore{#1}}%
-  \else
-    \let\next\tablex
-  \fi
-  \next
-}
-\def\tablex#1{%
-  \def\itemindicate{#1}%
-  \parsearg\tabley
-}
-\def\tabley#1{%
-  {%
-    \makevalueexpandable
-    \edef\temp{\noexpand\tablez #1\space\space\space}%
-    \expandafter
-  }\temp \endtablez
-}
-\def\tablez #1 #2 #3 #4\endtablez{%
-  \aboveenvbreak
-  \ifnum 0#1>0 \advance \leftskip by #1\mil \fi
-  \ifnum 0#2>0 \tableindent=#2\mil \fi
-  \ifnum 0#3>0 \advance \rightskip by #3\mil \fi
-  \itemmax=\tableindent
-  \advance \itemmax by -\itemmargin
-  \advance \leftskip by \tableindent
-  \exdentamount=\tableindent
-  \parindent = 0pt
-  \parskip = \smallskipamount
-  \ifdim \parskip=0pt \parskip=2pt \fi
-  \let\item = \internalBitem
-  \let\itemx = \internalBitemx
-}
-\def\Etable{\endgraf\afterenvbreak}
-\let\Eftable\Etable
-\let\Evtable\Etable
-\let\Eitemize\Etable
-\let\Eenumerate\Etable
-
-% This is the counter used by @enumerate, which is really @itemize
-
-\newcount \itemno
-
-\envdef\itemize{\parsearg\doitemize}
-
-\def\doitemize#1{%
-  \aboveenvbreak
-  \itemmax=\itemindent
-  \advance\itemmax by -\itemmargin
-  \advance\leftskip by \itemindent
-  \exdentamount=\itemindent
-  \parindent=0pt
-  \parskip=\smallskipamount
-  \ifdim\parskip=0pt \parskip=2pt \fi
-  %
-  % Try typesetting the item mark that if the document erroneously says
-  % something like @itemize @samp (intending @table), there's an error
-  % right away at the @itemize.  It's not the best error message in the
-  % world, but it's better than leaving it to the @item.  This means if
-  % the user wants an empty mark, they have to say @w{} not just @w.
-  \def\itemcontents{#1}%
-  \setbox0 = \hbox{\itemcontents}%
-  %
-  % @itemize with no arg is equivalent to @itemize @bullet.
-  \ifx\itemcontents\empty\def\itemcontents{\bullet}\fi
-  %
-  \let\item=\itemizeitem
-}
-
-% Definition of @item while inside @itemize and @enumerate.
-%
-\def\itemizeitem{%
-  \advance\itemno by 1  % for enumerations
-  {\let\par=\endgraf \smallbreak}% reasonable place to break
-  {%
-   % If the document has an @itemize directly after a section title, a
-   % \nobreak will be last on the list, and \sectionheading will have
-   % done a \vskip-\parskip.  In that case, we don't want to zero
-   % parskip, or the item text will crash with the heading.  On the
-   % other hand, when there is normal text preceding the item (as there
-   % usually is), we do want to zero parskip, or there would be too much
-   % space.  In that case, we won't have a \nobreak before.  At least
-   % that's the theory.
-   \ifnum\lastpenalty<10000 \parskip=0in \fi
-   \noindent
-   \hbox to 0pt{\hss \itemcontents \kern\itemmargin}%
-   %
-   \vadjust{\penalty 1200}}% not good to break after first line of item.
-  \flushcr
-}
-
-% \splitoff TOKENS\endmark defines \first to be the first token in
-% TOKENS, and \rest to be the remainder.
-%
-\def\splitoff#1#2\endmark{\def\first{#1}\def\rest{#2}}%
-
-% Allow an optional argument of an uppercase letter, lowercase letter,
-% or number, to specify the first label in the enumerated list.  No
-% argument is the same as `1'.
-%
-\envparseargdef\enumerate{\enumeratey #1  \endenumeratey}
-\def\enumeratey #1 #2\endenumeratey{%
-  % If we were given no argument, pretend we were given `1'.
-  \def\thearg{#1}%
-  \ifx\thearg\empty \def\thearg{1}\fi
-  %
-  % Detect if the argument is a single token.  If so, it might be a
-  % letter.  Otherwise, the only valid thing it can be is a number.
-  % (We will always have one token, because of the test we just made.
-  % This is a good thing, since \splitoff doesn't work given nothing at
-  % all -- the first parameter is undelimited.)
-  \expandafter\splitoff\thearg\endmark
-  \ifx\rest\empty
-    % Only one token in the argument.  It could still be anything.
-    % A ``lowercase letter'' is one whose \lccode is nonzero.
-    % An ``uppercase letter'' is one whose \lccode is both nonzero, and
-    %   not equal to itself.
-    % Otherwise, we assume it's a number.
-    %
-    % We need the \relax at the end of the \ifnum lines to stop TeX from
-    % continuing to look for a <number>.
-    %
-    \ifnum\lccode\expandafter`\thearg=0\relax
-      \numericenumerate % a number (we hope)
-    \else
-      % It's a letter.
-      \ifnum\lccode\expandafter`\thearg=\expandafter`\thearg\relax
-        \lowercaseenumerate % lowercase letter
-      \else
-        \uppercaseenumerate % uppercase letter
-      \fi
-    \fi
-  \else
-    % Multiple tokens in the argument.  We hope it's a number.
-    \numericenumerate
-  \fi
-}
-
-% An @enumerate whose labels are integers.  The starting integer is
-% given in \thearg.
-%
-\def\numericenumerate{%
-  \itemno = \thearg
-  \startenumeration{\the\itemno}%
-}
-
-% The starting (lowercase) letter is in \thearg.
-\def\lowercaseenumerate{%
-  \itemno = \expandafter`\thearg
-  \startenumeration{%
-    % Be sure we're not beyond the end of the alphabet.
-    \ifnum\itemno=0
-      \errmessage{No more lowercase letters in @enumerate; get a bigger
-                  alphabet}%
-    \fi
-    \char\lccode\itemno
-  }%
-}
-
-% The starting (uppercase) letter is in \thearg.
-\def\uppercaseenumerate{%
-  \itemno = \expandafter`\thearg
-  \startenumeration{%
-    % Be sure we're not beyond the end of the alphabet.
-    \ifnum\itemno=0
-      \errmessage{No more uppercase letters in @enumerate; get a bigger
-                  alphabet}
-    \fi
-    \char\uccode\itemno
-  }%
-}
-
-% Call \doitemize, adding a period to the first argument and supplying the
-% common last two arguments.  Also subtract one from the initial value in
-% \itemno, since @item increments \itemno.
-%
-\def\startenumeration#1{%
-  \advance\itemno by -1
-  \doitemize{#1.}\flushcr
-}
-
-% @alphaenumerate and @capsenumerate are abbreviations for giving an arg
-% to @enumerate.
-%
-\def\alphaenumerate{\enumerate{a}}
-\def\capsenumerate{\enumerate{A}}
-\def\Ealphaenumerate{\Eenumerate}
-\def\Ecapsenumerate{\Eenumerate}
-
-
-% @multitable macros
-% Amy Hendrickson, 8/18/94, 3/6/96
-%
-% @multitable ... @end multitable will make as many columns as desired.
-% Contents of each column will wrap at width given in preamble.  Width
-% can be specified either with sample text given in a template line,
-% or in percent of \hsize, the current width of text on page.
-
-% Table can continue over pages but will only break between lines.
-
-% To make preamble:
-%
-% Either define widths of columns in terms of percent of \hsize:
-%   @multitable @columnfractions .25 .3 .45
-%   @item ...
-%
-%   Numbers following @columnfractions are the percent of the total
-%   current hsize to be used for each column. You may use as many
-%   columns as desired.
-
-
-% Or use a template:
-%   @multitable {Column 1 template} {Column 2 template} {Column 3 template}
-%   @item ...
-%   using the widest term desired in each column.
-
-% Each new table line starts with @item, each subsequent new column
-% starts with @tab. Empty columns may be produced by supplying @tab's
-% with nothing between them for as many times as empty columns are needed,
-% ie, @tab@tab@tab will produce two empty columns.
-
-% @item, @tab do not need to be on their own lines, but it will not hurt
-% if they are.
-
-% Sample multitable:
-
-%   @multitable {Column 1 template} {Column 2 template} {Column 3 template}
-%   @item first col stuff @tab second col stuff @tab third col
-%   @item
-%   first col stuff
-%   @tab
-%   second col stuff
-%   @tab
-%   third col
-%   @item first col stuff @tab second col stuff
-%   @tab Many paragraphs of text may be used in any column.
-%
-%         They will wrap at the width determined by the template.
-%   @item@tab@tab This will be in third column.
-%   @end multitable
-
-% Default dimensions may be reset by user.
-% @multitableparskip is vertical space between paragraphs in table.
-% @multitableparindent is paragraph indent in table.
-% @multitablecolmargin is horizontal space to be left between columns.
-% @multitablelinespace is space to leave between table items, baseline
-%                                                            to baseline.
-%   0pt means it depends on current normal line spacing.
-%
-\newskip\multitableparskip
-\newskip\multitableparindent
-\newdimen\multitablecolspace
-\newskip\multitablelinespace
-\multitableparskip=0pt
-\multitableparindent=6pt
-\multitablecolspace=12pt
-\multitablelinespace=0pt
-
-% Macros used to set up halign preamble:
-%
-\let\endsetuptable\relax
-\def\xendsetuptable{\endsetuptable}
-\let\columnfractions\relax
-\def\xcolumnfractions{\columnfractions}
-\newif\ifsetpercent
-
-% #1 is the @columnfraction, usually a decimal number like .5, but might
-% be just 1.  We just use it, whatever it is.
-%
-\def\pickupwholefraction#1 {%
-  \global\advance\colcount by 1
-  \expandafter\xdef\csname col\the\colcount\endcsname{#1\hsize}%
-  \setuptable
-}
-
-\newcount\colcount
-\def\setuptable#1{%
-  \def\firstarg{#1}%
-  \ifx\firstarg\xendsetuptable
-    \let\go = \relax
-  \else
-    \ifx\firstarg\xcolumnfractions
-      \global\setpercenttrue
-    \else
-      \ifsetpercent
-         \let\go\pickupwholefraction
-      \else
-         \global\advance\colcount by 1
-         \setbox0=\hbox{#1\unskip\space}% Add a normal word space as a
-                   % separator; typically that is always in the input, anyway.
-         \expandafter\xdef\csname col\the\colcount\endcsname{\the\wd0}%
-      \fi
-    \fi
-    \ifx\go\pickupwholefraction
-      % Put the argument back for the \pickupwholefraction call, so
-      % we'll always have a period there to be parsed.
-      \def\go{\pickupwholefraction#1}%
-    \else
-      \let\go = \setuptable
-    \fi%
-  \fi
-  \go
-}
-
-% multitable-only commands.
-%
-% @headitem starts a heading row, which we typeset in bold.
-% Assignments have to be global since we are inside the implicit group
-% of an alignment entry.  \everycr resets \everytab so we don't have to
-% undo it ourselves.
-\def\headitemfont{\b}% for people to use in the template row; not changeable
-\def\headitem{%
-  \checkenv\multitable
-  \crcr
-  \global\everytab={\bf}% can't use \headitemfont since the parsing differs
-  \the\everytab % for the first item
-}%
-%
-% A \tab used to include \hskip1sp.  But then the space in a template
-% line is not enough.  That is bad.  So let's go back to just `&' until
-% we again encounter the problem the 1sp was intended to solve.
-%					--karl, nathan@acm.org, 20apr99.
-\def\tab{\checkenv\multitable &\the\everytab}%
-
-% @multitable ... @end multitable definitions:
-%
-\newtoks\everytab  % insert after every tab.
-%
-\envdef\multitable{%
-  \vskip\parskip
-  \startsavinginserts
-  %
-  % @item within a multitable starts a normal row.
-  % We use \def instead of \let so that if one of the multitable entries
-  % contains an @itemize, we don't choke on the \item (seen as \crcr aka
-  % \endtemplate) expanding \doitemize.
-  \def\item{\crcr}%
-  %
-  \tolerance=9500
-  \hbadness=9500
-  \setmultitablespacing
-  \parskip=\multitableparskip
-  \parindent=\multitableparindent
-  \overfullrule=0pt
-  \global\colcount=0
-  %
-  \everycr = {%
-    \noalign{%
-      \global\everytab={}%
-      \global\colcount=0 % Reset the column counter.
-      % Check for saved footnotes, etc.
-      \checkinserts
-      % Keeps underfull box messages off when table breaks over pages.
-      %\filbreak
-	% Maybe so, but it also creates really weird page breaks when the
-	% table breaks over pages. Wouldn't \vfil be better?  Wait until the
-	% problem manifests itself, so it can be fixed for real --karl.
-    }%
-  }%
-  %
-  \parsearg\domultitable
-}
-\def\domultitable#1{%
-  % To parse everything between @multitable and @item:
-  \setuptable#1 \endsetuptable
-  %
-  % This preamble sets up a generic column definition, which will
-  % be used as many times as user calls for columns.
-  % \vtop will set a single line and will also let text wrap and
-  % continue for many paragraphs if desired.
-  \halign\bgroup &%
-    \global\advance\colcount by 1
-    \multistrut
-    \vtop{%
-      % Use the current \colcount to find the correct column width:
-      \hsize=\expandafter\csname col\the\colcount\endcsname
-      %
-      % In order to keep entries from bumping into each other
-      % we will add a \leftskip of \multitablecolspace to all columns after
-      % the first one.
-      %
-      % If a template has been used, we will add \multitablecolspace
-      % to the width of each template entry.
-      %
-      % If the user has set preamble in terms of percent of \hsize we will
-      % use that dimension as the width of the column, and the \leftskip
-      % will keep entries from bumping into each other.  Table will start at
-      % left margin and final column will justify at right margin.
-      %
-      % Make sure we don't inherit \rightskip from the outer environment.
-      \rightskip=0pt
-      \ifnum\colcount=1
-	% The first column will be indented with the surrounding text.
-	\advance\hsize by\leftskip
-      \else
-	\ifsetpercent \else
-	  % If user has not set preamble in terms of percent of \hsize
-	  % we will advance \hsize by \multitablecolspace.
-	  \advance\hsize by \multitablecolspace
-	\fi
-       % In either case we will make \leftskip=\multitablecolspace:
-      \leftskip=\multitablecolspace
-      \fi
-      % Ignoring space at the beginning and end avoids an occasional spurious
-      % blank line, when TeX decides to break the line at the space before the
-      % box from the multistrut, so the strut ends up on a line by itself.
-      % For example:
-      % @multitable @columnfractions .11 .89
-      % @item @code{#}
-      % @tab Legal holiday which is valid in major parts of the whole country.
-      % Is automatically provided with highlighting sequences respectively
-      % marking characters.
-      \noindent\ignorespaces##\unskip\multistrut
-    }\cr
-}
-\def\Emultitable{%
-  \crcr
-  \egroup % end the \halign
-  \global\setpercentfalse
-}
-
-\def\setmultitablespacing{%
-  \def\multistrut{\strut}% just use the standard line spacing
-  %
-  % Compute \multitablelinespace (if not defined by user) for use in
-  % \multitableparskip calculation.  We used define \multistrut based on
-  % this, but (ironically) that caused the spacing to be off.
-  % See bug-texinfo report from Werner Lemberg, 31 Oct 2004 12:52:20 +0100.
-\ifdim\multitablelinespace=0pt
-\setbox0=\vbox{X}\global\multitablelinespace=\the\baselineskip
-\global\advance\multitablelinespace by-\ht0
-\fi
-% Test to see if parskip is larger than space between lines of
-% table. If not, do nothing.
-%        If so, set to same dimension as multitablelinespace.
-\ifdim\multitableparskip>\multitablelinespace
-\global\multitableparskip=\multitablelinespace
-\global\advance\multitableparskip-7pt % to keep parskip somewhat smaller
-                                      % than skip between lines in the table.
-\fi%
-\ifdim\multitableparskip=0pt
-\global\multitableparskip=\multitablelinespace
-\global\advance\multitableparskip-7pt % to keep parskip somewhat smaller
-                                      % than skip between lines in the table.
-\fi}
-
-
-\message{conditionals,}
-
-% @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotplaintext,
-% @ifnotxml always succeed.  They currently do nothing; we don't
-% attempt to check whether the conditionals are properly nested.  But we
-% have to remember that they are conditionals, so that @end doesn't
-% attempt to close an environment group.
-%
-\def\makecond#1{%
-  \expandafter\let\csname #1\endcsname = \relax
-  \expandafter\let\csname iscond.#1\endcsname = 1
-}
-\makecond{iftex}
-\makecond{ifnotdocbook}
-\makecond{ifnothtml}
-\makecond{ifnotinfo}
-\makecond{ifnotplaintext}
-\makecond{ifnotxml}
-
-% Ignore @ignore, @ifhtml, @ifinfo, and the like.
-%
-\def\direntry{\doignore{direntry}}
-\def\documentdescription{\doignore{documentdescription}}
-\def\docbook{\doignore{docbook}}
-\def\html{\doignore{html}}
-\def\ifdocbook{\doignore{ifdocbook}}
-\def\ifhtml{\doignore{ifhtml}}
-\def\ifinfo{\doignore{ifinfo}}
-\def\ifnottex{\doignore{ifnottex}}
-\def\ifplaintext{\doignore{ifplaintext}}
-\def\ifxml{\doignore{ifxml}}
-\def\ignore{\doignore{ignore}}
-\def\menu{\doignore{menu}}
-\def\xml{\doignore{xml}}
-
-% Ignore text until a line `@end #1', keeping track of nested conditionals.
-%
-% A count to remember the depth of nesting.
-\newcount\doignorecount
-
-\def\doignore#1{\begingroup
-  % Scan in ``verbatim'' mode:
-  \obeylines
-  \catcode`\@ = \other
-  \catcode`\{ = \other
-  \catcode`\} = \other
-  %
-  % Make sure that spaces turn into tokens that match what \doignoretext wants.
-  \spaceisspace
-  %
-  % Count number of #1's that we've seen.
-  \doignorecount = 0
-  %
-  % Swallow text until we reach the matching `@end #1'.
-  \dodoignore{#1}%
-}
-
-{ \catcode`_=11 % We want to use \_STOP_ which cannot appear in texinfo source.
-  \obeylines %
-  %
-  \gdef\dodoignore#1{%
-    % #1 contains the command name as a string, e.g., `ifinfo'.
-    %
-    % Define a command to find the next `@end #1'.
-    \long\def\doignoretext##1^^M@end #1{%
-      \doignoretextyyy##1^^M@#1\_STOP_}%
-    %
-    % And this command to find another #1 command, at the beginning of a
-    % line.  (Otherwise, we would consider a line `@c @ifset', for
-    % example, to count as an @ifset for nesting.)
-    \long\def\doignoretextyyy##1^^M@#1##2\_STOP_{\doignoreyyy{##2}\_STOP_}%
-    %
-    % And now expand that command.
-    \doignoretext ^^M%
-  }%
-}
-
-\def\doignoreyyy#1{%
-  \def\temp{#1}%
-  \ifx\temp\empty			% Nothing found.
-    \let\next\doignoretextzzz
-  \else					% Found a nested condition, ...
-    \advance\doignorecount by 1
-    \let\next\doignoretextyyy		% ..., look for another.
-    % If we're here, #1 ends with ^^M\ifinfo (for example).
-  \fi
-  \next #1% the token \_STOP_ is present just after this macro.
-}
-
-% We have to swallow the remaining "\_STOP_".
-%
-\def\doignoretextzzz#1{%
-  \ifnum\doignorecount = 0	% We have just found the outermost @end.
-    \let\next\enddoignore
-  \else				% Still inside a nested condition.
-    \advance\doignorecount by -1
-    \let\next\doignoretext      % Look for the next @end.
-  \fi
-  \next
-}
-
-% Finish off ignored text.
-{ \obeylines%
-  % Ignore anything after the last `@end #1'; this matters in verbatim
-  % environments, where otherwise the newline after an ignored conditional
-  % would result in a blank line in the output.
-  \gdef\enddoignore#1^^M{\endgroup\ignorespaces}%
-}
-
-
-% @set VAR sets the variable VAR to an empty value.
-% @set VAR REST-OF-LINE sets VAR to the value REST-OF-LINE.
-%
-% Since we want to separate VAR from REST-OF-LINE (which might be
-% empty), we can't just use \parsearg; we have to insert a space of our
-% own to delimit the rest of the line, and then take it out again if we
-% didn't need it.
-% We rely on the fact that \parsearg sets \catcode`\ =10.
-%
-\parseargdef\set{\setyyy#1 \endsetyyy}
-\def\setyyy#1 #2\endsetyyy{%
-  {%
-    \makevalueexpandable
-    \def\temp{#2}%
-    \edef\next{\gdef\makecsname{SET#1}}%
-    \ifx\temp\empty
-      \next{}%
-    \else
-      \setzzz#2\endsetzzz
-    \fi
-  }%
-}
-% Remove the trailing space \setxxx inserted.
-\def\setzzz#1 \endsetzzz{\next{#1}}
-
-% @clear VAR clears (i.e., unsets) the variable VAR.
-%
-\parseargdef\clear{%
-  {%
-    \makevalueexpandable
-    \global\expandafter\let\csname SET#1\endcsname=\relax
-  }%
-}
-
-% @value{foo} gets the text saved in variable foo.
-\def\value{\begingroup\makevalueexpandable\valuexxx}
-\def\valuexxx#1{\expandablevalue{#1}\endgroup}
-{
-  \catcode`\- = \active \catcode`\_ = \active
-  %
-  \gdef\makevalueexpandable{%
-    \let\value = \expandablevalue
-    % We don't want these characters active, ...
-    \catcode`\-=\other \catcode`\_=\other
-    % ..., but we might end up with active ones in the argument if
-    % we're called from @code, as @code{@value{foo-bar_}}, though.
-    % So \let them to their normal equivalents.
-    \let-\normaldash \let_\normalunderscore
-  }
-}
-
-% We have this subroutine so that we can handle at least some @value's
-% properly in indexes (we call \makevalueexpandable in \indexdummies).
-% The command has to be fully expandable (if the variable is set), since
-% the result winds up in the index file.  This means that if the
-% variable's value contains other Texinfo commands, it's almost certain
-% it will fail (although perhaps we could fix that with sufficient work
-% to do a one-level expansion on the result, instead of complete).
-%
-\def\expandablevalue#1{%
-  \expandafter\ifx\csname SET#1\endcsname\relax
-    {[No value for ``#1'']}%
-    \message{Variable `#1', used in @value, is not set.}%
-  \else
-    \csname SET#1\endcsname
-  \fi
-}
-
-% @ifset VAR ... @end ifset reads the `...' iff VAR has been defined
-% with @set.
-%
-% To get special treatment of `@end ifset,' call \makeond and the redefine.
-%
-\makecond{ifset}
-\def\ifset{\parsearg{\doifset{\let\next=\ifsetfail}}}
-\def\doifset#1#2{%
-  {%
-    \makevalueexpandable
-    \let\next=\empty
-    \expandafter\ifx\csname SET#2\endcsname\relax
-      #1% If not set, redefine \next.
-    \fi
-    \expandafter
-  }\next
-}
-\def\ifsetfail{\doignore{ifset}}
-
-% @ifclear VAR ... @end executes the `...' iff VAR has never been
-% defined with @set, or has been undefined with @clear.
-%
-% The `\else' inside the `\doifset' parameter is a trick to reuse the
-% above code: if the variable is not set, do nothing, if it is set,
-% then redefine \next to \ifclearfail.
-%
-\makecond{ifclear}
-\def\ifclear{\parsearg{\doifset{\else \let\next=\ifclearfail}}}
-\def\ifclearfail{\doignore{ifclear}}
-
-% @ifcommandisdefined CMD ... @end executes the `...' if CMD (written
-% without the @) is in fact defined.  We can only feasibly check at the
-% TeX level, so something like `mathcode' is going to considered
-% defined even though it is not a Texinfo command.
-% 
-\makecond{ifcommanddefined}
-\def\ifcommanddefined{\parsearg{\doifcmddefined{\let\next=\ifcmddefinedfail}}}
-%
-\def\doifcmddefined#1#2{{%
-    \makevalueexpandable
-    \let\next=\empty
-    \expandafter\ifx\csname #2\endcsname\relax
-      #1% If not defined, \let\next as above.
-    \fi
-    \expandafter
-  }\next
-}
-\def\ifcmddefinedfail{\doignore{ifcommanddefined}}
-
-% @ifcommandnotdefined CMD ... handled similar to @ifclear above.
-\makecond{ifcommandnotdefined}
-\def\ifcommandnotdefined{%
-  \parsearg{\doifcmddefined{\else \let\next=\ifcmdnotdefinedfail}}}
-\def\ifcmdnotdefinedfail{\doignore{ifcommandnotdefined}}
-
-% Set the `txicommandconditionals' variable, so documents have a way to
-% test if the @ifcommand...defined conditionals are available.
-\set txicommandconditionals
-
-% @dircategory CATEGORY  -- specify a category of the dir file
-% which this file should belong to.  Ignore this in TeX.
-\let\dircategory=\comment
-
-% @defininfoenclose.
-\let\definfoenclose=\comment
-
-
-\message{indexing,}
-% Index generation facilities
-
-% Define \newwrite to be identical to plain tex's \newwrite
-% except not \outer, so it can be used within macros and \if's.
-\edef\newwrite{\makecsname{ptexnewwrite}}
-
-% \newindex {foo} defines an index named foo.
-% It automatically defines \fooindex such that
-% \fooindex ...rest of line... puts an entry in the index foo.
-% It also defines \fooindfile to be the number of the output channel for
-% the file that accumulates this index.  The file's extension is foo.
-% The name of an index should be no more than 2 characters long
-% for the sake of vms.
-%
-\def\newindex#1{%
-  \iflinks
-    \expandafter\newwrite \csname#1indfile\endcsname
-    \openout \csname#1indfile\endcsname \jobname.#1 % Open the file
-  \fi
-  \expandafter\xdef\csname#1index\endcsname{%     % Define @#1index
-    \noexpand\doindex{#1}}
-}
-
-% @defindex foo  ==  \newindex{foo}
-%
-\def\defindex{\parsearg\newindex}
-
-% Define @defcodeindex, like @defindex except put all entries in @code.
-%
-\def\defcodeindex{\parsearg\newcodeindex}
-%
-\def\newcodeindex#1{%
-  \iflinks
-    \expandafter\newwrite \csname#1indfile\endcsname
-    \openout \csname#1indfile\endcsname \jobname.#1
-  \fi
-  \expandafter\xdef\csname#1index\endcsname{%
-    \noexpand\docodeindex{#1}}%
-}
-
-
-% @synindex foo bar    makes index foo feed into index bar.
-% Do this instead of @defindex foo if you don't want it as a separate index.
-%
-% @syncodeindex foo bar   similar, but put all entries made for index foo
-% inside @code.
-%
-\def\synindex#1 #2 {\dosynindex\doindex{#1}{#2}}
-\def\syncodeindex#1 #2 {\dosynindex\docodeindex{#1}{#2}}
-
-% #1 is \doindex or \docodeindex, #2 the index getting redefined (foo),
-% #3 the target index (bar).
-\def\dosynindex#1#2#3{%
-  % Only do \closeout if we haven't already done it, else we'll end up
-  % closing the target index.
-  \expandafter \ifx\csname donesynindex#2\endcsname \relax
-    % The \closeout helps reduce unnecessary open files; the limit on the
-    % Acorn RISC OS is a mere 16 files.
-    \expandafter\closeout\csname#2indfile\endcsname
-    \expandafter\let\csname donesynindex#2\endcsname = 1
-  \fi
-  % redefine \fooindfile:
-  \expandafter\let\expandafter\temp\expandafter=\csname#3indfile\endcsname
-  \expandafter\let\csname#2indfile\endcsname=\temp
-  % redefine \fooindex:
-  \expandafter\xdef\csname#2index\endcsname{\noexpand#1{#3}}%
-}
-
-% Define \doindex, the driver for all \fooindex macros.
-% Argument #1 is generated by the calling \fooindex macro,
-%  and it is "foo", the name of the index.
-
-% \doindex just uses \parsearg; it calls \doind for the actual work.
-% This is because \doind is more useful to call from other macros.
-
-% There is also \dosubind {index}{topic}{subtopic}
-% which makes an entry in a two-level index such as the operation index.
-
-\def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer}
-\def\singleindexer #1{\doind{\indexname}{#1}}
-
-% like the previous two, but they put @code around the argument.
-\def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer}
-\def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}}
-
-% Take care of Texinfo commands that can appear in an index entry.
-% Since there are some commands we want to expand, and others we don't,
-% we have to laboriously prevent expansion for those that we don't.
-%
-\def\indexdummies{%
-  \escapechar = `\\     % use backslash in output files.
-  \def\@{@}% change to @@ when we switch to @ as escape char in index files.
-  \def\ {\realbackslash\space }%
-  %
-  % Need these unexpandable (because we define \tt as a dummy)
-  % definitions when @{ or @} appear in index entry text.  Also, more
-  % complicated, when \tex is in effect and \{ is a \delimiter again.
-  % We can't use \lbracecmd and \rbracecmd because texindex assumes
-  % braces and backslashes are used only as delimiters.  Perhaps we
-  % should define @lbrace and @rbrace commands a la @comma.
-  \def\{{{\tt\char123}}%
-  \def\}{{\tt\char125}}%
-  %
-  % I don't entirely understand this, but when an index entry is
-  % generated from a macro call, the \endinput which \scanmacro inserts
-  % causes processing to be prematurely terminated.  This is,
-  % apparently, because \indexsorttmp is fully expanded, and \endinput
-  % is an expandable command.  The redefinition below makes \endinput
-  % disappear altogether for that purpose -- although logging shows that
-  % processing continues to some further point.  On the other hand, it
-  % seems \endinput does not hurt in the printed index arg, since that
-  % is still getting written without apparent harm.
-  %
-  % Sample source (mac-idx3.tex, reported by Graham Percival to
-  % help-texinfo, 22may06):
-  % @macro funindex {WORD}
-  % @findex xyz
-  % @end macro
-  % ...
-  % @funindex commtest
-  %
-  % The above is not enough to reproduce the bug, but it gives the flavor.
-  %
-  % Sample whatsit resulting:
-  % .@write3{\entry{xyz}{@folio }{@code {xyz@endinput }}}
-  %
-  % So:
-  \let\endinput = \empty
-  %
-  % Do the redefinitions.
-  \commondummies
-}
-
-% For the aux and toc files, @ is the escape character.  So we want to
-% redefine everything using @ as the escape character (instead of
-% \realbackslash, still used for index files).  When everything uses @,
-% this will be simpler.
-%
-\def\atdummies{%
-  \def\@{@@}%
-  \def\ {@ }%
-  \let\{ = \lbraceatcmd
-  \let\} = \rbraceatcmd
-  %
-  % Do the redefinitions.
-  \commondummies
-  \otherbackslash
-}
-
-% Called from \indexdummies and \atdummies.
-%
-\def\commondummies{%
-  %
-  % \definedummyword defines \#1 as \string\#1\space, thus effectively
-  % preventing its expansion.  This is used only for control words,
-  % not control letters, because the \space would be incorrect for
-  % control characters, but is needed to separate the control word
-  % from whatever follows.
-  %
-  % For control letters, we have \definedummyletter, which omits the
-  % space.
-  %
-  % These can be used both for control words that take an argument and
-  % those that do not.  If it is followed by {arg} in the input, then
-  % that will dutifully get written to the index (or wherever).
-  %
-  \def\definedummyword  ##1{\def##1{\string##1\space}}%
-  \def\definedummyletter##1{\def##1{\string##1}}%
-  \let\definedummyaccent\definedummyletter
-  %
-  \commondummiesnofonts
-  %
-  \definedummyletter\_%
-  \definedummyletter\-%
-  %
-  % Non-English letters.
-  \definedummyword\AA
-  \definedummyword\AE
-  \definedummyword\DH
-  \definedummyword\L
-  \definedummyword\O
-  \definedummyword\OE
-  \definedummyword\TH
-  \definedummyword\aa
-  \definedummyword\ae
-  \definedummyword\dh
-  \definedummyword\exclamdown
-  \definedummyword\l
-  \definedummyword\o
-  \definedummyword\oe
-  \definedummyword\ordf
-  \definedummyword\ordm
-  \definedummyword\questiondown
-  \definedummyword\ss
-  \definedummyword\th
-  %
-  % Although these internal commands shouldn't show up, sometimes they do.
-  \definedummyword\bf
-  \definedummyword\gtr
-  \definedummyword\hat
-  \definedummyword\less
-  \definedummyword\sf
-  \definedummyword\sl
-  \definedummyword\tclose
-  \definedummyword\tt
-  %
-  \definedummyword\LaTeX
-  \definedummyword\TeX
-  %
-  % Assorted special characters.
-  \definedummyword\arrow
-  \definedummyword\bullet
-  \definedummyword\comma
-  \definedummyword\copyright
-  \definedummyword\registeredsymbol
-  \definedummyword\dots
-  \definedummyword\enddots
-  \definedummyword\entrybreak
-  \definedummyword\equiv
-  \definedummyword\error
-  \definedummyword\euro
-  \definedummyword\expansion
-  \definedummyword\geq
-  \definedummyword\guillemetleft
-  \definedummyword\guillemetright
-  \definedummyword\guilsinglleft
-  \definedummyword\guilsinglright
-  \definedummyword\lbracechar
-  \definedummyword\leq
-  \definedummyword\minus
-  \definedummyword\ogonek
-  \definedummyword\pounds
-  \definedummyword\point
-  \definedummyword\print
-  \definedummyword\quotedblbase
-  \definedummyword\quotedblleft
-  \definedummyword\quotedblright
-  \definedummyword\quoteleft
-  \definedummyword\quoteright
-  \definedummyword\quotesinglbase
-  \definedummyword\rbracechar
-  \definedummyword\result
-  \definedummyword\textdegree
-  %
-  % We want to disable all macros so that they are not expanded by \write.
-  \macrolist
-  %
-  \normalturnoffactive
-  %
-  % Handle some cases of @value -- where it does not contain any
-  % (non-fully-expandable) commands.
-  \makevalueexpandable
-}
-
-% \commondummiesnofonts: common to \commondummies and \indexnofonts.
-%
-\def\commondummiesnofonts{%
-  % Control letters and accents.
-  \definedummyletter\!%
-  \definedummyaccent\"%
-  \definedummyaccent\'%
-  \definedummyletter\*%
-  \definedummyaccent\,%
-  \definedummyletter\.%
-  \definedummyletter\/%
-  \definedummyletter\:%
-  \definedummyaccent\=%
-  \definedummyletter\?%
-  \definedummyaccent\^%
-  \definedummyaccent\`%
-  \definedummyaccent\~%
-  \definedummyword\u
-  \definedummyword\v
-  \definedummyword\H
-  \definedummyword\dotaccent
-  \definedummyword\ogonek
-  \definedummyword\ringaccent
-  \definedummyword\tieaccent
-  \definedummyword\ubaraccent
-  \definedummyword\udotaccent
-  \definedummyword\dotless
-  %
-  % Texinfo font commands.
-  \definedummyword\b
-  \definedummyword\i
-  \definedummyword\r
-  \definedummyword\sansserif
-  \definedummyword\sc
-  \definedummyword\slanted
-  \definedummyword\t
-  %
-  % Commands that take arguments.
-  \definedummyword\abbr
-  \definedummyword\acronym
-  \definedummyword\anchor
-  \definedummyword\cite
-  \definedummyword\code
-  \definedummyword\command
-  \definedummyword\dfn
-  \definedummyword\dmn
-  \definedummyword\email
-  \definedummyword\emph
-  \definedummyword\env
-  \definedummyword\file
-  \definedummyword\image
-  \definedummyword\indicateurl
-  \definedummyword\inforef
-  \definedummyword\kbd
-  \definedummyword\key
-  \definedummyword\math
-  \definedummyword\option
-  \definedummyword\pxref
-  \definedummyword\ref
-  \definedummyword\samp
-  \definedummyword\strong
-  \definedummyword\tie
-  \definedummyword\uref
-  \definedummyword\url
-  \definedummyword\var
-  \definedummyword\verb
-  \definedummyword\w
-  \definedummyword\xref
-}
-
-% \indexnofonts is used when outputting the strings to sort the index
-% by, and when constructing control sequence names.  It eliminates all
-% control sequences and just writes whatever the best ASCII sort string
-% would be for a given command (usually its argument).
-%
-\def\indexnofonts{%
-  % Accent commands should become @asis.
-  \def\definedummyaccent##1{\let##1\asis}%
-  % We can just ignore other control letters.
-  \def\definedummyletter##1{\let##1\empty}%
-  % All control words become @asis by default; overrides below.
-  \let\definedummyword\definedummyaccent
-  %
-  \commondummiesnofonts
-  %
-  % Don't no-op \tt, since it isn't a user-level command
-  % and is used in the definitions of the active chars like <, >, |, etc.
-  % Likewise with the other plain tex font commands.
-  %\let\tt=\asis
-  %
-  \def\ { }%
-  \def\@{@}%
-  \def\_{\normalunderscore}%
-  \def\-{}% @- shouldn't affect sorting
-  %
-  % Unfortunately, texindex is not prepared to handle braces in the
-  % content at all.  So for index sorting, we map @{ and @} to strings
-  % starting with |, since that ASCII character is between ASCII { and }.
-  \def\{{|a}%
-  \def\lbracechar{|a}%
-  %
-  \def\}{|b}%
-  \def\rbracechar{|b}%
-  %
-  % Non-English letters.
-  \def\AA{AA}%
-  \def\AE{AE}%
-  \def\DH{DZZ}%
-  \def\L{L}%
-  \def\OE{OE}%
-  \def\O{O}%
-  \def\TH{ZZZ}%
-  \def\aa{aa}%
-  \def\ae{ae}%
-  \def\dh{dzz}%
-  \def\exclamdown{!}%
-  \def\l{l}%
-  \def\oe{oe}%
-  \def\ordf{a}%
-  \def\ordm{o}%
-  \def\o{o}%
-  \def\questiondown{?}%
-  \def\ss{ss}%
-  \def\th{zzz}%
-  %
-  \def\LaTeX{LaTeX}%
-  \def\TeX{TeX}%
-  %
-  % Assorted special characters.
-  % (The following {} will end up in the sort string, but that's ok.)
-  \def\arrow{->}%
-  \def\bullet{bullet}%
-  \def\comma{,}%
-  \def\copyright{copyright}%
-  \def\dots{...}%
-  \def\enddots{...}%
-  \def\equiv{==}%
-  \def\error{error}%
-  \def\euro{euro}%
-  \def\expansion{==>}%
-  \def\geq{>=}%
-  \def\guillemetleft{<<}%
-  \def\guillemetright{>>}%
-  \def\guilsinglleft{<}%
-  \def\guilsinglright{>}%
-  \def\leq{<=}%
-  \def\minus{-}%
-  \def\point{.}%
-  \def\pounds{pounds}%
-  \def\print{-|}%
-  \def\quotedblbase{"}%
-  \def\quotedblleft{"}%
-  \def\quotedblright{"}%
-  \def\quoteleft{`}%
-  \def\quoteright{'}%
-  \def\quotesinglbase{,}%
-  \def\registeredsymbol{R}%
-  \def\result{=>}%
-  \def\textdegree{o}%
-  %
-  \expandafter\ifx\csname SETtxiindexlquoteignore\endcsname\relax
-  \else \indexlquoteignore \fi
-  %
-  % We need to get rid of all macros, leaving only the arguments (if present).
-  % Of course this is not nearly correct, but it is the best we can do for now.
-  % makeinfo does not expand macros in the argument to @deffn, which ends up
-  % writing an index entry, and texindex isn't prepared for an index sort entry
-  % that starts with \.
-  %
-  % Since macro invocations are followed by braces, we can just redefine them
-  % to take a single TeX argument.  The case of a macro invocation that
-  % goes to end-of-line is not handled.
-  %
-  \macrolist
-}
-
-% Undocumented (for FSFS 2nd ed.): @set txiindexlquoteignore makes us
-% ignore left quotes in the sort term.
-{\catcode`\`=\active
- \gdef\indexlquoteignore{\let`=\empty}}
-
-\let\indexbackslash=0  %overridden during \printindex.
-\let\SETmarginindex=\relax % put index entries in margin (undocumented)?
-
-% Most index entries go through here, but \dosubind is the general case.
-% #1 is the index name, #2 is the entry text.
-\def\doind#1#2{\dosubind{#1}{#2}{}}
-
-% Workhorse for all \fooindexes.
-% #1 is name of index, #2 is stuff to put there, #3 is subentry --
-% empty if called from \doind, as we usually are (the main exception
-% is with most defuns, which call us directly).
-%
-\def\dosubind#1#2#3{%
-  \iflinks
-  {%
-    % Store the main index entry text (including the third arg).
-    \toks0 = {#2}%
-    % If third arg is present, precede it with a space.
-    \def\thirdarg{#3}%
-    \ifx\thirdarg\empty \else
-      \toks0 = \expandafter{\the\toks0 \space #3}%
-    \fi
-    %
-    \edef\writeto{\csname#1indfile\endcsname}%
-    %
-    \safewhatsit\dosubindwrite
-  }%
-  \fi
-}
-
-% Write the entry in \toks0 to the index file:
-%
-\def\dosubindwrite{%
-  % Put the index entry in the margin if desired.
-  \ifx\SETmarginindex\relax\else
-    \insert\margin{\hbox{\vrule height8pt depth3pt width0pt \the\toks0}}%
-  \fi
-  %
-  % Remember, we are within a group.
-  \indexdummies % Must do this here, since \bf, etc expand at this stage
-  \def\backslashcurfont{\indexbackslash}% \indexbackslash isn't defined now
-      % so it will be output as is; and it will print as backslash.
-  %
-  % Process the index entry with all font commands turned off, to
-  % get the string to sort by.
-  {\indexnofonts
-   \edef\temp{\the\toks0}% need full expansion
-   \xdef\indexsorttmp{\temp}%
-  }%
-  %
-  % Set up the complete index entry, with both the sort key and
-  % the original text, including any font commands.  We write
-  % three arguments to \entry to the .?? file (four in the
-  % subentry case), texindex reduces to two when writing the .??s
-  % sorted result.
-  \edef\temp{%
-    \write\writeto{%
-      \string\entry{\indexsorttmp}{\noexpand\folio}{\the\toks0}}%
-  }%
-  \temp
-}
-
-% Take care of unwanted page breaks/skips around a whatsit:
-%
-% If a skip is the last thing on the list now, preserve it
-% by backing up by \lastskip, doing the \write, then inserting
-% the skip again.  Otherwise, the whatsit generated by the
-% \write or \pdfdest will make \lastskip zero.  The result is that
-% sequences like this:
-% @end defun
-% @tindex whatever
-% @defun ...
-% will have extra space inserted, because the \medbreak in the
-% start of the @defun won't see the skip inserted by the @end of
-% the previous defun.
-%
-% But don't do any of this if we're not in vertical mode.  We
-% don't want to do a \vskip and prematurely end a paragraph.
-%
-% Avoid page breaks due to these extra skips, too.
-%
-% But wait, there is a catch there:
-% We'll have to check whether \lastskip is zero skip.  \ifdim is not
-% sufficient for this purpose, as it ignores stretch and shrink parts
-% of the skip.  The only way seems to be to check the textual
-% representation of the skip.
-%
-% The following is almost like \def\zeroskipmacro{0.0pt} except that
-% the ``p'' and ``t'' characters have catcode \other, not 11 (letter).
-%
-\edef\zeroskipmacro{\expandafter\the\csname z@skip\endcsname}
-%
-\newskip\whatsitskip
-\newcount\whatsitpenalty
-%
-% ..., ready, GO:
-%
-\def\safewhatsit#1{\ifhmode
-  #1%
- \else
-  % \lastskip and \lastpenalty cannot both be nonzero simultaneously.
-  \whatsitskip = \lastskip
-  \edef\lastskipmacro{\the\lastskip}%
-  \whatsitpenalty = \lastpenalty
-  %
-  % If \lastskip is nonzero, that means the last item was a
-  % skip.  And since a skip is discardable, that means this
-  % -\whatsitskip glue we're inserting is preceded by a
-  % non-discardable item, therefore it is not a potential
-  % breakpoint, therefore no \nobreak needed.
-  \ifx\lastskipmacro\zeroskipmacro
-  \else
-    \vskip-\whatsitskip
-  \fi
-  %
-  #1%
-  %
-  \ifx\lastskipmacro\zeroskipmacro
-    % If \lastskip was zero, perhaps the last item was a penalty, and
-    % perhaps it was >=10000, e.g., a \nobreak.  In that case, we want
-    % to re-insert the same penalty (values >10000 are used for various
-    % signals); since we just inserted a non-discardable item, any
-    % following glue (such as a \parskip) would be a breakpoint.  For example:
-    %   @deffn deffn-whatever
-    %   @vindex index-whatever
-    %   Description.
-    % would allow a break between the index-whatever whatsit
-    % and the "Description." paragraph.
-    \ifnum\whatsitpenalty>9999 \penalty\whatsitpenalty \fi
-  \else
-    % On the other hand, if we had a nonzero \lastskip,
-    % this make-up glue would be preceded by a non-discardable item
-    % (the whatsit from the \write), so we must insert a \nobreak.
-    \nobreak\vskip\whatsitskip
-  \fi
-\fi}
-
-% The index entry written in the file actually looks like
-%  \entry {sortstring}{page}{topic}
-% or
-%  \entry {sortstring}{page}{topic}{subtopic}
-% The texindex program reads in these files and writes files
-% containing these kinds of lines:
-%  \initial {c}
-%     before the first topic whose initial is c
-%  \entry {topic}{pagelist}
-%     for a topic that is used without subtopics
-%  \primary {topic}
-%     for the beginning of a topic that is used with subtopics
-%  \secondary {subtopic}{pagelist}
-%     for each subtopic.
-
-% Define the user-accessible indexing commands
-% @findex, @vindex, @kindex, @cindex.
-
-\def\findex {\fnindex}
-\def\kindex {\kyindex}
-\def\cindex {\cpindex}
-\def\vindex {\vrindex}
-\def\tindex {\tpindex}
-\def\pindex {\pgindex}
-
-\def\cindexsub {\begingroup\obeylines\cindexsub}
-{\obeylines %
-\gdef\cindexsub "#1" #2^^M{\endgroup %
-\dosubind{cp}{#2}{#1}}}
-
-% Define the macros used in formatting output of the sorted index material.
-
-% @printindex causes a particular index (the ??s file) to get printed.
-% It does not print any chapter heading (usually an @unnumbered).
-%
-\parseargdef\printindex{\begingroup
-  \dobreak \chapheadingskip{10000}%
-  %
-  \smallfonts \rm
-  \tolerance = 9500
-  \plainfrenchspacing
-  \everypar = {}% don't want the \kern\-parindent from indentation suppression.
-  %
-  % See if the index file exists and is nonempty.
-  % Change catcode of @ here so that if the index file contains
-  % \initial {@}
-  % as its first line, TeX doesn't complain about mismatched braces
-  % (because it thinks @} is a control sequence).
-  \catcode`\@ = 11
-  \openin 1 \jobname.#1s
-  \ifeof 1
-    % \enddoublecolumns gets confused if there is no text in the index,
-    % and it loses the chapter title and the aux file entries for the
-    % index.  The easiest way to prevent this problem is to make sure
-    % there is some text.
-    \putwordIndexNonexistent
-  \else
-    %
-    % If the index file exists but is empty, then \openin leaves \ifeof
-    % false.  We have to make TeX try to read something from the file, so
-    % it can discover if there is anything in it.
-    \read 1 to \temp
-    \ifeof 1
-      \putwordIndexIsEmpty
-    \else
-      % Index files are almost Texinfo source, but we use \ as the escape
-      % character.  It would be better to use @, but that's too big a change
-      % to make right now.
-      \def\indexbackslash{\backslashcurfont}%
-      \catcode`\\ = 0
-      \escapechar = `\\
-      \begindoublecolumns
-      \input \jobname.#1s
-      \enddoublecolumns
-    \fi
-  \fi
-  \closein 1
-\endgroup}
-
-% These macros are used by the sorted index file itself.
-% Change them to control the appearance of the index.
-
-\def\initial#1{{%
-  % Some minor font changes for the special characters.
-  \let\tentt=\sectt \let\tt=\sectt \let\sf=\sectt
-  %
-  % Remove any glue we may have, we'll be inserting our own.
-  \removelastskip
-  %
-  % We like breaks before the index initials, so insert a bonus.
-  \nobreak
-  \vskip 0pt plus 3\baselineskip
-  \penalty 0
-  \vskip 0pt plus -3\baselineskip
-  %
-  % Typeset the initial.  Making this add up to a whole number of
-  % baselineskips increases the chance of the dots lining up from column
-  % to column.  It still won't often be perfect, because of the stretch
-  % we need before each entry, but it's better.
-  %
-  % No shrink because it confuses \balancecolumns.
-  \vskip 1.67\baselineskip plus .5\baselineskip
-  \leftline{\secbf #1}%
-  % Do our best not to break after the initial.
-  \nobreak
-  \vskip .33\baselineskip plus .1\baselineskip
-}}
-
-% \entry typesets a paragraph consisting of the text (#1), dot leaders, and
-% then page number (#2) flushed to the right margin.  It is used for index
-% and table of contents entries.  The paragraph is indented by \leftskip.
-%
-% A straightforward implementation would start like this:
-%	\def\entry#1#2{...
-% But this freezes the catcodes in the argument, and can cause problems to
-% @code, which sets - active.  This problem was fixed by a kludge---
-% ``-'' was active throughout whole index, but this isn't really right.
-% The right solution is to prevent \entry from swallowing the whole text.
-%                                 --kasal, 21nov03
-\def\entry{%
-  \begingroup
-    %
-    % Start a new paragraph if necessary, so our assignments below can't
-    % affect previous text.
-    \par
-    %
-    % Do not fill out the last line with white space.
-    \parfillskip = 0in
-    %
-    % No extra space above this paragraph.
-    \parskip = 0in
-    %
-    % Do not prefer a separate line ending with a hyphen to fewer lines.
-    \finalhyphendemerits = 0
-    %
-    % \hangindent is only relevant when the entry text and page number
-    % don't both fit on one line.  In that case, bob suggests starting the
-    % dots pretty far over on the line.  Unfortunately, a large
-    % indentation looks wrong when the entry text itself is broken across
-    % lines.  So we use a small indentation and put up with long leaders.
-    %
-    % \hangafter is reset to 1 (which is the value we want) at the start
-    % of each paragraph, so we need not do anything with that.
-    \hangindent = 2em
-    %
-    % When the entry text needs to be broken, just fill out the first line
-    % with blank space.
-    \rightskip = 0pt plus1fil
-    %
-    % A bit of stretch before each entry for the benefit of balancing
-    % columns.
-    \vskip 0pt plus1pt
-    %
-    % When reading the text of entry, convert explicit line breaks
-    % from @* into spaces.  The user might give these in long section
-    % titles, for instance.
-    \def\*{\unskip\space\ignorespaces}%
-    \def\entrybreak{\hfil\break}%
-    %
-    % Swallow the left brace of the text (first parameter):
-    \afterassignment\doentry
-    \let\temp =
-}
-\def\entrybreak{\unskip\space\ignorespaces}%
-\def\doentry{%
-    \bgroup % Instead of the swallowed brace.
-      \noindent
-      \aftergroup\finishentry
-      % And now comes the text of the entry.
-}
-\def\finishentry#1{%
-    % #1 is the page number.
-    %
-    % The following is kludged to not output a line of dots in the index if
-    % there are no page numbers.  The next person who breaks this will be
-    % cursed by a Unix daemon.
-    \setbox\boxA = \hbox{#1}%
-    \ifdim\wd\boxA = 0pt
-      \ %
-    \else
-      %
-      % If we must, put the page number on a line of its own, and fill out
-      % this line with blank space.  (The \hfil is overwhelmed with the
-      % fill leaders glue in \indexdotfill if the page number does fit.)
-      \hfil\penalty50
-      \null\nobreak\indexdotfill % Have leaders before the page number.
-      %
-      % The `\ ' here is removed by the implicit \unskip that TeX does as
-      % part of (the primitive) \par.  Without it, a spurious underfull
-      % \hbox ensues.
-      \ifpdf
-	\pdfgettoks#1.%
-	\ \the\toksA
-      \else
-	\ #1%
-      \fi
-    \fi
-    \par
-  \endgroup
-}
-
-% Like plain.tex's \dotfill, except uses up at least 1 em.
-\def\indexdotfill{\cleaders
-  \hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 1em plus 1fill}
-
-\def\primary #1{\line{#1\hfil}}
-
-\newskip\secondaryindent \secondaryindent=0.5cm
-\def\secondary#1#2{{%
-  \parfillskip=0in
-  \parskip=0in
-  \hangindent=1in
-  \hangafter=1
-  \noindent\hskip\secondaryindent\hbox{#1}\indexdotfill
-  \ifpdf
-    \pdfgettoks#2.\ \the\toksA % The page number ends the paragraph.
-  \else
-    #2
-  \fi
-  \par
-}}
-
-% Define two-column mode, which we use to typeset indexes.
-% Adapted from the TeXbook, page 416, which is to say,
-% the manmac.tex format used to print the TeXbook itself.
-\catcode`\@=11
-
-\newbox\partialpage
-\newdimen\doublecolumnhsize
-
-\def\begindoublecolumns{\begingroup % ended by \enddoublecolumns
-  % Grab any single-column material above us.
-  \output = {%
-    %
-    % Here is a possibility not foreseen in manmac: if we accumulate a
-    % whole lot of material, we might end up calling this \output
-    % routine twice in a row (see the doublecol-lose test, which is
-    % essentially a couple of indexes with @setchapternewpage off).  In
-    % that case we just ship out what is in \partialpage with the normal
-    % output routine.  Generally, \partialpage will be empty when this
-    % runs and this will be a no-op.  See the indexspread.tex test case.
-    \ifvoid\partialpage \else
-      \onepageout{\pagecontents\partialpage}%
-    \fi
-    %
-    \global\setbox\partialpage = \vbox{%
-      % Unvbox the main output page.
-      \unvbox\PAGE
-      \kern-\topskip \kern\baselineskip
-    }%
-  }%
-  \eject % run that output routine to set \partialpage
-  %
-  % Use the double-column output routine for subsequent pages.
-  \output = {\doublecolumnout}%
-  %
-  % Change the page size parameters.  We could do this once outside this
-  % routine, in each of @smallbook, @afourpaper, and the default 8.5x11
-  % format, but then we repeat the same computation.  Repeating a couple
-  % of assignments once per index is clearly meaningless for the
-  % execution time, so we may as well do it in one place.
-  %
-  % First we halve the line length, less a little for the gutter between
-  % the columns.  We compute the gutter based on the line length, so it
-  % changes automatically with the paper format.  The magic constant
-  % below is chosen so that the gutter has the same value (well, +-<1pt)
-  % as it did when we hard-coded it.
-  %
-  % We put the result in a separate register, \doublecolumhsize, so we
-  % can restore it in \pagesofar, after \hsize itself has (potentially)
-  % been clobbered.
-  %
-  \doublecolumnhsize = \hsize
-    \advance\doublecolumnhsize by -.04154\hsize
-    \divide\doublecolumnhsize by 2
-  \hsize = \doublecolumnhsize
-  %
-  % Double the \vsize as well.  (We don't need a separate register here,
-  % since nobody clobbers \vsize.)
-  \vsize = 2\vsize
-}
-
-% The double-column output routine for all double-column pages except
-% the last.
-%
-\def\doublecolumnout{%
-  \splittopskip=\topskip \splitmaxdepth=\maxdepth
-  % Get the available space for the double columns -- the normal
-  % (undoubled) page height minus any material left over from the
-  % previous page.
-  \dimen@ = \vsize
-  \divide\dimen@ by 2
-  \advance\dimen@ by -\ht\partialpage
-  %
-  % box0 will be the left-hand column, box2 the right.
-  \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@
-  \onepageout\pagesofar
-  \unvbox255
-  \penalty\outputpenalty
-}
-%
-% Re-output the contents of the output page -- any previous material,
-% followed by the two boxes we just split, in box0 and box2.
-\def\pagesofar{%
-  \unvbox\partialpage
-  %
-  \hsize = \doublecolumnhsize
-  \wd0=\hsize \wd2=\hsize
-  \hbox to\pagewidth{\box0\hfil\box2}%
-}
-%
-% All done with double columns.
-\def\enddoublecolumns{%
-  % The following penalty ensures that the page builder is exercised
-  % _before_ we change the output routine.  This is necessary in the
-  % following situation:
-  %
-  % The last section of the index consists only of a single entry.
-  % Before this section, \pagetotal is less than \pagegoal, so no
-  % break occurs before the last section starts.  However, the last
-  % section, consisting of \initial and the single \entry, does not
-  % fit on the page and has to be broken off.  Without the following
-  % penalty the page builder will not be exercised until \eject
-  % below, and by that time we'll already have changed the output
-  % routine to the \balancecolumns version, so the next-to-last
-  % double-column page will be processed with \balancecolumns, which
-  % is wrong:  The two columns will go to the main vertical list, with
-  % the broken-off section in the recent contributions.  As soon as
-  % the output routine finishes, TeX starts reconsidering the page
-  % break.  The two columns and the broken-off section both fit on the
-  % page, because the two columns now take up only half of the page
-  % goal.  When TeX sees \eject from below which follows the final
-  % section, it invokes the new output routine that we've set after
-  % \balancecolumns below; \onepageout will try to fit the two columns
-  % and the final section into the vbox of \pageheight (see
-  % \pagebody), causing an overfull box.
-  %
-  % Note that glue won't work here, because glue does not exercise the
-  % page builder, unlike penalties (see The TeXbook, pp. 280-281).
-  \penalty0
-  %
-  \output = {%
-    % Split the last of the double-column material.  Leave it on the
-    % current page, no automatic page break.
-    \balancecolumns
-    %
-    % If we end up splitting too much material for the current page,
-    % though, there will be another page break right after this \output
-    % invocation ends.  Having called \balancecolumns once, we do not
-    % want to call it again.  Therefore, reset \output to its normal
-    % definition right away.  (We hope \balancecolumns will never be
-    % called on to balance too much material, but if it is, this makes
-    % the output somewhat more palatable.)
-    \global\output = {\onepageout{\pagecontents\PAGE}}%
-  }%
-  \eject
-  \endgroup % started in \begindoublecolumns
-  %
-  % \pagegoal was set to the doubled \vsize above, since we restarted
-  % the current page.  We're now back to normal single-column
-  % typesetting, so reset \pagegoal to the normal \vsize (after the
-  % \endgroup where \vsize got restored).
-  \pagegoal = \vsize
-}
-%
-% Called at the end of the double column material.
-\def\balancecolumns{%
-  \setbox0 = \vbox{\unvbox255}% like \box255 but more efficient, see p.120.
-  \dimen@ = \ht0
-  \advance\dimen@ by \topskip
-  \advance\dimen@ by-\baselineskip
-  \divide\dimen@ by 2 % target to split to
-  %debug\message{final 2-column material height=\the\ht0, target=\the\dimen@.}%
-  \splittopskip = \topskip
-  % Loop until we get a decent breakpoint.
-  {%
-    \vbadness = 10000
-    \loop
-      \global\setbox3 = \copy0
-      \global\setbox1 = \vsplit3 to \dimen@
-    \ifdim\ht3>\dimen@
-      \global\advance\dimen@ by 1pt
-    \repeat
-  }%
-  %debug\message{split to \the\dimen@, column heights: \the\ht1, \the\ht3.}%
-  \setbox0=\vbox to\dimen@{\unvbox1}%
-  \setbox2=\vbox to\dimen@{\unvbox3}%
-  %
-  \pagesofar
-}
-\catcode`\@ = \other
-
-
-\message{sectioning,}
-% Chapters, sections, etc.
-
-% Let's start with @part.
-\outer\parseargdef\part{\partzzz{#1}}
-\def\partzzz#1{%
-  \chapoddpage
-  \null
-  \vskip.3\vsize  % move it down on the page a bit
-  \begingroup
-    \noindent \titlefonts\rmisbold #1\par % the text
-    \let\lastnode=\empty      % no node to associate with
-    \writetocentry{part}{#1}{}% but put it in the toc
-    \headingsoff              % no headline or footline on the part page
-    \chapoddpage
-  \endgroup
-}
-
-% \unnumberedno is an oxymoron.  But we count the unnumbered
-% sections so that we can refer to them unambiguously in the pdf
-% outlines by their "section number".  We avoid collisions with chapter
-% numbers by starting them at 10000.  (If a document ever has 10000
-% chapters, we're in trouble anyway, I'm sure.)
-\newcount\unnumberedno \unnumberedno = 10000
-\newcount\chapno
-\newcount\secno        \secno=0
-\newcount\subsecno     \subsecno=0
-\newcount\subsubsecno  \subsubsecno=0
-
-% This counter is funny since it counts through charcodes of letters A, B, ...
-\newcount\appendixno  \appendixno = `\@
-%
-% \def\appendixletter{\char\the\appendixno}
-% We do the following ugly conditional instead of the above simple
-% construct for the sake of pdftex, which needs the actual
-% letter in the expansion, not just typeset.
-%
-\def\appendixletter{%
-  \ifnum\appendixno=`A A%
-  \else\ifnum\appendixno=`B B%
-  \else\ifnum\appendixno=`C C%
-  \else\ifnum\appendixno=`D D%
-  \else\ifnum\appendixno=`E E%
-  \else\ifnum\appendixno=`F F%
-  \else\ifnum\appendixno=`G G%
-  \else\ifnum\appendixno=`H H%
-  \else\ifnum\appendixno=`I I%
-  \else\ifnum\appendixno=`J J%
-  \else\ifnum\appendixno=`K K%
-  \else\ifnum\appendixno=`L L%
-  \else\ifnum\appendixno=`M M%
-  \else\ifnum\appendixno=`N N%
-  \else\ifnum\appendixno=`O O%
-  \else\ifnum\appendixno=`P P%
-  \else\ifnum\appendixno=`Q Q%
-  \else\ifnum\appendixno=`R R%
-  \else\ifnum\appendixno=`S S%
-  \else\ifnum\appendixno=`T T%
-  \else\ifnum\appendixno=`U U%
-  \else\ifnum\appendixno=`V V%
-  \else\ifnum\appendixno=`W W%
-  \else\ifnum\appendixno=`X X%
-  \else\ifnum\appendixno=`Y Y%
-  \else\ifnum\appendixno=`Z Z%
-  % The \the is necessary, despite appearances, because \appendixletter is
-  % expanded while writing the .toc file.  \char\appendixno is not
-  % expandable, thus it is written literally, thus all appendixes come out
-  % with the same letter (or @) in the toc without it.
-  \else\char\the\appendixno
-  \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
-  \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi}
-
-% Each @chapter defines these (using marks) as the number+name, number
-% and name of the chapter.  Page headings and footings can use
-% these.  @section does likewise.
-\def\thischapter{}
-\def\thischapternum{}
-\def\thischaptername{}
-\def\thissection{}
-\def\thissectionnum{}
-\def\thissectionname{}
-
-\newcount\absseclevel % used to calculate proper heading level
-\newcount\secbase\secbase=0 % @raisesections/@lowersections modify this count
-
-% @raisesections: treat @section as chapter, @subsection as section, etc.
-\def\raisesections{\global\advance\secbase by -1}
-\let\up=\raisesections % original BFox name
-
-% @lowersections: treat @chapter as section, @section as subsection, etc.
-\def\lowersections{\global\advance\secbase by 1}
-\let\down=\lowersections % original BFox name
-
-% we only have subsub.
-\chardef\maxseclevel = 3
-%
-% A numbered section within an unnumbered changes to unnumbered too.
-% To achieve this, remember the "biggest" unnum. sec. we are currently in:
-\chardef\unnlevel = \maxseclevel
-%
-% Trace whether the current chapter is an appendix or not:
-% \chapheadtype is "N" or "A", unnumbered chapters are ignored.
-\def\chapheadtype{N}
-
-% Choose a heading macro
-% #1 is heading type
-% #2 is heading level
-% #3 is text for heading
-\def\genhead#1#2#3{%
-  % Compute the abs. sec. level:
-  \absseclevel=#2
-  \advance\absseclevel by \secbase
-  % Make sure \absseclevel doesn't fall outside the range:
-  \ifnum \absseclevel < 0
-    \absseclevel = 0
-  \else
-    \ifnum \absseclevel > 3
-      \absseclevel = 3
-    \fi
-  \fi
-  % The heading type:
-  \def\headtype{#1}%
-  \if \headtype U%
-    \ifnum \absseclevel < \unnlevel
-      \chardef\unnlevel = \absseclevel
-    \fi
-  \else
-    % Check for appendix sections:
-    \ifnum \absseclevel = 0
-      \edef\chapheadtype{\headtype}%
-    \else
-      \if \headtype A\if \chapheadtype N%
-	\errmessage{@appendix... within a non-appendix chapter}%
-      \fi\fi
-    \fi
-    % Check for numbered within unnumbered:
-    \ifnum \absseclevel > \unnlevel
-      \def\headtype{U}%
-    \else
-      \chardef\unnlevel = 3
-    \fi
-  \fi
-  % Now print the heading:
-  \if \headtype U%
-    \ifcase\absseclevel
-	\unnumberedzzz{#3}%
-    \or \unnumberedseczzz{#3}%
-    \or \unnumberedsubseczzz{#3}%
-    \or \unnumberedsubsubseczzz{#3}%
-    \fi
-  \else
-    \if \headtype A%
-      \ifcase\absseclevel
-	  \appendixzzz{#3}%
-      \or \appendixsectionzzz{#3}%
-      \or \appendixsubseczzz{#3}%
-      \or \appendixsubsubseczzz{#3}%
-      \fi
-    \else
-      \ifcase\absseclevel
-	  \chapterzzz{#3}%
-      \or \seczzz{#3}%
-      \or \numberedsubseczzz{#3}%
-      \or \numberedsubsubseczzz{#3}%
-      \fi
-    \fi
-  \fi
-  \suppressfirstparagraphindent
-}
-
-% an interface:
-\def\numhead{\genhead N}
-\def\apphead{\genhead A}
-\def\unnmhead{\genhead U}
-
-% @chapter, @appendix, @unnumbered.  Increment top-level counter, reset
-% all lower-level sectioning counters to zero.
-%
-% Also set \chaplevelprefix, which we prepend to @float sequence numbers
-% (e.g., figures), q.v.  By default (before any chapter), that is empty.
-\let\chaplevelprefix = \empty
-%
-\outer\parseargdef\chapter{\numhead0{#1}} % normally numhead0 calls chapterzzz
-\def\chapterzzz#1{%
-  % section resetting is \global in case the chapter is in a group, such
-  % as an @include file.
-  \global\secno=0 \global\subsecno=0 \global\subsubsecno=0
-    \global\advance\chapno by 1
-  %
-  % Used for \float.
-  \gdef\chaplevelprefix{\the\chapno.}%
-  \resetallfloatnos
-  %
-  % \putwordChapter can contain complex things in translations.
-  \toks0=\expandafter{\putwordChapter}%
-  \message{\the\toks0 \space \the\chapno}%
-  %
-  % Write the actual heading.
-  \chapmacro{#1}{Ynumbered}{\the\chapno}%
-  %
-  % So @section and the like are numbered underneath this chapter.
-  \global\let\section = \numberedsec
-  \global\let\subsection = \numberedsubsec
-  \global\let\subsubsection = \numberedsubsubsec
-}
-
-\outer\parseargdef\appendix{\apphead0{#1}} % normally calls appendixzzz
-%
-\def\appendixzzz#1{%
-  \global\secno=0 \global\subsecno=0 \global\subsubsecno=0
-    \global\advance\appendixno by 1
-  \gdef\chaplevelprefix{\appendixletter.}%
-  \resetallfloatnos
-  %
-  % \putwordAppendix can contain complex things in translations.
-  \toks0=\expandafter{\putwordAppendix}%
-  \message{\the\toks0 \space \appendixletter}%
-  %
-  \chapmacro{#1}{Yappendix}{\appendixletter}%
-  %
-  \global\let\section = \appendixsec
-  \global\let\subsection = \appendixsubsec
-  \global\let\subsubsection = \appendixsubsubsec
-}
-
-% normally unnmhead0 calls unnumberedzzz:
-\outer\parseargdef\unnumbered{\unnmhead0{#1}}
-\def\unnumberedzzz#1{%
-  \global\secno=0 \global\subsecno=0 \global\subsubsecno=0
-    \global\advance\unnumberedno by 1
-  %
-  % Since an unnumbered has no number, no prefix for figures.
-  \global\let\chaplevelprefix = \empty
-  \resetallfloatnos
-  %
-  % This used to be simply \message{#1}, but TeX fully expands the
-  % argument to \message.  Therefore, if #1 contained @-commands, TeX
-  % expanded them.  For example, in `@unnumbered The @cite{Book}', TeX
-  % expanded @cite (which turns out to cause errors because \cite is meant
-  % to be executed, not expanded).
-  %
-  % Anyway, we don't want the fully-expanded definition of @cite to appear
-  % as a result of the \message, we just want `@cite' itself.  We use
-  % \the<toks register> to achieve this: TeX expands \the<toks> only once,
-  % simply yielding the contents of <toks register>.  (We also do this for
-  % the toc entries.)
-  \toks0 = {#1}%
-  \message{(\the\toks0)}%
-  %
-  \chapmacro{#1}{Ynothing}{\the\unnumberedno}%
-  %
-  \global\let\section = \unnumberedsec
-  \global\let\subsection = \unnumberedsubsec
-  \global\let\subsubsection = \unnumberedsubsubsec
-}
-
-% @centerchap is like @unnumbered, but the heading is centered.
-\outer\parseargdef\centerchap{%
-  % Well, we could do the following in a group, but that would break
-  % an assumption that \chapmacro is called at the outermost level.
-  % Thus we are safer this way:		--kasal, 24feb04
-  \let\centerparametersmaybe = \centerparameters
-  \unnmhead0{#1}%
-  \let\centerparametersmaybe = \relax
-}
-
-% @top is like @unnumbered.
-\let\top\unnumbered
-
-% Sections.
-% 
-\outer\parseargdef\numberedsec{\numhead1{#1}} % normally calls seczzz
-\def\seczzz#1{%
-  \global\subsecno=0 \global\subsubsecno=0  \global\advance\secno by 1
-  \sectionheading{#1}{sec}{Ynumbered}{\the\chapno.\the\secno}%
-}
-
-% normally calls appendixsectionzzz:
-\outer\parseargdef\appendixsection{\apphead1{#1}}
-\def\appendixsectionzzz#1{%
-  \global\subsecno=0 \global\subsubsecno=0  \global\advance\secno by 1
-  \sectionheading{#1}{sec}{Yappendix}{\appendixletter.\the\secno}%
-}
-\let\appendixsec\appendixsection
-
-% normally calls unnumberedseczzz:
-\outer\parseargdef\unnumberedsec{\unnmhead1{#1}}
-\def\unnumberedseczzz#1{%
-  \global\subsecno=0 \global\subsubsecno=0  \global\advance\secno by 1
-  \sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno.\the\secno}%
-}
-
-% Subsections.
-% 
-% normally calls numberedsubseczzz:
-\outer\parseargdef\numberedsubsec{\numhead2{#1}}
-\def\numberedsubseczzz#1{%
-  \global\subsubsecno=0  \global\advance\subsecno by 1
-  \sectionheading{#1}{subsec}{Ynumbered}{\the\chapno.\the\secno.\the\subsecno}%
-}
-
-% normally calls appendixsubseczzz:
-\outer\parseargdef\appendixsubsec{\apphead2{#1}}
-\def\appendixsubseczzz#1{%
-  \global\subsubsecno=0  \global\advance\subsecno by 1
-  \sectionheading{#1}{subsec}{Yappendix}%
-                 {\appendixletter.\the\secno.\the\subsecno}%
-}
-
-% normally calls unnumberedsubseczzz:
-\outer\parseargdef\unnumberedsubsec{\unnmhead2{#1}}
-\def\unnumberedsubseczzz#1{%
-  \global\subsubsecno=0  \global\advance\subsecno by 1
-  \sectionheading{#1}{subsec}{Ynothing}%
-                 {\the\unnumberedno.\the\secno.\the\subsecno}%
-}
-
-% Subsubsections.
-% 
-% normally numberedsubsubseczzz:
-\outer\parseargdef\numberedsubsubsec{\numhead3{#1}}
-\def\numberedsubsubseczzz#1{%
-  \global\advance\subsubsecno by 1
-  \sectionheading{#1}{subsubsec}{Ynumbered}%
-                 {\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno}%
-}
-
-% normally appendixsubsubseczzz:
-\outer\parseargdef\appendixsubsubsec{\apphead3{#1}}
-\def\appendixsubsubseczzz#1{%
-  \global\advance\subsubsecno by 1
-  \sectionheading{#1}{subsubsec}{Yappendix}%
-                 {\appendixletter.\the\secno.\the\subsecno.\the\subsubsecno}%
-}
-
-% normally unnumberedsubsubseczzz:
-\outer\parseargdef\unnumberedsubsubsec{\unnmhead3{#1}}
-\def\unnumberedsubsubseczzz#1{%
-  \global\advance\subsubsecno by 1
-  \sectionheading{#1}{subsubsec}{Ynothing}%
-                 {\the\unnumberedno.\the\secno.\the\subsecno.\the\subsubsecno}%
-}
-
-% These macros control what the section commands do, according
-% to what kind of chapter we are in (ordinary, appendix, or unnumbered).
-% Define them by default for a numbered chapter.
-\let\section = \numberedsec
-\let\subsection = \numberedsubsec
-\let\subsubsection = \numberedsubsubsec
-
-% Define @majorheading, @heading and @subheading
-
-\def\majorheading{%
-  {\advance\chapheadingskip by 10pt \chapbreak }%
-  \parsearg\chapheadingzzz
-}
-
-\def\chapheading{\chapbreak \parsearg\chapheadingzzz}
-\def\chapheadingzzz#1{%
-  \vbox{\chapfonts \raggedtitlesettings #1\par}%
-  \nobreak\bigskip \nobreak
-  \suppressfirstparagraphindent
-}
-
-% @heading, @subheading, @subsubheading.
-\parseargdef\heading{\sectionheading{#1}{sec}{Yomitfromtoc}{}
-  \suppressfirstparagraphindent}
-\parseargdef\subheading{\sectionheading{#1}{subsec}{Yomitfromtoc}{}
-  \suppressfirstparagraphindent}
-\parseargdef\subsubheading{\sectionheading{#1}{subsubsec}{Yomitfromtoc}{}
-  \suppressfirstparagraphindent}
-
-% These macros generate a chapter, section, etc. heading only
-% (including whitespace, linebreaking, etc. around it),
-% given all the information in convenient, parsed form.
-
-% Args are the skip and penalty (usually negative)
-\def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi}
-
-% Parameter controlling skip before chapter headings (if needed)
-\newskip\chapheadingskip
-
-% Define plain chapter starts, and page on/off switching for it.
-\def\chapbreak{\dobreak \chapheadingskip {-4000}}
-\def\chappager{\par\vfill\supereject}
-% Because \domark is called before \chapoddpage, the filler page will
-% get the headings for the next chapter, which is wrong.  But we don't
-% care -- we just disable all headings on the filler page.
-\def\chapoddpage{%
-  \chappager
-  \ifodd\pageno \else
-    \begingroup
-      \headingsoff
-      \null
-      \chappager
-    \endgroup
-  \fi
-}
-
-\def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname}
-
-\def\CHAPPAGoff{%
-\global\let\contentsalignmacro = \chappager
-\global\let\pchapsepmacro=\chapbreak
-\global\let\pagealignmacro=\chappager}
-
-\def\CHAPPAGon{%
-\global\let\contentsalignmacro = \chappager
-\global\let\pchapsepmacro=\chappager
-\global\let\pagealignmacro=\chappager
-\global\def\HEADINGSon{\HEADINGSsingle}}
-
-\def\CHAPPAGodd{%
-\global\let\contentsalignmacro = \chapoddpage
-\global\let\pchapsepmacro=\chapoddpage
-\global\let\pagealignmacro=\chapoddpage
-\global\def\HEADINGSon{\HEADINGSdouble}}
-
-\CHAPPAGon
-
-% Chapter opening.
-%
-% #1 is the text, #2 is the section type (Ynumbered, Ynothing,
-% Yappendix, Yomitfromtoc), #3 the chapter number.
-%
-% To test against our argument.
-\def\Ynothingkeyword{Ynothing}
-\def\Yomitfromtockeyword{Yomitfromtoc}
-\def\Yappendixkeyword{Yappendix}
-%
-\def\chapmacro#1#2#3{%
-  % Insert the first mark before the heading break (see notes for \domark).
-  \let\prevchapterdefs=\lastchapterdefs
-  \let\prevsectiondefs=\lastsectiondefs
-  \gdef\lastsectiondefs{\gdef\thissectionname{}\gdef\thissectionnum{}%
-                        \gdef\thissection{}}%
-  %
-  \def\temptype{#2}%
-  \ifx\temptype\Ynothingkeyword
-    \gdef\lastchapterdefs{\gdef\thischaptername{#1}\gdef\thischapternum{}%
-                          \gdef\thischapter{\thischaptername}}%
-  \else\ifx\temptype\Yomitfromtockeyword
-    \gdef\lastchapterdefs{\gdef\thischaptername{#1}\gdef\thischapternum{}%
-                          \gdef\thischapter{}}%
-  \else\ifx\temptype\Yappendixkeyword
-    \toks0={#1}%
-    \xdef\lastchapterdefs{%
-      \gdef\noexpand\thischaptername{\the\toks0}%
-      \gdef\noexpand\thischapternum{\appendixletter}%
-      % \noexpand\putwordAppendix avoids expanding indigestible
-      % commands in some of the translations.
-      \gdef\noexpand\thischapter{\noexpand\putwordAppendix{}
-                                 \noexpand\thischapternum:
-                                 \noexpand\thischaptername}%
-    }%
-  \else
-    \toks0={#1}%
-    \xdef\lastchapterdefs{%
-      \gdef\noexpand\thischaptername{\the\toks0}%
-      \gdef\noexpand\thischapternum{\the\chapno}%
-      % \noexpand\putwordChapter avoids expanding indigestible
-      % commands in some of the translations.
-      \gdef\noexpand\thischapter{\noexpand\putwordChapter{}
-                                 \noexpand\thischapternum:
-                                 \noexpand\thischaptername}%
-    }%
-  \fi\fi\fi
-  %
-  % Output the mark.  Pass it through \safewhatsit, to take care of
-  % the preceding space.
-  \safewhatsit\domark
-  %
-  % Insert the chapter heading break.
-  \pchapsepmacro
-  %
-  % Now the second mark, after the heading break.  No break points
-  % between here and the heading.
-  \let\prevchapterdefs=\lastchapterdefs
-  \let\prevsectiondefs=\lastsectiondefs
-  \domark
-  %
-  {%
-    \chapfonts \rmisbold
-    %
-    % Have to define \lastsection before calling \donoderef, because the
-    % xref code eventually uses it.  On the other hand, it has to be called
-    % after \pchapsepmacro, or the headline will change too soon.
-    \gdef\lastsection{#1}%
-    %
-    % Only insert the separating space if we have a chapter/appendix
-    % number, and don't print the unnumbered ``number''.
-    \ifx\temptype\Ynothingkeyword
-      \setbox0 = \hbox{}%
-      \def\toctype{unnchap}%
-    \else\ifx\temptype\Yomitfromtockeyword
-      \setbox0 = \hbox{}% contents like unnumbered, but no toc entry
-      \def\toctype{omit}%
-    \else\ifx\temptype\Yappendixkeyword
-      \setbox0 = \hbox{\putwordAppendix{} #3\enspace}%
-      \def\toctype{app}%
-    \else
-      \setbox0 = \hbox{#3\enspace}%
-      \def\toctype{numchap}%
-    \fi\fi\fi
-    %
-    % Write the toc entry for this chapter.  Must come before the
-    % \donoderef, because we include the current node name in the toc
-    % entry, and \donoderef resets it to empty.
-    \writetocentry{\toctype}{#1}{#3}%
-    %
-    % For pdftex, we have to write out the node definition (aka, make
-    % the pdfdest) after any page break, but before the actual text has
-    % been typeset.  If the destination for the pdf outline is after the
-    % text, then jumping from the outline may wind up with the text not
-    % being visible, for instance under high magnification.
-    \donoderef{#2}%
-    %
-    % Typeset the actual heading.
-    \nobreak % Avoid page breaks at the interline glue.
-    \vbox{\raggedtitlesettings \hangindent=\wd0 \centerparametersmaybe
-          \unhbox0 #1\par}%
-  }%
-  \nobreak\bigskip % no page break after a chapter title
-  \nobreak
-}
-
-% @centerchap -- centered and unnumbered.
-\let\centerparametersmaybe = \relax
-\def\centerparameters{%
-  \advance\rightskip by 3\rightskip
-  \leftskip = \rightskip
-  \parfillskip = 0pt
-}
-
-
-% I don't think this chapter style is supported any more, so I'm not
-% updating it with the new noderef stuff.  We'll see.  --karl, 11aug03.
-%
-\def\setchapterstyle #1 {\csname CHAPF#1\endcsname}
-%
-\def\unnchfopen #1{%
-  \chapoddpage
-  \vbox{\chapfonts \raggedtitlesettings #1\par}%
-  \nobreak\bigskip\nobreak
-}
-\def\chfopen #1#2{\chapoddpage {\chapfonts
-\vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}%
-\par\penalty 5000 %
-}
-\def\centerchfopen #1{%
-  \chapoddpage
-  \vbox{\chapfonts \raggedtitlesettings \hfill #1\hfill}%
-  \nobreak\bigskip \nobreak
-}
-\def\CHAPFopen{%
-  \global\let\chapmacro=\chfopen
-  \global\let\centerchapmacro=\centerchfopen}
-
-
-% Section titles.  These macros combine the section number parts and
-% call the generic \sectionheading to do the printing.
-%
-\newskip\secheadingskip
-\def\secheadingbreak{\dobreak \secheadingskip{-1000}}
-
-% Subsection titles.
-\newskip\subsecheadingskip
-\def\subsecheadingbreak{\dobreak \subsecheadingskip{-500}}
-
-% Subsubsection titles.
-\def\subsubsecheadingskip{\subsecheadingskip}
-\def\subsubsecheadingbreak{\subsecheadingbreak}
-
-
-% Print any size, any type, section title.
-%
-% #1 is the text, #2 is the section level (sec/subsec/subsubsec), #3 is
-% the section type for xrefs (Ynumbered, Ynothing, Yappendix), #4 is the
-% section number.
-%
-\def\seckeyword{sec}
-%
-\def\sectionheading#1#2#3#4{%
-  {%
-    \checkenv{}% should not be in an environment.
-    %
-    % Switch to the right set of fonts.
-    \csname #2fonts\endcsname \rmisbold
-    %
-    \def\sectionlevel{#2}%
-    \def\temptype{#3}%
-    %
-    % Insert first mark before the heading break (see notes for \domark).
-    \let\prevsectiondefs=\lastsectiondefs
-    \ifx\temptype\Ynothingkeyword
-      \ifx\sectionlevel\seckeyword
-        \gdef\lastsectiondefs{\gdef\thissectionname{#1}\gdef\thissectionnum{}%
-                              \gdef\thissection{\thissectionname}}%
-      \fi
-    \else\ifx\temptype\Yomitfromtockeyword
-      % Don't redefine \thissection.
-    \else\ifx\temptype\Yappendixkeyword
-      \ifx\sectionlevel\seckeyword
-        \toks0={#1}%
-        \xdef\lastsectiondefs{%
-          \gdef\noexpand\thissectionname{\the\toks0}%
-          \gdef\noexpand\thissectionnum{#4}%
-          % \noexpand\putwordSection avoids expanding indigestible
-          % commands in some of the translations.
-          \gdef\noexpand\thissection{\noexpand\putwordSection{}
-                                     \noexpand\thissectionnum:
-                                     \noexpand\thissectionname}%
-        }%
-      \fi
-    \else
-      \ifx\sectionlevel\seckeyword
-        \toks0={#1}%
-        \xdef\lastsectiondefs{%
-          \gdef\noexpand\thissectionname{\the\toks0}%
-          \gdef\noexpand\thissectionnum{#4}%
-          % \noexpand\putwordSection avoids expanding indigestible
-          % commands in some of the translations.
-          \gdef\noexpand\thissection{\noexpand\putwordSection{}
-                                     \noexpand\thissectionnum:
-                                     \noexpand\thissectionname}%
-        }%
-      \fi
-    \fi\fi\fi
-    %
-    % Go into vertical mode.  Usually we'll already be there, but we
-    % don't want the following whatsit to end up in a preceding paragraph
-    % if the document didn't happen to have a blank line.
-    \par
-    %
-    % Output the mark.  Pass it through \safewhatsit, to take care of
-    % the preceding space.
-    \safewhatsit\domark
-    %
-    % Insert space above the heading.
-    \csname #2headingbreak\endcsname
-    %
-    % Now the second mark, after the heading break.  No break points
-    % between here and the heading.
-    \let\prevsectiondefs=\lastsectiondefs
-    \domark
-    %
-    % Only insert the space after the number if we have a section number.
-    \ifx\temptype\Ynothingkeyword
-      \setbox0 = \hbox{}%
-      \def\toctype{unn}%
-      \gdef\lastsection{#1}%
-    \else\ifx\temptype\Yomitfromtockeyword
-      % for @headings -- no section number, don't include in toc,
-      % and don't redefine \lastsection.
-      \setbox0 = \hbox{}%
-      \def\toctype{omit}%
-      \let\sectionlevel=\empty
-    \else\ifx\temptype\Yappendixkeyword
-      \setbox0 = \hbox{#4\enspace}%
-      \def\toctype{app}%
-      \gdef\lastsection{#1}%
-    \else
-      \setbox0 = \hbox{#4\enspace}%
-      \def\toctype{num}%
-      \gdef\lastsection{#1}%
-    \fi\fi\fi
-    %
-    % Write the toc entry (before \donoderef).  See comments in \chapmacro.
-    \writetocentry{\toctype\sectionlevel}{#1}{#4}%
-    %
-    % Write the node reference (= pdf destination for pdftex).
-    % Again, see comments in \chapmacro.
-    \donoderef{#3}%
-    %
-    % Interline glue will be inserted when the vbox is completed.
-    % That glue will be a valid breakpoint for the page, since it'll be
-    % preceded by a whatsit (usually from the \donoderef, or from the
-    % \writetocentry if there was no node).  We don't want to allow that
-    % break, since then the whatsits could end up on page n while the
-    % section is on page n+1, thus toc/etc. are wrong.  Debian bug 276000.
-    \nobreak
-    %
-    % Output the actual section heading.
-    \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \ptexraggedright
-          \hangindent=\wd0  % zero if no section number
-          \unhbox0 #1}%
-  }%
-  % Add extra space after the heading -- half of whatever came above it.
-  % Don't allow stretch, though.
-  \kern .5 \csname #2headingskip\endcsname
-  %
-  % Do not let the kern be a potential breakpoint, as it would be if it
-  % was followed by glue.
-  \nobreak
-  %
-  % We'll almost certainly start a paragraph next, so don't let that
-  % glue accumulate.  (Not a breakpoint because it's preceded by a
-  % discardable item.)  However, when a paragraph is not started next
-  % (\startdefun, \cartouche, \center, etc.), this needs to be wiped out
-  % or the negative glue will cause weirdly wrong output, typically
-  % obscuring the section heading with something else.
-  \vskip-\parskip
-  %
-  % This is so the last item on the main vertical list is a known
-  % \penalty > 10000, so \startdefun, etc., can recognize the situation
-  % and do the needful.
-  \penalty 10001
-}
-
-
-\message{toc,}
-% Table of contents.
-\newwrite\tocfile
-
-% Write an entry to the toc file, opening it if necessary.
-% Called from @chapter, etc.
-%
-% Example usage: \writetocentry{sec}{Section Name}{\the\chapno.\the\secno}
-% We append the current node name (if any) and page number as additional
-% arguments for the \{chap,sec,...}entry macros which will eventually
-% read this.  The node name is used in the pdf outlines as the
-% destination to jump to.
-%
-% We open the .toc file for writing here instead of at @setfilename (or
-% any other fixed time) so that @contents can be anywhere in the document.
-% But if #1 is `omit', then we don't do anything.  This is used for the
-% table of contents chapter openings themselves.
-%
-\newif\iftocfileopened
-\def\omitkeyword{omit}%
-%
-\def\writetocentry#1#2#3{%
-  \edef\writetoctype{#1}%
-  \ifx\writetoctype\omitkeyword \else
-    \iftocfileopened\else
-      \immediate\openout\tocfile = \jobname.toc
-      \global\tocfileopenedtrue
-    \fi
-    %
-    \iflinks
-      {\atdummies
-       \edef\temp{%
-         \write\tocfile{@#1entry{#2}{#3}{\lastnode}{\noexpand\folio}}}%
-       \temp
-      }%
-    \fi
-  \fi
-  %
-  % Tell \shipout to create a pdf destination on each page, if we're
-  % writing pdf.  These are used in the table of contents.  We can't
-  % just write one on every page because the title pages are numbered
-  % 1 and 2 (the page numbers aren't printed), and so are the first
-  % two pages of the document.  Thus, we'd have two destinations named
-  % `1', and two named `2'.
-  \ifpdf \global\pdfmakepagedesttrue \fi
-}
-
-
-% These characters do not print properly in the Computer Modern roman
-% fonts, so we must take special care.  This is more or less redundant
-% with the Texinfo input format setup at the end of this file.
-%
-\def\activecatcodes{%
-  \catcode`\"=\active
-  \catcode`\$=\active
-  \catcode`\<=\active
-  \catcode`\>=\active
-  \catcode`\\=\active
-  \catcode`\^=\active
-  \catcode`\_=\active
-  \catcode`\|=\active
-  \catcode`\~=\active
-}
-
-
-% Read the toc file, which is essentially Texinfo input.
-\def\readtocfile{%
-  \setupdatafile
-  \activecatcodes
-  \input \tocreadfilename
-}
-
-\newskip\contentsrightmargin \contentsrightmargin=1in
-\newcount\savepageno
-\newcount\lastnegativepageno \lastnegativepageno = -1
-
-% Prepare to read what we've written to \tocfile.
-%
-\def\startcontents#1{%
-  % If @setchapternewpage on, and @headings double, the contents should
-  % start on an odd page, unlike chapters.  Thus, we maintain
-  % \contentsalignmacro in parallel with \pagealignmacro.
-  % From: Torbjorn Granlund <tege@matematik.su.se>
-  \contentsalignmacro
-  \immediate\closeout\tocfile
-  %
-  % Don't need to put `Contents' or `Short Contents' in the headline.
-  % It is abundantly clear what they are.
-  \chapmacro{#1}{Yomitfromtoc}{}%
-  %
-  \savepageno = \pageno
-  \begingroup                  % Set up to handle contents files properly.
-    \raggedbottom              % Worry more about breakpoints than the bottom.
-    \advance\hsize by -\contentsrightmargin % Don't use the full line length.
-    %
-    % Roman numerals for page numbers.
-    \ifnum \pageno>0 \global\pageno = \lastnegativepageno \fi
-}
-
-% redefined for the two-volume lispref.  We always output on
-% \jobname.toc even if this is redefined.
-%
-\def\tocreadfilename{\jobname.toc}
-
-% Normal (long) toc.
-%
-\def\contents{%
-  \startcontents{\putwordTOC}%
-    \openin 1 \tocreadfilename\space
-    \ifeof 1 \else
-      \readtocfile
-    \fi
-    \vfill \eject
-    \contentsalignmacro % in case @setchapternewpage odd is in effect
-    \ifeof 1 \else
-      \pdfmakeoutlines
-    \fi
-    \closein 1
-  \endgroup
-  \lastnegativepageno = \pageno
-  \global\pageno = \savepageno
-}
-
-% And just the chapters.
-\def\summarycontents{%
-  \startcontents{\putwordShortTOC}%
-    %
-    \let\partentry = \shortpartentry
-    \let\numchapentry = \shortchapentry
-    \let\appentry = \shortchapentry
-    \let\unnchapentry = \shortunnchapentry
-    % We want a true roman here for the page numbers.
-    \secfonts
-    \let\rm=\shortcontrm \let\bf=\shortcontbf
-    \let\sl=\shortcontsl \let\tt=\shortconttt
-    \rm
-    \hyphenpenalty = 10000
-    \advance\baselineskip by 1pt % Open it up a little.
-    \def\numsecentry##1##2##3##4{}
-    \let\appsecentry = \numsecentry
-    \let\unnsecentry = \numsecentry
-    \let\numsubsecentry = \numsecentry
-    \let\appsubsecentry = \numsecentry
-    \let\unnsubsecentry = \numsecentry
-    \let\numsubsubsecentry = \numsecentry
-    \let\appsubsubsecentry = \numsecentry
-    \let\unnsubsubsecentry = \numsecentry
-    \openin 1 \tocreadfilename\space
-    \ifeof 1 \else
-      \readtocfile
-    \fi
-    \closein 1
-    \vfill \eject
-    \contentsalignmacro % in case @setchapternewpage odd is in effect
-  \endgroup
-  \lastnegativepageno = \pageno
-  \global\pageno = \savepageno
-}
-\let\shortcontents = \summarycontents
-
-% Typeset the label for a chapter or appendix for the short contents.
-% The arg is, e.g., `A' for an appendix, or `3' for a chapter.
-%
-\def\shortchaplabel#1{%
-  % This space should be enough, since a single number is .5em, and the
-  % widest letter (M) is 1em, at least in the Computer Modern fonts.
-  % But use \hss just in case.
-  % (This space doesn't include the extra space that gets added after
-  % the label; that gets put in by \shortchapentry above.)
-  %
-  % We'd like to right-justify chapter numbers, but that looks strange
-  % with appendix letters.  And right-justifying numbers and
-  % left-justifying letters looks strange when there is less than 10
-  % chapters.  Have to read the whole toc once to know how many chapters
-  % there are before deciding ...
-  \hbox to 1em{#1\hss}%
-}
-
-% These macros generate individual entries in the table of contents.
-% The first argument is the chapter or section name.
-% The last argument is the page number.
-% The arguments in between are the chapter number, section number, ...
-
-% Parts, in the main contents.  Replace the part number, which doesn't
-% exist, with an empty box.  Let's hope all the numbers have the same width.
-% Also ignore the page number, which is conventionally not printed.
-\def\numeralbox{\setbox0=\hbox{8}\hbox to \wd0{\hfil}}
-\def\partentry#1#2#3#4{\dochapentry{\numeralbox\labelspace#1}{}}
-%
-% Parts, in the short toc.
-\def\shortpartentry#1#2#3#4{%
-  \penalty-300
-  \vskip.5\baselineskip plus.15\baselineskip minus.1\baselineskip
-  \shortchapentry{{\bf #1}}{\numeralbox}{}{}%
-}
-
-% Chapters, in the main contents.
-\def\numchapentry#1#2#3#4{\dochapentry{#2\labelspace#1}{#4}}
-%
-% Chapters, in the short toc.
-% See comments in \dochapentry re vbox and related settings.
-\def\shortchapentry#1#2#3#4{%
-  \tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#4\egroup}%
-}
-
-% Appendices, in the main contents.
-% Need the word Appendix, and a fixed-size box.
-%
-\def\appendixbox#1{%
-  % We use M since it's probably the widest letter.
-  \setbox0 = \hbox{\putwordAppendix{} M}%
-  \hbox to \wd0{\putwordAppendix{} #1\hss}}
-%
-\def\appentry#1#2#3#4{\dochapentry{\appendixbox{#2}\labelspace#1}{#4}}
-
-% Unnumbered chapters.
-\def\unnchapentry#1#2#3#4{\dochapentry{#1}{#4}}
-\def\shortunnchapentry#1#2#3#4{\tocentry{#1}{\doshortpageno\bgroup#4\egroup}}
-
-% Sections.
-\def\numsecentry#1#2#3#4{\dosecentry{#2\labelspace#1}{#4}}
-\let\appsecentry=\numsecentry
-\def\unnsecentry#1#2#3#4{\dosecentry{#1}{#4}}
-
-% Subsections.
-\def\numsubsecentry#1#2#3#4{\dosubsecentry{#2\labelspace#1}{#4}}
-\let\appsubsecentry=\numsubsecentry
-\def\unnsubsecentry#1#2#3#4{\dosubsecentry{#1}{#4}}
-
-% And subsubsections.
-\def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#2\labelspace#1}{#4}}
-\let\appsubsubsecentry=\numsubsubsecentry
-\def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#4}}
-
-% This parameter controls the indentation of the various levels.
-% Same as \defaultparindent.
-\newdimen\tocindent \tocindent = 15pt
-
-% Now for the actual typesetting. In all these, #1 is the text and #2 is the
-% page number.
-%
-% If the toc has to be broken over pages, we want it to be at chapters
-% if at all possible; hence the \penalty.
-\def\dochapentry#1#2{%
-   \penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip
-   \begingroup
-     \chapentryfonts
-     \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-   \endgroup
-   \nobreak\vskip .25\baselineskip plus.1\baselineskip
-}
-
-\def\dosecentry#1#2{\begingroup
-  \secentryfonts \leftskip=\tocindent
-  \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-\endgroup}
-
-\def\dosubsecentry#1#2{\begingroup
-  \subsecentryfonts \leftskip=2\tocindent
-  \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-\endgroup}
-
-\def\dosubsubsecentry#1#2{\begingroup
-  \subsubsecentryfonts \leftskip=3\tocindent
-  \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-\endgroup}
-
-% We use the same \entry macro as for the index entries.
-\let\tocentry = \entry
-
-% Space between chapter (or whatever) number and the title.
-\def\labelspace{\hskip1em \relax}
-
-\def\dopageno#1{{\rm #1}}
-\def\doshortpageno#1{{\rm #1}}
-
-\def\chapentryfonts{\secfonts \rm}
-\def\secentryfonts{\textfonts}
-\def\subsecentryfonts{\textfonts}
-\def\subsubsecentryfonts{\textfonts}
-
-
-\message{environments,}
-% @foo ... @end foo.
-
-% @tex ... @end tex    escapes into raw TeX temporarily.
-% One exception: @ is still an escape character, so that @end tex works.
-% But \@ or @@ will get a plain @ character.
-
-\envdef\tex{%
-  \setupmarkupstyle{tex}%
-  \catcode `\\=0 \catcode `\{=1 \catcode `\}=2
-  \catcode `\$=3 \catcode `\&=4 \catcode `\#=6
-  \catcode `\^=7 \catcode `\_=8 \catcode `\~=\active \let~=\tie
-  \catcode `\%=14
-  \catcode `\+=\other
-  \catcode `\"=\other
-  \catcode `\|=\other
-  \catcode `\<=\other
-  \catcode `\>=\other
-  \catcode`\`=\other
-  \catcode`\'=\other
-  \escapechar=`\\
-  %
-  % ' is active in math mode (mathcode"8000).  So reset it, and all our
-  % other math active characters (just in case), to plain's definitions.
-  \mathactive
-  %
-  \let\b=\ptexb
-  \let\bullet=\ptexbullet
-  \let\c=\ptexc
-  \let\,=\ptexcomma
-  \let\.=\ptexdot
-  \let\dots=\ptexdots
-  \let\equiv=\ptexequiv
-  \let\!=\ptexexclam
-  \let\i=\ptexi
-  \let\indent=\ptexindent
-  \let\noindent=\ptexnoindent
-  \let\{=\ptexlbrace
-  \let\+=\tabalign
-  \let\}=\ptexrbrace
-  \let\/=\ptexslash
-  \let\*=\ptexstar
-  \let\t=\ptext
-  \expandafter \let\csname top\endcsname=\ptextop  % outer
-  \let\frenchspacing=\plainfrenchspacing
-  %
-  \def\endldots{\mathinner{\ldots\ldots\ldots\ldots}}%
-  \def\enddots{\relax\ifmmode\endldots\else$\mathsurround=0pt \endldots\,$\fi}%
-  \def\@{@}%
-}
-% There is no need to define \Etex.
-
-% Define @lisp ... @end lisp.
-% @lisp environment forms a group so it can rebind things,
-% including the definition of @end lisp (which normally is erroneous).
-
-% Amount to narrow the margins by for @lisp.
-\newskip\lispnarrowing \lispnarrowing=0.4in
-
-% This is the definition that ^^M gets inside @lisp, @example, and other
-% such environments.  \null is better than a space, since it doesn't
-% have any width.
-\def\lisppar{\null\endgraf}
-
-% This space is always present above and below environments.
-\newskip\envskipamount \envskipamount = 0pt
-
-% Make spacing and below environment symmetrical.  We use \parskip here
-% to help in doing that, since in @example-like environments \parskip
-% is reset to zero; thus the \afterenvbreak inserts no space -- but the
-% start of the next paragraph will insert \parskip.
-%
-\def\aboveenvbreak{{%
-  % =10000 instead of <10000 because of a special case in \itemzzz and
-  % \sectionheading, q.v.
-  \ifnum \lastpenalty=10000 \else
-    \advance\envskipamount by \parskip
-    \endgraf
-    \ifdim\lastskip<\envskipamount
-      \removelastskip
-      % it's not a good place to break if the last penalty was \nobreak
-      % or better ...
-      \ifnum\lastpenalty<10000 \penalty-50 \fi
-      \vskip\envskipamount
-    \fi
-  \fi
-}}
-
-\let\afterenvbreak = \aboveenvbreak
-
-% \nonarrowing is a flag.  If "set", @lisp etc don't narrow margins; it will
-% also clear it, so that its embedded environments do the narrowing again.
-\let\nonarrowing=\relax
-
-% @cartouche ... @end cartouche: draw rectangle w/rounded corners around
-% environment contents.
-\font\circle=lcircle10
-\newdimen\circthick
-\newdimen\cartouter\newdimen\cartinner
-\newskip\normbskip\newskip\normpskip\newskip\normlskip
-\circthick=\fontdimen8\circle
-%
-\def\ctl{{\circle\char'013\hskip -6pt}}% 6pt from pl file: 1/2charwidth
-\def\ctr{{\hskip 6pt\circle\char'010}}
-\def\cbl{{\circle\char'012\hskip -6pt}}
-\def\cbr{{\hskip 6pt\circle\char'011}}
-\def\carttop{\hbox to \cartouter{\hskip\lskip
-        \ctl\leaders\hrule height\circthick\hfil\ctr
-        \hskip\rskip}}
-\def\cartbot{\hbox to \cartouter{\hskip\lskip
-        \cbl\leaders\hrule height\circthick\hfil\cbr
-        \hskip\rskip}}
-%
-\newskip\lskip\newskip\rskip
-
-\envdef\cartouche{%
-  \ifhmode\par\fi  % can't be in the midst of a paragraph.
-  \startsavinginserts
-  \lskip=\leftskip \rskip=\rightskip
-  \leftskip=0pt\rightskip=0pt % we want these *outside*.
-  \cartinner=\hsize \advance\cartinner by-\lskip
-  \advance\cartinner by-\rskip
-  \cartouter=\hsize
-  \advance\cartouter by 18.4pt	% allow for 3pt kerns on either
-				% side, and for 6pt waste from
-				% each corner char, and rule thickness
-  \normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip
-  % Flag to tell @lisp, etc., not to narrow margin.
-  \let\nonarrowing = t%
-  %
-  % If this cartouche directly follows a sectioning command, we need the
-  % \parskip glue (backspaced over by default) or the cartouche can
-  % collide with the section heading.
-  \ifnum\lastpenalty>10000 \vskip\parskip \penalty\lastpenalty \fi
-  %
-  \vbox\bgroup
-      \baselineskip=0pt\parskip=0pt\lineskip=0pt
-      \carttop
-      \hbox\bgroup
-	  \hskip\lskip
-	  \vrule\kern3pt
-	  \vbox\bgroup
-	      \kern3pt
-	      \hsize=\cartinner
-	      \baselineskip=\normbskip
-	      \lineskip=\normlskip
-	      \parskip=\normpskip
-	      \vskip -\parskip
-	      \comment % For explanation, see the end of def\group.
-}
-\def\Ecartouche{%
-              \ifhmode\par\fi
-	      \kern3pt
-	  \egroup
-	  \kern3pt\vrule
-	  \hskip\rskip
-      \egroup
-      \cartbot
-  \egroup
-  \checkinserts
-}
-
-
-% This macro is called at the beginning of all the @example variants,
-% inside a group.
-\newdimen\nonfillparindent
-\def\nonfillstart{%
-  \aboveenvbreak
-  \hfuzz = 12pt % Don't be fussy
-  \sepspaces % Make spaces be word-separators rather than space tokens.
-  \let\par = \lisppar % don't ignore blank lines
-  \obeylines % each line of input is a line of output
-  \parskip = 0pt
-  % Turn off paragraph indentation but redefine \indent to emulate
-  % the normal \indent.
-  \nonfillparindent=\parindent
-  \parindent = 0pt
-  \let\indent\nonfillindent
-  %
-  \emergencystretch = 0pt % don't try to avoid overfull boxes
-  \ifx\nonarrowing\relax
-    \advance \leftskip by \lispnarrowing
-    \exdentamount=\lispnarrowing
-  \else
-    \let\nonarrowing = \relax
-  \fi
-  \let\exdent=\nofillexdent
-}
-
-\begingroup
-\obeyspaces
-% We want to swallow spaces (but not other tokens) after the fake
-% @indent in our nonfill-environments, where spaces are normally
-% active and set to @tie, resulting in them not being ignored after
-% @indent.
-\gdef\nonfillindent{\futurelet\temp\nonfillindentcheck}%
-\gdef\nonfillindentcheck{%
-\ifx\temp %
-\expandafter\nonfillindentgobble%
-\else%
-\leavevmode\nonfillindentbox%
-\fi%
-}%
-\endgroup
-\def\nonfillindentgobble#1{\nonfillindent}
-\def\nonfillindentbox{\hbox to \nonfillparindent{\hss}}
-
-% If you want all examples etc. small: @set dispenvsize small.
-% If you want even small examples the full size: @set dispenvsize nosmall.
-% This affects the following displayed environments:
-%    @example, @display, @format, @lisp
-%
-\def\smallword{small}
-\def\nosmallword{nosmall}
-\let\SETdispenvsize\relax
-\def\setnormaldispenv{%
-  \ifx\SETdispenvsize\smallword
-    % end paragraph for sake of leading, in case document has no blank
-    % line.  This is redundant with what happens in \aboveenvbreak, but
-    % we need to do it before changing the fonts, and it's inconvenient
-    % to change the fonts afterward.
-    \ifnum \lastpenalty=10000 \else \endgraf \fi
-    \smallexamplefonts \rm
-  \fi
-}
-\def\setsmalldispenv{%
-  \ifx\SETdispenvsize\nosmallword
-  \else
-    \ifnum \lastpenalty=10000 \else \endgraf \fi
-    \smallexamplefonts \rm
-  \fi
-}
-
-% We often define two environments, @foo and @smallfoo.
-% Let's do it in one command.  #1 is the env name, #2 the definition.
-\def\makedispenvdef#1#2{%
-  \expandafter\envdef\csname#1\endcsname {\setnormaldispenv #2}%
-  \expandafter\envdef\csname small#1\endcsname {\setsmalldispenv #2}%
-  \expandafter\let\csname E#1\endcsname \afterenvbreak
-  \expandafter\let\csname Esmall#1\endcsname \afterenvbreak
-}
-
-% Define two environment synonyms (#1 and #2) for an environment.
-\def\maketwodispenvdef#1#2#3{%
-  \makedispenvdef{#1}{#3}%
-  \makedispenvdef{#2}{#3}%
-}
-%
-% @lisp: indented, narrowed, typewriter font;
-% @example: same as @lisp.
-%
-% @smallexample and @smalllisp: use smaller fonts.
-% Originally contributed by Pavel@xerox.
-%
-\maketwodispenvdef{lisp}{example}{%
-  \nonfillstart
-  \tt\setupmarkupstyle{example}%
-  \let\kbdfont = \kbdexamplefont % Allow @kbd to do something special.
-  \gobble % eat return
-}
-% @display/@smalldisplay: same as @lisp except keep current font.
-%
-\makedispenvdef{display}{%
-  \nonfillstart
-  \gobble
-}
-
-% @format/@smallformat: same as @display except don't narrow margins.
-%
-\makedispenvdef{format}{%
-  \let\nonarrowing = t%
-  \nonfillstart
-  \gobble
-}
-
-% @flushleft: same as @format, but doesn't obey \SETdispenvsize.
-\envdef\flushleft{%
-  \let\nonarrowing = t%
-  \nonfillstart
-  \gobble
-}
-\let\Eflushleft = \afterenvbreak
-
-% @flushright.
-%
-\envdef\flushright{%
-  \let\nonarrowing = t%
-  \nonfillstart
-  \advance\leftskip by 0pt plus 1fill\relax
-  \gobble
-}
-\let\Eflushright = \afterenvbreak
-
-
-% @raggedright does more-or-less normal line breaking but no right
-% justification.  From plain.tex.
-\envdef\raggedright{%
-  \rightskip0pt plus2em \spaceskip.3333em \xspaceskip.5em\relax
-}
-\let\Eraggedright\par
-
-\envdef\raggedleft{%
-  \parindent=0pt \leftskip0pt plus2em
-  \spaceskip.3333em \xspaceskip.5em \parfillskip=0pt
-  \hbadness=10000 % Last line will usually be underfull, so turn off
-                  % badness reporting.
-}
-\let\Eraggedleft\par
-
-\envdef\raggedcenter{%
-  \parindent=0pt \rightskip0pt plus1em \leftskip0pt plus1em
-  \spaceskip.3333em \xspaceskip.5em \parfillskip=0pt
-  \hbadness=10000 % Last line will usually be underfull, so turn off
-                  % badness reporting.
-}
-\let\Eraggedcenter\par
-
-
-% @quotation does normal linebreaking (hence we can't use \nonfillstart)
-% and narrows the margins.  We keep \parskip nonzero in general, since
-% we're doing normal filling.  So, when using \aboveenvbreak and
-% \afterenvbreak, temporarily make \parskip 0.
-%
-\makedispenvdef{quotation}{\quotationstart}
-%
-\def\quotationstart{%
-  \indentedblockstart % same as \indentedblock, but increase right margin too.
-  \ifx\nonarrowing\relax
-    \advance\rightskip by \lispnarrowing
-  \fi
-  \parsearg\quotationlabel
-}
-
-% We have retained a nonzero parskip for the environment, since we're
-% doing normal filling.
-%
-\def\Equotation{%
-  \par
-  \ifx\quotationauthor\thisisundefined\else
-    % indent a bit.
-    \leftline{\kern 2\leftskip \sl ---\quotationauthor}%
-  \fi
-  {\parskip=0pt \afterenvbreak}%
-}
-\def\Esmallquotation{\Equotation}
-
-% If we're given an argument, typeset it in bold with a colon after.
-\def\quotationlabel#1{%
-  \def\temp{#1}%
-  \ifx\temp\empty \else
-    {\bf #1: }%
-  \fi
-}
-
-% @indentedblock is like @quotation, but indents only on the left and
-% has no optional argument.
-% 
-\makedispenvdef{indentedblock}{\indentedblockstart}
-%
-\def\indentedblockstart{%
-  {\parskip=0pt \aboveenvbreak}% because \aboveenvbreak inserts \parskip
-  \parindent=0pt
-  %
-  % @cartouche defines \nonarrowing to inhibit narrowing at next level down.
-  \ifx\nonarrowing\relax
-    \advance\leftskip by \lispnarrowing
-    \exdentamount = \lispnarrowing
-  \else
-    \let\nonarrowing = \relax
-  \fi
-}
-
-% Keep a nonzero parskip for the environment, since we're doing normal filling.
-%
-\def\Eindentedblock{%
-  \par
-  {\parskip=0pt \afterenvbreak}%
-}
-\def\Esmallindentedblock{\Eindentedblock}
-
-
-% LaTeX-like @verbatim...@end verbatim and @verb{<char>...<char>}
-% If we want to allow any <char> as delimiter,
-% we need the curly braces so that makeinfo sees the @verb command, eg:
-% `@verbx...x' would look like the '@verbx' command.  --janneke@gnu.org
-%
-% [Knuth]: Donald Ervin Knuth, 1996.  The TeXbook.
-%
-% [Knuth] p.344; only we need to do the other characters Texinfo sets
-% active too.  Otherwise, they get lost as the first character on a
-% verbatim line.
-\def\dospecials{%
-  \do\ \do\\\do\{\do\}\do\$\do\&%
-  \do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~%
-  \do\<\do\>\do\|\do\@\do+\do\"%
-  % Don't do the quotes -- if we do, @set txicodequoteundirected and
-  % @set txicodequotebacktick will not have effect on @verb and
-  % @verbatim, and ?` and !` ligatures won't get disabled.
-  %\do\`\do\'%
-}
-%
-% [Knuth] p. 380
-\def\uncatcodespecials{%
-  \def\do##1{\catcode`##1=\other}\dospecials}
-%
-% Setup for the @verb command.
-%
-% Eight spaces for a tab
-\begingroup
-  \catcode`\^^I=\active
-  \gdef\tabeightspaces{\catcode`\^^I=\active\def^^I{\ \ \ \ \ \ \ \ }}
-\endgroup
-%
-\def\setupverb{%
-  \tt  % easiest (and conventionally used) font for verbatim
-  \def\par{\leavevmode\endgraf}%
-  \setupmarkupstyle{verb}%
-  \tabeightspaces
-  % Respect line breaks,
-  % print special symbols as themselves, and
-  % make each space count
-  % must do in this order:
-  \obeylines \uncatcodespecials \sepspaces
-}
-
-% Setup for the @verbatim environment
-%
-% Real tab expansion.
-\newdimen\tabw \setbox0=\hbox{\tt\space} \tabw=8\wd0 % tab amount
-%
-% We typeset each line of the verbatim in an \hbox, so we can handle
-% tabs.  The \global is in case the verbatim line starts with an accent,
-% or some other command that starts with a begin-group.  Otherwise, the
-% entire \verbbox would disappear at the corresponding end-group, before
-% it is typeset.  Meanwhile, we can't have nested verbatim commands
-% (can we?), so the \global won't be overwriting itself.
-\newbox\verbbox
-\def\starttabbox{\global\setbox\verbbox=\hbox\bgroup}
-%
-\begingroup
-  \catcode`\^^I=\active
-  \gdef\tabexpand{%
-    \catcode`\^^I=\active
-    \def^^I{\leavevmode\egroup
-      \dimen\verbbox=\wd\verbbox % the width so far, or since the previous tab
-      \divide\dimen\verbbox by\tabw
-      \multiply\dimen\verbbox by\tabw % compute previous multiple of \tabw
-      \advance\dimen\verbbox by\tabw  % advance to next multiple of \tabw
-      \wd\verbbox=\dimen\verbbox \box\verbbox \starttabbox
-    }%
-  }
-\endgroup
-
-% start the verbatim environment.
-\def\setupverbatim{%
-  \let\nonarrowing = t%
-  \nonfillstart
-  \tt % easiest (and conventionally used) font for verbatim
-  % The \leavevmode here is for blank lines.  Otherwise, we would
-  % never \starttabox and the \egroup would end verbatim mode.
-  \def\par{\leavevmode\egroup\box\verbbox\endgraf}%
-  \tabexpand
-  \setupmarkupstyle{verbatim}%
-  % Respect line breaks,
-  % print special symbols as themselves, and
-  % make each space count.
-  % Must do in this order:
-  \obeylines \uncatcodespecials \sepspaces
-  \everypar{\starttabbox}%
-}
-
-% Do the @verb magic: verbatim text is quoted by unique
-% delimiter characters.  Before first delimiter expect a
-% right brace, after last delimiter expect closing brace:
-%
-%    \def\doverb'{'<char>#1<char>'}'{#1}
-%
-% [Knuth] p. 382; only eat outer {}
-\begingroup
-  \catcode`[=1\catcode`]=2\catcode`\{=\other\catcode`\}=\other
-  \gdef\doverb{#1[\def\next##1#1}[##1\endgroup]\next]
-\endgroup
-%
-\def\verb{\begingroup\setupverb\doverb}
-%
-%
-% Do the @verbatim magic: define the macro \doverbatim so that
-% the (first) argument ends when '@end verbatim' is reached, ie:
-%
-%     \def\doverbatim#1@end verbatim{#1}
-%
-% For Texinfo it's a lot easier than for LaTeX,
-% because texinfo's \verbatim doesn't stop at '\end{verbatim}':
-% we need not redefine '\', '{' and '}'.
-%
-% Inspired by LaTeX's verbatim command set [latex.ltx]
-%
-\begingroup
-  \catcode`\ =\active
-  \obeylines %
-  % ignore everything up to the first ^^M, that's the newline at the end
-  % of the @verbatim input line itself.  Otherwise we get an extra blank
-  % line in the output.
-  \xdef\doverbatim#1^^M#2@end verbatim{#2\noexpand\end\gobble verbatim}%
-  % We really want {...\end verbatim} in the body of the macro, but
-  % without the active space; thus we have to use \xdef and \gobble.
-\endgroup
-%
-\envdef\verbatim{%
-    \setupverbatim\doverbatim
-}
-\let\Everbatim = \afterenvbreak
-
-
-% @verbatiminclude FILE - insert text of file in verbatim environment.
-%
-\def\verbatiminclude{\parseargusing\filenamecatcodes\doverbatiminclude}
-%
-\def\doverbatiminclude#1{%
-  {%
-    \makevalueexpandable
-    \setupverbatim
-    \indexnofonts       % Allow `@@' and other weird things in file names.
-    \wlog{texinfo.tex: doing @verbatiminclude of #1^^J}%
-    \input #1
-    \afterenvbreak
-  }%
-}
-
-% @copying ... @end copying.
-% Save the text away for @insertcopying later.
-%
-% We save the uninterpreted tokens, rather than creating a box.
-% Saving the text in a box would be much easier, but then all the
-% typesetting commands (@smallbook, font changes, etc.) have to be done
-% beforehand -- and a) we want @copying to be done first in the source
-% file; b) letting users define the frontmatter in as flexible order as
-% possible is very desirable.
-%
-\def\copying{\checkenv{}\begingroup\scanargctxt\docopying}
-\def\docopying#1@end copying{\endgroup\def\copyingtext{#1}}
-%
-\def\insertcopying{%
-  \begingroup
-    \parindent = 0pt  % paragraph indentation looks wrong on title page
-    \scanexp\copyingtext
-  \endgroup
-}
-
-
-\message{defuns,}
-% @defun etc.
-
-\newskip\defbodyindent \defbodyindent=.4in
-\newskip\defargsindent \defargsindent=50pt
-\newskip\deflastargmargin \deflastargmargin=18pt
-\newcount\defunpenalty
-
-% Start the processing of @deffn:
-\def\startdefun{%
-  \ifnum\lastpenalty<10000
-    \medbreak
-    \defunpenalty=10003 % Will keep this @deffn together with the
-                        % following @def command, see below.
-  \else
-    % If there are two @def commands in a row, we'll have a \nobreak,
-    % which is there to keep the function description together with its
-    % header.  But if there's nothing but headers, we need to allow a
-    % break somewhere.  Check specifically for penalty 10002, inserted
-    % by \printdefunline, instead of 10000, since the sectioning
-    % commands also insert a nobreak penalty, and we don't want to allow
-    % a break between a section heading and a defun.
-    %
-    % As a further refinement, we avoid "club" headers by signalling
-    % with penalty of 10003 after the very first @deffn in the
-    % sequence (see above), and penalty of 10002 after any following
-    % @def command.
-    \ifnum\lastpenalty=10002 \penalty2000 \else \defunpenalty=10002 \fi
-    %
-    % Similarly, after a section heading, do not allow a break.
-    % But do insert the glue.
-    \medskip  % preceded by discardable penalty, so not a breakpoint
-  \fi
-  %
-  \parindent=0in
-  \advance\leftskip by \defbodyindent
-  \exdentamount=\defbodyindent
-}
-
-\def\dodefunx#1{%
-  % First, check whether we are in the right environment:
-  \checkenv#1%
-  %
-  % As above, allow line break if we have multiple x headers in a row.
-  % It's not a great place, though.
-  \ifnum\lastpenalty=10002 \penalty3000 \else \defunpenalty=10002 \fi
-  %
-  % And now, it's time to reuse the body of the original defun:
-  \expandafter\gobbledefun#1%
-}
-\def\gobbledefun#1\startdefun{}
-
-% \printdefunline \deffnheader{text}
-%
-\def\printdefunline#1#2{%
-  \begingroup
-    % call \deffnheader:
-    #1#2 \endheader
-    % common ending:
-    \interlinepenalty = 10000
-    \advance\rightskip by 0pt plus 1fil\relax
-    \endgraf
-    \nobreak\vskip -\parskip
-    \penalty\defunpenalty  % signal to \startdefun and \dodefunx
-    % Some of the @defun-type tags do not enable magic parentheses,
-    % rendering the following check redundant.  But we don't optimize.
-    \checkparencounts
-  \endgroup
-}
-
-\def\Edefun{\endgraf\medbreak}
-
-% \makedefun{deffn} creates \deffn, \deffnx and \Edeffn;
-% the only thing remaining is to define \deffnheader.
-%
-\def\makedefun#1{%
-  \expandafter\let\csname E#1\endcsname = \Edefun
-  \edef\temp{\noexpand\domakedefun
-    \makecsname{#1}\makecsname{#1x}\makecsname{#1header}}%
-  \temp
-}
-
-% \domakedefun \deffn \deffnx \deffnheader
-%
-% Define \deffn and \deffnx, without parameters.
-% \deffnheader has to be defined explicitly.
-%
-\def\domakedefun#1#2#3{%
-  \envdef#1{%
-    \startdefun
-    \doingtypefnfalse    % distinguish typed functions from all else
-    \parseargusing\activeparens{\printdefunline#3}%
-  }%
-  \def#2{\dodefunx#1}%
-  \def#3%
-}
-
-\newif\ifdoingtypefn       % doing typed function?
-\newif\ifrettypeownline    % typeset return type on its own line?
-
-% @deftypefnnewline on|off says whether the return type of typed functions
-% are printed on their own line.  This affects @deftypefn, @deftypefun,
-% @deftypeop, and @deftypemethod.
-% 
-\parseargdef\deftypefnnewline{%
-  \def\temp{#1}%
-  \ifx\temp\onword
-    \expandafter\let\csname SETtxideftypefnnl\endcsname
-      = \empty
-  \else\ifx\temp\offword
-    \expandafter\let\csname SETtxideftypefnnl\endcsname
-      = \relax
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @txideftypefnnl value `\temp',
-                must be on|off}%
-  \fi\fi
-}
-
-% Untyped functions:
-
-% @deffn category name args
-\makedefun{deffn}{\deffngeneral{}}
-
-% @deffn category class name args
-\makedefun{defop}#1 {\defopon{#1\ \putwordon}}
-
-% \defopon {category on}class name args
-\def\defopon#1#2 {\deffngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} }
-
-% \deffngeneral {subind}category name args
-%
-\def\deffngeneral#1#2 #3 #4\endheader{%
-  % Remember that \dosubind{fn}{foo}{} is equivalent to \doind{fn}{foo}.
-  \dosubind{fn}{\code{#3}}{#1}%
-  \defname{#2}{}{#3}\magicamp\defunargs{#4\unskip}%
-}
-
-% Typed functions:
-
-% @deftypefn category type name args
-\makedefun{deftypefn}{\deftypefngeneral{}}
-
-% @deftypeop category class type name args
-\makedefun{deftypeop}#1 {\deftypeopon{#1\ \putwordon}}
-
-% \deftypeopon {category on}class type name args
-\def\deftypeopon#1#2 {\deftypefngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} }
-
-% \deftypefngeneral {subind}category type name args
-%
-\def\deftypefngeneral#1#2 #3 #4 #5\endheader{%
-  \dosubind{fn}{\code{#4}}{#1}%
-  \doingtypefntrue
-  \defname{#2}{#3}{#4}\defunargs{#5\unskip}%
-}
-
-% Typed variables:
-
-% @deftypevr category type var args
-\makedefun{deftypevr}{\deftypecvgeneral{}}
-
-% @deftypecv category class type var args
-\makedefun{deftypecv}#1 {\deftypecvof{#1\ \putwordof}}
-
-% \deftypecvof {category of}class type var args
-\def\deftypecvof#1#2 {\deftypecvgeneral{\putwordof\ \code{#2}}{#1\ \code{#2}} }
-
-% \deftypecvgeneral {subind}category type var args
-%
-\def\deftypecvgeneral#1#2 #3 #4 #5\endheader{%
-  \dosubind{vr}{\code{#4}}{#1}%
-  \defname{#2}{#3}{#4}\defunargs{#5\unskip}%
-}
-
-% Untyped variables:
-
-% @defvr category var args
-\makedefun{defvr}#1 {\deftypevrheader{#1} {} }
-
-% @defcv category class var args
-\makedefun{defcv}#1 {\defcvof{#1\ \putwordof}}
-
-% \defcvof {category of}class var args
-\def\defcvof#1#2 {\deftypecvof{#1}#2 {} }
-
-% Types:
-
-% @deftp category name args
-\makedefun{deftp}#1 #2 #3\endheader{%
-  \doind{tp}{\code{#2}}%
-  \defname{#1}{}{#2}\defunargs{#3\unskip}%
-}
-
-% Remaining @defun-like shortcuts:
-\makedefun{defun}{\deffnheader{\putwordDeffunc} }
-\makedefun{defmac}{\deffnheader{\putwordDefmac} }
-\makedefun{defspec}{\deffnheader{\putwordDefspec} }
-\makedefun{deftypefun}{\deftypefnheader{\putwordDeffunc} }
-\makedefun{defvar}{\defvrheader{\putwordDefvar} }
-\makedefun{defopt}{\defvrheader{\putwordDefopt} }
-\makedefun{deftypevar}{\deftypevrheader{\putwordDefvar} }
-\makedefun{defmethod}{\defopon\putwordMethodon}
-\makedefun{deftypemethod}{\deftypeopon\putwordMethodon}
-\makedefun{defivar}{\defcvof\putwordInstanceVariableof}
-\makedefun{deftypeivar}{\deftypecvof\putwordInstanceVariableof}
-
-% \defname, which formats the name of the @def (not the args).
-% #1 is the category, such as "Function".
-% #2 is the return type, if any.
-% #3 is the function name.
-%
-% We are followed by (but not passed) the arguments, if any.
-%
-\def\defname#1#2#3{%
-  \par
-  % Get the values of \leftskip and \rightskip as they were outside the @def...
-  \advance\leftskip by -\defbodyindent
-  %
-  % Determine if we are typesetting the return type of a typed function
-  % on a line by itself.
-  \rettypeownlinefalse
-  \ifdoingtypefn  % doing a typed function specifically?
-    % then check user option for putting return type on its own line:
-    \expandafter\ifx\csname SETtxideftypefnnl\endcsname\relax \else
-      \rettypeownlinetrue
-    \fi
-  \fi
-  %
-  % How we'll format the category name.  Putting it in brackets helps
-  % distinguish it from the body text that may end up on the next line
-  % just below it.
-  \def\temp{#1}%
-  \setbox0=\hbox{\kern\deflastargmargin \ifx\temp\empty\else [\rm\temp]\fi}
-  %
-  % Figure out line sizes for the paragraph shape.  We'll always have at
-  % least two.
-  \tempnum = 2
-  %
-  % The first line needs space for \box0; but if \rightskip is nonzero,
-  % we need only space for the part of \box0 which exceeds it:
-  \dimen0=\hsize  \advance\dimen0 by -\wd0  \advance\dimen0 by \rightskip
-  %
-  % If doing a return type on its own line, we'll have another line.
-  \ifrettypeownline
-    \advance\tempnum by 1
-    \def\maybeshapeline{0in \hsize}%
-  \else
-    \def\maybeshapeline{}%
-  \fi
-  %
-  % The continuations:
-  \dimen2=\hsize  \advance\dimen2 by -\defargsindent
-  %
-  % The final paragraph shape:
-  \parshape \tempnum  0in \dimen0  \maybeshapeline  \defargsindent \dimen2
-  %
-  % Put the category name at the right margin.
-  \noindent
-  \hbox to 0pt{%
-    \hfil\box0 \kern-\hsize
-    % \hsize has to be shortened this way:
-    \kern\leftskip
-    % Intentionally do not respect \rightskip, since we need the space.
-  }%
-  %
-  % Allow all lines to be underfull without complaint:
-  \tolerance=10000 \hbadness=10000
-  \exdentamount=\defbodyindent
-  {%
-    % defun fonts. We use typewriter by default (used to be bold) because:
-    % . we're printing identifiers, they should be in tt in principle.
-    % . in languages with many accents, such as Czech or French, it's
-    %   common to leave accents off identifiers.  The result looks ok in
-    %   tt, but exceedingly strange in rm.
-    % . we don't want -- and --- to be treated as ligatures.
-    % . this still does not fix the ?` and !` ligatures, but so far no
-    %   one has made identifiers using them :).
-    \df \tt
-    \def\temp{#2}% text of the return type
-    \ifx\temp\empty\else
-      \tclose{\temp}% typeset the return type
-      \ifrettypeownline
-        % put return type on its own line; prohibit line break following:
-        \hfil\vadjust{\nobreak}\break  
-      \else
-        \space  % type on same line, so just followed by a space
-      \fi
-    \fi           % no return type
-    #3% output function name
-  }%
-  {\rm\enskip}% hskip 0.5 em of \tenrm
-  %
-  \boldbrax
-  % arguments will be output next, if any.
-}
-
-% Print arguments in slanted roman (not ttsl), inconsistently with using
-% tt for the name.  This is because literal text is sometimes needed in
-% the argument list (groff manual), and ttsl and tt are not very
-% distinguishable.  Prevent hyphenation at `-' chars.
-%
-\def\defunargs#1{%
-  % use sl by default (not ttsl),
-  % tt for the names.
-  \df \sl \hyphenchar\font=0
-  %
-  % On the other hand, if an argument has two dashes (for instance), we
-  % want a way to get ttsl.  We used to recommend @var for that, so
-  % leave the code in, but it's strange for @var to lead to typewriter.
-  % Nowadays we recommend @code, since the difference between a ttsl hyphen
-  % and a tt hyphen is pretty tiny.  @code also disables ?` !`.
-  \def\var##1{{\setupmarkupstyle{var}\ttslanted{##1}}}%
-  #1%
-  \sl\hyphenchar\font=45
-}
-
-% We want ()&[] to print specially on the defun line.
-%
-\def\activeparens{%
-  \catcode`\(=\active \catcode`\)=\active
-  \catcode`\[=\active \catcode`\]=\active
-  \catcode`\&=\active
-}
-
-% Make control sequences which act like normal parenthesis chars.
-\let\lparen = ( \let\rparen = )
-
-% Be sure that we always have a definition for `(', etc.  For example,
-% if the fn name has parens in it, \boldbrax will not be in effect yet,
-% so TeX would otherwise complain about undefined control sequence.
-{
-  \activeparens
-  \global\let(=\lparen \global\let)=\rparen
-  \global\let[=\lbrack \global\let]=\rbrack
-  \global\let& = \&
-
-  \gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb}
-  \gdef\magicamp{\let&=\amprm}
-}
-
-\newcount\parencount
-
-% If we encounter &foo, then turn on ()-hacking afterwards
-\newif\ifampseen
-\def\amprm#1 {\ampseentrue{\bf\&#1 }}
-
-\def\parenfont{%
-  \ifampseen
-    % At the first level, print parens in roman,
-    % otherwise use the default font.
-    \ifnum \parencount=1 \rm \fi
-  \else
-    % The \sf parens (in \boldbrax) actually are a little bolder than
-    % the contained text.  This is especially needed for [ and ] .
-    \sf
-  \fi
-}
-\def\infirstlevel#1{%
-  \ifampseen
-    \ifnum\parencount=1
-      #1%
-    \fi
-  \fi
-}
-\def\bfafterword#1 {#1 \bf}
-
-\def\opnr{%
-  \global\advance\parencount by 1
-  {\parenfont(}%
-  \infirstlevel \bfafterword
-}
-\def\clnr{%
-  {\parenfont)}%
-  \infirstlevel \sl
-  \global\advance\parencount by -1
-}
-
-\newcount\brackcount
-\def\lbrb{%
-  \global\advance\brackcount by 1
-  {\bf[}%
-}
-\def\rbrb{%
-  {\bf]}%
-  \global\advance\brackcount by -1
-}
-
-\def\checkparencounts{%
-  \ifnum\parencount=0 \else \badparencount \fi
-  \ifnum\brackcount=0 \else \badbrackcount \fi
-}
-% these should not use \errmessage; the glibc manual, at least, actually
-% has such constructs (when documenting function pointers).
-\def\badparencount{%
-  \message{Warning: unbalanced parentheses in @def...}%
-  \global\parencount=0
-}
-\def\badbrackcount{%
-  \message{Warning: unbalanced square brackets in @def...}%
-  \global\brackcount=0
-}
-
-
-\message{macros,}
-% @macro.
-
-% To do this right we need a feature of e-TeX, \scantokens,
-% which we arrange to emulate with a temporary file in ordinary TeX.
-\ifx\eTeXversion\thisisundefined
-  \newwrite\macscribble
-  \def\scantokens#1{%
-    \toks0={#1}%
-    \immediate\openout\macscribble=\jobname.tmp
-    \immediate\write\macscribble{\the\toks0}%
-    \immediate\closeout\macscribble
-    \input \jobname.tmp
-  }
-\fi
-
-\def\scanmacro#1{\begingroup
-  \newlinechar`\^^M
-  \let\xeatspaces\eatspaces
-  %
-  % Undo catcode changes of \startcontents and \doprintindex
-  % When called from @insertcopying or (short)caption, we need active
-  % backslash to get it printed correctly.  Previously, we had
-  % \catcode`\\=\other instead.  We'll see whether a problem appears
-  % with macro expansion.				--kasal, 19aug04
-  \catcode`\@=0 \catcode`\\=\active \escapechar=`\@
-  %
-  % ... and for \example:
-  \spaceisspace
-  %
-  % The \empty here causes a following catcode 5 newline to be eaten as
-  % part of reading whitespace after a control sequence.  It does not
-  % eat a catcode 13 newline.  There's no good way to handle the two
-  % cases (untried: maybe e-TeX's \everyeof could help, though plain TeX
-  % would then have different behavior).  See the Macro Details node in
-  % the manual for the workaround we recommend for macros and
-  % line-oriented commands.
-  % 
-  \scantokens{#1\empty}%
-\endgroup}
-
-\def\scanexp#1{%
-  \edef\temp{\noexpand\scanmacro{#1}}%
-  \temp
-}
-
-\newcount\paramno   % Count of parameters
-\newtoks\macname    % Macro name
-\newif\ifrecursive  % Is it recursive?
-
-% List of all defined macros in the form
-%    \definedummyword\macro1\definedummyword\macro2...
-% Currently is also contains all @aliases; the list can be split
-% if there is a need.
-\def\macrolist{}
-
-% Add the macro to \macrolist
-\def\addtomacrolist#1{\expandafter \addtomacrolistxxx \csname#1\endcsname}
-\def\addtomacrolistxxx#1{%
-     \toks0 = \expandafter{\macrolist\definedummyword#1}%
-     \xdef\macrolist{\the\toks0}%
-}
-
-% Utility routines.
-% This does \let #1 = #2, with \csnames; that is,
-%   \let \csname#1\endcsname = \csname#2\endcsname
-% (except of course we have to play expansion games).
-%
-\def\cslet#1#2{%
-  \expandafter\let
-  \csname#1\expandafter\endcsname
-  \csname#2\endcsname
-}
-
-% Trim leading and trailing spaces off a string.
-% Concepts from aro-bend problem 15 (see CTAN).
-{\catcode`\@=11
-\gdef\eatspaces #1{\expandafter\trim@\expandafter{#1 }}
-\gdef\trim@ #1{\trim@@ @#1 @ #1 @ @@}
-\gdef\trim@@ #1@ #2@ #3@@{\trim@@@\empty #2 @}
-\def\unbrace#1{#1}
-\unbrace{\gdef\trim@@@ #1 } #2@{#1}
-}
-
-% Trim a single trailing ^^M off a string.
-{\catcode`\^^M=\other \catcode`\Q=3%
-\gdef\eatcr #1{\eatcra #1Q^^MQ}%
-\gdef\eatcra#1^^MQ{\eatcrb#1Q}%
-\gdef\eatcrb#1Q#2Q{#1}%
-}
-
-% Macro bodies are absorbed as an argument in a context where
-% all characters are catcode 10, 11 or 12, except \ which is active
-% (as in normal texinfo). It is necessary to change the definition of \
-% to recognize macro arguments; this is the job of \mbodybackslash.
-%
-% Non-ASCII encodings make 8-bit characters active, so un-activate
-% them to avoid their expansion.  Must do this non-globally, to
-% confine the change to the current group.
-%
-% It's necessary to have hard CRs when the macro is executed. This is
-% done by making ^^M (\endlinechar) catcode 12 when reading the macro
-% body, and then making it the \newlinechar in \scanmacro.
-%
-\def\scanctxt{% used as subroutine
-  \catcode`\"=\other
-  \catcode`\+=\other
-  \catcode`\<=\other
-  \catcode`\>=\other
-  \catcode`\@=\other
-  \catcode`\^=\other
-  \catcode`\_=\other
-  \catcode`\|=\other
-  \catcode`\~=\other
-  \ifx\declaredencoding\ascii \else \setnonasciicharscatcodenonglobal\other \fi
-}
-
-\def\scanargctxt{% used for copying and captions, not macros.
-  \scanctxt
-  \catcode`\\=\other
-  \catcode`\^^M=\other
-}
-
-\def\macrobodyctxt{% used for @macro definitions
-  \scanctxt
-  \catcode`\{=\other
-  \catcode`\}=\other
-  \catcode`\^^M=\other
-  \usembodybackslash
-}
-
-\def\macroargctxt{% used when scanning invocations
-  \scanctxt
-  \catcode`\\=0
-}
-% why catcode 0 for \ in the above?  To recognize \\ \{ \} as "escapes"
-% for the single characters \ { }.  Thus, we end up with the "commands"
-% that would be written @\ @{ @} in a Texinfo document.
-% 
-% We already have @{ and @}.  For @\, we define it here, and only for
-% this purpose, to produce a typewriter backslash (so, the @\ that we
-% define for @math can't be used with @macro calls):
-%
-\def\\{\normalbackslash}%
-% 
-% We would like to do this for \, too, since that is what makeinfo does.
-% But it is not possible, because Texinfo already has a command @, for a
-% cedilla accent.  Documents must use @comma{} instead.
-%
-% \anythingelse will almost certainly be an error of some kind.
-
-
-% \mbodybackslash is the definition of \ in @macro bodies.
-% It maps \foo\ => \csname macarg.foo\endcsname => #N
-% where N is the macro parameter number.
-% We define \csname macarg.\endcsname to be \realbackslash, so
-% \\ in macro replacement text gets you a backslash.
-%
-{\catcode`@=0 @catcode`@\=@active
- @gdef@usembodybackslash{@let\=@mbodybackslash}
- @gdef@mbodybackslash#1\{@csname macarg.#1@endcsname}
-}
-\expandafter\def\csname macarg.\endcsname{\realbackslash}
-
-\def\margbackslash#1{\char`\#1 }
-
-\def\macro{\recursivefalse\parsearg\macroxxx}
-\def\rmacro{\recursivetrue\parsearg\macroxxx}
-
-\def\macroxxx#1{%
-  \getargs{#1}% now \macname is the macname and \argl the arglist
-  \ifx\argl\empty       % no arguments
-     \paramno=0\relax
-  \else
-     \expandafter\parsemargdef \argl;%
-     \if\paramno>256\relax
-       \ifx\eTeXversion\thisisundefined
-         \errhelp = \EMsimple
-         \errmessage{You need eTeX to compile a file with macros with more than 256 arguments}
-       \fi
-     \fi
-  \fi
-  \if1\csname ismacro.\the\macname\endcsname
-     \message{Warning: redefining \the\macname}%
-  \else
-     \expandafter\ifx\csname \the\macname\endcsname \relax
-     \else \errmessage{Macro name \the\macname\space already defined}\fi
-     \global\cslet{macsave.\the\macname}{\the\macname}%
-     \global\expandafter\let\csname ismacro.\the\macname\endcsname=1%
-     \addtomacrolist{\the\macname}%
-  \fi
-  \begingroup \macrobodyctxt
-  \ifrecursive \expandafter\parsermacbody
-  \else \expandafter\parsemacbody
-  \fi}
-
-\parseargdef\unmacro{%
-  \if1\csname ismacro.#1\endcsname
-    \global\cslet{#1}{macsave.#1}%
-    \global\expandafter\let \csname ismacro.#1\endcsname=0%
-    % Remove the macro name from \macrolist:
-    \begingroup
-      \expandafter\let\csname#1\endcsname \relax
-      \let\definedummyword\unmacrodo
-      \xdef\macrolist{\macrolist}%
-    \endgroup
-  \else
-    \errmessage{Macro #1 not defined}%
-  \fi
-}
-
-% Called by \do from \dounmacro on each macro.  The idea is to omit any
-% macro definitions that have been changed to \relax.
-%
-\def\unmacrodo#1{%
-  \ifx #1\relax
-    % remove this
-  \else
-    \noexpand\definedummyword \noexpand#1%
-  \fi
-}
-
-% This makes use of the obscure feature that if the last token of a
-% <parameter list> is #, then the preceding argument is delimited by
-% an opening brace, and that opening brace is not consumed.
-\def\getargs#1{\getargsxxx#1{}}
-\def\getargsxxx#1#{\getmacname #1 \relax\getmacargs}
-\def\getmacname#1 #2\relax{\macname={#1}}
-\def\getmacargs#1{\def\argl{#1}}
-
-% For macro processing make @ a letter so that we can make Texinfo private macro names.
-\edef\texiatcatcode{\the\catcode`\@}
-\catcode `@=11\relax
-
-% Parse the optional {params} list.  Set up \paramno and \paramlist
-% so \defmacro knows what to do.  Define \macarg.BLAH for each BLAH
-% in the params list to some hook where the argument si to be expanded.  If
-% there are less than 10 arguments that hook is to be replaced by ##N where N
-% is the position in that list, that is to say the macro arguments are to be
-% defined `a la TeX in the macro body.  
-%
-% That gets used by \mbodybackslash (above).
-%
-% We need to get `macro parameter char #' into several definitions.
-% The technique used is stolen from LaTeX: let \hash be something
-% unexpandable, insert that wherever you need a #, and then redefine
-% it to # just before using the token list produced.
-%
-% The same technique is used to protect \eatspaces till just before
-% the macro is used.
-%
-% If there are 10 or more arguments, a different technique is used, where the
-% hook remains in the body, and when macro is to be expanded the body is
-% processed again to replace the arguments.
-%
-% In that case, the hook is \the\toks N-1, and we simply set \toks N-1 to the
-% argument N value and then \edef  the body (nothing else will expand because of
-% the catcode regime underwhich the body was input).
-%
-% If you compile with TeX (not eTeX), and you have macros with 10 or more
-% arguments, you need that no macro has more than 256 arguments, otherwise an
-% error is produced.
-\def\parsemargdef#1;{%
-  \paramno=0\def\paramlist{}%
-  \let\hash\relax
-  \let\xeatspaces\relax
-  \parsemargdefxxx#1,;,%
-  % In case that there are 10 or more arguments we parse again the arguments
-  % list to set new definitions for the \macarg.BLAH macros corresponding to
-  % each BLAH argument. It was anyhow needed to parse already once this list
-  % in order to count the arguments, and as macros with at most 9 arguments
-  % are by far more frequent than macro with 10 or more arguments, defining
-  % twice the \macarg.BLAH macros does not cost too much processing power.
-  \ifnum\paramno<10\relax\else
-    \paramno0\relax
-    \parsemmanyargdef@@#1,;,% 10 or more arguments
-  \fi
-}
-\def\parsemargdefxxx#1,{%
-  \if#1;\let\next=\relax
-  \else \let\next=\parsemargdefxxx
-    \advance\paramno by 1
-    \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname
-        {\xeatspaces{\hash\the\paramno}}%
-    \edef\paramlist{\paramlist\hash\the\paramno,}%
-  \fi\next}
-
-\def\parsemmanyargdef@@#1,{%
-  \if#1;\let\next=\relax
-  \else 
-    \let\next=\parsemmanyargdef@@
-    \edef\tempb{\eatspaces{#1}}%
-    \expandafter\def\expandafter\tempa
-       \expandafter{\csname macarg.\tempb\endcsname}%
-    % Note that we need some extra \noexpand\noexpand, this is because we
-    % don't want \the  to be expanded in the \parsermacbody  as it uses an
-    % \xdef .
-    \expandafter\edef\tempa
-      {\noexpand\noexpand\noexpand\the\toks\the\paramno}%
-    \advance\paramno by 1\relax
-  \fi\next}
-
-% These two commands read recursive and nonrecursive macro bodies.
-% (They're different since rec and nonrec macros end differently.)
-%
-
-\catcode `\@\texiatcatcode
-\long\def\parsemacbody#1@end macro%
-{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}%
-\long\def\parsermacbody#1@end rmacro%
-{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}%
-\catcode `\@=11\relax
-
-\let\endargs@\relax
-\let\nil@\relax
-\def\nilm@{\nil@}%
-\long\def\nillm@{\nil@}%
-
-% This macro is expanded during the Texinfo macro expansion, not during its
-% definition.  It gets all the arguments values and assigns them to macros
-% macarg.ARGNAME
-%
-% #1 is the macro name
-% #2 is the list of argument names
-% #3 is the list of argument values
-\def\getargvals@#1#2#3{%
-  \def\macargdeflist@{}%
-  \def\saveparamlist@{#2}% Need to keep a copy for parameter expansion.
-  \def\paramlist{#2,\nil@}%
-  \def\macroname{#1}%
-  \begingroup
-  \macroargctxt
-  \def\argvaluelist{#3,\nil@}%
-  \def\@tempa{#3}%
-  \ifx\@tempa\empty
-    \setemptyargvalues@
-  \else
-    \getargvals@@
-  \fi
-}
-
-% 
-\def\getargvals@@{%
-  \ifx\paramlist\nilm@
-      % Some sanity check needed here that \argvaluelist is also empty.
-      \ifx\argvaluelist\nillm@
-      \else
-        \errhelp = \EMsimple
-        \errmessage{Too many arguments in macro `\macroname'!}%
-      \fi
-      \let\next\macargexpandinbody@
-  \else
-    \ifx\argvaluelist\nillm@
-       % No more arguments values passed to macro.  Set remaining named-arg
-       % macros to empty.
-       \let\next\setemptyargvalues@
-    \else
-      % pop current arg name into \@tempb
-      \def\@tempa##1{\pop@{\@tempb}{\paramlist}##1\endargs@}%
-      \expandafter\@tempa\expandafter{\paramlist}%
-       % pop current argument value into \@tempc
-      \def\@tempa##1{\longpop@{\@tempc}{\argvaluelist}##1\endargs@}%
-      \expandafter\@tempa\expandafter{\argvaluelist}%
-       % Here \@tempb is the current arg name and \@tempc is the current arg value.
-       % First place the new argument macro definition into \@tempd
-       \expandafter\macname\expandafter{\@tempc}%
-       \expandafter\let\csname macarg.\@tempb\endcsname\relax
-       \expandafter\def\expandafter\@tempe\expandafter{%
-         \csname macarg.\@tempb\endcsname}%
-       \edef\@tempd{\long\def\@tempe{\the\macname}}%
-       \push@\@tempd\macargdeflist@
-       \let\next\getargvals@@
-    \fi
-  \fi
-  \next
-}
-
-\def\push@#1#2{%
-  \expandafter\expandafter\expandafter\def
-  \expandafter\expandafter\expandafter#2%
-  \expandafter\expandafter\expandafter{%
-  \expandafter#1#2}%
-}
-
-% Replace arguments by their values in the macro body, and place the result
-% in macro \@tempa
-\def\macvalstoargs@{%
-  %  To do this we use the property that token registers that are \the'ed
-  % within an \edef  expand only once. So we are going to place all argument
-  % values into respective token registers.
-  %
-  % First we save the token context, and initialize argument numbering.
-  \begingroup
-    \paramno0\relax
-    % Then, for each argument number #N, we place the corresponding argument
-    % value into a new token list register \toks#N
-    \expandafter\putargsintokens@\saveparamlist@,;,%
-    % Then, we expand the body so that argument are replaced by their
-    % values. The trick for values not to be expanded themselves is that they
-    % are within tokens and that tokens expand only once in an \edef .
-    \edef\@tempc{\csname mac.\macroname .body\endcsname}%
-    % Now we restore the token stack pointer to free the token list registers
-    % which we have used, but we make sure that expanded body is saved after
-    % group.
-    \expandafter
-  \endgroup
-  \expandafter\def\expandafter\@tempa\expandafter{\@tempc}%
-  }
-
-\def\macargexpandinbody@{% 
-  %% Define the named-macro outside of this group and then close this group. 
-  \expandafter
-  \endgroup
-  \macargdeflist@
-  % First the replace in body the macro arguments by their values, the result
-  % is in \@tempa .
-  \macvalstoargs@
-  % Then we point at the \norecurse or \gobble (for recursive) macro value
-  % with \@tempb .
-  \expandafter\let\expandafter\@tempb\csname mac.\macroname .recurse\endcsname
-  % Depending on whether it is recursive or not, we need some tailing
-  % \egroup .
-  \ifx\@tempb\gobble
-     \let\@tempc\relax
-  \else
-     \let\@tempc\egroup
-  \fi
-  % And now we do the real job:
-  \edef\@tempd{\noexpand\@tempb{\macroname}\noexpand\scanmacro{\@tempa}\@tempc}%
-  \@tempd
-}
-
-\def\putargsintokens@#1,{%
-  \if#1;\let\next\relax
-  \else
-    \let\next\putargsintokens@
-    % First we allocate the new token list register, and give it a temporary
-    % alias \@tempb .
-    \toksdef\@tempb\the\paramno
-    % Then we place the argument value into that token list register.
-    \expandafter\let\expandafter\@tempa\csname macarg.#1\endcsname
-    \expandafter\@tempb\expandafter{\@tempa}%
-    \advance\paramno by 1\relax
-  \fi
-  \next
-}
-
-% Save the token stack pointer into macro #1
-\def\texisavetoksstackpoint#1{\edef#1{\the\@cclvi}}
-% Restore the token stack pointer from number in macro #1
-\def\texirestoretoksstackpoint#1{\expandafter\mathchardef\expandafter\@cclvi#1\relax}
-% newtoks that can be used non \outer .
-\def\texinonouternewtoks{\alloc@ 5\toks \toksdef \@cclvi}
-
-% Tailing missing arguments are set to empty
-\def\setemptyargvalues@{%
-  \ifx\paramlist\nilm@
-    \let\next\macargexpandinbody@
-  \else
-    \expandafter\setemptyargvaluesparser@\paramlist\endargs@
-    \let\next\setemptyargvalues@
-  \fi
-  \next
-}
-
-\def\setemptyargvaluesparser@#1,#2\endargs@{%
-  \expandafter\def\expandafter\@tempa\expandafter{%
-    \expandafter\def\csname macarg.#1\endcsname{}}%
-  \push@\@tempa\macargdeflist@
-  \def\paramlist{#2}%
-}
-
-% #1 is the element target macro
-% #2 is the list macro
-% #3,#4\endargs@ is the list value
-\def\pop@#1#2#3,#4\endargs@{%
-   \def#1{#3}%
-   \def#2{#4}%
-}
-\long\def\longpop@#1#2#3,#4\endargs@{%
-   \long\def#1{#3}%
-   \long\def#2{#4}%
-}
-
-% This defines a Texinfo @macro. There are eight cases: recursive and
-% nonrecursive macros of zero, one, up to nine, and many arguments.
-% Much magic with \expandafter here.
-% \xdef is used so that macro definitions will survive the file
-% they're defined in; @include reads the file inside a group.
-%
-\def\defmacro{%
-  \let\hash=##% convert placeholders to macro parameter chars
-  \ifrecursive
-    \ifcase\paramno
-    % 0
-      \expandafter\xdef\csname\the\macname\endcsname{%
-        \noexpand\scanmacro{\temp}}%
-    \or % 1
-      \expandafter\xdef\csname\the\macname\endcsname{%
-         \bgroup\noexpand\macroargctxt
-         \noexpand\braceorline
-         \expandafter\noexpand\csname\the\macname xxx\endcsname}%
-      \expandafter\xdef\csname\the\macname xxx\endcsname##1{%
-         \egroup\noexpand\scanmacro{\temp}}%
-    \else
-      \ifnum\paramno<10\relax % at most 9
-        \expandafter\xdef\csname\the\macname\endcsname{%
-           \bgroup\noexpand\macroargctxt
-           \noexpand\csname\the\macname xx\endcsname}%
-        \expandafter\xdef\csname\the\macname xx\endcsname##1{%
-            \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}%
-        \expandafter\expandafter
-        \expandafter\xdef
-        \expandafter\expandafter
-          \csname\the\macname xxx\endcsname
-            \paramlist{\egroup\noexpand\scanmacro{\temp}}%
-      \else % 10 or more
-        \expandafter\xdef\csname\the\macname\endcsname{%
-          \noexpand\getargvals@{\the\macname}{\argl}%
-        }%    
-        \global\expandafter\let\csname mac.\the\macname .body\endcsname\temp
-        \global\expandafter\let\csname mac.\the\macname .recurse\endcsname\gobble
-      \fi
-    \fi
-  \else
-    \ifcase\paramno
-    % 0
-      \expandafter\xdef\csname\the\macname\endcsname{%
-        \noexpand\norecurse{\the\macname}%
-        \noexpand\scanmacro{\temp}\egroup}%
-    \or % 1
-      \expandafter\xdef\csname\the\macname\endcsname{%
-         \bgroup\noexpand\macroargctxt
-         \noexpand\braceorline
-         \expandafter\noexpand\csname\the\macname xxx\endcsname}%
-      \expandafter\xdef\csname\the\macname xxx\endcsname##1{%
-        \egroup
-        \noexpand\norecurse{\the\macname}%
-        \noexpand\scanmacro{\temp}\egroup}%
-    \else % at most 9
-      \ifnum\paramno<10\relax
-        \expandafter\xdef\csname\the\macname\endcsname{%
-           \bgroup\noexpand\macroargctxt
-           \expandafter\noexpand\csname\the\macname xx\endcsname}%
-        \expandafter\xdef\csname\the\macname xx\endcsname##1{%
-            \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}%
-        \expandafter\expandafter
-        \expandafter\xdef
-        \expandafter\expandafter
-        \csname\the\macname xxx\endcsname
-        \paramlist{%
-            \egroup
-            \noexpand\norecurse{\the\macname}%
-            \noexpand\scanmacro{\temp}\egroup}%
-      \else % 10 or more:
-        \expandafter\xdef\csname\the\macname\endcsname{%
-          \noexpand\getargvals@{\the\macname}{\argl}%
-        }%
-        \global\expandafter\let\csname mac.\the\macname .body\endcsname\temp
-        \global\expandafter\let\csname mac.\the\macname .recurse\endcsname\norecurse
-      \fi
-    \fi
-  \fi}
-
-\catcode `\@\texiatcatcode\relax
-
-\def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}}
-
-% \braceorline decides whether the next nonwhitespace character is a
-% {.  If so it reads up to the closing }, if not, it reads the whole
-% line.  Whatever was read is then fed to the next control sequence
-% as an argument (by \parsebrace or \parsearg).
-% 
-\def\braceorline#1{\let\macnamexxx=#1\futurelet\nchar\braceorlinexxx}
-\def\braceorlinexxx{%
-  \ifx\nchar\bgroup\else
-    \expandafter\parsearg
-  \fi \macnamexxx}
-
-
-% @alias.
-% We need some trickery to remove the optional spaces around the equal
-% sign.  Make them active and then expand them all to nothing.
-%
-\def\alias{\parseargusing\obeyspaces\aliasxxx}
-\def\aliasxxx #1{\aliasyyy#1\relax}
-\def\aliasyyy #1=#2\relax{%
-  {%
-    \expandafter\let\obeyedspace=\empty
-    \addtomacrolist{#1}%
-    \xdef\next{\global\let\makecsname{#1}=\makecsname{#2}}%
-  }%
-  \next
-}
-
-
-\message{cross references,}
-
-\newwrite\auxfile
-\newif\ifhavexrefs    % True if xref values are known.
-\newif\ifwarnedxrefs  % True if we warned once that they aren't known.
-
-% @inforef is relatively simple.
-\def\inforef #1{\inforefzzz #1,,,,**}
-\def\inforefzzz #1,#2,#3,#4**{%
-  \putwordSee{} \putwordInfo{} \putwordfile{} \file{\ignorespaces #3{}},
-  node \samp{\ignorespaces#1{}}}
-
-% @node's only job in TeX is to define \lastnode, which is used in
-% cross-references.  The @node line might or might not have commas, and
-% might or might not have spaces before the first comma, like:
-% @node foo , bar , ...
-% We don't want such trailing spaces in the node name.
-%
-\parseargdef\node{\checkenv{}\donode #1 ,\finishnodeparse}
-%
-% also remove a trailing comma, in case of something like this:
-% @node Help-Cross,  ,  , Cross-refs
-\def\donode#1 ,#2\finishnodeparse{\dodonode #1,\finishnodeparse}
-\def\dodonode#1,#2\finishnodeparse{\gdef\lastnode{#1}}
-
-\let\nwnode=\node
-\let\lastnode=\empty
-
-% Write a cross-reference definition for the current node.  #1 is the
-% type (Ynumbered, Yappendix, Ynothing).
-%
-\def\donoderef#1{%
-  \ifx\lastnode\empty\else
-    \setref{\lastnode}{#1}%
-    \global\let\lastnode=\empty
-  \fi
-}
-
-% @anchor{NAME} -- define xref target at arbitrary point.
-%
-\newcount\savesfregister
-%
-\def\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi}
-\def\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi}
-\def\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces}
-
-% \setref{NAME}{SNT} defines a cross-reference point NAME (a node or an
-% anchor), which consists of three parts:
-% 1) NAME-title - the current sectioning name taken from \lastsection,
-%                 or the anchor name.
-% 2) NAME-snt   - section number and type, passed as the SNT arg, or
-%                 empty for anchors.
-% 3) NAME-pg    - the page number.
-%
-% This is called from \donoderef, \anchor, and \dofloat.  In the case of
-% floats, there is an additional part, which is not written here:
-% 4) NAME-lof   - the text as it should appear in a @listoffloats.
-%
-\def\setref#1#2{%
-  \pdfmkdest{#1}%
-  \iflinks
-    {%
-      \atdummies  % preserve commands, but don't expand them
-      \edef\writexrdef##1##2{%
-	\write\auxfile{@xrdef{#1-% #1 of \setref, expanded by the \edef
-	  ##1}{##2}}% these are parameters of \writexrdef
-      }%
-      \toks0 = \expandafter{\lastsection}%
-      \immediate \writexrdef{title}{\the\toks0 }%
-      \immediate \writexrdef{snt}{\csname #2\endcsname}% \Ynumbered etc.
-      \safewhatsit{\writexrdef{pg}{\folio}}% will be written later, at \shipout
-    }%
-  \fi
-}
-
-% @xrefautosectiontitle on|off says whether @section(ing) names are used
-% automatically in xrefs, if the third arg is not explicitly specified.
-% This was provided as a "secret" @set xref-automatic-section-title
-% variable, now it's official.
-% 
-\parseargdef\xrefautomaticsectiontitle{%
-  \def\temp{#1}%
-  \ifx\temp\onword
-    \expandafter\let\csname SETxref-automatic-section-title\endcsname
-      = \empty
-  \else\ifx\temp\offword
-    \expandafter\let\csname SETxref-automatic-section-title\endcsname
-      = \relax
-  \else
-    \errhelp = \EMsimple
-    \errmessage{Unknown @xrefautomaticsectiontitle value `\temp',
-                must be on|off}%
-  \fi\fi
-}
-
-% 
-% @xref, @pxref, and @ref generate cross-references.  For \xrefX, #1 is
-% the node name, #2 the name of the Info cross-reference, #3 the printed
-% node name, #4 the name of the Info file, #5 the name of the printed
-% manual.  All but the node name can be omitted.
-%
-\def\pxref#1{\putwordsee{} \xrefX[#1,,,,,,,]}
-\def\xref#1{\putwordSee{} \xrefX[#1,,,,,,,]}
-\def\ref#1{\xrefX[#1,,,,,,,]}
-%
-\newbox\toprefbox
-\newbox\printedrefnamebox
-\newbox\infofilenamebox
-\newbox\printedmanualbox
-%
-\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
-  \unsepspaces
-  %
-  % Get args without leading/trailing spaces.
-  \def\printedrefname{\ignorespaces #3}%
-  \setbox\printedrefnamebox = \hbox{\printedrefname\unskip}%
-  %
-  \def\infofilename{\ignorespaces #4}%
-  \setbox\infofilenamebox = \hbox{\infofilename\unskip}%
-  %
-  \def\printedmanual{\ignorespaces #5}%
-  \setbox\printedmanualbox  = \hbox{\printedmanual\unskip}%
-  %
-  % If the printed reference name (arg #3) was not explicitly given in
-  % the @xref, figure out what we want to use.
-  \ifdim \wd\printedrefnamebox = 0pt
-    % No printed node name was explicitly given.
-    \expandafter\ifx\csname SETxref-automatic-section-title\endcsname \relax
-      % Not auto section-title: use node name inside the square brackets.
-      \def\printedrefname{\ignorespaces #1}%
-    \else
-      % Auto section-title: use chapter/section title inside
-      % the square brackets if we have it.
-      \ifdim \wd\printedmanualbox > 0pt
-        % It is in another manual, so we don't have it; use node name.
-        \def\printedrefname{\ignorespaces #1}%
-      \else
-        \ifhavexrefs
-          % We (should) know the real title if we have the xref values.
-          \def\printedrefname{\refx{#1-title}{}}%
-        \else
-          % Otherwise just copy the Info node name.
-          \def\printedrefname{\ignorespaces #1}%
-        \fi%
-      \fi
-    \fi
-  \fi
-  %
-  % Make link in pdf output.
-  \ifpdf
-    {\indexnofonts
-     \turnoffactive
-     \makevalueexpandable
-     % This expands tokens, so do it after making catcode changes, so _
-     % etc. don't get their TeX definitions.  This ignores all spaces in
-     % #4, including (wrongly) those in the middle of the filename.
-     \getfilename{#4}%
-     %
-     % This (wrongly) does not take account of leading or trailing
-     % spaces in #1, which should be ignored.
-     \edef\pdfxrefdest{#1}%
-     \ifx\pdfxrefdest\empty
-       \def\pdfxrefdest{Top}% no empty targets
-     \else
-       \txiescapepdf\pdfxrefdest  % escape PDF special chars
-     \fi
-     %
-     \leavevmode
-     \startlink attr{/Border [0 0 0]}%
-     \ifnum\filenamelength>0
-       goto file{\the\filename.pdf} name{\pdfxrefdest}%
-     \else
-       goto name{\pdfmkpgn{\pdfxrefdest}}%
-     \fi
-    }%
-    \setcolor{\linkcolor}%
-  \fi
-  %
-  % Float references are printed completely differently: "Figure 1.2"
-  % instead of "[somenode], p.3".  We distinguish them by the
-  % LABEL-title being set to a magic string.
-  {%
-    % Have to otherify everything special to allow the \csname to
-    % include an _ in the xref name, etc.
-    \indexnofonts
-    \turnoffactive
-    \expandafter\global\expandafter\let\expandafter\Xthisreftitle
-      \csname XR#1-title\endcsname
-  }%
-  \iffloat\Xthisreftitle
-    % If the user specified the print name (third arg) to the ref,
-    % print it instead of our usual "Figure 1.2".
-    \ifdim\wd\printedrefnamebox = 0pt
-      \refx{#1-snt}{}%
-    \else
-      \printedrefname
-    \fi
-    %
-    % If the user also gave the printed manual name (fifth arg), append
-    % "in MANUALNAME".
-    \ifdim \wd\printedmanualbox > 0pt
-      \space \putwordin{} \cite{\printedmanual}%
-    \fi
-  \else
-    % node/anchor (non-float) references.
-    % 
-    % If we use \unhbox to print the node names, TeX does not insert
-    % empty discretionaries after hyphens, which means that it will not
-    % find a line break at a hyphen in a node names.  Since some manuals
-    % are best written with fairly long node names, containing hyphens,
-    % this is a loss.  Therefore, we give the text of the node name
-    % again, so it is as if TeX is seeing it for the first time.
-    % 
-    \ifdim \wd\printedmanualbox > 0pt
-      % Cross-manual reference with a printed manual name.
-      % 
-      \crossmanualxref{\cite{\printedmanual\unskip}}%
-    %
-    \else\ifdim \wd\infofilenamebox > 0pt
-      % Cross-manual reference with only an info filename (arg 4), no
-      % printed manual name (arg 5).  This is essentially the same as
-      % the case above; we output the filename, since we have nothing else.
-      % 
-      \crossmanualxref{\code{\infofilename\unskip}}%
-    %
-    \else
-      % Reference within this manual.
-      %
-      % _ (for example) has to be the character _ for the purposes of the
-      % control sequence corresponding to the node, but it has to expand
-      % into the usual \leavevmode...\vrule stuff for purposes of
-      % printing. So we \turnoffactive for the \refx-snt, back on for the
-      % printing, back off for the \refx-pg.
-      {\turnoffactive
-       % Only output a following space if the -snt ref is nonempty; for
-       % @unnumbered and @anchor, it won't be.
-       \setbox2 = \hbox{\ignorespaces \refx{#1-snt}{}}%
-       \ifdim \wd2 > 0pt \refx{#1-snt}\space\fi
-      }%
-      % output the `[mynode]' via the macro below so it can be overridden.
-      \xrefprintnodename\printedrefname
-      %
-      % But we always want a comma and a space:
-      ,\space
-      %
-      % output the `page 3'.
-      \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
-    \fi\fi
-  \fi
-  \endlink
-\endgroup}
-
-% Output a cross-manual xref to #1.  Used just above (twice).
-% 
-% Only include the text "Section ``foo'' in" if the foo is neither
-% missing or Top.  Thus, @xref{,,,foo,The Foo Manual} outputs simply
-% "see The Foo Manual", the idea being to refer to the whole manual.
-% 
-% But, this being TeX, we can't easily compare our node name against the
-% string "Top" while ignoring the possible spaces before and after in
-% the input.  By adding the arbitrary 7sp below, we make it much less
-% likely that a real node name would have the same width as "Top" (e.g.,
-% in a monospaced font).  Hopefully it will never happen in practice.
-% 
-% For the same basic reason, we retypeset the "Top" at every
-% reference, since the current font is indeterminate.
-% 
-\def\crossmanualxref#1{%
-  \setbox\toprefbox = \hbox{Top\kern7sp}%
-  \setbox2 = \hbox{\ignorespaces \printedrefname \unskip \kern7sp}%
-  \ifdim \wd2 > 7sp  % nonempty?
-    \ifdim \wd2 = \wd\toprefbox \else  % same as Top?
-      \putwordSection{} ``\printedrefname'' \putwordin{}\space
-    \fi
-  \fi
-  #1%
-}
-
-% This macro is called from \xrefX for the `[nodename]' part of xref
-% output.  It's a separate macro only so it can be changed more easily,
-% since square brackets don't work well in some documents.  Particularly
-% one that Bob is working on :).
-%
-\def\xrefprintnodename#1{[#1]}
-
-% Things referred to by \setref.
-%
-\def\Ynothing{}
-\def\Yomitfromtoc{}
-\def\Ynumbered{%
-  \ifnum\secno=0
-    \putwordChapter@tie \the\chapno
-  \else \ifnum\subsecno=0
-    \putwordSection@tie \the\chapno.\the\secno
-  \else \ifnum\subsubsecno=0
-    \putwordSection@tie \the\chapno.\the\secno.\the\subsecno
-  \else
-    \putwordSection@tie \the\chapno.\the\secno.\the\subsecno.\the\subsubsecno
-  \fi\fi\fi
-}
-\def\Yappendix{%
-  \ifnum\secno=0
-     \putwordAppendix@tie @char\the\appendixno{}%
-  \else \ifnum\subsecno=0
-     \putwordSection@tie @char\the\appendixno.\the\secno
-  \else \ifnum\subsubsecno=0
-    \putwordSection@tie @char\the\appendixno.\the\secno.\the\subsecno
-  \else
-    \putwordSection@tie
-      @char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno
-  \fi\fi\fi
-}
-
-% Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME.
-% If its value is nonempty, SUFFIX is output afterward.
-%
-\def\refx#1#2{%
-  {%
-    \indexnofonts
-    \otherbackslash
-    \expandafter\global\expandafter\let\expandafter\thisrefX
-      \csname XR#1\endcsname
-  }%
-  \ifx\thisrefX\relax
-    % If not defined, say something at least.
-    \angleleft un\-de\-fined\angleright
-    \iflinks
-      \ifhavexrefs
-        {\toks0 = {#1}% avoid expansion of possibly-complex value
-         \message{\linenumber Undefined cross reference `\the\toks0'.}}%
-      \else
-        \ifwarnedxrefs\else
-          \global\warnedxrefstrue
-          \message{Cross reference values unknown; you must run TeX again.}%
-        \fi
-      \fi
-    \fi
-  \else
-    % It's defined, so just use it.
-    \thisrefX
-  \fi
-  #2% Output the suffix in any case.
-}
-
-% This is the macro invoked by entries in the aux file.  Usually it's
-% just a \def (we prepend XR to the control sequence name to avoid
-% collisions).  But if this is a float type, we have more work to do.
-%
-\def\xrdef#1#2{%
-  {% The node name might contain 8-bit characters, which in our current
-   % implementation are changed to commands like @'e.  Don't let these
-   % mess up the control sequence name.
-    \indexnofonts
-    \turnoffactive
-    \xdef\safexrefname{#1}%
-  }%
-  %
-  \expandafter\gdef\csname XR\safexrefname\endcsname{#2}% remember this xref
-  %
-  % Was that xref control sequence that we just defined for a float?
-  \expandafter\iffloat\csname XR\safexrefname\endcsname
-    % it was a float, and we have the (safe) float type in \iffloattype.
-    \expandafter\let\expandafter\floatlist
-      \csname floatlist\iffloattype\endcsname
-    %
-    % Is this the first time we've seen this float type?
-    \expandafter\ifx\floatlist\relax
-      \toks0 = {\do}% yes, so just \do
-    \else
-      % had it before, so preserve previous elements in list.
-      \toks0 = \expandafter{\floatlist\do}%
-    \fi
-    %
-    % Remember this xref in the control sequence \floatlistFLOATTYPE,
-    % for later use in \listoffloats.
-    \expandafter\xdef\csname floatlist\iffloattype\endcsname{\the\toks0
-      {\safexrefname}}%
-  \fi
-}
-
-% Read the last existing aux file, if any.  No error if none exists.
-%
-\def\tryauxfile{%
-  \openin 1 \jobname.aux
-  \ifeof 1 \else
-    \readdatafile{aux}%
-    \global\havexrefstrue
-  \fi
-  \closein 1
-}
-
-\def\setupdatafile{%
-  \catcode`\^^@=\other
-  \catcode`\^^A=\other
-  \catcode`\^^B=\other
-  \catcode`\^^C=\other
-  \catcode`\^^D=\other
-  \catcode`\^^E=\other
-  \catcode`\^^F=\other
-  \catcode`\^^G=\other
-  \catcode`\^^H=\other
-  \catcode`\^^K=\other
-  \catcode`\^^L=\other
-  \catcode`\^^N=\other
-  \catcode`\^^P=\other
-  \catcode`\^^Q=\other
-  \catcode`\^^R=\other
-  \catcode`\^^S=\other
-  \catcode`\^^T=\other
-  \catcode`\^^U=\other
-  \catcode`\^^V=\other
-  \catcode`\^^W=\other
-  \catcode`\^^X=\other
-  \catcode`\^^Z=\other
-  \catcode`\^^[=\other
-  \catcode`\^^\=\other
-  \catcode`\^^]=\other
-  \catcode`\^^^=\other
-  \catcode`\^^_=\other
-  % It was suggested to set the catcode of ^ to 7, which would allow ^^e4 etc.
-  % in xref tags, i.e., node names.  But since ^^e4 notation isn't
-  % supported in the main text, it doesn't seem desirable.  Furthermore,
-  % that is not enough: for node names that actually contain a ^
-  % character, we would end up writing a line like this: 'xrdef {'hat
-  % b-title}{'hat b} and \xrdef does a \csname...\endcsname on the first
-  % argument, and \hat is not an expandable control sequence.  It could
-  % all be worked out, but why?  Either we support ^^ or we don't.
-  %
-  % The other change necessary for this was to define \auxhat:
-  % \def\auxhat{\def^{'hat }}% extra space so ok if followed by letter
-  % and then to call \auxhat in \setq.
-  %
-  \catcode`\^=\other
-  %
-  % Special characters.  Should be turned off anyway, but...
-  \catcode`\~=\other
-  \catcode`\[=\other
-  \catcode`\]=\other
-  \catcode`\"=\other
-  \catcode`\_=\other
-  \catcode`\|=\other
-  \catcode`\<=\other
-  \catcode`\>=\other
-  \catcode`\$=\other
-  \catcode`\#=\other
-  \catcode`\&=\other
-  \catcode`\%=\other
-  \catcode`+=\other % avoid \+ for paranoia even though we've turned it off
-  %
-  % This is to support \ in node names and titles, since the \
-  % characters end up in a \csname.  It's easier than
-  % leaving it active and making its active definition an actual \
-  % character.  What I don't understand is why it works in the *value*
-  % of the xrdef.  Seems like it should be a catcode12 \, and that
-  % should not typeset properly.  But it works, so I'm moving on for
-  % now.  --karl, 15jan04.
-  \catcode`\\=\other
-  %
-  % Make the characters 128-255 be printing characters.
-  {%
-    \count1=128
-    \def\loop{%
-      \catcode\count1=\other
-      \advance\count1 by 1
-      \ifnum \count1<256 \loop \fi
-    }%
-  }%
-  %
-  % @ is our escape character in .aux files, and we need braces.
-  \catcode`\{=1
-  \catcode`\}=2
-  \catcode`\@=0
-}
-
-\def\readdatafile#1{%
-\begingroup
-  \setupdatafile
-  \input\jobname.#1
-\endgroup}
-
-
-\message{insertions,}
-% including footnotes.
-
-\newcount \footnoteno
-
-% The trailing space in the following definition for supereject is
-% vital for proper filling; pages come out unaligned when you do a
-% pagealignmacro call if that space before the closing brace is
-% removed. (Generally, numeric constants should always be followed by a
-% space to prevent strange expansion errors.)
-\def\supereject{\par\penalty -20000\footnoteno =0 }
-
-% @footnotestyle is meaningful for Info output only.
-\let\footnotestyle=\comment
-
-{\catcode `\@=11
-%
-% Auto-number footnotes.  Otherwise like plain.
-\gdef\footnote{%
-  \let\indent=\ptexindent
-  \let\noindent=\ptexnoindent
-  \global\advance\footnoteno by \@ne
-  \edef\thisfootno{$^{\the\footnoteno}$}%
-  %
-  % In case the footnote comes at the end of a sentence, preserve the
-  % extra spacing after we do the footnote number.
-  \let\@sf\empty
-  \ifhmode\edef\@sf{\spacefactor\the\spacefactor}\ptexslash\fi
-  %
-  % Remove inadvertent blank space before typesetting the footnote number.
-  \unskip
-  \thisfootno\@sf
-  \dofootnote
-}%
-
-% Don't bother with the trickery in plain.tex to not require the
-% footnote text as a parameter.  Our footnotes don't need to be so general.
-%
-% Oh yes, they do; otherwise, @ifset (and anything else that uses
-% \parseargline) fails inside footnotes because the tokens are fixed when
-% the footnote is read.  --karl, 16nov96.
-%
-\gdef\dofootnote{%
-  \insert\footins\bgroup
-  % We want to typeset this text as a normal paragraph, even if the
-  % footnote reference occurs in (for example) a display environment.
-  % So reset some parameters.
-  \hsize=\pagewidth
-  \interlinepenalty\interfootnotelinepenalty
-  \splittopskip\ht\strutbox % top baseline for broken footnotes
-  \splitmaxdepth\dp\strutbox
-  \floatingpenalty\@MM
-  \leftskip\z@skip
-  \rightskip\z@skip
-  \spaceskip\z@skip
-  \xspaceskip\z@skip
-  \parindent\defaultparindent
-  %
-  \smallfonts \rm
-  %
-  % Because we use hanging indentation in footnotes, a @noindent appears
-  % to exdent this text, so make it be a no-op.  makeinfo does not use
-  % hanging indentation so @noindent can still be needed within footnote
-  % text after an @example or the like (not that this is good style).
-  \let\noindent = \relax
-  %
-  % Hang the footnote text off the number.  Use \everypar in case the
-  % footnote extends for more than one paragraph.
-  \everypar = {\hang}%
-  \textindent{\thisfootno}%
-  %
-  % Don't crash into the line above the footnote text.  Since this
-  % expands into a box, it must come within the paragraph, lest it
-  % provide a place where TeX can split the footnote.
-  \footstrut
-  %
-  % Invoke rest of plain TeX footnote routine.
-  \futurelet\next\fo@t
-}
-}%end \catcode `\@=11
-
-% In case a @footnote appears in a vbox, save the footnote text and create
-% the real \insert just after the vbox finished.  Otherwise, the insertion
-% would be lost.
-% Similarly, if a @footnote appears inside an alignment, save the footnote
-% text to a box and make the \insert when a row of the table is finished.
-% And the same can be done for other insert classes.  --kasal, 16nov03.
-
-% Replace the \insert primitive by a cheating macro.
-% Deeper inside, just make sure that the saved insertions are not spilled
-% out prematurely.
-%
-\def\startsavinginserts{%
-  \ifx \insert\ptexinsert
-    \let\insert\saveinsert
-  \else
-    \let\checkinserts\relax
-  \fi
-}
-
-% This \insert replacement works for both \insert\footins{foo} and
-% \insert\footins\bgroup foo\egroup, but it doesn't work for \insert27{foo}.
-%
-\def\saveinsert#1{%
-  \edef\next{\noexpand\savetobox \makeSAVEname#1}%
-  \afterassignment\next
-  % swallow the left brace
-  \let\temp =
-}
-\def\makeSAVEname#1{\makecsname{SAVE\expandafter\gobble\string#1}}
-\def\savetobox#1{\global\setbox#1 = \vbox\bgroup \unvbox#1}
-
-\def\checksaveins#1{\ifvoid#1\else \placesaveins#1\fi}
-
-\def\placesaveins#1{%
-  \ptexinsert \csname\expandafter\gobblesave\string#1\endcsname
-    {\box#1}%
-}
-
-% eat @SAVE -- beware, all of them have catcode \other:
-{
-  \def\dospecials{\do S\do A\do V\do E} \uncatcodespecials  %  ;-)
-  \gdef\gobblesave @SAVE{}
-}
-
-% initialization:
-\def\newsaveins #1{%
-  \edef\next{\noexpand\newsaveinsX \makeSAVEname#1}%
-  \next
-}
-\def\newsaveinsX #1{%
-  \csname newbox\endcsname #1%
-  \expandafter\def\expandafter\checkinserts\expandafter{\checkinserts
-    \checksaveins #1}%
-}
-
-% initialize:
-\let\checkinserts\empty
-\newsaveins\footins
-\newsaveins\margin
-
-
-% @image.  We use the macros from epsf.tex to support this.
-% If epsf.tex is not installed and @image is used, we complain.
-%
-% Check for and read epsf.tex up front.  If we read it only at @image
-% time, we might be inside a group, and then its definitions would get
-% undone and the next image would fail.
-\openin 1 = epsf.tex
-\ifeof 1 \else
-  % Do not bother showing banner with epsf.tex v2.7k (available in
-  % doc/epsf.tex and on ctan).
-  \def\epsfannounce{\toks0 = }%
-  \input epsf.tex
-\fi
-\closein 1
-%
-% We will only complain once about lack of epsf.tex.
-\newif\ifwarnednoepsf
-\newhelp\noepsfhelp{epsf.tex must be installed for images to
-  work.  It is also included in the Texinfo distribution, or you can get
-  it from ftp://tug.org/tex/epsf.tex.}
-%
-\def\image#1{%
-  \ifx\epsfbox\thisisundefined
-    \ifwarnednoepsf \else
-      \errhelp = \noepsfhelp
-      \errmessage{epsf.tex not found, images will be ignored}%
-      \global\warnednoepsftrue
-    \fi
-  \else
-    \imagexxx #1,,,,,\finish
-  \fi
-}
-%
-% Arguments to @image:
-% #1 is (mandatory) image filename; we tack on .eps extension.
-% #2 is (optional) width, #3 is (optional) height.
-% #4 is (ignored optional) html alt text.
-% #5 is (ignored optional) extension.
-% #6 is just the usual extra ignored arg for parsing stuff.
-\newif\ifimagevmode
-\def\imagexxx#1,#2,#3,#4,#5,#6\finish{\begingroup
-  \catcode`\^^M = 5     % in case we're inside an example
-  \normalturnoffactive  % allow _ et al. in names
-  % If the image is by itself, center it.
-  \ifvmode
-    \imagevmodetrue
-  \else \ifx\centersub\centerV
-    % for @center @image, we need a vbox so we can have our vertical space
-    \imagevmodetrue
-    \vbox\bgroup % vbox has better behavior than vtop herev
-  \fi\fi
-  %
-  \ifimagevmode
-    \nobreak\medskip
-    % Usually we'll have text after the image which will insert
-    % \parskip glue, so insert it here too to equalize the space
-    % above and below.
-    \nobreak\vskip\parskip
-    \nobreak
-  \fi
-  %
-  % Leave vertical mode so that indentation from an enclosing
-  %  environment such as @quotation is respected.
-  % However, if we're at the top level, we don't want the
-  %  normal paragraph indentation.
-  % On the other hand, if we are in the case of @center @image, we don't
-  %  want to start a paragraph, which will create a hsize-width box and
-  %  eradicate the centering.
-  \ifx\centersub\centerV\else \noindent \fi
-  %
-  % Output the image.
-  \ifpdf
-    \dopdfimage{#1}{#2}{#3}%
-  \else
-    % \epsfbox itself resets \epsf?size at each figure.
-    \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \epsfxsize=#2\relax \fi
-    \setbox0 = \hbox{\ignorespaces #3}\ifdim\wd0 > 0pt \epsfysize=#3\relax \fi
-    \epsfbox{#1.eps}%
-  \fi
-  %
-  \ifimagevmode
-    \medskip  % space after a standalone image
-  \fi  
-  \ifx\centersub\centerV \egroup \fi
-\endgroup}
-
-
-% @float FLOATTYPE,LABEL,LOC ... @end float for displayed figures, tables,
-% etc.  We don't actually implement floating yet, we always include the
-% float "here".  But it seemed the best name for the future.
-%
-\envparseargdef\float{\eatcommaspace\eatcommaspace\dofloat#1, , ,\finish}
-
-% There may be a space before second and/or third parameter; delete it.
-\def\eatcommaspace#1, {#1,}
-
-% #1 is the optional FLOATTYPE, the text label for this float, typically
-% "Figure", "Table", "Example", etc.  Can't contain commas.  If omitted,
-% this float will not be numbered and cannot be referred to.
-%
-% #2 is the optional xref label.  Also must be present for the float to
-% be referable.
-%
-% #3 is the optional positioning argument; for now, it is ignored.  It
-% will somehow specify the positions allowed to float to (here, top, bottom).
-%
-% We keep a separate counter for each FLOATTYPE, which we reset at each
-% chapter-level command.
-\let\resetallfloatnos=\empty
-%
-\def\dofloat#1,#2,#3,#4\finish{%
-  \let\thiscaption=\empty
-  \let\thisshortcaption=\empty
-  %
-  % don't lose footnotes inside @float.
-  %
-  % BEWARE: when the floats start float, we have to issue warning whenever an
-  % insert appears inside a float which could possibly float. --kasal, 26may04
-  %
-  \startsavinginserts
-  %
-  % We can't be used inside a paragraph.
-  \par
-  %
-  \vtop\bgroup
-    \def\floattype{#1}%
-    \def\floatlabel{#2}%
-    \def\floatloc{#3}% we do nothing with this yet.
-    %
-    \ifx\floattype\empty
-      \let\safefloattype=\empty
-    \else
-      {%
-        % the floattype might have accents or other special characters,
-        % but we need to use it in a control sequence name.
-        \indexnofonts
-        \turnoffactive
-        \xdef\safefloattype{\floattype}%
-      }%
-    \fi
-    %
-    % If label is given but no type, we handle that as the empty type.
-    \ifx\floatlabel\empty \else
-      % We want each FLOATTYPE to be numbered separately (Figure 1,
-      % Table 1, Figure 2, ...).  (And if no label, no number.)
-      %
-      \expandafter\getfloatno\csname\safefloattype floatno\endcsname
-      \global\advance\floatno by 1
-      %
-      {%
-        % This magic value for \lastsection is output by \setref as the
-        % XREFLABEL-title value.  \xrefX uses it to distinguish float
-        % labels (which have a completely different output format) from
-        % node and anchor labels.  And \xrdef uses it to construct the
-        % lists of floats.
-        %
-        \edef\lastsection{\floatmagic=\safefloattype}%
-        \setref{\floatlabel}{Yfloat}%
-      }%
-    \fi
-    %
-    % start with \parskip glue, I guess.
-    \vskip\parskip
-    %
-    % Don't suppress indentation if a float happens to start a section.
-    \restorefirstparagraphindent
-}
-
-% we have these possibilities:
-% @float Foo,lbl & @caption{Cap}: Foo 1.1: Cap
-% @float Foo,lbl & no caption:    Foo 1.1
-% @float Foo & @caption{Cap}:     Foo: Cap
-% @float Foo & no caption:        Foo
-% @float ,lbl & Caption{Cap}:     1.1: Cap
-% @float ,lbl & no caption:       1.1
-% @float & @caption{Cap}:         Cap
-% @float & no caption:
-%
-\def\Efloat{%
-    \let\floatident = \empty
-    %
-    % In all cases, if we have a float type, it comes first.
-    \ifx\floattype\empty \else \def\floatident{\floattype}\fi
-    %
-    % If we have an xref label, the number comes next.
-    \ifx\floatlabel\empty \else
-      \ifx\floattype\empty \else % if also had float type, need tie first.
-        \appendtomacro\floatident{\tie}%
-      \fi
-      % the number.
-      \appendtomacro\floatident{\chaplevelprefix\the\floatno}%
-    \fi
-    %
-    % Start the printed caption with what we've constructed in
-    % \floatident, but keep it separate; we need \floatident again.
-    \let\captionline = \floatident
-    %
-    \ifx\thiscaption\empty \else
-      \ifx\floatident\empty \else
-	\appendtomacro\captionline{: }% had ident, so need a colon between
-      \fi
-      %
-      % caption text.
-      \appendtomacro\captionline{\scanexp\thiscaption}%
-    \fi
-    %
-    % If we have anything to print, print it, with space before.
-    % Eventually this needs to become an \insert.
-    \ifx\captionline\empty \else
-      \vskip.5\parskip
-      \captionline
-      %
-      % Space below caption.
-      \vskip\parskip
-    \fi
-    %
-    % If have an xref label, write the list of floats info.  Do this
-    % after the caption, to avoid chance of it being a breakpoint.
-    \ifx\floatlabel\empty \else
-      % Write the text that goes in the lof to the aux file as
-      % \floatlabel-lof.  Besides \floatident, we include the short
-      % caption if specified, else the full caption if specified, else nothing.
-      {%
-        \atdummies
-        %
-        % since we read the caption text in the macro world, where ^^M
-        % is turned into a normal character, we have to scan it back, so
-        % we don't write the literal three characters "^^M" into the aux file.
-	\scanexp{%
-	  \xdef\noexpand\gtemp{%
-	    \ifx\thisshortcaption\empty
-	      \thiscaption
-	    \else
-	      \thisshortcaption
-	    \fi
-	  }%
-	}%
-        \immediate\write\auxfile{@xrdef{\floatlabel-lof}{\floatident
-	  \ifx\gtemp\empty \else : \gtemp \fi}}%
-      }%
-    \fi
-  \egroup  % end of \vtop
-  %
-  % place the captured inserts
-  %
-  % BEWARE: when the floats start floating, we have to issue warning
-  % whenever an insert appears inside a float which could possibly
-  % float. --kasal, 26may04
-  %
-  \checkinserts
-}
-
-% Append the tokens #2 to the definition of macro #1, not expanding either.
-%
-\def\appendtomacro#1#2{%
-  \expandafter\def\expandafter#1\expandafter{#1#2}%
-}
-
-% @caption, @shortcaption
-%
-\def\caption{\docaption\thiscaption}
-\def\shortcaption{\docaption\thisshortcaption}
-\def\docaption{\checkenv\float \bgroup\scanargctxt\defcaption}
-\def\defcaption#1#2{\egroup \def#1{#2}}
-
-% The parameter is the control sequence identifying the counter we are
-% going to use.  Create it if it doesn't exist and assign it to \floatno.
-\def\getfloatno#1{%
-  \ifx#1\relax
-      % Haven't seen this figure type before.
-      \csname newcount\endcsname #1%
-      %
-      % Remember to reset this floatno at the next chap.
-      \expandafter\gdef\expandafter\resetallfloatnos
-        \expandafter{\resetallfloatnos #1=0 }%
-  \fi
-  \let\floatno#1%
-}
-
-% \setref calls this to get the XREFLABEL-snt value.  We want an @xref
-% to the FLOATLABEL to expand to "Figure 3.1".  We call \setref when we
-% first read the @float command.
-%
-\def\Yfloat{\floattype@tie \chaplevelprefix\the\floatno}%
-
-% Magic string used for the XREFLABEL-title value, so \xrefX can
-% distinguish floats from other xref types.
-\def\floatmagic{!!float!!}
-
-% #1 is the control sequence we are passed; we expand into a conditional
-% which is true if #1 represents a float ref.  That is, the magic
-% \lastsection value which we \setref above.
-%
-\def\iffloat#1{\expandafter\doiffloat#1==\finish}
-%
-% #1 is (maybe) the \floatmagic string.  If so, #2 will be the
-% (safe) float type for this float.  We set \iffloattype to #2.
-%
-\def\doiffloat#1=#2=#3\finish{%
-  \def\temp{#1}%
-  \def\iffloattype{#2}%
-  \ifx\temp\floatmagic
-}
-
-% @listoffloats FLOATTYPE - print a list of floats like a table of contents.
-%
-\parseargdef\listoffloats{%
-  \def\floattype{#1}% floattype
-  {%
-    % the floattype might have accents or other special characters,
-    % but we need to use it in a control sequence name.
-    \indexnofonts
-    \turnoffactive
-    \xdef\safefloattype{\floattype}%
-  }%
-  %
-  % \xrdef saves the floats as a \do-list in \floatlistSAFEFLOATTYPE.
-  \expandafter\ifx\csname floatlist\safefloattype\endcsname \relax
-    \ifhavexrefs
-      % if the user said @listoffloats foo but never @float foo.
-      \message{\linenumber No `\safefloattype' floats to list.}%
-    \fi
-  \else
-    \begingroup
-      \leftskip=\tocindent  % indent these entries like a toc
-      \let\do=\listoffloatsdo
-      \csname floatlist\safefloattype\endcsname
-    \endgroup
-  \fi
-}
-
-% This is called on each entry in a list of floats.  We're passed the
-% xref label, in the form LABEL-title, which is how we save it in the
-% aux file.  We strip off the -title and look up \XRLABEL-lof, which
-% has the text we're supposed to typeset here.
-%
-% Figures without xref labels will not be included in the list (since
-% they won't appear in the aux file).
-%
-\def\listoffloatsdo#1{\listoffloatsdoentry#1\finish}
-\def\listoffloatsdoentry#1-title\finish{{%
-  % Can't fully expand XR#1-lof because it can contain anything.  Just
-  % pass the control sequence.  On the other hand, XR#1-pg is just the
-  % page number, and we want to fully expand that so we can get a link
-  % in pdf output.
-  \toksA = \expandafter{\csname XR#1-lof\endcsname}%
-  %
-  % use the same \entry macro we use to generate the TOC and index.
-  \edef\writeentry{\noexpand\entry{\the\toksA}{\csname XR#1-pg\endcsname}}%
-  \writeentry
-}}
-
-
-\message{localization,}
-
-% For single-language documents, @documentlanguage is usually given very
-% early, just after @documentencoding.  Single argument is the language
-% (de) or locale (de_DE) abbreviation.
-%
-{
-  \catcode`\_ = \active
-  \globaldefs=1
-\parseargdef\documentlanguage{\begingroup
-  \let_=\normalunderscore  % normal _ character for filenames
-  \tex % read txi-??.tex file in plain TeX.
-    % Read the file by the name they passed if it exists.
-    \openin 1 txi-#1.tex
-    \ifeof 1
-      \documentlanguagetrywithoutunderscore{#1_\finish}%
-    \else
-      \globaldefs = 1  % everything in the txi-LL files needs to persist
-      \input txi-#1.tex
-    \fi
-    \closein 1
-  \endgroup % end raw TeX
-\endgroup}
-%
-% If they passed de_DE, and txi-de_DE.tex doesn't exist,
-% try txi-de.tex.
-%
-\gdef\documentlanguagetrywithoutunderscore#1_#2\finish{%
-  \openin 1 txi-#1.tex
-  \ifeof 1
-    \errhelp = \nolanghelp
-    \errmessage{Cannot read language file txi-#1.tex}%
-  \else
-    \globaldefs = 1  % everything in the txi-LL files needs to persist
-    \input txi-#1.tex
-  \fi
-  \closein 1
-}
-}% end of special _ catcode
-%
-\newhelp\nolanghelp{The given language definition file cannot be found or
-is empty.  Maybe you need to install it?  Putting it in the current
-directory should work if nowhere else does.}
-
-% This macro is called from txi-??.tex files; the first argument is the
-% \language name to set (without the "\lang@" prefix), the second and
-% third args are \{left,right}hyphenmin.
-%
-% The language names to pass are determined when the format is built.
-% See the etex.log file created at that time, e.g.,
-% /usr/local/texlive/2008/texmf-var/web2c/pdftex/etex.log.
-%
-% With TeX Live 2008, etex now includes hyphenation patterns for all
-% available languages.  This means we can support hyphenation in
-% Texinfo, at least to some extent.  (This still doesn't solve the
-% accented characters problem.)
-%
-\catcode`@=11
-\def\txisetlanguage#1#2#3{%
-  % do not set the language if the name is undefined in the current TeX.
-  \expandafter\ifx\csname lang@#1\endcsname \relax
-    \message{no patterns for #1}%
-  \else
-    \global\language = \csname lang@#1\endcsname
-  \fi
-  % but there is no harm in adjusting the hyphenmin values regardless.
-  \global\lefthyphenmin = #2\relax
-  \global\righthyphenmin = #3\relax
-}
-
-% Helpers for encodings.
-% Set the catcode of characters 128 through 255 to the specified number.
-%
-\def\setnonasciicharscatcode#1{%
-   \count255=128
-   \loop\ifnum\count255<256
-      \global\catcode\count255=#1\relax
-      \advance\count255 by 1
-   \repeat
-}
-
-\def\setnonasciicharscatcodenonglobal#1{%
-   \count255=128
-   \loop\ifnum\count255<256
-      \catcode\count255=#1\relax
-      \advance\count255 by 1
-   \repeat
-}
-
-% @documentencoding sets the definition of non-ASCII characters
-% according to the specified encoding.
-%
-\parseargdef\documentencoding{%
-  % Encoding being declared for the document.
-  \def\declaredencoding{\csname #1.enc\endcsname}%
-  %
-  % Supported encodings: names converted to tokens in order to be able
-  % to compare them with \ifx.
-  \def\ascii{\csname US-ASCII.enc\endcsname}%
-  \def\latnine{\csname ISO-8859-15.enc\endcsname}%
-  \def\latone{\csname ISO-8859-1.enc\endcsname}%
-  \def\lattwo{\csname ISO-8859-2.enc\endcsname}%
-  \def\utfeight{\csname UTF-8.enc\endcsname}%
-  %
-  \ifx \declaredencoding \ascii
-     \asciichardefs
-  %
-  \else \ifx \declaredencoding \lattwo
-     \setnonasciicharscatcode\active
-     \lattwochardefs
-  %
-  \else \ifx \declaredencoding \latone
-     \setnonasciicharscatcode\active
-     \latonechardefs
-  %
-  \else \ifx \declaredencoding \latnine
-     \setnonasciicharscatcode\active
-     \latninechardefs
-  %
-  \else \ifx \declaredencoding \utfeight
-     \setnonasciicharscatcode\active
-     \utfeightchardefs
-  %
-  \else
-    \message{Unknown document encoding #1, ignoring.}%
-  %
-  \fi % utfeight
-  \fi % latnine
-  \fi % latone
-  \fi % lattwo
-  \fi % ascii
-}
-
-% A message to be logged when using a character that isn't available
-% the default font encoding (OT1).
-%
-\def\missingcharmsg#1{\message{Character missing in OT1 encoding: #1.}}
-
-% Take account of \c (plain) vs. \, (Texinfo) difference.
-\def\cedilla#1{\ifx\c\ptexc\c{#1}\else\,{#1}\fi}
-
-% First, make active non-ASCII characters in order for them to be
-% correctly categorized when TeX reads the replacement text of
-% macros containing the character definitions.
-\setnonasciicharscatcode\active
-%
-% Latin1 (ISO-8859-1) character definitions.
-\def\latonechardefs{%
-  \gdef^^a0{\tie}
-  \gdef^^a1{\exclamdown}
-  \gdef^^a2{\missingcharmsg{CENT SIGN}}
-  \gdef^^a3{{\pounds}}
-  \gdef^^a4{\missingcharmsg{CURRENCY SIGN}}
-  \gdef^^a5{\missingcharmsg{YEN SIGN}}
-  \gdef^^a6{\missingcharmsg{BROKEN BAR}}
-  \gdef^^a7{\S}
-  \gdef^^a8{\"{}}
-  \gdef^^a9{\copyright}
-  \gdef^^aa{\ordf}
-  \gdef^^ab{\guillemetleft}
-  \gdef^^ac{$\lnot$}
-  \gdef^^ad{\-}
-  \gdef^^ae{\registeredsymbol}
-  \gdef^^af{\={}}
-  %
-  \gdef^^b0{\textdegree}
-  \gdef^^b1{$\pm$}
-  \gdef^^b2{$^2$}
-  \gdef^^b3{$^3$}
-  \gdef^^b4{\'{}}
-  \gdef^^b5{$\mu$}
-  \gdef^^b6{\P}
-  %
-  \gdef^^b7{$^.$}
-  \gdef^^b8{\cedilla\ }
-  \gdef^^b9{$^1$}
-  \gdef^^ba{\ordm}
-  %
-  \gdef^^bb{\guillemetright}
-  \gdef^^bc{$1\over4$}
-  \gdef^^bd{$1\over2$}
-  \gdef^^be{$3\over4$}
-  \gdef^^bf{\questiondown}
-  %
-  \gdef^^c0{\`A}
-  \gdef^^c1{\'A}
-  \gdef^^c2{\^A}
-  \gdef^^c3{\~A}
-  \gdef^^c4{\"A}
-  \gdef^^c5{\ringaccent A}
-  \gdef^^c6{\AE}
-  \gdef^^c7{\cedilla C}
-  \gdef^^c8{\`E}
-  \gdef^^c9{\'E}
-  \gdef^^ca{\^E}
-  \gdef^^cb{\"E}
-  \gdef^^cc{\`I}
-  \gdef^^cd{\'I}
-  \gdef^^ce{\^I}
-  \gdef^^cf{\"I}
-  %
-  \gdef^^d0{\DH}
-  \gdef^^d1{\~N}
-  \gdef^^d2{\`O}
-  \gdef^^d3{\'O}
-  \gdef^^d4{\^O}
-  \gdef^^d5{\~O}
-  \gdef^^d6{\"O}
-  \gdef^^d7{$\times$}
-  \gdef^^d8{\O}
-  \gdef^^d9{\`U}
-  \gdef^^da{\'U}
-  \gdef^^db{\^U}
-  \gdef^^dc{\"U}
-  \gdef^^dd{\'Y}
-  \gdef^^de{\TH}
-  \gdef^^df{\ss}
-  %
-  \gdef^^e0{\`a}
-  \gdef^^e1{\'a}
-  \gdef^^e2{\^a}
-  \gdef^^e3{\~a}
-  \gdef^^e4{\"a}
-  \gdef^^e5{\ringaccent a}
-  \gdef^^e6{\ae}
-  \gdef^^e7{\cedilla c}
-  \gdef^^e8{\`e}
-  \gdef^^e9{\'e}
-  \gdef^^ea{\^e}
-  \gdef^^eb{\"e}
-  \gdef^^ec{\`{\dotless i}}
-  \gdef^^ed{\'{\dotless i}}
-  \gdef^^ee{\^{\dotless i}}
-  \gdef^^ef{\"{\dotless i}}
-  %
-  \gdef^^f0{\dh}
-  \gdef^^f1{\~n}
-  \gdef^^f2{\`o}
-  \gdef^^f3{\'o}
-  \gdef^^f4{\^o}
-  \gdef^^f5{\~o}
-  \gdef^^f6{\"o}
-  \gdef^^f7{$\div$}
-  \gdef^^f8{\o}
-  \gdef^^f9{\`u}
-  \gdef^^fa{\'u}
-  \gdef^^fb{\^u}
-  \gdef^^fc{\"u}
-  \gdef^^fd{\'y}
-  \gdef^^fe{\th}
-  \gdef^^ff{\"y}
-}
-
-% Latin9 (ISO-8859-15) encoding character definitions.
-\def\latninechardefs{%
-  % Encoding is almost identical to Latin1.
-  \latonechardefs
-  %
-  \gdef^^a4{\euro}
-  \gdef^^a6{\v S}
-  \gdef^^a8{\v s}
-  \gdef^^b4{\v Z}
-  \gdef^^b8{\v z}
-  \gdef^^bc{\OE}
-  \gdef^^bd{\oe}
-  \gdef^^be{\"Y}
-}
-
-% Latin2 (ISO-8859-2) character definitions.
-\def\lattwochardefs{%
-  \gdef^^a0{\tie}
-  \gdef^^a1{\ogonek{A}}
-  \gdef^^a2{\u{}}
-  \gdef^^a3{\L}
-  \gdef^^a4{\missingcharmsg{CURRENCY SIGN}}
-  \gdef^^a5{\v L}
-  \gdef^^a6{\'S}
-  \gdef^^a7{\S}
-  \gdef^^a8{\"{}}
-  \gdef^^a9{\v S}
-  \gdef^^aa{\cedilla S}
-  \gdef^^ab{\v T}
-  \gdef^^ac{\'Z}
-  \gdef^^ad{\-}
-  \gdef^^ae{\v Z}
-  \gdef^^af{\dotaccent Z}
-  %
-  \gdef^^b0{\textdegree}
-  \gdef^^b1{\ogonek{a}}
-  \gdef^^b2{\ogonek{ }}
-  \gdef^^b3{\l}
-  \gdef^^b4{\'{}}
-  \gdef^^b5{\v l}
-  \gdef^^b6{\'s}
-  \gdef^^b7{\v{}}
-  \gdef^^b8{\cedilla\ }
-  \gdef^^b9{\v s}
-  \gdef^^ba{\cedilla s}
-  \gdef^^bb{\v t}
-  \gdef^^bc{\'z}
-  \gdef^^bd{\H{}}
-  \gdef^^be{\v z}
-  \gdef^^bf{\dotaccent z}
-  %
-  \gdef^^c0{\'R}
-  \gdef^^c1{\'A}
-  \gdef^^c2{\^A}
-  \gdef^^c3{\u A}
-  \gdef^^c4{\"A}
-  \gdef^^c5{\'L}
-  \gdef^^c6{\'C}
-  \gdef^^c7{\cedilla C}
-  \gdef^^c8{\v C}
-  \gdef^^c9{\'E}
-  \gdef^^ca{\ogonek{E}}
-  \gdef^^cb{\"E}
-  \gdef^^cc{\v E}
-  \gdef^^cd{\'I}
-  \gdef^^ce{\^I}
-  \gdef^^cf{\v D}
-  %
-  \gdef^^d0{\DH}
-  \gdef^^d1{\'N}
-  \gdef^^d2{\v N}
-  \gdef^^d3{\'O}
-  \gdef^^d4{\^O}
-  \gdef^^d5{\H O}
-  \gdef^^d6{\"O}
-  \gdef^^d7{$\times$}
-  \gdef^^d8{\v R}
-  \gdef^^d9{\ringaccent U}
-  \gdef^^da{\'U}
-  \gdef^^db{\H U}
-  \gdef^^dc{\"U}
-  \gdef^^dd{\'Y}
-  \gdef^^de{\cedilla T}
-  \gdef^^df{\ss}
-  %
-  \gdef^^e0{\'r}
-  \gdef^^e1{\'a}
-  \gdef^^e2{\^a}
-  \gdef^^e3{\u a}
-  \gdef^^e4{\"a}
-  \gdef^^e5{\'l}
-  \gdef^^e6{\'c}
-  \gdef^^e7{\cedilla c}
-  \gdef^^e8{\v c}
-  \gdef^^e9{\'e}
-  \gdef^^ea{\ogonek{e}}
-  \gdef^^eb{\"e}
-  \gdef^^ec{\v e}
-  \gdef^^ed{\'{\dotless{i}}}
-  \gdef^^ee{\^{\dotless{i}}}
-  \gdef^^ef{\v d}
-  %
-  \gdef^^f0{\dh}
-  \gdef^^f1{\'n}
-  \gdef^^f2{\v n}
-  \gdef^^f3{\'o}
-  \gdef^^f4{\^o}
-  \gdef^^f5{\H o}
-  \gdef^^f6{\"o}
-  \gdef^^f7{$\div$}
-  \gdef^^f8{\v r}
-  \gdef^^f9{\ringaccent u}
-  \gdef^^fa{\'u}
-  \gdef^^fb{\H u}
-  \gdef^^fc{\"u}
-  \gdef^^fd{\'y}
-  \gdef^^fe{\cedilla t}
-  \gdef^^ff{\dotaccent{}}
-}
-
-% UTF-8 character definitions.
-%
-% This code to support UTF-8 is based on LaTeX's utf8.def, with some
-% changes for Texinfo conventions.  It is included here under the GPL by
-% permission from Frank Mittelbach and the LaTeX team.
-%
-\newcount\countUTFx
-\newcount\countUTFy
-\newcount\countUTFz
-
-\gdef\UTFviiiTwoOctets#1#2{\expandafter
-   \UTFviiiDefined\csname u8:#1\string #2\endcsname}
-%
-\gdef\UTFviiiThreeOctets#1#2#3{\expandafter
-   \UTFviiiDefined\csname u8:#1\string #2\string #3\endcsname}
-%
-\gdef\UTFviiiFourOctets#1#2#3#4{\expandafter
-   \UTFviiiDefined\csname u8:#1\string #2\string #3\string #4\endcsname}
-
-\gdef\UTFviiiDefined#1{%
-  \ifx #1\relax
-    \message{\linenumber Unicode char \string #1 not defined for Texinfo}%
-  \else
-    \expandafter #1%
-  \fi
-}
-
-\begingroup
-  \catcode`\~13
-  \catcode`\"12
-
-  \def\UTFviiiLoop{%
-    \global\catcode\countUTFx\active
-    \uccode`\~\countUTFx
-    \uppercase\expandafter{\UTFviiiTmp}%
-    \advance\countUTFx by 1
-    \ifnum\countUTFx < \countUTFy
-      \expandafter\UTFviiiLoop
-    \fi}
-
-  \countUTFx = "C2
-  \countUTFy = "E0
-  \def\UTFviiiTmp{%
-    \xdef~{\noexpand\UTFviiiTwoOctets\string~}}
-  \UTFviiiLoop
-
-  \countUTFx = "E0
-  \countUTFy = "F0
-  \def\UTFviiiTmp{%
-    \xdef~{\noexpand\UTFviiiThreeOctets\string~}}
-  \UTFviiiLoop
-
-  \countUTFx = "F0
-  \countUTFy = "F4
-  \def\UTFviiiTmp{%
-    \xdef~{\noexpand\UTFviiiFourOctets\string~}}
-  \UTFviiiLoop
-\endgroup
-
-\begingroup
-  \catcode`\"=12
-  \catcode`\<=12
-  \catcode`\.=12
-  \catcode`\,=12
-  \catcode`\;=12
-  \catcode`\!=12
-  \catcode`\~=13
-
-  \gdef\DeclareUnicodeCharacter#1#2{%
-    \countUTFz = "#1\relax
-    %\wlog{\space\space defining Unicode char U+#1 (decimal \the\countUTFz)}%
-    \begingroup
-      \parseXMLCharref
-      \def\UTFviiiTwoOctets##1##2{%
-        \csname u8:##1\string ##2\endcsname}%
-      \def\UTFviiiThreeOctets##1##2##3{%
-        \csname u8:##1\string ##2\string ##3\endcsname}%
-      \def\UTFviiiFourOctets##1##2##3##4{%
-        \csname u8:##1\string ##2\string ##3\string ##4\endcsname}%
-      \expandafter\expandafter\expandafter\expandafter
-       \expandafter\expandafter\expandafter
-       \gdef\UTFviiiTmp{#2}%
-    \endgroup}
-
-  \gdef\parseXMLCharref{%
-    \ifnum\countUTFz < "A0\relax
-      \errhelp = \EMsimple
-      \errmessage{Cannot define Unicode char value < 00A0}%
-    \else\ifnum\countUTFz < "800\relax
-      \parseUTFviiiA,%
-      \parseUTFviiiB C\UTFviiiTwoOctets.,%
-    \else\ifnum\countUTFz < "10000\relax
-      \parseUTFviiiA;%
-      \parseUTFviiiA,%
-      \parseUTFviiiB E\UTFviiiThreeOctets.{,;}%
-    \else
-      \parseUTFviiiA;%
-      \parseUTFviiiA,%
-      \parseUTFviiiA!%
-      \parseUTFviiiB F\UTFviiiFourOctets.{!,;}%
-    \fi\fi\fi
-  }
-
-  \gdef\parseUTFviiiA#1{%
-    \countUTFx = \countUTFz
-    \divide\countUTFz by 64
-    \countUTFy = \countUTFz
-    \multiply\countUTFz by 64
-    \advance\countUTFx by -\countUTFz
-    \advance\countUTFx by 128
-    \uccode `#1\countUTFx
-    \countUTFz = \countUTFy}
-
-  \gdef\parseUTFviiiB#1#2#3#4{%
-    \advance\countUTFz by "#10\relax
-    \uccode `#3\countUTFz
-    \uppercase{\gdef\UTFviiiTmp{#2#3#4}}}
-\endgroup
-
-\def\utfeightchardefs{%
-  \DeclareUnicodeCharacter{00A0}{\tie}
-  \DeclareUnicodeCharacter{00A1}{\exclamdown}
-  \DeclareUnicodeCharacter{00A3}{\pounds}
-  \DeclareUnicodeCharacter{00A8}{\"{ }}
-  \DeclareUnicodeCharacter{00A9}{\copyright}
-  \DeclareUnicodeCharacter{00AA}{\ordf}
-  \DeclareUnicodeCharacter{00AB}{\guillemetleft}
-  \DeclareUnicodeCharacter{00AD}{\-}
-  \DeclareUnicodeCharacter{00AE}{\registeredsymbol}
-  \DeclareUnicodeCharacter{00AF}{\={ }}
-
-  \DeclareUnicodeCharacter{00B0}{\ringaccent{ }}
-  \DeclareUnicodeCharacter{00B4}{\'{ }}
-  \DeclareUnicodeCharacter{00B8}{\cedilla{ }}
-  \DeclareUnicodeCharacter{00BA}{\ordm}
-  \DeclareUnicodeCharacter{00BB}{\guillemetright}
-  \DeclareUnicodeCharacter{00BF}{\questiondown}
-
-  \DeclareUnicodeCharacter{00C0}{\`A}
-  \DeclareUnicodeCharacter{00C1}{\'A}
-  \DeclareUnicodeCharacter{00C2}{\^A}
-  \DeclareUnicodeCharacter{00C3}{\~A}
-  \DeclareUnicodeCharacter{00C4}{\"A}
-  \DeclareUnicodeCharacter{00C5}{\AA}
-  \DeclareUnicodeCharacter{00C6}{\AE}
-  \DeclareUnicodeCharacter{00C7}{\cedilla{C}}
-  \DeclareUnicodeCharacter{00C8}{\`E}
-  \DeclareUnicodeCharacter{00C9}{\'E}
-  \DeclareUnicodeCharacter{00CA}{\^E}
-  \DeclareUnicodeCharacter{00CB}{\"E}
-  \DeclareUnicodeCharacter{00CC}{\`I}
-  \DeclareUnicodeCharacter{00CD}{\'I}
-  \DeclareUnicodeCharacter{00CE}{\^I}
-  \DeclareUnicodeCharacter{00CF}{\"I}
-
-  \DeclareUnicodeCharacter{00D0}{\DH}
-  \DeclareUnicodeCharacter{00D1}{\~N}
-  \DeclareUnicodeCharacter{00D2}{\`O}
-  \DeclareUnicodeCharacter{00D3}{\'O}
-  \DeclareUnicodeCharacter{00D4}{\^O}
-  \DeclareUnicodeCharacter{00D5}{\~O}
-  \DeclareUnicodeCharacter{00D6}{\"O}
-  \DeclareUnicodeCharacter{00D8}{\O}
-  \DeclareUnicodeCharacter{00D9}{\`U}
-  \DeclareUnicodeCharacter{00DA}{\'U}
-  \DeclareUnicodeCharacter{00DB}{\^U}
-  \DeclareUnicodeCharacter{00DC}{\"U}
-  \DeclareUnicodeCharacter{00DD}{\'Y}
-  \DeclareUnicodeCharacter{00DE}{\TH}
-  \DeclareUnicodeCharacter{00DF}{\ss}
-
-  \DeclareUnicodeCharacter{00E0}{\`a}
-  \DeclareUnicodeCharacter{00E1}{\'a}
-  \DeclareUnicodeCharacter{00E2}{\^a}
-  \DeclareUnicodeCharacter{00E3}{\~a}
-  \DeclareUnicodeCharacter{00E4}{\"a}
-  \DeclareUnicodeCharacter{00E5}{\aa}
-  \DeclareUnicodeCharacter{00E6}{\ae}
-  \DeclareUnicodeCharacter{00E7}{\cedilla{c}}
-  \DeclareUnicodeCharacter{00E8}{\`e}
-  \DeclareUnicodeCharacter{00E9}{\'e}
-  \DeclareUnicodeCharacter{00EA}{\^e}
-  \DeclareUnicodeCharacter{00EB}{\"e}
-  \DeclareUnicodeCharacter{00EC}{\`{\dotless{i}}}
-  \DeclareUnicodeCharacter{00ED}{\'{\dotless{i}}}
-  \DeclareUnicodeCharacter{00EE}{\^{\dotless{i}}}
-  \DeclareUnicodeCharacter{00EF}{\"{\dotless{i}}}
-
-  \DeclareUnicodeCharacter{00F0}{\dh}
-  \DeclareUnicodeCharacter{00F1}{\~n}
-  \DeclareUnicodeCharacter{00F2}{\`o}
-  \DeclareUnicodeCharacter{00F3}{\'o}
-  \DeclareUnicodeCharacter{00F4}{\^o}
-  \DeclareUnicodeCharacter{00F5}{\~o}
-  \DeclareUnicodeCharacter{00F6}{\"o}
-  \DeclareUnicodeCharacter{00F8}{\o}
-  \DeclareUnicodeCharacter{00F9}{\`u}
-  \DeclareUnicodeCharacter{00FA}{\'u}
-  \DeclareUnicodeCharacter{00FB}{\^u}
-  \DeclareUnicodeCharacter{00FC}{\"u}
-  \DeclareUnicodeCharacter{00FD}{\'y}
-  \DeclareUnicodeCharacter{00FE}{\th}
-  \DeclareUnicodeCharacter{00FF}{\"y}
-
-  \DeclareUnicodeCharacter{0100}{\=A}
-  \DeclareUnicodeCharacter{0101}{\=a}
-  \DeclareUnicodeCharacter{0102}{\u{A}}
-  \DeclareUnicodeCharacter{0103}{\u{a}}
-  \DeclareUnicodeCharacter{0104}{\ogonek{A}}
-  \DeclareUnicodeCharacter{0105}{\ogonek{a}}
-  \DeclareUnicodeCharacter{0106}{\'C}
-  \DeclareUnicodeCharacter{0107}{\'c}
-  \DeclareUnicodeCharacter{0108}{\^C}
-  \DeclareUnicodeCharacter{0109}{\^c}
-  \DeclareUnicodeCharacter{0118}{\ogonek{E}}
-  \DeclareUnicodeCharacter{0119}{\ogonek{e}}
-  \DeclareUnicodeCharacter{010A}{\dotaccent{C}}
-  \DeclareUnicodeCharacter{010B}{\dotaccent{c}}
-  \DeclareUnicodeCharacter{010C}{\v{C}}
-  \DeclareUnicodeCharacter{010D}{\v{c}}
-  \DeclareUnicodeCharacter{010E}{\v{D}}
-
-  \DeclareUnicodeCharacter{0112}{\=E}
-  \DeclareUnicodeCharacter{0113}{\=e}
-  \DeclareUnicodeCharacter{0114}{\u{E}}
-  \DeclareUnicodeCharacter{0115}{\u{e}}
-  \DeclareUnicodeCharacter{0116}{\dotaccent{E}}
-  \DeclareUnicodeCharacter{0117}{\dotaccent{e}}
-  \DeclareUnicodeCharacter{011A}{\v{E}}
-  \DeclareUnicodeCharacter{011B}{\v{e}}
-  \DeclareUnicodeCharacter{011C}{\^G}
-  \DeclareUnicodeCharacter{011D}{\^g}
-  \DeclareUnicodeCharacter{011E}{\u{G}}
-  \DeclareUnicodeCharacter{011F}{\u{g}}
-
-  \DeclareUnicodeCharacter{0120}{\dotaccent{G}}
-  \DeclareUnicodeCharacter{0121}{\dotaccent{g}}
-  \DeclareUnicodeCharacter{0124}{\^H}
-  \DeclareUnicodeCharacter{0125}{\^h}
-  \DeclareUnicodeCharacter{0128}{\~I}
-  \DeclareUnicodeCharacter{0129}{\~{\dotless{i}}}
-  \DeclareUnicodeCharacter{012A}{\=I}
-  \DeclareUnicodeCharacter{012B}{\={\dotless{i}}}
-  \DeclareUnicodeCharacter{012C}{\u{I}}
-  \DeclareUnicodeCharacter{012D}{\u{\dotless{i}}}
-
-  \DeclareUnicodeCharacter{0130}{\dotaccent{I}}
-  \DeclareUnicodeCharacter{0131}{\dotless{i}}
-  \DeclareUnicodeCharacter{0132}{IJ}
-  \DeclareUnicodeCharacter{0133}{ij}
-  \DeclareUnicodeCharacter{0134}{\^J}
-  \DeclareUnicodeCharacter{0135}{\^{\dotless{j}}}
-  \DeclareUnicodeCharacter{0139}{\'L}
-  \DeclareUnicodeCharacter{013A}{\'l}
-
-  \DeclareUnicodeCharacter{0141}{\L}
-  \DeclareUnicodeCharacter{0142}{\l}
-  \DeclareUnicodeCharacter{0143}{\'N}
-  \DeclareUnicodeCharacter{0144}{\'n}
-  \DeclareUnicodeCharacter{0147}{\v{N}}
-  \DeclareUnicodeCharacter{0148}{\v{n}}
-  \DeclareUnicodeCharacter{014C}{\=O}
-  \DeclareUnicodeCharacter{014D}{\=o}
-  \DeclareUnicodeCharacter{014E}{\u{O}}
-  \DeclareUnicodeCharacter{014F}{\u{o}}
-
-  \DeclareUnicodeCharacter{0150}{\H{O}}
-  \DeclareUnicodeCharacter{0151}{\H{o}}
-  \DeclareUnicodeCharacter{0152}{\OE}
-  \DeclareUnicodeCharacter{0153}{\oe}
-  \DeclareUnicodeCharacter{0154}{\'R}
-  \DeclareUnicodeCharacter{0155}{\'r}
-  \DeclareUnicodeCharacter{0158}{\v{R}}
-  \DeclareUnicodeCharacter{0159}{\v{r}}
-  \DeclareUnicodeCharacter{015A}{\'S}
-  \DeclareUnicodeCharacter{015B}{\'s}
-  \DeclareUnicodeCharacter{015C}{\^S}
-  \DeclareUnicodeCharacter{015D}{\^s}
-  \DeclareUnicodeCharacter{015E}{\cedilla{S}}
-  \DeclareUnicodeCharacter{015F}{\cedilla{s}}
-
-  \DeclareUnicodeCharacter{0160}{\v{S}}
-  \DeclareUnicodeCharacter{0161}{\v{s}}
-  \DeclareUnicodeCharacter{0162}{\cedilla{t}}
-  \DeclareUnicodeCharacter{0163}{\cedilla{T}}
-  \DeclareUnicodeCharacter{0164}{\v{T}}
-
-  \DeclareUnicodeCharacter{0168}{\~U}
-  \DeclareUnicodeCharacter{0169}{\~u}
-  \DeclareUnicodeCharacter{016A}{\=U}
-  \DeclareUnicodeCharacter{016B}{\=u}
-  \DeclareUnicodeCharacter{016C}{\u{U}}
-  \DeclareUnicodeCharacter{016D}{\u{u}}
-  \DeclareUnicodeCharacter{016E}{\ringaccent{U}}
-  \DeclareUnicodeCharacter{016F}{\ringaccent{u}}
-
-  \DeclareUnicodeCharacter{0170}{\H{U}}
-  \DeclareUnicodeCharacter{0171}{\H{u}}
-  \DeclareUnicodeCharacter{0174}{\^W}
-  \DeclareUnicodeCharacter{0175}{\^w}
-  \DeclareUnicodeCharacter{0176}{\^Y}
-  \DeclareUnicodeCharacter{0177}{\^y}
-  \DeclareUnicodeCharacter{0178}{\"Y}
-  \DeclareUnicodeCharacter{0179}{\'Z}
-  \DeclareUnicodeCharacter{017A}{\'z}
-  \DeclareUnicodeCharacter{017B}{\dotaccent{Z}}
-  \DeclareUnicodeCharacter{017C}{\dotaccent{z}}
-  \DeclareUnicodeCharacter{017D}{\v{Z}}
-  \DeclareUnicodeCharacter{017E}{\v{z}}
-
-  \DeclareUnicodeCharacter{01C4}{D\v{Z}}
-  \DeclareUnicodeCharacter{01C5}{D\v{z}}
-  \DeclareUnicodeCharacter{01C6}{d\v{z}}
-  \DeclareUnicodeCharacter{01C7}{LJ}
-  \DeclareUnicodeCharacter{01C8}{Lj}
-  \DeclareUnicodeCharacter{01C9}{lj}
-  \DeclareUnicodeCharacter{01CA}{NJ}
-  \DeclareUnicodeCharacter{01CB}{Nj}
-  \DeclareUnicodeCharacter{01CC}{nj}
-  \DeclareUnicodeCharacter{01CD}{\v{A}}
-  \DeclareUnicodeCharacter{01CE}{\v{a}}
-  \DeclareUnicodeCharacter{01CF}{\v{I}}
-
-  \DeclareUnicodeCharacter{01D0}{\v{\dotless{i}}}
-  \DeclareUnicodeCharacter{01D1}{\v{O}}
-  \DeclareUnicodeCharacter{01D2}{\v{o}}
-  \DeclareUnicodeCharacter{01D3}{\v{U}}
-  \DeclareUnicodeCharacter{01D4}{\v{u}}
-
-  \DeclareUnicodeCharacter{01E2}{\={\AE}}
-  \DeclareUnicodeCharacter{01E3}{\={\ae}}
-  \DeclareUnicodeCharacter{01E6}{\v{G}}
-  \DeclareUnicodeCharacter{01E7}{\v{g}}
-  \DeclareUnicodeCharacter{01E8}{\v{K}}
-  \DeclareUnicodeCharacter{01E9}{\v{k}}
-
-  \DeclareUnicodeCharacter{01F0}{\v{\dotless{j}}}
-  \DeclareUnicodeCharacter{01F1}{DZ}
-  \DeclareUnicodeCharacter{01F2}{Dz}
-  \DeclareUnicodeCharacter{01F3}{dz}
-  \DeclareUnicodeCharacter{01F4}{\'G}
-  \DeclareUnicodeCharacter{01F5}{\'g}
-  \DeclareUnicodeCharacter{01F8}{\`N}
-  \DeclareUnicodeCharacter{01F9}{\`n}
-  \DeclareUnicodeCharacter{01FC}{\'{\AE}}
-  \DeclareUnicodeCharacter{01FD}{\'{\ae}}
-  \DeclareUnicodeCharacter{01FE}{\'{\O}}
-  \DeclareUnicodeCharacter{01FF}{\'{\o}}
-
-  \DeclareUnicodeCharacter{021E}{\v{H}}
-  \DeclareUnicodeCharacter{021F}{\v{h}}
-
-  \DeclareUnicodeCharacter{0226}{\dotaccent{A}}
-  \DeclareUnicodeCharacter{0227}{\dotaccent{a}}
-  \DeclareUnicodeCharacter{0228}{\cedilla{E}}
-  \DeclareUnicodeCharacter{0229}{\cedilla{e}}
-  \DeclareUnicodeCharacter{022E}{\dotaccent{O}}
-  \DeclareUnicodeCharacter{022F}{\dotaccent{o}}
-
-  \DeclareUnicodeCharacter{0232}{\=Y}
-  \DeclareUnicodeCharacter{0233}{\=y}
-  \DeclareUnicodeCharacter{0237}{\dotless{j}}
-
-  \DeclareUnicodeCharacter{02DB}{\ogonek{ }}
-
-  \DeclareUnicodeCharacter{1E02}{\dotaccent{B}}
-  \DeclareUnicodeCharacter{1E03}{\dotaccent{b}}
-  \DeclareUnicodeCharacter{1E04}{\udotaccent{B}}
-  \DeclareUnicodeCharacter{1E05}{\udotaccent{b}}
-  \DeclareUnicodeCharacter{1E06}{\ubaraccent{B}}
-  \DeclareUnicodeCharacter{1E07}{\ubaraccent{b}}
-  \DeclareUnicodeCharacter{1E0A}{\dotaccent{D}}
-  \DeclareUnicodeCharacter{1E0B}{\dotaccent{d}}
-  \DeclareUnicodeCharacter{1E0C}{\udotaccent{D}}
-  \DeclareUnicodeCharacter{1E0D}{\udotaccent{d}}
-  \DeclareUnicodeCharacter{1E0E}{\ubaraccent{D}}
-  \DeclareUnicodeCharacter{1E0F}{\ubaraccent{d}}
-
-  \DeclareUnicodeCharacter{1E1E}{\dotaccent{F}}
-  \DeclareUnicodeCharacter{1E1F}{\dotaccent{f}}
-
-  \DeclareUnicodeCharacter{1E20}{\=G}
-  \DeclareUnicodeCharacter{1E21}{\=g}
-  \DeclareUnicodeCharacter{1E22}{\dotaccent{H}}
-  \DeclareUnicodeCharacter{1E23}{\dotaccent{h}}
-  \DeclareUnicodeCharacter{1E24}{\udotaccent{H}}
-  \DeclareUnicodeCharacter{1E25}{\udotaccent{h}}
-  \DeclareUnicodeCharacter{1E26}{\"H}
-  \DeclareUnicodeCharacter{1E27}{\"h}
-
-  \DeclareUnicodeCharacter{1E30}{\'K}
-  \DeclareUnicodeCharacter{1E31}{\'k}
-  \DeclareUnicodeCharacter{1E32}{\udotaccent{K}}
-  \DeclareUnicodeCharacter{1E33}{\udotaccent{k}}
-  \DeclareUnicodeCharacter{1E34}{\ubaraccent{K}}
-  \DeclareUnicodeCharacter{1E35}{\ubaraccent{k}}
-  \DeclareUnicodeCharacter{1E36}{\udotaccent{L}}
-  \DeclareUnicodeCharacter{1E37}{\udotaccent{l}}
-  \DeclareUnicodeCharacter{1E3A}{\ubaraccent{L}}
-  \DeclareUnicodeCharacter{1E3B}{\ubaraccent{l}}
-  \DeclareUnicodeCharacter{1E3E}{\'M}
-  \DeclareUnicodeCharacter{1E3F}{\'m}
-
-  \DeclareUnicodeCharacter{1E40}{\dotaccent{M}}
-  \DeclareUnicodeCharacter{1E41}{\dotaccent{m}}
-  \DeclareUnicodeCharacter{1E42}{\udotaccent{M}}
-  \DeclareUnicodeCharacter{1E43}{\udotaccent{m}}
-  \DeclareUnicodeCharacter{1E44}{\dotaccent{N}}
-  \DeclareUnicodeCharacter{1E45}{\dotaccent{n}}
-  \DeclareUnicodeCharacter{1E46}{\udotaccent{N}}
-  \DeclareUnicodeCharacter{1E47}{\udotaccent{n}}
-  \DeclareUnicodeCharacter{1E48}{\ubaraccent{N}}
-  \DeclareUnicodeCharacter{1E49}{\ubaraccent{n}}
-
-  \DeclareUnicodeCharacter{1E54}{\'P}
-  \DeclareUnicodeCharacter{1E55}{\'p}
-  \DeclareUnicodeCharacter{1E56}{\dotaccent{P}}
-  \DeclareUnicodeCharacter{1E57}{\dotaccent{p}}
-  \DeclareUnicodeCharacter{1E58}{\dotaccent{R}}
-  \DeclareUnicodeCharacter{1E59}{\dotaccent{r}}
-  \DeclareUnicodeCharacter{1E5A}{\udotaccent{R}}
-  \DeclareUnicodeCharacter{1E5B}{\udotaccent{r}}
-  \DeclareUnicodeCharacter{1E5E}{\ubaraccent{R}}
-  \DeclareUnicodeCharacter{1E5F}{\ubaraccent{r}}
-
-  \DeclareUnicodeCharacter{1E60}{\dotaccent{S}}
-  \DeclareUnicodeCharacter{1E61}{\dotaccent{s}}
-  \DeclareUnicodeCharacter{1E62}{\udotaccent{S}}
-  \DeclareUnicodeCharacter{1E63}{\udotaccent{s}}
-  \DeclareUnicodeCharacter{1E6A}{\dotaccent{T}}
-  \DeclareUnicodeCharacter{1E6B}{\dotaccent{t}}
-  \DeclareUnicodeCharacter{1E6C}{\udotaccent{T}}
-  \DeclareUnicodeCharacter{1E6D}{\udotaccent{t}}
-  \DeclareUnicodeCharacter{1E6E}{\ubaraccent{T}}
-  \DeclareUnicodeCharacter{1E6F}{\ubaraccent{t}}
-
-  \DeclareUnicodeCharacter{1E7C}{\~V}
-  \DeclareUnicodeCharacter{1E7D}{\~v}
-  \DeclareUnicodeCharacter{1E7E}{\udotaccent{V}}
-  \DeclareUnicodeCharacter{1E7F}{\udotaccent{v}}
-
-  \DeclareUnicodeCharacter{1E80}{\`W}
-  \DeclareUnicodeCharacter{1E81}{\`w}
-  \DeclareUnicodeCharacter{1E82}{\'W}
-  \DeclareUnicodeCharacter{1E83}{\'w}
-  \DeclareUnicodeCharacter{1E84}{\"W}
-  \DeclareUnicodeCharacter{1E85}{\"w}
-  \DeclareUnicodeCharacter{1E86}{\dotaccent{W}}
-  \DeclareUnicodeCharacter{1E87}{\dotaccent{w}}
-  \DeclareUnicodeCharacter{1E88}{\udotaccent{W}}
-  \DeclareUnicodeCharacter{1E89}{\udotaccent{w}}
-  \DeclareUnicodeCharacter{1E8A}{\dotaccent{X}}
-  \DeclareUnicodeCharacter{1E8B}{\dotaccent{x}}
-  \DeclareUnicodeCharacter{1E8C}{\"X}
-  \DeclareUnicodeCharacter{1E8D}{\"x}
-  \DeclareUnicodeCharacter{1E8E}{\dotaccent{Y}}
-  \DeclareUnicodeCharacter{1E8F}{\dotaccent{y}}
-
-  \DeclareUnicodeCharacter{1E90}{\^Z}
-  \DeclareUnicodeCharacter{1E91}{\^z}
-  \DeclareUnicodeCharacter{1E92}{\udotaccent{Z}}
-  \DeclareUnicodeCharacter{1E93}{\udotaccent{z}}
-  \DeclareUnicodeCharacter{1E94}{\ubaraccent{Z}}
-  \DeclareUnicodeCharacter{1E95}{\ubaraccent{z}}
-  \DeclareUnicodeCharacter{1E96}{\ubaraccent{h}}
-  \DeclareUnicodeCharacter{1E97}{\"t}
-  \DeclareUnicodeCharacter{1E98}{\ringaccent{w}}
-  \DeclareUnicodeCharacter{1E99}{\ringaccent{y}}
-
-  \DeclareUnicodeCharacter{1EA0}{\udotaccent{A}}
-  \DeclareUnicodeCharacter{1EA1}{\udotaccent{a}}
-
-  \DeclareUnicodeCharacter{1EB8}{\udotaccent{E}}
-  \DeclareUnicodeCharacter{1EB9}{\udotaccent{e}}
-  \DeclareUnicodeCharacter{1EBC}{\~E}
-  \DeclareUnicodeCharacter{1EBD}{\~e}
-
-  \DeclareUnicodeCharacter{1ECA}{\udotaccent{I}}
-  \DeclareUnicodeCharacter{1ECB}{\udotaccent{i}}
-  \DeclareUnicodeCharacter{1ECC}{\udotaccent{O}}
-  \DeclareUnicodeCharacter{1ECD}{\udotaccent{o}}
-
-  \DeclareUnicodeCharacter{1EE4}{\udotaccent{U}}
-  \DeclareUnicodeCharacter{1EE5}{\udotaccent{u}}
-
-  \DeclareUnicodeCharacter{1EF2}{\`Y}
-  \DeclareUnicodeCharacter{1EF3}{\`y}
-  \DeclareUnicodeCharacter{1EF4}{\udotaccent{Y}}
-
-  \DeclareUnicodeCharacter{1EF8}{\~Y}
-  \DeclareUnicodeCharacter{1EF9}{\~y}
-
-  \DeclareUnicodeCharacter{2013}{--}
-  \DeclareUnicodeCharacter{2014}{---}
-  \DeclareUnicodeCharacter{2018}{\quoteleft}
-  \DeclareUnicodeCharacter{2019}{\quoteright}
-  \DeclareUnicodeCharacter{201A}{\quotesinglbase}
-  \DeclareUnicodeCharacter{201C}{\quotedblleft}
-  \DeclareUnicodeCharacter{201D}{\quotedblright}
-  \DeclareUnicodeCharacter{201E}{\quotedblbase}
-  \DeclareUnicodeCharacter{2022}{\bullet}
-  \DeclareUnicodeCharacter{2026}{\dots}
-  \DeclareUnicodeCharacter{2039}{\guilsinglleft}
-  \DeclareUnicodeCharacter{203A}{\guilsinglright}
-  \DeclareUnicodeCharacter{20AC}{\euro}
-
-  \DeclareUnicodeCharacter{2192}{\expansion}
-  \DeclareUnicodeCharacter{21D2}{\result}
-
-  \DeclareUnicodeCharacter{2212}{\minus}
-  \DeclareUnicodeCharacter{2217}{\point}
-  \DeclareUnicodeCharacter{2261}{\equiv}
-}% end of \utfeightchardefs
-
-
-% US-ASCII character definitions.
-\def\asciichardefs{% nothing need be done
-   \relax
-}
-
-% Make non-ASCII characters printable again for compatibility with
-% existing Texinfo documents that may use them, even without declaring a
-% document encoding.
-%
-\setnonasciicharscatcode \other
-
-
-\message{formatting,}
-
-\newdimen\defaultparindent \defaultparindent = 15pt
-
-\chapheadingskip = 15pt plus 4pt minus 2pt
-\secheadingskip = 12pt plus 3pt minus 2pt
-\subsecheadingskip = 9pt plus 2pt minus 2pt
-
-% Prevent underfull vbox error messages.
-\vbadness = 10000
-
-% Don't be very finicky about underfull hboxes, either.
-\hbadness = 6666
-
-% Following George Bush, get rid of widows and orphans.
-\widowpenalty=10000
-\clubpenalty=10000
-
-% Use TeX 3.0's \emergencystretch to help line breaking, but if we're
-% using an old version of TeX, don't do anything.  We want the amount of
-% stretch added to depend on the line length, hence the dependence on
-% \hsize.  We call this whenever the paper size is set.
-%
-\def\setemergencystretch{%
-  \ifx\emergencystretch\thisisundefined
-    % Allow us to assign to \emergencystretch anyway.
-    \def\emergencystretch{\dimen0}%
-  \else
-    \emergencystretch = .15\hsize
-  \fi
-}
-
-% Parameters in order: 1) textheight; 2) textwidth;
-% 3) voffset; 4) hoffset; 5) binding offset; 6) topskip;
-% 7) physical page height; 8) physical page width.
-%
-% We also call \setleading{\textleading}, so the caller should define
-% \textleading.  The caller should also set \parskip.
-%
-\def\internalpagesizes#1#2#3#4#5#6#7#8{%
-  \voffset = #3\relax
-  \topskip = #6\relax
-  \splittopskip = \topskip
-  %
-  \vsize = #1\relax
-  \advance\vsize by \topskip
-  \outervsize = \vsize
-  \advance\outervsize by 2\topandbottommargin
-  \pageheight = \vsize
-  %
-  \hsize = #2\relax
-  \outerhsize = \hsize
-  \advance\outerhsize by 0.5in
-  \pagewidth = \hsize
-  %
-  \normaloffset = #4\relax
-  \bindingoffset = #5\relax
-  %
-  \ifpdf
-    \pdfpageheight #7\relax
-    \pdfpagewidth #8\relax
-    % if we don't reset these, they will remain at "1 true in" of
-    % whatever layout pdftex was dumped with.
-    \pdfhorigin = 1 true in
-    \pdfvorigin = 1 true in
-  \fi
-  %
-  \setleading{\textleading}
-  %
-  \parindent = \defaultparindent
-  \setemergencystretch
-}
-
-% @letterpaper (the default).
-\def\letterpaper{{\globaldefs = 1
-  \parskip = 3pt plus 2pt minus 1pt
-  \textleading = 13.2pt
-  %
-  % If page is nothing but text, make it come out even.
-  \internalpagesizes{607.2pt}{6in}% that's 46 lines
-                    {\voffset}{.25in}%
-                    {\bindingoffset}{36pt}%
-                    {11in}{8.5in}%
-}}
-
-% Use @smallbook to reset parameters for 7x9.25 trim size.
-\def\smallbook{{\globaldefs = 1
-  \parskip = 2pt plus 1pt
-  \textleading = 12pt
-  %
-  \internalpagesizes{7.5in}{5in}%
-                    {-.2in}{0in}%
-                    {\bindingoffset}{16pt}%
-                    {9.25in}{7in}%
-  %
-  \lispnarrowing = 0.3in
-  \tolerance = 700
-  \hfuzz = 1pt
-  \contentsrightmargin = 0pt
-  \defbodyindent = .5cm
-}}
-
-% Use @smallerbook to reset parameters for 6x9 trim size.
-% (Just testing, parameters still in flux.)
-\def\smallerbook{{\globaldefs = 1
-  \parskip = 1.5pt plus 1pt
-  \textleading = 12pt
-  %
-  \internalpagesizes{7.4in}{4.8in}%
-                    {-.2in}{-.4in}%
-                    {0pt}{14pt}%
-                    {9in}{6in}%
-  %
-  \lispnarrowing = 0.25in
-  \tolerance = 700
-  \hfuzz = 1pt
-  \contentsrightmargin = 0pt
-  \defbodyindent = .4cm
-}}
-
-% Use @afourpaper to print on European A4 paper.
-\def\afourpaper{{\globaldefs = 1
-  \parskip = 3pt plus 2pt minus 1pt
-  \textleading = 13.2pt
-  %
-  % Double-side printing via postscript on Laserjet 4050
-  % prints double-sided nicely when \bindingoffset=10mm and \hoffset=-6mm.
-  % To change the settings for a different printer or situation, adjust
-  % \normaloffset until the front-side and back-side texts align.  Then
-  % do the same for \bindingoffset.  You can set these for testing in
-  % your texinfo source file like this:
-  % @tex
-  % \global\normaloffset = -6mm
-  % \global\bindingoffset = 10mm
-  % @end tex
-  \internalpagesizes{673.2pt}{160mm}% that's 51 lines
-                    {\voffset}{\hoffset}%
-                    {\bindingoffset}{44pt}%
-                    {297mm}{210mm}%
-  %
-  \tolerance = 700
-  \hfuzz = 1pt
-  \contentsrightmargin = 0pt
-  \defbodyindent = 5mm
-}}
-
-% Use @afivepaper to print on European A5 paper.
-% From romildo@urano.iceb.ufop.br, 2 July 2000.
-% He also recommends making @example and @lisp be small.
-\def\afivepaper{{\globaldefs = 1
-  \parskip = 2pt plus 1pt minus 0.1pt
-  \textleading = 12.5pt
-  %
-  \internalpagesizes{160mm}{120mm}%
-                    {\voffset}{\hoffset}%
-                    {\bindingoffset}{8pt}%
-                    {210mm}{148mm}%
-  %
-  \lispnarrowing = 0.2in
-  \tolerance = 800
-  \hfuzz = 1.2pt
-  \contentsrightmargin = 0pt
-  \defbodyindent = 2mm
-  \tableindent = 12mm
-}}
-
-% A specific text layout, 24x15cm overall, intended for A4 paper.
-\def\afourlatex{{\globaldefs = 1
-  \afourpaper
-  \internalpagesizes{237mm}{150mm}%
-                    {\voffset}{4.6mm}%
-                    {\bindingoffset}{7mm}%
-                    {297mm}{210mm}%
-  %
-  % Must explicitly reset to 0 because we call \afourpaper.
-  \globaldefs = 0
-}}
-
-% Use @afourwide to print on A4 paper in landscape format.
-\def\afourwide{{\globaldefs = 1
-  \afourpaper
-  \internalpagesizes{241mm}{165mm}%
-                    {\voffset}{-2.95mm}%
-                    {\bindingoffset}{7mm}%
-                    {297mm}{210mm}%
-  \globaldefs = 0
-}}
-
-% @pagesizes TEXTHEIGHT[,TEXTWIDTH]
-% Perhaps we should allow setting the margins, \topskip, \parskip,
-% and/or leading, also. Or perhaps we should compute them somehow.
-%
-\parseargdef\pagesizes{\pagesizesyyy #1,,\finish}
-\def\pagesizesyyy#1,#2,#3\finish{{%
-  \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \hsize=#2\relax \fi
-  \globaldefs = 1
-  %
-  \parskip = 3pt plus 2pt minus 1pt
-  \setleading{\textleading}%
-  %
-  \dimen0 = #1\relax
-  \advance\dimen0 by \voffset
-  %
-  \dimen2 = \hsize
-  \advance\dimen2 by \normaloffset
-  %
-  \internalpagesizes{#1}{\hsize}%
-                    {\voffset}{\normaloffset}%
-                    {\bindingoffset}{44pt}%
-                    {\dimen0}{\dimen2}%
-}}
-
-% Set default to letter.
-%
-\letterpaper
-
-
-\message{and turning on texinfo input format.}
-
-\def^^L{\par} % remove \outer, so ^L can appear in an @comment
-
-% DEL is a comment character, in case @c does not suffice.
-\catcode`\^^? = 14
-
-% Define macros to output various characters with catcode for normal text.
-\catcode`\"=\other \def\normaldoublequote{"}
-\catcode`\$=\other \def\normaldollar{$}%$ font-lock fix
-\catcode`\+=\other \def\normalplus{+}
-\catcode`\<=\other \def\normalless{<}
-\catcode`\>=\other \def\normalgreater{>}
-\catcode`\^=\other \def\normalcaret{^}
-\catcode`\_=\other \def\normalunderscore{_}
-\catcode`\|=\other \def\normalverticalbar{|}
-\catcode`\~=\other \def\normaltilde{~}
-
-% This macro is used to make a character print one way in \tt
-% (where it can probably be output as-is), and another way in other fonts,
-% where something hairier probably needs to be done.
-%
-% #1 is what to print if we are indeed using \tt; #2 is what to print
-% otherwise.  Since all the Computer Modern typewriter fonts have zero
-% interword stretch (and shrink), and it is reasonable to expect all
-% typewriter fonts to have this, we can check that font parameter.
-%
-\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi}
-
-% Same as above, but check for italic font.  Actually this also catches
-% non-italic slanted fonts since it is impossible to distinguish them from
-% italic fonts.  But since this is only used by $ and it uses \sl anyway
-% this is not a problem.
-\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi}
-
-% Turn off all special characters except @
-% (and those which the user can use as if they were ordinary).
-% Most of these we simply print from the \tt font, but for some, we can
-% use math or other variants that look better in normal text.
-
-\catcode`\"=\active
-\def\activedoublequote{{\tt\char34}}
-\let"=\activedoublequote
-\catcode`\~=\active
-\def~{{\tt\char126}}
-\chardef\hat=`\^
-\catcode`\^=\active
-\def^{{\tt \hat}}
-
-\catcode`\_=\active
-\def_{\ifusingtt\normalunderscore\_}
-\let\realunder=_
-% Subroutine for the previous macro.
-\def\_{\leavevmode \kern.07em \vbox{\hrule width.3em height.1ex}\kern .07em }
-
-\catcode`\|=\active
-\def|{{\tt\char124}}
-\chardef \less=`\<
-\catcode`\<=\active
-\def<{{\tt \less}}
-\chardef \gtr=`\>
-\catcode`\>=\active
-\def>{{\tt \gtr}}
-\catcode`\+=\active
-\def+{{\tt \char 43}}
-\catcode`\$=\active
-\def${\ifusingit{{\sl\$}}\normaldollar}%$ font-lock fix
-
-% If a .fmt file is being used, characters that might appear in a file
-% name cannot be active until we have parsed the command line.
-% So turn them off again, and have \everyjob (or @setfilename) turn them on.
-% \otherifyactive is called near the end of this file.
-\def\otherifyactive{\catcode`+=\other \catcode`\_=\other}
-
-% Used sometimes to turn off (effectively) the active characters even after
-% parsing them.
-\def\turnoffactive{%
-  \normalturnoffactive
-  \otherbackslash
-}
-
-\catcode`\@=0
-
-% \backslashcurfont outputs one backslash character in current font,
-% as in \char`\\.
-\global\chardef\backslashcurfont=`\\
-\global\let\rawbackslashxx=\backslashcurfont  % let existing .??s files work
-
-% \realbackslash is an actual character `\' with catcode other, and
-% \doublebackslash is two of them (for the pdf outlines).
-{\catcode`\\=\other @gdef@realbackslash{\} @gdef@doublebackslash{\\}}
-
-% In texinfo, backslash is an active character; it prints the backslash
-% in fixed width font.
-\catcode`\\=\active  % @ for escape char from now on.
-
-% The story here is that in math mode, the \char of \backslashcurfont
-% ends up printing the roman \ from the math symbol font (because \char
-% in math mode uses the \mathcode, and plain.tex sets
-% \mathcode`\\="026E).  It seems better for @backslashchar{} to always
-% print a typewriter backslash, hence we use an explicit \mathchar,
-% which is the decimal equivalent of "715c (class 7, e.g., use \fam;
-% ignored family value; char position "5C).  We can't use " for the
-% usual hex value because it has already been made active.
-@def@normalbackslash{{@tt @ifmmode @mathchar29020 @else @backslashcurfont @fi}}
-@let@backslashchar = @normalbackslash % @backslashchar{} is for user documents.
-
-% On startup, @fixbackslash assigns:
-%  @let \ = @normalbackslash
-% \rawbackslash defines an active \ to do \backslashcurfont.
-% \otherbackslash defines an active \ to be a literal `\' character with
-% catcode other.  We switch back and forth between these.
-@gdef@rawbackslash{@let\=@backslashcurfont}
-@gdef@otherbackslash{@let\=@realbackslash}
-
-% Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of
-% the literal character `\'.  Also revert - to its normal character, in
-% case the active - from code has slipped in.
-%
-{@catcode`- = @active
- @gdef@normalturnoffactive{%
-   @let-=@normaldash
-   @let"=@normaldoublequote
-   @let$=@normaldollar %$ font-lock fix
-   @let+=@normalplus
-   @let<=@normalless
-   @let>=@normalgreater
-   @let\=@normalbackslash
-   @let^=@normalcaret
-   @let_=@normalunderscore
-   @let|=@normalverticalbar
-   @let~=@normaltilde
-   @markupsetuplqdefault
-   @markupsetuprqdefault
-   @unsepspaces
- }
-}
-
-% Make _ and + \other characters, temporarily.
-% This is canceled by @fixbackslash.
-@otherifyactive
-
-% If a .fmt file is being used, we don't want the `\input texinfo' to show up.
-% That is what \eatinput is for; after that, the `\' should revert to printing
-% a backslash.
-%
-@gdef@eatinput input texinfo{@fixbackslash}
-@global@let\ = @eatinput
-
-% On the other hand, perhaps the file did not have a `\input texinfo'. Then
-% the first `\' in the file would cause an error. This macro tries to fix
-% that, assuming it is called before the first `\' could plausibly occur.
-% Also turn back on active characters that might appear in the input
-% file name, in case not using a pre-dumped format.
-%
-@gdef@fixbackslash{%
-  @ifx\@eatinput @let\ = @normalbackslash @fi
-  @catcode`+=@active
-  @catcode`@_=@active
-}
-
-% Say @foo, not \foo, in error messages.
-@escapechar = `@@
-
-% These (along with & and #) are made active for url-breaking, so need
-% active definitions as the normal characters.
-@def@normaldot{.}
-@def@normalquest{?}
-@def@normalslash{/}
-
-% These look ok in all fonts, so just make them not special.
-% @hashchar{} gets its own user-level command, because of #line.
-@catcode`@& = @other @def@normalamp{&}
-@catcode`@# = @other @def@normalhash{#}
-@catcode`@% = @other @def@normalpercent{%}
-
-@let @hashchar = @normalhash
-
-@c Finally, make ` and ' active, so that txicodequoteundirected and
-@c txicodequotebacktick work right in, e.g., @w{@code{`foo'}}.  If we
-@c don't make ` and ' active, @code will not get them as active chars.
-@c Do this last of all since we use ` in the previous @catcode assignments.
-@catcode`@'=@active
-@catcode`@`=@active
-@markupsetuplqdefault
-@markupsetuprqdefault
-
-@c Local variables:
-@c eval: (add-hook 'write-file-hooks 'time-stamp)
-@c page-delimiter: "^\\\\message"
-@c time-stamp-start: "def\\\\texinfoversion{"
-@c time-stamp-format: "%:y-%02m-%02d.%02H"
-@c time-stamp-end: "}"
-@c End:
-
-@c vim:sw=2:
-
-@ignore
-   arch-tag: e1b36e32-c96e-4135-a41a-0b2efa2ea115
-@end ignore
diff --git a/doc/version.texi b/doc/version.texi
deleted file mode 100644
index c8c24ba..0000000
--- a/doc/version.texi
+++ /dev/null
@@ -1,4 +0,0 @@
-@set UPDATED 3 April 2015
-@set UPDATED-MONTH April 2015
-@set EDITION 0.9.42
-@set VERSION 0.9.42
diff --git a/install-sh b/install-sh
deleted file mode 100755
index 377bb86..0000000
--- a/install-sh
+++ /dev/null
@@ -1,527 +0,0 @@
-#!/bin/sh
-# install - install a program, script, or datafile
-
-scriptversion=2011-11-20.07; # UTC
-
-# This originates from X11R5 (mit/util/scripts/install.sh), which was
-# later released in X11R6 (xc/config/util/install.sh) with the
-# following copyright and license.
-#
-# Copyright (C) 1994 X Consortium
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
-# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name of the X Consortium shall not
-# be used in advertising or otherwise to promote the sale, use or other deal-
-# ings in this Software without prior written authorization from the X Consor-
-# tium.
-#
-#
-# FSF changes to this file are in the public domain.
-#
-# Calling this script install-sh is preferred over install.sh, to prevent
-# 'make' implicit rules from creating a file called install from it
-# when there is no Makefile.
-#
-# This script is compatible with the BSD install script, but was written
-# from scratch.
-
-nl='
-'
-IFS=" ""	$nl"
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
-
-# Put in absolute file names if you don't have them in your path;
-# or use environment vars.
-
-chgrpprog=${CHGRPPROG-chgrp}
-chmodprog=${CHMODPROG-chmod}
-chownprog=${CHOWNPROG-chown}
-cmpprog=${CMPPROG-cmp}
-cpprog=${CPPROG-cp}
-mkdirprog=${MKDIRPROG-mkdir}
-mvprog=${MVPROG-mv}
-rmprog=${RMPROG-rm}
-stripprog=${STRIPPROG-strip}
-
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
-posix_mkdir=
-
-# Desired mode of installed file.
-mode=0755
-
-chgrpcmd=
-chmodcmd=$chmodprog
-chowncmd=
-mvcmd=$mvprog
-rmcmd="$rmprog -f"
-stripcmd=
-
-src=
-dst=
-dir_arg=
-dst_arg=
-
-copy_on_change=false
-no_target_directory=
-
-usage="\
-Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
-   or: $0 [OPTION]... SRCFILES... DIRECTORY
-   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
-   or: $0 [OPTION]... -d DIRECTORIES...
-
-In the 1st form, copy SRCFILE to DSTFILE.
-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
-In the 4th, create DIRECTORIES.
-
-Options:
-     --help     display this help and exit.
-     --version  display version info and exit.
-
-  -c            (ignored)
-  -C            install only if different (preserve the last data modification time)
-  -d            create directories instead of installing files.
-  -g GROUP      $chgrpprog installed files to GROUP.
-  -m MODE       $chmodprog installed files to MODE.
-  -o USER       $chownprog installed files to USER.
-  -s            $stripprog installed files.
-  -t DIRECTORY  install into DIRECTORY.
-  -T            report an error if DSTFILE is a directory.
-
-Environment variables override the default commands:
-  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
-  RMPROG STRIPPROG
-"
-
-while test $# -ne 0; do
-  case $1 in
-    -c) ;;
-
-    -C) copy_on_change=true;;
-
-    -d) dir_arg=true;;
-
-    -g) chgrpcmd="$chgrpprog $2"
-	shift;;
-
-    --help) echo "$usage"; exit $?;;
-
-    -m) mode=$2
-	case $mode in
-	  *' '* | *'	'* | *'
-'*	  | *'*'* | *'?'* | *'['*)
-	    echo "$0: invalid mode: $mode" >&2
-	    exit 1;;
-	esac
-	shift;;
-
-    -o) chowncmd="$chownprog $2"
-	shift;;
-
-    -s) stripcmd=$stripprog;;
-
-    -t) dst_arg=$2
-	# Protect names problematic for 'test' and other utilities.
-	case $dst_arg in
-	  -* | [=\(\)!]) dst_arg=./$dst_arg;;
-	esac
-	shift;;
-
-    -T) no_target_directory=true;;
-
-    --version) echo "$0 $scriptversion"; exit $?;;
-
-    --)	shift
-	break;;
-
-    -*)	echo "$0: invalid option: $1" >&2
-	exit 1;;
-
-    *)  break;;
-  esac
-  shift
-done
-
-if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
-  # When -d is used, all remaining arguments are directories to create.
-  # When -t is used, the destination is already specified.
-  # Otherwise, the last argument is the destination.  Remove it from $@.
-  for arg
-  do
-    if test -n "$dst_arg"; then
-      # $@ is not empty: it contains at least $arg.
-      set fnord "$@" "$dst_arg"
-      shift # fnord
-    fi
-    shift # arg
-    dst_arg=$arg
-    # Protect names problematic for 'test' and other utilities.
-    case $dst_arg in
-      -* | [=\(\)!]) dst_arg=./$dst_arg;;
-    esac
-  done
-fi
-
-if test $# -eq 0; then
-  if test -z "$dir_arg"; then
-    echo "$0: no input file specified." >&2
-    exit 1
-  fi
-  # It's OK to call 'install-sh -d' without argument.
-  # This can happen when creating conditional directories.
-  exit 0
-fi
-
-if test -z "$dir_arg"; then
-  do_exit='(exit $ret); exit $ret'
-  trap "ret=129; $do_exit" 1
-  trap "ret=130; $do_exit" 2
-  trap "ret=141; $do_exit" 13
-  trap "ret=143; $do_exit" 15
-
-  # Set umask so as not to create temps with too-generous modes.
-  # However, 'strip' requires both read and write access to temps.
-  case $mode in
-    # Optimize common cases.
-    *644) cp_umask=133;;
-    *755) cp_umask=22;;
-
-    *[0-7])
-      if test -z "$stripcmd"; then
-	u_plus_rw=
-      else
-	u_plus_rw='% 200'
-      fi
-      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
-    *)
-      if test -z "$stripcmd"; then
-	u_plus_rw=
-      else
-	u_plus_rw=,u+rw
-      fi
-      cp_umask=$mode$u_plus_rw;;
-  esac
-fi
-
-for src
-do
-  # Protect names problematic for 'test' and other utilities.
-  case $src in
-    -* | [=\(\)!]) src=./$src;;
-  esac
-
-  if test -n "$dir_arg"; then
-    dst=$src
-    dstdir=$dst
-    test -d "$dstdir"
-    dstdir_status=$?
-  else
-
-    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
-    # might cause directories to be created, which would be especially bad
-    # if $src (and thus $dsttmp) contains '*'.
-    if test ! -f "$src" && test ! -d "$src"; then
-      echo "$0: $src does not exist." >&2
-      exit 1
-    fi
-
-    if test -z "$dst_arg"; then
-      echo "$0: no destination specified." >&2
-      exit 1
-    fi
-    dst=$dst_arg
-
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
-    if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-	echo "$0: $dst_arg: Is a directory" >&2
-	exit 1
-      fi
-      dstdir=$dst
-      dst=$dstdir/`basename "$src"`
-      dstdir_status=0
-    else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-	(dirname "$dst") 2>/dev/null ||
-	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	     X"$dst" : 'X\(//\)[^/]' \| \
-	     X"$dst" : 'X\(//\)$' \| \
-	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-	echo X"$dst" |
-	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-		   s//\1/
-		   q
-		 }
-		 /^X\(\/\/\)[^/].*/{
-		   s//\1/
-		   q
-		 }
-		 /^X\(\/\/\)$/{
-		   s//\1/
-		   q
-		 }
-		 /^X\(\/\).*/{
-		   s//\1/
-		   q
-		 }
-		 s/.*/./; q'
-      `
-
-      test -d "$dstdir"
-      dstdir_status=$?
-    fi
-  fi
-
-  obsolete_mkdir_used=false
-
-  if test $dstdir_status != 0; then
-    case $posix_mkdir in
-      '')
-	# Create intermediate dirs using mode 755 as modified by the umask.
-	# This is like FreeBSD 'install' as of 1997-10-28.
-	umask=`umask`
-	case $stripcmd.$umask in
-	  # Optimize common cases.
-	  *[2367][2367]) mkdir_umask=$umask;;
-	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-	  *[0-7])
-	    mkdir_umask=`expr $umask + 22 \
-	      - $umask % 100 % 40 + $umask % 20 \
-	      - $umask % 10 % 4 + $umask % 2
-	    `;;
-	  *) mkdir_umask=$umask,go-w;;
-	esac
-
-	# With -d, create the new directory with the user-specified mode.
-	# Otherwise, rely on $mkdir_umask.
-	if test -n "$dir_arg"; then
-	  mkdir_mode=-m$mode
-	else
-	  mkdir_mode=
-	fi
-
-	posix_mkdir=false
-	case $umask in
-	  *[123567][0-7][0-7])
-	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
-	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-	    ;;
-	  *)
-	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-	    if (umask $mkdir_umask &&
-		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-	    then
-	      if test -z "$dir_arg" || {
-		   # Check for POSIX incompatibilities with -m.
-		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-		   # other-writable bit of parent directory when it shouldn't.
-		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
-		   case $ls_ld_tmpdir in
-		     d????-?r-*) different_mode=700;;
-		     d????-?--*) different_mode=755;;
-		     *) false;;
-		   esac &&
-		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-		   }
-		 }
-	      then posix_mkdir=:
-	      fi
-	      rmdir "$tmpdir/d" "$tmpdir"
-	    else
-	      # Remove any dirs left behind by ancient mkdir implementations.
-	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-	    fi
-	    trap '' 0;;
-	esac;;
-    esac
-
-    if
-      $posix_mkdir && (
-	umask $mkdir_umask &&
-	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
-      )
-    then :
-    else
-
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
-      # or it failed possibly due to a race condition.  Create the
-      # directory the slow way, step by step, checking for races as we go.
-
-      case $dstdir in
-	/*) prefix='/';;
-	[-=\(\)!]*) prefix='./';;
-	*)  prefix='';;
-      esac
-
-      eval "$initialize_posix_glob"
-
-      oIFS=$IFS
-      IFS=/
-      $posix_glob set -f
-      set fnord $dstdir
-      shift
-      $posix_glob set +f
-      IFS=$oIFS
-
-      prefixes=
-
-      for d
-      do
-	test X"$d" = X && continue
-
-	prefix=$prefix$d
-	if test -d "$prefix"; then
-	  prefixes=
-	else
-	  if $posix_mkdir; then
-	    (umask=$mkdir_umask &&
-	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-	    # Don't fail if two instances are running concurrently.
-	    test -d "$prefix" || exit 1
-	  else
-	    case $prefix in
-	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-	      *) qprefix=$prefix;;
-	    esac
-	    prefixes="$prefixes '$qprefix'"
-	  fi
-	fi
-	prefix=$prefix/
-      done
-
-      if test -n "$prefixes"; then
-	# Don't fail if two instances are running concurrently.
-	(umask $mkdir_umask &&
-	 eval "\$doit_exec \$mkdirprog $prefixes") ||
-	  test -d "$dstdir" || exit 1
-	obsolete_mkdir_used=true
-      fi
-    fi
-  fi
-
-  if test -n "$dir_arg"; then
-    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
-    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
-      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
-  else
-
-    # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
-
-    # Trap to clean up those temp files at exit.
-    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
-
-    # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
-
-    # and set any options; do chmod last to preserve setuid bits.
-    #
-    # If any of these fail, we abort the whole thing.  If we want to
-    # ignore errors from any of these, just make sure not to ignore
-    # errors from the above "$doit $cpprog $src $dsttmp" command.
-    #
-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
-    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
-    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
-
-    # If -C, don't bother to copy if it wouldn't change the file.
-    if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
-       set X $old && old=:$2:$4:$5:$6 &&
-       set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
-       test "$old" = "$new" &&
-       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
-    then
-      rm -f "$dsttmp"
-    else
-      # Rename the file to the real destination.
-      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
-
-      # The rename failed, perhaps because mv can't rename something else
-      # to itself, or perhaps because mv is so ancient that it does not
-      # support -f.
-      {
-	# Now remove or move aside any old file at destination location.
-	# We try this two ways since rm can't unlink itself on some
-	# systems and the destination file might be busy for other
-	# reasons.  In this case, the final cleanup might fail but the new
-	# file should still install successfully.
-	{
-	  test ! -f "$dst" ||
-	  $doit $rmcmd -f "$dst" 2>/dev/null ||
-	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-	  } ||
-	  { echo "$0: cannot unlink or rename $dst" >&2
-	    (exit 1); exit 1
-	  }
-	} &&
-
-	# Now rename the file to the real destination.
-	$doit $mvcmd "$dsttmp" "$dst"
-      }
-    fi || exit 1
-
-    trap '' 0
-  fi
-done
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/libmicrospdy.pc.in b/libmicrospdy.pc.in
deleted file mode 100644
index fa9062f..0000000
--- a/libmicrospdy.pc.in
+++ /dev/null
@@ -1,13 +0,0 @@
-prefix=@prefix@
-exec_prefix=@exec_prefix@
-libdir=@libdir@
-includedir=@includedir@
-
-Name: libmicrospdy
-Description: A library for creating an embedded SPDY server
-Version: @VERSION@
-Requires:
-Conflicts:
-Libs: -L${libdir} -lmicrospdy
-Libs.private: @SPDY_LIBDEPS@
-Cflags: -I${includedir}
diff --git a/ltmain.sh b/ltmain.sh
deleted file mode 100644
index bffda54..0000000
--- a/ltmain.sh
+++ /dev/null
@@ -1,9661 +0,0 @@
-
-# libtool (GNU libtool) 2.4.2
-# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
-
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
-# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
-# This is free software; see the source for copying conditions.  There is NO
-# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-
-# GNU Libtool 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 2 of the License, or
-# (at your option) any later version.
-#
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
-#
-# GNU Libtool 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 GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html,
-# or obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
-# Usage: $progname [OPTION]... [MODE-ARG]...
-#
-# Provide generalized library-building support services.
-#
-#       --config             show all configuration variables
-#       --debug              enable verbose shell tracing
-#   -n, --dry-run            display commands without modifying any files
-#       --features           display basic configuration information and exit
-#       --mode=MODE          use operation mode MODE
-#       --preserve-dup-deps  don't remove duplicate dependency libraries
-#       --quiet, --silent    don't print informational messages
-#       --no-quiet, --no-silent
-#                            print informational messages (default)
-#       --no-warn            don't display warning messages
-#       --tag=TAG            use configuration variables from tag TAG
-#   -v, --verbose            print more informational messages than default
-#       --no-verbose         don't print the extra informational messages
-#       --version            print version information
-#   -h, --help, --help-all   print short, long, or detailed help message
-#
-# MODE must be one of the following:
-#
-#         clean              remove files from the build directory
-#         compile            compile a source file into a libtool object
-#         execute            automatically set library path, then run a program
-#         finish             complete the installation of libtool libraries
-#         install            install libraries or executables
-#         link               create a library or an executable
-#         uninstall          remove libraries from an installed directory
-#
-# MODE-ARGS vary depending on the MODE.  When passed as first option,
-# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.
-# Try `$progname --help --mode=MODE' for a more detailed description of MODE.
-#
-# When reporting a bug, please describe a test case to reproduce it and
-# include the following information:
-#
-#         host-triplet:	$host
-#         shell:		$SHELL
-#         compiler:		$LTCC
-#         compiler flags:		$LTCFLAGS
-#         linker:		$LD (gnu? $with_gnu_ld)
-#         $progname:	(GNU libtool) 2.4.2 Debian-2.4.2-1.11
-#         automake:	$automake_version
-#         autoconf:	$autoconf_version
-#
-# Report bugs to <bug-libtool@gnu.org>.
-# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
-# General help using GNU software: <http://www.gnu.org/gethelp/>.
-
-PROGRAM=libtool
-PACKAGE=libtool
-VERSION="2.4.2 Debian-2.4.2-1.11"
-TIMESTAMP=""
-package_revision=1.3337
-
-# Be Bourne compatible
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
-fi
-BIN_SH=xpg4; export BIN_SH # for Tru64
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# A function that is used when there is no print builtin or printf.
-func_fallback_echo ()
-{
-  eval 'cat <<_LTECHO_EOF
-$1
-_LTECHO_EOF'
-}
-
-# NLS nuisances: We save the old values to restore during execute mode.
-lt_user_locale=
-lt_safe_locale=
-for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
-do
-  eval "if test \"\${$lt_var+set}\" = set; then
-          save_$lt_var=\$$lt_var
-          $lt_var=C
-	  export $lt_var
-	  lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\"
-	  lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\"
-	fi"
-done
-LC_ALL=C
-LANGUAGE=C
-export LANGUAGE LC_ALL
-
-$lt_unset CDPATH
-
-
-# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
-# is ksh but when the shell is invoked as "sh" and the current value of
-# the _XPG environment variable is not equal to 1 (one), the special
-# positional parameter $0, within a function call, is the name of the
-# function.
-progpath="$0"
-
-
-
-: ${CP="cp -f"}
-test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'}
-: ${MAKE="make"}
-: ${MKDIR="mkdir"}
-: ${MV="mv -f"}
-: ${RM="rm -f"}
-: ${SHELL="${CONFIG_SHELL-/bin/sh}"}
-: ${Xsed="$SED -e 1s/^X//"}
-
-# Global variables:
-EXIT_SUCCESS=0
-EXIT_FAILURE=1
-EXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.
-EXIT_SKIP=77	  # $? = 77 is used to indicate a skipped test to automake.
-
-exit_status=$EXIT_SUCCESS
-
-# Make sure IFS has a sensible default
-lt_nl='
-'
-IFS=" 	$lt_nl"
-
-dirname="s,/[^/]*$,,"
-basename="s,^.*/,,"
-
-# func_dirname file append nondir_replacement
-# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
-# otherwise set result to NONDIR_REPLACEMENT.
-func_dirname ()
-{
-    func_dirname_result=`$ECHO "${1}" | $SED "$dirname"`
-    if test "X$func_dirname_result" = "X${1}"; then
-      func_dirname_result="${3}"
-    else
-      func_dirname_result="$func_dirname_result${2}"
-    fi
-} # func_dirname may be replaced by extended shell implementation
-
-
-# func_basename file
-func_basename ()
-{
-    func_basename_result=`$ECHO "${1}" | $SED "$basename"`
-} # func_basename may be replaced by extended shell implementation
-
-
-# func_dirname_and_basename file append nondir_replacement
-# perform func_basename and func_dirname in a single function
-# call:
-#   dirname:  Compute the dirname of FILE.  If nonempty,
-#             add APPEND to the result, otherwise set result
-#             to NONDIR_REPLACEMENT.
-#             value returned in "$func_dirname_result"
-#   basename: Compute filename of FILE.
-#             value retuned in "$func_basename_result"
-# Implementation must be kept synchronized with func_dirname
-# and func_basename. For efficiency, we do not delegate to
-# those functions but instead duplicate the functionality here.
-func_dirname_and_basename ()
-{
-    # Extract subdirectory from the argument.
-    func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"`
-    if test "X$func_dirname_result" = "X${1}"; then
-      func_dirname_result="${3}"
-    else
-      func_dirname_result="$func_dirname_result${2}"
-    fi
-    func_basename_result=`$ECHO "${1}" | $SED -e "$basename"`
-} # func_dirname_and_basename may be replaced by extended shell implementation
-
-
-# func_stripname prefix suffix name
-# strip PREFIX and SUFFIX off of NAME.
-# PREFIX and SUFFIX must not contain globbing or regex special
-# characters, hashes, percent signs, but SUFFIX may contain a leading
-# dot (in which case that matches only a dot).
-# func_strip_suffix prefix name
-func_stripname ()
-{
-    case ${2} in
-      .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
-      *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
-    esac
-} # func_stripname may be replaced by extended shell implementation
-
-
-# These SED scripts presuppose an absolute path with a trailing slash.
-pathcar='s,^/\([^/]*\).*$,\1,'
-pathcdr='s,^/[^/]*,,'
-removedotparts=':dotsl
-		s@/\./@/@g
-		t dotsl
-		s,/\.$,/,'
-collapseslashes='s@/\{1,\}@/@g'
-finalslash='s,/*$,/,'
-
-# func_normal_abspath PATH
-# Remove doubled-up and trailing slashes, "." path components,
-# and cancel out any ".." path components in PATH after making
-# it an absolute path.
-#             value returned in "$func_normal_abspath_result"
-func_normal_abspath ()
-{
-  # Start from root dir and reassemble the path.
-  func_normal_abspath_result=
-  func_normal_abspath_tpath=$1
-  func_normal_abspath_altnamespace=
-  case $func_normal_abspath_tpath in
-    "")
-      # Empty path, that just means $cwd.
-      func_stripname '' '/' "`pwd`"
-      func_normal_abspath_result=$func_stripname_result
-      return
-    ;;
-    # The next three entries are used to spot a run of precisely
-    # two leading slashes without using negated character classes;
-    # we take advantage of case's first-match behaviour.
-    ///*)
-      # Unusual form of absolute path, do nothing.
-    ;;
-    //*)
-      # Not necessarily an ordinary path; POSIX reserves leading '//'
-      # and for example Cygwin uses it to access remote file shares
-      # over CIFS/SMB, so we conserve a leading double slash if found.
-      func_normal_abspath_altnamespace=/
-    ;;
-    /*)
-      # Absolute path, do nothing.
-    ;;
-    *)
-      # Relative path, prepend $cwd.
-      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath
-    ;;
-  esac
-  # Cancel out all the simple stuff to save iterations.  We also want
-  # the path to end with a slash for ease of parsing, so make sure
-  # there is one (and only one) here.
-  func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
-        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
-  while :; do
-    # Processed it all yet?
-    if test "$func_normal_abspath_tpath" = / ; then
-      # If we ascended to the root using ".." the result may be empty now.
-      if test -z "$func_normal_abspath_result" ; then
-        func_normal_abspath_result=/
-      fi
-      break
-    fi
-    func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \
-        -e "$pathcar"`
-    func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \
-        -e "$pathcdr"`
-    # Figure out what to do with it
-    case $func_normal_abspath_tcomponent in
-      "")
-        # Trailing empty path component, ignore it.
-      ;;
-      ..)
-        # Parent dir; strip last assembled component from result.
-        func_dirname "$func_normal_abspath_result"
-        func_normal_abspath_result=$func_dirname_result
-      ;;
-      *)
-        # Actual path component, append it.
-        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent
-      ;;
-    esac
-  done
-  # Restore leading double-slash if one was found on entry.
-  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result
-}
-
-# func_relative_path SRCDIR DSTDIR
-# generates a relative path from SRCDIR to DSTDIR, with a trailing
-# slash if non-empty, suitable for immediately appending a filename
-# without needing to append a separator.
-#             value returned in "$func_relative_path_result"
-func_relative_path ()
-{
-  func_relative_path_result=
-  func_normal_abspath "$1"
-  func_relative_path_tlibdir=$func_normal_abspath_result
-  func_normal_abspath "$2"
-  func_relative_path_tbindir=$func_normal_abspath_result
-
-  # Ascend the tree starting from libdir
-  while :; do
-    # check if we have found a prefix of bindir
-    case $func_relative_path_tbindir in
-      $func_relative_path_tlibdir)
-        # found an exact match
-        func_relative_path_tcancelled=
-        break
-        ;;
-      $func_relative_path_tlibdir*)
-        # found a matching prefix
-        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir"
-        func_relative_path_tcancelled=$func_stripname_result
-        if test -z "$func_relative_path_result"; then
-          func_relative_path_result=.
-        fi
-        break
-        ;;
-      *)
-        func_dirname $func_relative_path_tlibdir
-        func_relative_path_tlibdir=${func_dirname_result}
-        if test "x$func_relative_path_tlibdir" = x ; then
-          # Have to descend all the way to the root!
-          func_relative_path_result=../$func_relative_path_result
-          func_relative_path_tcancelled=$func_relative_path_tbindir
-          break
-        fi
-        func_relative_path_result=../$func_relative_path_result
-        ;;
-    esac
-  done
-
-  # Now calculate path; take care to avoid doubling-up slashes.
-  func_stripname '' '/' "$func_relative_path_result"
-  func_relative_path_result=$func_stripname_result
-  func_stripname '/' '/' "$func_relative_path_tcancelled"
-  if test "x$func_stripname_result" != x ; then
-    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}
-  fi
-
-  # Normalisation. If bindir is libdir, return empty string,
-  # else relative path ending with a slash; either way, target
-  # file name can be directly appended.
-  if test ! -z "$func_relative_path_result"; then
-    func_stripname './' '' "$func_relative_path_result/"
-    func_relative_path_result=$func_stripname_result
-  fi
-}
-
-# The name of this program:
-func_dirname_and_basename "$progpath"
-progname=$func_basename_result
-
-# Make sure we have an absolute path for reexecution:
-case $progpath in
-  [\\/]*|[A-Za-z]:\\*) ;;
-  *[\\/]*)
-     progdir=$func_dirname_result
-     progdir=`cd "$progdir" && pwd`
-     progpath="$progdir/$progname"
-     ;;
-  *)
-     save_IFS="$IFS"
-     IFS=${PATH_SEPARATOR-:}
-     for progdir in $PATH; do
-       IFS="$save_IFS"
-       test -x "$progdir/$progname" && break
-     done
-     IFS="$save_IFS"
-     test -n "$progdir" || progdir=`pwd`
-     progpath="$progdir/$progname"
-     ;;
-esac
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed="${SED}"' -e 1s/^X//'
-sed_quote_subst='s/\([`"$\\]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\(["`\\]\)/\\\1/g'
-
-# Sed substitution that turns a string into a regex matching for the
-# string literally.
-sed_make_literal_regex='s,[].[^$\\*\/],\\&,g'
-
-# Sed substitution that converts a w32 file name or path
-# which contains forward slashes, into one that contains
-# (escaped) backslashes.  A very naive implementation.
-lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
-
-# Re-`\' parameter expansions in output of double_quote_subst that were
-# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
-# in input to double_quote_subst, that '$' was protected from expansion.
-# Since each input `\' is now two `\'s, look for any number of runs of
-# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
-bs='\\'
-bs2='\\\\'
-bs4='\\\\\\\\'
-dollar='\$'
-sed_double_backslash="\
-  s/$bs4/&\\
-/g
-  s/^$bs2$dollar/$bs&/
-  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
-  s/\n//g"
-
-# Standard options:
-opt_dry_run=false
-opt_help=false
-opt_quiet=false
-opt_verbose=false
-opt_warning=:
-
-# func_echo arg...
-# Echo program name prefixed message, along with the current mode
-# name if it has been set yet.
-func_echo ()
-{
-    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
-}
-
-# func_verbose arg...
-# Echo program name prefixed message in verbose mode only.
-func_verbose ()
-{
-    $opt_verbose && func_echo ${1+"$@"}
-
-    # A bug in bash halts the script if the last line of a function
-    # fails when set -e is in force, so we need another command to
-    # work around that:
-    :
-}
-
-# func_echo_all arg...
-# Invoke $ECHO with all args, space-separated.
-func_echo_all ()
-{
-    $ECHO "$*"
-}
-
-# func_error arg...
-# Echo program name prefixed message to standard error.
-func_error ()
-{
-    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
-}
-
-# func_warning arg...
-# Echo program name prefixed warning message to standard error.
-func_warning ()
-{
-    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2
-
-    # bash bug again:
-    :
-}
-
-# func_fatal_error arg...
-# Echo program name prefixed message to standard error, and exit.
-func_fatal_error ()
-{
-    func_error ${1+"$@"}
-    exit $EXIT_FAILURE
-}
-
-# func_fatal_help arg...
-# Echo program name prefixed message to standard error, followed by
-# a help hint, and exit.
-func_fatal_help ()
-{
-    func_error ${1+"$@"}
-    func_fatal_error "$help"
-}
-help="Try \`$progname --help' for more information."  ## default
-
-
-# func_grep expression filename
-# Check whether EXPRESSION matches any line of FILENAME, without output.
-func_grep ()
-{
-    $GREP "$1" "$2" >/dev/null 2>&1
-}
-
-
-# func_mkdir_p directory-path
-# Make sure the entire path to DIRECTORY-PATH is available.
-func_mkdir_p ()
-{
-    my_directory_path="$1"
-    my_dir_list=
-
-    if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then
-
-      # Protect directory names starting with `-'
-      case $my_directory_path in
-        -*) my_directory_path="./$my_directory_path" ;;
-      esac
-
-      # While some portion of DIR does not yet exist...
-      while test ! -d "$my_directory_path"; do
-        # ...make a list in topmost first order.  Use a colon delimited
-	# list incase some portion of path contains whitespace.
-        my_dir_list="$my_directory_path:$my_dir_list"
-
-        # If the last portion added has no slash in it, the list is done
-        case $my_directory_path in */*) ;; *) break ;; esac
-
-        # ...otherwise throw away the child directory and loop
-        my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"`
-      done
-      my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
-
-      save_mkdir_p_IFS="$IFS"; IFS=':'
-      for my_dir in $my_dir_list; do
-	IFS="$save_mkdir_p_IFS"
-        # mkdir can fail with a `File exist' error if two processes
-        # try to create one of the directories concurrently.  Don't
-        # stop in that case!
-        $MKDIR "$my_dir" 2>/dev/null || :
-      done
-      IFS="$save_mkdir_p_IFS"
-
-      # Bail out if we (or some other process) failed to create a directory.
-      test -d "$my_directory_path" || \
-        func_fatal_error "Failed to create \`$1'"
-    fi
-}
-
-
-# func_mktempdir [string]
-# Make a temporary directory that won't clash with other running
-# libtool processes, and avoids race conditions if possible.  If
-# given, STRING is the basename for that directory.
-func_mktempdir ()
-{
-    my_template="${TMPDIR-/tmp}/${1-$progname}"
-
-    if test "$opt_dry_run" = ":"; then
-      # Return a directory name, but don't create it in dry-run mode
-      my_tmpdir="${my_template}-$$"
-    else
-
-      # If mktemp works, use that first and foremost
-      my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
-
-      if test ! -d "$my_tmpdir"; then
-        # Failing that, at least try and use $RANDOM to avoid a race
-        my_tmpdir="${my_template}-${RANDOM-0}$$"
-
-        save_mktempdir_umask=`umask`
-        umask 0077
-        $MKDIR "$my_tmpdir"
-        umask $save_mktempdir_umask
-      fi
-
-      # If we're not in dry-run mode, bomb out on failure
-      test -d "$my_tmpdir" || \
-        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
-    fi
-
-    $ECHO "$my_tmpdir"
-}
-
-
-# func_quote_for_eval arg
-# Aesthetically quote ARG to be evaled later.
-# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
-# is double-quoted, suitable for a subsequent eval, whereas
-# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
-# which are still active within double quotes backslashified.
-func_quote_for_eval ()
-{
-    case $1 in
-      *[\\\`\"\$]*)
-	func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;;
-      *)
-        func_quote_for_eval_unquoted_result="$1" ;;
-    esac
-
-    case $func_quote_for_eval_unquoted_result in
-      # Double-quote args containing shell metacharacters to delay
-      # word splitting, command substitution and and variable
-      # expansion for a subsequent eval.
-      # Many Bourne shells cannot handle close brackets correctly
-      # in scan sets, so we specify it separately.
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-        func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\""
-        ;;
-      *)
-        func_quote_for_eval_result="$func_quote_for_eval_unquoted_result"
-    esac
-}
-
-
-# func_quote_for_expand arg
-# Aesthetically quote ARG to be evaled later; same as above,
-# but do not quote variable references.
-func_quote_for_expand ()
-{
-    case $1 in
-      *[\\\`\"]*)
-	my_arg=`$ECHO "$1" | $SED \
-	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
-      *)
-        my_arg="$1" ;;
-    esac
-
-    case $my_arg in
-      # Double-quote args containing shell metacharacters to delay
-      # word splitting and command substitution for a subsequent eval.
-      # Many Bourne shells cannot handle close brackets correctly
-      # in scan sets, so we specify it separately.
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-        my_arg="\"$my_arg\""
-        ;;
-    esac
-
-    func_quote_for_expand_result="$my_arg"
-}
-
-
-# func_show_eval cmd [fail_exp]
-# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
-# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
-# is given, then evaluate it.
-func_show_eval ()
-{
-    my_cmd="$1"
-    my_fail_exp="${2-:}"
-
-    ${opt_silent-false} || {
-      func_quote_for_expand "$my_cmd"
-      eval "func_echo $func_quote_for_expand_result"
-    }
-
-    if ${opt_dry_run-false}; then :; else
-      eval "$my_cmd"
-      my_status=$?
-      if test "$my_status" -eq 0; then :; else
-	eval "(exit $my_status); $my_fail_exp"
-      fi
-    fi
-}
-
-
-# func_show_eval_locale cmd [fail_exp]
-# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
-# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
-# is given, then evaluate it.  Use the saved locale for evaluation.
-func_show_eval_locale ()
-{
-    my_cmd="$1"
-    my_fail_exp="${2-:}"
-
-    ${opt_silent-false} || {
-      func_quote_for_expand "$my_cmd"
-      eval "func_echo $func_quote_for_expand_result"
-    }
-
-    if ${opt_dry_run-false}; then :; else
-      eval "$lt_user_locale
-	    $my_cmd"
-      my_status=$?
-      eval "$lt_safe_locale"
-      if test "$my_status" -eq 0; then :; else
-	eval "(exit $my_status); $my_fail_exp"
-      fi
-    fi
-}
-
-# func_tr_sh
-# Turn $1 into a string suitable for a shell variable name.
-# Result is stored in $func_tr_sh_result.  All characters
-# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
-# if $1 begins with a digit, a '_' is prepended as well.
-func_tr_sh ()
-{
-  case $1 in
-  [0-9]* | *[!a-zA-Z0-9_]*)
-    func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'`
-    ;;
-  * )
-    func_tr_sh_result=$1
-    ;;
-  esac
-}
-
-
-# func_version
-# Echo version message to standard output and exit.
-func_version ()
-{
-    $opt_debug
-
-    $SED -n '/(C)/!b go
-	:more
-	/\./!{
-	  N
-	  s/\n# / /
-	  b more
-	}
-	:go
-	/^# '$PROGRAM' (GNU /,/# warranty; / {
-        s/^# //
-	s/^# *$//
-        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
-        p
-     }' < "$progpath"
-     exit $?
-}
-
-# func_usage
-# Echo short help message to standard output and exit.
-func_usage ()
-{
-    $opt_debug
-
-    $SED -n '/^# Usage:/,/^#  *.*--help/ {
-        s/^# //
-	s/^# *$//
-	s/\$progname/'$progname'/
-	p
-    }' < "$progpath"
-    echo
-    $ECHO "run \`$progname --help | more' for full usage"
-    exit $?
-}
-
-# func_help [NOEXIT]
-# Echo long help message to standard output and exit,
-# unless 'noexit' is passed as argument.
-func_help ()
-{
-    $opt_debug
-
-    $SED -n '/^# Usage:/,/# Report bugs to/ {
-	:print
-        s/^# //
-	s/^# *$//
-	s*\$progname*'$progname'*
-	s*\$host*'"$host"'*
-	s*\$SHELL*'"$SHELL"'*
-	s*\$LTCC*'"$LTCC"'*
-	s*\$LTCFLAGS*'"$LTCFLAGS"'*
-	s*\$LD*'"$LD"'*
-	s/\$with_gnu_ld/'"$with_gnu_ld"'/
-	s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/
-	s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/
-	p
-	d
-     }
-     /^# .* home page:/b print
-     /^# General help using/b print
-     ' < "$progpath"
-    ret=$?
-    if test -z "$1"; then
-      exit $ret
-    fi
-}
-
-# func_missing_arg argname
-# Echo program name prefixed message to standard error and set global
-# exit_cmd.
-func_missing_arg ()
-{
-    $opt_debug
-
-    func_error "missing argument for $1."
-    exit_cmd=exit
-}
-
-
-# func_split_short_opt shortopt
-# Set func_split_short_opt_name and func_split_short_opt_arg shell
-# variables after splitting SHORTOPT after the 2nd character.
-func_split_short_opt ()
-{
-    my_sed_short_opt='1s/^\(..\).*$/\1/;q'
-    my_sed_short_rest='1s/^..\(.*\)$/\1/;q'
-
-    func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"`
-    func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"`
-} # func_split_short_opt may be replaced by extended shell implementation
-
-
-# func_split_long_opt longopt
-# Set func_split_long_opt_name and func_split_long_opt_arg shell
-# variables after splitting LONGOPT at the `=' sign.
-func_split_long_opt ()
-{
-    my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q'
-    my_sed_long_arg='1s/^--[^=]*=//'
-
-    func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"`
-    func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"`
-} # func_split_long_opt may be replaced by extended shell implementation
-
-exit_cmd=:
-
-
-
-
-
-magic="%%%MAGIC variable%%%"
-magic_exe="%%%MAGIC EXE variable%%%"
-
-# Global variables.
-nonopt=
-preserve_args=
-lo2o="s/\\.lo\$/.${objext}/"
-o2lo="s/\\.${objext}\$/.lo/"
-extracted_archives=
-extracted_serial=0
-
-# If this variable is set in any of the actions, the command in it
-# will be execed at the end.  This prevents here-documents from being
-# left over by shells.
-exec_cmd=
-
-# func_append var value
-# Append VALUE to the end of shell variable VAR.
-func_append ()
-{
-    eval "${1}=\$${1}\${2}"
-} # func_append may be replaced by extended shell implementation
-
-# func_append_quoted var value
-# Quote VALUE and append to the end of shell variable VAR, separated
-# by a space.
-func_append_quoted ()
-{
-    func_quote_for_eval "${2}"
-    eval "${1}=\$${1}\\ \$func_quote_for_eval_result"
-} # func_append_quoted may be replaced by extended shell implementation
-
-
-# func_arith arithmetic-term...
-func_arith ()
-{
-    func_arith_result=`expr "${@}"`
-} # func_arith may be replaced by extended shell implementation
-
-
-# func_len string
-# STRING may not start with a hyphen.
-func_len ()
-{
-    func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
-} # func_len may be replaced by extended shell implementation
-
-
-# func_lo2o object
-func_lo2o ()
-{
-    func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"`
-} # func_lo2o may be replaced by extended shell implementation
-
-
-# func_xform libobj-or-source
-func_xform ()
-{
-    func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
-} # func_xform may be replaced by extended shell implementation
-
-
-# func_fatal_configuration arg...
-# Echo program name prefixed message to standard error, followed by
-# a configuration failure hint, and exit.
-func_fatal_configuration ()
-{
-    func_error ${1+"$@"}
-    func_error "See the $PACKAGE documentation for more information."
-    func_fatal_error "Fatal configuration error."
-}
-
-
-# func_config
-# Display the configuration for all the tags in this script.
-func_config ()
-{
-    re_begincf='^# ### BEGIN LIBTOOL'
-    re_endcf='^# ### END LIBTOOL'
-
-    # Default configuration.
-    $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath"
-
-    # Now print the configurations for the tags.
-    for tagname in $taglist; do
-      $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath"
-    done
-
-    exit $?
-}
-
-# func_features
-# Display the features supported by this script.
-func_features ()
-{
-    echo "host: $host"
-    if test "$build_libtool_libs" = yes; then
-      echo "enable shared libraries"
-    else
-      echo "disable shared libraries"
-    fi
-    if test "$build_old_libs" = yes; then
-      echo "enable static libraries"
-    else
-      echo "disable static libraries"
-    fi
-
-    exit $?
-}
-
-# func_enable_tag tagname
-# Verify that TAGNAME is valid, and either flag an error and exit, or
-# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
-# variable here.
-func_enable_tag ()
-{
-  # Global variable:
-  tagname="$1"
-
-  re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
-  re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$"
-  sed_extractcf="/$re_begincf/,/$re_endcf/p"
-
-  # Validate tagname.
-  case $tagname in
-    *[!-_A-Za-z0-9,/]*)
-      func_fatal_error "invalid tag name: $tagname"
-      ;;
-  esac
-
-  # Don't test for the "default" C tag, as we know it's
-  # there but not specially marked.
-  case $tagname in
-    CC) ;;
-    *)
-      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
-	taglist="$taglist $tagname"
-
-	# Evaluate the configuration.  Be careful to quote the path
-	# and the sed script, to avoid splitting on whitespace, but
-	# also don't use non-portable quotes within backquotes within
-	# quotes we have to do it in 2 steps:
-	extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"`
-	eval "$extractedcf"
-      else
-	func_error "ignoring unknown tag $tagname"
-      fi
-      ;;
-  esac
-}
-
-# func_check_version_match
-# Ensure that we are using m4 macros, and libtool script from the same
-# release of libtool.
-func_check_version_match ()
-{
-  if test "$package_revision" != "$macro_revision"; then
-    if test "$VERSION" != "$macro_version"; then
-      if test -z "$macro_version"; then
-        cat >&2 <<_LT_EOF
-$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
-$progname: definition of this LT_INIT comes from an older release.
-$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
-$progname: and run autoconf again.
-_LT_EOF
-      else
-        cat >&2 <<_LT_EOF
-$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
-$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
-$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION
-$progname: and run autoconf again.
-_LT_EOF
-      fi
-    else
-      cat >&2 <<_LT_EOF
-$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,
-$progname: but the definition of this LT_INIT comes from revision $macro_revision.
-$progname: You should recreate aclocal.m4 with macros from revision $package_revision
-$progname: of $PACKAGE $VERSION and run autoconf again.
-_LT_EOF
-    fi
-
-    exit $EXIT_MISMATCH
-  fi
-}
-
-
-# Shorthand for --mode=foo, only valid as the first argument
-case $1 in
-clean|clea|cle|cl)
-  shift; set dummy --mode clean ${1+"$@"}; shift
-  ;;
-compile|compil|compi|comp|com|co|c)
-  shift; set dummy --mode compile ${1+"$@"}; shift
-  ;;
-execute|execut|execu|exec|exe|ex|e)
-  shift; set dummy --mode execute ${1+"$@"}; shift
-  ;;
-finish|finis|fini|fin|fi|f)
-  shift; set dummy --mode finish ${1+"$@"}; shift
-  ;;
-install|instal|insta|inst|ins|in|i)
-  shift; set dummy --mode install ${1+"$@"}; shift
-  ;;
-link|lin|li|l)
-  shift; set dummy --mode link ${1+"$@"}; shift
-  ;;
-uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
-  shift; set dummy --mode uninstall ${1+"$@"}; shift
-  ;;
-esac
-
-
-
-# Option defaults:
-opt_debug=:
-opt_dry_run=false
-opt_config=false
-opt_preserve_dup_deps=false
-opt_features=false
-opt_finish=false
-opt_help=false
-opt_help_all=false
-opt_silent=:
-opt_warning=:
-opt_verbose=:
-opt_silent=false
-opt_verbose=false
-
-
-# Parse options once, thoroughly.  This comes as soon as possible in the
-# script to make things like `--version' happen as quickly as we can.
-{
-  # this just eases exit handling
-  while test $# -gt 0; do
-    opt="$1"
-    shift
-    case $opt in
-      --debug|-x)	opt_debug='set -x'
-			func_echo "enabling shell trace mode"
-			$opt_debug
-			;;
-      --dry-run|--dryrun|-n)
-			opt_dry_run=:
-			;;
-      --config)
-			opt_config=:
-func_config
-			;;
-      --dlopen|-dlopen)
-			optarg="$1"
-			opt_dlopen="${opt_dlopen+$opt_dlopen
-}$optarg"
-			shift
-			;;
-      --preserve-dup-deps)
-			opt_preserve_dup_deps=:
-			;;
-      --features)
-			opt_features=:
-func_features
-			;;
-      --finish)
-			opt_finish=:
-set dummy --mode finish ${1+"$@"}; shift
-			;;
-      --help)
-			opt_help=:
-			;;
-      --help-all)
-			opt_help_all=:
-opt_help=': help-all'
-			;;
-      --mode)
-			test $# = 0 && func_missing_arg $opt && break
-			optarg="$1"
-			opt_mode="$optarg"
-case $optarg in
-  # Valid mode arguments:
-  clean|compile|execute|finish|install|link|relink|uninstall) ;;
-
-  # Catch anything else as an error
-  *) func_error "invalid argument for $opt"
-     exit_cmd=exit
-     break
-     ;;
-esac
-			shift
-			;;
-      --no-silent|--no-quiet)
-			opt_silent=false
-func_append preserve_args " $opt"
-			;;
-      --no-warning|--no-warn)
-			opt_warning=false
-func_append preserve_args " $opt"
-			;;
-      --no-verbose)
-			opt_verbose=false
-func_append preserve_args " $opt"
-			;;
-      --silent|--quiet)
-			opt_silent=:
-func_append preserve_args " $opt"
-        opt_verbose=false
-			;;
-      --verbose|-v)
-			opt_verbose=:
-func_append preserve_args " $opt"
-opt_silent=false
-			;;
-      --tag)
-			test $# = 0 && func_missing_arg $opt && break
-			optarg="$1"
-			opt_tag="$optarg"
-func_append preserve_args " $opt $optarg"
-func_enable_tag "$optarg"
-			shift
-			;;
-
-      -\?|-h)		func_usage				;;
-      --help)		func_help				;;
-      --version)	func_version				;;
-
-      # Separate optargs to long options:
-      --*=*)
-			func_split_long_opt "$opt"
-			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"}
-			shift
-			;;
-
-      # Separate non-argument short options:
-      -\?*|-h*|-n*|-v*)
-			func_split_short_opt "$opt"
-			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"}
-			shift
-			;;
-
-      --)		break					;;
-      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
-      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
-    esac
-  done
-
-  # Validate options:
-
-  # save first non-option argument
-  if test "$#" -gt 0; then
-    nonopt="$opt"
-    shift
-  fi
-
-  # preserve --debug
-  test "$opt_debug" = : || func_append preserve_args " --debug"
-
-  case $host in
-    *cygwin* | *mingw* | *pw32* | *cegcc*)
-      # don't eliminate duplications in $postdeps and $predeps
-      opt_duplicate_compiler_generated_deps=:
-      ;;
-    *)
-      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps
-      ;;
-  esac
-
-  $opt_help || {
-    # Sanity checks first:
-    func_check_version_match
-
-    if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then
-      func_fatal_configuration "not configured to build any kind of library"
-    fi
-
-    # Darwin sucks
-    eval std_shrext=\"$shrext_cmds\"
-
-    # Only execute mode is allowed to have -dlopen flags.
-    if test -n "$opt_dlopen" && test "$opt_mode" != execute; then
-      func_error "unrecognized option \`-dlopen'"
-      $ECHO "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
-
-    # Change the help message to a mode-specific one.
-    generic_help="$help"
-    help="Try \`$progname --help --mode=$opt_mode' for more information."
-  }
-
-
-  # Bail if the options were screwed
-  $exit_cmd $EXIT_FAILURE
-}
-
-
-
-
-## ----------- ##
-##    Main.    ##
-## ----------- ##
-
-# func_lalib_p file
-# True iff FILE is a libtool `.la' library or `.lo' object file.
-# This function is only a basic sanity check; it will hardly flush out
-# determined imposters.
-func_lalib_p ()
-{
-    test -f "$1" &&
-      $SED -e 4q "$1" 2>/dev/null \
-        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
-}
-
-# func_lalib_unsafe_p file
-# True iff FILE is a libtool `.la' library or `.lo' object file.
-# This function implements the same check as func_lalib_p without
-# resorting to external programs.  To this end, it redirects stdin and
-# closes it afterwards, without saving the original file descriptor.
-# As a safety measure, use it only where a negative result would be
-# fatal anyway.  Works if `file' does not exist.
-func_lalib_unsafe_p ()
-{
-    lalib_p=no
-    if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then
-	for lalib_p_l in 1 2 3 4
-	do
-	    read lalib_p_line
-	    case "$lalib_p_line" in
-		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;;
-	    esac
-	done
-	exec 0<&5 5<&-
-    fi
-    test "$lalib_p" = yes
-}
-
-# func_ltwrapper_script_p file
-# True iff FILE is a libtool wrapper script
-# This function is only a basic sanity check; it will hardly flush out
-# determined imposters.
-func_ltwrapper_script_p ()
-{
-    func_lalib_p "$1"
-}
-
-# func_ltwrapper_executable_p file
-# True iff FILE is a libtool wrapper executable
-# This function is only a basic sanity check; it will hardly flush out
-# determined imposters.
-func_ltwrapper_executable_p ()
-{
-    func_ltwrapper_exec_suffix=
-    case $1 in
-    *.exe) ;;
-    *) func_ltwrapper_exec_suffix=.exe ;;
-    esac
-    $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1
-}
-
-# func_ltwrapper_scriptname file
-# Assumes file is an ltwrapper_executable
-# uses $file to determine the appropriate filename for a
-# temporary ltwrapper_script.
-func_ltwrapper_scriptname ()
-{
-    func_dirname_and_basename "$1" "" "."
-    func_stripname '' '.exe' "$func_basename_result"
-    func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper"
-}
-
-# func_ltwrapper_p file
-# True iff FILE is a libtool wrapper script or wrapper executable
-# This function is only a basic sanity check; it will hardly flush out
-# determined imposters.
-func_ltwrapper_p ()
-{
-    func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1"
-}
-
-
-# func_execute_cmds commands fail_cmd
-# Execute tilde-delimited COMMANDS.
-# If FAIL_CMD is given, eval that upon failure.
-# FAIL_CMD may read-access the current command in variable CMD!
-func_execute_cmds ()
-{
-    $opt_debug
-    save_ifs=$IFS; IFS='~'
-    for cmd in $1; do
-      IFS=$save_ifs
-      eval cmd=\"$cmd\"
-      func_show_eval "$cmd" "${2-:}"
-    done
-    IFS=$save_ifs
-}
-
-
-# func_source file
-# Source FILE, adding directory component if necessary.
-# Note that it is not necessary on cygwin/mingw to append a dot to
-# FILE even if both FILE and FILE.exe exist: automatic-append-.exe
-# behavior happens only for exec(3), not for open(2)!  Also, sourcing
-# `FILE.' does not work on cygwin managed mounts.
-func_source ()
-{
-    $opt_debug
-    case $1 in
-    */* | *\\*)	. "$1" ;;
-    *)		. "./$1" ;;
-    esac
-}
-
-
-# func_resolve_sysroot PATH
-# Replace a leading = in PATH with a sysroot.  Store the result into
-# func_resolve_sysroot_result
-func_resolve_sysroot ()
-{
-  func_resolve_sysroot_result=$1
-  case $func_resolve_sysroot_result in
-  =*)
-    func_stripname '=' '' "$func_resolve_sysroot_result"
-    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result
-    ;;
-  esac
-}
-
-# func_replace_sysroot PATH
-# If PATH begins with the sysroot, replace it with = and
-# store the result into func_replace_sysroot_result.
-func_replace_sysroot ()
-{
-  case "$lt_sysroot:$1" in
-  ?*:"$lt_sysroot"*)
-    func_stripname "$lt_sysroot" '' "$1"
-    func_replace_sysroot_result="=$func_stripname_result"
-    ;;
-  *)
-    # Including no sysroot.
-    func_replace_sysroot_result=$1
-    ;;
-  esac
-}
-
-# func_infer_tag arg
-# Infer tagged configuration to use if any are available and
-# if one wasn't chosen via the "--tag" command line option.
-# Only attempt this if the compiler in the base compile
-# command doesn't match the default compiler.
-# arg is usually of the form 'gcc ...'
-func_infer_tag ()
-{
-    $opt_debug
-    if test -n "$available_tags" && test -z "$tagname"; then
-      CC_quoted=
-      for arg in $CC; do
-	func_append_quoted CC_quoted "$arg"
-      done
-      CC_expanded=`func_echo_all $CC`
-      CC_quoted_expanded=`func_echo_all $CC_quoted`
-      case $@ in
-      # Blanks in the command may have been stripped by the calling shell,
-      # but not from the CC environment variable when configure was run.
-      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
-      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;;
-      # Blanks at the start of $base_compile will cause this to fail
-      # if we don't check for them as well.
-      *)
-	for z in $available_tags; do
-	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then
-	    # Evaluate the configuration.
-	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
-	    CC_quoted=
-	    for arg in $CC; do
-	      # Double-quote args containing other shell metacharacters.
-	      func_append_quoted CC_quoted "$arg"
-	    done
-	    CC_expanded=`func_echo_all $CC`
-	    CC_quoted_expanded=`func_echo_all $CC_quoted`
-	    case "$@ " in
-	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
-	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*)
-	      # The compiler in the base compile command matches
-	      # the one in the tagged configuration.
-	      # Assume this is the tagged configuration we want.
-	      tagname=$z
-	      break
-	      ;;
-	    esac
-	  fi
-	done
-	# If $tagname still isn't set, then no tagged configuration
-	# was found and let the user know that the "--tag" command
-	# line option must be used.
-	if test -z "$tagname"; then
-	  func_echo "unable to infer tagged configuration"
-	  func_fatal_error "specify a tag with \`--tag'"
-#	else
-#	  func_verbose "using $tagname tagged configuration"
-	fi
-	;;
-      esac
-    fi
-}
-
-
-
-# func_write_libtool_object output_name pic_name nonpic_name
-# Create a libtool object file (analogous to a ".la" file),
-# but don't create it if we're doing a dry run.
-func_write_libtool_object ()
-{
-    write_libobj=${1}
-    if test "$build_libtool_libs" = yes; then
-      write_lobj=\'${2}\'
-    else
-      write_lobj=none
-    fi
-
-    if test "$build_old_libs" = yes; then
-      write_oldobj=\'${3}\'
-    else
-      write_oldobj=none
-    fi
-
-    $opt_dry_run || {
-      cat >${write_libobj}T <<EOF
-# $write_libobj - a libtool object file
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
-#
-# Please DO NOT delete this file!
-# It is necessary for linking the library.
-
-# Name of the PIC object.
-pic_object=$write_lobj
-
-# Name of the non-PIC object
-non_pic_object=$write_oldobj
-
-EOF
-      $MV "${write_libobj}T" "${write_libobj}"
-    }
-}
-
-
-##################################################
-# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
-##################################################
-
-# func_convert_core_file_wine_to_w32 ARG
-# Helper function used by file name conversion functions when $build is *nix,
-# and $host is mingw, cygwin, or some other w32 environment. Relies on a
-# correctly configured wine environment available, with the winepath program
-# in $build's $PATH.
-#
-# ARG is the $build file name to be converted to w32 format.
-# Result is available in $func_convert_core_file_wine_to_w32_result, and will
-# be empty on error (or when ARG is empty)
-func_convert_core_file_wine_to_w32 ()
-{
-  $opt_debug
-  func_convert_core_file_wine_to_w32_result="$1"
-  if test -n "$1"; then
-    # Unfortunately, winepath does not exit with a non-zero error code, so we
-    # are forced to check the contents of stdout. On the other hand, if the
-    # command is not found, the shell will set an exit code of 127 and print
-    # *an error message* to stdout. So we must check for both error code of
-    # zero AND non-empty stdout, which explains the odd construction:
-    func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null`
-    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then
-      func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" |
-        $SED -e "$lt_sed_naive_backslashify"`
-    else
-      func_convert_core_file_wine_to_w32_result=
-    fi
-  fi
-}
-# end: func_convert_core_file_wine_to_w32
-
-
-# func_convert_core_path_wine_to_w32 ARG
-# Helper function used by path conversion functions when $build is *nix, and
-# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly
-# configured wine environment available, with the winepath program in $build's
-# $PATH. Assumes ARG has no leading or trailing path separator characters.
-#
-# ARG is path to be converted from $build format to win32.
-# Result is available in $func_convert_core_path_wine_to_w32_result.
-# Unconvertible file (directory) names in ARG are skipped; if no directory names
-# are convertible, then the result may be empty.
-func_convert_core_path_wine_to_w32 ()
-{
-  $opt_debug
-  # unfortunately, winepath doesn't convert paths, only file names
-  func_convert_core_path_wine_to_w32_result=""
-  if test -n "$1"; then
-    oldIFS=$IFS
-    IFS=:
-    for func_convert_core_path_wine_to_w32_f in $1; do
-      IFS=$oldIFS
-      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f"
-      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
-        if test -z "$func_convert_core_path_wine_to_w32_result"; then
-          func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result"
-        else
-          func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result"
-        fi
-      fi
-    done
-    IFS=$oldIFS
-  fi
-}
-# end: func_convert_core_path_wine_to_w32
-
-
-# func_cygpath ARGS...
-# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when
-# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)
-# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or
-# (2), returns the Cygwin file name or path in func_cygpath_result (input
-# file name or path is assumed to be in w32 format, as previously converted
-# from $build's *nix or MSYS format). In case (3), returns the w32 file name
-# or path in func_cygpath_result (input file name or path is assumed to be in
-# Cygwin format). Returns an empty string on error.
-#
-# ARGS are passed to cygpath, with the last one being the file name or path to
-# be converted.
-#
-# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
-# environment variable; do not put it in $PATH.
-func_cygpath ()
-{
-  $opt_debug
-  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
-    func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null`
-    if test "$?" -ne 0; then
-      # on failure, ensure result is empty
-      func_cygpath_result=
-    fi
-  else
-    func_cygpath_result=
-    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'"
-  fi
-}
-#end: func_cygpath
-
-
-# func_convert_core_msys_to_w32 ARG
-# Convert file name or path ARG from MSYS format to w32 format.  Return
-# result in func_convert_core_msys_to_w32_result.
-func_convert_core_msys_to_w32 ()
-{
-  $opt_debug
-  # awkward: cmd appends spaces to result
-  func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null |
-    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
-}
-#end: func_convert_core_msys_to_w32
-
-
-# func_convert_file_check ARG1 ARG2
-# Verify that ARG1 (a file name in $build format) was converted to $host
-# format in ARG2. Otherwise, emit an error message, but continue (resetting
-# func_to_host_file_result to ARG1).
-func_convert_file_check ()
-{
-  $opt_debug
-  if test -z "$2" && test -n "$1" ; then
-    func_error "Could not determine host file name corresponding to"
-    func_error "  \`$1'"
-    func_error "Continuing, but uninstalled executables may not work."
-    # Fallback:
-    func_to_host_file_result="$1"
-  fi
-}
-# end func_convert_file_check
-
-
-# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
-# Verify that FROM_PATH (a path in $build format) was converted to $host
-# format in TO_PATH. Otherwise, emit an error message, but continue, resetting
-# func_to_host_file_result to a simplistic fallback value (see below).
-func_convert_path_check ()
-{
-  $opt_debug
-  if test -z "$4" && test -n "$3"; then
-    func_error "Could not determine the host path corresponding to"
-    func_error "  \`$3'"
-    func_error "Continuing, but uninstalled executables may not work."
-    # Fallback.  This is a deliberately simplistic "conversion" and
-    # should not be "improved".  See libtool.info.
-    if test "x$1" != "x$2"; then
-      lt_replace_pathsep_chars="s|$1|$2|g"
-      func_to_host_path_result=`echo "$3" |
-        $SED -e "$lt_replace_pathsep_chars"`
-    else
-      func_to_host_path_result="$3"
-    fi
-  fi
-}
-# end func_convert_path_check
-
-
-# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
-# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT
-# and appending REPL if ORIG matches BACKPAT.
-func_convert_path_front_back_pathsep ()
-{
-  $opt_debug
-  case $4 in
-  $1 ) func_to_host_path_result="$3$func_to_host_path_result"
-    ;;
-  esac
-  case $4 in
-  $2 ) func_append func_to_host_path_result "$3"
-    ;;
-  esac
-}
-# end func_convert_path_front_back_pathsep
-
-
-##################################################
-# $build to $host FILE NAME CONVERSION FUNCTIONS #
-##################################################
-# invoked via `$to_host_file_cmd ARG'
-#
-# In each case, ARG is the path to be converted from $build to $host format.
-# Result will be available in $func_to_host_file_result.
-
-
-# func_to_host_file ARG
-# Converts the file name ARG from $build format to $host format. Return result
-# in func_to_host_file_result.
-func_to_host_file ()
-{
-  $opt_debug
-  $to_host_file_cmd "$1"
-}
-# end func_to_host_file
-
-
-# func_to_tool_file ARG LAZY
-# converts the file name ARG from $build format to toolchain format. Return
-# result in func_to_tool_file_result.  If the conversion in use is listed
-# in (the comma separated) LAZY, no conversion takes place.
-func_to_tool_file ()
-{
-  $opt_debug
-  case ,$2, in
-    *,"$to_tool_file_cmd",*)
-      func_to_tool_file_result=$1
-      ;;
-    *)
-      $to_tool_file_cmd "$1"
-      func_to_tool_file_result=$func_to_host_file_result
-      ;;
-  esac
-}
-# end func_to_tool_file
-
-
-# func_convert_file_noop ARG
-# Copy ARG to func_to_host_file_result.
-func_convert_file_noop ()
-{
-  func_to_host_file_result="$1"
-}
-# end func_convert_file_noop
-
-
-# func_convert_file_msys_to_w32 ARG
-# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
-# conversion to w32 is not available inside the cwrapper.  Returns result in
-# func_to_host_file_result.
-func_convert_file_msys_to_w32 ()
-{
-  $opt_debug
-  func_to_host_file_result="$1"
-  if test -n "$1"; then
-    func_convert_core_msys_to_w32 "$1"
-    func_to_host_file_result="$func_convert_core_msys_to_w32_result"
-  fi
-  func_convert_file_check "$1" "$func_to_host_file_result"
-}
-# end func_convert_file_msys_to_w32
-
-
-# func_convert_file_cygwin_to_w32 ARG
-# Convert file name ARG from Cygwin to w32 format.  Returns result in
-# func_to_host_file_result.
-func_convert_file_cygwin_to_w32 ()
-{
-  $opt_debug
-  func_to_host_file_result="$1"
-  if test -n "$1"; then
-    # because $build is cygwin, we call "the" cygpath in $PATH; no need to use
-    # LT_CYGPATH in this case.
-    func_to_host_file_result=`cygpath -m "$1"`
-  fi
-  func_convert_file_check "$1" "$func_to_host_file_result"
-}
-# end func_convert_file_cygwin_to_w32
-
-
-# func_convert_file_nix_to_w32 ARG
-# Convert file name ARG from *nix to w32 format.  Requires a wine environment
-# and a working winepath. Returns result in func_to_host_file_result.
-func_convert_file_nix_to_w32 ()
-{
-  $opt_debug
-  func_to_host_file_result="$1"
-  if test -n "$1"; then
-    func_convert_core_file_wine_to_w32 "$1"
-    func_to_host_file_result="$func_convert_core_file_wine_to_w32_result"
-  fi
-  func_convert_file_check "$1" "$func_to_host_file_result"
-}
-# end func_convert_file_nix_to_w32
-
-
-# func_convert_file_msys_to_cygwin ARG
-# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
-# Returns result in func_to_host_file_result.
-func_convert_file_msys_to_cygwin ()
-{
-  $opt_debug
-  func_to_host_file_result="$1"
-  if test -n "$1"; then
-    func_convert_core_msys_to_w32 "$1"
-    func_cygpath -u "$func_convert_core_msys_to_w32_result"
-    func_to_host_file_result="$func_cygpath_result"
-  fi
-  func_convert_file_check "$1" "$func_to_host_file_result"
-}
-# end func_convert_file_msys_to_cygwin
-
-
-# func_convert_file_nix_to_cygwin ARG
-# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed
-# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result
-# in func_to_host_file_result.
-func_convert_file_nix_to_cygwin ()
-{
-  $opt_debug
-  func_to_host_file_result="$1"
-  if test -n "$1"; then
-    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.
-    func_convert_core_file_wine_to_w32 "$1"
-    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
-    func_to_host_file_result="$func_cygpath_result"
-  fi
-  func_convert_file_check "$1" "$func_to_host_file_result"
-}
-# end func_convert_file_nix_to_cygwin
-
-
-#############################################
-# $build to $host PATH CONVERSION FUNCTIONS #
-#############################################
-# invoked via `$to_host_path_cmd ARG'
-#
-# In each case, ARG is the path to be converted from $build to $host format.
-# The result will be available in $func_to_host_path_result.
-#
-# Path separators are also converted from $build format to $host format.  If
-# ARG begins or ends with a path separator character, it is preserved (but
-# converted to $host format) on output.
-#
-# All path conversion functions are named using the following convention:
-#   file name conversion function    : func_convert_file_X_to_Y ()
-#   path conversion function         : func_convert_path_X_to_Y ()
-# where, for any given $build/$host combination the 'X_to_Y' value is the
-# same.  If conversion functions are added for new $build/$host combinations,
-# the two new functions must follow this pattern, or func_init_to_host_path_cmd
-# will break.
-
-
-# func_init_to_host_path_cmd
-# Ensures that function "pointer" variable $to_host_path_cmd is set to the
-# appropriate value, based on the value of $to_host_file_cmd.
-to_host_path_cmd=
-func_init_to_host_path_cmd ()
-{
-  $opt_debug
-  if test -z "$to_host_path_cmd"; then
-    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
-    to_host_path_cmd="func_convert_path_${func_stripname_result}"
-  fi
-}
-
-
-# func_to_host_path ARG
-# Converts the path ARG from $build format to $host format. Return result
-# in func_to_host_path_result.
-func_to_host_path ()
-{
-  $opt_debug
-  func_init_to_host_path_cmd
-  $to_host_path_cmd "$1"
-}
-# end func_to_host_path
-
-
-# func_convert_path_noop ARG
-# Copy ARG to func_to_host_path_result.
-func_convert_path_noop ()
-{
-  func_to_host_path_result="$1"
-}
-# end func_convert_path_noop
-
-
-# func_convert_path_msys_to_w32 ARG
-# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
-# conversion to w32 is not available inside the cwrapper.  Returns result in
-# func_to_host_path_result.
-func_convert_path_msys_to_w32 ()
-{
-  $opt_debug
-  func_to_host_path_result="$1"
-  if test -n "$1"; then
-    # Remove leading and trailing path separator characters from ARG.  MSYS
-    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
-    # and winepath ignores them completely.
-    func_stripname : : "$1"
-    func_to_host_path_tmp1=$func_stripname_result
-    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
-    func_to_host_path_result="$func_convert_core_msys_to_w32_result"
-    func_convert_path_check : ";" \
-      "$func_to_host_path_tmp1" "$func_to_host_path_result"
-    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
-  fi
-}
-# end func_convert_path_msys_to_w32
-
-
-# func_convert_path_cygwin_to_w32 ARG
-# Convert path ARG from Cygwin to w32 format.  Returns result in
-# func_to_host_file_result.
-func_convert_path_cygwin_to_w32 ()
-{
-  $opt_debug
-  func_to_host_path_result="$1"
-  if test -n "$1"; then
-    # See func_convert_path_msys_to_w32:
-    func_stripname : : "$1"
-    func_to_host_path_tmp1=$func_stripname_result
-    func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"`
-    func_convert_path_check : ";" \
-      "$func_to_host_path_tmp1" "$func_to_host_path_result"
-    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
-  fi
-}
-# end func_convert_path_cygwin_to_w32
-
-
-# func_convert_path_nix_to_w32 ARG
-# Convert path ARG from *nix to w32 format.  Requires a wine environment and
-# a working winepath.  Returns result in func_to_host_file_result.
-func_convert_path_nix_to_w32 ()
-{
-  $opt_debug
-  func_to_host_path_result="$1"
-  if test -n "$1"; then
-    # See func_convert_path_msys_to_w32:
-    func_stripname : : "$1"
-    func_to_host_path_tmp1=$func_stripname_result
-    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
-    func_to_host_path_result="$func_convert_core_path_wine_to_w32_result"
-    func_convert_path_check : ";" \
-      "$func_to_host_path_tmp1" "$func_to_host_path_result"
-    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
-  fi
-}
-# end func_convert_path_nix_to_w32
-
-
-# func_convert_path_msys_to_cygwin ARG
-# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
-# Returns result in func_to_host_file_result.
-func_convert_path_msys_to_cygwin ()
-{
-  $opt_debug
-  func_to_host_path_result="$1"
-  if test -n "$1"; then
-    # See func_convert_path_msys_to_w32:
-    func_stripname : : "$1"
-    func_to_host_path_tmp1=$func_stripname_result
-    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
-    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
-    func_to_host_path_result="$func_cygpath_result"
-    func_convert_path_check : : \
-      "$func_to_host_path_tmp1" "$func_to_host_path_result"
-    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
-  fi
-}
-# end func_convert_path_msys_to_cygwin
-
-
-# func_convert_path_nix_to_cygwin ARG
-# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a
-# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in
-# func_to_host_file_result.
-func_convert_path_nix_to_cygwin ()
-{
-  $opt_debug
-  func_to_host_path_result="$1"
-  if test -n "$1"; then
-    # Remove leading and trailing path separator characters from
-    # ARG. msys behavior is inconsistent here, cygpath turns them
-    # into '.;' and ';.', and winepath ignores them completely.
-    func_stripname : : "$1"
-    func_to_host_path_tmp1=$func_stripname_result
-    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
-    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
-    func_to_host_path_result="$func_cygpath_result"
-    func_convert_path_check : : \
-      "$func_to_host_path_tmp1" "$func_to_host_path_result"
-    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
-  fi
-}
-# end func_convert_path_nix_to_cygwin
-
-
-# func_mode_compile arg...
-func_mode_compile ()
-{
-    $opt_debug
-    # Get the compilation command and the source file.
-    base_compile=
-    srcfile="$nonopt"  #  always keep a non-empty value in "srcfile"
-    suppress_opt=yes
-    suppress_output=
-    arg_mode=normal
-    libobj=
-    later=
-    pie_flag=
-
-    for arg
-    do
-      case $arg_mode in
-      arg  )
-	# do not "continue".  Instead, add this to base_compile
-	lastarg="$arg"
-	arg_mode=normal
-	;;
-
-      target )
-	libobj="$arg"
-	arg_mode=normal
-	continue
-	;;
-
-      normal )
-	# Accept any command-line options.
-	case $arg in
-	-o)
-	  test -n "$libobj" && \
-	    func_fatal_error "you cannot specify \`-o' more than once"
-	  arg_mode=target
-	  continue
-	  ;;
-
-	-pie | -fpie | -fPIE)
-          func_append pie_flag " $arg"
-	  continue
-	  ;;
-
-	-shared | -static | -prefer-pic | -prefer-non-pic)
-	  func_append later " $arg"
-	  continue
-	  ;;
-
-	-no-suppress)
-	  suppress_opt=no
-	  continue
-	  ;;
-
-	-Xcompiler)
-	  arg_mode=arg  #  the next one goes into the "base_compile" arg list
-	  continue      #  The current "srcfile" will either be retained or
-	  ;;            #  replaced later.  I would guess that would be a bug.
-
-	-Wc,*)
-	  func_stripname '-Wc,' '' "$arg"
-	  args=$func_stripname_result
-	  lastarg=
-	  save_ifs="$IFS"; IFS=','
-	  for arg in $args; do
-	    IFS="$save_ifs"
-	    func_append_quoted lastarg "$arg"
-	  done
-	  IFS="$save_ifs"
-	  func_stripname ' ' '' "$lastarg"
-	  lastarg=$func_stripname_result
-
-	  # Add the arguments to base_compile.
-	  func_append base_compile " $lastarg"
-	  continue
-	  ;;
-
-	*)
-	  # Accept the current argument as the source file.
-	  # The previous "srcfile" becomes the current argument.
-	  #
-	  lastarg="$srcfile"
-	  srcfile="$arg"
-	  ;;
-	esac  #  case $arg
-	;;
-      esac    #  case $arg_mode
-
-      # Aesthetically quote the previous argument.
-      func_append_quoted base_compile "$lastarg"
-    done # for arg
-
-    case $arg_mode in
-    arg)
-      func_fatal_error "you must specify an argument for -Xcompile"
-      ;;
-    target)
-      func_fatal_error "you must specify a target with \`-o'"
-      ;;
-    *)
-      # Get the name of the library object.
-      test -z "$libobj" && {
-	func_basename "$srcfile"
-	libobj="$func_basename_result"
-      }
-      ;;
-    esac
-
-    # Recognize several different file suffixes.
-    # If the user specifies -o file.o, it is replaced with file.lo
-    case $libobj in
-    *.[cCFSifmso] | \
-    *.ada | *.adb | *.ads | *.asm | \
-    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
-    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)
-      func_xform "$libobj"
-      libobj=$func_xform_result
-      ;;
-    esac
-
-    case $libobj in
-    *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;;
-    *)
-      func_fatal_error "cannot determine name of library object from \`$libobj'"
-      ;;
-    esac
-
-    func_infer_tag $base_compile
-
-    for arg in $later; do
-      case $arg in
-      -shared)
-	test "$build_libtool_libs" != yes && \
-	  func_fatal_configuration "can not build a shared library"
-	build_old_libs=no
-	continue
-	;;
-
-      -static)
-	build_libtool_libs=no
-	build_old_libs=yes
-	continue
-	;;
-
-      -prefer-pic)
-	pic_mode=yes
-	continue
-	;;
-
-      -prefer-non-pic)
-	pic_mode=no
-	continue
-	;;
-      esac
-    done
-
-    func_quote_for_eval "$libobj"
-    test "X$libobj" != "X$func_quote_for_eval_result" \
-      && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
-      && func_warning "libobj name \`$libobj' may not contain shell special characters."
-    func_dirname_and_basename "$obj" "/" ""
-    objname="$func_basename_result"
-    xdir="$func_dirname_result"
-    lobj=${xdir}$objdir/$objname
-
-    test -z "$base_compile" && \
-      func_fatal_help "you must specify a compilation command"
-
-    # Delete any leftover library objects.
-    if test "$build_old_libs" = yes; then
-      removelist="$obj $lobj $libobj ${libobj}T"
-    else
-      removelist="$lobj $libobj ${libobj}T"
-    fi
-
-    # On Cygwin there's no "real" PIC flag so we must build both object types
-    case $host_os in
-    cygwin* | mingw* | pw32* | os2* | cegcc*)
-      pic_mode=default
-      ;;
-    esac
-    if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then
-      # non-PIC code in shared libraries is not supported
-      pic_mode=default
-    fi
-
-    # Calculate the filename of the output object if compiler does
-    # not support -o with -c
-    if test "$compiler_c_o" = no; then
-      output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext}
-      lockfile="$output_obj.lock"
-    else
-      output_obj=
-      need_locks=no
-      lockfile=
-    fi
-
-    # Lock this critical section if it is needed
-    # We use this script file to make the link, it avoids creating a new file
-    if test "$need_locks" = yes; then
-      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
-	func_echo "Waiting for $lockfile to be removed"
-	sleep 2
-      done
-    elif test "$need_locks" = warn; then
-      if test -f "$lockfile"; then
-	$ECHO "\
-*** ERROR, $lockfile exists and contains:
-`cat $lockfile 2>/dev/null`
-
-This indicates that another process is trying to use the same
-temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
-repeat this compilation, it may succeed, by chance, but you had better
-avoid parallel builds (make -j) in this platform, or get a better
-compiler."
-
-	$opt_dry_run || $RM $removelist
-	exit $EXIT_FAILURE
-      fi
-      func_append removelist " $output_obj"
-      $ECHO "$srcfile" > "$lockfile"
-    fi
-
-    $opt_dry_run || $RM $removelist
-    func_append removelist " $lockfile"
-    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
-
-    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
-    srcfile=$func_to_tool_file_result
-    func_quote_for_eval "$srcfile"
-    qsrcfile=$func_quote_for_eval_result
-
-    # Only build a PIC object if we are building libtool libraries.
-    if test "$build_libtool_libs" = yes; then
-      # Without this assignment, base_compile gets emptied.
-      fbsd_hideous_sh_bug=$base_compile
-
-      if test "$pic_mode" != no; then
-	command="$base_compile $qsrcfile $pic_flag"
-      else
-	# Don't build PIC code
-	command="$base_compile $qsrcfile"
-      fi
-
-      func_mkdir_p "$xdir$objdir"
-
-      if test -z "$output_obj"; then
-	# Place PIC objects in $objdir
-	func_append command " -o $lobj"
-      fi
-
-      func_show_eval_locale "$command"	\
-          'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'
-
-      if test "$need_locks" = warn &&
-	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
-	$ECHO "\
-*** ERROR, $lockfile contains:
-`cat $lockfile 2>/dev/null`
-
-but it should contain:
-$srcfile
-
-This indicates that another process is trying to use the same
-temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
-repeat this compilation, it may succeed, by chance, but you had better
-avoid parallel builds (make -j) in this platform, or get a better
-compiler."
-
-	$opt_dry_run || $RM $removelist
-	exit $EXIT_FAILURE
-      fi
-
-      # Just move the object if needed, then go on to compile the next one
-      if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then
-	func_show_eval '$MV "$output_obj" "$lobj"' \
-	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
-      fi
-
-      # Allow error messages only from the first compilation.
-      if test "$suppress_opt" = yes; then
-	suppress_output=' >/dev/null 2>&1'
-      fi
-    fi
-
-    # Only build a position-dependent object if we build old libraries.
-    if test "$build_old_libs" = yes; then
-      if test "$pic_mode" != yes; then
-	# Don't build PIC code
-	command="$base_compile $qsrcfile$pie_flag"
-      else
-	command="$base_compile $qsrcfile $pic_flag"
-      fi
-      if test "$compiler_c_o" = yes; then
-	func_append command " -o $obj"
-      fi
-
-      # Suppress compiler output if we already did a PIC compilation.
-      func_append command "$suppress_output"
-      func_show_eval_locale "$command" \
-        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
-
-      if test "$need_locks" = warn &&
-	 test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then
-	$ECHO "\
-*** ERROR, $lockfile contains:
-`cat $lockfile 2>/dev/null`
-
-but it should contain:
-$srcfile
-
-This indicates that another process is trying to use the same
-temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
-repeat this compilation, it may succeed, by chance, but you had better
-avoid parallel builds (make -j) in this platform, or get a better
-compiler."
-
-	$opt_dry_run || $RM $removelist
-	exit $EXIT_FAILURE
-      fi
-
-      # Just move the object if needed
-      if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then
-	func_show_eval '$MV "$output_obj" "$obj"' \
-	  'error=$?; $opt_dry_run || $RM $removelist; exit $error'
-      fi
-    fi
-
-    $opt_dry_run || {
-      func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"
-
-      # Unlock the critical section if it was locked
-      if test "$need_locks" != no; then
-	removelist=$lockfile
-        $RM "$lockfile"
-      fi
-    }
-
-    exit $EXIT_SUCCESS
-}
-
-$opt_help || {
-  test "$opt_mode" = compile && func_mode_compile ${1+"$@"}
-}
-
-func_mode_help ()
-{
-    # We need to display help for each of the modes.
-    case $opt_mode in
-      "")
-        # Generic help is extracted from the usage comments
-        # at the start of this file.
-        func_help
-        ;;
-
-      clean)
-        $ECHO \
-"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...
-
-Remove files from the build directory.
-
-RM is the name of the program to use to delete files associated with each FILE
-(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
-to RM.
-
-If FILE is a libtool library, object or program, all the files associated
-with it are deleted. Otherwise, only FILE itself is deleted using RM."
-        ;;
-
-      compile)
-      $ECHO \
-"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE
-
-Compile a source file into a libtool library object.
-
-This mode accepts the following additional options:
-
-  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
-  -no-suppress      do not suppress compiler output for multiple passes
-  -prefer-pic       try to build PIC objects only
-  -prefer-non-pic   try to build non-PIC objects only
-  -shared           do not build a \`.o' file suitable for static linking
-  -static           only build a \`.o' file suitable for static linking
-  -Wc,FLAG          pass FLAG directly to the compiler
-
-COMPILE-COMMAND is a command to be used in creating a \`standard' object file
-from the given SOURCEFILE.
-
-The output file name is determined by removing the directory component from
-SOURCEFILE, then substituting the C source code suffix \`.c' with the
-library object suffix, \`.lo'."
-        ;;
-
-      execute)
-        $ECHO \
-"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...
-
-Automatically set library path, then run a program.
-
-This mode accepts the following additional options:
-
-  -dlopen FILE      add the directory containing FILE to the library path
-
-This mode sets the library path environment variable according to \`-dlopen'
-flags.
-
-If any of the ARGS are libtool executable wrappers, then they are translated
-into their corresponding uninstalled binary, and any of their required library
-directories are added to the library path.
-
-Then, COMMAND is executed, with ARGS as arguments."
-        ;;
-
-      finish)
-        $ECHO \
-"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...
-
-Complete the installation of libtool libraries.
-
-Each LIBDIR is a directory that contains libtool libraries.
-
-The commands that this mode executes may require superuser privileges.  Use
-the \`--dry-run' option if you just want to see what would be executed."
-        ;;
-
-      install)
-        $ECHO \
-"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...
-
-Install executables or libraries.
-
-INSTALL-COMMAND is the installation command.  The first component should be
-either the \`install' or \`cp' program.
-
-The following components of INSTALL-COMMAND are treated specially:
-
-  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation
-
-The rest of the components are interpreted as arguments to that command (only
-BSD-compatible install options are recognized)."
-        ;;
-
-      link)
-        $ECHO \
-"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...
-
-Link object files or libraries together to form another library, or to
-create an executable program.
-
-LINK-COMMAND is a command using the C compiler that you would use to create
-a program from several object files.
-
-The following components of LINK-COMMAND are treated specially:
-
-  -all-static       do not do any dynamic linking at all
-  -avoid-version    do not add a version suffix if possible
-  -bindir BINDIR    specify path to binaries directory (for systems where
-                    libraries must be found in the PATH setting at runtime)
-  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
-  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols
-  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)
-  -export-symbols SYMFILE
-                    try to export only the symbols listed in SYMFILE
-  -export-symbols-regex REGEX
-                    try to export only the symbols matching REGEX
-  -LLIBDIR          search LIBDIR for required installed libraries
-  -lNAME            OUTPUT-FILE requires the installed library libNAME
-  -module           build a library that can dlopened
-  -no-fast-install  disable the fast-install mode
-  -no-install       link a not-installable executable
-  -no-undefined     declare that a library does not refer to external symbols
-  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
-  -objectlist FILE  Use a list of object files found in FILE to specify objects
-  -precious-files-regex REGEX
-                    don't remove output files matching REGEX
-  -release RELEASE  specify package release information
-  -rpath LIBDIR     the created library will eventually be installed in LIBDIR
-  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries
-  -shared           only do dynamic linking of libtool libraries
-  -shrext SUFFIX    override the standard shared library file extension
-  -static           do not do any dynamic linking of uninstalled libtool libraries
-  -static-libtool-libs
-                    do not do any dynamic linking of libtool libraries
-  -version-info CURRENT[:REVISION[:AGE]]
-                    specify library version info [each variable defaults to 0]
-  -weak LIBNAME     declare that the target provides the LIBNAME interface
-  -Wc,FLAG
-  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
-  -Wl,FLAG
-  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
-  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
-
-All other options (arguments beginning with \`-') are ignored.
-
-Every other argument is treated as a filename.  Files ending in \`.la' are
-treated as uninstalled libtool libraries, other files are standard or library
-object files.
-
-If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
-only library objects (\`.lo' files) may be specified, and \`-rpath' is
-required, except when creating a convenience library.
-
-If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
-using \`ar' and \`ranlib', or on Windows using \`lib'.
-
-If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file
-is created, otherwise an executable program is created."
-        ;;
-
-      uninstall)
-        $ECHO \
-"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...
-
-Remove libraries from an installation directory.
-
-RM is the name of the program to use to delete files associated with each FILE
-(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be passed
-to RM.
-
-If FILE is a libtool library, all the files associated with it are deleted.
-Otherwise, only FILE itself is deleted using RM."
-        ;;
-
-      *)
-        func_fatal_help "invalid operation mode \`$opt_mode'"
-        ;;
-    esac
-
-    echo
-    $ECHO "Try \`$progname --help' for more information about other modes."
-}
-
-# Now that we've collected a possible --mode arg, show help if necessary
-if $opt_help; then
-  if test "$opt_help" = :; then
-    func_mode_help
-  else
-    {
-      func_help noexit
-      for opt_mode in compile link execute install finish uninstall clean; do
-	func_mode_help
-      done
-    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
-    {
-      func_help noexit
-      for opt_mode in compile link execute install finish uninstall clean; do
-	echo
-	func_mode_help
-      done
-    } |
-    sed '1d
-      /^When reporting/,/^Report/{
-	H
-	d
-      }
-      $x
-      /information about other modes/d
-      /more detailed .*MODE/d
-      s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/'
-  fi
-  exit $?
-fi
-
-
-# func_mode_execute arg...
-func_mode_execute ()
-{
-    $opt_debug
-    # The first argument is the command name.
-    cmd="$nonopt"
-    test -z "$cmd" && \
-      func_fatal_help "you must specify a COMMAND"
-
-    # Handle -dlopen flags immediately.
-    for file in $opt_dlopen; do
-      test -f "$file" \
-	|| func_fatal_help "\`$file' is not a file"
-
-      dir=
-      case $file in
-      *.la)
-	func_resolve_sysroot "$file"
-	file=$func_resolve_sysroot_result
-
-	# Check to see that this really is a libtool archive.
-	func_lalib_unsafe_p "$file" \
-	  || func_fatal_help "\`$lib' is not a valid libtool archive"
-
-	# Read the libtool library.
-	dlname=
-	library_names=
-	func_source "$file"
-
-	# Skip this library if it cannot be dlopened.
-	if test -z "$dlname"; then
-	  # Warn if it was a shared library.
-	  test -n "$library_names" && \
-	    func_warning "\`$file' was not linked with \`-export-dynamic'"
-	  continue
-	fi
-
-	func_dirname "$file" "" "."
-	dir="$func_dirname_result"
-
-	if test -f "$dir/$objdir/$dlname"; then
-	  func_append dir "/$objdir"
-	else
-	  if test ! -f "$dir/$dlname"; then
-	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"
-	  fi
-	fi
-	;;
-
-      *.lo)
-	# Just add the directory containing the .lo file.
-	func_dirname "$file" "" "."
-	dir="$func_dirname_result"
-	;;
-
-      *)
-	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
-	continue
-	;;
-      esac
-
-      # Get the absolute pathname.
-      absdir=`cd "$dir" && pwd`
-      test -n "$absdir" && dir="$absdir"
-
-      # Now add the directory to shlibpath_var.
-      if eval "test -z \"\$$shlibpath_var\""; then
-	eval "$shlibpath_var=\"\$dir\""
-      else
-	eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\""
-      fi
-    done
-
-    # This variable tells wrapper scripts just to set shlibpath_var
-    # rather than running their programs.
-    libtool_execute_magic="$magic"
-
-    # Check if any of the arguments is a wrapper script.
-    args=
-    for file
-    do
-      case $file in
-      -* | *.la | *.lo ) ;;
-      *)
-	# Do a test to see if this is really a libtool program.
-	if func_ltwrapper_script_p "$file"; then
-	  func_source "$file"
-	  # Transform arg to wrapped name.
-	  file="$progdir/$program"
-	elif func_ltwrapper_executable_p "$file"; then
-	  func_ltwrapper_scriptname "$file"
-	  func_source "$func_ltwrapper_scriptname_result"
-	  # Transform arg to wrapped name.
-	  file="$progdir/$program"
-	fi
-	;;
-      esac
-      # Quote arguments (to preserve shell metacharacters).
-      func_append_quoted args "$file"
-    done
-
-    if test "X$opt_dry_run" = Xfalse; then
-      if test -n "$shlibpath_var"; then
-	# Export the shlibpath_var.
-	eval "export $shlibpath_var"
-      fi
-
-      # Restore saved environment variables
-      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
-      do
-	eval "if test \"\${save_$lt_var+set}\" = set; then
-                $lt_var=\$save_$lt_var; export $lt_var
-	      else
-		$lt_unset $lt_var
-	      fi"
-      done
-
-      # Now prepare to actually exec the command.
-      exec_cmd="\$cmd$args"
-    else
-      # Display what would be done.
-      if test -n "$shlibpath_var"; then
-	eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\""
-	echo "export $shlibpath_var"
-      fi
-      $ECHO "$cmd$args"
-      exit $EXIT_SUCCESS
-    fi
-}
-
-test "$opt_mode" = execute && func_mode_execute ${1+"$@"}
-
-
-# func_mode_finish arg...
-func_mode_finish ()
-{
-    $opt_debug
-    libs=
-    libdirs=
-    admincmds=
-
-    for opt in "$nonopt" ${1+"$@"}
-    do
-      if test -d "$opt"; then
-	func_append libdirs " $opt"
-
-      elif test -f "$opt"; then
-	if func_lalib_unsafe_p "$opt"; then
-	  func_append libs " $opt"
-	else
-	  func_warning "\`$opt' is not a valid libtool archive"
-	fi
-
-      else
-	func_fatal_error "invalid argument \`$opt'"
-      fi
-    done
-
-    if test -n "$libs"; then
-      if test -n "$lt_sysroot"; then
-        sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"`
-        sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;"
-      else
-        sysroot_cmd=
-      fi
-
-      # Remove sysroot references
-      if $opt_dry_run; then
-        for lib in $libs; do
-          echo "removing references to $lt_sysroot and \`=' prefixes from $lib"
-        done
-      else
-        tmpdir=`func_mktempdir`
-        for lib in $libs; do
-	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \
-	    > $tmpdir/tmp-la
-	  mv -f $tmpdir/tmp-la $lib
-	done
-        ${RM}r "$tmpdir"
-      fi
-    fi
-
-    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
-      for libdir in $libdirs; do
-	if test -n "$finish_cmds"; then
-	  # Do each command in the finish commands.
-	  func_execute_cmds "$finish_cmds" 'admincmds="$admincmds
-'"$cmd"'"'
-	fi
-	if test -n "$finish_eval"; then
-	  # Do the single finish_eval.
-	  eval cmds=\"$finish_eval\"
-	  $opt_dry_run || eval "$cmds" || func_append admincmds "
-       $cmds"
-	fi
-      done
-    fi
-
-    # Exit here if they wanted silent mode.
-    $opt_silent && exit $EXIT_SUCCESS
-
-    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
-      echo "----------------------------------------------------------------------"
-      echo "Libraries have been installed in:"
-      for libdir in $libdirs; do
-	$ECHO "   $libdir"
-      done
-      echo
-      echo "If you ever happen to want to link against installed libraries"
-      echo "in a given directory, LIBDIR, you must either use libtool, and"
-      echo "specify the full pathname of the library, or use the \`-LLIBDIR'"
-      echo "flag during linking and do at least one of the following:"
-      if test -n "$shlibpath_var"; then
-	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
-	echo "     during execution"
-      fi
-      if test -n "$runpath_var"; then
-	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
-	echo "     during linking"
-      fi
-      if test -n "$hardcode_libdir_flag_spec"; then
-	libdir=LIBDIR
-	eval flag=\"$hardcode_libdir_flag_spec\"
-
-	$ECHO "   - use the \`$flag' linker flag"
-      fi
-      if test -n "$admincmds"; then
-	$ECHO "   - have your system administrator run these commands:$admincmds"
-      fi
-      if test -f /etc/ld.so.conf; then
-	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf'"
-      fi
-      echo
-
-      echo "See any operating system documentation about shared libraries for"
-      case $host in
-	solaris2.[6789]|solaris2.1[0-9])
-	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
-	  echo "pages."
-	  ;;
-	*)
-	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
-	  ;;
-      esac
-      echo "----------------------------------------------------------------------"
-    fi
-    exit $EXIT_SUCCESS
-}
-
-test "$opt_mode" = finish && func_mode_finish ${1+"$@"}
-
-
-# func_mode_install arg...
-func_mode_install ()
-{
-    $opt_debug
-    # There may be an optional sh(1) argument at the beginning of
-    # install_prog (especially on Windows NT).
-    if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh ||
-       # Allow the use of GNU shtool's install command.
-       case $nonopt in *shtool*) :;; *) false;; esac; then
-      # Aesthetically quote it.
-      func_quote_for_eval "$nonopt"
-      install_prog="$func_quote_for_eval_result "
-      arg=$1
-      shift
-    else
-      install_prog=
-      arg=$nonopt
-    fi
-
-    # The real first argument should be the name of the installation program.
-    # Aesthetically quote it.
-    func_quote_for_eval "$arg"
-    func_append install_prog "$func_quote_for_eval_result"
-    install_shared_prog=$install_prog
-    case " $install_prog " in
-      *[\\\ /]cp\ *) install_cp=: ;;
-      *) install_cp=false ;;
-    esac
-
-    # We need to accept at least all the BSD install flags.
-    dest=
-    files=
-    opts=
-    prev=
-    install_type=
-    isdir=no
-    stripme=
-    no_mode=:
-    for arg
-    do
-      arg2=
-      if test -n "$dest"; then
-	func_append files " $dest"
-	dest=$arg
-	continue
-      fi
-
-      case $arg in
-      -d) isdir=yes ;;
-      -f)
-	if $install_cp; then :; else
-	  prev=$arg
-	fi
-	;;
-      -g | -m | -o)
-	prev=$arg
-	;;
-      -s)
-	stripme=" -s"
-	continue
-	;;
-      -*)
-	;;
-      *)
-	# If the previous option needed an argument, then skip it.
-	if test -n "$prev"; then
-	  if test "x$prev" = x-m && test -n "$install_override_mode"; then
-	    arg2=$install_override_mode
-	    no_mode=false
-	  fi
-	  prev=
-	else
-	  dest=$arg
-	  continue
-	fi
-	;;
-      esac
-
-      # Aesthetically quote the argument.
-      func_quote_for_eval "$arg"
-      func_append install_prog " $func_quote_for_eval_result"
-      if test -n "$arg2"; then
-	func_quote_for_eval "$arg2"
-      fi
-      func_append install_shared_prog " $func_quote_for_eval_result"
-    done
-
-    test -z "$install_prog" && \
-      func_fatal_help "you must specify an install program"
-
-    test -n "$prev" && \
-      func_fatal_help "the \`$prev' option requires an argument"
-
-    if test -n "$install_override_mode" && $no_mode; then
-      if $install_cp; then :; else
-	func_quote_for_eval "$install_override_mode"
-	func_append install_shared_prog " -m $func_quote_for_eval_result"
-      fi
-    fi
-
-    if test -z "$files"; then
-      if test -z "$dest"; then
-	func_fatal_help "no file or destination specified"
-      else
-	func_fatal_help "you must specify a destination"
-      fi
-    fi
-
-    # Strip any trailing slash from the destination.
-    func_stripname '' '/' "$dest"
-    dest=$func_stripname_result
-
-    # Check to see that the destination is a directory.
-    test -d "$dest" && isdir=yes
-    if test "$isdir" = yes; then
-      destdir="$dest"
-      destname=
-    else
-      func_dirname_and_basename "$dest" "" "."
-      destdir="$func_dirname_result"
-      destname="$func_basename_result"
-
-      # Not a directory, so check to see that there is only one file specified.
-      set dummy $files; shift
-      test "$#" -gt 1 && \
-	func_fatal_help "\`$dest' is not a directory"
-    fi
-    case $destdir in
-    [\\/]* | [A-Za-z]:[\\/]*) ;;
-    *)
-      for file in $files; do
-	case $file in
-	*.lo) ;;
-	*)
-	  func_fatal_help "\`$destdir' must be an absolute directory name"
-	  ;;
-	esac
-      done
-      ;;
-    esac
-
-    # This variable tells wrapper scripts just to set variables rather
-    # than running their programs.
-    libtool_install_magic="$magic"
-
-    staticlibs=
-    future_libdirs=
-    current_libdirs=
-    for file in $files; do
-
-      # Do each installation.
-      case $file in
-      *.$libext)
-	# Do the static libraries later.
-	func_append staticlibs " $file"
-	;;
-
-      *.la)
-	func_resolve_sysroot "$file"
-	file=$func_resolve_sysroot_result
-
-	# Check to see that this really is a libtool archive.
-	func_lalib_unsafe_p "$file" \
-	  || func_fatal_help "\`$file' is not a valid libtool archive"
-
-	library_names=
-	old_library=
-	relink_command=
-	func_source "$file"
-
-	# Add the libdir to current_libdirs if it is the destination.
-	if test "X$destdir" = "X$libdir"; then
-	  case "$current_libdirs " in
-	  *" $libdir "*) ;;
-	  *) func_append current_libdirs " $libdir" ;;
-	  esac
-	else
-	  # Note the libdir as a future libdir.
-	  case "$future_libdirs " in
-	  *" $libdir "*) ;;
-	  *) func_append future_libdirs " $libdir" ;;
-	  esac
-	fi
-
-	func_dirname "$file" "/" ""
-	dir="$func_dirname_result"
-	func_append dir "$objdir"
-
-	if test -n "$relink_command"; then
-	  # Determine the prefix the user has applied to our future dir.
-	  inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
-
-	  # Don't allow the user to place us outside of our expected
-	  # location b/c this prevents finding dependent libraries that
-	  # are installed to the same prefix.
-	  # At present, this check doesn't affect windows .dll's that
-	  # are installed into $libdir/../bin (currently, that works fine)
-	  # but it's something to keep an eye on.
-	  test "$inst_prefix_dir" = "$destdir" && \
-	    func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir"
-
-	  if test -n "$inst_prefix_dir"; then
-	    # Stick the inst_prefix_dir data into the link command.
-	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"`
-	  else
-	    relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"`
-	  fi
-
-	  func_warning "relinking \`$file'"
-	  func_show_eval "$relink_command" \
-	    'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"'
-	fi
-
-	# See the names of the shared library.
-	set dummy $library_names; shift
-	if test -n "$1"; then
-	  realname="$1"
-	  shift
-
-	  srcname="$realname"
-	  test -n "$relink_command" && srcname="$realname"T
-
-	  # Install the shared library and build the symlinks.
-	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
-	      'exit $?'
-	  tstripme="$stripme"
-	  case $host_os in
-	  cygwin* | mingw* | pw32* | cegcc*)
-	    case $realname in
-	    *.dll.a)
-	      tstripme=""
-	      ;;
-	    esac
-	    ;;
-	  esac
-	  if test -n "$tstripme" && test -n "$striplib"; then
-	    func_show_eval "$striplib $destdir/$realname" 'exit $?'
-	  fi
-
-	  if test "$#" -gt 0; then
-	    # Delete the old symlinks, and create new ones.
-	    # Try `ln -sf' first, because the `ln' binary might depend on
-	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
-	    # so we also need to try rm && ln -s.
-	    for linkname
-	    do
-	      test "$linkname" != "$realname" \
-		&& func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })"
-	    done
-	  fi
-
-	  # Do each command in the postinstall commands.
-	  lib="$destdir/$realname"
-	  func_execute_cmds "$postinstall_cmds" 'exit $?'
-	fi
-
-	# Install the pseudo-library for information purposes.
-	func_basename "$file"
-	name="$func_basename_result"
-	instname="$dir/$name"i
-	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'
-
-	# Maybe install the static library, too.
-	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
-	;;
-
-      *.lo)
-	# Install (i.e. copy) a libtool object.
-
-	# Figure out destination file name, if it wasn't already specified.
-	if test -n "$destname"; then
-	  destfile="$destdir/$destname"
-	else
-	  func_basename "$file"
-	  destfile="$func_basename_result"
-	  destfile="$destdir/$destfile"
-	fi
-
-	# Deduce the name of the destination old-style object file.
-	case $destfile in
-	*.lo)
-	  func_lo2o "$destfile"
-	  staticdest=$func_lo2o_result
-	  ;;
-	*.$objext)
-	  staticdest="$destfile"
-	  destfile=
-	  ;;
-	*)
-	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
-	  ;;
-	esac
-
-	# Install the libtool object if requested.
-	test -n "$destfile" && \
-	  func_show_eval "$install_prog $file $destfile" 'exit $?'
-
-	# Install the old object if enabled.
-	if test "$build_old_libs" = yes; then
-	  # Deduce the name of the old-style object file.
-	  func_lo2o "$file"
-	  staticobj=$func_lo2o_result
-	  func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?'
-	fi
-	exit $EXIT_SUCCESS
-	;;
-
-      *)
-	# Figure out destination file name, if it wasn't already specified.
-	if test -n "$destname"; then
-	  destfile="$destdir/$destname"
-	else
-	  func_basename "$file"
-	  destfile="$func_basename_result"
-	  destfile="$destdir/$destfile"
-	fi
-
-	# If the file is missing, and there is a .exe on the end, strip it
-	# because it is most likely a libtool script we actually want to
-	# install
-	stripped_ext=""
-	case $file in
-	  *.exe)
-	    if test ! -f "$file"; then
-	      func_stripname '' '.exe' "$file"
-	      file=$func_stripname_result
-	      stripped_ext=".exe"
-	    fi
-	    ;;
-	esac
-
-	# Do a test to see if this is really a libtool program.
-	case $host in
-	*cygwin* | *mingw*)
-	    if func_ltwrapper_executable_p "$file"; then
-	      func_ltwrapper_scriptname "$file"
-	      wrapper=$func_ltwrapper_scriptname_result
-	    else
-	      func_stripname '' '.exe' "$file"
-	      wrapper=$func_stripname_result
-	    fi
-	    ;;
-	*)
-	    wrapper=$file
-	    ;;
-	esac
-	if func_ltwrapper_script_p "$wrapper"; then
-	  notinst_deplibs=
-	  relink_command=
-
-	  func_source "$wrapper"
-
-	  # Check the variables that should have been set.
-	  test -z "$generated_by_libtool_version" && \
-	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"
-
-	  finalize=yes
-	  for lib in $notinst_deplibs; do
-	    # Check to see that each library is installed.
-	    libdir=
-	    if test -f "$lib"; then
-	      func_source "$lib"
-	    fi
-	    libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test
-	    if test -n "$libdir" && test ! -f "$libfile"; then
-	      func_warning "\`$lib' has not been installed in \`$libdir'"
-	      finalize=no
-	    fi
-	  done
-
-	  relink_command=
-	  func_source "$wrapper"
-
-	  outputname=
-	  if test "$fast_install" = no && test -n "$relink_command"; then
-	    $opt_dry_run || {
-	      if test "$finalize" = yes; then
-	        tmpdir=`func_mktempdir`
-		func_basename "$file$stripped_ext"
-		file="$func_basename_result"
-	        outputname="$tmpdir/$file"
-	        # Replace the output file specification.
-	        relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'`
-
-	        $opt_silent || {
-	          func_quote_for_expand "$relink_command"
-		  eval "func_echo $func_quote_for_expand_result"
-	        }
-	        if eval "$relink_command"; then :
-	          else
-		  func_error "error: relink \`$file' with the above command before installing it"
-		  $opt_dry_run || ${RM}r "$tmpdir"
-		  continue
-	        fi
-	        file="$outputname"
-	      else
-	        func_warning "cannot relink \`$file'"
-	      fi
-	    }
-	  else
-	    # Install the binary that we compiled earlier.
-	    file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
-	  fi
-	fi
-
-	# remove .exe since cygwin /usr/bin/install will append another
-	# one anyway
-	case $install_prog,$host in
-	*/usr/bin/install*,*cygwin*)
-	  case $file:$destfile in
-	  *.exe:*.exe)
-	    # this is ok
-	    ;;
-	  *.exe:*)
-	    destfile=$destfile.exe
-	    ;;
-	  *:*.exe)
-	    func_stripname '' '.exe' "$destfile"
-	    destfile=$func_stripname_result
-	    ;;
-	  esac
-	  ;;
-	esac
-	func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?'
-	$opt_dry_run || if test -n "$outputname"; then
-	  ${RM}r "$tmpdir"
-	fi
-	;;
-      esac
-    done
-
-    for file in $staticlibs; do
-      func_basename "$file"
-      name="$func_basename_result"
-
-      # Set up the ranlib parameters.
-      oldlib="$destdir/$name"
-      func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
-      tool_oldlib=$func_to_tool_file_result
-
-      func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
-
-      if test -n "$stripme" && test -n "$old_striplib"; then
-	func_show_eval "$old_striplib $tool_oldlib" 'exit $?'
-      fi
-
-      # Do each command in the postinstall commands.
-      func_execute_cmds "$old_postinstall_cmds" 'exit $?'
-    done
-
-    test -n "$future_libdirs" && \
-      func_warning "remember to run \`$progname --finish$future_libdirs'"
-
-    if test -n "$current_libdirs"; then
-      # Maybe just do a dry run.
-      $opt_dry_run && current_libdirs=" -n$current_libdirs"
-      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'
-    else
-      exit $EXIT_SUCCESS
-    fi
-}
-
-test "$opt_mode" = install && func_mode_install ${1+"$@"}
-
-
-# func_generate_dlsyms outputname originator pic_p
-# Extract symbols from dlprefiles and create ${outputname}S.o with
-# a dlpreopen symbol table.
-func_generate_dlsyms ()
-{
-    $opt_debug
-    my_outputname="$1"
-    my_originator="$2"
-    my_pic_p="${3-no}"
-    my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
-    my_dlsyms=
-
-    if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
-      if test -n "$NM" && test -n "$global_symbol_pipe"; then
-	my_dlsyms="${my_outputname}S.c"
-      else
-	func_error "not configured to extract global symbols from dlpreopened files"
-      fi
-    fi
-
-    if test -n "$my_dlsyms"; then
-      case $my_dlsyms in
-      "") ;;
-      *.c)
-	# Discover the nlist of each of the dlfiles.
-	nlist="$output_objdir/${my_outputname}.nm"
-
-	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"
-
-	# Parse the name list into a source file.
-	func_verbose "creating $output_objdir/$my_dlsyms"
-
-	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
-/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */
-/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */
-
-#ifdef __cplusplus
-extern \"C\" {
-#endif
-
-#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))
-#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
-#endif
-
-/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
-   relocations are performed -- see ld's documentation on pseudo-relocs.  */
-# define LT_DLSYM_CONST
-#elif defined(__osf__)
-/* This system does not cope well with relocations in const data.  */
-# define LT_DLSYM_CONST
-#else
-# define LT_DLSYM_CONST const
-#endif
-
-/* External symbol declarations for the compiler. */\
-"
-
-	if test "$dlself" = yes; then
-	  func_verbose "generating symbol list for \`$output'"
-
-	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"
-
-	  # Add our own program objects to the symbol list.
-	  progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
-	  for progfile in $progfiles; do
-	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
-	    func_verbose "extracting global C symbols from \`$func_to_tool_file_result'"
-	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'"
-	  done
-
-	  if test -n "$exclude_expsyms"; then
-	    $opt_dry_run || {
-	      eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
-	      eval '$MV "$nlist"T "$nlist"'
-	    }
-	  fi
-
-	  if test -n "$export_symbols_regex"; then
-	    $opt_dry_run || {
-	      eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
-	      eval '$MV "$nlist"T "$nlist"'
-	    }
-	  fi
-
-	  # Prepare the list of exported symbols
-	  if test -z "$export_symbols"; then
-	    export_symbols="$output_objdir/$outputname.exp"
-	    $opt_dry_run || {
-	      $RM $export_symbols
-	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"'
-	      case $host in
-	      *cygwin* | *mingw* | *cegcc* )
-                eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
-                eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
-	        ;;
-	      esac
-	    }
-	  else
-	    $opt_dry_run || {
-	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
-	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T'
-	      eval '$MV "$nlist"T "$nlist"'
-	      case $host in
-	        *cygwin* | *mingw* | *cegcc* )
-	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
-	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
-	          ;;
-	      esac
-	    }
-	  fi
-	fi
-
-	for dlprefile in $dlprefiles; do
-	  func_verbose "extracting global C symbols from \`$dlprefile'"
-	  func_basename "$dlprefile"
-	  name="$func_basename_result"
-          case $host in
-	    *cygwin* | *mingw* | *cegcc* )
-	      # if an import library, we need to obtain dlname
-	      if func_win32_import_lib_p "$dlprefile"; then
-	        func_tr_sh "$dlprefile"
-	        eval "curr_lafile=\$libfile_$func_tr_sh_result"
-	        dlprefile_dlbasename=""
-	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
-	          # Use subshell, to avoid clobbering current variable values
-	          dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"`
-	          if test -n "$dlprefile_dlname" ; then
-	            func_basename "$dlprefile_dlname"
-	            dlprefile_dlbasename="$func_basename_result"
-	          else
-	            # no lafile. user explicitly requested -dlpreopen <import library>.
-	            $sharedlib_from_linklib_cmd "$dlprefile"
-	            dlprefile_dlbasename=$sharedlib_from_linklib_result
-	          fi
-	        fi
-	        $opt_dry_run || {
-	          if test -n "$dlprefile_dlbasename" ; then
-	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
-	          else
-	            func_warning "Could not compute DLL name from $name"
-	            eval '$ECHO ": $name " >> "$nlist"'
-	          fi
-	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
-	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe |
-	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
-	        }
-	      else # not an import lib
-	        $opt_dry_run || {
-	          eval '$ECHO ": $name " >> "$nlist"'
-	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
-	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
-	        }
-	      fi
-	    ;;
-	    *)
-	      $opt_dry_run || {
-	        eval '$ECHO ": $name " >> "$nlist"'
-	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
-	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'"
-	      }
-	    ;;
-          esac
-	done
-
-	$opt_dry_run || {
-	  # Make sure we have at least an empty file.
-	  test -f "$nlist" || : > "$nlist"
-
-	  if test -n "$exclude_expsyms"; then
-	    $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
-	    $MV "$nlist"T "$nlist"
-	  fi
-
-	  # Try sorting and uniquifying the output.
-	  if $GREP -v "^: " < "$nlist" |
-	      if sort -k 3 </dev/null >/dev/null 2>&1; then
-		sort -k 3
-	      else
-		sort +2
-	      fi |
-	      uniq > "$nlist"S; then
-	    :
-	  else
-	    $GREP -v "^: " < "$nlist" > "$nlist"S
-	  fi
-
-	  if test -f "$nlist"S; then
-	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"'
-	  else
-	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
-	  fi
-
-	  echo >> "$output_objdir/$my_dlsyms" "\
-
-/* The mapping between symbol names and symbols.  */
-typedef struct {
-  const char *name;
-  void *address;
-} lt_dlsymlist;
-extern LT_DLSYM_CONST lt_dlsymlist
-lt_${my_prefix}_LTX_preloaded_symbols[];
-LT_DLSYM_CONST lt_dlsymlist
-lt_${my_prefix}_LTX_preloaded_symbols[] =
-{\
-  { \"$my_originator\", (void *) 0 },"
-
-	  case $need_lib_prefix in
-	  no)
-	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms"
-	    ;;
-	  *)
-	    eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms"
-	    ;;
-	  esac
-	  echo >> "$output_objdir/$my_dlsyms" "\
-  {0, (void *) 0}
-};
-
-/* This works around a problem in FreeBSD linker */
-#ifdef FREEBSD_WORKAROUND
-static const void *lt_preloaded_setup() {
-  return lt_${my_prefix}_LTX_preloaded_symbols;
-}
-#endif
-
-#ifdef __cplusplus
-}
-#endif\
-"
-	} # !$opt_dry_run
-
-	pic_flag_for_symtable=
-	case "$compile_command " in
-	*" -static "*) ;;
-	*)
-	  case $host in
-	  # compiling the symbol table file with pic_flag works around
-	  # a FreeBSD bug that causes programs to crash when -lm is
-	  # linked before any other PIC object.  But we must not use
-	  # pic_flag when linking with -static.  The problem exists in
-	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
-	  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
-	    pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;;
-	  *-*-hpux*)
-	    pic_flag_for_symtable=" $pic_flag"  ;;
-	  *)
-	    if test "X$my_pic_p" != Xno; then
-	      pic_flag_for_symtable=" $pic_flag"
-	    fi
-	    ;;
-	  esac
-	  ;;
-	esac
-	symtab_cflags=
-	for arg in $LTCFLAGS; do
-	  case $arg in
-	  -pie | -fpie | -fPIE) ;;
-	  *) func_append symtab_cflags " $arg" ;;
-	  esac
-	done
-
-	# Now compile the dynamic symbol file.
-	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'
-
-	# Clean up the generated files.
-	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"'
-
-	# Transform the symbol file into the correct name.
-	symfileobj="$output_objdir/${my_outputname}S.$objext"
-	case $host in
-	*cygwin* | *mingw* | *cegcc* )
-	  if test -f "$output_objdir/$my_outputname.def"; then
-	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
-	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"`
-	  else
-	    compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
-	    finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
-	  fi
-	  ;;
-	*)
-	  compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"`
-	  finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"`
-	  ;;
-	esac
-	;;
-      *)
-	func_fatal_error "unknown suffix for \`$my_dlsyms'"
-	;;
-      esac
-    else
-      # We keep going just in case the user didn't refer to
-      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
-      # really was required.
-
-      # Nullify the symbol file.
-      compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
-      finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"`
-    fi
-}
-
-# func_win32_libid arg
-# return the library type of file 'arg'
-#
-# Need a lot of goo to handle *both* DLLs and import libs
-# Has to be a shell function in order to 'eat' the argument
-# that is supplied when $file_magic_command is called.
-# Despite the name, also deal with 64 bit binaries.
-func_win32_libid ()
-{
-  $opt_debug
-  win32_libid_type="unknown"
-  win32_fileres=`file -L $1 2>/dev/null`
-  case $win32_fileres in
-  *ar\ archive\ import\ library*) # definitely import
-    win32_libid_type="x86 archive import"
-    ;;
-  *ar\ archive*) # could be an import, or static
-    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.
-    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
-       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then
-      func_to_tool_file "$1" func_convert_file_msys_to_w32
-      win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" |
-	$SED -n -e '
-	    1,100{
-		/ I /{
-		    s,.*,import,
-		    p
-		    q
-		}
-	    }'`
-      case $win32_nmres in
-      import*)  win32_libid_type="x86 archive import";;
-      *)        win32_libid_type="x86 archive static";;
-      esac
-    fi
-    ;;
-  *DLL*)
-    win32_libid_type="x86 DLL"
-    ;;
-  *executable*) # but shell scripts are "executable" too...
-    case $win32_fileres in
-    *MS\ Windows\ PE\ Intel*)
-      win32_libid_type="x86 DLL"
-      ;;
-    esac
-    ;;
-  esac
-  $ECHO "$win32_libid_type"
-}
-
-# func_cygming_dll_for_implib ARG
-#
-# Platform-specific function to extract the
-# name of the DLL associated with the specified
-# import library ARG.
-# Invoked by eval'ing the libtool variable
-#    $sharedlib_from_linklib_cmd
-# Result is available in the variable
-#    $sharedlib_from_linklib_result
-func_cygming_dll_for_implib ()
-{
-  $opt_debug
-  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"`
-}
-
-# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
-#
-# The is the core of a fallback implementation of a
-# platform-specific function to extract the name of the
-# DLL associated with the specified import library LIBNAME.
-#
-# SECTION_NAME is either .idata$6 or .idata$7, depending
-# on the platform and compiler that created the implib.
-#
-# Echos the name of the DLL associated with the
-# specified import library.
-func_cygming_dll_for_implib_fallback_core ()
-{
-  $opt_debug
-  match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"`
-  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
-    $SED '/^Contents of section '"$match_literal"':/{
-      # Place marker at beginning of archive member dllname section
-      s/.*/====MARK====/
-      p
-      d
-    }
-    # These lines can sometimes be longer than 43 characters, but
-    # are always uninteresting
-    /:[	 ]*file format pe[i]\{,1\}-/d
-    /^In archive [^:]*:/d
-    # Ensure marker is printed
-    /^====MARK====/p
-    # Remove all lines with less than 43 characters
-    /^.\{43\}/!d
-    # From remaining lines, remove first 43 characters
-    s/^.\{43\}//' |
-    $SED -n '
-      # Join marker and all lines until next marker into a single line
-      /^====MARK====/ b para
-      H
-      $ b para
-      b
-      :para
-      x
-      s/\n//g
-      # Remove the marker
-      s/^====MARK====//
-      # Remove trailing dots and whitespace
-      s/[\. \t]*$//
-      # Print
-      /./p' |
-    # we now have a list, one entry per line, of the stringified
-    # contents of the appropriate section of all members of the
-    # archive which possess that section. Heuristic: eliminate
-    # all those which have a first or second character that is
-    # a '.' (that is, objdump's representation of an unprintable
-    # character.) This should work for all archives with less than
-    # 0x302f exports -- but will fail for DLLs whose name actually
-    # begins with a literal '.' or a single character followed by
-    # a '.'.
-    #
-    # Of those that remain, print the first one.
-    $SED -e '/^\./d;/^.\./d;q'
-}
-
-# func_cygming_gnu_implib_p ARG
-# This predicate returns with zero status (TRUE) if
-# ARG is a GNU/binutils-style import library. Returns
-# with nonzero status (FALSE) otherwise.
-func_cygming_gnu_implib_p ()
-{
-  $opt_debug
-  func_to_tool_file "$1" func_convert_file_msys_to_w32
-  func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`
-  test -n "$func_cygming_gnu_implib_tmp"
-}
-
-# func_cygming_ms_implib_p ARG
-# This predicate returns with zero status (TRUE) if
-# ARG is an MS-style import library. Returns
-# with nonzero status (FALSE) otherwise.
-func_cygming_ms_implib_p ()
-{
-  $opt_debug
-  func_to_tool_file "$1" func_convert_file_msys_to_w32
-  func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
-  test -n "$func_cygming_ms_implib_tmp"
-}
-
-# func_cygming_dll_for_implib_fallback ARG
-# Platform-specific function to extract the
-# name of the DLL associated with the specified
-# import library ARG.
-#
-# This fallback implementation is for use when $DLLTOOL
-# does not support the --identify-strict option.
-# Invoked by eval'ing the libtool variable
-#    $sharedlib_from_linklib_cmd
-# Result is available in the variable
-#    $sharedlib_from_linklib_result
-func_cygming_dll_for_implib_fallback ()
-{
-  $opt_debug
-  if func_cygming_gnu_implib_p "$1" ; then
-    # binutils import library
-    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"`
-  elif func_cygming_ms_implib_p "$1" ; then
-    # ms-generated import library
-    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"`
-  else
-    # unknown
-    sharedlib_from_linklib_result=""
-  fi
-}
-
-
-# func_extract_an_archive dir oldlib
-func_extract_an_archive ()
-{
-    $opt_debug
-    f_ex_an_ar_dir="$1"; shift
-    f_ex_an_ar_oldlib="$1"
-    if test "$lock_old_archive_extraction" = yes; then
-      lockfile=$f_ex_an_ar_oldlib.lock
-      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
-	func_echo "Waiting for $lockfile to be removed"
-	sleep 2
-      done
-    fi
-    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \
-		   'stat=$?; rm -f "$lockfile"; exit $stat'
-    if test "$lock_old_archive_extraction" = yes; then
-      $opt_dry_run || rm -f "$lockfile"
-    fi
-    if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
-     :
-    else
-      func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib"
-    fi
-}
-
-
-# func_extract_archives gentop oldlib ...
-func_extract_archives ()
-{
-    $opt_debug
-    my_gentop="$1"; shift
-    my_oldlibs=${1+"$@"}
-    my_oldobjs=""
-    my_xlib=""
-    my_xabs=""
-    my_xdir=""
-
-    for my_xlib in $my_oldlibs; do
-      # Extract the objects.
-      case $my_xlib in
-	[\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;;
-	*) my_xabs=`pwd`"/$my_xlib" ;;
-      esac
-      func_basename "$my_xlib"
-      my_xlib="$func_basename_result"
-      my_xlib_u=$my_xlib
-      while :; do
-        case " $extracted_archives " in
-	*" $my_xlib_u "*)
-	  func_arith $extracted_serial + 1
-	  extracted_serial=$func_arith_result
-	  my_xlib_u=lt$extracted_serial-$my_xlib ;;
-	*) break ;;
-	esac
-      done
-      extracted_archives="$extracted_archives $my_xlib_u"
-      my_xdir="$my_gentop/$my_xlib_u"
-
-      func_mkdir_p "$my_xdir"
-
-      case $host in
-      *-darwin*)
-	func_verbose "Extracting $my_xabs"
-	# Do not bother doing anything if just a dry run
-	$opt_dry_run || {
-	  darwin_orig_dir=`pwd`
-	  cd $my_xdir || exit $?
-	  darwin_archive=$my_xabs
-	  darwin_curdir=`pwd`
-	  darwin_base_archive=`basename "$darwin_archive"`
-	  darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true`
-	  if test -n "$darwin_arches"; then
-	    darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
-	    darwin_arch=
-	    func_verbose "$darwin_base_archive has multiple architectures $darwin_arches"
-	    for darwin_arch in  $darwin_arches ; do
-	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
-	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
-	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
-	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
-	      cd "$darwin_curdir"
-	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}"
-	    done # $darwin_arches
-            ## Okay now we've a bunch of thin objects, gotta fatten them up :)
-	    darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u`
-	    darwin_file=
-	    darwin_files=
-	    for darwin_file in $darwin_filelist; do
-	      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`
-	      $LIPO -create -output "$darwin_file" $darwin_files
-	    done # $darwin_filelist
-	    $RM -rf unfat-$$
-	    cd "$darwin_orig_dir"
-	  else
-	    cd $darwin_orig_dir
-	    func_extract_an_archive "$my_xdir" "$my_xabs"
-	  fi # $darwin_arches
-	} # !$opt_dry_run
-	;;
-      *)
-        func_extract_an_archive "$my_xdir" "$my_xabs"
-	;;
-      esac
-      my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP`
-    done
-
-    func_extract_archives_result="$my_oldobjs"
-}
-
-
-# func_emit_wrapper [arg=no]
-#
-# Emit a libtool wrapper script on stdout.
-# Don't directly open a file because we may want to
-# incorporate the script contents within a cygwin/mingw
-# wrapper executable.  Must ONLY be called from within
-# func_mode_link because it depends on a number of variables
-# set therein.
-#
-# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
-# variable will take.  If 'yes', then the emitted script
-# will assume that the directory in which it is stored is
-# the $objdir directory.  This is a cygwin/mingw-specific
-# behavior.
-func_emit_wrapper ()
-{
-	func_emit_wrapper_arg1=${1-no}
-
-	$ECHO "\
-#! $SHELL
-
-# $output - temporary wrapper script for $objdir/$outputname
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
-#
-# The $output program cannot be directly executed until all the libtool
-# libraries that it depends on are installed.
-#
-# This wrapper script should never be moved out of the build directory.
-# If it is, it will not operate correctly.
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-sed_quote_subst='$sed_quote_subst'
-
-# Be Bourne compatible
-if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '\${1+\"\$@\"}'='\"\$@\"'
-  setopt NO_GLOB_SUBST
-else
-  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
-fi
-BIN_SH=xpg4; export BIN_SH # for Tru64
-DUALCASE=1; export DUALCASE # for MKS sh
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-relink_command=\"$relink_command\"
-
-# This environment variable determines our operation mode.
-if test \"\$libtool_install_magic\" = \"$magic\"; then
-  # install mode needs the following variables:
-  generated_by_libtool_version='$macro_version'
-  notinst_deplibs='$notinst_deplibs'
-else
-  # When we are sourced in execute mode, \$file and \$ECHO are already set.
-  if test \"\$libtool_execute_magic\" != \"$magic\"; then
-    file=\"\$0\""
-
-    qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
-    $ECHO "\
-
-# A function that is used when there is no print builtin or printf.
-func_fallback_echo ()
-{
-  eval 'cat <<_LTECHO_EOF
-\$1
-_LTECHO_EOF'
-}
-    ECHO=\"$qECHO\"
-  fi
-
-# Very basic option parsing. These options are (a) specific to
-# the libtool wrapper, (b) are identical between the wrapper
-# /script/ and the wrapper /executable/ which is used only on
-# windows platforms, and (c) all begin with the string "--lt-"
-# (application programs are unlikely to have options which match
-# this pattern).
-#
-# There are only two supported options: --lt-debug and
-# --lt-dump-script. There is, deliberately, no --lt-help.
-#
-# The first argument to this parsing function should be the
-# script's $0 value, followed by "$@".
-lt_option_debug=
-func_parse_lt_options ()
-{
-  lt_script_arg0=\$0
-  shift
-  for lt_opt
-  do
-    case \"\$lt_opt\" in
-    --lt-debug) lt_option_debug=1 ;;
-    --lt-dump-script)
-        lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\`
-        test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=.
-        lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\`
-        cat \"\$lt_dump_D/\$lt_dump_F\"
-        exit 0
-      ;;
-    --lt-*)
-        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
-        exit 1
-      ;;
-    esac
-  done
-
-  # Print the debug banner immediately:
-  if test -n \"\$lt_option_debug\"; then
-    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2
-  fi
-}
-
-# Used when --lt-debug. Prints its arguments to stdout
-# (redirection is the responsibility of the caller)
-func_lt_dump_args ()
-{
-  lt_dump_args_N=1;
-  for lt_arg
-  do
-    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\"
-    lt_dump_args_N=\`expr \$lt_dump_args_N + 1\`
-  done
-}
-
-# Core function for launching the target application
-func_exec_program_core ()
-{
-"
-  case $host in
-  # Backslashes separate directories on plain windows
-  *-*-mingw | *-*-os2* | *-cegcc*)
-    $ECHO "\
-      if test -n \"\$lt_option_debug\"; then
-        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2
-        func_lt_dump_args \${1+\"\$@\"} 1>&2
-      fi
-      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
-"
-    ;;
-
-  *)
-    $ECHO "\
-      if test -n \"\$lt_option_debug\"; then
-        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2
-        func_lt_dump_args \${1+\"\$@\"} 1>&2
-      fi
-      exec \"\$progdir/\$program\" \${1+\"\$@\"}
-"
-    ;;
-  esac
-  $ECHO "\
-      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
-      exit 1
-}
-
-# A function to encapsulate launching the target application
-# Strips options in the --lt-* namespace from \$@ and
-# launches target application with the remaining arguments.
-func_exec_program ()
-{
-  case \" \$* \" in
-  *\\ --lt-*)
-    for lt_wr_arg
-    do
-      case \$lt_wr_arg in
-      --lt-*) ;;
-      *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
-      esac
-      shift
-    done ;;
-  esac
-  func_exec_program_core \${1+\"\$@\"}
-}
-
-  # Parse options
-  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
-
-  # Find the directory that this script lives in.
-  thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
-  test \"x\$thisdir\" = \"x\$file\" && thisdir=.
-
-  # Follow symbolic links until we get to the real thisdir.
-  file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
-  while test -n \"\$file\"; do
-    destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
-
-    # If there was a directory component, then change thisdir.
-    if test \"x\$destdir\" != \"x\$file\"; then
-      case \"\$destdir\" in
-      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;;
-      *) thisdir=\"\$thisdir/\$destdir\" ;;
-      esac
-    fi
-
-    file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
-    file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
-  done
-
-  # Usually 'no', except on cygwin/mingw when embedded into
-  # the cwrapper.
-  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1
-  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then
-    # special case for '.'
-    if test \"\$thisdir\" = \".\"; then
-      thisdir=\`pwd\`
-    fi
-    # remove .libs from thisdir
-    case \"\$thisdir\" in
-    *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;;
-    $objdir )   thisdir=. ;;
-    esac
-  fi
-
-  # Try to get the absolute directory name.
-  absdir=\`cd \"\$thisdir\" && pwd\`
-  test -n \"\$absdir\" && thisdir=\"\$absdir\"
-"
-
-	if test "$fast_install" = yes; then
-	  $ECHO "\
-  program=lt-'$outputname'$exeext
-  progdir=\"\$thisdir/$objdir\"
-
-  if test ! -f \"\$progdir/\$program\" ||
-     { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\
-       test \"X\$file\" != \"X\$progdir/\$program\"; }; then
-
-    file=\"\$\$-\$program\"
-
-    if test ! -d \"\$progdir\"; then
-      $MKDIR \"\$progdir\"
-    else
-      $RM \"\$progdir/\$file\"
-    fi"
-
-	  $ECHO "\
-
-    # relink executable if necessary
-    if test -n \"\$relink_command\"; then
-      if relink_command_output=\`eval \$relink_command 2>&1\`; then :
-      else
-	$ECHO \"\$relink_command_output\" >&2
-	$RM \"\$progdir/\$file\"
-	exit 1
-      fi
-    fi
-
-    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
-    { $RM \"\$progdir/\$program\";
-      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
-    $RM \"\$progdir/\$file\"
-  fi"
-	else
-	  $ECHO "\
-  program='$outputname'
-  progdir=\"\$thisdir/$objdir\"
-"
-	fi
-
-	$ECHO "\
-
-  if test -f \"\$progdir/\$program\"; then"
-
-	# fixup the dll searchpath if we need to.
-	#
-	# Fix the DLL searchpath if we need to.  Do this before prepending
-	# to shlibpath, because on Windows, both are PATH and uninstalled
-	# libraries must come first.
-	if test -n "$dllsearchpath"; then
-	  $ECHO "\
-    # Add the dll search path components to the executable PATH
-    PATH=$dllsearchpath:\$PATH
-"
-	fi
-
-	# Export our shlibpath_var if we have one.
-	if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
-	  $ECHO "\
-    # Add our own library path to $shlibpath_var
-    $shlibpath_var=\"$temp_rpath\$$shlibpath_var\"
-
-    # Some systems cannot cope with colon-terminated $shlibpath_var
-    # The second colon is a workaround for a bug in BeOS R4 sed
-    $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
-
-    export $shlibpath_var
-"
-	fi
-
-	$ECHO "\
-    if test \"\$libtool_execute_magic\" != \"$magic\"; then
-      # Run the actual program with our arguments.
-      func_exec_program \${1+\"\$@\"}
-    fi
-  else
-    # The program doesn't exist.
-    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
-    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
-    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
-    exit 1
-  fi
-fi\
-"
-}
-
-
-# func_emit_cwrapperexe_src
-# emit the source code for a wrapper executable on stdout
-# Must ONLY be called from within func_mode_link because
-# it depends on a number of variable set therein.
-func_emit_cwrapperexe_src ()
-{
-	cat <<EOF
-
-/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
-   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
-
-   The $output program cannot be directly executed until all the libtool
-   libraries that it depends on are installed.
-
-   This wrapper executable should never be moved out of the build directory.
-   If it is, it will not operate correctly.
-*/
-EOF
-	    cat <<"EOF"
-#ifdef _MSC_VER
-# define _CRT_SECURE_NO_DEPRECATE 1
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#ifdef _MSC_VER
-# include <direct.h>
-# include <process.h>
-# include <io.h>
-#else
-# include <unistd.h>
-# include <stdint.h>
-# ifdef __CYGWIN__
-#  include <io.h>
-# endif
-#endif
-#include <malloc.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <string.h>
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-
-/* declarations of non-ANSI functions */
-#if defined(__MINGW32__)
-# ifdef __STRICT_ANSI__
-int _putenv (const char *);
-# endif
-#elif defined(__CYGWIN__)
-# ifdef __STRICT_ANSI__
-char *realpath (const char *, char *);
-int putenv (char *);
-int setenv (const char *, const char *, int);
-# endif
-/* #elif defined (other platforms) ... */
-#endif
-
-/* portability defines, excluding path handling macros */
-#if defined(_MSC_VER)
-# define setmode _setmode
-# define stat    _stat
-# define chmod   _chmod
-# define getcwd  _getcwd
-# define putenv  _putenv
-# define S_IXUSR _S_IEXEC
-# ifndef _INTPTR_T_DEFINED
-#  define _INTPTR_T_DEFINED
-#  define intptr_t int
-# endif
-#elif defined(__MINGW32__)
-# define setmode _setmode
-# define stat    _stat
-# define chmod   _chmod
-# define getcwd  _getcwd
-# define putenv  _putenv
-#elif defined(__CYGWIN__)
-# define HAVE_SETENV
-# define FOPEN_WB "wb"
-/* #elif defined (other platforms) ... */
-#endif
-
-#if defined(PATH_MAX)
-# define LT_PATHMAX PATH_MAX
-#elif defined(MAXPATHLEN)
-# define LT_PATHMAX MAXPATHLEN
-#else
-# define LT_PATHMAX 1024
-#endif
-
-#ifndef S_IXOTH
-# define S_IXOTH 0
-#endif
-#ifndef S_IXGRP
-# define S_IXGRP 0
-#endif
-
-/* path handling portability macros */
-#ifndef DIR_SEPARATOR
-# define DIR_SEPARATOR '/'
-# define PATH_SEPARATOR ':'
-#endif
-
-#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
-  defined (__OS2__)
-# define HAVE_DOS_BASED_FILE_SYSTEM
-# define FOPEN_WB "wb"
-# ifndef DIR_SEPARATOR_2
-#  define DIR_SEPARATOR_2 '\\'
-# endif
-# ifndef PATH_SEPARATOR_2
-#  define PATH_SEPARATOR_2 ';'
-# endif
-#endif
-
-#ifndef DIR_SEPARATOR_2
-# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
-#else /* DIR_SEPARATOR_2 */
-# define IS_DIR_SEPARATOR(ch) \
-	(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
-#endif /* DIR_SEPARATOR_2 */
-
-#ifndef PATH_SEPARATOR_2
-# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)
-#else /* PATH_SEPARATOR_2 */
-# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)
-#endif /* PATH_SEPARATOR_2 */
-
-#ifndef FOPEN_WB
-# define FOPEN_WB "w"
-#endif
-#ifndef _O_BINARY
-# define _O_BINARY 0
-#endif
-
-#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
-#define XFREE(stale) do { \
-  if (stale) { free ((void *) stale); stale = 0; } \
-} while (0)
-
-#if defined(LT_DEBUGWRAPPER)
-static int lt_debug = 1;
-#else
-static int lt_debug = 0;
-#endif
-
-const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */
-
-void *xmalloc (size_t num);
-char *xstrdup (const char *string);
-const char *base_name (const char *name);
-char *find_executable (const char *wrapper);
-char *chase_symlinks (const char *pathspec);
-int make_executable (const char *path);
-int check_executable (const char *path);
-char *strendzap (char *str, const char *pat);
-void lt_debugprintf (const char *file, int line, const char *fmt, ...);
-void lt_fatal (const char *file, int line, const char *message, ...);
-static const char *nonnull (const char *s);
-static const char *nonempty (const char *s);
-void lt_setenv (const char *name, const char *value);
-char *lt_extend_str (const char *orig_value, const char *add, int to_end);
-void lt_update_exe_path (const char *name, const char *value);
-void lt_update_lib_path (const char *name, const char *value);
-char **prepare_spawn (char **argv);
-void lt_dump_script (FILE *f);
-EOF
-
-	    cat <<EOF
-volatile const char * MAGIC_EXE = "$magic_exe";
-const char * LIB_PATH_VARNAME = "$shlibpath_var";
-EOF
-
-	    if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then
-              func_to_host_path "$temp_rpath"
-	      cat <<EOF
-const char * LIB_PATH_VALUE   = "$func_to_host_path_result";
-EOF
-	    else
-	      cat <<"EOF"
-const char * LIB_PATH_VALUE   = "";
-EOF
-	    fi
-
-	    if test -n "$dllsearchpath"; then
-              func_to_host_path "$dllsearchpath:"
-	      cat <<EOF
-const char * EXE_PATH_VARNAME = "PATH";
-const char * EXE_PATH_VALUE   = "$func_to_host_path_result";
-EOF
-	    else
-	      cat <<"EOF"
-const char * EXE_PATH_VARNAME = "";
-const char * EXE_PATH_VALUE   = "";
-EOF
-	    fi
-
-	    if test "$fast_install" = yes; then
-	      cat <<EOF
-const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */
-EOF
-	    else
-	      cat <<EOF
-const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */
-EOF
-	    fi
-
-
-	    cat <<"EOF"
-
-#define LTWRAPPER_OPTION_PREFIX         "--lt-"
-
-static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;
-static const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX "dump-script";
-static const char *debug_opt            = LTWRAPPER_OPTION_PREFIX "debug";
-
-int
-main (int argc, char *argv[])
-{
-  char **newargz;
-  int  newargc;
-  char *tmp_pathspec;
-  char *actual_cwrapper_path;
-  char *actual_cwrapper_name;
-  char *target_name;
-  char *lt_argv_zero;
-  intptr_t rval = 127;
-
-  int i;
-
-  program_name = (char *) xstrdup (base_name (argv[0]));
-  newargz = XMALLOC (char *, argc + 1);
-
-  /* very simple arg parsing; don't want to rely on getopt
-   * also, copy all non cwrapper options to newargz, except
-   * argz[0], which is handled differently
-   */
-  newargc=0;
-  for (i = 1; i < argc; i++)
-    {
-      if (strcmp (argv[i], dumpscript_opt) == 0)
-	{
-EOF
-	    case "$host" in
-	      *mingw* | *cygwin* )
-		# make stdout use "unix" line endings
-		echo "          setmode(1,_O_BINARY);"
-		;;
-	      esac
-
-	    cat <<"EOF"
-	  lt_dump_script (stdout);
-	  return 0;
-	}
-      if (strcmp (argv[i], debug_opt) == 0)
-	{
-          lt_debug = 1;
-          continue;
-	}
-      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)
-        {
-          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
-             namespace, but it is not one of the ones we know about and
-             have already dealt with, above (inluding dump-script), then
-             report an error. Otherwise, targets might begin to believe
-             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
-             namespace. The first time any user complains about this, we'll
-             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
-             or a configure.ac-settable value.
-           */
-          lt_fatal (__FILE__, __LINE__,
-		    "unrecognized %s option: '%s'",
-                    ltwrapper_option_prefix, argv[i]);
-        }
-      /* otherwise ... */
-      newargz[++newargc] = xstrdup (argv[i]);
-    }
-  newargz[++newargc] = NULL;
-
-EOF
-	    cat <<EOF
-  /* The GNU banner must be the first non-error debug message */
-  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n");
-EOF
-	    cat <<"EOF"
-  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
-  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name);
-
-  tmp_pathspec = find_executable (argv[0]);
-  if (tmp_pathspec == NULL)
-    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
-  lt_debugprintf (__FILE__, __LINE__,
-                  "(main) found exe (before symlink chase) at: %s\n",
-		  tmp_pathspec);
-
-  actual_cwrapper_path = chase_symlinks (tmp_pathspec);
-  lt_debugprintf (__FILE__, __LINE__,
-                  "(main) found exe (after symlink chase) at: %s\n",
-		  actual_cwrapper_path);
-  XFREE (tmp_pathspec);
-
-  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));
-  strendzap (actual_cwrapper_path, actual_cwrapper_name);
-
-  /* wrapper name transforms */
-  strendzap (actual_cwrapper_name, ".exe");
-  tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1);
-  XFREE (actual_cwrapper_name);
-  actual_cwrapper_name = tmp_pathspec;
-  tmp_pathspec = 0;
-
-  /* target_name transforms -- use actual target program name; might have lt- prefix */
-  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));
-  strendzap (target_name, ".exe");
-  tmp_pathspec = lt_extend_str (target_name, ".exe", 1);
-  XFREE (target_name);
-  target_name = tmp_pathspec;
-  tmp_pathspec = 0;
-
-  lt_debugprintf (__FILE__, __LINE__,
-		  "(main) libtool target name: %s\n",
-		  target_name);
-EOF
-
-	    cat <<EOF
-  newargz[0] =
-    XMALLOC (char, (strlen (actual_cwrapper_path) +
-		    strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1));
-  strcpy (newargz[0], actual_cwrapper_path);
-  strcat (newargz[0], "$objdir");
-  strcat (newargz[0], "/");
-EOF
-
-	    cat <<"EOF"
-  /* stop here, and copy so we don't have to do this twice */
-  tmp_pathspec = xstrdup (newargz[0]);
-
-  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */
-  strcat (newargz[0], actual_cwrapper_name);
-
-  /* DO want the lt- prefix here if it exists, so use target_name */
-  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);
-  XFREE (tmp_pathspec);
-  tmp_pathspec = NULL;
-EOF
-
-	    case $host_os in
-	      mingw*)
-	    cat <<"EOF"
-  {
-    char* p;
-    while ((p = strchr (newargz[0], '\\')) != NULL)
-      {
-	*p = '/';
-      }
-    while ((p = strchr (lt_argv_zero, '\\')) != NULL)
-      {
-	*p = '/';
-      }
-  }
-EOF
-	    ;;
-	    esac
-
-	    cat <<"EOF"
-  XFREE (target_name);
-  XFREE (actual_cwrapper_path);
-  XFREE (actual_cwrapper_name);
-
-  lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
-  lt_setenv ("DUALCASE", "1");  /* for MSK sh */
-  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
-     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)
-     because on Windows, both *_VARNAMEs are PATH but uninstalled
-     libraries must come first. */
-  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
-  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
-
-  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
-		  nonnull (lt_argv_zero));
-  for (i = 0; i < newargc; i++)
-    {
-      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
-		      i, nonnull (newargz[i]));
-    }
-
-EOF
-
-	    case $host_os in
-	      mingw*)
-		cat <<"EOF"
-  /* execv doesn't actually work on mingw as expected on unix */
-  newargz = prepare_spawn (newargz);
-  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
-  if (rval == -1)
-    {
-      /* failed to start process */
-      lt_debugprintf (__FILE__, __LINE__,
-		      "(main) failed to launch target \"%s\": %s\n",
-		      lt_argv_zero, nonnull (strerror (errno)));
-      return 127;
-    }
-  return rval;
-EOF
-		;;
-	      *)
-		cat <<"EOF"
-  execv (lt_argv_zero, newargz);
-  return rval; /* =127, but avoids unused variable warning */
-EOF
-		;;
-	    esac
-
-	    cat <<"EOF"
-}
-
-void *
-xmalloc (size_t num)
-{
-  void *p = (void *) malloc (num);
-  if (!p)
-    lt_fatal (__FILE__, __LINE__, "memory exhausted");
-
-  return p;
-}
-
-char *
-xstrdup (const char *string)
-{
-  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),
-			  string) : NULL;
-}
-
-const char *
-base_name (const char *name)
-{
-  const char *base;
-
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-  /* Skip over the disk name in MSDOS pathnames. */
-  if (isalpha ((unsigned char) name[0]) && name[1] == ':')
-    name += 2;
-#endif
-
-  for (base = name; *name; name++)
-    if (IS_DIR_SEPARATOR (*name))
-      base = name + 1;
-  return base;
-}
-
-int
-check_executable (const char *path)
-{
-  struct stat st;
-
-  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
-                  nonempty (path));
-  if ((!path) || (!*path))
-    return 0;
-
-  if ((stat (path, &st) >= 0)
-      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
-    return 1;
-  else
-    return 0;
-}
-
-int
-make_executable (const char *path)
-{
-  int rval = 0;
-  struct stat st;
-
-  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
-                  nonempty (path));
-  if ((!path) || (!*path))
-    return 0;
-
-  if (stat (path, &st) >= 0)
-    {
-      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);
-    }
-  return rval;
-}
-
-/* Searches for the full path of the wrapper.  Returns
-   newly allocated full path name if found, NULL otherwise
-   Does not chase symlinks, even on platforms that support them.
-*/
-char *
-find_executable (const char *wrapper)
-{
-  int has_slash = 0;
-  const char *p;
-  const char *p_next;
-  /* static buffer for getcwd */
-  char tmp[LT_PATHMAX + 1];
-  int tmp_len;
-  char *concat_name;
-
-  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
-                  nonempty (wrapper));
-
-  if ((wrapper == NULL) || (*wrapper == '\0'))
-    return NULL;
-
-  /* Absolute path? */
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')
-    {
-      concat_name = xstrdup (wrapper);
-      if (check_executable (concat_name))
-	return concat_name;
-      XFREE (concat_name);
-    }
-  else
-    {
-#endif
-      if (IS_DIR_SEPARATOR (wrapper[0]))
-	{
-	  concat_name = xstrdup (wrapper);
-	  if (check_executable (concat_name))
-	    return concat_name;
-	  XFREE (concat_name);
-	}
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-    }
-#endif
-
-  for (p = wrapper; *p; p++)
-    if (*p == '/')
-      {
-	has_slash = 1;
-	break;
-      }
-  if (!has_slash)
-    {
-      /* no slashes; search PATH */
-      const char *path = getenv ("PATH");
-      if (path != NULL)
-	{
-	  for (p = path; *p; p = p_next)
-	    {
-	      const char *q;
-	      size_t p_len;
-	      for (q = p; *q; q++)
-		if (IS_PATH_SEPARATOR (*q))
-		  break;
-	      p_len = q - p;
-	      p_next = (*q == '\0' ? q : q + 1);
-	      if (p_len == 0)
-		{
-		  /* empty path: current directory */
-		  if (getcwd (tmp, LT_PATHMAX) == NULL)
-		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
-                              nonnull (strerror (errno)));
-		  tmp_len = strlen (tmp);
-		  concat_name =
-		    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
-		  memcpy (concat_name, tmp, tmp_len);
-		  concat_name[tmp_len] = '/';
-		  strcpy (concat_name + tmp_len + 1, wrapper);
-		}
-	      else
-		{
-		  concat_name =
-		    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);
-		  memcpy (concat_name, p, p_len);
-		  concat_name[p_len] = '/';
-		  strcpy (concat_name + p_len + 1, wrapper);
-		}
-	      if (check_executable (concat_name))
-		return concat_name;
-	      XFREE (concat_name);
-	    }
-	}
-      /* not found in PATH; assume curdir */
-    }
-  /* Relative path | not found in path: prepend cwd */
-  if (getcwd (tmp, LT_PATHMAX) == NULL)
-    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
-              nonnull (strerror (errno)));
-  tmp_len = strlen (tmp);
-  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
-  memcpy (concat_name, tmp, tmp_len);
-  concat_name[tmp_len] = '/';
-  strcpy (concat_name + tmp_len + 1, wrapper);
-
-  if (check_executable (concat_name))
-    return concat_name;
-  XFREE (concat_name);
-  return NULL;
-}
-
-char *
-chase_symlinks (const char *pathspec)
-{
-#ifndef S_ISLNK
-  return xstrdup (pathspec);
-#else
-  char buf[LT_PATHMAX];
-  struct stat s;
-  char *tmp_pathspec = xstrdup (pathspec);
-  char *p;
-  int has_symlinks = 0;
-  while (strlen (tmp_pathspec) && !has_symlinks)
-    {
-      lt_debugprintf (__FILE__, __LINE__,
-		      "checking path component for symlinks: %s\n",
-		      tmp_pathspec);
-      if (lstat (tmp_pathspec, &s) == 0)
-	{
-	  if (S_ISLNK (s.st_mode) != 0)
-	    {
-	      has_symlinks = 1;
-	      break;
-	    }
-
-	  /* search backwards for last DIR_SEPARATOR */
-	  p = tmp_pathspec + strlen (tmp_pathspec) - 1;
-	  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
-	    p--;
-	  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
-	    {
-	      /* no more DIR_SEPARATORS left */
-	      break;
-	    }
-	  *p = '\0';
-	}
-      else
-	{
-	  lt_fatal (__FILE__, __LINE__,
-		    "error accessing file \"%s\": %s",
-		    tmp_pathspec, nonnull (strerror (errno)));
-	}
-    }
-  XFREE (tmp_pathspec);
-
-  if (!has_symlinks)
-    {
-      return xstrdup (pathspec);
-    }
-
-  tmp_pathspec = realpath (pathspec, buf);
-  if (tmp_pathspec == 0)
-    {
-      lt_fatal (__FILE__, __LINE__,
-		"could not follow symlinks for %s", pathspec);
-    }
-  return xstrdup (tmp_pathspec);
-#endif
-}
-
-char *
-strendzap (char *str, const char *pat)
-{
-  size_t len, patlen;
-
-  assert (str != NULL);
-  assert (pat != NULL);
-
-  len = strlen (str);
-  patlen = strlen (pat);
-
-  if (patlen <= len)
-    {
-      str += len - patlen;
-      if (strcmp (str, pat) == 0)
-	*str = '\0';
-    }
-  return str;
-}
-
-void
-lt_debugprintf (const char *file, int line, const char *fmt, ...)
-{
-  va_list args;
-  if (lt_debug)
-    {
-      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
-      va_start (args, fmt);
-      (void) vfprintf (stderr, fmt, args);
-      va_end (args);
-    }
-}
-
-static void
-lt_error_core (int exit_status, const char *file,
-	       int line, const char *mode,
-	       const char *message, va_list ap)
-{
-  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
-  vfprintf (stderr, message, ap);
-  fprintf (stderr, ".\n");
-
-  if (exit_status >= 0)
-    exit (exit_status);
-}
-
-void
-lt_fatal (const char *file, int line, const char *message, ...)
-{
-  va_list ap;
-  va_start (ap, message);
-  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
-  va_end (ap);
-}
-
-static const char *
-nonnull (const char *s)
-{
-  return s ? s : "(null)";
-}
-
-static const char *
-nonempty (const char *s)
-{
-  return (s && !*s) ? "(empty)" : nonnull (s);
-}
-
-void
-lt_setenv (const char *name, const char *value)
-{
-  lt_debugprintf (__FILE__, __LINE__,
-		  "(lt_setenv) setting '%s' to '%s'\n",
-                  nonnull (name), nonnull (value));
-  {
-#ifdef HAVE_SETENV
-    /* always make a copy, for consistency with !HAVE_SETENV */
-    char *str = xstrdup (value);
-    setenv (name, str, 1);
-#else
-    int len = strlen (name) + 1 + strlen (value) + 1;
-    char *str = XMALLOC (char, len);
-    sprintf (str, "%s=%s", name, value);
-    if (putenv (str) != EXIT_SUCCESS)
-      {
-        XFREE (str);
-      }
-#endif
-  }
-}
-
-char *
-lt_extend_str (const char *orig_value, const char *add, int to_end)
-{
-  char *new_value;
-  if (orig_value && *orig_value)
-    {
-      int orig_value_len = strlen (orig_value);
-      int add_len = strlen (add);
-      new_value = XMALLOC (char, add_len + orig_value_len + 1);
-      if (to_end)
-        {
-          strcpy (new_value, orig_value);
-          strcpy (new_value + orig_value_len, add);
-        }
-      else
-        {
-          strcpy (new_value, add);
-          strcpy (new_value + add_len, orig_value);
-        }
-    }
-  else
-    {
-      new_value = xstrdup (add);
-    }
-  return new_value;
-}
-
-void
-lt_update_exe_path (const char *name, const char *value)
-{
-  lt_debugprintf (__FILE__, __LINE__,
-		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
-                  nonnull (name), nonnull (value));
-
-  if (name && *name && value && *value)
-    {
-      char *new_value = lt_extend_str (getenv (name), value, 0);
-      /* some systems can't cope with a ':'-terminated path #' */
-      int len = strlen (new_value);
-      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))
-        {
-          new_value[len-1] = '\0';
-        }
-      lt_setenv (name, new_value);
-      XFREE (new_value);
-    }
-}
-
-void
-lt_update_lib_path (const char *name, const char *value)
-{
-  lt_debugprintf (__FILE__, __LINE__,
-		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
-                  nonnull (name), nonnull (value));
-
-  if (name && *name && value && *value)
-    {
-      char *new_value = lt_extend_str (getenv (name), value, 0);
-      lt_setenv (name, new_value);
-      XFREE (new_value);
-    }
-}
-
-EOF
-	    case $host_os in
-	      mingw*)
-		cat <<"EOF"
-
-/* Prepares an argument vector before calling spawn().
-   Note that spawn() does not by itself call the command interpreter
-     (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
-      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-         GetVersionEx(&v);
-         v.dwPlatformId == VER_PLATFORM_WIN32_NT;
-      }) ? "cmd.exe" : "command.com").
-   Instead it simply concatenates the arguments, separated by ' ', and calls
-   CreateProcess().  We must quote the arguments since Win32 CreateProcess()
-   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
-   special way:
-   - Space and tab are interpreted as delimiters. They are not treated as
-     delimiters if they are surrounded by double quotes: "...".
-   - Unescaped double quotes are removed from the input. Their only effect is
-     that within double quotes, space and tab are treated like normal
-     characters.
-   - Backslashes not followed by double quotes are not special.
-   - But 2*n+1 backslashes followed by a double quote become
-     n backslashes followed by a double quote (n >= 0):
-       \" -> "
-       \\\" -> \"
-       \\\\\" -> \\"
- */
-#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
-#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
-char **
-prepare_spawn (char **argv)
-{
-  size_t argc;
-  char **new_argv;
-  size_t i;
-
-  /* Count number of arguments.  */
-  for (argc = 0; argv[argc] != NULL; argc++)
-    ;
-
-  /* Allocate new argument vector.  */
-  new_argv = XMALLOC (char *, argc + 1);
-
-  /* Put quoted arguments into the new argument vector.  */
-  for (i = 0; i < argc; i++)
-    {
-      const char *string = argv[i];
-
-      if (string[0] == '\0')
-	new_argv[i] = xstrdup ("\"\"");
-      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
-	{
-	  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
-	  size_t length;
-	  unsigned int backslashes;
-	  const char *s;
-	  char *quoted_string;
-	  char *p;
-
-	  length = 0;
-	  backslashes = 0;
-	  if (quote_around)
-	    length++;
-	  for (s = string; *s != '\0'; s++)
-	    {
-	      char c = *s;
-	      if (c == '"')
-		length += backslashes + 1;
-	      length++;
-	      if (c == '\\')
-		backslashes++;
-	      else
-		backslashes = 0;
-	    }
-	  if (quote_around)
-	    length += backslashes + 1;
-
-	  quoted_string = XMALLOC (char, length + 1);
-
-	  p = quoted_string;
-	  backslashes = 0;
-	  if (quote_around)
-	    *p++ = '"';
-	  for (s = string; *s != '\0'; s++)
-	    {
-	      char c = *s;
-	      if (c == '"')
-		{
-		  unsigned int j;
-		  for (j = backslashes + 1; j > 0; j--)
-		    *p++ = '\\';
-		}
-	      *p++ = c;
-	      if (c == '\\')
-		backslashes++;
-	      else
-		backslashes = 0;
-	    }
-	  if (quote_around)
-	    {
-	      unsigned int j;
-	      for (j = backslashes; j > 0; j--)
-		*p++ = '\\';
-	      *p++ = '"';
-	    }
-	  *p = '\0';
-
-	  new_argv[i] = quoted_string;
-	}
-      else
-	new_argv[i] = (char *) string;
-    }
-  new_argv[argc] = NULL;
-
-  return new_argv;
-}
-EOF
-		;;
-	    esac
-
-            cat <<"EOF"
-void lt_dump_script (FILE* f)
-{
-EOF
-	    func_emit_wrapper yes |
-	      $SED -n -e '
-s/^\(.\{79\}\)\(..*\)/\1\
-\2/
-h
-s/\([\\"]\)/\\\1/g
-s/$/\\n/
-s/\([^\n]*\).*/  fputs ("\1", f);/p
-g
-D'
-            cat <<"EOF"
-}
-EOF
-}
-# end: func_emit_cwrapperexe_src
-
-# func_win32_import_lib_p ARG
-# True if ARG is an import lib, as indicated by $file_magic_cmd
-func_win32_import_lib_p ()
-{
-    $opt_debug
-    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
-    *import*) : ;;
-    *) false ;;
-    esac
-}
-
-# func_mode_link arg...
-func_mode_link ()
-{
-    $opt_debug
-    case $host in
-    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
-      # It is impossible to link a dll without this setting, and
-      # we shouldn't force the makefile maintainer to figure out
-      # which system we are compiling for in order to pass an extra
-      # flag for every libtool invocation.
-      # allow_undefined=no
-
-      # FIXME: Unfortunately, there are problems with the above when trying
-      # to make a dll which has undefined symbols, in which case not
-      # even a static library is built.  For now, we need to specify
-      # -no-undefined on the libtool link line when we can be certain
-      # that all symbols are satisfied, otherwise we get a static library.
-      allow_undefined=yes
-      ;;
-    *)
-      allow_undefined=yes
-      ;;
-    esac
-    libtool_args=$nonopt
-    base_compile="$nonopt $@"
-    compile_command=$nonopt
-    finalize_command=$nonopt
-
-    compile_rpath=
-    finalize_rpath=
-    compile_shlibpath=
-    finalize_shlibpath=
-    convenience=
-    old_convenience=
-    deplibs=
-    old_deplibs=
-    compiler_flags=
-    linker_flags=
-    dllsearchpath=
-    lib_search_path=`pwd`
-    inst_prefix_dir=
-    new_inherited_linker_flags=
-
-    avoid_version=no
-    bindir=
-    dlfiles=
-    dlprefiles=
-    dlself=no
-    export_dynamic=no
-    export_symbols=
-    export_symbols_regex=
-    generated=
-    libobjs=
-    ltlibs=
-    module=no
-    no_install=no
-    objs=
-    non_pic_objects=
-    precious_files_regex=
-    prefer_static_libs=no
-    preload=no
-    prev=
-    prevarg=
-    release=
-    rpath=
-    xrpath=
-    perm_rpath=
-    temp_rpath=
-    thread_safe=no
-    vinfo=
-    vinfo_number=no
-    weak_libs=
-    single_module="${wl}-single_module"
-    func_infer_tag $base_compile
-
-    # We need to know -static, to get the right output filenames.
-    for arg
-    do
-      case $arg in
-      -shared)
-	test "$build_libtool_libs" != yes && \
-	  func_fatal_configuration "can not build a shared library"
-	build_old_libs=no
-	break
-	;;
-      -all-static | -static | -static-libtool-libs)
-	case $arg in
-	-all-static)
-	  if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then
-	    func_warning "complete static linking is impossible in this configuration"
-	  fi
-	  if test -n "$link_static_flag"; then
-	    dlopen_self=$dlopen_self_static
-	  fi
-	  prefer_static_libs=yes
-	  ;;
-	-static)
-	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
-	    dlopen_self=$dlopen_self_static
-	  fi
-	  prefer_static_libs=built
-	  ;;
-	-static-libtool-libs)
-	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
-	    dlopen_self=$dlopen_self_static
-	  fi
-	  prefer_static_libs=yes
-	  ;;
-	esac
-	build_libtool_libs=no
-	build_old_libs=yes
-	break
-	;;
-      esac
-    done
-
-    # See if our shared archives depend on static archives.
-    test -n "$old_archive_from_new_cmds" && build_old_libs=yes
-
-    # Go through the arguments, transforming them on the way.
-    while test "$#" -gt 0; do
-      arg="$1"
-      shift
-      func_quote_for_eval "$arg"
-      qarg=$func_quote_for_eval_unquoted_result
-      func_append libtool_args " $func_quote_for_eval_result"
-
-      # If the previous option needs an argument, assign it.
-      if test -n "$prev"; then
-	case $prev in
-	output)
-	  func_append compile_command " @OUTPUT@"
-	  func_append finalize_command " @OUTPUT@"
-	  ;;
-	esac
-
-	case $prev in
-	bindir)
-	  bindir="$arg"
-	  prev=
-	  continue
-	  ;;
-	dlfiles|dlprefiles)
-	  if test "$preload" = no; then
-	    # Add the symbol object into the linking commands.
-	    func_append compile_command " @SYMFILE@"
-	    func_append finalize_command " @SYMFILE@"
-	    preload=yes
-	  fi
-	  case $arg in
-	  *.la | *.lo) ;;  # We handle these cases below.
-	  force)
-	    if test "$dlself" = no; then
-	      dlself=needless
-	      export_dynamic=yes
-	    fi
-	    prev=
-	    continue
-	    ;;
-	  self)
-	    if test "$prev" = dlprefiles; then
-	      dlself=yes
-	    elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then
-	      dlself=yes
-	    else
-	      dlself=needless
-	      export_dynamic=yes
-	    fi
-	    prev=
-	    continue
-	    ;;
-	  *)
-	    if test "$prev" = dlfiles; then
-	      func_append dlfiles " $arg"
-	    else
-	      func_append dlprefiles " $arg"
-	    fi
-	    prev=
-	    continue
-	    ;;
-	  esac
-	  ;;
-	expsyms)
-	  export_symbols="$arg"
-	  test -f "$arg" \
-	    || func_fatal_error "symbol file \`$arg' does not exist"
-	  prev=
-	  continue
-	  ;;
-	expsyms_regex)
-	  export_symbols_regex="$arg"
-	  prev=
-	  continue
-	  ;;
-	framework)
-	  case $host in
-	    *-*-darwin*)
-	      case "$deplibs " in
-		*" $qarg.ltframework "*) ;;
-		*) func_append deplibs " $qarg.ltframework" # this is fixed later
-		   ;;
-	      esac
-	      ;;
-	  esac
-	  prev=
-	  continue
-	  ;;
-	inst_prefix)
-	  inst_prefix_dir="$arg"
-	  prev=
-	  continue
-	  ;;
-	objectlist)
-	  if test -f "$arg"; then
-	    save_arg=$arg
-	    moreargs=
-	    for fil in `cat "$save_arg"`
-	    do
-#	      func_append moreargs " $fil"
-	      arg=$fil
-	      # A libtool-controlled object.
-
-	      # Check to see that this really is a libtool object.
-	      if func_lalib_unsafe_p "$arg"; then
-		pic_object=
-		non_pic_object=
-
-		# Read the .lo file
-		func_source "$arg"
-
-		if test -z "$pic_object" ||
-		   test -z "$non_pic_object" ||
-		   test "$pic_object" = none &&
-		   test "$non_pic_object" = none; then
-		  func_fatal_error "cannot find name of object for \`$arg'"
-		fi
-
-		# Extract subdirectory from the argument.
-		func_dirname "$arg" "/" ""
-		xdir="$func_dirname_result"
-
-		if test "$pic_object" != none; then
-		  # Prepend the subdirectory the object is found in.
-		  pic_object="$xdir$pic_object"
-
-		  if test "$prev" = dlfiles; then
-		    if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
-		      func_append dlfiles " $pic_object"
-		      prev=
-		      continue
-		    else
-		      # If libtool objects are unsupported, then we need to preload.
-		      prev=dlprefiles
-		    fi
-		  fi
-
-		  # CHECK ME:  I think I busted this.  -Ossama
-		  if test "$prev" = dlprefiles; then
-		    # Preload the old-style object.
-		    func_append dlprefiles " $pic_object"
-		    prev=
-		  fi
-
-		  # A PIC object.
-		  func_append libobjs " $pic_object"
-		  arg="$pic_object"
-		fi
-
-		# Non-PIC object.
-		if test "$non_pic_object" != none; then
-		  # Prepend the subdirectory the object is found in.
-		  non_pic_object="$xdir$non_pic_object"
-
-		  # A standard non-PIC object
-		  func_append non_pic_objects " $non_pic_object"
-		  if test -z "$pic_object" || test "$pic_object" = none ; then
-		    arg="$non_pic_object"
-		  fi
-		else
-		  # If the PIC object exists, use it instead.
-		  # $xdir was prepended to $pic_object above.
-		  non_pic_object="$pic_object"
-		  func_append non_pic_objects " $non_pic_object"
-		fi
-	      else
-		# Only an error if not doing a dry-run.
-		if $opt_dry_run; then
-		  # Extract subdirectory from the argument.
-		  func_dirname "$arg" "/" ""
-		  xdir="$func_dirname_result"
-
-		  func_lo2o "$arg"
-		  pic_object=$xdir$objdir/$func_lo2o_result
-		  non_pic_object=$xdir$func_lo2o_result
-		  func_append libobjs " $pic_object"
-		  func_append non_pic_objects " $non_pic_object"
-	        else
-		  func_fatal_error "\`$arg' is not a valid libtool object"
-		fi
-	      fi
-	    done
-	  else
-	    func_fatal_error "link input file \`$arg' does not exist"
-	  fi
-	  arg=$save_arg
-	  prev=
-	  continue
-	  ;;
-	precious_regex)
-	  precious_files_regex="$arg"
-	  prev=
-	  continue
-	  ;;
-	release)
-	  release="-$arg"
-	  prev=
-	  continue
-	  ;;
-	rpath | xrpath)
-	  # We need an absolute path.
-	  case $arg in
-	  [\\/]* | [A-Za-z]:[\\/]*) ;;
-	  *)
-	    func_fatal_error "only absolute run-paths are allowed"
-	    ;;
-	  esac
-	  if test "$prev" = rpath; then
-	    case "$rpath " in
-	    *" $arg "*) ;;
-	    *) func_append rpath " $arg" ;;
-	    esac
-	  else
-	    case "$xrpath " in
-	    *" $arg "*) ;;
-	    *) func_append xrpath " $arg" ;;
-	    esac
-	  fi
-	  prev=
-	  continue
-	  ;;
-	shrext)
-	  shrext_cmds="$arg"
-	  prev=
-	  continue
-	  ;;
-	weak)
-	  func_append weak_libs " $arg"
-	  prev=
-	  continue
-	  ;;
-	xcclinker)
-	  func_append linker_flags " $qarg"
-	  func_append compiler_flags " $qarg"
-	  prev=
-	  func_append compile_command " $qarg"
-	  func_append finalize_command " $qarg"
-	  continue
-	  ;;
-	xcompiler)
-	  func_append compiler_flags " $qarg"
-	  prev=
-	  func_append compile_command " $qarg"
-	  func_append finalize_command " $qarg"
-	  continue
-	  ;;
-	xlinker)
-	  func_append linker_flags " $qarg"
-	  func_append compiler_flags " $wl$qarg"
-	  prev=
-	  func_append compile_command " $wl$qarg"
-	  func_append finalize_command " $wl$qarg"
-	  continue
-	  ;;
-	*)
-	  eval "$prev=\"\$arg\""
-	  prev=
-	  continue
-	  ;;
-	esac
-      fi # test -n "$prev"
-
-      prevarg="$arg"
-
-      case $arg in
-      -all-static)
-	if test -n "$link_static_flag"; then
-	  # See comment for -static flag below, for more details.
-	  func_append compile_command " $link_static_flag"
-	  func_append finalize_command " $link_static_flag"
-	fi
-	continue
-	;;
-
-      -allow-undefined)
-	# FIXME: remove this flag sometime in the future.
-	func_fatal_error "\`-allow-undefined' must not be used because it is the default"
-	;;
-
-      -avoid-version)
-	avoid_version=yes
-	continue
-	;;
-
-      -bindir)
-	prev=bindir
-	continue
-	;;
-
-      -dlopen)
-	prev=dlfiles
-	continue
-	;;
-
-      -dlpreopen)
-	prev=dlprefiles
-	continue
-	;;
-
-      -export-dynamic)
-	export_dynamic=yes
-	continue
-	;;
-
-      -export-symbols | -export-symbols-regex)
-	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
-	  func_fatal_error "more than one -exported-symbols argument is not allowed"
-	fi
-	if test "X$arg" = "X-export-symbols"; then
-	  prev=expsyms
-	else
-	  prev=expsyms_regex
-	fi
-	continue
-	;;
-
-      -framework)
-	prev=framework
-	continue
-	;;
-
-      -inst-prefix-dir)
-	prev=inst_prefix
-	continue
-	;;
-
-      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*
-      # so, if we see these flags be careful not to treat them like -L
-      -L[A-Z][A-Z]*:*)
-	case $with_gcc/$host in
-	no/*-*-irix* | /*-*-irix*)
-	  func_append compile_command " $arg"
-	  func_append finalize_command " $arg"
-	  ;;
-	esac
-	continue
-	;;
-
-      -L*)
-	func_stripname "-L" '' "$arg"
-	if test -z "$func_stripname_result"; then
-	  if test "$#" -gt 0; then
-	    func_fatal_error "require no space between \`-L' and \`$1'"
-	  else
-	    func_fatal_error "need path for \`-L' option"
-	  fi
-	fi
-	func_resolve_sysroot "$func_stripname_result"
-	dir=$func_resolve_sysroot_result
-	# We need an absolute path.
-	case $dir in
-	[\\/]* | [A-Za-z]:[\\/]*) ;;
-	*)
-	  absdir=`cd "$dir" && pwd`
-	  test -z "$absdir" && \
-	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
-	  dir="$absdir"
-	  ;;
-	esac
-	case "$deplibs " in
-	*" -L$dir "* | *" $arg "*)
-	  # Will only happen for absolute or sysroot arguments
-	  ;;
-	*)
-	  # Preserve sysroot, but never include relative directories
-	  case $dir in
-	    [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;;
-	    *) func_append deplibs " -L$dir" ;;
-	  esac
-	  func_append lib_search_path " $dir"
-	  ;;
-	esac
-	case $host in
-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
-	  testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
-	  case :$dllsearchpath: in
-	  *":$dir:"*) ;;
-	  ::) dllsearchpath=$dir;;
-	  *) func_append dllsearchpath ":$dir";;
-	  esac
-	  case :$dllsearchpath: in
-	  *":$testbindir:"*) ;;
-	  ::) dllsearchpath=$testbindir;;
-	  *) func_append dllsearchpath ":$testbindir";;
-	  esac
-	  ;;
-	esac
-	continue
-	;;
-
-      -l*)
-	if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then
-	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)
-	    # These systems don't actually have a C or math library (as such)
-	    continue
-	    ;;
-	  *-*-os2*)
-	    # These systems don't actually have a C library (as such)
-	    test "X$arg" = "X-lc" && continue
-	    ;;
-	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
-	    # Do not include libc due to us having libc/libc_r.
-	    test "X$arg" = "X-lc" && continue
-	    ;;
-	  *-*-rhapsody* | *-*-darwin1.[012])
-	    # Rhapsody C and math libraries are in the System framework
-	    func_append deplibs " System.ltframework"
-	    continue
-	    ;;
-	  *-*-sco3.2v5* | *-*-sco5v6*)
-	    # Causes problems with __ctype
-	    test "X$arg" = "X-lc" && continue
-	    ;;
-	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
-	    # Compiler inserts libc in the correct place for threads to work
-	    test "X$arg" = "X-lc" && continue
-	    ;;
-	  esac
-	elif test "X$arg" = "X-lc_r"; then
-	 case $host in
-	 *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
-	   # Do not include libc_r directly, use -pthread flag.
-	   continue
-	   ;;
-	 esac
-	fi
-	func_append deplibs " $arg"
-	continue
-	;;
-
-      -module)
-	module=yes
-	continue
-	;;
-
-      # Tru64 UNIX uses -model [arg] to determine the layout of C++
-      # classes, name mangling, and exception handling.
-      # Darwin uses the -arch flag to determine output architecture.
-      -model|-arch|-isysroot|--sysroot)
-	func_append compiler_flags " $arg"
-	func_append compile_command " $arg"
-	func_append finalize_command " $arg"
-	prev=xcompiler
-	continue
-	;;
-
-      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
-      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
-	func_append compiler_flags " $arg"
-	func_append compile_command " $arg"
-	func_append finalize_command " $arg"
-	case "$new_inherited_linker_flags " in
-	    *" $arg "*) ;;
-	    * ) func_append new_inherited_linker_flags " $arg" ;;
-	esac
-	continue
-	;;
-
-      -multi_module)
-	single_module="${wl}-multi_module"
-	continue
-	;;
-
-      -no-fast-install)
-	fast_install=no
-	continue
-	;;
-
-      -no-install)
-	case $host in
-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
-	  # The PATH hackery in wrapper scripts is required on Windows
-	  # and Darwin in order for the loader to find any dlls it needs.
-	  func_warning "\`-no-install' is ignored for $host"
-	  func_warning "assuming \`-no-fast-install' instead"
-	  fast_install=no
-	  ;;
-	*) no_install=yes ;;
-	esac
-	continue
-	;;
-
-      -no-undefined)
-	allow_undefined=no
-	continue
-	;;
-
-      -objectlist)
-	prev=objectlist
-	continue
-	;;
-
-      -o) prev=output ;;
-
-      -precious-files-regex)
-	prev=precious_regex
-	continue
-	;;
-
-      -release)
-	prev=release
-	continue
-	;;
-
-      -rpath)
-	prev=rpath
-	continue
-	;;
-
-      -R)
-	prev=xrpath
-	continue
-	;;
-
-      -R*)
-	func_stripname '-R' '' "$arg"
-	dir=$func_stripname_result
-	# We need an absolute path.
-	case $dir in
-	[\\/]* | [A-Za-z]:[\\/]*) ;;
-	=*)
-	  func_stripname '=' '' "$dir"
-	  dir=$lt_sysroot$func_stripname_result
-	  ;;
-	*)
-	  func_fatal_error "only absolute run-paths are allowed"
-	  ;;
-	esac
-	case "$xrpath " in
-	*" $dir "*) ;;
-	*) func_append xrpath " $dir" ;;
-	esac
-	continue
-	;;
-
-      -shared)
-	# The effects of -shared are defined in a previous loop.
-	continue
-	;;
-
-      -shrext)
-	prev=shrext
-	continue
-	;;
-
-      -static | -static-libtool-libs)
-	# The effects of -static are defined in a previous loop.
-	# We used to do the same as -all-static on platforms that
-	# didn't have a PIC flag, but the assumption that the effects
-	# would be equivalent was wrong.  It would break on at least
-	# Digital Unix and AIX.
-	continue
-	;;
-
-      -thread-safe)
-	thread_safe=yes
-	continue
-	;;
-
-      -version-info)
-	prev=vinfo
-	continue
-	;;
-
-      -version-number)
-	prev=vinfo
-	vinfo_number=yes
-	continue
-	;;
-
-      -weak)
-        prev=weak
-	continue
-	;;
-
-      -Wc,*)
-	func_stripname '-Wc,' '' "$arg"
-	args=$func_stripname_result
-	arg=
-	save_ifs="$IFS"; IFS=','
-	for flag in $args; do
-	  IFS="$save_ifs"
-          func_quote_for_eval "$flag"
-	  func_append arg " $func_quote_for_eval_result"
-	  func_append compiler_flags " $func_quote_for_eval_result"
-	done
-	IFS="$save_ifs"
-	func_stripname ' ' '' "$arg"
-	arg=$func_stripname_result
-	;;
-
-      -Wl,*)
-	func_stripname '-Wl,' '' "$arg"
-	args=$func_stripname_result
-	arg=
-	save_ifs="$IFS"; IFS=','
-	for flag in $args; do
-	  IFS="$save_ifs"
-          func_quote_for_eval "$flag"
-	  func_append arg " $wl$func_quote_for_eval_result"
-	  func_append compiler_flags " $wl$func_quote_for_eval_result"
-	  func_append linker_flags " $func_quote_for_eval_result"
-	done
-	IFS="$save_ifs"
-	func_stripname ' ' '' "$arg"
-	arg=$func_stripname_result
-	;;
-
-      -Xcompiler)
-	prev=xcompiler
-	continue
-	;;
-
-      -Xlinker)
-	prev=xlinker
-	continue
-	;;
-
-      -XCClinker)
-	prev=xcclinker
-	continue
-	;;
-
-      # -msg_* for osf cc
-      -msg_*)
-	func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
-	;;
-
-      # Flags to be passed through unchanged, with rationale:
-      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
-      # -r[0-9][0-9]*        specify processor for the SGI compiler
-      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler
-      # +DA*, +DD*           enable 64-bit mode for the HP compiler
-      # -q*                  compiler args for the IBM compiler
-      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
-      # -F/path              path to uninstalled frameworks, gcc on darwin
-      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
-      # @file                GCC response files
-      # -tp=*                Portland pgcc target processor selection
-      # --sysroot=*          for sysroot support
-      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization
-      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \
-      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \
-      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
-        func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
-        func_append compile_command " $arg"
-        func_append finalize_command " $arg"
-        func_append compiler_flags " $arg"
-        continue
-        ;;
-
-      # Some other compiler flag.
-      -* | +*)
-        func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
-	;;
-
-      *.$objext)
-	# A standard object.
-	func_append objs " $arg"
-	;;
-
-      *.lo)
-	# A libtool-controlled object.
-
-	# Check to see that this really is a libtool object.
-	if func_lalib_unsafe_p "$arg"; then
-	  pic_object=
-	  non_pic_object=
-
-	  # Read the .lo file
-	  func_source "$arg"
-
-	  if test -z "$pic_object" ||
-	     test -z "$non_pic_object" ||
-	     test "$pic_object" = none &&
-	     test "$non_pic_object" = none; then
-	    func_fatal_error "cannot find name of object for \`$arg'"
-	  fi
-
-	  # Extract subdirectory from the argument.
-	  func_dirname "$arg" "/" ""
-	  xdir="$func_dirname_result"
-
-	  if test "$pic_object" != none; then
-	    # Prepend the subdirectory the object is found in.
-	    pic_object="$xdir$pic_object"
-
-	    if test "$prev" = dlfiles; then
-	      if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then
-		func_append dlfiles " $pic_object"
-		prev=
-		continue
-	      else
-		# If libtool objects are unsupported, then we need to preload.
-		prev=dlprefiles
-	      fi
-	    fi
-
-	    # CHECK ME:  I think I busted this.  -Ossama
-	    if test "$prev" = dlprefiles; then
-	      # Preload the old-style object.
-	      func_append dlprefiles " $pic_object"
-	      prev=
-	    fi
-
-	    # A PIC object.
-	    func_append libobjs " $pic_object"
-	    arg="$pic_object"
-	  fi
-
-	  # Non-PIC object.
-	  if test "$non_pic_object" != none; then
-	    # Prepend the subdirectory the object is found in.
-	    non_pic_object="$xdir$non_pic_object"
-
-	    # A standard non-PIC object
-	    func_append non_pic_objects " $non_pic_object"
-	    if test -z "$pic_object" || test "$pic_object" = none ; then
-	      arg="$non_pic_object"
-	    fi
-	  else
-	    # If the PIC object exists, use it instead.
-	    # $xdir was prepended to $pic_object above.
-	    non_pic_object="$pic_object"
-	    func_append non_pic_objects " $non_pic_object"
-	  fi
-	else
-	  # Only an error if not doing a dry-run.
-	  if $opt_dry_run; then
-	    # Extract subdirectory from the argument.
-	    func_dirname "$arg" "/" ""
-	    xdir="$func_dirname_result"
-
-	    func_lo2o "$arg"
-	    pic_object=$xdir$objdir/$func_lo2o_result
-	    non_pic_object=$xdir$func_lo2o_result
-	    func_append libobjs " $pic_object"
-	    func_append non_pic_objects " $non_pic_object"
-	  else
-	    func_fatal_error "\`$arg' is not a valid libtool object"
-	  fi
-	fi
-	;;
-
-      *.$libext)
-	# An archive.
-	func_append deplibs " $arg"
-	func_append old_deplibs " $arg"
-	continue
-	;;
-
-      *.la)
-	# A libtool-controlled library.
-
-	func_resolve_sysroot "$arg"
-	if test "$prev" = dlfiles; then
-	  # This library was specified with -dlopen.
-	  func_append dlfiles " $func_resolve_sysroot_result"
-	  prev=
-	elif test "$prev" = dlprefiles; then
-	  # The library was specified with -dlpreopen.
-	  func_append dlprefiles " $func_resolve_sysroot_result"
-	  prev=
-	else
-	  func_append deplibs " $func_resolve_sysroot_result"
-	fi
-	continue
-	;;
-
-      # Some other compiler argument.
-      *)
-	# Unknown arguments in both finalize_command and compile_command need
-	# to be aesthetically quoted because they are evaled later.
-	func_quote_for_eval "$arg"
-	arg="$func_quote_for_eval_result"
-	;;
-      esac # arg
-
-      # Now actually substitute the argument into the commands.
-      if test -n "$arg"; then
-	func_append compile_command " $arg"
-	func_append finalize_command " $arg"
-      fi
-    done # argument parsing loop
-
-    test -n "$prev" && \
-      func_fatal_help "the \`$prevarg' option requires an argument"
-
-    if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then
-      eval arg=\"$export_dynamic_flag_spec\"
-      func_append compile_command " $arg"
-      func_append finalize_command " $arg"
-    fi
-
-    oldlibs=
-    # calculate the name of the file, without its directory
-    func_basename "$output"
-    outputname="$func_basename_result"
-    libobjs_save="$libobjs"
-
-    if test -n "$shlibpath_var"; then
-      # get the directories listed in $shlibpath_var
-      eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\`
-    else
-      shlib_search_path=
-    fi
-    eval sys_lib_search_path=\"$sys_lib_search_path_spec\"
-    eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\"
-
-    func_dirname "$output" "/" ""
-    output_objdir="$func_dirname_result$objdir"
-    func_to_tool_file "$output_objdir/"
-    tool_output_objdir=$func_to_tool_file_result
-    # Create the object directory.
-    func_mkdir_p "$output_objdir"
-
-    # Determine the type of output
-    case $output in
-    "")
-      func_fatal_help "you must specify an output file"
-      ;;
-    *.$libext) linkmode=oldlib ;;
-    *.lo | *.$objext) linkmode=obj ;;
-    *.la) linkmode=lib ;;
-    *) linkmode=prog ;; # Anything else should be a program.
-    esac
-
-    specialdeplibs=
-
-    libs=
-    # Find all interdependent deplibs by searching for libraries
-    # that are linked more than once (e.g. -la -lb -la)
-    for deplib in $deplibs; do
-      if $opt_preserve_dup_deps ; then
-	case "$libs " in
-	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
-	esac
-      fi
-      func_append libs " $deplib"
-    done
-
-    if test "$linkmode" = lib; then
-      libs="$predeps $libs $compiler_lib_search_path $postdeps"
-
-      # Compute libraries that are listed more than once in $predeps
-      # $postdeps and mark them as special (i.e., whose duplicates are
-      # not to be eliminated).
-      pre_post_deps=
-      if $opt_duplicate_compiler_generated_deps; then
-	for pre_post_dep in $predeps $postdeps; do
-	  case "$pre_post_deps " in
-	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
-	  esac
-	  func_append pre_post_deps " $pre_post_dep"
-	done
-      fi
-      pre_post_deps=
-    fi
-
-    deplibs=
-    newdependency_libs=
-    newlib_search_path=
-    need_relink=no # whether we're linking any uninstalled libtool libraries
-    notinst_deplibs= # not-installed libtool libraries
-    notinst_path= # paths that contain not-installed libtool libraries
-
-    case $linkmode in
-    lib)
-	passes="conv dlpreopen link"
-	for file in $dlfiles $dlprefiles; do
-	  case $file in
-	  *.la) ;;
-	  *)
-	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file"
-	    ;;
-	  esac
-	done
-	;;
-    prog)
-	compile_deplibs=
-	finalize_deplibs=
-	alldeplibs=no
-	newdlfiles=
-	newdlprefiles=
-	passes="conv scan dlopen dlpreopen link"
-	;;
-    *)  passes="conv"
-	;;
-    esac
-
-    for pass in $passes; do
-      # The preopen pass in lib mode reverses $deplibs; put it back here
-      # so that -L comes before libs that need it for instance...
-      if test "$linkmode,$pass" = "lib,link"; then
-	## FIXME: Find the place where the list is rebuilt in the wrong
-	##        order, and fix it there properly
-        tmp_deplibs=
-	for deplib in $deplibs; do
-	  tmp_deplibs="$deplib $tmp_deplibs"
-	done
-	deplibs="$tmp_deplibs"
-      fi
-
-      if test "$linkmode,$pass" = "lib,link" ||
-	 test "$linkmode,$pass" = "prog,scan"; then
-	libs="$deplibs"
-	deplibs=
-      fi
-      if test "$linkmode" = prog; then
-	case $pass in
-	dlopen) libs="$dlfiles" ;;
-	dlpreopen) libs="$dlprefiles" ;;
-	link)
-	  libs="$deplibs %DEPLIBS%"
-	  test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs"
-	  ;;
-	esac
-      fi
-      if test "$linkmode,$pass" = "lib,dlpreopen"; then
-	# Collect and forward deplibs of preopened libtool libs
-	for lib in $dlprefiles; do
-	  # Ignore non-libtool-libs
-	  dependency_libs=
-	  func_resolve_sysroot "$lib"
-	  case $lib in
-	  *.la)	func_source "$func_resolve_sysroot_result" ;;
-	  esac
-
-	  # Collect preopened libtool deplibs, except any this library
-	  # has declared as weak libs
-	  for deplib in $dependency_libs; do
-	    func_basename "$deplib"
-            deplib_base=$func_basename_result
-	    case " $weak_libs " in
-	    *" $deplib_base "*) ;;
-	    *) func_append deplibs " $deplib" ;;
-	    esac
-	  done
-	done
-	libs="$dlprefiles"
-      fi
-      if test "$pass" = dlopen; then
-	# Collect dlpreopened libraries
-	save_deplibs="$deplibs"
-	deplibs=
-      fi
-
-      for deplib in $libs; do
-	lib=
-	found=no
-	case $deplib in
-	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \
-        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)
-	  if test "$linkmode,$pass" = "prog,link"; then
-	    compile_deplibs="$deplib $compile_deplibs"
-	    finalize_deplibs="$deplib $finalize_deplibs"
-	  else
-	    func_append compiler_flags " $deplib"
-	    if test "$linkmode" = lib ; then
-		case "$new_inherited_linker_flags " in
-		    *" $deplib "*) ;;
-		    * ) func_append new_inherited_linker_flags " $deplib" ;;
-		esac
-	    fi
-	  fi
-	  continue
-	  ;;
-	-l*)
-	  if test "$linkmode" != lib && test "$linkmode" != prog; then
-	    func_warning "\`-l' is ignored for archives/objects"
-	    continue
-	  fi
-	  func_stripname '-l' '' "$deplib"
-	  name=$func_stripname_result
-	  if test "$linkmode" = lib; then
-	    searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path"
-	  else
-	    searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path"
-	  fi
-	  for searchdir in $searchdirs; do
-	    for search_ext in .la $std_shrext .so .a; do
-	      # Search the libtool library
-	      lib="$searchdir/lib${name}${search_ext}"
-	      if test -f "$lib"; then
-		if test "$search_ext" = ".la"; then
-		  found=yes
-		else
-		  found=no
-		fi
-		break 2
-	      fi
-	    done
-	  done
-	  if test "$found" != yes; then
-	    # deplib doesn't seem to be a libtool library
-	    if test "$linkmode,$pass" = "prog,link"; then
-	      compile_deplibs="$deplib $compile_deplibs"
-	      finalize_deplibs="$deplib $finalize_deplibs"
-	    else
-	      deplibs="$deplib $deplibs"
-	      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
-	    fi
-	    continue
-	  else # deplib is a libtool library
-	    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,
-	    # We need to do some special things here, and not later.
-	    if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-	      case " $predeps $postdeps " in
-	      *" $deplib "*)
-		if func_lalib_p "$lib"; then
-		  library_names=
-		  old_library=
-		  func_source "$lib"
-		  for l in $old_library $library_names; do
-		    ll="$l"
-		  done
-		  if test "X$ll" = "X$old_library" ; then # only static version available
-		    found=no
-		    func_dirname "$lib" "" "."
-		    ladir="$func_dirname_result"
-		    lib=$ladir/$old_library
-		    if test "$linkmode,$pass" = "prog,link"; then
-		      compile_deplibs="$deplib $compile_deplibs"
-		      finalize_deplibs="$deplib $finalize_deplibs"
-		    else
-		      deplibs="$deplib $deplibs"
-		      test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs"
-		    fi
-		    continue
-		  fi
-		fi
-		;;
-	      *) ;;
-	      esac
-	    fi
-	  fi
-	  ;; # -l
-	*.ltframework)
-	  if test "$linkmode,$pass" = "prog,link"; then
-	    compile_deplibs="$deplib $compile_deplibs"
-	    finalize_deplibs="$deplib $finalize_deplibs"
-	  else
-	    deplibs="$deplib $deplibs"
-	    if test "$linkmode" = lib ; then
-		case "$new_inherited_linker_flags " in
-		    *" $deplib "*) ;;
-		    * ) func_append new_inherited_linker_flags " $deplib" ;;
-		esac
-	    fi
-	  fi
-	  continue
-	  ;;
-	-L*)
-	  case $linkmode in
-	  lib)
-	    deplibs="$deplib $deplibs"
-	    test "$pass" = conv && continue
-	    newdependency_libs="$deplib $newdependency_libs"
-	    func_stripname '-L' '' "$deplib"
-	    func_resolve_sysroot "$func_stripname_result"
-	    func_append newlib_search_path " $func_resolve_sysroot_result"
-	    ;;
-	  prog)
-	    if test "$pass" = conv; then
-	      deplibs="$deplib $deplibs"
-	      continue
-	    fi
-	    if test "$pass" = scan; then
-	      deplibs="$deplib $deplibs"
-	    else
-	      compile_deplibs="$deplib $compile_deplibs"
-	      finalize_deplibs="$deplib $finalize_deplibs"
-	    fi
-	    func_stripname '-L' '' "$deplib"
-	    func_resolve_sysroot "$func_stripname_result"
-	    func_append newlib_search_path " $func_resolve_sysroot_result"
-	    ;;
-	  *)
-	    func_warning "\`-L' is ignored for archives/objects"
-	    ;;
-	  esac # linkmode
-	  continue
-	  ;; # -L
-	-R*)
-	  if test "$pass" = link; then
-	    func_stripname '-R' '' "$deplib"
-	    func_resolve_sysroot "$func_stripname_result"
-	    dir=$func_resolve_sysroot_result
-	    # Make sure the xrpath contains only unique directories.
-	    case "$xrpath " in
-	    *" $dir "*) ;;
-	    *) func_append xrpath " $dir" ;;
-	    esac
-	  fi
-	  deplibs="$deplib $deplibs"
-	  continue
-	  ;;
-	*.la)
-	  func_resolve_sysroot "$deplib"
-	  lib=$func_resolve_sysroot_result
-	  ;;
-	*.$libext)
-	  if test "$pass" = conv; then
-	    deplibs="$deplib $deplibs"
-	    continue
-	  fi
-	  case $linkmode in
-	  lib)
-	    # Linking convenience modules into shared libraries is allowed,
-	    # but linking other static libraries is non-portable.
-	    case " $dlpreconveniencelibs " in
-	    *" $deplib "*) ;;
-	    *)
-	      valid_a_lib=no
-	      case $deplibs_check_method in
-		match_pattern*)
-		  set dummy $deplibs_check_method; shift
-		  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
-		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
-		    | $EGREP "$match_pattern_regex" > /dev/null; then
-		    valid_a_lib=yes
-		  fi
-		;;
-		pass_all)
-		  valid_a_lib=yes
-		;;
-	      esac
-	      if test "$valid_a_lib" != yes; then
-		echo
-		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
-		echo "*** I have the capability to make that library automatically link in when"
-		echo "*** you link to this library.  But I can only do this if you have a"
-		echo "*** shared version of the library, which you do not appear to have"
-		echo "*** because the file extensions .$libext of this argument makes me believe"
-		echo "*** that it is just a static archive that I should not use here."
-	      else
-		echo
-		$ECHO "*** Warning: Linking the shared library $output against the"
-		$ECHO "*** static library $deplib is not portable!"
-		deplibs="$deplib $deplibs"
-	      fi
-	      ;;
-	    esac
-	    continue
-	    ;;
-	  prog)
-	    if test "$pass" != link; then
-	      deplibs="$deplib $deplibs"
-	    else
-	      compile_deplibs="$deplib $compile_deplibs"
-	      finalize_deplibs="$deplib $finalize_deplibs"
-	    fi
-	    continue
-	    ;;
-	  esac # linkmode
-	  ;; # *.$libext
-	*.lo | *.$objext)
-	  if test "$pass" = conv; then
-	    deplibs="$deplib $deplibs"
-	  elif test "$linkmode" = prog; then
-	    if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then
-	      # If there is no dlopen support or we're linking statically,
-	      # we need to preload.
-	      func_append newdlprefiles " $deplib"
-	      compile_deplibs="$deplib $compile_deplibs"
-	      finalize_deplibs="$deplib $finalize_deplibs"
-	    else
-	      func_append newdlfiles " $deplib"
-	    fi
-	  fi
-	  continue
-	  ;;
-	%DEPLIBS%)
-	  alldeplibs=yes
-	  continue
-	  ;;
-	esac # case $deplib
-
-	if test "$found" = yes || test -f "$lib"; then :
-	else
-	  func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'"
-	fi
-
-	# Check to see that this really is a libtool archive.
-	func_lalib_unsafe_p "$lib" \
-	  || func_fatal_error "\`$lib' is not a valid libtool archive"
-
-	func_dirname "$lib" "" "."
-	ladir="$func_dirname_result"
-
-	dlname=
-	dlopen=
-	dlpreopen=
-	libdir=
-	library_names=
-	old_library=
-	inherited_linker_flags=
-	# If the library was installed with an old release of libtool,
-	# it will not redefine variables installed, or shouldnotlink
-	installed=yes
-	shouldnotlink=no
-	avoidtemprpath=
-
-
-	# Read the .la file
-	func_source "$lib"
-
-	# Convert "-framework foo" to "foo.ltframework"
-	if test -n "$inherited_linker_flags"; then
-	  tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'`
-	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
-	    case " $new_inherited_linker_flags " in
-	      *" $tmp_inherited_linker_flag "*) ;;
-	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";;
-	    esac
-	  done
-	fi
-	dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	if test "$linkmode,$pass" = "lib,link" ||
-	   test "$linkmode,$pass" = "prog,scan" ||
-	   { test "$linkmode" != prog && test "$linkmode" != lib; }; then
-	  test -n "$dlopen" && func_append dlfiles " $dlopen"
-	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
-	fi
-
-	if test "$pass" = conv; then
-	  # Only check for convenience libraries
-	  deplibs="$lib $deplibs"
-	  if test -z "$libdir"; then
-	    if test -z "$old_library"; then
-	      func_fatal_error "cannot find name of link library for \`$lib'"
-	    fi
-	    # It is a libtool convenience library, so add in its objects.
-	    func_append convenience " $ladir/$objdir/$old_library"
-	    func_append old_convenience " $ladir/$objdir/$old_library"
-	    tmp_libs=
-	    for deplib in $dependency_libs; do
-	      deplibs="$deplib $deplibs"
-	      if $opt_preserve_dup_deps ; then
-		case "$tmp_libs " in
-		*" $deplib "*) func_append specialdeplibs " $deplib" ;;
-		esac
-	      fi
-	      func_append tmp_libs " $deplib"
-	    done
-	  elif test "$linkmode" != prog && test "$linkmode" != lib; then
-	    func_fatal_error "\`$lib' is not a convenience library"
-	  fi
-	  continue
-	fi # $pass = conv
-
-
-	# Get the name of the library we link against.
-	linklib=
-	if test -n "$old_library" &&
-	   { test "$prefer_static_libs" = yes ||
-	     test "$prefer_static_libs,$installed" = "built,no"; }; then
-	  linklib=$old_library
-	else
-	  for l in $old_library $library_names; do
-	    linklib="$l"
-	  done
-	fi
-	if test -z "$linklib"; then
-	  func_fatal_error "cannot find name of link library for \`$lib'"
-	fi
-
-	# This library was specified with -dlopen.
-	if test "$pass" = dlopen; then
-	  if test -z "$libdir"; then
-	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
-	  fi
-	  if test -z "$dlname" ||
-	     test "$dlopen_support" != yes ||
-	     test "$build_libtool_libs" = no; then
-	    # If there is no dlname, no dlopen support or we're linking
-	    # statically, we need to preload.  We also need to preload any
-	    # dependent libraries so libltdl's deplib preloader doesn't
-	    # bomb out in the load deplibs phase.
-	    func_append dlprefiles " $lib $dependency_libs"
-	  else
-	    func_append newdlfiles " $lib"
-	  fi
-	  continue
-	fi # $pass = dlopen
-
-	# We need an absolute path.
-	case $ladir in
-	[\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;;
-	*)
-	  abs_ladir=`cd "$ladir" && pwd`
-	  if test -z "$abs_ladir"; then
-	    func_warning "cannot determine absolute directory name of \`$ladir'"
-	    func_warning "passing it literally to the linker, although it might fail"
-	    abs_ladir="$ladir"
-	  fi
-	  ;;
-	esac
-	func_basename "$lib"
-	laname="$func_basename_result"
-
-	# Find the relevant object directory and library name.
-	if test "X$installed" = Xyes; then
-	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
-	    func_warning "library \`$lib' was moved."
-	    dir="$ladir"
-	    absdir="$abs_ladir"
-	    libdir="$abs_ladir"
-	  else
-	    dir="$lt_sysroot$libdir"
-	    absdir="$lt_sysroot$libdir"
-	  fi
-	  test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes
-	else
-	  if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then
-	    dir="$ladir"
-	    absdir="$abs_ladir"
-	    # Remove this search path later
-	    func_append notinst_path " $abs_ladir"
-	  else
-	    dir="$ladir/$objdir"
-	    absdir="$abs_ladir/$objdir"
-	    # Remove this search path later
-	    func_append notinst_path " $abs_ladir"
-	  fi
-	fi # $installed = yes
-	func_stripname 'lib' '.la' "$laname"
-	name=$func_stripname_result
-
-	# This library was specified with -dlpreopen.
-	if test "$pass" = dlpreopen; then
-	  if test -z "$libdir" && test "$linkmode" = prog; then
-	    func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'"
-	  fi
-	  case "$host" in
-	    # special handling for platforms with PE-DLLs.
-	    *cygwin* | *mingw* | *cegcc* )
-	      # Linker will automatically link against shared library if both
-	      # static and shared are present.  Therefore, ensure we extract
-	      # symbols from the import library if a shared library is present
-	      # (otherwise, the dlopen module name will be incorrect).  We do
-	      # this by putting the import library name into $newdlprefiles.
-	      # We recover the dlopen module name by 'saving' the la file
-	      # name in a special purpose variable, and (later) extracting the
-	      # dlname from the la file.
-	      if test -n "$dlname"; then
-	        func_tr_sh "$dir/$linklib"
-	        eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname"
-	        func_append newdlprefiles " $dir/$linklib"
-	      else
-	        func_append newdlprefiles " $dir/$old_library"
-	        # Keep a list of preopened convenience libraries to check
-	        # that they are being used correctly in the link pass.
-	        test -z "$libdir" && \
-	          func_append dlpreconveniencelibs " $dir/$old_library"
-	      fi
-	    ;;
-	    * )
-	      # Prefer using a static library (so that no silly _DYNAMIC symbols
-	      # are required to link).
-	      if test -n "$old_library"; then
-	        func_append newdlprefiles " $dir/$old_library"
-	        # Keep a list of preopened convenience libraries to check
-	        # that they are being used correctly in the link pass.
-	        test -z "$libdir" && \
-	          func_append dlpreconveniencelibs " $dir/$old_library"
-	      # Otherwise, use the dlname, so that lt_dlopen finds it.
-	      elif test -n "$dlname"; then
-	        func_append newdlprefiles " $dir/$dlname"
-	      else
-	        func_append newdlprefiles " $dir/$linklib"
-	      fi
-	    ;;
-	  esac
-	fi # $pass = dlpreopen
-
-	if test -z "$libdir"; then
-	  # Link the convenience library
-	  if test "$linkmode" = lib; then
-	    deplibs="$dir/$old_library $deplibs"
-	  elif test "$linkmode,$pass" = "prog,link"; then
-	    compile_deplibs="$dir/$old_library $compile_deplibs"
-	    finalize_deplibs="$dir/$old_library $finalize_deplibs"
-	  else
-	    deplibs="$lib $deplibs" # used for prog,scan pass
-	  fi
-	  continue
-	fi
-
-
-	if test "$linkmode" = prog && test "$pass" != link; then
-	  func_append newlib_search_path " $ladir"
-	  deplibs="$lib $deplibs"
-
-	  linkalldeplibs=no
-	  if test "$link_all_deplibs" != no || test -z "$library_names" ||
-	     test "$build_libtool_libs" = no; then
-	    linkalldeplibs=yes
-	  fi
-
-	  tmp_libs=
-	  for deplib in $dependency_libs; do
-	    case $deplib in
-	    -L*) func_stripname '-L' '' "$deplib"
-	         func_resolve_sysroot "$func_stripname_result"
-	         func_append newlib_search_path " $func_resolve_sysroot_result"
-		 ;;
-	    esac
-	    # Need to link against all dependency_libs?
-	    if test "$linkalldeplibs" = yes; then
-	      deplibs="$deplib $deplibs"
-	    else
-	      # Need to hardcode shared library paths
-	      # or/and link against static libraries
-	      newdependency_libs="$deplib $newdependency_libs"
-	    fi
-	    if $opt_preserve_dup_deps ; then
-	      case "$tmp_libs " in
-	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
-	      esac
-	    fi
-	    func_append tmp_libs " $deplib"
-	  done # for deplib
-	  continue
-	fi # $linkmode = prog...
-
-	if test "$linkmode,$pass" = "prog,link"; then
-	  if test -n "$library_names" &&
-	     { { test "$prefer_static_libs" = no ||
-	         test "$prefer_static_libs,$installed" = "built,yes"; } ||
-	       test -z "$old_library"; }; then
-	    # We need to hardcode the library path
-	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
-	      # Make sure the rpath contains only unique directories.
-	      case "$temp_rpath:" in
-	      *"$absdir:"*) ;;
-	      *) func_append temp_rpath "$absdir:" ;;
-	      esac
-	    fi
-
-	    # Hardcode the library path.
-	    # Skip directories that are in the system default run-time
-	    # search path.
-	    case " $sys_lib_dlsearch_path " in
-	    *" $absdir "*) ;;
-	    *)
-	      case "$compile_rpath " in
-	      *" $absdir "*) ;;
-	      *) func_append compile_rpath " $absdir" ;;
-	      esac
-	      ;;
-	    esac
-	    case " $sys_lib_dlsearch_path " in
-	    *" $libdir "*) ;;
-	    *)
-	      case "$finalize_rpath " in
-	      *" $libdir "*) ;;
-	      *) func_append finalize_rpath " $libdir" ;;
-	      esac
-	      ;;
-	    esac
-	  fi # $linkmode,$pass = prog,link...
-
-	  if test "$alldeplibs" = yes &&
-	     { test "$deplibs_check_method" = pass_all ||
-	       { test "$build_libtool_libs" = yes &&
-		 test -n "$library_names"; }; }; then
-	    # We only need to search for static libraries
-	    continue
-	  fi
-	fi
-
-	link_static=no # Whether the deplib will be linked statically
-	use_static_libs=$prefer_static_libs
-	if test "$use_static_libs" = built && test "$installed" = yes; then
-	  use_static_libs=no
-	fi
-	if test -n "$library_names" &&
-	   { test "$use_static_libs" = no || test -z "$old_library"; }; then
-	  case $host in
-	  *cygwin* | *mingw* | *cegcc*)
-	      # No point in relinking DLLs because paths are not encoded
-	      func_append notinst_deplibs " $lib"
-	      need_relink=no
-	    ;;
-	  *)
-	    if test "$installed" = no; then
-	      func_append notinst_deplibs " $lib"
-	      need_relink=yes
-	    fi
-	    ;;
-	  esac
-	  # This is a shared library
-
-	  # Warn about portability, can't link against -module's on some
-	  # systems (darwin).  Don't bleat about dlopened modules though!
-	  dlopenmodule=""
-	  for dlpremoduletest in $dlprefiles; do
-	    if test "X$dlpremoduletest" = "X$lib"; then
-	      dlopenmodule="$dlpremoduletest"
-	      break
-	    fi
-	  done
-	  if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then
-	    echo
-	    if test "$linkmode" = prog; then
-	      $ECHO "*** Warning: Linking the executable $output against the loadable module"
-	    else
-	      $ECHO "*** Warning: Linking the shared library $output against the loadable module"
-	    fi
-	    $ECHO "*** $linklib is not portable!"
-	  fi
-	  if test "$linkmode" = lib &&
-	     test "$hardcode_into_libs" = yes; then
-	    # Hardcode the library path.
-	    # Skip directories that are in the system default run-time
-	    # search path.
-	    case " $sys_lib_dlsearch_path " in
-	    *" $absdir "*) ;;
-	    *)
-	      case "$compile_rpath " in
-	      *" $absdir "*) ;;
-	      *) func_append compile_rpath " $absdir" ;;
-	      esac
-	      ;;
-	    esac
-	    case " $sys_lib_dlsearch_path " in
-	    *" $libdir "*) ;;
-	    *)
-	      case "$finalize_rpath " in
-	      *" $libdir "*) ;;
-	      *) func_append finalize_rpath " $libdir" ;;
-	      esac
-	      ;;
-	    esac
-	  fi
-
-	  if test -n "$old_archive_from_expsyms_cmds"; then
-	    # figure out the soname
-	    set dummy $library_names
-	    shift
-	    realname="$1"
-	    shift
-	    libname=`eval "\\$ECHO \"$libname_spec\""`
-	    # use dlname if we got it. it's perfectly good, no?
-	    if test -n "$dlname"; then
-	      soname="$dlname"
-	    elif test -n "$soname_spec"; then
-	      # bleh windows
-	      case $host in
-	      *cygwin* | mingw* | *cegcc*)
-	        func_arith $current - $age
-		major=$func_arith_result
-		versuffix="-$major"
-		;;
-	      esac
-	      eval soname=\"$soname_spec\"
-	    else
-	      soname="$realname"
-	    fi
-
-	    # Make a new name for the extract_expsyms_cmds to use
-	    soroot="$soname"
-	    func_basename "$soroot"
-	    soname="$func_basename_result"
-	    func_stripname 'lib' '.dll' "$soname"
-	    newlib=libimp-$func_stripname_result.a
-
-	    # If the library has no export list, then create one now
-	    if test -f "$output_objdir/$soname-def"; then :
-	    else
-	      func_verbose "extracting exported symbol list from \`$soname'"
-	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
-	    fi
-
-	    # Create $newlib
-	    if test -f "$output_objdir/$newlib"; then :; else
-	      func_verbose "generating import library for \`$soname'"
-	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
-	    fi
-	    # make sure the library variables are pointing to the new library
-	    dir=$output_objdir
-	    linklib=$newlib
-	  fi # test -n "$old_archive_from_expsyms_cmds"
-
-	  if test "$linkmode" = prog || test "$opt_mode" != relink; then
-	    add_shlibpath=
-	    add_dir=
-	    add=
-	    lib_linked=yes
-	    case $hardcode_action in
-	    immediate | unsupported)
-	      if test "$hardcode_direct" = no; then
-		add="$dir/$linklib"
-		case $host in
-		  *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;;
-		  *-*-sysv4*uw2*) add_dir="-L$dir" ;;
-		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
-		    *-*-unixware7*) add_dir="-L$dir" ;;
-		  *-*-darwin* )
-		    # if the lib is a (non-dlopened) module then we can not
-		    # link against it, someone is ignoring the earlier warnings
-		    if /usr/bin/file -L $add 2> /dev/null |
-			 $GREP ": [^:]* bundle" >/dev/null ; then
-		      if test "X$dlopenmodule" != "X$lib"; then
-			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
-			if test -z "$old_library" ; then
-			  echo
-			  echo "*** And there doesn't seem to be a static archive available"
-			  echo "*** The link will probably fail, sorry"
-			else
-			  add="$dir/$old_library"
-			fi
-		      elif test -n "$old_library"; then
-			add="$dir/$old_library"
-		      fi
-		    fi
-		esac
-	      elif test "$hardcode_minus_L" = no; then
-		case $host in
-		*-*-sunos*) add_shlibpath="$dir" ;;
-		esac
-		add_dir="-L$dir"
-		add="-l$name"
-	      elif test "$hardcode_shlibpath_var" = no; then
-		add_shlibpath="$dir"
-		add="-l$name"
-	      else
-		lib_linked=no
-	      fi
-	      ;;
-	    relink)
-	      if test "$hardcode_direct" = yes &&
-	         test "$hardcode_direct_absolute" = no; then
-		add="$dir/$linklib"
-	      elif test "$hardcode_minus_L" = yes; then
-		add_dir="-L$absdir"
-		# Try looking first in the location we're being installed to.
-		if test -n "$inst_prefix_dir"; then
-		  case $libdir in
-		    [\\/]*)
-		      func_append add_dir " -L$inst_prefix_dir$libdir"
-		      ;;
-		  esac
-		fi
-		add="-l$name"
-	      elif test "$hardcode_shlibpath_var" = yes; then
-		add_shlibpath="$dir"
-		add="-l$name"
-	      else
-		lib_linked=no
-	      fi
-	      ;;
-	    *) lib_linked=no ;;
-	    esac
-
-	    if test "$lib_linked" != yes; then
-	      func_fatal_configuration "unsupported hardcode properties"
-	    fi
-
-	    if test -n "$add_shlibpath"; then
-	      case :$compile_shlibpath: in
-	      *":$add_shlibpath:"*) ;;
-	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
-	      esac
-	    fi
-	    if test "$linkmode" = prog; then
-	      test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs"
-	      test -n "$add" && compile_deplibs="$add $compile_deplibs"
-	    else
-	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
-	      test -n "$add" && deplibs="$add $deplibs"
-	      if test "$hardcode_direct" != yes &&
-		 test "$hardcode_minus_L" != yes &&
-		 test "$hardcode_shlibpath_var" = yes; then
-		case :$finalize_shlibpath: in
-		*":$libdir:"*) ;;
-		*) func_append finalize_shlibpath "$libdir:" ;;
-		esac
-	      fi
-	    fi
-	  fi
-
-	  if test "$linkmode" = prog || test "$opt_mode" = relink; then
-	    add_shlibpath=
-	    add_dir=
-	    add=
-	    # Finalize command for both is simple: just hardcode it.
-	    if test "$hardcode_direct" = yes &&
-	       test "$hardcode_direct_absolute" = no; then
-	      add="$libdir/$linklib"
-	    elif test "$hardcode_minus_L" = yes; then
-	      add_dir="-L$libdir"
-	      add="-l$name"
-	    elif test "$hardcode_shlibpath_var" = yes; then
-	      case :$finalize_shlibpath: in
-	      *":$libdir:"*) ;;
-	      *) func_append finalize_shlibpath "$libdir:" ;;
-	      esac
-	      add="-l$name"
-	    elif test "$hardcode_automatic" = yes; then
-	      if test -n "$inst_prefix_dir" &&
-		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
-		add="$inst_prefix_dir$libdir/$linklib"
-	      else
-		add="$libdir/$linklib"
-	      fi
-	    else
-	      # We cannot seem to hardcode it, guess we'll fake it.
-	      add_dir="-L$libdir"
-	      # Try looking first in the location we're being installed to.
-	      if test -n "$inst_prefix_dir"; then
-		case $libdir in
-		  [\\/]*)
-		    func_append add_dir " -L$inst_prefix_dir$libdir"
-		    ;;
-		esac
-	      fi
-	      add="-l$name"
-	    fi
-
-	    if test "$linkmode" = prog; then
-	      test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs"
-	      test -n "$add" && finalize_deplibs="$add $finalize_deplibs"
-	    else
-	      test -n "$add_dir" && deplibs="$add_dir $deplibs"
-	      test -n "$add" && deplibs="$add $deplibs"
-	    fi
-	  fi
-	elif test "$linkmode" = prog; then
-	  # Here we assume that one of hardcode_direct or hardcode_minus_L
-	  # is not unsupported.  This is valid on all known static and
-	  # shared platforms.
-	  if test "$hardcode_direct" != unsupported; then
-	    test -n "$old_library" && linklib="$old_library"
-	    compile_deplibs="$dir/$linklib $compile_deplibs"
-	    finalize_deplibs="$dir/$linklib $finalize_deplibs"
-	  else
-	    compile_deplibs="-l$name -L$dir $compile_deplibs"
-	    finalize_deplibs="-l$name -L$dir $finalize_deplibs"
-	  fi
-	elif test "$build_libtool_libs" = yes; then
-	  # Not a shared library
-	  if test "$deplibs_check_method" != pass_all; then
-	    # We're trying link a shared library against a static one
-	    # but the system doesn't support it.
-
-	    # Just print a warning and add the library to dependency_libs so
-	    # that the program can be linked against the static library.
-	    echo
-	    $ECHO "*** Warning: This system can not link to static lib archive $lib."
-	    echo "*** I have the capability to make that library automatically link in when"
-	    echo "*** you link to this library.  But I can only do this if you have a"
-	    echo "*** shared version of the library, which you do not appear to have."
-	    if test "$module" = yes; then
-	      echo "*** But as you try to build a module library, libtool will still create "
-	      echo "*** a static module, that should work as long as the dlopening application"
-	      echo "*** is linked with the -dlopen flag to resolve symbols at runtime."
-	      if test -z "$global_symbol_pipe"; then
-		echo
-		echo "*** However, this would only work if libtool was able to extract symbol"
-		echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
-		echo "*** not find such a program.  So, this module is probably useless."
-		echo "*** \`nm' from GNU binutils and a full rebuild may help."
-	      fi
-	      if test "$build_old_libs" = no; then
-		build_libtool_libs=module
-		build_old_libs=yes
-	      else
-		build_libtool_libs=no
-	      fi
-	    fi
-	  else
-	    deplibs="$dir/$old_library $deplibs"
-	    link_static=yes
-	  fi
-	fi # link shared/static library?
-
-	if test "$linkmode" = lib; then
-	  if test -n "$dependency_libs" &&
-	     { test "$hardcode_into_libs" != yes ||
-	       test "$build_old_libs" = yes ||
-	       test "$link_static" = yes; }; then
-	    # Extract -R from dependency_libs
-	    temp_deplibs=
-	    for libdir in $dependency_libs; do
-	      case $libdir in
-	      -R*) func_stripname '-R' '' "$libdir"
-	           temp_xrpath=$func_stripname_result
-		   case " $xrpath " in
-		   *" $temp_xrpath "*) ;;
-		   *) func_append xrpath " $temp_xrpath";;
-		   esac;;
-	      *) func_append temp_deplibs " $libdir";;
-	      esac
-	    done
-	    dependency_libs="$temp_deplibs"
-	  fi
-
-	  func_append newlib_search_path " $absdir"
-	  # Link against this library
-	  test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs"
-	  # ... and its dependency_libs
-	  tmp_libs=
-	  for deplib in $dependency_libs; do
-	    newdependency_libs="$deplib $newdependency_libs"
-	    case $deplib in
-              -L*) func_stripname '-L' '' "$deplib"
-                   func_resolve_sysroot "$func_stripname_result";;
-              *) func_resolve_sysroot "$deplib" ;;
-            esac
-	    if $opt_preserve_dup_deps ; then
-	      case "$tmp_libs " in
-	      *" $func_resolve_sysroot_result "*)
-                func_append specialdeplibs " $func_resolve_sysroot_result" ;;
-	      esac
-	    fi
-	    func_append tmp_libs " $func_resolve_sysroot_result"
-	  done
-
-	  if test "$link_all_deplibs" != no; then
-	    # Add the search paths of all dependency libraries
-	    for deplib in $dependency_libs; do
-	      path=
-	      case $deplib in
-	      -L*) path="$deplib" ;;
-	      *.la)
-	        func_resolve_sysroot "$deplib"
-	        deplib=$func_resolve_sysroot_result
-	        func_dirname "$deplib" "" "."
-		dir=$func_dirname_result
-		# We need an absolute path.
-		case $dir in
-		[\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;;
-		*)
-		  absdir=`cd "$dir" && pwd`
-		  if test -z "$absdir"; then
-		    func_warning "cannot determine absolute directory name of \`$dir'"
-		    absdir="$dir"
-		  fi
-		  ;;
-		esac
-		if $GREP "^installed=no" $deplib > /dev/null; then
-		case $host in
-		*-*-darwin*)
-		  depdepl=
-		  eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib`
-		  if test -n "$deplibrary_names" ; then
-		    for tmp in $deplibrary_names ; do
-		      depdepl=$tmp
-		    done
-		    if test -f "$absdir/$objdir/$depdepl" ; then
-		      depdepl="$absdir/$objdir/$depdepl"
-		      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`
-                      if test -z "$darwin_install_name"; then
-                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`
-                      fi
-		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}"
-		      func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}"
-		      path=
-		    fi
-		  fi
-		  ;;
-		*)
-		  path="-L$absdir/$objdir"
-		  ;;
-		esac
-		else
-		  eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib`
-		  test -z "$libdir" && \
-		    func_fatal_error "\`$deplib' is not a valid libtool archive"
-		  test "$absdir" != "$libdir" && \
-		    func_warning "\`$deplib' seems to be moved"
-
-		  path="-L$absdir"
-		fi
-		;;
-	      esac
-	      case " $deplibs " in
-	      *" $path "*) ;;
-	      *) deplibs="$path $deplibs" ;;
-	      esac
-	    done
-	  fi # link_all_deplibs != no
-	fi # linkmode = lib
-      done # for deplib in $libs
-      if test "$pass" = link; then
-	if test "$linkmode" = "prog"; then
-	  compile_deplibs="$new_inherited_linker_flags $compile_deplibs"
-	  finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs"
-	else
-	  compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	fi
-      fi
-      dependency_libs="$newdependency_libs"
-      if test "$pass" = dlpreopen; then
-	# Link the dlpreopened libraries before other libraries
-	for deplib in $save_deplibs; do
-	  deplibs="$deplib $deplibs"
-	done
-      fi
-      if test "$pass" != dlopen; then
-	if test "$pass" != conv; then
-	  # Make sure lib_search_path contains only unique directories.
-	  lib_search_path=
-	  for dir in $newlib_search_path; do
-	    case "$lib_search_path " in
-	    *" $dir "*) ;;
-	    *) func_append lib_search_path " $dir" ;;
-	    esac
-	  done
-	  newlib_search_path=
-	fi
-
-	if test "$linkmode,$pass" != "prog,link"; then
-	  vars="deplibs"
-	else
-	  vars="compile_deplibs finalize_deplibs"
-	fi
-	for var in $vars dependency_libs; do
-	  # Add libraries to $var in reverse order
-	  eval tmp_libs=\"\$$var\"
-	  new_libs=
-	  for deplib in $tmp_libs; do
-	    # FIXME: Pedantically, this is the right thing to do, so
-	    #        that some nasty dependency loop isn't accidentally
-	    #        broken:
-	    #new_libs="$deplib $new_libs"
-	    # Pragmatically, this seems to cause very few problems in
-	    # practice:
-	    case $deplib in
-	    -L*) new_libs="$deplib $new_libs" ;;
-	    -R*) ;;
-	    *)
-	      # And here is the reason: when a library appears more
-	      # than once as an explicit dependence of a library, or
-	      # is implicitly linked in more than once by the
-	      # compiler, it is considered special, and multiple
-	      # occurrences thereof are not removed.  Compare this
-	      # with having the same library being listed as a
-	      # dependency of multiple other libraries: in this case,
-	      # we know (pedantically, we assume) the library does not
-	      # need to be listed more than once, so we keep only the
-	      # last copy.  This is not always right, but it is rare
-	      # enough that we require users that really mean to play
-	      # such unportable linking tricks to link the library
-	      # using -Wl,-lname, so that libtool does not consider it
-	      # for duplicate removal.
-	      case " $specialdeplibs " in
-	      *" $deplib "*) new_libs="$deplib $new_libs" ;;
-	      *)
-		case " $new_libs " in
-		*" $deplib "*) ;;
-		*) new_libs="$deplib $new_libs" ;;
-		esac
-		;;
-	      esac
-	      ;;
-	    esac
-	  done
-	  tmp_libs=
-	  for deplib in $new_libs; do
-	    case $deplib in
-	    -L*)
-	      case " $tmp_libs " in
-	      *" $deplib "*) ;;
-	      *) func_append tmp_libs " $deplib" ;;
-	      esac
-	      ;;
-	    *) func_append tmp_libs " $deplib" ;;
-	    esac
-	  done
-	  eval $var=\"$tmp_libs\"
-	done # for var
-      fi
-      # Last step: remove runtime libs from dependency_libs
-      # (they stay in deplibs)
-      tmp_libs=
-      for i in $dependency_libs ; do
-	case " $predeps $postdeps $compiler_lib_search_path " in
-	*" $i "*)
-	  i=""
-	  ;;
-	esac
-	if test -n "$i" ; then
-	  func_append tmp_libs " $i"
-	fi
-      done
-      dependency_libs=$tmp_libs
-    done # for pass
-    if test "$linkmode" = prog; then
-      dlfiles="$newdlfiles"
-    fi
-    if test "$linkmode" = prog || test "$linkmode" = lib; then
-      dlprefiles="$newdlprefiles"
-    fi
-
-    case $linkmode in
-    oldlib)
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
-	func_warning "\`-dlopen' is ignored for archives"
-      fi
-
-      case " $deplibs" in
-      *\ -l* | *\ -L*)
-	func_warning "\`-l' and \`-L' are ignored for archives" ;;
-      esac
-
-      test -n "$rpath" && \
-	func_warning "\`-rpath' is ignored for archives"
-
-      test -n "$xrpath" && \
-	func_warning "\`-R' is ignored for archives"
-
-      test -n "$vinfo" && \
-	func_warning "\`-version-info/-version-number' is ignored for archives"
-
-      test -n "$release" && \
-	func_warning "\`-release' is ignored for archives"
-
-      test -n "$export_symbols$export_symbols_regex" && \
-	func_warning "\`-export-symbols' is ignored for archives"
-
-      # Now set the variables for building old libraries.
-      build_libtool_libs=no
-      oldlibs="$output"
-      func_append objs "$old_deplibs"
-      ;;
-
-    lib)
-      # Make sure we only generate libraries of the form `libNAME.la'.
-      case $outputname in
-      lib*)
-	func_stripname 'lib' '.la' "$outputname"
-	name=$func_stripname_result
-	eval shared_ext=\"$shrext_cmds\"
-	eval libname=\"$libname_spec\"
-	;;
-      *)
-	test "$module" = no && \
-	  func_fatal_help "libtool library \`$output' must begin with \`lib'"
-
-	if test "$need_lib_prefix" != no; then
-	  # Add the "lib" prefix for modules if required
-	  func_stripname '' '.la' "$outputname"
-	  name=$func_stripname_result
-	  eval shared_ext=\"$shrext_cmds\"
-	  eval libname=\"$libname_spec\"
-	else
-	  func_stripname '' '.la' "$outputname"
-	  libname=$func_stripname_result
-	fi
-	;;
-      esac
-
-      if test -n "$objs"; then
-	if test "$deplibs_check_method" != pass_all; then
-	  func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs"
-	else
-	  echo
-	  $ECHO "*** Warning: Linking the shared library $output against the non-libtool"
-	  $ECHO "*** objects $objs is not portable!"
-	  func_append libobjs " $objs"
-	fi
-      fi
-
-      test "$dlself" != no && \
-	func_warning "\`-dlopen self' is ignored for libtool libraries"
-
-      set dummy $rpath
-      shift
-      test "$#" -gt 1 && \
-	func_warning "ignoring multiple \`-rpath's for a libtool library"
-
-      install_libdir="$1"
-
-      oldlibs=
-      if test -z "$rpath"; then
-	if test "$build_libtool_libs" = yes; then
-	  # Building a libtool convenience library.
-	  # Some compilers have problems with a `.al' extension so
-	  # convenience libraries should have the same extension an
-	  # archive normally would.
-	  oldlibs="$output_objdir/$libname.$libext $oldlibs"
-	  build_libtool_libs=convenience
-	  build_old_libs=yes
-	fi
-
-	test -n "$vinfo" && \
-	  func_warning "\`-version-info/-version-number' is ignored for convenience libraries"
-
-	test -n "$release" && \
-	  func_warning "\`-release' is ignored for convenience libraries"
-      else
-
-	# Parse the version information argument.
-	save_ifs="$IFS"; IFS=':'
-	set dummy $vinfo 0 0 0
-	shift
-	IFS="$save_ifs"
-
-	test -n "$7" && \
-	  func_fatal_help "too many parameters to \`-version-info'"
-
-	# convert absolute version numbers to libtool ages
-	# this retains compatibility with .la files and attempts
-	# to make the code below a bit more comprehensible
-
-	case $vinfo_number in
-	yes)
-	  number_major="$1"
-	  number_minor="$2"
-	  number_revision="$3"
-	  #
-	  # There are really only two kinds -- those that
-	  # use the current revision as the major version
-	  # and those that subtract age and use age as
-	  # a minor version.  But, then there is irix
-	  # which has an extra 1 added just for fun
-	  #
-	  case $version_type in
-	  # correct linux to gnu/linux during the next big refactor
-	  darwin|linux|osf|windows|none)
-	    func_arith $number_major + $number_minor
-	    current=$func_arith_result
-	    age="$number_minor"
-	    revision="$number_revision"
-	    ;;
-	  freebsd-aout|freebsd-elf|qnx|sunos)
-	    current="$number_major"
-	    revision="$number_minor"
-	    age="0"
-	    ;;
-	  irix|nonstopux)
-	    func_arith $number_major + $number_minor
-	    current=$func_arith_result
-	    age="$number_minor"
-	    revision="$number_minor"
-	    lt_irix_increment=no
-	    ;;
-	  *)
-	    func_fatal_configuration "$modename: unknown library version type \`$version_type'"
-	    ;;
-	  esac
-	  ;;
-	no)
-	  current="$1"
-	  revision="$2"
-	  age="$3"
-	  ;;
-	esac
-
-	# Check that each of the things are valid numbers.
-	case $current in
-	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
-	*)
-	  func_error "CURRENT \`$current' must be a nonnegative integer"
-	  func_fatal_error "\`$vinfo' is not valid version information"
-	  ;;
-	esac
-
-	case $revision in
-	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
-	*)
-	  func_error "REVISION \`$revision' must be a nonnegative integer"
-	  func_fatal_error "\`$vinfo' is not valid version information"
-	  ;;
-	esac
-
-	case $age in
-	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;
-	*)
-	  func_error "AGE \`$age' must be a nonnegative integer"
-	  func_fatal_error "\`$vinfo' is not valid version information"
-	  ;;
-	esac
-
-	if test "$age" -gt "$current"; then
-	  func_error "AGE \`$age' is greater than the current interface number \`$current'"
-	  func_fatal_error "\`$vinfo' is not valid version information"
-	fi
-
-	# Calculate the version variables.
-	major=
-	versuffix=
-	verstring=
-	case $version_type in
-	none) ;;
-
-	darwin)
-	  # Like Linux, but with the current version available in
-	  # verstring for coding it into the library header
-	  func_arith $current - $age
-	  major=.$func_arith_result
-	  versuffix="$major.$age.$revision"
-	  # Darwin ld doesn't like 0 for these options...
-	  func_arith $current + 1
-	  minor_current=$func_arith_result
-	  xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision"
-	  verstring="-compatibility_version $minor_current -current_version $minor_current.$revision"
-	  ;;
-
-	freebsd-aout)
-	  major=".$current"
-	  versuffix=".$current.$revision";
-	  ;;
-
-	freebsd-elf)
-	  major=".$current"
-	  versuffix=".$current"
-	  ;;
-
-	irix | nonstopux)
-	  if test "X$lt_irix_increment" = "Xno"; then
-	    func_arith $current - $age
-	  else
-	    func_arith $current - $age + 1
-	  fi
-	  major=$func_arith_result
-
-	  case $version_type in
-	    nonstopux) verstring_prefix=nonstopux ;;
-	    *)         verstring_prefix=sgi ;;
-	  esac
-	  verstring="$verstring_prefix$major.$revision"
-
-	  # Add in all the interfaces that we are compatible with.
-	  loop=$revision
-	  while test "$loop" -ne 0; do
-	    func_arith $revision - $loop
-	    iface=$func_arith_result
-	    func_arith $loop - 1
-	    loop=$func_arith_result
-	    verstring="$verstring_prefix$major.$iface:$verstring"
-	  done
-
-	  # Before this point, $major must not contain `.'.
-	  major=.$major
-	  versuffix="$major.$revision"
-	  ;;
-
-	linux) # correct to gnu/linux during the next big refactor
-	  func_arith $current - $age
-	  major=.$func_arith_result
-	  versuffix="$major.$age.$revision"
-	  ;;
-
-	osf)
-	  func_arith $current - $age
-	  major=.$func_arith_result
-	  versuffix=".$current.$age.$revision"
-	  verstring="$current.$age.$revision"
-
-	  # Add in all the interfaces that we are compatible with.
-	  loop=$age
-	  while test "$loop" -ne 0; do
-	    func_arith $current - $loop
-	    iface=$func_arith_result
-	    func_arith $loop - 1
-	    loop=$func_arith_result
-	    verstring="$verstring:${iface}.0"
-	  done
-
-	  # Make executables depend on our current version.
-	  func_append verstring ":${current}.0"
-	  ;;
-
-	qnx)
-	  major=".$current"
-	  versuffix=".$current"
-	  ;;
-
-	sunos)
-	  major=".$current"
-	  versuffix=".$current.$revision"
-	  ;;
-
-	windows)
-	  # Use '-' rather than '.', since we only want one
-	  # extension on DOS 8.3 filesystems.
-	  func_arith $current - $age
-	  major=$func_arith_result
-	  versuffix="-$major"
-	  ;;
-
-	*)
-	  func_fatal_configuration "unknown library version type \`$version_type'"
-	  ;;
-	esac
-
-	# Clear the version info if we defaulted, and they specified a release.
-	if test -z "$vinfo" && test -n "$release"; then
-	  major=
-	  case $version_type in
-	  darwin)
-	    # we can't check for "0.0" in archive_cmds due to quoting
-	    # problems, so we reset it completely
-	    verstring=
-	    ;;
-	  *)
-	    verstring="0.0"
-	    ;;
-	  esac
-	  if test "$need_version" = no; then
-	    versuffix=
-	  else
-	    versuffix=".0.0"
-	  fi
-	fi
-
-	# Remove version info from name if versioning should be avoided
-	if test "$avoid_version" = yes && test "$need_version" = no; then
-	  major=
-	  versuffix=
-	  verstring=""
-	fi
-
-	# Check to see if the archive will have undefined symbols.
-	if test "$allow_undefined" = yes; then
-	  if test "$allow_undefined_flag" = unsupported; then
-	    func_warning "undefined symbols not allowed in $host shared libraries"
-	    build_libtool_libs=no
-	    build_old_libs=yes
-	  fi
-	else
-	  # Don't allow undefined symbols.
-	  allow_undefined_flag="$no_undefined_flag"
-	fi
-
-      fi
-
-      func_generate_dlsyms "$libname" "$libname" "yes"
-      func_append libobjs " $symfileobj"
-      test "X$libobjs" = "X " && libobjs=
-
-      if test "$opt_mode" != relink; then
-	# Remove our outputs, but don't remove object files since they
-	# may have been created when compiling PIC objects.
-	removelist=
-	tempremovelist=`$ECHO "$output_objdir/*"`
-	for p in $tempremovelist; do
-	  case $p in
-	    *.$objext | *.gcno)
-	       ;;
-	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)
-	       if test "X$precious_files_regex" != "X"; then
-		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
-		 then
-		   continue
-		 fi
-	       fi
-	       func_append removelist " $p"
-	       ;;
-	    *) ;;
-	  esac
-	done
-	test -n "$removelist" && \
-	  func_show_eval "${RM}r \$removelist"
-      fi
-
-      # Now set the variables for building old libraries.
-      if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then
-	func_append oldlibs " $output_objdir/$libname.$libext"
-
-	# Transform .lo files to .o files.
-	oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP`
-      fi
-
-      # Eliminate all temporary directories.
-      #for path in $notinst_path; do
-      #	lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"`
-      #	deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
-      #	dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"`
-      #done
-
-      if test -n "$xrpath"; then
-	# If the user specified any rpath flags, then add them.
-	temp_xrpath=
-	for libdir in $xrpath; do
-	  func_replace_sysroot "$libdir"
-	  func_append temp_xrpath " -R$func_replace_sysroot_result"
-	  case "$finalize_rpath " in
-	  *" $libdir "*) ;;
-	  *) func_append finalize_rpath " $libdir" ;;
-	  esac
-	done
-	if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then
-	  dependency_libs="$temp_xrpath $dependency_libs"
-	fi
-      fi
-
-      # Make sure dlfiles contains only unique files that won't be dlpreopened
-      old_dlfiles="$dlfiles"
-      dlfiles=
-      for lib in $old_dlfiles; do
-	case " $dlprefiles $dlfiles " in
-	*" $lib "*) ;;
-	*) func_append dlfiles " $lib" ;;
-	esac
-      done
-
-      # Make sure dlprefiles contains only unique files
-      old_dlprefiles="$dlprefiles"
-      dlprefiles=
-      for lib in $old_dlprefiles; do
-	case "$dlprefiles " in
-	*" $lib "*) ;;
-	*) func_append dlprefiles " $lib" ;;
-	esac
-      done
-
-      if test "$build_libtool_libs" = yes; then
-	if test -n "$rpath"; then
-	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)
-	    # these systems don't actually have a c library (as such)!
-	    ;;
-	  *-*-rhapsody* | *-*-darwin1.[012])
-	    # Rhapsody C library is in the System framework
-	    func_append deplibs " System.ltframework"
-	    ;;
-	  *-*-netbsd*)
-	    # Don't link with libc until the a.out ld.so is fixed.
-	    ;;
-	  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)
-	    # Do not include libc due to us having libc/libc_r.
-	    ;;
-	  *-*-sco3.2v5* | *-*-sco5v6*)
-	    # Causes problems with __ctype
-	    ;;
-	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
-	    # Compiler inserts libc in the correct place for threads to work
-	    ;;
-	  *)
-	    # Add libc to deplibs on all other systems if necessary.
-	    if test "$build_libtool_need_lc" = "yes"; then
-	      func_append deplibs " -lc"
-	    fi
-	    ;;
-	  esac
-	fi
-
-	# Transform deplibs into only deplibs that can be linked in shared.
-	name_save=$name
-	libname_save=$libname
-	release_save=$release
-	versuffix_save=$versuffix
-	major_save=$major
-	# I'm not sure if I'm treating the release correctly.  I think
-	# release should show up in the -l (ie -lgmp5) so we don't want to
-	# add it in twice.  Is that correct?
-	release=""
-	versuffix=""
-	major=""
-	newdeplibs=
-	droppeddeps=no
-	case $deplibs_check_method in
-	pass_all)
-	  # Don't check for shared/static.  Everything works.
-	  # This might be a little naive.  We might want to check
-	  # whether the library exists or not.  But this is on
-	  # osf3 & osf4 and I'm not really sure... Just
-	  # implementing what was already the behavior.
-	  newdeplibs=$deplibs
-	  ;;
-	test_compile)
-	  # This code stresses the "libraries are programs" paradigm to its
-	  # limits. Maybe even breaks it.  We compile a program, linking it
-	  # against the deplibs as a proxy for the library.  Then we can check
-	  # whether they linked in statically or dynamically with ldd.
-	  $opt_dry_run || $RM conftest.c
-	  cat > conftest.c <<EOF
-	  int main() { return 0; }
-EOF
-	  $opt_dry_run || $RM conftest
-	  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
-	    ldd_output=`ldd conftest`
-	    for i in $deplibs; do
-	      case $i in
-	      -l*)
-		func_stripname -l '' "$i"
-		name=$func_stripname_result
-		if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-		  case " $predeps $postdeps " in
-		  *" $i "*)
-		    func_append newdeplibs " $i"
-		    i=""
-		    ;;
-		  esac
-		fi
-		if test -n "$i" ; then
-		  libname=`eval "\\$ECHO \"$libname_spec\""`
-		  deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
-		  set dummy $deplib_matches; shift
-		  deplib_match=$1
-		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		    func_append newdeplibs " $i"
-		  else
-		    droppeddeps=yes
-		    echo
-		    $ECHO "*** Warning: dynamic linker does not accept needed library $i."
-		    echo "*** I have the capability to make that library automatically link in when"
-		    echo "*** you link to this library.  But I can only do this if you have a"
-		    echo "*** shared version of the library, which I believe you do not have"
-		    echo "*** because a test_compile did reveal that the linker did not use it for"
-		    echo "*** its dynamic dependency list that programs get resolved with at runtime."
-		  fi
-		fi
-		;;
-	      *)
-		func_append newdeplibs " $i"
-		;;
-	      esac
-	    done
-	  else
-	    # Error occurred in the first compile.  Let's try to salvage
-	    # the situation: Compile a separate program for each library.
-	    for i in $deplibs; do
-	      case $i in
-	      -l*)
-		func_stripname -l '' "$i"
-		name=$func_stripname_result
-		$opt_dry_run || $RM conftest
-		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
-		  ldd_output=`ldd conftest`
-		  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-		    case " $predeps $postdeps " in
-		    *" $i "*)
-		      func_append newdeplibs " $i"
-		      i=""
-		      ;;
-		    esac
-		  fi
-		  if test -n "$i" ; then
-		    libname=`eval "\\$ECHO \"$libname_spec\""`
-		    deplib_matches=`eval "\\$ECHO \"$library_names_spec\""`
-		    set dummy $deplib_matches; shift
-		    deplib_match=$1
-		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		      func_append newdeplibs " $i"
-		    else
-		      droppeddeps=yes
-		      echo
-		      $ECHO "*** Warning: dynamic linker does not accept needed library $i."
-		      echo "*** I have the capability to make that library automatically link in when"
-		      echo "*** you link to this library.  But I can only do this if you have a"
-		      echo "*** shared version of the library, which you do not appear to have"
-		      echo "*** because a test_compile did reveal that the linker did not use this one"
-		      echo "*** as a dynamic dependency that programs can get resolved with at runtime."
-		    fi
-		  fi
-		else
-		  droppeddeps=yes
-		  echo
-		  $ECHO "*** Warning!  Library $i is needed by this library but I was not able to"
-		  echo "*** make it link in!  You will probably need to install it or some"
-		  echo "*** library that it depends on before this library will be fully"
-		  echo "*** functional.  Installing it before continuing would be even better."
-		fi
-		;;
-	      *)
-		func_append newdeplibs " $i"
-		;;
-	      esac
-	    done
-	  fi
-	  ;;
-	file_magic*)
-	  set dummy $deplibs_check_method; shift
-	  file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
-	  for a_deplib in $deplibs; do
-	    case $a_deplib in
-	    -l*)
-	      func_stripname -l '' "$a_deplib"
-	      name=$func_stripname_result
-	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-		case " $predeps $postdeps " in
-		*" $a_deplib "*)
-		  func_append newdeplibs " $a_deplib"
-		  a_deplib=""
-		  ;;
-		esac
-	      fi
-	      if test -n "$a_deplib" ; then
-		libname=`eval "\\$ECHO \"$libname_spec\""`
-		if test -n "$file_magic_glob"; then
-		  libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob`
-		else
-		  libnameglob=$libname
-		fi
-		test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob`
-		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
-		  if test "$want_nocaseglob" = yes; then
-		    shopt -s nocaseglob
-		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
-		    $nocaseglob
-		  else
-		    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`
-		  fi
-		  for potent_lib in $potential_libs; do
-		      # Follow soft links.
-		      if ls -lLd "$potent_lib" 2>/dev/null |
-			 $GREP " -> " >/dev/null; then
-			continue
-		      fi
-		      # The statement above tries to avoid entering an
-		      # endless loop below, in case of cyclic links.
-		      # We might still enter an endless loop, since a link
-		      # loop can be closed while we follow links,
-		      # but so what?
-		      potlib="$potent_lib"
-		      while test -h "$potlib" 2>/dev/null; do
-			potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`
-			case $potliblink in
-			[\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";;
-			*) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
-			esac
-		      done
-		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
-			 $SED -e 10q |
-			 $EGREP "$file_magic_regex" > /dev/null; then
-			func_append newdeplibs " $a_deplib"
-			a_deplib=""
-			break 2
-		      fi
-		  done
-		done
-	      fi
-	      if test -n "$a_deplib" ; then
-		droppeddeps=yes
-		echo
-		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
-		echo "*** I have the capability to make that library automatically link in when"
-		echo "*** you link to this library.  But I can only do this if you have a"
-		echo "*** shared version of the library, which you do not appear to have"
-		echo "*** because I did check the linker path looking for a file starting"
-		if test -z "$potlib" ; then
-		  $ECHO "*** with $libname but no candidates were found. (...for file magic test)"
-		else
-		  $ECHO "*** with $libname and none of the candidates passed a file format test"
-		  $ECHO "*** using a file magic. Last file checked: $potlib"
-		fi
-	      fi
-	      ;;
-	    *)
-	      # Add a -L argument.
-	      func_append newdeplibs " $a_deplib"
-	      ;;
-	    esac
-	  done # Gone through all deplibs.
-	  ;;
-	match_pattern*)
-	  set dummy $deplibs_check_method; shift
-	  match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"`
-	  for a_deplib in $deplibs; do
-	    case $a_deplib in
-	    -l*)
-	      func_stripname -l '' "$a_deplib"
-	      name=$func_stripname_result
-	      if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-		case " $predeps $postdeps " in
-		*" $a_deplib "*)
-		  func_append newdeplibs " $a_deplib"
-		  a_deplib=""
-		  ;;
-		esac
-	      fi
-	      if test -n "$a_deplib" ; then
-		libname=`eval "\\$ECHO \"$libname_spec\""`
-		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
-		  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`
-		  for potent_lib in $potential_libs; do
-		    potlib="$potent_lib" # see symlink-check above in file_magic test
-		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
-		       $EGREP "$match_pattern_regex" > /dev/null; then
-		      func_append newdeplibs " $a_deplib"
-		      a_deplib=""
-		      break 2
-		    fi
-		  done
-		done
-	      fi
-	      if test -n "$a_deplib" ; then
-		droppeddeps=yes
-		echo
-		$ECHO "*** Warning: linker path does not have real file for library $a_deplib."
-		echo "*** I have the capability to make that library automatically link in when"
-		echo "*** you link to this library.  But I can only do this if you have a"
-		echo "*** shared version of the library, which you do not appear to have"
-		echo "*** because I did check the linker path looking for a file starting"
-		if test -z "$potlib" ; then
-		  $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)"
-		else
-		  $ECHO "*** with $libname and none of the candidates passed a file format test"
-		  $ECHO "*** using a regex pattern. Last file checked: $potlib"
-		fi
-	      fi
-	      ;;
-	    *)
-	      # Add a -L argument.
-	      func_append newdeplibs " $a_deplib"
-	      ;;
-	    esac
-	  done # Gone through all deplibs.
-	  ;;
-	none | unknown | *)
-	  newdeplibs=""
-	  tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
-	  if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then
-	    for i in $predeps $postdeps ; do
-	      # can't use Xsed below, because $i might contain '/'
-	      tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
-	    done
-	  fi
-	  case $tmp_deplibs in
-	  *[!\	\ ]*)
-	    echo
-	    if test "X$deplibs_check_method" = "Xnone"; then
-	      echo "*** Warning: inter-library dependencies are not supported in this platform."
-	    else
-	      echo "*** Warning: inter-library dependencies are not known to be supported."
-	    fi
-	    echo "*** All declared inter-library dependencies are being dropped."
-	    droppeddeps=yes
-	    ;;
-	  esac
-	  ;;
-	esac
-	versuffix=$versuffix_save
-	major=$major_save
-	release=$release_save
-	libname=$libname_save
-	name=$name_save
-
-	case $host in
-	*-*-rhapsody* | *-*-darwin1.[012])
-	  # On Rhapsody replace the C library with the System framework
-	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'`
-	  ;;
-	esac
-
-	if test "$droppeddeps" = yes; then
-	  if test "$module" = yes; then
-	    echo
-	    echo "*** Warning: libtool could not satisfy all declared inter-library"
-	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will create"
-	    echo "*** a static module, that should work as long as the dlopening"
-	    echo "*** application is linked with the -dlopen flag."
-	    if test -z "$global_symbol_pipe"; then
-	      echo
-	      echo "*** However, this would only work if libtool was able to extract symbol"
-	      echo "*** lists from a program, using \`nm' or equivalent, but libtool could"
-	      echo "*** not find such a program.  So, this module is probably useless."
-	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
-	    fi
-	    if test "$build_old_libs" = no; then
-	      oldlibs="$output_objdir/$libname.$libext"
-	      build_libtool_libs=module
-	      build_old_libs=yes
-	    else
-	      build_libtool_libs=no
-	    fi
-	  else
-	    echo "*** The inter-library dependencies that have been dropped here will be"
-	    echo "*** automatically added whenever a program is linked with this library"
-	    echo "*** or is declared to -dlopen it."
-
-	    if test "$allow_undefined" = no; then
-	      echo
-	      echo "*** Since this library must not contain undefined symbols,"
-	      echo "*** because either the platform does not support them or"
-	      echo "*** it was explicitly requested with -no-undefined,"
-	      echo "*** libtool will only create a static version of it."
-	      if test "$build_old_libs" = no; then
-		oldlibs="$output_objdir/$libname.$libext"
-		build_libtool_libs=module
-		build_old_libs=yes
-	      else
-		build_libtool_libs=no
-	      fi
-	    fi
-	  fi
-	fi
-	# Done checking deplibs!
-	deplibs=$newdeplibs
-      fi
-      # Time to change all our "foo.ltframework" stuff back to "-framework foo"
-      case $host in
-	*-*-darwin*)
-	  newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	  ;;
-      esac
-
-      # move library search paths that coincide with paths to not yet
-      # installed libraries to the beginning of the library search list
-      new_libs=
-      for path in $notinst_path; do
-	case " $new_libs " in
-	*" -L$path/$objdir "*) ;;
-	*)
-	  case " $deplibs " in
-	  *" -L$path/$objdir "*)
-	    func_append new_libs " -L$path/$objdir" ;;
-	  esac
-	  ;;
-	esac
-      done
-      for deplib in $deplibs; do
-	case $deplib in
-	-L*)
-	  case " $new_libs " in
-	  *" $deplib "*) ;;
-	  *) func_append new_libs " $deplib" ;;
-	  esac
-	  ;;
-	*) func_append new_libs " $deplib" ;;
-	esac
-      done
-      deplibs="$new_libs"
-
-      # All the library-specific variables (install_libdir is set above).
-      library_names=
-      old_library=
-      dlname=
-
-      # Test again, we may have decided not to build it any more
-      if test "$build_libtool_libs" = yes; then
-	# Remove ${wl} instances when linking with ld.
-	# FIXME: should test the right _cmds variable.
-	case $archive_cmds in
-	  *\$LD\ *) wl= ;;
-        esac
-	if test "$hardcode_into_libs" = yes; then
-	  # Hardcode the library paths
-	  hardcode_libdirs=
-	  dep_rpath=
-	  rpath="$finalize_rpath"
-	  test "$opt_mode" != relink && rpath="$compile_rpath$rpath"
-	  for libdir in $rpath; do
-	    if test -n "$hardcode_libdir_flag_spec"; then
-	      if test -n "$hardcode_libdir_separator"; then
-		func_replace_sysroot "$libdir"
-		libdir=$func_replace_sysroot_result
-		if test -z "$hardcode_libdirs"; then
-		  hardcode_libdirs="$libdir"
-		else
-		  # Just accumulate the unique libdirs.
-		  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
-		  *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
-		    ;;
-		  *)
-		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
-		    ;;
-		  esac
-		fi
-	      else
-		eval flag=\"$hardcode_libdir_flag_spec\"
-		func_append dep_rpath " $flag"
-	      fi
-	    elif test -n "$runpath_var"; then
-	      case "$perm_rpath " in
-	      *" $libdir "*) ;;
-	      *) func_append perm_rpath " $libdir" ;;
-	      esac
-	    fi
-	  done
-	  # Substitute the hardcoded libdirs into the rpath.
-	  if test -n "$hardcode_libdir_separator" &&
-	     test -n "$hardcode_libdirs"; then
-	    libdir="$hardcode_libdirs"
-	    eval "dep_rpath=\"$hardcode_libdir_flag_spec\""
-	  fi
-	  if test -n "$runpath_var" && test -n "$perm_rpath"; then
-	    # We should set the runpath_var.
-	    rpath=
-	    for dir in $perm_rpath; do
-	      func_append rpath "$dir:"
-	    done
-	    eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var"
-	  fi
-	  test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs"
-	fi
-
-	shlibpath="$finalize_shlibpath"
-	test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath"
-	if test -n "$shlibpath"; then
-	  eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var"
-	fi
-
-	# Get the real and link names of the library.
-	eval shared_ext=\"$shrext_cmds\"
-	eval library_names=\"$library_names_spec\"
-	set dummy $library_names
-	shift
-	realname="$1"
-	shift
-
-	if test -n "$soname_spec"; then
-	  eval soname=\"$soname_spec\"
-	else
-	  soname="$realname"
-	fi
-	if test -z "$dlname"; then
-	  dlname=$soname
-	fi
-
-	lib="$output_objdir/$realname"
-	linknames=
-	for link
-	do
-	  func_append linknames " $link"
-	done
-
-	# Use standard objects if they are pic
-	test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP`
-	test "X$libobjs" = "X " && libobjs=
-
-	delfiles=
-	if test -n "$export_symbols" && test -n "$include_expsyms"; then
-	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
-	  export_symbols="$output_objdir/$libname.uexp"
-	  func_append delfiles " $export_symbols"
-	fi
-
-	orig_export_symbols=
-	case $host_os in
-	cygwin* | mingw* | cegcc*)
-	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
-	    # exporting using user supplied symfile
-	    if test "x`$SED 1q $export_symbols`" != xEXPORTS; then
-	      # and it's NOT already a .def file. Must figure out
-	      # which of the given symbols are data symbols and tag
-	      # them as such. So, trigger use of export_symbols_cmds.
-	      # export_symbols gets reassigned inside the "prepare
-	      # the list of exported symbols" if statement, so the
-	      # include_expsyms logic still works.
-	      orig_export_symbols="$export_symbols"
-	      export_symbols=
-	      always_export_symbols=yes
-	    fi
-	  fi
-	  ;;
-	esac
-
-	# Prepare the list of exported symbols
-	if test -z "$export_symbols"; then
-	  if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then
-	    func_verbose "generating symbol list for \`$libname.la'"
-	    export_symbols="$output_objdir/$libname.exp"
-	    $opt_dry_run || $RM $export_symbols
-	    cmds=$export_symbols_cmds
-	    save_ifs="$IFS"; IFS='~'
-	    for cmd1 in $cmds; do
-	      IFS="$save_ifs"
-	      # Take the normal branch if the nm_file_list_spec branch
-	      # doesn't work or if tool conversion is not needed.
-	      case $nm_file_list_spec~$to_tool_file_cmd in
-		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
-		  try_normal_branch=yes
-		  eval cmd=\"$cmd1\"
-		  func_len " $cmd"
-		  len=$func_len_result
-		  ;;
-		*)
-		  try_normal_branch=no
-		  ;;
-	      esac
-	      if test "$try_normal_branch" = yes \
-		 && { test "$len" -lt "$max_cmd_len" \
-		      || test "$max_cmd_len" -le -1; }
-	      then
-		func_show_eval "$cmd" 'exit $?'
-		skipped_export=false
-	      elif test -n "$nm_file_list_spec"; then
-		func_basename "$output"
-		output_la=$func_basename_result
-		save_libobjs=$libobjs
-		save_output=$output
-		output=${output_objdir}/${output_la}.nm
-		func_to_tool_file "$output"
-		libobjs=$nm_file_list_spec$func_to_tool_file_result
-		func_append delfiles " $output"
-		func_verbose "creating $NM input file list: $output"
-		for obj in $save_libobjs; do
-		  func_to_tool_file "$obj"
-		  $ECHO "$func_to_tool_file_result"
-		done > "$output"
-		eval cmd=\"$cmd1\"
-		func_show_eval "$cmd" 'exit $?'
-		output=$save_output
-		libobjs=$save_libobjs
-		skipped_export=false
-	      else
-		# The command line is too long to execute in one step.
-		func_verbose "using reloadable object file for export list..."
-		skipped_export=:
-		# Break out early, otherwise skipped_export may be
-		# set to false by a later but shorter cmd.
-		break
-	      fi
-	    done
-	    IFS="$save_ifs"
-	    if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then
-	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
-	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
-	    fi
-	  fi
-	fi
-
-	if test -n "$export_symbols" && test -n "$include_expsyms"; then
-	  tmp_export_symbols="$export_symbols"
-	  test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
-	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
-	fi
-
-	if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then
-	  # The given exports_symbols file has to be filtered, so filter it.
-	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
-	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
-	  # 's' commands which not all seds can handle. GNU sed should be fine
-	  # though. Also, the filter scales superlinearly with the number of
-	  # global variables. join(1) would be nice here, but unfortunately
-	  # isn't a blessed tool.
-	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
-	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
-	  export_symbols=$output_objdir/$libname.def
-	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
-	fi
-
-	tmp_deplibs=
-	for test_deplib in $deplibs; do
-	  case " $convenience " in
-	  *" $test_deplib "*) ;;
-	  *)
-	    func_append tmp_deplibs " $test_deplib"
-	    ;;
-	  esac
-	done
-	deplibs="$tmp_deplibs"
-
-	if test -n "$convenience"; then
-	  if test -n "$whole_archive_flag_spec" &&
-	    test "$compiler_needs_object" = yes &&
-	    test -z "$libobjs"; then
-	    # extract the archives, so we have objects to list.
-	    # TODO: could optimize this to just extract one archive.
-	    whole_archive_flag_spec=
-	  fi
-	  if test -n "$whole_archive_flag_spec"; then
-	    save_libobjs=$libobjs
-	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
-	    test "X$libobjs" = "X " && libobjs=
-	  else
-	    gentop="$output_objdir/${outputname}x"
-	    func_append generated " $gentop"
-
-	    func_extract_archives $gentop $convenience
-	    func_append libobjs " $func_extract_archives_result"
-	    test "X$libobjs" = "X " && libobjs=
-	  fi
-	fi
-
-	if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then
-	  eval flag=\"$thread_safe_flag_spec\"
-	  func_append linker_flags " $flag"
-	fi
-
-	# Make a backup of the uninstalled library when relinking
-	if test "$opt_mode" = relink; then
-	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?
-	fi
-
-	# Do each of the archive commands.
-	if test "$module" = yes && test -n "$module_cmds" ; then
-	  if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
-	    eval test_cmds=\"$module_expsym_cmds\"
-	    cmds=$module_expsym_cmds
-	  else
-	    eval test_cmds=\"$module_cmds\"
-	    cmds=$module_cmds
-	  fi
-	else
-	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
-	    eval test_cmds=\"$archive_expsym_cmds\"
-	    cmds=$archive_expsym_cmds
-	  else
-	    eval test_cmds=\"$archive_cmds\"
-	    cmds=$archive_cmds
-	  fi
-	fi
-
-	if test "X$skipped_export" != "X:" &&
-	   func_len " $test_cmds" &&
-	   len=$func_len_result &&
-	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
-	  :
-	else
-	  # The command line is too long to link in one step, link piecewise
-	  # or, if using GNU ld and skipped_export is not :, use a linker
-	  # script.
-
-	  # Save the value of $output and $libobjs because we want to
-	  # use them later.  If we have whole_archive_flag_spec, we
-	  # want to use save_libobjs as it was before
-	  # whole_archive_flag_spec was expanded, because we can't
-	  # assume the linker understands whole_archive_flag_spec.
-	  # This may have to be revisited, in case too many
-	  # convenience libraries get linked in and end up exceeding
-	  # the spec.
-	  if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then
-	    save_libobjs=$libobjs
-	  fi
-	  save_output=$output
-	  func_basename "$output"
-	  output_la=$func_basename_result
-
-	  # Clear the reloadable object creation command queue and
-	  # initialize k to one.
-	  test_cmds=
-	  concat_cmds=
-	  objlist=
-	  last_robj=
-	  k=1
-
-	  if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then
-	    output=${output_objdir}/${output_la}.lnkscript
-	    func_verbose "creating GNU ld script: $output"
-	    echo 'INPUT (' > $output
-	    for obj in $save_libobjs
-	    do
-	      func_to_tool_file "$obj"
-	      $ECHO "$func_to_tool_file_result" >> $output
-	    done
-	    echo ')' >> $output
-	    func_append delfiles " $output"
-	    func_to_tool_file "$output"
-	    output=$func_to_tool_file_result
-	  elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then
-	    output=${output_objdir}/${output_la}.lnk
-	    func_verbose "creating linker input file list: $output"
-	    : > $output
-	    set x $save_libobjs
-	    shift
-	    firstobj=
-	    if test "$compiler_needs_object" = yes; then
-	      firstobj="$1 "
-	      shift
-	    fi
-	    for obj
-	    do
-	      func_to_tool_file "$obj"
-	      $ECHO "$func_to_tool_file_result" >> $output
-	    done
-	    func_append delfiles " $output"
-	    func_to_tool_file "$output"
-	    output=$firstobj\"$file_list_spec$func_to_tool_file_result\"
-	  else
-	    if test -n "$save_libobjs"; then
-	      func_verbose "creating reloadable object files..."
-	      output=$output_objdir/$output_la-${k}.$objext
-	      eval test_cmds=\"$reload_cmds\"
-	      func_len " $test_cmds"
-	      len0=$func_len_result
-	      len=$len0
-
-	      # Loop over the list of objects to be linked.
-	      for obj in $save_libobjs
-	      do
-		func_len " $obj"
-		func_arith $len + $func_len_result
-		len=$func_arith_result
-		if test "X$objlist" = X ||
-		   test "$len" -lt "$max_cmd_len"; then
-		  func_append objlist " $obj"
-		else
-		  # The command $test_cmds is almost too long, add a
-		  # command to the queue.
-		  if test "$k" -eq 1 ; then
-		    # The first file doesn't have a previous command to add.
-		    reload_objs=$objlist
-		    eval concat_cmds=\"$reload_cmds\"
-		  else
-		    # All subsequent reloadable object files will link in
-		    # the last one created.
-		    reload_objs="$objlist $last_robj"
-		    eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
-		  fi
-		  last_robj=$output_objdir/$output_la-${k}.$objext
-		  func_arith $k + 1
-		  k=$func_arith_result
-		  output=$output_objdir/$output_la-${k}.$objext
-		  objlist=" $obj"
-		  func_len " $last_robj"
-		  func_arith $len0 + $func_len_result
-		  len=$func_arith_result
-		fi
-	      done
-	      # Handle the remaining objects by creating one last
-	      # reloadable object file.  All subsequent reloadable object
-	      # files will link in the last one created.
-	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
-	      reload_objs="$objlist $last_robj"
-	      eval concat_cmds=\"\${concat_cmds}$reload_cmds\"
-	      if test -n "$last_robj"; then
-	        eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\"
-	      fi
-	      func_append delfiles " $output"
-
-	    else
-	      output=
-	    fi
-
-	    if ${skipped_export-false}; then
-	      func_verbose "generating symbol list for \`$libname.la'"
-	      export_symbols="$output_objdir/$libname.exp"
-	      $opt_dry_run || $RM $export_symbols
-	      libobjs=$output
-	      # Append the command to create the export file.
-	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
-	      eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\"
-	      if test -n "$last_robj"; then
-		eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\"
-	      fi
-	    fi
-
-	    test -n "$save_libobjs" &&
-	      func_verbose "creating a temporary reloadable object file: $output"
-
-	    # Loop through the commands generated above and execute them.
-	    save_ifs="$IFS"; IFS='~'
-	    for cmd in $concat_cmds; do
-	      IFS="$save_ifs"
-	      $opt_silent || {
-		  func_quote_for_expand "$cmd"
-		  eval "func_echo $func_quote_for_expand_result"
-	      }
-	      $opt_dry_run || eval "$cmd" || {
-		lt_exit=$?
-
-		# Restore the uninstalled library and exit
-		if test "$opt_mode" = relink; then
-		  ( cd "$output_objdir" && \
-		    $RM "${realname}T" && \
-		    $MV "${realname}U" "$realname" )
-		fi
-
-		exit $lt_exit
-	      }
-	    done
-	    IFS="$save_ifs"
-
-	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
-	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"'
-	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
-	    fi
-	  fi
-
-          if ${skipped_export-false}; then
-	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
-	      tmp_export_symbols="$export_symbols"
-	      test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols"
-	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"'
-	    fi
-
-	    if test -n "$orig_export_symbols"; then
-	      # The given exports_symbols file has to be filtered, so filter it.
-	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
-	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
-	      # 's' commands which not all seds can handle. GNU sed should be fine
-	      # though. Also, the filter scales superlinearly with the number of
-	      # global variables. join(1) would be nice here, but unfortunately
-	      # isn't a blessed tool.
-	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter
-	      func_append delfiles " $export_symbols $output_objdir/$libname.filter"
-	      export_symbols=$output_objdir/$libname.def
-	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols
-	    fi
-	  fi
-
-	  libobjs=$output
-	  # Restore the value of output.
-	  output=$save_output
-
-	  if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
-	    eval libobjs=\"\$libobjs $whole_archive_flag_spec\"
-	    test "X$libobjs" = "X " && libobjs=
-	  fi
-	  # Expand the library linking commands again to reset the
-	  # value of $libobjs for piecewise linking.
-
-	  # Do each of the archive commands.
-	  if test "$module" = yes && test -n "$module_cmds" ; then
-	    if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then
-	      cmds=$module_expsym_cmds
-	    else
-	      cmds=$module_cmds
-	    fi
-	  else
-	    if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
-	      cmds=$archive_expsym_cmds
-	    else
-	      cmds=$archive_cmds
-	    fi
-	  fi
-	fi
-
-	if test -n "$delfiles"; then
-	  # Append the command to remove temporary files to $cmds.
-	  eval cmds=\"\$cmds~\$RM $delfiles\"
-	fi
-
-	# Add any objects from preloaded convenience libraries
-	if test -n "$dlprefiles"; then
-	  gentop="$output_objdir/${outputname}x"
-	  func_append generated " $gentop"
-
-	  func_extract_archives $gentop $dlprefiles
-	  func_append libobjs " $func_extract_archives_result"
-	  test "X$libobjs" = "X " && libobjs=
-	fi
-
-	save_ifs="$IFS"; IFS='~'
-	for cmd in $cmds; do
-	  IFS="$save_ifs"
-	  eval cmd=\"$cmd\"
-	  $opt_silent || {
-	    func_quote_for_expand "$cmd"
-	    eval "func_echo $func_quote_for_expand_result"
-	  }
-	  $opt_dry_run || eval "$cmd" || {
-	    lt_exit=$?
-
-	    # Restore the uninstalled library and exit
-	    if test "$opt_mode" = relink; then
-	      ( cd "$output_objdir" && \
-	        $RM "${realname}T" && \
-		$MV "${realname}U" "$realname" )
-	    fi
-
-	    exit $lt_exit
-	  }
-	done
-	IFS="$save_ifs"
-
-	# Restore the uninstalled library and exit
-	if test "$opt_mode" = relink; then
-	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?
-
-	  if test -n "$convenience"; then
-	    if test -z "$whole_archive_flag_spec"; then
-	      func_show_eval '${RM}r "$gentop"'
-	    fi
-	  fi
-
-	  exit $EXIT_SUCCESS
-	fi
-
-	# Create links to the real library.
-	for linkname in $linknames; do
-	  if test "$realname" != "$linkname"; then
-	    func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?'
-	  fi
-	done
-
-	# If -module or -export-dynamic was specified, set the dlname.
-	if test "$module" = yes || test "$export_dynamic" = yes; then
-	  # On all known operating systems, these are identical.
-	  dlname="$soname"
-	fi
-      fi
-      ;;
-
-    obj)
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then
-	func_warning "\`-dlopen' is ignored for objects"
-      fi
-
-      case " $deplibs" in
-      *\ -l* | *\ -L*)
-	func_warning "\`-l' and \`-L' are ignored for objects" ;;
-      esac
-
-      test -n "$rpath" && \
-	func_warning "\`-rpath' is ignored for objects"
-
-      test -n "$xrpath" && \
-	func_warning "\`-R' is ignored for objects"
-
-      test -n "$vinfo" && \
-	func_warning "\`-version-info' is ignored for objects"
-
-      test -n "$release" && \
-	func_warning "\`-release' is ignored for objects"
-
-      case $output in
-      *.lo)
-	test -n "$objs$old_deplibs" && \
-	  func_fatal_error "cannot build library object \`$output' from non-libtool objects"
-
-	libobj=$output
-	func_lo2o "$libobj"
-	obj=$func_lo2o_result
-	;;
-      *)
-	libobj=
-	obj="$output"
-	;;
-      esac
-
-      # Delete the old objects.
-      $opt_dry_run || $RM $obj $libobj
-
-      # Objects from convenience libraries.  This assumes
-      # single-version convenience libraries.  Whenever we create
-      # different ones for PIC/non-PIC, this we'll have to duplicate
-      # the extraction.
-      reload_conv_objs=
-      gentop=
-      # reload_cmds runs $LD directly, so let us get rid of
-      # -Wl from whole_archive_flag_spec and hope we can get by with
-      # turning comma into space..
-      wl=
-
-      if test -n "$convenience"; then
-	if test -n "$whole_archive_flag_spec"; then
-	  eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\"
-	  reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'`
-	else
-	  gentop="$output_objdir/${obj}x"
-	  func_append generated " $gentop"
-
-	  func_extract_archives $gentop $convenience
-	  reload_conv_objs="$reload_objs $func_extract_archives_result"
-	fi
-      fi
-
-      # If we're not building shared, we need to use non_pic_objs
-      test "$build_libtool_libs" != yes && libobjs="$non_pic_objects"
-
-      # Create the old-style object.
-      reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test
-
-      output="$obj"
-      func_execute_cmds "$reload_cmds" 'exit $?'
-
-      # Exit if we aren't doing a library object file.
-      if test -z "$libobj"; then
-	if test -n "$gentop"; then
-	  func_show_eval '${RM}r "$gentop"'
-	fi
-
-	exit $EXIT_SUCCESS
-      fi
-
-      if test "$build_libtool_libs" != yes; then
-	if test -n "$gentop"; then
-	  func_show_eval '${RM}r "$gentop"'
-	fi
-
-	# Create an invalid libtool object if no PIC, so that we don't
-	# accidentally link it into a program.
-	# $show "echo timestamp > $libobj"
-	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
-	exit $EXIT_SUCCESS
-      fi
-
-      if test -n "$pic_flag" || test "$pic_mode" != default; then
-	# Only do commands if we really have different PIC objects.
-	reload_objs="$libobjs $reload_conv_objs"
-	output="$libobj"
-	func_execute_cmds "$reload_cmds" 'exit $?'
-      fi
-
-      if test -n "$gentop"; then
-	func_show_eval '${RM}r "$gentop"'
-      fi
-
-      exit $EXIT_SUCCESS
-      ;;
-
-    prog)
-      case $host in
-	*cygwin*) func_stripname '' '.exe' "$output"
-	          output=$func_stripname_result.exe;;
-      esac
-      test -n "$vinfo" && \
-	func_warning "\`-version-info' is ignored for programs"
-
-      test -n "$release" && \
-	func_warning "\`-release' is ignored for programs"
-
-      test "$preload" = yes \
-        && test "$dlopen_support" = unknown \
-	&& test "$dlopen_self" = unknown \
-	&& test "$dlopen_self_static" = unknown && \
-	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support."
-
-      case $host in
-      *-*-rhapsody* | *-*-darwin1.[012])
-	# On Rhapsody replace the C library is the System framework
-	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'`
-	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'`
-	;;
-      esac
-
-      case $host in
-      *-*-darwin*)
-	# Don't allow lazy linking, it breaks C++ global constructors
-	# But is supposedly fixed on 10.4 or later (yay!).
-	if test "$tagname" = CXX ; then
-	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
-	    10.[0123])
-	      func_append compile_command " ${wl}-bind_at_load"
-	      func_append finalize_command " ${wl}-bind_at_load"
-	    ;;
-	  esac
-	fi
-	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
-	compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
-	;;
-      esac
-
-
-      # move library search paths that coincide with paths to not yet
-      # installed libraries to the beginning of the library search list
-      new_libs=
-      for path in $notinst_path; do
-	case " $new_libs " in
-	*" -L$path/$objdir "*) ;;
-	*)
-	  case " $compile_deplibs " in
-	  *" -L$path/$objdir "*)
-	    func_append new_libs " -L$path/$objdir" ;;
-	  esac
-	  ;;
-	esac
-      done
-      for deplib in $compile_deplibs; do
-	case $deplib in
-	-L*)
-	  case " $new_libs " in
-	  *" $deplib "*) ;;
-	  *) func_append new_libs " $deplib" ;;
-	  esac
-	  ;;
-	*) func_append new_libs " $deplib" ;;
-	esac
-      done
-      compile_deplibs="$new_libs"
-
-
-      func_append compile_command " $compile_deplibs"
-      func_append finalize_command " $finalize_deplibs"
-
-      if test -n "$rpath$xrpath"; then
-	# If the user specified any rpath flags, then add them.
-	for libdir in $rpath $xrpath; do
-	  # This is the magic to use -rpath.
-	  case "$finalize_rpath " in
-	  *" $libdir "*) ;;
-	  *) func_append finalize_rpath " $libdir" ;;
-	  esac
-	done
-      fi
-
-      # Now hardcode the library paths
-      rpath=
-      hardcode_libdirs=
-      for libdir in $compile_rpath $finalize_rpath; do
-	if test -n "$hardcode_libdir_flag_spec"; then
-	  if test -n "$hardcode_libdir_separator"; then
-	    if test -z "$hardcode_libdirs"; then
-	      hardcode_libdirs="$libdir"
-	    else
-	      # Just accumulate the unique libdirs.
-	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
-	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
-		;;
-	      *)
-		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
-		;;
-	      esac
-	    fi
-	  else
-	    eval flag=\"$hardcode_libdir_flag_spec\"
-	    func_append rpath " $flag"
-	  fi
-	elif test -n "$runpath_var"; then
-	  case "$perm_rpath " in
-	  *" $libdir "*) ;;
-	  *) func_append perm_rpath " $libdir" ;;
-	  esac
-	fi
-	case $host in
-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
-	  testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
-	  case :$dllsearchpath: in
-	  *":$libdir:"*) ;;
-	  ::) dllsearchpath=$libdir;;
-	  *) func_append dllsearchpath ":$libdir";;
-	  esac
-	  case :$dllsearchpath: in
-	  *":$testbindir:"*) ;;
-	  ::) dllsearchpath=$testbindir;;
-	  *) func_append dllsearchpath ":$testbindir";;
-	  esac
-	  ;;
-	esac
-      done
-      # Substitute the hardcoded libdirs into the rpath.
-      if test -n "$hardcode_libdir_separator" &&
-	 test -n "$hardcode_libdirs"; then
-	libdir="$hardcode_libdirs"
-	eval rpath=\" $hardcode_libdir_flag_spec\"
-      fi
-      compile_rpath="$rpath"
-
-      rpath=
-      hardcode_libdirs=
-      for libdir in $finalize_rpath; do
-	if test -n "$hardcode_libdir_flag_spec"; then
-	  if test -n "$hardcode_libdir_separator"; then
-	    if test -z "$hardcode_libdirs"; then
-	      hardcode_libdirs="$libdir"
-	    else
-	      # Just accumulate the unique libdirs.
-	      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in
-	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
-		;;
-	      *)
-		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
-		;;
-	      esac
-	    fi
-	  else
-	    eval flag=\"$hardcode_libdir_flag_spec\"
-	    func_append rpath " $flag"
-	  fi
-	elif test -n "$runpath_var"; then
-	  case "$finalize_perm_rpath " in
-	  *" $libdir "*) ;;
-	  *) func_append finalize_perm_rpath " $libdir" ;;
-	  esac
-	fi
-      done
-      # Substitute the hardcoded libdirs into the rpath.
-      if test -n "$hardcode_libdir_separator" &&
-	 test -n "$hardcode_libdirs"; then
-	libdir="$hardcode_libdirs"
-	eval rpath=\" $hardcode_libdir_flag_spec\"
-      fi
-      finalize_rpath="$rpath"
-
-      if test -n "$libobjs" && test "$build_old_libs" = yes; then
-	# Transform all the library objects into standard objects.
-	compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
-	finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP`
-      fi
-
-      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"
-
-      # template prelinking step
-      if test -n "$prelink_cmds"; then
-	func_execute_cmds "$prelink_cmds" 'exit $?'
-      fi
-
-      wrappers_required=yes
-      case $host in
-      *cegcc* | *mingw32ce*)
-        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.
-        wrappers_required=no
-        ;;
-      *cygwin* | *mingw* )
-        if test "$build_libtool_libs" != yes; then
-          wrappers_required=no
-        fi
-        ;;
-      *)
-        if test "$need_relink" = no || test "$build_libtool_libs" != yes; then
-          wrappers_required=no
-        fi
-        ;;
-      esac
-      if test "$wrappers_required" = no; then
-	# Replace the output file specification.
-	compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
-	link_command="$compile_command$compile_rpath"
-
-	# We have no uninstalled library dependencies, so finalize right now.
-	exit_status=0
-	func_show_eval "$link_command" 'exit_status=$?'
-
-	if test -n "$postlink_cmds"; then
-	  func_to_tool_file "$output"
-	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
-	  func_execute_cmds "$postlink_cmds" 'exit $?'
-	fi
-
-	# Delete the generated files.
-	if test -f "$output_objdir/${outputname}S.${objext}"; then
-	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
-	fi
-
-	exit $exit_status
-      fi
-
-      if test -n "$compile_shlibpath$finalize_shlibpath"; then
-	compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command"
-      fi
-      if test -n "$finalize_shlibpath"; then
-	finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command"
-      fi
-
-      compile_var=
-      finalize_var=
-      if test -n "$runpath_var"; then
-	if test -n "$perm_rpath"; then
-	  # We should set the runpath_var.
-	  rpath=
-	  for dir in $perm_rpath; do
-	    func_append rpath "$dir:"
-	  done
-	  compile_var="$runpath_var=\"$rpath\$$runpath_var\" "
-	fi
-	if test -n "$finalize_perm_rpath"; then
-	  # We should set the runpath_var.
-	  rpath=
-	  for dir in $finalize_perm_rpath; do
-	    func_append rpath "$dir:"
-	  done
-	  finalize_var="$runpath_var=\"$rpath\$$runpath_var\" "
-	fi
-      fi
-
-      if test "$no_install" = yes; then
-	# We don't need to create a wrapper script.
-	link_command="$compile_var$compile_command$compile_rpath"
-	# Replace the output file specification.
-	link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
-	# Delete the old output file.
-	$opt_dry_run || $RM $output
-	# Link the executable and exit
-	func_show_eval "$link_command" 'exit $?'
-
-	if test -n "$postlink_cmds"; then
-	  func_to_tool_file "$output"
-	  postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
-	  func_execute_cmds "$postlink_cmds" 'exit $?'
-	fi
-
-	exit $EXIT_SUCCESS
-      fi
-
-      if test "$hardcode_action" = relink; then
-	# Fast installation is not supported
-	link_command="$compile_var$compile_command$compile_rpath"
-	relink_command="$finalize_var$finalize_command$finalize_rpath"
-
-	func_warning "this platform does not like uninstalled shared libraries"
-	func_warning "\`$output' will be relinked during installation"
-      else
-	if test "$fast_install" != no; then
-	  link_command="$finalize_var$compile_command$finalize_rpath"
-	  if test "$fast_install" = yes; then
-	    relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'`
-	  else
-	    # fast_install is set to needless
-	    relink_command=
-	  fi
-	else
-	  link_command="$compile_var$compile_command$compile_rpath"
-	  relink_command="$finalize_var$finalize_command$finalize_rpath"
-	fi
-      fi
-
-      # Replace the output file specification.
-      link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'`
-
-      # Delete the old output files.
-      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname
-
-      func_show_eval "$link_command" 'exit $?'
-
-      if test -n "$postlink_cmds"; then
-	func_to_tool_file "$output_objdir/$outputname"
-	postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
-	func_execute_cmds "$postlink_cmds" 'exit $?'
-      fi
-
-      # Now create the wrapper script.
-      func_verbose "creating $output"
-
-      # Quote the relink command for shipping.
-      if test -n "$relink_command"; then
-	# Preserve any variables that may affect compiler behavior
-	for var in $variables_saved_for_relink; do
-	  if eval test -z \"\${$var+set}\"; then
-	    relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
-	  elif eval var_value=\$$var; test -z "$var_value"; then
-	    relink_command="$var=; export $var; $relink_command"
-	  else
-	    func_quote_for_eval "$var_value"
-	    relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
-	  fi
-	done
-	relink_command="(cd `pwd`; $relink_command)"
-	relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
-      fi
-
-      # Only actually do things if not in dry run mode.
-      $opt_dry_run || {
-	# win32 will think the script is a binary if it has
-	# a .exe suffix, so we strip it off here.
-	case $output in
-	  *.exe) func_stripname '' '.exe' "$output"
-	         output=$func_stripname_result ;;
-	esac
-	# test for cygwin because mv fails w/o .exe extensions
-	case $host in
-	  *cygwin*)
-	    exeext=.exe
-	    func_stripname '' '.exe' "$outputname"
-	    outputname=$func_stripname_result ;;
-	  *) exeext= ;;
-	esac
-	case $host in
-	  *cygwin* | *mingw* )
-	    func_dirname_and_basename "$output" "" "."
-	    output_name=$func_basename_result
-	    output_path=$func_dirname_result
-	    cwrappersource="$output_path/$objdir/lt-$output_name.c"
-	    cwrapper="$output_path/$output_name.exe"
-	    $RM $cwrappersource $cwrapper
-	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
-
-	    func_emit_cwrapperexe_src > $cwrappersource
-
-	    # The wrapper executable is built using the $host compiler,
-	    # because it contains $host paths and files. If cross-
-	    # compiling, it, like the target executable, must be
-	    # executed on the $host or under an emulation environment.
-	    $opt_dry_run || {
-	      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource
-	      $STRIP $cwrapper
-	    }
-
-	    # Now, create the wrapper script for func_source use:
-	    func_ltwrapper_scriptname $cwrapper
-	    $RM $func_ltwrapper_scriptname_result
-	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15
-	    $opt_dry_run || {
-	      # note: this script will not be executed, so do not chmod.
-	      if test "x$build" = "x$host" ; then
-		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
-	      else
-		func_emit_wrapper no > $func_ltwrapper_scriptname_result
-	      fi
-	    }
-	  ;;
-	  * )
-	    $RM $output
-	    trap "$RM $output; exit $EXIT_FAILURE" 1 2 15
-
-	    func_emit_wrapper no > $output
-	    chmod +x $output
-	  ;;
-	esac
-      }
-      exit $EXIT_SUCCESS
-      ;;
-    esac
-
-    # See if we need to build an old-fashioned archive.
-    for oldlib in $oldlibs; do
-
-      if test "$build_libtool_libs" = convenience; then
-	oldobjs="$libobjs_save $symfileobj"
-	addlibs="$convenience"
-	build_libtool_libs=no
-      else
-	if test "$build_libtool_libs" = module; then
-	  oldobjs="$libobjs_save"
-	  build_libtool_libs=no
-	else
-	  oldobjs="$old_deplibs $non_pic_objects"
-	  if test "$preload" = yes && test -f "$symfileobj"; then
-	    func_append oldobjs " $symfileobj"
-	  fi
-	fi
-	addlibs="$old_convenience"
-      fi
-
-      if test -n "$addlibs"; then
-	gentop="$output_objdir/${outputname}x"
-	func_append generated " $gentop"
-
-	func_extract_archives $gentop $addlibs
-	func_append oldobjs " $func_extract_archives_result"
-      fi
-
-      # Do each command in the archive commands.
-      if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then
-	cmds=$old_archive_from_new_cmds
-      else
-
-	# Add any objects from preloaded convenience libraries
-	if test -n "$dlprefiles"; then
-	  gentop="$output_objdir/${outputname}x"
-	  func_append generated " $gentop"
-
-	  func_extract_archives $gentop $dlprefiles
-	  func_append oldobjs " $func_extract_archives_result"
-	fi
-
-	# POSIX demands no paths to be encoded in archives.  We have
-	# to avoid creating archives with duplicate basenames if we
-	# might have to extract them afterwards, e.g., when creating a
-	# static archive out of a convenience library, or when linking
-	# the entirety of a libtool archive into another (currently
-	# not supported by libtool).
-	if (for obj in $oldobjs
-	    do
-	      func_basename "$obj"
-	      $ECHO "$func_basename_result"
-	    done | sort | sort -uc >/dev/null 2>&1); then
-	  :
-	else
-	  echo "copying selected object files to avoid basename conflicts..."
-	  gentop="$output_objdir/${outputname}x"
-	  func_append generated " $gentop"
-	  func_mkdir_p "$gentop"
-	  save_oldobjs=$oldobjs
-	  oldobjs=
-	  counter=1
-	  for obj in $save_oldobjs
-	  do
-	    func_basename "$obj"
-	    objbase="$func_basename_result"
-	    case " $oldobjs " in
-	    " ") oldobjs=$obj ;;
-	    *[\ /]"$objbase "*)
-	      while :; do
-		# Make sure we don't pick an alternate name that also
-		# overlaps.
-		newobj=lt$counter-$objbase
-		func_arith $counter + 1
-		counter=$func_arith_result
-		case " $oldobjs " in
-		*[\ /]"$newobj "*) ;;
-		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
-		esac
-	      done
-	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
-	      func_append oldobjs " $gentop/$newobj"
-	      ;;
-	    *) func_append oldobjs " $obj" ;;
-	    esac
-	  done
-	fi
-	func_to_tool_file "$oldlib" func_convert_file_msys_to_w32
-	tool_oldlib=$func_to_tool_file_result
-	eval cmds=\"$old_archive_cmds\"
-
-	func_len " $cmds"
-	len=$func_len_result
-	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
-	  cmds=$old_archive_cmds
-	elif test -n "$archiver_list_spec"; then
-	  func_verbose "using command file archive linking..."
-	  for obj in $oldobjs
-	  do
-	    func_to_tool_file "$obj"
-	    $ECHO "$func_to_tool_file_result"
-	  done > $output_objdir/$libname.libcmd
-	  func_to_tool_file "$output_objdir/$libname.libcmd"
-	  oldobjs=" $archiver_list_spec$func_to_tool_file_result"
-	  cmds=$old_archive_cmds
-	else
-	  # the command line is too long to link in one step, link in parts
-	  func_verbose "using piecewise archive linking..."
-	  save_RANLIB=$RANLIB
-	  RANLIB=:
-	  objlist=
-	  concat_cmds=
-	  save_oldobjs=$oldobjs
-	  oldobjs=
-	  # Is there a better way of finding the last object in the list?
-	  for obj in $save_oldobjs
-	  do
-	    last_oldobj=$obj
-	  done
-	  eval test_cmds=\"$old_archive_cmds\"
-	  func_len " $test_cmds"
-	  len0=$func_len_result
-	  len=$len0
-	  for obj in $save_oldobjs
-	  do
-	    func_len " $obj"
-	    func_arith $len + $func_len_result
-	    len=$func_arith_result
-	    func_append objlist " $obj"
-	    if test "$len" -lt "$max_cmd_len"; then
-	      :
-	    else
-	      # the above command should be used before it gets too long
-	      oldobjs=$objlist
-	      if test "$obj" = "$last_oldobj" ; then
-		RANLIB=$save_RANLIB
-	      fi
-	      test -z "$concat_cmds" || concat_cmds=$concat_cmds~
-	      eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\"
-	      objlist=
-	      len=$len0
-	    fi
-	  done
-	  RANLIB=$save_RANLIB
-	  oldobjs=$objlist
-	  if test "X$oldobjs" = "X" ; then
-	    eval cmds=\"\$concat_cmds\"
-	  else
-	    eval cmds=\"\$concat_cmds~\$old_archive_cmds\"
-	  fi
-	fi
-      fi
-      func_execute_cmds "$cmds" 'exit $?'
-    done
-
-    test -n "$generated" && \
-      func_show_eval "${RM}r$generated"
-
-    # Now create the libtool archive.
-    case $output in
-    *.la)
-      old_library=
-      test "$build_old_libs" = yes && old_library="$libname.$libext"
-      func_verbose "creating $output"
-
-      # Preserve any variables that may affect compiler behavior
-      for var in $variables_saved_for_relink; do
-	if eval test -z \"\${$var+set}\"; then
-	  relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command"
-	elif eval var_value=\$$var; test -z "$var_value"; then
-	  relink_command="$var=; export $var; $relink_command"
-	else
-	  func_quote_for_eval "$var_value"
-	  relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command"
-	fi
-      done
-      # Quote the link command for shipping.
-      relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)"
-      relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
-      if test "$hardcode_automatic" = yes ; then
-	relink_command=
-      fi
-
-      # Only create the output if not a dry run.
-      $opt_dry_run || {
-	for installed in no yes; do
-	  if test "$installed" = yes; then
-	    if test -z "$install_libdir"; then
-	      break
-	    fi
-	    output="$output_objdir/$outputname"i
-	    # Replace all uninstalled libtool libraries with the installed ones
-	    newdependency_libs=
-	    for deplib in $dependency_libs; do
-	      case $deplib in
-	      *.la)
-		func_basename "$deplib"
-		name="$func_basename_result"
-		func_resolve_sysroot "$deplib"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result`
-		test -z "$libdir" && \
-		  func_fatal_error "\`$deplib' is not a valid libtool archive"
-		func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name"
-		;;
-	      -L*)
-		func_stripname -L '' "$deplib"
-		func_replace_sysroot "$func_stripname_result"
-		func_append newdependency_libs " -L$func_replace_sysroot_result"
-		;;
-	      -R*)
-		func_stripname -R '' "$deplib"
-		func_replace_sysroot "$func_stripname_result"
-		func_append newdependency_libs " -R$func_replace_sysroot_result"
-		;;
-	      *) func_append newdependency_libs " $deplib" ;;
-	      esac
-	    done
-	    dependency_libs="$newdependency_libs"
-	    newdlfiles=
-
-	    for lib in $dlfiles; do
-	      case $lib in
-	      *.la)
-	        func_basename "$lib"
-		name="$func_basename_result"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
-		test -z "$libdir" && \
-		  func_fatal_error "\`$lib' is not a valid libtool archive"
-		func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name"
-		;;
-	      *) func_append newdlfiles " $lib" ;;
-	      esac
-	    done
-	    dlfiles="$newdlfiles"
-	    newdlprefiles=
-	    for lib in $dlprefiles; do
-	      case $lib in
-	      *.la)
-		# Only pass preopened files to the pseudo-archive (for
-		# eventual linking with the app. that links it) if we
-		# didn't already link the preopened objects directly into
-		# the library:
-		func_basename "$lib"
-		name="$func_basename_result"
-		eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib`
-		test -z "$libdir" && \
-		  func_fatal_error "\`$lib' is not a valid libtool archive"
-		func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name"
-		;;
-	      esac
-	    done
-	    dlprefiles="$newdlprefiles"
-	  else
-	    newdlfiles=
-	    for lib in $dlfiles; do
-	      case $lib in
-		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
-		*) abs=`pwd`"/$lib" ;;
-	      esac
-	      func_append newdlfiles " $abs"
-	    done
-	    dlfiles="$newdlfiles"
-	    newdlprefiles=
-	    for lib in $dlprefiles; do
-	      case $lib in
-		[\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;;
-		*) abs=`pwd`"/$lib" ;;
-	      esac
-	      func_append newdlprefiles " $abs"
-	    done
-	    dlprefiles="$newdlprefiles"
-	  fi
-	  $RM $output
-	  # place dlname in correct position for cygwin
-	  # In fact, it would be nice if we could use this code for all target
-	  # systems that can't hard-code library paths into their executables
-	  # and that have no shared library path variable independent of PATH,
-	  # but it turns out we can't easily determine that from inspecting
-	  # libtool variables, so we have to hard-code the OSs to which it
-	  # applies here; at the moment, that means platforms that use the PE
-	  # object format with DLL files.  See the long comment at the top of
-	  # tests/bindir.at for full details.
-	  tdlname=$dlname
-	  case $host,$output,$installed,$module,$dlname in
-	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)
-	      # If a -bindir argument was supplied, place the dll there.
-	      if test "x$bindir" != x ;
-	      then
-		func_relative_path "$install_libdir" "$bindir"
-		tdlname=$func_relative_path_result$dlname
-	      else
-		# Otherwise fall back on heuristic.
-		tdlname=../bin/$dlname
-	      fi
-	      ;;
-	  esac
-	  $ECHO > $output "\
-# $outputname - a libtool library file
-# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
-#
-# Please DO NOT delete this file!
-# It is necessary for linking the library.
-
-# The name that we can dlopen(3).
-dlname='$tdlname'
-
-# Names of this library.
-library_names='$library_names'
-
-# The name of the static archive.
-old_library='$old_library'
-
-# Linker flags that can not go in dependency_libs.
-inherited_linker_flags='$new_inherited_linker_flags'
-
-# Libraries that this one depends upon.
-dependency_libs='$dependency_libs'
-
-# Names of additional weak libraries provided by this library
-weak_library_names='$weak_libs'
-
-# Version information for $libname.
-current=$current
-age=$age
-revision=$revision
-
-# Is this an already installed library?
-installed=$installed
-
-# Should we warn about portability when linking against -modules?
-shouldnotlink=$module
-
-# Files to dlopen/dlpreopen
-dlopen='$dlfiles'
-dlpreopen='$dlprefiles'
-
-# Directory that this library needs to be installed in:
-libdir='$install_libdir'"
-	  if test "$installed" = no && test "$need_relink" = yes; then
-	    $ECHO >> $output "\
-relink_command=\"$relink_command\""
-	  fi
-	done
-      }
-
-      # Do a symbolic link so that the libtool archive can be found in
-      # LD_LIBRARY_PATH before the program is installed.
-      func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?'
-      ;;
-    esac
-    exit $EXIT_SUCCESS
-}
-
-{ test "$opt_mode" = link || test "$opt_mode" = relink; } &&
-    func_mode_link ${1+"$@"}
-
-
-# func_mode_uninstall arg...
-func_mode_uninstall ()
-{
-    $opt_debug
-    RM="$nonopt"
-    files=
-    rmforce=
-    exit_status=0
-
-    # This variable tells wrapper scripts just to set variables rather
-    # than running their programs.
-    libtool_install_magic="$magic"
-
-    for arg
-    do
-      case $arg in
-      -f) func_append RM " $arg"; rmforce=yes ;;
-      -*) func_append RM " $arg" ;;
-      *) func_append files " $arg" ;;
-      esac
-    done
-
-    test -z "$RM" && \
-      func_fatal_help "you must specify an RM program"
-
-    rmdirs=
-
-    for file in $files; do
-      func_dirname "$file" "" "."
-      dir="$func_dirname_result"
-      if test "X$dir" = X.; then
-	odir="$objdir"
-      else
-	odir="$dir/$objdir"
-      fi
-      func_basename "$file"
-      name="$func_basename_result"
-      test "$opt_mode" = uninstall && odir="$dir"
-
-      # Remember odir for removal later, being careful to avoid duplicates
-      if test "$opt_mode" = clean; then
-	case " $rmdirs " in
-	  *" $odir "*) ;;
-	  *) func_append rmdirs " $odir" ;;
-	esac
-      fi
-
-      # Don't error if the file doesn't exist and rm -f was used.
-      if { test -L "$file"; } >/dev/null 2>&1 ||
-	 { test -h "$file"; } >/dev/null 2>&1 ||
-	 test -f "$file"; then
-	:
-      elif test -d "$file"; then
-	exit_status=1
-	continue
-      elif test "$rmforce" = yes; then
-	continue
-      fi
-
-      rmfiles="$file"
-
-      case $name in
-      *.la)
-	# Possibly a libtool archive, so verify it.
-	if func_lalib_p "$file"; then
-	  func_source $dir/$name
-
-	  # Delete the libtool libraries and symlinks.
-	  for n in $library_names; do
-	    func_append rmfiles " $odir/$n"
-	  done
-	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
-
-	  case "$opt_mode" in
-	  clean)
-	    case " $library_names " in
-	    *" $dlname "*) ;;
-	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
-	    esac
-	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
-	    ;;
-	  uninstall)
-	    if test -n "$library_names"; then
-	      # Do each command in the postuninstall commands.
-	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
-	    fi
-
-	    if test -n "$old_library"; then
-	      # Do each command in the old_postuninstall commands.
-	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1'
-	    fi
-	    # FIXME: should reinstall the best remaining shared library.
-	    ;;
-	  esac
-	fi
-	;;
-
-      *.lo)
-	# Possibly a libtool object, so verify it.
-	if func_lalib_p "$file"; then
-
-	  # Read the .lo file
-	  func_source $dir/$name
-
-	  # Add PIC object to the list of files to remove.
-	  if test -n "$pic_object" &&
-	     test "$pic_object" != none; then
-	    func_append rmfiles " $dir/$pic_object"
-	  fi
-
-	  # Add non-PIC object to the list of files to remove.
-	  if test -n "$non_pic_object" &&
-	     test "$non_pic_object" != none; then
-	    func_append rmfiles " $dir/$non_pic_object"
-	  fi
-	fi
-	;;
-
-      *)
-	if test "$opt_mode" = clean ; then
-	  noexename=$name
-	  case $file in
-	  *.exe)
-	    func_stripname '' '.exe' "$file"
-	    file=$func_stripname_result
-	    func_stripname '' '.exe' "$name"
-	    noexename=$func_stripname_result
-	    # $file with .exe has already been added to rmfiles,
-	    # add $file without .exe
-	    func_append rmfiles " $file"
-	    ;;
-	  esac
-	  # Do a test to see if this is a libtool program.
-	  if func_ltwrapper_p "$file"; then
-	    if func_ltwrapper_executable_p "$file"; then
-	      func_ltwrapper_scriptname "$file"
-	      relink_command=
-	      func_source $func_ltwrapper_scriptname_result
-	      func_append rmfiles " $func_ltwrapper_scriptname_result"
-	    else
-	      relink_command=
-	      func_source $dir/$noexename
-	    fi
-
-	    # note $name still contains .exe if it was in $file originally
-	    # as does the version of $file that was added into $rmfiles
-	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
-	    if test "$fast_install" = yes && test -n "$relink_command"; then
-	      func_append rmfiles " $odir/lt-$name"
-	    fi
-	    if test "X$noexename" != "X$name" ; then
-	      func_append rmfiles " $odir/lt-${noexename}.c"
-	    fi
-	  fi
-	fi
-	;;
-      esac
-      func_show_eval "$RM $rmfiles" 'exit_status=1'
-    done
-
-    # Try to remove the ${objdir}s in the directories where we deleted files
-    for dir in $rmdirs; do
-      if test -d "$dir"; then
-	func_show_eval "rmdir $dir >/dev/null 2>&1"
-      fi
-    done
-
-    exit $exit_status
-}
-
-{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } &&
-    func_mode_uninstall ${1+"$@"}
-
-test -z "$opt_mode" && {
-  help="$generic_help"
-  func_fatal_help "you must specify a MODE"
-}
-
-test -z "$exec_cmd" && \
-  func_fatal_help "invalid operation mode \`$opt_mode'"
-
-if test -n "$exec_cmd"; then
-  eval exec "$exec_cmd"
-  exit $EXIT_FAILURE
-fi
-
-exit $exit_status
-
-
-# The TAGs below are defined such that we never get into a situation
-# in which we disable both kinds of libraries.  Given conflicting
-# choices, we go for a static library, that is the most portable,
-# since we can't tell whether shared libraries were disabled because
-# the user asked for that or because the platform doesn't support
-# them.  This is particularly important on AIX, because we don't
-# support having both static and shared libraries enabled at the same
-# time on that platform, so we default to a shared-only configuration.
-# If a disable-shared tag is given, we'll fallback to a static-only
-# configuration.  But we'll never go from static-only to shared-only.
-
-# ### BEGIN LIBTOOL TAG CONFIG: disable-shared
-build_libtool_libs=no
-build_old_libs=yes
-# ### END LIBTOOL TAG CONFIG: disable-shared
-
-# ### BEGIN LIBTOOL TAG CONFIG: disable-static
-build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`
-# ### END LIBTOOL TAG CONFIG: disable-static
-
-# Local Variables:
-# mode:shell-script
-# sh-indentation:2
-# End:
-# vi:sw=2
-
diff --git a/m4/.gitignore b/m4/.gitignore
new file mode 100644
index 0000000..9ebe42c
--- /dev/null
+++ b/m4/.gitignore
@@ -0,0 +1,6 @@
+/lt~obsolete.m4
+/ltversion.m4
+/ltsugar.m4
+/ltoptions.m4
+/libtool.m4
+/c_backported.m4
diff --git a/m4/Makefile.in b/m4/Makefile.in
deleted file mode 100644
index 0998c05..0000000
--- a/m4/Makefile.in
+++ /dev/null
@@ -1,483 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-subdir = m4
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-EXTRA_DIST = libcurl.m4
-all: all-am
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu m4/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu m4/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-tags TAGS:
-
-ctags CTAGS:
-
-cscope cscopelist:
-
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-am
-all-am: Makefile
-installdirs:
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-am
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: install-am install-strip
-
-.PHONY: all all-am check check-am clean clean-generic clean-libtool \
-	cscopelist-am ctags-am distclean distclean-generic \
-	distclean-libtool distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	maintainer-clean maintainer-clean-generic mostlyclean \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags-am uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/m4/ac_define_dir.m4 b/m4/ac_define_dir.m4
new file mode 100644
index 0000000..e15cea2
--- /dev/null
+++ b/m4/ac_define_dir.m4
@@ -0,0 +1,34 @@
+dnl @synopsis AC_DEFINE_DIR(VARNAME, DIR [, DESCRIPTION])
+dnl
+dnl This macro sets VARNAME to the expansion of the DIR variable,
+dnl taking care of fixing up ${prefix} and such.
+dnl
+dnl VARNAME is then offered as both an output variable and a C
+dnl preprocessor symbol.
+dnl
+dnl Example:
+dnl
+dnl    AC_DEFINE_DIR([DATADIR], [datadir], [Where data are placed to.])
+dnl
+dnl @category Misc
+dnl @author Stepan Kasal <kasal@ucw.cz>
+dnl @author Andreas Schwab <schwab@suse.de>
+dnl @author Guido U. Draheim <guidod@gmx.de>
+dnl @author Alexandre Oliva
+dnl @version 2006-10-13
+dnl @license AllPermissive
+
+AC_DEFUN([AC_DEFINE_DIR], [
+  prefix_NONE=
+  exec_prefix_NONE=
+  test "x$prefix" = xNONE && prefix_NONE=yes && prefix=$ac_default_prefix
+  test "x$exec_prefix" = xNONE && exec_prefix_NONE=yes && exec_prefix=$prefix
+dnl In Autoconf 2.60, ${datadir} refers to ${datarootdir}, which in turn
+dnl refers to ${prefix}.  Thus we have to use `eval' twice.
+  eval ac_define_dir="\"[$]$2\""
+  eval ac_define_dir="\"$ac_define_dir\""
+  AC_SUBST($1, "$ac_define_dir")
+  AC_DEFINE_UNQUOTED($1, "$ac_define_dir", [$3])
+  test "$prefix_NONE" && prefix=NONE
+  test "$exec_prefix_NONE" && exec_prefix=NONE
+])
diff --git a/m4/ax_append_compile_flags.m4 b/m4/ax_append_compile_flags.m4
index dc7b866..9c85635 100644
--- a/m4/ax_append_compile_flags.m4
+++ b/m4/ax_append_compile_flags.m4
@@ -1,10 +1,10 @@
-# ===========================================================================
-#  http://www.gnu.org/software/autoconf-archive/ax_append_compile_flags.html
-# ===========================================================================
+# ============================================================================
+#  https://www.gnu.org/software/autoconf-archive/ax_append_compile_flags.html
+# ============================================================================
 #
 # SYNOPSIS
 #
-#   AX_APPEND_COMPILE_FLAGS([FLAG1 FLAG2 ...], [FLAGS-VARIABLE], [EXTRA-FLAGS])
+#   AX_APPEND_COMPILE_FLAGS([FLAG1 FLAG2 ...], [FLAGS-VARIABLE], [EXTRA-FLAGS], [INPUT])
 #
 # DESCRIPTION
 #
@@ -20,6 +20,8 @@
 #   the flags: "CFLAGS EXTRA-FLAGS FLAG".  This can for example be used to
 #   force the compiler to issue an error when a bad flag is given.
 #
+#   INPUT gives an alternative input source to AC_COMPILE_IFELSE.
+#
 #   NOTE: This macro depends on the AX_APPEND_FLAG and
 #   AX_CHECK_COMPILE_FLAG. Please keep this macro in sync with
 #   AX_APPEND_LINK_FLAGS.
@@ -28,38 +30,17 @@
 #
 #   Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
 #
-#   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/>.
-#
-#   As a special exception, the respective Autoconf Macro's copyright owner
-#   gives unlimited permission to copy, distribute and modify the configure
-#   scripts that are the output of Autoconf when processing the Macro. You
-#   need not follow the terms of the GNU General Public License when using
-#   or distributing such scripts, even though portions of the text of the
-#   Macro appear in them. The GNU General Public License (GPL) does govern
-#   all other use of the material that constitutes the Autoconf Macro.
-#
-#   This special exception to the GPL applies to versions of the Autoconf
-#   Macro released by the Autoconf Archive. When you make and distribute a
-#   modified version of the Autoconf Macro, you may extend this special
-#   exception to the GPL to apply to your modified version as well.
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.  This file is offered as-is, without any
+#   warranty.
 
-#serial 4
+#serial 7
 
 AC_DEFUN([AX_APPEND_COMPILE_FLAGS],
 [AX_REQUIRE_DEFINED([AX_CHECK_COMPILE_FLAG])
 AX_REQUIRE_DEFINED([AX_APPEND_FLAG])
 for flag in $1; do
-  AX_CHECK_COMPILE_FLAG([$flag], [AX_APPEND_FLAG([$flag], [$2])], [], [$3])
+  AX_CHECK_COMPILE_FLAG([$flag], [AX_APPEND_FLAG([$flag], [$2])], [], [$3], [$4])
 done
 ])dnl AX_APPEND_COMPILE_FLAGS
diff --git a/m4/ax_append_flag.m4 b/m4/ax_append_flag.m4
index 1d38b76..dd6d8b6 100644
--- a/m4/ax_append_flag.m4
+++ b/m4/ax_append_flag.m4
@@ -1,5 +1,5 @@
 # ===========================================================================
-#      http://www.gnu.org/software/autoconf-archive/ax_append_flag.html
+#      https://www.gnu.org/software/autoconf-archive/ax_append_flag.html
 # ===========================================================================
 #
 # SYNOPSIS
@@ -23,47 +23,28 @@
 #   Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
 #   Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
 #
-#   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/>.
-#
-#   As a special exception, the respective Autoconf Macro's copyright owner
-#   gives unlimited permission to copy, distribute and modify the configure
-#   scripts that are the output of Autoconf when processing the Macro. You
-#   need not follow the terms of the GNU General Public License when using
-#   or distributing such scripts, even though portions of the text of the
-#   Macro appear in them. The GNU General Public License (GPL) does govern
-#   all other use of the material that constitutes the Autoconf Macro.
-#
-#   This special exception to the GPL applies to versions of the Autoconf
-#   Macro released by the Autoconf Archive. When you make and distribute a
-#   modified version of the Autoconf Macro, you may extend this special
-#   exception to the GPL to apply to your modified version as well.
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.  This file is offered as-is, without any
+#   warranty.
 
-#serial 2
+#serial 8
 
 AC_DEFUN([AX_APPEND_FLAG],
-[AC_PREREQ(2.59)dnl for _AC_LANG_PREFIX
-AS_VAR_PUSHDEF([FLAGS], [m4_default($2,_AC_LANG_PREFIX[FLAGS])])dnl
-AS_VAR_SET_IF(FLAGS,
-  [case " AS_VAR_GET(FLAGS) " in
-    *" $1 "*)
-      AC_RUN_LOG([: FLAGS already contains $1])
-      ;;
-    *)
-      AC_RUN_LOG([: FLAGS="$FLAGS $1"])
-      AS_VAR_SET(FLAGS, ["AS_VAR_GET(FLAGS) $1"])
-      ;;
-   esac],
-  [AS_VAR_SET(FLAGS,["$1"])])
+[dnl
+AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_SET_IF
+AS_VAR_PUSHDEF([FLAGS], [m4_default($2,_AC_LANG_PREFIX[FLAGS])])
+AS_VAR_SET_IF(FLAGS,[
+  AS_CASE([" AS_VAR_GET(FLAGS) "],
+    [*" $1 "*], [AC_RUN_LOG([: FLAGS already contains $1])],
+    [
+     AS_VAR_APPEND(FLAGS,[" $1"])
+     AC_RUN_LOG([: FLAGS="$FLAGS"])
+    ])
+  ],
+  [
+  AS_VAR_SET(FLAGS,[$1])
+  AC_RUN_LOG([: FLAGS="$FLAGS"])
+  ])
 AS_VAR_POPDEF([FLAGS])dnl
 ])dnl AX_APPEND_FLAG
diff --git a/m4/ax_append_link_flags.m4 b/m4/ax_append_link_flags.m4
new file mode 100644
index 0000000..99b9fa5
--- /dev/null
+++ b/m4/ax_append_link_flags.m4
@@ -0,0 +1,44 @@
+# ===========================================================================
+#   https://www.gnu.org/software/autoconf-archive/ax_append_link_flags.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_APPEND_LINK_FLAGS([FLAG1 FLAG2 ...], [FLAGS-VARIABLE], [EXTRA-FLAGS], [INPUT])
+#
+# DESCRIPTION
+#
+#   For every FLAG1, FLAG2 it is checked whether the linker works with the
+#   flag.  If it does, the flag is added FLAGS-VARIABLE
+#
+#   If FLAGS-VARIABLE is not specified, the linker's flags (LDFLAGS) is
+#   used. During the check the flag is always added to the linker's flags.
+#
+#   If EXTRA-FLAGS is defined, it is added to the linker's default flags
+#   when the check is done.  The check is thus made with the flags: "LDFLAGS
+#   EXTRA-FLAGS FLAG".  This can for example be used to force the linker to
+#   issue an error when a bad flag is given.
+#
+#   INPUT gives an alternative input source to AC_COMPILE_IFELSE.
+#
+#   NOTE: This macro depends on the AX_APPEND_FLAG and AX_CHECK_LINK_FLAG.
+#   Please keep this macro in sync with AX_APPEND_COMPILE_FLAGS.
+#
+# LICENSE
+#
+#   Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.  This file is offered as-is, without any
+#   warranty.
+
+#serial 7
+
+AC_DEFUN([AX_APPEND_LINK_FLAGS],
+[AX_REQUIRE_DEFINED([AX_CHECK_LINK_FLAG])
+AX_REQUIRE_DEFINED([AX_APPEND_FLAG])
+for flag in $1; do
+  AX_CHECK_LINK_FLAG([$flag], [AX_APPEND_FLAG([$flag], [m4_default([$2], [LDFLAGS])])], [], [$3], [$4])
+done
+])dnl AX_APPEND_LINK_FLAGS
diff --git a/m4/ax_check_compile_flag.m4 b/m4/ax_check_compile_flag.m4
index 51df0c0..bd753b3 100644
--- a/m4/ax_check_compile_flag.m4
+++ b/m4/ax_check_compile_flag.m4
@@ -1,5 +1,5 @@
 # ===========================================================================
-#   http://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html
+#  https://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html
 # ===========================================================================
 #
 # SYNOPSIS
@@ -29,36 +29,15 @@
 #   Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
 #   Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
 #
-#   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/>.
-#
-#   As a special exception, the respective Autoconf Macro's copyright owner
-#   gives unlimited permission to copy, distribute and modify the configure
-#   scripts that are the output of Autoconf when processing the Macro. You
-#   need not follow the terms of the GNU General Public License when using
-#   or distributing such scripts, even though portions of the text of the
-#   Macro appear in them. The GNU General Public License (GPL) does govern
-#   all other use of the material that constitutes the Autoconf Macro.
-#
-#   This special exception to the GPL applies to versions of the Autoconf
-#   Macro released by the Autoconf Archive. When you make and distribute a
-#   modified version of the Autoconf Macro, you may extend this special
-#   exception to the GPL to apply to your modified version as well.
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.  This file is offered as-is, without any
+#   warranty.
 
-#serial 3
+#serial 6
 
 AC_DEFUN([AX_CHECK_COMPILE_FLAG],
-[AC_PREREQ(2.59)dnl for _AC_LANG_PREFIX
+[AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF
 AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl
 AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [
   ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS
@@ -67,7 +46,7 @@
     [AS_VAR_SET(CACHEVAR,[yes])],
     [AS_VAR_SET(CACHEVAR,[no])])
   _AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags])
-AS_IF([test x"AS_VAR_GET(CACHEVAR)" = xyes],
+AS_VAR_IF(CACHEVAR,yes,
   [m4_default([$2], :)],
   [m4_default([$3], :)])
 AS_VAR_POPDEF([CACHEVAR])dnl
diff --git a/m4/ax_check_link_flag.m4 b/m4/ax_check_link_flag.m4
index db899dd..03a30ce 100644
--- a/m4/ax_check_link_flag.m4
+++ b/m4/ax_check_link_flag.m4
@@ -1,5 +1,5 @@
 # ===========================================================================
-#    http://www.gnu.org/software/autoconf-archive/ax_check_link_flag.html
+#    https://www.gnu.org/software/autoconf-archive/ax_check_link_flag.html
 # ===========================================================================
 #
 # SYNOPSIS
@@ -29,36 +29,16 @@
 #   Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
 #   Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
 #
-#   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/>.
-#
-#   As a special exception, the respective Autoconf Macro's copyright owner
-#   gives unlimited permission to copy, distribute and modify the configure
-#   scripts that are the output of Autoconf when processing the Macro. You
-#   need not follow the terms of the GNU General Public License when using
-#   or distributing such scripts, even though portions of the text of the
-#   Macro appear in them. The GNU General Public License (GPL) does govern
-#   all other use of the material that constitutes the Autoconf Macro.
-#
-#   This special exception to the GPL applies to versions of the Autoconf
-#   Macro released by the Autoconf Archive. When you make and distribute a
-#   modified version of the Autoconf Macro, you may extend this special
-#   exception to the GPL to apply to your modified version as well.
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.  This file is offered as-is, without any
+#   warranty.
 
-#serial 3
+#serial 6
 
 AC_DEFUN([AX_CHECK_LINK_FLAG],
-[AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_ldflags_$4_$1])dnl
+[AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF
+AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_ldflags_$4_$1])dnl
 AC_CACHE_CHECK([whether the linker accepts $1], CACHEVAR, [
   ax_check_save_flags=$LDFLAGS
   LDFLAGS="$LDFLAGS $4 $1"
@@ -66,7 +46,7 @@
     [AS_VAR_SET(CACHEVAR,[yes])],
     [AS_VAR_SET(CACHEVAR,[no])])
   LDFLAGS=$ax_check_save_flags])
-AS_IF([test x"AS_VAR_GET(CACHEVAR)" = xyes],
+AS_VAR_IF(CACHEVAR,yes,
   [m4_default([$2], :)],
   [m4_default([$3], :)])
 AS_VAR_POPDEF([CACHEVAR])dnl
diff --git a/m4/ax_check_openssl.m4 b/m4/ax_check_openssl.m4
deleted file mode 100644
index a87c5a6..0000000
--- a/m4/ax_check_openssl.m4
+++ /dev/null
@@ -1,124 +0,0 @@
-# ===========================================================================
-#     http://www.gnu.org/software/autoconf-archive/ax_check_openssl.html
-# ===========================================================================
-#
-# SYNOPSIS
-#
-#   AX_CHECK_OPENSSL([action-if-found[, action-if-not-found]])
-#
-# DESCRIPTION
-#
-#   Look for OpenSSL in a number of default spots, or in a user-selected
-#   spot (via --with-openssl).  Sets
-#
-#     OPENSSL_INCLUDES to the include directives required
-#     OPENSSL_LIBS to the -l directives required
-#     OPENSSL_LDFLAGS to the -L or -R flags required
-#
-#   and calls ACTION-IF-FOUND or ACTION-IF-NOT-FOUND appropriately
-#
-#   This macro sets OPENSSL_INCLUDES such that source files should use the
-#   openssl/ directory in include directives:
-#
-#     #include <openssl/hmac.h>
-#
-# LICENSE
-#
-#   Copyright (c) 2009,2010 Zmanda Inc. <http://www.zmanda.com/>
-#   Copyright (c) 2009,2010 Dustin J. Mitchell <dustin@zmanda.com>
-#
-#   Copying and distribution of this file, with or without modification, are
-#   permitted in any medium without royalty provided the copyright notice
-#   and this notice are preserved. This file is offered as-is, without any
-#   warranty.
-
-#serial 8
-
-AU_ALIAS([CHECK_SSL], [AX_CHECK_OPENSSL])
-AC_DEFUN([AX_CHECK_OPENSSL], [
-    found=false
-    AC_ARG_WITH([openssl],
-        [AS_HELP_STRING([--with-openssl=DIR],
-            [root of the OpenSSL directory])],
-        [
-            case "$withval" in
-            "" | y | ye | yes | n | no)
-            AC_MSG_ERROR([Invalid --with-openssl value])
-              ;;
-            *) ssldirs="$withval"
-              ;;
-            esac
-        ], [
-            # if pkg-config is installed and openssl has installed a .pc file,
-            # then use that information and don't search ssldirs
-            AC_PATH_PROG([PKG_CONFIG], [pkg-config])
-            if test x"$PKG_CONFIG" != x""; then
-                OPENSSL_LDFLAGS=`$PKG_CONFIG openssl --libs-only-L 2>/dev/null`
-                if test $? = 0; then
-                    OPENSSL_LIBS=`$PKG_CONFIG openssl --libs-only-l 2>/dev/null`
-                    OPENSSL_INCLUDES=`$PKG_CONFIG openssl --cflags-only-I 2>/dev/null`
-                    found=true
-                fi
-            fi
-
-            # no such luck; use some default ssldirs
-            if ! $found; then
-                ssldirs="/usr/local/ssl /usr/lib/ssl /usr/ssl /usr/pkg /usr/local /usr"
-            fi
-        ]
-        )
-
-
-    # note that we #include <openssl/foo.h>, so the OpenSSL headers have to be in
-    # an 'openssl' subdirectory
-
-    if ! $found; then
-        OPENSSL_INCLUDES=
-        for ssldir in $ssldirs; do
-            AC_MSG_CHECKING([for openssl/ssl.h in $ssldir])
-            if test -f "$ssldir/include/openssl/ssl.h"; then
-                OPENSSL_INCLUDES="-I$ssldir/include"
-                OPENSSL_LDFLAGS="-L$ssldir/lib"
-                OPENSSL_LIBS="-lssl -lcrypto"
-                found=true
-                AC_MSG_RESULT([yes])
-                break
-            else
-                AC_MSG_RESULT([no])
-            fi
-        done
-
-        # if the file wasn't found, well, go ahead and try the link anyway -- maybe
-        # it will just work!
-    fi
-
-    # try the preprocessor and linker with our new flags,
-    # being careful not to pollute the global LIBS, LDFLAGS, and CPPFLAGS
-
-    AC_MSG_CHECKING([whether compiling and linking against OpenSSL works])
-    echo "Trying link with OPENSSL_LDFLAGS=$OPENSSL_LDFLAGS;" \
-        "OPENSSL_LIBS=$OPENSSL_LIBS; OPENSSL_INCLUDES=$OPENSSL_INCLUDES" >&AS_MESSAGE_LOG_FD
-
-    save_LIBS="$LIBS"
-    save_LDFLAGS="$LDFLAGS"
-    save_CPPFLAGS="$CPPFLAGS"
-    LDFLAGS="$LDFLAGS $OPENSSL_LDFLAGS"
-    LIBS="$OPENSSL_LIBS $LIBS"
-    CPPFLAGS="$OPENSSL_INCLUDES $CPPFLAGS"
-    AC_LINK_IFELSE(
-        [AC_LANG_PROGRAM([#include <openssl/ssl.h>], [SSL_new(NULL)])],
-        [
-            AC_MSG_RESULT([yes])
-            $1
-        ], [
-            AC_MSG_RESULT([no])
-            $2
-        ])
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-
-    AC_SUBST([OPENSSL_INCLUDES])
-    AC_SUBST([OPENSSL_LIBS])
-    AC_SUBST([OPENSSL_LDFLAGS])
-])
diff --git a/m4/ax_count_cpus.m4 b/m4/ax_count_cpus.m4
index 39b68d3..5db8925 100644
--- a/m4/ax_count_cpus.m4
+++ b/m4/ax_count_cpus.m4
@@ -1,21 +1,24 @@
 # ===========================================================================
-#       http://www.gnu.org/software/autoconf-archive/ax_count_cpus.html
+#      https://www.gnu.org/software/autoconf-archive/ax_count_cpus.html
 # ===========================================================================
 #
 # SYNOPSIS
 #
-#   AX_COUNT_CPUS
+#   AX_COUNT_CPUS([ACTION-IF-DETECTED],[ACTION-IF-NOT-DETECTED])
 #
 # DESCRIPTION
 #
-#   Attempt to count the number of processors present on the machine. If the
-#   detection fails, then a value of 1 is assumed.
+#   Attempt to count the number of logical processor cores (including
+#   virtual and HT cores) currently available to use on the machine and
+#   place detected value in CPU_COUNT variable.
 #
-#   The value is placed in the CPU_COUNT variable.
+#   On successful detection, ACTION-IF-DETECTED is executed if present. If
+#   the detection fails, then ACTION-IF-NOT-DETECTED is triggered. The
+#   default ACTION-IF-NOT-DETECTED is to set CPU_COUNT to 1.
 #
 # LICENSE
 #
-#   Copyright (c) 2014 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#   Copyright (c) 2014,2016 Karlson2k (Evgeny Grin) <k2k@narod.ru>
 #   Copyright (c) 2012 Brian Aker <brian@tangent.org>
 #   Copyright (c) 2008 Michael Paul Bailey <jinxidoru@byu.net>
 #   Copyright (c) 2008 Christophe Tournayre <turn3r@users.sourceforge.net>
@@ -25,42 +28,74 @@
 #   and this notice are preserved. This file is offered as-is, without any
 #   warranty.
 
-#serial 10
+#serial 22
 
-  AC_DEFUN([AX_COUNT_CPUS],[
-      AC_REQUIRE([AC_CANONICAL_HOST])
-      AC_REQUIRE([AC_PROG_EGREP])
+  AC_DEFUN([AX_COUNT_CPUS],[dnl
+      AC_REQUIRE([AC_CANONICAL_HOST])dnl
+      AC_REQUIRE([AC_PROG_EGREP])dnl
       AC_MSG_CHECKING([the number of available CPUs])
       CPU_COUNT="0"
 
-      AS_CASE([$host_os],[
-        *darwin*],[
-        AS_IF([test -x /usr/sbin/sysctl],[
-          sysctl_a=`/usr/sbin/sysctl -a 2>/dev/null| grep -c hw.cpu`
-          AS_IF([test sysctl_a],[
-            CPU_COUNT=`/usr/sbin/sysctl -n hw.ncpu`
-            ])
-          ])],[
-        *linux*],[
-        AS_IF([test "x$CPU_COUNT" = "x0" -a -e /proc/cpuinfo],[
-          AS_IF([test "x$CPU_COUNT" = "x0" -a -e /proc/cpuinfo],[
-            CPU_COUNT=`$EGREP -c '^processor' /proc/cpuinfo`
-            ])
-          ])],[
-        *mingw*],[
-        AS_IF([test -n "$NUMBER_OF_PROCESSORS"],[
-          CPU_COUNT="$NUMBER_OF_PROCESSORS"
-          ])],[
-        *cygwin*],[
-        AS_IF([test -n "$NUMBER_OF_PROCESSORS"],[
-          CPU_COUNT="$NUMBER_OF_PROCESSORS"
-          ])
-        ])
+      # Try generic methods
 
-      AS_IF([test "x$CPU_COUNT" = "x0"],[
-        CPU_COUNT="1"
-        AC_MSG_RESULT( [unable to detect (assuming 1)] )
-        ],[
-        AC_MSG_RESULT( $CPU_COUNT )
-        ])
-      ])
+      # 'getconf' is POSIX utility, but '_NPROCESSORS_ONLN' and
+      # 'NPROCESSORS_ONLN' are platform-specific
+      command -v getconf >/dev/null 2>&1 && \
+        CPU_COUNT=`getconf _NPROCESSORS_ONLN 2>/dev/null || getconf NPROCESSORS_ONLN 2>/dev/null` || CPU_COUNT="0"
+      AS_IF([[test "$CPU_COUNT" -gt "0" 2>/dev/null || ! command -v nproc >/dev/null 2>&1]],[[: # empty]],[dnl
+        # 'nproc' is part of GNU Coreutils and is widely available
+        CPU_COUNT=`OMP_NUM_THREADS='' nproc 2>/dev/null` || CPU_COUNT=`nproc 2>/dev/null` || CPU_COUNT="0"
+      ])dnl
+
+      AS_IF([[test "$CPU_COUNT" -gt "0" 2>/dev/null]],[[: # empty]],[dnl
+        # Try platform-specific preferred methods
+        AS_CASE([[$host_os]],dnl
+          [[*linux*]],[[CPU_COUNT=`lscpu -p 2>/dev/null | $EGREP -e '^@<:@0-9@:>@+,' -c` || CPU_COUNT="0"]],dnl
+          [[*darwin*]],[[CPU_COUNT=`sysctl -n hw.logicalcpu 2>/dev/null` || CPU_COUNT="0"]],dnl
+          [[freebsd*]],[[command -v sysctl >/dev/null 2>&1 && CPU_COUNT=`sysctl -n kern.smp.cpus 2>/dev/null` || CPU_COUNT="0"]],dnl
+          [[netbsd*]], [[command -v sysctl >/dev/null 2>&1 && CPU_COUNT=`sysctl -n hw.ncpuonline 2>/dev/null` || CPU_COUNT="0"]],dnl
+          [[solaris*]],[[command -v psrinfo >/dev/null 2>&1 && CPU_COUNT=`psrinfo 2>/dev/null | $EGREP -e '^@<:@0-9@:>@.*on-line' -c 2>/dev/null` || CPU_COUNT="0"]],dnl
+          [[mingw*]],[[CPU_COUNT=`ls -qpU1 /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor/ 2>/dev/null | $EGREP -e '^@<:@0-9@:>@+/' -c` || CPU_COUNT="0"]],dnl
+          [[msys*]],[[CPU_COUNT=`ls -qpU1 /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor/ 2>/dev/null | $EGREP -e '^@<:@0-9@:>@+/' -c` || CPU_COUNT="0"]],dnl
+          [[cygwin*]],[[CPU_COUNT=`ls -qpU1 /proc/registry/HKEY_LOCAL_MACHINE/HARDWARE/DESCRIPTION/System/CentralProcessor/ 2>/dev/null | $EGREP -e '^@<:@0-9@:>@+/' -c` || CPU_COUNT="0"]]dnl
+        )dnl
+      ])dnl
+
+      AS_IF([[test "$CPU_COUNT" -gt "0" 2>/dev/null || ! command -v sysctl >/dev/null 2>&1]],[[: # empty]],[dnl
+        # Try less preferred generic method
+        # 'hw.ncpu' exist on many platforms, but not on GNU/Linux
+        CPU_COUNT=`sysctl -n hw.ncpu 2>/dev/null` || CPU_COUNT="0"
+      ])dnl
+
+      AS_IF([[test "$CPU_COUNT" -gt "0" 2>/dev/null]],[[: # empty]],[dnl
+      # Try platform-specific fallback methods
+      # They can be less accurate and slower then preferred methods
+        AS_CASE([[$host_os]],dnl
+          [[*linux*]],[[CPU_COUNT=`$EGREP -e '^processor' -c /proc/cpuinfo 2>/dev/null` || CPU_COUNT="0"]],dnl
+          [[*darwin*]],[[CPU_COUNT=`system_profiler SPHardwareDataType 2>/dev/null | $EGREP -i -e 'number of cores:'|cut -d : -f 2 -s|tr -d ' '` || CPU_COUNT="0"]],dnl
+          [[freebsd*]],[[CPU_COUNT=`dmesg 2>/dev/null| $EGREP -e '^cpu@<:@0-9@:>@+: '|sort -u|$EGREP -e '^' -c` || CPU_COUNT="0"]],dnl
+          [[netbsd*]], [[CPU_COUNT=`command -v cpuctl >/dev/null 2>&1 && cpuctl list 2>/dev/null| $EGREP -e '^@<:@0-9@:>@+ .* online ' -c` || \
+                           CPU_COUNT=`dmesg 2>/dev/null| $EGREP -e '^cpu@<:@0-9@:>@+ at'|sort -u|$EGREP -e '^' -c` || CPU_COUNT="0"]],dnl
+          [[solaris*]],[[command -v kstat >/dev/null 2>&1 && CPU_COUNT=`kstat -m cpu_info -s state -p 2>/dev/null | $EGREP -c -e 'on-line'` || \
+                           CPU_COUNT=`kstat -m cpu_info 2>/dev/null | $EGREP -c -e 'module: cpu_info'` || CPU_COUNT="0"]],dnl
+          [[mingw*]],[AS_IF([[CPU_COUNT=`reg query 'HKLM\\Hardware\\Description\\System\\CentralProcessor' 2>/dev/null | $EGREP -e '\\\\@<:@0-9@:>@+$' -c`]],dnl
+                        [[: # empty]],[[test "$NUMBER_OF_PROCESSORS" -gt "0" 2>/dev/null && CPU_COUNT="$NUMBER_OF_PROCESSORS"]])],dnl
+          [[msys*]],[[test "$NUMBER_OF_PROCESSORS" -gt "0" 2>/dev/null && CPU_COUNT="$NUMBER_OF_PROCESSORS"]],dnl
+          [[cygwin*]],[[test "$NUMBER_OF_PROCESSORS" -gt "0" 2>/dev/null && CPU_COUNT="$NUMBER_OF_PROCESSORS"]]dnl
+        )dnl
+      ])dnl
+
+      AS_IF([[test "x$CPU_COUNT" != "x0" && test "$CPU_COUNT" -gt 0 2>/dev/null]],[dnl
+          AC_MSG_RESULT([[$CPU_COUNT]])
+          m4_ifvaln([$1],[$1],)dnl
+        ],[dnl
+          m4_ifval([$2],[dnl
+            AS_UNSET([[CPU_COUNT]])
+            AC_MSG_RESULT([[unable to detect]])
+            $2
+          ], [dnl
+            CPU_COUNT="1"
+            AC_MSG_RESULT([[unable to detect (assuming 1)]])
+          ])dnl
+        ])dnl
+      ])dnl
diff --git a/m4/ax_have_epoll.m4 b/m4/ax_have_epoll.m4
index 07ceb49..3098de6 100644
--- a/m4/ax_have_epoll.m4
+++ b/m4/ax_have_epoll.m4
@@ -1,5 +1,5 @@
 # ===========================================================================
-#       http://www.gnu.org/software/autoconf-archive/ax_have_epoll.html
+#      https://www.gnu.org/software/autoconf-archive/ax_have_epoll.html
 # ===========================================================================
 #
 # SYNOPSIS
@@ -42,11 +42,11 @@
 #   and this notice are preserved. This file is offered as-is, without any
 #   warranty.
 
-#serial 10
+#serial 12
 
 AC_DEFUN([AX_HAVE_EPOLL], [dnl
   ax_have_epoll_cppflags="${CPPFLAGS}"
-  AC_CHECK_HEADER([linux/version.h], [CPPFLAGS="${CPPFLAGS} -DHAVE_LINUX_VERSION_H"])
+  AC_CHECK_HEADER([linux/version.h], [CPPFLAGS="${CPPFLAGS} -DHAVE_LINUX_VERSION_H"], [], [AC_INCLUDES_DEFAULT])
   AC_MSG_CHECKING([for Linux epoll(7) interface])
   AC_CACHE_VAL([ax_cv_have_epoll], [dnl
     AC_LINK_IFELSE([dnl
@@ -59,10 +59,10 @@
 #  endif
 #endif
 ], [dnl
-int fd, rc;
+int fd;
 struct epoll_event ev;
 fd = epoll_create(128);
-rc = epoll_wait(fd, &ev, 1, 0);])],
+epoll_wait(fd, &ev, 1, 0);])],
       [ax_cv_have_epoll=yes],
       [ax_cv_have_epoll=no])])
   CPPFLAGS="${ax_have_epoll_cppflags}"
@@ -89,11 +89,11 @@
 #include <sys/epoll.h>
 #include <signal.h>
 ], [dnl
-int fd, rc;
+int fd;
 struct epoll_event ev;
 fd = epoll_create(128);
-rc = epoll_wait(fd, &ev, 1, 0);
-rc = epoll_pwait(fd, &ev, 1, 0, (sigset_t const *)(0));])],
+epoll_wait(fd, &ev, 1, 0);
+epoll_pwait(fd, &ev, 1, 0, (sigset_t const *)(0));])],
       [ax_cv_have_epoll_pwait=yes],
       [ax_cv_have_epoll_pwait=no])])
   CPPFLAGS="${ax_have_epoll_cppflags}"
diff --git a/m4/ax_pthread.m4 b/m4/ax_pthread.m4
index d383ad5..9f35d13 100644
--- a/m4/ax_pthread.m4
+++ b/m4/ax_pthread.m4
@@ -1,5 +1,5 @@
 # ===========================================================================
-#        http://www.gnu.org/software/autoconf-archive/ax_pthread.html
+#        https://www.gnu.org/software/autoconf-archive/ax_pthread.html
 # ===========================================================================
 #
 # SYNOPSIS
@@ -14,24 +14,28 @@
 #   flags that are needed. (The user can also force certain compiler
 #   flags/libs to be tested by setting these environment variables.)
 #
-#   Also sets PTHREAD_CC to any special C compiler that is needed for
-#   multi-threaded programs (defaults to the value of CC otherwise). (This
-#   is necessary on AIX to use the special cc_r compiler alias.)
+#   Also sets PTHREAD_CC and PTHREAD_CXX to any special C compiler that is
+#   needed for multi-threaded programs (defaults to the value of CC
+#   respectively CXX otherwise). (This is necessary on e.g. AIX to use the
+#   special cc_r/CC_r compiler alias.)
 #
 #   NOTE: You are assumed to not only compile your program with these flags,
-#   but also link it with them as well. e.g. you should link with
+#   but also to link with them as well. For example, you might link with
 #   $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
+#   $PTHREAD_CXX $CXXFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
 #
-#   If you are only building threads programs, you may wish to use these
+#   If you are only building threaded programs, you may wish to use these
 #   variables in your default LIBS, CFLAGS, and CC:
 #
 #     LIBS="$PTHREAD_LIBS $LIBS"
 #     CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+#     CXXFLAGS="$CXXFLAGS $PTHREAD_CFLAGS"
 #     CC="$PTHREAD_CC"
+#     CXX="$PTHREAD_CXX"
 #
 #   In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
-#   has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name
-#   (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
+#   has a nonstandard name, this macro defines PTHREAD_CREATE_JOINABLE to
+#   that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
 #
 #   Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
 #   PTHREAD_PRIO_INHERIT symbol is defined when compiling with
@@ -55,6 +59,7 @@
 #
 #   Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
 #   Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
+#   Copyright (c) 2019 Marc Stevens <marc.stevens@cwi.nl>
 #
 #   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
@@ -67,7 +72,7 @@
 #   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/>.
+#   with this program. If not, see <https://www.gnu.org/licenses/>.
 #
 #   As a special exception, the respective Autoconf Macro's copyright owner
 #   gives unlimited permission to copy, distribute and modify the configure
@@ -82,35 +87,41 @@
 #   modified version of the Autoconf Macro, you may extend this special
 #   exception to the GPL to apply to your modified version as well.
 
-#serial 21
+#serial 31
 
 AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
 AC_DEFUN([AX_PTHREAD], [
 AC_REQUIRE([AC_CANONICAL_HOST])
+AC_REQUIRE([AC_PROG_CC])
+AC_REQUIRE([AC_PROG_SED])
 AC_LANG_PUSH([C])
 ax_pthread_ok=no
 
 # We used to check for pthread.h first, but this fails if pthread.h
-# requires special compiler flags (e.g. on True64 or Sequent).
+# requires special compiler flags (e.g. on Tru64 or Sequent).
 # It gets checked for in the link test anyway.
 
 # First of all, check if the user has set any of the PTHREAD_LIBS,
 # etcetera environment variables, and if threads linking works using
 # them:
-if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
-        save_CFLAGS="$CFLAGS"
+if test "x$PTHREAD_CFLAGS$PTHREAD_LIBS" != "x"; then
+        ax_pthread_save_CC="$CC"
+        ax_pthread_save_CFLAGS="$CFLAGS"
+        ax_pthread_save_LIBS="$LIBS"
+        AS_IF([test "x$PTHREAD_CC" != "x"], [CC="$PTHREAD_CC"])
+        AS_IF([test "x$PTHREAD_CXX" != "x"], [CXX="$PTHREAD_CXX"])
         CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-        save_LIBS="$LIBS"
         LIBS="$PTHREAD_LIBS $LIBS"
-        AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
-        AC_TRY_LINK_FUNC([pthread_join], [ax_pthread_ok=yes])
+        AC_MSG_CHECKING([for pthread_join using $CC $PTHREAD_CFLAGS $PTHREAD_LIBS])
+        AC_LINK_IFELSE([AC_LANG_CALL([], [pthread_join])], [ax_pthread_ok=yes])
         AC_MSG_RESULT([$ax_pthread_ok])
-        if test x"$ax_pthread_ok" = xno; then
+        if test "x$ax_pthread_ok" = "xno"; then
                 PTHREAD_LIBS=""
                 PTHREAD_CFLAGS=""
         fi
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
+        CC="$ax_pthread_save_CC"
+        CFLAGS="$ax_pthread_save_CFLAGS"
+        LIBS="$ax_pthread_save_LIBS"
 fi
 
 # We must check for the threads library under a number of different
@@ -118,12 +129,14 @@
 # (e.g. DEC) have both -lpthread and -lpthreads, where one of the
 # libraries is broken (non-POSIX).
 
-# Create a list of thread flags to try.  Items starting with a "-" are
-# C compiler flags, and other items are library names, except for "none"
-# which indicates that we try without any flags at all, and "pthread-config"
-# which is a program returning the flags for the Pth emulation library.
+# Create a list of thread flags to try. Items with a "," contain both
+# C compiler flags (before ",") and linker flags (after ","). Other items
+# starting with a "-" are C compiler flags, and remaining items are
+# library names, except for "none" which indicates that we try without
+# any flags at all, and "pthread-config" which is a program returning
+# the flags for the Pth emulation library.
 
-ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
+ax_pthread_flags="pthreads none -Kthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
 
 # The ordering *is* (sometimes) important.  Some notes on the
 # individual items follow:
@@ -132,82 +145,163 @@
 # none: in case threads are in libc; should be tried before -Kthread and
 #       other compiler flags to prevent continual compiler warnings
 # -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
-# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
-# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
-# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
-# -pthreads: Solaris/gcc
-# -mthreads: Mingw32/gcc, Lynx/gcc
+# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads), Tru64
+#           (Note: HP C rejects this with "bad form for `-t' option")
+# -pthreads: Solaris/gcc (Note: HP C also rejects)
 # -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
-#      doesn't hurt to check since this sometimes defines pthreads too;
-#      also defines -D_REENTRANT)
-#      ... -mt is also the pthreads flag for HP/aCC
+#      doesn't hurt to check since this sometimes defines pthreads and
+#      -D_REENTRANT too), HP C (must be checked before -lpthread, which
+#      is present but should not be used directly; and before -mthreads,
+#      because the compiler interprets this as "-mt" + "-hreads")
+# -mthreads: Mingw32/gcc, Lynx/gcc
 # pthread: Linux, etcetera
 # --thread-safe: KAI C++
 # pthread-config: use pthread-config program (for GNU Pth library)
 
-case ${host_os} in
+case $host_os in
+
+        freebsd*)
+
+        # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+        # lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+
+        ax_pthread_flags="-kthread lthread $ax_pthread_flags"
+        ;;
+
+        hpux*)
+
+        # From the cc(1) man page: "[-mt] Sets various -D flags to enable
+        # multi-threading and also sets -lpthread."
+
+        ax_pthread_flags="-mt -pthread pthread $ax_pthread_flags"
+        ;;
+
+        openedition*)
+
+        # IBM z/OS requires a feature-test macro to be defined in order to
+        # enable POSIX threads at all, so give the user a hint if this is
+        # not set. (We don't define these ourselves, as they can affect
+        # other portions of the system API in unpredictable ways.)
+
+        AC_EGREP_CPP([AX_PTHREAD_ZOS_MISSING],
+            [
+#            if !defined(_OPEN_THREADS) && !defined(_UNIX03_THREADS)
+             AX_PTHREAD_ZOS_MISSING
+#            endif
+            ],
+            [AC_MSG_WARN([IBM z/OS requires -D_OPEN_THREADS or -D_UNIX03_THREADS to enable pthreads support.])])
+        ;;
+
         solaris*)
 
         # On Solaris (at least, for some versions), libc contains stubbed
         # (non-functional) versions of the pthreads routines, so link-based
-        # tests will erroneously succeed.  (We need to link with -pthreads/-mt/
-        # -lpthread.)  (The stubs are missing pthread_cleanup_push, or rather
-        # a function called by this macro, so we could check for that, but
-        # who knows whether they'll stub that too in a future libc.)  So,
-        # we'll just look for -pthreads and -lpthread first:
+        # tests will erroneously succeed. (N.B.: The stubs are missing
+        # pthread_cleanup_push, or rather a function called by this macro,
+        # so we could check for that, but who knows whether they'll stub
+        # that too in a future libc.)  So we'll check first for the
+        # standard Solaris way of linking pthreads (-mt -lpthread).
 
-        ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags"
-        ;;
-
-        darwin*)
-        ax_pthread_flags="-pthread $ax_pthread_flags"
+        ax_pthread_flags="-mt,-lpthread pthread $ax_pthread_flags"
         ;;
 esac
 
-# Clang doesn't consider unrecognized options an error unless we specify
-# -Werror. We throw in some extra Clang-specific options to ensure that
-# this doesn't happen for GCC, which also accepts -Werror.
+# Are we compiling with Clang?
 
-AC_MSG_CHECKING([if compiler needs -Werror to reject unknown flags])
-save_CFLAGS="$CFLAGS"
-ax_pthread_extra_flags="-Werror"
-CFLAGS="$CFLAGS $ax_pthread_extra_flags -Wunknown-warning-option -Wsizeof-array-argument"
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([int foo(void);],[foo()])],
-                  [AC_MSG_RESULT([yes])],
-                  [ax_pthread_extra_flags=
-                   AC_MSG_RESULT([no])])
-CFLAGS="$save_CFLAGS"
+AC_CACHE_CHECK([whether $CC is Clang],
+    [ax_cv_PTHREAD_CLANG],
+    [ax_cv_PTHREAD_CLANG=no
+     # Note that Autoconf sets GCC=yes for Clang as well as GCC
+     if test "x$GCC" = "xyes"; then
+        AC_EGREP_CPP([AX_PTHREAD_CC_IS_CLANG],
+            [/* Note: Clang 2.7 lacks __clang_[a-z]+__ */
+#            if defined(__clang__) && defined(__llvm__)
+             AX_PTHREAD_CC_IS_CLANG
+#            endif
+            ],
+            [ax_cv_PTHREAD_CLANG=yes])
+     fi
+    ])
+ax_pthread_clang="$ax_cv_PTHREAD_CLANG"
 
-if test x"$ax_pthread_ok" = xno; then
-for flag in $ax_pthread_flags; do
 
-        case $flag in
+# GCC generally uses -pthread, or -pthreads on some platforms (e.g. SPARC)
+
+# Note that for GCC and Clang -pthread generally implies -lpthread,
+# except when -nostdlib is passed.
+# This is problematic using libtool to build C++ shared libraries with pthread:
+# [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25460
+# [2] https://bugzilla.redhat.com/show_bug.cgi?id=661333
+# [3] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=468555
+# To solve this, first try -pthread together with -lpthread for GCC
+
+AS_IF([test "x$GCC" = "xyes"],
+      [ax_pthread_flags="-pthread,-lpthread -pthread -pthreads $ax_pthread_flags"])
+
+# Clang takes -pthread (never supported any other flag), but we'll try with -lpthread first
+
+AS_IF([test "x$ax_pthread_clang" = "xyes"],
+      [ax_pthread_flags="-pthread,-lpthread -pthread"])
+
+
+# The presence of a feature test macro requesting re-entrant function
+# definitions is, on some systems, a strong hint that pthreads support is
+# correctly enabled
+
+case $host_os in
+        darwin* | hpux* | linux* | osf* | solaris*)
+        ax_pthread_check_macro="_REENTRANT"
+        ;;
+
+        aix*)
+        ax_pthread_check_macro="_THREAD_SAFE"
+        ;;
+
+        *)
+        ax_pthread_check_macro="--"
+        ;;
+esac
+AS_IF([test "x$ax_pthread_check_macro" = "x--"],
+      [ax_pthread_check_cond=0],
+      [ax_pthread_check_cond="!defined($ax_pthread_check_macro)"])
+
+
+if test "x$ax_pthread_ok" = "xno"; then
+for ax_pthread_try_flag in $ax_pthread_flags; do
+
+        case $ax_pthread_try_flag in
                 none)
                 AC_MSG_CHECKING([whether pthreads work without any flags])
                 ;;
 
+                *,*)
+                PTHREAD_CFLAGS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\1/"`
+                PTHREAD_LIBS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\2/"`
+                AC_MSG_CHECKING([whether pthreads work with "$PTHREAD_CFLAGS" and "$PTHREAD_LIBS"])
+                ;;
+
                 -*)
-                AC_MSG_CHECKING([whether pthreads work with $flag])
-                PTHREAD_CFLAGS="$flag"
+                AC_MSG_CHECKING([whether pthreads work with $ax_pthread_try_flag])
+                PTHREAD_CFLAGS="$ax_pthread_try_flag"
                 ;;
 
                 pthread-config)
                 AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no])
-                if test x"$ax_pthread_config" = xno; then continue; fi
+                AS_IF([test "x$ax_pthread_config" = "xno"], [continue])
                 PTHREAD_CFLAGS="`pthread-config --cflags`"
                 PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
                 ;;
 
                 *)
-                AC_MSG_CHECKING([for the pthreads library -l$flag])
-                PTHREAD_LIBS="-l$flag"
+                AC_MSG_CHECKING([for the pthreads library -l$ax_pthread_try_flag])
+                PTHREAD_LIBS="-l$ax_pthread_try_flag"
                 ;;
         esac
 
-        save_LIBS="$LIBS"
-        save_CFLAGS="$CFLAGS"
+        ax_pthread_save_CFLAGS="$CFLAGS"
+        ax_pthread_save_LIBS="$LIBS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
         LIBS="$PTHREAD_LIBS $LIBS"
-        CFLAGS="$CFLAGS $PTHREAD_CFLAGS $ax_pthread_extra_flags"
 
         # Check for various functions.  We must include pthread.h,
         # since some functions may be macros.  (On the Sequent, we
@@ -218,8 +312,18 @@
         # pthread_cleanup_push because it is one of the few pthread
         # functions on Solaris that doesn't have a non-functional libc stub.
         # We try pthread_create on general principles.
+
         AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
-                        static void routine(void *a) { a = 0; }
+#                       if $ax_pthread_check_cond
+#                        error "$ax_pthread_check_macro must be defined"
+#                       endif
+                        static void *some_global = NULL;
+                        static void routine(void *a)
+                          {
+                             /* To avoid any unused-parameter or
+                                unused-but-set-parameter warning.  */
+                             some_global = a;
+                          }
                         static void *start_routine(void *a) { return a; }],
                        [pthread_t th; pthread_attr_t attr;
                         pthread_create(&th, 0, start_routine, 0);
@@ -227,101 +331,187 @@
                         pthread_attr_init(&attr);
                         pthread_cleanup_push(routine, 0);
                         pthread_cleanup_pop(0) /* ; */])],
-                [ax_pthread_ok=yes],
-                [])
+            [ax_pthread_ok=yes],
+            [])
 
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
+        CFLAGS="$ax_pthread_save_CFLAGS"
+        LIBS="$ax_pthread_save_LIBS"
 
         AC_MSG_RESULT([$ax_pthread_ok])
-        if test "x$ax_pthread_ok" = xyes; then
-                break;
-        fi
+        AS_IF([test "x$ax_pthread_ok" = "xyes"], [break])
 
         PTHREAD_LIBS=""
         PTHREAD_CFLAGS=""
 done
 fi
 
+
+# Clang needs special handling, because older versions handle the -pthread
+# option in a rather... idiosyncratic way
+
+if test "x$ax_pthread_clang" = "xyes"; then
+
+        # Clang takes -pthread; it has never supported any other flag
+
+        # (Note 1: This will need to be revisited if a system that Clang
+        # supports has POSIX threads in a separate library.  This tends not
+        # to be the way of modern systems, but it's conceivable.)
+
+        # (Note 2: On some systems, notably Darwin, -pthread is not needed
+        # to get POSIX threads support; the API is always present and
+        # active.  We could reasonably leave PTHREAD_CFLAGS empty.  But
+        # -pthread does define _REENTRANT, and while the Darwin headers
+        # ignore this macro, third-party headers might not.)
+
+        # However, older versions of Clang make a point of warning the user
+        # that, in an invocation where only linking and no compilation is
+        # taking place, the -pthread option has no effect ("argument unused
+        # during compilation").  They expect -pthread to be passed in only
+        # when source code is being compiled.
+        #
+        # Problem is, this is at odds with the way Automake and most other
+        # C build frameworks function, which is that the same flags used in
+        # compilation (CFLAGS) are also used in linking.  Many systems
+        # supported by AX_PTHREAD require exactly this for POSIX threads
+        # support, and in fact it is often not straightforward to specify a
+        # flag that is used only in the compilation phase and not in
+        # linking.  Such a scenario is extremely rare in practice.
+        #
+        # Even though use of the -pthread flag in linking would only print
+        # a warning, this can be a nuisance for well-run software projects
+        # that build with -Werror.  So if the active version of Clang has
+        # this misfeature, we search for an option to squash it.
+
+        AC_CACHE_CHECK([whether Clang needs flag to prevent "argument unused" warning when linking with -pthread],
+            [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG],
+            [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG=unknown
+             # Create an alternate version of $ac_link that compiles and
+             # links in two steps (.c -> .o, .o -> exe) instead of one
+             # (.c -> exe), because the warning occurs only in the second
+             # step
+             ax_pthread_save_ac_link="$ac_link"
+             ax_pthread_sed='s/conftest\.\$ac_ext/conftest.$ac_objext/g'
+             ax_pthread_link_step=`AS_ECHO(["$ac_link"]) | sed "$ax_pthread_sed"`
+             ax_pthread_2step_ac_link="($ac_compile) && (echo ==== >&5) && ($ax_pthread_link_step)"
+             ax_pthread_save_CFLAGS="$CFLAGS"
+             for ax_pthread_try in '' -Qunused-arguments -Wno-unused-command-line-argument unknown; do
+                AS_IF([test "x$ax_pthread_try" = "xunknown"], [break])
+                CFLAGS="-Werror -Wunknown-warning-option $ax_pthread_try -pthread $ax_pthread_save_CFLAGS"
+                ac_link="$ax_pthread_save_ac_link"
+                AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
+                    [ac_link="$ax_pthread_2step_ac_link"
+                     AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
+                         [break])
+                    ])
+             done
+             ac_link="$ax_pthread_save_ac_link"
+             CFLAGS="$ax_pthread_save_CFLAGS"
+             AS_IF([test "x$ax_pthread_try" = "x"], [ax_pthread_try=no])
+             ax_cv_PTHREAD_CLANG_NO_WARN_FLAG="$ax_pthread_try"
+            ])
+
+        case "$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG" in
+                no | unknown) ;;
+                *) PTHREAD_CFLAGS="$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG $PTHREAD_CFLAGS" ;;
+        esac
+
+fi # $ax_pthread_clang = yes
+
+
+
 # Various other checks:
-if test "x$ax_pthread_ok" = xyes; then
-        save_LIBS="$LIBS"
-        LIBS="$PTHREAD_LIBS $LIBS"
-        save_CFLAGS="$CFLAGS"
+if test "x$ax_pthread_ok" = "xyes"; then
+        ax_pthread_save_CFLAGS="$CFLAGS"
+        ax_pthread_save_LIBS="$LIBS"
         CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+        LIBS="$PTHREAD_LIBS $LIBS"
 
         # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
-        AC_MSG_CHECKING([for joinable pthread attribute])
-        attr_name=unknown
-        for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
-            AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
-                           [int attr = $attr; return attr /* ; */])],
-                [attr_name=$attr; break],
-                [])
-        done
-        AC_MSG_RESULT([$attr_name])
-        if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
-            AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE], [$attr_name],
-                               [Define to necessary symbol if this constant
-                                uses a non-standard name on your system.])
-        fi
+        AC_CACHE_CHECK([for joinable pthread attribute],
+            [ax_cv_PTHREAD_JOINABLE_ATTR],
+            [ax_cv_PTHREAD_JOINABLE_ATTR=unknown
+             for ax_pthread_attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+                 AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
+                                                 [int attr = $ax_pthread_attr; return attr /* ; */])],
+                                [ax_cv_PTHREAD_JOINABLE_ATTR=$ax_pthread_attr; break],
+                                [])
+             done
+            ])
+        AS_IF([test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xunknown" && \
+               test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xPTHREAD_CREATE_JOINABLE" && \
+               test "x$ax_pthread_joinable_attr_defined" != "xyes"],
+              [AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE],
+                                  [$ax_cv_PTHREAD_JOINABLE_ATTR],
+                                  [Define to necessary symbol if this constant
+                                   uses a non-standard name on your system.])
+               ax_pthread_joinable_attr_defined=yes
+              ])
 
-        AC_MSG_CHECKING([if more special flags are required for pthreads])
-        flag=no
-        case ${host_os} in
-            aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";;
-            osf* | hpux*) flag="-D_REENTRANT";;
-            solaris*)
-            if test "$GCC" = "yes"; then
-                flag="-D_REENTRANT"
-            else
-                # TODO: What about Clang on Solaris?
-                flag="-mt -D_REENTRANT"
-            fi
-            ;;
-        esac
-        AC_MSG_RESULT([$flag])
-        if test "x$flag" != xno; then
-            PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
-        fi
+        AC_CACHE_CHECK([whether more special flags are required for pthreads],
+            [ax_cv_PTHREAD_SPECIAL_FLAGS],
+            [ax_cv_PTHREAD_SPECIAL_FLAGS=no
+             case $host_os in
+             solaris*)
+             ax_cv_PTHREAD_SPECIAL_FLAGS="-D_POSIX_PTHREAD_SEMANTICS"
+             ;;
+             esac
+            ])
+        AS_IF([test "x$ax_cv_PTHREAD_SPECIAL_FLAGS" != "xno" && \
+               test "x$ax_pthread_special_flags_added" != "xyes"],
+              [PTHREAD_CFLAGS="$ax_cv_PTHREAD_SPECIAL_FLAGS $PTHREAD_CFLAGS"
+               ax_pthread_special_flags_added=yes])
 
         AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
-            [ax_cv_PTHREAD_PRIO_INHERIT], [
-                AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <pthread.h>]],
-                                                [[int i = PTHREAD_PRIO_INHERIT;]])],
-                    [ax_cv_PTHREAD_PRIO_INHERIT=yes],
-                    [ax_cv_PTHREAD_PRIO_INHERIT=no])
+            [ax_cv_PTHREAD_PRIO_INHERIT],
+            [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <pthread.h>]],
+                                             [[int i = PTHREAD_PRIO_INHERIT;
+                                               return i;]])],
+                            [ax_cv_PTHREAD_PRIO_INHERIT=yes],
+                            [ax_cv_PTHREAD_PRIO_INHERIT=no])
             ])
-        AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"],
-            [AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])])
+        AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes" && \
+               test "x$ax_pthread_prio_inherit_defined" != "xyes"],
+              [AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])
+               ax_pthread_prio_inherit_defined=yes
+              ])
 
-        LIBS="$save_LIBS"
-        CFLAGS="$save_CFLAGS"
+        CFLAGS="$ax_pthread_save_CFLAGS"
+        LIBS="$ax_pthread_save_LIBS"
 
         # More AIX lossage: compile with *_r variant
-        if test "x$GCC" != xyes; then
+        if test "x$GCC" != "xyes"; then
             case $host_os in
                 aix*)
                 AS_CASE(["x/$CC"],
-                  [x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
-                  [#handle absolute path differently from PATH based program lookup
-                   AS_CASE(["x$CC"],
-                     [x/*],
-                     [AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])],
-                     [AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])])])
+                    [x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
+                    [#handle absolute path differently from PATH based program lookup
+                     AS_CASE(["x$CC"],
+                         [x/*],
+                         [
+			   AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])
+			   AS_IF([test "x${CXX}" != "x"], [AS_IF([AS_EXECUTABLE_P([${CXX}_r])],[PTHREAD_CXX="${CXX}_r"])])
+			 ],
+                         [
+			   AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])
+			   AS_IF([test "x${CXX}" != "x"], [AC_CHECK_PROGS([PTHREAD_CXX],[${CXX}_r],[$CXX])])
+			 ]
+                     )
+                    ])
                 ;;
             esac
         fi
 fi
 
 test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
+test -n "$PTHREAD_CXX" || PTHREAD_CXX="$CXX"
 
 AC_SUBST([PTHREAD_LIBS])
 AC_SUBST([PTHREAD_CFLAGS])
 AC_SUBST([PTHREAD_CC])
+AC_SUBST([PTHREAD_CXX])
 
 # Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
-if test x"$ax_pthread_ok" = xyes; then
+if test "x$ax_pthread_ok" = "xyes"; then
         ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1])
         :
 else
diff --git a/m4/ax_require_defined.m4 b/m4/ax_require_defined.m4
index cae1111..17c3eab 100644
--- a/m4/ax_require_defined.m4
+++ b/m4/ax_require_defined.m4
@@ -1,5 +1,5 @@
 # ===========================================================================
-#    http://www.gnu.org/software/autoconf-archive/ax_require_defined.html
+#    https://www.gnu.org/software/autoconf-archive/ax_require_defined.html
 # ===========================================================================
 #
 # SYNOPSIS
@@ -30,7 +30,7 @@
 #   and this notice are preserved. This file is offered as-is, without any
 #   warranty.
 
-#serial 1
+#serial 2
 
 AC_DEFUN([AX_REQUIRE_DEFINED], [dnl
   m4_ifndef([$1], [m4_fatal([macro ]$1[ is not defined; is a m4 file missing?])])
diff --git a/m4/codeset.m4 b/m4/codeset.m4
new file mode 100644
index 0000000..bc98201
--- /dev/null
+++ b/m4/codeset.m4
@@ -0,0 +1,24 @@
+# codeset.m4 serial 5 (gettext-0.18.2)
+dnl Copyright (C) 2000-2002, 2006, 2008-2014, 2016 Free Software Foundation,
+dnl Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([AM_LANGINFO_CODESET],
+[
+  AC_CACHE_CHECK([for nl_langinfo and CODESET], [am_cv_langinfo_codeset],
+    [AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <langinfo.h>]],
+          [[char* cs = nl_langinfo(CODESET); return !cs;]])],
+       [am_cv_langinfo_codeset=yes],
+       [am_cv_langinfo_codeset=no])
+    ])
+  if test $am_cv_langinfo_codeset = yes; then
+    AC_DEFINE([HAVE_LANGINFO_CODESET], [1],
+      [Define if you have <langinfo.h> and nl_langinfo(CODESET).])
+  fi
+])
diff --git a/m4/extern-inline.m4 b/m4/extern-inline.m4
new file mode 100644
index 0000000..a2acf12
--- /dev/null
+++ b/m4/extern-inline.m4
@@ -0,0 +1,114 @@
+dnl 'extern inline' a la ISO C99.
+
+dnl Copyright 2012-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+AC_DEFUN([gl_EXTERN_INLINE],
+[
+  AH_VERBATIM([extern_inline],
+[/* Please see the Gnulib manual for how to use these macros.
+
+   Suppress extern inline with HP-UX cc, as it appears to be broken; see
+   <https://lists.gnu.org/r/bug-texinfo/2013-02/msg00030.html>.
+
+   Suppress extern inline with Sun C in standards-conformance mode, as it
+   mishandles inline functions that call each other.  E.g., for 'inline void f
+   (void) { } inline void g (void) { f (); }', c99 incorrectly complains
+   'reference to static identifier "f" in extern inline function'.
+   This bug was observed with Sun C 5.12 SunOS_i386 2011/11/16.
+
+   Suppress extern inline (with or without __attribute__ ((__gnu_inline__)))
+   on configurations that mistakenly use 'static inline' to implement
+   functions or macros in standard C headers like <ctype.h>.  For example,
+   if isdigit is mistakenly implemented via a static inline function,
+   a program containing an extern inline function that calls isdigit
+   may not work since the C standard prohibits extern inline functions
+   from calling static functions (ISO C 99 section 6.7.4.(3).
+   This bug is known to occur on:
+
+     OS X 10.8 and earlier; see:
+     https://lists.gnu.org/r/bug-gnulib/2012-12/msg00023.html
+
+     DragonFly; see
+     http://muscles.dragonflybsd.org/bulk/clang-master-potential/20141111_102002/logs/ah-tty-0.3.12.log
+
+     FreeBSD; see:
+     https://lists.gnu.org/r/bug-gnulib/2014-07/msg00104.html
+
+   OS X 10.9 has a macro __header_inline indicating the bug is fixed for C and
+   for clang but remains for g++; see <https://trac.macports.org/ticket/41033>.
+   Assume DragonFly and FreeBSD will be similar.
+
+   GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99
+   inline semantics, unless -fgnu89-inline is used.  It defines a macro
+   __GNUC_STDC_INLINE__ to indicate this situation or a macro
+   __GNUC_GNU_INLINE__ to indicate the opposite situation.
+   GCC 4.2 with -std=c99 or -std=gnu99 implements the GNU C inline
+   semantics but warns, unless -fgnu89-inline is used:
+     warning: C99 inline functions are not supported; using GNU89
+     warning: to disable this warning use -fgnu89-inline or the gnu_inline function attribute
+   It defines a macro __GNUC_GNU_INLINE__ to indicate this situation.
+ */
+#if (((defined __APPLE__ && defined __MACH__) \
+      || defined __DragonFly__ || defined __FreeBSD__) \
+     && (defined __header_inline \
+         ? (defined __cplusplus && defined __GNUC_STDC_INLINE__ \
+            && ! defined __clang__) \
+         : ((! defined _DONT_USE_CTYPE_INLINE_ \
+             && (defined __GNUC__ || defined __cplusplus)) \
+            || (defined _FORTIFY_SOURCE && 0 < _FORTIFY_SOURCE \
+                && defined __GNUC__ && ! defined __cplusplus))))
+# define _GL_EXTERN_INLINE_STDHEADER_BUG
+#endif
+#if ((__GNUC__ \
+      ? defined __GNUC_STDC_INLINE__ && __GNUC_STDC_INLINE__ \
+      : (199901L <= __STDC_VERSION__ \
+         && !defined __HP_cc \
+         && !defined __PGI \
+         && !(defined __SUNPRO_C && __STDC__))) \
+     && !defined _GL_EXTERN_INLINE_STDHEADER_BUG)
+# define _GL_INLINE inline
+# define _GL_EXTERN_INLINE extern inline
+# define _GL_EXTERN_INLINE_IN_USE
+#elif (2 < __GNUC__ + (7 <= __GNUC_MINOR__) && !defined __STRICT_ANSI__ \
+       && !defined _GL_EXTERN_INLINE_STDHEADER_BUG)
+# if defined __GNUC_GNU_INLINE__ && __GNUC_GNU_INLINE__
+   /* __gnu_inline__ suppresses a GCC 4.2 diagnostic.  */
+#  define _GL_INLINE extern inline __attribute__ ((__gnu_inline__))
+# else
+#  define _GL_INLINE extern inline
+# endif
+# define _GL_EXTERN_INLINE extern
+# define _GL_EXTERN_INLINE_IN_USE
+#else
+# define _GL_INLINE static _GL_UNUSED
+# define _GL_EXTERN_INLINE static _GL_UNUSED
+#endif
+
+/* In GCC 4.6 (inclusive) to 5.1 (exclusive),
+   suppress bogus "no previous prototype for 'FOO'"
+   and "no previous declaration for 'FOO'" diagnostics,
+   when FOO is an inline function in the header; see
+   <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54113> and
+   <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63877>.  */
+#if __GNUC__ == 4 && 6 <= __GNUC_MINOR__
+# if defined __GNUC_STDC_INLINE__ && __GNUC_STDC_INLINE__
+#  define _GL_INLINE_HEADER_CONST_PRAGMA
+# else
+#  define _GL_INLINE_HEADER_CONST_PRAGMA \
+     _Pragma ("GCC diagnostic ignored \"-Wsuggest-attribute=const\"")
+# endif
+# define _GL_INLINE_HEADER_BEGIN \
+    _Pragma ("GCC diagnostic push") \
+    _Pragma ("GCC diagnostic ignored \"-Wmissing-prototypes\"") \
+    _Pragma ("GCC diagnostic ignored \"-Wmissing-declarations\"") \
+    _GL_INLINE_HEADER_CONST_PRAGMA
+# define _GL_INLINE_HEADER_END \
+    _Pragma ("GCC diagnostic pop")
+#else
+# define _GL_INLINE_HEADER_BEGIN
+# define _GL_INLINE_HEADER_END
+#endif])
+])
diff --git a/m4/fcntl-o.m4 b/m4/fcntl-o.m4
new file mode 100644
index 0000000..7c459ad
--- /dev/null
+++ b/m4/fcntl-o.m4
@@ -0,0 +1,140 @@
+# fcntl-o.m4 serial 7
+dnl Copyright (C) 2006, 2009-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl Written by Paul Eggert.
+
+AC_PREREQ([2.60])
+
+# Test whether the flags O_NOATIME and O_NOFOLLOW actually work.
+# Define HAVE_WORKING_O_NOATIME to 1 if O_NOATIME works, or to 0 otherwise.
+# Define HAVE_WORKING_O_NOFOLLOW to 1 if O_NOFOLLOW works, or to 0 otherwise.
+AC_DEFUN([gl_FCNTL_O_FLAGS],
+[
+  dnl Persuade glibc <fcntl.h> to define O_NOATIME and O_NOFOLLOW.
+  AC_REQUIRE([AC_USE_SYSTEM_EXTENSIONS])
+
+  AC_REQUIRE([AC_CANONICAL_HOST]) dnl for cross-compiles
+  AC_CHECK_HEADERS_ONCE([unistd.h])
+  AC_CHECK_FUNCS_ONCE([symlink])
+  AC_CACHE_CHECK([for working fcntl.h], [gl_cv_header_working_fcntl_h],
+    [AC_RUN_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <sys/types.h>
+           #include <sys/stat.h>
+           #if HAVE_UNISTD_H
+           # include <unistd.h>
+           #else /* on Windows with MSVC */
+           # include <io.h>
+           # include <stdlib.h>
+           # defined sleep(n) _sleep ((n) * 1000)
+           #endif
+           #include <fcntl.h>
+           ]GL_MDA_DEFINES[
+           #ifndef O_NOATIME
+            #define O_NOATIME 0
+           #endif
+           #ifndef O_NOFOLLOW
+            #define O_NOFOLLOW 0
+           #endif
+           static int const constants[] =
+            {
+              O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC, O_APPEND,
+              O_NONBLOCK, O_SYNC, O_ACCMODE, O_RDONLY, O_RDWR, O_WRONLY
+            };
+          ]],
+          [[
+            int result = !constants;
+            #if HAVE_SYMLINK
+            {
+              static char const sym[] = "conftest.sym";
+              if (symlink ("/dev/null", sym) != 0)
+                result |= 2;
+              else
+                {
+                  int fd = open (sym, O_WRONLY | O_NOFOLLOW | O_CREAT, 0);
+                  if (fd >= 0)
+                    {
+                      close (fd);
+                      result |= 4;
+                    }
+                }
+              if (unlink (sym) != 0 || symlink (".", sym) != 0)
+                result |= 2;
+              else
+                {
+                  int fd = open (sym, O_RDONLY | O_NOFOLLOW);
+                  if (fd >= 0)
+                    {
+                      close (fd);
+                      result |= 4;
+                    }
+                }
+              unlink (sym);
+            }
+            #endif
+            {
+              static char const file[] = "confdefs.h";
+              int fd = open (file, O_RDONLY | O_NOATIME);
+              if (fd < 0)
+                result |= 8;
+              else
+                {
+                  struct stat st0;
+                  if (fstat (fd, &st0) != 0)
+                    result |= 16;
+                  else
+                    {
+                      char c;
+                      sleep (1);
+                      if (read (fd, &c, 1) != 1)
+                        result |= 24;
+                      else
+                        {
+                          if (close (fd) != 0)
+                            result |= 32;
+                          else
+                            {
+                              struct stat st1;
+                              if (stat (file, &st1) != 0)
+                                result |= 40;
+                              else
+                                if (st0.st_atime != st1.st_atime)
+                                  result |= 64;
+                            }
+                        }
+                    }
+                }
+            }
+            return result;]])],
+       [gl_cv_header_working_fcntl_h=yes],
+       [case $? in #(
+        4) gl_cv_header_working_fcntl_h='no (bad O_NOFOLLOW)';; #(
+        64) gl_cv_header_working_fcntl_h='no (bad O_NOATIME)';; #(
+        68) gl_cv_header_working_fcntl_h='no (bad O_NOATIME, O_NOFOLLOW)';; #(
+         *) gl_cv_header_working_fcntl_h='no';;
+        esac],
+       [case "$host_os" in
+                  # Guess 'no' on native Windows.
+          mingw*) gl_cv_header_working_fcntl_h='no' ;;
+          *)      gl_cv_header_working_fcntl_h=cross-compiling ;;
+        esac
+       ])
+    ])
+
+  case $gl_cv_header_working_fcntl_h in #(
+  *O_NOATIME* | no | cross-compiling) ac_val=0;; #(
+  *) ac_val=1;;
+  esac
+  AC_DEFINE_UNQUOTED([HAVE_WORKING_O_NOATIME], [$ac_val],
+    [Define to 1 if O_NOATIME works.])
+
+  case $gl_cv_header_working_fcntl_h in #(
+  *O_NOFOLLOW* | no | cross-compiling) ac_val=0;; #(
+  *) ac_val=1;;
+  esac
+  AC_DEFINE_UNQUOTED([HAVE_WORKING_O_NOFOLLOW], [$ac_val],
+    [Define to 1 if O_NOFOLLOW works.])
+])
diff --git a/m4/glibc2.m4 b/m4/glibc2.m4
new file mode 100644
index 0000000..785bba0
--- /dev/null
+++ b/m4/glibc2.m4
@@ -0,0 +1,31 @@
+# glibc2.m4 serial 3
+dnl Copyright (C) 2000-2002, 2004, 2008, 2010-2016 Free Software Foundation,
+dnl Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+# Test for the GNU C Library, version 2.0 or newer.
+# From Bruno Haible.
+
+AC_DEFUN([gt_GLIBC2],
+  [
+    AC_CACHE_CHECK([whether we are using the GNU C Library 2 or newer],
+      [ac_cv_gnu_library_2],
+      [AC_EGREP_CPP([Lucky GNU user],
+        [
+#include <features.h>
+#ifdef __GNU_LIBRARY__
+ #if (__GLIBC__ >= 2) && !defined __UCLIBC__
+  Lucky GNU user
+ #endif
+#endif
+        ],
+        [ac_cv_gnu_library_2=yes],
+        [ac_cv_gnu_library_2=no])
+      ]
+    )
+    AC_SUBST([GLIBC2])
+    GLIBC2="$ac_cv_gnu_library_2"
+  ]
+)
diff --git a/m4/glibc21.m4 b/m4/glibc21.m4
new file mode 100644
index 0000000..dafebf5
--- /dev/null
+++ b/m4/glibc21.m4
@@ -0,0 +1,34 @@
+# glibc21.m4 serial 5
+dnl Copyright (C) 2000-2002, 2004, 2008, 2010-2016 Free Software Foundation,
+dnl Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+# Test for the GNU C Library, version 2.1 or newer, or uClibc.
+# From Bruno Haible.
+
+AC_DEFUN([gl_GLIBC21],
+  [
+    AC_CACHE_CHECK([whether we are using the GNU C Library >= 2.1 or uClibc],
+      [ac_cv_gnu_library_2_1],
+      [AC_EGREP_CPP([Lucky],
+        [
+#include <features.h>
+#ifdef __GNU_LIBRARY__
+ #if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)
+  Lucky GNU user
+ #endif
+#endif
+#ifdef __UCLIBC__
+ Lucky user
+#endif
+        ],
+        [ac_cv_gnu_library_2_1=yes],
+        [ac_cv_gnu_library_2_1=no])
+      ]
+    )
+    AC_SUBST([GLIBC21])
+    GLIBC21="$ac_cv_gnu_library_2_1"
+  ]
+)
diff --git a/m4/intdiv0.m4 b/m4/intdiv0.m4
new file mode 100644
index 0000000..c1034c7
--- /dev/null
+++ b/m4/intdiv0.m4
@@ -0,0 +1,90 @@
+# intdiv0.m4 serial 7 (gettext-0.20.2)
+dnl Copyright (C) 2002, 2007-2008, 2010-2020 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([gt_INTDIV0],
+[
+  AC_REQUIRE([AC_PROG_CC])dnl
+  AC_REQUIRE([AC_CANONICAL_HOST])dnl
+
+  AC_CACHE_CHECK([whether integer division by zero raises SIGFPE],
+    gt_cv_int_divbyzero_sigfpe,
+    [
+      gt_cv_int_divbyzero_sigfpe=
+changequote(,)dnl
+      case "$host_os" in
+        macos* | darwin[6-9]* | darwin[1-9][0-9]*)
+          # On Mac OS X 10.2 or newer, just assume the same as when cross-
+          # compiling. If we were to perform the real test, 1 Crash Report
+          # dialog window would pop up.
+          case "$host_cpu" in
+            i[34567]86 | x86_64)
+              gt_cv_int_divbyzero_sigfpe="guessing yes" ;;
+          esac
+          ;;
+      esac
+changequote([,])dnl
+      if test -z "$gt_cv_int_divbyzero_sigfpe"; then
+        AC_RUN_IFELSE(
+          [AC_LANG_SOURCE([[
+#include <stdlib.h> /* for exit() */
+#include <signal.h>
+#if !(defined _WIN32 && !defined __CYGWIN__)
+#include <unistd.h> /* for _exit() */
+#endif
+
+static void
+sigfpe_handler (int sig)
+{
+  /* Exit with code 0 if SIGFPE, with code 1 if any other signal.  */
+  _exit (sig != SIGFPE);
+}
+
+int x = 1;
+int y = 0;
+int z;
+int nan;
+
+int main ()
+{
+  signal (SIGFPE, sigfpe_handler);
+/* IRIX and AIX (when "xlc -qcheck" is used) yield signal SIGTRAP.  */
+#if (defined (__sgi) || defined (_AIX)) && defined (SIGTRAP)
+  signal (SIGTRAP, sigfpe_handler);
+#endif
+/* Linux/SPARC yields signal SIGILL.  */
+#if defined (__sparc__) && defined (__linux__)
+  signal (SIGILL, sigfpe_handler);
+#endif
+
+  z = x / y;
+  nan = y / y;
+  exit (2);
+}
+]])],
+          [gt_cv_int_divbyzero_sigfpe=yes],
+          [gt_cv_int_divbyzero_sigfpe=no],
+          [
+            # Guess based on the CPU.
+changequote(,)dnl
+            case "$host_cpu" in
+              alpha* | i[34567]86 | x86_64 | m68k | s390*)
+                gt_cv_int_divbyzero_sigfpe="guessing yes";;
+              *)
+                gt_cv_int_divbyzero_sigfpe="guessing no";;
+            esac
+changequote([,])dnl
+          ])
+      fi
+    ])
+  case "$gt_cv_int_divbyzero_sigfpe" in
+    *yes) value=1;;
+    *) value=0;;
+  esac
+  AC_DEFINE_UNQUOTED([INTDIV0_RAISES_SIGFPE], [$value],
+    [Define if integer division by zero raises signal SIGFPE.])
+])
diff --git a/m4/intl-thread-locale.m4 b/m4/intl-thread-locale.m4
new file mode 100644
index 0000000..890fec0
--- /dev/null
+++ b/m4/intl-thread-locale.m4
@@ -0,0 +1,219 @@
+# intl-thread-locale.m4 serial 9
+dnl Copyright (C) 2015-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Check how to retrieve the name of a per-thread locale (POSIX locale_t).
+dnl Sets gt_nameless_locales.
+AC_DEFUN([gt_INTL_THREAD_LOCALE_NAME],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST])
+
+  dnl Persuade Solaris <locale.h> to define 'locale_t'.
+  AC_REQUIRE([AC_USE_SYSTEM_EXTENSIONS])
+
+  dnl Test whether uselocale() exists and works at all.
+  gt_FUNC_USELOCALE
+
+  dnl On OpenBSD >= 6.2, the locale_t type and the uselocale(), newlocale(),
+  dnl duplocale(), freelocale() functions exist but are effectively useless,
+  dnl because the locale_t value depends only on the LC_CTYPE category of the
+  dnl locale and furthermore contains only one bit of information (it
+  dnl distinguishes the "C" locale from the *.UTF-8 locales). See
+  dnl <https://cvsweb.openbsd.org/src/lib/libc/locale/newlocale.c?rev=1.1&content-type=text/x-cvsweb-markup>.
+  dnl In the setlocale() implementation they have thought about the programs
+  dnl that use the API ("Even though only LC_CTYPE has any effect in the
+  dnl OpenBSD base system, store complete information about the global locale,
+  dnl such that third-party software can access it"), but for uselocale()
+  dnl they did not think about the programs.
+  dnl In this situation, even the HAVE_NAMELESS_LOCALES support does not work.
+  dnl So, define HAVE_FAKE_LOCALES and disable all locale_t support.
+  case "$gt_cv_func_uselocale_works" in
+    *yes)
+      AC_CHECK_HEADERS_ONCE([xlocale.h])
+      AC_CACHE_CHECK([for fake locale system (OpenBSD)],
+        [gt_cv_locale_fake],
+        [AC_RUN_IFELSE(
+           [AC_LANG_SOURCE([[
+#include <locale.h>
+#if HAVE_XLOCALE_H
+# include <xlocale.h>
+#endif
+int main ()
+{
+  locale_t loc1, loc2;
+  if (setlocale (LC_ALL, "de_DE.UTF-8") == NULL) return 1;
+  if (setlocale (LC_ALL, "fr_FR.UTF-8") == NULL) return 1;
+  loc1 = newlocale (LC_ALL_MASK, "de_DE.UTF-8", (locale_t)0);
+  loc2 = newlocale (LC_ALL_MASK, "fr_FR.UTF-8", (locale_t)0);
+  return !(loc1 == loc2);
+}]])],
+           [gt_cv_locale_fake=yes],
+           [gt_cv_locale_fake=no],
+           [dnl Guess the locale system is fake only on OpenBSD.
+            case "$host_os" in
+              openbsd*) gt_cv_locale_fake="guessing yes" ;;
+              *)        gt_cv_locale_fake="guessing no" ;;
+            esac
+           ])
+        ])
+      ;;
+    *) gt_cv_locale_fake=no ;;
+  esac
+  case "$gt_cv_locale_fake" in
+    *yes)
+      gt_fake_locales=yes
+      AC_DEFINE([HAVE_FAKE_LOCALES], [1],
+        [Define if the locale_t type contains insufficient information, as on OpenBSD.])
+      ;;
+    *)
+      gt_fake_locales=no
+      ;;
+  esac
+
+  case "$gt_cv_func_uselocale_works" in
+    *yes)
+      AC_CACHE_CHECK([for Solaris 11.4 locale system],
+        [gt_cv_locale_solaris114],
+        [case "$host_os" in
+           solaris*)
+             dnl Test whether <locale.h> defines locale_t as a typedef of
+             dnl 'struct _LC_locale_t **' (whereas Illumos defines it as a
+             dnl typedef of 'struct _locale *').
+             dnl Another possible test would be to include <sys/localedef.h>
+             dnl and test whether it defines the _LC_core_data_locale_t type.
+             dnl This type was added in Solaris 11.4.
+             AC_COMPILE_IFELSE(
+               [AC_LANG_PROGRAM([[
+                  #include <locale.h>
+                  struct _LC_locale_t *x;
+                  locale_t y;
+                ]],
+                [[*y = x;]])],
+               [gt_cv_locale_solaris114=yes],
+               [gt_cv_locale_solaris114=no])
+             ;;
+           *) gt_cv_locale_solaris114=no ;;
+         esac
+        ])
+      ;;
+    *) gt_cv_locale_solaris114=no ;;
+  esac
+  if test $gt_cv_locale_solaris114 = yes; then
+    AC_DEFINE([HAVE_SOLARIS114_LOCALES], [1],
+      [Define if the locale_t type is as on Solaris 11.4.])
+  fi
+
+  dnl Solaris 12 will maybe provide getlocalename_l.  If it does, it will
+  dnl improve the implementation of gl_locale_name_thread(), by removing
+  dnl the use of undocumented structures.
+  case "$gt_cv_func_uselocale_works" in
+    *yes)
+      AC_CHECK_FUNCS([getlocalename_l])
+      ;;
+  esac
+
+  dnl This code is for platforms where the locale_t type does not provide access
+  dnl to the name of each locale category.  This code has the drawback that it
+  dnl requires the gnulib overrides of 'newlocale', 'duplocale', 'freelocale',
+  dnl which is a problem for GNU libunistring.  Therefore try hard to avoid
+  dnl enabling this code!
+  gt_nameless_locales=no
+  case "$host_os" in
+    dnl It's needed on AIX 7.2.
+    aix*)
+      gt_nameless_locales=yes
+      AC_DEFINE([HAVE_NAMELESS_LOCALES], [1],
+        [Define if the locale_t type does not contain the name of each locale category.])
+      ;;
+  esac
+
+  dnl We cannot support uselocale() on platforms where the locale_t type is
+  dnl fake.  So, set
+  dnl   gt_good_uselocale = gt_working_uselocale && !gt_fake_locales.
+  if test $gt_working_uselocale = yes && test $gt_fake_locales = no; then
+    gt_good_uselocale=yes
+    AC_DEFINE([HAVE_GOOD_USELOCALE], [1],
+      [Define if the uselocale exists, may be safely called, and returns sufficient information.])
+  else
+    gt_good_uselocale=no
+  fi
+
+  dnl Set gt_localename_enhances_locale_funcs to indicate whether localename.c
+  dnl overrides newlocale(), duplocale(), freelocale() to keep track of locale
+  dnl names.
+  if test $gt_good_uselocale = yes && test $gt_nameless_locales = yes; then
+    gt_localename_enhances_locale_funcs=yes
+    LOCALENAME_ENHANCE_LOCALE_FUNCS=1
+    AC_DEFINE([LOCALENAME_ENHANCE_LOCALE_FUNCS], [1],
+      [Define if localename.c overrides newlocale(), duplocale(), freelocale().])
+  else
+    gt_localename_enhances_locale_funcs=no
+  fi
+])
+
+dnl Tests whether uselocale() exists and is usable.
+dnl Sets gt_working_uselocale and defines HAVE_WORKING_USELOCALE.
+AC_DEFUN([gt_FUNC_USELOCALE],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST]) dnl for cross-compiles
+
+  dnl Persuade glibc and Solaris <locale.h> to define 'locale_t'.
+  AC_REQUIRE([AC_USE_SYSTEM_EXTENSIONS])
+
+  AC_CHECK_FUNCS_ONCE([uselocale])
+
+  dnl On AIX 7.2, the uselocale() function is not documented and leads to
+  dnl crashes in subsequent setlocale() invocations.
+  dnl In 2019, some versions of z/OS lack the locale_t type and have a broken
+  dnl uselocale function.
+  if test $ac_cv_func_uselocale = yes; then
+    AC_CHECK_HEADERS_ONCE([xlocale.h])
+    AC_CACHE_CHECK([whether uselocale works],
+      [gt_cv_func_uselocale_works],
+      [AC_RUN_IFELSE(
+         [AC_LANG_SOURCE([[
+#include <locale.h>
+#if HAVE_XLOCALE_H
+# include <xlocale.h>
+#endif
+locale_t loc1;
+int main ()
+{
+  uselocale (NULL);
+  setlocale (LC_ALL, "en_US.UTF-8");
+  return 0;
+}]])],
+         [gt_cv_func_uselocale_works=yes],
+         [gt_cv_func_uselocale_works=no],
+         [# Guess no on AIX and z/OS, yes otherwise.
+          case "$host_os" in
+            aix* | openedition*) gt_cv_func_uselocale_works="guessing no" ;;
+            *)                   gt_cv_func_uselocale_works="guessing yes" ;;
+          esac
+         ])
+      ])
+  else
+    gt_cv_func_uselocale_works=no
+  fi
+  case "$gt_cv_func_uselocale_works" in
+    *yes)
+      gt_working_uselocale=yes
+      AC_DEFINE([HAVE_WORKING_USELOCALE], [1],
+        [Define if the uselocale function exists and may safely be called.])
+      ;;
+    *)
+      gt_working_uselocale=no
+      ;;
+  esac
+])
diff --git a/m4/intl.m4 b/m4/intl.m4
new file mode 100644
index 0000000..043176d
--- /dev/null
+++ b/m4/intl.m4
@@ -0,0 +1,287 @@
+# intl.m4 serial 44 (gettext-0.21)
+dnl Copyright (C) 1995-2014, 2016-2020 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl   Bruno Haible <haible@clisp.cons.org>, 2000-2009.
+
+AC_PREREQ([2.60])
+
+dnl Checks for all prerequisites of the intl subdirectory,
+dnl except for LIBTOOL, USE_INCLUDED_LIBINTL, BUILD_INCLUDED_LIBINTL.
+AC_DEFUN([AM_INTL_SUBDIR],
+[
+  AC_REQUIRE([AC_PROG_INSTALL])dnl
+  AC_REQUIRE([AC_PROG_MKDIR_P])dnl
+  AC_REQUIRE([AC_PROG_CC])dnl
+  AC_REQUIRE([AC_CANONICAL_HOST])dnl
+  AC_REQUIRE([gt_GLIBC2])dnl
+  AC_REQUIRE([gl_VISIBILITY])dnl
+  AC_REQUIRE([gt_INTL_SUBDIR_CORE])dnl
+  AC_REQUIRE([AC_TYPE_LONG_LONG_INT])dnl
+  AC_REQUIRE([gt_TYPE_WCHAR_T])dnl
+  AC_REQUIRE([gt_TYPE_WINT_T])dnl
+  AC_REQUIRE([gl_AC_HEADER_INTTYPES_H])
+  AC_REQUIRE([gt_TYPE_INTMAX_T])
+  AC_REQUIRE([gt_PRINTF_POSIX])
+  AC_REQUIRE([gl_GLIBC21])dnl
+  AC_REQUIRE([gl_XSIZE])dnl
+  AC_REQUIRE([gl_FCNTL_O_FLAGS])dnl
+  AC_REQUIRE([gt_INTL_THREAD_LOCALE_NAME])
+  AC_REQUIRE([gt_INTL_MACOSX])dnl
+  AC_REQUIRE([gl_EXTERN_INLINE])dnl
+  AC_REQUIRE([gt_GL_ATTRIBUTE])dnl
+  AC_REQUIRE([AC_C_FLEXIBLE_ARRAY_MEMBER])dnl
+
+  dnl In projects that use gnulib, use gl_PROG_AR_RANLIB.
+  dnl The '][' hides this use from 'aclocal'.
+  m4_ifdef([g][l_PROG_AR_RANLIB],
+    [AC_REQUIRE([g][l_PROG_AR_RANLIB])],
+    [AC_REQUIRE([AC_PROG_RANLIB])
+     dnl Use Automake-documented default values for AR and ARFLAGS, but prefer
+     dnl ${host}-ar over ar (useful for cross-compiling).
+     AC_CHECK_TOOL([AR], [ar], [ar])
+     if test -z "$ARFLAGS"; then
+       ARFLAGS='cr'
+     fi
+     AC_SUBST([AR])
+     AC_SUBST([ARFLAGS])
+    ])
+
+  dnl Support for automake's --enable-silent-rules.
+  case "$enable_silent_rules" in
+    yes) INTL_DEFAULT_VERBOSITY=0;;
+    no)  INTL_DEFAULT_VERBOSITY=1;;
+    *)   INTL_DEFAULT_VERBOSITY=1;;
+  esac
+  AC_SUBST([INTL_DEFAULT_VERBOSITY])
+
+  AC_CHECK_TYPE([ptrdiff_t], ,
+    [AC_DEFINE([ptrdiff_t], [long],
+       [Define as the type of the result of subtracting two pointers, if the system doesn't define it.])
+    ])
+  AC_CHECK_HEADERS([features.h stddef.h stdlib.h string.h])
+  AC_CHECK_FUNCS([asprintf wprintf newlocale putenv setenv \
+    snprintf strnlen uselocale wcslen wcsnlen mbrtowc wcrtomb])
+
+  dnl Use the _snprintf function only if it is declared (because on NetBSD it
+  dnl is defined as a weak alias of snprintf; we prefer to use the latter).
+  AC_CHECK_DECLS([_snprintf, _snwprintf], , , [#include <stdio.h>])
+
+  dnl Use the *_unlocked functions only if they are declared.
+  dnl (because some of them were defined without being declared in Solaris
+  dnl 2.5.1 but were removed in Solaris 2.6, whereas we want binaries built
+  dnl on Solaris 2.5.1 to run on Solaris 2.6).
+  AC_CHECK_DECLS([getc_unlocked], , , [#include <stdio.h>])
+
+  case $gt_cv_func_printf_posix in
+    *yes) HAVE_POSIX_PRINTF=1 ;;
+    *) HAVE_POSIX_PRINTF=0 ;;
+  esac
+  AC_SUBST([HAVE_POSIX_PRINTF])
+  if test "$ac_cv_func_asprintf" = yes; then
+    HAVE_ASPRINTF=1
+  else
+    HAVE_ASPRINTF=0
+  fi
+  AC_SUBST([HAVE_ASPRINTF])
+  if test "$ac_cv_func_snprintf" = yes; then
+    HAVE_SNPRINTF=1
+  else
+    HAVE_SNPRINTF=0
+  fi
+  AC_SUBST([HAVE_SNPRINTF])
+  if test "$ac_cv_func_newlocale" = yes; then
+    HAVE_NEWLOCALE=1
+  else
+    HAVE_NEWLOCALE=0
+  fi
+  AC_SUBST([HAVE_NEWLOCALE])
+  if test "$ac_cv_func_wprintf" = yes; then
+    HAVE_WPRINTF=1
+  else
+    HAVE_WPRINTF=0
+  fi
+  AC_SUBST([HAVE_WPRINTF])
+
+  AM_LANGINFO_CODESET
+  gt_LC_MESSAGES
+
+  if test $gt_nameless_locales = yes; then
+    HAVE_NAMELESS_LOCALES=1
+  else
+    HAVE_NAMELESS_LOCALES=0
+  fi
+  AC_SUBST([HAVE_NAMELESS_LOCALES])
+
+  dnl Compilation on mingw and Cygwin needs special Makefile rules, because
+  dnl 1. when we install a shared library, we must arrange to export
+  dnl    auxiliary pointer variables for every exported variable,
+  dnl 2. when we install a shared library and a static library simultaneously,
+  dnl    the include file specifies __declspec(dllimport) and therefore we
+  dnl    must arrange to define the auxiliary pointer variables for the
+  dnl    exported variables _also_ in the static library.
+  if test "$enable_shared" = yes; then
+    case "$host_os" in
+      mingw* | cygwin*) is_woe32dll=yes ;;
+      *) is_woe32dll=no ;;
+    esac
+  else
+    is_woe32dll=no
+  fi
+  WOE32DLL=$is_woe32dll
+  AC_SUBST([WOE32DLL])
+
+  dnl On mingw and Cygwin, we can activate special Makefile rules which add
+  dnl version information to the shared libraries and executables.
+  case "$host_os" in
+    mingw* | cygwin*) is_woe32=yes ;;
+    *) is_woe32=no ;;
+  esac
+  WOE32=$is_woe32
+  AC_SUBST([WOE32])
+  if test $WOE32 = yes; then
+    dnl Check for a program that compiles Windows resource files.
+    AC_CHECK_TOOL([WINDRES], [windres])
+  fi
+
+  dnl Rename some macros and functions used for locking.
+  AH_BOTTOM([
+#define __libc_lock_t                   gl_lock_t
+#define __libc_lock_define              gl_lock_define
+#define __libc_lock_define_initialized  gl_lock_define_initialized
+#define __libc_lock_init                gl_lock_init
+#define __libc_lock_lock                gl_lock_lock
+#define __libc_lock_unlock              gl_lock_unlock
+#define __libc_lock_recursive_t                   gl_recursive_lock_t
+#define __libc_lock_define_recursive              gl_recursive_lock_define
+#define __libc_lock_define_initialized_recursive  gl_recursive_lock_define_initialized
+#define __libc_lock_init_recursive                gl_recursive_lock_init
+#define __libc_lock_lock_recursive                gl_recursive_lock_lock
+#define __libc_lock_unlock_recursive              gl_recursive_lock_unlock
+#define glthread_in_use  libintl_thread_in_use
+#define glthread_lock_init_func     libintl_lock_init_func
+#define glthread_lock_lock_func     libintl_lock_lock_func
+#define glthread_lock_unlock_func   libintl_lock_unlock_func
+#define glthread_lock_destroy_func  libintl_lock_destroy_func
+#define glthread_rwlock_init_multithreaded     libintl_rwlock_init_multithreaded
+#define glthread_rwlock_init_func              libintl_rwlock_init_func
+#define glthread_rwlock_rdlock_multithreaded   libintl_rwlock_rdlock_multithreaded
+#define glthread_rwlock_rdlock_func            libintl_rwlock_rdlock_func
+#define glthread_rwlock_wrlock_multithreaded   libintl_rwlock_wrlock_multithreaded
+#define glthread_rwlock_wrlock_func            libintl_rwlock_wrlock_func
+#define glthread_rwlock_unlock_multithreaded   libintl_rwlock_unlock_multithreaded
+#define glthread_rwlock_unlock_func            libintl_rwlock_unlock_func
+#define glthread_rwlock_destroy_multithreaded  libintl_rwlock_destroy_multithreaded
+#define glthread_rwlock_destroy_func           libintl_rwlock_destroy_func
+#define glthread_recursive_lock_init_multithreaded     libintl_recursive_lock_init_multithreaded
+#define glthread_recursive_lock_init_func              libintl_recursive_lock_init_func
+#define glthread_recursive_lock_lock_multithreaded     libintl_recursive_lock_lock_multithreaded
+#define glthread_recursive_lock_lock_func              libintl_recursive_lock_lock_func
+#define glthread_recursive_lock_unlock_multithreaded   libintl_recursive_lock_unlock_multithreaded
+#define glthread_recursive_lock_unlock_func            libintl_recursive_lock_unlock_func
+#define glthread_recursive_lock_destroy_multithreaded  libintl_recursive_lock_destroy_multithreaded
+#define glthread_recursive_lock_destroy_func           libintl_recursive_lock_destroy_func
+#define glthread_once_func            libintl_once_func
+#define glthread_once_singlethreaded  libintl_once_singlethreaded
+#define glthread_once_multithreaded   libintl_once_multithreaded
+])
+])
+
+
+dnl Checks for the core files of the intl subdirectory:
+dnl   dcigettext.c
+dnl   eval-plural.h
+dnl   explodename.c
+dnl   finddomain.c
+dnl   gettextP.h
+dnl   gmo.h
+dnl   hash-string.h hash-string.c
+dnl   l10nflist.c
+dnl   libgnuintl.h.in (except the *printf stuff)
+dnl   loadinfo.h
+dnl   loadmsgcat.c
+dnl   localealias.c
+dnl   log.c
+dnl   plural-exp.h plural-exp.c
+dnl   plural.y
+dnl Used by libglocale.
+AC_DEFUN([gt_INTL_SUBDIR_CORE],
+[
+  AC_REQUIRE([AC_C_INLINE])dnl
+  AC_REQUIRE([AC_TYPE_SIZE_T])dnl
+  AC_REQUIRE([gl_AC_HEADER_STDINT_H])
+  AC_REQUIRE([AC_FUNC_ALLOCA])dnl
+  AC_REQUIRE([AC_FUNC_MMAP])dnl
+  AC_REQUIRE([gt_INTDIV0])dnl
+  AC_REQUIRE([gl_AC_TYPE_UINTMAX_T])dnl
+  AC_REQUIRE([gl_LOCK])dnl
+
+  AC_LINK_IFELSE(
+    [AC_LANG_PROGRAM(
+       [[int foo (int a) { a = __builtin_expect (a, 10); return a == 10 ? 0 : 1; }]],
+       [[]])],
+    [AC_DEFINE([HAVE_BUILTIN_EXPECT], [1],
+       [Define to 1 if the compiler understands __builtin_expect.])])
+
+  AC_CHECK_HEADERS([inttypes.h limits.h unistd.h sys/param.h])
+  AC_CHECK_FUNCS([getcwd getegid geteuid getgid getuid mempcpy munmap \
+    stpcpy strcasecmp strdup strtoul tsearch __fsetlocking])
+
+  dnl Use the *_unlocked functions only if they are declared.
+  dnl (because some of them were defined without being declared in Solaris
+  dnl 2.5.1 but were removed in Solaris 2.6, whereas we want binaries built
+  dnl on Solaris 2.5.1 to run on Solaris 2.6).
+  AC_CHECK_DECLS([feof_unlocked, fgets_unlocked], , , [#include <stdio.h>])
+
+  AM_ICONV
+
+  dnl intl/plural.c is generated from intl/plural.y. It requires bison,
+  dnl because plural.y uses bison specific features. It requires at least
+  dnl bison-3.0 for %precedence.
+  dnl bison is only needed for the maintainer (who touches plural.y). But in
+  dnl order to avoid separate Makefiles or --enable-maintainer-mode, we put
+  dnl the rule in general Makefile. Now, some people carelessly touch the
+  dnl files or have a broken "make" program, hence the plural.c rule will
+  dnl sometimes fire. To avoid an error, defines BISON to ":" if it is not
+  dnl present or too old.
+  gl_PROG_BISON([INTLBISON], [3.0])
+])
+
+dnl Copies _GL_UNUSED and _GL_ATTRIBUTE_PURE definitions from
+dnl gnulib-common.m4 as a fallback, if the project isn't using Gnulib.
+AC_DEFUN([gt_GL_ATTRIBUTE], [
+  m4_ifndef([gl_[]COMMON],
+    AH_VERBATIM([gt_gl_attribute],
+[/* Define as a marker that can be attached to declarations that might not
+    be used.  This helps to reduce warnings, such as from
+    GCC -Wunused-parameter.  */
+#ifndef _GL_UNUSED
+# if __GNUC__ >= 3 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
+#  define _GL_UNUSED __attribute__ ((__unused__))
+# else
+#  define _GL_UNUSED
+# endif
+#endif
+
+/* The __pure__ attribute was added in gcc 2.96.  */
+#ifndef _GL_ATTRIBUTE_PURE
+# if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+#  define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
+# else
+#  define _GL_ATTRIBUTE_PURE /* empty */
+# endif
+#endif
+]))])
diff --git a/m4/intldir.m4 b/m4/intldir.m4
new file mode 100644
index 0000000..ebae76d
--- /dev/null
+++ b/m4/intldir.m4
@@ -0,0 +1,19 @@
+# intldir.m4 serial 2 (gettext-0.18)
+dnl Copyright (C) 2006, 2009-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Library General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Library General Public License, and the rest of the GNU
+dnl gettext package package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+AC_PREREQ([2.52])
+
+dnl Tells the AM_GNU_GETTEXT macro to consider an intl/ directory.
+AC_DEFUN([AM_GNU_GETTEXT_INTL_SUBDIR], [])
diff --git a/m4/intmax.m4 b/m4/intmax.m4
new file mode 100644
index 0000000..1a47107
--- /dev/null
+++ b/m4/intmax.m4
@@ -0,0 +1,36 @@
+# intmax.m4 serial 6 (gettext-0.18.2)
+dnl Copyright (C) 2002-2005, 2008-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+dnl Test whether the system has the 'intmax_t' type, but don't attempt to
+dnl find a replacement if it is lacking.
+
+AC_DEFUN([gt_TYPE_INTMAX_T],
+[
+  AC_REQUIRE([gl_AC_HEADER_INTTYPES_H])
+  AC_REQUIRE([gl_AC_HEADER_STDINT_H])
+  AC_CACHE_CHECK([for intmax_t], [gt_cv_c_intmax_t],
+    [AC_COMPILE_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[
+#include <stddef.h>
+#include <stdlib.h>
+#if HAVE_STDINT_H_WITH_UINTMAX
+#include <stdint.h>
+#endif
+#if HAVE_INTTYPES_H_WITH_UINTMAX
+#include <inttypes.h>
+#endif
+          ]],
+          [[intmax_t x = -1;
+            return !x;]])],
+       [gt_cv_c_intmax_t=yes],
+       [gt_cv_c_intmax_t=no])])
+  if test $gt_cv_c_intmax_t = yes; then
+    AC_DEFINE([HAVE_INTMAX_T], [1],
+      [Define if you have the 'intmax_t' type in <stdint.h> or <inttypes.h>.])
+  fi
+])
diff --git a/m4/inttypes-pri.m4 b/m4/inttypes-pri.m4
new file mode 100644
index 0000000..ae20183
--- /dev/null
+++ b/m4/inttypes-pri.m4
@@ -0,0 +1,42 @@
+# inttypes-pri.m4 serial 7 (gettext-0.18.2)
+dnl Copyright (C) 1997-2002, 2006, 2008-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_PREREQ([2.53])
+
+# Define PRI_MACROS_BROKEN if <inttypes.h> exists and defines the PRI*
+# macros to non-string values.  This is the case on AIX 4.3.3.
+
+AC_DEFUN([gt_INTTYPES_PRI],
+[
+  AC_CHECK_HEADERS([inttypes.h])
+  if test $ac_cv_header_inttypes_h = yes; then
+    AC_CACHE_CHECK([whether the inttypes.h PRIxNN macros are broken],
+      [gt_cv_inttypes_pri_broken],
+      [
+        AC_COMPILE_IFELSE(
+          [AC_LANG_PROGRAM(
+             [[
+#include <inttypes.h>
+#ifdef PRId32
+char *p = PRId32;
+#endif
+             ]],
+             [[]])],
+          [gt_cv_inttypes_pri_broken=no],
+          [gt_cv_inttypes_pri_broken=yes])
+      ])
+  fi
+  if test "$gt_cv_inttypes_pri_broken" = yes; then
+    AC_DEFINE_UNQUOTED([PRI_MACROS_BROKEN], [1],
+      [Define if <inttypes.h> exists and defines unusable PRI* macros.])
+    PRI_MACROS_BROKEN=1
+  else
+    PRI_MACROS_BROKEN=0
+  fi
+  AC_SUBST([PRI_MACROS_BROKEN])
+])
diff --git a/m4/inttypes_h.m4 b/m4/inttypes_h.m4
new file mode 100644
index 0000000..7657119
--- /dev/null
+++ b/m4/inttypes_h.m4
@@ -0,0 +1,29 @@
+# inttypes_h.m4 serial 10
+dnl Copyright (C) 1997-2004, 2006, 2008-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Paul Eggert.
+
+# Define HAVE_INTTYPES_H_WITH_UINTMAX if <inttypes.h> exists,
+# doesn't clash with <sys/types.h>, and declares uintmax_t.
+
+AC_DEFUN([gl_AC_HEADER_INTTYPES_H],
+[
+  AC_CACHE_CHECK([for inttypes.h], [gl_cv_header_inttypes_h],
+    [AC_COMPILE_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[
+#include <sys/types.h>
+#include <inttypes.h>
+          ]],
+          [[uintmax_t i = (uintmax_t) -1; return !i;]])],
+       [gl_cv_header_inttypes_h=yes],
+       [gl_cv_header_inttypes_h=no])])
+  if test $gl_cv_header_inttypes_h = yes; then
+    AC_DEFINE_UNQUOTED([HAVE_INTTYPES_H_WITH_UINTMAX], [1],
+      [Define if <inttypes.h> exists, doesn't clash with <sys/types.h>,
+       and declares uintmax_t. ])
+  fi
+])
diff --git a/m4/lcmessage.m4 b/m4/lcmessage.m4
new file mode 100644
index 0000000..a52700e
--- /dev/null
+++ b/m4/lcmessage.m4
@@ -0,0 +1,35 @@
+# lcmessage.m4 serial 8
+dnl Copyright (C) 1995-2002, 2004-2005, 2008-2014, 2016, 2019-2021 Free
+dnl Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1995.
+
+# Check whether LC_MESSAGES is available in <locale.h>.
+
+AC_DEFUN([gt_LC_MESSAGES],
+[
+  AC_CACHE_CHECK([for LC_MESSAGES], [gt_cv_val_LC_MESSAGES],
+    [AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <locale.h>]],
+          [[return LC_MESSAGES]])],
+       [gt_cv_val_LC_MESSAGES=yes],
+       [gt_cv_val_LC_MESSAGES=no])])
+  if test $gt_cv_val_LC_MESSAGES = yes; then
+    AC_DEFINE([HAVE_LC_MESSAGES], [1],
+      [Define if your <locale.h> file defines LC_MESSAGES.])
+  fi
+])
diff --git a/m4/libcurl.m4 b/m4/libcurl.m4
index 7e0a3c4..d020920 100644
--- a/m4/libcurl.m4
+++ b/m4/libcurl.m4
@@ -1,3 +1,26 @@
+#***************************************************************************
+#                                  _   _ ____  _
+#  Project                     ___| | | |  _ \| |
+#                             / __| | | | |_) | |
+#                            | (__| |_| |  _ <| |___
+#                             \___|\___/|_| \_\_____|
+#
+# Copyright (C) David Shaw <dshaw@jabberwocky.com>
+#
+# This software is licensed as described in the file COPYING, which
+# you should have received as part of this distribution. The terms
+# are also available at https://curl.se/docs/copyright.html.
+#
+# You may opt to use, copy, modify, merge, publish, distribute and/or sell
+# copies of the Software, and permit persons to whom the Software is
+# furnished to do so, under the terms of the COPYING file.
+#
+# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+# KIND, either express or implied.
+#
+# SPDX-License-Identifier: curl
+#
+###########################################################################
 # LIBCURL_CHECK_CONFIG ([DEFAULT-ACTION], [MINIMUM-VERSION],
 #                       [ACTION-IF-YES], [ACTION-IF-NO])
 # ----------------------------------------------------------
@@ -61,7 +84,7 @@
   AH_TEMPLATE([LIBCURL_PROTOCOL_SMTP],[Defined if libcurl supports SMTP])
 
   AC_ARG_WITH(libcurl,
-     AC_HELP_STRING([--with-libcurl=PREFIX],[look for the curl library in PREFIX/lib and headers in PREFIX/include]),
+     AS_HELP_STRING([--with-libcurl=PREFIX],[look for the curl library in PREFIX/lib and headers in PREFIX/include]),
      [_libcurl_with=$withval],[_libcurl_with=ifelse([$1],,[yes],[$1])])
 
   if test "$_libcurl_with" != "no" ; then
@@ -153,11 +176,11 @@
 curl_easy_setopt(NULL,CURLOPT_URL,NULL);
 x=CURL_ERROR_SIZE;
 x=CURLOPT_WRITEFUNCTION;
-x=CURLOPT_FILE;
+x=CURLOPT_WRITEDATA;
 x=CURLOPT_ERRORBUFFER;
 x=CURLOPT_STDERR;
 x=CURLOPT_VERBOSE;
-if (x) ;
+if (x) {;}
 ]])],libcurl_cv_lib_curl_usable=yes,libcurl_cv_lib_curl_usable=no)
 
            CPPFLAGS=$_libcurl_save_cppflags
@@ -176,9 +199,10 @@
            _libcurl_save_libs=$LIBS
            LIBS="$LIBS $LIBCURL"
 
-           AC_CHECK_FUNC(curl_free,,
-              AC_DEFINE(curl_free,free,
-                [Define curl_free() as free() if our version of curl lacks curl_free.]))
+           AC_CHECK_DECL([curl_free],[],
+              [AC_DEFINE([curl_free],[free],
+                [Define curl_free() as free() if our version of curl lacks curl_free.])],
+              [[#include <curl/curl.h>]])
 
            CPPFLAGS=$_libcurl_save_cppflags
            LIBS=$_libcurl_save_libs
@@ -201,8 +225,6 @@
               # protocols are available
               _libcurl_protocols="HTTP FTP FILE TELNET LDAP DICT TFTP"
 
-              test -z "$_libcurl_version" && _libcurl_version=0
-
               if test x$libcurl_feature_SSL = xyes ; then
                  _libcurl_protocols="$_libcurl_protocols HTTPS"
 
diff --git a/m4/libgcrypt.m4 b/m4/libgcrypt.m4
index 75863ba..19d514f 100644
--- a/m4/libgcrypt.m4
+++ b/m4/libgcrypt.m4
@@ -1,47 +1,74 @@
-dnl Autoconf macros for libgcrypt
-dnl       Copyright (C) 2002, 2004, 2011 Free Software Foundation, Inc.
-dnl       Copyright (C) 2014 Karlson2k (Evgeny Grin)
-dnl
-dnl This file is free software; as a special exception the author gives
-dnl unlimited permission to copy and/or distribute it, with or without
-dnl modifications, as long as this notice is preserved.
-dnl
-dnl This file is distributed in the hope that it will be useful, but
-dnl WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
-dnl implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# libgcrypt.m4 - Autoconf macros to detect libgcrypt
+# Copyright (C) 2002, 2003, 2004, 2011, 2014, 2018, 2020 g10 Code GmbH
+#
+# This file is free software; as a special exception the author gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+#
+# This file is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+#
+# Last-changed: 2020-09-27
 
 
 dnl AM_PATH_LIBGCRYPT([MINIMUM-VERSION,
 dnl                   [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND ]]])
 dnl Test for libgcrypt and define LIBGCRYPT_CFLAGS and LIBGCRYPT_LIBS.
-dnl MINIMUN-VERSION is a string with the version number optionalliy prefixed
+dnl MINIMUM-VERSION is a string with the version number optionally prefixed
 dnl with the API version to also check the API compatibility. Example:
-dnl a MINIMUN-VERSION of 1:1.2.5 won't pass the test unless the installed
+dnl a MINIMUM-VERSION of 1:1.2.5 won't pass the test unless the installed
 dnl version of libgcrypt is at least 1.2.5 *and* the API number is 1.  Using
 dnl this features allows to prevent build against newer versions of libgcrypt
 dnl with a changed API.
 dnl
-dnl Updated by Karlson2k to be more tolerant to host tools variations.
+dnl If a prefix option is not used, the config script is first
+dnl searched in $SYSROOT/bin and then along $PATH.  If the used
+dnl config script does not match the host specification the script
+dnl is added to the gpg_config_script_warn variable.
 dnl
 AC_DEFUN([AM_PATH_LIBGCRYPT],
 [ AC_REQUIRE([AC_CANONICAL_HOST])
-  AC_REQUIRE([AC_PROG_GREP])
-  AC_REQUIRE([AC_PROG_SED])
   AC_ARG_WITH(libgcrypt-prefix,
-            AC_HELP_STRING([--with-libgcrypt-prefix=PFX],
+            AS_HELP_STRING([--with-libgcrypt-prefix=PFX],
                            [prefix where LIBGCRYPT is installed (optional)]),
      libgcrypt_config_prefix="$withval", libgcrypt_config_prefix="")
-  if test x$libgcrypt_config_prefix != x ; then
-     if test x${LIBGCRYPT_CONFIG+set} != xset ; then
-        LIBGCRYPT_CONFIG=$libgcrypt_config_prefix/bin/libgcrypt-config
+  if test x"${LIBGCRYPT_CONFIG}" = x ; then
+     if test x"${libgcrypt_config_prefix}" != x ; then
+        LIBGCRYPT_CONFIG="${libgcrypt_config_prefix}/bin/libgcrypt-config"
      fi
   fi
 
-  AC_PATH_TOOL(LIBGCRYPT_CONFIG, libgcrypt-config, no)
+  use_gpgrt_config=""
+  if test x"${LIBGCRYPT_CONFIG}" = x -a x"$GPGRT_CONFIG" != x -a "$GPGRT_CONFIG" != "no"; then
+    if $GPGRT_CONFIG libgcrypt --exists; then
+      LIBGCRYPT_CONFIG="$GPGRT_CONFIG libgcrypt"
+      AC_MSG_NOTICE([Use gpgrt-config as libgcrypt-config])
+      use_gpgrt_config=yes
+    fi
+  fi
+  if test -z "$use_gpgrt_config"; then
+    if test x"${LIBGCRYPT_CONFIG}" = x ; then
+      case "${SYSROOT}" in
+         /*)
+           if test -x "${SYSROOT}/bin/libgcrypt-config" ; then
+             LIBGCRYPT_CONFIG="${SYSROOT}/bin/libgcrypt-config"
+           fi
+           ;;
+         '')
+           ;;
+          *)
+           AC_MSG_WARN([Ignoring \$SYSROOT as it is not an absolute path.])
+           ;;
+      esac
+    fi
+    AC_PATH_PROG(LIBGCRYPT_CONFIG, libgcrypt-config, no)
+  fi
+
   tmp=ifelse([$1], ,1:1.2.0,$1)
-  if echo "$tmp" | $GREP ':' >/dev/null 2>/dev/null ; then
-     req_libgcrypt_api=`echo "$tmp"     | $SED 's/\(.*\):\(.*\)/\1/'`
-     min_libgcrypt_version=`echo "$tmp" | $SED 's/\(.*\):\(.*\)/\2/'`
+  if echo "$tmp" | grep ':' >/dev/null 2>/dev/null ; then
+     req_libgcrypt_api=`echo "$tmp"     | sed 's/\(.*\):\(.*\)/\1/'`
+     min_libgcrypt_version=`echo "$tmp" | sed 's/\(.*\):\(.*\)/\2/'`
   else
      req_libgcrypt_api=0
      min_libgcrypt_version="$tmp"
@@ -51,18 +78,22 @@
   ok=no
   if test "$LIBGCRYPT_CONFIG" != "no" ; then
     req_major=`echo $min_libgcrypt_version | \
-               $SED 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\1/'`
+               sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\1/'`
     req_minor=`echo $min_libgcrypt_version | \
-               $SED 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\2/'`
+               sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\2/'`
     req_micro=`echo $min_libgcrypt_version | \
-               $SED 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\3/'`
-    libgcrypt_config_version=`$LIBGCRYPT_CONFIG --version`
+               sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\)/\3/'`
+    if test -z "$use_gpgrt_config"; then
+      libgcrypt_config_version=`$LIBGCRYPT_CONFIG --version`
+    else
+      libgcrypt_config_version=`$LIBGCRYPT_CONFIG --modversion`
+    fi
     major=`echo $libgcrypt_config_version | \
-               $SED 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\1/'`
+               sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\1/'`
     minor=`echo $libgcrypt_config_version | \
-               $SED 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\2/'`
+               sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\2/'`
     micro=`echo $libgcrypt_config_version | \
-               $SED 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\3/'`
+               sed 's/\([[0-9]]*\)\.\([[0-9]]*\)\.\([[0-9]]*\).*/\3/'`
     if test "$major" -gt "$req_major"; then
         ok=yes
     else
@@ -88,7 +119,11 @@
      # If we have a recent libgcrypt, we should also check that the
      # API is compatible
      if test "$req_libgcrypt_api" -gt 0 ; then
-        tmp=`$LIBGCRYPT_CONFIG --api-version 2>/dev/null || echo 0`
+        if test -z "$use_gpgrt_config"; then
+           tmp=`$LIBGCRYPT_CONFIG --api-version 2>/dev/null || echo 0`
+	else
+           tmp=`$LIBGCRYPT_CONFIG --variable=api_version 2>/dev/null || echo 0`
+	fi
         if test "$tmp" -gt 0 ; then
            AC_MSG_CHECKING([LIBGCRYPT API version])
            if test "$req_libgcrypt_api" -eq "$tmp" ; then
@@ -104,17 +139,22 @@
     LIBGCRYPT_CFLAGS=`$LIBGCRYPT_CONFIG --cflags`
     LIBGCRYPT_LIBS=`$LIBGCRYPT_CONFIG --libs`
     ifelse([$2], , :, [$2])
-    libgcrypt_config_host=`$LIBGCRYPT_CONFIG --host 2>/dev/null || echo none`
+    if test -z "$use_gpgrt_config"; then
+      libgcrypt_config_host=`$LIBGCRYPT_CONFIG --host 2>/dev/null || echo none`
+    else
+      libgcrypt_config_host=`$LIBGCRYPT_CONFIG --variable=host 2>/dev/null || echo none`
+    fi
     if test x"$libgcrypt_config_host" != xnone ; then
       if test x"$libgcrypt_config_host" != x"$host" ; then
   AC_MSG_WARN([[
 ***
-*** The config script $LIBGCRYPT_CONFIG was
+*** The config script "$LIBGCRYPT_CONFIG" was
 *** built for $libgcrypt_config_host and thus may not match the
 *** used host $host.
 *** You may want to use the configure option --with-libgcrypt-prefix
-*** to specify a matching config script.
+*** to specify a matching config script or use \$SYSROOT.
 ***]])
+        gpg_config_script_warn="$gpg_config_script_warn libgcrypt"
       fi
     fi
   else
diff --git a/m4/libtool.m4 b/m4/libtool.m4
deleted file mode 100644
index d7c043f..0000000
--- a/m4/libtool.m4
+++ /dev/null
@@ -1,7997 +0,0 @@
-# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
-#
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-m4_define([_LT_COPYING], [dnl
-#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
-#                 2006, 2007, 2008, 2009, 2010, 2011 Free Software
-#                 Foundation, Inc.
-#   Written by Gordon Matzigkeit, 1996
-#
-#   This file is part of GNU Libtool.
-#
-# GNU Libtool 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 2 of
-# the License, or (at your option) any later version.
-#
-# As a special exception to the GNU General Public License,
-# if you distribute this file as part of a program or library that
-# is built using GNU Libtool, you may include this file under the
-# same distribution terms that you use for the rest of that program.
-#
-# GNU Libtool 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 GNU Libtool; see the file COPYING.  If not, a copy
-# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
-# obtained by writing to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-])
-
-# serial 57 LT_INIT
-
-
-# LT_PREREQ(VERSION)
-# ------------------
-# Complain and exit if this libtool version is less that VERSION.
-m4_defun([LT_PREREQ],
-[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
-       [m4_default([$3],
-		   [m4_fatal([Libtool version $1 or higher is required],
-		             63)])],
-       [$2])])
-
-
-# _LT_CHECK_BUILDDIR
-# ------------------
-# Complain if the absolute build directory name contains unusual characters
-m4_defun([_LT_CHECK_BUILDDIR],
-[case `pwd` in
-  *\ * | *\	*)
-    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
-esac
-])
-
-
-# LT_INIT([OPTIONS])
-# ------------------
-AC_DEFUN([LT_INIT],
-[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
-AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl
-AC_BEFORE([$0], [LT_LANG])dnl
-AC_BEFORE([$0], [LT_OUTPUT])dnl
-AC_BEFORE([$0], [LTDL_INIT])dnl
-m4_require([_LT_CHECK_BUILDDIR])dnl
-
-dnl Autoconf doesn't catch unexpanded LT_ macros by default:
-m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
-m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
-dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
-dnl unless we require an AC_DEFUNed macro:
-AC_REQUIRE([LTOPTIONS_VERSION])dnl
-AC_REQUIRE([LTSUGAR_VERSION])dnl
-AC_REQUIRE([LTVERSION_VERSION])dnl
-AC_REQUIRE([LTOBSOLETE_VERSION])dnl
-m4_require([_LT_PROG_LTMAIN])dnl
-
-_LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}])
-
-dnl Parse OPTIONS
-_LT_SET_OPTIONS([$0], [$1])
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS="$ltmain"
-
-# Always use our own libtool.
-LIBTOOL='$(SHELL) $(top_builddir)/libtool'
-AC_SUBST(LIBTOOL)dnl
-
-_LT_SETUP
-
-# Only expand once:
-m4_define([LT_INIT])
-])# LT_INIT
-
-# Old names:
-AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
-AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
-dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
-
-
-# _LT_CC_BASENAME(CC)
-# -------------------
-# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
-m4_defun([_LT_CC_BASENAME],
-[for cc_temp in $1""; do
-  case $cc_temp in
-    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
-    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
-])
-
-
-# _LT_FILEUTILS_DEFAULTS
-# ----------------------
-# It is okay to use these file commands and assume they have been set
-# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
-m4_defun([_LT_FILEUTILS_DEFAULTS],
-[: ${CP="cp -f"}
-: ${MV="mv -f"}
-: ${RM="rm -f"}
-])# _LT_FILEUTILS_DEFAULTS
-
-
-# _LT_SETUP
-# ---------
-m4_defun([_LT_SETUP],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl
-AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl
-
-_LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl
-dnl
-_LT_DECL([], [host_alias], [0], [The host system])dnl
-_LT_DECL([], [host], [0])dnl
-_LT_DECL([], [host_os], [0])dnl
-dnl
-_LT_DECL([], [build_alias], [0], [The build system])dnl
-_LT_DECL([], [build], [0])dnl
-_LT_DECL([], [build_os], [0])dnl
-dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([LT_PATH_LD])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-dnl
-AC_REQUIRE([AC_PROG_LN_S])dnl
-test -z "$LN_S" && LN_S="ln -s"
-_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
-dnl
-AC_REQUIRE([LT_CMD_MAX_LEN])dnl
-_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
-_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
-dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_CHECK_SHELL_FEATURES])dnl
-m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl
-m4_require([_LT_CMD_RELOAD])dnl
-m4_require([_LT_CHECK_MAGIC_METHOD])dnl
-m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl
-m4_require([_LT_CMD_OLD_ARCHIVE])dnl
-m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
-m4_require([_LT_WITH_SYSROOT])dnl
-
-_LT_CONFIG_LIBTOOL_INIT([
-# See if we are running on zsh, and set the options which allow our
-# commands through without removal of \ escapes INIT.
-if test -n "\${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-])
-if test -n "${ZSH_VERSION+set}" ; then
-   setopt NO_GLOB_SUBST
-fi
-
-_LT_CHECK_OBJDIR
-
-m4_require([_LT_TAG_COMPILER])dnl
-
-case $host_os in
-aix3*)
-  # AIX sometimes has problems with the GCC collect2 program.  For some
-  # reason, if we set the COLLECT_NAMES environment variable, the problems
-  # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" != Xset; then
-    COLLECT_NAMES=
-    export COLLECT_NAMES
-  fi
-  ;;
-esac
-
-# Global variables:
-ofile=libtool
-can_build_shared=yes
-
-# All known linkers require a `.a' archive for static linking (except MSVC,
-# which needs '.lib').
-libext=a
-
-with_gnu_ld="$lt_cv_prog_gnu_ld"
-
-old_CC="$CC"
-old_CFLAGS="$CFLAGS"
-
-# Set sane defaults for various variables
-test -z "$CC" && CC=cc
-test -z "$LTCC" && LTCC=$CC
-test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
-test -z "$LD" && LD=ld
-test -z "$ac_objext" && ac_objext=o
-
-_LT_CC_BASENAME([$compiler])
-
-# Only perform the check for file, if the check method requires it
-test -z "$MAGIC_CMD" && MAGIC_CMD=file
-case $deplibs_check_method in
-file_magic*)
-  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
-    _LT_PATH_MAGIC
-  fi
-  ;;
-esac
-
-# Use C for the default configuration in the libtool script
-LT_SUPPORTED_TAG([CC])
-_LT_LANG_C_CONFIG
-_LT_LANG_DEFAULT_CONFIG
-_LT_CONFIG_COMMANDS
-])# _LT_SETUP
-
-
-# _LT_PREPARE_SED_QUOTE_VARS
-# --------------------------
-# Define a few sed substitution that help us do robust quoting.
-m4_defun([_LT_PREPARE_SED_QUOTE_VARS],
-[# Backslashify metacharacters that are still active within
-# double-quoted strings.
-sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst='s/\([["`\\]]\)/\\\1/g'
-
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
-
-# Sed substitution to delay expansion of an escaped single quote.
-delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
-
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst='s/\*/\\\*/g'
-])
-
-# _LT_PROG_LTMAIN
-# ---------------
-# Note that this code is called both from `configure', and `config.status'
-# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
-# `config.status' has no value for ac_aux_dir unless we are using Automake,
-# so we pass a copy along to make sure it has a sensible value anyway.
-m4_defun([_LT_PROG_LTMAIN],
-[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
-_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
-ltmain="$ac_aux_dir/ltmain.sh"
-])# _LT_PROG_LTMAIN
-
-
-## ------------------------------------- ##
-## Accumulate code for creating libtool. ##
-## ------------------------------------- ##
-
-# So that we can recreate a full libtool script including additional
-# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
-# in macros and then make a single call at the end using the `libtool'
-# label.
-
-
-# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
-# ----------------------------------------
-# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
-m4_define([_LT_CONFIG_LIBTOOL_INIT],
-[m4_ifval([$1],
-          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
-                     [$1
-])])])
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_INIT])
-
-
-# _LT_CONFIG_LIBTOOL([COMMANDS])
-# ------------------------------
-# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
-m4_define([_LT_CONFIG_LIBTOOL],
-[m4_ifval([$1],
-          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
-                     [$1
-])])])
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
-
-
-# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
-# -----------------------------------------------------
-m4_defun([_LT_CONFIG_SAVE_COMMANDS],
-[_LT_CONFIG_LIBTOOL([$1])
-_LT_CONFIG_LIBTOOL_INIT([$2])
-])
-
-
-# _LT_FORMAT_COMMENT([COMMENT])
-# -----------------------------
-# Add leading comment marks to the start of each line, and a trailing
-# full-stop to the whole comment if one is not present already.
-m4_define([_LT_FORMAT_COMMENT],
-[m4_ifval([$1], [
-m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
-              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
-)])
-
-
-
-## ------------------------ ##
-## FIXME: Eliminate VARNAME ##
-## ------------------------ ##
-
-
-# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
-# -------------------------------------------------------------------
-# CONFIGNAME is the name given to the value in the libtool script.
-# VARNAME is the (base) name used in the configure script.
-# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
-# VARNAME.  Any other value will be used directly.
-m4_define([_LT_DECL],
-[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
-    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
-	[m4_ifval([$1], [$1], [$2])])
-    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
-    m4_ifval([$4],
-	[lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
-    lt_dict_add_subkey([lt_decl_dict], [$2],
-	[tagged?], [m4_ifval([$5], [yes], [no])])])
-])
-
-
-# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
-# --------------------------------------------------------
-m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
-
-
-# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
-# ------------------------------------------------
-m4_define([lt_decl_tag_varnames],
-[_lt_decl_filter([tagged?], [yes], $@)])
-
-
-# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
-# ---------------------------------------------------------
-m4_define([_lt_decl_filter],
-[m4_case([$#],
-  [0], [m4_fatal([$0: too few arguments: $#])],
-  [1], [m4_fatal([$0: too few arguments: $#: $1])],
-  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
-  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
-  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
-])
-
-
-# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
-# --------------------------------------------------
-m4_define([lt_decl_quote_varnames],
-[_lt_decl_filter([value], [1], $@)])
-
-
-# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
-# ---------------------------------------------------
-m4_define([lt_decl_dquote_varnames],
-[_lt_decl_filter([value], [2], $@)])
-
-
-# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
-# ---------------------------------------------------
-m4_define([lt_decl_varnames_tagged],
-[m4_assert([$# <= 2])dnl
-_$0(m4_quote(m4_default([$1], [[, ]])),
-    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
-    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
-m4_define([_lt_decl_varnames_tagged],
-[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
-
-
-# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
-# ------------------------------------------------
-m4_define([lt_decl_all_varnames],
-[_$0(m4_quote(m4_default([$1], [[, ]])),
-     m4_if([$2], [],
-	   m4_quote(lt_decl_varnames),
-	m4_quote(m4_shift($@))))[]dnl
-])
-m4_define([_lt_decl_all_varnames],
-[lt_join($@, lt_decl_varnames_tagged([$1],
-			lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
-])
-
-
-# _LT_CONFIG_STATUS_DECLARE([VARNAME])
-# ------------------------------------
-# Quote a variable value, and forward it to `config.status' so that its
-# declaration there will have the same value as in `configure'.  VARNAME
-# must have a single quote delimited value for this to work.
-m4_define([_LT_CONFIG_STATUS_DECLARE],
-[$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`'])
-
-
-# _LT_CONFIG_STATUS_DECLARATIONS
-# ------------------------------
-# We delimit libtool config variables with single quotes, so when
-# we write them to config.status, we have to be sure to quote all
-# embedded single quotes properly.  In configure, this macro expands
-# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
-#
-#    <var>='`$ECHO "$<var>" | $SED "$delay_single_quote_subst"`'
-m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
-[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
-    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
-
-
-# _LT_LIBTOOL_TAGS
-# ----------------
-# Output comment and list of tags supported by the script
-m4_defun([_LT_LIBTOOL_TAGS],
-[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
-available_tags="_LT_TAGS"dnl
-])
-
-
-# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
-# -----------------------------------
-# Extract the dictionary values for VARNAME (optionally with TAG) and
-# expand to a commented shell variable setting:
-#
-#    # Some comment about what VAR is for.
-#    visible_name=$lt_internal_name
-m4_define([_LT_LIBTOOL_DECLARE],
-[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
-					   [description])))[]dnl
-m4_pushdef([_libtool_name],
-    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
-m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
-    [0], [_libtool_name=[$]$1],
-    [1], [_libtool_name=$lt_[]$1],
-    [2], [_libtool_name=$lt_[]$1],
-    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
-m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
-])
-
-
-# _LT_LIBTOOL_CONFIG_VARS
-# -----------------------
-# Produce commented declarations of non-tagged libtool config variables
-# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
-# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
-# section) are produced by _LT_LIBTOOL_TAG_VARS.
-m4_defun([_LT_LIBTOOL_CONFIG_VARS],
-[m4_foreach([_lt_var],
-    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
-    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
-
-
-# _LT_LIBTOOL_TAG_VARS(TAG)
-# -------------------------
-m4_define([_LT_LIBTOOL_TAG_VARS],
-[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
-    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
-
-
-# _LT_TAGVAR(VARNAME, [TAGNAME])
-# ------------------------------
-m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
-
-
-# _LT_CONFIG_COMMANDS
-# -------------------
-# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
-# variables for single and double quote escaping we saved from calls
-# to _LT_DECL, we can put quote escaped variables declarations
-# into `config.status', and then the shell code to quote escape them in
-# for loops in `config.status'.  Finally, any additional code accumulated
-# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
-m4_defun([_LT_CONFIG_COMMANDS],
-[AC_PROVIDE_IFELSE([LT_OUTPUT],
-	dnl If the libtool generation code has been placed in $CONFIG_LT,
-	dnl instead of duplicating it all over again into config.status,
-	dnl then we will have config.status run $CONFIG_LT later, so it
-	dnl needs to know what name is stored there:
-        [AC_CONFIG_COMMANDS([libtool],
-            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
-    dnl If the libtool generation code is destined for config.status,
-    dnl expand the accumulated commands and init code now:
-    [AC_CONFIG_COMMANDS([libtool],
-        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
-])#_LT_CONFIG_COMMANDS
-
-
-# Initialize.
-m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
-[
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-sed_quote_subst='$sed_quote_subst'
-double_quote_subst='$double_quote_subst'
-delay_variable_subst='$delay_variable_subst'
-_LT_CONFIG_STATUS_DECLARATIONS
-LTCC='$LTCC'
-LTCFLAGS='$LTCFLAGS'
-compiler='$compiler_DEFAULT'
-
-# A function that is used when there is no print builtin or printf.
-func_fallback_echo ()
-{
-  eval 'cat <<_LTECHO_EOF
-\$[]1
-_LTECHO_EOF'
-}
-
-# Quote evaled strings.
-for var in lt_decl_all_varnames([[ \
-]], lt_decl_quote_varnames); do
-    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
-    *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-# Double-quote double-evaled strings.
-for var in lt_decl_all_varnames([[ \
-]], lt_decl_dquote_varnames); do
-    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
-    *[[\\\\\\\`\\"\\\$]]*)
-      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
-      ;;
-    *)
-      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
-      ;;
-    esac
-done
-
-_LT_OUTPUT_LIBTOOL_INIT
-])
-
-# _LT_GENERATED_FILE_INIT(FILE, [COMMENT])
-# ------------------------------------
-# Generate a child script FILE with all initialization necessary to
-# reuse the environment learned by the parent script, and make the
-# file executable.  If COMMENT is supplied, it is inserted after the
-# `#!' sequence but before initialization text begins.  After this
-# macro, additional text can be appended to FILE to form the body of
-# the child script.  The macro ends with non-zero status if the
-# file could not be fully written (such as if the disk is full).
-m4_ifdef([AS_INIT_GENERATED],
-[m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])],
-[m4_defun([_LT_GENERATED_FILE_INIT],
-[m4_require([AS_PREPARE])]dnl
-[m4_pushdef([AS_MESSAGE_LOG_FD])]dnl
-[lt_write_fail=0
-cat >$1 <<_ASEOF || lt_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-$2
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$1 <<\_ASEOF || lt_write_fail=1
-AS_SHELL_SANITIZE
-_AS_PREPARE
-exec AS_MESSAGE_FD>&1
-_ASEOF
-test $lt_write_fail = 0 && chmod +x $1[]dnl
-m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT
-
-# LT_OUTPUT
-# ---------
-# This macro allows early generation of the libtool script (before
-# AC_OUTPUT is called), incase it is used in configure for compilation
-# tests.
-AC_DEFUN([LT_OUTPUT],
-[: ${CONFIG_LT=./config.lt}
-AC_MSG_NOTICE([creating $CONFIG_LT])
-_LT_GENERATED_FILE_INIT(["$CONFIG_LT"],
-[# Run this file to recreate a libtool stub with the current configuration.])
-
-cat >>"$CONFIG_LT" <<\_LTEOF
-lt_cl_silent=false
-exec AS_MESSAGE_LOG_FD>>config.log
-{
-  echo
-  AS_BOX([Running $as_me.])
-} >&AS_MESSAGE_LOG_FD
-
-lt_cl_help="\
-\`$as_me' creates a local libtool stub from the current configuration,
-for use in further configure time tests before the real libtool is
-generated.
-
-Usage: $[0] [[OPTIONS]]
-
-  -h, --help      print this help, then exit
-  -V, --version   print version number, then exit
-  -q, --quiet     do not print progress messages
-  -d, --debug     don't remove temporary files
-
-Report bugs to <bug-libtool@gnu.org>."
-
-lt_cl_version="\
-m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
-m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
-configured by $[0], generated by m4_PACKAGE_STRING.
-
-Copyright (C) 2011 Free Software Foundation, Inc.
-This config.lt script is free software; the Free Software Foundation
-gives unlimited permision to copy, distribute and modify it."
-
-while test $[#] != 0
-do
-  case $[1] in
-    --version | --v* | -V )
-      echo "$lt_cl_version"; exit 0 ;;
-    --help | --h* | -h )
-      echo "$lt_cl_help"; exit 0 ;;
-    --debug | --d* | -d )
-      debug=: ;;
-    --quiet | --q* | --silent | --s* | -q )
-      lt_cl_silent=: ;;
-
-    -*) AC_MSG_ERROR([unrecognized option: $[1]
-Try \`$[0] --help' for more information.]) ;;
-
-    *) AC_MSG_ERROR([unrecognized argument: $[1]
-Try \`$[0] --help' for more information.]) ;;
-  esac
-  shift
-done
-
-if $lt_cl_silent; then
-  exec AS_MESSAGE_FD>/dev/null
-fi
-_LTEOF
-
-cat >>"$CONFIG_LT" <<_LTEOF
-_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
-_LTEOF
-
-cat >>"$CONFIG_LT" <<\_LTEOF
-AC_MSG_NOTICE([creating $ofile])
-_LT_OUTPUT_LIBTOOL_COMMANDS
-AS_EXIT(0)
-_LTEOF
-chmod +x "$CONFIG_LT"
-
-# configure is writing to config.log, but config.lt does its own redirection,
-# appending to config.log, which fails on DOS, as config.log is still kept
-# open by configure.  Here we exec the FD to /dev/null, effectively closing
-# config.log, so it can be properly (re)opened and appended to by config.lt.
-lt_cl_success=:
-test "$silent" = yes &&
-  lt_config_lt_args="$lt_config_lt_args --quiet"
-exec AS_MESSAGE_LOG_FD>/dev/null
-$SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
-exec AS_MESSAGE_LOG_FD>>config.log
-$lt_cl_success || AS_EXIT(1)
-])# LT_OUTPUT
-
-
-# _LT_CONFIG(TAG)
-# ---------------
-# If TAG is the built-in tag, create an initial libtool script with a
-# default configuration from the untagged config vars.  Otherwise add code
-# to config.status for appending the configuration named by TAG from the
-# matching tagged config vars.
-m4_defun([_LT_CONFIG],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-_LT_CONFIG_SAVE_COMMANDS([
-  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
-  m4_if(_LT_TAG, [C], [
-    # See if we are running on zsh, and set the options which allow our
-    # commands through without removal of \ escapes.
-    if test -n "${ZSH_VERSION+set}" ; then
-      setopt NO_GLOB_SUBST
-    fi
-
-    cfgfile="${ofile}T"
-    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
-    $RM "$cfgfile"
-
-    cat <<_LT_EOF >> "$cfgfile"
-#! $SHELL
-
-# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
-# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
-# NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
-_LT_COPYING
-_LT_LIBTOOL_TAGS
-
-# ### BEGIN LIBTOOL CONFIG
-_LT_LIBTOOL_CONFIG_VARS
-_LT_LIBTOOL_TAG_VARS
-# ### END LIBTOOL CONFIG
-
-_LT_EOF
-
-  case $host_os in
-  aix3*)
-    cat <<\_LT_EOF >> "$cfgfile"
-# AIX sometimes has problems with the GCC collect2 program.  For some
-# reason, if we set the COLLECT_NAMES environment variable, the problems
-# vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" != Xset; then
-  COLLECT_NAMES=
-  export COLLECT_NAMES
-fi
-_LT_EOF
-    ;;
-  esac
-
-  _LT_PROG_LTMAIN
-
-  # We use sed instead of cat because bash on DJGPP gets confused if
-  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
-  # text mode, it properly converts lines to CR/LF.  This bash problem
-  # is reportedly fixed, but why not run on old versions too?
-  sed '$q' "$ltmain" >> "$cfgfile" \
-     || (rm -f "$cfgfile"; exit 1)
-
-  _LT_PROG_REPLACE_SHELLFNS
-
-   mv -f "$cfgfile" "$ofile" ||
-    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
-  chmod +x "$ofile"
-],
-[cat <<_LT_EOF >> "$ofile"
-
-dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
-dnl in a comment (ie after a #).
-# ### BEGIN LIBTOOL TAG CONFIG: $1
-_LT_LIBTOOL_TAG_VARS(_LT_TAG)
-# ### END LIBTOOL TAG CONFIG: $1
-_LT_EOF
-])dnl /m4_if
-],
-[m4_if([$1], [], [
-    PACKAGE='$PACKAGE'
-    VERSION='$VERSION'
-    TIMESTAMP='$TIMESTAMP'
-    RM='$RM'
-    ofile='$ofile'], [])
-])dnl /_LT_CONFIG_SAVE_COMMANDS
-])# _LT_CONFIG
-
-
-# LT_SUPPORTED_TAG(TAG)
-# ---------------------
-# Trace this macro to discover what tags are supported by the libtool
-# --tag option, using:
-#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
-AC_DEFUN([LT_SUPPORTED_TAG], [])
-
-
-# C support is built-in for now
-m4_define([_LT_LANG_C_enabled], [])
-m4_define([_LT_TAGS], [])
-
-
-# LT_LANG(LANG)
-# -------------
-# Enable libtool support for the given language if not already enabled.
-AC_DEFUN([LT_LANG],
-[AC_BEFORE([$0], [LT_OUTPUT])dnl
-m4_case([$1],
-  [C],			[_LT_LANG(C)],
-  [C++],		[_LT_LANG(CXX)],
-  [Go],			[_LT_LANG(GO)],
-  [Java],		[_LT_LANG(GCJ)],
-  [Fortran 77],		[_LT_LANG(F77)],
-  [Fortran],		[_LT_LANG(FC)],
-  [Windows Resource],	[_LT_LANG(RC)],
-  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
-    [_LT_LANG($1)],
-    [m4_fatal([$0: unsupported language: "$1"])])])dnl
-])# LT_LANG
-
-
-# _LT_LANG(LANGNAME)
-# ------------------
-m4_defun([_LT_LANG],
-[m4_ifdef([_LT_LANG_]$1[_enabled], [],
-  [LT_SUPPORTED_TAG([$1])dnl
-  m4_append([_LT_TAGS], [$1 ])dnl
-  m4_define([_LT_LANG_]$1[_enabled], [])dnl
-  _LT_LANG_$1_CONFIG($1)])dnl
-])# _LT_LANG
-
-
-m4_ifndef([AC_PROG_GO], [
-############################################################
-# NOTE: This macro has been submitted for inclusion into   #
-#  GNU Autoconf as AC_PROG_GO.  When it is available in    #
-#  a released version of Autoconf we should remove this    #
-#  macro and use it instead.                               #
-############################################################
-m4_defun([AC_PROG_GO],
-[AC_LANG_PUSH(Go)dnl
-AC_ARG_VAR([GOC],     [Go compiler command])dnl
-AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl
-_AC_ARG_VAR_LDFLAGS()dnl
-AC_CHECK_TOOL(GOC, gccgo)
-if test -z "$GOC"; then
-  if test -n "$ac_tool_prefix"; then
-    AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo])
-  fi
-fi
-if test -z "$GOC"; then
-  AC_CHECK_PROG(GOC, gccgo, gccgo, false)
-fi
-])#m4_defun
-])#m4_ifndef
-
-
-# _LT_LANG_DEFAULT_CONFIG
-# -----------------------
-m4_defun([_LT_LANG_DEFAULT_CONFIG],
-[AC_PROVIDE_IFELSE([AC_PROG_CXX],
-  [LT_LANG(CXX)],
-  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
-
-AC_PROVIDE_IFELSE([AC_PROG_F77],
-  [LT_LANG(F77)],
-  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
-
-AC_PROVIDE_IFELSE([AC_PROG_FC],
-  [LT_LANG(FC)],
-  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
-
-dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
-dnl pulling things in needlessly.
-AC_PROVIDE_IFELSE([AC_PROG_GCJ],
-  [LT_LANG(GCJ)],
-  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
-    [LT_LANG(GCJ)],
-    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
-      [LT_LANG(GCJ)],
-      [m4_ifdef([AC_PROG_GCJ],
-	[m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
-       m4_ifdef([A][M_PROG_GCJ],
-	[m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
-       m4_ifdef([LT_PROG_GCJ],
-	[m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
-
-AC_PROVIDE_IFELSE([AC_PROG_GO],
-  [LT_LANG(GO)],
-  [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])])
-
-AC_PROVIDE_IFELSE([LT_PROG_RC],
-  [LT_LANG(RC)],
-  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
-])# _LT_LANG_DEFAULT_CONFIG
-
-# Obsolete macros:
-AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
-AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
-AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
-AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
-AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
-dnl AC_DEFUN([AC_LIBTOOL_F77], [])
-dnl AC_DEFUN([AC_LIBTOOL_FC], [])
-dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
-dnl AC_DEFUN([AC_LIBTOOL_RC], [])
-
-
-# _LT_TAG_COMPILER
-# ----------------
-m4_defun([_LT_TAG_COMPILER],
-[AC_REQUIRE([AC_PROG_CC])dnl
-
-_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
-_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
-_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
-_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
-
-# If no C compiler was specified, use CC.
-LTCC=${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=$CC
-])# _LT_TAG_COMPILER
-
-
-# _LT_COMPILER_BOILERPLATE
-# ------------------------
-# Check for compiler boilerplate output or warnings with
-# the simple compiler test code.
-m4_defun([_LT_COMPILER_BOILERPLATE],
-[m4_require([_LT_DECL_SED])dnl
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=`cat conftest.err`
-$RM conftest*
-])# _LT_COMPILER_BOILERPLATE
-
-
-# _LT_LINKER_BOILERPLATE
-# ----------------------
-# Check for linker boilerplate output or warnings with
-# the simple link test code.
-m4_defun([_LT_LINKER_BOILERPLATE],
-[m4_require([_LT_DECL_SED])dnl
-ac_outfile=conftest.$ac_objext
-echo "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=`cat conftest.err`
-$RM -r conftest*
-])# _LT_LINKER_BOILERPLATE
-
-# _LT_REQUIRED_DARWIN_CHECKS
-# -------------------------
-m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
-  case $host_os in
-    rhapsody* | darwin*)
-    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
-    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
-    AC_CHECK_TOOL([LIPO], [lipo], [:])
-    AC_CHECK_TOOL([OTOOL], [otool], [:])
-    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
-    _LT_DECL([], [DSYMUTIL], [1],
-      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
-    _LT_DECL([], [NMEDIT], [1],
-      [Tool to change global to local symbols on Mac OS X])
-    _LT_DECL([], [LIPO], [1],
-      [Tool to manipulate fat objects and archives on Mac OS X])
-    _LT_DECL([], [OTOOL], [1],
-      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
-    _LT_DECL([], [OTOOL64], [1],
-      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
-
-    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
-      [lt_cv_apple_cc_single_mod=no
-      if test -z "${LT_MULTI_MODULE}"; then
-	# By default we will add the -single_module flag. You can override
-	# by either setting the environment variable LT_MULTI_MODULE
-	# non-empty at configure time, or by adding -multi_module to the
-	# link flags.
-	rm -rf libconftest.dylib*
-	echo "int foo(void){return 1;}" > conftest.c
-	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
--dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
-	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
-	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
-        _lt_result=$?
-	# If there is a non-empty error log, and "single_module"
-	# appears in it, assume the flag caused a linker warning
-        if test -s conftest.err && $GREP single_module conftest.err; then
-	  cat conftest.err >&AS_MESSAGE_LOG_FD
-	# Otherwise, if the output was created with a 0 exit code from
-	# the compiler, it worked.
-	elif test -f libconftest.dylib && test $_lt_result -eq 0; then
-	  lt_cv_apple_cc_single_mod=yes
-	else
-	  cat conftest.err >&AS_MESSAGE_LOG_FD
-	fi
-	rm -rf libconftest.dylib*
-	rm -f conftest.*
-      fi])
-
-    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
-      [lt_cv_ld_exported_symbols_list],
-      [lt_cv_ld_exported_symbols_list=no
-      save_LDFLAGS=$LDFLAGS
-      echo "_main" > conftest.sym
-      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
-      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
-	[lt_cv_ld_exported_symbols_list=yes],
-	[lt_cv_ld_exported_symbols_list=no])
-	LDFLAGS="$save_LDFLAGS"
-    ])
-
-    AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load],
-      [lt_cv_ld_force_load=no
-      cat > conftest.c << _LT_EOF
-int forced_loaded() { return 2;}
-_LT_EOF
-      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD
-      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD
-      echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD
-      $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD
-      echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD
-      $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD
-      cat > conftest.c << _LT_EOF
-int main() { return 0;}
-_LT_EOF
-      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD
-      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err
-      _lt_result=$?
-      if test -s conftest.err && $GREP force_load conftest.err; then
-	cat conftest.err >&AS_MESSAGE_LOG_FD
-      elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then
-	lt_cv_ld_force_load=yes
-      else
-	cat conftest.err >&AS_MESSAGE_LOG_FD
-      fi
-        rm -f conftest.err libconftest.a conftest conftest.c
-        rm -rf conftest.dSYM
-    ])
-    case $host_os in
-    rhapsody* | darwin1.[[012]])
-      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
-    darwin1.*)
-      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-    darwin*) # darwin 5.x on
-      # if running on 10.5 or later, the deployment target defaults
-      # to the OS version, if on x86, and 10.4, the deployment
-      # target defaults to 10.4. Don't you love it?
-      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
-	10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-	10.[[012]]*)
-	  _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
-	10.*)
-	  _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
-      esac
-    ;;
-  esac
-    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
-      _lt_dar_single_mod='$single_module'
-    fi
-    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
-      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
-    else
-      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    fi
-    if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then
-      _lt_dsymutil='~$DSYMUTIL $lib || :'
-    else
-      _lt_dsymutil=
-    fi
-    ;;
-  esac
-])
-
-
-# _LT_DARWIN_LINKER_FEATURES([TAG])
-# ---------------------------------
-# Checks for linker and compiler features on darwin
-m4_defun([_LT_DARWIN_LINKER_FEATURES],
-[
-  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
-  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-  _LT_TAGVAR(hardcode_direct, $1)=no
-  _LT_TAGVAR(hardcode_automatic, $1)=yes
-  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  if test "$lt_cv_ld_force_load" = "yes"; then
-    _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`'
-    m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes],
-                  [FC],  [_LT_TAGVAR(compiler_needs_object, $1)=yes])
-  else
-    _LT_TAGVAR(whole_archive_flag_spec, $1)=''
-  fi
-  _LT_TAGVAR(link_all_deplibs, $1)=yes
-  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
-  case $cc_basename in
-     ifort*) _lt_dar_can_shared=yes ;;
-     *) _lt_dar_can_shared=$GCC ;;
-  esac
-  if test "$_lt_dar_can_shared" = "yes"; then
-    output_verbose_link_cmd=func_echo_all
-    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
-    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
-    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
-    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
-    m4_if([$1], [CXX],
-[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
-      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
-      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
-    fi
-],[])
-  else
-  _LT_TAGVAR(ld_shlibs, $1)=no
-  fi
-])
-
-# _LT_SYS_MODULE_PATH_AIX([TAGNAME])
-# ----------------------------------
-# Links a minimal program and checks the executable
-# for the system default hardcoded library path. In most cases,
-# this is /usr/lib:/lib, but when the MPI compilers are used
-# the location of the communication and MPI libs are included too.
-# If we don't find anything, use the default library path according
-# to the aix ld manual.
-# Store the results from the different compilers for each TAGNAME.
-# Allow to override them for all tags through lt_cv_aix_libpath.
-m4_defun([_LT_SYS_MODULE_PATH_AIX],
-[m4_require([_LT_DECL_SED])dnl
-if test "${lt_cv_aix_libpath+set}" = set; then
-  aix_libpath=$lt_cv_aix_libpath
-else
-  AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])],
-  [AC_LINK_IFELSE([AC_LANG_PROGRAM],[
-  lt_aix_libpath_sed='[
-      /Import File Strings/,/^$/ {
-	  /^0/ {
-	      s/^0  *\([^ ]*\) *$/\1/
-	      p
-	  }
-      }]'
-  _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  # Check for a 64-bit object if we didn't find anything.
-  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
-    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
-  fi],[])
-  if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then
-    _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib"
-  fi
-  ])
-  aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])
-fi
-])# _LT_SYS_MODULE_PATH_AIX
-
-
-# _LT_SHELL_INIT(ARG)
-# -------------------
-m4_define([_LT_SHELL_INIT],
-[m4_divert_text([M4SH-INIT], [$1
-])])# _LT_SHELL_INIT
-
-
-
-# _LT_PROG_ECHO_BACKSLASH
-# -----------------------
-# Find how we can fake an echo command that does not interpret backslash.
-# In particular, with Autoconf 2.60 or later we add some code to the start
-# of the generated configure script which will find a shell with a builtin
-# printf (which we can use as an echo command).
-m4_defun([_LT_PROG_ECHO_BACKSLASH],
-[ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
-ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
-
-AC_MSG_CHECKING([how to print strings])
-# Test print first, because it will be a builtin if present.
-if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \
-   test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='print -r --'
-elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then
-  ECHO='printf %s\n'
-else
-  # Use this function as a fallback that always works.
-  func_fallback_echo ()
-  {
-    eval 'cat <<_LTECHO_EOF
-$[]1
-_LTECHO_EOF'
-  }
-  ECHO='func_fallback_echo'
-fi
-
-# func_echo_all arg...
-# Invoke $ECHO with all args, space-separated.
-func_echo_all ()
-{
-    $ECHO "$*" 
-}
-
-case "$ECHO" in
-  printf*) AC_MSG_RESULT([printf]) ;;
-  print*) AC_MSG_RESULT([print -r]) ;;
-  *) AC_MSG_RESULT([cat]) ;;
-esac
-
-m4_ifdef([_AS_DETECT_SUGGESTED],
-[_AS_DETECT_SUGGESTED([
-  test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || (
-    ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO
-    ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
-    PATH=/empty FPATH=/empty; export PATH FPATH
-    test "X`printf %s $ECHO`" = "X$ECHO" \
-      || test "X`print -r -- $ECHO`" = "X$ECHO" )])])
-
-_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
-_LT_DECL([], [ECHO], [1], [An echo program that protects backslashes])
-])# _LT_PROG_ECHO_BACKSLASH
-
-
-# _LT_WITH_SYSROOT
-# ----------------
-AC_DEFUN([_LT_WITH_SYSROOT],
-[AC_MSG_CHECKING([for sysroot])
-AC_ARG_WITH([sysroot],
-[  --with-sysroot[=DIR] Search for dependent libraries within DIR
-                        (or the compiler's sysroot if not specified).],
-[], [with_sysroot=no])
-
-dnl lt_sysroot will always be passed unquoted.  We quote it here
-dnl in case the user passed a directory name.
-lt_sysroot=
-case ${with_sysroot} in #(
- yes)
-   if test "$GCC" = yes; then
-     lt_sysroot=`$CC --print-sysroot 2>/dev/null`
-   fi
-   ;; #(
- /*)
-   lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
-   ;; #(
- no|'')
-   ;; #(
- *)
-   AC_MSG_RESULT([${with_sysroot}])
-   AC_MSG_ERROR([The sysroot must be an absolute path.])
-   ;;
-esac
-
- AC_MSG_RESULT([${lt_sysroot:-no}])
-_LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl
-[dependent libraries, and in which our libraries should be installed.])])
-
-# _LT_ENABLE_LOCK
-# ---------------
-m4_defun([_LT_ENABLE_LOCK],
-[AC_ARG_ENABLE([libtool-lock],
-  [AS_HELP_STRING([--disable-libtool-lock],
-    [avoid locking (might break parallel builds)])])
-test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
-
-# Some flags need to be propagated to the compiler or linker for good
-# libtool support.
-case $host in
-ia64-*-hpux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.$ac_objext` in
-      *ELF-32*)
-	HPUX_IA64_MODE="32"
-	;;
-      *ELF-64*)
-	HPUX_IA64_MODE="64"
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-*-*-irix6*)
-  # Find out which ABI we are using.
-  echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    if test "$lt_cv_prog_gnu_ld" = yes; then
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -melf32bsmip"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -melf32bmipn32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -melf64bmip"
-	;;
-      esac
-    else
-      case `/usr/bin/file conftest.$ac_objext` in
-	*32-bit*)
-	  LD="${LD-ld} -32"
-	  ;;
-	*N32*)
-	  LD="${LD-ld} -n32"
-	  ;;
-	*64-bit*)
-	  LD="${LD-ld} -64"
-	  ;;
-      esac
-    fi
-  fi
-  rm -rf conftest*
-  ;;
-
-x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \
-s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-      *32-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_i386_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    case `/usr/bin/file conftest.o` in
-	      *x86-64*)
-		LD="${LD-ld} -m elf32_x86_64"
-		;;
-	      *)
-		LD="${LD-ld} -m elf_i386"
-		;;
-	    esac
-	    ;;
-	  powerpc64le-*)
-	    LD="${LD-ld} -m elf32lppclinux"
-	    ;;
-	  powerpc64-*)
-	    LD="${LD-ld} -m elf32ppclinux"
-	    ;;
-	  s390x-*linux*)
-	    LD="${LD-ld} -m elf_s390"
-	    ;;
-	  sparc64-*linux*)
-	    LD="${LD-ld} -m elf32_sparc"
-	    ;;
-	esac
-	;;
-      *64-bit*)
-	case $host in
-	  x86_64-*kfreebsd*-gnu)
-	    LD="${LD-ld} -m elf_x86_64_fbsd"
-	    ;;
-	  x86_64-*linux*)
-	    LD="${LD-ld} -m elf_x86_64"
-	    ;;
-	  powerpcle-*)
-	    LD="${LD-ld} -m elf64lppc"
-	    ;;
-	  powerpc-*)
-	    LD="${LD-ld} -m elf64ppc"
-	    ;;
-	  s390*-*linux*|s390*-*tpf*)
-	    LD="${LD-ld} -m elf64_s390"
-	    ;;
-	  sparc*-*linux*)
-	    LD="${LD-ld} -m elf64_sparc"
-	    ;;
-	esac
-	;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-*-*-sco3.2v5*)
-  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS="$CFLAGS"
-  CFLAGS="$CFLAGS -belf"
-  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
-    [AC_LANG_PUSH(C)
-     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
-     AC_LANG_POP])
-  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
-    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS="$SAVE_CFLAGS"
-  fi
-  ;;
-*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*)
-        case $host in
-        i?86-*-solaris*)
-          LD="${LD-ld} -m elf_x86_64"
-          ;;
-        sparc*-*-solaris*)
-          LD="${LD-ld} -m elf64_sparc"
-          ;;
-        esac
-        # GNU ld 2.21 introduced _sol2 emulations.  Use them if available.
-        if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then
-          LD="${LD-ld}_sol2"
-        fi
-        ;;
-      *)
-	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
-	  LD="${LD-ld} -64"
-	fi
-	;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-esac
-
-need_locks="$enable_libtool_lock"
-])# _LT_ENABLE_LOCK
-
-
-# _LT_PROG_AR
-# -----------
-m4_defun([_LT_PROG_AR],
-[AC_CHECK_TOOLS(AR, [ar], false)
-: ${AR=ar}
-: ${AR_FLAGS=cru}
-_LT_DECL([], [AR], [1], [The archiver])
-_LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive])
-
-AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file],
-  [lt_cv_ar_at_file=no
-   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
-     [echo conftest.$ac_objext > conftest.lst
-      lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD'
-      AC_TRY_EVAL([lt_ar_try])
-      if test "$ac_status" -eq 0; then
-	# Ensure the archiver fails upon bogus file names.
-	rm -f conftest.$ac_objext libconftest.a
-	AC_TRY_EVAL([lt_ar_try])
-	if test "$ac_status" -ne 0; then
-          lt_cv_ar_at_file=@
-        fi
-      fi
-      rm -f conftest.* libconftest.a
-     ])
-  ])
-
-if test "x$lt_cv_ar_at_file" = xno; then
-  archiver_list_spec=
-else
-  archiver_list_spec=$lt_cv_ar_at_file
-fi
-_LT_DECL([], [archiver_list_spec], [1],
-  [How to feed a file listing to the archiver])
-])# _LT_PROG_AR
-
-
-# _LT_CMD_OLD_ARCHIVE
-# -------------------
-m4_defun([_LT_CMD_OLD_ARCHIVE],
-[_LT_PROG_AR
-
-AC_CHECK_TOOL(STRIP, strip, :)
-test -z "$STRIP" && STRIP=:
-_LT_DECL([], [STRIP], [1], [A symbol stripping program])
-
-AC_CHECK_TOOL(RANLIB, ranlib, :)
-test -z "$RANLIB" && RANLIB=:
-_LT_DECL([], [RANLIB], [1],
-    [Commands used to install an old-style archive])
-
-# Determine commands to create old-style static archives.
-old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
-old_postinstall_cmds='chmod 644 $oldlib'
-old_postuninstall_cmds=
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib"
-    ;;
-  *)
-    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib"
-    ;;
-  esac
-  old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib"
-fi
-
-case $host_os in
-  darwin*)
-    lock_old_archive_extraction=yes ;;
-  *)
-    lock_old_archive_extraction=no ;;
-esac
-_LT_DECL([], [old_postinstall_cmds], [2])
-_LT_DECL([], [old_postuninstall_cmds], [2])
-_LT_TAGDECL([], [old_archive_cmds], [2],
-    [Commands used to build an old-style archive])
-_LT_DECL([], [lock_old_archive_extraction], [0],
-    [Whether to use a lock for old archive extraction])
-])# _LT_CMD_OLD_ARCHIVE
-
-
-# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------------------
-# Check whether the given compiler option works
-AC_DEFUN([_LT_COMPILER_OPTION],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_CACHE_CHECK([$1], [$2],
-  [$2=no
-   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag="$3"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=$?
-   cat conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
-       $2=yes
-     fi
-   fi
-   $RM conftest*
-])
-
-if test x"[$]$2" = xyes; then
-    m4_if([$5], , :, [$5])
-else
-    m4_if([$6], , :, [$6])
-fi
-])# _LT_COMPILER_OPTION
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
-
-
-# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#                  [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------
-# Check whether the given linker option works
-AC_DEFUN([_LT_LINKER_OPTION],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_SED])dnl
-AC_CACHE_CHECK([$1], [$2],
-  [$2=no
-   save_LDFLAGS="$LDFLAGS"
-   LDFLAGS="$LDFLAGS $3"
-   echo "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&AS_MESSAGE_LOG_FD
-       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         $2=yes
-       fi
-     else
-       $2=yes
-     fi
-   fi
-   $RM -r conftest*
-   LDFLAGS="$save_LDFLAGS"
-])
-
-if test x"[$]$2" = xyes; then
-    m4_if([$4], , :, [$4])
-else
-    m4_if([$5], , :, [$5])
-fi
-])# _LT_LINKER_OPTION
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
-
-
-# LT_CMD_MAX_LEN
-#---------------
-AC_DEFUN([LT_CMD_MAX_LEN],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-# find the maximum length of command line arguments
-AC_MSG_CHECKING([the maximum length of command line arguments])
-AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
-  i=0
-  teststring="ABCD"
-
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
-    ;;
-
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=-1;
-    ;;
-
-  cygwin* | mingw* | cegcc*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # Instead, let's just punt: use the minimum linelength reported by
-    # all of the supported platforms: 8192 (on NT/2K/XP).
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  mint*)
-    # On MiNT this can take a long time and run out of memory.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=8192;
-    ;;
-
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BSD)
-    lt_cv_sys_max_cmd_len=196608
-    ;;
-
-  os2*)
-    # The test takes a long time on OS/2.
-    lt_cv_sys_max_cmd_len=8192
-    ;;
-
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[	 ]]//'`
-    else
-      lt_cv_sys_max_cmd_len=32768
-    fi
-    ;;
-  *)
-    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
-    if test -n "$lt_cv_sys_max_cmd_len" && \
-	test undefined != "$lt_cv_sys_max_cmd_len"; then
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
-    else
-      # Make teststring a little bigger before we do anything with it.
-      # a 1K string should be a reasonable start.
-      for i in 1 2 3 4 5 6 7 8 ; do
-        teststring=$teststring$teststring
-      done
-      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
-      # If test is not a shell built-in, we'll probably end up computing a
-      # maximum length that is only half of the actual maximum length, but
-      # we can't tell.
-      while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \
-	         = "X$teststring$teststring"; } >/dev/null 2>&1 &&
-	      test $i != 17 # 1/2 MB should be enough
-      do
-        i=`expr $i + 1`
-        teststring=$teststring$teststring
-      done
-      # Only check the string length outside the loop.
-      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
-      teststring=
-      # Add a significant safety factor because C++ compilers can tack on
-      # massive amounts of additional arguments before passing them to the
-      # linker.  It appears as though 1/2 is a usable value.
-      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
-    fi
-    ;;
-  esac
-])
-if test -n $lt_cv_sys_max_cmd_len ; then
-  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
-else
-  AC_MSG_RESULT(none)
-fi
-max_cmd_len=$lt_cv_sys_max_cmd_len
-_LT_DECL([], [max_cmd_len], [0],
-    [What is the maximum length of a command?])
-])# LT_CMD_MAX_LEN
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
-
-
-# _LT_HEADER_DLFCN
-# ----------------
-m4_defun([_LT_HEADER_DLFCN],
-[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
-])# _LT_HEADER_DLFCN
-
-
-# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
-#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
-# ----------------------------------------------------------------
-m4_defun([_LT_TRY_DLOPEN_SELF],
-[m4_require([_LT_HEADER_DLFCN])dnl
-if test "$cross_compiling" = yes; then :
-  [$4]
-else
-  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
-  lt_status=$lt_dlunknown
-  cat > conftest.$ac_ext <<_LT_EOF
-[#line $LINENO "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-/* When -fvisbility=hidden is used, assume the code has been annotated
-   correspondingly for the symbols needed.  */
-#if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3))
-int fnord () __attribute__((visibility("default")));
-#endif
-
-int fnord () { return 42; }
-int main ()
-{
-  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status = $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
-      else
-        {
-	  if (dlsym( self,"_fnord"))  status = $lt_dlneed_uscore;
-          else puts (dlerror ());
-	}
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-  return status;
-}]
-_LT_EOF
-  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
-    lt_status=$?
-    case x$lt_status in
-      x$lt_dlno_uscore) $1 ;;
-      x$lt_dlneed_uscore) $2 ;;
-      x$lt_dlunknown|x*) $3 ;;
-    esac
-  else :
-    # compilation failed
-    $3
-  fi
-fi
-rm -fr conftest*
-])# _LT_TRY_DLOPEN_SELF
-
-
-# LT_SYS_DLOPEN_SELF
-# ------------------
-AC_DEFUN([LT_SYS_DLOPEN_SELF],
-[m4_require([_LT_HEADER_DLFCN])dnl
-if test "x$enable_dlopen" != xyes; then
-  enable_dlopen=unknown
-  enable_dlopen_self=unknown
-  enable_dlopen_self_static=unknown
-else
-  lt_cv_dlopen=no
-  lt_cv_dlopen_libs=
-
-  case $host_os in
-  beos*)
-    lt_cv_dlopen="load_add_on"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ;;
-
-  mingw* | pw32* | cegcc*)
-    lt_cv_dlopen="LoadLibrary"
-    lt_cv_dlopen_libs=
-    ;;
-
-  cygwin*)
-    lt_cv_dlopen="dlopen"
-    lt_cv_dlopen_libs=
-    ;;
-
-  darwin*)
-  # if libdl is installed we need to link against it
-    AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
-    lt_cv_dlopen="dyld"
-    lt_cv_dlopen_libs=
-    lt_cv_dlopen_self=yes
-    ])
-    ;;
-
-  *)
-    AC_CHECK_FUNC([shl_load],
-	  [lt_cv_dlopen="shl_load"],
-      [AC_CHECK_LIB([dld], [shl_load],
-	    [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
-	[AC_CHECK_FUNC([dlopen],
-	      [lt_cv_dlopen="dlopen"],
-	  [AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
-	    [AC_CHECK_LIB([svld], [dlopen],
-		  [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
-	      [AC_CHECK_LIB([dld], [dld_link],
-		    [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
-	      ])
-	    ])
-	  ])
-	])
-      ])
-    ;;
-  esac
-
-  if test "x$lt_cv_dlopen" != xno; then
-    enable_dlopen=yes
-  else
-    enable_dlopen=no
-  fi
-
-  case $lt_cv_dlopen in
-  dlopen)
-    save_CPPFLAGS="$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
-
-    save_LDFLAGS="$LDFLAGS"
-    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
-
-    save_LIBS="$LIBS"
-    LIBS="$lt_cv_dlopen_libs $LIBS"
-
-    AC_CACHE_CHECK([whether a program can dlopen itself],
-	  lt_cv_dlopen_self, [dnl
-	  _LT_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
-	    lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
-    ])
-
-    if test "x$lt_cv_dlopen_self" = xyes; then
-      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
-      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
-	  lt_cv_dlopen_self_static, [dnl
-	  _LT_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
-	    lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
-      ])
-    fi
-
-    CPPFLAGS="$save_CPPFLAGS"
-    LDFLAGS="$save_LDFLAGS"
-    LIBS="$save_LIBS"
-    ;;
-  esac
-
-  case $lt_cv_dlopen_self in
-  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
-  *) enable_dlopen_self=unknown ;;
-  esac
-
-  case $lt_cv_dlopen_self_static in
-  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
-  *) enable_dlopen_self_static=unknown ;;
-  esac
-fi
-_LT_DECL([dlopen_support], [enable_dlopen], [0],
-	 [Whether dlopen is supported])
-_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
-	 [Whether dlopen of programs is supported])
-_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
-	 [Whether dlopen of statically linked programs is supported])
-])# LT_SYS_DLOPEN_SELF
-
-# Old name:
-AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
-
-
-# _LT_COMPILER_C_O([TAGNAME])
-# ---------------------------
-# Check to see if options -c and -o are simultaneously supported by compiler.
-# This macro does not hard code the compiler like AC_PROG_CC_C_O.
-m4_defun([_LT_COMPILER_C_O],
-[m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
-  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
-  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
-   $RM -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag="-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=$?
-   cat out/conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
-       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
-     fi
-   fi
-   chmod u+w . 2>&AS_MESSAGE_LOG_FD
-   $RM conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
-   $RM out/* && rmdir out
-   cd ..
-   $RM -r conftest
-   $RM conftest*
-])
-_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
-	[Does compiler simultaneously support -c and -o options?])
-])# _LT_COMPILER_C_O
-
-
-# _LT_COMPILER_FILE_LOCKS([TAGNAME])
-# ----------------------------------
-# Check to see if we can do hard links to lock some files if needed
-m4_defun([_LT_COMPILER_FILE_LOCKS],
-[m4_require([_LT_ENABLE_LOCK])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-_LT_COMPILER_C_O([$1])
-
-hard_links="nottested"
-if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
-  # do not overwrite the value of need_locks provided by the user
-  AC_MSG_CHECKING([if we can lock with hard links])
-  hard_links=yes
-  $RM conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=no
-  ln conftest.a conftest.b 2>/dev/null && hard_links=no
-  AC_MSG_RESULT([$hard_links])
-  if test "$hard_links" = no; then
-    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
-    need_locks=warn
-  fi
-else
-  need_locks=no
-fi
-_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
-])# _LT_COMPILER_FILE_LOCKS
-
-
-# _LT_CHECK_OBJDIR
-# ----------------
-m4_defun([_LT_CHECK_OBJDIR],
-[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
-[rm -f .libs 2>/dev/null
-mkdir .libs 2>/dev/null
-if test -d .libs; then
-  lt_cv_objdir=.libs
-else
-  # MS-DOS does not allow filenames that begin with a dot.
-  lt_cv_objdir=_libs
-fi
-rmdir .libs 2>/dev/null])
-objdir=$lt_cv_objdir
-_LT_DECL([], [objdir], [0],
-         [The name of the directory that contains temporary libtool files])dnl
-m4_pattern_allow([LT_OBJDIR])dnl
-AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
-  [Define to the sub-directory in which libtool stores uninstalled libraries.])
-])# _LT_CHECK_OBJDIR
-
-
-# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
-# --------------------------------------
-# Check hardcoding attributes.
-m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
-[AC_MSG_CHECKING([how to hardcode library paths into programs])
-_LT_TAGVAR(hardcode_action, $1)=
-if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
-   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
-   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
-
-  # We can hardcode non-existent directories.
-  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
-     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
-    # Linking always hardcodes the temporary library directory.
-    _LT_TAGVAR(hardcode_action, $1)=relink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    _LT_TAGVAR(hardcode_action, $1)=immediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  _LT_TAGVAR(hardcode_action, $1)=unsupported
-fi
-AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
-
-if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
-   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
-  # Fast installation is not supported
-  enable_fast_install=no
-elif test "$shlibpath_overrides_runpath" = yes ||
-     test "$enable_shared" = no; then
-  # Fast installation is not necessary
-  enable_fast_install=needless
-fi
-_LT_TAGDECL([], [hardcode_action], [0],
-    [How to hardcode a shared library path into an executable])
-])# _LT_LINKER_HARDCODE_LIBPATH
-
-
-# _LT_CMD_STRIPLIB
-# ----------------
-m4_defun([_LT_CMD_STRIPLIB],
-[m4_require([_LT_DECL_EGREP])
-striplib=
-old_striplib=
-AC_MSG_CHECKING([whether stripping libraries is possible])
-if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
-  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
-  AC_MSG_RESULT([yes])
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-  darwin*)
-    if test -n "$STRIP" ; then
-      striplib="$STRIP -x"
-      old_striplib="$STRIP -S"
-      AC_MSG_RESULT([yes])
-    else
-      AC_MSG_RESULT([no])
-    fi
-    ;;
-  *)
-    AC_MSG_RESULT([no])
-    ;;
-  esac
-fi
-_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
-_LT_DECL([], [striplib], [1])
-])# _LT_CMD_STRIPLIB
-
-
-# _LT_SYS_DYNAMIC_LINKER([TAG])
-# -----------------------------
-# PORTME Fill in your ld.so characteristics
-m4_defun([_LT_SYS_DYNAMIC_LINKER],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_OBJDUMP])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_CHECK_SHELL_FEATURES])dnl
-AC_MSG_CHECKING([dynamic linker characteristics])
-m4_if([$1],
-	[], [
-if test "$GCC" = yes; then
-  case $host_os in
-    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
-    *) lt_awk_arg="/^libraries:/" ;;
-  esac
-  case $host_os in
-    mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;;
-    *) lt_sed_strip_eq="s,=/,/,g" ;;
-  esac
-  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq`
-  case $lt_search_path_spec in
-  *\;*)
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that should
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
-    ;;
-  *)
-    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"`
-    ;;
-  esac
-  # Ok, now we have the path, separated by spaces, we can step through it
-  # and add multilib dir if necessary.
-  lt_tmp_lt_search_path_spec=
-  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
-  for lt_sys_path in $lt_search_path_spec; do
-    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
-      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
-    else
-      test -d "$lt_sys_path" && \
-	lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
-    fi
-  done
-  lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
-BEGIN {RS=" "; FS="/|\n";} {
-  lt_foo="";
-  lt_count=0;
-  for (lt_i = NF; lt_i > 0; lt_i--) {
-    if ($lt_i != "" && $lt_i != ".") {
-      if ($lt_i == "..") {
-        lt_count++;
-      } else {
-        if (lt_count == 0) {
-          lt_foo="/" $lt_i lt_foo;
-        } else {
-          lt_count--;
-        }
-      }
-    }
-  }
-  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
-  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
-}'`
-  # AWK program above erroneously prepends '/' to C:/dos/paths
-  # for these hosts.
-  case $host_os in
-    mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\
-      $SED 's,/\([[A-Za-z]]:\),\1,g'` ;;
-  esac
-  sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
-else
-  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
-fi])
-library_names_spec=
-libname_spec='lib$name'
-soname_spec=
-shrext_cmds=".so"
-postinstall_cmds=
-postuninstall_cmds=
-finish_cmds=
-finish_eval=
-shlibpath_var=
-shlibpath_overrides_runpath=unknown
-version_type=none
-dynamic_linker="$host_os ld.so"
-sys_lib_dlsearch_path_spec="/lib /usr/lib"
-need_lib_prefix=unknown
-hardcode_into_libs=no
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=unknown
-
-case $host_os in
-aix3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
-  shlibpath_var=LIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the name.
-  soname_spec='${libname}${release}${shared_ext}$major'
-  ;;
-
-aix[[4-9]]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  hardcode_into_libs=yes
-  if test "$host_cpu" = ia64; then
-    # AIX 5 supports IA64
-    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=LD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[[01]] | aix4.[[01]].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
-	:
-      else
-	can_build_shared=no
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" = yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec='${libname}${release}.a $libname.a'
-      soname_spec='${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=LIBPATH
-  fi
-  ;;
-
-amigaos*)
-  case $host_cpu in
-  powerpc)
-    # Since July 2007 AmigaOS4 officially supports .so libraries.
-    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    ;;
-  m68k)
-    library_names_spec='$libname.ixlibrary $libname.a'
-    # Create ${libname}_ixlibrary.a entries in /sys/libs.
-    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
-    ;;
-  esac
-  ;;
-
-beos*)
-  library_names_spec='${libname}${shared_ext}'
-  dynamic_linker="$host_os ld.so"
-  shlibpath_var=LIBRARY_PATH
-  ;;
-
-bsdi[[45]]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32* | cegcc*)
-  version_type=windows
-  shrext_cmds=".dll"
-  need_version=no
-  need_lib_prefix=no
-
-  case $GCC,$cc_basename in
-  yes,*)
-    # gcc
-    library_names_spec='$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname~
-      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
-        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
-      fi'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-m4_if([$1], [],[
-      sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"])
-      ;;
-    mingw* | cegcc*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    dynamic_linker='Win32 ld.exe'
-    ;;
-
-  *,cl*)
-    # Native MSVC
-    libname_spec='$name'
-    soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-    library_names_spec='${libname}.dll.lib'
-
-    case $build_os in
-    mingw*)
-      sys_lib_search_path_spec=
-      lt_save_ifs=$IFS
-      IFS=';'
-      for lt_path in $LIB
-      do
-        IFS=$lt_save_ifs
-        # Let DOS variable expansion print the short 8.3 style file name.
-        lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"`
-        sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path"
-      done
-      IFS=$lt_save_ifs
-      # Convert to MSYS style.
-      sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'`
-      ;;
-    cygwin*)
-      # Convert to unix form, then to dos form, then back to unix form
-      # but this time dos style (no spaces!) so that the unix form looks
-      # like /cygdrive/c/PROGRA~1:/cygdr...
-      sys_lib_search_path_spec=`cygpath --path --unix "$LIB"`
-      sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null`
-      sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
-      ;;
-    *)
-      sys_lib_search_path_spec="$LIB"
-      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
-        # It is most probably a Windows format PATH.
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      # FIXME: find the short name or the path components, as spaces are
-      # common. (e.g. "Program Files" -> "PROGRA~1")
-      ;;
-    esac
-
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds='base_file=`basename \${file}`~
-      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
-      dldir=$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname'
-    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
-      dlpath=$dir/\$dldll~
-       $RM \$dlpath'
-    shlibpath_overrides_runpath=yes
-    dynamic_linker='Win32 link.exe'
-    ;;
-
-  *)
-    # Assume MSVC wrapper
-    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
-    dynamic_linker='Win32 ld.exe'
-    ;;
-  esac
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=PATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker="$host_os dyld"
-  version_type=darwin
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
-  soname_spec='${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=yes
-  shlibpath_var=DYLD_LIBRARY_PATH
-  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
-m4_if([$1], [],[
-  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
-  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[[23]].*) objformat=aout ;;
-    *) objformat=elf ;;
-    esac
-  fi
-  version_type=freebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=no
-      need_lib_prefix=no
-      ;;
-    freebsd-*)
-      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
-      need_version=yes
-      ;;
-  esac
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_os in
-  freebsd2.*)
-    shlibpath_overrides_runpath=yes
-    ;;
-  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
-  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=no
-    hardcode_into_libs=yes
-    ;;
-  *) # from 4.6 on, and DragonFly
-    shlibpath_overrides_runpath=yes
-    hardcode_into_libs=yes
-    ;;
-  esac
-  ;;
-
-haiku*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  dynamic_linker="$host_os runtime_loader"
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib'
-  hardcode_into_libs=yes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuses to
-  # link against other versions.
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  case $host_cpu in
-  ia64*)
-    shrext_cmds='.so'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.so"
-    shlibpath_var=LD_LIBRARY_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" = X32; then
-      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
-    else
-      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  hppa*64*)
-    shrext_cmds='.sl'
-    hardcode_into_libs=yes
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
-    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
-    ;;
-  *)
-    shrext_cmds='.sl'
-    dynamic_linker="$host_os dld.sl"
-    shlibpath_var=SHLIB_PATH
-    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
-  postinstall_cmds='chmod 555 $lib'
-  # or fails outright, so override atomically:
-  install_override_mode=555
-  ;;
-
-interix[[3-9]]*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=nonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" = yes; then
-		version_type=linux # correct to gnu/linux during the next big refactor
-	else
-		version_type=irix
-	fi ;;
-  esac
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff= shlibsuff=
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff= shlibsuff= libmagic=32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=32 shlibsuff=N32 libmagic=N32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=64 shlibsuff=64 libmagic=64-bit;;
-    *) libsuff= shlibsuff= libmagic=never-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=no
-  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
-  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=yes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=no
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-
-  # Some binutils ld are patched to set DT_RUNPATH
-  AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath],
-    [lt_cv_shlibpath_overrides_runpath=no
-    save_LDFLAGS=$LDFLAGS
-    save_libdir=$libdir
-    eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
-	 LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
-    AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
-      [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
-	 [lt_cv_shlibpath_overrides_runpath=yes])])
-    LDFLAGS=$save_LDFLAGS
-    libdir=$save_libdir
-    ])
-  shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath
-
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=yes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker='GNU/Linux ld.so'
-  ;;
-
-netbsdelf*-gnu)
-  version_type=linux
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='NetBSD ld.elf_so'
-  ;;
-
-netbsd*)
-  version_type=sunos
-  need_lib_prefix=no
-  need_version=no
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker='NetBSD (a.out) ld.so'
-  else
-    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec='${libname}${release}${shared_ext}$major'
-    dynamic_linker='NetBSD ld.elf_so'
-  fi
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  ;;
-
-newsos6)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  ;;
-
-*nto* | *qnx*)
-  version_type=qnx
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  dynamic_linker='ldqnx.so'
-  ;;
-
-openbsd*)
-  version_type=sunos
-  sys_lib_dlsearch_path_spec="/usr/lib"
-  need_lib_prefix=no
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*)	need_version=yes ;;
-    *)				need_version=no  ;;
-  esac
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[[89]] | openbsd2.[[89]].*)
-	shlibpath_overrides_runpath=no
-	;;
-      *)
-	shlibpath_overrides_runpath=yes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=yes
-  fi
-  ;;
-
-os2*)
-  libname_spec='$name'
-  shrext_cmds=".dll"
-  need_lib_prefix=no
-  library_names_spec='$libname${shared_ext} $libname.a'
-  dynamic_linker='OS/2 ld.exe'
-  shlibpath_var=LIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=osf
-  need_lib_prefix=no
-  need_version=no
-  soname_spec='${libname}${release}${shared_ext}$major'
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
-  ;;
-
-rdos*)
-  dynamic_linker=no
-  ;;
-
-solaris*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  # ldd complains unless libraries are executable
-  postinstall_cmds='chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=sunos
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
-  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  if test "$with_gnu_ld" = yes; then
-    need_lib_prefix=no
-  fi
-  need_version=yes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=no
-      need_lib_prefix=no
-      runpath_var=LD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=no
-      ;;
-    motorola)
-      need_lib_prefix=no
-      need_version=no
-      shlibpath_overrides_runpath=no
-      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=linux # correct to gnu/linux during the next big refactor
-    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
-    soname_spec='$libname${shared_ext}.$major'
-    shlibpath_var=LD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=freebsd-elf
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=yes
-  hardcode_into_libs=yes
-  if test "$with_gnu_ld" = yes; then
-    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
-  else
-    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec='/usr/lib'
-  ;;
-
-tpf*)
-  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
-  version_type=linux # correct to gnu/linux during the next big refactor
-  need_lib_prefix=no
-  need_version=no
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=LD_LIBRARY_PATH
-  shlibpath_overrides_runpath=no
-  hardcode_into_libs=yes
-  ;;
-
-uts4*)
-  version_type=linux # correct to gnu/linux during the next big refactor
-  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec='${libname}${release}${shared_ext}$major'
-  shlibpath_var=LD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=no
-  ;;
-esac
-AC_MSG_RESULT([$dynamic_linker])
-test "$dynamic_linker" = no && can_build_shared=no
-
-variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
-if test "$GCC" = yes; then
-  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
-fi
-
-if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
-  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
-fi
-if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
-  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
-fi
-
-_LT_DECL([], [variables_saved_for_relink], [1],
-    [Variables whose values should be saved in libtool wrapper scripts and
-    restored at link time])
-_LT_DECL([], [need_lib_prefix], [0],
-    [Do we need the "lib" prefix for modules?])
-_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
-_LT_DECL([], [version_type], [0], [Library versioning type])
-_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
-_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
-_LT_DECL([], [shlibpath_overrides_runpath], [0],
-    [Is shlibpath searched before the hard-coded library search path?])
-_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
-_LT_DECL([], [library_names_spec], [1],
-    [[List of archive names.  First name is the real one, the rest are links.
-    The last name is the one that the linker finds with -lNAME]])
-_LT_DECL([], [soname_spec], [1],
-    [[The coded name of the library, if different from the real name]])
-_LT_DECL([], [install_override_mode], [1],
-    [Permission mode override for installation of shared libraries])
-_LT_DECL([], [postinstall_cmds], [2],
-    [Command to use after installation of a shared archive])
-_LT_DECL([], [postuninstall_cmds], [2],
-    [Command to use after uninstallation of a shared archive])
-_LT_DECL([], [finish_cmds], [2],
-    [Commands used to finish a libtool library installation in a directory])
-_LT_DECL([], [finish_eval], [1],
-    [[As "finish_cmds", except a single script fragment to be evaled but
-    not shown]])
-_LT_DECL([], [hardcode_into_libs], [0],
-    [Whether we should hardcode library paths into libraries])
-_LT_DECL([], [sys_lib_search_path_spec], [2],
-    [Compile-time system search path for libraries])
-_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
-    [Run-time system search path for libraries])
-])# _LT_SYS_DYNAMIC_LINKER
-
-
-# _LT_PATH_TOOL_PREFIX(TOOL)
-# --------------------------
-# find a file program which can recognize shared library
-AC_DEFUN([_LT_PATH_TOOL_PREFIX],
-[m4_require([_LT_DECL_EGREP])dnl
-AC_MSG_CHECKING([for $1])
-AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
-[case $MAGIC_CMD in
-[[\\/*] |  ?:[\\/]*])
-  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
-  ;;
-*)
-  lt_save_MAGIC_CMD="$MAGIC_CMD"
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-dnl $ac_dummy forces splitting on constant user-supplied paths.
-dnl POSIX.2 word splitting is done only on the output of word expansions,
-dnl not every word.  This closes a longstanding sh security hole.
-  ac_dummy="m4_if([$2], , $PATH, [$2])"
-  for ac_dir in $ac_dummy; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$1; then
-      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    $EGREP "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <<_LT_EOF 1>&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool@gnu.org
-
-_LT_EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS="$lt_save_ifs"
-  MAGIC_CMD="$lt_save_MAGIC_CMD"
-  ;;
-esac])
-MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  AC_MSG_RESULT($MAGIC_CMD)
-else
-  AC_MSG_RESULT(no)
-fi
-_LT_DECL([], [MAGIC_CMD], [0],
-	 [Used to examine libraries when file_magic_cmd begins with "file"])dnl
-])# _LT_PATH_TOOL_PREFIX
-
-# Old name:
-AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
-
-
-# _LT_PATH_MAGIC
-# --------------
-# find a file program which can recognize a shared library
-m4_defun([_LT_PATH_MAGIC],
-[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
-if test -z "$lt_cv_path_MAGIC_CMD"; then
-  if test -n "$ac_tool_prefix"; then
-    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
-  else
-    MAGIC_CMD=:
-  fi
-fi
-])# _LT_PATH_MAGIC
-
-
-# LT_PATH_LD
-# ----------
-# find the pathname to the GNU or non-GNU linker
-AC_DEFUN([LT_PATH_LD],
-[AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_PROG_ECHO_BACKSLASH])dnl
-
-AC_ARG_WITH([gnu-ld],
-    [AS_HELP_STRING([--with-gnu-ld],
-	[assume the C compiler uses GNU ld @<:@default=no@:>@])],
-    [test "$withval" = no || with_gnu_ld=yes],
-    [with_gnu_ld=no])dnl
-
-ac_prog=ld
-if test "$GCC" = yes; then
-  # Check if gcc -print-prog-name=ld gives a path.
-  AC_MSG_CHECKING([for ld used by $CC])
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [[\\/]]* | ?:[[\\/]]*)
-      re_direlt='/[[^/]][[^/]]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
-      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD="$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=ld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=unknown
-    ;;
-  esac
-elif test "$with_gnu_ld" = yes; then
-  AC_MSG_CHECKING([for GNU ld])
-else
-  AC_MSG_CHECKING([for non-GNU ld])
-fi
-AC_CACHE_VAL(lt_cv_path_LD,
-[if test -z "$LD"; then
-  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS="$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
-      lt_cv_path_LD="$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" != no && break
-	;;
-      *)
-	test "$with_gnu_ld" != yes && break
-	;;
-      esac
-    fi
-  done
-  IFS="$lt_save_ifs"
-else
-  lt_cv_path_LD="$LD" # Let the user override the test with a path.
-fi])
-LD="$lt_cv_path_LD"
-if test -n "$LD"; then
-  AC_MSG_RESULT($LD)
-else
-  AC_MSG_RESULT(no)
-fi
-test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
-_LT_PATH_LD_GNU
-AC_SUBST([LD])
-
-_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
-])# LT_PATH_LD
-
-# Old names:
-AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
-AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_PROG_LD], [])
-dnl AC_DEFUN([AC_PROG_LD], [])
-
-
-# _LT_PATH_LD_GNU
-#- --------------
-m4_defun([_LT_PATH_LD_GNU],
-[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
-[# I'd rather use --version here, but apparently some GNU lds only accept -v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=yes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=no
-  ;;
-esac])
-with_gnu_ld=$lt_cv_prog_gnu_ld
-])# _LT_PATH_LD_GNU
-
-
-# _LT_CMD_RELOAD
-# --------------
-# find reload flag for linker
-#   -- PORTME Some linkers may need a different reload flag.
-m4_defun([_LT_CMD_RELOAD],
-[AC_CACHE_CHECK([for $LD option to reload object files],
-  lt_cv_ld_reload_flag,
-  [lt_cv_ld_reload_flag='-r'])
-reload_flag=$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=" $reload_flag" ;;
-esac
-reload_cmds='$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    if test "$GCC" != yes; then
-      reload_cmds=false
-    fi
-    ;;
-  darwin*)
-    if test "$GCC" = yes; then
-      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
-    else
-      reload_cmds='$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
-_LT_TAGDECL([], [reload_flag], [1], [How to create reloadable object files])dnl
-_LT_TAGDECL([], [reload_cmds], [2])dnl
-])# _LT_CMD_RELOAD
-
-
-# _LT_CHECK_MAGIC_METHOD
-# ----------------------
-# how to check for library dependencies
-#  -- PORTME fill in with the dynamic library characteristics
-m4_defun([_LT_CHECK_MAGIC_METHOD],
-[m4_require([_LT_DECL_EGREP])
-m4_require([_LT_DECL_OBJDUMP])
-AC_CACHE_CHECK([how to recognize dependent libraries],
-lt_cv_deplibs_check_method,
-[lt_cv_file_magic_cmd='$MAGIC_CMD'
-lt_cv_file_magic_test_file=
-lt_cv_deplibs_check_method='unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix[[4-9]]*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-beos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-bsdi[[45]]*)
-  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd='/usr/bin/file -L'
-  lt_cv_file_magic_test_file=/shlib/libc.so
-  ;;
-
-cygwin*)
-  # func_win32_libid is a shell function defined in ltmain.sh
-  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-  lt_cv_file_magic_cmd='func_win32_libid'
-  ;;
-
-mingw* | pw32*)
-  # Base MSYS/MinGW do not provide the 'file' command needed by
-  # func_win32_libid shell function, so use a weaker test based on 'objdump',
-  # unless we find 'file', for example because we are cross-compiling.
-  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
-  if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then
-    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
-    lt_cv_file_magic_cmd='func_win32_libid'
-  else
-    # Keep this pattern in sync with the one in func_win32_libid.
-    lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)'
-    lt_cv_file_magic_cmd='$OBJDUMP -f'
-  fi
-  ;;
-
-cegcc*)
-  # use the weaker test based on 'objdump'. See mingw*.
-  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
-  lt_cv_file_magic_cmd='$OBJDUMP -f'
-  ;;
-
-darwin* | rhapsody*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-freebsd* | dragonfly*)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=/usr/bin/file
-      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=pass_all
-  fi
-  ;;
-
-haiku*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-hpux10.20* | hpux11*)
-  lt_cv_file_magic_cmd=/usr/bin/file
-  case $host_cpu in
-  ia64*)
-    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
-    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
-    ;;
-  hppa*64*)
-    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]']
-    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
-    ;;
-  *)
-    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library'
-    lt_cv_file_magic_test_file=/usr/lib/libc.sl
-    ;;
-  esac
-  ;;
-
-interix[[3-9]]*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $LD in
-  *-32|*"-32 ") libmagic=32-bit;;
-  *-n32|*"-n32 ") libmagic=N32;;
-  *-64|*"-64 ") libmagic=64-bit;;
-  *) libmagic=never-match;;
-  esac
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-# This must be glibc/ELF.
-linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-netbsd* | netbsdelf*-gnu)
-  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
-  fi
-  ;;
-
-newos6*)
-  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=/usr/bin/file
-  lt_cv_file_magic_test_file=/usr/lib/libnls.so
-  ;;
-
-*nto* | *qnx*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
-  fi
-  ;;
-
-osf3* | osf4* | osf5*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-rdos*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-solaris*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-
-sysv4 | sysv4.3*)
-  case $host_vendor in
-  motorola)
-    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
-    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
-    ;;
-  ncr)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  sequent)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
-    ;;
-  sni)
-    lt_cv_file_magic_cmd='/bin/file'
-    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
-    lt_cv_file_magic_test_file=/lib/libc.so
-    ;;
-  siemens)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  pc)
-    lt_cv_deplibs_check_method=pass_all
-    ;;
-  esac
-  ;;
-
-tpf*)
-  lt_cv_deplibs_check_method=pass_all
-  ;;
-esac
-])
-
-file_magic_glob=
-want_nocaseglob=no
-if test "$build" = "$host"; then
-  case $host_os in
-  mingw* | pw32*)
-    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
-      want_nocaseglob=yes
-    else
-      file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"`
-    fi
-    ;;
-  esac
-fi
-
-file_magic_cmd=$lt_cv_file_magic_cmd
-deplibs_check_method=$lt_cv_deplibs_check_method
-test -z "$deplibs_check_method" && deplibs_check_method=unknown
-
-_LT_DECL([], [deplibs_check_method], [1],
-    [Method to check whether dependent libraries are shared objects])
-_LT_DECL([], [file_magic_cmd], [1],
-    [Command to use when deplibs_check_method = "file_magic"])
-_LT_DECL([], [file_magic_glob], [1],
-    [How to find potential files when deplibs_check_method = "file_magic"])
-_LT_DECL([], [want_nocaseglob], [1],
-    [Find potential files using nocaseglob when deplibs_check_method = "file_magic"])
-])# _LT_CHECK_MAGIC_METHOD
-
-
-# LT_PATH_NM
-# ----------
-# find the pathname to a BSD- or MS-compatible name lister
-AC_DEFUN([LT_PATH_NM],
-[AC_REQUIRE([AC_PROG_CC])dnl
-AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
-[if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM="$NM"
-else
-  lt_nm_to_check="${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
-    lt_nm_to_check="$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS="$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=.
-      tmp_nm="$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM="$tmp_nm -B"
-	  break
-	  ;;
-	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM="$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
-	  ;;
-	esac
-      fi
-    done
-    IFS="$lt_save_ifs"
-  done
-  : ${lt_cv_path_NM=no}
-fi])
-if test "$lt_cv_path_NM" != "no"; then
-  NM="$lt_cv_path_NM"
-else
-  # Didn't find any BSD compatible name lister, look for dumpbin.
-  if test -n "$DUMPBIN"; then :
-    # Let the user override the test.
-  else
-    AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :)
-    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
-    *COFF*)
-      DUMPBIN="$DUMPBIN -symbols"
-      ;;
-    *)
-      DUMPBIN=:
-      ;;
-    esac
-  fi
-  AC_SUBST([DUMPBIN])
-  if test "$DUMPBIN" != ":"; then
-    NM="$DUMPBIN"
-  fi
-fi
-test -z "$NM" && NM=nm
-AC_SUBST([NM])
-_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
-
-AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
-  [lt_cv_nm_interface="BSD nm"
-  echo "int some_variable = 0;" > conftest.$ac_ext
-  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
-  (eval "$ac_compile" 2>conftest.err)
-  cat conftest.err >&AS_MESSAGE_LOG_FD
-  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
-  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
-  cat conftest.err >&AS_MESSAGE_LOG_FD
-  (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD)
-  cat conftest.out >&AS_MESSAGE_LOG_FD
-  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
-    lt_cv_nm_interface="MS dumpbin"
-  fi
-  rm -f conftest*])
-])# LT_PATH_NM
-
-# Old names:
-AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
-AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_PROG_NM], [])
-dnl AC_DEFUN([AC_PROG_NM], [])
-
-# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
-# --------------------------------
-# how to determine the name of the shared library
-# associated with a specific link library.
-#  -- PORTME fill in with the dynamic library characteristics
-m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB],
-[m4_require([_LT_DECL_EGREP])
-m4_require([_LT_DECL_OBJDUMP])
-m4_require([_LT_DECL_DLLTOOL])
-AC_CACHE_CHECK([how to associate runtime and link libraries],
-lt_cv_sharedlib_from_linklib_cmd,
-[lt_cv_sharedlib_from_linklib_cmd='unknown'
-
-case $host_os in
-cygwin* | mingw* | pw32* | cegcc*)
-  # two different shell functions defined in ltmain.sh
-  # decide which to use based on capabilities of $DLLTOOL
-  case `$DLLTOOL --help 2>&1` in
-  *--identify-strict*)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib
-    ;;
-  *)
-    lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback
-    ;;
-  esac
-  ;;
-*)
-  # fallback: assume linklib IS sharedlib
-  lt_cv_sharedlib_from_linklib_cmd="$ECHO"
-  ;;
-esac
-])
-sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd
-test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO
-
-_LT_DECL([], [sharedlib_from_linklib_cmd], [1],
-    [Command to associate shared and link libraries])
-])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB
-
-
-# _LT_PATH_MANIFEST_TOOL
-# ----------------------
-# locate the manifest tool
-m4_defun([_LT_PATH_MANIFEST_TOOL],
-[AC_CHECK_TOOL(MANIFEST_TOOL, mt, :)
-test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt
-AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool],
-  [lt_cv_path_mainfest_tool=no
-  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD
-  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
-  cat conftest.err >&AS_MESSAGE_LOG_FD
-  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
-    lt_cv_path_mainfest_tool=yes
-  fi
-  rm -f conftest*])
-if test "x$lt_cv_path_mainfest_tool" != xyes; then
-  MANIFEST_TOOL=:
-fi
-_LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl
-])# _LT_PATH_MANIFEST_TOOL
-
-
-# LT_LIB_M
-# --------
-# check for math library
-AC_DEFUN([LT_LIB_M],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-LIBM=
-case $host in
-*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*)
-  # These system don't have libm, or don't need it
-  ;;
-*-ncr-sysv4.3*)
-  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
-  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
-  ;;
-*)
-  AC_CHECK_LIB(m, cos, LIBM="-lm")
-  ;;
-esac
-AC_SUBST([LIBM])
-])# LT_LIB_M
-
-# Old name:
-AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_CHECK_LIBM], [])
-
-
-# _LT_COMPILER_NO_RTTI([TAGNAME])
-# -------------------------------
-m4_defun([_LT_COMPILER_NO_RTTI],
-[m4_require([_LT_TAG_COMPILER])dnl
-
-_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
-
-if test "$GCC" = yes; then
-  case $cc_basename in
-  nvcc*)
-    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;;
-  *)
-    _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;;
-  esac
-
-  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
-    lt_cv_prog_compiler_rtti_exceptions,
-    [-fno-rtti -fno-exceptions], [],
-    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
-fi
-_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
-	[Compiler flag to turn off builtin functions])
-])# _LT_COMPILER_NO_RTTI
-
-
-# _LT_CMD_GLOBAL_SYMBOLS
-# ----------------------
-m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_PROG_AWK])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-AC_REQUIRE([LT_PATH_LD])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-
-# Check for command to grab the raw symbol name followed by C symbol from nm.
-AC_MSG_CHECKING([command to parse $NM output from $compiler object])
-AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
-[
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode='[[BCDEGRST]]'
-
-# Regexp to match symbols that can be accessed directly from C.
-sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
-
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode='[[BCDT]]'
-  ;;
-cygwin* | mingw* | pw32* | cegcc*)
-  symcode='[[ABCDGISTW]]'
-  ;;
-hpux*)
-  if test "$host_cpu" = ia64; then
-    symcode='[[ABCDEGRST]]'
-  fi
-  ;;
-irix* | nonstopux*)
-  symcode='[[BCDEGRST]]'
-  ;;
-osf*)
-  symcode='[[BCDEGQRST]]'
-  ;;
-solaris*)
-  symcode='[[BDRT]]'
-  ;;
-sco3.2v5*)
-  symcode='[[DT]]'
-  ;;
-sysv4.2uw2*)
-  symcode='[[DT]]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode='[[ABDT]]'
-  ;;
-sysv4)
-  symcode='[[DFNSTU]]'
-  ;;
-esac
-
-# If we're using GNU nm, then use its standard symbol codes.
-case `$NM -V 2>&1` in
-*GNU* | *'with BFD'*)
-  symcode='[[ABCDGIRSTW]]' ;;
-esac
-
-# Transform an extracted symbol line into a proper C declaration.
-# Some systems (esp. on ia64) link data and code symbols differently,
-# so use this general approach.
-lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-
-# Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
-lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
-
-# Handle CRLF in mingw tool chain
-opt_cr=
-case $build_os in
-mingw*)
-  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
-  ;;
-esac
-
-# Try without a prefix underscore, then with it.
-for ac_symprfx in "" "_"; do
-
-  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
-  symxfrm="\\1 $ac_symprfx\\2 \\2"
-
-  # Write the raw and C identifiers.
-  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-    # Fake it for dumpbin and say T for any non-static function
-    # and D for any global variable.
-    # Also find C++ and __fastcall symbols from MSVC++,
-    # which start with @ or ?.
-    lt_cv_sys_global_symbol_pipe="$AWK ['"\
-"     {last_section=section; section=\$ 3};"\
-"     /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\
-"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
-"     \$ 0!~/External *\|/{next};"\
-"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
-"     {if(hide[section]) next};"\
-"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
-"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
-"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
-"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
-"     ' prfx=^$ac_symprfx]"
-  else
-    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[	 ]]\($symcode$symcode*\)[[	 ]][[	 ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
-  fi
-  lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'"
-
-  # Check to see that the pipe works correctly.
-  pipe_works=no
-
-  rm -f conftest*
-  cat > conftest.$ac_ext <<_LT_EOF
-#ifdef __cplusplus
-extern "C" {
-#endif
-char nm_test_var;
-void nm_test_func(void);
-void nm_test_func(void){}
-#ifdef __cplusplus
-}
-#endif
-int main(){nm_test_var='a';nm_test_func();return(0);}
-_LT_EOF
-
-  if AC_TRY_EVAL(ac_compile); then
-    # Now try to grab the symbols.
-    nlist=conftest.nm
-    if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then
-      # Try sorting and uniquifying the output.
-      if sort "$nlist" | uniq > "$nlist"T; then
-	mv -f "$nlist"T "$nlist"
-      else
-	rm -f "$nlist"T
-      fi
-
-      # Make sure that we snagged all the symbols we need.
-      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
-	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
-	  cat <<_LT_EOF > conftest.$ac_ext
-/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */
-#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
-/* DATA imports from DLLs on WIN32 con't be const, because runtime
-   relocations are performed -- see ld's documentation on pseudo-relocs.  */
-# define LT@&t@_DLSYM_CONST
-#elif defined(__osf__)
-/* This system does not cope well with relocations in const data.  */
-# define LT@&t@_DLSYM_CONST
-#else
-# define LT@&t@_DLSYM_CONST const
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-_LT_EOF
-	  # Now generate the symbol file.
-	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
-
-	  cat <<_LT_EOF >> conftest.$ac_ext
-
-/* The mapping between symbol names and symbols.  */
-LT@&t@_DLSYM_CONST struct {
-  const char *name;
-  void       *address;
-}
-lt__PROGRAM__LTX_preloaded_symbols[[]] =
-{
-  { "@PROGRAM@", (void *) 0 },
-_LT_EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
-	  cat <<\_LT_EOF >> conftest.$ac_ext
-  {0, (void *) 0}
-};
-
-/* This works around a problem in FreeBSD linker */
-#ifdef FREEBSD_WORKAROUND
-static const void *lt_preloaded_setup() {
-  return lt__PROGRAM__LTX_preloaded_symbols;
-}
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-_LT_EOF
-	  # Now try linking the two files.
-	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_globsym_save_LIBS=$LIBS
-	  lt_globsym_save_CFLAGS=$CFLAGS
-	  LIBS="conftstm.$ac_objext"
-	  CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
-	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
-	    pipe_works=yes
-	  fi
-	  LIBS=$lt_globsym_save_LIBS
-	  CFLAGS=$lt_globsym_save_CFLAGS
-	else
-	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
-	fi
-      else
-	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
-      fi
-    else
-      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
-    fi
-  else
-    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
-    cat conftest.$ac_ext >&5
-  fi
-  rm -rf conftest* conftst*
-
-  # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" = yes; then
-    break
-  else
-    lt_cv_sys_global_symbol_pipe=
-  fi
-done
-])
-if test -z "$lt_cv_sys_global_symbol_pipe"; then
-  lt_cv_sys_global_symbol_to_cdecl=
-fi
-if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
-  AC_MSG_RESULT(failed)
-else
-  AC_MSG_RESULT(ok)
-fi
-
-# Response file support.
-if test "$lt_cv_nm_interface" = "MS dumpbin"; then
-  nm_file_list_spec='@'
-elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then
-  nm_file_list_spec='@'
-fi
-
-_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
-    [Take the output of nm and produce a listing of raw symbols and C names])
-_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
-    [Transform the output of nm in a proper C declaration])
-_LT_DECL([global_symbol_to_c_name_address],
-    [lt_cv_sys_global_symbol_to_c_name_address], [1],
-    [Transform the output of nm in a C name address pair])
-_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
-    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
-    [Transform the output of nm in a C name address pair when lib prefix is needed])
-_LT_DECL([], [nm_file_list_spec], [1],
-    [Specify filename containing input files for $NM])
-]) # _LT_CMD_GLOBAL_SYMBOLS
-
-
-# _LT_COMPILER_PIC([TAGNAME])
-# ---------------------------
-m4_defun([_LT_COMPILER_PIC],
-[m4_require([_LT_TAG_COMPILER])dnl
-_LT_TAGVAR(lt_prog_compiler_wl, $1)=
-_LT_TAGVAR(lt_prog_compiler_pic, $1)=
-_LT_TAGVAR(lt_prog_compiler_static, $1)=
-
-m4_if([$1], [CXX], [
-  # C++ specific cases for pic, static, wl, etc.
-  if test "$GXX" = yes; then
-    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-
-    case $host_os in
-    aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-    mingw* | cygwin* | os2* | pw32* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
-      ;;
-    *djgpp*)
-      # DJGPP does not support shared libraries at all
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-      ;;
-    haiku*)
-      # PIC is the default for Haiku.
-      # The "-static" flag exists, but is broken.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)=
-      ;;
-    interix[[3-9]]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
-      fi
-      ;;
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	;;
-      esac
-      ;;
-    *qnx* | *nto*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-    *)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-      ;;
-    esac
-  else
-    case $host_os in
-      aix[[4-9]]*)
-	# All AIX code is PIC.
-	if test "$host_cpu" = ia64; then
-	  # AIX 5 now supports IA64 processor
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	else
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
-	fi
-	;;
-      chorus*)
-	case $cc_basename in
-	cxch68*)
-	  # Green Hills C++ Compiler
-	  # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
-	  ;;
-	esac
-	;;
-      mingw* | cygwin* | os2* | pw32* | cegcc*)
-	# This hack is so that the source file can tell whether it is being
-	# built for inclusion in a dll (and should export symbols for example).
-	m4_if([$1], [GCJ], [],
-	  [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-	;;
-      dgux*)
-	case $cc_basename in
-	  ec++*)
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    ;;
-	  ghcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      freebsd* | dragonfly*)
-	# FreeBSD uses GNU C++
-	;;
-      hpux9* | hpux10* | hpux11*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    if test "$host_cpu" != ia64; then
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	    fi
-	    ;;
-	  aCC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-	    case $host_cpu in
-	    hppa*64*|ia64*)
-	      # +Z the default
-	      ;;
-	    *)
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	      ;;
-	    esac
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
-      irix5* | irix6* | nonstopux*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    # CC pic flag -KPIC is the default.
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-	case $cc_basename in
-	  KCC*)
-	    # KAI C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	    ;;
-	  ecpc* )
-	    # old Intel C++ for x86_64 which still supported -KPIC.
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	    ;;
-	  icpc* )
-	    # Intel C++, used to be incompatible with GCC.
-	    # ICC 10 doesn't accept -KPIC any more.
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	    ;;
-	  pgCC* | pgcpp*)
-	    # Portland Group C++ compiler
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	  cxx*)
-	    # Compaq C++
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    ;;
-	  xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*)
-	    # IBM XL 8.0, 9.0 on PPC and BlueGene
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
-	    ;;
-	  *)
-	    case `$CC -V 2>&1 | sed 5q` in
-	    *Sun\ C*)
-	      # Sun C++ 5.9
-	      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-	      ;;
-	    esac
-	    ;;
-	esac
-	;;
-      lynxos*)
-	;;
-      m88k*)
-	;;
-      mvs*)
-	case $cc_basename in
-	  cxx*)
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      netbsd* | netbsdelf*-gnu)
-	;;
-      *qnx* | *nto*)
-        # QNX uses GNU C++, but need to define -shared option too, otherwise
-        # it will coredump.
-        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-        ;;
-      osf3* | osf4* | osf5*)
-	case $cc_basename in
-	  KCC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
-	    ;;
-	  RCC*)
-	    # Rational C++ 2.4.1
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  cxx*)
-	    # Digital/Compaq C++
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      psos*)
-	;;
-      solaris*)
-	case $cc_basename in
-	  CC* | sunCC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-	    ;;
-	  gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sunos4*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.x
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	  lcc*)
-	    # Lucid
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	    ;;
-	esac
-	;;
-      tandem*)
-	case $cc_basename in
-	  NCC*)
-	    # NonStop-UX NCC 3.20
-	    _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      vxworks*)
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-	;;
-    esac
-  fi
-],
-[
-  if test "$GCC" = yes; then
-    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-        ;;
-      m68k)
-            # FIXME: we need at least 68020 code to build shared libraries, but
-            # adding the `-m68020' flag to GCC prevents building anything better,
-            # like `-m68040'.
-            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
-        ;;
-      esac
-      ;;
-
-    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      # Although the cygwin gcc ignores -fPIC, still need this for old-style
-      # (--disable-auto-import) libraries
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
-      ;;
-
-    haiku*)
-      # PIC is the default for Haiku.
-      # The "-static" flag exists, but is broken.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)=
-      ;;
-
-    hpux*)
-      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
-      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
-      # sets the default TLS model and affects inlining.
-      case $host_cpu in
-      hppa*64*)
-	# +Z the default
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	;;
-      esac
-      ;;
-
-    interix[[3-9]]*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared libraries
-      # on systems that don't support them.
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      enable_shared=no
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
-      fi
-      ;;
-
-    *)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-      ;;
-    esac
-
-    case $cc_basename in
-    nvcc*) # Cuda Compiler Driver 2.2
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker '
-      if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
-        _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)"
-      fi
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compiler.
-    case $host_os in
-    aix*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      if test "$host_cpu" = ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      else
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-
-    mingw* | cygwin* | pw32* | os2* | cegcc*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for example).
-      m4_if([$1], [GCJ], [],
-	[_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bundled CC?
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # PIC (with -KPIC) is the default.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-      case $cc_basename in
-      # old Intel for x86_64 which still supported -KPIC.
-      ecc*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-        ;;
-      # icc used to be incompatible with GCC.
-      # ICC 10 doesn't accept -KPIC any more.
-      icc* | ifort*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-        ;;
-      # Lahey Fortran 8.1.
-      lf95*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
-	;;
-      nagfor*)
-	# NAG Fortran compiler
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	;;
-      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-        ;;
-      ccc*)
-        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-        # All Alpha code is PIC.
-        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-        ;;
-      xl* | bgxl* | bgf* | mpixl*)
-	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
-	;;
-      *)
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*)
-	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
-	  ;;
-	*Sun\ F* | *Sun*Fortran*)
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-	  ;;
-	*Sun\ C*)
-	  # Sun C 5.9
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	  ;;
-        *Intel*\ [[CF]]*Compiler*)
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
-	  ;;
-	*Portland\ Group*)
-	  _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-	  _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
-	  _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-	  ;;
-	esac
-	;;
-      esac
-      ;;
-
-    newsos6)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    *nto* | *qnx*)
-      # QNX uses GNU C++, but need to define -shared option too, otherwise
-      # it will coredump.
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
-      ;;
-
-    osf3* | osf4* | osf5*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      # All OSF/1 code is PIC.
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    rdos*)
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
-      ;;
-
-    solaris*)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
-      *)
-	_LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	_LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
-	_LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    unicos*)
-      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      ;;
-
-    uts4*)
-      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
-      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
-      ;;
-
-    *)
-      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
-      ;;
-    esac
-  fi
-])
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
-    ;;
-  *)
-    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
-    ;;
-esac
-
-AC_CACHE_CHECK([for $compiler option to produce PIC],
-  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)],
-  [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
-_LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
-  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
-    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
-    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
-    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
-     "" | " "*) ;;
-     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
-     esac],
-    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
-     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
-fi
-_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
-	[Additional compiler flags for building library objects])
-
-_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
-	[How to pass a linker flag through the compiler])
-#
-# Check to make sure the static flag actually works.
-#
-wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
-_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
-  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
-  $lt_tmp_static_flag,
-  [],
-  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
-_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
-	[Compiler flag to prevent dynamic linking])
-])# _LT_COMPILER_PIC
-
-
-# _LT_LINKER_SHLIBS([TAGNAME])
-# ----------------------------
-# See if the linker supports building shared libraries.
-m4_defun([_LT_LINKER_SHLIBS],
-[AC_REQUIRE([LT_PATH_LD])dnl
-AC_REQUIRE([LT_PATH_NM])dnl
-m4_require([_LT_PATH_MANIFEST_TOOL])dnl
-m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_DECL_SED])dnl
-m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
-m4_require([_LT_TAG_COMPILER])dnl
-AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
-m4_if([$1], [CXX], [
-  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
-  case $host_os in
-  aix[[4-9]]*)
-    # If we're using GNU nm, then we don't want the "-C" option.
-    # -C means demangle to AIX nm, but means don't demangle with GNU nm
-    # Also, AIX nm treats weak defined symbols like other global defined
-    # symbols, whereas GNU nm marks them as "W".
-    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-    else
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-    fi
-    ;;
-  pw32*)
-    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
-    ;;
-  cygwin* | mingw* | cegcc*)
-    case $cc_basename in
-    cl*)
-      _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
-      ;;
-    *)
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
-      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
-      ;;
-    esac
-    ;;
-  linux* | k*bsd*-gnu | gnu*)
-    _LT_TAGVAR(link_all_deplibs, $1)=no
-    ;;
-  *)
-    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-    ;;
-  esac
-], [
-  runpath_var=
-  _LT_TAGVAR(allow_undefined_flag, $1)=
-  _LT_TAGVAR(always_export_symbols, $1)=no
-  _LT_TAGVAR(archive_cmds, $1)=
-  _LT_TAGVAR(archive_expsym_cmds, $1)=
-  _LT_TAGVAR(compiler_needs_object, $1)=no
-  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
-  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  _LT_TAGVAR(hardcode_automatic, $1)=no
-  _LT_TAGVAR(hardcode_direct, $1)=no
-  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
-  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-  _LT_TAGVAR(hardcode_libdir_separator, $1)=
-  _LT_TAGVAR(hardcode_minus_L, $1)=no
-  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-  _LT_TAGVAR(inherit_rpath, $1)=no
-  _LT_TAGVAR(link_all_deplibs, $1)=unknown
-  _LT_TAGVAR(module_cmds, $1)=
-  _LT_TAGVAR(module_expsym_cmds, $1)=
-  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
-  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
-  _LT_TAGVAR(thread_safe_flag_spec, $1)=
-  _LT_TAGVAR(whole_archive_flag_spec, $1)=
-  # include_expsyms should be a list of space-separated symbols to be *always*
-  # included in the symbol list
-  _LT_TAGVAR(include_expsyms, $1)=
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
-  # as well as any symbol that contains `d'.
-  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  # Exclude shared library initialization/finalization symbols.
-dnl Note also adjust exclude_expsyms for C++ above.
-  extract_expsyms_cmds=
-
-  case $host_os in
-  cygwin* | mingw* | pw32* | cegcc*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" != yes; then
-      with_gnu_ld=no
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (= MSVC++)
-    with_gnu_ld=yes
-    ;;
-  openbsd*)
-    with_gnu_ld=no
-    ;;
-  linux* | k*bsd*-gnu | gnu*)
-    _LT_TAGVAR(link_all_deplibs, $1)=no
-    ;;
-  esac
-
-  _LT_TAGVAR(ld_shlibs, $1)=yes
-
-  # On some targets, GNU ld is compatible enough with the native linker
-  # that we're better off using the native interface for both.
-  lt_use_gnu_ld_interface=no
-  if test "$with_gnu_ld" = yes; then
-    case $host_os in
-      aix*)
-	# The AIX port of GNU ld has always aspired to compatibility
-	# with the native linker.  However, as the warning in the GNU ld
-	# block says, versions before 2.19.5* couldn't really create working
-	# shared libraries, regardless of the interface used.
-	case `$LD -v 2>&1` in
-	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
-	  *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;;
-	  *\ \(GNU\ Binutils\)\ [[3-9]]*) ;;
-	  *)
-	    lt_use_gnu_ld_interface=yes
-	    ;;
-	esac
-	;;
-      *)
-	lt_use_gnu_ld_interface=yes
-	;;
-    esac
-  fi
-
-  if test "$lt_use_gnu_ld_interface" = yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc='${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=LD_RUN_PATH
-    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
-      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-    else
-      _LT_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-    supports_anon_versioning=no
-    case `$LD -v 2>&1` in
-      *GNU\ gold*) supports_anon_versioning=yes ;;
-      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=yes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix[[3-9]]*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" != ia64; then
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.19, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to install binutils
-*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
-*** You will then need to restart the configuration process.
-
-_LT_EOF
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            _LT_TAGVAR(archive_expsym_cmds, $1)=''
-        ;;
-      m68k)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes
-        ;;
-      esac
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	# Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	_LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
-      # as there is no search path for DLLs.
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(always_export_symbols, $1)=no
-      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
-      _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname']
-
-      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    haiku*)
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    interix[[3-9]]*)
-      _LT_TAGVAR(hardcode_direct, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-      # Instead, shared libraries are loaded at an image base (0x10000000 by
-      # default) and relocated if they conflict, which is a slow very memory
-      # consuming and fragmenting process.  To avoid this, we pick a random,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      ;;
-
-    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
-      tmp_diet=no
-      if test "$host_os" = linux-dietlibc; then
-	case $cc_basename in
-	  diet\ *) tmp_diet=yes;;	# linux-dietlibc with static linking (!diet-dyn)
-	esac
-      fi
-      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
-	 && test "$tmp_diet" = no
-      then
-	tmp_addflag=' $pic_flag'
-	tmp_sharedflag='-shared'
-	case $cc_basename,$host_cpu in
-        pgcc*)				# Portland Group C compiler
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95* | pgfortran*)
-					# Portland Group f77 and f90 compilers
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
-	  tmp_addflag=' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=' -nofor_main' ;;
-	lf95*)				# Lahey Fortran 8.1
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)=
-	  tmp_sharedflag='--shared' ;;
-	xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below)
-	  tmp_sharedflag='-qmkshrobj'
-	  tmp_addflag= ;;
-	nvcc*)	# Cuda Compiler Driver 2.2
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  _LT_TAGVAR(compiler_needs_object, $1)=yes
-	  ;;
-	esac
-	case `$CC -V 2>&1 | sed 5q` in
-	*Sun\ C*)			# Sun C 5.9
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	  _LT_TAGVAR(compiler_needs_object, $1)=yes
-	  tmp_sharedflag='-G' ;;
-	*Sun\ F*)			# Sun Fortran 8.3
-	  tmp_sharedflag='-G' ;;
-	esac
-	_LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-        if test "x$supports_anon_versioning" = xyes; then
-          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	    echo "local: *; };" >> $output_objdir/$libname.ver~
-	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-        fi
-
-	case $cc_basename in
-	xlf* | bgf* | bgxlf* | mpixlf*)
-	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib'
-	  if test "x$supports_anon_versioning" = xyes; then
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-	      echo "local: *; };" >> $output_objdir/$libname.ver~
-	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
-	  fi
-	  ;;
-	esac
-      else
-        _LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    netbsd* | netbsdelf*-gnu)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
-	wlarc=
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  # For security reasons, it is highly recommended that you always
-	  # use absolute paths for naming shared libraries, and exclude the
-	  # DT_RUNPATH tag from executables and libraries.  But doing so
-	  # requires that you compile everything twice, which is a pain.
-	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-	  else
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      wlarc=
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *)
-      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-    esac
-
-    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
-      runpath_var=
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
-      _LT_TAGVAR(whole_archive_flag_spec, $1)=
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(always_export_symbols, $1)=yes
-      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	_LT_TAGVAR(hardcode_direct, $1)=unsupported
-      fi
-      ;;
-
-    aix[[4-9]]*)
-      if test "$host_cpu" = ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=no
-	exp_sym_flag='-Bexport'
-	no_entry_flag=""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	# Also, AIX nm treats weak defined symbols like other global
-	# defined symbols, whereas GNU nm marks them as "W".
-	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-	else
-	  _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
-	fi
-	aix_use_runtimelinking=no
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
-	  for ld_flag in $LDFLAGS; do
-	  if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
-	    aix_use_runtimelinking=yes
-	    break
-	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag='-bexport'
-	no_entry_flag='-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      _LT_TAGVAR(archive_cmds, $1)=''
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
-
-      if test "$GCC" = yes; then
-	case $host_os in aix4.[[012]]|aix4.[[012]].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	  # We have reworked collect2
-	  :
-	  else
-	  # We have old collect2
-	  _LT_TAGVAR(hardcode_direct, $1)=unsupported
-	  # It fails to find uninstalled libraries when the uninstalled
-	  # path is not listed in the libpath.  Setting hardcode_minus_L
-	  # to unsupported forces relinking
-	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	  _LT_TAGVAR(hardcode_libdir_separator, $1)=
-	  fi
-	  ;;
-	esac
-	shared_flag='-shared'
-	if test "$aix_use_runtimelinking" = yes; then
-	  shared_flag="$shared_flag "'${wl}-G'
-	fi
-	_LT_TAGVAR(link_all_deplibs, $1)=no
-      else
-	# not using gcc
-	if test "$host_cpu" = ia64; then
-	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-	else
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag='${wl}-G'
-	  else
-	    shared_flag='${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to export.
-      _LT_TAGVAR(always_export_symbols, $1)=yes
-      if test "$aix_use_runtimelinking" = yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	_LT_TAGVAR(allow_undefined_flag, $1)='-berok'
-        # Determine the default libpath from the value encoded in an
-        # empty executable.
-        _LT_SYS_MODULE_PATH_AIX([$1])
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-      else
-	if test "$host_cpu" = ia64; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
-	  _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an
-	 # empty executable.
-	 _LT_SYS_MODULE_PATH_AIX([$1])
-	 _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
-	  _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	  if test "$with_gnu_ld" = yes; then
-	    # We only use this code for GNU lds that support --whole-archive.
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	  else
-	    # Exported symbols can be pulled into shared objects from archives
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
-	  fi
-	  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      case $host_cpu in
-      powerpc)
-            # see comment about AmigaOS4 .so support
-            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-            _LT_TAGVAR(archive_expsym_cmds, $1)=''
-        ;;
-      m68k)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
-            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes
-        ;;
-      esac
-      ;;
-
-    bsdi[[45]]*)
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32* | cegcc*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      case $cc_basename in
-      cl*)
-	# Native MSVC
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	_LT_TAGVAR(always_export_symbols, $1)=yes
-	_LT_TAGVAR(file_list_spec, $1)='@'
-	# Tell ltmain to make .lib files, not .a files.
-	libext=lib
-	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
-	# FIXME: Setting linknames here is a bad hack.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	_LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	  else
-	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	  fi~
-	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	  linknames='
-	# The linker will not automatically build a static lib if we build a DLL.
-	# _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-	_LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*'
-	_LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
-	# Don't use ranlib
-	_LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
-	_LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
-	  lt_tool_outputfile="@TOOL_OUTPUT@"~
-	  case $lt_outputfile in
-	    *.exe|*.EXE) ;;
-	    *)
-	      lt_outputfile="$lt_outputfile.exe"
-	      lt_tool_outputfile="$lt_tool_outputfile.exe"
-	      ;;
-	  esac~
-	  if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	    $RM "$lt_outputfile.manifest";
-	  fi'
-	;;
-      *)
-	# Assume MSVC wrapper
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-	_LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	# Tell ltmain to make .lib files, not .a files.
-	libext=lib
-	# Tell ltmain to make .dll files, not .so files.
-	shrext_cmds=".dll"
-	# FIXME: Setting linknames here is a bad hack.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames='
-	# The linker will automatically build a .lib file if we build a DLL.
-	_LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-	# FIXME: Should let the user specify the lib program.
-	_LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
-	_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-	;;
-      esac
-      ;;
-
-    darwin* | rhapsody*)
-      _LT_DARWIN_LINKER_FEATURES($1)
-      ;;
-
-    dgux*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
-    # support.  Future versions do this automatically, but an explicit c++rt0.o
-    # does not break anything, and helps significantly (at the cost of a little
-    # extra space).
-    freebsd2.2*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2.*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | dragonfly*)
-      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    hpux9*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-      ;;
-
-    hpux10*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
-	_LT_TAGVAR(hardcode_direct, $1)=yes
-	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	_LT_TAGVAR(hardcode_minus_L, $1)=yes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" = yes && test "$with_gnu_ld" = no; then
-	case $host_cpu in
-	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	m4_if($1, [], [
-	  # Older versions of the 11.00 compiler do not understand -b yet
-	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
-	  _LT_LINKER_OPTION([if $CC understands -b],
-	    _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b],
-	    [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'],
-	    [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])],
-	  [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'])
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" = no; then
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  _LT_TAGVAR(hardcode_direct, $1)=no
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	  ;;
-	*)
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	  ;;
-	esac
-      fi
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	# Try to use the -exported_symbol ld option, if it does not
-	# work, assume that -exports_file does not work either and
-	# implicitly export all symbols.
-	# This should be the same for all languages, so no per-tag cache variable.
-	AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol],
-	  [lt_cv_irix_exported_symbol],
-	  [save_LDFLAGS="$LDFLAGS"
-	   LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
-	   AC_LINK_IFELSE(
-	     [AC_LANG_SOURCE(
-	        [AC_LANG_CASE([C], [[int foo (void) { return 0; }]],
-			      [C++], [[int foo (void) { return 0; }]],
-			      [Fortran 77], [[
-      subroutine foo
-      end]],
-			      [Fortran], [[
-      subroutine foo
-      end]])])],
-	      [lt_cv_irix_exported_symbol=yes],
-	      [lt_cv_irix_exported_symbol=no])
-           LDFLAGS="$save_LDFLAGS"])
-	if test "$lt_cv_irix_exported_symbol" = yes; then
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
-	fi
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(inherit_rpath, $1)=yes
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    netbsd* | netbsdelf*-gnu)
-      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    newsos6)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *nto* | *qnx*)
-      ;;
-
-    openbsd*)
-      if test -f /usr/libexec/ld.so; then
-	_LT_TAGVAR(hardcode_direct, $1)=yes
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	else
-	  case $host_os in
-	   openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
-	     _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	     ;;
-	   *)
-	     _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
-	     _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	     ;;
-	  esac
-	fi
-      else
-	_LT_TAGVAR(ld_shlibs, $1)=no
-      fi
-      ;;
-
-    os2*)
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-      else
-	_LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
-	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
-
-	# Both c and cxx compiler support -rpath directly
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-      fi
-      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-      ;;
-
-    solaris*)
-      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
-      if test "$GCC" = yes; then
-	wlarc='${wl}'
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-      else
-	case `$CC -V 2>&1` in
-	*"Compilers 5.0"*)
-	  wlarc=''
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
-	  ;;
-	*)
-	  wlarc='${wl}'
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
-	  ;;
-	esac
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      case $host_os in
-      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-      *)
-	# The compiler driver will combine and reorder linker options,
-	# but understands `-z linker_flag'.  GCC discards it without `$wl',
-	# but is careful enough not to reorder.
-	# Supported since Solaris 2.6 (maybe 2.5.1?)
-	if test "$GCC" = yes; then
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-	else
-	  _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
-	fi
-	;;
-      esac
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" = xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
-      fi
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_direct, $1)=yes
-      _LT_TAGVAR(hardcode_minus_L, $1)=yes
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
-	  _LT_TAGVAR(hardcode_direct, $1)=no
-        ;;
-	motorola)
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	  _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
-	;;
-      esac
-      runpath_var='LD_RUN_PATH'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    sysv4.3*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	runpath_var=LD_RUN_PATH
-	hardcode_runpath_var=yes
-	_LT_TAGVAR(ld_shlibs, $1)=yes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
-      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-      _LT_TAGVAR(link_all_deplibs, $1)=yes
-      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-      runpath_var='LD_RUN_PATH'
-
-      if test "$GCC" = yes; then
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    uts4*)
-      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
-      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      ;;
-
-    *)
-      _LT_TAGVAR(ld_shlibs, $1)=no
-      ;;
-    esac
-
-    if test x$host_vendor = xsni; then
-      case $host in
-      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
-	;;
-      esac
-    fi
-  fi
-])
-AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
-
-_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
-
-_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
-_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
-_LT_DECL([], [extract_expsyms_cmds], [2],
-    [The commands to extract the exported symbol list from a shared archive])
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
-x|xyes)
-  # Assume -lc should be added
-  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-
-  if test "$enable_shared" = yes && test "$GCC" = yes; then
-    case $_LT_TAGVAR(archive_cmds, $1) in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      AC_CACHE_CHECK([whether -lc should be explicitly linked in],
-	[lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1),
-	[$RM conftest*
-	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-	if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
-	  soname=conftest
-	  lib=conftest
-	  libobjs=conftest.$ac_objext
-	  deplibs=
-	  wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
-	  pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
-	  compiler_flags=-v
-	  linker_flags=-v
-	  verstring=
-	  output_objdir=.
-	  libname=conftest
-	  lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
-	  _LT_TAGVAR(allow_undefined_flag, $1)=
-	  if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
-	  then
-	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	  else
-	    lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	  fi
-	  _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
-	else
-	  cat conftest.err 1>&5
-	fi
-	$RM conftest*
-	])
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
-    [Whether or not to add -lc for building shared libraries])
-_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
-    [enable_shared_with_static_runtimes], [0],
-    [Whether or not to disallow shared libs when runtime libs are static])
-_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
-    [Compiler flag to allow reflexive dlopens])
-_LT_TAGDECL([], [whole_archive_flag_spec], [1],
-    [Compiler flag to generate shared objects directly from archives])
-_LT_TAGDECL([], [compiler_needs_object], [1],
-    [Whether the compiler copes with passing no objects directly])
-_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
-    [Create an old-style archive from a shared archive])
-_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
-    [Create a temporary old-style archive to link instead of a shared archive])
-_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
-_LT_TAGDECL([], [archive_expsym_cmds], [2])
-_LT_TAGDECL([], [module_cmds], [2],
-    [Commands used to build a loadable module if different from building
-    a shared archive.])
-_LT_TAGDECL([], [module_expsym_cmds], [2])
-_LT_TAGDECL([], [with_gnu_ld], [1],
-    [Whether we are building with GNU ld or not])
-_LT_TAGDECL([], [allow_undefined_flag], [1],
-    [Flag that allows shared libraries with undefined symbols to be built])
-_LT_TAGDECL([], [no_undefined_flag], [1],
-    [Flag that enforces no undefined symbols])
-_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
-    [Flag to hardcode $libdir into a binary during linking.
-    This must work even if $libdir does not exist])
-_LT_TAGDECL([], [hardcode_libdir_separator], [1],
-    [Whether we need a single "-rpath" flag with a separated argument])
-_LT_TAGDECL([], [hardcode_direct], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
-    DIR into the resulting binary])
-_LT_TAGDECL([], [hardcode_direct_absolute], [0],
-    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
-    DIR into the resulting binary and the resulting library dependency is
-    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
-    library is relocated])
-_LT_TAGDECL([], [hardcode_minus_L], [0],
-    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
-    into the resulting binary])
-_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
-    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
-    into the resulting binary])
-_LT_TAGDECL([], [hardcode_automatic], [0],
-    [Set to "yes" if building a shared library automatically hardcodes DIR
-    into the library and all subsequent libraries and executables linked
-    against it])
-_LT_TAGDECL([], [inherit_rpath], [0],
-    [Set to yes if linker adds runtime paths of dependent libraries
-    to runtime path list])
-_LT_TAGDECL([], [link_all_deplibs], [0],
-    [Whether libtool must link a program against all its dependency libraries])
-_LT_TAGDECL([], [always_export_symbols], [0],
-    [Set to "yes" if exported symbols are required])
-_LT_TAGDECL([], [export_symbols_cmds], [2],
-    [The commands to list exported symbols])
-_LT_TAGDECL([], [exclude_expsyms], [1],
-    [Symbols that should not be listed in the preloaded symbols])
-_LT_TAGDECL([], [include_expsyms], [1],
-    [Symbols that must always be exported])
-_LT_TAGDECL([], [prelink_cmds], [2],
-    [Commands necessary for linking programs (against libraries) with templates])
-_LT_TAGDECL([], [postlink_cmds], [2],
-    [Commands necessary for finishing linking programs])
-_LT_TAGDECL([], [file_list_spec], [1],
-    [Specify filename containing input files])
-dnl FIXME: Not yet implemented
-dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
-dnl    [Compiler flag to generate thread safe objects])
-])# _LT_LINKER_SHLIBS
-
-
-# _LT_LANG_C_CONFIG([TAG])
-# ------------------------
-# Ensure that the configuration variables for a C compiler are suitably
-# defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_C_CONFIG],
-[m4_require([_LT_DECL_EGREP])dnl
-lt_save_CC="$CC"
-AC_LANG_PUSH(C)
-
-# Source file extension for C test sources.
-ac_ext=c
-
-# Object file extension for compiled C test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="int some_variable = 0;"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='int main(){return(0);}'
-
-_LT_TAG_COMPILER
-# Save the default compiler, since it gets overwritten when the other
-# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
-compiler_DEFAULT=$CC
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-  _LT_COMPILER_NO_RTTI($1)
-  _LT_COMPILER_PIC($1)
-  _LT_COMPILER_C_O($1)
-  _LT_COMPILER_FILE_LOCKS($1)
-  _LT_LINKER_SHLIBS($1)
-  _LT_SYS_DYNAMIC_LINKER($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-  LT_SYS_DLOPEN_SELF
-  _LT_CMD_STRIPLIB
-
-  # Report which library types will actually be built
-  AC_MSG_CHECKING([if libtool supports shared libraries])
-  AC_MSG_RESULT([$can_build_shared])
-
-  AC_MSG_CHECKING([whether to build shared libraries])
-  test "$can_build_shared" = "no" && enable_shared=no
-
-  # On AIX, shared libraries and static libraries use the same namespace, and
-  # are all built from PIC.
-  case $host_os in
-  aix3*)
-    test "$enable_shared" = yes && enable_static=no
-    if test -n "$RANLIB"; then
-      archive_cmds="$archive_cmds~\$RANLIB \$lib"
-      postinstall_cmds='$RANLIB $lib'
-    fi
-    ;;
-
-  aix[[4-9]]*)
-    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-      test "$enable_shared" = yes && enable_static=no
-    fi
-    ;;
-  esac
-  AC_MSG_RESULT([$enable_shared])
-
-  AC_MSG_CHECKING([whether to build static libraries])
-  # Make sure either enable_shared or enable_static is yes.
-  test "$enable_shared" = yes || enable_static=yes
-  AC_MSG_RESULT([$enable_static])
-
-  _LT_CONFIG($1)
-fi
-AC_LANG_POP
-CC="$lt_save_CC"
-])# _LT_LANG_C_CONFIG
-
-
-# _LT_LANG_CXX_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for a C++ compiler are suitably
-# defined.  These variables are subsequently used by _LT_CONFIG to write
-# the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_CXX_CONFIG],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-m4_require([_LT_DECL_EGREP])dnl
-m4_require([_LT_PATH_MANIFEST_TOOL])dnl
-if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
-    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-    (test "X$CXX" != "Xg++"))) ; then
-  AC_PROG_CXXCPP
-else
-  _lt_caught_CXX_error=yes
-fi
-
-AC_LANG_PUSH(C++)
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(compiler_needs_object, $1)=no
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_LT_TAGVAR(hardcode_direct_absolute, $1)=no
-_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_separator, $1)=
-_LT_TAGVAR(hardcode_minus_L, $1)=no
-_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for C++ test sources.
-ac_ext=cpp
-
-# Object file extension for compiled C++ test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the CXX compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_caught_CXX_error" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="int some_variable = 0;"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
-
-  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
-  _LT_TAG_COMPILER
-
-  # save warnings/boilerplate of simple test code
-  _LT_COMPILER_BOILERPLATE
-  _LT_LINKER_BOILERPLATE
-
-  # Allow CC to be a program name with arguments.
-  lt_save_CC=$CC
-  lt_save_CFLAGS=$CFLAGS
-  lt_save_LD=$LD
-  lt_save_GCC=$GCC
-  GCC=$GXX
-  lt_save_with_gnu_ld=$with_gnu_ld
-  lt_save_path_LD=$lt_cv_path_LD
-  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
-    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
-  else
-    $as_unset lt_cv_prog_gnu_ld
-  fi
-  if test -n "${lt_cv_path_LDCXX+set}"; then
-    lt_cv_path_LD=$lt_cv_path_LDCXX
-  else
-    $as_unset lt_cv_path_LD
-  fi
-  test -z "${LDCXX+set}" || LD=$LDCXX
-  CC=${CXX-"c++"}
-  CFLAGS=$CXXFLAGS
-  compiler=$CC
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-
-  if test -n "$compiler"; then
-    # We don't want -fno-exception when compiling C++ code, so set the
-    # no_builtin_flag separately
-    if test "$GXX" = yes; then
-      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
-    else
-      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
-    fi
-
-    if test "$GXX" = yes; then
-      # Set up default GNU C++ configuration
-
-      LT_PATH_LD
-
-      # Check if GNU C++ uses GNU ld as the underlying linker, since the
-      # archiving commands below assume that GNU ld is being used.
-      if test "$with_gnu_ld" = yes; then
-        _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-
-        # If archive_cmds runs LD, not CC, wlarc should be empty
-        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
-        #     investigate it a little bit more. (MM)
-        wlarc='${wl}'
-
-        # ancient GNU ld didn't support --whole-archive et. al.
-        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
-	  $GREP 'no-whole-archive' > /dev/null; then
-          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-        else
-          _LT_TAGVAR(whole_archive_flag_spec, $1)=
-        fi
-      else
-        with_gnu_ld=no
-        wlarc=
-
-        # A generic and very simple default shared library creation
-        # command for GNU C++ for the case where it uses the native
-        # linker, instead of GNU ld.  If possible, this setting should
-        # overridden to take advantage of the native linker features on
-        # the platform it is being used on.
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-      fi
-
-      # Commands to make compiler produce verbose output that lists
-      # what "hidden" libraries, object files and flags are used when
-      # linking a shared library.
-      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-
-    else
-      GXX=no
-      with_gnu_ld=no
-      wlarc=
-    fi
-
-    # PORTME: fill in a description of your system's C++ link characteristics
-    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
-    _LT_TAGVAR(ld_shlibs, $1)=yes
-    case $host_os in
-      aix3*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-      aix[[4-9]]*)
-        if test "$host_cpu" = ia64; then
-          # On IA64, the linker does run time linking by default, so we don't
-          # have to do anything special.
-          aix_use_runtimelinking=no
-          exp_sym_flag='-Bexport'
-          no_entry_flag=""
-        else
-          aix_use_runtimelinking=no
-
-          # Test if we are trying to use run time linking or normal
-          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
-          # need to do runtime linking.
-          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
-	    for ld_flag in $LDFLAGS; do
-	      case $ld_flag in
-	      *-brtl*)
-	        aix_use_runtimelinking=yes
-	        break
-	        ;;
-	      esac
-	    done
-	    ;;
-          esac
-
-          exp_sym_flag='-bexport'
-          no_entry_flag='-bnoentry'
-        fi
-
-        # When large executables or shared objects are built, AIX ld can
-        # have problems creating the table of contents.  If linking a library
-        # or program results in "error TOC overflow" add -mminimal-toc to
-        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-        _LT_TAGVAR(archive_cmds, $1)=''
-        _LT_TAGVAR(hardcode_direct, $1)=yes
-        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-        _LT_TAGVAR(link_all_deplibs, $1)=yes
-        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
-
-        if test "$GXX" = yes; then
-          case $host_os in aix4.[[012]]|aix4.[[012]].*)
-          # We only want to do this on AIX 4.2 and lower, the check
-          # below for broken collect2 doesn't work under 4.3+
-	  collect2name=`${CC} -print-prog-name=collect2`
-	  if test -f "$collect2name" &&
-	     strings "$collect2name" | $GREP resolve_lib_name >/dev/null
-	  then
-	    # We have reworked collect2
-	    :
-	  else
-	    # We have old collect2
-	    _LT_TAGVAR(hardcode_direct, $1)=unsupported
-	    # It fails to find uninstalled libraries when the uninstalled
-	    # path is not listed in the libpath.  Setting hardcode_minus_L
-	    # to unsupported forces relinking
-	    _LT_TAGVAR(hardcode_minus_L, $1)=yes
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=
-	  fi
-          esac
-          shared_flag='-shared'
-	  if test "$aix_use_runtimelinking" = yes; then
-	    shared_flag="$shared_flag "'${wl}-G'
-	  fi
-        else
-          # not using gcc
-          if test "$host_cpu" = ia64; then
-	  # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	  # chokes on -Wl,-G. The following line is correct:
-	  shared_flag='-G'
-          else
-	    if test "$aix_use_runtimelinking" = yes; then
-	      shared_flag='${wl}-G'
-	    else
-	      shared_flag='${wl}-bM:SRE'
-	    fi
-          fi
-        fi
-
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
-        # It seems that -bexpall does not export symbols beginning with
-        # underscore (_), so it is better to generate a list of symbols to
-	# export.
-        _LT_TAGVAR(always_export_symbols, $1)=yes
-        if test "$aix_use_runtimelinking" = yes; then
-          # Warning - without using the other runtime loading flags (-brtl),
-          # -berok will link without error, but may produce a broken library.
-          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
-          # Determine the default libpath from the value encoded in an empty
-          # executable.
-          _LT_SYS_MODULE_PATH_AIX([$1])
-          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-
-          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-        else
-          if test "$host_cpu" = ia64; then
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
-	    _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-          else
-	    # Determine the default libpath from the value encoded in an
-	    # empty executable.
-	    _LT_SYS_MODULE_PATH_AIX([$1])
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
-	    # Warning - without using the other run time loading flags,
-	    # -berok will link without error, but may produce a broken library.
-	    _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
-	    _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
-	    if test "$with_gnu_ld" = yes; then
-	      # We only use this code for GNU lds that support --whole-archive.
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	    else
-	      # Exported symbols can be pulled into shared objects from archives
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
-	    fi
-	    _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
-	    # This is similar to how AIX traditionally builds its shared
-	    # libraries.
-	    _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
-          fi
-        fi
-        ;;
-
-      beos*)
-	if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
-	  # support --undefined.  This deserves some investigation.  FIXME
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	else
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	fi
-	;;
-
-      chorus*)
-        case $cc_basename in
-          *)
-	  # FIXME: insert proper C++ library support
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	  ;;
-        esac
-        ;;
-
-      cygwin* | mingw* | pw32* | cegcc*)
-	case $GXX,$cc_basename in
-	,cl* | no,cl*)
-	  # Native MSVC
-	  # hardcode_libdir_flag_spec is actually meaningless, as there is
-	  # no search path for DLLs.
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  _LT_TAGVAR(always_export_symbols, $1)=yes
-	  _LT_TAGVAR(file_list_spec, $1)='@'
-	  # Tell ltmain to make .lib files, not .a files.
-	  libext=lib
-	  # Tell ltmain to make .dll files, not .so files.
-	  shrext_cmds=".dll"
-	  # FIXME: Setting linknames here is a bad hack.
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames='
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	      $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp;
-	    else
-	      $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp;
-	    fi~
-	    $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~
-	    linknames='
-	  # The linker will not automatically build a static lib if we build a DLL.
-	  # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
-	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-	  # Don't use ranlib
-	  _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib'
-	  _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~
-	    lt_tool_outputfile="@TOOL_OUTPUT@"~
-	    case $lt_outputfile in
-	      *.exe|*.EXE) ;;
-	      *)
-		lt_outputfile="$lt_outputfile.exe"
-		lt_tool_outputfile="$lt_tool_outputfile.exe"
-		;;
-	    esac~
-	    func_to_tool_file "$lt_outputfile"~
-	    if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then
-	      $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1;
-	      $RM "$lt_outputfile.manifest";
-	    fi'
-	  ;;
-	*)
-	  # g++
-	  # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
-	  # as there is no search path for DLLs.
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
-	  _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols'
-	  _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
-	  _LT_TAGVAR(always_export_symbols, $1)=no
-	  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
-
-	  if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	    # If the export-symbols file already is a .def file (1st line
-	    # is EXPORTS), use it as is; otherwise, prepend...
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
-	      cp $export_symbols $output_objdir/$soname.def;
-	    else
-	      echo EXPORTS > $output_objdir/$soname.def;
-	      cat $export_symbols >> $output_objdir/$soname.def;
-	    fi~
-	    $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-	  else
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	  fi
-	  ;;
-	esac
-	;;
-      darwin* | rhapsody*)
-        _LT_DARWIN_LINKER_FEATURES($1)
-	;;
-
-      dgux*)
-        case $cc_basename in
-          ec++*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          ghcx*)
-	    # Green Hills C++ Compiler
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      freebsd2.*)
-        # C++ shared libraries reported to be fairly broken before
-	# switch to ELF
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      freebsd-elf*)
-        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-        ;;
-
-      freebsd* | dragonfly*)
-        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
-        # conventions
-        _LT_TAGVAR(ld_shlibs, $1)=yes
-        ;;
-
-      haiku*)
-        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-        _LT_TAGVAR(link_all_deplibs, $1)=yes
-        ;;
-
-      hpux9*)
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-        _LT_TAGVAR(hardcode_direct, $1)=yes
-        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
-				             # but as the default
-				             # location of the library.
-
-        case $cc_basename in
-          CC*)
-            # FIXME: insert proper C++ library support
-            _LT_TAGVAR(ld_shlibs, $1)=no
-            ;;
-          aCC*)
-            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-            # Commands to make compiler produce verbose output that lists
-            # what "hidden" libraries, object files and flags are used when
-            # linking a shared library.
-            #
-            # There doesn't appear to be a way to prevent this compiler from
-            # explicitly linking system object files so we need to strip them
-            # from the output so that they don't get included in the library
-            # dependencies.
-            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-            ;;
-          *)
-            if test "$GXX" = yes; then
-              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
-            else
-              # FIXME: insert proper C++ library support
-              _LT_TAGVAR(ld_shlibs, $1)=no
-            fi
-            ;;
-        esac
-        ;;
-
-      hpux10*|hpux11*)
-        if test $with_gnu_ld = no; then
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
-	  _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-          case $host_cpu in
-            hppa*64*|ia64*)
-              ;;
-            *)
-	      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-              ;;
-          esac
-        fi
-        case $host_cpu in
-          hppa*64*|ia64*)
-            _LT_TAGVAR(hardcode_direct, $1)=no
-            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-            ;;
-          *)
-            _LT_TAGVAR(hardcode_direct, $1)=yes
-            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
-					         # but as the default
-					         # location of the library.
-            ;;
-        esac
-
-        case $cc_basename in
-          CC*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          aCC*)
-	    case $host_cpu in
-	      hppa*64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	      ia64*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	      *)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	        ;;
-	    esac
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-	    ;;
-          *)
-	    if test "$GXX" = yes; then
-	      if test $with_gnu_ld = no; then
-	        case $host_cpu in
-	          hppa*64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	          ia64*)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	          *)
-	            _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	            ;;
-	        esac
-	      fi
-	    else
-	      # FIXME: insert proper C++ library support
-	      _LT_TAGVAR(ld_shlibs, $1)=no
-	    fi
-	    ;;
-        esac
-        ;;
-
-      interix[[3-9]]*)
-	_LT_TAGVAR(hardcode_direct, $1)=no
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	# Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-	# Instead, shared libraries are loaded at an image base (0x10000000 by
-	# default) and relocated if they conflict, which is a slow very memory
-	# consuming and fragmenting process.  To avoid this, we pick a random,
-	# 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-	# time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-	_LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	_LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-	;;
-      irix5* | irix6*)
-        case $cc_basename in
-          CC*)
-	    # SGI C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
-	    # necessary to make sure instantiated templates are included
-	    # in the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
-	    ;;
-          *)
-	    if test "$GXX" = yes; then
-	      if test "$with_gnu_ld" = no; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	      else
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib'
-	      fi
-	    fi
-	    _LT_TAGVAR(link_all_deplibs, $1)=yes
-	    ;;
-        esac
-        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-        _LT_TAGVAR(inherit_rpath, $1)=yes
-        ;;
-
-      linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*)
-        case $cc_basename in
-          KCC*)
-	    # Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	    # KCC will only create a shared library if the output file
-	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
-	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
-	    ;;
-	  icpc* | ecpc* )
-	    # Intel C++
-	    with_gnu_ld=yes
-	    # version 8.0 and above of icpc choke on multiply defined symbols
-	    # if we add $predep_objects and $postdep_objects, however 7.1 and
-	    # earlier do not add the objects themselves.
-	    case `$CC -V 2>&1` in
-	      *"Version 7."*)
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-		;;
-	      *)  # Version 8.0 or newer
-	        tmp_idyn=
-	        case $host_cpu in
-		  ia64*) tmp_idyn=' -i_dynamic';;
-		esac
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-		_LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-		;;
-	    esac
-	    _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
-	    ;;
-          pgCC* | pgcpp*)
-            # Portland Group C++ compiler
-	    case `$CC -V` in
-	    *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*)
-	      _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
-		compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"'
-	      _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
-		$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~
-		$RANLIB $oldlib'
-	      _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
-		rm -rf $tpldir~
-		$CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
-		$CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
-	      ;;
-	    *) # Version 6 and above use weak symbols
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
-	      ;;
-	    esac
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-            ;;
-	  cxx*)
-	    # Compaq C++
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
-
-	    runpath_var=LD_RUN_PATH
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed'
-	    ;;
-	  xl* | mpixl* | bgxl*)
-	    # IBM XL 8.0 on PPC, with GNU ld
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	    if test "x$supports_anon_versioning" = xyes; then
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
-		cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
-		echo "local: *; };" >> $output_objdir/$libname.ver~
-		$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
-	    fi
-	    ;;
-	  *)
-	    case `$CC -V 2>&1 | sed 5q` in
-	    *Sun\ C*)
-	      # Sun C++ 5.9
-	      _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	      _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	      _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	      _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
-	      _LT_TAGVAR(compiler_needs_object, $1)=yes
-
-	      # Not sure whether something based on
-	      # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
-	      # would be better.
-	      output_verbose_link_cmd='func_echo_all'
-
-	      # Archives containing C++ object files must be created using
-	      # "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	      # necessary to make sure instantiated templates are included
-	      # in the archive.
-	      _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
-	      ;;
-	    esac
-	    ;;
-	esac
-	;;
-
-      lynxos*)
-        # FIXME: insert proper C++ library support
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      m88k*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      mvs*)
-        case $cc_basename in
-          cxx*)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-	  *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-	esac
-	;;
-
-      netbsd*)
-        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
-	  _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
-	  wlarc=
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	fi
-	# Workaround some broken pre-1.5 toolchains
-	output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
-	;;
-
-      *nto* | *qnx*)
-        _LT_TAGVAR(ld_shlibs, $1)=yes
-	;;
-
-      openbsd2*)
-        # C++ shared libraries are fairly broken
-	_LT_TAGVAR(ld_shlibs, $1)=no
-	;;
-
-      openbsd*)
-	if test -f /usr/libexec/ld.so; then
-	  _LT_TAGVAR(hardcode_direct, $1)=yes
-	  _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	  _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-	  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
-	    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
-	    _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
-	  fi
-	  output_verbose_link_cmd=func_echo_all
-	else
-	  _LT_TAGVAR(ld_shlibs, $1)=no
-	fi
-	;;
-
-      osf3* | osf4* | osf5*)
-        case $cc_basename in
-          KCC*)
-	    # Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	    # KCC will only create a shared library if the output file
-	    # ends with ".so" (or ".sl" for HP-UX), so rename the library
-	    # to its proper name (with version) after linking.
-	    _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Archives containing C++ object files must be created using
-	    # the KAI C++ compiler.
-	    case $host in
-	      osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
-	      *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
-	    esac
-	    ;;
-          RCC*)
-	    # Rational C++ 2.4.1
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          cxx*)
-	    case $host in
-	      osf3*)
-	        _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-		;;
-	      *)
-	        _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
-	        _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
-	          echo "-hidden">> $lib.exp~
-	          $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~
-	          $RM $lib.exp'
-	        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
-		;;
-	    esac
-
-	    _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    #
-	    # There doesn't appear to be a way to prevent this compiler from
-	    # explicitly linking system object files so we need to strip them
-	    # from the output so that they don't get included in the library
-	    # dependencies.
-	    output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"'
-	    ;;
-	  *)
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
-	      case $host in
-	        osf3*)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-		  ;;
-	        *)
-	          _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-		  ;;
-	      esac
-
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
-	      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
-
-	      # Commands to make compiler produce verbose output that lists
-	      # what "hidden" libraries, object files and flags are used when
-	      # linking a shared library.
-	      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-
-	    else
-	      # FIXME: insert proper C++ library support
-	      _LT_TAGVAR(ld_shlibs, $1)=no
-	    fi
-	    ;;
-        esac
-        ;;
-
-      psos*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      sunos4*)
-        case $cc_basename in
-          CC*)
-	    # Sun C++ 4.x
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          lcc*)
-	    # Lucid
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      solaris*)
-        case $cc_basename in
-          CC* | sunCC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
-	    _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-	      $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
-	    _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	    case $host_os in
-	      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-	      *)
-		# The compiler driver will combine and reorder linker options,
-		# but understands `-z linker_flag'.
-	        # Supported since Solaris 2.6 (maybe 2.5.1?)
-		_LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
-	        ;;
-	    esac
-	    _LT_TAGVAR(link_all_deplibs, $1)=yes
-
-	    output_verbose_link_cmd='func_echo_all'
-
-	    # Archives containing C++ object files must be created using
-	    # "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	    # necessary to make sure instantiated templates are included
-	    # in the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
-	    ;;
-          gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-
-	    # The C++ compiler must be used to create the archive.
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
-	    ;;
-          *)
-	    # GNU C++ compiler with Solaris linker
-	    if test "$GXX" = yes && test "$with_gnu_ld" = no; then
-	      _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
-	      if $CC --version | $GREP -v '^2\.7' > /dev/null; then
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	        # Commands to make compiler produce verbose output that lists
-	        # what "hidden" libraries, object files and flags are used when
-	        # linking a shared library.
-	        output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-	      else
-	        # g++ 2.7 appears to require `-G' NOT `-shared' on this
-	        # platform.
-	        _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-	        _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
-		  $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
-
-	        # Commands to make compiler produce verbose output that lists
-	        # what "hidden" libraries, object files and flags are used when
-	        # linking a shared library.
-	        output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"'
-	      fi
-
-	      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
-	      case $host_os in
-		solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-		*)
-		  _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
-		  ;;
-	      esac
-	    fi
-	    ;;
-        esac
-        ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
-      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
-      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-      runpath_var='LD_RUN_PATH'
-
-      case $cc_basename in
-        CC*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-      esac
-      ;;
-
-      sysv5* | sco3.2v5* | sco5v6*)
-	# Note: We can NOT use -z defs as we might desire, because we do not
-	# link with -lc, and that would cause any symbols used from libc to
-	# always be unresolved, which means just about no library would
-	# ever link correctly.  If we're not using GNU ld we use -z text
-	# though, which does catch some bad symbols but isn't as heavy-handed
-	# as -z defs.
-	_LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
-	_LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
-	_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-	_LT_TAGVAR(hardcode_shlibpath_var, $1)=no
-	_LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
-	_LT_TAGVAR(hardcode_libdir_separator, $1)=':'
-	_LT_TAGVAR(link_all_deplibs, $1)=yes
-	_LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
-	runpath_var='LD_RUN_PATH'
-
-	case $cc_basename in
-          CC*)
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~
-	      '"$_LT_TAGVAR(old_archive_cmds, $1)"
-	    _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~
-	      '"$_LT_TAGVAR(reload_cmds, $1)"
-	    ;;
-	  *)
-	    _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	    ;;
-	esac
-      ;;
-
-      tandem*)
-        case $cc_basename in
-          NCC*)
-	    # NonStop-UX NCC 3.20
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-          *)
-	    # FIXME: insert proper C++ library support
-	    _LT_TAGVAR(ld_shlibs, $1)=no
-	    ;;
-        esac
-        ;;
-
-      vxworks*)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-
-      *)
-        # FIXME: insert proper C++ library support
-        _LT_TAGVAR(ld_shlibs, $1)=no
-        ;;
-    esac
-
-    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
-    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
-
-    _LT_TAGVAR(GCC, $1)="$GXX"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## CAVEAT EMPTOR:
-    ## There is no encapsulation within the following macros, do not change
-    ## the running order or otherwise move them around unless you know exactly
-    ## what you are doing...
-    _LT_SYS_HIDDEN_LIBDEPS($1)
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  CC=$lt_save_CC
-  CFLAGS=$lt_save_CFLAGS
-  LDCXX=$LD
-  LD=$lt_save_LD
-  GCC=$lt_save_GCC
-  with_gnu_ld=$lt_save_with_gnu_ld
-  lt_cv_path_LDCXX=$lt_cv_path_LD
-  lt_cv_path_LD=$lt_save_path_LD
-  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
-  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
-fi # test "$_lt_caught_CXX_error" != yes
-
-AC_LANG_POP
-])# _LT_LANG_CXX_CONFIG
-
-
-# _LT_FUNC_STRIPNAME_CNF
-# ----------------------
-# func_stripname_cnf prefix suffix name
-# strip PREFIX and SUFFIX off of NAME.
-# PREFIX and SUFFIX must not contain globbing or regex special
-# characters, hashes, percent signs, but SUFFIX may contain a leading
-# dot (in which case that matches only a dot).
-#
-# This function is identical to the (non-XSI) version of func_stripname,
-# except this one can be used by m4 code that may be executed by configure,
-# rather than the libtool script.
-m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl
-AC_REQUIRE([_LT_DECL_SED])
-AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])
-func_stripname_cnf ()
-{
-  case ${2} in
-  .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;;
-  *)  func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;;
-  esac
-} # func_stripname_cnf
-])# _LT_FUNC_STRIPNAME_CNF
-
-# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
-# ---------------------------------
-# Figure out "hidden" library dependencies from verbose
-# compiler output when linking a shared library.
-# Parse the compiler output and extract the necessary
-# objects, libraries and library flags.
-m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
-[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
-AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl
-# Dependencies to place before and after the object being linked:
-_LT_TAGVAR(predep_objects, $1)=
-_LT_TAGVAR(postdep_objects, $1)=
-_LT_TAGVAR(predeps, $1)=
-_LT_TAGVAR(postdeps, $1)=
-_LT_TAGVAR(compiler_lib_search_path, $1)=
-
-dnl we can't use the lt_simple_compile_test_code here,
-dnl because it contains code intended for an executable,
-dnl not a library.  It's possible we should let each
-dnl tag define a new lt_????_link_test_code variable,
-dnl but it's only used here...
-m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
-int a;
-void foo (void) { a = 0; }
-_LT_EOF
-], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
-class Foo
-{
-public:
-  Foo (void) { a = 0; }
-private:
-  int a;
-};
-_LT_EOF
-], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
-      subroutine foo
-      implicit none
-      integer*4 a
-      a=0
-      return
-      end
-_LT_EOF
-], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
-      subroutine foo
-      implicit none
-      integer a
-      a=0
-      return
-      end
-_LT_EOF
-], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
-public class foo {
-  private int a;
-  public void bar (void) {
-    a = 0;
-  }
-};
-_LT_EOF
-], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF
-package foo
-func foo() {
-}
-_LT_EOF
-])
-
-_lt_libdeps_save_CFLAGS=$CFLAGS
-case "$CC $CFLAGS " in #(
-*\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;;
-*\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;;
-*\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;;
-esac
-
-dnl Parse the compiler output and extract the necessary
-dnl objects, libraries and library flags.
-if AC_TRY_EVAL(ac_compile); then
-  # Parse the compiler output and extract the necessary
-  # objects, libraries and library flags.
-
-  # Sentinel used to keep track of whether or not we are before
-  # the conftest object file.
-  pre_test_object_deps_done=no
-
-  for p in `eval "$output_verbose_link_cmd"`; do
-    case ${prev}${p} in
-
-    -L* | -R* | -l*)
-       # Some compilers place space between "-{L,R}" and the path.
-       # Remove the space.
-       if test $p = "-L" ||
-          test $p = "-R"; then
-	 prev=$p
-	 continue
-       fi
-
-       # Expand the sysroot to ease extracting the directories later.
-       if test -z "$prev"; then
-         case $p in
-         -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;;
-         -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;;
-         -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;;
-         esac
-       fi
-       case $p in
-       =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;;
-       esac
-       if test "$pre_test_object_deps_done" = no; then
-	 case ${prev} in
-	 -L | -R)
-	   # Internal compiler library paths should come after those
-	   # provided the user.  The postdeps already come after the
-	   # user supplied libs so there is no need to process them.
-	   if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
-	   else
-	     _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
-	   fi
-	   ;;
-	 # The "-l" case would never come before the object being
-	 # linked, so don't bother handling this case.
-	 esac
-       else
-	 if test -z "$_LT_TAGVAR(postdeps, $1)"; then
-	   _LT_TAGVAR(postdeps, $1)="${prev}${p}"
-	 else
-	   _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
-	 fi
-       fi
-       prev=
-       ;;
-
-    *.lto.$objext) ;; # Ignore GCC LTO objects
-    *.$objext)
-       # This assumes that the test object file only shows up
-       # once in the compiler output.
-       if test "$p" = "conftest.$objext"; then
-	 pre_test_object_deps_done=yes
-	 continue
-       fi
-
-       if test "$pre_test_object_deps_done" = no; then
-	 if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
-	   _LT_TAGVAR(predep_objects, $1)="$p"
-	 else
-	   _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
-	 fi
-       else
-	 if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
-	   _LT_TAGVAR(postdep_objects, $1)="$p"
-	 else
-	   _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
-	 fi
-       fi
-       ;;
-
-    *) ;; # Ignore the rest.
-
-    esac
-  done
-
-  # Clean up.
-  rm -f a.out a.exe
-else
-  echo "libtool.m4: error: problem compiling $1 test program"
-fi
-
-$RM -f confest.$objext
-CFLAGS=$_lt_libdeps_save_CFLAGS
-
-# PORTME: override above test on systems where it is broken
-m4_if([$1], [CXX],
-[case $host_os in
-interix[[3-9]]*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  _LT_TAGVAR(predep_objects,$1)=
-  _LT_TAGVAR(postdep_objects,$1)=
-  _LT_TAGVAR(postdeps,$1)=
-  ;;
-
-linux*)
-  case `$CC -V 2>&1 | sed 5q` in
-  *Sun\ C*)
-    # Sun C++ 5.9
-
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC* | sunCC*)
-    # The more standards-conforming stlport4 library is
-    # incompatible with the Cstd library. Avoid specifying
-    # it if it's in CXXFLAGS. Ignore libCrun as
-    # -library=stlport4 depends on it.
-    case " $CXX $CXXFLAGS " in
-    *" -library=stlport4 "*)
-      solaris_use_stlport4=yes
-      ;;
-    esac
-
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    if test "$solaris_use_stlport4" != yes; then
-      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
-    fi
-    ;;
-  esac
-  ;;
-esac
-])
-
-case " $_LT_TAGVAR(postdeps, $1) " in
-*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
-esac
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=
-if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
- _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
-fi
-_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
-    [The directories searched by this compiler when creating a shared library])
-_LT_TAGDECL([], [predep_objects], [1],
-    [Dependencies to place before and after the objects being linked to
-    create a shared library])
-_LT_TAGDECL([], [postdep_objects], [1])
-_LT_TAGDECL([], [predeps], [1])
-_LT_TAGDECL([], [postdeps], [1])
-_LT_TAGDECL([], [compiler_lib_search_path], [1],
-    [The library search path used internally by the compiler when linking
-    a shared library])
-])# _LT_SYS_HIDDEN_LIBDEPS
-
-
-# _LT_LANG_F77_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for a Fortran 77 compiler are
-# suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_F77_CONFIG],
-[AC_LANG_PUSH(Fortran 77)
-if test -z "$F77" || test "X$F77" = "Xno"; then
-  _lt_disable_F77=yes
-fi
-
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_LT_TAGVAR(hardcode_direct_absolute, $1)=no
-_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_separator, $1)=
-_LT_TAGVAR(hardcode_minus_L, $1)=no
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for f77 test sources.
-ac_ext=f
-
-# Object file extension for compiled f77 test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the F77 compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_F77" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="\
-      subroutine t
-      return
-      end
-"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code="\
-      program t
-      end
-"
-
-  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
-  _LT_TAG_COMPILER
-
-  # save warnings/boilerplate of simple test code
-  _LT_COMPILER_BOILERPLATE
-  _LT_LINKER_BOILERPLATE
-
-  # Allow CC to be a program name with arguments.
-  lt_save_CC="$CC"
-  lt_save_GCC=$GCC
-  lt_save_CFLAGS=$CFLAGS
-  CC=${F77-"f77"}
-  CFLAGS=$FFLAGS
-  compiler=$CC
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-  GCC=$G77
-  if test -n "$compiler"; then
-    AC_MSG_CHECKING([if libtool supports shared libraries])
-    AC_MSG_RESULT([$can_build_shared])
-
-    AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
-
-    # On AIX, shared libraries and static libraries use the same namespace, and
-    # are all built from PIC.
-    case $host_os in
-      aix3*)
-        test "$enable_shared" = yes && enable_static=no
-        if test -n "$RANLIB"; then
-          archive_cmds="$archive_cmds~\$RANLIB \$lib"
-          postinstall_cmds='$RANLIB $lib'
-        fi
-        ;;
-      aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
-	fi
-        ;;
-    esac
-    AC_MSG_RESULT([$enable_shared])
-
-    AC_MSG_CHECKING([whether to build static libraries])
-    # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
-    AC_MSG_RESULT([$enable_static])
-
-    _LT_TAGVAR(GCC, $1)="$G77"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## CAVEAT EMPTOR:
-    ## There is no encapsulation within the following macros, do not change
-    ## the running order or otherwise move them around unless you know exactly
-    ## what you are doing...
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  GCC=$lt_save_GCC
-  CC="$lt_save_CC"
-  CFLAGS="$lt_save_CFLAGS"
-fi # test "$_lt_disable_F77" != yes
-
-AC_LANG_POP
-])# _LT_LANG_F77_CONFIG
-
-
-# _LT_LANG_FC_CONFIG([TAG])
-# -------------------------
-# Ensure that the configuration variables for a Fortran compiler are
-# suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_FC_CONFIG],
-[AC_LANG_PUSH(Fortran)
-
-if test -z "$FC" || test "X$FC" = "Xno"; then
-  _lt_disable_FC=yes
-fi
-
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-_LT_TAGVAR(allow_undefined_flag, $1)=
-_LT_TAGVAR(always_export_symbols, $1)=no
-_LT_TAGVAR(archive_expsym_cmds, $1)=
-_LT_TAGVAR(export_dynamic_flag_spec, $1)=
-_LT_TAGVAR(hardcode_direct, $1)=no
-_LT_TAGVAR(hardcode_direct_absolute, $1)=no
-_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
-_LT_TAGVAR(hardcode_libdir_separator, $1)=
-_LT_TAGVAR(hardcode_minus_L, $1)=no
-_LT_TAGVAR(hardcode_automatic, $1)=no
-_LT_TAGVAR(inherit_rpath, $1)=no
-_LT_TAGVAR(module_cmds, $1)=
-_LT_TAGVAR(module_expsym_cmds, $1)=
-_LT_TAGVAR(link_all_deplibs, $1)=unknown
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-_LT_TAGVAR(no_undefined_flag, $1)=
-_LT_TAGVAR(whole_archive_flag_spec, $1)=
-_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
-
-# Source file extension for fc test sources.
-ac_ext=${ac_fc_srcext-f}
-
-# Object file extension for compiled fc test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# No sense in running all these tests if we already determined that
-# the FC compiler isn't working.  Some variables (like enable_shared)
-# are currently assumed to apply to all compilers on this platform,
-# and will be corrupted by setting them based on a non-working compiler.
-if test "$_lt_disable_FC" != yes; then
-  # Code to be used in simple compile tests
-  lt_simple_compile_test_code="\
-      subroutine t
-      return
-      end
-"
-
-  # Code to be used in simple link tests
-  lt_simple_link_test_code="\
-      program t
-      end
-"
-
-  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
-  _LT_TAG_COMPILER
-
-  # save warnings/boilerplate of simple test code
-  _LT_COMPILER_BOILERPLATE
-  _LT_LINKER_BOILERPLATE
-
-  # Allow CC to be a program name with arguments.
-  lt_save_CC="$CC"
-  lt_save_GCC=$GCC
-  lt_save_CFLAGS=$CFLAGS
-  CC=${FC-"f95"}
-  CFLAGS=$FCFLAGS
-  compiler=$CC
-  GCC=$ac_cv_fc_compiler_gnu
-
-  _LT_TAGVAR(compiler, $1)=$CC
-  _LT_CC_BASENAME([$compiler])
-
-  if test -n "$compiler"; then
-    AC_MSG_CHECKING([if libtool supports shared libraries])
-    AC_MSG_RESULT([$can_build_shared])
-
-    AC_MSG_CHECKING([whether to build shared libraries])
-    test "$can_build_shared" = "no" && enable_shared=no
-
-    # On AIX, shared libraries and static libraries use the same namespace, and
-    # are all built from PIC.
-    case $host_os in
-      aix3*)
-        test "$enable_shared" = yes && enable_static=no
-        if test -n "$RANLIB"; then
-          archive_cmds="$archive_cmds~\$RANLIB \$lib"
-          postinstall_cmds='$RANLIB $lib'
-        fi
-        ;;
-      aix[[4-9]]*)
-	if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
-	  test "$enable_shared" = yes && enable_static=no
-	fi
-        ;;
-    esac
-    AC_MSG_RESULT([$enable_shared])
-
-    AC_MSG_CHECKING([whether to build static libraries])
-    # Make sure either enable_shared or enable_static is yes.
-    test "$enable_shared" = yes || enable_static=yes
-    AC_MSG_RESULT([$enable_static])
-
-    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
-    _LT_TAGVAR(LD, $1)="$LD"
-
-    ## CAVEAT EMPTOR:
-    ## There is no encapsulation within the following macros, do not change
-    ## the running order or otherwise move them around unless you know exactly
-    ## what you are doing...
-    _LT_SYS_HIDDEN_LIBDEPS($1)
-    _LT_COMPILER_PIC($1)
-    _LT_COMPILER_C_O($1)
-    _LT_COMPILER_FILE_LOCKS($1)
-    _LT_LINKER_SHLIBS($1)
-    _LT_SYS_DYNAMIC_LINKER($1)
-    _LT_LINKER_HARDCODE_LIBPATH($1)
-
-    _LT_CONFIG($1)
-  fi # test -n "$compiler"
-
-  GCC=$lt_save_GCC
-  CC=$lt_save_CC
-  CFLAGS=$lt_save_CFLAGS
-fi # test "$_lt_disable_FC" != yes
-
-AC_LANG_POP
-])# _LT_LANG_FC_CONFIG
-
-
-# _LT_LANG_GCJ_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for the GNU Java Compiler compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_GCJ_CONFIG],
-[AC_REQUIRE([LT_PROG_GCJ])dnl
-AC_LANG_SAVE
-
-# Source file extension for Java test sources.
-ac_ext=java
-
-# Object file extension for compiled Java test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="class foo {}"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_TAG_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=$CC
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=yes
-CC=${GCJ-"gcj"}
-CFLAGS=$GCJFLAGS
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
-_LT_CC_BASENAME([$compiler])
-
-# GCJ did not exist at the time GCC didn't implicitly link libc in.
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-  _LT_COMPILER_NO_RTTI($1)
-  _LT_COMPILER_PIC($1)
-  _LT_COMPILER_C_O($1)
-  _LT_COMPILER_FILE_LOCKS($1)
-  _LT_LINKER_SHLIBS($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-
-  _LT_CONFIG($1)
-fi
-
-AC_LANG_RESTORE
-
-GCC=$lt_save_GCC
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-])# _LT_LANG_GCJ_CONFIG
-
-
-# _LT_LANG_GO_CONFIG([TAG])
-# --------------------------
-# Ensure that the configuration variables for the GNU Go compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_GO_CONFIG],
-[AC_REQUIRE([LT_PROG_GO])dnl
-AC_LANG_SAVE
-
-# Source file extension for Go test sources.
-ac_ext=go
-
-# Object file extension for compiled Go test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code="package main; func main() { }"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code='package main; func main() { }'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_TAG_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=$CC
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=yes
-CC=${GOC-"gccgo"}
-CFLAGS=$GOFLAGS
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_TAGVAR(LD, $1)="$LD"
-_LT_CC_BASENAME([$compiler])
-
-# Go did not exist at the time GCC didn't implicitly link libc in.
-_LT_TAGVAR(archive_cmds_need_lc, $1)=no
-
-_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
-_LT_TAGVAR(reload_flag, $1)=$reload_flag
-_LT_TAGVAR(reload_cmds, $1)=$reload_cmds
-
-## CAVEAT EMPTOR:
-## There is no encapsulation within the following macros, do not change
-## the running order or otherwise move them around unless you know exactly
-## what you are doing...
-if test -n "$compiler"; then
-  _LT_COMPILER_NO_RTTI($1)
-  _LT_COMPILER_PIC($1)
-  _LT_COMPILER_C_O($1)
-  _LT_COMPILER_FILE_LOCKS($1)
-  _LT_LINKER_SHLIBS($1)
-  _LT_LINKER_HARDCODE_LIBPATH($1)
-
-  _LT_CONFIG($1)
-fi
-
-AC_LANG_RESTORE
-
-GCC=$lt_save_GCC
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-])# _LT_LANG_GO_CONFIG
-
-
-# _LT_LANG_RC_CONFIG([TAG])
-# -------------------------
-# Ensure that the configuration variables for the Windows resource compiler
-# are suitably defined.  These variables are subsequently used by _LT_CONFIG
-# to write the compiler configuration to `libtool'.
-m4_defun([_LT_LANG_RC_CONFIG],
-[AC_REQUIRE([LT_PROG_RC])dnl
-AC_LANG_SAVE
-
-# Source file extension for RC test sources.
-ac_ext=rc
-
-# Object file extension for compiled RC test sources.
-objext=o
-_LT_TAGVAR(objext, $1)=$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
-
-# Code to be used in simple link tests
-lt_simple_link_test_code="$lt_simple_compile_test_code"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_TAG_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC="$CC"
-lt_save_CFLAGS=$CFLAGS
-lt_save_GCC=$GCC
-GCC=
-CC=${RC-"windres"}
-CFLAGS=
-compiler=$CC
-_LT_TAGVAR(compiler, $1)=$CC
-_LT_CC_BASENAME([$compiler])
-_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
-
-if test -n "$compiler"; then
-  :
-  _LT_CONFIG($1)
-fi
-
-GCC=$lt_save_GCC
-AC_LANG_RESTORE
-CC=$lt_save_CC
-CFLAGS=$lt_save_CFLAGS
-])# _LT_LANG_RC_CONFIG
-
-
-# LT_PROG_GCJ
-# -----------
-AC_DEFUN([LT_PROG_GCJ],
-[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
-  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
-    [AC_CHECK_TOOL(GCJ, gcj,)
-      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
-      AC_SUBST(GCJFLAGS)])])[]dnl
-])
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
-
-
-# LT_PROG_GO
-# ----------
-AC_DEFUN([LT_PROG_GO],
-[AC_CHECK_TOOL(GOC, gccgo,)
-])
-
-
-# LT_PROG_RC
-# ----------
-AC_DEFUN([LT_PROG_RC],
-[AC_CHECK_TOOL(RC, windres,)
-])
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_RC], [])
-
-
-# _LT_DECL_EGREP
-# --------------
-# If we don't have a new enough Autoconf to choose the best grep
-# available, choose the one first in the user's PATH.
-m4_defun([_LT_DECL_EGREP],
-[AC_REQUIRE([AC_PROG_EGREP])dnl
-AC_REQUIRE([AC_PROG_FGREP])dnl
-test -z "$GREP" && GREP=grep
-_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
-_LT_DECL([], [EGREP], [1], [An ERE matcher])
-_LT_DECL([], [FGREP], [1], [A literal string matcher])
-dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
-AC_SUBST([GREP])
-])
-
-
-# _LT_DECL_OBJDUMP
-# --------------
-# If we don't have a new enough Autoconf to choose the best objdump
-# available, choose the one first in the user's PATH.
-m4_defun([_LT_DECL_OBJDUMP],
-[AC_CHECK_TOOL(OBJDUMP, objdump, false)
-test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
-AC_SUBST([OBJDUMP])
-])
-
-# _LT_DECL_DLLTOOL
-# ----------------
-# Ensure DLLTOOL variable is set.
-m4_defun([_LT_DECL_DLLTOOL],
-[AC_CHECK_TOOL(DLLTOOL, dlltool, false)
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-_LT_DECL([], [DLLTOOL], [1], [DLL creation program])
-AC_SUBST([DLLTOOL])
-])
-
-# _LT_DECL_SED
-# ------------
-# Check for a fully-functional sed program, that truncates
-# as few characters as possible.  Prefer GNU sed if found.
-m4_defun([_LT_DECL_SED],
-[AC_PROG_SED
-test -z "$SED" && SED=sed
-Xsed="$SED -e 1s/^X//"
-_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
-_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
-    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
-])# _LT_DECL_SED
-
-m4_ifndef([AC_PROG_SED], [
-############################################################
-# NOTE: This macro has been submitted for inclusion into   #
-#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
-#  a released version of Autoconf we should remove this    #
-#  macro and use it instead.                               #
-############################################################
-
-m4_defun([AC_PROG_SED],
-[AC_MSG_CHECKING([for a sed that does not truncate output])
-AC_CACHE_VAL(lt_cv_path_SED,
-[# Loop through the user's path and test for sed and gsed.
-# Then use that list of sed's as ones to test for truncation.
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for lt_ac_prog in sed gsed; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
-        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
-      fi
-    done
-  done
-done
-IFS=$as_save_IFS
-lt_ac_max=0
-lt_ac_count=0
-# Add /usr/xpg4/bin/sed as it is typically found on Solaris
-# along with /bin/sed that truncates output.
-for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
-  test ! -f $lt_ac_sed && continue
-  cat /dev/null > conftest.in
-  lt_ac_count=0
-  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
-  # Check for GNU sed and select it if it is found.
-  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
-    lt_cv_path_SED=$lt_ac_sed
-    break
-  fi
-  while true; do
-    cat conftest.in conftest.in >conftest.tmp
-    mv conftest.tmp conftest.in
-    cp conftest.in conftest.nl
-    echo >>conftest.nl
-    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
-    cmp -s conftest.out conftest.nl || break
-    # 10000 chars as input seems more than enough
-    test $lt_ac_count -gt 10 && break
-    lt_ac_count=`expr $lt_ac_count + 1`
-    if test $lt_ac_count -gt $lt_ac_max; then
-      lt_ac_max=$lt_ac_count
-      lt_cv_path_SED=$lt_ac_sed
-    fi
-  done
-done
-])
-SED=$lt_cv_path_SED
-AC_SUBST([SED])
-AC_MSG_RESULT([$SED])
-])#AC_PROG_SED
-])#m4_ifndef
-
-# Old name:
-AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([LT_AC_PROG_SED], [])
-
-
-# _LT_CHECK_SHELL_FEATURES
-# ------------------------
-# Find out whether the shell is Bourne or XSI compatible,
-# or has some other useful features.
-m4_defun([_LT_CHECK_SHELL_FEATURES],
-[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
-# Try some XSI features
-xsi_shell=no
-( _lt_dummy="a/b/c"
-  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \
-      = c,a/b,b/c, \
-    && eval 'test $(( 1 + 1 )) -eq 2 \
-    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
-  && xsi_shell=yes
-AC_MSG_RESULT([$xsi_shell])
-_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
-
-AC_MSG_CHECKING([whether the shell understands "+="])
-lt_shell_append=no
-( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
-    >/dev/null 2>&1 \
-  && lt_shell_append=yes
-AC_MSG_RESULT([$lt_shell_append])
-_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
-
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  lt_unset=unset
-else
-  lt_unset=false
-fi
-_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
-
-# test EBCDIC or ASCII
-case `echo X|tr X '\101'` in
- A) # ASCII based system
-    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
-  lt_SP2NL='tr \040 \012'
-  lt_NL2SP='tr \015\012 \040\040'
-  ;;
- *) # EBCDIC based system
-  lt_SP2NL='tr \100 \n'
-  lt_NL2SP='tr \r\n \100\100'
-  ;;
-esac
-_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
-_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
-])# _LT_CHECK_SHELL_FEATURES
-
-
-# _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY)
-# ------------------------------------------------------
-# In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and
-# '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY.
-m4_defun([_LT_PROG_FUNCTION_REPLACE],
-[dnl {
-sed -e '/^$1 ()$/,/^} # $1 /c\
-$1 ()\
-{\
-m4_bpatsubsts([$2], [$], [\\], [^\([	 ]\)], [\\\1])
-} # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \
-  && mv -f "$cfgfile.tmp" "$cfgfile" \
-    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-test 0 -eq $? || _lt_function_replace_fail=:
-])
-
-
-# _LT_PROG_REPLACE_SHELLFNS
-# -------------------------
-# Replace existing portable implementations of several shell functions with
-# equivalent extended shell implementations where those features are available..
-m4_defun([_LT_PROG_REPLACE_SHELLFNS],
-[if test x"$xsi_shell" = xyes; then
-  _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl
-    case ${1} in
-      */*) func_dirname_result="${1%/*}${2}" ;;
-      *  ) func_dirname_result="${3}" ;;
-    esac])
-
-  _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl
-    func_basename_result="${1##*/}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl
-    case ${1} in
-      */*) func_dirname_result="${1%/*}${2}" ;;
-      *  ) func_dirname_result="${3}" ;;
-    esac
-    func_basename_result="${1##*/}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl
-    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
-    # positional parameters, so assign one to ordinary parameter first.
-    func_stripname_result=${3}
-    func_stripname_result=${func_stripname_result#"${1}"}
-    func_stripname_result=${func_stripname_result%"${2}"}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl
-    func_split_long_opt_name=${1%%=*}
-    func_split_long_opt_arg=${1#*=}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl
-    func_split_short_opt_arg=${1#??}
-    func_split_short_opt_name=${1%"$func_split_short_opt_arg"}])
-
-  _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl
-    case ${1} in
-      *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
-      *)    func_lo2o_result=${1} ;;
-    esac])
-
-  _LT_PROG_FUNCTION_REPLACE([func_xform], [    func_xform_result=${1%.*}.lo])
-
-  _LT_PROG_FUNCTION_REPLACE([func_arith], [    func_arith_result=$(( $[*] ))])
-
-  _LT_PROG_FUNCTION_REPLACE([func_len], [    func_len_result=${#1}])
-fi
-
-if test x"$lt_shell_append" = xyes; then
-  _LT_PROG_FUNCTION_REPLACE([func_append], [    eval "${1}+=\\${2}"])
-
-  _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl
-    func_quote_for_eval "${2}"
-dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \
-    eval "${1}+=\\\\ \\$func_quote_for_eval_result"])
-
-  # Save a `func_append' function call where possible by direct use of '+='
-  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-else
-  # Save a `func_append' function call even when '+=' is not available
-  sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \
-    && mv -f "$cfgfile.tmp" "$cfgfile" \
-      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp")
-  test 0 -eq $? || _lt_function_replace_fail=:
-fi
-
-if test x"$_lt_function_replace_fail" = x":"; then
-  AC_MSG_WARN([Unable to substitute extended shell functions in $ofile])
-fi
-])
-
-# _LT_PATH_CONVERSION_FUNCTIONS
-# -----------------------------
-# Determine which file name conversion functions should be used by
-# func_to_host_file (and, implicitly, by func_to_host_path).  These are needed
-# for certain cross-compile configurations and native mingw.
-m4_defun([_LT_PATH_CONVERSION_FUNCTIONS],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-AC_MSG_CHECKING([how to convert $build file names to $host format])
-AC_CACHE_VAL(lt_cv_to_host_file_cmd,
-[case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32
-        ;;
-    esac
-    ;;
-  *-*-cygwin* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin
-        ;;
-      *-*-cygwin* )
-        lt_cv_to_host_file_cmd=func_convert_file_noop
-        ;;
-      * ) # otherwise, assume *nix
-        lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin
-        ;;
-    esac
-    ;;
-  * ) # unhandled hosts (and "normal" native builds)
-    lt_cv_to_host_file_cmd=func_convert_file_noop
-    ;;
-esac
-])
-to_host_file_cmd=$lt_cv_to_host_file_cmd
-AC_MSG_RESULT([$lt_cv_to_host_file_cmd])
-_LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd],
-         [0], [convert $build file names to $host format])dnl
-
-AC_MSG_CHECKING([how to convert $build file names to toolchain format])
-AC_CACHE_VAL(lt_cv_to_tool_file_cmd,
-[#assume ordinary cross tools, or native build.
-lt_cv_to_tool_file_cmd=func_convert_file_noop
-case $host in
-  *-*-mingw* )
-    case $build in
-      *-*-mingw* ) # actually msys
-        lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32
-        ;;
-    esac
-    ;;
-esac
-])
-to_tool_file_cmd=$lt_cv_to_tool_file_cmd
-AC_MSG_RESULT([$lt_cv_to_tool_file_cmd])
-_LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd],
-         [0], [convert $build files to toolchain format])dnl
-])# _LT_PATH_CONVERSION_FUNCTIONS
diff --git a/m4/lock.m4 b/m4/lock.m4
new file mode 100644
index 0000000..d68c12d
--- /dev/null
+++ b/m4/lock.m4
@@ -0,0 +1,47 @@
+# lock.m4 serial 14
+dnl Copyright (C) 2005-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([gl_LOCK],
+[
+  AC_REQUIRE([gl_THREADLIB])
+  if test "$gl_threads_api" = posix; then
+    # OSF/1 4.0 and Mac OS X 10.1 lack the pthread_rwlock_t type and the
+    # pthread_rwlock_* functions.
+    has_rwlock=false
+    AC_CHECK_TYPE([pthread_rwlock_t],
+      [has_rwlock=true
+       AC_DEFINE([HAVE_PTHREAD_RWLOCK], [1],
+         [Define if the POSIX multithreading library has read/write locks.])],
+      [],
+      [#include <pthread.h>])
+    if $has_rwlock; then
+      gl_PTHREAD_RWLOCK_RDLOCK_PREFER_WRITER
+    fi
+    # glibc defines PTHREAD_MUTEX_RECURSIVE as enum, not as a macro.
+    AC_COMPILE_IFELSE([
+      AC_LANG_PROGRAM(
+        [[#include <pthread.h>]],
+        [[
+#if __FreeBSD__ == 4
+error "No, in FreeBSD 4.0 recursive mutexes actually don't work."
+#elif (defined __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ \
+       && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
+error "No, in Mac OS X < 10.7 recursive mutexes actually don't work."
+#else
+int x = (int)PTHREAD_MUTEX_RECURSIVE;
+return !x;
+#endif
+        ]])],
+      [AC_DEFINE([HAVE_PTHREAD_MUTEX_RECURSIVE], [1],
+         [Define if the <pthread.h> defines PTHREAD_MUTEX_RECURSIVE.])])
+  fi
+  gl_PREREQ_LOCK
+])
+
+# Prerequisites of lib/glthread/lock.c.
+AC_DEFUN([gl_PREREQ_LOCK], [:])
diff --git a/m4/longlong.m4 b/m4/longlong.m4
new file mode 100644
index 0000000..7559db5
--- /dev/null
+++ b/m4/longlong.m4
@@ -0,0 +1,113 @@
+# longlong.m4 serial 19
+dnl Copyright (C) 1999-2007, 2009-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Paul Eggert.
+
+AC_PREREQ([2.62])
+
+# Define HAVE_LONG_LONG_INT if 'long long int' works.
+# This can be faster than what's in Autoconf 2.62 through 2.68.
+
+# Note: If the type 'long long int' exists but is only 32 bits large
+# (as on some very old compilers), HAVE_LONG_LONG_INT will not be
+# defined. In this case you can treat 'long long int' like 'long int'.
+
+AC_DEFUN([AC_TYPE_LONG_LONG_INT],
+[
+  AC_REQUIRE([AC_TYPE_UNSIGNED_LONG_LONG_INT])
+  AC_CACHE_CHECK([for long long int], [ac_cv_type_long_long_int],
+     [ac_cv_type_long_long_int=yes
+      if test "x${ac_cv_prog_cc_c99-no}" = xno; then
+        ac_cv_type_long_long_int=$ac_cv_type_unsigned_long_long_int
+        if test $ac_cv_type_long_long_int = yes; then
+          dnl Catch a bug in Tandem NonStop Kernel (OSS) cc -O circa 2004.
+          dnl If cross compiling, assume the bug is not important, since
+          dnl nobody cross compiles for this platform as far as we know.
+          AC_RUN_IFELSE(
+            [AC_LANG_PROGRAM(
+               [[#include <limits.h>
+                 #ifndef LLONG_MAX
+                 # define HALF \
+                          (1LL << (sizeof (long long int) * CHAR_BIT - 2))
+                 # define LLONG_MAX (HALF - 1 + HALF)
+                 #endif]],
+               [[long long int n = 1;
+                 int i;
+                 for (i = 0; ; i++)
+                   {
+                     long long int m = n << i;
+                     if (m >> i != n)
+                       return 1;
+                     if (LLONG_MAX / 2 < m)
+                       break;
+                   }
+                 return 0;]])],
+            [],
+            [ac_cv_type_long_long_int=no],
+            [:])
+        fi
+      fi])
+  if test $ac_cv_type_long_long_int = yes; then
+    AC_DEFINE([HAVE_LONG_LONG_INT], [1],
+      [Define to 1 if the system has the type 'long long int'.])
+  fi
+])
+
+# Define HAVE_UNSIGNED_LONG_LONG_INT if 'unsigned long long int' works.
+# This can be faster than what's in Autoconf 2.62 through 2.68.
+
+# Note: If the type 'unsigned long long int' exists but is only 32 bits
+# large (as on some very old compilers), AC_TYPE_UNSIGNED_LONG_LONG_INT
+# will not be defined. In this case you can treat 'unsigned long long int'
+# like 'unsigned long int'.
+
+AC_DEFUN([AC_TYPE_UNSIGNED_LONG_LONG_INT],
+[
+  AC_CACHE_CHECK([for unsigned long long int],
+    [ac_cv_type_unsigned_long_long_int],
+    [ac_cv_type_unsigned_long_long_int=yes
+     if test "x${ac_cv_prog_cc_c99-no}" = xno; then
+       AC_LINK_IFELSE(
+         [_AC_TYPE_LONG_LONG_SNIPPET],
+         [],
+         [ac_cv_type_unsigned_long_long_int=no])
+     fi])
+  if test $ac_cv_type_unsigned_long_long_int = yes; then
+    AC_DEFINE([HAVE_UNSIGNED_LONG_LONG_INT], [1],
+      [Define to 1 if the system has the type 'unsigned long long int'.])
+  fi
+])
+
+# Expands to a C program that can be used to test for simultaneous support
+# of 'long long' and 'unsigned long long'. We don't want to say that
+# 'long long' is available if 'unsigned long long' is not, or vice versa,
+# because too many programs rely on the symmetry between signed and unsigned
+# integer types (excluding 'bool').
+AC_DEFUN([_AC_TYPE_LONG_LONG_SNIPPET],
+[
+  AC_LANG_PROGRAM(
+    [[/* For now, do not test the preprocessor; as of 2007 there are too many
+         implementations with broken preprocessors.  Perhaps this can
+         be revisited in 2012.  In the meantime, code should not expect
+         #if to work with literals wider than 32 bits.  */
+      /* Test literals.  */
+      long long int ll = 9223372036854775807ll;
+      long long int nll = -9223372036854775807LL;
+      unsigned long long int ull = 18446744073709551615ULL;
+      /* Test constant expressions.   */
+      typedef int a[((-9223372036854775807LL < 0 && 0 < 9223372036854775807ll)
+                     ? 1 : -1)];
+      typedef int b[(18446744073709551615ULL <= (unsigned long long int) -1
+                     ? 1 : -1)];
+      int i = 63;]],
+    [[/* Test availability of runtime routines for shift and division.  */
+      long long int llmax = 9223372036854775807ll;
+      unsigned long long int ullmax = 18446744073709551615ull;
+      return ((ll << 63) | (ll >> 63) | (ll < i) | (ll > i)
+              | (llmax / ll) | (llmax % ll)
+              | (ull << 63) | (ull >> 63) | (ull << i) | (ull >> i)
+              | (ullmax / ull) | (ullmax % ull));]])
+])
diff --git a/m4/ltoptions.m4 b/m4/ltoptions.m4
deleted file mode 100644
index 5d9acd8..0000000
--- a/m4/ltoptions.m4
+++ /dev/null
@@ -1,384 +0,0 @@
-# Helper functions for option handling.                    -*- Autoconf -*-
-#
-#   Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation,
-#   Inc.
-#   Written by Gary V. Vaughan, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 7 ltoptions.m4
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
-
-
-# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
-# ------------------------------------------
-m4_define([_LT_MANGLE_OPTION],
-[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
-
-
-# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
-# ---------------------------------------
-# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
-# matching handler defined, dispatch to it.  Other OPTION-NAMEs are
-# saved as a flag.
-m4_define([_LT_SET_OPTION],
-[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
-m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
-        _LT_MANGLE_DEFUN([$1], [$2]),
-    [m4_warning([Unknown $1 option `$2'])])[]dnl
-])
-
-
-# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
-# ------------------------------------------------------------
-# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
-m4_define([_LT_IF_OPTION],
-[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
-
-
-# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
-# -------------------------------------------------------
-# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
-# are set.
-m4_define([_LT_UNLESS_OPTIONS],
-[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
-	    [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
-		      [m4_define([$0_found])])])[]dnl
-m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
-])[]dnl
-])
-
-
-# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
-# ----------------------------------------
-# OPTION-LIST is a space-separated list of Libtool options associated
-# with MACRO-NAME.  If any OPTION has a matching handler declared with
-# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
-# the unknown option and exit.
-m4_defun([_LT_SET_OPTIONS],
-[# Set options
-m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
-    [_LT_SET_OPTION([$1], _LT_Option)])
-
-m4_if([$1],[LT_INIT],[
-  dnl
-  dnl Simply set some default values (i.e off) if boolean options were not
-  dnl specified:
-  _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
-  ])
-  _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
-  ])
-  dnl
-  dnl If no reference was made to various pairs of opposing options, then
-  dnl we run the default mode handler for the pair.  For example, if neither
-  dnl `shared' nor `disable-shared' was passed, we enable building of shared
-  dnl archives by default:
-  _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
-  _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
-  _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
-  _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
-  		   [_LT_ENABLE_FAST_INSTALL])
-  ])
-])# _LT_SET_OPTIONS
-
-
-## --------------------------------- ##
-## Macros to handle LT_INIT options. ##
-## --------------------------------- ##
-
-# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
-# -----------------------------------------
-m4_define([_LT_MANGLE_DEFUN],
-[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
-
-
-# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
-# -----------------------------------------------
-m4_define([LT_OPTION_DEFINE],
-[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
-])# LT_OPTION_DEFINE
-
-
-# dlopen
-# ------
-LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
-])
-
-AU_DEFUN([AC_LIBTOOL_DLOPEN],
-[_LT_SET_OPTION([LT_INIT], [dlopen])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `dlopen' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
-
-
-# win32-dll
-# ---------
-# Declare package support for building win32 dll's.
-LT_OPTION_DEFINE([LT_INIT], [win32-dll],
-[enable_win32_dll=yes
-
-case $host in
-*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
-  AC_CHECK_TOOL(AS, as, false)
-  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
-  AC_CHECK_TOOL(OBJDUMP, objdump, false)
-  ;;
-esac
-
-test -z "$AS" && AS=as
-_LT_DECL([], [AS],      [1], [Assembler program])dnl
-
-test -z "$DLLTOOL" && DLLTOOL=dlltool
-_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
-
-test -z "$OBJDUMP" && OBJDUMP=objdump
-_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
-])# win32-dll
-
-AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-_LT_SET_OPTION([LT_INIT], [win32-dll])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `win32-dll' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
-
-
-# _LT_ENABLE_SHARED([DEFAULT])
-# ----------------------------
-# implement the --enable-shared flag, and supports the `shared' and
-# `disable-shared' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_SHARED],
-[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([shared],
-    [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
-	[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=yes ;;
-    no) enable_shared=no ;;
-    *)
-      enable_shared=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_shared=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
-
-    _LT_DECL([build_libtool_libs], [enable_shared], [0],
-	[Whether or not to build shared libraries])
-])# _LT_ENABLE_SHARED
-
-LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
-
-# Old names:
-AC_DEFUN([AC_ENABLE_SHARED],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
-])
-
-AC_DEFUN([AC_DISABLE_SHARED],
-[_LT_SET_OPTION([LT_INIT], [disable-shared])
-])
-
-AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
-AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_ENABLE_SHARED], [])
-dnl AC_DEFUN([AM_DISABLE_SHARED], [])
-
-
-
-# _LT_ENABLE_STATIC([DEFAULT])
-# ----------------------------
-# implement the --enable-static flag, and support the `static' and
-# `disable-static' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_STATIC],
-[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([static],
-    [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
-	[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=yes ;;
-    no) enable_static=no ;;
-    *)
-     enable_static=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_static=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_static=]_LT_ENABLE_STATIC_DEFAULT)
-
-    _LT_DECL([build_old_libs], [enable_static], [0],
-	[Whether or not to build static libraries])
-])# _LT_ENABLE_STATIC
-
-LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
-
-# Old names:
-AC_DEFUN([AC_ENABLE_STATIC],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
-])
-
-AC_DEFUN([AC_DISABLE_STATIC],
-[_LT_SET_OPTION([LT_INIT], [disable-static])
-])
-
-AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
-AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AM_ENABLE_STATIC], [])
-dnl AC_DEFUN([AM_DISABLE_STATIC], [])
-
-
-
-# _LT_ENABLE_FAST_INSTALL([DEFAULT])
-# ----------------------------------
-# implement the --enable-fast-install flag, and support the `fast-install'
-# and `disable-fast-install' LT_INIT options.
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-m4_define([_LT_ENABLE_FAST_INSTALL],
-[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
-AC_ARG_ENABLE([fast-install],
-    [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
-    [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
-    [p=${PACKAGE-default}
-    case $enableval in
-    yes) enable_fast_install=yes ;;
-    no) enable_fast_install=no ;;
-    *)
-      enable_fast_install=no
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS="$lt_save_ifs"
-	if test "X$pkg" = "X$p"; then
-	  enable_fast_install=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
-
-_LT_DECL([fast_install], [enable_fast_install], [0],
-	 [Whether or not to optimize for fast installation])dnl
-])# _LT_ENABLE_FAST_INSTALL
-
-LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
-LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
-
-# Old names:
-AU_DEFUN([AC_ENABLE_FAST_INSTALL],
-[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `fast-install' option into LT_INIT's first parameter.])
-])
-
-AU_DEFUN([AC_DISABLE_FAST_INSTALL],
-[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you put
-the `disable-fast-install' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
-dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
-
-
-# _LT_WITH_PIC([MODE])
-# --------------------
-# implement the --with-pic flag, and support the `pic-only' and `no-pic'
-# LT_INIT options.
-# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
-m4_define([_LT_WITH_PIC],
-[AC_ARG_WITH([pic],
-    [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
-	[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
-    [lt_p=${PACKAGE-default}
-    case $withval in
-    yes|no) pic_mode=$withval ;;
-    *)
-      pic_mode=default
-      # Look at the argument we got.  We use all the common list separators.
-      lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR,"
-      for lt_pkg in $withval; do
-	IFS="$lt_save_ifs"
-	if test "X$lt_pkg" = "X$lt_p"; then
-	  pic_mode=yes
-	fi
-      done
-      IFS="$lt_save_ifs"
-      ;;
-    esac],
-    [pic_mode=default])
-
-test -z "$pic_mode" && pic_mode=m4_default([$1], [default])
-
-_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
-])# _LT_WITH_PIC
-
-LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
-LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
-
-# Old name:
-AU_DEFUN([AC_LIBTOOL_PICMODE],
-[_LT_SET_OPTION([LT_INIT], [pic-only])
-AC_DIAGNOSE([obsolete],
-[$0: Remove this warning and the call to _LT_SET_OPTION when you
-put the `pic-only' option into LT_INIT's first parameter.])
-])
-
-dnl aclocal-1.4 backwards compatibility:
-dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
-
-## ----------------- ##
-## LTDL_INIT Options ##
-## ----------------- ##
-
-m4_define([_LTDL_MODE], [])
-LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
-		 [m4_define([_LTDL_MODE], [nonrecursive])])
-LT_OPTION_DEFINE([LTDL_INIT], [recursive],
-		 [m4_define([_LTDL_MODE], [recursive])])
-LT_OPTION_DEFINE([LTDL_INIT], [subproject],
-		 [m4_define([_LTDL_MODE], [subproject])])
-
-m4_define([_LTDL_TYPE], [])
-LT_OPTION_DEFINE([LTDL_INIT], [installable],
-		 [m4_define([_LTDL_TYPE], [installable])])
-LT_OPTION_DEFINE([LTDL_INIT], [convenience],
-		 [m4_define([_LTDL_TYPE], [convenience])])
diff --git a/m4/ltsugar.m4 b/m4/ltsugar.m4
deleted file mode 100644
index 9000a05..0000000
--- a/m4/ltsugar.m4
+++ /dev/null
@@ -1,123 +0,0 @@
-# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
-#
-# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc.
-# Written by Gary V. Vaughan, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 6 ltsugar.m4
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
-
-
-# lt_join(SEP, ARG1, [ARG2...])
-# -----------------------------
-# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
-# associated separator.
-# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
-# versions in m4sugar had bugs.
-m4_define([lt_join],
-[m4_if([$#], [1], [],
-       [$#], [2], [[$2]],
-       [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
-m4_define([_lt_join],
-[m4_if([$#$2], [2], [],
-       [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
-
-
-# lt_car(LIST)
-# lt_cdr(LIST)
-# ------------
-# Manipulate m4 lists.
-# These macros are necessary as long as will still need to support
-# Autoconf-2.59 which quotes differently.
-m4_define([lt_car], [[$1]])
-m4_define([lt_cdr],
-[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
-       [$#], 1, [],
-       [m4_dquote(m4_shift($@))])])
-m4_define([lt_unquote], $1)
-
-
-# lt_append(MACRO-NAME, STRING, [SEPARATOR])
-# ------------------------------------------
-# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'.
-# Note that neither SEPARATOR nor STRING are expanded; they are appended
-# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
-# No SEPARATOR is output if MACRO-NAME was previously undefined (different
-# than defined and empty).
-#
-# This macro is needed until we can rely on Autoconf 2.62, since earlier
-# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
-m4_define([lt_append],
-[m4_define([$1],
-	   m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
-
-
-
-# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
-# ----------------------------------------------------------
-# Produce a SEP delimited list of all paired combinations of elements of
-# PREFIX-LIST with SUFFIX1 through SUFFIXn.  Each element of the list
-# has the form PREFIXmINFIXSUFFIXn.
-# Needed until we can rely on m4_combine added in Autoconf 2.62.
-m4_define([lt_combine],
-[m4_if(m4_eval([$# > 3]), [1],
-       [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
-[[m4_foreach([_Lt_prefix], [$2],
-	     [m4_foreach([_Lt_suffix],
-		]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
-	[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
-
-
-# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
-# -----------------------------------------------------------------------
-# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
-# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
-m4_define([lt_if_append_uniq],
-[m4_ifdef([$1],
-	  [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
-		 [lt_append([$1], [$2], [$3])$4],
-		 [$5])],
-	  [lt_append([$1], [$2], [$3])$4])])
-
-
-# lt_dict_add(DICT, KEY, VALUE)
-# -----------------------------
-m4_define([lt_dict_add],
-[m4_define([$1($2)], [$3])])
-
-
-# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
-# --------------------------------------------
-m4_define([lt_dict_add_subkey],
-[m4_define([$1($2:$3)], [$4])])
-
-
-# lt_dict_fetch(DICT, KEY, [SUBKEY])
-# ----------------------------------
-m4_define([lt_dict_fetch],
-[m4_ifval([$3],
-	m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
-    m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
-
-
-# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
-# -----------------------------------------------------------------
-m4_define([lt_if_dict_fetch],
-[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
-	[$5],
-    [$6])])
-
-
-# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
-# --------------------------------------------------------------
-m4_define([lt_dict_filter],
-[m4_if([$5], [], [],
-  [lt_join(m4_quote(m4_default([$4], [[, ]])),
-           lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
-		      [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
-])
diff --git a/m4/ltversion.m4 b/m4/ltversion.m4
deleted file mode 100644
index 07a8602..0000000
--- a/m4/ltversion.m4
+++ /dev/null
@@ -1,23 +0,0 @@
-# ltversion.m4 -- version numbers			-*- Autoconf -*-
-#
-#   Copyright (C) 2004 Free Software Foundation, Inc.
-#   Written by Scott James Remnant, 2004
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# @configure_input@
-
-# serial 3337 ltversion.m4
-# This file is part of GNU Libtool
-
-m4_define([LT_PACKAGE_VERSION], [2.4.2])
-m4_define([LT_PACKAGE_REVISION], [1.3337])
-
-AC_DEFUN([LTVERSION_VERSION],
-[macro_version='2.4.2'
-macro_revision='1.3337'
-_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
-_LT_DECL(, macro_revision, 0)
-])
diff --git a/m4/lt~obsolete.m4 b/m4/lt~obsolete.m4
deleted file mode 100644
index c573da9..0000000
--- a/m4/lt~obsolete.m4
+++ /dev/null
@@ -1,98 +0,0 @@
-# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
-#
-#   Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
-#   Written by Scott James Remnant, 2004.
-#
-# This file is free software; the Free Software Foundation gives
-# unlimited permission to copy and/or distribute it, with or without
-# modifications, as long as this notice is preserved.
-
-# serial 5 lt~obsolete.m4
-
-# These exist entirely to fool aclocal when bootstrapping libtool.
-#
-# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN)
-# which have later been changed to m4_define as they aren't part of the
-# exported API, or moved to Autoconf or Automake where they belong.
-#
-# The trouble is, aclocal is a bit thick.  It'll see the old AC_DEFUN
-# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
-# using a macro with the same name in our local m4/libtool.m4 it'll
-# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
-# and doesn't know about Autoconf macros at all.)
-#
-# So we provide this file, which has a silly filename so it's always
-# included after everything else.  This provides aclocal with the
-# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
-# because those macros already exist, or will be overwritten later.
-# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. 
-#
-# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
-# Yes, that means every name once taken will need to remain here until
-# we give up compatibility with versions before 1.7, at which point
-# we need to keep only those names which we still refer to.
-
-# This is to help aclocal find these macros, as it can't see m4_define.
-AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
-
-m4_ifndef([AC_LIBTOOL_LINKER_OPTION],	[AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
-m4_ifndef([AC_PROG_EGREP],		[AC_DEFUN([AC_PROG_EGREP])])
-m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
-m4_ifndef([_LT_AC_SHELL_INIT],		[AC_DEFUN([_LT_AC_SHELL_INIT])])
-m4_ifndef([_LT_AC_SYS_LIBPATH_AIX],	[AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
-m4_ifndef([_LT_PROG_LTMAIN],		[AC_DEFUN([_LT_PROG_LTMAIN])])
-m4_ifndef([_LT_AC_TAGVAR],		[AC_DEFUN([_LT_AC_TAGVAR])])
-m4_ifndef([AC_LTDL_ENABLE_INSTALL],	[AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
-m4_ifndef([AC_LTDL_PREOPEN],		[AC_DEFUN([AC_LTDL_PREOPEN])])
-m4_ifndef([_LT_AC_SYS_COMPILER],	[AC_DEFUN([_LT_AC_SYS_COMPILER])])
-m4_ifndef([_LT_AC_LOCK],		[AC_DEFUN([_LT_AC_LOCK])])
-m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE],	[AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
-m4_ifndef([_LT_AC_TRY_DLOPEN_SELF],	[AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
-m4_ifndef([AC_LIBTOOL_PROG_CC_C_O],	[AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
-m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
-m4_ifndef([AC_LIBTOOL_OBJDIR],		[AC_DEFUN([AC_LIBTOOL_OBJDIR])])
-m4_ifndef([AC_LTDL_OBJDIR],		[AC_DEFUN([AC_LTDL_OBJDIR])])
-m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
-m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP],	[AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
-m4_ifndef([AC_PATH_MAGIC],		[AC_DEFUN([AC_PATH_MAGIC])])
-m4_ifndef([AC_PROG_LD_GNU],		[AC_DEFUN([AC_PROG_LD_GNU])])
-m4_ifndef([AC_PROG_LD_RELOAD_FLAG],	[AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
-m4_ifndef([AC_DEPLIBS_CHECK_METHOD],	[AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
-m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
-m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
-m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
-m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS],	[AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
-m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP],	[AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
-m4_ifndef([LT_AC_PROG_EGREP],		[AC_DEFUN([LT_AC_PROG_EGREP])])
-m4_ifndef([LT_AC_PROG_SED],		[AC_DEFUN([LT_AC_PROG_SED])])
-m4_ifndef([_LT_CC_BASENAME],		[AC_DEFUN([_LT_CC_BASENAME])])
-m4_ifndef([_LT_COMPILER_BOILERPLATE],	[AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
-m4_ifndef([_LT_LINKER_BOILERPLATE],	[AC_DEFUN([_LT_LINKER_BOILERPLATE])])
-m4_ifndef([_AC_PROG_LIBTOOL],		[AC_DEFUN([_AC_PROG_LIBTOOL])])
-m4_ifndef([AC_LIBTOOL_SETUP],		[AC_DEFUN([AC_LIBTOOL_SETUP])])
-m4_ifndef([_LT_AC_CHECK_DLFCN],		[AC_DEFUN([_LT_AC_CHECK_DLFCN])])
-m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER],	[AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
-m4_ifndef([_LT_AC_TAGCONFIG],		[AC_DEFUN([_LT_AC_TAGCONFIG])])
-m4_ifndef([AC_DISABLE_FAST_INSTALL],	[AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
-m4_ifndef([_LT_AC_LANG_CXX],		[AC_DEFUN([_LT_AC_LANG_CXX])])
-m4_ifndef([_LT_AC_LANG_F77],		[AC_DEFUN([_LT_AC_LANG_F77])])
-m4_ifndef([_LT_AC_LANG_GCJ],		[AC_DEFUN([_LT_AC_LANG_GCJ])])
-m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
-m4_ifndef([_LT_AC_LANG_C_CONFIG],	[AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
-m4_ifndef([_LT_AC_LANG_CXX_CONFIG],	[AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
-m4_ifndef([_LT_AC_LANG_F77_CONFIG],	[AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
-m4_ifndef([_LT_AC_LANG_GCJ_CONFIG],	[AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
-m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG],	[AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
-m4_ifndef([_LT_AC_LANG_RC_CONFIG],	[AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
-m4_ifndef([AC_LIBTOOL_CONFIG],		[AC_DEFUN([AC_LIBTOOL_CONFIG])])
-m4_ifndef([_LT_AC_FILE_LTDLL_C],	[AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
-m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS],	[AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
-m4_ifndef([_LT_AC_PROG_CXXCPP],		[AC_DEFUN([_LT_AC_PROG_CXXCPP])])
-m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS],	[AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
-m4_ifndef([_LT_PROG_ECHO_BACKSLASH],	[AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
-m4_ifndef([_LT_PROG_F77],		[AC_DEFUN([_LT_PROG_F77])])
-m4_ifndef([_LT_PROG_FC],		[AC_DEFUN([_LT_PROG_FC])])
-m4_ifndef([_LT_PROG_CXX],		[AC_DEFUN([_LT_PROG_CXX])])
diff --git a/m4/mhd_append_flag_to_var.m4 b/m4/mhd_append_flag_to_var.m4
new file mode 100644
index 0000000..261110c
--- /dev/null
+++ b/m4/mhd_append_flag_to_var.m4
@@ -0,0 +1,48 @@
+# SYNOPSIS
+#
+#   MHD_APPEND_FLAG_TO_VAR([VARIABLE-TO-EXTEND], [FLAG-TO-APPEND])
+#
+# DESCRIPTION
+#
+#   This macro sets VARIABLE-TO-EXTEND to the value of VARIABLE-TO-EXTEND with
+#   appended FLAG-TO-APPEND. If current value of VARIABLE-TO-EXTEND and
+#   FLAG-TO-APPEND are both non-empty strings then space is added between them.
+#
+#   Example usage:
+#
+#     MHD_APPEND_FLAG_TO_VAR([my_CFLAGS], [-Wall])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_APPEND_FLAG_TO_VAR],[dnl
+m4_ifblank([$1],[m4_fatal([$0: First macro argument must not be empty])])dnl
+m4_bmatch([$1], [\$], [m4_fatal([$0: First macro argument must not contain '$'])])dnl
+m4_bmatch([$1], [,], [m4_fatal([$0: First macro argument must not contain ','])])dnl
+m4_bmatch(_mhd_norm_expd([$1]), [\s],dnl
+[m4_fatal([$0: First macro argument must not contain whitespaces])])dnl
+m4_pushdef([varExtd],_mhd_norm_expd([$1]))dnl
+m4_bmatch([$2],[\$],dnl
+[dnl The second parameter is a variable value
+AS_IF([test -z "_mhd_norm_expd([$2])"],dnl
+[varExtd="${varExtd}"],dnl
+[test -z "${varExtd}"],dnl
+[varExtd="_mhd_norm_expd([$2])"],dnl
+[varExtd="${varExtd} _mhd_norm_expd([$2])"])
+],dnl
+[dnl The second parameter is not a variable value
+m4_ifnblank(_mhd_norm_expd([$2]),dnl
+[AS_IF([test -z "${varExtd}"],[varExtd="_mhd_norm_expd([$2])"],[varExtd="${varExtd} _mhd_norm_expd([$2])"])
+],dnl
+[m4_n([varExtd="${varExtd}"])])])dnl m4_ifnblank m4_bmatch
+m4_popdef([varExtd])dnl
+])dnl AC_DEFUN
diff --git a/m4/mhd_check_add_cc_cflag.m4 b/m4/mhd_check_add_cc_cflag.m4
new file mode 100644
index 0000000..0d110e8
--- /dev/null
+++ b/m4/mhd_check_add_cc_cflag.m4
@@ -0,0 +1,63 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_ADD_CC_CFLAG([FLAG-TO-TEST], [VARIABLE-TO-EXTEND],
+#                          [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED])
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flag is supported.
+#   The check is performing by appending FLAG-TO-TEST to the value of
+#   VARIABLE-TO-EXTEND (CFLAGS if not specified), then prepending result to
+#   CFLAGS (unless VARIABLE-TO-EXTEND is CFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND. Otherwise, if compile and link without test flag cannot
+#   be done without any warning, the flag is considered to be unsuppoted.
+#
+#   Example usage:
+#
+#     MHD_CHECK_ADD_CC_CFLAG([-Wshadow], [additional_CFLAGS])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_CHECK_ADD_CC_CFLAG],[dnl
+_MHD_CHECK_ADD_CC_XFLAG([$1],[$2],[$3],[$4],[[CFLAGS]])dnl
+])
+
+
+# SYNOPSIS
+#
+#   _MHD_CHECK_ADD_CC_XFLAG([FLAG-TO-TEST], [VARIABLE-TO-EXTEND],
+#                           [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED],
+#                           [CFLAGS|LDFLAGS])
+#
+AC_DEFUN([_MHD_CHECK_ADD_CC_XFLAG],[dnl
+  AC_PREREQ([2.64])dnl for AS_VAR_IF, m4_ifnblank, m4_default
+  AC_LANG_ASSERT([C])dnl
+  m4_ifblank([$1], [m4_fatal([First macro argument must not be empty])])dnl
+  m4_bmatch(_mhd_norm_expd([$1]), [\s],dnl
+            [m4_fatal([First macro argument must not contain whitespaces])])dnl
+  m4_bmatch(_mhd_norm_expd([$2]), [\s],dnl
+            [m4_fatal([Second macro argument must not contain whitespaces])])dnl
+  m4_bmatch([$1], [\$], [m4_fatal([$0: First macro argument must not contain '$'])])dnl
+  m4_bmatch([$2], [\$], [m4_fatal([$0: Second macro argument must not contain '$'])])dnl
+  m4_bmatch(_mhd_norm_expd([$5]), [^\(CFLAGS\|LDFLAGS\)$],[],dnl
+   [m4_fatal([$0: Fifth macro argument must be either 'CFLAGS' or 'LDFLAGS; ']_mhd_norm_expd([$5])[' is not supported])])dnl
+  m4_ifnblank([$2],
+    [_MHD_CHECK_CC_XFLAG([$1], [$2],
+      [MHD_APPEND_FLAG_TO_VAR(_mhd_norm_expd([$2]),_mhd_norm_expd([$1]))
+       $3],[$4],[$5])],
+    [_MHD_CHECK_CC_XFLAG([$1],_mhd_norm_expd([$5]),
+      [MHD_APPEND_FLAG_TO_VAR(_mhd_norm_expd([$5]),_mhd_norm_expd([$1]))
+       $3],[$4],[$5])]
+  )
+])
diff --git a/m4/mhd_check_add_cc_cflags.m4 b/m4/mhd_check_add_cc_cflags.m4
new file mode 100644
index 0000000..2f13192
--- /dev/null
+++ b/m4/mhd_check_add_cc_cflags.m4
@@ -0,0 +1,39 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_ADD_CC_CFLAGS([FLAGS-TO-TEST], [VARIABLE-TO-EXTEND])
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flags are supported.
+#   The FLAGS-TO-TEST parameter is whitespace-separated flagto to test.
+#   The flags are tested one-by-one, all supported flags are added to the
+#   VARIABLE-TO-EXTEND.
+#   Every flag check is performing by appending one flag to the value of
+#   VARIABLE-TO-EXTEND (CFLAGS if not specified), then prepending result to
+#   CFLAGS (unless VARIABLE-TO-EXTEND is CFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND. Otherwise, if compile and link without test flag cannot
+#   be done without any warning, the flag is considered to be unsuppoted.
+#
+#   Example usage:
+#
+#     MHD_CHECK_ADD_CC_CFLAGS([-Wshadow -Walloc-zero -Winit-self],
+#                             [additional_CFLAGS])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_CHECK_ADD_CC_CFLAGS],[dnl
+m4_foreach_w([test_flag],[$1],
+[MHD_CHECK_ADD_CC_CFLAG([test_flag],[$2])
+])dnl
+])
diff --git a/m4/mhd_check_add_cc_ldflag.m4 b/m4/mhd_check_add_cc_ldflag.m4
new file mode 100644
index 0000000..132d33a
--- /dev/null
+++ b/m4/mhd_check_add_cc_ldflag.m4
@@ -0,0 +1,34 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_ADD_CC_LDFLAG([FLAG-TO-TEST], [VARIABLE-TO-EXTEND],
+#                           [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED])
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flag is supported.
+#   The check is performing by appending FLAG-TO-TEST to the value of
+#   VARIABLE-TO-EXTEND (LDFLAGS if not specified), then prepending result to
+#   LDFLAGS (unless VARIABLE-TO-EXTEND is LDFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND. Otherwise, if compile and link without test flag cannot
+#   be done without any warning, the flag is considered to be unsuppoted.
+#
+#   Example usage:
+#
+#     MHD_CHECK_ADD_CC_LDFLAG([-pie], [additional_LDFLAGS])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_CHECK_ADD_CC_LDFLAG],[dnl
+_MHD_CHECK_ADD_CC_XFLAG([$1],[$2],[$3],[$4],[[LDFLAGS]])dnl
+])
diff --git a/m4/mhd_check_add_cc_ldflags.m4 b/m4/mhd_check_add_cc_ldflags.m4
new file mode 100644
index 0000000..5b013f2
--- /dev/null
+++ b/m4/mhd_check_add_cc_ldflags.m4
@@ -0,0 +1,39 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_ADD_CC_LDFLAGS([FLAGS-TO-TEST], [VARIABLE-TO-EXTEND])
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flags are supported.
+#   The FLAGS-TO-TEST parameter is whitespace-separated flagto to test.
+#   The flags are tested one-by-one, all supported flags are added to the
+#   VARIABLE-TO-EXTEND.
+#   Every flag check is performing by appending one flag to the value of
+#   VARIABLE-TO-EXTEND (LDFLAGS if not specified), then prepending result to
+#   LDFLAGS (unless VARIABLE-TO-EXTEND is LDFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND. Otherwise, if compile and link without test flag cannot
+#   be done without any warning, the flag is considered to be unsuppoted.
+#
+#   Example usage:
+#
+#     MHD_CHECK_ADD_CC_LDFLAGS([-W,--strip-all -Wl,--fatal-warnings],
+#                              [additional_LDFLAGS])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_CHECK_ADD_CC_LDFLAGS],[dnl
+m4_foreach_w([test_flag],[$1],
+[MHD_CHECK_ADD_CC_LDFLAG([test_flag],[$2])
+])dnl
+])
diff --git a/m4/mhd_check_cc_cflag.m4 b/m4/mhd_check_cc_cflag.m4
new file mode 100644
index 0000000..bdac60e
--- /dev/null
+++ b/m4/mhd_check_cc_cflag.m4
@@ -0,0 +1,256 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_CC_CFLAG([FLAG-TO-TEST], [VARIABLE-TO-PREPEND-CFLAGS],
+#                      [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED])
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flag is supported.
+#   The check is performing by prepending FLAG-TO-TEST to CFLAGS, then
+#   prepending value of VARIABLE-TO-PREPEND-CFLAGS (if any) to CFLAGS, and
+#   then performing compile and link test. If test succeed without warnings,
+#   then the flag is considered to be supported. Otherwise, if compile and link
+#   without test flag can be done without any warning, the flag is considered
+#   to be unsuppoted.
+#
+#   Example usage:
+#
+#     MHD_CHECK_CC_CFLAG([-Wshadow], [additional_CFLAGS],
+#                        [additional_CFLAGS="${additional_CFLAGS} -Wshadow"])
+#
+#   Defined cache variable used in check so if any test will not work
+#   correctly on some platform, user may simply fix it by giving cache
+#   variable in configure parameters, for example:
+#
+#     ./configure mhd_cv_cc_fl_supp__Wshadow=no
+#
+#   This simplify building from source on exotic platforms as patching
+#   of configure.ac is not required to change results of tests.
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_CHECK_CC_CFLAG],[dnl
+_MHD_CHECK_CC_XFLAG([$1],[$2],[$3],[$4],[[CFLAGS]])dnl
+])
+
+# SYNOPSIS
+#
+#   _MHD_CHECK_CC_XFLAG([FLAG-TO-TEST], [VARIABLE-TO-PREPEND-CFLAGS],
+#                       [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED],
+#                       [CFLAGS|LDFLAGS])
+#
+AC_DEFUN([_MHD_CHECK_CC_XFLAG],[dnl
+  AC_PREREQ([2.64])dnl for AS_VAR_IF, m4_ifnblank
+  AC_LANG_ASSERT([C])dnl
+  AC_REQUIRE([AC_PROG_CC])dnl
+  m4_ifblank([$1], [m4_fatal([$0: First macro argument must not be empty])])dnl
+  m4_bmatch(m4_normalize([$1]), [\s],dnl
+            [m4_fatal([$0: First macro argument must not contain whitespaces])])dnl
+  m4_bmatch(_mhd_norm_expd([$2]), [\s],dnl
+            [m4_fatal([$0: Second macro argument must not contain whitespaces])])dnl
+  m4_bmatch([$1], [\$], [m4_fatal([$0: First macro argument must not contain '$'])])dnl
+  m4_bmatch([$2], [\$], [m4_fatal([$0: Second macro argument must not contain '$'])])dnl
+  AC_REQUIRE([MHD_FIND_CC_XFLAG_WARNPARAMS])dnl sets 'mhd_xFLAGS_params_warn' variable
+  m4_bmatch(_mhd_norm_expd([$5]), [^\(CFLAGS\|LDFLAGS\)$],[],dnl
+   [m4_fatal([$0: Fifth macro argument must be either 'CFLAGS' or 'LDFLAGS; ']_mhd_norm_expd([$5])[' is not supported])])dnl
+  _MHD_CHECK_CC_XFLAG_BODY([$1],[$2],[$3],[$4],[mhd_xFLAGS_params_warn],[$5])dnl
+])
+
+
+# SYNOPSIS
+#
+#   _MHD_CHECK_CC_XFLAG_BODY([FLAG-TO-TEST], [VARIABLE-TO-PREPEND-CFLAGS],
+#                            [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED],
+#                            [VARIABLE-TO-ENABLE-WARNS], [CFLAGS|LDFLAGS])
+#
+AC_DEFUN([_MHD_CHECK_CC_XFLAG_BODY],[dnl
+  AC_LANG_ASSERT([C])dnl
+  m4_ifblank([$1], [m4_fatal([$0: First macro argument must not be empty])])dnl
+  m4_bmatch(_mhd_norm_expd([$1]), [\s],dnl
+            [m4_fatal([$0: First macro argument must not contain whitespaces])])dnl
+  m4_bmatch(_mhd_norm_expd([$2]), [\s],dnl
+            [m4_fatal([$0: Second macro argument must not contain whitespaces])])dnl
+  m4_bmatch([$1], [\$], [m4_fatal([$0: First macro argument must not contain '$'])])dnl
+  m4_bmatch([$2], [\$], [m4_fatal([$0: Second macro argument must not contain '$'])])dnl
+  m4_ifblank([$5], [m4_fatal([$0: Fifth macro argument must not be empty])])dnl
+  m4_bmatch([$5], [\$], [m4_fatal([$0: Fifth macro argument must not contain '$'])])dnl
+  m4_bmatch(_mhd_norm_expd([$6]), [^\(CFLAGS\|LDFLAGS\)$],[],dnl
+   [m4_fatal([$0: Sixth macro argument must be either 'CFLAGS' or 'LDFLAGS; ']_mhd_norm_expd([$6])[' is not supported])])dnl
+  m4_pushdef([XFLAGS],_mhd_norm_expd([$6]))dnl
+  dnl Keep uppercase letters to avoid clashes for parameters like -fPIE and -fpie
+  AS_VAR_PUSHDEF([cv_Var],[mhd_cv_cc_]m4_tolower(m4_substr(_mhd_norm_expd([$6]),0,1))[fl_supp_]m4_bpatsubst(_mhd_norm_expd([$1]),[[^a-zA-Z0-9]],[_]))dnl
+
+  AC_CACHE_CHECK([whether $[]CC supports _mhd_norm_expd([$1]) flag], cv_Var,
+    [dnl
+      AS_VAR_PUSHDEF([save_xFLAGS_Var], [mhd_check_cc_flag_save_]XFLAGS)dnl
+      AS_VAR_SET([save_xFLAGS_Var],["${XFLAGS}"])
+      m4_ifnblank([$2],[dnl
+        m4_if(_mhd_norm_expd([$2]),[XFLAGS],
+          [XFLAGS="${save_xFLAGS_Var} _mhd_norm_expd([$1]) $[]{_mhd_norm_expd([$5])}"],
+          [XFLAGS="$[]{_mhd_norm_expd([$2])} _mhd_norm_expd([$1]) ${save_xFLAGS_Var} $[]{_mhd_norm_expd([$5])}"])
+      ],[dnl
+        XFLAGS="_mhd_norm_expd([$1]) $[]XFLAGS $[]{_mhd_norm_expd([$5])}"
+      ])dnl
+      mhd_check_cc_flag_save_c_werror_flag="$ac_c_werror_flag"
+      ac_c_werror_flag=yes
+      [#] Reuse the same source for all the checks here
+      AC_LANG_CONFTEST([AC_LANG_SOURCE([[
+int main(void)
+{
+  return 0;
+}
+      ]])])
+      AC_LINK_IFELSE([],
+        [AS_VAR_SET([cv_Var],["yes"])],
+        [ [#] Compile and link failed with test flag added
+          m4_ifnblank([$2],[dnl
+            m4_if(_mhd_norm_expd([$2]),[XFLAGS],
+              [XFLAGS="${save_xFLAGS_Var} $[]{_mhd_norm_expd([$5])}"],
+              [XFLAGS="$[]{_mhd_norm_expd([$2])} ${save_xFLAGS_Var} $[]{_mhd_norm_expd([$5])}"])
+          ],[dnl
+            XFLAGS="${save_xFLAGS_Var} $[]{_mhd_norm_expd([$5])}"
+            ])dnl
+          AC_LINK_IFELSE([],
+            [AS_VAR_SET([cv_Var],["no"])],
+            [ [#] Compile and link failed with test flag removed as well
+              m4_ifnblank([$2],[dnl
+                m4_if(_mhd_norm_expd([$2]),[XFLAGS],
+                  [XFLAGS="${save_xFLAGS_Var} _mhd_norm_expd([$1])"],
+                  [XFLAGS="$[]{_mhd_norm_expd([$2])} _mhd_norm_expd([$1]) ${save_xFLAGS_Var}"])
+              ],[dnl
+                XFLAGS="_mhd_norm_expd([$1]) ${save_xFLAGS_Var}"
+              ])dnl
+              ac_c_werror_flag="$mhd_check_cc_flag_save_c_werror_flag"
+              AC_LINK_IFELSE([],
+                [AS_VAR_SET([cv_Var],["yes"])],
+                [AS_VAR_SET([cv_Var],["no"])],
+              )
+            ]
+          )
+        ]
+      )
+      ac_c_werror_flag="$mhd_check_cc_flag_save_c_werror_flag"
+      AS_VAR_SET([XFLAGS],["${save_xFLAGS_Var}"])
+      AS_UNSET(save_xFLAGS_Var)
+      AS_VAR_POPDEF([save_xFLAGS_Var])dnl
+    ]
+  )
+  m4_ifnblank([$3$4],[dnl
+    AS_VAR_IF([cv_Var], ["yes"], [$3], m4_default_nblank([$4]))
+    ])dnl
+  AS_VAR_POPDEF([cv_Var])dnl
+  m4_popdef([XFLAGS])dnl
+])
+
+
+#
+# SYNOPSIS
+#
+#   MHD_FIND_CC_XFLAG_WARNPARAMS()
+#
+AC_DEFUN([MHD_FIND_CC_XFLAG_WARNPARAMS],[dnl
+  AC_LANG_ASSERT([C])dnl
+  AC_REQUIRE([MHD_FIND_CC_CFLAG_WWARN])dnl
+  mhd_xFLAGS_params_warn=''
+  _MHD_CHECK_CC_XFLAG_BODY([-Wunused-command-line-argument],[],
+    [
+      MHD_APPEND_FLAG_TO_VAR([mhd_xFLAGS_params_warn],[-Wunused-command-line-argument])
+    ],[],[mhd_cv_cc_flag_Wwarn],[[CFLAGS]]
+  )
+  _MHD_CHECK_CC_XFLAG_BODY([-Wignored-optimization-argument],[],
+    [
+      MHD_APPEND_FLAG_TO_VAR([mhd_xFLAGS_params_warn],[-Wignored-optimization-argument])
+    ],[],[mhd_cv_cc_flag_Wwarn],[[CFLAGS]]
+  )
+  _MHD_CHECK_CC_XFLAG_BODY([-Winvalid-command-line-argument],[],
+    [
+      MHD_APPEND_FLAG_TO_VAR([mhd_xFLAGS_params_warn],[-Winvalid-command-line-argument])
+    ],[],[mhd_cv_cc_flag_Wwarn],[[CFLAGS]]
+  )
+  _MHD_CHECK_CC_XFLAG_BODY([-Wunknown-argument],[],
+    [
+      MHD_APPEND_FLAG_TO_VAR([mhd_xFLAGS_params_warn],[-Wunknown-argument])
+    ],[],[mhd_cv_cc_flag_Wwarn],[[CFLAGS]]
+  )
+  MHD_PREPEND_FLAG_TO_VAR([mhd_xFLAGS_params_warn],[$mhd_cv_cc_flag_Wwarn])
+])
+
+
+#
+# SYNOPSIS
+#
+#   MHD_FIND_CC_CFLAG_WWARN()
+#
+AC_DEFUN([MHD_FIND_CC_CFLAG_WWARN],[dnl
+  AC_PREREQ([2.64])dnl for AS_VAR_IF, m4_ifnblank
+  AC_REQUIRE([AC_PROG_CC])dnl
+  AC_LANG_ASSERT([C])dnl
+  AC_MSG_CHECKING([for $[]CC flag to warn on unknown -W parameters])
+  AC_CACHE_VAL([mhd_cv_cc_flag_Wwarn],
+    [
+      mhd_check_cc_flagwarn_save_c_werror_flag="$ac_c_werror_flag"
+      ac_c_werror_flag=yes
+      mhd_find_cc_Wwarn_save_CFLAGS="$CFLAGS"
+      AS_UNSET([mhd_cv_cc_flag_Wwarn])
+      for mhd_cv_cc_flag_Wwarn in '' '-Wunknown-warning-option' '-Werror=unknown-warning-option' ; do
+        AS_VAR_IF([mhd_cv_cc_flag_Wwarn], ["unknown"], [break])
+        [#] Reuse the same source for all the checks here
+        AC_LANG_CONFTEST([AC_LANG_SOURCE([[
+int main(void)
+{
+  return 0;
+}
+        ]])])
+        CFLAGS="-Wmhd-noexist-flag $mhd_find_cc_Wwarn_save_CFLAGS $mhd_cv_cc_flag_Wwarn"
+        AC_LINK_IFELSE([],
+          [],
+          [ [#] Compile and link failed if test flag and non-existing flag added
+            CFLAGS="$mhd_find_cc_Wwarn_save_CFLAGS $mhd_cv_cc_flag_Wwarn"
+            AC_LINK_IFELSE([],
+              [ [#] Compile and link succeed if only test flag added
+                break
+              ]
+            )
+          ]
+        )
+      done
+      CFLAGS="$mhd_find_cc_Wwarn_save_CFLAGS"
+      AS_VAR_IF([mhd_cv_cc_flag_Wwarn], ["unknown"],
+        [
+          _AS_ECHO_LOG([No suitable flags detected. Check whether default flags are correct.])
+          AC_LINK_IFELSE([AC_LANG_SOURCE([[
+int main(void)
+{
+  return 0;
+}
+            ]])],
+            [:],
+            [ [#] Compile and link fails (or warns) with default flags
+              AC_MSG_WARN([Compiler warns (of fails) with default flags!])
+              AC_MSG_WARN([Check whether compiler and compiler flags are correct.])
+            ]
+          )
+        ]
+      )
+      CFLAGS="$mhd_find_cc_Wwarn_save_CFLAGS"
+      AS_UNSET([mhd_find_cc_Wwarn_save_CFLAGS])
+      ac_c_werror_flag="$mhd_check_cc_flagwarn_save_c_werror_flag"
+      AS_UNSET([mhd_check_cc_flagwarn_save_c_werror_flag])
+    ]
+  )
+  AS_IF([test -z "$mhd_cv_cc_flag_Wwarn"],
+    [AC_MSG_RESULT([none needed])],
+    [AC_MSG_RESULT([$mhd_cv_cc_flag_Wwarn])])
+  AS_VAR_IF([mhd_cv_cc_flag_Wwarn], ["unknown"],
+    [AC_MSG_WARN([Unable to find compiler flags to warn on unsupported -W options. Final compiler options may be suboptimal.])])
+
+])
diff --git a/m4/mhd_check_cc_ldflag.m4 b/m4/mhd_check_cc_ldflag.m4
new file mode 100644
index 0000000..9eb5b96
--- /dev/null
+++ b/m4/mhd_check_cc_ldflag.m4
@@ -0,0 +1,43 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_CC_LDFLAG([FLAG-TO-TEST], [VARIABLE-TO-PREPEND-LDFLAGS],
+#                       [ACTION-IF-SUPPORTED], [ACTION-IF-NOT-SUPPORTED])
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flag is supported.
+#   The check is performing by prepending FLAG-TO-TEST to LDFLAGS, then
+#   prepending value of VARIABLE-TO-PREPEND-LDFLAGS (if any) to LDFLAGS, and
+#   then performing compile and link test. If test succeed without warnings,
+#   then the flag is considered to be supported. Otherwise, if compile and link
+#   without test flag can be done without any warning, the flag is considered
+#   to be unsuppoted.
+#
+#   Example usage:
+#
+#     MHD_CHECK_CC_LDFLAG([-pie], [additional_LDFLAGS],
+#                         [additional_LDFLAGS="${additional_LDFLAGS} -pie"])
+#
+#   Defined cache variable used in check so if any test will not work
+#   correctly on some platform, user may simply fix it by giving cache
+#   variable in configure parameters, for example:
+#
+#     ./configure mhd_cv_cc_fl_supp__wshadow=no
+#
+#   This simplify building from source on exotic platforms as patching
+#   of configure.ac is not required to change results of tests.
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_CHECK_CC_LDFLAG],[dnl
+_MHD_CHECK_CC_XFLAG([$1],[$2],[$3],[$4],[[LDFLAGS]])dnl
+])
diff --git a/m4/mhd_check_func.m4 b/m4/mhd_check_func.m4
new file mode 100644
index 0000000..77e6bac
--- /dev/null
+++ b/m4/mhd_check_func.m4
@@ -0,0 +1,104 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_FUNC([FUNCTION_NAME],
+#                  [INCLUDES=AC_INCLUDES_DEFAULT], [CHECK_CODE],
+#                  [ACTION-IF-AVAILABLE], [ACTION-IF-NOT-AVAILABLE],
+#                  [ADDITIONAL_LIBS])
+#
+# DESCRIPTION
+#
+#   This macro checks for presence of specific function by including
+#   specified headers and compiling and linking CHECK_CODE.
+#   This checks both declaration and presence in library.
+#   If function is available then macro HAVE_function_name (the name
+#   of the function convetedd to all uppercase characters) is defined
+#   automatically.
+#   Unlike AC_CHECK_FUNCS macro, this macro do not produce false
+#   negative result if function is declared with specific calling
+#   conventions like __stdcall' or attribute like
+#   __attribute__((__dllimport__)) and linker failing to build test
+#   program due to the different calling conventions. 
+#   By using definition from provided headers, this macro ensures that
+#   correct calling convention is used for detection.
+#
+#   Example usage:
+#
+#     MHD_CHECK_FUNC([memmem],
+#                    [[#include <string.h>]],
+#                    [const void *ptr = memmem("aa", 2, "a", 1); (void)ptr;],
+#                    [var_use_memmem='yes'], [var_use_memmem='no'])
+#
+#   The cache variable used in check so if any test will not work
+#   correctly on some platform, user may simply fix it by giving cache
+#   variable in configure parameters, for example:
+#
+#     ./configure mhd_cv_func_memmem_have=no
+#
+#   This simplifies building from source on exotic platforms as patching
+#   of configure.ac is not required to change results of tests.
+#
+# LICENSE
+#
+#   Copyright (c) 2019-2023 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 5
+
+AC_DEFUN([MHD_CHECK_FUNC],[dnl
+AC_PREREQ([2.64])dnl for AS_VAR_IF, m4_ifblank, m4_ifnblank
+m4_newline([[# Expansion of $0 macro starts here]])
+AC_LANG_ASSERT([C])dnl
+m4_ifblank(m4_translit([$1],[()],[  ]), [m4_fatal([First macro argument must not be empty])])dnl
+m4_ifblank([$3], [m4_fatal([Third macro argument must not be empty])])dnl
+m4_bmatch(m4_normalize([$1]), [\s],dnl
+          [m4_fatal([First macro argument must not contain whitespaces])])dnl
+m4_if(m4_index([$3], m4_normalize(m4_translit([$1],[()],[  ]))), [-1], dnl
+      [m4_fatal([CHECK_CODE parameter (third macro argument) does not contain ']m4_normalize([$1])[' token])])dnl
+AS_VAR_PUSHDEF([decl_cv_Var],[ac_cv_have_decl_]m4_bpatsubst(_mhd_norm_expd(m4_translit([$1],[()],[  ])),[[^a-zA-Z0-9]],[_]))dnl
+AS_VAR_PUSHDEF([cv_Var],[mhd_cv_func_]m4_bpatsubst(_mhd_norm_expd(m4_translit([$1],[()],[  ])),[[^a-zA-Z0-9]],[_]))dnl
+AS_VAR_SET_IF([cv_Var],[],[AC_CHECK_DECL(_mhd_norm_expd([$1]),[],[],[$2])])
+AC_CACHE_CHECK([for function $1], [cv_Var],dnl
+  [dnl
+    AS_VAR_IF([decl_cv_Var],["yes"],dnl
+      [dnl
+        m4_ifnblank([$6],[dnl
+          mhd_check_func_SAVE_LIBS="$LIBS"
+          LIBS="_mhd_norm_expd([$6]) $LIBS"
+        ])dnl
+        AC_LINK_IFELSE(
+          [AC_LANG_SOURCE([
+m4_default_nblank([$2],[AC_INCLUDES_DEFAULT])
+
+[int main(void)
+{
+
+  ]$3[
+
+  return 0;
+}
+            ]])
+          ],
+          [AS_VAR_SET([cv_Var],["yes"])],
+          [AS_VAR_SET([cv_Var],["no"])]dnl
+        )
+        m4_ifnblank([$6],[dnl
+          LIBS="${mhd_check_func_SAVE_LIBS}"
+          AS_UNSET([mhd_check_func_SAVE_LIBS])
+        ])dnl
+      ],[AS_VAR_SET([cv_Var],["no"])]dnl
+    )dnl
+  ]dnl
+)
+AS_VAR_IF([cv_Var], ["yes"],
+          [AC_DEFINE([[HAVE_]]m4_bpatsubst(m4_toupper(_mhd_norm_expd(m4_translit([$1],[()],[  ]))),[[^A-Z0-9]],[_]),
+                     [1], [Define to 1 if you have the ']_mhd_norm_expd(m4_translit([$1],[()],[  ]))[' function.])
+          m4_n([$4])dnl
+          ],[$5])
+AS_VAR_POPDEF([cv_Var])dnl
+AS_VAR_POPDEF([decl_cv_Var])dnl
+m4_newline([[# Expansion of $0 macro ends here]])
+])dnl AC_DEFUN MHD_CHECK_FUNC
diff --git a/m4/mhd_check_func_gettimeofday.m4 b/m4/mhd_check_func_gettimeofday.m4
new file mode 100644
index 0000000..8ef69cc
--- /dev/null
+++ b/m4/mhd_check_func_gettimeofday.m4
@@ -0,0 +1,53 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_FUNC_GETTIMEOFDAY([ACTION-IF-AVAILABLE],
+#                               [ACTION-IF-NOT-AVAILABLE])
+#
+# DESCRIPTION
+#
+#   This macro checks for presence of gettimeofday() function.
+#   If function is available macro HAVE_GETTIMEOFDAY is defined
+#   automatically.
+#
+#   Example usage:
+#
+#     MHD_CHECK_FUNC_GETTIMEOFDAY([var_use_gettimeofday='yes'])
+#
+#   The cache variable used in check so if any test will not work
+#   correctly on some platform, user may simply fix it by giving cache
+#   variable in configure parameters, for example:
+#
+#     ./configure mhd_cv_func_memmem_have=no
+#
+#   This simplifies building from source on exotic platforms as patching
+#   of configure.ac is not required to change results of tests.
+#
+# LICENSE
+#
+#   Copyright (c) 2019-2023 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_CHECK_FUNC_GETTIMEOFDAY],[dnl
+AC_CHECK_HEADERS([sys/time.h time.h])dnl
+MHD_CHECK_FUNC([[gettimeofday]],
+  [[
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+  ]],
+  [[
+  struct timeval tv;
+  if (0 != gettimeofday (&tv, (void*) 0))
+    return 1;
+  ]],[$1],[$2]
+)
+])dnl AC_DEFUN MHD_CHECK_FUNC_GETTIMEOFDAY
diff --git a/m4/mhd_check_link_run.m4 b/m4/mhd_check_link_run.m4
new file mode 100644
index 0000000..25ff129
--- /dev/null
+++ b/m4/mhd_check_link_run.m4
@@ -0,0 +1,67 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_LINK_RUN(MESSAGE, CACHE_ID, COMMAND_IF_CROSS_COMPILING, INPUT,
+#                      [ACTION_IF_SUCCEED], [ACTION_IF_FAILED])
+#
+# DESCRIPTION
+#
+#   Improved version of AC_RUN_IFELSE macro.
+#   Unlike AC_RUN_IFELSE, this macro tries to link the code if cross-compiling.
+#   Action COMMAND_IF_CROSS_COMPILING is executed only if link is succeed,
+#   otherwise CACHE_ID variable set to "no". 
+#   COMMAND_IF_CROSS_COMPILING action must set CACHE_ID variable to "yes", "no",
+#   "assuming yes" or "assuming no".
+#   ACTION_IF_SUCCEED is executed if result is "yes" or "assuming yes".
+#   ACTION_IF_FAILED is executed if result is "no" or "assuming no".
+#
+#   Example usage:
+#
+#     MHD_CHECK_LINK_RUN([for valid snprintf()], [mhd_cv_snprintf_valid],
+#                        [AC_LANG_PROGRAM([AC_INCLUDES_DEFAULT],
+#                                         [if (4 != snprintf(NULL, 0, "test"))
+#                                            return 2;])],
+#                        [mhd_cv_snprintf_valid='assuming no'])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_CHECK_LINK_RUN],[dnl
+m4_ifblank([$1],[m4_fatal([$0: The first macro argument ("MESSAGE") must not be empty])])dnl
+m4_ifblank([$2],[m4_fatal([$0: The second macro argument ("CACHE_ID") must not be empty])])dnl
+m4_ifblank([$3],[m4_fatal([$0: The third macro argument ("COMMAND_IF_CROSS_COMPILING") ]dnl
+[must not be empty])])dnl
+m4_ifblank([$4],[m4_fatal([$0: The fourth macro argument ("INPUT") must not be empty])])dnl
+m4_bmatch(_mhd_norm_expd([$2]),[\s],dnl
+[m4_fatal([$0: The second macro argument ("CACHE_ID") must not contain whitespaces])])dnl
+m4_bmatch(_mhd_norm_expd([$3]),[\<]m4_re_escape(_mhd_norm_expd([$2]))[\>],[],dnl
+[m4_fatal([$0: The third macro argument ("COMMAND_IF_CROSS_COMPILING") must assign ]dnl
+[a value to the cache variable ']_mhd_norm_expd([$2])['])])dnl
+m4_pushdef([cacheVar],_mhd_norm_expd([$2]))dnl
+AC_CACHE_CHECK([$1],[$2],
+[
+AC_LANG_CONFTEST([$4])
+AS_VAR_IF([cross_compiling],["yes"],
+[AC_LINK_IFELSE([],[
+$3
+],[cacheVar='no'])dnl AC_LINK_IFELSE
+],dnl
+[AC_RUN_IFELSE([],[cacheVar='yes'],[cacheVar='no'],[[# Dummy placeholder]])
+])
+rm -f conftest.$ac_ext
+])
+m4_ifnblank([$5],[
+AS_IF([test "x$cacheVar" = "xyes" || test "x$cacheVar" = "xassuming yes"],[$5])dnl AS_IF
+])dnl m4_ifnblank
+m4_ifnblank([$6],[
+AS_IF([test "x$cacheVar" = "xno" || test "x$cacheVar" = "xassuming no"],[$6])dnl AS_IF
+])dnl m4_ifnblank
+])dnl AC_DEFUN
diff --git a/m4/mhd_find_add_cc_cflag.m4 b/m4/mhd_find_add_cc_cflag.m4
new file mode 100644
index 0000000..49c7bff
--- /dev/null
+++ b/m4/mhd_find_add_cc_cflag.m4
@@ -0,0 +1,85 @@
+# SYNOPSIS
+#
+#   MHD_FIND_ADD_CC_CFLAG([VARIABLE-TO-EXTEND],
+#                         [FLAG1-TO-TEST], [FLAG2-TO-TEST], ...)
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flags are supported.
+#   The flags are checked one-by-one. The checking is stopped when the first
+#   supported flag found.
+#   The checks are performing by appending FLAGx-TO-TEST to the value of
+#   VARIABLE-TO-EXTEND (CFLAGS if not specified), then prepending result to
+#   CFLAGS (unless VARIABLE-TO-EXTEND is CFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND and next flags are not checked. If compile-link cycle
+#   cannot be performed without warning with all tested flags, no flag is
+#   added to the VARIABLE-TO-EXTEND.
+#
+#   Example usage:
+#
+#     MHD_CHECK_CC_CFLAG([additional_CFLAGS],
+#                        [-ggdb3], [-g3], [-ggdb], [-g])
+#
+#   Note: Unlike others MHD_CHECK_*CC_CFLAG* macro, this macro uses another
+#   order of parameters.
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_FIND_ADD_CC_CFLAG],[dnl
+_MHD_FIND_ADD_CC_XFLAG([[CFLAGS]],[],[],$@)])
+
+
+# SYNOPSIS
+#
+#   _MHD_FIND_ADD_CC_XFLAG([CFLAGS|LDFLAGS],
+#                          [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND],
+#                          [VARIABLE-TO-EXTEND],
+#                          [FLAG1-TO-TEST], [FLAG2-TO-TEST], ...)
+#
+AC_DEFUN([_MHD_FIND_ADD_CC_XFLAG],[dnl
+  AC_PREREQ([2.64])dnl for m4_ifnblank
+  AC_LANG_ASSERT([C])dnl
+  m4_if(m4_eval([$# >= 5]), [0], [m4_fatal([$0: Macro must have at least five parameters])])dnl
+  m4_ifblank([$5],[m4_fatal([$0: Fifth macro argument must not be empty])])dnl
+  m4_ifnblank([$2$3],[m4_newline([m4_n([AS_UNSET([mhd_cc_found_flag])])])])dnl
+  m4_bmatch(_mhd_norm_expd([$1]), [^\(CFLAGS\|LDFLAGS\)$],[],dnl
+   [m4_fatal([$0: First macro argument must be either 'CFLAGS' or 'LDFLAGS; ']_mhd_norm_expd([$1])[' is not supported])])dnl
+  m4_ifnblank([$4],[_MHD_FIND_ADD_CC_XFLAG_BODY(m4_ifnblank([$2$3],[mhd_cc_found_flag]),[$1],[$4],m4_shiftn([4],$@))],dnl
+  [_MHD_FIND_ADD_CC_XFLAG_BODY(m4_ifnblank([$2$3],[mhd_cc_found_flag]),[$1],[$1],m4_shiftn([4],$@))])dnl
+  m4_ifnblank([$2$3],[
+    AS_IF([test -n "${mhd_cc_found_flag}"],[$2],[$3])
+    AS_UNSET([mhd_cc_found_flag])
+    ])dnl
+  ])dnl
+])
+
+
+# SYNOPSIS
+#
+#   _MHD_FIND_ADD_CC_XFLAG_BODY([VAR-TO-SET],
+#                               [CFLAGS|LDFLAGS],
+#                               [VARIABLE-TO-EXTEND],
+#                               [FLAG1-TO-TEST], [FLAG2-TO-TEST], ...)
+#
+m4_define([_MHD_FIND_ADD_CC_XFLAG_BODY],[dnl
+m4_version_prereq([2.64])dnl for m4_ifnblank
+m4_if([$#],[0],[m4_fatal([$0: no parameters])])dnl
+m4_bmatch(_mhd_norm_expd([$2]),[^\(CFLAGS\|LDFLAGS\)$],[],dnl
+[m4_fatal([$0: Second macro argument must be either 'CFLAGS' or 'LDFLAGS; ']_mhd_norm_expd([$2])[' is not supported])])dnl
+m4_if([$#],[1],[m4_fatal([$0: not enough parameters])])dnl
+m4_if([$#],[2],[m4_fatal([$0: not enough parameters])])dnl
+m4_if([$#],[3],[m4_fatal([$0: not enough parameters])])dnl
+m4_if([$#],[4],[m4_ifnblank([$4],[_MHD_CHECK_ADD_CC_XFLAG([$4],[$3],m4_ifnblank([$1],[$1="_mhd_norm_expd([$4])"]),[],[$2])])],
+[m4_ifnblank([$4],[_MHD_CHECK_ADD_CC_XFLAG([$4],[$3],m4_ifnblank([$1],[$1="_mhd_norm_expd([$4])"]),[$0([$1],[$2],[$3],m4_shiftn([4],$@))],[$2])],
+[$0([$1],[$2],[$3],m4_shiftn([4],$@))])])dnl
+])
diff --git a/m4/mhd_find_add_cc_cflag_ifelse.m4 b/m4/mhd_find_add_cc_cflag_ifelse.m4
new file mode 100644
index 0000000..337c456
--- /dev/null
+++ b/m4/mhd_find_add_cc_cflag_ifelse.m4
@@ -0,0 +1,45 @@
+# SYNOPSIS
+#
+#   MHD_FIND_ADD_CC_CFLAG_IFELSE([ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND],
+#                                [VARIABLE-TO-EXTEND],
+#                                [FLAG1-TO-TEST], [FLAG2-TO-TEST], ...)
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flags are supported.
+#   The flags are checked one-by-one. The checking is stopped when the first
+#   supported flag found.
+#   The checks are performing by appending FLAGx-TO-TEST to the value of
+#   VARIABLE-TO-EXTEND (CFLAGS if not specified), then prepending result to
+#   CFLAGS (unless VARIABLE-TO-EXTEND is CFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND and next flags are not checked. If compile-link cycle
+#   cannot be performed without warning with all tested flags, no flag is
+#   added to the VARIABLE-TO-EXTEND.
+#   If any suitable flag is found, ACTION-IF-FOUND is executed otherwise
+#   ACTION-IF-NOT-FOUND is executed. Found flag (if any) is available as
+#   value of shell variable $mhd_cc_found_flag during action execution.
+#
+#   Example usage:
+#
+#     MHD_FIND_ADD_CC_CFLAG_IFELSE([AC_MSG_NOTICE([Enabled debug information])],
+#                                  [],
+#                                  [additional_CFLAGS],
+#                                  [-ggdb3], [-g3], [-ggdb], [-g])
+#
+#   Note: Unlike others MHD_CHECK_*CC_CFLAG* macro, this macro uses another
+#   order of parameters.
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_FIND_ADD_CC_CFLAG_IFELSE],[dnl
+_MHD_FIND_ADD_CC_XFLAG([[CFLAGS]],$@)])
diff --git a/m4/mhd_find_add_cc_ldflag.m4 b/m4/mhd_find_add_cc_ldflag.m4
new file mode 100644
index 0000000..374ecf0
--- /dev/null
+++ b/m4/mhd_find_add_cc_ldflag.m4
@@ -0,0 +1,39 @@
+# SYNOPSIS
+#
+#   MHD_FIND_ADD_CC_LDFLAG([VARIABLE-TO-EXTEND],
+#                         [FLAG1-TO-TEST], [FLAG2-TO-TEST], ...)
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flags are supported.
+#   The flags are checked one-by-one. The checking is stopped when the first
+#   supported flag found.
+#   The checks are performing by appending FLAGx-TO-TEST to the value of
+#   VARIABLE-TO-EXTEND (LDFLAGS if not specified), then prepending result to
+#   LDFLAGS (unless VARIABLE-TO-EXTEND is LDFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND and next flags are not checked. If compile-link cycle
+#   cannot be performed without warning with all tested flags, no flag is
+#   added to the VARIABLE-TO-EXTEND.
+#
+#   Example usage:
+#
+#     MHD_CHECK_CC_LDFLAG([additional_LDFLAGS],
+#                         [-Wl,--strip-all], [-Wl,--strip-debug])
+#
+#   Note: Unlike others MHD_CHECK_*CC_LDFLAG* macro, this macro uses another
+#   order of parameters.
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_FIND_ADD_CC_LDFLAG],[dnl
+_MHD_FIND_ADD_CC_XFLAG([[LDFLAGS]],[],[],$@)])
diff --git a/m4/mhd_find_add_cc_ldflag_ifelse.m4 b/m4/mhd_find_add_cc_ldflag_ifelse.m4
new file mode 100644
index 0000000..fbb0fd4
--- /dev/null
+++ b/m4/mhd_find_add_cc_ldflag_ifelse.m4
@@ -0,0 +1,44 @@
+# SYNOPSIS
+#
+#   MHD_FIND_ADD_CC_LDFLAG_IFELSE([ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND],
+#                                 [VARIABLE-TO-EXTEND],
+#                                 [FLAG1-TO-TEST], [FLAG2-TO-TEST], ...)
+#
+# DESCRIPTION
+#
+#   This macro checks whether the specific compiler flags are supported.
+#   The flags are checked one-by-one. The checking is stopped when the first
+#   supported flag found.
+#   The checks are performing by appending FLAGx-TO-TEST to the value of
+#   VARIABLE-TO-EXTEND (LDFLAGS if not specified), then prepending result to
+#   LDFLAGS (unless VARIABLE-TO-EXTEND is LDFLAGS), and then performing compile
+#   and link test. If test succeed without warnings, then the flag is added to
+#   VARIABLE-TO-EXTEND and next flags are not checked. If compile-link cycle
+#   cannot be performed without warning with all tested flags, no flag is
+#   added to the VARIABLE-TO-EXTEND.
+#   If any suitable flag is found, ACTION-IF-FOUND is executed otherwise
+#   ACTION-IF-NOT-FOUND is executed. Found flag (if any) is available as
+#   value of shell variable $mhd_cc_found_flag during action execution.
+#
+#   Example usage:
+#
+#     MHD_CHECK_CC_LDFLAG([],[AC_MSG_WARN([Stripping is not supported]),
+#                         [additional_LDFLAGS],
+#                         [-Wl,--strip-all], [-Wl,--strip-debug])
+#
+#   Note: Unlike others MHD_CHECK_*CC_LDFLAG* macro, this macro uses another
+#   order of parameters.
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_FIND_ADD_CC_LDFLAG_IFELSE],[dnl
+_MHD_FIND_ADD_CC_XFLAG([[LDFLAGS]],$@)])
diff --git a/m4/mhd_find_lib.m4 b/m4/mhd_find_lib.m4
new file mode 100644
index 0000000..c4b5d0a
--- /dev/null
+++ b/m4/mhd_find_lib.m4
@@ -0,0 +1,142 @@
+# SYNOPSIS
+#
+#   MHD_FIND_LIB([FUNCTION_NAME],
+#                [INCLUDES=AC_INCLUDES_DEFAULT], [CHECK_CODE],
+#                [LIBS_TO_CHECK],
+#                [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND],
+#                [VAR_TO_PREPEND_LIB=LIBS], [ADDITIONAL_LIBS])
+#
+# DESCRIPTION
+#
+#   This macro checks for presence of specific function by including
+#   specified headers and compiling and linking CHECK_CODE.
+#   This checks both the declaration and the presence in library.
+#   If declaration is not found in headers then libraries are not
+#   checked.
+#   LIBS_TO_CHECK is whitespace-separated list of libraries to check.
+#   The macro first tries to link without any library, and if it fails
+#   the libraries are checked one by one. 
+#   The required library (if any) prepended to VAR_TO_PREPEND_LIB (or
+#   to the LIBS variable if VAR_TO_APPEND_LIB is not specified).
+#   By using definition from provided headers, this macro ensures that
+#   correct calling convention is used for detection.
+#
+#   Example usage:
+#
+#     MHD_FIND_LIB([clock_gettime],
+#                  [[#include <time.h>]],
+#                  [[struct timespec tp;
+#                    if (0 > clock_gettime(CLOCK_REALTIME, &tp)) return 3;]],
+#                  [rt],
+#                  [var_use_gettime='yes'],[var_use_gettime='no'])
+#
+#   Defined cache variable used in the check so if any test will not
+#   work correctly on some platform, a user may simply fix it by giving
+#   cache variable in configure parameters, for example:
+#
+#     ./configure mhd_cv_find_clock_gettime=no
+#
+#   This simplifies building from source on exotic platforms as patching
+#   of configure.ac is not required to change results of tests.
+#
+# LICENSE
+#
+#   Copyright (c) 2023 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([MHD_FIND_LIB],[dnl
+AC_PREREQ([2.64])dnl for AS_VAR_IF, m4_ifblank, m4_ifnblank
+m4_newline([[# Expansion of $0 macro starts here]])
+AC_LANG_ASSERT([C])dnl
+m4_ifblank(m4_translit([$1],[()],[  ]), [m4_fatal([First macro argument FUNCTION_NAME must not be empty])])dnl
+m4_ifblank([$3], [m4_fatal([Third macro argument CHECK_CODE must not be empty])])dnl
+m4_bmatch(m4_normalize([$1]), [\s],dnl
+          [m4_fatal([First macro argument FUNCTION_NAME must not contain whitespaces])])dnl
+m4_if(m4_index([$3], m4_normalize(m4_translit([$1],[()],[  ]))), [-1], dnl
+      [m4_fatal([CHECK_CODE parameter (third macro argument) does not contain ']m4_normalize([$1])[' token])])dnl
+m4_bmatch([$7], [\$], [m4_fatal([$0: Seventh macro argument VAR_TO_PREPEND_LIB must not contain '$'])])dnl
+_MHD_FIND_LIB_BODY([$1],[$2],[$3],[$4],[$5],[$6],m4_default_nblank(_mhd_norm_expd([$7]),[LIBS]),[$8])dnl
+])dnl AC_DEFUN MHD_FIND_LIB
+
+# SYNOPSIS
+#
+#   _MHD_FIND_LIB_BODY([1_FUNCTION_NAME],
+#                      [2_INCLUDES=AC_INCLUDES_DEFAULT], [3_CHECK_CODE],
+#                      [4_LIBS_TO_CHECK],
+#                      [5_ACTION-IF-FOUND], [6_ACTION-IF-NOT-FOUND],
+#                      [7_VAR_TO_PREPEND_LIB=LIBS], [8_ADDITIONAL_LIBS])
+
+AC_DEFUN([_MHD_FIND_LIB_BODY],[dnl
+AS_VAR_PUSHDEF([decl_cv_Var],[ac_cv_have_decl_]m4_bpatsubst(_mhd_norm_expd(m4_translit([$1],[()],[  ])),[[^a-zA-Z0-9]],[_]))dnl
+AS_VAR_PUSHDEF([cv_Var], [mhd_cv_find_lib_]m4_bpatsubst(_mhd_norm_expd(m4_translit([$1],[()],[  ])),[[^a-zA-Z0-9]],[_]))dnl
+AS_VAR_SET_IF([cv_Var],[],[AC_CHECK_DECL(_mhd_norm_expd([$1]),[],[],[$2])])
+AC_CACHE_CHECK([for library containing function $1], [cv_Var],
+  [
+    AS_VAR_IF([decl_cv_Var],["yes"],dnl
+      [dnl
+        mhd_find_lib_SAVE_LIBS="$LIBS"
+        m4_if([$7],LIBS,[dnl
+            mhd_find_lib_CHECK_LIBS="_mhd_norm_expd([$8]) $LIBS"
+          ],[dnl
+            mhd_find_lib_CHECK_LIBS="[$]$7 _mhd_norm_expd([$8]) $LIBS"
+          ]
+        )
+        # Reuse the same source file
+        AC_LANG_CONFTEST(
+          [AC_LANG_SOURCE([
+m4_default_nblank([$2],[AC_INCLUDES_DEFAULT])
+
+[int main(void)
+{
+
+  ]$3[
+
+  return 0;
+}
+             ]])
+          ]
+        )
+        for mhd_find_lib_LIB in '' $4
+        do
+          AS_IF([test -z "${mhd_find_lib_LIB}"],
+            [LIBS="${mhd_find_lib_CHECK_LIBS}"],
+            [LIBS="-l${mhd_find_lib_LIB} ${mhd_find_lib_CHECK_LIBS}"]
+          )
+          AC_LINK_IFELSE([],
+            [
+              AS_IF([test -z "${mhd_find_lib_LIB}"],
+                [AS_VAR_SET([cv_Var],["none required"])],
+                [AS_VAR_SET([cv_Var],["-l${mhd_find_lib_LIB}"])]
+              )
+            ]
+          )
+          AS_VAR_SET_IF([cv_Var],[break])
+        done
+        AS_UNSET([mhd_find_lib_LIB])
+        rm -f conftest.$ac_ext
+        LIBS="${mhd_find_lib_SAVE_LIBS}"
+        AS_UNSET([mhd_find_lib_SAVE_LIBS])
+      ]
+    )
+    AS_VAR_SET_IF([cv_Var],[:],[AS_VAR_SET([cv_Var],["no"])])
+  ]
+)
+AS_IF([test "x${cv_Var}" != "xno"],
+[dnl
+  AS_VAR_IF([cv_Var],["none required"],[:],
+    [
+      AS_IF([test -z "[$]$7"],[$7="${cv_Var}"],[$7="${cv_Var} [$]$7"])
+    ]
+  )
+  m4_n([$5])dnl
+],[$6])dnl AS_VAR_SET_IF cv_Var
+AS_VAR_POPDEF([cv_Var])dnl
+AS_VAR_POPDEF([decl_cv_Var])dnl
+m4_newline([[# Expansion of $0 macro ends here]])
+])dnl AC_DEFUN MHD_CHECK_FUNC
diff --git a/m4/mhd_norm_expd.m4 b/m4/mhd_norm_expd.m4
new file mode 100644
index 0000000..c8ff474
--- /dev/null
+++ b/m4/mhd_norm_expd.m4
@@ -0,0 +1,21 @@
+# SYNOPSIS
+#
+#   _mhd_norm_expd([macro])
+#
+# DESCRIPTION
+#
+#   Normalize string after expansion of the macros.
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 1
+
+AC_DEFUN([_mhd_norm_expd],[m4_normalize(m4_expand([$1]))])
diff --git a/m4/mhd_prepend_flag_to_var.m4 b/m4/mhd_prepend_flag_to_var.m4
new file mode 100644
index 0000000..1d0bd1c
--- /dev/null
+++ b/m4/mhd_prepend_flag_to_var.m4
@@ -0,0 +1,48 @@
+# SYNOPSIS
+#
+#   MHD_PREPEND_FLAG_TO_VAR([VARIABLE-TO-EXTEND], [FLAG-TO-PREPEND])
+#
+# DESCRIPTION
+#
+#   This macro sets VARIABLE-TO-EXTEND to the value of VARIABLE-TO-EXTEND with
+#   appended FLAG-TO-APPEND. If current value of VARIABLE-TO-EXTEND and
+#   FLAG-TO-APPEND are both non-empty strings then space is added between them.
+#
+#   Example usage:
+#
+#     MHD_PREPEND_FLAG_TO_VAR([my_CFLAGS], [-Wall])
+#
+#
+# LICENSE
+#
+#   Copyright (c) 2022 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_PREPEND_FLAG_TO_VAR],[dnl
+m4_ifblank([$1],[m4_fatal([$0: First macro argument must not be empty])])dnl
+m4_bmatch([$1], [\$], [m4_fatal([$0: First macro argument must not contain '$'])])dnl
+m4_bmatch([$1], [,], [m4_fatal([$0: First macro argument must not contain ','])])dnl
+m4_bmatch(_mhd_norm_expd([$1]), [\s],dnl
+[m4_fatal([$0: First macro argument must not contain whitespaces])])dnl
+m4_pushdef([varExtd],_mhd_norm_expd([$1]))dnl
+m4_bmatch([$2],[\$],dnl
+[dnl The second parameter is a variable value
+AS_IF([test -z "_mhd_norm_expd([$2])"],dnl
+[varExtd="${varExtd}"],dnl
+[test -z "${varExtd}"],dnl
+[varExtd="_mhd_norm_expd([$2])"],dnl
+[varExtd="_mhd_norm_expd([$2]) ${varExtd}"])
+],dnl
+[dnl The second parameter is not a variable value
+m4_ifnblank(_mhd_norm_expd([$2]),dnl
+[AS_IF([test -z "${varExtd}"],[varExtd="_mhd_norm_expd([$2])"],[varExtd="_mhd_norm_expd([$2]) ${varExtd}"])
+],dnl
+[m4_n([varExtd="${varExtd}"])])])dnl m4_ifnblank m4_bmatch
+m4_popdef([varExtd])dnl
+])dnl AC_DEFUN
diff --git a/m4/mhd_shutdown_socket_trigger.m4 b/m4/mhd_shutdown_socket_trigger.m4
new file mode 100644
index 0000000..5f3bbb4
--- /dev/null
+++ b/m4/mhd_shutdown_socket_trigger.m4
@@ -0,0 +1,378 @@
+# SYNOPSIS
+#
+#   MHD_CHECK_SOCKET_SHUTDOWN_TRIGGER([ACTION-IF-TRIGGER], [ACTION-IF-NOT],
+#                                     [ACTION-IF-UNKNOWN])
+#
+# DESCRIPTION
+#
+#   Check whether shutdown of listen socket triggers waiting select().
+#   If cross-compiling, result may be unknown (third action).
+#   Result is cached in $mhd_cv_host_shtdwn_trgr_select variable.
+#
+# LICENSE
+#
+#   Copyright (c) 2017-2023 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 6
+
+AC_DEFUN([MHD_CHECK_SOCKET_SHUTDOWN_TRIGGER],[dnl
+  AC_PREREQ([2.64])dnl
+  AC_REQUIRE([AC_CANONICAL_HOST])dnl
+  AC_REQUIRE([AC_PROG_CC])dnl
+  AC_REQUIRE([AX_PTHREAD])dnl
+  AC_REQUIRE([MHD_CHECK_FUNC_GETTIMEOFDAY])dnl
+  MHD_CHECK_FUNC([[usleep]], [[#include <unistd.h>]], [[usleep(100000);]])
+  MHD_CHECK_FUNC([[nanosleep]], [[#include <time.h>]], [[struct timespec ts2, ts1 = {0, 0}; nanosleep(&ts1, &ts2);]])
+  AC_CHECK_HEADERS([string.h sys/types.h sys/socket.h netinet/in.h time.h sys/select.h netinet/tcp.h],[],[], [AC_INCLUDES_DEFAULT])
+  AC_CACHE_CHECK([[whether shutdown of listen socket triggers select()]],
+    [[mhd_cv_host_shtdwn_trgr_select]], [dnl
+    _MHD_OS_KNOWN_SOCKET_SHUTDOWN_TRIGGER([[mhd_cv_host_shtdwn_trgr_select]])
+    AS_VAR_IF([mhd_cv_host_shtdwn_trgr_select], [["maybe"]],
+      [_MHD_RUN_CHECK_SOCKET_SHUTDOWN_TRIGGER([[mhd_cv_host_shtdwn_trgr_select]])])
+    ]
+  )
+  AS_IF([[test "x$mhd_cv_host_shtdwn_trgr_select" = "xyes"]], [$1],
+    [[test "x$mhd_cv_host_shtdwn_trgr_select" = "xno"]], [$2], [$3])
+  ]
+)
+
+#
+# _MHD_OS_KNOWN_SOCKET_SHUTDOWN_TRIGGER(VAR)
+#
+# Sets VAR to 'yes', 'no' or 'maybe'.
+
+AC_DEFUN([_MHD_OS_KNOWN_SOCKET_SHUTDOWN_TRIGGER],[dnl
+[#] On Linux shutdown of listen socket always trigger select().
+[#] On Windows select() always ignore shutdown of listen socket.
+[#] On other paltforms result may vary depending on platform version.
+  AS_CASE([[$host_os]],
+    [[linux | linux-* | *-linux | *-linux-*]], [$1='yes'],
+    [[mingw*]], [$1='no'],
+    [[cygwin* | msys*]], [$1='no'],
+    [[winnt* | interix*]], [$1='no'],
+    [[mks]], [$1='no'],
+    [[uwin]], [$1='no'],
+    [$1='maybe']
+  )
+  ]
+)
+
+#
+# _MHD_RUN_CHECK_SOCKET_SHUTDOWN_TRIGGER(VAR)
+#
+# Sets VAR to 'yes', 'no' or 'guessing no'.
+
+AC_DEFUN([_MHD_RUN_CHECK_SOCKET_SHUTDOWN_TRIGGER],[dnl
+  AC_LANG_PUSH([C])
+  MHD_CST_SAVE_CC="$CC"
+  MHD_CST_SAVE_CFLAGS="$CFLAGS"
+  MHD_CST_SAVE_LIBS="$LIBS"
+  CC="$PTHREAD_CC"
+  CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+  LIBS="$PTHREAD_LIBS $LIBS"
+  AC_RUN_IFELSE([AC_LANG_SOURCE([[
+#include <stdlib.h>
+
+#ifdef HAVE_UNISTD_H
+#  include <unistd.h>
+#endif
+#ifdef HAVE_TIME_H
+#  include <time.h>
+#endif
+#ifdef HAVE_STRING_H
+#  include <string.h>
+#endif
+
+#if !defined(_WIN32) || defined(__CYGWIN__)
+#  ifdef HAVE_SYS_TYPES_H
+#    include <sys/types.h>
+#  endif
+#  ifdef HAVE_SYS_SOCKET_H
+#    include <sys/socket.h>
+#  endif
+#  ifdef HAVE_NETINET_IN_H
+#    include <netinet/in.h>
+#  endif
+#  ifdef HAVE_SYS_TIME_H
+#    include <sys/time.h>
+#  endif
+#  ifdef HAVE_SYS_SELECT_H
+#    include <sys/select.h>
+#  endif
+#  ifdef HAVE_NETINET_TCP_H
+#    include <netinet/tcp.h>
+#  endif
+   typedef int MHD_socket;
+#  define MHD_INVALID_SOCKET (-1)
+#  define MHD_POSIX_SOCKETS 1
+#else
+#  include <winsock2.h>
+#  include <ws2tcpip.h>
+#  include <windows.h>
+   typedef SOCKET MHD_socket;
+#  define MHD_INVALID_SOCKET (INVALID_SOCKET)
+#  define MHD_WINSOCK_SOCKETS 1
+#endif
+
+#include <pthread.h>
+
+#ifndef SHUT_RD
+#  define SHUT_RD 0
+#endif
+#ifndef SHUT_WR
+#  define SHUT_WR 1
+#endif
+#ifndef SHUT_RDWR
+#  define SHUT_RDWR 2
+#endif
+
+#ifndef NULL
+#  define NULL ((void*)0)
+#endif
+
+#ifdef HAVE_GETTIMEOFDAY
+#  if defined(_WIN32) && !defined(__CYGWIN__)
+#    undef HAVE_GETTIMEOFDAY
+#  endif
+#endif
+
+
+#ifdef HAVE_NANOSLEEP
+static const struct timespec sm_tmout = {0, 1000};
+#  define short_sleep() nanosleep(&sm_tmout, NULL)
+#elif defined(HAVE_USLEEP)
+#  define short_sleep() usleep(1)
+#else
+#  define short_sleep() (void)0
+#endif
+
+static volatile int going_select = 0;
+static volatile int select_ends = 0;
+static volatile int gerror = 0;
+static int timeout_mils;
+
+#ifndef HAVE_GETTIMEOFDAY
+static volatile long long select_elapsed_time = 0;
+
+static long long time_chk(void)
+{
+  long long ret = time(NULL);
+  if (-1 == ret)
+    gerror = 4;
+  return ret;
+}
+#endif
+
+
+static void* select_thrd_func(void* param)
+{
+#ifndef HAVE_GETTIMEOFDAY
+  long long start, stop;
+#endif
+  fd_set rs;
+  struct timeval tmot = {0, 0};
+  MHD_socket fd = *((MHD_socket*)param);
+
+  FD_ZERO(&rs);
+  FD_SET(fd, &rs);
+  tmot.tv_usec = timeout_mils * 1000;
+#ifndef HAVE_GETTIMEOFDAY
+  start = time_chk();
+#endif
+  going_select = 1;
+  if (0 > select ((int)(fd) + 1, &rs, NULL, NULL, &tmot))
+    gerror = 5;
+#ifndef HAVE_GETTIMEOFDAY
+  stop = time_chk();
+  select_elapsed_time = stop - start;
+#endif
+  select_ends = 1;
+  return NULL;
+}
+
+
+static MHD_socket create_socket(void)
+{ return socket (AF_INET, SOCK_STREAM, 0); }
+
+static void close_socket(MHD_socket fd)
+{
+#ifdef MHD_POSIX_SOCKETS
+  close(fd);
+#else
+  closesocket(fd);
+#endif
+}
+
+static MHD_socket
+create_socket_listen(int port)
+{
+  MHD_socket fd;
+  struct sockaddr_in sock_addr;
+  fd = create_socket();
+  if (MHD_INVALID_SOCKET == fd)
+    return fd;
+
+  memset (&sock_addr, 0, sizeof (struct sockaddr_in));
+  sock_addr.sin_family = AF_INET;
+  sock_addr.sin_port = htons(port);
+  sock_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+
+  if (bind (fd, (const struct sockaddr*) &sock_addr, sizeof(sock_addr)) < 0 ||
+      listen(fd, SOMAXCONN) < 0)
+    {
+      close_socket(fd);
+      return MHD_INVALID_SOCKET;
+    }
+  return fd;
+}
+
+#ifdef HAVE_GETTIMEOFDAY
+#define diff_time(tv1, tv2) ((long long)(tv1.tv_sec-tv2.tv_sec)*10000 + (long long)(tv1.tv_usec-tv2.tv_usec)/100)
+#else
+#define diff_time(tv1, tv2) ((long long)(tv1-tv2))
+#endif
+
+static long long test_run_select(int timeout_millsec, int use_shutdown, long long delay_before_shutdown)
+{
+  pthread_t select_thrd;
+  MHD_socket fd;
+#ifdef HAVE_GETTIMEOFDAY
+  struct timeval start, stop;
+#else
+  long long start;
+#endif
+
+  fd = create_socket_listen(0);
+  if (MHD_INVALID_SOCKET == fd)
+    return -7;
+  going_select = 0;
+  select_ends = 0;
+  gerror = 0;
+  timeout_mils = timeout_millsec;
+  if (0 != pthread_create (&select_thrd, NULL, select_thrd_func, (void*)&fd))
+    return -8;
+  while (!going_select) {short_sleep();}
+#ifdef HAVE_GETTIMEOFDAY
+  gettimeofday (&start, NULL);
+#else
+  start = time_chk();
+#endif
+  if (use_shutdown)
+    {
+#ifdef HAVE_GETTIMEOFDAY
+      struct timeval current;
+      do {short_sleep(); gettimeofday(&current, NULL); } while (delay_before_shutdown > diff_time(current, start));
+#else
+      while (delay_before_shutdown > time_chk() - start) {short_sleep();}
+#endif
+      shutdown(fd, SHUT_RDWR);
+    }
+#ifdef HAVE_GETTIMEOFDAY
+  while (!select_ends) {short_sleep();}
+  gettimeofday (&stop, NULL);
+#endif
+  if (0 != pthread_join(select_thrd, NULL))
+    return -9;
+  close_socket(fd);
+  if (gerror)
+    return -10;
+#ifdef HAVE_GETTIMEOFDAY
+  return (long long)diff_time(stop, start);
+#else
+  return select_elapsed_time;
+#endif
+}
+
+static int test_it(void)
+{
+  long long duration2;
+#ifdef HAVE_GETTIMEOFDAY
+  long long duration0, duration1;
+  duration0 = test_run_select(0, 0, 0);
+  if (0 > duration0)
+    return -duration0;
+
+  duration1 = test_run_select(50, 0, 0);
+  if (0 > duration1)
+    return -duration1 + 20;
+
+  duration2 = test_run_select(500, 1, (duration0 + duration1) / 2);
+  if (0 > duration2)
+    return -duration2 + 40;
+
+  if (duration1 * 2 > duration2)
+    { /* Check second time to be sure. */
+      duration2 = test_run_select(500, 1, (duration0 + duration1) / 2);
+      if (0 > duration2)
+        return -duration2 + 60;
+      if (duration1 * 2 > duration2)
+        return 0;
+    }
+#else
+  duration2 = test_run_select(5000, 1, 2);
+  if (0 > duration2)
+    return -duration2 + 80;
+
+  if (4 > duration2)
+    { /* Check second time to be sure. */
+      duration2 = test_run_select(5000, 1, 2);
+      if (0 > duration2)
+      return -duration2 + 100;
+      if (4 > duration2)
+        return 0;
+    }
+#endif
+  return 1;
+}
+
+
+static int init(void)
+{
+#ifdef MHD_WINSOCK_SOCKETS
+  WSADATA wsa_data;
+
+  if (0 != WSAStartup(MAKEWORD(2, 2), &wsa_data) || MAKEWORD(2, 2) != wsa_data.wVersion)
+    {
+      WSACleanup();
+      return 0;
+    }
+#endif /* MHD_WINSOCK_SOCKETS */
+  return 1;
+}
+
+static void cleanup(void)
+{
+#ifdef MHD_WINSOCK_SOCKETS
+  WSACleanup();
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+int main(void)
+{
+  int res;
+  if (!init())
+    return 19;
+
+  res = test_it();
+
+  cleanup();
+  if (gerror)
+    return gerror;
+
+  return res;
+}
+]])], [$1='yes'], [$1='no'], [$1='guessing no'])
+  CC="$MHD_CST_SAVE_CC"
+  CFLAGS="$MHD_CST_SAVE_CFLAGS"
+  LIBS="$MHD_CST_SAVE_LIBS"
+  AS_UNSET([[MHD_CST_SAVE_CC]])
+  AS_UNSET([[MHD_CST_SAVE_CFLAGS]])
+  AS_UNSET([[MHD_CST_SAVE_LIBS]])
+  AC_LANG_POP([C])
+  ]
+)
diff --git a/m4/mhd_sys_extentions.m4 b/m4/mhd_sys_extentions.m4
new file mode 100644
index 0000000..13da648
--- /dev/null
+++ b/m4/mhd_sys_extentions.m4
@@ -0,0 +1,1324 @@
+# SYNOPSIS
+#
+#   MHD_SYS_EXT([VAR-ADD-CPPFLAGS])
+#
+# DESCRIPTION
+#
+#   This macro checks system headers and add defines that enable maximum
+#   number of exposed system interfaces. Macro verifies that added defines
+#   will not break basic headers, some defines are also checked against
+#   real recognition by headers.
+#   If VAR-ADD-CPPFLAGS is specified, defines will be added to this variable
+#   in form suitable for CPPFLAGS. Otherwise defines will be added to
+#   configuration header (usually 'config.h').
+#
+#   Example usage:
+#
+#     MHD_SYS_EXT
+#
+#   or
+#
+#     MHD_SYS_EXT([CPPFLAGS])
+#
+#   Macro is not enforced to be called before AC_COMPILE_IFELSE, but it
+#   advisable to call macro before any compile and header tests since
+#   additional defines can change results of those tests.
+#
+#   Defined in command line macros are always honored and cache variables
+#   used in all checks so if any test will not work correctly on some
+#   platform, user may simply fix it by giving correct defines in CPPFLAGS
+#   or by giving cache variable in configure parameters, for example:
+#
+#     ./configure CPPFLAGS='-D_XOPEN_SOURCE=1 -D_XOPEN_SOURCE_EXTENDED'
+#
+#   or
+#
+#     ./configure mhd_cv_define__xopen_source_sevenh_works=no
+#
+#   This simplify building from source on exotic platforms as patching
+#   of configure.ac is not required to change results of tests.
+#
+# LICENSE
+#
+#   Copyright (c) 2016, 2017 Karlson2k (Evgeny Grin) <k2k@narod.ru>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 2
+
+AC_DEFUN([MHD_SYS_EXT],[dnl
+  AC_PREREQ([2.64])dnl for AS_VAR_IF, AS_VAR_SET_IF, m4_ifnblank
+  AC_LANG_PUSH([C])dnl Use C language for simplicity
+  mhd_mse_sys_ext_defines=""
+  mhd_mse_sys_ext_flags=""
+
+  dnl Check platform-specific extensions.
+  dnl Use compiler-based test for determinig target.
+
+  dnl Always add _GNU_SOURCE if headers allow.
+  MHD_CHECK_DEF_AND_ACCEPT([[_GNU_SOURCE]], [],
+    [[${mhd_mse_sys_ext_defines}]], [mhd_cv_macro_add__gnu_source="no"],
+    [mhd_cv_macro_add__gnu_source="yes"],
+    [mhd_cv_macro_add__gnu_source="no"]
+  )
+  AS_VAR_IF([mhd_cv_macro_add__gnu_source], ["yes"],
+    [
+      _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[_GNU_SOURCE]])
+    ]
+  )
+
+  dnl __BSD_VISIBLE is actually a small hack for FreeBSD.
+  dnl Funny that it's used in some Android versions too.
+  AC_CACHE_CHECK([[whether to try __BSD_VISIBLE macro]],
+    [[mhd_cv_macro_try___bsd_visible]], [dnl
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+/* Warning: test with inverted logic! */
+#ifdef __FreeBSD__
+#error Target FreeBSD
+choke me now;
+#endif /* __FreeBSD__ */
+
+#ifdef __ANDROID__
+#include <android/api-level.h>
+#ifndef __ANDROID_API_O__
+#error Target is Android NDK before R14
+choke me now;
+#endif /* ! __ANDROID_API_O__ */
+#endif /* __ANDROID__ */
+        ]],[])],
+      [[mhd_cv_macro_try___bsd_visible="no"]],
+      [[mhd_cv_macro_try___bsd_visible="yes"]]
+    )
+  ])
+  AS_VAR_IF([[mhd_cv_macro_try___bsd_visible]], [["yes"]],
+  [dnl
+    AC_CACHE_CHECK([[whether __BSD_VISIBLE is already defined]],
+      [[mhd_cv_macro___bsd_visible_defined]], [dnl
+      AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+${mhd_mse_sys_ext_defines}
+/* Warning: test with inverted logic! */
+#ifdef __BSD_VISIBLE
+#error __BSD_VISIBLE is defined
+choke me now;
+#endif
+          ]],[])
+      ],
+        [[mhd_cv_macro___bsd_visible_defined="no"]],
+        [[mhd_cv_macro___bsd_visible_defined="yes"]]
+      )
+    ])
+    AS_VAR_IF([[mhd_cv_macro___bsd_visible_defined]], [["yes"]], [[:]],
+    [dnl
+      MHD_CHECK_ACCEPT_DEFINE(
+        [[__BSD_VISIBLE]], [], [[${mhd_mse_sys_ext_defines}]],
+        [
+          _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[__BSD_VISIBLE]])
+        ]
+      )dnl
+    ])
+  ])
+
+
+  dnl _DARWIN_C_SOURCE enables additional functionality on Darwin.
+  MHD_CHECK_DEFINED_MSG([[__APPLE__]], [[${mhd_mse_sys_ext_defines}]],
+    [[whether to try _DARWIN_C_SOURCE macro]],
+  [dnl
+    MHD_CHECK_DEF_AND_ACCEPT(
+      [[_DARWIN_C_SOURCE]], [], [[${mhd_mse_sys_ext_defines}]], [],
+      [
+        _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[_DARWIN_C_SOURCE]])
+      ]
+    )dnl
+  ])
+
+  dnl __EXTENSIONS__ unlocks almost all interfaces on Solaris.
+  MHD_CHECK_DEFINED_MSG([[__sun]], [[${mhd_mse_sys_ext_defines}]],
+    [[whether to try __EXTENSIONS__ macro]],
+  [dnl
+    MHD_CHECK_DEF_AND_ACCEPT(
+      [[__EXTENSIONS__]], [], [[${mhd_mse_sys_ext_defines}]], [],
+      [
+        _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[__EXTENSIONS__]])
+      ]
+    )dnl
+  ])
+
+  dnl _NETBSD_SOURCE switch on almost all headers definitions on NetBSD.
+  MHD_CHECK_DEFINED_MSG([[__NetBSD__]], [[${mhd_mse_sys_ext_defines}]],
+    [[whether to try _NETBSD_SOURCE macro]],
+  [dnl
+    MHD_CHECK_DEF_AND_ACCEPT(
+      [[_NETBSD_SOURCE]], [], [[${mhd_mse_sys_ext_defines}]], [],
+      [
+        _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[_NETBSD_SOURCE]])
+      ]
+    )dnl
+  ])
+
+  dnl _BSD_SOURCE currently used only on OpenBSD to unhide functions.
+  MHD_CHECK_DEFINED_MSG([[__OpenBSD__]], [[${mhd_mse_sys_ext_defines}]],
+    [[whether to try _BSD_SOURCE macro]],
+  [dnl
+    MHD_CHECK_DEF_AND_ACCEPT(
+      [[_BSD_SOURCE]], [], [[${mhd_mse_sys_ext_defines}]], [],
+      [
+        _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[_BSD_SOURCE]])
+      ]
+    )dnl
+  ])
+
+  dnl _TANDEM_SOURCE unhides most functions on NonStop OS
+  dnl (which comes from Tandem Computers decades ago).
+  MHD_CHECK_DEFINED_MSG([[__TANDEM]], [[${mhd_mse_sys_ext_defines}]],
+    [[whether to try _TANDEM_SOURCE macro]],
+  [dnl
+    MHD_CHECK_DEF_AND_ACCEPT(
+      [[_TANDEM_SOURCE]], [], [[${mhd_mse_sys_ext_defines}]], [],
+      [
+        _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[_TANDEM_SOURCE]])
+      ]
+    )dnl
+  ])
+
+  dnl _ALL_SOURCE makes visible POSIX and non-POSIX symbols
+  dnl on z/OS, AIX and Interix.
+  AC_CACHE_CHECK([[whether to try _ALL_SOURCE macro]],
+    [[mhd_cv_macro_try__all_source]], [dnl
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+#if !defined(__TOS_MVS__) && !defined (__INTERIX)
+#error Target is not z/OS, AIX or Interix
+choke me now;
+#endif
+        ]],[])],
+      [[mhd_cv_macro_try__all_source="yes"]],
+      [[mhd_cv_macro_try__all_source="no"]]
+    )
+  ])
+  AS_VAR_IF([[mhd_cv_macro_try__all_source]], [["yes"]],
+  [dnl
+    MHD_CHECK_DEF_AND_ACCEPT(
+      [[_ALL_SOURCE]], [], [[${mhd_mse_sys_ext_defines}]], [],
+      [
+        _MHD_SYS_EXT_VAR_ADD_FLAG([[mhd_mse_sys_ext_defines]], [[mhd_mse_sys_ext_flags]], [[_ALL_SOURCE]])
+      ]
+    )dnl
+  ])
+
+  mhd_mse_xopen_features=""
+  mhd_mse_xopen_defines=""
+  mhd_mse_xopen_flags=""
+
+  AC_CACHE_CHECK([[whether _XOPEN_SOURCE is already defined]],
+    [[mhd_cv_macro__xopen_source_defined]], [
+      _MHD_CHECK_DEFINED([[_XOPEN_SOURCE]], [[${mhd_mse_sys_ext_defines}]],
+        [[mhd_cv_macro__xopen_source_defined="yes"]],
+        [[mhd_cv_macro__xopen_source_defined="no"]]
+      )
+    ]
+  )
+  AS_VAR_IF([[mhd_cv_macro__xopen_source_defined]], [["no"]],
+    [
+      dnl Some platforms (namely: Solaris) use '==' checks instead of '>='
+      dnl for _XOPEN_SOURCE, resulting that unknown for platform values are
+      dnl interpreted as oldest and platform expose reduced number of
+      dnl interfaces. Next checks will ensure that platform recognise
+      dnl requested mode instead of blindly define high number that can
+      dnl be simply ignored by platform.
+      _MHD_CHECK_POSIX2008([[mhd_mse_xopen_defines]],
+        [[mhd_mse_xopen_flags]],
+        [[${mhd_mse_sys_ext_defines}]],
+        [mhd_mse_xopen_features="${mhd_cv_headers_posix2008}"],
+        [
+          _MHD_CHECK_POSIX2001([[mhd_mse_xopen_defines]],
+            [[mhd_mse_xopen_flags]],
+             [[${mhd_mse_sys_ext_defines}]],
+            [mhd_mse_xopen_features="${mhd_cv_headers_posix2001}"],
+            [
+              _MHD_CHECK_SUSV2([[mhd_mse_xopen_defines]],
+                [[mhd_mse_xopen_flags]],
+                [[${mhd_mse_sys_ext_defines}]],
+                [mhd_mse_xopen_features="${mhd_cv_headers_susv2}"],
+                [mhd_mse_xopen_features="${mhd_cv_headers_susv2}"]
+              )
+            ]
+          )
+        ]
+      )
+    ]
+  )
+
+  AS_IF([[test "x${mhd_cv_macro__xopen_source_defined}" = "xno" && \
+          test "x${mhd_cv_macro__xopen_source_def_fiveh}" = "xno" || \
+          test "x${mhd_mse_xopen_features}" = "xnot available" ]],
+    [
+      _MHD_XOPEN_VAR_ADD([mhd_mse_xopen_defines], [mhd_mse_xopen_flags], [${mhd_mse_sys_ext_defines}])
+    ]
+  )
+
+  mhd_mse_sys_features_src="
+#ifdef __APPLE__
+#include <sys/socket.h>
+#else
+#error No useful system features.
+choke me now;
+#endif
+
+int main()
+{
+#ifdef __APPLE__
+#ifndef sendfile
+  (void) sendfile;
+#endif
+#endif
+  return 0;
+}
+"
+  AC_CACHE_CHECK([[for useful system-specific features]],
+    [[mhd_cv_headers_useful_features_present]], [dnl
+    AC_COMPILE_IFELSE([AC_LANG_SOURCE([[
+${mhd_mse_sys_ext_defines}
+${mhd_mse_sys_features_src}
+      ]])],
+      [[mhd_cv_headers_useful_features_present="yes"]],
+      [[mhd_cv_headers_useful_features_present="no"]]
+    )dnl
+  ])
+  AS_VAR_IF([[mhd_cv_headers_useful_features_present]], [["yes"]],
+    [
+      AS_IF([[test "x${mhd_mse_xopen_flags}" = "x"]], [[:]],
+        [
+          AC_CACHE_CHECK([[whether useful system-specific features works with ${mhd_mse_xopen_flags}]],
+            [[mhd_cv_headers_useful_features_works_xopen]], [dnl
+            AC_COMPILE_IFELSE([AC_LANG_SOURCE([[
+${mhd_mse_sys_ext_defines}
+${mhd_mse_xopen_defines}
+${mhd_mse_sys_features_src}
+              ]])],
+              [[mhd_cv_headers_useful_features_works_xopen="yes"]],
+              [[mhd_cv_headers_useful_features_works_xopen="no"]]
+            )dnl
+          ])dnl
+        ]
+      )dnl
+    ]
+  )
+
+
+  AS_IF([[test "x${mhd_cv_headers_useful_features_present}" = "xyes" && \
+          test "x${mhd_cv_headers_useful_features_works_xopen}" = "xno" && \
+          test "x${mhd_mse_xopen_flags}" != "x"]],
+    [
+      _MHD_VAR_CONTAIN([[mhd_mse_xopen_features]], [[, activated by _XOPEN_SOURCE]],
+        [
+          AC_MSG_WARN([[_XOPEN_SOURCE macro is required to activate all headers symbols, however some useful system-specific features does not work with _XOPEN_SOURCE. ]dnl
+          [_XOPEN_SOURCE macro will not be used.]])
+        ]
+      )
+      AS_UNSET([[mhd_mse_xopen_defines]])
+      AS_UNSET([[mhd_mse_xopen_flags]])
+      AS_UNSET([[mhd_mse_xopen_values]])
+    ]
+  )
+
+  dnl Discard temporal source variables
+  AS_UNSET([[mhd_mse_sys_features_src]])
+  AS_UNSET([[mhd_mse_xopen_defines]])
+  AS_UNSET([[mhd_mse_sys_ext_defines]])
+
+  dnl Determined all required defines.
+  AC_MSG_CHECKING([[for final set of defined symbols]])
+  m4_ifblank([$1], [dnl
+    AH_TEMPLATE([[_XOPEN_SOURCE]], [Define to maximum value supported by system headers])dnl
+    AH_TEMPLATE([[_XOPEN_SOURCE_EXTENDED]], [Define to 1 if _XOPEN_SOURCE is defined to value less than 500 ]dnl
+      [and system headers require this symbol])dnl
+    AH_TEMPLATE([[_XOPEN_VERSION]], [Define to maximum value supported by system headers if _XOPEN_SOURCE ]dnl
+      [is defined to value less than 500 and headers do not support _XOPEN_SOURCE_EXTENDED])dnl
+    AH_TEMPLATE([[_GNU_SOURCE]], [Define to 1 to enable GNU-related header features])dnl
+    AH_TEMPLATE([[__BSD_VISIBLE]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+    AH_TEMPLATE([[_DARWIN_C_SOURCE]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+    AH_TEMPLATE([[__EXTENSIONS__]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+    AH_TEMPLATE([[_NETBSD_SOURCE]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+    AH_TEMPLATE([[_BSD_SOURCE]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+    AH_TEMPLATE([[_TANDEM_SOURCE]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+    AH_TEMPLATE([[_ALL_SOURCE]], [Define to 1 if it is required by headers to expose additional symbols])dnl
+  ])
+  for mhd_mse_Flag in ${mhd_mse_sys_ext_flags} ${mhd_mse_xopen_flags}
+  do
+    m4_ifnblank([$1], [dnl
+      AS_VAR_APPEND([$1],[[" -D$mhd_mse_Flag"]])
+    ], [dnl
+      AS_CASE([[$mhd_mse_Flag]], [[*=*]],
+      [dnl
+        AC_DEFINE_UNQUOTED([[`echo $mhd_mse_Flag | cut -f 1 -d =`]],
+          [[`echo $mhd_mse_Flag | cut -f 2 -d = -s`]])
+      ], [dnl
+        AC_DEFINE_UNQUOTED([[$mhd_mse_Flag]])
+      ])
+    ])
+  done
+  AS_UNSET([[mhd_mse_Flag]])
+  dnl Trim whitespaces
+  mhd_mse_result=`echo ${mhd_mse_sys_ext_flags} ${mhd_mse_xopen_flags}`
+  AC_MSG_RESULT([[${mhd_mse_result}]])
+  AS_UNSET([[mhd_mse_result]])
+  AS_UNSET([[mhd_mse_xopen_flags]])
+  AS_UNSET([[mhd_mse_sys_ext_flags]])
+  AC_LANG_POP([C])
+])
+
+
+#
+# _MHD_SYS_EXT_VAR_ADD_FLAG(DEFINES_VAR, FLAGS_VAR,
+#                           FLAG, [FLAG-VALUE = 1])
+#
+# Internal macro, only to be used from MHD_SYS_EXT, _MHD_XOPEN_VAR_ADD
+
+m4_define([_MHD_SYS_EXT_VAR_ADD_FLAG], [dnl
+  m4_ifnblank([$4],[dnl
+    ]m4_normalize([$1])[="[$]{]m4_normalize([$1])[}[#define ]m4_normalize($3) ]m4_normalize([$4])[
+"
+    AS_IF([test "x[$]{]m4_normalize([$2])[}" = "x"],
+      []m4_normalize([$2])[="]m4_normalize([$3])[=]m4_normalize([$4])["],
+      []m4_normalize([$2])[="[$]{]m4_normalize([$2])[} ]m4_normalize([$3])[=]m4_normalize([$4])["]
+    )dnl
+  ], [dnl
+    ]m4_normalize([$1])[="[$]{]m4_normalize([$1])[}[#define ]m4_normalize($3) 1
+"
+    AS_IF([test "x[$]{]m4_normalize([$2])[}" = "x"],
+      []m4_normalize([$2])[="]m4_normalize([$3])["],
+      []m4_normalize([$2])[="[$]{]m4_normalize([$2])[} ]m4_normalize([$3])["]
+    )dnl
+  ])dnl
+])
+
+#
+# _MHD_VAR_IF(VAR, VALUE, [IF-EQ], [IF-NOT-EQ])
+#
+# Same as AS_VAR_IF, except that it expands to nothing if
+# both IF-EQ and IF-NOT-EQ are empty.
+
+m4_define([_MHD_VAR_IF],[dnl
+m4_ifnblank([$3$4],[dnl
+AS_VAR_IF([$1],[$2],[$3],[$4])])])
+
+#
+# _MHD_STRING_CONTAIN(VAR, MATCH, [IF-MATCH], [IF-NOT-MATCH])
+#
+
+AC_DEFUN([_MHD_VAR_CONTAIN],[dnl
+AC_REQUIRE([AC_PROG_FGREP])dnl
+AS_IF([[`echo "${]$1[}" | $FGREP ']$2[' >/dev/null 2>&1`]], [$3], [$4])
+])
+
+#
+# _MHD_STRING_CONTAIN_BRE(VAR, BRE, [IF-MATCH], [IF-NOT-MATCH])
+#
+
+AC_DEFUN([_MHD_VAR_CONTAIN_BRE],[dnl
+AC_REQUIRE([AC_PROG_GREP])dnl
+AS_IF([[`echo "${]$1[}" | $GREP ']$2[' >/dev/null 2>&1`]], [$3], [$4])
+])
+
+# SYNOPSIS
+#
+# _MHD_CHECK_POSIX2008(DEFINES_VAR, FLAGS_VAR,
+#                      [EXT_DEFINES],
+#                      [ACTION-IF-AVAILABLE],
+#                      [ACTION-IF-NOT-AVAILABLE])
+#
+#
+AC_DEFUN([_MHD_CHECK_POSIX2008], [dnl
+  AC_CACHE_CHECK([headers for POSIX.1-2008/SUSv4 features],
+    [[mhd_cv_headers_posix2008]], [dnl
+      _MHD_CHECK_POSIX_FEATURES_SINGLE([
+_MHD_BASIC_INCLUDES
+[
+/* Check will be passed if ALL features are available 
+ * and failed if ANY feature is not available. */
+int main()
+{
+
+#ifndef stpncpy
+  (void) stpncpy;
+#endif
+#ifndef strnlen
+  (void) strnlen;
+#endif
+
+#if !defined(__NetBSD__) && !defined(__OpenBSD__)
+/* NetBSD and OpenBSD didn't implement wcsnlen() for some reason. */
+#ifndef wcsnlen
+  (void) wcsnlen;
+#endif
+#endif
+
+#ifdef __CYGWIN__
+/* The only depend function on Cygwin, but missing on some other platforms */
+#ifndef strndup
+  (void) strndup;
+#endif
+#endif
+
+#ifndef __sun
+/* illumos forget to uncomment some _XPG7 macros. */
+#ifndef renameat
+  (void) renameat;
+#endif
+
+#ifndef getline
+  (void) getline;
+#endif
+#endif /* ! __sun */
+
+/* gmtime_r() becomes mandatory only in POSIX.1-2008. */
+#ifndef gmtime_r
+  (void) gmtime_r;
+#endif
+
+/* unsetenv() actually defined in POSIX.1-2001 so it
+ * must be present with _XOPEN_SOURCE == 700 too. */
+#ifndef unsetenv
+  (void) unsetenv;
+#endif
+
+  return 0;
+}
+        ]],
+        [$3], [[700]],
+        [[mhd_cv_headers_posix2008]]dnl
+      )
+    ]
+  )
+  _MHD_VAR_CONTAIN_BRE([[mhd_cv_headers_posix2008]], [[^available]],
+    [
+      _MHD_VAR_CONTAIN([[mhd_cv_headers_posix2008]], [[does not work with _XOPEN_SOURCE]], [[:]],
+        [_MHD_SYS_EXT_VAR_ADD_FLAG([$1],[$2],[[_XOPEN_SOURCE]],[[700]])]
+      )
+      $4
+    ],
+    [$5]
+  )
+])
+
+
+# SYNOPSIS
+#
+# _MHD_CHECK_POSIX2001(DEFINES_VAR, FLAGS_VAR,
+#                      [EXT_DEFINES],
+#                      [ACTION-IF-AVAILABLE],
+#                      [ACTION-IF-NOT-AVAILABLE])
+#
+#
+AC_DEFUN([_MHD_CHECK_POSIX2001], [dnl
+  AC_CACHE_CHECK([headers for POSIX.1-2001/SUSv3 features],
+    [[mhd_cv_headers_posix2001]], [
+      _MHD_CHECK_POSIX_FEATURES_SINGLE([
+_MHD_BASIC_INCLUDES
+[
+/* Check will be passed if ALL features are available
+ * and failed if ANY feature is not available. */
+int main()
+{
+
+#ifndef setenv
+  (void) setenv;
+#endif
+
+#ifndef __NetBSD__
+#ifndef vsscanf
+  (void) vsscanf;
+#endif
+#endif
+
+/* Availability of next features varies, but they all must be present
+ * on platform with support for _XOPEN_SOURCE = 600. */
+
+/* vsnprintf() should be available with _XOPEN_SOURCE >= 500, but some platforms
+ * provide it only with _POSIX_C_SOURCE >= 200112 (autodefined when
+ * _XOPEN_SOURCE >= 600) where specification of vsnprintf() is aligned with
+ * ISO C99 while others platforms defined it with even earlier standards. */
+#ifndef vsnprintf
+  (void) vsnprintf;
+#endif
+
+/* On platforms that prefer POSIX over X/Open, fseeko() is available
+ * with _POSIX_C_SOURCE >= 200112 (autodefined when _XOPEN_SOURCE >= 600).
+ * On other platforms it should be available with _XOPEN_SOURCE >= 500. */
+#ifndef fseeko
+  (void) fseeko;
+#endif
+
+/* F_GETOWN must be defined with _XOPEN_SOURCE >= 600, but some platforms
+ * define it with _XOPEN_SOURCE >= 500. */
+#ifndef F_GETOWN
+#error F_GETOWN is not defined
+choke me now;
+#endif
+  return 0;
+}
+        ]],
+        [$3],[[600]],[[mhd_cv_headers_posix2001]]dnl
+      )
+    ]
+  )
+  _MHD_VAR_CONTAIN_BRE([[mhd_cv_headers_posix2001]], [[^available]],
+    [
+      _MHD_VAR_CONTAIN([[mhd_cv_headers_posix2001]], [[does not work with _XOPEN_SOURCE]], [[:]],
+        [_MHD_SYS_EXT_VAR_ADD_FLAG([$1],[$2],[[_XOPEN_SOURCE]],[[600]])]
+      )
+      $4
+    ],
+    [$5]
+  )
+])
+
+
+# SYNOPSIS
+#
+# _MHD_CHECK_SUSV2(DEFINES_VAR, FLAGS_VAR,
+#                  [EXT_DEFINES],
+#                  [ACTION-IF-AVAILABLE],
+#                  [ACTION-IF-NOT-AVAILABLE])
+#
+#
+AC_DEFUN([_MHD_CHECK_SUSV2], [dnl
+  AC_CACHE_CHECK([headers for SUSv2/XPG5 features],
+    [[mhd_cv_headers_susv2]], [
+      _MHD_CHECK_POSIX_FEATURES_SINGLE([
+_MHD_BASIC_INCLUDES
+[
+/* Check will be passed if ALL features are available
+ * and failed if ANY feature is not available. */
+int main()
+{
+/* It's not easy to write reliable test for _XOPEN_SOURCE = 500 as
+ * platforms not always precisely follow this standard and some
+ * functions are already deprecated in later standards. */
+
+/* Availability of next features varies, but they all must be present
+ * on platform with correct support for _XOPEN_SOURCE = 500. */
+
+/* Mandatory with _XOPEN_SOURCE >= 500 but as XSI extension available
+ * with much older standards. */
+#ifndef ftruncate
+  (void) ftruncate;
+#endif
+
+/* Added with _XOPEN_SOURCE >= 500 but was available in some standards
+ * before. XSI extension. */
+#ifndef pread
+  (void) pread;
+#endif
+
+#ifndef __APPLE__
+/* Actually comes from XPG4v2 and must be available
+ * with _XOPEN_SOURCE >= 500 as well. */
+#ifndef symlink
+  (void) symlink;
+#endif
+
+/* Actually comes from XPG4v2 and must be available
+ * with _XOPEN_SOURCE >= 500 as well. XSI extension. */
+#ifndef strdup
+  (void) strdup;
+#endif
+#endif /* ! __APPLE__ */
+  return 0;
+}
+        ]],
+        [$3],[[500]],[[mhd_cv_headers_susv2]]dnl
+      )
+    ]
+  )
+  _MHD_VAR_CONTAIN_BRE([[mhd_cv_headers_susv2]], [[^available]],
+    [
+      _MHD_VAR_CONTAIN([[mhd_cv_headers_susv2]], [[does not work with _XOPEN_SOURCE]], [[:]],
+        [_MHD_SYS_EXT_VAR_ADD_FLAG([$1],[$2],[[_XOPEN_SOURCE]],[[500]])]
+      )
+      $4
+    ],
+    [$5]
+  )
+])
+
+
+# SYNOPSIS
+#
+# _MHD_CHECK_POSIX_FEATURES_SINGLE(FEATURES_TEST,
+#                                  EXT_DEFINES,
+#                                  _XOPEN_SOURCE-VALUE,
+#                                  VAR-RESULT)
+
+AC_DEFUN([_MHD_CHECK_POSIX_FEATURES_SINGLE], [dnl
+  AS_VAR_PUSHDEF([avail_Var], [mhd_cpsxfs_tmp_features_available])dnl
+  AS_VAR_PUSHDEF([ext_Var], [mhd_cpsxfs_tmp_extentions_allowed])dnl
+  AS_VAR_PUSHDEF([xopen_Var], [mhd_cpsxfs_tmp_src_xopen_allowed])dnl
+  AS_VAR_PUSHDEF([dislb_Var], [mhd_cpsxfs_tmp_features_disableable])dnl
+  AS_UNSET([avail_Var])
+  AS_UNSET([ext_Var])
+  AS_UNSET([xopen_Var])
+  AS_UNSET([dislb_Var])
+  _MHD_CHECK_POSIX_FEATURES([$1], [$2], [$3], [avail_Var], [ext_Var], [xopen_Var], [dislb_Var])
+  AS_VAR_IF([avail_Var], ["yes"],
+    [
+      AS_VAR_IF([dislb_Var], ["yes"],
+        [
+          AS_VAR_IF([ext_Var], ["required"],
+            [
+              AS_VAR_IF([xopen_Var], ["allowed"],
+                [
+                  AS_VAR_SET(m4_normalize([$4]), ["available, activated by extension macro, works with _XOPEN_SOURCE=]m4_normalize([$3])["])
+                ],
+                [
+                  AS_VAR_SET(m4_normalize([$4]), ["available, activated by extension macro, does not work with _XOPEN_SOURCE=]m4_normalize([$3])["])
+                ]
+              )
+            ],
+            [
+              AS_VAR_IF([ext_Var], ["allowed"],
+                [
+                  AS_VAR_IF([xopen_Var], ["required"],
+                    [
+                      AS_VAR_SET(m4_normalize([$4]), ["available, activated by _XOPEN_SOURCE=]m4_normalize([$3])[, works with extension macro"])
+                    ],
+                    [
+                      AS_VAR_IF([xopen_Var], ["allowed"],
+                        [
+                          AS_VAR_SET(m4_normalize([$4]), ["available, works with _XOPEN_SOURCE=]m4_normalize([$3])[, works with extension macro"])
+                        ],
+                        [
+                          AS_VAR_SET(m4_normalize([$4]), ["available, works with extension macro, does not work with _XOPEN_SOURCE=]m4_normalize([$3])["])
+                        ]
+                      )
+                    ]
+                  )
+                ],
+                [
+                  AS_VAR_IF([xopen_Var], ["required"],
+                    [
+                      AS_VAR_SET(m4_normalize([$4]), ["available, activated by _XOPEN_SOURCE=]m4_normalize([$3])[, does not work with extension macro"])
+                    ],
+                    [
+                      AS_VAR_IF([xopen_Var], ["allowed"],
+                        [
+                          AS_VAR_SET(m4_normalize([$4]), ["available, works with _XOPEN_SOURCE=]m4_normalize([$3])[, does not work with extension macro"])
+                        ],
+                        [
+                          AS_VAR_SET(m4_normalize([$4]), ["available, does not work with _XOPEN_SOURCE=]m4_normalize([$3])[, does not work with extension macro"])
+                        ]
+                      )
+                    ]
+                  )
+                ]
+              )
+            ]
+          )
+        ],
+        [
+          AS_VAR_SET(m4_normalize([$4]), ["available, works always"])
+        ]
+      )
+    ],
+    [
+      AS_VAR_SET(m4_normalize([$4]), ["not available"])
+    ]
+  )
+  AS_UNSET([dislb_Var])
+  AS_UNSET([xopen_Var])
+  AS_UNSET([ext_Var])
+  AS_UNSET([avail_Var])
+  AS_VAR_POPDEF([dislb_Var])dnl
+  AS_VAR_POPDEF([xopen_Var])dnl
+  AS_VAR_POPDEF([ext_Var])dnl
+  AS_VAR_POPDEF([avail_Var])dnl
+])
+
+# SYNOPSIS
+#
+# _MHD_CHECK_POSIX_FEATURES(FEATURES_TEST, EXT_DEFINES, _XOPEN_SOURCE-VALUE,
+#                           [VAR-FEATURES-AVAILABLE-YES_NO],
+#                           [VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED],
+#                           [VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED],
+#                           [VAR-FEATURES-DISABLEABLE-YES_NO])
+
+AC_DEFUN([_MHD_CHECK_POSIX_FEATURES], [dnl
+  AS_VAR_PUSHDEF([src_Var], [mhd_cpsxf_tmp_src_variable])dnl
+  AS_VAR_PUSHDEF([defs_Var], [mhd_cpsxf_tmp_defs_variable])dnl
+  AS_VAR_SET([src_Var],["
+$1
+"])
+  dnl To reduce 'configure' size
+  AS_VAR_SET([defs_Var],["
+$2
+"])
+  dnl To reduce 'configure' size
+
+  dnl Some platforms enable most features when no
+  dnl specific mode is requested by macro.
+  dnl Check whether features test works without _XOPEN_SOURCE and
+  dnl with disabled extensions (undefined most of
+  dnl predefined macros for specific requested mode).
+  AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+_MHD_UNDEF_ALL_EXT
+$src_Var
+    ])],
+    [dnl
+      _AS_ECHO_LOG([[Checked features work with undefined all extensions and without _XOPEN_SOURCE]])
+      AS_VAR_SET(m4_normalize([$4]),["yes"]) # VAR-FEATURES-AVAILABLE-YES_NO
+
+      dnl Check whether features will work extensions
+      AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$defs_Var
+$src_Var
+        ])],
+        [dnl
+          _AS_ECHO_LOG([[Checked features work with extensions]])
+          AS_VAR_SET(m4_normalize([$5]),["allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+          dnl Check whether features will work with _XOPEN_SOURCE
+          AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$defs_Var
+[#define _XOPEN_SOURCE ]]m4_normalize([$3])[
+$src_Var
+            ])],
+            [dnl
+              _AS_ECHO_LOG([Checked features work with extensions and with _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$6]),["allowed"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+              dnl Check whether features could be disabled
+              dnl Request oldest POSIX mode and strict ANSI mode
+              AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+_MHD_UNDEF_ALL_EXT
+[#define _POSIX_C_SOURCE 1]
+[#define  _ANSI_SOURCE 1]
+$src_Var
+                ])],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features work with disabled extensions, with _POSIX_C_SOURCE=1 and _ANSI_SOURCE=1]])
+                  AS_VAR_SET(m4_normalize([$7]),["no"]) # VAR-FEATURES-DISABLEABLE-YES_NO
+                ],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features DO NOT work with disabled extensions, with _POSIX_C_SOURCE=1 and _ANSI_SOURCE=1]])
+                  AS_VAR_SET(m4_normalize([$7]),["yes"]) # VAR-FEATURES-DISABLEABLE-YES_NO
+                ]
+              )
+            ],
+            [dnl
+              _AS_ECHO_LOG([Checked features DO NOT work with extensions and with _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$6]),["not allowed"])  # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+              AS_VAR_SET(m4_normalize([$7]),["yes"]) # VAR-FEATURES-DISABLEABLE-YES_NO
+            ]
+          )
+        ],
+        [dnl
+          _AS_ECHO_LOG([[Checked features DO NOT work with extensions]])
+          AS_VAR_SET(m4_normalize([$7]),["yes"]) # VAR-FEATURES-DISABLEABLE-YES_NO
+          dnl Check whether features work with _XOPEN_SOURCE
+          AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+[#define _XOPEN_SOURCE ]m4_normalize($3)
+$src_Var
+            ])],
+            [dnl
+              _AS_ECHO_LOG([Checked features work with _XOPEN_SOURCE=]m4_normalize([$3])[])
+              dnl Check default state (without enabling/disabling)
+              AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$src_Var
+                ])],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features work by default]])
+                  AS_VAR_SET(m4_normalize([$6]),["allowed"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+                ],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features DO NOT by default]])
+                  AS_VAR_SET(m4_normalize([$6]),["required"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+                ]
+              )
+              dnl Check whether features work with _XOPEN_SOURCE and extensions
+              AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$defs_Var
+[#define _XOPEN_SOURCE] ]m4_normalize([$3])[
+$src_Var
+                ])],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features work with _XOPEN_SOURCE and extensions]])
+                  AS_VAR_SET(m4_normalize([$5]),["allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+                ],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features DO NOT work with _XOPEN_SOURCE and extensions]])
+                  AS_VAR_SET(m4_normalize([$5]),["not allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+                ]
+              )
+            ],
+            [dnl
+              _AS_ECHO_LOG([Checked features DO NOT work with _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$5]),["not allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+              AS_VAR_SET(m4_normalize([$6]),["not allowed"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+            ]
+          )
+        ]
+      )
+    ],
+    [dnl
+      _AS_ECHO_LOG([[Checked features DO NOT work with undefined all extensions and without _XOPEN_SOURCE]])
+      dnl Let's find the way to enable POSIX features
+      AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$defs_Var
+$src_Var
+        ])],
+        [dnl
+          _AS_ECHO_LOG([[Checked features work with extensions]])
+          AS_VAR_SET(m4_normalize([$4]),["yes"]) # VAR-FEATURES-AVAILABLE-YES_NO
+          AS_VAR_SET(m4_normalize([$7]),["yes"]) # VAR-FEATURES-DISABLEABLE-YES_NO
+          dnl Check default state (without enabling/disabling)
+          AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$src_Var
+            ])],
+            [dnl
+              _AS_ECHO_LOG([[Checked features work by default]])
+              AS_VAR_SET(m4_normalize([$5]),["allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+            ],
+            [dnl
+              _AS_ECHO_LOG([[Checked features DO NOT by default]])
+              AS_VAR_SET(m4_normalize([$5]),["required"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+            ]
+          )
+          dnl Check whether features work with extensions and _XOPEN_SOURCE
+          AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$defs_Var
+[#define _XOPEN_SOURCE] ]m4_normalize([$3])[
+$src_Var
+            ])],
+            [dnl
+              _AS_ECHO_LOG([Checked features work with extensions and _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$6]),["allowed"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+            ],
+            [dnl
+              _AS_ECHO_LOG([Checked features DO NOT work with extensions and _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$6]),["not allowed"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+            ]
+          )
+        ],
+        [dnl
+          _AS_ECHO_LOG([[Checked features DO NOT work with extensions]])
+          dnl Check whether features work with _XOPEN_SOURCE
+          AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+[#define _XOPEN_SOURCE] ]m4_normalize([$3])[
+$src_Var
+            ])],
+            [dnl
+              _AS_ECHO_LOG([Checked features work with _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$4]),["yes"]) # VAR-FEATURES-AVAILABLE-YES_NO
+              dnl Check default state (without enabling/disabling)
+              AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$src_Var
+                ])],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features work by default]])
+                  AS_VAR_SET(m4_normalize([$6]),["allowed"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+                ],
+                [dnl
+                  _AS_ECHO_LOG([[Checked features DO NOT by default]])
+                  AS_VAR_SET(m4_normalize([$6]),["required"]) # VAR-XOPEN-REQUIRED_NOT-ALLOWED_ALLOWED
+                ]
+              )
+              dnl Check whether features work with _XOPEN_SOURCE and extensions
+              AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+$defs_Var
+[#define _XOPEN_SOURCE] ]m4_normalize([$3])[
+$src_Var
+                ])],
+                [dnl
+                  _AS_ECHO_LOG([Checked features work with _XOPEN_SOURCE=]m4_normalize([$3])[ and extensions])
+                  AS_VAR_SET(m4_normalize([$5]),["allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+                ],
+                [dnl
+                  _AS_ECHO_LOG([Checked features DO NOT work with _XOPEN_SOURCE=]m4_normalize([$3])[ and extensions])
+                  AS_VAR_SET(m4_normalize([$5]),["not allowed"]) # VAR-EXTENSIONS-REQUIRED_NOT-ALLOWED_ALLOWED
+                ]
+              )
+            ],
+            [dnl
+              _AS_ECHO_LOG([Checked features DO NOT work with _XOPEN_SOURCE=]m4_normalize([$3])[])
+              AS_VAR_SET(m4_normalize([$4]),["no"]) # VAR-FEATURES-AVAILABLE-YES_NO
+            ]
+          )
+        ]
+      )
+    ]
+  )
+  AS_UNSET([defs_Var])
+  AS_UNSET([src_Var])
+  AS_VAR_POPDEF([defs_Var])dnl
+  AS_VAR_POPDEF([src_Var])dnl
+])
+
+
+#
+# MHD_CHECK_HEADER_PRESENCE(headername.h)
+#
+# Check only by preprocessor whether header file is present.
+
+AC_DEFUN([MHD_CHECK_HEADER_PRESENCE], [dnl
+  AC_PREREQ([2.64])dnl for AS_VAR_PUSHDEF, AS_VAR_SET
+  AS_VAR_PUSHDEF([mhd_cache_Var],[mhd_cv_header_[]$1[]_present])dnl
+  AC_CACHE_CHECK([for presence of $1], [mhd_cache_Var], [dnl
+    dnl Hack autoconf to get pure result of only single header presence
+    cat > conftest.$ac_ext <<_ACEOF
+@%:@include <[]$1[]>
+_ACEOF
+    AC_PREPROC_IFELSE([],
+      [AS_VAR_SET([mhd_cache_Var],[["yes"]])],
+      [AS_VAR_SET([mhd_cache_Var],[["no"]])]
+    )
+    rm -f conftest.$ac_ext
+  ])
+  AS_VAR_POPDEF([mhd_cache_Var])dnl
+])
+
+
+#
+# MHD_CHECK_HEADERS_PRESENCE(oneheader.h otherheader.h ...)
+#
+# Check each specified header in whitespace-separated list for presence.
+
+AC_DEFUN([MHD_CHECK_HEADERS_PRESENCE], [dnl
+  AC_PREREQ([2.60])dnl for m4_foreach_w
+  m4_foreach_w([mhd_chk_Header], [$1],
+    [MHD_CHECK_HEADER_PRESENCE(m4_defn([mhd_chk_Header]))]
+  )dnl
+])
+
+
+#
+# MHD_CHECK_HEADERS_PRESENCE_COMPACT(oneheader.h otherheader.h ...)
+#
+# Same as MHD_CHECK_HEADERS_PRESENCE, but a bit slower and produce more compact 'configure'.
+
+AC_DEFUN([MHD_CHECK_HEADERS_PRESENCE_COMPACT], [dnl
+  for mhd_chk_Header in $1 ; do
+    MHD_CHECK_HEADER_PRESENCE([[${mhd_chk_Header}]])
+  done
+])
+
+
+#
+# MHD_CHECK_BASIC_HEADERS_PRESENCE
+#
+# Check basic headers for presence.
+
+AC_DEFUN([MHD_CHECK_BASIC_HEADERS_PRESENCE], [dnl
+  MHD_CHECK_HEADERS_PRESENCE([stdio.h wchar.h stdlib.h string.h strings.h stdint.h fcntl.h sys/types.h time.h unistd.h])
+])
+
+
+#
+# _MHD_SET_BASIC_INCLUDES
+#
+# Internal preparatory macro.
+
+AC_DEFUN([_MHD_SET_BASIC_INCLUDES], [dnl
+  AC_REQUIRE([MHD_CHECK_BASIC_HEADERS_PRESENCE])dnl
+  AS_IF([[test -z "$mhd_basic_headers_includes"]], [dnl
+    AS_VAR_IF([mhd_cv_header_stdio_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="\
+#include <stdio.h>
+"     ]],[[mhd_basic_headers_includes=""]]
+    )
+    AS_VAR_IF([mhd_cv_header_sys_types_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <sys/types.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_wchar_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <wchar.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_stdlib_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <stdlib.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_string_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <string.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_strings_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <strings.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_stdint_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <stdint.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_fcntl_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <fcntl.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_time_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <time.h>
+"     ]]
+    )
+    AS_VAR_IF([mhd_cv_header_unistd_h_present], [["yes"]],
+      [[mhd_basic_headers_includes="${mhd_basic_headers_includes}\
+#include <unistd.h>
+"     ]]
+    )
+  ])dnl
+])
+
+
+#
+# _MHD_BASIC_INCLUDES
+#
+# Internal macro. Output set of basic includes.
+
+AC_DEFUN([_MHD_BASIC_INCLUDES], [AC_REQUIRE([_MHD_SET_BASIC_INCLUDES])dnl
+[ /* Start of MHD basic test includes */
+$mhd_basic_headers_includes /* End of MHD basic test includes */
+]])
+
+
+#
+# MHD_CHECK_BASIC_HEADERS([PROLOG], [ACTION-IF-OK], [ACTION-IF-FAIL])
+#
+# Check whether basic headers can be compiled with specified prolog.
+
+AC_DEFUN([MHD_CHECK_BASIC_HEADERS], [dnl
+  AC_COMPILE_IFELSE([dnl
+    AC_LANG_PROGRAM([m4_n([$1])dnl
+_MHD_BASIC_INCLUDES
+    ], [[int i = 1; i++; if(i) return i]])
+  ], [$2], [$3])
+])
+
+
+#
+# _MHD_SET_UNDEF_ALL_EXT
+#
+# Internal preparatory macro.
+
+AC_DEFUN([_MHD_SET_UNDEF_ALL_EXT], [m4_divert_text([INIT_PREPARE],[dnl
+[mhd_undef_all_extensions="
+#ifdef _GNU_SOURCE
+#undef _GNU_SOURCE
+#endif
+#ifdef _XOPEN_SOURCE
+#undef _XOPEN_SOURCE
+#endif
+#ifdef _XOPEN_SOURCE_EXTENDED
+#undef _XOPEN_SOURCE_EXTENDED
+#endif
+#ifdef _XOPEN_VERSION
+#undef _XOPEN_VERSION
+#endif
+#ifdef _POSIX_C_SOURCE
+#undef _POSIX_C_SOURCE
+#endif
+#ifdef _POSIX_SOURCE
+#undef _POSIX_SOURCE
+#endif
+#ifdef _DEFAULT_SOURCE
+#undef _DEFAULT_SOURCE
+#endif
+#ifdef _BSD_SOURCE
+#undef _BSD_SOURCE
+#endif
+#ifdef _SVID_SOURCE
+#undef _SVID_SOURCE
+#endif
+#ifdef __EXTENSIONS__
+#undef __EXTENSIONS__
+#endif
+#ifdef _ALL_SOURCE
+#undef _ALL_SOURCE
+#endif
+#ifdef _TANDEM_SOURCE
+#undef _TANDEM_SOURCE
+#endif
+#ifdef _DARWIN_C_SOURCE
+#undef _DARWIN_C_SOURCE
+#endif
+#ifdef __BSD_VISIBLE
+#undef __BSD_VISIBLE
+#endif
+#ifdef _NETBSD_SOURCE
+#undef _NETBSD_SOURCE
+#endif
+"
+]])])
+
+
+#
+# _MHD_UNDEF_ALL_EXT
+#
+# Output prolog that undefine all known extension and visibility macros.
+
+AC_DEFUN([_MHD_UNDEF_ALL_EXT], [dnl
+AC_REQUIRE([_MHD_SET_UNDEF_ALL_EXT])dnl
+$mhd_undef_all_extensions
+])
+
+
+#
+# _MHD_CHECK_DEFINED(SYMBOL, [PROLOG],
+#                    [ACTION-IF-DEFINED], [ACTION-IF-NOT-DEFINED])
+#
+# Silently checks for defined symbols.
+
+AC_DEFUN([_MHD_CHECK_DEFINED], [dnl
+  AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+m4_n([$2])dnl
+[#ifndef ]$1[
+#error ]$1[ is not defined
+choke me now;
+#endif
+        ]],[])
+    ], [m4_default_nblank([$3])], [m4_default_nblank([$4])]
+  )
+])
+
+
+#
+# MHD_CHECK_DEFINED(SYMBOL, [PROLOG],
+#                   [ACTION-IF-DEFINED], [ACTION-IF-NOT-DEFINED],
+#                   [MESSAGE])
+#
+# Cache-check for defined symbols with printing results.
+
+AC_DEFUN([MHD_CHECK_DEFINED], [dnl
+  AS_VAR_PUSHDEF([mhd_cache_Var],[mhd_cv_macro_[]m4_tolower(m4_normalize($1))_defined])dnl
+  AC_CACHE_CHECK([dnl
+m4_ifnblank([$5], [$5], [whether ]m4_normalize([$1])[ is already defined])],
+    [mhd_cache_Var], [dnl
+    _MHD_CHECK_DEFINED(m4_normalize([$1]), [$2],
+      [mhd_cache_Var="yes"],
+      [mhd_cache_Var="no"]
+    )
+  ])
+  _MHD_VAR_IF([mhd_cache_Var], [["yes"]], [$3], [$4])
+  AS_VAR_POPDEF([mhd_cache_Var])dnl
+])
+
+
+#
+# MHD_CHECK_DEFINED_MSG(SYMBOL, [PROLOG], [MESSAGE]
+#                       [ACTION-IF-DEFINED], [ACTION-IF-NOT-DEFINED])
+#
+# Cache-check for defined symbols with printing results.
+# Reordered arguments for better readability.
+
+AC_DEFUN([MHD_CHECK_DEFINED_MSG],[dnl
+MHD_CHECK_DEFINED([$1],[$2],[$4],[$5],[$3])])
+
+#
+# MHD_CHECK_ACCEPT_DEFINE(DEFINE-SYMBOL, [DEFINE-VALUE = 1], [PROLOG],
+#                         [ACTION-IF-ACCEPTED], [ACTION-IF-NOT-ACCEPTED],
+#                         [MESSAGE])
+#
+# Cache-check whether specific defined symbol do not break basic headers.
+
+AC_DEFUN([MHD_CHECK_ACCEPT_DEFINE], [dnl
+  AC_PREREQ([2.64])dnl for AS_VAR_PUSHDEF, AS_VAR_SET, m4_ifnblank
+  AS_VAR_PUSHDEF([mhd_cache_Var],
+    [mhd_cv_define_[]m4_tolower(m4_normalize($1))[]_accepted[]m4_ifnblank([$2],[_[]$2])])dnl
+  AC_CACHE_CHECK([dnl
+m4_ifnblank([$6],[$6],[whether headers accept $1[]m4_ifnblank([$2],[[ with value ]$2])])],
+    [mhd_cache_Var], [dnl
+    MHD_CHECK_BASIC_HEADERS([
+m4_n([$3])[#define ]$1 m4_default_nblank($2,[[1]])],
+      [mhd_cache_Var="yes"], [mhd_cache_Var="no"]
+    )
+  ])
+  _MHD_VAR_IF([mhd_cache_Var], [["yes"]], [$4], [$5])
+  AS_VAR_POPDEF([mhd_cache_Var])dnl
+])
+
+
+#
+# MHD_CHECK_DEF_AND_ACCEPT(DEFINE-SYMBOL, [DEFINE-VALUE = 1], [PROLOG],
+#                         [ACTION-IF-DEFINED],
+#                         [ACTION-IF-ACCEPTED], [ACTION-IF-NOT-ACCEPTED])
+#
+# Combination of MHD_CHECK_DEFINED_ECHO and MHD_CHECK_ACCEPT_DEFINE.
+# First check whether symbol is already defined and, if not defined,
+# checks whether it can be defined.
+
+AC_DEFUN([MHD_CHECK_DEF_AND_ACCEPT], [dnl
+  MHD_CHECK_DEFINED([$1], [$3], [$4], [dnl
+    MHD_CHECK_ACCEPT_DEFINE([$1], [$2], [$3], [$5], [$6])dnl
+  ])dnl
+])
+
+#
+# _MHD_XOPEN_VAR_ADD(DEFINES_VAR, FLAGS_VAR, [PROLOG])
+#
+# Internal macro. Only to be used in MHD_SYS_EXT.
+
+AC_DEFUN([_MHD_XOPEN_VAR_ADD], [dnl
+  MHD_CHECK_DEF_AND_ACCEPT([[_XOPEN_SOURCE]], [[1]], [$3],
+    [
+      AC_CACHE_CHECK([[whether predefined value of _XOPEN_SOURCE is more or equal 500]],
+        [[mhd_cv_macro__xopen_source_def_fiveh]], [dnl
+          AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+m4_n([$3])dnl
+[#if _XOPEN_SOURCE+0 < 500
+#error Value of _XOPEN_SOURCE is less than 500
+choke me now;
+#endif
+              ]],[[int i = 0; i++; if(i) return i]])],
+            [[mhd_cv_macro__xopen_source_def_fiveh="yes"]],
+            [[mhd_cv_macro__xopen_source_def_fiveh="no"]]
+          )dnl
+        ]
+      )dnl
+    ],
+    [_MHD_SYS_EXT_VAR_ADD_FLAG([$1], [$2], [[_XOPEN_SOURCE]], [[1]])]
+  )
+  AS_IF([[test "x${mhd_cv_define__xopen_source_accepted_1}" = "xyes" || \
+          test "x${mhd_cv_macro__xopen_source_def_fiveh}" = "xno"]],
+    [
+      MHD_CHECK_DEF_AND_ACCEPT([[_XOPEN_SOURCE_EXTENDED]], [],
+        [
+m4_n([$3])], [],
+      [dnl
+        _MHD_SYS_EXT_VAR_ADD_FLAG([$1],[$2],[[_XOPEN_SOURCE_EXTENDED]])
+      ], [dnl
+        MHD_CHECK_DEFINED([[_XOPEN_VERSION]],
+          [
+m4_n([$3])], [],
+        [dnl
+          AC_CACHE_CHECK([[for value of _XOPEN_VERSION accepted by headers]],
+            [mhd_cv_define__xopen_version_accepted], [dnl
+            MHD_CHECK_BASIC_HEADERS([
+m4_n([$3])
+[#define _XOPEN_VERSION 4]],
+              [[mhd_cv_define__xopen_version_accepted="4"]],
+            [
+              MHD_CHECK_BASIC_HEADERS([
+m4_n([$3])
+[#define _XOPEN_VERSION 3]],
+                [[mhd_cv_define__xopen_version_accepted="3"]],
+                [[mhd_cv_define__xopen_version_accepted="no"]]
+              )
+            ])
+          ])
+          AS_VAR_IF([mhd_cv_define__xopen_version_accepted], [["no"]],
+            [[:]],
+          [dnl
+            _MHD_SYS_EXT_VAR_ADD_FLAG([$1],[$2],[[_XOPEN_VERSION]],
+              [[${mhd_cv_define__xopen_version_accepted}]]dnl
+            )
+          ])
+        ])
+      ])
+    ]
+  )dnl
+])
+
diff --git a/m4/pkg.m4 b/m4/pkg.m4
new file mode 100644
index 0000000..f9075e5
--- /dev/null
+++ b/m4/pkg.m4
@@ -0,0 +1,275 @@
+# pkg.m4 - Macros to locate and utilise pkg-config.   -*- Autoconf -*-
+# serial 12 (pkg-config-0.29.2)
+
+dnl Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
+dnl Copyright © 2012-2015 Dan Nicholson <dbn.lists@gmail.com>
+dnl
+dnl This program is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2 of the License, or
+dnl (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful, but
+dnl WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+dnl General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; if not, write to the Free Software
+dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+dnl 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if you
+dnl distribute this file as part of a program that contains a
+dnl configuration script generated by Autoconf, you may include it under
+dnl the same distribution terms that you use for the rest of that
+dnl program.
+
+dnl PKG_PREREQ(MIN-VERSION)
+dnl -----------------------
+dnl Since: 0.29
+dnl
+dnl Verify that the version of the pkg-config macros are at least
+dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's
+dnl installed version of pkg-config, this checks the developer's version
+dnl of pkg.m4 when generating configure.
+dnl
+dnl To ensure that this macro is defined, also add:
+dnl m4_ifndef([PKG_PREREQ],
+dnl     [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])])
+dnl
+dnl See the "Since" comment for each macro you use to see what version
+dnl of the macros you require.
+m4_defun([PKG_PREREQ],
+[m4_define([PKG_MACROS_VERSION], [0.29.2])
+m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1,
+    [m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])])
+])dnl PKG_PREREQ
+
+dnl PKG_PROG_PKG_CONFIG([MIN-VERSION])
+dnl ----------------------------------
+dnl Since: 0.16
+dnl
+dnl Search for the pkg-config tool and set the PKG_CONFIG variable to
+dnl first found in the path. Checks that the version of pkg-config found
+dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is
+dnl used since that's the first version where most current features of
+dnl pkg-config existed.
+AC_DEFUN([PKG_PROG_PKG_CONFIG],
+[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
+m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
+m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
+AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
+AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
+AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
+
+if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
+	AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
+fi
+if test -n "$PKG_CONFIG"; then
+	_pkg_min_version=m4_default([$1], [0.9.0])
+	AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
+	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
+		AC_MSG_RESULT([yes])
+	else
+		AC_MSG_RESULT([no])
+		PKG_CONFIG=""
+	fi
+fi[]dnl
+])dnl PKG_PROG_PKG_CONFIG
+
+dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+dnl -------------------------------------------------------------------
+dnl Since: 0.18
+dnl
+dnl Check to see whether a particular set of modules exists. Similar to
+dnl PKG_CHECK_MODULES(), but does not set variables or print errors.
+dnl
+dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+dnl only at the first occurrence in configure.ac, so if the first place
+dnl it's called might be skipped (such as if it is within an "if", you
+dnl have to call PKG_CHECK_EXISTS manually
+AC_DEFUN([PKG_CHECK_EXISTS],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+if test -n "$PKG_CONFIG" && \
+    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
+  m4_default([$2], [:])
+m4_ifvaln([$3], [else
+  $3])dnl
+fi])
+
+dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
+dnl ---------------------------------------------
+dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting
+dnl pkg_failed based on the result.
+m4_define([_PKG_CONFIG],
+[if test -n "$$1"; then
+    pkg_cv_[]$1="$$1"
+ elif test -n "$PKG_CONFIG"; then
+    PKG_CHECK_EXISTS([$3],
+                     [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
+		      test "x$?" != "x0" && pkg_failed=yes ],
+		     [pkg_failed=yes])
+ else
+    pkg_failed=untried
+fi[]dnl
+])dnl _PKG_CONFIG
+
+dnl _PKG_SHORT_ERRORS_SUPPORTED
+dnl ---------------------------
+dnl Internal check to see if pkg-config supports short errors.
+AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
+        _pkg_short_errors_supported=yes
+else
+        _pkg_short_errors_supported=no
+fi[]dnl
+])dnl _PKG_SHORT_ERRORS_SUPPORTED
+
+
+dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+dnl   [ACTION-IF-NOT-FOUND])
+dnl --------------------------------------------------------------
+dnl Since: 0.4.0
+dnl
+dnl Note that if there is a possibility the first call to
+dnl PKG_CHECK_MODULES might not happen, you should be sure to include an
+dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
+AC_DEFUN([PKG_CHECK_MODULES],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
+AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
+
+pkg_failed=no
+AC_MSG_CHECKING([for $2])
+
+_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
+_PKG_CONFIG([$1][_LIBS], [libs], [$2])
+
+m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
+and $1[]_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details.])
+
+if test $pkg_failed = yes; then
+        AC_MSG_RESULT([no])
+        _PKG_SHORT_ERRORS_SUPPORTED
+        if test $_pkg_short_errors_supported = yes; then
+	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
+        else
+	        $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
+        fi
+	# Put the nasty error message in config.log where it belongs
+	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
+
+	m4_default([$4], [AC_MSG_ERROR(
+[Package requirements ($2) were not met:
+
+$$1_PKG_ERRORS
+
+Consider adjusting the PKG_CONFIG_PATH environment variable if you
+installed software in a non-standard prefix.
+
+_PKG_TEXT])[]dnl
+        ])
+elif test $pkg_failed = untried; then
+        AC_MSG_RESULT([no])
+	m4_default([$4], [AC_MSG_FAILURE(
+[The pkg-config script could not be found or is too old.  Make sure it
+is in your PATH or set the PKG_CONFIG environment variable to the full
+path to pkg-config.
+
+_PKG_TEXT
+
+To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl
+        ])
+else
+	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
+	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
+        AC_MSG_RESULT([yes])
+	$3
+fi[]dnl
+])dnl PKG_CHECK_MODULES
+
+
+dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+dnl   [ACTION-IF-NOT-FOUND])
+dnl ---------------------------------------------------------------------
+dnl Since: 0.29
+dnl
+dnl Checks for existence of MODULES and gathers its build flags with
+dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags
+dnl and VARIABLE-PREFIX_LIBS from --libs.
+dnl
+dnl Note that if there is a possibility the first call to
+dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to
+dnl include an explicit call to PKG_PROG_PKG_CONFIG in your
+dnl configure.ac.
+AC_DEFUN([PKG_CHECK_MODULES_STATIC],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+_save_PKG_CONFIG=$PKG_CONFIG
+PKG_CONFIG="$PKG_CONFIG --static"
+PKG_CHECK_MODULES($@)
+PKG_CONFIG=$_save_PKG_CONFIG[]dnl
+])dnl PKG_CHECK_MODULES_STATIC
+
+
+dnl PKG_INSTALLDIR([DIRECTORY])
+dnl -------------------------
+dnl Since: 0.27
+dnl
+dnl Substitutes the variable pkgconfigdir as the location where a module
+dnl should install pkg-config .pc files. By default the directory is
+dnl $libdir/pkgconfig, but the default can be changed by passing
+dnl DIRECTORY. The user can override through the --with-pkgconfigdir
+dnl parameter.
+AC_DEFUN([PKG_INSTALLDIR],
+[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
+m4_pushdef([pkg_description],
+    [pkg-config installation directory @<:@]pkg_default[@:>@])
+AC_ARG_WITH([pkgconfigdir],
+    [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
+    [with_pkgconfigdir=]pkg_default)
+AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
+m4_popdef([pkg_default])
+m4_popdef([pkg_description])
+])dnl PKG_INSTALLDIR
+
+
+dnl PKG_NOARCH_INSTALLDIR([DIRECTORY])
+dnl --------------------------------
+dnl Since: 0.27
+dnl
+dnl Substitutes the variable noarch_pkgconfigdir as the location where a
+dnl module should install arch-independent pkg-config .pc files. By
+dnl default the directory is $datadir/pkgconfig, but the default can be
+dnl changed by passing DIRECTORY. The user can override through the
+dnl --with-noarch-pkgconfigdir parameter.
+AC_DEFUN([PKG_NOARCH_INSTALLDIR],
+[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
+m4_pushdef([pkg_description],
+    [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
+AC_ARG_WITH([noarch-pkgconfigdir],
+    [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
+    [with_noarch_pkgconfigdir=]pkg_default)
+AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
+m4_popdef([pkg_default])
+m4_popdef([pkg_description])
+])dnl PKG_NOARCH_INSTALLDIR
+
+
+dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
+dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+dnl -------------------------------------------
+dnl Since: 0.28
+dnl
+dnl Retrieves the value of the pkg-config variable for the given module.
+AC_DEFUN([PKG_CHECK_VAR],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
+
+_PKG_CONFIG([$1], [variable="][$3]["], [$2])
+AS_VAR_COPY([$1], [pkg_cv_][$1])
+
+AS_VAR_IF([$1], [""], [$5], [$4])dnl
+])dnl PKG_CHECK_VAR
diff --git a/m4/printf-posix.m4 b/m4/printf-posix.m4
new file mode 100644
index 0000000..f9088c0
--- /dev/null
+++ b/m4/printf-posix.m4
@@ -0,0 +1,48 @@
+# printf-posix.m4 serial 6 (gettext-0.18.2)
+dnl Copyright (C) 2003, 2007, 2009-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+dnl Test whether the printf() function supports POSIX/XSI format strings with
+dnl positions.
+
+AC_DEFUN([gt_PRINTF_POSIX],
+[
+  AC_REQUIRE([AC_PROG_CC])
+  AC_CACHE_CHECK([whether printf() supports POSIX/XSI format strings],
+    gt_cv_func_printf_posix,
+    [
+      AC_RUN_IFELSE(
+        [AC_LANG_SOURCE([[
+#include <stdio.h>
+#include <string.h>
+/* The string "%2$d %1$d", with dollar characters protected from the shell's
+   dollar expansion (possibly an autoconf bug).  */
+static char format[] = { '%', '2', '$', 'd', ' ', '%', '1', '$', 'd', '\0' };
+static char buf[100];
+int main ()
+{
+  sprintf (buf, format, 33, 55);
+  return (strcmp (buf, "55 33") != 0);
+}]])],
+        [gt_cv_func_printf_posix=yes],
+        [gt_cv_func_printf_posix=no],
+        [
+          AC_EGREP_CPP([notposix], [
+#if defined __NetBSD__ || defined __BEOS__ || defined _MSC_VER || defined __MINGW32__ || defined __CYGWIN__
+  notposix
+#endif
+            ],
+            [gt_cv_func_printf_posix="guessing no"],
+            [gt_cv_func_printf_posix="guessing yes"])
+        ])
+    ])
+  case $gt_cv_func_printf_posix in
+    *yes)
+      AC_DEFINE([HAVE_POSIX_PRINTF], [1],
+        [Define if your printf() function supports format strings with positions.])
+      ;;
+  esac
+])
diff --git a/m4/size_max.m4 b/m4/size_max.m4
new file mode 100644
index 0000000..1d41ce9
--- /dev/null
+++ b/m4/size_max.m4
@@ -0,0 +1,75 @@
+# size_max.m4 serial 12
+dnl Copyright (C) 2003, 2005-2006, 2008-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_PREREQ([2.61])
+
+AC_DEFUN([gl_SIZE_MAX],
+[
+  AC_CHECK_HEADERS([stdint.h])
+  dnl First test whether the system already has SIZE_MAX.
+  AC_CACHE_CHECK([for SIZE_MAX], [gl_cv_size_max], [
+    gl_cv_size_max=no
+    AC_EGREP_CPP([Found it], [
+#include <limits.h>
+#if HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#ifdef SIZE_MAX
+Found it
+#endif
+], [gl_cv_size_max=yes])
+    if test $gl_cv_size_max != yes; then
+      dnl Define it ourselves. Here we assume that the type 'size_t' is not wider
+      dnl than the type 'unsigned long'. Try hard to find a definition that can
+      dnl be used in a preprocessor #if, i.e. doesn't contain a cast.
+      AC_COMPUTE_INT([size_t_bits_minus_1], [sizeof (size_t) * CHAR_BIT - 1],
+        [#include <stddef.h>
+#include <limits.h>], [size_t_bits_minus_1=])
+      AC_COMPUTE_INT([fits_in_uint], [sizeof (size_t) <= sizeof (unsigned int)],
+        [#include <stddef.h>], [fits_in_uint=])
+      if test -n "$size_t_bits_minus_1" && test -n "$fits_in_uint"; then
+        if test $fits_in_uint = 1; then
+          dnl Even though SIZE_MAX fits in an unsigned int, it must be of type
+          dnl 'unsigned long' if the type 'size_t' is the same as 'unsigned long'.
+          AC_COMPILE_IFELSE(
+            [AC_LANG_PROGRAM(
+               [[#include <stddef.h>
+                 extern size_t foo;
+                 extern unsigned long foo;
+               ]],
+               [[]])],
+            [fits_in_uint=0])
+        fi
+        dnl We cannot use 'expr' to simplify this expression, because 'expr'
+        dnl works only with 'long' integers in the host environment, while we
+        dnl might be cross-compiling from a 32-bit platform to a 64-bit platform.
+        if test $fits_in_uint = 1; then
+          gl_cv_size_max="(((1U << $size_t_bits_minus_1) - 1) * 2 + 1)"
+        else
+          gl_cv_size_max="(((1UL << $size_t_bits_minus_1) - 1) * 2 + 1)"
+        fi
+      else
+        dnl Shouldn't happen, but who knows...
+        gl_cv_size_max='((size_t)~(size_t)0)'
+      fi
+    fi
+  ])
+  if test "$gl_cv_size_max" != yes; then
+    AC_DEFINE_UNQUOTED([SIZE_MAX], [$gl_cv_size_max],
+      [Define as the maximum value of type 'size_t', if the system doesn't define it.])
+  fi
+  dnl Don't redefine SIZE_MAX in config.h if config.h is re-included after
+  dnl <stdint.h>. Remember that the #undef in AH_VERBATIM gets replaced with
+  dnl #define by AC_DEFINE_UNQUOTED.
+  AH_VERBATIM([SIZE_MAX],
+[/* Define as the maximum value of type 'size_t', if the system doesn't define
+   it. */
+#ifndef SIZE_MAX
+# undef SIZE_MAX
+#endif])
+])
diff --git a/m4/stdint_h.m4 b/m4/stdint_h.m4
new file mode 100644
index 0000000..f823b94
--- /dev/null
+++ b/m4/stdint_h.m4
@@ -0,0 +1,27 @@
+# stdint_h.m4 serial 9
+dnl Copyright (C) 1997-2004, 2006, 2008-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Paul Eggert.
+
+# Define HAVE_STDINT_H_WITH_UINTMAX if <stdint.h> exists,
+# doesn't clash with <sys/types.h>, and declares uintmax_t.
+
+AC_DEFUN([gl_AC_HEADER_STDINT_H],
+[
+  AC_CACHE_CHECK([for stdint.h], [gl_cv_header_stdint_h],
+    [AC_COMPILE_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <sys/types.h>
+            #include <stdint.h>]],
+          [[uintmax_t i = (uintmax_t) -1; return !i;]])],
+       [gl_cv_header_stdint_h=yes],
+       [gl_cv_header_stdint_h=no])])
+  if test $gl_cv_header_stdint_h = yes; then
+    AC_DEFINE_UNQUOTED([HAVE_STDINT_H_WITH_UINTMAX], [1],
+      [Define if <stdint.h> exists, doesn't clash with <sys/types.h>,
+       and declares uintmax_t. ])
+  fi
+])
diff --git a/m4/threadlib.m4 b/m4/threadlib.m4
new file mode 100644
index 0000000..20b383a
--- /dev/null
+++ b/m4/threadlib.m4
@@ -0,0 +1,622 @@
+# threadlib.m4 serial 29
+dnl Copyright (C) 2005-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_PREREQ([2.60])
+
+dnl The general structure of the multithreading modules in gnulib is that we
+dnl have three set of modules:
+dnl
+dnl   * POSIX API:
+dnl     pthread, which combines
+dnl       pthread-h
+dnl       pthread-thread
+dnl       pthread-once
+dnl       pthread-mutex
+dnl       pthread-rwlock
+dnl       pthread-cond
+dnl       pthread-tss
+dnl       pthread-spin
+dnl     sched_yield
+dnl
+dnl   * ISO C API:
+dnl     threads, which combines
+dnl       threads-h
+dnl       thrd
+dnl       mtx
+dnl       cnd
+dnl       tss
+dnl
+dnl   * Gnulib API, with an implementation that can be chosen at configure
+dnl     time through the option --enable-threads=...
+dnl       thread
+dnl       lock
+dnl       cond
+dnl       tls
+dnl       yield
+dnl
+dnl They are independent, except for the fact that
+dnl   - the implementation of the ISO C API may use the POSIX (or some other
+dnl     platform dependent) API,
+dnl   - the implementation of the Gnulib API may use the POSIX or ISO C or
+dnl     some other platform dependent API, depending on the --enable-threads
+dnl     option.
+dnl
+dnl This file contains macros for all of these APIs!
+
+dnl ============================================================================
+dnl Macros for all thread APIs
+
+AC_DEFUN([gl_ANYTHREADLIB_EARLY],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  if test -z "$gl_anythreadlib_early_done"; then
+    case "$host_os" in
+      osf*)
+        # On OSF/1, the compiler needs the flag -D_REENTRANT so that it
+        # groks <pthread.h>. cc also understands the flag -pthread, but
+        # we don't use it because 1. gcc-2.95 doesn't understand -pthread,
+        # 2. putting a flag into CPPFLAGS that has an effect on the linker
+        # causes the AC_LINK_IFELSE test below to succeed unexpectedly,
+        # leading to wrong values of LIBTHREAD and LTLIBTHREAD.
+        CPPFLAGS="$CPPFLAGS -D_REENTRANT"
+        ;;
+    esac
+    # Some systems optimize for single-threaded programs by default, and
+    # need special flags to disable these optimizations. For example, the
+    # definition of 'errno' in <errno.h>.
+    case "$host_os" in
+      aix* | freebsd*) CPPFLAGS="$CPPFLAGS -D_THREAD_SAFE" ;;
+      solaris*) CPPFLAGS="$CPPFLAGS -D_REENTRANT" ;;
+    esac
+    gl_anythreadlib_early_done=done
+  fi
+])
+
+dnl Checks whether the compiler and linker support weak declarations of symbols.
+
+AC_DEFUN([gl_WEAK_SYMBOLS],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  AC_CACHE_CHECK([whether imported symbols can be declared weak],
+    [gl_cv_have_weak],
+    [gl_cv_have_weak=no
+     dnl First, test whether the compiler accepts it syntactically.
+     AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[extern void xyzzy ();
+#pragma weak xyzzy]],
+          [[xyzzy();]])],
+       [gl_cv_have_weak=maybe])
+     if test $gl_cv_have_weak = maybe; then
+       dnl Second, test whether it actually works. On Cygwin 1.7.2, with
+       dnl gcc 4.3, symbols declared weak always evaluate to the address 0.
+       AC_RUN_IFELSE(
+         [AC_LANG_SOURCE([[
+#include <stdio.h>
+#pragma weak fputs
+int main ()
+{
+  return (fputs == NULL);
+}]])],
+         [gl_cv_have_weak=yes],
+         [gl_cv_have_weak=no],
+         [dnl When cross-compiling, assume that only ELF platforms support
+          dnl weak symbols.
+          AC_EGREP_CPP([Extensible Linking Format],
+            [#ifdef __ELF__
+             Extensible Linking Format
+             #endif
+            ],
+            [gl_cv_have_weak="guessing yes"],
+            [gl_cv_have_weak="guessing no"])
+         ])
+     fi
+     dnl But when linking statically, weak symbols don't work.
+     case " $LDFLAGS " in
+       *" -static "*) gl_cv_have_weak=no ;;
+     esac
+     dnl Test for a bug in FreeBSD 11: A link error occurs when using a weak
+     dnl symbol and linking against a shared library that has a dependency on
+     dnl the shared library that defines the symbol.
+     case "$gl_cv_have_weak" in
+       *yes)
+         case "$host_os" in
+           freebsd* | dragonfly*)
+             : > conftest1.c
+             $CC $CPPFLAGS $CFLAGS $LDFLAGS -fPIC -shared -o libempty.so conftest1.c -lpthread >&AS_MESSAGE_LOG_FD 2>&1
+             cat <<EOF > conftest2.c
+#include <pthread.h>
+#pragma weak pthread_mutexattr_gettype
+int main ()
+{
+  return (pthread_mutexattr_gettype != NULL);
+}
+EOF
+             $CC $CPPFLAGS $CFLAGS $LDFLAGS -o conftest conftest2.c libempty.so >&AS_MESSAGE_LOG_FD 2>&1 \
+               || gl_cv_have_weak=no
+             rm -f conftest1.c libempty.so conftest2.c conftest
+             ;;
+         esac
+         ;;
+     esac
+    ])
+  case "$gl_cv_have_weak" in
+    *yes)
+      AC_DEFINE([HAVE_WEAK_SYMBOLS], [1],
+        [Define to 1 if the compiler and linker support weak declarations of symbols.])
+      ;;
+  esac
+])
+
+dnl ============================================================================
+dnl Macros for the POSIX API
+
+dnl gl_PTHREADLIB
+dnl -------------
+dnl Tests for the libraries needs for using the POSIX threads API.
+dnl Sets the variable LIBPTHREAD to the linker options for use in a Makefile.
+dnl Sets the variable LIBPMULTITHREAD, for programs that really need
+dnl multithread functionality. The difference between LIBPTHREAD and
+dnl LIBPMULTITHREAD is that on platforms supporting weak symbols, typically
+dnl LIBPTHREAD is empty whereas LIBPMULTITHREAD is not.
+dnl Sets the variable LIB_SCHED_YIELD to the linker options needed to use the
+dnl sched_yield() function.
+dnl Adds to CPPFLAGS the flag -D_REENTRANT or -D_THREAD_SAFE if needed for
+dnl multithread-safe programs.
+dnl Defines the C macro HAVE_PTHREAD_API if (at least parts of) the POSIX
+dnl threads API is available.
+
+dnl The guts of gl_PTHREADLIB. Needs to be expanded only once.
+
+AC_DEFUN([gl_PTHREADLIB_BODY],
+[
+  AC_REQUIRE([gl_ANYTHREADLIB_EARLY])
+  if test -z "$gl_pthreadlib_body_done"; then
+    gl_pthread_api=no
+    LIBPTHREAD=
+    LIBPMULTITHREAD=
+    # On OSF/1, the compiler needs the flag -pthread or -D_REENTRANT so that
+    # it groks <pthread.h>. It's added above, in gl_ANYTHREADLIB_EARLY.
+    AC_CHECK_HEADER([pthread.h],
+      [gl_have_pthread_h=yes], [gl_have_pthread_h=no])
+    if test "$gl_have_pthread_h" = yes; then
+      # Other possible tests:
+      #   -lpthreads (FSU threads, PCthreads)
+      #   -lgthreads
+      # Test whether both pthread_mutex_lock and pthread_mutexattr_init exist
+      # in libc. IRIX 6.5 has the first one in both libc and libpthread, but
+      # the second one only in libpthread, and lock.c needs it.
+      #
+      # If -pthread works, prefer it to -lpthread, since Ubuntu 14.04
+      # needs -pthread for some reason.  See:
+      # https://lists.gnu.org/r/bug-gnulib/2014-09/msg00023.html
+      save_LIBS=$LIBS
+      for gl_pthread in '' '-pthread'; do
+        LIBS="$LIBS $gl_pthread"
+        AC_LINK_IFELSE(
+          [AC_LANG_PROGRAM(
+             [[#include <pthread.h>
+               pthread_mutex_t m;
+               pthread_mutexattr_t ma;
+             ]],
+             [[pthread_mutex_lock (&m);
+               pthread_mutexattr_init (&ma);]])],
+          [gl_pthread_api=yes
+           LIBPTHREAD=$gl_pthread
+           LIBPMULTITHREAD=$gl_pthread])
+        LIBS=$save_LIBS
+        test $gl_pthread_api = yes && break
+      done
+
+      # Test for libpthread by looking for pthread_kill. (Not pthread_self,
+      # since it is defined as a macro on OSF/1.)
+      if test $gl_pthread_api = yes && test -z "$LIBPTHREAD"; then
+        # The program links fine without libpthread. But it may actually
+        # need to link with libpthread in order to create multiple threads.
+        AC_CHECK_LIB([pthread], [pthread_kill],
+          [LIBPMULTITHREAD=-lpthread
+           # On Solaris and HP-UX, most pthread functions exist also in libc.
+           # Therefore pthread_in_use() needs to actually try to create a
+           # thread: pthread_create from libc will fail, whereas
+           # pthread_create will actually create a thread.
+           # On Solaris 10 or newer, this test is no longer needed, because
+           # libc contains the fully functional pthread functions.
+           case "$host_os" in
+             solaris | solaris2.[1-9] | solaris2.[1-9].* | hpux*)
+               AC_DEFINE([PTHREAD_IN_USE_DETECTION_HARD], [1],
+                 [Define if the pthread_in_use() detection is hard.])
+           esac
+          ])
+      elif test $gl_pthread_api != yes; then
+        # Some library is needed. Try libpthread and libc_r.
+        AC_CHECK_LIB([pthread], [pthread_kill],
+          [gl_pthread_api=yes
+           LIBPTHREAD=-lpthread
+           LIBPMULTITHREAD=-lpthread])
+        if test $gl_pthread_api != yes; then
+          # For FreeBSD 4.
+          AC_CHECK_LIB([c_r], [pthread_kill],
+            [gl_pthread_api=yes
+             LIBPTHREAD=-lc_r
+             LIBPMULTITHREAD=-lc_r])
+        fi
+      fi
+    fi
+    AC_MSG_CHECKING([whether POSIX threads API is available])
+    AC_MSG_RESULT([$gl_pthread_api])
+    AC_SUBST([LIBPTHREAD])
+    AC_SUBST([LIBPMULTITHREAD])
+    if test $gl_pthread_api = yes; then
+      AC_DEFINE([HAVE_PTHREAD_API], [1],
+        [Define if you have the <pthread.h> header and the POSIX threads API.])
+    fi
+
+    dnl On some systems, sched_yield is in librt, rather than in libpthread.
+    AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM(
+         [[#include <sched.h>]],
+         [[sched_yield ();]])],
+      [LIB_SCHED_YIELD=
+      ],
+      [dnl Solaris 7...10 has sched_yield in librt, not in libpthread or libc.
+       AC_CHECK_LIB([rt], [sched_yield], [LIB_SCHED_YIELD=-lrt],
+         [dnl Solaris 2.5.1, 2.6 has sched_yield in libposix4, not librt.
+          AC_CHECK_LIB([posix4], [sched_yield], [LIB_SCHED_YIELD=-lposix4])])
+      ])
+    AC_SUBST([LIB_SCHED_YIELD])
+
+    gl_pthreadlib_body_done=done
+  fi
+])
+
+AC_DEFUN([gl_PTHREADLIB],
+[
+  AC_REQUIRE([gl_ANYTHREADLIB_EARLY])
+  gl_PTHREADLIB_BODY
+])
+
+dnl ============================================================================
+dnl Macros for the ISO C API
+
+dnl gl_STDTHREADLIB
+dnl ---------------
+dnl Tests for the libraries needs for using the ISO C threads API.
+dnl Sets the variable LIBSTDTHREAD to the linker options for use in a Makefile.
+dnl Adds to CPPFLAGS the flag -D_REENTRANT or -D_THREAD_SAFE if needed for
+dnl multithread-safe programs.
+dnl Defines the C macro HAVE_THREADS_H if (at least parts of) the ISO C threads
+dnl API is available.
+
+dnl The guts of gl_STDTHREADLIB. Needs to be expanded only once.
+
+AC_DEFUN([gl_STDTHREADLIB_BODY],
+[
+  AC_REQUIRE([gl_ANYTHREADLIB_EARLY])
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  if test -z "$gl_stdthreadlib_body_done"; then
+    AC_CHECK_HEADERS_ONCE([threads.h])
+
+    case "$host_os" in
+      mingw*)
+        LIBSTDTHREAD=
+        ;;
+      *)
+        gl_PTHREADLIB_BODY
+        if test $ac_cv_header_threads_h = yes; then
+          dnl glibc >= 2.29 has thrd_create in libpthread.
+          dnl FreeBSD >= 10 has thrd_create in libstdthreads; this library depends
+          dnl on libpthread (for the symbol 'pthread_mutexattr_gettype').
+          dnl AIX >= 7.1 and Solaris >= 11.4 have thrd_create in libc.
+          AC_CHECK_FUNCS([thrd_create])
+          if test $ac_cv_func_thrd_create = yes; then
+            LIBSTDTHREAD=
+          else
+            AC_CHECK_LIB([stdthreads], [thrd_create], [
+              LIBSTDTHREAD='-lstdthreads -lpthread'
+            ], [
+              dnl Guess that thrd_create is in libpthread.
+              LIBSTDTHREAD="$LIBPMULTITHREAD"
+            ])
+          fi
+        else
+          dnl Libraries needed by thrd.c, mtx.c, cnd.c, tss.c.
+          LIBSTDTHREAD="$LIBPMULTITHREAD $LIB_SCHED_YIELD"
+        fi
+        ;;
+    esac
+    AC_SUBST([LIBSTDTHREAD])
+
+    AC_MSG_CHECKING([whether ISO C threads API is available])
+    AC_MSG_RESULT([$ac_cv_header_threads_h])
+    gl_stdthreadlib_body_done=done
+  fi
+])
+
+AC_DEFUN([gl_STDTHREADLIB],
+[
+  AC_REQUIRE([gl_ANYTHREADLIB_EARLY])
+  gl_STDTHREADLIB_BODY
+])
+
+dnl ============================================================================
+dnl Macros for the Gnulib API
+
+dnl gl_THREADLIB
+dnl ------------
+dnl Tests for a multithreading library to be used.
+dnl If the configure.ac contains a definition of the gl_THREADLIB_DEFAULT_NO
+dnl (it must be placed before the invocation of gl_THREADLIB_EARLY!), then the
+dnl default is 'no', otherwise it is system dependent. In both cases, the user
+dnl can change the choice through the options --enable-threads=choice or
+dnl --disable-threads.
+dnl Defines at most one of the macros USE_ISOC_THREADS, USE_POSIX_THREADS,
+dnl USE_ISOC_AND_POSIX_THREADS, USE_WINDOWS_THREADS.
+dnl The choice --enable-threads=isoc+posix is available only on platforms that
+dnl have both the ISO C and the POSIX threads APIs. It has the effect of using
+dnl the ISO C API for most things and the POSIX API only for creating and
+dnl controlling threads (because there is no equivalent to pthread_atfork in
+dnl the ISO C API).
+dnl Sets the variables LIBTHREAD and LTLIBTHREAD to the linker options for use
+dnl in a Makefile (LIBTHREAD for use without libtool, LTLIBTHREAD for use with
+dnl libtool).
+dnl Sets the variables LIBMULTITHREAD and LTLIBMULTITHREAD similarly, for
+dnl programs that really need multithread functionality. The difference
+dnl between LIBTHREAD and LIBMULTITHREAD is that on platforms supporting weak
+dnl symbols, typically LIBTHREAD is empty whereas LIBMULTITHREAD is not.
+dnl Adds to CPPFLAGS the flag -D_REENTRANT or -D_THREAD_SAFE if needed for
+dnl multithread-safe programs.
+dnl Since support for GNU pth was removed, $LTLIBTHREAD and $LIBTHREAD have the
+dnl same value, and similarly $LTLIBMULTITHREAD and $LIBMULTITHREAD have the
+dnl same value. Only system libraries are needed.
+
+AC_DEFUN([gl_THREADLIB_EARLY],
+[
+  AC_REQUIRE([gl_THREADLIB_EARLY_BODY])
+])
+
+dnl The guts of gl_THREADLIB_EARLY. Needs to be expanded only once.
+
+AC_DEFUN([gl_THREADLIB_EARLY_BODY],
+[
+  dnl Ordering constraints: This macro modifies CPPFLAGS in a way that
+  dnl influences the result of the autoconf tests that test for *_unlocked
+  dnl declarations, on AIX 5 at least. Therefore it must come early.
+  AC_BEFORE([$0], [gl_FUNC_GLIBC_UNLOCKED_IO])dnl
+  AC_BEFORE([$0], [gl_ARGP])dnl
+
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  dnl _GNU_SOURCE is needed for pthread_rwlock_t on glibc systems.
+  AC_REQUIRE([AC_USE_SYSTEM_EXTENSIONS])
+  dnl Check for multithreading.
+  m4_ifdef([gl_THREADLIB_DEFAULT_NO],
+    [m4_divert_text([DEFAULTS], [gl_use_threads_default=no])],
+    [m4_divert_text([DEFAULTS], [gl_use_threads_default=])])
+  m4_divert_text([DEFAULTS], [gl_use_winpthreads_default=])
+  AC_ARG_ENABLE([threads],
+AS_HELP_STRING([--enable-threads={isoc|posix|isoc+posix|windows}], [specify multithreading API])m4_ifdef([gl_THREADLIB_DEFAULT_NO], [], [
+AS_HELP_STRING([--disable-threads], [build without multithread safety])]),
+    [gl_use_threads=$enableval],
+    [if test -n "$gl_use_threads_default"; then
+       gl_use_threads="$gl_use_threads_default"
+     else
+changequote(,)dnl
+       case "$host_os" in
+         dnl Disable multithreading by default on OSF/1, because it interferes
+         dnl with fork()/exec(): When msgexec is linked with -lpthread, its
+         dnl child process gets an endless segmentation fault inside execvp().
+         osf*) gl_use_threads=no ;;
+         dnl Disable multithreading by default on Cygwin 1.5.x, because it has
+         dnl bugs that lead to endless loops or crashes. See
+         dnl <https://cygwin.com/ml/cygwin/2009-08/msg00283.html>.
+         cygwin*)
+               case `uname -r` in
+                 1.[0-5].*) gl_use_threads=no ;;
+                 *)         gl_use_threads=yes ;;
+               esac
+               ;;
+         dnl Obey gl_AVOID_WINPTHREAD on mingw.
+         mingw*)
+               case "$gl_use_winpthreads_default" in
+                 yes) gl_use_threads=posix ;;
+                 no)  gl_use_threads=windows ;;
+                 *)   gl_use_threads=yes ;;
+               esac
+               ;;
+         *)    gl_use_threads=yes ;;
+       esac
+changequote([,])dnl
+     fi
+    ])
+  if test "$gl_use_threads" = yes \
+     || test "$gl_use_threads" = isoc \
+     || test "$gl_use_threads" = posix \
+     || test "$gl_use_threads" = isoc+posix; then
+    # For using <threads.h> or <pthread.h>:
+    gl_ANYTHREADLIB_EARLY
+  fi
+])
+
+dnl The guts of gl_THREADLIB. Needs to be expanded only once.
+
+AC_DEFUN([gl_THREADLIB_BODY],
+[
+  AC_REQUIRE([gl_THREADLIB_EARLY_BODY])
+  gl_threads_api=none
+  LIBTHREAD=
+  LTLIBTHREAD=
+  LIBMULTITHREAD=
+  LTLIBMULTITHREAD=
+  if test "$gl_use_threads" != no; then
+    dnl Check whether the compiler and linker support weak declarations.
+    gl_WEAK_SYMBOLS
+    if case "$gl_cv_have_weak" in *yes) true;; *) false;; esac; then
+      dnl If we use weak symbols to implement pthread_in_use / pth_in_use /
+      dnl thread_in_use, we also need to test whether the ISO C 11 thrd_create
+      dnl facility is in use.
+      AC_CHECK_HEADERS_ONCE([threads.h])
+      :
+    fi
+    if test "$gl_use_threads" = isoc || test "$gl_use_threads" = isoc+posix; then
+      AC_CHECK_HEADERS_ONCE([threads.h])
+      gl_have_isoc_threads="$ac_cv_header_threads_h"
+    fi
+    if test "$gl_use_threads" = yes \
+       || test "$gl_use_threads" = posix \
+       || test "$gl_use_threads" = isoc+posix; then
+      gl_PTHREADLIB_BODY
+      LIBTHREAD=$LIBPTHREAD LTLIBTHREAD=$LIBPTHREAD
+      LIBMULTITHREAD=$LIBPMULTITHREAD LTLIBMULTITHREAD=$LIBPMULTITHREAD
+      if test $gl_pthread_api = yes; then
+        if test "$gl_use_threads" = isoc+posix && test "$gl_have_isoc_threads" = yes; then
+          gl_threads_api='isoc+posix'
+          AC_DEFINE([USE_ISOC_AND_POSIX_THREADS], [1],
+            [Define if the combination of the ISO C and POSIX multithreading APIs can be used.])
+          LIBTHREAD= LTLIBTHREAD=
+        else
+          gl_threads_api=posix
+          AC_DEFINE([USE_POSIX_THREADS], [1],
+            [Define if the POSIX multithreading library can be used.])
+          if test -n "$LIBMULTITHREAD" || test -n "$LTLIBMULTITHREAD"; then
+            if case "$gl_cv_have_weak" in *yes) true;; *) false;; esac; then
+              AC_DEFINE([USE_POSIX_THREADS_WEAK], [1],
+                [Define if references to the POSIX multithreading library should be made weak.])
+              LIBTHREAD= LTLIBTHREAD=
+            else
+              case "$host_os" in
+                freebsd* | dragonfly*)
+                  if test "x$LIBTHREAD" != "x$LIBMULTITHREAD"; then
+                    dnl If weak symbols can't tell whether pthread_create(), pthread_key_create()
+                    dnl etc. will succeed, we need a runtime test.
+                    AC_DEFINE([PTHREAD_IN_USE_DETECTION_HARD], [1],
+                      [Define if the pthread_in_use() detection is hard.])
+                  fi
+                  ;;
+              esac
+            fi
+          fi
+        fi
+      fi
+    fi
+    if test $gl_threads_api = none; then
+      if test "$gl_use_threads" = isoc && test "$gl_have_isoc_threads" = yes; then
+        gl_STDTHREADLIB_BODY
+        LIBTHREAD=$LIBSTDTHREAD LTLIBTHREAD=$LIBSTDTHREAD
+        LIBMULTITHREAD=$LIBSTDTHREAD LTLIBMULTITHREAD=$LIBSTDTHREAD
+        gl_threads_api=isoc
+        AC_DEFINE([USE_ISOC_THREADS], [1],
+          [Define if the ISO C multithreading library can be used.])
+      fi
+    fi
+    if test $gl_threads_api = none; then
+      case "$gl_use_threads" in
+        yes | windows | win32) # The 'win32' is for backward compatibility.
+          if { case "$host_os" in
+                 mingw*) true;;
+                 *) false;;
+               esac
+             }; then
+            gl_threads_api=windows
+            AC_DEFINE([USE_WINDOWS_THREADS], [1],
+              [Define if the native Windows multithreading API can be used.])
+          fi
+          ;;
+      esac
+    fi
+  fi
+  AC_MSG_CHECKING([for multithread API to use])
+  AC_MSG_RESULT([$gl_threads_api])
+  AC_SUBST([LIBTHREAD])
+  AC_SUBST([LTLIBTHREAD])
+  AC_SUBST([LIBMULTITHREAD])
+  AC_SUBST([LTLIBMULTITHREAD])
+])
+
+AC_DEFUN([gl_THREADLIB],
+[
+  AC_REQUIRE([gl_THREADLIB_EARLY])
+  AC_REQUIRE([gl_THREADLIB_BODY])
+])
+
+
+dnl gl_DISABLE_THREADS
+dnl ------------------
+dnl Sets the gl_THREADLIB default so that threads are not used by default.
+dnl The user can still override it at installation time, by using the
+dnl configure option '--enable-threads'.
+
+AC_DEFUN([gl_DISABLE_THREADS], [
+  m4_divert_text([INIT_PREPARE], [gl_use_threads_default=no])
+])
+
+
+dnl gl_AVOID_WINPTHREAD
+dnl -------------------
+dnl Sets the gl_THREADLIB default so that on mingw, a dependency to the
+dnl libwinpthread DLL (mingw-w64 winpthreads library) is avoided.
+dnl The user can still override it at installation time, by using the
+dnl configure option '--enable-threads'.
+
+AC_DEFUN([gl_AVOID_WINPTHREAD], [
+  m4_divert_text([INIT_PREPARE], [gl_use_winpthreads_default=no])
+])
+
+
+dnl ============================================================================
+
+
+dnl Survey of platforms:
+dnl
+dnl Platform           Available  Compiler    Supports   test-lock
+dnl                    flavours   option      weak       result
+dnl ---------------    ---------  ---------   --------   ---------
+dnl Linux 2.4/glibc    posix      -lpthread       Y      OK
+dnl
+dnl GNU Hurd/glibc     posix
+dnl
+dnl Ubuntu 14.04       posix      -pthread        Y      OK
+dnl
+dnl FreeBSD 5.3        posix      -lc_r           Y
+dnl                    posix      -lkse ?         Y
+dnl                    posix      -lpthread ?     Y
+dnl                    posix      -lthr           Y
+dnl
+dnl FreeBSD 5.2        posix      -lc_r           Y
+dnl                    posix      -lkse           Y
+dnl                    posix      -lthr           Y
+dnl
+dnl FreeBSD 4.0,4.10   posix      -lc_r           Y      OK
+dnl
+dnl NetBSD 1.6         --
+dnl
+dnl OpenBSD 3.4        posix      -lpthread       Y      OK
+dnl
+dnl Mac OS X 10.[123]  posix      -lpthread       Y      OK
+dnl
+dnl Solaris 7,8,9      posix      -lpthread       Y      Sol 7,8: 0.0; Sol 9: OK
+dnl
+dnl HP-UX 11           posix      -lpthread       N (cc) OK
+dnl                                               Y (gcc)
+dnl
+dnl IRIX 6.5           posix      -lpthread       Y      0.5
+dnl
+dnl AIX 4.3,5.1        posix      -lpthread       N      AIX 4: 0.5; AIX 5: OK
+dnl
+dnl OSF/1 4.0,5.1      posix      -pthread (cc)   N      OK
+dnl                               -lpthread (gcc) Y
+dnl
+dnl Cygwin             posix      -lpthread       Y      OK
+dnl
+dnl Mingw              windows                    N      OK
+dnl
+dnl BeOS 5             --
+dnl
+dnl The test-lock result shows what happens if in test-lock.c EXPLICIT_YIELD is
+dnl turned off:
+dnl   OK if all three tests terminate OK,
+dnl   0.5 if the first test terminates OK but the second one loops endlessly,
+dnl   0.0 if the first test already loops endlessly.
diff --git a/m4/uintmax_t.m4 b/m4/uintmax_t.m4
new file mode 100644
index 0000000..03b51bc
--- /dev/null
+++ b/m4/uintmax_t.m4
@@ -0,0 +1,30 @@
+# uintmax_t.m4 serial 12
+dnl Copyright (C) 1997-2004, 2007-2010 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Paul Eggert.
+
+AC_PREREQ([2.13])
+
+# Define uintmax_t to 'unsigned long' or 'unsigned long long'
+# if it is not already defined in <stdint.h> or <inttypes.h>.
+
+AC_DEFUN([gl_AC_TYPE_UINTMAX_T],
+[
+  AC_REQUIRE([gl_AC_HEADER_INTTYPES_H])
+  AC_REQUIRE([gl_AC_HEADER_STDINT_H])
+  if test $gl_cv_header_inttypes_h = no && test $gl_cv_header_stdint_h = no; then
+    AC_REQUIRE([AC_TYPE_UNSIGNED_LONG_LONG_INT])
+    test $ac_cv_type_unsigned_long_long_int = yes \
+      && ac_type='unsigned long long' \
+      || ac_type='unsigned long'
+    AC_DEFINE_UNQUOTED([uintmax_t], [$ac_type],
+      [Define to unsigned long or unsigned long long
+       if <stdint.h> and <inttypes.h> don't define.])
+  else
+    AC_DEFINE([HAVE_UINTMAX_T], [1],
+      [Define if you have the 'uintmax_t' type in <stdint.h> or <inttypes.h>.])
+  fi
+])
diff --git a/m4/visibility.m4 b/m4/visibility.m4
new file mode 100644
index 0000000..6e4b461
--- /dev/null
+++ b/m4/visibility.m4
@@ -0,0 +1,77 @@
+# visibility.m4 serial 6
+dnl Copyright (C) 2005, 2008, 2010-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+dnl Tests whether the compiler supports the command-line option
+dnl -fvisibility=hidden and the function and variable attributes
+dnl __attribute__((__visibility__("hidden"))) and
+dnl __attribute__((__visibility__("default"))).
+dnl Does *not* test for __visibility__("protected") - which has tricky
+dnl semantics (see the 'vismain' test in glibc) and does not exist e.g. on
+dnl Mac OS X.
+dnl Does *not* test for __visibility__("internal") - which has processor
+dnl dependent semantics.
+dnl Does *not* test for #pragma GCC visibility push(hidden) - which is
+dnl "really only recommended for legacy code".
+dnl Set the variable CFLAG_VISIBILITY.
+dnl Defines and sets the variable HAVE_VISIBILITY.
+
+AC_DEFUN([gl_VISIBILITY],
+[
+  AC_REQUIRE([AC_PROG_CC])
+  CFLAG_VISIBILITY=
+  HAVE_VISIBILITY=0
+  if test -n "$GCC"; then
+    dnl First, check whether -Werror can be added to the command line, or
+    dnl whether it leads to an error because of some other option that the
+    dnl user has put into $CC $CFLAGS $CPPFLAGS.
+    AC_CACHE_CHECK([whether the -Werror option is usable],
+      [gl_cv_cc_vis_werror],
+      [gl_save_CFLAGS="$CFLAGS"
+       CFLAGS="$CFLAGS -Werror"
+       AC_COMPILE_IFELSE(
+         [AC_LANG_PROGRAM([[]], [[]])],
+         [gl_cv_cc_vis_werror=yes],
+         [gl_cv_cc_vis_werror=no])
+       CFLAGS="$gl_save_CFLAGS"
+      ])
+    dnl Now check whether visibility declarations are supported.
+    AC_CACHE_CHECK([for simple visibility declarations],
+      [gl_cv_cc_visibility],
+      [gl_save_CFLAGS="$CFLAGS"
+       CFLAGS="$CFLAGS -fvisibility=hidden"
+       dnl We use the option -Werror and a function dummyfunc, because on some
+       dnl platforms (Cygwin 1.7) the use of -fvisibility triggers a warning
+       dnl "visibility attribute not supported in this configuration; ignored"
+       dnl at the first function definition in every compilation unit, and we
+       dnl don't want to use the option in this case.
+       if test $gl_cv_cc_vis_werror = yes; then
+         CFLAGS="$CFLAGS -Werror"
+       fi
+       AC_COMPILE_IFELSE(
+         [AC_LANG_PROGRAM(
+            [[extern __attribute__((__visibility__("hidden"))) int hiddenvar;
+              extern __attribute__((__visibility__("default"))) int exportedvar;
+              extern __attribute__((__visibility__("hidden"))) int hiddenfunc (void);
+              extern __attribute__((__visibility__("default"))) int exportedfunc (void);
+              void dummyfunc (void) {}
+            ]],
+            [[]])],
+         [gl_cv_cc_visibility=yes],
+         [gl_cv_cc_visibility=no])
+       CFLAGS="$gl_save_CFLAGS"
+      ])
+    if test $gl_cv_cc_visibility = yes; then
+      CFLAG_VISIBILITY="-fvisibility=hidden"
+      HAVE_VISIBILITY=1
+    fi
+  fi
+  AC_SUBST([CFLAG_VISIBILITY])
+  AC_SUBST([HAVE_VISIBILITY])
+  AC_DEFINE_UNQUOTED([HAVE_VISIBILITY], [$HAVE_VISIBILITY],
+    [Define to 1 or 0, depending whether the compiler supports simple visibility declarations.])
+])
diff --git a/m4/wchar_t.m4 b/m4/wchar_t.m4
new file mode 100644
index 0000000..2db8c3f
--- /dev/null
+++ b/m4/wchar_t.m4
@@ -0,0 +1,24 @@
+# wchar_t.m4 serial 4 (gettext-0.18.2)
+dnl Copyright (C) 2002-2003, 2008-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+dnl Test whether <stddef.h> has the 'wchar_t' type.
+dnl Prerequisite: AC_PROG_CC
+
+AC_DEFUN([gt_TYPE_WCHAR_T],
+[
+  AC_CACHE_CHECK([for wchar_t], [gt_cv_c_wchar_t],
+    [AC_COMPILE_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <stddef.h>
+            wchar_t foo = (wchar_t)'\0';]],
+          [[]])],
+       [gt_cv_c_wchar_t=yes],
+       [gt_cv_c_wchar_t=no])])
+  if test $gt_cv_c_wchar_t = yes; then
+    AC_DEFINE([HAVE_WCHAR_T], [1], [Define if you have the 'wchar_t' type.])
+  fi
+])
diff --git a/m4/wint_t.m4 b/m4/wint_t.m4
new file mode 100644
index 0000000..2fc7467
--- /dev/null
+++ b/m4/wint_t.m4
@@ -0,0 +1,57 @@
+# wint_t.m4 serial 10
+dnl Copyright (C) 2003, 2007-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+dnl Test whether <wchar.h> has the 'wint_t' type and whether gnulib's
+dnl <wchar.h> or <wctype.h> would, if present, override 'wint_t'.
+dnl Prerequisite: AC_PROG_CC
+
+AC_DEFUN([gt_TYPE_WINT_T],
+[
+  AC_CACHE_CHECK([for wint_t], [gt_cv_c_wint_t],
+    [AC_COMPILE_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <wchar.h>
+            wint_t foo = (wchar_t)'\0';]],
+          [[]])],
+       [gt_cv_c_wint_t=yes],
+       [gt_cv_c_wint_t=no])])
+  if test $gt_cv_c_wint_t = yes; then
+    AC_DEFINE([HAVE_WINT_T], [1], [Define if you have the 'wint_t' type.])
+
+    dnl Determine whether gnulib's <wchar.h> or <wctype.h> would, if present,
+    dnl override 'wint_t'.
+    AC_CACHE_CHECK([whether wint_t is large enough],
+      [gl_cv_type_wint_t_large_enough],
+      [AC_COMPILE_IFELSE(
+         [AC_LANG_PROGRAM(
+            [[#include <wchar.h>
+              int verify[sizeof (wint_t) < sizeof (int) ? -1 : 1];
+            ]])],
+         [gl_cv_type_wint_t_large_enough=yes],
+         [gl_cv_type_wint_t_large_enough=no])])
+    if test $gl_cv_type_wint_t_large_enough = no; then
+      GNULIB_OVERRIDES_WINT_T=1
+    else
+      GNULIB_OVERRIDES_WINT_T=0
+    fi
+  else
+    GNULIB_OVERRIDES_WINT_T=0
+  fi
+  AC_SUBST([GNULIB_OVERRIDES_WINT_T])
+])
+
+dnl Prerequisites of the 'wint_t' override.
+AC_DEFUN([gl_TYPE_WINT_T_PREREQ],
+[
+  AC_CHECK_HEADERS_ONCE([crtdefs.h])
+  if test $ac_cv_header_crtdefs_h = yes; then
+    HAVE_CRTDEFS_H=1
+  else
+    HAVE_CRTDEFS_H=0
+  fi
+  AC_SUBST([HAVE_CRTDEFS_H])
+])
diff --git a/m4/xsize.m4 b/m4/xsize.m4
new file mode 100644
index 0000000..16764e8
--- /dev/null
+++ b/m4/xsize.m4
@@ -0,0 +1,12 @@
+# xsize.m4 serial 5
+dnl Copyright (C) 2003-2004, 2008-2016 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+AC_DEFUN([gl_XSIZE],
+[
+  dnl Prerequisites of lib/xsize.h.
+  AC_REQUIRE([gl_SIZE_MAX])
+  AC_CHECK_HEADERS([stdint.h])
+])
diff --git a/missing b/missing
deleted file mode 100755
index db98974..0000000
--- a/missing
+++ /dev/null
@@ -1,215 +0,0 @@
-#! /bin/sh
-# Common wrapper for a few potentially missing GNU programs.
-
-scriptversion=2013-10-28.13; # UTC
-
-# Copyright (C) 1996-2013 Free Software Foundation, Inc.
-# Originally written by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
-
-# 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 2, 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/>.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-if test $# -eq 0; then
-  echo 1>&2 "Try '$0 --help' for more information"
-  exit 1
-fi
-
-case $1 in
-
-  --is-lightweight)
-    # Used by our autoconf macros to check whether the available missing
-    # script is modern enough.
-    exit 0
-    ;;
-
-  --run)
-    # Back-compat with the calling convention used by older automake.
-    shift
-    ;;
-
-  -h|--h|--he|--hel|--help)
-    echo "\
-$0 [OPTION]... PROGRAM [ARGUMENT]...
-
-Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due
-to PROGRAM being missing or too old.
-
-Options:
-  -h, --help      display this help and exit
-  -v, --version   output version information and exit
-
-Supported PROGRAM values:
-  aclocal   autoconf  autoheader   autom4te  automake  makeinfo
-  bison     yacc      flex         lex       help2man
-
-Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and
-'g' are ignored when checking the name.
-
-Send bug reports to <bug-automake@gnu.org>."
-    exit $?
-    ;;
-
-  -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
-    echo "missing $scriptversion (GNU Automake)"
-    exit $?
-    ;;
-
-  -*)
-    echo 1>&2 "$0: unknown '$1' option"
-    echo 1>&2 "Try '$0 --help' for more information"
-    exit 1
-    ;;
-
-esac
-
-# Run the given program, remember its exit status.
-"$@"; st=$?
-
-# If it succeeded, we are done.
-test $st -eq 0 && exit 0
-
-# Also exit now if we it failed (or wasn't found), and '--version' was
-# passed; such an option is passed most likely to detect whether the
-# program is present and works.
-case $2 in --version|--help) exit $st;; esac
-
-# Exit code 63 means version mismatch.  This often happens when the user
-# tries to use an ancient version of a tool on a file that requires a
-# minimum version.
-if test $st -eq 63; then
-  msg="probably too old"
-elif test $st -eq 127; then
-  # Program was missing.
-  msg="missing on your system"
-else
-  # Program was found and executed, but failed.  Give up.
-  exit $st
-fi
-
-perl_URL=http://www.perl.org/
-flex_URL=http://flex.sourceforge.net/
-gnu_software_URL=http://www.gnu.org/software
-
-program_details ()
-{
-  case $1 in
-    aclocal|automake)
-      echo "The '$1' program is part of the GNU Automake package:"
-      echo "<$gnu_software_URL/automake>"
-      echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:"
-      echo "<$gnu_software_URL/autoconf>"
-      echo "<$gnu_software_URL/m4/>"
-      echo "<$perl_URL>"
-      ;;
-    autoconf|autom4te|autoheader)
-      echo "The '$1' program is part of the GNU Autoconf package:"
-      echo "<$gnu_software_URL/autoconf/>"
-      echo "It also requires GNU m4 and Perl in order to run:"
-      echo "<$gnu_software_URL/m4/>"
-      echo "<$perl_URL>"
-      ;;
-  esac
-}
-
-give_advice ()
-{
-  # Normalize program name to check for.
-  normalized_program=`echo "$1" | sed '
-    s/^gnu-//; t
-    s/^gnu//; t
-    s/^g//; t'`
-
-  printf '%s\n' "'$1' is $msg."
-
-  configure_deps="'configure.ac' or m4 files included by 'configure.ac'"
-  case $normalized_program in
-    autoconf*)
-      echo "You should only need it if you modified 'configure.ac',"
-      echo "or m4 files included by it."
-      program_details 'autoconf'
-      ;;
-    autoheader*)
-      echo "You should only need it if you modified 'acconfig.h' or"
-      echo "$configure_deps."
-      program_details 'autoheader'
-      ;;
-    automake*)
-      echo "You should only need it if you modified 'Makefile.am' or"
-      echo "$configure_deps."
-      program_details 'automake'
-      ;;
-    aclocal*)
-      echo "You should only need it if you modified 'acinclude.m4' or"
-      echo "$configure_deps."
-      program_details 'aclocal'
-      ;;
-   autom4te*)
-      echo "You might have modified some maintainer files that require"
-      echo "the 'autom4te' program to be rebuilt."
-      program_details 'autom4te'
-      ;;
-    bison*|yacc*)
-      echo "You should only need it if you modified a '.y' file."
-      echo "You may want to install the GNU Bison package:"
-      echo "<$gnu_software_URL/bison/>"
-      ;;
-    lex*|flex*)
-      echo "You should only need it if you modified a '.l' file."
-      echo "You may want to install the Fast Lexical Analyzer package:"
-      echo "<$flex_URL>"
-      ;;
-    help2man*)
-      echo "You should only need it if you modified a dependency" \
-           "of a man page."
-      echo "You may want to install the GNU Help2man package:"
-      echo "<$gnu_software_URL/help2man/>"
-    ;;
-    makeinfo*)
-      echo "You should only need it if you modified a '.texi' file, or"
-      echo "any other file indirectly affecting the aspect of the manual."
-      echo "You might want to install the Texinfo package:"
-      echo "<$gnu_software_URL/texinfo/>"
-      echo "The spurious makeinfo call might also be the consequence of"
-      echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might"
-      echo "want to install GNU make:"
-      echo "<$gnu_software_URL/make/>"
-      ;;
-    *)
-      echo "You might have modified some files without having the proper"
-      echo "tools for further handling them.  Check the 'README' file, it"
-      echo "often tells you about the needed prerequisites for installing"
-      echo "this package.  You may also peek at any GNU archive site, in"
-      echo "case some other package contains this missing '$1' program."
-      ;;
-  esac
-}
-
-give_advice "$1" | sed -e '1s/^/WARNING: /' \
-                       -e '2,$s/^/         /' >&2
-
-# Propagate the correct exit status (expected to be 127 for a program
-# not found, 63 for a program that failed due to version mismatch).
-exit $st
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/po/.gitignore b/po/.gitignore
new file mode 100644
index 0000000..ff723e0
--- /dev/null
+++ b/po/.gitignore
@@ -0,0 +1,4 @@
+/build-aux/install?sh
+/autopoint-trigger
+/autopoint-timestamp
+/stamp-m.in
diff --git a/po/ABOUT-NLS b/po/ABOUT-NLS
new file mode 100644
index 0000000..0a9d56d
--- /dev/null
+++ b/po/ABOUT-NLS
@@ -0,0 +1 @@
+<https://www.gnu.org/software/gettext/manual/html_node/Users.html>
diff --git a/po/Makefile.in.in b/po/Makefile.in.in
new file mode 100644
index 0000000..6b25f0d
--- /dev/null
+++ b/po/Makefile.in.in
@@ -0,0 +1,510 @@
+# Makefile for PO directory in any package using GNU gettext.
+# Copyright (C) 1995-2000 Ulrich Drepper <drepper@gnu.ai.mit.edu>
+# Copyright (C) 2000-2020 Free Software Foundation, Inc.
+#
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty provided the copyright
+# notice and this notice are preserved.  This file is offered as-is,
+# without any warranty.
+#
+# Origin: gettext-0.21
+GETTEXT_MACRO_VERSION = 0.20
+
+PACKAGE = @PACKAGE@
+VERSION = @VERSION@
+PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
+
+SED = @SED@
+SHELL = /bin/sh
+@SET_MAKE@
+
+srcdir = @srcdir@
+top_srcdir = @top_srcdir@
+VPATH = @srcdir@
+
+prefix = @prefix@
+exec_prefix = @exec_prefix@
+datarootdir = @datarootdir@
+datadir = @datadir@
+localedir = @localedir@
+gettextsrcdir = $(datadir)/gettext/po
+
+INSTALL = @INSTALL@
+INSTALL_DATA = @INSTALL_DATA@
+
+# We use $(mkdir_p).
+# In automake <= 1.9.x, $(mkdir_p) is defined either as "mkdir -p --" or as
+# "$(mkinstalldirs)" or as "$(install_sh) -d". For these automake versions,
+# @install_sh@ does not start with $(SHELL), so we add it.
+# In automake >= 1.10, @mkdir_p@ is derived from ${MKDIR_P}, which is defined
+# either as "/path/to/mkdir -p" or ".../install-sh -c -d". For these automake
+# versions, $(mkinstalldirs) and $(install_sh) are unused.
+mkinstalldirs = $(SHELL) @install_sh@ -d
+install_sh = $(SHELL) @install_sh@
+MKDIR_P = @MKDIR_P@
+mkdir_p = @mkdir_p@
+
+# When building gettext-tools, we prefer to use the built programs
+# rather than installed programs.  However, we can't do that when we
+# are cross compiling.
+CROSS_COMPILING = @CROSS_COMPILING@
+
+GMSGFMT_ = @GMSGFMT@
+GMSGFMT_no = @GMSGFMT@
+GMSGFMT_yes = @GMSGFMT_015@
+GMSGFMT = $(GMSGFMT_$(USE_MSGCTXT))
+XGETTEXT_ = @XGETTEXT@
+XGETTEXT_no = @XGETTEXT@
+XGETTEXT_yes = @XGETTEXT_015@
+XGETTEXT = $(XGETTEXT_$(USE_MSGCTXT))
+MSGMERGE = @MSGMERGE@
+MSGMERGE_UPDATE = @MSGMERGE@ --update
+MSGMERGE_FOR_MSGFMT_OPTION = @MSGMERGE_FOR_MSGFMT_OPTION@
+MSGINIT = msginit
+MSGCONV = msgconv
+MSGFILTER = msgfilter
+
+POFILES = @POFILES@
+GMOFILES = @GMOFILES@
+UPDATEPOFILES = @UPDATEPOFILES@
+DUMMYPOFILES = @DUMMYPOFILES@
+DISTFILES.common = Makefile.in.in remove-potcdate.sin \
+$(DISTFILES.common.extra1) $(DISTFILES.common.extra2) $(DISTFILES.common.extra3)
+DISTFILES = $(DISTFILES.common) Makevars POTFILES.in \
+$(POFILES) $(GMOFILES) \
+$(DISTFILES.extra1) $(DISTFILES.extra2) $(DISTFILES.extra3)
+
+POTFILES = \
+
+CATALOGS = @CATALOGS@
+
+POFILESDEPS_ = $(srcdir)/$(DOMAIN).pot
+POFILESDEPS_yes = $(POFILESDEPS_)
+POFILESDEPS_no =
+POFILESDEPS = $(POFILESDEPS_$(PO_DEPENDS_ON_POT))
+
+DISTFILESDEPS_ = update-po
+DISTFILESDEPS_yes = $(DISTFILESDEPS_)
+DISTFILESDEPS_no =
+DISTFILESDEPS = $(DISTFILESDEPS_$(DIST_DEPENDS_ON_UPDATE_PO))
+
+# Makevars gets inserted here. (Don't remove this line!)
+
+all: all-@USE_NLS@
+
+
+.SUFFIXES:
+.SUFFIXES: .po .gmo .sed .sin .nop .po-create .po-update
+
+# The .pot file, stamp-po, .po files, and .gmo files appear in release tarballs.
+# The GNU Coding Standards say in
+# <https://www.gnu.org/prep/standards/html_node/Makefile-Basics.html>:
+#   "GNU distributions usually contain some files which are not source files
+#    ... . Since these files normally appear in the source directory, they
+#    should always appear in the source directory, not in the build directory.
+#    So Makefile rules to update them should put the updated files in the
+#    source directory."
+# Therefore we put these files in the source directory, not the build directory.
+
+# During .po -> .gmo conversion, take into account the most recent changes to
+# the .pot file. This eliminates the need to update the .po files when the
+# .pot file has changed, which would be troublesome if the .po files are put
+# under version control.
+$(GMOFILES): $(srcdir)/$(DOMAIN).pot
+.po.gmo:
+	@lang=`echo $* | sed -e 's,.*/,,'`; \
+	test "$(srcdir)" = . && cdcmd="" || cdcmd="cd $(srcdir) && "; \
+	echo "$${cdcmd}rm -f $${lang}.gmo && $(MSGMERGE) $(MSGMERGE_FOR_MSGFMT_OPTION) -o $${lang}.1po $${lang}.po $(DOMAIN).pot && $(GMSGFMT) -c --statistics --verbose -o $${lang}.gmo $${lang}.1po && rm -f $${lang}.1po"; \
+	cd $(srcdir) && \
+	rm -f $${lang}.gmo && \
+	$(MSGMERGE) $(MSGMERGE_FOR_MSGFMT_OPTION) -o $${lang}.1po $${lang}.po $(DOMAIN).pot && \
+	$(GMSGFMT) -c --statistics --verbose -o t-$${lang}.gmo $${lang}.1po && \
+	mv t-$${lang}.gmo $${lang}.gmo && \
+	rm -f $${lang}.1po
+
+.sin.sed:
+	sed -e '/^#/d' $< > t-$@
+	mv t-$@ $@
+
+
+all-yes: $(srcdir)/stamp-po
+all-no:
+
+# Ensure that the gettext macros and this Makefile.in.in are in sync.
+CHECK_MACRO_VERSION = \
+	test "$(GETTEXT_MACRO_VERSION)" = "@GETTEXT_MACRO_VERSION@" \
+	  || { echo "*** error: gettext infrastructure mismatch: using a Makefile.in.in from gettext version $(GETTEXT_MACRO_VERSION) but the autoconf macros are from gettext version @GETTEXT_MACRO_VERSION@" 1>&2; \
+	       exit 1; \
+	     }
+
+# $(srcdir)/$(DOMAIN).pot is only created when needed. When xgettext finds no
+# internationalized messages, no $(srcdir)/$(DOMAIN).pot is created (because
+# we don't want to bother translators with empty POT files). We assume that
+# LINGUAS is empty in this case, i.e. $(POFILES) and $(GMOFILES) are empty.
+# In this case, $(srcdir)/stamp-po is a nop (i.e. a phony target).
+
+# $(srcdir)/stamp-po is a timestamp denoting the last time at which the CATALOGS
+# have been loosely updated. Its purpose is that when a developer or translator
+# checks out the package from a version control system, and the $(DOMAIN).pot
+# file is not under version control, "make" will update the $(DOMAIN).pot and
+# the $(CATALOGS), but subsequent invocations of "make" will do nothing. This
+# timestamp would not be necessary if updating the $(CATALOGS) would always
+# touch them; however, the rule for $(POFILES) has been designed to not touch
+# files that don't need to be changed.
+$(srcdir)/stamp-po: $(srcdir)/$(DOMAIN).pot
+	@$(CHECK_MACRO_VERSION)
+	test ! -f $(srcdir)/$(DOMAIN).pot || \
+	  test -z "$(GMOFILES)" || $(MAKE) $(GMOFILES)
+	@test ! -f $(srcdir)/$(DOMAIN).pot || { \
+	  echo "touch $(srcdir)/stamp-po" && \
+	  echo timestamp > $(srcdir)/stamp-poT && \
+	  mv $(srcdir)/stamp-poT $(srcdir)/stamp-po; \
+	}
+
+# Note: Target 'all' must not depend on target '$(DOMAIN).pot-update',
+# otherwise packages like GCC can not be built if only parts of the source
+# have been downloaded.
+
+# This target rebuilds $(DOMAIN).pot; it is an expensive operation.
+# Note that $(DOMAIN).pot is not touched if it doesn't need to be changed.
+# The determination of whether the package xyz is a GNU one is based on the
+# heuristic whether some file in the top level directory mentions "GNU xyz".
+# If GNU 'find' is available, we avoid grepping through monster files.
+$(DOMAIN).pot-update: $(POTFILES) $(srcdir)/POTFILES.in remove-potcdate.sed
+	package_gnu="$(PACKAGE_GNU)"; \
+	test -n "$$package_gnu" || { \
+	  if { if (LC_ALL=C find --version) 2>/dev/null | grep GNU >/dev/null; then \
+	         LC_ALL=C find -L $(top_srcdir) -maxdepth 1 -type f -size -10000000c -exec grep -i 'GNU @PACKAGE@' /dev/null '{}' ';' 2>/dev/null; \
+	       else \
+	         LC_ALL=C grep -i 'GNU @PACKAGE@' $(top_srcdir)/* 2>/dev/null; \
+	       fi; \
+	     } | grep -v 'libtool:' >/dev/null; then \
+	     package_gnu=yes; \
+	   else \
+	     package_gnu=no; \
+	   fi; \
+	}; \
+	if test "$$package_gnu" = "yes"; then \
+	  package_prefix='GNU '; \
+	else \
+	  package_prefix=''; \
+	fi; \
+	if test -n '$(MSGID_BUGS_ADDRESS)' || test '$(PACKAGE_BUGREPORT)' = '@'PACKAGE_BUGREPORT'@'; then \
+	  msgid_bugs_address='$(MSGID_BUGS_ADDRESS)'; \
+	else \
+	  msgid_bugs_address='$(PACKAGE_BUGREPORT)'; \
+	fi; \
+	case `$(XGETTEXT) --version | sed 1q | sed -e 's,^[^0-9]*,,'` in \
+	  '' | 0.[0-9] | 0.[0-9].* | 0.1[0-5] | 0.1[0-5].* | 0.16 | 0.16.[0-1]*) \
+	    $(XGETTEXT) --default-domain=$(DOMAIN) --directory=$(top_srcdir) \
+	      --add-comments=TRANSLATORS: \
+	      --files-from=$(srcdir)/POTFILES.in \
+	      --copyright-holder='$(COPYRIGHT_HOLDER)' \
+	      --msgid-bugs-address="$$msgid_bugs_address" \
+	      $(XGETTEXT_OPTIONS) @XGETTEXT_EXTRA_OPTIONS@ \
+	    ;; \
+	  *) \
+	    $(XGETTEXT) --default-domain=$(DOMAIN) --directory=$(top_srcdir) \
+	      --add-comments=TRANSLATORS: \
+	      --files-from=$(srcdir)/POTFILES.in \
+	      --copyright-holder='$(COPYRIGHT_HOLDER)' \
+	      --package-name="$${package_prefix}@PACKAGE@" \
+	      --package-version='@VERSION@' \
+	      --msgid-bugs-address="$$msgid_bugs_address" \
+	      $(XGETTEXT_OPTIONS) @XGETTEXT_EXTRA_OPTIONS@ \
+	    ;; \
+	esac
+	test ! -f $(DOMAIN).po || { \
+	  if test -f $(srcdir)/$(DOMAIN).pot-header; then \
+	    sed -e '1,/^#$$/d' < $(DOMAIN).po > $(DOMAIN).1po && \
+	    cat $(srcdir)/$(DOMAIN).pot-header $(DOMAIN).1po > $(DOMAIN).po && \
+	    rm -f $(DOMAIN).1po \
+	    || exit 1; \
+	  fi; \
+	  if test -f $(srcdir)/$(DOMAIN).pot; then \
+	    sed -f remove-potcdate.sed < $(srcdir)/$(DOMAIN).pot > $(DOMAIN).1po && \
+	    sed -f remove-potcdate.sed < $(DOMAIN).po > $(DOMAIN).2po && \
+	    if cmp $(DOMAIN).1po $(DOMAIN).2po >/dev/null 2>&1; then \
+	      rm -f $(DOMAIN).1po $(DOMAIN).2po $(DOMAIN).po; \
+	    else \
+	      rm -f $(DOMAIN).1po $(DOMAIN).2po $(srcdir)/$(DOMAIN).pot && \
+	      mv $(DOMAIN).po $(srcdir)/$(DOMAIN).pot; \
+	    fi; \
+	  else \
+	    mv $(DOMAIN).po $(srcdir)/$(DOMAIN).pot; \
+	  fi; \
+	}
+
+# This rule has no dependencies: we don't need to update $(DOMAIN).pot at
+# every "make" invocation, only create it when it is missing.
+# Only "make $(DOMAIN).pot-update" or "make dist" will force an update.
+$(srcdir)/$(DOMAIN).pot:
+	$(MAKE) $(DOMAIN).pot-update
+
+# This target rebuilds a PO file if $(DOMAIN).pot has changed.
+# Note that a PO file is not touched if it doesn't need to be changed.
+$(POFILES): $(POFILESDEPS)
+	@test -f $(srcdir)/$(DOMAIN).pot || $(MAKE) $(srcdir)/$(DOMAIN).pot
+	@lang=`echo $@ | sed -e 's,.*/,,' -e 's/\.po$$//'`; \
+	if test -f "$(srcdir)/$${lang}.po"; then \
+	  test "$(srcdir)" = . && cdcmd="" || cdcmd="cd $(srcdir) && "; \
+	  echo "$${cdcmd}$(MSGMERGE_UPDATE) $(MSGMERGE_OPTIONS) --lang=$${lang} --previous $${lang}.po $(DOMAIN).pot"; \
+	  cd $(srcdir) \
+	    && { case `$(MSGMERGE_UPDATE) --version | sed 1q | sed -e 's,^[^0-9]*,,'` in \
+	           '' | 0.[0-9] | 0.[0-9].* | 0.1[0-5] | 0.1[0-5].*) \
+	             $(MSGMERGE_UPDATE) $(MSGMERGE_OPTIONS) $${lang}.po $(DOMAIN).pot;; \
+	           0.1[6-7] | 0.1[6-7].*) \
+	             $(MSGMERGE_UPDATE) $(MSGMERGE_OPTIONS) --previous $${lang}.po $(DOMAIN).pot;; \
+	           *) \
+	             $(MSGMERGE_UPDATE) $(MSGMERGE_OPTIONS) --lang=$${lang} --previous $${lang}.po $(DOMAIN).pot;; \
+	         esac; \
+	       }; \
+	else \
+	  $(MAKE) $${lang}.po-create; \
+	fi
+
+
+install: install-exec install-data
+install-exec:
+install-data: install-data-@USE_NLS@
+	if test "$(PACKAGE)" = "gettext-tools"; then \
+	  $(mkdir_p) $(DESTDIR)$(gettextsrcdir); \
+	  for file in $(DISTFILES.common) Makevars.template; do \
+	    $(INSTALL_DATA) $(srcdir)/$$file \
+			    $(DESTDIR)$(gettextsrcdir)/$$file; \
+	  done; \
+	  for file in Makevars; do \
+	    rm -f $(DESTDIR)$(gettextsrcdir)/$$file; \
+	  done; \
+	else \
+	  : ; \
+	fi
+install-data-no: all
+install-data-yes: all
+	@catalogs='$(CATALOGS)'; \
+	for cat in $$catalogs; do \
+	  cat=`basename $$cat`; \
+	  lang=`echo $$cat | sed -e 's/\.gmo$$//'`; \
+	  dir=$(localedir)/$$lang/LC_MESSAGES; \
+	  $(mkdir_p) $(DESTDIR)$$dir; \
+	  if test -r $$cat; then realcat=$$cat; else realcat=$(srcdir)/$$cat; fi; \
+	  $(INSTALL_DATA) $$realcat $(DESTDIR)$$dir/$(DOMAIN).mo; \
+	  echo "installing $$realcat as $(DESTDIR)$$dir/$(DOMAIN).mo"; \
+	  for lc in '' $(EXTRA_LOCALE_CATEGORIES); do \
+	    if test -n "$$lc"; then \
+	      if (cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc 2>/dev/null) | grep ' -> ' >/dev/null; then \
+	        link=`cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc | sed -e 's/^.* -> //'`; \
+	        mv $(DESTDIR)$(localedir)/$$lang/$$lc $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
+	        mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
+	        (cd $(DESTDIR)$(localedir)/$$lang/$$lc.old && \
+	         for file in *; do \
+	           if test -f $$file; then \
+	             ln -s ../$$link/$$file $(DESTDIR)$(localedir)/$$lang/$$lc/$$file; \
+	           fi; \
+	         done); \
+	        rm -f $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
+	      else \
+	        if test -d $(DESTDIR)$(localedir)/$$lang/$$lc; then \
+	          :; \
+	        else \
+	          rm -f $(DESTDIR)$(localedir)/$$lang/$$lc; \
+	          mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
+	        fi; \
+	      fi; \
+	      rm -f $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo; \
+	      ln -s ../LC_MESSAGES/$(DOMAIN).mo $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo 2>/dev/null || \
+	      ln $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(DOMAIN).mo $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo 2>/dev/null || \
+	      cp -p $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(DOMAIN).mo $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo; \
+	      echo "installing $$realcat link as $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo"; \
+	    fi; \
+	  done; \
+	done
+
+install-strip: install
+
+installdirs: installdirs-exec installdirs-data
+installdirs-exec:
+installdirs-data: installdirs-data-@USE_NLS@
+	if test "$(PACKAGE)" = "gettext-tools"; then \
+	  $(mkdir_p) $(DESTDIR)$(gettextsrcdir); \
+	else \
+	  : ; \
+	fi
+installdirs-data-no:
+installdirs-data-yes:
+	@catalogs='$(CATALOGS)'; \
+	for cat in $$catalogs; do \
+	  cat=`basename $$cat`; \
+	  lang=`echo $$cat | sed -e 's/\.gmo$$//'`; \
+	  dir=$(localedir)/$$lang/LC_MESSAGES; \
+	  $(mkdir_p) $(DESTDIR)$$dir; \
+	  for lc in '' $(EXTRA_LOCALE_CATEGORIES); do \
+	    if test -n "$$lc"; then \
+	      if (cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc 2>/dev/null) | grep ' -> ' >/dev/null; then \
+	        link=`cd $(DESTDIR)$(localedir)/$$lang && LC_ALL=C ls -l -d $$lc | sed -e 's/^.* -> //'`; \
+	        mv $(DESTDIR)$(localedir)/$$lang/$$lc $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
+	        mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
+	        (cd $(DESTDIR)$(localedir)/$$lang/$$lc.old && \
+	         for file in *; do \
+	           if test -f $$file; then \
+	             ln -s ../$$link/$$file $(DESTDIR)$(localedir)/$$lang/$$lc/$$file; \
+	           fi; \
+	         done); \
+	        rm -f $(DESTDIR)$(localedir)/$$lang/$$lc.old; \
+	      else \
+	        if test -d $(DESTDIR)$(localedir)/$$lang/$$lc; then \
+	          :; \
+	        else \
+	          rm -f $(DESTDIR)$(localedir)/$$lang/$$lc; \
+	          mkdir $(DESTDIR)$(localedir)/$$lang/$$lc; \
+	        fi; \
+	      fi; \
+	    fi; \
+	  done; \
+	done
+
+# Define this as empty until I found a useful application.
+installcheck:
+
+uninstall: uninstall-exec uninstall-data
+uninstall-exec:
+uninstall-data: uninstall-data-@USE_NLS@
+	if test "$(PACKAGE)" = "gettext-tools"; then \
+	  for file in $(DISTFILES.common) Makevars.template; do \
+	    rm -f $(DESTDIR)$(gettextsrcdir)/$$file; \
+	  done; \
+	else \
+	  : ; \
+	fi
+uninstall-data-no:
+uninstall-data-yes:
+	catalogs='$(CATALOGS)'; \
+	for cat in $$catalogs; do \
+	  cat=`basename $$cat`; \
+	  lang=`echo $$cat | sed -e 's/\.gmo$$//'`; \
+	  for lc in LC_MESSAGES $(EXTRA_LOCALE_CATEGORIES); do \
+	    rm -f $(DESTDIR)$(localedir)/$$lang/$$lc/$(DOMAIN).mo; \
+	  done; \
+	done
+
+check: all
+
+info dvi ps pdf html tags TAGS ctags CTAGS ID:
+
+install-dvi install-ps install-pdf install-html:
+
+mostlyclean:
+	rm -f remove-potcdate.sed
+	rm -f $(srcdir)/stamp-poT
+	rm -f core core.* $(DOMAIN).po $(DOMAIN).1po $(DOMAIN).2po *.new.po
+	rm -fr *.o
+
+clean: mostlyclean
+
+distclean: clean
+	rm -f Makefile Makefile.in POTFILES
+
+maintainer-clean: distclean
+	@echo "This command is intended for maintainers to use;"
+	@echo "it deletes files that may require special tools to rebuild."
+	rm -f $(srcdir)/$(DOMAIN).pot $(srcdir)/stamp-po $(GMOFILES)
+
+distdir = $(top_builddir)/$(PACKAGE)-$(VERSION)/$(subdir)
+dist distdir:
+	test -z "$(DISTFILESDEPS)" || $(MAKE) $(DISTFILESDEPS)
+	@$(MAKE) dist2
+# This is a separate target because 'update-po' must be executed before.
+dist2: $(srcdir)/stamp-po $(DISTFILES)
+	@dists="$(DISTFILES)"; \
+	if test "$(PACKAGE)" = "gettext-tools"; then \
+	  dists="$$dists Makevars.template"; \
+	fi; \
+	if test -f $(srcdir)/$(DOMAIN).pot; then \
+	  dists="$$dists $(DOMAIN).pot stamp-po"; \
+	else \
+	  case $(XGETTEXT) in \
+	    :) echo "Warning: Creating a tarball without '$(DOMAIN).pot', because a suitable 'xgettext' program was not found in PATH." 1>&2;; \
+	    *) echo "Warning: Creating a tarball without '$(DOMAIN).pot', because 'xgettext' found no strings to extract. Check the contents of the POTFILES.in file and the XGETTEXT_OPTIONS in the Makevars file." 1>&2;; \
+	  esac; \
+	fi; \
+	if test -f $(srcdir)/ChangeLog; then \
+	  dists="$$dists ChangeLog"; \
+	fi; \
+	for i in 0 1 2 3 4 5 6 7 8 9; do \
+	  if test -f $(srcdir)/ChangeLog.$$i; then \
+	    dists="$$dists ChangeLog.$$i"; \
+	  fi; \
+	done; \
+	if test -f $(srcdir)/LINGUAS; then dists="$$dists LINGUAS"; fi; \
+	for file in $$dists; do \
+	  if test -f $$file; then \
+	    cp -p $$file $(distdir) || exit 1; \
+	  else \
+	    cp -p $(srcdir)/$$file $(distdir) || exit 1; \
+	  fi; \
+	done
+
+update-po: Makefile
+	$(MAKE) $(DOMAIN).pot-update
+	test -z "$(UPDATEPOFILES)" || $(MAKE) $(UPDATEPOFILES)
+	$(MAKE) update-gmo
+
+# General rule for creating PO files.
+
+.nop.po-create:
+	@lang=`echo $@ | sed -e 's/\.po-create$$//'`; \
+	echo "File $$lang.po does not exist. If you are a translator, you can create it through 'msginit'." 1>&2; \
+	exit 1
+
+# General rule for updating PO files.
+
+.nop.po-update:
+	@lang=`echo $@ | sed -e 's/\.po-update$$//'`; \
+	if test "$(PACKAGE)" = "gettext-tools" && test "$(CROSS_COMPILING)" != "yes"; then PATH=`pwd`/../src:$$PATH; fi; \
+	tmpdir=`pwd`; \
+	echo "$$lang:"; \
+	test "$(srcdir)" = . && cdcmd="" || cdcmd="cd $(srcdir) && "; \
+	echo "$${cdcmd}$(MSGMERGE) $(MSGMERGE_OPTIONS) --lang=$$lang --previous $$lang.po $(DOMAIN).pot -o $$lang.new.po"; \
+	cd $(srcdir); \
+	if { case `$(MSGMERGE) --version | sed 1q | sed -e 's,^[^0-9]*,,'` in \
+	       '' | 0.[0-9] | 0.[0-9].* | 0.1[0-5] | 0.1[0-5].*) \
+	         $(MSGMERGE) $(MSGMERGE_OPTIONS) -o $$tmpdir/$$lang.new.po $$lang.po $(DOMAIN).pot;; \
+	       0.1[6-7] | 0.1[6-7].*) \
+	         $(MSGMERGE) $(MSGMERGE_OPTIONS) --previous -o $$tmpdir/$$lang.new.po $$lang.po $(DOMAIN).pot;; \
+	       *) \
+	         $(MSGMERGE) $(MSGMERGE_OPTIONS) --lang=$$lang --previous -o $$tmpdir/$$lang.new.po $$lang.po $(DOMAIN).pot;; \
+	     esac; \
+	   }; then \
+	  if cmp $$lang.po $$tmpdir/$$lang.new.po >/dev/null 2>&1; then \
+	    rm -f $$tmpdir/$$lang.new.po; \
+	  else \
+	    if mv -f $$tmpdir/$$lang.new.po $$lang.po; then \
+	      :; \
+	    else \
+	      echo "msgmerge for $$lang.po failed: cannot move $$tmpdir/$$lang.new.po to $$lang.po" 1>&2; \
+	      exit 1; \
+	    fi; \
+	  fi; \
+	else \
+	  echo "msgmerge for $$lang.po failed!" 1>&2; \
+	  rm -f $$tmpdir/$$lang.new.po; \
+	fi
+
+$(DUMMYPOFILES):
+
+update-gmo: Makefile $(GMOFILES)
+	@:
+
+# Recreate Makefile by invoking config.status. Explicitly invoke the shell,
+# because execution permission bits may not work on the current file system.
+# Use @SHELL@, which is the shell determined by autoconf for the use by its
+# scripts, not $(SHELL) which is hardwired to /bin/sh and may be deficient.
+Makefile: Makefile.in.in Makevars $(top_builddir)/config.status @POMAKEFILEDEPS@
+	cd $(top_builddir) \
+	  && @SHELL@ ./config.status $(subdir)/$@.in po-directories
+
+force:
+
+# Tell versions [3.59,3.63) of GNU make not to export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/po/Makevars b/po/Makevars
new file mode 100644
index 0000000..0325c71
--- /dev/null
+++ b/po/Makevars
@@ -0,0 +1,113 @@
+# Makefile variables for PO directory in any package using GNU gettext.
+#
+# Copyright (C) 2003-2019 Free Software Foundation, Inc.
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to use, copy, distribute, and modify it.
+
+# Usually the message domain is the same as the package name.
+DOMAIN = $(PACKAGE)
+
+# These two variables depend on the location of this directory.
+subdir = po
+top_builddir = ..
+
+# These options get passed to xgettext.
+XGETTEXT_OPTIONS = --keyword=_ --keyword=N_
+
+# This is the copyright holder that gets inserted into the header of the
+# $(DOMAIN).pot file.  Set this to the copyright holder of the surrounding
+# package.  (Note that the msgstr strings, extracted from the package's
+# sources, belong to the copyright holder of the package.)  Translators are
+# expected to transfer the copyright for their translations to this person
+# or entity, or to disclaim their copyright.  The empty string stands for
+# the public domain; in this case the translators are expected to disclaim
+# their copyright.
+COPYRIGHT_HOLDER = Free Software Foundation, Inc.
+
+# This tells whether or not to prepend "GNU " prefix to the package
+# name that gets inserted into the header of the $(DOMAIN).pot file.
+# Possible values are "yes", "no", or empty.  If it is empty, try to
+# detect it automatically by scanning the files in $(top_srcdir) for
+# "GNU packagename" string.
+PACKAGE_GNU = yes
+
+# This is the email address or URL to which the translators shall report
+# bugs in the untranslated strings:
+# - Strings which are not entire sentences, see the maintainer guidelines
+#   in the GNU gettext documentation, section 'Preparing Strings'.
+# - Strings which use unclear terms or require additional context to be
+#   understood.
+# - Strings which make invalid assumptions about notation of date, time or
+#   money.
+# - Pluralisation problems.
+# - Incorrect English spelling.
+# - Incorrect formatting.
+# It can be your email address, or a mailing list address where translators
+# can write to without being subscribed, or the URL of a web page through
+# which the translators can contact you.
+MSGID_BUGS_ADDRESS = libmicrohttpd@gnu.org
+
+# This is the list of locale categories, beyond LC_MESSAGES, for which the
+# message catalogs shall be used.  It is usually empty.
+EXTRA_LOCALE_CATEGORIES =
+
+# This tells whether the $(DOMAIN).pot file contains messages with an 'msgctxt'
+# context.  Possible values are "yes" and "no".  Set this to yes if the
+# package uses functions taking also a message context, like pgettext(), or
+# if in $(XGETTEXT_OPTIONS) you define keywords with a context argument.
+USE_MSGCTXT = no
+
+# These options get passed to msgmerge.
+# Useful options are in particular:
+#   --previous            to keep previous msgids of translated messages,
+#   --quiet               to reduce the verbosity.
+MSGMERGE_OPTIONS =
+
+# These options get passed to msginit.
+# If you want to disable line wrapping when writing PO files, add
+# --no-wrap to MSGMERGE_OPTIONS, XGETTEXT_OPTIONS, and
+# MSGINIT_OPTIONS.
+MSGINIT_OPTIONS =
+
+# This tells whether or not to regenerate a PO file when $(DOMAIN).pot
+# has changed.  Possible values are "yes" and "no".  Set this to no if
+# the POT file is checked in the repository and the version control
+# program ignores timestamps.
+PO_DEPENDS_ON_POT = yes
+
+# This tells whether or not to forcibly update $(DOMAIN).pot and
+# regenerate PO files on "make dist".  Possible values are "yes" and
+# "no".  Set this to no if the POT file and PO files are maintained
+# externally.
+DIST_DEPENDS_ON_UPDATE_PO = yes
+
+# Hacks for MHD
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+
+$(top_builddir)/po-config.status: $(srcdir)/po-configure.ac.in $(top_srcdir)/configure.ac
+	@echo "cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) po-config.status" && \
+	$(am__cd) '$(top_builddir)' && $(MAKE) $(AM_MAKEFLAGS) po-config.status
+
+$(srcdir)/POTFILES.in: $(top_srcdir)/src/microhttpd/Makefile.am
+	@echo "cd $(top_srcdir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) update-po-POTFILES.in" && \
+	$(am__cd) '$(top_srcdir)/src/microhttpd' && $(MAKE) $(AM_MAKEFLAGS) update-po-POTFILES.in
+
+$(srcdir)/stamp-m.in:
+	@: > '$@'
+
+stamp-m: $(srcdir)/Makefile.in.in $(srcdir)/Makevars $(top_builddir)/po-config.status $(srcdir)/POTFILES.in $(srcdir)/stamp-m.in
+	@$(am__cd) $(top_builddir) \
+	    && $(MHD_CONFIG_SHELL) ./po-config.status po/stamp-m po/Makefile.in po-directories
+
+.DELETE_ON_ERROR: stamp-m
+
+$(srcdir)/$(MHD_AUX_DIR)/install-sh: $(topsrcdir)/$(MHD_AUX_DIR)/install-sh
+	@$(MKDIR_P) '$(topsrcdir)/$(MHD_AUX_DIR)'
+	cp -f '$(topsrcdir)/$(MHD_AUX_DIR)/install-sh' '$@'
+
+mostlyclean: mostlycleancustom
+mostlycleancustom:
+	-rm -f stamp-m Makefile.in po-configure.ac
+	-rm -f $(top_builddir)/po-config.status
+
+.PHONY: mostlycleancustom
diff --git a/po/Makevars.template b/po/Makevars.template
new file mode 100644
index 0000000..86a11f1
--- /dev/null
+++ b/po/Makevars.template
@@ -0,0 +1,82 @@
+# Makefile variables for PO directory in any package using GNU gettext.
+#
+# Copyright (C) 2003-2019 Free Software Foundation, Inc.
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to use, copy, distribute, and modify it.
+
+# Usually the message domain is the same as the package name.
+DOMAIN = $(PACKAGE)
+
+# These two variables depend on the location of this directory.
+subdir = po
+top_builddir = ..
+
+# These options get passed to xgettext.
+XGETTEXT_OPTIONS = --keyword=_ --keyword=N_
+
+# This is the copyright holder that gets inserted into the header of the
+# $(DOMAIN).pot file.  Set this to the copyright holder of the surrounding
+# package.  (Note that the msgstr strings, extracted from the package's
+# sources, belong to the copyright holder of the package.)  Translators are
+# expected to transfer the copyright for their translations to this person
+# or entity, or to disclaim their copyright.  The empty string stands for
+# the public domain; in this case the translators are expected to disclaim
+# their copyright.
+COPYRIGHT_HOLDER = Free Software Foundation, Inc.
+
+# This tells whether or not to prepend "GNU " prefix to the package
+# name that gets inserted into the header of the $(DOMAIN).pot file.
+# Possible values are "yes", "no", or empty.  If it is empty, try to
+# detect it automatically by scanning the files in $(top_srcdir) for
+# "GNU packagename" string.
+PACKAGE_GNU =
+
+# This is the email address or URL to which the translators shall report
+# bugs in the untranslated strings:
+# - Strings which are not entire sentences, see the maintainer guidelines
+#   in the GNU gettext documentation, section 'Preparing Strings'.
+# - Strings which use unclear terms or require additional context to be
+#   understood.
+# - Strings which make invalid assumptions about notation of date, time or
+#   money.
+# - Pluralisation problems.
+# - Incorrect English spelling.
+# - Incorrect formatting.
+# It can be your email address, or a mailing list address where translators
+# can write to without being subscribed, or the URL of a web page through
+# which the translators can contact you.
+MSGID_BUGS_ADDRESS =
+
+# This is the list of locale categories, beyond LC_MESSAGES, for which the
+# message catalogs shall be used.  It is usually empty.
+EXTRA_LOCALE_CATEGORIES =
+
+# This tells whether the $(DOMAIN).pot file contains messages with an 'msgctxt'
+# context.  Possible values are "yes" and "no".  Set this to yes if the
+# package uses functions taking also a message context, like pgettext(), or
+# if in $(XGETTEXT_OPTIONS) you define keywords with a context argument.
+USE_MSGCTXT = no
+
+# These options get passed to msgmerge.
+# Useful options are in particular:
+#   --previous            to keep previous msgids of translated messages,
+#   --quiet               to reduce the verbosity.
+MSGMERGE_OPTIONS =
+
+# These options get passed to msginit.
+# If you want to disable line wrapping when writing PO files, add
+# --no-wrap to MSGMERGE_OPTIONS, XGETTEXT_OPTIONS, and
+# MSGINIT_OPTIONS.
+MSGINIT_OPTIONS =
+
+# This tells whether or not to regenerate a PO file when $(DOMAIN).pot
+# has changed.  Possible values are "yes" and "no".  Set this to no if
+# the POT file is checked in the repository and the version control
+# program ignores timestamps.
+PO_DEPENDS_ON_POT = yes
+
+# This tells whether or not to forcibly update $(DOMAIN).pot and
+# regenerate PO files on "make dist".  Possible values are "yes" and
+# "no".  Set this to no if the POT file and PO files are maintained
+# externally.
+DIST_DEPENDS_ON_UPDATE_PO = yes
diff --git a/po/POTFILES.in b/po/POTFILES.in
new file mode 100644
index 0000000..261c6a7
--- /dev/null
+++ b/po/POTFILES.in
@@ -0,0 +1,41 @@
+src/include/microhttpd.h
+src/microhttpd/base64.h
+src/microhttpd/mhd_mono_clock.h
+src/microhttpd/tsearch.h
+src/microhttpd/connection_https.c
+src/microhttpd/reason_phrase.c
+src/microhttpd/mhd_itc_types.h
+src/microhttpd/sysfdsetsize.h
+src/microhttpd/mhd_threads.h
+src/microhttpd/mhd_sockets.c
+src/microhttpd/mhd_threads.c
+src/microhttpd/mhd_str.h
+src/microhttpd/mhd_compat.c
+src/microhttpd/tsearch.c
+src/microhttpd/internal.c
+src/microhttpd/mhd_byteorder.h
+src/microhttpd/mhd_locks.h
+src/microhttpd/memorypool.h
+src/microhttpd/memorypool.c
+src/microhttpd/connection.h
+src/microhttpd/internal.h
+src/microhttpd/digestauth.c
+src/microhttpd/sysfdsetsize.c
+src/microhttpd/md5.h
+src/microhttpd/postprocessor.c
+src/microhttpd/response.h
+src/microhttpd/mhd_str.c
+src/microhttpd/daemon.c
+src/microhttpd/mhd_assert.h
+src/microhttpd/mhd_mono_clock.c
+src/microhttpd/base64.c
+src/microhttpd/md5.c
+src/microhttpd/mhd_sockets.h
+src/microhttpd/mhd_compat.h
+src/microhttpd/connection.c
+src/microhttpd/response.c
+src/microhttpd/mhd_itc.h
+src/microhttpd/connection_https.h
+src/microhttpd/mhd_limits.h
+src/microhttpd/mhd_itc.c
+src/microhttpd/basicauth.c
diff --git a/po/Rules-quot b/po/Rules-quot
new file mode 100644
index 0000000..18c024b
--- /dev/null
+++ b/po/Rules-quot
@@ -0,0 +1,62 @@
+# Special Makefile rules for English message catalogs with quotation marks.
+#
+# Copyright (C) 2001-2017 Free Software Foundation, Inc.
+# This file, Rules-quot, and its auxiliary files (listed under
+# DISTFILES.common.extra1) are free software; the Free Software Foundation
+# gives unlimited permission to use, copy, distribute, and modify them.
+
+DISTFILES.common.extra1 = quot.sed boldquot.sed en@quot.header en@boldquot.header insert-header.sin Rules-quot
+
+.SUFFIXES: .insert-header .po-update-en
+
+en@quot.po-create:
+	$(MAKE) en@quot.po-update
+en@boldquot.po-create:
+	$(MAKE) en@boldquot.po-update
+
+en@quot.po-update: en@quot.po-update-en
+en@boldquot.po-update: en@boldquot.po-update-en
+
+.insert-header.po-update-en:
+	@lang=`echo $@ | sed -e 's/\.po-update-en$$//'`; \
+	if test "$(PACKAGE)" = "gettext-tools" && test "$(CROSS_COMPILING)" != "yes"; then PATH=`pwd`/../src:$$PATH; GETTEXTLIBDIR=`cd $(top_srcdir)/src && pwd`; export GETTEXTLIBDIR; fi; \
+	tmpdir=`pwd`; \
+	echo "$$lang:"; \
+	ll=`echo $$lang | sed -e 's/@.*//'`; \
+	LC_ALL=C; export LC_ALL; \
+	cd $(srcdir); \
+	if $(MSGINIT) $(MSGINIT_OPTIONS) -i $(DOMAIN).pot --no-translator -l $$lang -o - 2>/dev/null \
+	   | $(SED) -f $$tmpdir/$$lang.insert-header | $(MSGCONV) -t UTF-8 | \
+	   { case `$(MSGFILTER) --version | sed 1q | sed -e 's,^[^0-9]*,,'` in \
+	     '' | 0.[0-9] | 0.[0-9].* | 0.1[0-8] | 0.1[0-8].*) \
+	       $(MSGFILTER) $(SED) -f `echo $$lang | sed -e 's/.*@//'`.sed \
+	       ;; \
+	     *) \
+	       $(MSGFILTER) `echo $$lang | sed -e 's/.*@//'` \
+	       ;; \
+	     esac } 2>/dev/null > $$tmpdir/$$lang.new.po \
+	     ; then \
+	  if cmp $$lang.po $$tmpdir/$$lang.new.po >/dev/null 2>&1; then \
+	    rm -f $$tmpdir/$$lang.new.po; \
+	  else \
+	    if mv -f $$tmpdir/$$lang.new.po $$lang.po; then \
+	      :; \
+	    else \
+	      echo "creation of $$lang.po failed: cannot move $$tmpdir/$$lang.new.po to $$lang.po" 1>&2; \
+	      exit 1; \
+	    fi; \
+	  fi; \
+	else \
+	  echo "creation of $$lang.po failed!" 1>&2; \
+	  rm -f $$tmpdir/$$lang.new.po; \
+	fi
+
+en@quot.insert-header: insert-header.sin
+	sed -e '/^#/d' -e 's/HEADER/en@quot.header/g' $(srcdir)/insert-header.sin > en@quot.insert-header
+
+en@boldquot.insert-header: insert-header.sin
+	sed -e '/^#/d' -e 's/HEADER/en@boldquot.header/g' $(srcdir)/insert-header.sin > en@boldquot.insert-header
+
+mostlyclean: mostlyclean-quot
+mostlyclean-quot:
+	rm -f *.insert-header
diff --git a/po/boldquot.sed b/po/boldquot.sed
new file mode 100644
index 0000000..4b937aa
--- /dev/null
+++ b/po/boldquot.sed
@@ -0,0 +1,10 @@
+s/"\([^"]*\)"/“\1”/g
+s/`\([^`']*\)'/‘\1’/g
+s/ '\([^`']*\)' / ‘\1’ /g
+s/ '\([^`']*\)'$/ ‘\1’/g
+s/^'\([^`']*\)' /‘\1’ /g
+s/“”/""/g
+s/“/“/g
+s/”/”/g
+s/‘/‘/g
+s/’/’/g
diff --git a/po/build-aux/config.rpath b/po/build-aux/config.rpath
new file mode 100755
index 0000000..1e1ab67
--- /dev/null
+++ b/po/build-aux/config.rpath
@@ -0,0 +1,684 @@
+#! /bin/sh
+# Output a system dependent set of variables, describing how to set the
+# run time search path of shared libraries in an executable.
+#
+#   Copyright 1996-2022 Free Software Foundation, Inc.
+#   Taken from GNU libtool, 2001
+#   Originally by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996
+#
+#   This file is free software; the Free Software Foundation gives
+#   unlimited permission to copy and/or distribute it, with or without
+#   modifications, as long as this notice is preserved.
+#
+# The first argument passed to this file is the canonical host specification,
+#    CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or
+#    CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# The environment variables CC, GCC, LDFLAGS, LD, with_gnu_ld
+# should be set by the caller.
+#
+# The set of defined variables is at the end of this script.
+
+# Known limitations:
+# - On IRIX 6.5 with CC="cc", the run time search patch must not be longer
+#   than 256 bytes, otherwise the compiler driver will dump core. The only
+#   known workaround is to choose shorter directory names for the build
+#   directory and/or the installation directory.
+
+# All known linkers require a '.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+shrext=.so
+
+host="$1"
+host_cpu=`echo "$host" | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
+host_vendor=`echo "$host" | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
+host_os=`echo "$host" | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
+
+# Code taken from libtool.m4's _LT_CC_BASENAME.
+
+for cc_temp in $CC""; do
+  case $cc_temp in
+    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
+    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`echo "$cc_temp" | sed -e 's%^.*/%%'`
+
+# Code taken from libtool.m4's _LT_COMPILER_PIC.
+
+wl=
+if test "$GCC" = yes; then
+  wl='-Wl,'
+else
+  case "$host_os" in
+    aix*)
+      wl='-Wl,'
+      ;;
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      ;;
+    hpux9* | hpux10* | hpux11*)
+      wl='-Wl,'
+      ;;
+    irix5* | irix6* | nonstopux*)
+      wl='-Wl,'
+      ;;
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
+      case $cc_basename in
+        ecc*)
+          wl='-Wl,'
+          ;;
+        icc* | ifort*)
+          wl='-Wl,'
+          ;;
+        lf95*)
+          wl='-Wl,'
+          ;;
+        nagfor*)
+          wl='-Wl,-Wl,,'
+          ;;
+        pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
+          wl='-Wl,'
+          ;;
+        ccc*)
+          wl='-Wl,'
+          ;;
+        xl* | bgxl* | bgf* | mpixl*)
+          wl='-Wl,'
+          ;;
+        como)
+          wl='-lopt='
+          ;;
+        *)
+          case `$CC -V 2>&1 | sed 5q` in
+            *Sun\ F* | *Sun*Fortran*)
+              wl=
+              ;;
+            *Sun\ C*)
+              wl='-Wl,'
+              ;;
+          esac
+          ;;
+      esac
+      ;;
+    newsos6)
+      ;;
+    *nto* | *qnx*)
+      ;;
+    osf3* | osf4* | osf5*)
+      wl='-Wl,'
+      ;;
+    rdos*)
+      ;;
+    solaris*)
+      case $cc_basename in
+        f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
+          wl='-Qoption ld '
+          ;;
+        *)
+          wl='-Wl,'
+          ;;
+      esac
+      ;;
+    sunos4*)
+      wl='-Qoption ld '
+      ;;
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      wl='-Wl,'
+      ;;
+    sysv4*MP*)
+      ;;
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      wl='-Wl,'
+      ;;
+    unicos*)
+      wl='-Wl,'
+      ;;
+    uts4*)
+      ;;
+  esac
+fi
+
+# Code taken from libtool.m4's _LT_LINKER_SHLIBS.
+
+hardcode_libdir_flag_spec=
+hardcode_libdir_separator=
+hardcode_direct=no
+hardcode_minus_L=no
+
+case "$host_os" in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+esac
+
+ld_shlibs=yes
+if test "$with_gnu_ld" = yes; then
+  # Set some defaults for GNU ld with shared library support. These
+  # are reset later if shared libraries are not supported. Putting them
+  # here allows them to be overridden if necessary.
+  # Unlike libtool, we use -rpath here, not --rpath, since the documented
+  # option of GNU ld is called -rpath, not --rpath.
+  hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+  case "$host_os" in
+    aix[3-9]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+        ld_shlibs=no
+      fi
+      ;;
+    amigaos*)
+      case "$host_cpu" in
+        powerpc)
+          ;;
+        m68k)
+          hardcode_libdir_flag_spec='-L$libdir'
+          hardcode_minus_L=yes
+          ;;
+      esac
+      ;;
+    beos*)
+      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+        :
+      else
+        ld_shlibs=no
+      fi
+      ;;
+    cygwin* | mingw* | pw32* | cegcc*)
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      hardcode_libdir_flag_spec='-L$libdir'
+      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+        :
+      else
+        ld_shlibs=no
+      fi
+      ;;
+    haiku*)
+      ;;
+    interix[3-9]*)
+      hardcode_direct=no
+      hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+      ;;
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+        :
+      else
+        ld_shlibs=no
+      fi
+      ;;
+    netbsd*)
+      ;;
+    solaris*)
+      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+        ld_shlibs=no
+      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+        :
+      else
+        ld_shlibs=no
+      fi
+      ;;
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
+          ld_shlibs=no
+          ;;
+        *)
+          if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+            hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`'
+          else
+            ld_shlibs=no
+          fi
+          ;;
+      esac
+      ;;
+    sunos4*)
+      hardcode_direct=yes
+      ;;
+    *)
+      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
+        :
+      else
+        ld_shlibs=no
+      fi
+      ;;
+  esac
+  if test "$ld_shlibs" = no; then
+    hardcode_libdir_flag_spec=
+  fi
+else
+  case "$host_os" in
+    aix3*)
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      hardcode_minus_L=yes
+      if test "$GCC" = yes; then
+        # Neither direct hardcoding nor static linking is supported with a
+        # broken collect2.
+        hardcode_direct=unsupported
+      fi
+      ;;
+    aix[4-9]*)
+      if test "$host_cpu" = ia64; then
+        # On IA64, the linker does run time linking by default, so we don't
+        # have to do anything special.
+        aix_use_runtimelinking=no
+      else
+        aix_use_runtimelinking=no
+        # Test if we are trying to use run time linking or normal
+        # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+        # need to do runtime linking.
+        case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*)
+          for ld_flag in $LDFLAGS; do
+            if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+              aix_use_runtimelinking=yes
+              break
+            fi
+          done
+          ;;
+        esac
+      fi
+      hardcode_direct=yes
+      hardcode_libdir_separator=':'
+      if test "$GCC" = yes; then
+        case $host_os in aix4.[012]|aix4.[012].*)
+          collect2name=`${CC} -print-prog-name=collect2`
+          if test -f "$collect2name" && \
+            strings "$collect2name" | grep resolve_lib_name >/dev/null
+          then
+            # We have reworked collect2
+            :
+          else
+            # We have old collect2
+            hardcode_direct=unsupported
+            hardcode_minus_L=yes
+            hardcode_libdir_flag_spec='-L$libdir'
+            hardcode_libdir_separator=
+          fi
+          ;;
+        esac
+      fi
+      # Begin _LT_AC_SYS_LIBPATH_AIX.
+      echo 'int main () { return 0; }' > conftest.c
+      ${CC} ${LDFLAGS} conftest.c -o conftest
+      aix_libpath=`dump -H conftest 2>/dev/null | sed -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
+}'`
+      if test -z "$aix_libpath"; then
+        aix_libpath=`dump -HX64 conftest 2>/dev/null | sed -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
+}'`
+      fi
+      if test -z "$aix_libpath"; then
+        aix_libpath="/usr/lib:/lib"
+      fi
+      rm -f conftest.c conftest
+      # End _LT_AC_SYS_LIBPATH_AIX.
+      if test "$aix_use_runtimelinking" = yes; then
+        hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+      else
+        if test "$host_cpu" = ia64; then
+          hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib'
+        else
+          hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath"
+        fi
+      fi
+      ;;
+    amigaos*)
+      case "$host_cpu" in
+        powerpc)
+          ;;
+        m68k)
+          hardcode_libdir_flag_spec='-L$libdir'
+          hardcode_minus_L=yes
+          ;;
+      esac
+      ;;
+    bsdi[45]*)
+      ;;
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      hardcode_libdir_flag_spec=' '
+      libext=lib
+      ;;
+    darwin* | rhapsody*)
+      hardcode_direct=no
+      if { case $cc_basename in ifort*) true;; *) test "$GCC" = yes;; esac; }; then
+        :
+      else
+        ld_shlibs=no
+      fi
+      ;;
+    dgux*)
+      hardcode_libdir_flag_spec='-L$libdir'
+      ;;
+    freebsd2.[01]*)
+      hardcode_direct=yes
+      hardcode_minus_L=yes
+      ;;
+    freebsd* | dragonfly* | midnightbsd*)
+      hardcode_libdir_flag_spec='-R$libdir'
+      hardcode_direct=yes
+      ;;
+    hpux9*)
+      hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+      hardcode_libdir_separator=:
+      hardcode_direct=yes
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      hardcode_minus_L=yes
+      ;;
+    hpux10*)
+      if test "$with_gnu_ld" = no; then
+        hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+        hardcode_libdir_separator=:
+        hardcode_direct=yes
+        # hardcode_minus_L: Not really in the search PATH,
+        # but as the default location of the library.
+        hardcode_minus_L=yes
+      fi
+      ;;
+    hpux11*)
+      if test "$with_gnu_ld" = no; then
+        hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
+        hardcode_libdir_separator=:
+        case $host_cpu in
+          hppa*64*|ia64*)
+            hardcode_direct=no
+            ;;
+          *)
+            hardcode_direct=yes
+            # hardcode_minus_L: Not really in the search PATH,
+            # but as the default location of the library.
+            hardcode_minus_L=yes
+            ;;
+        esac
+      fi
+      ;;
+    irix5* | irix6* | nonstopux*)
+      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator=:
+      ;;
+    netbsd*)
+      hardcode_libdir_flag_spec='-R$libdir'
+      hardcode_direct=yes
+      ;;
+    newsos6)
+      hardcode_direct=yes
+      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator=:
+      ;;
+    *nto* | *qnx*)
+      ;;
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+        hardcode_direct=yes
+        if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+          hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+        else
+          case "$host_os" in
+            openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+              hardcode_libdir_flag_spec='-R$libdir'
+              ;;
+            *)
+              hardcode_libdir_flag_spec='${wl}-rpath,$libdir'
+              ;;
+          esac
+        fi
+      else
+        ld_shlibs=no
+      fi
+      ;;
+    os2*)
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_minus_L=yes
+      ;;
+    osf3*)
+      hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      hardcode_libdir_separator=:
+      ;;
+    osf4* | osf5*)
+      if test "$GCC" = yes; then
+        hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
+      else
+        # Both cc and cxx compiler support -rpath directly
+        hardcode_libdir_flag_spec='-rpath $libdir'
+      fi
+      hardcode_libdir_separator=:
+      ;;
+    solaris*)
+      hardcode_libdir_flag_spec='-R$libdir'
+      ;;
+    sunos4*)
+      hardcode_libdir_flag_spec='-L$libdir'
+      hardcode_direct=yes
+      hardcode_minus_L=yes
+      ;;
+    sysv4)
+      case $host_vendor in
+        sni)
+          hardcode_direct=yes # is this really true???
+          ;;
+        siemens)
+          hardcode_direct=no
+          ;;
+        motorola)
+          hardcode_direct=no #Motorola manual says yes, but my tests say they lie
+          ;;
+      esac
+      ;;
+    sysv4.3*)
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+        ld_shlibs=yes
+      fi
+      ;;
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*)
+      ;;
+    sysv5* | sco3.2v5* | sco5v6*)
+      hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`'
+      hardcode_libdir_separator=':'
+      ;;
+    uts4*)
+      hardcode_libdir_flag_spec='-L$libdir'
+      ;;
+    *)
+      ld_shlibs=no
+      ;;
+  esac
+fi
+
+# Check dynamic linker characteristics
+# Code taken from libtool.m4's _LT_SYS_DYNAMIC_LINKER.
+# Unlike libtool.m4, here we don't care about _all_ names of the library, but
+# only about the one the linker finds when passed -lNAME. This is the last
+# element of library_names_spec in libtool.m4, or possibly two of them if the
+# linker has special search rules.
+library_names_spec=      # the last element of library_names_spec in libtool.m4
+libname_spec='lib$name'
+case "$host_os" in
+  aix3*)
+    library_names_spec='$libname.a'
+    ;;
+  aix[4-9]*)
+    library_names_spec='$libname$shrext'
+    ;;
+  amigaos*)
+    case "$host_cpu" in
+      powerpc*)
+        library_names_spec='$libname$shrext' ;;
+      m68k)
+        library_names_spec='$libname.a' ;;
+    esac
+    ;;
+  beos*)
+    library_names_spec='$libname$shrext'
+    ;;
+  bsdi[45]*)
+    library_names_spec='$libname$shrext'
+    ;;
+  cygwin* | mingw* | pw32* | cegcc*)
+    shrext=.dll
+    library_names_spec='$libname.dll.a $libname.lib'
+    ;;
+  darwin* | rhapsody*)
+    shrext=.dylib
+    library_names_spec='$libname$shrext'
+    ;;
+  dgux*)
+    library_names_spec='$libname$shrext'
+    ;;
+  freebsd[23].*)
+    library_names_spec='$libname$shrext$versuffix'
+    ;;
+  freebsd* | dragonfly* | midnightbsd*)
+    library_names_spec='$libname$shrext'
+    ;;
+  gnu*)
+    library_names_spec='$libname$shrext'
+    ;;
+  haiku*)
+    library_names_spec='$libname$shrext'
+    ;;
+  hpux9* | hpux10* | hpux11*)
+    case $host_cpu in
+      ia64*)
+        shrext=.so
+        ;;
+      hppa*64*)
+        shrext=.sl
+        ;;
+      *)
+        shrext=.sl
+        ;;
+    esac
+    library_names_spec='$libname$shrext'
+    ;;
+  interix[3-9]*)
+    library_names_spec='$libname$shrext'
+    ;;
+  irix5* | irix6* | nonstopux*)
+    library_names_spec='$libname$shrext'
+    case "$host_os" in
+      irix5* | nonstopux*)
+        libsuff= shlibsuff=
+        ;;
+      *)
+        case $LD in
+          *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= ;;
+          *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 ;;
+          *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 ;;
+          *) libsuff= shlibsuff= ;;
+        esac
+        ;;
+    esac
+    ;;
+  linux*oldld* | linux*aout* | linux*coff*)
+    ;;
+  linux* | k*bsd*-gnu | kopensolaris*-gnu)
+    library_names_spec='$libname$shrext'
+    ;;
+  knetbsd*-gnu)
+    library_names_spec='$libname$shrext'
+    ;;
+  netbsd*)
+    library_names_spec='$libname$shrext'
+    ;;
+  newsos6)
+    library_names_spec='$libname$shrext'
+    ;;
+  *nto* | *qnx*)
+    library_names_spec='$libname$shrext'
+    ;;
+  openbsd*)
+    library_names_spec='$libname$shrext$versuffix'
+    ;;
+  os2*)
+    libname_spec='$name'
+    shrext=.dll
+    library_names_spec='$libname.a'
+    ;;
+  osf3* | osf4* | osf5*)
+    library_names_spec='$libname$shrext'
+    ;;
+  rdos*)
+    ;;
+  solaris*)
+    library_names_spec='$libname$shrext'
+    ;;
+  sunos4*)
+    library_names_spec='$libname$shrext$versuffix'
+    ;;
+  sysv4 | sysv4.3*)
+    library_names_spec='$libname$shrext'
+    ;;
+  sysv4*MP*)
+    library_names_spec='$libname$shrext'
+    ;;
+  sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+    library_names_spec='$libname$shrext'
+    ;;
+  tpf*)
+    library_names_spec='$libname$shrext'
+    ;;
+  uts4*)
+    library_names_spec='$libname$shrext'
+    ;;
+esac
+
+sed_quote_subst='s/\(["`$\\]\)/\\\1/g'
+escaped_wl=`echo "X$wl" | sed -e 's/^X//' -e "$sed_quote_subst"`
+shlibext=`echo "$shrext" | sed -e 's,^\.,,'`
+escaped_libname_spec=`echo "X$libname_spec" | sed -e 's/^X//' -e "$sed_quote_subst"`
+escaped_library_names_spec=`echo "X$library_names_spec" | sed -e 's/^X//' -e "$sed_quote_subst"`
+escaped_hardcode_libdir_flag_spec=`echo "X$hardcode_libdir_flag_spec" | sed -e 's/^X//' -e "$sed_quote_subst"`
+
+LC_ALL=C sed -e 's/^\([a-zA-Z0-9_]*\)=/acl_cv_\1=/' <<EOF
+
+# How to pass a linker flag through the compiler.
+wl="$escaped_wl"
+
+# Static library suffix (normally "a").
+libext="$libext"
+
+# Shared library suffix (normally "so").
+shlibext="$shlibext"
+
+# Format of library name prefix.
+libname_spec="$escaped_libname_spec"
+
+# Library names that the linker finds when passed -lNAME.
+library_names_spec="$escaped_library_names_spec"
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec="$escaped_hardcode_libdir_flag_spec"
+
+# Whether we need a single -rpath flag with a separated argument.
+hardcode_libdir_separator="$hardcode_libdir_separator"
+
+# Set to yes if using DIR/libNAME.so during linking hardcodes DIR into the
+# resulting binary.
+hardcode_direct="$hardcode_direct"
+
+# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
+# resulting binary.
+hardcode_minus_L="$hardcode_minus_L"
+
+EOF
diff --git a/po/en@boldquot.header b/po/en@boldquot.header
new file mode 100644
index 0000000..506ca9e
--- /dev/null
+++ b/po/en@boldquot.header
@@ -0,0 +1,25 @@
+# All this catalog "translates" are quotation characters.
+# The msgids must be ASCII and therefore cannot contain real quotation
+# characters, only substitutes like grave accent (0x60), apostrophe (0x27)
+# and double quote (0x22). These substitutes look strange; see
+# https://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html
+#
+# This catalog translates grave accent (0x60) and apostrophe (0x27) to
+# left single quotation mark (U+2018) and right single quotation mark (U+2019).
+# It also translates pairs of apostrophe (0x27) to
+# left single quotation mark (U+2018) and right single quotation mark (U+2019)
+# and pairs of quotation mark (0x22) to
+# left double quotation mark (U+201C) and right double quotation mark (U+201D).
+#
+# When output to an UTF-8 terminal, the quotation characters appear perfectly.
+# When output to an ISO-8859-1 terminal, the single quotation marks are
+# transliterated to apostrophes (by iconv in glibc 2.2 or newer) or to
+# grave/acute accent (by libiconv), and the double quotation marks are
+# transliterated to 0x22.
+# When output to an ASCII terminal, the single quotation marks are
+# transliterated to apostrophes, and the double quotation marks are
+# transliterated to 0x22.
+#
+# This catalog furthermore displays the text between the quotation marks in
+# bold face, assuming the VT100/XTerm escape sequences.
+#
diff --git a/po/en@quot.header b/po/en@quot.header
new file mode 100644
index 0000000..6522f0c
--- /dev/null
+++ b/po/en@quot.header
@@ -0,0 +1,22 @@
+# All this catalog "translates" are quotation characters.
+# The msgids must be ASCII and therefore cannot contain real quotation
+# characters, only substitutes like grave accent (0x60), apostrophe (0x27)
+# and double quote (0x22). These substitutes look strange; see
+# https://www.cl.cam.ac.uk/~mgk25/ucs/quotes.html
+#
+# This catalog translates grave accent (0x60) and apostrophe (0x27) to
+# left single quotation mark (U+2018) and right single quotation mark (U+2019).
+# It also translates pairs of apostrophe (0x27) to
+# left single quotation mark (U+2018) and right single quotation mark (U+2019)
+# and pairs of quotation mark (0x22) to
+# left double quotation mark (U+201C) and right double quotation mark (U+201D).
+#
+# When output to an UTF-8 terminal, the quotation characters appear perfectly.
+# When output to an ISO-8859-1 terminal, the single quotation marks are
+# transliterated to apostrophes (by iconv in glibc 2.2 or newer) or to
+# grave/acute accent (by libiconv), and the double quotation marks are
+# transliterated to 0x22.
+# When output to an ASCII terminal, the single quotation marks are
+# transliterated to apostrophes, and the double quotation marks are
+# transliterated to 0x22.
+#
diff --git a/po/insert-header.sin b/po/insert-header.sin
new file mode 100644
index 0000000..ceeebb9
--- /dev/null
+++ b/po/insert-header.sin
@@ -0,0 +1,28 @@
+# Sed script that inserts the file called HEADER before the header entry.
+#
+# Copyright (C) 2001 Free Software Foundation, Inc.
+# Written by Bruno Haible <bruno@clisp.org>, 2001.
+# This file is free software; the Free Software Foundation gives
+# unlimited permission to use, copy, distribute, and modify it.
+#
+# At each occurrence of a line starting with "msgid ", we execute the following
+# commands. At the first occurrence, insert the file. At the following
+# occurrences, do nothing. The distinction between the first and the following
+# occurrences is achieved by looking at the hold space.
+/^msgid /{
+x
+# Test if the hold space is empty.
+s/m/m/
+ta
+# Yes it was empty. First occurrence. Read the file.
+r HEADER
+# Output the file's contents by reading the next line. But don't lose the
+# current line while doing this.
+g
+N
+bb
+:a
+# The hold space was nonempty. Following occurrences. Do nothing.
+x
+:b
+}
diff --git a/po/libmicrohttpd.pot b/po/libmicrohttpd.pot
new file mode 100644
index 0000000..d789804
--- /dev/null
+++ b/po/libmicrohttpd.pot
@@ -0,0 +1,1053 @@
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR Free Software Foundation, Inc.
+# This file is distributed under the same license as the GNU libmicrohttpd package.
+# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: GNU libmicrohttpd 0.9.75\n"
+"Report-Msgid-Bugs-To: libmicrohttpd@gnu.org\n"
+"POT-Creation-Date: 2021-12-26 20:30+0300\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"Language: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=CHARSET\n"
+"Content-Transfer-Encoding: 8bit\n"
+
+#: src/microhttpd/connection_https.c:167
+msgid "Error: received handshake message out of context.\n"
+msgstr ""
+
+#: src/microhttpd/mhd_locks.h:127
+msgid "Failed to destroy mutex.\n"
+msgstr ""
+
+#: src/microhttpd/mhd_locks.h:160
+msgid "Failed to lock mutex.\n"
+msgstr ""
+
+#: src/microhttpd/mhd_locks.h:186
+msgid "Failed to unlock mutex.\n"
+msgstr ""
+
+#: src/microhttpd/internal.h:105
+msgid "Failed to close FD.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:605
+msgid ""
+"Stale nonce received.  If this happens a lot, you should probably increase "
+"the size of the nonce array.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:807
+msgid "Failed to allocate memory for copy of URI arguments.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:951
+msgid "Authentication failed, invalid timestamp format.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1013
+msgid "Authentication failed, invalid format.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1023
+msgid "Authentication failed, invalid nc format.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1049
+msgid "Failed to allocate memory for auth header processing.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1109
+msgid "Authentication failed, URI does not match.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1128
+msgid "Authentication failed, arguments do not match.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1290
+msgid "Digest size mismatch.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1383
+msgid "Could not register nonce (is the nonce array size zero?).\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1408
+msgid "Failed to allocate memory for auth response header.\n"
+msgstr ""
+
+#: src/microhttpd/digestauth.c:1450
+msgid "Failed to add Digest auth header.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:137
+#, c-format
+msgid "Fatal error in GNU libmicrohttpd %s:%u: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:450
+msgid "Failed to add IP connection count node.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:508
+msgid "Failed to find previously-added IP address.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:514
+msgid "Previously-added IP address had counter of zero.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:566
+msgid "Too long trust certificate.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:578
+msgid "Bad trust certificate format.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:603
+msgid "Too long key or certificate.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:624
+msgid ""
+"Failed to setup x509 certificate/key: pre 3.X.X version of GnuTLS does not "
+"support setting key password.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:638
+#, c-format
+msgid "GnuTLS failed to setup x509 certificate/key: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:653
+msgid "You need to specify a certificate and key location.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:683
+#, c-format
+msgid "Error: invalid credentials type %d specified.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1093
+#, c-format
+msgid "Maximum socket in select set: %d\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1156
+msgid ""
+"MHD_get_fdset2() called with except_fd_set set to NULL. Such behavior is "
+"unsupported.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1373 src/microhttpd/daemon.c:7532
+msgid ""
+"Initiated daemon shutdown while \"upgraded\" connection was not closed.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1387
+#, c-format
+msgid ""
+"Failed to forward to application %<PRIu64> bytes of data received from "
+"remote side: application shut down socket.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1555
+#, c-format
+msgid ""
+"Failed to forward to remote client %<PRIu64> bytes of data received from "
+"application: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1625
+#, c-format
+msgid ""
+"Failed to forward to application %<PRIu64> bytes of data received from "
+"remote side: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1681
+#, c-format
+msgid ""
+"Failed to forward to remote client %<PRIu64> bytes of data received from "
+"application: daemon shut down.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1751
+msgid "Error preparing select.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1786 src/microhttpd/daemon.c:1988
+#: src/microhttpd/daemon.c:2126
+#, c-format
+msgid "Error during select (%d): `%s'\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1836 src/microhttpd/daemon.c:2009
+#: src/microhttpd/daemon.c:2195
+#, c-format
+msgid "Error during poll: `%s'\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:1972 src/microhttpd/daemon.c:2108
+msgid "Failed to add FD to fd_set.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2247
+msgid "Processing thread terminating. Closing connection.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2277
+msgid ""
+"Failed to signal thread termination via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2359
+msgid "Internal server error. This should be impossible.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2369 src/microhttpd/daemon.c:2408
+msgid "PSK not supported by this server.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2384
+msgid "PSK authentication failed: gnutls_malloc failed to allocate memory.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2393
+msgid "PSK authentication failed: PSK too long.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2456
+#, c-format
+msgid "Accepted connection on socket %d.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2469 src/microhttpd/daemon.c:2790
+msgid "Server reached connection limit. Closing inbound connection.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2487
+msgid "Connection rejected by application. Closing connection.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2505 src/microhttpd/daemon.c:2532
+#: src/microhttpd/daemon.c:2774 src/microhttpd/daemon.c:4413
+#, c-format
+msgid "Error allocating memory: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2602
+msgid "Failed to initialise TLS session.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2628
+msgid "Failed to set ALPN protocols.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2656
+#, c-format
+msgid "Failed to setup TLS credentials: unknown credential type %d.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2666
+msgid "Unknown credential type.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2693
+msgid "TLS connection on non-TLS daemon.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2831 src/microhttpd/daemon.c:7189
+msgid ""
+"Failed to create a new thread because it would have exceeded the system "
+"limit on the number of threads or no system resources available.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2837
+#, c-format
+msgid "Failed to create a thread: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2869 src/microhttpd/daemon.c:4924
+#: src/microhttpd/daemon.c:4957 src/microhttpd/daemon.c:6330
+#: src/microhttpd/daemon.c:6349 src/microhttpd/connection.c:4908
+#: src/microhttpd/response.c:1787 src/microhttpd/response.c:1813
+#, c-format
+msgid "Call to epoll_ctl failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:2989
+#, c-format
+msgid ""
+"New connection socket descriptor (%d) is not less than FD_SETSIZE (%d).\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3006
+msgid "Epoll mode supports only non-blocking sockets\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3043
+msgid ""
+"Failed to signal new connection via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3088
+msgid "Failed to start serving new connection.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3162 src/microhttpd/daemon.c:3832
+#: src/microhttpd/daemon.c:7399 src/microhttpd/connection.c:899
+#: src/microhttpd/connection.c:918
+msgid "Failed to remove FD from epoll set.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3220
+msgid "Cannot suspend connections without enabling MHD_ALLOW_SUSPEND_RESUME!\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3227
+msgid "Error: connection scheduled for \"upgrade\" cannot be suspended.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3251
+msgid "Cannot resume connections without enabling MHD_ALLOW_SUSPEND_RESUME!\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3266
+msgid "Failed to signal resume via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3406
+msgid ""
+"Failed to signal resume of connection via inter-thread communication "
+"channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3460
+msgid ""
+"MHD_add_connection() has been called for daemon started without MHD_USE_ITC "
+"flag.\n"
+"Daemon will not process newly added connection until any activity occurs in "
+"already added sockets.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3471
+#, c-format
+msgid "Failed to set nonblocking mode on new client socket: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3490
+#, c-format
+msgid "Failed to suppress SIGPIPE on new client socket: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3516
+msgid "Failed to set noninheritable mode on new client socket.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3646
+#, c-format
+msgid "Error accepting connection: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3663
+msgid ""
+"Hit process or system resource limit at FIRST connection. This is really bad "
+"as there is no sane way to proceed. Will try busy waiting for system "
+"resources to become magically available.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3680
+#, c-format
+msgid ""
+"Hit process or system resource limit at %u connections, temporarily "
+"suspending accept(). Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3694
+#, c-format
+msgid "Failed to set nonblocking mode on incoming connection socket: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3708
+msgid "Failed to set noninheritable mode on incoming connection socket.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3720
+#, c-format
+msgid "Failed to suppress SIGPIPE on incoming connection socket: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3742
+#, c-format
+msgid "Accepted connection on socket %d\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3787 src/microhttpd/daemon.c:7573
+#: src/microhttpd/daemon.c:7605 src/microhttpd/daemon.c:7638
+#: src/microhttpd/daemon.c:7744
+msgid "Failed to join a thread.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:3911
+msgid "Illegal call to MHD_get_timeout.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4142
+msgid ""
+"MHD_run_from_select() called with except_fd_set set to NULL. Such behavior "
+"is deprecated.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4223
+msgid "Could not obtain daemon fdsets.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4240
+msgid "Could not add listen socket to fdset.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4269
+msgid "Could not add control inter-thread communication channel FD to fdset.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4349
+#, c-format
+msgid "select failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4489 src/microhttpd/daemon.c:4643
+#, c-format
+msgid "poll failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4786 src/microhttpd/daemon.c:5011
+#, c-format
+msgid "Call to epoll_wait failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:4976 src/microhttpd/daemon.c:5531
+msgid "Failed to remove listen FD from epoll set.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5376
+#, c-format
+msgid "Failed to block SIGPIPE on daemon thread: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5512
+msgid "Using MHD_quiesce_daemon in this mode requires MHD_USE_ITC.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5540
+msgid "Failed to signal quiesce via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5563
+msgid "failed to signal quiesce via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5675 src/microhttpd/connection.c:5048
+#, c-format
+msgid ""
+"The specified connection timeout (%u) is too large. Maximum allowed value "
+"(%<PRIu64>) will be used instead.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5726
+msgid ""
+"Warning: Zero size, specified for thread pool size, is ignored. Thread pool "
+"is not used.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5735
+msgid ""
+"Warning: \"1\", specified for thread pool size, is ignored. Thread pool is "
+"not used.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5749
+#, c-format
+msgid "Specified thread pool size (%u) too big.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5761
+msgid ""
+"MHD_OPTION_THREAD_POOL_SIZE option is specified but "
+"MHD_USE_INTERNAL_POLLING_THREAD flag is not specified.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5770
+msgid ""
+"Both MHD_OPTION_THREAD_POOL_SIZE option and MHD_USE_THREAD_PER_CONNECTION "
+"flag are specified.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5788 src/microhttpd/daemon.c:5801
+#: src/microhttpd/daemon.c:5814 src/microhttpd/daemon.c:5827
+#: src/microhttpd/daemon.c:5879 src/microhttpd/daemon.c:5908
+#: src/microhttpd/daemon.c:5929 src/microhttpd/daemon.c:5951
+#: src/microhttpd/daemon.c:6219
+#, c-format
+msgid "MHD HTTPS option %d passed to MHD but MHD_USE_TLS not set.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5847
+msgid "Error initializing DH parameters.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5857
+msgid "Diffie-Hellman parameters string too long.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5868
+msgid "Bad Diffie-Hellman parameters format.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5896
+#, c-format
+msgid "Setting priorities to `%s' failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5917
+msgid ""
+"MHD_OPTION_HTTPS_CERT_CALLBACK requires building MHD with GnuTLS >= 3.0.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5939
+msgid ""
+"MHD_OPTION_HTTPS_CERT_CALLBACK2 requires building MHD with GnuTLS >= 3.6.3.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:5974
+msgid ""
+"MHD_OPTION_LISTEN_SOCKET specified for daemon with MHD_USE_NO_LISTEN_SOCKET "
+"flag set.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6012
+msgid ""
+"MHD_OPTION_EXTERNAL_LOGGER is not the first option specified for the daemon. "
+"Some messages may be printed by the standard MHD logger.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6037
+msgid "TCP fastopen is not supported on this platform.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6056
+msgid ""
+"Flag MHD_USE_PEDANTIC_CHECKS is ignored because another behavior is "
+"specified by MHD_OPTION_STRICT_CLIENT.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6194
+#, c-format
+msgid "MHD HTTPS option %d passed to MHD compiled without GNUtls >= 3.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6233
+#, c-format
+msgid "MHD HTTPS option %d passed to MHD compiled without HTTPS support.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6240
+#, c-format
+msgid "Invalid option %d! (Did you terminate the list with MHD_OPTION_END?).\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6270
+#, c-format
+msgid "Call to epoll_create1 failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6280
+msgid "Failed to set noninheritable mode on epoll FD.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6587
+msgid ""
+"Warning: MHD_USE_THREAD_PER_CONNECTION must be used only with "
+"MHD_USE_INTERNAL_POLLING_THREAD. Flag MHD_USE_INTERNAL_POLLING_THREAD was "
+"added. Consider setting MHD_USE_INTERNAL_POLLING_THREAD explicitly.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6600
+msgid "Using debug build of libmicrohttpd.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6614
+#, c-format
+msgid "Failed to create inter-thread communication channel: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6631
+msgid ""
+"file descriptor for inter-thread communication channel exceeds maximum "
+"value.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6651
+msgid "Specified value for NC_SIZE too large.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6665
+#, c-format
+msgid "Failed to allocate memory for nonce-nc map: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6682
+msgid "MHD failed to initialize nonce-nc mutex.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6703
+msgid "MHD thread polling only works with MHD_USE_INTERNAL_POLLING_THREAD.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6727
+#, c-format
+msgid "Failed to create socket for listening: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6748 src/microhttpd/daemon.c:6767
+#: src/microhttpd/daemon.c:6790 src/microhttpd/daemon.c:6828
+#: src/microhttpd/daemon.c:6905 src/microhttpd/daemon.c:6936
+#, c-format
+msgid "setsockopt failed: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6801
+msgid "Cannot allow listening address reuse: SO_REUSEPORT not defined.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6837
+msgid ""
+"Cannot disallow listening address reuse: SO_EXCLUSIVEADDRUSE not defined.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6916
+#, c-format
+msgid "Failed to bind to port %u: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6947
+#, c-format
+msgid "Failed to listen for connections: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6978
+#, c-format
+msgid "Failed to get listen port number: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:6989
+msgid ""
+"Failed to get listen port number (`struct sockaddr_storage` too small!?).\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7030
+msgid "Unknown address family!\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7045
+#, c-format
+msgid "Failed to set nonblocking mode on listening socket: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7070
+#, c-format
+msgid "Listen socket descriptor (%d) is not less than FD_SETSIZE (%d).\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7094
+msgid ""
+"Combining MHD_USE_THREAD_PER_CONNECTION and MHD_USE_EPOLL is not supported.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7108 src/microhttpd/daemon.c:7118
+msgid "MHD failed to initialize IP connection limit mutex.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7136
+msgid "Failed to initialize TLS support.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7169 src/microhttpd/daemon.c:7242
+#: src/microhttpd/daemon.c:7349
+msgid "Failed to initialise mutex.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7195
+#, c-format
+msgid "Failed to create listen thread: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7253
+#, c-format
+msgid "Failed to create worker inter-thread communication channel: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7266
+msgid ""
+"File descriptor for worker inter-thread communication channel exceeds "
+"maximum value.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7304
+msgid "MHD failed to initialize cleanup connection mutex.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7323
+msgid ""
+"Failed to create a new pool thread because it would have exceeded the system "
+"limit on the number of threads or no system resources available.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7329
+#, c-format
+msgid "Failed to create pool thread: %s\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7518 src/microhttpd/daemon.c:7551
+msgid "MHD_stop_daemon() called while we have suspended connections.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7590 src/microhttpd/daemon.c:7688
+#: src/microhttpd/daemon.c:7726
+msgid "Failed to signal shutdown via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:7663
+msgid "MHD_stop_daemon() was called twice."
+msgstr ""
+
+#: src/microhttpd/daemon.c:8176
+msgid "Failed to initialize winsock.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:8179
+msgid "Winsock version 2.2 is not available.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:8187 src/microhttpd/daemon.c:8191
+msgid "Failed to initialise multithreading in libgcrypt.\n"
+msgstr ""
+
+#: src/microhttpd/daemon.c:8197
+msgid "libgcrypt is too old. MHD was compiled for libgcrypt 1.6.0 or newer.\n"
+msgstr ""
+
+#: src/microhttpd/mhd_sockets.h:345
+msgid "Close socket failed.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:206
+msgid "The operation would block, retry later"
+msgstr ""
+
+#: src/microhttpd/connection.c:208
+msgid "The connection was forcibly closed by remote peer"
+msgstr ""
+
+#: src/microhttpd/connection.c:210
+msgid "The socket is not connected"
+msgstr ""
+
+#: src/microhttpd/connection.c:212
+msgid "Not enough system resources to serve the request"
+msgstr ""
+
+#: src/microhttpd/connection.c:214
+msgid "Bad FD value"
+msgstr ""
+
+#: src/microhttpd/connection.c:216
+msgid "Argument value is invalid"
+msgstr ""
+
+#: src/microhttpd/connection.c:218
+msgid "Argument value is not supported"
+msgstr ""
+
+#: src/microhttpd/connection.c:220
+msgid "The socket is no longer available for sending"
+msgstr ""
+
+#: src/microhttpd/connection.c:222
+msgid "TLS encryption or decryption error"
+msgstr ""
+
+#: src/microhttpd/connection.c:227
+msgid "Not an error code"
+msgstr ""
+
+#: src/microhttpd/connection.c:230
+msgid "Wrong error code value"
+msgstr ""
+
+#: src/microhttpd/connection.c:1047 src/microhttpd/connection.c:1157
+msgid "Closing connection (out of memory)."
+msgstr ""
+
+#: src/microhttpd/connection.c:1094
+msgid "Closing connection (application reported error generating data)."
+msgstr ""
+
+#: src/microhttpd/connection.c:1212
+msgid "No callback for the chunked data."
+msgstr ""
+
+#: src/microhttpd/connection.c:1230
+msgid "Closing connection (application error generating response)."
+msgstr ""
+
+#: src/microhttpd/connection.c:1254
+msgid "Closing connection (application returned more data than requested)."
+msgstr ""
+
+#: src/microhttpd/connection.c:2292
+#, c-format
+msgid ""
+"Error processing request (HTTP response code is %u ('%s')). Closing "
+"connection.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:2301
+msgid "Too late to send an error response, response is being sent already.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:2307
+msgid "Too late for error response."
+msgstr ""
+
+#: src/microhttpd/connection.c:2335
+msgid "Failed to create error response.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:2351
+msgid "Closing connection (failed to queue error response)."
+msgstr ""
+
+#: src/microhttpd/connection.c:2383
+msgid "Closing connection (failed to create error response header)."
+msgstr ""
+
+#: src/microhttpd/connection.c:2435 src/microhttpd/connection.c:3795
+#: src/microhttpd/connection.c:3872 src/microhttpd/connection.c:4437
+#, c-format
+msgid "In function %s handling connection at state: %s\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:2678
+msgid "Not enough memory in pool to allocate header record!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:2724
+msgid "Not enough memory in pool to parse cookies!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3083 src/microhttpd/connection.c:3322
+msgid "Application reported internal error, closing connection."
+msgstr ""
+
+#: src/microhttpd/connection.c:3331
+msgid "libmicrohttpd API violation.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3346
+msgid ""
+"WARNING: incomplete upload processing and connection not suspended may "
+"result in hung connection.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3573
+msgid "Received HTTP/1.1 request without `Host' header.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3620
+msgid "Too large value of 'Content-Length' header. Closing connection.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3631
+msgid "Failed to parse `Content-Length' header. Closing connection.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3744
+msgid "Socket has been disconnected when reading request.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3756
+#, c-format
+msgid "Connection socket is closed when reading request due to the error: %s\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3774
+msgid "Connection was closed by remote side with incomplete request.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3900
+#, c-format
+msgid "Failed to send data in request for %s.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3909
+#, c-format
+msgid "Sent 100 continue response: `%.*s'\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:3986
+#, c-format
+msgid ""
+"Failed to send the response headers for the request for `%s'. Error: %s\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4052
+msgid "Data offset exceeds limit.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4062
+#, c-format
+msgid "Sent %d-byte DATA response: `%.*s'\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4079
+#, c-format
+msgid "Failed to send the response body for the request for `%s'. Error: %s\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4111
+#, c-format
+msgid ""
+"Failed to send the chunked response body for the request for `%s'. Error: "
+"%s\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4147
+#, c-format
+msgid "Failed to send the footers for the request for `%s'. Error: %s\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4176
+msgid "Internal error.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4215
+#, c-format
+msgid "Detected system clock %u milliseconds jump back.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4222
+#, c-format
+msgid "Detected too large system clock %<PRIu64> milliseconds jump back.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4304
+msgid ""
+"Failed to signal end of connection via inter-thread communication channel.\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4688
+msgid "Closing connection (failed to create response header).\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:4807
+msgid "Closing connection (failed to create response footer)."
+msgstr ""
+
+#: src/microhttpd/connection.c:5117
+msgid "Attempted to queue response on wrong thread!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5140
+msgid ""
+"Attempted 'upgrade' connection on daemon without MHD_ALLOW_UPGRADE option!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5149
+msgid "Application used invalid status code for 'upgrade' response!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5158
+msgid "Application used invalid response without \"Connection\" header!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5172
+msgid ""
+"Application used invalid response without \"upgrade\" token in \"Connection"
+"\" header!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5182
+msgid "Connection \"Upgrade\" can be used with HTTP/1.1 connections!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5194
+#, c-format
+msgid ""
+"Refused wrong status code (%u). HTTP requires three digits status code!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5206
+#, c-format
+msgid ""
+"Wrong status code (%u) refused. HTTP/1.0 clients do not support 1xx status "
+"codes!\n"
+msgstr ""
+
+#: src/microhttpd/connection.c:5217
+#, c-format
+msgid ""
+"Wrong status code (%u) refused. HTTP/1.0 reply mode does not support 1xx "
+"status codes!\n"
+msgstr ""
+
+#: src/microhttpd/response.c:1646
+msgid ""
+"Invalid response for upgrade: application failed to set the 'Upgrade' "
+"header!\n"
+msgstr ""
+
+#: src/microhttpd/response.c:1690
+msgid "Failed to make loopback sockets non-blocking.\n"
+msgstr ""
+
+#: src/microhttpd/response.c:1709
+msgid "Failed to set SO_NOSIGPIPE on loopback sockets.\n"
+msgstr ""
+
+#: src/microhttpd/response.c:1729
+#, c-format
+msgid "Socketpair descriptor larger than FD_SETSIZE: %d > %d\n"
+msgstr ""
+
+#: src/microhttpd/response.c:1810
+msgid "Error cleaning up while handling epoll error.\n"
+msgstr ""
+
+#: src/microhttpd/mhd_itc.h:357
+msgid "Failed to destroy ITC.\n"
+msgstr ""
+
+#: src/microhttpd/basicauth.c:71
+msgid "Error decoding basic authentication.\n"
+msgstr ""
+
+#: src/microhttpd/basicauth.c:81
+msgid "Basic authentication doesn't contain ':' separator.\n"
+msgstr ""
+
+#: src/microhttpd/basicauth.c:99
+msgid "Failed to allocate memory for password.\n"
+msgstr ""
+
+#: src/microhttpd/basicauth.c:164
+msgid "Failed to add Basic auth header.\n"
+msgstr ""
diff --git a/po/m4/gettext.m4 b/po/m4/gettext.m4
new file mode 100644
index 0000000..f449240
--- /dev/null
+++ b/po/m4/gettext.m4
@@ -0,0 +1,386 @@
+# gettext.m4 serial 72 (gettext-0.21.1)
+dnl Copyright (C) 1995-2014, 2016, 2018-2020 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl   Bruno Haible <haible@clisp.cons.org>, 2000-2006, 2008-2010.
+
+dnl Macro to add for using GNU gettext.
+
+dnl Usage: AM_GNU_GETTEXT([INTLSYMBOL], [NEEDSYMBOL], [INTLDIR]).
+dnl INTLSYMBOL must be one of 'external', 'use-libtool'.
+dnl    INTLSYMBOL should be 'external' for packages other than GNU gettext, and
+dnl    'use-libtool' for the packages 'gettext-runtime' and 'gettext-tools'.
+dnl    If INTLSYMBOL is 'use-libtool', then a libtool library
+dnl    $(top_builddir)/intl/libintl.la will be created (shared and/or static,
+dnl    depending on --{enable,disable}-{shared,static} and on the presence of
+dnl    AM-DISABLE-SHARED).
+dnl If NEEDSYMBOL is specified and is 'need-ngettext', then GNU gettext
+dnl    implementations (in libc or libintl) without the ngettext() function
+dnl    will be ignored.  If NEEDSYMBOL is specified and is
+dnl    'need-formatstring-macros', then GNU gettext implementations that don't
+dnl    support the ISO C 99 <inttypes.h> formatstring macros will be ignored.
+dnl INTLDIR is used to find the intl libraries.  If empty,
+dnl    the value '$(top_builddir)/intl/' is used.
+dnl
+dnl The result of the configuration is one of three cases:
+dnl 1) GNU gettext, as included in the intl subdirectory, will be compiled
+dnl    and used.
+dnl    Catalog format: GNU --> install in $(datadir)
+dnl    Catalog extension: .mo after installation, .gmo in source tree
+dnl 2) GNU gettext has been found in the system's C library.
+dnl    Catalog format: GNU --> install in $(datadir)
+dnl    Catalog extension: .mo after installation, .gmo in source tree
+dnl 3) No internationalization, always use English msgid.
+dnl    Catalog format: none
+dnl    Catalog extension: none
+dnl If INTLSYMBOL is 'external', only cases 2 and 3 can occur.
+dnl The use of .gmo is historical (it was needed to avoid overwriting the
+dnl GNU format catalogs when building on a platform with an X/Open gettext),
+dnl but we keep it in order not to force irrelevant filename changes on the
+dnl maintainers.
+dnl
+AC_DEFUN([AM_GNU_GETTEXT],
+[
+  dnl Argument checking.
+  m4_if([$1], [], , [m4_if([$1], [external], , [m4_if([$1], [use-libtool], ,
+    [errprint([ERROR: invalid first argument to AM_GNU_GETTEXT
+])])])])
+  m4_if(m4_if([$1], [], [old])[]m4_if([$1], [no-libtool], [old]), [old],
+    [errprint([ERROR: Use of AM_GNU_GETTEXT without [external] argument is no longer supported.
+])])
+  m4_if([$2], [], , [m4_if([$2], [need-ngettext], , [m4_if([$2], [need-formatstring-macros], ,
+    [errprint([ERROR: invalid second argument to AM_GNU_GETTEXT
+])])])])
+  define([gt_included_intl],
+    m4_if([$1], [external], [no], [yes]))
+  gt_NEEDS_INIT
+  AM_GNU_GETTEXT_NEED([$2])
+
+  AC_REQUIRE([AM_PO_SUBDIRS])dnl
+  m4_if(gt_included_intl, yes, [
+    AC_REQUIRE([AM_INTL_SUBDIR])dnl
+  ])
+
+  dnl Prerequisites of AC_LIB_LINKFLAGS_BODY.
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+
+  dnl Sometimes libintl requires libiconv, so first search for libiconv.
+  dnl Ideally we would do this search only after the
+  dnl      if test "$USE_NLS" = "yes"; then
+  dnl        if { eval "gt_val=\$$gt_func_gnugettext_libc"; test "$gt_val" != "yes"; }; then
+  dnl tests. But if configure.in invokes AM_ICONV after AM_GNU_GETTEXT
+  dnl the configure script would need to contain the same shell code
+  dnl again, outside any 'if'. There are two solutions:
+  dnl - Invoke AM_ICONV_LINKFLAGS_BODY here, outside any 'if'.
+  dnl - Control the expansions in more detail using AC_PROVIDE_IFELSE.
+  dnl Since AC_PROVIDE_IFELSE is not documented, we avoid it.
+  m4_if(gt_included_intl, yes, , [
+    AC_REQUIRE([AM_ICONV_LINKFLAGS_BODY])
+  ])
+
+  dnl Sometimes, on Mac OS X, libintl requires linking with CoreFoundation.
+  gt_INTL_MACOSX
+
+  dnl Set USE_NLS.
+  AC_REQUIRE([AM_NLS])
+
+  m4_if(gt_included_intl, yes, [
+    BUILD_INCLUDED_LIBINTL=no
+    USE_INCLUDED_LIBINTL=no
+  ])
+  LIBINTL=
+  LTLIBINTL=
+  POSUB=
+
+  dnl Add a version number to the cache macros.
+  case " $gt_needs " in
+    *" need-formatstring-macros "*) gt_api_version=3 ;;
+    *" need-ngettext "*) gt_api_version=2 ;;
+    *) gt_api_version=1 ;;
+  esac
+  gt_func_gnugettext_libc="gt_cv_func_gnugettext${gt_api_version}_libc"
+  gt_func_gnugettext_libintl="gt_cv_func_gnugettext${gt_api_version}_libintl"
+
+  dnl If we use NLS figure out what method
+  if test "$USE_NLS" = "yes"; then
+    gt_use_preinstalled_gnugettext=no
+    m4_if(gt_included_intl, yes, [
+      AC_MSG_CHECKING([whether included gettext is requested])
+      AC_ARG_WITH([included-gettext],
+        [  --with-included-gettext use the GNU gettext library included here],
+        nls_cv_force_use_gnu_gettext=$withval,
+        nls_cv_force_use_gnu_gettext=no)
+      AC_MSG_RESULT([$nls_cv_force_use_gnu_gettext])
+
+      nls_cv_use_gnu_gettext="$nls_cv_force_use_gnu_gettext"
+      if test "$nls_cv_force_use_gnu_gettext" != "yes"; then
+    ])
+        dnl User does not insist on using GNU NLS library.  Figure out what
+        dnl to use.  If GNU gettext is available we use this.  Else we have
+        dnl to fall back to GNU NLS library.
+
+        if test $gt_api_version -ge 3; then
+          gt_revision_test_code='
+#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+#define __GNU_GETTEXT_SUPPORTED_REVISION(major) ((major) == 0 ? 0 : -1)
+#endif
+changequote(,)dnl
+typedef int array [2 * (__GNU_GETTEXT_SUPPORTED_REVISION(0) >= 1) - 1];
+changequote([,])dnl
+'
+        else
+          gt_revision_test_code=
+        fi
+        if test $gt_api_version -ge 2; then
+          gt_expression_test_code=' + * ngettext ("", "", 0)'
+        else
+          gt_expression_test_code=
+        fi
+
+        AC_CACHE_CHECK([for GNU gettext in libc], [$gt_func_gnugettext_libc],
+         [AC_LINK_IFELSE(
+            [AC_LANG_PROGRAM(
+               [[
+#include <libintl.h>
+#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+extern int _nl_msg_cat_cntr;
+extern int *_nl_domain_bindings;
+#define __GNU_GETTEXT_SYMBOL_EXPRESSION (_nl_msg_cat_cntr + *_nl_domain_bindings)
+#else
+#define __GNU_GETTEXT_SYMBOL_EXPRESSION 0
+#endif
+$gt_revision_test_code
+               ]],
+               [[
+bindtextdomain ("", "");
+return * gettext ("")$gt_expression_test_code + __GNU_GETTEXT_SYMBOL_EXPRESSION
+               ]])],
+            [eval "$gt_func_gnugettext_libc=yes"],
+            [eval "$gt_func_gnugettext_libc=no"])])
+
+        if { eval "gt_val=\$$gt_func_gnugettext_libc"; test "$gt_val" != "yes"; }; then
+          dnl Sometimes libintl requires libiconv, so first search for libiconv.
+          m4_if(gt_included_intl, yes, , [
+            AM_ICONV_LINK
+          ])
+          dnl Search for libintl and define LIBINTL, LTLIBINTL and INCINTL
+          dnl accordingly. Don't use AC_LIB_LINKFLAGS_BODY([intl],[iconv])
+          dnl because that would add "-liconv" to LIBINTL and LTLIBINTL
+          dnl even if libiconv doesn't exist.
+          AC_LIB_LINKFLAGS_BODY([intl])
+          AC_CACHE_CHECK([for GNU gettext in libintl],
+            [$gt_func_gnugettext_libintl],
+           [gt_save_CPPFLAGS="$CPPFLAGS"
+            CPPFLAGS="$CPPFLAGS $INCINTL"
+            gt_save_LIBS="$LIBS"
+            LIBS="$LIBS $LIBINTL"
+            dnl Now see whether libintl exists and does not depend on libiconv.
+            AC_LINK_IFELSE(
+              [AC_LANG_PROGRAM(
+                 [[
+#include <libintl.h>
+#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+extern int _nl_msg_cat_cntr;
+extern
+#ifdef __cplusplus
+"C"
+#endif
+const char *_nl_expand_alias (const char *);
+#define __GNU_GETTEXT_SYMBOL_EXPRESSION (_nl_msg_cat_cntr + *_nl_expand_alias (""))
+#else
+#define __GNU_GETTEXT_SYMBOL_EXPRESSION 0
+#endif
+$gt_revision_test_code
+                 ]],
+                 [[
+bindtextdomain ("", "");
+return * gettext ("")$gt_expression_test_code + __GNU_GETTEXT_SYMBOL_EXPRESSION
+                 ]])],
+              [eval "$gt_func_gnugettext_libintl=yes"],
+              [eval "$gt_func_gnugettext_libintl=no"])
+            dnl Now see whether libintl exists and depends on libiconv.
+            if { eval "gt_val=\$$gt_func_gnugettext_libintl"; test "$gt_val" != yes; } && test -n "$LIBICONV"; then
+              LIBS="$LIBS $LIBICONV"
+              AC_LINK_IFELSE(
+                [AC_LANG_PROGRAM(
+                   [[
+#include <libintl.h>
+#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+extern int _nl_msg_cat_cntr;
+extern
+#ifdef __cplusplus
+"C"
+#endif
+const char *_nl_expand_alias (const char *);
+#define __GNU_GETTEXT_SYMBOL_EXPRESSION (_nl_msg_cat_cntr + *_nl_expand_alias (""))
+#else
+#define __GNU_GETTEXT_SYMBOL_EXPRESSION 0
+#endif
+$gt_revision_test_code
+                   ]],
+                   [[
+bindtextdomain ("", "");
+return * gettext ("")$gt_expression_test_code + __GNU_GETTEXT_SYMBOL_EXPRESSION
+                   ]])],
+                [LIBINTL="$LIBINTL $LIBICONV"
+                 LTLIBINTL="$LTLIBINTL $LTLIBICONV"
+                 eval "$gt_func_gnugettext_libintl=yes"
+                ])
+            fi
+            CPPFLAGS="$gt_save_CPPFLAGS"
+            LIBS="$gt_save_LIBS"])
+        fi
+
+        dnl If an already present or preinstalled GNU gettext() is found,
+        dnl use it.  But if this macro is used in GNU gettext, and GNU
+        dnl gettext is already preinstalled in libintl, we update this
+        dnl libintl.  (Cf. the install rule in intl/Makefile.in.)
+        if { eval "gt_val=\$$gt_func_gnugettext_libc"; test "$gt_val" = "yes"; } \
+           || { { eval "gt_val=\$$gt_func_gnugettext_libintl"; test "$gt_val" = "yes"; } \
+                && test "$PACKAGE" != gettext-runtime \
+                && test "$PACKAGE" != gettext-tools; }; then
+          gt_use_preinstalled_gnugettext=yes
+        else
+          dnl Reset the values set by searching for libintl.
+          LIBINTL=
+          LTLIBINTL=
+          INCINTL=
+        fi
+
+    m4_if(gt_included_intl, yes, [
+        if test "$gt_use_preinstalled_gnugettext" != "yes"; then
+          dnl GNU gettext is not found in the C library.
+          dnl Fall back on included GNU gettext library.
+          nls_cv_use_gnu_gettext=yes
+        fi
+      fi
+
+      if test "$nls_cv_use_gnu_gettext" = "yes"; then
+        dnl Mark actions used to generate GNU NLS library.
+        BUILD_INCLUDED_LIBINTL=yes
+        USE_INCLUDED_LIBINTL=yes
+        LIBINTL="m4_if([$3],[],\${top_builddir}/intl,[$3])/libintl.la $LIBICONV $LIBTHREAD"
+        LTLIBINTL="m4_if([$3],[],\${top_builddir}/intl,[$3])/libintl.la $LTLIBICONV $LTLIBTHREAD"
+        LIBS=`echo " $LIBS " | sed -e 's/ -lintl / /' -e 's/^ //' -e 's/ $//'`
+      fi
+
+      CATOBJEXT=
+      if test "$gt_use_preinstalled_gnugettext" = "yes" \
+         || test "$nls_cv_use_gnu_gettext" = "yes"; then
+        dnl Mark actions to use GNU gettext tools.
+        CATOBJEXT=.gmo
+      fi
+    ])
+
+    if test -n "$INTL_MACOSX_LIBS"; then
+      if test "$gt_use_preinstalled_gnugettext" = "yes" \
+         || test "$nls_cv_use_gnu_gettext" = "yes"; then
+        dnl Some extra flags are needed during linking.
+        LIBINTL="$LIBINTL $INTL_MACOSX_LIBS"
+        LTLIBINTL="$LTLIBINTL $INTL_MACOSX_LIBS"
+      fi
+    fi
+
+    if test "$gt_use_preinstalled_gnugettext" = "yes" \
+       || test "$nls_cv_use_gnu_gettext" = "yes"; then
+      AC_DEFINE([ENABLE_NLS], [1],
+        [Define to 1 if translation of program messages to the user's native language
+   is requested.])
+    else
+      USE_NLS=no
+    fi
+  fi
+
+  AC_MSG_CHECKING([whether to use NLS])
+  AC_MSG_RESULT([$USE_NLS])
+  if test "$USE_NLS" = "yes"; then
+    AC_MSG_CHECKING([where the gettext function comes from])
+    if test "$gt_use_preinstalled_gnugettext" = "yes"; then
+      if { eval "gt_val=\$$gt_func_gnugettext_libintl"; test "$gt_val" = "yes"; }; then
+        gt_source="external libintl"
+      else
+        gt_source="libc"
+      fi
+    else
+      gt_source="included intl directory"
+    fi
+    AC_MSG_RESULT([$gt_source])
+  fi
+
+  if test "$USE_NLS" = "yes"; then
+
+    if test "$gt_use_preinstalled_gnugettext" = "yes"; then
+      if { eval "gt_val=\$$gt_func_gnugettext_libintl"; test "$gt_val" = "yes"; }; then
+        AC_MSG_CHECKING([how to link with libintl])
+        AC_MSG_RESULT([$LIBINTL])
+        AC_LIB_APPENDTOVAR([CPPFLAGS], [$INCINTL])
+      fi
+
+      dnl For backward compatibility. Some packages may be using this.
+      AC_DEFINE([HAVE_GETTEXT], [1],
+       [Define if the GNU gettext() function is already present or preinstalled.])
+      AC_DEFINE([HAVE_DCGETTEXT], [1],
+       [Define if the GNU dcgettext() function is already present or preinstalled.])
+    fi
+
+    dnl We need to process the po/ directory.
+    POSUB=po
+  fi
+
+  m4_if(gt_included_intl, yes, [
+    dnl In GNU gettext we have to set BUILD_INCLUDED_LIBINTL to 'yes'
+    dnl because some of the testsuite requires it.
+    BUILD_INCLUDED_LIBINTL=yes
+
+    dnl Make all variables we use known to autoconf.
+    AC_SUBST([BUILD_INCLUDED_LIBINTL])
+    AC_SUBST([USE_INCLUDED_LIBINTL])
+    AC_SUBST([CATOBJEXT])
+  ])
+
+  dnl For backward compatibility. Some Makefiles may be using this.
+  INTLLIBS="$LIBINTL"
+  AC_SUBST([INTLLIBS])
+
+  dnl Make all documented variables known to autoconf.
+  AC_SUBST([LIBINTL])
+  AC_SUBST([LTLIBINTL])
+  AC_SUBST([POSUB])
+])
+
+
+dnl gt_NEEDS_INIT ensures that the gt_needs variable is initialized.
+m4_define([gt_NEEDS_INIT],
+[
+  m4_divert_text([DEFAULTS], [gt_needs=])
+  m4_define([gt_NEEDS_INIT], [])
+])
+
+
+dnl Usage: AM_GNU_GETTEXT_NEED([NEEDSYMBOL])
+AC_DEFUN([AM_GNU_GETTEXT_NEED],
+[
+  m4_divert_text([INIT_PREPARE], [gt_needs="$gt_needs $1"])
+])
+
+
+dnl Usage: AM_GNU_GETTEXT_VERSION([gettext-version])
+AC_DEFUN([AM_GNU_GETTEXT_VERSION], [])
+
+
+dnl Usage: AM_GNU_GETTEXT_REQUIRE_VERSION([gettext-version])
+AC_DEFUN([AM_GNU_GETTEXT_REQUIRE_VERSION], [])
diff --git a/po/m4/host-cpu-c-abi.m4 b/po/m4/host-cpu-c-abi.m4
new file mode 100644
index 0000000..b922324
--- /dev/null
+++ b/po/m4/host-cpu-c-abi.m4
@@ -0,0 +1,678 @@
+# host-cpu-c-abi.m4 serial 15
+dnl Copyright (C) 2002-2022 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible and Sam Steingold.
+
+dnl Sets the HOST_CPU variable to the canonical name of the CPU.
+dnl Sets the HOST_CPU_C_ABI variable to the canonical name of the CPU with its
+dnl C language ABI (application binary interface).
+dnl Also defines __${HOST_CPU}__ and __${HOST_CPU_C_ABI}__ as C macros in
+dnl config.h.
+dnl
+dnl This canonical name can be used to select a particular assembly language
+dnl source file that will interoperate with C code on the given host.
+dnl
+dnl For example:
+dnl * 'i386' and 'sparc' are different canonical names, because code for i386
+dnl   will not run on SPARC CPUs and vice versa. They have different
+dnl   instruction sets.
+dnl * 'sparc' and 'sparc64' are different canonical names, because code for
+dnl   'sparc' and code for 'sparc64' cannot be linked together: 'sparc' code
+dnl   contains 32-bit instructions, whereas 'sparc64' code contains 64-bit
+dnl   instructions. A process on a SPARC CPU can be in 32-bit mode or in 64-bit
+dnl   mode, but not both.
+dnl * 'mips' and 'mipsn32' are different canonical names, because they use
+dnl   different argument passing and return conventions for C functions, and
+dnl   although the instruction set of 'mips' is a large subset of the
+dnl   instruction set of 'mipsn32'.
+dnl * 'mipsn32' and 'mips64' are different canonical names, because they use
+dnl   different sizes for the C types like 'int' and 'void *', and although
+dnl   the instruction sets of 'mipsn32' and 'mips64' are the same.
+dnl * The same canonical name is used for different endiannesses. You can
+dnl   determine the endianness through preprocessor symbols:
+dnl   - 'arm': test __ARMEL__.
+dnl   - 'mips', 'mipsn32', 'mips64': test _MIPSEB vs. _MIPSEL.
+dnl   - 'powerpc64': test _BIG_ENDIAN vs. _LITTLE_ENDIAN.
+dnl * The same name 'i386' is used for CPUs of type i386, i486, i586
+dnl   (Pentium), AMD K7, Pentium II, Pentium IV, etc., because
+dnl   - Instructions that do not exist on all of these CPUs (cmpxchg,
+dnl     MMX, SSE, SSE2, 3DNow! etc.) are not frequently used. If your
+dnl     assembly language source files use such instructions, you will
+dnl     need to make the distinction.
+dnl   - Speed of execution of the common instruction set is reasonable across
+dnl     the entire family of CPUs. If you have assembly language source files
+dnl     that are optimized for particular CPU types (like GNU gmp has), you
+dnl     will need to make the distinction.
+dnl   See <https://en.wikipedia.org/wiki/X86_instruction_listings>.
+AC_DEFUN([gl_HOST_CPU_C_ABI],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  AC_REQUIRE([gl_C_ASM])
+  AC_CACHE_CHECK([host CPU and C ABI], [gl_cv_host_cpu_c_abi],
+    [case "$host_cpu" in
+
+changequote(,)dnl
+       i[34567]86 )
+changequote([,])dnl
+         gl_cv_host_cpu_c_abi=i386
+         ;;
+
+       x86_64 )
+         # On x86_64 systems, the C compiler may be generating code in one of
+         # these ABIs:
+         # - 64-bit instruction set, 64-bit pointers, 64-bit 'long': x86_64.
+         # - 64-bit instruction set, 64-bit pointers, 32-bit 'long': x86_64
+         #   with native Windows (mingw, MSVC).
+         # - 64-bit instruction set, 32-bit pointers, 32-bit 'long': x86_64-x32.
+         # - 32-bit instruction set, 32-bit pointers, 32-bit 'long': i386.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if (defined __x86_64__ || defined __amd64__ \
+                     || defined _M_X64 || defined _M_AMD64)
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [AC_COMPILE_IFELSE(
+              [AC_LANG_SOURCE(
+                 [[#if defined __ILP32__ || defined _ILP32
+                    int ok;
+                   #else
+                    error fail
+                   #endif
+                 ]])],
+              [gl_cv_host_cpu_c_abi=x86_64-x32],
+              [gl_cv_host_cpu_c_abi=x86_64])],
+           [gl_cv_host_cpu_c_abi=i386])
+         ;;
+
+changequote(,)dnl
+       alphaev[4-8] | alphaev56 | alphapca5[67] | alphaev6[78] )
+changequote([,])dnl
+         gl_cv_host_cpu_c_abi=alpha
+         ;;
+
+       arm* | aarch64 )
+         # Assume arm with EABI.
+         # On arm64 systems, the C compiler may be generating code in one of
+         # these ABIs:
+         # - aarch64 instruction set, 64-bit pointers, 64-bit 'long': arm64.
+         # - aarch64 instruction set, 32-bit pointers, 32-bit 'long': arm64-ilp32.
+         # - 32-bit instruction set, 32-bit pointers, 32-bit 'long': arm or armhf.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#ifdef __aarch64__
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [AC_COMPILE_IFELSE(
+              [AC_LANG_SOURCE(
+                [[#if defined __ILP32__ || defined _ILP32
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+              [gl_cv_host_cpu_c_abi=arm64-ilp32],
+              [gl_cv_host_cpu_c_abi=arm64])],
+           [# Don't distinguish little-endian and big-endian arm, since they
+            # don't require different machine code for simple operations and
+            # since the user can distinguish them through the preprocessor
+            # defines __ARMEL__ vs. __ARMEB__.
+            # But distinguish arm which passes floating-point arguments and
+            # return values in integer registers (r0, r1, ...) - this is
+            # gcc -mfloat-abi=soft or gcc -mfloat-abi=softfp - from arm which
+            # passes them in float registers (s0, s1, ...) and double registers
+            # (d0, d1, ...) - this is gcc -mfloat-abi=hard. GCC 4.6 or newer
+            # sets the preprocessor defines __ARM_PCS (for the first case) and
+            # __ARM_PCS_VFP (for the second case), but older GCC does not.
+            echo 'double ddd; void func (double dd) { ddd = dd; }' > conftest.c
+            # Look for a reference to the register d0 in the .s file.
+            AC_TRY_COMMAND(${CC-cc} $CFLAGS $CPPFLAGS $gl_c_asm_opt conftest.c) >/dev/null 2>&1
+            if LC_ALL=C grep 'd0,' conftest.$gl_asmext >/dev/null; then
+              gl_cv_host_cpu_c_abi=armhf
+            else
+              gl_cv_host_cpu_c_abi=arm
+            fi
+            rm -f conftest*
+           ])
+         ;;
+
+       hppa1.0 | hppa1.1 | hppa2.0* | hppa64 )
+         # On hppa, the C compiler may be generating 32-bit code or 64-bit
+         # code. In the latter case, it defines _LP64 and __LP64__.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#ifdef __LP64__
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [gl_cv_host_cpu_c_abi=hppa64],
+           [gl_cv_host_cpu_c_abi=hppa])
+         ;;
+
+       ia64* )
+         # On ia64 on HP-UX, the C compiler may be generating 64-bit code or
+         # 32-bit code. In the latter case, it defines _ILP32.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#ifdef _ILP32
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [gl_cv_host_cpu_c_abi=ia64-ilp32],
+           [gl_cv_host_cpu_c_abi=ia64])
+         ;;
+
+       mips* )
+         # We should also check for (_MIPS_SZPTR == 64), but gcc keeps this
+         # at 32.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if defined _MIPS_SZLONG && (_MIPS_SZLONG == 64)
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [gl_cv_host_cpu_c_abi=mips64],
+           [# In the n32 ABI, _ABIN32 is defined, _ABIO32 is not defined (but
+            # may later get defined by <sgidefs.h>), and _MIPS_SIM == _ABIN32.
+            # In the 32 ABI, _ABIO32 is defined, _ABIN32 is not defined (but
+            # may later get defined by <sgidefs.h>), and _MIPS_SIM == _ABIO32.
+            AC_COMPILE_IFELSE(
+              [AC_LANG_SOURCE(
+                 [[#if (_MIPS_SIM == _ABIN32)
+                    int ok;
+                   #else
+                    error fail
+                   #endif
+                 ]])],
+              [gl_cv_host_cpu_c_abi=mipsn32],
+              [gl_cv_host_cpu_c_abi=mips])])
+         ;;
+
+       powerpc* )
+         # Different ABIs are in use on AIX vs. Mac OS X vs. Linux,*BSD.
+         # No need to distinguish them here; the caller may distinguish
+         # them based on the OS.
+         # On powerpc64 systems, the C compiler may still be generating
+         # 32-bit code. And on powerpc-ibm-aix systems, the C compiler may
+         # be generating 64-bit code.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if defined __powerpc64__ || defined __LP64__
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [# On powerpc64, there are two ABIs on Linux: The AIX compatible
+            # one and the ELFv2 one. The latter defines _CALL_ELF=2.
+            AC_COMPILE_IFELSE(
+              [AC_LANG_SOURCE(
+                 [[#if defined _CALL_ELF && _CALL_ELF == 2
+                    int ok;
+                   #else
+                    error fail
+                   #endif
+                 ]])],
+              [gl_cv_host_cpu_c_abi=powerpc64-elfv2],
+              [gl_cv_host_cpu_c_abi=powerpc64])
+           ],
+           [gl_cv_host_cpu_c_abi=powerpc])
+         ;;
+
+       rs6000 )
+         gl_cv_host_cpu_c_abi=powerpc
+         ;;
+
+       riscv32 | riscv64 )
+         # There are 2 architectures (with variants): rv32* and rv64*.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if __riscv_xlen == 64
+                  int ok;
+                #else
+                  error fail
+                #endif
+              ]])],
+           [cpu=riscv64],
+           [cpu=riscv32])
+         # There are 6 ABIs: ilp32, ilp32f, ilp32d, lp64, lp64f, lp64d.
+         # Size of 'long' and 'void *':
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if defined __LP64__
+                  int ok;
+                #else
+                  error fail
+                #endif
+              ]])],
+           [main_abi=lp64],
+           [main_abi=ilp32])
+         # Float ABIs:
+         # __riscv_float_abi_double:
+         #   'float' and 'double' are passed in floating-point registers.
+         # __riscv_float_abi_single:
+         #   'float' are passed in floating-point registers.
+         # __riscv_float_abi_soft:
+         #   No values are passed in floating-point registers.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if defined __riscv_float_abi_double
+                  int ok;
+                #else
+                  error fail
+                #endif
+              ]])],
+           [float_abi=d],
+           [AC_COMPILE_IFELSE(
+              [AC_LANG_SOURCE(
+                 [[#if defined __riscv_float_abi_single
+                     int ok;
+                   #else
+                     error fail
+                   #endif
+                 ]])],
+              [float_abi=f],
+              [float_abi=''])
+           ])
+         gl_cv_host_cpu_c_abi="${cpu}-${main_abi}${float_abi}"
+         ;;
+
+       s390* )
+         # On s390x, the C compiler may be generating 64-bit (= s390x) code
+         # or 31-bit (= s390) code.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if defined __LP64__ || defined __s390x__
+                  int ok;
+                #else
+                  error fail
+                #endif
+              ]])],
+           [gl_cv_host_cpu_c_abi=s390x],
+           [gl_cv_host_cpu_c_abi=s390])
+         ;;
+
+       sparc | sparc64 )
+         # UltraSPARCs running Linux have `uname -m` = "sparc64", but the
+         # C compiler still generates 32-bit code.
+         AC_COMPILE_IFELSE(
+           [AC_LANG_SOURCE(
+              [[#if defined __sparcv9 || defined __arch64__
+                 int ok;
+                #else
+                 error fail
+                #endif
+              ]])],
+           [gl_cv_host_cpu_c_abi=sparc64],
+           [gl_cv_host_cpu_c_abi=sparc])
+         ;;
+
+       *)
+         gl_cv_host_cpu_c_abi="$host_cpu"
+         ;;
+     esac
+    ])
+
+  dnl In most cases, $HOST_CPU and $HOST_CPU_C_ABI are the same.
+  HOST_CPU=`echo "$gl_cv_host_cpu_c_abi" | sed -e 's/-.*//'`
+  HOST_CPU_C_ABI="$gl_cv_host_cpu_c_abi"
+  AC_SUBST([HOST_CPU])
+  AC_SUBST([HOST_CPU_C_ABI])
+
+  # This was
+  #   AC_DEFINE_UNQUOTED([__${HOST_CPU}__])
+  #   AC_DEFINE_UNQUOTED([__${HOST_CPU_C_ABI}__])
+  # earlier, but KAI C++ 3.2d doesn't like this.
+  sed -e 's/-/_/g' >> confdefs.h <<EOF
+#ifndef __${HOST_CPU}__
+#define __${HOST_CPU}__ 1
+#endif
+#ifndef __${HOST_CPU_C_ABI}__
+#define __${HOST_CPU_C_ABI}__ 1
+#endif
+EOF
+  AH_TOP([/* CPU and C ABI indicator */
+#ifndef __i386__
+#undef __i386__
+#endif
+#ifndef __x86_64_x32__
+#undef __x86_64_x32__
+#endif
+#ifndef __x86_64__
+#undef __x86_64__
+#endif
+#ifndef __alpha__
+#undef __alpha__
+#endif
+#ifndef __arm__
+#undef __arm__
+#endif
+#ifndef __armhf__
+#undef __armhf__
+#endif
+#ifndef __arm64_ilp32__
+#undef __arm64_ilp32__
+#endif
+#ifndef __arm64__
+#undef __arm64__
+#endif
+#ifndef __hppa__
+#undef __hppa__
+#endif
+#ifndef __hppa64__
+#undef __hppa64__
+#endif
+#ifndef __ia64_ilp32__
+#undef __ia64_ilp32__
+#endif
+#ifndef __ia64__
+#undef __ia64__
+#endif
+#ifndef __loongarch64__
+#undef __loongarch64__
+#endif
+#ifndef __m68k__
+#undef __m68k__
+#endif
+#ifndef __mips__
+#undef __mips__
+#endif
+#ifndef __mipsn32__
+#undef __mipsn32__
+#endif
+#ifndef __mips64__
+#undef __mips64__
+#endif
+#ifndef __powerpc__
+#undef __powerpc__
+#endif
+#ifndef __powerpc64__
+#undef __powerpc64__
+#endif
+#ifndef __powerpc64_elfv2__
+#undef __powerpc64_elfv2__
+#endif
+#ifndef __riscv32__
+#undef __riscv32__
+#endif
+#ifndef __riscv64__
+#undef __riscv64__
+#endif
+#ifndef __riscv32_ilp32__
+#undef __riscv32_ilp32__
+#endif
+#ifndef __riscv32_ilp32f__
+#undef __riscv32_ilp32f__
+#endif
+#ifndef __riscv32_ilp32d__
+#undef __riscv32_ilp32d__
+#endif
+#ifndef __riscv64_ilp32__
+#undef __riscv64_ilp32__
+#endif
+#ifndef __riscv64_ilp32f__
+#undef __riscv64_ilp32f__
+#endif
+#ifndef __riscv64_ilp32d__
+#undef __riscv64_ilp32d__
+#endif
+#ifndef __riscv64_lp64__
+#undef __riscv64_lp64__
+#endif
+#ifndef __riscv64_lp64f__
+#undef __riscv64_lp64f__
+#endif
+#ifndef __riscv64_lp64d__
+#undef __riscv64_lp64d__
+#endif
+#ifndef __s390__
+#undef __s390__
+#endif
+#ifndef __s390x__
+#undef __s390x__
+#endif
+#ifndef __sh__
+#undef __sh__
+#endif
+#ifndef __sparc__
+#undef __sparc__
+#endif
+#ifndef __sparc64__
+#undef __sparc64__
+#endif
+])
+
+])
+
+
+dnl Sets the HOST_CPU_C_ABI_32BIT variable to 'yes' if the C language ABI
+dnl (application binary interface) is a 32-bit one, to 'no' if it is a 64-bit
+dnl one, or to 'unknown' if unknown.
+dnl This is a simplified variant of gl_HOST_CPU_C_ABI.
+AC_DEFUN([gl_HOST_CPU_C_ABI_32BIT],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  AC_CACHE_CHECK([32-bit host C ABI], [gl_cv_host_cpu_c_abi_32bit],
+    [if test -n "$gl_cv_host_cpu_c_abi"; then
+       case "$gl_cv_host_cpu_c_abi" in
+         i386 | x86_64-x32 | arm | armhf | arm64-ilp32 | hppa | ia64-ilp32 | mips | mipsn32 | powerpc | riscv*-ilp32* | s390 | sparc)
+           gl_cv_host_cpu_c_abi_32bit=yes ;;
+         x86_64 | alpha | arm64 | hppa64 | ia64 | mips64 | powerpc64 | powerpc64-elfv2 | riscv*-lp64* | s390x | sparc64 )
+           gl_cv_host_cpu_c_abi_32bit=no ;;
+         *)
+           gl_cv_host_cpu_c_abi_32bit=unknown ;;
+       esac
+     else
+       case "$host_cpu" in
+
+         # CPUs that only support a 32-bit ABI.
+         arc \
+         | bfin \
+         | cris* \
+         | csky \
+         | epiphany \
+         | ft32 \
+         | h8300 \
+         | m68k \
+         | microblaze | microblazeel \
+         | nds32 | nds32le | nds32be \
+         | nios2 | nios2eb | nios2el \
+         | or1k* \
+         | or32 \
+         | sh | sh[1234] | sh[1234]e[lb] \
+         | tic6x \
+         | xtensa* )
+           gl_cv_host_cpu_c_abi_32bit=yes
+           ;;
+
+         # CPUs that only support a 64-bit ABI.
+changequote(,)dnl
+         alpha | alphaev[4-8] | alphaev56 | alphapca5[67] | alphaev6[78] \
+         | mmix )
+changequote([,])dnl
+           gl_cv_host_cpu_c_abi_32bit=no
+           ;;
+
+changequote(,)dnl
+         i[34567]86 )
+changequote([,])dnl
+           gl_cv_host_cpu_c_abi_32bit=yes
+           ;;
+
+         x86_64 )
+           # On x86_64 systems, the C compiler may be generating code in one of
+           # these ABIs:
+           # - 64-bit instruction set, 64-bit pointers, 64-bit 'long': x86_64.
+           # - 64-bit instruction set, 64-bit pointers, 32-bit 'long': x86_64
+           #   with native Windows (mingw, MSVC).
+           # - 64-bit instruction set, 32-bit pointers, 32-bit 'long': x86_64-x32.
+           # - 32-bit instruction set, 32-bit pointers, 32-bit 'long': i386.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if (defined __x86_64__ || defined __amd64__ \
+                       || defined _M_X64 || defined _M_AMD64) \
+                      && !(defined __ILP32__ || defined _ILP32)
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         arm* | aarch64 )
+           # Assume arm with EABI.
+           # On arm64 systems, the C compiler may be generating code in one of
+           # these ABIs:
+           # - aarch64 instruction set, 64-bit pointers, 64-bit 'long': arm64.
+           # - aarch64 instruction set, 32-bit pointers, 32-bit 'long': arm64-ilp32.
+           # - 32-bit instruction set, 32-bit pointers, 32-bit 'long': arm or armhf.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if defined __aarch64__ && !(defined __ILP32__ || defined _ILP32)
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         hppa1.0 | hppa1.1 | hppa2.0* | hppa64 )
+           # On hppa, the C compiler may be generating 32-bit code or 64-bit
+           # code. In the latter case, it defines _LP64 and __LP64__.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#ifdef __LP64__
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         ia64* )
+           # On ia64 on HP-UX, the C compiler may be generating 64-bit code or
+           # 32-bit code. In the latter case, it defines _ILP32.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#ifdef _ILP32
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=yes],
+             [gl_cv_host_cpu_c_abi_32bit=no])
+           ;;
+
+         mips* )
+           # We should also check for (_MIPS_SZPTR == 64), but gcc keeps this
+           # at 32.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if defined _MIPS_SZLONG && (_MIPS_SZLONG == 64)
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         powerpc* )
+           # Different ABIs are in use on AIX vs. Mac OS X vs. Linux,*BSD.
+           # No need to distinguish them here; the caller may distinguish
+           # them based on the OS.
+           # On powerpc64 systems, the C compiler may still be generating
+           # 32-bit code. And on powerpc-ibm-aix systems, the C compiler may
+           # be generating 64-bit code.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if defined __powerpc64__ || defined __LP64__
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         rs6000 )
+           gl_cv_host_cpu_c_abi_32bit=yes
+           ;;
+
+         riscv32 | riscv64 )
+           # There are 6 ABIs: ilp32, ilp32f, ilp32d, lp64, lp64f, lp64d.
+           # Size of 'long' and 'void *':
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if defined __LP64__
+                    int ok;
+                  #else
+                    error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         s390* )
+           # On s390x, the C compiler may be generating 64-bit (= s390x) code
+           # or 31-bit (= s390) code.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if defined __LP64__ || defined __s390x__
+                    int ok;
+                  #else
+                    error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         sparc | sparc64 )
+           # UltraSPARCs running Linux have `uname -m` = "sparc64", but the
+           # C compiler still generates 32-bit code.
+           AC_COMPILE_IFELSE(
+             [AC_LANG_SOURCE(
+                [[#if defined __sparcv9 || defined __arch64__
+                   int ok;
+                  #else
+                   error fail
+                  #endif
+                ]])],
+             [gl_cv_host_cpu_c_abi_32bit=no],
+             [gl_cv_host_cpu_c_abi_32bit=yes])
+           ;;
+
+         *)
+           gl_cv_host_cpu_c_abi_32bit=unknown
+           ;;
+       esac
+     fi
+    ])
+
+  HOST_CPU_C_ABI_32BIT="$gl_cv_host_cpu_c_abi_32bit"
+])
diff --git a/po/m4/iconv.m4 b/po/m4/iconv.m4
new file mode 100644
index 0000000..d0e61de
--- /dev/null
+++ b/po/m4/iconv.m4
@@ -0,0 +1,283 @@
+# iconv.m4 serial 24
+dnl Copyright (C) 2000-2002, 2007-2014, 2016-2021 Free Software Foundation,
+dnl Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_PREREQ([2.64])
+
+dnl Note: AM_ICONV is documented in the GNU gettext manual
+dnl <https://www.gnu.org/software/gettext/manual/html_node/AM_005fICONV.html>.
+dnl Don't make changes that are incompatible with that documentation!
+
+AC_DEFUN([AM_ICONV_LINKFLAGS_BODY],
+[
+  dnl Prerequisites of AC_LIB_LINKFLAGS_BODY.
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+
+  dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV
+  dnl accordingly.
+  AC_LIB_LINKFLAGS_BODY([iconv])
+])
+
+AC_DEFUN([AM_ICONV_LINK],
+[
+  dnl Some systems have iconv in libc, some have it in libiconv (OSF/1 and
+  dnl those with the standalone portable GNU libiconv installed).
+  AC_REQUIRE([AC_CANONICAL_HOST]) dnl for cross-compiles
+
+  dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV
+  dnl accordingly.
+  AC_REQUIRE([AM_ICONV_LINKFLAGS_BODY])
+
+  dnl Add $INCICONV to CPPFLAGS before performing the following checks,
+  dnl because if the user has installed libiconv and not disabled its use
+  dnl via --without-libiconv-prefix, he wants to use it. The first
+  dnl AC_LINK_IFELSE will then fail, the second AC_LINK_IFELSE will succeed.
+  am_save_CPPFLAGS="$CPPFLAGS"
+  AC_LIB_APPENDTOVAR([CPPFLAGS], [$INCICONV])
+
+  AC_CACHE_CHECK([for iconv], [am_cv_func_iconv], [
+    am_cv_func_iconv="no, consider installing GNU libiconv"
+    am_cv_lib_iconv=no
+    AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM(
+         [[
+#include <stdlib.h>
+#include <iconv.h>
+         ]],
+         [[iconv_t cd = iconv_open("","");
+           iconv(cd,NULL,NULL,NULL,NULL);
+           iconv_close(cd);]])],
+      [am_cv_func_iconv=yes])
+    if test "$am_cv_func_iconv" != yes; then
+      am_save_LIBS="$LIBS"
+      LIBS="$LIBS $LIBICONV"
+      AC_LINK_IFELSE(
+        [AC_LANG_PROGRAM(
+           [[
+#include <stdlib.h>
+#include <iconv.h>
+           ]],
+           [[iconv_t cd = iconv_open("","");
+             iconv(cd,NULL,NULL,NULL,NULL);
+             iconv_close(cd);]])],
+        [am_cv_lib_iconv=yes]
+        [am_cv_func_iconv=yes])
+      LIBS="$am_save_LIBS"
+    fi
+  ])
+  if test "$am_cv_func_iconv" = yes; then
+    AC_CACHE_CHECK([for working iconv], [am_cv_func_iconv_works], [
+      dnl This tests against bugs in AIX 5.1, AIX 6.1..7.1, HP-UX 11.11,
+      dnl Solaris 10.
+      am_save_LIBS="$LIBS"
+      if test $am_cv_lib_iconv = yes; then
+        LIBS="$LIBS $LIBICONV"
+      fi
+      am_cv_func_iconv_works=no
+      for ac_iconv_const in '' 'const'; do
+        AC_RUN_IFELSE(
+          [AC_LANG_PROGRAM(
+             [[
+#include <iconv.h>
+#include <string.h>
+
+#ifndef ICONV_CONST
+# define ICONV_CONST $ac_iconv_const
+#endif
+             ]],
+             [[int result = 0;
+  /* Test against AIX 5.1...7.2 bug: Failures are not distinguishable from
+     successful returns.  This is even documented in
+     <https://www.ibm.com/support/knowledgecenter/ssw_aix_72/i_bostechref/iconv.html> */
+  {
+    iconv_t cd_utf8_to_88591 = iconv_open ("ISO8859-1", "UTF-8");
+    if (cd_utf8_to_88591 != (iconv_t)(-1))
+      {
+        static ICONV_CONST char input[] = "\342\202\254"; /* EURO SIGN */
+        char buf[10];
+        ICONV_CONST char *inptr = input;
+        size_t inbytesleft = strlen (input);
+        char *outptr = buf;
+        size_t outbytesleft = sizeof (buf);
+        size_t res = iconv (cd_utf8_to_88591,
+                            &inptr, &inbytesleft,
+                            &outptr, &outbytesleft);
+        if (res == 0)
+          result |= 1;
+        iconv_close (cd_utf8_to_88591);
+      }
+  }
+  /* Test against Solaris 10 bug: Failures are not distinguishable from
+     successful returns.  */
+  {
+    iconv_t cd_ascii_to_88591 = iconv_open ("ISO8859-1", "646");
+    if (cd_ascii_to_88591 != (iconv_t)(-1))
+      {
+        static ICONV_CONST char input[] = "\263";
+        char buf[10];
+        ICONV_CONST char *inptr = input;
+        size_t inbytesleft = strlen (input);
+        char *outptr = buf;
+        size_t outbytesleft = sizeof (buf);
+        size_t res = iconv (cd_ascii_to_88591,
+                            &inptr, &inbytesleft,
+                            &outptr, &outbytesleft);
+        if (res == 0)
+          result |= 2;
+        iconv_close (cd_ascii_to_88591);
+      }
+  }
+  /* Test against AIX 6.1..7.1 bug: Buffer overrun.  */
+  {
+    iconv_t cd_88591_to_utf8 = iconv_open ("UTF-8", "ISO-8859-1");
+    if (cd_88591_to_utf8 != (iconv_t)(-1))
+      {
+        static ICONV_CONST char input[] = "\304";
+        static char buf[2] = { (char)0xDE, (char)0xAD };
+        ICONV_CONST char *inptr = input;
+        size_t inbytesleft = 1;
+        char *outptr = buf;
+        size_t outbytesleft = 1;
+        size_t res = iconv (cd_88591_to_utf8,
+                            &inptr, &inbytesleft,
+                            &outptr, &outbytesleft);
+        if (res != (size_t)(-1) || outptr - buf > 1 || buf[1] != (char)0xAD)
+          result |= 4;
+        iconv_close (cd_88591_to_utf8);
+      }
+  }
+#if 0 /* This bug could be worked around by the caller.  */
+  /* Test against HP-UX 11.11 bug: Positive return value instead of 0.  */
+  {
+    iconv_t cd_88591_to_utf8 = iconv_open ("utf8", "iso88591");
+    if (cd_88591_to_utf8 != (iconv_t)(-1))
+      {
+        static ICONV_CONST char input[] = "\304rger mit b\366sen B\374bchen ohne Augenma\337";
+        char buf[50];
+        ICONV_CONST char *inptr = input;
+        size_t inbytesleft = strlen (input);
+        char *outptr = buf;
+        size_t outbytesleft = sizeof (buf);
+        size_t res = iconv (cd_88591_to_utf8,
+                            &inptr, &inbytesleft,
+                            &outptr, &outbytesleft);
+        if ((int)res > 0)
+          result |= 8;
+        iconv_close (cd_88591_to_utf8);
+      }
+  }
+#endif
+  /* Test against HP-UX 11.11 bug: No converter from EUC-JP to UTF-8 is
+     provided.  */
+  {
+    /* Try standardized names.  */
+    iconv_t cd1 = iconv_open ("UTF-8", "EUC-JP");
+    /* Try IRIX, OSF/1 names.  */
+    iconv_t cd2 = iconv_open ("UTF-8", "eucJP");
+    /* Try AIX names.  */
+    iconv_t cd3 = iconv_open ("UTF-8", "IBM-eucJP");
+    /* Try HP-UX names.  */
+    iconv_t cd4 = iconv_open ("utf8", "eucJP");
+    if (cd1 == (iconv_t)(-1) && cd2 == (iconv_t)(-1)
+        && cd3 == (iconv_t)(-1) && cd4 == (iconv_t)(-1))
+      result |= 16;
+    if (cd1 != (iconv_t)(-1))
+      iconv_close (cd1);
+    if (cd2 != (iconv_t)(-1))
+      iconv_close (cd2);
+    if (cd3 != (iconv_t)(-1))
+      iconv_close (cd3);
+    if (cd4 != (iconv_t)(-1))
+      iconv_close (cd4);
+  }
+  return result;
+]])],
+          [am_cv_func_iconv_works=yes], ,
+          [case "$host_os" in
+             aix* | hpux*) am_cv_func_iconv_works="guessing no" ;;
+             *)            am_cv_func_iconv_works="guessing yes" ;;
+           esac])
+        test "$am_cv_func_iconv_works" = no || break
+      done
+      LIBS="$am_save_LIBS"
+    ])
+    case "$am_cv_func_iconv_works" in
+      *no) am_func_iconv=no am_cv_lib_iconv=no ;;
+      *)   am_func_iconv=yes ;;
+    esac
+  else
+    am_func_iconv=no am_cv_lib_iconv=no
+  fi
+  if test "$am_func_iconv" = yes; then
+    AC_DEFINE([HAVE_ICONV], [1],
+      [Define if you have the iconv() function and it works.])
+  fi
+  if test "$am_cv_lib_iconv" = yes; then
+    AC_MSG_CHECKING([how to link with libiconv])
+    AC_MSG_RESULT([$LIBICONV])
+  else
+    dnl If $LIBICONV didn't lead to a usable library, we don't need $INCICONV
+    dnl either.
+    CPPFLAGS="$am_save_CPPFLAGS"
+    LIBICONV=
+    LTLIBICONV=
+  fi
+  AC_SUBST([LIBICONV])
+  AC_SUBST([LTLIBICONV])
+])
+
+dnl Define AM_ICONV using AC_DEFUN_ONCE, in order to avoid warnings like
+dnl "warning: AC_REQUIRE: `AM_ICONV' was expanded before it was required".
+dnl This is tricky because of the way 'aclocal' is implemented:
+dnl - It requires defining an auxiliary macro whose name ends in AC_DEFUN.
+dnl   Otherwise aclocal's initial scan pass would miss the macro definition.
+dnl - It requires a line break inside the AC_DEFUN_ONCE and AC_DEFUN expansions.
+dnl   Otherwise aclocal would emit many "Use of uninitialized value $1"
+dnl   warnings.
+AC_DEFUN_ONCE([AM_ICONV],
+[
+  AM_ICONV_LINK
+  if test "$am_cv_func_iconv" = yes; then
+    AC_CACHE_CHECK([whether iconv is compatible with its POSIX signature],
+      [gl_cv_iconv_nonconst],
+      [AC_COMPILE_IFELSE(
+         [AC_LANG_PROGRAM(
+            [[
+#include <stdlib.h>
+#include <iconv.h>
+extern
+#ifdef __cplusplus
+"C"
+#endif
+size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
+            ]],
+            [[]])],
+         [gl_cv_iconv_nonconst=yes],
+         [gl_cv_iconv_nonconst=no])
+      ])
+  else
+    dnl When compiling GNU libiconv on a system that does not have iconv yet,
+    dnl pick the POSIX compliant declaration without 'const'.
+    gl_cv_iconv_nonconst=yes
+  fi
+  if test $gl_cv_iconv_nonconst = yes; then
+    iconv_arg1=""
+  else
+    iconv_arg1="const"
+  fi
+  AC_DEFINE_UNQUOTED([ICONV_CONST], [$iconv_arg1],
+    [Define as const if the declaration of iconv() needs const.])
+  dnl Also substitute ICONV_CONST in the gnulib generated <iconv.h>.
+  m4_ifdef([gl_ICONV_H_DEFAULTS],
+    [AC_REQUIRE([gl_ICONV_H_DEFAULTS])
+     if test $gl_cv_iconv_nonconst != yes; then
+       ICONV_CONST="const"
+     fi
+    ])
+])
diff --git a/po/m4/intlmacosx.m4 b/po/m4/intlmacosx.m4
new file mode 100644
index 0000000..4ae0d12
--- /dev/null
+++ b/po/m4/intlmacosx.m4
@@ -0,0 +1,65 @@
+# intlmacosx.m4 serial 8 (gettext-0.20.2)
+dnl Copyright (C) 2004-2014, 2016, 2019-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Checks for special options needed on Mac OS X.
+dnl Defines INTL_MACOSX_LIBS.
+AC_DEFUN([gt_INTL_MACOSX],
+[
+  dnl Check for API introduced in Mac OS X 10.4.
+  AC_CACHE_CHECK([for CFPreferencesCopyAppValue],
+    [gt_cv_func_CFPreferencesCopyAppValue],
+    [gt_save_LIBS="$LIBS"
+     LIBS="$LIBS -Wl,-framework -Wl,CoreFoundation"
+     AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <CoreFoundation/CFPreferences.h>]],
+          [[CFPreferencesCopyAppValue(NULL, NULL)]])],
+       [gt_cv_func_CFPreferencesCopyAppValue=yes],
+       [gt_cv_func_CFPreferencesCopyAppValue=no])
+     LIBS="$gt_save_LIBS"])
+  if test $gt_cv_func_CFPreferencesCopyAppValue = yes; then
+    AC_DEFINE([HAVE_CFPREFERENCESCOPYAPPVALUE], [1],
+      [Define to 1 if you have the Mac OS X function CFPreferencesCopyAppValue in the CoreFoundation framework.])
+  fi
+  dnl Don't check for the API introduced in Mac OS X 10.5, CFLocaleCopyCurrent,
+  dnl because in macOS 10.13.4 it has the following behaviour:
+  dnl When two or more languages are specified in the
+  dnl "System Preferences > Language & Region > Preferred Languages" panel,
+  dnl it returns en_CC where CC is the territory (even when English is not among
+  dnl the preferred languages!).  What we want instead is what
+  dnl CFLocaleCopyCurrent returned in earlier macOS releases and what
+  dnl CFPreferencesCopyAppValue still returns, namely ll_CC where ll is the
+  dnl first among the preferred languages and CC is the territory.
+  AC_CACHE_CHECK([for CFLocaleCopyPreferredLanguages], [gt_cv_func_CFLocaleCopyPreferredLanguages],
+    [gt_save_LIBS="$LIBS"
+     LIBS="$LIBS -Wl,-framework -Wl,CoreFoundation"
+     AC_LINK_IFELSE(
+       [AC_LANG_PROGRAM(
+          [[#include <CoreFoundation/CFLocale.h>]],
+          [[CFLocaleCopyPreferredLanguages();]])],
+       [gt_cv_func_CFLocaleCopyPreferredLanguages=yes],
+       [gt_cv_func_CFLocaleCopyPreferredLanguages=no])
+     LIBS="$gt_save_LIBS"])
+  if test $gt_cv_func_CFLocaleCopyPreferredLanguages = yes; then
+    AC_DEFINE([HAVE_CFLOCALECOPYPREFERREDLANGUAGES], [1],
+      [Define to 1 if you have the Mac OS X function CFLocaleCopyPreferredLanguages in the CoreFoundation framework.])
+  fi
+  INTL_MACOSX_LIBS=
+  if test $gt_cv_func_CFPreferencesCopyAppValue = yes \
+     || test $gt_cv_func_CFLocaleCopyPreferredLanguages = yes; then
+    INTL_MACOSX_LIBS="-Wl,-framework -Wl,CoreFoundation"
+  fi
+  AC_SUBST([INTL_MACOSX_LIBS])
+])
diff --git a/po/m4/lib-ld.m4 b/po/m4/lib-ld.m4
new file mode 100644
index 0000000..934207a
--- /dev/null
+++ b/po/m4/lib-ld.m4
@@ -0,0 +1,168 @@
+# lib-ld.m4 serial 10
+dnl Copyright (C) 1996-2003, 2009-2022 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl Subroutines of libtool.m4,
+dnl with replacements s/_*LT_PATH/AC_LIB_PROG/ and s/lt_/acl_/ to avoid
+dnl collision with libtool.m4.
+
+dnl From libtool-2.4. Sets the variable with_gnu_ld to yes or no.
+AC_DEFUN([AC_LIB_PROG_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], [acl_cv_prog_gnu_ld],
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  acl_cv_prog_gnu_ld=yes
+  ;;
+*)
+  acl_cv_prog_gnu_ld=no
+  ;;
+esac])
+with_gnu_ld=$acl_cv_prog_gnu_ld
+])
+
+dnl From libtool-2.4. Sets the variable LD.
+AC_DEFUN([AC_LIB_PROG_LD],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+
+AC_ARG_WITH([gnu-ld],
+    [AS_HELP_STRING([--with-gnu-ld],
+        [assume the C compiler uses GNU ld [default=no]])],
+    [test "$withval" = no || with_gnu_ld=yes],
+    [with_gnu_ld=no])dnl
+
+# Prepare PATH_SEPARATOR.
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  # Determine PATH_SEPARATOR by trying to find /bin/sh in a PATH which
+  # contains only /bin. Note that ksh looks also at the FPATH variable,
+  # so we have to set that as well for the test.
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 \
+    && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 \
+           || PATH_SEPARATOR=';'
+       }
+fi
+
+if test -n "$LD"; then
+  AC_MSG_CHECKING([for ld])
+elif test "$GCC" = yes; then
+  AC_MSG_CHECKING([for ld used by $CC])
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+if test -n "$LD"; then
+  # Let the user override the test with a path.
+  :
+else
+  AC_CACHE_VAL([acl_cv_path_LD],
+  [
+    acl_cv_path_LD= # Final result of this test
+    ac_prog=ld # Program to search in $PATH
+    if test "$GCC" = yes; then
+      # Check if gcc -print-prog-name=ld gives a path.
+      case $host in
+        *-*-mingw*)
+          # gcc leaves a trailing carriage return which upsets mingw
+          acl_output=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+        *)
+          acl_output=`($CC -print-prog-name=ld) 2>&5` ;;
+      esac
+      case $acl_output in
+        # Accept absolute paths.
+        [[\\/]]* | ?:[[\\/]]*)
+          re_direlt='/[[^/]][[^/]]*/\.\./'
+          # Canonicalize the pathname of ld
+          acl_output=`echo "$acl_output" | sed 's%\\\\%/%g'`
+          while echo "$acl_output" | grep "$re_direlt" > /dev/null 2>&1; do
+            acl_output=`echo $acl_output | sed "s%$re_direlt%/%"`
+          done
+          # Got the pathname. No search in PATH is needed.
+          acl_cv_path_LD="$acl_output"
+          ac_prog=
+          ;;
+        "")
+          # If it fails, then pretend we aren't using GCC.
+          ;;
+        *)
+          # If it is relative, then search for the first ld in PATH.
+          with_gnu_ld=unknown
+          ;;
+      esac
+    fi
+    if test -n "$ac_prog"; then
+      # Search for $ac_prog in $PATH.
+      acl_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+      for ac_dir in $PATH; do
+        IFS="$acl_save_ifs"
+        test -z "$ac_dir" && ac_dir=.
+        if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+          acl_cv_path_LD="$ac_dir/$ac_prog"
+          # Check to see if the program is GNU ld.  I'd rather use --version,
+          # but apparently some variants of GNU ld only accept -v.
+          # Break only if it was the GNU/non-GNU ld that we prefer.
+          case `"$acl_cv_path_LD" -v 2>&1 </dev/null` in
+            *GNU* | *'with BFD'*)
+              test "$with_gnu_ld" != no && break
+              ;;
+            *)
+              test "$with_gnu_ld" != yes && break
+              ;;
+          esac
+        fi
+      done
+      IFS="$acl_save_ifs"
+    fi
+    case $host in
+      *-*-aix*)
+        AC_COMPILE_IFELSE(
+          [AC_LANG_SOURCE(
+             [[#if defined __powerpc64__ || defined __LP64__
+                int ok;
+               #else
+                error fail
+               #endif
+             ]])],
+          [# The compiler produces 64-bit code. Add option '-b64' so that the
+           # linker groks 64-bit object files.
+           case "$acl_cv_path_LD " in
+             *" -b64 "*) ;;
+             *) acl_cv_path_LD="$acl_cv_path_LD -b64" ;;
+           esac
+          ], [])
+        ;;
+      sparc64-*-netbsd*)
+        AC_COMPILE_IFELSE(
+          [AC_LANG_SOURCE(
+             [[#if defined __sparcv9 || defined __arch64__
+                int ok;
+               #else
+                error fail
+               #endif
+             ]])],
+          [],
+          [# The compiler produces 32-bit code. Add option '-m elf32_sparc'
+           # so that the linker groks 32-bit object files.
+           case "$acl_cv_path_LD " in
+             *" -m elf32_sparc "*) ;;
+             *) acl_cv_path_LD="$acl_cv_path_LD -m elf32_sparc" ;;
+           esac
+          ])
+        ;;
+    esac
+  ])
+  LD="$acl_cv_path_LD"
+fi
+if test -n "$LD"; then
+  AC_MSG_RESULT([$LD])
+else
+  AC_MSG_RESULT([no])
+  AC_MSG_ERROR([no acceptable ld found in \$PATH])
+fi
+AC_LIB_PROG_LD_GNU
+])
diff --git a/po/m4/lib-link.m4 b/po/m4/lib-link.m4
new file mode 100644
index 0000000..3b75bcd
--- /dev/null
+++ b/po/m4/lib-link.m4
@@ -0,0 +1,813 @@
+# lib-link.m4 serial 33
+dnl Copyright (C) 2001-2022 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+AC_PREREQ([2.61])
+
+dnl AC_LIB_LINKFLAGS(name [, dependencies]) searches for libname and
+dnl the libraries corresponding to explicit and implicit dependencies.
+dnl Sets and AC_SUBSTs the LIB${NAME} and LTLIB${NAME} variables and
+dnl augments the CPPFLAGS variable.
+dnl Sets and AC_SUBSTs the LIB${NAME}_PREFIX variable to nonempty if libname
+dnl was found in ${LIB${NAME}_PREFIX}/$acl_libdirstem.
+AC_DEFUN([AC_LIB_LINKFLAGS],
+[
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+  pushdef([Name],[m4_translit([$1],[./+-], [____])])
+  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
+                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  AC_CACHE_CHECK([how to link with lib[]$1], [ac_cv_lib[]Name[]_libs], [
+    AC_LIB_LINKFLAGS_BODY([$1], [$2])
+    ac_cv_lib[]Name[]_libs="$LIB[]NAME"
+    ac_cv_lib[]Name[]_ltlibs="$LTLIB[]NAME"
+    ac_cv_lib[]Name[]_cppflags="$INC[]NAME"
+    ac_cv_lib[]Name[]_prefix="$LIB[]NAME[]_PREFIX"
+  ])
+  LIB[]NAME="$ac_cv_lib[]Name[]_libs"
+  LTLIB[]NAME="$ac_cv_lib[]Name[]_ltlibs"
+  INC[]NAME="$ac_cv_lib[]Name[]_cppflags"
+  LIB[]NAME[]_PREFIX="$ac_cv_lib[]Name[]_prefix"
+  AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME)
+  AC_SUBST([LIB]NAME)
+  AC_SUBST([LTLIB]NAME)
+  AC_SUBST([LIB]NAME[_PREFIX])
+  dnl Also set HAVE_LIB[]NAME so that AC_LIB_HAVE_LINKFLAGS can reuse the
+  dnl results of this search when this library appears as a dependency.
+  HAVE_LIB[]NAME=yes
+  popdef([NAME])
+  popdef([Name])
+])
+
+dnl AC_LIB_HAVE_LINKFLAGS(name, dependencies, includes, testcode, [missing-message])
+dnl searches for libname and the libraries corresponding to explicit and
+dnl implicit dependencies, together with the specified include files and
+dnl the ability to compile and link the specified testcode. The missing-message
+dnl defaults to 'no' and may contain additional hints for the user.
+dnl If found, it sets and AC_SUBSTs HAVE_LIB${NAME}=yes and the LIB${NAME}
+dnl and LTLIB${NAME} variables and augments the CPPFLAGS variable, and
+dnl #defines HAVE_LIB${NAME} to 1. Otherwise, it sets and AC_SUBSTs
+dnl HAVE_LIB${NAME}=no and LIB${NAME} and LTLIB${NAME} to empty.
+dnl Sets and AC_SUBSTs the LIB${NAME}_PREFIX variable to nonempty if libname
+dnl was found in ${LIB${NAME}_PREFIX}/$acl_libdirstem.
+AC_DEFUN([AC_LIB_HAVE_LINKFLAGS],
+[
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+  pushdef([Name],[m4_translit([$1],[./+-], [____])])
+  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
+                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+
+  dnl Search for lib[]Name and define LIB[]NAME, LTLIB[]NAME and INC[]NAME
+  dnl accordingly.
+  AC_LIB_LINKFLAGS_BODY([$1], [$2])
+
+  dnl Add $INC[]NAME to CPPFLAGS before performing the following checks,
+  dnl because if the user has installed lib[]Name and not disabled its use
+  dnl via --without-lib[]Name-prefix, he wants to use it.
+  ac_save_CPPFLAGS="$CPPFLAGS"
+  AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME)
+
+  AC_CACHE_CHECK([for lib[]$1], [ac_cv_lib[]Name], [
+    ac_save_LIBS="$LIBS"
+    dnl If $LIB[]NAME contains some -l options, add it to the end of LIBS,
+    dnl because these -l options might require -L options that are present in
+    dnl LIBS. -l options benefit only from the -L options listed before it.
+    dnl Otherwise, add it to the front of LIBS, because it may be a static
+    dnl library that depends on another static library that is present in LIBS.
+    dnl Static libraries benefit only from the static libraries listed after
+    dnl it.
+    case " $LIB[]NAME" in
+      *" -l"*) LIBS="$LIBS $LIB[]NAME" ;;
+      *)       LIBS="$LIB[]NAME $LIBS" ;;
+    esac
+    AC_LINK_IFELSE(
+      [AC_LANG_PROGRAM([[$3]], [[$4]])],
+      [ac_cv_lib[]Name=yes],
+      [ac_cv_lib[]Name='m4_if([$5], [], [no], [[$5]])'])
+    LIBS="$ac_save_LIBS"
+  ])
+  if test "$ac_cv_lib[]Name" = yes; then
+    HAVE_LIB[]NAME=yes
+    AC_DEFINE([HAVE_LIB]NAME, 1, [Define if you have the lib][$1 library.])
+    AC_MSG_CHECKING([how to link with lib[]$1])
+    AC_MSG_RESULT([$LIB[]NAME])
+  else
+    HAVE_LIB[]NAME=no
+    dnl If $LIB[]NAME didn't lead to a usable library, we don't need
+    dnl $INC[]NAME either.
+    CPPFLAGS="$ac_save_CPPFLAGS"
+    LIB[]NAME=
+    LTLIB[]NAME=
+    LIB[]NAME[]_PREFIX=
+  fi
+  AC_SUBST([HAVE_LIB]NAME)
+  AC_SUBST([LIB]NAME)
+  AC_SUBST([LTLIB]NAME)
+  AC_SUBST([LIB]NAME[_PREFIX])
+  popdef([NAME])
+  popdef([Name])
+])
+
+dnl Determine the platform dependent parameters needed to use rpath:
+dnl   acl_libext,
+dnl   acl_shlibext,
+dnl   acl_libname_spec,
+dnl   acl_library_names_spec,
+dnl   acl_hardcode_libdir_flag_spec,
+dnl   acl_hardcode_libdir_separator,
+dnl   acl_hardcode_direct,
+dnl   acl_hardcode_minus_L.
+AC_DEFUN([AC_LIB_RPATH],
+[
+  dnl Complain if config.rpath is missing.
+  AC_REQUIRE_AUX_FILE([config.rpath])
+  AC_REQUIRE([AC_PROG_CC])                dnl we use $CC, $GCC, $LDFLAGS
+  AC_REQUIRE([AC_LIB_PROG_LD])            dnl we use $LD, $with_gnu_ld
+  AC_REQUIRE([AC_CANONICAL_HOST])         dnl we use $host
+  AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT]) dnl we use $ac_aux_dir
+  AC_CACHE_CHECK([for shared library run path origin], [acl_cv_rpath], [
+    CC="$CC" GCC="$GCC" LDFLAGS="$LDFLAGS" LD="$LD" with_gnu_ld="$with_gnu_ld" \
+    ${CONFIG_SHELL-/bin/sh} "$ac_aux_dir/config.rpath" "$host" > conftest.sh
+    . ./conftest.sh
+    rm -f ./conftest.sh
+    acl_cv_rpath=done
+  ])
+  wl="$acl_cv_wl"
+  acl_libext="$acl_cv_libext"
+  acl_shlibext="$acl_cv_shlibext"
+  acl_libname_spec="$acl_cv_libname_spec"
+  acl_library_names_spec="$acl_cv_library_names_spec"
+  acl_hardcode_libdir_flag_spec="$acl_cv_hardcode_libdir_flag_spec"
+  acl_hardcode_libdir_separator="$acl_cv_hardcode_libdir_separator"
+  acl_hardcode_direct="$acl_cv_hardcode_direct"
+  acl_hardcode_minus_L="$acl_cv_hardcode_minus_L"
+  dnl Determine whether the user wants rpath handling at all.
+  AC_ARG_ENABLE([rpath],
+    [  --disable-rpath         do not hardcode runtime library paths],
+    :, enable_rpath=yes)
+])
+
+dnl AC_LIB_FROMPACKAGE(name, package)
+dnl declares that libname comes from the given package. The configure file
+dnl will then not have a --with-libname-prefix option but a
+dnl --with-package-prefix option. Several libraries can come from the same
+dnl package. This declaration must occur before an AC_LIB_LINKFLAGS or similar
+dnl macro call that searches for libname.
+AC_DEFUN([AC_LIB_FROMPACKAGE],
+[
+  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
+                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  define([acl_frompackage_]NAME, [$2])
+  popdef([NAME])
+  pushdef([PACK],[$2])
+  pushdef([PACKUP],[m4_translit(PACK,[abcdefghijklmnopqrstuvwxyz./+-],
+                                     [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  define([acl_libsinpackage_]PACKUP,
+    m4_ifdef([acl_libsinpackage_]PACKUP, [m4_defn([acl_libsinpackage_]PACKUP)[, ]],)[lib$1])
+  popdef([PACKUP])
+  popdef([PACK])
+])
+
+dnl AC_LIB_LINKFLAGS_BODY(name [, dependencies]) searches for libname and
+dnl the libraries corresponding to explicit and implicit dependencies.
+dnl Sets the LIB${NAME}, LTLIB${NAME} and INC${NAME} variables.
+dnl Also, sets the LIB${NAME}_PREFIX variable to nonempty if libname was found
+dnl in ${LIB${NAME}_PREFIX}/$acl_libdirstem.
+AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
+[
+  AC_REQUIRE([AC_LIB_PREPARE_MULTILIB])
+  pushdef([NAME],[m4_translit([$1],[abcdefghijklmnopqrstuvwxyz./+-],
+                                   [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  pushdef([PACK],[m4_ifdef([acl_frompackage_]NAME, [acl_frompackage_]NAME, lib[$1])])
+  pushdef([PACKUP],[m4_translit(PACK,[abcdefghijklmnopqrstuvwxyz./+-],
+                                     [ABCDEFGHIJKLMNOPQRSTUVWXYZ____])])
+  pushdef([PACKLIBS],[m4_ifdef([acl_frompackage_]NAME, [acl_libsinpackage_]PACKUP, lib[$1])])
+  dnl By default, look in $includedir and $libdir.
+  use_additional=yes
+  AC_LIB_WITH_FINAL_PREFIX([
+    eval additional_includedir=\"$includedir\"
+    eval additional_libdir=\"$libdir\"
+    eval additional_libdir2=\"$exec_prefix/$acl_libdirstem2\"
+    eval additional_libdir3=\"$exec_prefix/$acl_libdirstem3\"
+  ])
+  AC_ARG_WITH(PACK[-prefix],
+[[  --with-]]PACK[[-prefix[=DIR]  search for ]]PACKLIBS[[ in DIR/include and DIR/lib
+  --without-]]PACK[[-prefix     don't search for ]]PACKLIBS[[ in includedir and libdir]],
+[
+    if test "X$withval" = "Xno"; then
+      use_additional=no
+    else
+      if test "X$withval" = "X"; then
+        AC_LIB_WITH_FINAL_PREFIX([
+          eval additional_includedir=\"$includedir\"
+          eval additional_libdir=\"$libdir\"
+          eval additional_libdir2=\"$exec_prefix/$acl_libdirstem2\"
+          eval additional_libdir3=\"$exec_prefix/$acl_libdirstem3\"
+        ])
+      else
+        additional_includedir="$withval/include"
+        additional_libdir="$withval/$acl_libdirstem"
+        additional_libdir2="$withval/$acl_libdirstem2"
+        additional_libdir3="$withval/$acl_libdirstem3"
+      fi
+    fi
+])
+  if test "X$additional_libdir2" = "X$additional_libdir"; then
+    additional_libdir2=
+  fi
+  if test "X$additional_libdir3" = "X$additional_libdir"; then
+    additional_libdir3=
+  fi
+  dnl Search the library and its dependencies in $additional_libdir and
+  dnl $LDFLAGS. Using breadth-first-seach.
+  LIB[]NAME=
+  LTLIB[]NAME=
+  INC[]NAME=
+  LIB[]NAME[]_PREFIX=
+  dnl HAVE_LIB${NAME} is an indicator that LIB${NAME}, LTLIB${NAME} have been
+  dnl computed. So it has to be reset here.
+  HAVE_LIB[]NAME=
+  rpathdirs=
+  ltrpathdirs=
+  names_already_handled=
+  names_next_round='$1 $2'
+  while test -n "$names_next_round"; do
+    names_this_round="$names_next_round"
+    names_next_round=
+    for name in $names_this_round; do
+      already_handled=
+      for n in $names_already_handled; do
+        if test "$n" = "$name"; then
+          already_handled=yes
+          break
+        fi
+      done
+      if test -z "$already_handled"; then
+        names_already_handled="$names_already_handled $name"
+        dnl See if it was already located by an earlier AC_LIB_LINKFLAGS
+        dnl or AC_LIB_HAVE_LINKFLAGS call.
+        uppername=`echo "$name" | sed -e 'y|abcdefghijklmnopqrstuvwxyz./+-|ABCDEFGHIJKLMNOPQRSTUVWXYZ____|'`
+        eval value=\"\$HAVE_LIB$uppername\"
+        if test -n "$value"; then
+          if test "$value" = yes; then
+            eval value=\"\$LIB$uppername\"
+            test -z "$value" || LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$value"
+            eval value=\"\$LTLIB$uppername\"
+            test -z "$value" || LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$value"
+          else
+            dnl An earlier call to AC_LIB_HAVE_LINKFLAGS has determined
+            dnl that this library doesn't exist. So just drop it.
+            :
+          fi
+        else
+          dnl Search the library lib$name in $additional_libdir and $LDFLAGS
+          dnl and the already constructed $LIBNAME/$LTLIBNAME.
+          found_dir=
+          found_la=
+          found_so=
+          found_a=
+          eval libname=\"$acl_libname_spec\"    # typically: libname=lib$name
+          if test -n "$acl_shlibext"; then
+            shrext=".$acl_shlibext"             # typically: shrext=.so
+          else
+            shrext=
+          fi
+          if test $use_additional = yes; then
+            for additional_libdir_variable in additional_libdir additional_libdir2 additional_libdir3; do
+              if test "X$found_dir" = "X"; then
+                eval dir=\$$additional_libdir_variable
+                if test -n "$dir"; then
+                  dnl The same code as in the loop below:
+                  dnl First look for a shared library.
+                  if test -n "$acl_shlibext"; then
+                    if test -f "$dir/$libname$shrext" && acl_is_expected_elfclass < "$dir/$libname$shrext"; then
+                      found_dir="$dir"
+                      found_so="$dir/$libname$shrext"
+                    else
+                      if test "$acl_library_names_spec" = '$libname$shrext$versuffix'; then
+                        ver=`(cd "$dir" && \
+                              for f in "$libname$shrext".*; do echo "$f"; done \
+                              | sed -e "s,^$libname$shrext\\\\.,," \
+                              | sort -t '.' -n -r -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 \
+                              | sed 1q ) 2>/dev/null`
+                        if test -n "$ver" && test -f "$dir/$libname$shrext.$ver" && acl_is_expected_elfclass < "$dir/$libname$shrext.$ver"; then
+                          found_dir="$dir"
+                          found_so="$dir/$libname$shrext.$ver"
+                        fi
+                      else
+                        eval library_names=\"$acl_library_names_spec\"
+                        for f in $library_names; do
+                          if test -f "$dir/$f" && acl_is_expected_elfclass < "$dir/$f"; then
+                            found_dir="$dir"
+                            found_so="$dir/$f"
+                            break
+                          fi
+                        done
+                      fi
+                    fi
+                  fi
+                  dnl Then look for a static library.
+                  if test "X$found_dir" = "X"; then
+                    if test -f "$dir/$libname.$acl_libext" && ${AR-ar} -p "$dir/$libname.$acl_libext" | acl_is_expected_elfclass; then
+                      found_dir="$dir"
+                      found_a="$dir/$libname.$acl_libext"
+                    fi
+                  fi
+                  if test "X$found_dir" != "X"; then
+                    if test -f "$dir/$libname.la"; then
+                      found_la="$dir/$libname.la"
+                    fi
+                  fi
+                fi
+              fi
+            done
+          fi
+          if test "X$found_dir" = "X"; then
+            for x in $LDFLAGS $LTLIB[]NAME; do
+              AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+              case "$x" in
+                -L*)
+                  dir=`echo "X$x" | sed -e 's/^X-L//'`
+                  dnl First look for a shared library.
+                  if test -n "$acl_shlibext"; then
+                    if test -f "$dir/$libname$shrext" && acl_is_expected_elfclass < "$dir/$libname$shrext"; then
+                      found_dir="$dir"
+                      found_so="$dir/$libname$shrext"
+                    else
+                      if test "$acl_library_names_spec" = '$libname$shrext$versuffix'; then
+                        ver=`(cd "$dir" && \
+                              for f in "$libname$shrext".*; do echo "$f"; done \
+                              | sed -e "s,^$libname$shrext\\\\.,," \
+                              | sort -t '.' -n -r -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 \
+                              | sed 1q ) 2>/dev/null`
+                        if test -n "$ver" && test -f "$dir/$libname$shrext.$ver" && acl_is_expected_elfclass < "$dir/$libname$shrext.$ver"; then
+                          found_dir="$dir"
+                          found_so="$dir/$libname$shrext.$ver"
+                        fi
+                      else
+                        eval library_names=\"$acl_library_names_spec\"
+                        for f in $library_names; do
+                          if test -f "$dir/$f" && acl_is_expected_elfclass < "$dir/$f"; then
+                            found_dir="$dir"
+                            found_so="$dir/$f"
+                            break
+                          fi
+                        done
+                      fi
+                    fi
+                  fi
+                  dnl Then look for a static library.
+                  if test "X$found_dir" = "X"; then
+                    if test -f "$dir/$libname.$acl_libext" && ${AR-ar} -p "$dir/$libname.$acl_libext" | acl_is_expected_elfclass; then
+                      found_dir="$dir"
+                      found_a="$dir/$libname.$acl_libext"
+                    fi
+                  fi
+                  if test "X$found_dir" != "X"; then
+                    if test -f "$dir/$libname.la"; then
+                      found_la="$dir/$libname.la"
+                    fi
+                  fi
+                  ;;
+              esac
+              if test "X$found_dir" != "X"; then
+                break
+              fi
+            done
+          fi
+          if test "X$found_dir" != "X"; then
+            dnl Found the library.
+            LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$found_dir -l$name"
+            if test "X$found_so" != "X"; then
+              dnl Linking with a shared library. We attempt to hardcode its
+              dnl directory into the executable's runpath, unless it's the
+              dnl standard /usr/lib.
+              if test "$enable_rpath" = no \
+                 || test "X$found_dir" = "X/usr/$acl_libdirstem" \
+                 || test "X$found_dir" = "X/usr/$acl_libdirstem2" \
+                 || test "X$found_dir" = "X/usr/$acl_libdirstem3"; then
+                dnl No hardcoding is needed.
+                LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+              else
+                dnl Use an explicit option to hardcode DIR into the resulting
+                dnl binary.
+                dnl Potentially add DIR to ltrpathdirs.
+                dnl The ltrpathdirs will be appended to $LTLIBNAME at the end.
+                haveit=
+                for x in $ltrpathdirs; do
+                  if test "X$x" = "X$found_dir"; then
+                    haveit=yes
+                    break
+                  fi
+                done
+                if test -z "$haveit"; then
+                  ltrpathdirs="$ltrpathdirs $found_dir"
+                fi
+                dnl The hardcoding into $LIBNAME is system dependent.
+                if test "$acl_hardcode_direct" = yes; then
+                  dnl Using DIR/libNAME.so during linking hardcodes DIR into the
+                  dnl resulting binary.
+                  LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+                else
+                  if test -n "$acl_hardcode_libdir_flag_spec" && test "$acl_hardcode_minus_L" = no; then
+                    dnl Use an explicit option to hardcode DIR into the resulting
+                    dnl binary.
+                    LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+                    dnl Potentially add DIR to rpathdirs.
+                    dnl The rpathdirs will be appended to $LIBNAME at the end.
+                    haveit=
+                    for x in $rpathdirs; do
+                      if test "X$x" = "X$found_dir"; then
+                        haveit=yes
+                        break
+                      fi
+                    done
+                    if test -z "$haveit"; then
+                      rpathdirs="$rpathdirs $found_dir"
+                    fi
+                  else
+                    dnl Rely on "-L$found_dir".
+                    dnl But don't add it if it's already contained in the LDFLAGS
+                    dnl or the already constructed $LIBNAME
+                    haveit=
+                    for x in $LDFLAGS $LIB[]NAME; do
+                      AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                      if test "X$x" = "X-L$found_dir"; then
+                        haveit=yes
+                        break
+                      fi
+                    done
+                    if test -z "$haveit"; then
+                      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir"
+                    fi
+                    if test "$acl_hardcode_minus_L" != no; then
+                      dnl FIXME: Not sure whether we should use
+                      dnl "-L$found_dir -l$name" or "-L$found_dir $found_so"
+                      dnl here.
+                      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+                    else
+                      dnl We cannot use $acl_hardcode_runpath_var and LD_RUN_PATH
+                      dnl here, because this doesn't fit in flags passed to the
+                      dnl compiler. So give up. No hardcoding. This affects only
+                      dnl very old systems.
+                      dnl FIXME: Not sure whether we should use
+                      dnl "-L$found_dir -l$name" or "-L$found_dir $found_so"
+                      dnl here.
+                      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name"
+                    fi
+                  fi
+                fi
+              fi
+            else
+              if test "X$found_a" != "X"; then
+                dnl Linking with a static library.
+                LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_a"
+              else
+                dnl We shouldn't come here, but anyway it's good to have a
+                dnl fallback.
+                LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir -l$name"
+              fi
+            fi
+            dnl Assume the include files are nearby.
+            additional_includedir=
+            case "$found_dir" in
+              */$acl_libdirstem | */$acl_libdirstem/)
+                basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e "s,/$acl_libdirstem/"'*$,,'`
+                if test "$name" = '$1'; then
+                  LIB[]NAME[]_PREFIX="$basedir"
+                fi
+                additional_includedir="$basedir/include"
+                ;;
+              */$acl_libdirstem2 | */$acl_libdirstem2/)
+                basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e "s,/$acl_libdirstem2/"'*$,,'`
+                if test "$name" = '$1'; then
+                  LIB[]NAME[]_PREFIX="$basedir"
+                fi
+                additional_includedir="$basedir/include"
+                ;;
+              */$acl_libdirstem3 | */$acl_libdirstem3/)
+                basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e "s,/$acl_libdirstem3/"'*$,,'`
+                if test "$name" = '$1'; then
+                  LIB[]NAME[]_PREFIX="$basedir"
+                fi
+                additional_includedir="$basedir/include"
+                ;;
+            esac
+            if test "X$additional_includedir" != "X"; then
+              dnl Potentially add $additional_includedir to $INCNAME.
+              dnl But don't add it
+              dnl   1. if it's the standard /usr/include,
+              dnl   2. if it's /usr/local/include and we are using GCC on Linux,
+              dnl   3. if it's already present in $CPPFLAGS or the already
+              dnl      constructed $INCNAME,
+              dnl   4. if it doesn't exist as a directory.
+              if test "X$additional_includedir" != "X/usr/include"; then
+                haveit=
+                if test "X$additional_includedir" = "X/usr/local/include"; then
+                  if test -n "$GCC"; then
+                    case $host_os in
+                      linux* | gnu* | k*bsd*-gnu) haveit=yes;;
+                    esac
+                  fi
+                fi
+                if test -z "$haveit"; then
+                  for x in $CPPFLAGS $INC[]NAME; do
+                    AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                    if test "X$x" = "X-I$additional_includedir"; then
+                      haveit=yes
+                      break
+                    fi
+                  done
+                  if test -z "$haveit"; then
+                    if test -d "$additional_includedir"; then
+                      dnl Really add $additional_includedir to $INCNAME.
+                      INC[]NAME="${INC[]NAME}${INC[]NAME:+ }-I$additional_includedir"
+                    fi
+                  fi
+                fi
+              fi
+            fi
+            dnl Look for dependencies.
+            if test -n "$found_la"; then
+              dnl Read the .la file. It defines the variables
+              dnl dlname, library_names, old_library, dependency_libs, current,
+              dnl age, revision, installed, dlopen, dlpreopen, libdir.
+              save_libdir="$libdir"
+              case "$found_la" in
+                */* | *\\*) . "$found_la" ;;
+                *) . "./$found_la" ;;
+              esac
+              libdir="$save_libdir"
+              dnl We use only dependency_libs.
+              for dep in $dependency_libs; do
+                case "$dep" in
+                  -L*)
+                    dependency_libdir=`echo "X$dep" | sed -e 's/^X-L//'`
+                    dnl Potentially add $dependency_libdir to $LIBNAME and $LTLIBNAME.
+                    dnl But don't add it
+                    dnl   1. if it's the standard /usr/lib,
+                    dnl   2. if it's /usr/local/lib and we are using GCC on Linux,
+                    dnl   3. if it's already present in $LDFLAGS or the already
+                    dnl      constructed $LIBNAME,
+                    dnl   4. if it doesn't exist as a directory.
+                    if test "X$dependency_libdir" != "X/usr/$acl_libdirstem" \
+                       && test "X$dependency_libdir" != "X/usr/$acl_libdirstem2" \
+                       && test "X$dependency_libdir" != "X/usr/$acl_libdirstem3"; then
+                      haveit=
+                      if test "X$dependency_libdir" = "X/usr/local/$acl_libdirstem" \
+                         || test "X$dependency_libdir" = "X/usr/local/$acl_libdirstem2" \
+                         || test "X$dependency_libdir" = "X/usr/local/$acl_libdirstem3"; then
+                        if test -n "$GCC"; then
+                          case $host_os in
+                            linux* | gnu* | k*bsd*-gnu) haveit=yes;;
+                          esac
+                        fi
+                      fi
+                      if test -z "$haveit"; then
+                        haveit=
+                        for x in $LDFLAGS $LIB[]NAME; do
+                          AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                          if test "X$x" = "X-L$dependency_libdir"; then
+                            haveit=yes
+                            break
+                          fi
+                        done
+                        if test -z "$haveit"; then
+                          if test -d "$dependency_libdir"; then
+                            dnl Really add $dependency_libdir to $LIBNAME.
+                            LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$dependency_libdir"
+                          fi
+                        fi
+                        haveit=
+                        for x in $LDFLAGS $LTLIB[]NAME; do
+                          AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                          if test "X$x" = "X-L$dependency_libdir"; then
+                            haveit=yes
+                            break
+                          fi
+                        done
+                        if test -z "$haveit"; then
+                          if test -d "$dependency_libdir"; then
+                            dnl Really add $dependency_libdir to $LTLIBNAME.
+                            LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$dependency_libdir"
+                          fi
+                        fi
+                      fi
+                    fi
+                    ;;
+                  -R*)
+                    dir=`echo "X$dep" | sed -e 's/^X-R//'`
+                    if test "$enable_rpath" != no; then
+                      dnl Potentially add DIR to rpathdirs.
+                      dnl The rpathdirs will be appended to $LIBNAME at the end.
+                      haveit=
+                      for x in $rpathdirs; do
+                        if test "X$x" = "X$dir"; then
+                          haveit=yes
+                          break
+                        fi
+                      done
+                      if test -z "$haveit"; then
+                        rpathdirs="$rpathdirs $dir"
+                      fi
+                      dnl Potentially add DIR to ltrpathdirs.
+                      dnl The ltrpathdirs will be appended to $LTLIBNAME at the end.
+                      haveit=
+                      for x in $ltrpathdirs; do
+                        if test "X$x" = "X$dir"; then
+                          haveit=yes
+                          break
+                        fi
+                      done
+                      if test -z "$haveit"; then
+                        ltrpathdirs="$ltrpathdirs $dir"
+                      fi
+                    fi
+                    ;;
+                  -l*)
+                    dnl Handle this in the next round.
+                    dnl But on GNU systems, ignore -lc options, because
+                    dnl   - linking with libc is the default anyway,
+                    dnl   - linking with libc.a may produce an error
+                    dnl     "/usr/bin/ld: dynamic STT_GNU_IFUNC symbol `strcmp' with pointer equality in `/usr/lib/libc.a(strcmp.o)' can not be used when making an executable; recompile with -fPIE and relink with -pie"
+                    dnl     or may produce an executable that always crashes, see
+                    dnl     <https://lists.gnu.org/archive/html/grep-devel/2020-09/msg00052.html>.
+                    dep=`echo "X$dep" | sed -e 's/^X-l//'`
+                    if test "X$dep" != Xc \
+                       || case $host_os in
+                            linux* | gnu* | k*bsd*-gnu) false ;;
+                            *)                          true ;;
+                          esac; then
+                      names_next_round="$names_next_round $dep"
+                    fi
+                    ;;
+                  *.la)
+                    dnl Handle this in the next round. Throw away the .la's
+                    dnl directory; it is already contained in a preceding -L
+                    dnl option.
+                    names_next_round="$names_next_round "`echo "X$dep" | sed -e 's,^X.*/,,' -e 's,^lib,,' -e 's,\.la$,,'`
+                    ;;
+                  *)
+                    dnl Most likely an immediate library name.
+                    LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$dep"
+                    LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$dep"
+                    ;;
+                esac
+              done
+            fi
+          else
+            dnl Didn't find the library; assume it is in the system directories
+            dnl known to the linker and runtime loader. (All the system
+            dnl directories known to the linker should also be known to the
+            dnl runtime loader, otherwise the system is severely misconfigured.)
+            LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name"
+            LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-l$name"
+          fi
+        fi
+      fi
+    done
+  done
+  if test "X$rpathdirs" != "X"; then
+    if test -n "$acl_hardcode_libdir_separator"; then
+      dnl Weird platform: only the last -rpath option counts, the user must
+      dnl pass all path elements in one option. We can arrange that for a
+      dnl single library, but not when more than one $LIBNAMEs are used.
+      alldirs=
+      for found_dir in $rpathdirs; do
+        alldirs="${alldirs}${alldirs:+$acl_hardcode_libdir_separator}$found_dir"
+      done
+      dnl Note: acl_hardcode_libdir_flag_spec uses $libdir and $wl.
+      acl_save_libdir="$libdir"
+      libdir="$alldirs"
+      eval flag=\"$acl_hardcode_libdir_flag_spec\"
+      libdir="$acl_save_libdir"
+      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag"
+    else
+      dnl The -rpath options are cumulative.
+      for found_dir in $rpathdirs; do
+        acl_save_libdir="$libdir"
+        libdir="$found_dir"
+        eval flag=\"$acl_hardcode_libdir_flag_spec\"
+        libdir="$acl_save_libdir"
+        LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag"
+      done
+    fi
+  fi
+  if test "X$ltrpathdirs" != "X"; then
+    dnl When using libtool, the option that works for both libraries and
+    dnl executables is -R. The -R options are cumulative.
+    for found_dir in $ltrpathdirs; do
+      LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-R$found_dir"
+    done
+  fi
+  popdef([PACKLIBS])
+  popdef([PACKUP])
+  popdef([PACK])
+  popdef([NAME])
+])
+
+dnl AC_LIB_APPENDTOVAR(VAR, CONTENTS) appends the elements of CONTENTS to VAR,
+dnl unless already present in VAR.
+dnl Works only for CPPFLAGS, not for LIB* variables because that sometimes
+dnl contains two or three consecutive elements that belong together.
+AC_DEFUN([AC_LIB_APPENDTOVAR],
+[
+  for element in [$2]; do
+    haveit=
+    for x in $[$1]; do
+      AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+      if test "X$x" = "X$element"; then
+        haveit=yes
+        break
+      fi
+    done
+    if test -z "$haveit"; then
+      [$1]="${[$1]}${[$1]:+ }$element"
+    fi
+  done
+])
+
+dnl For those cases where a variable contains several -L and -l options
+dnl referring to unknown libraries and directories, this macro determines the
+dnl necessary additional linker options for the runtime path.
+dnl AC_LIB_LINKFLAGS_FROM_LIBS([LDADDVAR], [LIBSVALUE], [USE-LIBTOOL])
+dnl sets LDADDVAR to linker options needed together with LIBSVALUE.
+dnl If USE-LIBTOOL evaluates to non-empty, linking with libtool is assumed,
+dnl otherwise linking without libtool is assumed.
+AC_DEFUN([AC_LIB_LINKFLAGS_FROM_LIBS],
+[
+  AC_REQUIRE([AC_LIB_RPATH])
+  AC_REQUIRE([AC_LIB_PREPARE_MULTILIB])
+  $1=
+  if test "$enable_rpath" != no; then
+    if test -n "$acl_hardcode_libdir_flag_spec" && test "$acl_hardcode_minus_L" = no; then
+      dnl Use an explicit option to hardcode directories into the resulting
+      dnl binary.
+      rpathdirs=
+      next=
+      for opt in $2; do
+        if test -n "$next"; then
+          dir="$next"
+          dnl No need to hardcode the standard /usr/lib.
+          if test "X$dir" != "X/usr/$acl_libdirstem" \
+             && test "X$dir" != "X/usr/$acl_libdirstem2" \
+             && test "X$dir" != "X/usr/$acl_libdirstem3"; then
+            rpathdirs="$rpathdirs $dir"
+          fi
+          next=
+        else
+          case $opt in
+            -L) next=yes ;;
+            -L*) dir=`echo "X$opt" | sed -e 's,^X-L,,'`
+                 dnl No need to hardcode the standard /usr/lib.
+                 if test "X$dir" != "X/usr/$acl_libdirstem" \
+                    && test "X$dir" != "X/usr/$acl_libdirstem2" \
+                    && test "X$dir" != "X/usr/$acl_libdirstem3"; then
+                   rpathdirs="$rpathdirs $dir"
+                 fi
+                 next= ;;
+            *) next= ;;
+          esac
+        fi
+      done
+      if test "X$rpathdirs" != "X"; then
+        if test -n ""$3""; then
+          dnl libtool is used for linking. Use -R options.
+          for dir in $rpathdirs; do
+            $1="${$1}${$1:+ }-R$dir"
+          done
+        else
+          dnl The linker is used for linking directly.
+          if test -n "$acl_hardcode_libdir_separator"; then
+            dnl Weird platform: only the last -rpath option counts, the user
+            dnl must pass all path elements in one option.
+            alldirs=
+            for dir in $rpathdirs; do
+              alldirs="${alldirs}${alldirs:+$acl_hardcode_libdir_separator}$dir"
+            done
+            acl_save_libdir="$libdir"
+            libdir="$alldirs"
+            eval flag=\"$acl_hardcode_libdir_flag_spec\"
+            libdir="$acl_save_libdir"
+            $1="$flag"
+          else
+            dnl The -rpath options are cumulative.
+            for dir in $rpathdirs; do
+              acl_save_libdir="$libdir"
+              libdir="$dir"
+              eval flag=\"$acl_hardcode_libdir_flag_spec\"
+              libdir="$acl_save_libdir"
+              $1="${$1}${$1:+ }$flag"
+            done
+          fi
+        fi
+      fi
+    fi
+  fi
+  AC_SUBST([$1])
+])
diff --git a/po/m4/lib-prefix.m4 b/po/m4/lib-prefix.m4
new file mode 100644
index 0000000..999f712
--- /dev/null
+++ b/po/m4/lib-prefix.m4
@@ -0,0 +1,323 @@
+# lib-prefix.m4 serial 20
+dnl Copyright (C) 2001-2005, 2008-2022 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+
+dnl From Bruno Haible.
+
+dnl AC_LIB_PREFIX adds to the CPPFLAGS and LDFLAGS the flags that are needed
+dnl to access previously installed libraries. The basic assumption is that
+dnl a user will want packages to use other packages he previously installed
+dnl with the same --prefix option.
+dnl This macro is not needed if only AC_LIB_LINKFLAGS is used to locate
+dnl libraries, but is otherwise very convenient.
+AC_DEFUN([AC_LIB_PREFIX],
+[
+  AC_BEFORE([$0], [AC_LIB_LINKFLAGS])
+  AC_REQUIRE([AC_PROG_CC])
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  AC_REQUIRE([AC_LIB_PREPARE_MULTILIB])
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  dnl By default, look in $includedir and $libdir.
+  use_additional=yes
+  AC_LIB_WITH_FINAL_PREFIX([
+    eval additional_includedir=\"$includedir\"
+    eval additional_libdir=\"$libdir\"
+  ])
+  AC_ARG_WITH([lib-prefix],
+[[  --with-lib-prefix[=DIR] search for libraries in DIR/include and DIR/lib
+  --without-lib-prefix    don't search for libraries in includedir and libdir]],
+[
+    if test "X$withval" = "Xno"; then
+      use_additional=no
+    else
+      if test "X$withval" = "X"; then
+        AC_LIB_WITH_FINAL_PREFIX([
+          eval additional_includedir=\"$includedir\"
+          eval additional_libdir=\"$libdir\"
+        ])
+      else
+        additional_includedir="$withval/include"
+        additional_libdir="$withval/$acl_libdirstem"
+      fi
+    fi
+])
+  if test $use_additional = yes; then
+    dnl Potentially add $additional_includedir to $CPPFLAGS.
+    dnl But don't add it
+    dnl   1. if it's the standard /usr/include,
+    dnl   2. if it's already present in $CPPFLAGS,
+    dnl   3. if it's /usr/local/include and we are using GCC on Linux,
+    dnl   4. if it doesn't exist as a directory.
+    if test "X$additional_includedir" != "X/usr/include"; then
+      haveit=
+      for x in $CPPFLAGS; do
+        AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+        if test "X$x" = "X-I$additional_includedir"; then
+          haveit=yes
+          break
+        fi
+      done
+      if test -z "$haveit"; then
+        if test "X$additional_includedir" = "X/usr/local/include"; then
+          if test -n "$GCC"; then
+            case $host_os in
+              linux* | gnu* | k*bsd*-gnu) haveit=yes;;
+            esac
+          fi
+        fi
+        if test -z "$haveit"; then
+          if test -d "$additional_includedir"; then
+            dnl Really add $additional_includedir to $CPPFLAGS.
+            CPPFLAGS="${CPPFLAGS}${CPPFLAGS:+ }-I$additional_includedir"
+          fi
+        fi
+      fi
+    fi
+    dnl Potentially add $additional_libdir to $LDFLAGS.
+    dnl But don't add it
+    dnl   1. if it's the standard /usr/lib,
+    dnl   2. if it's already present in $LDFLAGS,
+    dnl   3. if it's /usr/local/lib and we are using GCC on Linux,
+    dnl   4. if it doesn't exist as a directory.
+    if test "X$additional_libdir" != "X/usr/$acl_libdirstem"; then
+      haveit=
+      for x in $LDFLAGS; do
+        AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+        if test "X$x" = "X-L$additional_libdir"; then
+          haveit=yes
+          break
+        fi
+      done
+      if test -z "$haveit"; then
+        if test "X$additional_libdir" = "X/usr/local/$acl_libdirstem"; then
+          if test -n "$GCC"; then
+            case $host_os in
+              linux*) haveit=yes;;
+            esac
+          fi
+        fi
+        if test -z "$haveit"; then
+          if test -d "$additional_libdir"; then
+            dnl Really add $additional_libdir to $LDFLAGS.
+            LDFLAGS="${LDFLAGS}${LDFLAGS:+ }-L$additional_libdir"
+          fi
+        fi
+      fi
+    fi
+  fi
+])
+
+dnl AC_LIB_PREPARE_PREFIX creates variables acl_final_prefix,
+dnl acl_final_exec_prefix, containing the values to which $prefix and
+dnl $exec_prefix will expand at the end of the configure script.
+AC_DEFUN([AC_LIB_PREPARE_PREFIX],
+[
+  dnl Unfortunately, prefix and exec_prefix get only finally determined
+  dnl at the end of configure.
+  if test "X$prefix" = "XNONE"; then
+    acl_final_prefix="$ac_default_prefix"
+  else
+    acl_final_prefix="$prefix"
+  fi
+  if test "X$exec_prefix" = "XNONE"; then
+    acl_final_exec_prefix='${prefix}'
+  else
+    acl_final_exec_prefix="$exec_prefix"
+  fi
+  acl_save_prefix="$prefix"
+  prefix="$acl_final_prefix"
+  eval acl_final_exec_prefix=\"$acl_final_exec_prefix\"
+  prefix="$acl_save_prefix"
+])
+
+dnl AC_LIB_WITH_FINAL_PREFIX([statement]) evaluates statement, with the
+dnl variables prefix and exec_prefix bound to the values they will have
+dnl at the end of the configure script.
+AC_DEFUN([AC_LIB_WITH_FINAL_PREFIX],
+[
+  acl_save_prefix="$prefix"
+  prefix="$acl_final_prefix"
+  acl_save_exec_prefix="$exec_prefix"
+  exec_prefix="$acl_final_exec_prefix"
+  $1
+  exec_prefix="$acl_save_exec_prefix"
+  prefix="$acl_save_prefix"
+])
+
+dnl AC_LIB_PREPARE_MULTILIB creates
+dnl - a function acl_is_expected_elfclass, that tests whether standard input
+dn;   has a 32-bit or 64-bit ELF header, depending on the host CPU ABI,
+dnl - 3 variables acl_libdirstem, acl_libdirstem2, acl_libdirstem3, containing
+dnl   the basename of the libdir to try in turn, either "lib" or "lib64" or
+dnl   "lib/64" or "lib32" or "lib/sparcv9" or "lib/amd64" or similar.
+AC_DEFUN([AC_LIB_PREPARE_MULTILIB],
+[
+  dnl There is no formal standard regarding lib, lib32, and lib64.
+  dnl On most glibc systems, the current practice is that on a system supporting
+  dnl 32-bit and 64-bit instruction sets or ABIs, 64-bit libraries go under
+  dnl $prefix/lib64 and 32-bit libraries go under $prefix/lib. However, on
+  dnl Arch Linux based distributions, it's the opposite: 32-bit libraries go
+  dnl under $prefix/lib32 and 64-bit libraries go under $prefix/lib.
+  dnl We determine the compiler's default mode by looking at the compiler's
+  dnl library search path. If at least one of its elements ends in /lib64 or
+  dnl points to a directory whose absolute pathname ends in /lib64, we use that
+  dnl for 64-bit ABIs. Similarly for 32-bit ABIs. Otherwise we use the default,
+  dnl namely "lib".
+  dnl On Solaris systems, the current practice is that on a system supporting
+  dnl 32-bit and 64-bit instruction sets or ABIs, 64-bit libraries go under
+  dnl $prefix/lib/64 (which is a symlink to either $prefix/lib/sparcv9 or
+  dnl $prefix/lib/amd64) and 32-bit libraries go under $prefix/lib.
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  AC_REQUIRE([gl_HOST_CPU_C_ABI_32BIT])
+
+  AC_CACHE_CHECK([for ELF binary format], [gl_cv_elf],
+    [AC_EGREP_CPP([Extensible Linking Format],
+       [#if defined __ELF__ || (defined __linux__ && defined __EDG__)
+        Extensible Linking Format
+        #endif
+       ],
+       [gl_cv_elf=yes],
+       [gl_cv_elf=no])
+    ])
+  if test $gl_cv_elf = yes; then
+    # Extract the ELF class of a file (5th byte) in decimal.
+    # Cf. https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header
+    if od -A x < /dev/null >/dev/null 2>/dev/null; then
+      # Use POSIX od.
+      func_elfclass ()
+      {
+        od -A n -t d1 -j 4 -N 1
+      }
+    else
+      # Use BSD hexdump.
+      func_elfclass ()
+      {
+        dd bs=1 count=1 skip=4 2>/dev/null | hexdump -e '1/1 "%3d "'
+        echo
+      }
+    fi
+    # Use 'expr', not 'test', to compare the values of func_elfclass, because on
+    # Solaris 11 OpenIndiana and Solaris 11 OmniOS, the result is 001 or 002,
+    # not 1 or 2.
+changequote(,)dnl
+    case $HOST_CPU_C_ABI_32BIT in
+      yes)
+        # 32-bit ABI.
+        acl_is_expected_elfclass ()
+        {
+          expr "`func_elfclass | sed -e 's/[ 	]//g'`" = 1 > /dev/null
+        }
+        ;;
+      no)
+        # 64-bit ABI.
+        acl_is_expected_elfclass ()
+        {
+          expr "`func_elfclass | sed -e 's/[ 	]//g'`" = 2 > /dev/null
+        }
+        ;;
+      *)
+        # Unknown.
+        acl_is_expected_elfclass ()
+        {
+          :
+        }
+        ;;
+    esac
+changequote([,])dnl
+  else
+    acl_is_expected_elfclass ()
+    {
+      :
+    }
+  fi
+
+  dnl Allow the user to override the result by setting acl_cv_libdirstems.
+  AC_CACHE_CHECK([for the common suffixes of directories in the library search path],
+    [acl_cv_libdirstems],
+    [dnl Try 'lib' first, because that's the default for libdir in GNU, see
+     dnl <https://www.gnu.org/prep/standards/html_node/Directory-Variables.html>.
+     acl_libdirstem=lib
+     acl_libdirstem2=
+     acl_libdirstem3=
+     case "$host_os" in
+       solaris*)
+         dnl See Solaris 10 Software Developer Collection > Solaris 64-bit Developer's Guide > The Development Environment
+         dnl <https://docs.oracle.com/cd/E19253-01/816-5138/dev-env/index.html>.
+         dnl "Portable Makefiles should refer to any library directories using the 64 symbolic link."
+         dnl But we want to recognize the sparcv9 or amd64 subdirectory also if the
+         dnl symlink is missing, so we set acl_libdirstem2 too.
+         if test $HOST_CPU_C_ABI_32BIT = no; then
+           acl_libdirstem2=lib/64
+           case "$host_cpu" in
+             sparc*)        acl_libdirstem3=lib/sparcv9 ;;
+             i*86 | x86_64) acl_libdirstem3=lib/amd64 ;;
+           esac
+         fi
+         ;;
+       *)
+         dnl If $CC generates code for a 32-bit ABI, the libraries are
+         dnl surely under $prefix/lib or $prefix/lib32, not $prefix/lib64.
+         dnl Similarly, if $CC generates code for a 64-bit ABI, the libraries
+         dnl are surely under $prefix/lib or $prefix/lib64, not $prefix/lib32.
+         dnl Find the compiler's search path. However, non-system compilers
+         dnl sometimes have odd library search paths. But we can't simply invoke
+         dnl '/usr/bin/gcc -print-search-dirs' because that would not take into
+         dnl account the -m32/-m31 or -m64 options from the $CC or $CFLAGS.
+         searchpath=`(LC_ALL=C $CC $CPPFLAGS $CFLAGS -print-search-dirs) 2>/dev/null \
+                     | sed -n -e 's,^libraries: ,,p' | sed -e 's,^=,,'`
+         if test $HOST_CPU_C_ABI_32BIT != no; then
+           # 32-bit or unknown ABI.
+           if test -d /usr/lib32; then
+             acl_libdirstem2=lib32
+           fi
+         fi
+         if test $HOST_CPU_C_ABI_32BIT != yes; then
+           # 64-bit or unknown ABI.
+           if test -d /usr/lib64; then
+             acl_libdirstem3=lib64
+           fi
+         fi
+         if test -n "$searchpath"; then
+           acl_save_IFS="${IFS= 	}"; IFS=":"
+           for searchdir in $searchpath; do
+             if test -d "$searchdir"; then
+               case "$searchdir" in
+                 */lib32/ | */lib32 ) acl_libdirstem2=lib32 ;;
+                 */lib64/ | */lib64 ) acl_libdirstem3=lib64 ;;
+                 */../ | */.. )
+                   # Better ignore directories of this form. They are misleading.
+                   ;;
+                 *) searchdir=`cd "$searchdir" && pwd`
+                    case "$searchdir" in
+                      */lib32 ) acl_libdirstem2=lib32 ;;
+                      */lib64 ) acl_libdirstem3=lib64 ;;
+                    esac ;;
+               esac
+             fi
+           done
+           IFS="$acl_save_IFS"
+           if test $HOST_CPU_C_ABI_32BIT = yes; then
+             # 32-bit ABI.
+             acl_libdirstem3=
+           fi
+           if test $HOST_CPU_C_ABI_32BIT = no; then
+             # 64-bit ABI.
+             acl_libdirstem2=
+           fi
+         fi
+         ;;
+     esac
+     test -n "$acl_libdirstem2" || acl_libdirstem2="$acl_libdirstem"
+     test -n "$acl_libdirstem3" || acl_libdirstem3="$acl_libdirstem"
+     acl_cv_libdirstems="$acl_libdirstem,$acl_libdirstem2,$acl_libdirstem3"
+    ])
+  dnl Decompose acl_cv_libdirstems into acl_libdirstem, acl_libdirstem2, and
+  dnl acl_libdirstem3.
+changequote(,)dnl
+  acl_libdirstem=`echo "$acl_cv_libdirstems" | sed -e 's/,.*//'`
+  acl_libdirstem2=`echo "$acl_cv_libdirstems" | sed -e 's/^[^,]*,//' -e 's/,.*//'`
+  acl_libdirstem3=`echo "$acl_cv_libdirstems" | sed -e 's/^[^,]*,[^,]*,//' -e 's/,.*//'`
+changequote([,])dnl
+])
diff --git a/po/m4/nls.m4 b/po/m4/nls.m4
new file mode 100644
index 0000000..f4f6b80
--- /dev/null
+++ b/po/m4/nls.m4
@@ -0,0 +1,32 @@
+# nls.m4 serial 6 (gettext-0.20.2)
+dnl Copyright (C) 1995-2003, 2005-2006, 2008-2014, 2016, 2019-2021 Free
+dnl Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl   Bruno Haible <haible@clisp.cons.org>, 2000-2003.
+
+AC_PREREQ([2.50])
+
+AC_DEFUN([AM_NLS],
+[
+  AC_MSG_CHECKING([whether NLS is requested])
+  dnl Default is enabled NLS
+  AC_ARG_ENABLE([nls],
+    [  --disable-nls           do not use Native Language Support],
+    USE_NLS=$enableval, USE_NLS=yes)
+  AC_MSG_RESULT([$USE_NLS])
+  AC_SUBST([USE_NLS])
+])
diff --git a/po/m4/po.m4 b/po/m4/po.m4
new file mode 100644
index 0000000..2f14f8e
--- /dev/null
+++ b/po/m4/po.m4
@@ -0,0 +1,454 @@
+# po.m4 serial 32 (gettext-0.21.1)
+dnl Copyright (C) 1995-2014, 2016, 2018-2022 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl   Bruno Haible <haible@clisp.cons.org>, 2000-2003.
+
+AC_PREREQ([2.60])
+
+dnl Checks for all prerequisites of the po subdirectory.
+AC_DEFUN([AM_PO_SUBDIRS],
+[
+  AC_REQUIRE([AC_PROG_MAKE_SET])dnl
+  AC_REQUIRE([AC_PROG_INSTALL])dnl
+  AC_REQUIRE([AC_PROG_MKDIR_P])dnl
+  AC_REQUIRE([AC_PROG_SED])dnl
+  AC_REQUIRE([AM_NLS])dnl
+
+  dnl Release version of the gettext macros. This is used to ensure that
+  dnl the gettext macros and po/Makefile.in.in are in sync.
+  AC_SUBST([GETTEXT_MACRO_VERSION], [0.20])
+
+  dnl Perform the following tests also if --disable-nls has been given,
+  dnl because they are needed for "make dist" to work.
+
+  dnl Search for GNU msgfmt in the PATH.
+  dnl The first test excludes Solaris msgfmt and early GNU msgfmt versions.
+  dnl The second test excludes FreeBSD msgfmt.
+  AM_PATH_PROG_WITH_TEST(MSGFMT, msgfmt,
+    [$ac_dir/$ac_word --statistics /dev/null >&]AS_MESSAGE_LOG_FD[ 2>&1 &&
+     (if $ac_dir/$ac_word --statistics /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi)],
+    :)
+  AC_PATH_PROG([GMSGFMT], [gmsgfmt], [$MSGFMT])
+
+  dnl Test whether it is GNU msgfmt >= 0.15.
+changequote(,)dnl
+  case `$GMSGFMT --version | sed 1q | sed -e 's,^[^0-9]*,,'` in
+    '' | 0.[0-9] | 0.[0-9].* | 0.1[0-4] | 0.1[0-4].*) GMSGFMT_015=: ;;
+    *) GMSGFMT_015=$GMSGFMT ;;
+  esac
+changequote([,])dnl
+  AC_SUBST([GMSGFMT_015])
+
+  dnl Search for GNU xgettext 0.12 or newer in the PATH.
+  dnl The first test excludes Solaris xgettext and early GNU xgettext versions.
+  dnl The second test excludes FreeBSD xgettext.
+  AM_PATH_PROG_WITH_TEST(XGETTEXT, xgettext,
+    [$ac_dir/$ac_word --omit-header --copyright-holder= --msgid-bugs-address= /dev/null >&]AS_MESSAGE_LOG_FD[ 2>&1 &&
+     (if $ac_dir/$ac_word --omit-header --copyright-holder= --msgid-bugs-address= /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi)],
+    :)
+  dnl Remove leftover from FreeBSD xgettext call.
+  rm -f messages.po
+
+  dnl Test whether it is GNU xgettext >= 0.15.
+changequote(,)dnl
+  case `$XGETTEXT --version | sed 1q | sed -e 's,^[^0-9]*,,'` in
+    '' | 0.[0-9] | 0.[0-9].* | 0.1[0-4] | 0.1[0-4].*) XGETTEXT_015=: ;;
+    *) XGETTEXT_015=$XGETTEXT ;;
+  esac
+changequote([,])dnl
+  AC_SUBST([XGETTEXT_015])
+
+  dnl Search for GNU msgmerge 0.11 or newer in the PATH.
+  AM_PATH_PROG_WITH_TEST(MSGMERGE, msgmerge,
+    [$ac_dir/$ac_word --update -q /dev/null /dev/null >&]AS_MESSAGE_LOG_FD[ 2>&1], :)
+
+  dnl Test whether it is GNU msgmerge >= 0.20.
+  if LC_ALL=C $MSGMERGE --help | grep ' --for-msgfmt ' >/dev/null; then
+    MSGMERGE_FOR_MSGFMT_OPTION='--for-msgfmt'
+  else
+    dnl Test whether it is GNU msgmerge >= 0.12.
+    if LC_ALL=C $MSGMERGE --help | grep ' --no-fuzzy-matching ' >/dev/null; then
+      MSGMERGE_FOR_MSGFMT_OPTION='--no-fuzzy-matching --no-location --quiet'
+    else
+      dnl With these old versions, $(MSGMERGE) $(MSGMERGE_FOR_MSGFMT_OPTION) is
+      dnl slow. But this is not a big problem, as such old gettext versions are
+      dnl hardly in use any more.
+      MSGMERGE_FOR_MSGFMT_OPTION='--no-location --quiet'
+    fi
+  fi
+  AC_SUBST([MSGMERGE_FOR_MSGFMT_OPTION])
+
+  dnl Support for AM_XGETTEXT_OPTION.
+  test -n "${XGETTEXT_EXTRA_OPTIONS+set}" || XGETTEXT_EXTRA_OPTIONS=
+  AC_SUBST([XGETTEXT_EXTRA_OPTIONS])
+
+  AC_CONFIG_COMMANDS([po-directories], [[
+    for ac_file in $CONFIG_FILES; do
+      # Support "outfile[:infile[:infile...]]"
+      case "$ac_file" in
+        *:*) ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
+      esac
+      # PO directories have a Makefile.in generated from Makefile.in.in.
+      case "$ac_file" in */Makefile.in)
+        # Adjust a relative srcdir.
+        ac_dir=`echo "$ac_file"|sed 's%/[^/][^/]*$%%'`
+        ac_dir_suffix=/`echo "$ac_dir"|sed 's%^\./%%'`
+        ac_dots=`echo "$ac_dir_suffix"|sed 's%/[^/]*%../%g'`
+        # In autoconf-2.13 it is called $ac_given_srcdir.
+        # In autoconf-2.50 it is called $srcdir.
+        test -n "$ac_given_srcdir" || ac_given_srcdir="$srcdir"
+        case "$ac_given_srcdir" in
+          .)  top_srcdir=`echo $ac_dots|sed 's%/$%%'` ;;
+          /*) top_srcdir="$ac_given_srcdir" ;;
+          *)  top_srcdir="$ac_dots$ac_given_srcdir" ;;
+        esac
+        # Treat a directory as a PO directory if and only if it has a
+        # POTFILES.in file. This allows packages to have multiple PO
+        # directories under different names or in different locations.
+        if test -f "$ac_given_srcdir/$ac_dir/POTFILES.in"; then
+          rm -f "$ac_dir/POTFILES"
+          test -n "$as_me" && echo "$as_me: creating $ac_dir/POTFILES" || echo "creating $ac_dir/POTFILES"
+          gt_tab=`printf '\t'`
+          cat "$ac_given_srcdir/$ac_dir/POTFILES.in" | sed -e "/^#/d" -e "/^[ ${gt_tab}]*\$/d" -e "s,.*,     $top_srcdir/& \\\\," | sed -e "\$s/\(.*\) \\\\/\1/" > "$ac_dir/POTFILES"
+          POMAKEFILEDEPS="POTFILES.in"
+          # ALL_LINGUAS, POFILES, UPDATEPOFILES, DUMMYPOFILES, GMOFILES depend
+          # on $ac_dir but don't depend on user-specified configuration
+          # parameters.
+          if test -f "$ac_given_srcdir/$ac_dir/LINGUAS"; then
+            # The LINGUAS file contains the set of available languages.
+            if test -n "$OBSOLETE_ALL_LINGUAS"; then
+              test -n "$as_me" && echo "$as_me: setting ALL_LINGUAS in configure.in is obsolete" || echo "setting ALL_LINGUAS in configure.in is obsolete"
+            fi
+            ALL_LINGUAS=`sed -e "/^#/d" -e "s/#.*//" "$ac_given_srcdir/$ac_dir/LINGUAS"`
+            POMAKEFILEDEPS="$POMAKEFILEDEPS LINGUAS"
+          else
+            # The set of available languages was given in configure.in.
+            ALL_LINGUAS=$OBSOLETE_ALL_LINGUAS
+          fi
+          # Compute POFILES
+          # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(lang).po)
+          # Compute UPDATEPOFILES
+          # as      $(foreach lang, $(ALL_LINGUAS), $(lang).po-update)
+          # Compute DUMMYPOFILES
+          # as      $(foreach lang, $(ALL_LINGUAS), $(lang).nop)
+          # Compute GMOFILES
+          # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(lang).gmo)
+          case "$ac_given_srcdir" in
+            .) srcdirpre= ;;
+            *) srcdirpre='$(srcdir)/' ;;
+          esac
+          POFILES=
+          UPDATEPOFILES=
+          DUMMYPOFILES=
+          GMOFILES=
+          for lang in $ALL_LINGUAS; do
+            POFILES="$POFILES $srcdirpre$lang.po"
+            UPDATEPOFILES="$UPDATEPOFILES $lang.po-update"
+            DUMMYPOFILES="$DUMMYPOFILES $lang.nop"
+            GMOFILES="$GMOFILES $srcdirpre$lang.gmo"
+          done
+          # CATALOGS depends on both $ac_dir and the user's LINGUAS
+          # environment variable.
+          INST_LINGUAS=
+          if test -n "$ALL_LINGUAS"; then
+            for presentlang in $ALL_LINGUAS; do
+              useit=no
+              if test "%UNSET%" != "$LINGUAS"; then
+                desiredlanguages="$LINGUAS"
+              else
+                desiredlanguages="$ALL_LINGUAS"
+              fi
+              for desiredlang in $desiredlanguages; do
+                # Use the presentlang catalog if desiredlang is
+                #   a. equal to presentlang, or
+                #   b. a variant of presentlang (because in this case,
+                #      presentlang can be used as a fallback for messages
+                #      which are not translated in the desiredlang catalog).
+                case "$desiredlang" in
+                  "$presentlang" | "$presentlang"_* | "$presentlang".* | "$presentlang"@*)
+                    useit=yes
+                    ;;
+                esac
+              done
+              if test $useit = yes; then
+                INST_LINGUAS="$INST_LINGUAS $presentlang"
+              fi
+            done
+          fi
+          CATALOGS=
+          if test -n "$INST_LINGUAS"; then
+            for lang in $INST_LINGUAS; do
+              CATALOGS="$CATALOGS $lang.gmo"
+            done
+          fi
+          test -n "$as_me" && echo "$as_me: creating $ac_dir/Makefile" || echo "creating $ac_dir/Makefile"
+          sed -e "/^POTFILES =/r $ac_dir/POTFILES" -e "/^# Makevars/r $ac_given_srcdir/$ac_dir/Makevars" -e "s|@POFILES@|$POFILES|g" -e "s|@UPDATEPOFILES@|$UPDATEPOFILES|g" -e "s|@DUMMYPOFILES@|$DUMMYPOFILES|g" -e "s|@GMOFILES@|$GMOFILES|g" -e "s|@CATALOGS@|$CATALOGS|g" -e "s|@POMAKEFILEDEPS@|$POMAKEFILEDEPS|g" "$ac_dir/Makefile.in" > "$ac_dir/Makefile"
+          for f in "$ac_given_srcdir/$ac_dir"/Rules-*; do
+            if test -f "$f"; then
+              case "$f" in
+                *.orig | *.bak | *~) ;;
+                *) cat "$f" >> "$ac_dir/Makefile" ;;
+              esac
+            fi
+          done
+        fi
+        ;;
+      esac
+    done]],
+   [# Capture the value of obsolete ALL_LINGUAS because we need it to compute
+    # POFILES, UPDATEPOFILES, DUMMYPOFILES, GMOFILES, CATALOGS.
+    OBSOLETE_ALL_LINGUAS="$ALL_LINGUAS"
+    # Capture the value of LINGUAS because we need it to compute CATALOGS.
+    LINGUAS="${LINGUAS-%UNSET%}"
+   ])
+])
+
+dnl Postprocesses a Makefile in a directory containing PO files.
+AC_DEFUN([AM_POSTPROCESS_PO_MAKEFILE],
+[
+  # When this code is run, in config.status, two variables have already been
+  # set:
+  # - OBSOLETE_ALL_LINGUAS is the value of LINGUAS set in configure.in,
+  # - LINGUAS is the value of the environment variable LINGUAS at configure
+  #   time.
+
+changequote(,)dnl
+  # Adjust a relative srcdir.
+  ac_dir=`echo "$ac_file"|sed 's%/[^/][^/]*$%%'`
+  ac_dir_suffix=/`echo "$ac_dir"|sed 's%^\./%%'`
+  ac_dots=`echo "$ac_dir_suffix"|sed 's%/[^/]*%../%g'`
+  # In autoconf-2.13 it is called $ac_given_srcdir.
+  # In autoconf-2.50 it is called $srcdir.
+  test -n "$ac_given_srcdir" || ac_given_srcdir="$srcdir"
+  case "$ac_given_srcdir" in
+    .)  top_srcdir=`echo $ac_dots|sed 's%/$%%'` ;;
+    /*) top_srcdir="$ac_given_srcdir" ;;
+    *)  top_srcdir="$ac_dots$ac_given_srcdir" ;;
+  esac
+
+  # Find a way to echo strings without interpreting backslash.
+  if test "X`(echo '\t') 2>/dev/null`" = 'X\t'; then
+    gt_echo='echo'
+  else
+    if test "X`(printf '%s\n' '\t') 2>/dev/null`" = 'X\t'; then
+      gt_echo='printf %s\n'
+    else
+      echo_func () {
+        cat <<EOT
+$*
+EOT
+      }
+      gt_echo='echo_func'
+    fi
+  fi
+
+  # A sed script that extracts the value of VARIABLE from a Makefile.
+  tab=`printf '\t'`
+  sed_x_variable='
+# Test if the hold space is empty.
+x
+s/P/P/
+x
+ta
+# Yes it was empty. Look if we have the expected variable definition.
+/^['"${tab}"' ]*VARIABLE['"${tab}"' ]*=/{
+  # Seen the first line of the variable definition.
+  s/^['"${tab}"' ]*VARIABLE['"${tab}"' ]*=//
+  ba
+}
+bd
+:a
+# Here we are processing a line from the variable definition.
+# Remove comment, more precisely replace it with a space.
+s/#.*$/ /
+# See if the line ends in a backslash.
+tb
+:b
+s/\\$//
+# Print the line, without the trailing backslash.
+p
+tc
+# There was no trailing backslash. The end of the variable definition is
+# reached. Clear the hold space.
+s/^.*$//
+x
+bd
+:c
+# A trailing backslash means that the variable definition continues in the
+# next line. Put a nonempty string into the hold space to indicate this.
+s/^.*$/P/
+x
+:d
+'
+changequote([,])dnl
+
+  # Set POTFILES to the value of the Makefile variable POTFILES.
+  sed_x_POTFILES=`$gt_echo "$sed_x_variable" | sed -e '/^ *#/d' -e 's/VARIABLE/POTFILES/g'`
+  POTFILES=`sed -n -e "$sed_x_POTFILES" < "$ac_file"`
+  # Compute POTFILES_DEPS as
+  #   $(foreach file, $(POTFILES), $(top_srcdir)/$(file))
+  POTFILES_DEPS=
+  for file in $POTFILES; do
+    POTFILES_DEPS="$POTFILES_DEPS "'$(top_srcdir)/'"$file"
+  done
+  POMAKEFILEDEPS=""
+
+  if test -n "$OBSOLETE_ALL_LINGUAS"; then
+    test -n "$as_me" && echo "$as_me: setting ALL_LINGUAS in configure.in is obsolete" || echo "setting ALL_LINGUAS in configure.in is obsolete"
+  fi
+  if test -f "$ac_given_srcdir/$ac_dir/LINGUAS"; then
+    # The LINGUAS file contains the set of available languages.
+    ALL_LINGUAS=`sed -e "/^#/d" -e "s/#.*//" "$ac_given_srcdir/$ac_dir/LINGUAS"`
+    POMAKEFILEDEPS="$POMAKEFILEDEPS LINGUAS"
+  else
+    # Set ALL_LINGUAS to the value of the Makefile variable LINGUAS.
+    sed_x_LINGUAS=`$gt_echo "$sed_x_variable" | sed -e '/^ *#/d' -e 's/VARIABLE/LINGUAS/g'`
+    ALL_LINGUAS=`sed -n -e "$sed_x_LINGUAS" < "$ac_file"`
+  fi
+  # Compute POFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(lang).po)
+  # Compute UPDATEPOFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(lang).po-update)
+  # Compute DUMMYPOFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(lang).nop)
+  # Compute GMOFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(lang).gmo)
+  # Compute PROPERTIESFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(DOMAIN)_$(lang).properties)
+  # Compute CLASSFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(DOMAIN)_$(lang).class)
+  # Compute QMFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(lang).qm)
+  # Compute MSGFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(frob $(lang)).msg)
+  # Compute RESOURCESDLLFILES
+  # as      $(foreach lang, $(ALL_LINGUAS), $(srcdir)/$(frob $(lang))/$(DOMAIN).resources.dll)
+  case "$ac_given_srcdir" in
+    .) srcdirpre= ;;
+    *) srcdirpre='$(srcdir)/' ;;
+  esac
+  POFILES=
+  UPDATEPOFILES=
+  DUMMYPOFILES=
+  GMOFILES=
+  PROPERTIESFILES=
+  CLASSFILES=
+  QMFILES=
+  MSGFILES=
+  RESOURCESDLLFILES=
+  for lang in $ALL_LINGUAS; do
+    POFILES="$POFILES $srcdirpre$lang.po"
+    UPDATEPOFILES="$UPDATEPOFILES $lang.po-update"
+    DUMMYPOFILES="$DUMMYPOFILES $lang.nop"
+    GMOFILES="$GMOFILES $srcdirpre$lang.gmo"
+    PROPERTIESFILES="$PROPERTIESFILES \$(srcdir)/\$(DOMAIN)_$lang.properties"
+    CLASSFILES="$CLASSFILES \$(srcdir)/\$(DOMAIN)_$lang.class"
+    QMFILES="$QMFILES $srcdirpre$lang.qm"
+    frobbedlang=`echo $lang | sed -e 's/\..*$//' -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'`
+    MSGFILES="$MSGFILES $srcdirpre$frobbedlang.msg"
+    frobbedlang=`echo $lang | sed -e 's/_/-/g' -e 's/^sr-CS/sr-SP/' -e 's/@latin$/-Latn/' -e 's/@cyrillic$/-Cyrl/' -e 's/^sr-SP$/sr-SP-Latn/' -e 's/^uz-UZ$/uz-UZ-Latn/'`
+    RESOURCESDLLFILES="$RESOURCESDLLFILES $srcdirpre$frobbedlang/\$(DOMAIN).resources.dll"
+  done
+  # CATALOGS depends on both $ac_dir and the user's LINGUAS
+  # environment variable.
+  INST_LINGUAS=
+  if test -n "$ALL_LINGUAS"; then
+    for presentlang in $ALL_LINGUAS; do
+      useit=no
+      if test "%UNSET%" != "$LINGUAS"; then
+        desiredlanguages="$LINGUAS"
+      else
+        desiredlanguages="$ALL_LINGUAS"
+      fi
+      for desiredlang in $desiredlanguages; do
+        # Use the presentlang catalog if desiredlang is
+        #   a. equal to presentlang, or
+        #   b. a variant of presentlang (because in this case,
+        #      presentlang can be used as a fallback for messages
+        #      which are not translated in the desiredlang catalog).
+        case "$desiredlang" in
+          "$presentlang" | "$presentlang"_* | "$presentlang".* | "$presentlang"@*)
+            useit=yes
+            ;;
+        esac
+      done
+      if test $useit = yes; then
+        INST_LINGUAS="$INST_LINGUAS $presentlang"
+      fi
+    done
+  fi
+  CATALOGS=
+  JAVACATALOGS=
+  QTCATALOGS=
+  TCLCATALOGS=
+  CSHARPCATALOGS=
+  if test -n "$INST_LINGUAS"; then
+    for lang in $INST_LINGUAS; do
+      CATALOGS="$CATALOGS $lang.gmo"
+      JAVACATALOGS="$JAVACATALOGS \$(DOMAIN)_$lang.properties"
+      QTCATALOGS="$QTCATALOGS $lang.qm"
+      frobbedlang=`echo $lang | sed -e 's/\..*$//' -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'`
+      TCLCATALOGS="$TCLCATALOGS $frobbedlang.msg"
+      frobbedlang=`echo $lang | sed -e 's/_/-/g' -e 's/^sr-CS/sr-SP/' -e 's/@latin$/-Latn/' -e 's/@cyrillic$/-Cyrl/' -e 's/^sr-SP$/sr-SP-Latn/' -e 's/^uz-UZ$/uz-UZ-Latn/'`
+      CSHARPCATALOGS="$CSHARPCATALOGS $frobbedlang/\$(DOMAIN).resources.dll"
+    done
+  fi
+
+  sed -e "s|@POTFILES_DEPS@|$POTFILES_DEPS|g" -e "s|@POFILES@|$POFILES|g" -e "s|@UPDATEPOFILES@|$UPDATEPOFILES|g" -e "s|@DUMMYPOFILES@|$DUMMYPOFILES|g" -e "s|@GMOFILES@|$GMOFILES|g" -e "s|@PROPERTIESFILES@|$PROPERTIESFILES|g" -e "s|@CLASSFILES@|$CLASSFILES|g" -e "s|@QMFILES@|$QMFILES|g" -e "s|@MSGFILES@|$MSGFILES|g" -e "s|@RESOURCESDLLFILES@|$RESOURCESDLLFILES|g" -e "s|@CATALOGS@|$CATALOGS|g" -e "s|@JAVACATALOGS@|$JAVACATALOGS|g" -e "s|@QTCATALOGS@|$QTCATALOGS|g" -e "s|@TCLCATALOGS@|$TCLCATALOGS|g" -e "s|@CSHARPCATALOGS@|$CSHARPCATALOGS|g" -e 's,^#distdir:,distdir:,' < "$ac_file" > "$ac_file.tmp"
+  tab=`printf '\t'`
+  if grep -l '@TCLCATALOGS@' "$ac_file" > /dev/null; then
+    # Add dependencies that cannot be formulated as a simple suffix rule.
+    for lang in $ALL_LINGUAS; do
+      frobbedlang=`echo $lang | sed -e 's/\..*$//' -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'`
+      cat >> "$ac_file.tmp" <<EOF
+$frobbedlang.msg: $lang.po
+${tab}@echo "\$(MSGFMT) -c --tcl -d \$(srcdir) -l $lang $srcdirpre$lang.po"; \
+${tab}\$(MSGFMT) -c --tcl -d "\$(srcdir)" -l $lang $srcdirpre$lang.po || { rm -f "\$(srcdir)/$frobbedlang.msg"; exit 1; }
+EOF
+    done
+  fi
+  if grep -l '@CSHARPCATALOGS@' "$ac_file" > /dev/null; then
+    # Add dependencies that cannot be formulated as a simple suffix rule.
+    for lang in $ALL_LINGUAS; do
+      frobbedlang=`echo $lang | sed -e 's/_/-/g' -e 's/^sr-CS/sr-SP/' -e 's/@latin$/-Latn/' -e 's/@cyrillic$/-Cyrl/' -e 's/^sr-SP$/sr-SP-Latn/' -e 's/^uz-UZ$/uz-UZ-Latn/'`
+      cat >> "$ac_file.tmp" <<EOF
+$frobbedlang/\$(DOMAIN).resources.dll: $lang.po
+${tab}@echo "\$(MSGFMT) -c --csharp -d \$(srcdir) -l $lang $srcdirpre$lang.po -r \$(DOMAIN)"; \
+${tab}\$(MSGFMT) -c --csharp -d "\$(srcdir)" -l $lang $srcdirpre$lang.po -r "\$(DOMAIN)" || { rm -f "\$(srcdir)/$frobbedlang.msg"; exit 1; }
+EOF
+    done
+  fi
+  if test -n "$POMAKEFILEDEPS"; then
+    cat >> "$ac_file.tmp" <<EOF
+Makefile: $POMAKEFILEDEPS
+EOF
+  fi
+  mv "$ac_file.tmp" "$ac_file"
+])
+
+dnl Initializes the accumulator used by AM_XGETTEXT_OPTION.
+AC_DEFUN([AM_XGETTEXT_OPTION_INIT],
+[
+  XGETTEXT_EXTRA_OPTIONS=
+])
+
+dnl Registers an option to be passed to xgettext in the po subdirectory.
+AC_DEFUN([AM_XGETTEXT_OPTION],
+[
+  AC_REQUIRE([AM_XGETTEXT_OPTION_INIT])
+  XGETTEXT_EXTRA_OPTIONS="$XGETTEXT_EXTRA_OPTIONS $1"
+])
diff --git a/po/m4/progtest.m4 b/po/m4/progtest.m4
new file mode 100644
index 0000000..9e8823c
--- /dev/null
+++ b/po/m4/progtest.m4
@@ -0,0 +1,91 @@
+# progtest.m4 serial 9 (gettext-0.21.1)
+dnl Copyright (C) 1996-2003, 2005, 2008-2021 Free Software Foundation, Inc.
+dnl This file is free software; the Free Software Foundation
+dnl gives unlimited permission to copy and/or distribute it,
+dnl with or without modifications, as long as this notice is preserved.
+dnl
+dnl This file can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Lesser General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Lesser General Public License, and the rest of the GNU
+dnl gettext package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1996.
+
+AC_PREREQ([2.53])
+
+# Search path for a program which passes the given test.
+
+dnl AM_PATH_PROG_WITH_TEST(VARIABLE, PROG-TO-CHECK-FOR,
+dnl   TEST-PERFORMED-ON-FOUND_PROGRAM [, VALUE-IF-NOT-FOUND [, PATH]])
+AC_DEFUN([AM_PATH_PROG_WITH_TEST],
+[
+# Prepare PATH_SEPARATOR.
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  # Determine PATH_SEPARATOR by trying to find /bin/sh in a PATH which
+  # contains only /bin. Note that ksh looks also at the FPATH variable,
+  # so we have to set that as well for the test.
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 \
+    && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 \
+           || PATH_SEPARATOR=';'
+       }
+fi
+
+# Find out how to test for executable files. Don't use a zero-byte file,
+# as systems may use methods other than mode bits to determine executability.
+cat >conf$$.file <<_ASEOF
+#! /bin/sh
+exit 0
+_ASEOF
+chmod +x conf$$.file
+if test -x conf$$.file >/dev/null 2>&1; then
+  ac_executable_p="test -x"
+else
+  ac_executable_p="test -f"
+fi
+rm -f conf$$.file
+
+# Extract the first word of "$2", so it can be a program name with args.
+set dummy $2; ac_word=[$]2
+AC_MSG_CHECKING([for $ac_word])
+AC_CACHE_VAL([ac_cv_path_$1],
+[case "[$]$1" in
+  [[\\/]]* | ?:[[\\/]]*)
+    ac_cv_path_$1="[$]$1" # Let the user override the test with a path.
+    ;;
+  *)
+    ac_save_IFS="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in m4_if([$5], , $PATH, [$5]); do
+      IFS="$ac_save_IFS"
+      test -z "$ac_dir" && ac_dir=.
+      for ac_exec_ext in '' $ac_executable_extensions; do
+        if $ac_executable_p "$ac_dir/$ac_word$ac_exec_ext"; then
+          echo "$as_me: trying $ac_dir/$ac_word..." >&AS_MESSAGE_LOG_FD
+          if [$3]; then
+            ac_cv_path_$1="$ac_dir/$ac_word$ac_exec_ext"
+            break 2
+          fi
+        fi
+      done
+    done
+    IFS="$ac_save_IFS"
+dnl If no 4th arg is given, leave the cache variable unset,
+dnl so AC_PATH_PROGS will keep looking.
+m4_if([$4], , , [  test -z "[$]ac_cv_path_$1" && ac_cv_path_$1="$4"
+])dnl
+    ;;
+esac])dnl
+$1="$ac_cv_path_$1"
+if test m4_if([$4], , [-n "[$]$1"], ["[$]$1" != "$4"]); then
+  AC_MSG_RESULT([$][$1])
+else
+  AC_MSG_RESULT([no])
+fi
+AC_SUBST([$1])dnl
+])
diff --git a/po/po-configure.ac.in b/po/po-configure.ac.in
new file mode 100644
index 0000000..6f5e4a6
--- /dev/null
+++ b/po/po-configure.ac.in
@@ -0,0 +1,51 @@
+AC_INIT([@PACKAGE_NAME@],[@PACKAGE_VERSION@],[@PACKAGE_BUGREPORT@])
+CONFIG_STATUS='./po-config.status'
+
+AC_CONFIG_AUX_DIR([@MHD_AUX_DIR@])
+AC_CONFIG_MACRO_DIR([m4])
+
+AC_PRESERVE_HELP_ORDER
+
+AC_MSG_NOTICE([
+This special $as_me is designed to be run only internally as part of distribution tarball building process.
+The only purpose of the $as_me is a preparation of the files to update ${PACKAGE_TARNAME}.pot
+
+$as_me is not meant to be started by the user and is not needed to build ${PACKAGE_NAME} library.
+])
+AC_MSG_NOTICE([Check src/examples/msgs_i18n.c for inspiration how to use ${PACKAGE_TARNAME}.pot])
+
+AM_PROG_INSTALL_SH
+AC_PROG_MKDIR_P
+
+AS_VAR_SET_IF([enable_nls], [], [[enable_nls=no]])
+AM_GNU_GETTEXT([external],[need-ngettext])
+AM_GNU_GETTEXT_REQUIRE_VERSION([0.18])
+
+m4_divert_text([HELP_VAR_END], [[
+###############################################################################
+This special po-configure is designed to be run only internally as part of
+distribution tarball building process.
+The only purpose of the po-configure is a preparation of the files to update
+@PACKAGE_TARNAME@.pot
+
+po-configure is not meant to be started by the user and is not needed to build
+@PACKAGE_NAME@ library.
+###############################################################################
+]])
+
+# Hacks for libmicrohttpd
+AC_CONFIG_FILES([po/stamp-m],[echo 'timestamp' > po/stamp-m])
+AC_SUBST([POMAKEFILEDEPS],["POTFILES.in stamp-m"])
+AM_SUBST_NOTMAKE([POMAKEFILEDEPS])
+AC_SUBST([MHD_CONFIG_SHELL],["${CONFIG_SHELL}"])
+AC_SUBST([MHD_AUX_DIR],['@MHD_AUX_DIR@'])
+
+AC_CONFIG_FILES([po/Makefile.in])
+AS_IF([test -z "${XGETTEXT}" || test "x${XGETTEXT}" = "x:"], [AC_MSG_ERROR([Cannot find xgettext. xgettext is required to update distribution tarball files.])])
+AC_SUBST([PACKAGE],["${PACKAGE_TARNAME}"])
+AC_SUBST([VERSION],["${PACKAGE_VERSION}"])
+AC_SUBST([CROSS_COMPILING],["${cross_compiling}"])
+AC_SUBST([MKDIR_P])
+AC_SUBST([mkdir_p],['$(MKDIR_P)'])
+
+AC_OUTPUT
diff --git a/po/quot.sed b/po/quot.sed
new file mode 100644
index 0000000..0122c46
--- /dev/null
+++ b/po/quot.sed
@@ -0,0 +1,6 @@
+s/"\([^"]*\)"/“\1”/g
+s/`\([^`']*\)'/‘\1’/g
+s/ '\([^`']*\)' / ‘\1’ /g
+s/ '\([^`']*\)'$/ ‘\1’/g
+s/^'\([^`']*\)' /‘\1’ /g
+s/“”/""/g
diff --git a/po/remove-potcdate.sin b/po/remove-potcdate.sin
new file mode 100644
index 0000000..8c70dfb
--- /dev/null
+++ b/po/remove-potcdate.sin
@@ -0,0 +1,25 @@
+# Sed script that removes the POT-Creation-Date line in the header entry
+# from a POT file.
+#
+# Copyright (C) 2002 Free Software Foundation, Inc.
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty provided the copyright
+# notice and this notice are preserved.  This file is offered as-is,
+# without any warranty.
+#
+# The distinction between the first and the following occurrences of the
+# pattern is achieved by looking at the hold space.
+/^"POT-Creation-Date: .*"$/{
+x
+# Test if the hold space is empty.
+s/P/P/
+ta
+# Yes it was empty. First occurrence. Remove the line.
+g
+d
+bb
+:a
+# The hold space was nonempty. Following occurrences. Do nothing.
+x
+:b
+}
diff --git a/po/stamp-po b/po/stamp-po
new file mode 100644
index 0000000..9788f70
--- /dev/null
+++ b/po/stamp-po
@@ -0,0 +1 @@
+timestamp
diff --git a/src/.gitignore b/src/.gitignore
new file mode 100644
index 0000000..e3884c1
--- /dev/null
+++ b/src/.gitignore
@@ -0,0 +1,6 @@
+*.exe
+*.o
+*.lo
+*.la
+*.log
+*.trs
diff --git a/src/Makefile.am b/src/Makefile.am
index d496c95..85a1051 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,31 +1,26 @@
 # This Makefile.am is in the public domain
-if HAVE_CURL
-curltests = testcurl
-if HAVE_ZZUF
-if HAVE_SOCAT
-zzuftests = testzzuf
-endif
-endif
-endif
-if ENABLE_SPDY
-if HAVE_OPENSSL
-microspdy = microspdy
-if HAVE_CURL
-microspdy += spdy2http
-endif
-#if HAVE_SPDYLAY
-microspdy += testspdy
-#endif
+
+SUBDIRS = include microhttpd .
+
+if RUN_LIBCURL_TESTS
+SUBDIRS += testcurl
+if RUN_ZZUF_TESTS
+SUBDIRS += testzzuf
 endif
 endif
 
-SUBDIRS = include platform microhttpd $(microspdy) $(curltests) $(zzuftests) .
+# Finally (last!) also build experimental lib...
+if HAVE_EXPERIMENTAL
+SUBDIRS += microhttpd_ws lib
+endif
 
 if BUILD_EXAMPLES
 SUBDIRS += examples
 endif
 
+
 EXTRA_DIST = \
  datadir/cert-and-key.pem \
- datadir/cert-and-key-for-wireshark.pem \
- datadir/spdy-draft.txt
+ datadir/cert-and-key-for-wireshark.pem
+
+.NOTPARALLEL:
diff --git a/src/Makefile.in b/src/Makefile.in
deleted file mode 100644
index 8c4db5b..0000000
--- a/src/Makefile.in
+++ /dev/null
@@ -1,678 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@ENABLE_SPDY_TRUE@@HAVE_CURL_TRUE@@HAVE_OPENSSL_TRUE@am__append_1 = spdy2http
-@BUILD_EXAMPLES_TRUE@am__append_2 = examples
-subdir = src
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = include platform microhttpd microspdy spdy2http \
-	testspdy testcurl testzzuf . examples
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-@HAVE_CURL_TRUE@curltests = testcurl
-@HAVE_CURL_TRUE@@HAVE_SOCAT_TRUE@@HAVE_ZZUF_TRUE@zzuftests = testzzuf
-#if HAVE_SPDYLAY
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@microspdy = microspdy \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@	$(am__append_1) testspdy
-#endif
-SUBDIRS = include platform microhttpd $(microspdy) $(curltests) \
-	$(zzuftests) . $(am__append_2)
-EXTRA_DIST = \
- datadir/cert-and-key.pem \
- datadir/cert-and-key-for-wireshark.pem \
- datadir/spdy-draft.txt
-
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-am clean clean-generic clean-libtool cscopelist-am ctags \
-	ctags-am distclean distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \
-	ps ps-am tags tags-am uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/datadir/cert-and-key-for-wireshark.pem b/src/datadir/cert-and-key-for-wireshark.pem
deleted file mode 100644
index eacd4b4..0000000
--- a/src/datadir/cert-and-key-for-wireshark.pem
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXgIBAAKBgQDc1k7EFEspRcr6PdPmvAd02hBDUG2O5dDkoRK+6tgEBvQxsTxz
-50TGwJ8RbSV+qUOnncZBwhnI4i71QSEezMP6I6liRA+fUtdh3cZFvdDpxgU6P15y
-5JxfnnDeZJR5O4tfMxN99t34EOEMruZZ0CNYJJgbmIteE0hLI418oUs7cwIDAQAB
-AoGAW3WOLXrSHge/pp/QkLCyzdw5/AblONdJCkcDQnp0eEaA/8uNY9sWCtJfjpIL
-g0eKs3KOV1GR6DZ0iDIvC1h2mO6pwyrJhRYHKPO9pnx7xpv1T9zYTuVwoMfVjPfO
-UCWFedSsSKR76+oP0TrwPDqp3JoMFcAyAqZKMg2JrRUpL3ECQQD92cVSYxSEKwX3
-cHWXVp1mSkuRMR/KX70NC/9XpYr8FEjvtXBTkmp7oG3TaDwd6nhSAodtY+Zkseyj
-k5NXM6sNAkEA3rT6opc1YK0pL3uweg+AFP4lRUYrrft1bDELhLmVm9Nf4xEdTnDO
-IotiX4GYQ64Bm8J+yxVU204soGynVXbgfwJBALQLCqq+X0TGhvrSpnRqGET+mM4n
-u1Z7xMhGJBpz7TmQ4ZIya7K6fA+m3347xbeqHyB7brYlTrlIgIAcITqOCNkCQQDE
-3tuJC34mHi0ASqkw3a7t39R2rpdCT733jEuQYrY8b9id061CgDnZE7o8j0VY3uOR
-G5gWUp8W1r5gemxaAqJlAkEAwVImBKyKy3oIMsd3WsoqYCMBM+cpX8H2JAEEISPT
-Y5zSPZ7kT9JgY2zJwXf3qL+uG1oKZ6f0wn4BYujctTbXwQ==
------END RSA PRIVATE KEY-----
diff --git a/src/datadir/cert-and-key.pem b/src/datadir/cert-and-key.pem
deleted file mode 100644
index e33608c..0000000
--- a/src/datadir/cert-and-key.pem
+++ /dev/null
@@ -1,34 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXgIBAAKBgQDc1k7EFEspRcr6PdPmvAd02hBDUG2O5dDkoRK+6tgEBvQxsTxz
-50TGwJ8RbSV+qUOnncZBwhnI4i71QSEezMP6I6liRA+fUtdh3cZFvdDpxgU6P15y
-5JxfnnDeZJR5O4tfMxN99t34EOEMruZZ0CNYJJgbmIteE0hLI418oUs7cwIDAQAB
-AoGAW3WOLXrSHge/pp/QkLCyzdw5/AblONdJCkcDQnp0eEaA/8uNY9sWCtJfjpIL
-g0eKs3KOV1GR6DZ0iDIvC1h2mO6pwyrJhRYHKPO9pnx7xpv1T9zYTuVwoMfVjPfO
-UCWFedSsSKR76+oP0TrwPDqp3JoMFcAyAqZKMg2JrRUpL3ECQQD92cVSYxSEKwX3
-cHWXVp1mSkuRMR/KX70NC/9XpYr8FEjvtXBTkmp7oG3TaDwd6nhSAodtY+Zkseyj
-k5NXM6sNAkEA3rT6opc1YK0pL3uweg+AFP4lRUYrrft1bDELhLmVm9Nf4xEdTnDO
-IotiX4GYQ64Bm8J+yxVU204soGynVXbgfwJBALQLCqq+X0TGhvrSpnRqGET+mM4n
-u1Z7xMhGJBpz7TmQ4ZIya7K6fA+m3347xbeqHyB7brYlTrlIgIAcITqOCNkCQQDE
-3tuJC34mHi0ASqkw3a7t39R2rpdCT733jEuQYrY8b9id061CgDnZE7o8j0VY3uOR
-G5gWUp8W1r5gemxaAqJlAkEAwVImBKyKy3oIMsd3WsoqYCMBM+cpX8H2JAEEISPT
-Y5zSPZ7kT9JgY2zJwXf3qL+uG1oKZ6f0wn4BYujctTbXwQ==
------END RSA PRIVATE KEY-----
------BEGIN CERTIFICATE-----
-MIIDJTCCAo6gAwIBAgIJAIjfJkuxM1pAMA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV
-BAYTAkJHMQ4wDAYDVQQIEwVTb2ZpYTEOMAwGA1UEBxMFU29maWExCzAJBgNVBAoT
-AkFVMQ8wDQYDVQQDEwZBbmRyZXkxHjAcBgkqhkiG9w0BCQEWD3Jvb3RAZ29vZ2xl
-LmNvbTAeFw0xMjA5MDgxMTU2MzNaFw0xMzA5MDgxMTU2MzNaMGsxCzAJBgNVBAYT
-AkJHMQ4wDAYDVQQIEwVTb2ZpYTEOMAwGA1UEBxMFU29maWExCzAJBgNVBAoTAkFV
-MQ8wDQYDVQQDEwZBbmRyZXkxHjAcBgkqhkiG9w0BCQEWD3Jvb3RAZ29vZ2xlLmNv
-bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3NZOxBRLKUXK+j3T5rwHdNoQ
-Q1BtjuXQ5KESvurYBAb0MbE8c+dExsCfEW0lfqlDp53GQcIZyOIu9UEhHszD+iOp
-YkQPn1LXYd3GRb3Q6cYFOj9ecuScX55w3mSUeTuLXzMTffbd+BDhDK7mWdAjWCSY
-G5iLXhNISyONfKFLO3MCAwEAAaOB0DCBzTAdBgNVHQ4EFgQUPp4dR3IT0t6bSE3Y
-b91MyHJU2+8wgZ0GA1UdIwSBlTCBkoAUPp4dR3IT0t6bSE3Yb91MyHJU2++hb6Rt
-MGsxCzAJBgNVBAYTAkJHMQ4wDAYDVQQIEwVTb2ZpYTEOMAwGA1UEBxMFU29maWEx
-CzAJBgNVBAoTAkFVMQ8wDQYDVQQDEwZBbmRyZXkxHjAcBgkqhkiG9w0BCQEWD3Jv
-b3RAZ29vZ2xlLmNvbYIJAIjfJkuxM1pAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN
-AQEFBQADgYEAeBPoIRueOJ+SwpVniE2gmnvogWH9+irJnapDKGZrC/JsTA7ArqRd
-EHO1xZxqF+v+v128LmwWAdaazgMUHjR7e7B0xo4Tcp+9+voczc/GBTO0wnp6HT76
-2kUB6rPwwg9bycW8hAJiJJtr3IW5eYMtXDqM4RrbxhA1n2EAaZPVa5s=
------END CERTIFICATE-----
diff --git a/src/datadir/spdy-draft.txt b/src/datadir/spdy-draft.txt
deleted file mode 100644
index c31648c..0000000
--- a/src/datadir/spdy-draft.txt
+++ /dev/null
@@ -1,2856 +0,0 @@
-
-
-
-Network Working Group                                          M. Belshe
-Internet-Draft                                                     Twist
-Expires: August 4, 2012                                          R. Peon
-                                                             Google, Inc
-                                                                Feb 2012
-
-
-                             SPDY Protocol
-                     draft-mbelshe-httpbis-spdy-00
-
-Abstract
-
-   This document describes SPDY, a protocol designed for low-latency
-   transport of content over the World Wide Web. SPDY introduces two
-   layers of protocol.  The lower layer is a general purpose framing
-   layer which can be used atop a reliable transport (likely TCP) for
-   multiplexed, prioritized, and compressed data communication of many
-   concurrent streams.  The upper layer of the protocol provides HTTP-
-   like RFC2616 [RFC2616] semantics for compatibility with existing HTTP
-   application servers.
-
-Status of this Memo
-
-   This Internet-Draft is submitted in full conformance with the
-   provisions of BCP 78 and BCP 79.
-
-   Internet-Drafts are working documents of the Internet Engineering
-   Task Force (IETF).  Note that other groups may also distribute
-   working documents as Internet-Drafts.  The list of current Internet-
-   Drafts is at http://datatracker.ietf.org/drafts/current/.
-
-   Internet-Drafts are draft documents valid for a maximum of six months
-   and may be updated, replaced, or obsoleted by other documents at any
-   time.  It is inappropriate to use Internet-Drafts as reference
-   material or to cite them other than as "work in progress."
-
-   This Internet-Draft will expire on August 4, 2012.
-
-Copyright Notice
-
-   Copyright (c) 2012 IETF Trust and the persons identified as the
-   document authors.  All rights reserved.
-
-   This document is subject to BCP 78 and the IETF Trust's Legal
-   Provisions Relating to IETF Documents
-   (http://trustee.ietf.org/license-info) in effect on the date of
-   publication of this document.  Please review these documents
-   carefully, as they describe your rights and restrictions with respect
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 1]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   to this document.  Code Components extracted from this document must
-   include Simplified BSD License text as described in Section 4.e of
-   the Trust Legal Provisions and are provided without warranty as
-   described in the Simplified BSD License.
-
-
-Table of Contents
-
-   1.  Overview . . . . . . . . . . . . . . . . . . . . . . . . . . .  4
-     1.1.  Document Organization  . . . . . . . . . . . . . . . . . .  4
-     1.2.  Definitions  . . . . . . . . . . . . . . . . . . . . . . .  5
-   2.  SPDY Framing Layer . . . . . . . . . . . . . . . . . . . . . .  6
-     2.1.  Session (Connections)  . . . . . . . . . . . . . . . . . .  6
-     2.2.  Framing  . . . . . . . . . . . . . . . . . . . . . . . . .  6
-       2.2.1.  Control frames . . . . . . . . . . . . . . . . . . . .  6
-       2.2.2.  Data frames  . . . . . . . . . . . . . . . . . . . . .  7
-     2.3.  Streams  . . . . . . . . . . . . . . . . . . . . . . . . .  8
-       2.3.1.  Stream frames  . . . . . . . . . . . . . . . . . . . .  9
-       2.3.2.  Stream creation  . . . . . . . . . . . . . . . . . . .  9
-       2.3.3.  Stream priority  . . . . . . . . . . . . . . . . . . . 10
-       2.3.4.  Stream headers . . . . . . . . . . . . . . . . . . . . 10
-       2.3.5.  Stream data exchange . . . . . . . . . . . . . . . . . 10
-       2.3.6.  Stream half-close  . . . . . . . . . . . . . . . . . . 10
-       2.3.7.  Stream close . . . . . . . . . . . . . . . . . . . . . 11
-     2.4.  Error Handling . . . . . . . . . . . . . . . . . . . . . . 11
-       2.4.1.  Session Error Handling . . . . . . . . . . . . . . . . 11
-       2.4.2.  Stream Error Handling  . . . . . . . . . . . . . . . . 12
-     2.5.  Data flow  . . . . . . . . . . . . . . . . . . . . . . . . 12
-     2.6.  Control frame types  . . . . . . . . . . . . . . . . . . . 12
-       2.6.1.  SYN_STREAM . . . . . . . . . . . . . . . . . . . . . . 12
-       2.6.2.  SYN_REPLY  . . . . . . . . . . . . . . . . . . . . . . 14
-       2.6.3.  RST_STREAM . . . . . . . . . . . . . . . . . . . . . . 15
-       2.6.4.  SETTINGS . . . . . . . . . . . . . . . . . . . . . . . 16
-       2.6.5.  PING . . . . . . . . . . . . . . . . . . . . . . . . . 19
-       2.6.6.  GOAWAY . . . . . . . . . . . . . . . . . . . . . . . . 20
-       2.6.7.  HEADERS  . . . . . . . . . . . . . . . . . . . . . . . 21
-       2.6.8.  WINDOW_UPDATE  . . . . . . . . . . . . . . . . . . . . 22
-       2.6.9.  CREDENTIAL . . . . . . . . . . . . . . . . . . . . . . 24
-       2.6.10. Name/Value Header Block  . . . . . . . . . . . . . . . 26
-   3.  HTTP Layering over SPDY  . . . . . . . . . . . . . . . . . . . 33
-     3.1.  Connection Management  . . . . . . . . . . . . . . . . . . 33
-       3.1.1.  Use of GOAWAY  . . . . . . . . . . . . . . . . . . . . 33
-     3.2.  HTTP Request/Response  . . . . . . . . . . . . . . . . . . 34
-       3.2.1.  Request  . . . . . . . . . . . . . . . . . . . . . . . 34
-       3.2.2.  Response . . . . . . . . . . . . . . . . . . . . . . . 35
-       3.2.3.  Authentication . . . . . . . . . . . . . . . . . . . . 36
-     3.3.  Server Push Transactions . . . . . . . . . . . . . . . . . 37
-       3.3.1.  Server implementation  . . . . . . . . . . . . . . . . 38
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 2]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-       3.3.2.  Client implementation  . . . . . . . . . . . . . . . . 39
-   4.  Design Rationale and Notes . . . . . . . . . . . . . . . . . . 40
-     4.1.  Separation of Framing Layer and Application Layer  . . . . 40
-     4.2.  Error handling - Framing Layer . . . . . . . . . . . . . . 40
-     4.3.  One Connection Per Domain  . . . . . . . . . . . . . . . . 40
-     4.4.  Fixed vs Variable Length Fields  . . . . . . . . . . . . . 41
-     4.5.  Compression Context(s) . . . . . . . . . . . . . . . . . . 41
-     4.6.  Unidirectional streams . . . . . . . . . . . . . . . . . . 42
-     4.7.  Data Compression . . . . . . . . . . . . . . . . . . . . . 42
-     4.8.  Server Push  . . . . . . . . . . . . . . . . . . . . . . . 42
-   5.  Security Considerations  . . . . . . . . . . . . . . . . . . . 43
-     5.1.  Use of Same-origin constraints . . . . . . . . . . . . . . 43
-     5.2.  HTTP Headers and SPDY Headers  . . . . . . . . . . . . . . 43
-     5.3.  Cross-Protocol Attacks . . . . . . . . . . . . . . . . . . 43
-     5.4.  Server Push Implicit Headers . . . . . . . . . . . . . . . 43
-   6.  Privacy Considerations . . . . . . . . . . . . . . . . . . . . 44
-     6.1.  Long Lived Connections . . . . . . . . . . . . . . . . . . 44
-     6.2.  SETTINGS frame . . . . . . . . . . . . . . . . . . . . . . 44
-   7.  Incompatibilities with SPDY draft #2 . . . . . . . . . . . . . 45
-   8.  Requirements Notation  . . . . . . . . . . . . . . . . . . . . 46
-   9.  Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 47
-   10. Normative References . . . . . . . . . . . . . . . . . . . . . 48
-   Appendix A.  Changes . . . . . . . . . . . . . . . . . . . . . . . 50
-   Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . . 51
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 3]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-1.  Overview
-
-   One of the bottlenecks of HTTP implementations is that HTTP relies on
-   multiple connections for concurrency.  This causes several problems,
-   including additional round trips for connection setup, slow-start
-   delays, and connection rationing by the client, where it tries to
-   avoid opening too many connections to any single server.  HTTP
-   pipelining helps some, but only achieves partial multiplexing.  In
-   addition, pipelining has proven non-deployable in existing browsers
-   due to intermediary interference.
-
-   SPDY adds a framing layer for multiplexing multiple, concurrent
-   streams across a single TCP connection (or any reliable transport
-   stream).  The framing layer is optimized for HTTP-like request-
-   response streams, such that applications which run over HTTP today
-   can work over SPDY with little or no change on behalf of the web
-   application writer.
-
-   The SPDY session offers four improvements over HTTP:
-
-      Multiplexed requests: There is no limit to the number of requests
-      that can be issued concurrently over a single SPDY connection.
-
-      Prioritized requests: Clients can request certain resources to be
-      delivered first.  This avoids the problem of congesting the
-      network channel with non-critical resources when a high-priority
-      request is pending.
-
-      Compressed headers: Clients today send a significant amount of
-      redundant data in the form of HTTP headers.  Because a single web
-      page may require 50 or 100 subrequests, this data is significant.
-
-      Server pushed streams: Server Push enables content to be pushed
-      from servers to clients without a request.
-
-   SPDY attempts to preserve the existing semantics of HTTP.  All
-   features such as cookies, ETags, Vary headers, Content-Encoding
-   negotiations, etc work as they do with HTTP; SPDY only replaces the
-   way the data is written to the network.
-
-1.1.  Document Organization
-
-   The SPDY Specification is split into two parts: a framing layer
-   (Section 2), which multiplexes a TCP connection into independent,
-   length-prefixed frames, and an HTTP layer (Section 3), which
-   specifies the mechanism for overlaying HTTP request/response pairs on
-   top of the framing layer.  While some of the framing layer concepts
-   are isolated from the HTTP layer, building a generic framing layer
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 4]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   has not been a goal.  The framing layer is tailored to the needs of
-   the HTTP protocol and server push.
-
-1.2.  Definitions
-
-      client: The endpoint initiating the SPDY session.
-
-      connection: A transport-level connection between two endpoints.
-
-      endpoint: Either the client or server of a connection.
-
-      frame: A header-prefixed sequence of bytes sent over a SPDY
-      session.
-
-      server: The endpoint which did not initiate the SPDY session.
-
-      session: A synonym for a connection.
-
-      session error: An error on the SPDY session.
-
-      stream: A bi-directional flow of bytes across a virtual channel
-      within a SPDY session.
-
-      stream error: An error on an individual SPDY stream.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 5]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-2.  SPDY Framing Layer
-
-2.1.  Session (Connections)
-
-   The SPDY framing layer (or "session") runs atop a reliable transport
-   layer such as TCP [RFC0793].  The client is the TCP connection
-   initiator.  SPDY connections are persistent connections.
-
-   For best performance, it is expected that clients will not close open
-   connections until the user navigates away from all web pages
-   referencing a connection, or until the server closes the connection.
-   Servers are encouraged to leave connections open for as long as
-   possible, but can terminate idle connections if necessary.  When
-   either endpoint closes the transport-level connection, it MUST first
-   send a GOAWAY (Section 2.6.6) frame so that the endpoints can
-   reliably determine if requests finished before the close.
-
-2.2.  Framing
-
-   Once the connection is established, clients and servers exchange
-   framed messages.  There are two types of frames: control frames
-   (Section 2.2.1) and data frames (Section 2.2.2).  Frames always have
-   a common header which is 8 bytes in length.
-
-   The first bit is a control bit indicating whether a frame is a
-   control frame or data frame.  Control frames carry a version number,
-   a frame type, flags, and a length.  Data frames contain the stream
-   ID, flags, and the length for the payload carried after the common
-   header.  The simple header is designed to make reading and writing of
-   frames easy.
-
-   All integer values, including length, version, and type, are in
-   network byte order.  SPDY does not enforce alignment of types in
-   dynamically sized frames.
-
-2.2.1.  Control frames
-
-   +----------------------------------+
-   |C| Version(15bits) | Type(16bits) |
-   +----------------------------------+
-   | Flags (8)  |  Length (24 bits)   |
-   +----------------------------------+
-   |               Data               |
-   +----------------------------------+
-
-   Control bit: The 'C' bit is a single bit indicating if this is a
-   control message.  For control frames this value is always 1.
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 6]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   Version: The version number of the SPDY protocol.  This document
-   describes SPDY version 3.
-
-   Type: The type of control frame.  See Control Frames for the complete
-   list of control frames.
-
-   Flags: Flags related to this frame.  Flags for control frames and
-   data frames are different.
-
-   Length: An unsigned 24-bit value representing the number of bytes
-   after the length field.
-
-   Data: data associated with this control frame.  The format and length
-   of this data is controlled by the control frame type.
-
-   Control frame processing requirements:
-
-      Note that full length control frames (16MB) can be large for
-      implementations running on resource-limited hardware.  In such
-      cases, implementations MAY limit the maximum length frame
-      supported.  However, all implementations MUST be able to receive
-      control frames of at least 8192 octets in length.
-
-2.2.2.  Data frames
-
-   +----------------------------------+
-   |C|       Stream-ID (31bits)       |
-   +----------------------------------+
-   | Flags (8)  |  Length (24 bits)   |
-   +----------------------------------+
-   |               Data               |
-   +----------------------------------+
-
-   Control bit: For data frames this value is always 0.
-
-   Stream-ID: A 31-bit value identifying the stream.
-
-   Flags: Flags related to this frame.  Valid flags are:
-
-      0x01 = FLAG_FIN - signifies that this frame represents the last
-      frame to be transmitted on this stream.  See Stream Close
-      (Section 2.3.7) below.
-
-      0x02 = FLAG_COMPRESS - indicates that the data in this frame has
-      been compressed.
-
-   Length: An unsigned 24-bit value representing the number of bytes
-   after the length field.  The total size of a data frame is 8 bytes +
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 7]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   length.  It is valid to have a zero-length data frame.
-
-   Data: The variable-length data payload; the length was defined in the
-   length field.
-
-   Data frame processing requirements:
-
-      If an endpoint receives a data frame for a stream-id which is not
-      open and the endpoint has not sent a GOAWAY (Section 2.6.6) frame,
-      it MUST send issue a stream error (Section 2.4.2) with the error
-      code INVALID_STREAM for the stream-id.
-
-      If the endpoint which created the stream receives a data frame
-      before receiving a SYN_REPLY on that stream, it is a protocol
-      error, and the recipient MUST issue a stream error (Section 2.4.2)
-      with the status code PROTOCOL_ERROR for the stream-id.
-
-      Implementors note: If an endpoint receives multiple data frames
-      for invalid stream-ids, it MAY close the session.
-
-      All SPDY endpoints MUST accept compressed data frames.
-      Compression of data frames is always done using zlib compression.
-      Each stream initializes and uses its own compression context
-      dedicated to use within that stream.  Endpoints are encouraged to
-      use application level compression rather than SPDY stream level
-      compression.
-
-      Each SPDY stream sending compressed frames creates its own zlib
-      context for that stream, and these compression contexts MUST be
-      distinct from the compression contexts used with SYN_STREAM/
-      SYN_REPLY/HEADER compression.  (Thus, if both endpoints of a
-      stream are compressing data on the stream, there will be two zlib
-      contexts, one for sending and one for receiving).
-
-2.3.  Streams
-
-   Streams are independent sequences of bi-directional data divided into
-   frames with several properties:
-
-      Streams may be created by either the client or server.
-
-      Streams optionally carry a set of name/value header pairs.
-
-      Streams can concurrently send data interleaved with other streams.
-
-      Streams may be cancelled.
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 8]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-2.3.1.  Stream frames
-
-   SPDY defines 3 control frames to manage the lifecycle of a stream:
-
-      SYN_STREAM - Open a new stream
-
-      SYN_REPLY - Remote acknowledgement of a new, open stream
-
-      RST_STREAM - Close a stream
-
-2.3.2.  Stream creation
-
-   A stream is created by sending a control frame with the type set to
-   SYN_STREAM (Section 2.6.1).  If the server is initiating the stream,
-   the Stream-ID must be even.  If the client is initiating the stream,
-   the Stream-ID must be odd. 0 is not a valid Stream-ID.  Stream-IDs
-   from each side of the connection must increase monotonically as new
-   streams are created.  E.g.  Stream 2 may be created after stream 3,
-   but stream 7 must not be created after stream 9.  Stream IDs do not
-   wrap: when a client or server cannot create a new stream id without
-   exceeding a 31 bit value, it MUST NOT create a new stream.
-
-   The stream-id MUST increase with each new stream.  If an endpoint
-   receives a SYN_STREAM with a stream id which is less than any
-   previously received SYN_STREAM, it MUST issue a session error
-   (Section 2.4.1) with the status PROTOCOL_ERROR.
-
-   It is a protocol error to send two SYN_STREAMs with the same
-   stream-id.  If a recipient receives a second SYN_STREAM for the same
-   stream, it MUST issue a stream error (Section 2.4.2) with the status
-   code PROTOCOL_ERROR.
-
-   Upon receipt of a SYN_STREAM, the recipient can reject the stream by
-   sending a stream error (Section 2.4.2) with the error code
-   REFUSED_STREAM.  Note, however, that the creating endpoint may have
-   already sent additional frames for that stream which cannot be
-   immediately stopped.
-
-   Once the stream is created, the creator may immediately send HEADERS
-   or DATA frames for that stream, without needing to wait for the
-   recipient to acknowledge.
-
-2.3.2.1.  Unidirectional streams
-
-   When an endpoint creates a stream with the FLAG_UNIDIRECTIONAL flag
-   set, it creates a unidirectional stream which the creating endpoint
-   can use to send frames, but the receiving endpoint cannot.  The
-   receiving endpoint is implicitly already in the half-closed
-
-
-
-Belshe & Peon            Expires August 4, 2012                 [Page 9]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   (Section 2.3.6) state.
-
-2.3.2.2.  Bidirectional streams
-
-   SYN_STREAM frames which do not use the FLAG_UNIDIRECTIONAL flag are
-   bidirectional streams.  Both endpoints can send data on a bi-
-   directional stream.
-
-2.3.3.  Stream priority
-
-   The creator of a stream assigns a priority for that stream.  Priority
-   is represented as an integer from 0 to 7. 0 represents the highest
-   priority and 7 represents the lowest priority.
-
-   The sender and recipient SHOULD use best-effort to process streams in
-   the order of highest priority to lowest priority.
-
-2.3.4.  Stream headers
-
-   Streams carry optional sets of name/value pair headers which carry
-   metadata about the stream.  After the stream has been created, and as
-   long as the sender is not closed (Section 2.3.7) or half-closed
-   (Section 2.3.6), each side may send HEADERS frame(s) containing the
-   header data.  Header data can be sent in multiple HEADERS frames, and
-   HEADERS frames may be interleaved with data frames.
-
-2.3.5.  Stream data exchange
-
-   Once a stream is created, it can be used to send arbitrary amounts of
-   data.  Generally this means that a series of data frames will be sent
-   on the stream until a frame containing the FLAG_FIN flag is set.  The
-   FLAG_FIN can be set on a SYN_STREAM (Section 2.6.1), SYN_REPLY
-   (Section 2.6.2), HEADERS (Section 2.6.7) or a DATA (Section 2.2.2)
-   frame.  Once the FLAG_FIN has been sent, the stream is considered to
-   be half-closed.
-
-2.3.6.  Stream half-close
-
-   When one side of the stream sends a frame with the FLAG_FIN flag set,
-   the stream is half-closed from that endpoint.  The sender of the
-   FLAG_FIN MUST NOT send further frames on that stream.  When both
-   sides have half-closed, the stream is closed.
-
-   If an endpoint receives a data frame after the stream is half-closed
-   from the sender (e.g. the endpoint has already received a prior frame
-   for the stream with the FIN flag set), it MUST send a RST_STREAM to
-   the sender with the status STREAM_ALREADY_CLOSED.
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 10]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-2.3.7.  Stream close
-
-   There are 3 ways that streams can be terminated:
-
-      Normal termination: Normal stream termination occurs when both
-      sender and recipient have half-closed the stream by sending a
-      FLAG_FIN.
-
-      Abrupt termination: Either the client or server can send a
-      RST_STREAM control frame at any time.  A RST_STREAM contains an
-      error code to indicate the reason for failure.  When a RST_STREAM
-      is sent from the stream originator, it indicates a failure to
-      complete the stream and that no further data will be sent on the
-      stream.  When a RST_STREAM is sent from the stream recipient, the
-      sender, upon receipt, should stop sending any data on the stream.
-      The stream recipient should be aware that there is a race between
-      data already in transit from the sender and the time the
-      RST_STREAM is received.  See Stream Error Handling (Section 2.4.2)
-
-      TCP connection teardown: If the TCP connection is torn down while
-      un-closed streams exist, then the endpoint must assume that the
-      stream was abnormally interrupted and may be incomplete.
-
-   If an endpoint receives a data frame after the stream is closed, it
-   must send a RST_STREAM to the sender with the status PROTOCOL_ERROR.
-
-2.4.  Error Handling
-
-   The SPDY framing layer has only two types of errors, and they are
-   always handled consistently.  Any reference in this specification to
-   "issue a session error" refers to Section 2.4.1.  Any reference to
-   "issue a stream error" refers to Section 2.4.2.
-
-2.4.1.  Session Error Handling
-
-   A session error is any error which prevents further processing of the
-   framing layer or which corrupts the session compression state.  When
-   a session error occurs, the endpoint encountering the error MUST
-   first send a GOAWAY (Section 2.6.6) frame with the stream id of most
-   recently received stream from the remote endpoint, and the error code
-   for why the session is terminating.  After sending the GOAWAY frame,
-   the endpoint MUST close the TCP connection.
-
-   Note that the session compression state is dependent upon both
-   endpoints always processing all compressed data.  If an endpoint
-   partially processes a frame containing compressed data without
-   updating compression state properly, future control frames which use
-   compression will be always be errored.  Implementations SHOULD always
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 11]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   try to process compressed data so that errors which could be handled
-   as stream errors do not become session errors.
-
-   Note that because this GOAWAY is sent during a session error case, it
-   is possible that the GOAWAY will not be reliably received by the
-   receiving endpoint.  It is a best-effort attempt to communicate with
-   the remote about why the session is going down.
-
-2.4.2.  Stream Error Handling
-
-   A stream error is an error related to a specific stream-id which does
-   not affect processing of other streams at the framing layer.  Upon a
-   stream error, the endpoint MUST send a RST_STREAM (Section 2.6.3)
-   frame which contains the stream id of the stream where the error
-   occurred and the error status which caused the error.  After sending
-   the RST_STREAM, the stream is closed to the sending endpoint.  After
-   sending the RST_STREAM, if the sender receives any frames other than
-   a RST_STREAM for that stream id, it will result in sending additional
-   RST_STREAM frames.  An endpoint MUST NOT send a RST_STREAM in
-   response to an RST_STREAM, as doing so would lead to RST_STREAM
-   loops.  Sending a RST_STREAM does not cause the SPDY session to be
-   closed.
-
-   If an endpoint has multiple RST_STREAM frames to send in succession
-   for the same stream-id and the same error code, it MAY coalesce them
-   into a single RST_STREAM frame.  (This can happen if a stream is
-   closed, but the remote sends multiple data frames.  There is no
-   reason to send a RST_STREAM for each frame in succession).
-
-2.5.  Data flow
-
-   Because TCP provides a single stream of data on which SPDY
-   multiplexes multiple logical streams, clients and servers must
-   intelligently interleave data messages for concurrent sessions.
-
-2.6.  Control frame types
-
-2.6.1.  SYN_STREAM
-
-   The SYN_STREAM control frame allows the sender to asynchronously
-   create a stream between the endpoints.  See Stream Creation
-   (Section 2.3.2)
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 12]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-+------------------------------------+
-|1|    version    |         1        |
-+------------------------------------+
-|  Flags (8)  |  Length (24 bits)    |
-+------------------------------------+
-|X|           Stream-ID (31bits)     |
-+------------------------------------+
-|X| Associated-To-Stream-ID (31bits) |
-+------------------------------------+
-| Pri|Unused | Slot |                |
-+-------------------+                |
-| Number of Name/Value pairs (int32) |   <+
-+------------------------------------+    |
-|     Length of name (int32)         |    | This section is the "Name/Value
-+------------------------------------+    | Header Block", and is compressed.
-|           Name (string)            |    |
-+------------------------------------+    |
-|     Length of value  (int32)       |    |
-+------------------------------------+    |
-|          Value   (string)          |    |
-+------------------------------------+    |
-|           (repeats)                |   <+
-
-   Flags: Flags related to this frame.  Valid flags are:
-
-      0x01 = FLAG_FIN - marks this frame as the last frame to be
-      transmitted on this stream and puts the sender in the half-closed
-      (Section 2.3.6) state.
-
-      0x02 = FLAG_UNIDIRECTIONAL - a stream created with this flag puts
-      the recipient in the half-closed (Section 2.3.6) state.
-
-   Length: The length is the number of bytes which follow the length
-   field in the frame.  For SYN_STREAM frames, this is 10 bytes plus the
-   length of the compressed Name/Value block.
-
-   Stream-ID: The 31-bit identifier for this stream.  This stream-id
-   will be used in frames which are part of this stream.
-
-   Associated-To-Stream-ID: The 31-bit identifier for a stream which
-   this stream is associated to.  If this stream is independent of all
-   other streams, it should be 0.
-
-   Priority: A 3-bit priority (Section 2.3.3) field.
-
-   Unused: 5 bits of unused space, reserved for future use.
-
-   Slot: An 8 bit unsigned integer specifying the index in the server's
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 13]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   CREDENTIAL vector of the client certificate to be used for this
-   request. see CREDENTIAL frame (Section 2.6.9).  The value 0 means no
-   client certificate should be associated with this stream.
-
-   Name/Value Header Block: A set of name/value pairs carried as part of
-   the SYN_STREAM. see Name/Value Header Block (Section 2.6.10).
-
-   If an endpoint receives a SYN_STREAM which is larger than the
-   implementation supports, it MAY send a RST_STREAM with error code
-   FRAME_TOO_LARGE.  All implementations MUST support the minimum size
-   limits defined in the Control Frames section (Section 2.2.1).
-
-2.6.2.  SYN_REPLY
-
-   SYN_REPLY indicates the acceptance of a stream creation by the
-   recipient of a SYN_STREAM frame.
-
-+------------------------------------+
-|1|    version    |         2        |
-+------------------------------------+
-|  Flags (8)  |  Length (24 bits)    |
-+------------------------------------+
-|X|           Stream-ID (31bits)     |
-+------------------------------------+
-| Number of Name/Value pairs (int32) |   <+
-+------------------------------------+    |
-|     Length of name (int32)         |    | This section is the "Name/Value
-+------------------------------------+    | Header Block", and is compressed.
-|           Name (string)            |    |
-+------------------------------------+    |
-|     Length of value  (int32)       |    |
-+------------------------------------+    |
-|          Value   (string)          |    |
-+------------------------------------+    |
-|           (repeats)                |   <+
-
-   Flags: Flags related to this frame.  Valid flags are:
-
-      0x01 = FLAG_FIN - marks this frame as the last frame to be
-      transmitted on this stream and puts the sender in the half-closed
-      (Section 2.3.6) state.
-
-   Length: The length is the number of bytes which follow the length
-   field in the frame.  For SYN_REPLY frames, this is 4 bytes plus the
-   length of the compressed Name/Value block.
-
-   Stream-ID: The 31-bit identifier for this stream.
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 14]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   If an endpoint receives multiple SYN_REPLY frames for the same active
-   stream ID, it MUST issue a stream error (Section 2.4.2) with the
-   error code STREAM_IN_USE.
-
-   Name/Value Header Block: A set of name/value pairs carried as part of
-   the SYN_STREAM. see Name/Value Header Block (Section 2.6.10).
-
-   If an endpoint receives a SYN_REPLY which is larger than the
-   implementation supports, it MAY send a RST_STREAM with error code
-   FRAME_TOO_LARGE.  All implementations MUST support the minimum size
-   limits defined in the Control Frames section (Section 2.2.1).
-
-2.6.3.  RST_STREAM
-
-   The RST_STREAM frame allows for abnormal termination of a stream.
-   When sent by the creator of a stream, it indicates the creator wishes
-   to cancel the stream.  When sent by the recipient of a stream, it
-   indicates an error or that the recipient did not want to accept the
-   stream, so the stream should be closed.
-
-   +----------------------------------+
-   |1|   version    |         3       |
-   +----------------------------------+
-   | Flags (8)  |         8           |
-   +----------------------------------+
-   |X|          Stream-ID (31bits)    |
-   +----------------------------------+
-   |          Status code             |
-   +----------------------------------+
-
-   Flags: Flags related to this frame.  RST_STREAM does not define any
-   flags.  This value must be 0.
-
-   Length: An unsigned 24-bit value representing the number of bytes
-   after the length field.  For RST_STREAM control frames, this value is
-   always 8.
-
-   Stream-ID: The 31-bit identifier for this stream.
-
-   Status code: (32 bits) An indicator for why the stream is being
-   terminated.The following status codes are defined:
-
-      1 - PROTOCOL_ERROR.  This is a generic error, and should only be
-      used if a more specific error is not available.
-
-      2 - INVALID_STREAM.  This is returned when a frame is received for
-      a stream which is not active.
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 15]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-      3 - REFUSED_STREAM.  Indicates that the stream was refused before
-      any processing has been done on the stream.
-
-      4 - UNSUPPORTED_VERSION.  Indicates that the recipient of a stream
-      does not support the SPDY version requested.
-
-      5 - CANCEL.  Used by the creator of a stream to indicate that the
-      stream is no longer needed.
-
-      6 - INTERNAL_ERROR.  This is a generic error which can be used
-      when the implementation has internally failed, not due to anything
-      in the protocol.
-
-      7 - FLOW_CONTROL_ERROR.  The endpoint detected that its peer
-      violated the flow control protocol.
-
-      8 - STREAM_IN_USE.  The endpoint received a SYN_REPLY for a stream
-      already open.
-
-      9 - STREAM_ALREADY_CLOSED.  The endpoint received a data or
-      SYN_REPLY frame for a stream which is half closed.
-
-      10 - INVALID_CREDENTIALS.  The server received a request for a
-      resource whose origin does not have valid credentials in the
-      client certificate vector.
-
-      11 - FRAME_TOO_LARGE.  The endpoint received a frame which this
-      implementation could not support.  If FRAME_TOO_LARGE is sent for
-      a SYN_STREAM, HEADERS, or SYN_REPLY frame without fully processing
-      the compressed portion of those frames, then the compression state
-      will be out-of-sync with the other endpoint.  In this case,
-      senders of FRAME_TOO_LARGE MUST close the session.
-
-      Note: 0 is not a valid status code for a RST_STREAM.
-
-   After receiving a RST_STREAM on a stream, the recipient must not send
-   additional frames for that stream, and the stream moves into the
-   closed state.
-
-2.6.4.  SETTINGS
-
-   A SETTINGS frame contains a set of id/value pairs for communicating
-   configuration data about how the two endpoints may communicate.
-   SETTINGS frames can be sent at any time by either endpoint, are
-   optionally sent, and are fully asynchronous.  When the server is the
-   sender, the sender can request that configuration data be persisted
-   by the client across SPDY sessions and returned to the server in
-   future communications.
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 16]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   Persistence of SETTINGS ID/Value pairs is done on a per origin/IP
-   pair (the "origin" is the set of scheme, host, and port from the URI.
-   See [RFC6454]).  That is, when a client connects to a server, and the
-   server persists settings within the client, the client SHOULD return
-   the persisted settings on future connections to the same origin AND
-   IP address and TCP port.  Clients MUST NOT request servers to use the
-   persistence features of the SETTINGS frames, and servers MUST ignore
-   persistence related flags sent by a client.
-
-   +----------------------------------+
-   |1|   version    |         4       |
-   +----------------------------------+
-   | Flags (8)  |  Length (24 bits)   |
-   +----------------------------------+
-   |         Number of entries        |
-   +----------------------------------+
-   |          ID/Value Pairs          |
-   |             ...                  |
-
-   Control bit: The control bit is always 1 for this message.
-
-   Version: The SPDY version number.
-
-   Type: The message type for a SETTINGS message is 4.
-
-   Flags: FLAG_SETTINGS_CLEAR_SETTINGS (0x1): When set, the client
-   should clear any previously persisted SETTINGS ID/Value pairs.  If
-   this frame contains ID/Value pairs with the
-   FLAG_SETTINGS_PERSIST_VALUE set, then the client will first clear its
-   existing, persisted settings, and then persist the values with the
-   flag set which are contained within this frame.  Because persistence
-   is only implemented on the client, this flag can only be used when
-   the sender is the server.
-
-   Length: An unsigned 24-bit value representing the number of bytes
-   after the length field.  The total size of a SETTINGS frame is 8
-   bytes + length.
-
-   Number of entries: A 32-bit value representing the number of ID/value
-   pairs in this message.
-
-   ID: A 32-bit ID number, comprised of 8 bits of flags and 24 bits of
-   unique ID.
-
-      ID.flags:
-
-         FLAG_SETTINGS_PERSIST_VALUE (0x1): When set, the sender of this
-         SETTINGS frame is requesting that the recipient persist the ID/
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 17]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-         Value and return it in future SETTINGS frames sent from the
-         sender to this recipient.  Because persistence is only
-         implemented on the client, this flag is only sent by the
-         server.
-
-         FLAG_SETTINGS_PERSISTED (0x2): When set, the sender is
-         notifying the recipient that this ID/Value pair was previously
-         sent to the sender by the recipient with the
-         FLAG_SETTINGS_PERSIST_VALUE, and the sender is returning it.
-         Because persistence is only implemented on the client, this
-         flag is only sent by the client.
-
-      Defined IDs:
-
-         1 - SETTINGS_UPLOAD_BANDWIDTH allows the sender to send its
-         expected upload bandwidth on this channel.  This number is an
-         estimate.  The value should be the integral number of kilobytes
-         per second that the sender predicts as an expected maximum
-         upload channel capacity.
-
-         2 - SETTINGS_DOWNLOAD_BANDWIDTH allows the sender to send its
-         expected download bandwidth on this channel.  This number is an
-         estimate.  The value should be the integral number of kilobytes
-         per second that the sender predicts as an expected maximum
-         download channel capacity.
-
-         3 - SETTINGS_ROUND_TRIP_TIME allows the sender to send its
-         expected round-trip-time on this channel.  The round trip time
-         is defined as the minimum amount of time to send a control
-         frame from this client to the remote and receive a response.
-         The value is represented in milliseconds.
-
-         4 - SETTINGS_MAX_CONCURRENT_STREAMS allows the sender to inform
-         the remote endpoint the maximum number of concurrent streams
-         which it will allow.  By default there is no limit.  For
-         implementors it is recommended that this value be no smaller
-         than 100.
-
-         5 - SETTINGS_CURRENT_CWND allows the sender to inform the
-         remote endpoint of the current TCP CWND value.
-
-         6 - SETTINGS_DOWNLOAD_RETRANS_RATE allows the sender to inform
-         the remote endpoint the retransmission rate (bytes
-         retransmitted / total bytes transmitted).
-
-         7 - SETTINGS_INITIAL_WINDOW_SIZE allows the sender to inform
-         the remote endpoint the initial window size (in bytes) for new
-         streams.
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 18]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-         8 - SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE allows the server
-         to inform the client if the new size of the client certificate
-         vector.
-
-   Value: A 32-bit value.
-
-   The message is intentionally extensible for future information which
-   may improve client-server communications.  The sender does not need
-   to send every type of ID/value.  It must only send those for which it
-   has accurate values to convey.  When multiple ID/value pairs are
-   sent, they should be sent in order of lowest id to highest id.  A
-   single SETTINGS frame MUST not contain multiple values for the same
-   ID.  If the recipient of a SETTINGS frame discovers multiple values
-   for the same ID, it MUST ignore all values except the first one.
-
-   A server may send multiple SETTINGS frames containing different ID/
-   Value pairs.  When the same ID/Value is sent twice, the most recent
-   value overrides any previously sent values.  If the server sends IDs
-   1, 2, and 3 with the FLAG_SETTINGS_PERSIST_VALUE in a first SETTINGS
-   frame, and then sends IDs 4 and 5 with the
-   FLAG_SETTINGS_PERSIST_VALUE, when the client returns the persisted
-   state on its next SETTINGS frame, it SHOULD send all 5 settings (1,
-   2, 3, 4, and 5 in this example) to the server.
-
-2.6.5.  PING
-
-   The PING control frame is a mechanism for measuring a minimal round-
-   trip time from the sender.  It can be sent from the client or the
-   server.  Recipients of a PING frame should send an identical frame to
-   the sender as soon as possible (if there is other pending data
-   waiting to be sent, PING should take highest priority).  Each ping
-   sent by a sender should use a unique ID.
-
-   +----------------------------------+
-   |1|   version    |         6       |
-   +----------------------------------+
-   | 0 (flags) |     4 (length)       |
-   +----------------------------------|
-   |            32-bit ID             |
-   +----------------------------------+
-
-   Control bit: The control bit is always 1 for this message.
-
-   Version: The SPDY version number.
-
-   Type: The message type for a PING message is 6.
-
-   Length: This frame is always 4 bytes long.
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 19]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   ID: A unique ID for this ping, represented as an unsigned 32 bit
-   value.  When the client initiates a ping, it must use an odd numbered
-   ID.  When the server initiates a ping, it must use an even numbered
-   ping.  Use of odd/even IDs is required in order to avoid accidental
-   looping on PINGs (where each side initiates an identical PING at the
-   same time).
-
-   Note: If a sender uses all possible PING ids (e.g. has sent all 2^31
-   possible IDs), it can wrap and start re-using IDs.
-
-   If a server receives an even numbered PING which it did not initiate,
-   it must ignore the PING.  If a client receives an odd numbered PING
-   which it did not initiate, it must ignore the PING.
-
-2.6.6.  GOAWAY
-
-   The GOAWAY control frame is a mechanism to tell the remote side of
-   the connection to stop creating streams on this session.  It can be
-   sent from the client or the server.  Once sent, the sender will not
-   respond to any new SYN_STREAMs on this session.  Recipients of a
-   GOAWAY frame must not send additional streams on this session,
-   although a new session can be established for new streams.  The
-   purpose of this message is to allow an endpoint to gracefully stop
-   accepting new streams (perhaps for a reboot or maintenance), while
-   still finishing processing of previously established streams.
-
-   There is an inherent race condition between an endpoint sending
-   SYN_STREAMs and the remote sending a GOAWAY message.  To deal with
-   this case, the GOAWAY contains a last-stream-id indicating the
-   stream-id of the last stream which was created on the sending
-   endpoint in this session.  If the receiver of the GOAWAY sent new
-   SYN_STREAMs for sessions after this last-stream-id, they were not
-   processed by the server and the receiver may treat the stream as
-   though it had never been created at all (hence the receiver may want
-   to re-create the stream later on a new session).
-
-   Endpoints should always send a GOAWAY message before closing a
-   connection so that the remote can know whether a stream has been
-   partially processed or not.  (For example, if an HTTP client sends a
-   POST at the same time that a server closes a connection, the client
-   cannot know if the server started to process that POST request if the
-   server does not send a GOAWAY frame to indicate where it stopped
-   working).
-
-   After sending a GOAWAY message, the sender must ignore all SYN_STREAM
-   frames for new streams.
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 20]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   +----------------------------------+
-   |1|   version    |         7       |
-   +----------------------------------+
-   | 0 (flags) |     8 (length)       |
-   +----------------------------------|
-   |X|  Last-good-stream-ID (31 bits) |
-   +----------------------------------+
-   |          Status code             |
-   +----------------------------------+
-
-   Control bit: The control bit is always 1 for this message.
-
-   Version: The SPDY version number.
-
-   Type: The message type for a GOAWAY message is 7.
-
-   Length: This frame is always 8 bytes long.
-
-   Last-good-stream-Id: The last stream id which was replied to (with
-   either a SYN_REPLY or RST_STREAM) by the sender of the GOAWAY
-   message.  If no streams were replied to, this value MUST be 0.
-
-   Status: The reason for closing the session.
-
-      0 - OK.  This is a normal session teardown.
-
-      1 - PROTOCOL_ERROR.  This is a generic error, and should only be
-      used if a more specific error is not available.
-
-      11 - INTERNAL_ERROR.  This is a generic error which can be used
-      when the implementation has internally failed, not due to anything
-      in the protocol.
-
-2.6.7.  HEADERS
-
-   The HEADERS frame augments a stream with additional headers.  It may
-   be optionally sent on an existing stream at any time.  Specific
-   application of the headers in this frame is application-dependent.
-   The name/value header block within this frame is compressed.
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 21]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-+------------------------------------+
-|1|   version     |          8       |
-+------------------------------------+
-| Flags (8)  |   Length (24 bits)    |
-+------------------------------------+
-|X|          Stream-ID (31bits)      |
-+------------------------------------+
-| Number of Name/Value pairs (int32) |   <+
-+------------------------------------+    |
-|     Length of name (int32)         |    | This section is the "Name/Value
-+------------------------------------+    | Header Block", and is compressed.
-|           Name (string)            |    |
-+------------------------------------+    |
-|     Length of value  (int32)       |    |
-+------------------------------------+    |
-|          Value   (string)          |    |
-+------------------------------------+    |
-|           (repeats)                |   <+
-
-   Flags: Flags related to this frame.  Valid flags are:
-
-      0x01 = FLAG_FIN - marks this frame as the last frame to be
-      transmitted on this stream and puts the sender in the half-closed
-      (Section 2.3.6) state.
-
-   Length: An unsigned 24 bit value representing the number of bytes
-   after the length field.  The minimum length of the length field is 4
-   (when the number of name value pairs is 0).
-
-   Stream-ID: The stream this HEADERS block is associated with.
-
-   Name/Value Header Block: A set of name/value pairs carried as part of
-   the SYN_STREAM. see Name/Value Header Block (Section 2.6.10).
-
-2.6.8.  WINDOW_UPDATE
-
-   The WINDOW_UPDATE control frame is used to implement per stream flow
-   control in SPDY.  Flow control in SPDY is per hop, that is, only
-   between the two endpoints of a SPDY connection.  If there are one or
-   more intermediaries between the client and the origin server, flow
-   control signals are not explicitly forwarded by the intermediaries.
-   (However, throttling of data transfer by any recipient may have the
-   effect of indirectly propagating flow control information upstream
-   back to the original sender.)  Flow control only applies to the data
-   portion of data frames.  Recipients must buffer all control frames.
-   If a recipient fails to buffer an entire control frame, it MUST issue
-   a stream error (Section 2.4.2) with the status code
-   FLOW_CONTROL_ERROR for the stream.
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 22]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   Flow control in SPDY is implemented by a data transfer window kept by
-   the sender of each stream.  The data transfer window is a simple
-   uint32 that indicates how many bytes of data the sender can transmit.
-   After a stream is created, but before any data frames have been
-   transmitted, the sender begins with the initial window size.  This
-   window size is a measure of the buffering capability of the
-   recipient.  The sender must not send a data frame with data length
-   greater than the transfer window size.  After sending each data
-   frame, the sender decrements its transfer window size by the amount
-   of data transmitted.  When the window size becomes less than or equal
-   to 0, the sender must pause transmitting data frames.  At the other
-   end of the stream, the recipient sends a WINDOW_UPDATE control back
-   to notify the sender that it has consumed some data and freed up
-   buffer space to receive more data.
-
-   +----------------------------------+
-   |1|   version    |         9       |
-   +----------------------------------+
-   | 0 (flags) |     8 (length)       |
-   +----------------------------------+
-   |X|     Stream-ID (31-bits)        |
-   +----------------------------------+
-   |X|  Delta-Window-Size (31-bits)   |
-   +----------------------------------+
-
-   Control bit: The control bit is always 1 for this message.
-
-   Version: The SPDY version number.
-
-   Type: The message type for a WINDOW_UPDATE message is 9.
-
-   Length: The length field is always 8 for this frame (there are 8
-   bytes after the length field).
-
-   Stream-ID: The stream ID that this WINDOW_UPDATE control frame is
-   for.
-
-   Delta-Window-Size: The additional number of bytes that the sender can
-   transmit in addition to existing remaining window size.  The legal
-   range for this field is 1 to 2^31 - 1 (0x7fffffff) bytes.
-
-   The window size as kept by the sender must never exceed 2^31
-   (although it can become negative in one special case).  If a sender
-   receives a WINDOW_UPDATE that causes the its window size to exceed
-   this limit, it must send RST_STREAM with status code
-   FLOW_CONTROL_ERROR to terminate the stream.
-
-   When a SPDY connection is first established, the default initial
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 23]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   window size for all streams is 64KB.  An endpoint can use the
-   SETTINGS control frame to adjust the initial window size for the
-   connection.  That is, its peer can start out using the 64KB default
-   initial window size when sending data frames before receiving the
-   SETTINGS.  Because SETTINGS is asynchronous, there may be a race
-   condition if the recipient wants to decrease the initial window size,
-   but its peer immediately sends 64KB on the creation of a new
-   connection, before waiting for the SETTINGS to arrive.  This is one
-   case where the window size kept by the sender will become negative.
-   Once the sender detects this condition, it must stop sending data
-   frames and wait for the recipient to catch up.  The recipient has two
-   choices:
-
-      immediately send RST_STREAM with FLOW_CONTROL_ERROR status code.
-
-      allow the head of line blocking (as there is only one stream for
-      the session and the amount of data in flight is bounded by the
-      default initial window size), and send WINDOW_UPDATE as it
-      consumes data.
-
-   In the case of option 2, both sides must compute the window size
-   based on the initial window size in the SETTINGS.  For example, if
-   the recipient sets the initial window size to be 16KB, and the sender
-   sends 64KB immediately on connection establishment, the sender will
-   discover its window size is -48KB on receipt of the SETTINGS.  As the
-   recipient consumes the first 16KB, it must send a WINDOW_UPDATE of
-   16KB back to the sender.  This interaction continues until the
-   sender's window size becomes positive again, and it can resume
-   transmitting data frames.
-
-   After the recipient reads in a data frame with FLAG_FIN that marks
-   the end of the data stream, it should not send WINDOW_UPDATE frames
-   as it consumes the last data frame.  A sender should ignore all the
-   WINDOW_UPDATE frames associated with the stream after it send the
-   last frame for the stream.
-
-   The data frames from the sender and the WINDOW_UPDATE frames from the
-   recipient are completely asynchronous with respect to each other.
-   This property allows a recipient to aggressively update the window
-   size kept by the sender to prevent the stream from stalling.
-
-2.6.9.  CREDENTIAL
-
-   The CREDENTIAL control frame is used by the client to send additional
-   client certificates to the server.  A SPDY client may decide to send
-   requests for resources from different origins on the same SPDY
-   session if it decides that that server handles both origins.  For
-   example if the IP address associated with both hostnames matches and
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 24]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   the SSL server certificate presented in the initial handshake is
-   valid for both hostnames.  However, because the SSL connection can
-   contain at most one client certificate, the client needs a mechanism
-   to send additional client certificates to the server.
-
-   The server is required to maintain a vector of client certificates
-   associated with a SPDY session.  When the client needs to send a
-   client certificate to the server, it will send a CREDENTIAL frame
-   that specifies the index of the slot in which to store the
-   certificate as well as proof that the client posesses the
-   corresponding private key.  The initial size of this vector must be
-   8.  If the client provides a client certificate during the first TLS
-   handshake, the contents of this certificate must be copied into the
-   first slot (index 1) in the CREDENTIAL vector, though it may be
-   overwritten by subsequent CREDENTIAL frames.  The server must
-   exclusively use the CREDNETIAL vector when evaluating the client
-   certificates associated with an origin.  The server may change the
-   size of this vector by sending a SETTINGS frame with the setting
-   SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE value specified.  In the
-   event that the new size is smaller than the current size, truncation
-   occurs preserving lower-index slots as possible.
-
-   TLS renegotiation with client authentication is incompatible with
-   SPDY given the multiplexed nature of SPDY.  Specifically, imagine
-   that the client has 2 requests outstanding to the server for two
-   different pages (in different tabs).  When the renegotiation + client
-   certificate request comes in, the browser is unable to determine
-   which resource triggered the client certificate request, in order to
-   prompt the user accordingly.
-
-   +----------------------------------+
-   |1|000000000000001|0000000000001011|
-   +----------------------------------+
-   | flags (8)  |  Length (24 bits)   |
-   +----------------------------------+
-   |  Slot (16 bits) |                |
-   +-----------------+                |
-   |      Proof Length (32 bits)      |
-   +----------------------------------+
-   |               Proof              |
-   +----------------------------------+ <+
-   |   Certificate Length (32 bits)   |  |
-   +----------------------------------+  | Repeated until end of frame
-   |            Certificate           |  |
-   +----------------------------------+ <+
-
-   Slot: The index in the server's client certificate vector where this
-   certificate should be stored.  If there is already a certificate
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 25]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   stored at this index, it will be overwritten.  The index is one
-   based, not zero based; zero is an invalid slot index.
-
-   Proof: Cryptographic proof that the client has possession of the
-   private key associated with the certificate.  The format is a TLS
-   digitally-signed element
-   (http://tools.ietf.org/html/rfc5246#section-4.7).  The signature
-   algorithm must be the same as that used in the CertificateVerify
-   message.  However, since the MD5+SHA1 signature type used in TLS 1.0
-   connections can not be correctly encoded in a digitally-signed
-   element, SHA1 must be used when MD5+SHA1 was used in the SSL
-   connection.  The signature is calculated over a 32 byte TLS extractor
-   value (http://tools.ietf.org/html/rfc5705) with a label of "EXPORTER
-   SPDY certificate proof" using the empty string as context.  ForRSA
-   certificates the signature would be a PKCS#1 v1.5 signature.  For
-   ECDSA, it would be an ECDSA-Sig-Value
-   (http://tools.ietf.org/html/rfc5480#appendix-A).  For a 1024-bit RSA
-   key, the CREDENTIAL message would be ~500 bytes.
-
-   Certificate: The certificate chain, starting with the leaf
-   certificate.  Each certificate must be encoded as a 32 bit length,
-   followed by a DER encoded certificate.  The certificate must be of
-   the same type (RSA, ECDSA, etc) as the client certificate associated
-   with the SSL connection.
-
-   If the server receives a request for a resource with unacceptable
-   credential (either missing or invalid), it must reply with a
-   RST_STREAM frame with the status code INVALID_CREDENTIALS.  Upon
-   receipt of a RST_STREAM frame with INVALID_CREDENTIALS, the client
-   should initiate a new stream directly to the requested origin and
-   resend the request.  Note, SPDY does not allow the server to request
-   different client authentication for different resources in the same
-   origin.
-
-   If the server receives an invalid CREDENTIAL frame, it MUST respond
-   with a GOAWAY frame and shutdown the session.
-
-2.6.10.  Name/Value Header Block
-
-   The Name/Value Header Block is found in the SYN_STREAM, SYN_REPLY and
-   HEADERS control frames, and shares a common format:
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 26]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   +------------------------------------+
-   | Number of Name/Value pairs (int32) |
-   +------------------------------------+
-   |     Length of name (int32)         |
-   +------------------------------------+
-   |           Name (string)            |
-   +------------------------------------+
-   |     Length of value  (int32)       |
-   +------------------------------------+
-   |          Value   (string)          |
-   +------------------------------------+
-   |           (repeats)                |
-
-   Number of Name/Value pairs: The number of repeating name/value pairs
-   following this field.
-
-   List of Name/Value pairs:
-
-      Length of Name: a 32-bit value containing the number of octets in
-      the name field.  Note that in practice, this length must not
-      exceed 2^24, as that is the maximum size of a SPDY frame.
-
-      Name: 0 or more octets, 8-bit sequences of data, excluding 0.
-
-      Length of Value: a 32-bit value containing the number of octets in
-      the value field.  Note that in practice, this length must not
-      exceed 2^24, as that is the maximum size of a SPDY frame.
-
-      Value: 0 or more octets, 8-bit sequences of data, excluding 0.
-
-   Each header name must have at least one value.  Header names are
-   encoded using the US-ASCII character set [ASCII] and must be all
-   lower case.  The length of each name must be greater than zero.  A
-   recipient of a zero-length name MUST issue a stream error
-   (Section 2.4.2) with the status code PROTOCOL_ERROR for the
-   stream-id.
-
-   Duplicate header names are not allowed.  To send two identically
-   named headers, send a header with two values, where the values are
-   separated by a single NUL (0) byte.  A header value can either be
-   empty (e.g. the length is zero) or it can contain multiple, NUL-
-   separated values, each with length greater than zero.  The value
-   never starts nor ends with a NUL character.  Recipients of illegal
-   value fields MUST issue a stream error (Section 2.4.2) with the
-   status code PROTOCOL_ERROR for the stream-id.
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 27]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-2.6.10.1.  Compression
-
-   The Name/Value Header Block is a section of the SYN_STREAM,
-   SYN_REPLY, and HEADERS frames used to carry header meta-data.  This
-   block is always compressed using zlib compression.  Within this
-   specification, any reference to 'zlib' is referring to the ZLIB
-   Compressed Data Format Specification Version 3.3 as part of RFC1950.
-   [RFC1950]
-
-   For each HEADERS compression instance, the initial state is
-   initialized using the following dictionary [UDELCOMPRESSION]:
-
-   const unsigned char SPDY_dictionary_txt[] = {
-           0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69,   \\ - - - - o p t i
-           0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68,   \\ o n s - - - - h
-           0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70,   \\ e a d - - - - p
-           0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70,   \\ o s t - - - - p
-           0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65,   \\ u t - - - - d e
-           0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05,   \\ l e t e - - - -
-           0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00,   \\ t r a c e - - -
-           0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00,   \\ - a c c e p t -
-           0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70,   \\ - - - a c c e p
-           0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65,   \\ t - c h a r s e
-           0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63,   \\ t - - - - a c c
-           0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f,   \\ e p t - e n c o
-           0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f,   \\ d i n g - - - -
-           0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c,   \\ a c c e p t - l
-           0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00,   \\ a n g u a g e -
-           0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70,   \\ - - - a c c e p
-           0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73,   \\ t - r a n g e s
-           0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00,   \\ - - - - a g e -
-           0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77,   \\ - - - a l l o w
-           0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68,   \\ - - - - a u t h
-           0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f,   \\ o r i z a t i o
-           0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63,   \\ n - - - - c a c
-           0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72,   \\ h e - c o n t r
-           0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f,   \\ o l - - - - c o
-           0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e,   \\ n n e c t i o n
-           0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74,   \\ - - - - c o n t
-           0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65,   \\ e n t - b a s e
-           0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74,   \\ - - - - c o n t
-           0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f,   \\ e n t - e n c o
-           0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10,   \\ d i n g - - - -
-           0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d,   \\ c o n t e n t -
-           0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65,   \\ l a n g u a g e
-           0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74,   \\ - - - - c o n t
-           0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67,   \\ e n t - l e n g
-           0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f,   \\ t h - - - - c o
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 28]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-           0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f,   \\ n t e n t - l o
-           0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00,   \\ c a t i o n - -
-           0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e,   \\ - - c o n t e n
-           0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00,   \\ t - m d 5 - - -
-           0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,   \\ - c o n t e n t
-           0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00,   \\ - r a n g e - -
-           0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e,   \\ - - c o n t e n
-           0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00,   \\ t - t y p e - -
-           0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00,   \\ - - d a t e - -
-           0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00,   \\ - - e t a g - -
-           0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74,   \\ - - e x p e c t
-           0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69,   \\ - - - - e x p i
-           0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66,   \\ r e s - - - - f
-           0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68,   \\ r o m - - - - h
-           0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69,   \\ o s t - - - - i
-           0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00,   \\ f - m a t c h -
-           0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f,   \\ - - - i f - m o
-           0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73,   \\ d i f i e d - s
-           0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d,   \\ i n c e - - - -
-           0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d,   \\ i f - n o n e -
-           0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00,   \\ m a t c h - - -
-           0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67,   \\ - i f - r a n g
-           0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d,   \\ e - - - - i f -
-           0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69,   \\ u n m o d i f i
-           0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65,   \\ e d - s i n c e
-           0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74,   \\ - - - - l a s t
-           0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65,   \\ - m o d i f i e
-           0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63,   \\ d - - - - l o c
-           0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00,   \\ a t i o n - - -
-           0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72,   \\ - m a x - f o r
-           0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00,   \\ w a r d s - - -
-           0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00,   \\ - p r a g m a -
-           0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79,   \\ - - - p r o x y
-           0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74,   \\ - a u t h e n t
-           0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00,   \\ i c a t e - - -
-           0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61,   \\ - p r o x y - a
-           0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61,   \\ u t h o r i z a
-           0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05,   \\ t i o n - - - -
-           0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00,   \\ r a n g e - - -
-           0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72,   \\ - r e f e r e r
-           0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72,   \\ - - - - r e t r
-           0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00,   \\ y - a f t e r -
-           0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65,   \\ - - - s e r v e
-           0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00,   \\ r - - - - t e -
-           0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c,   \\ - - - t r a i l
-           0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72,   \\ e r - - - - t r
-           0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65,   \\ a n s f e r - e
-           0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00,   \\ n c o d i n g -
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 29]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-           0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61,   \\ - - - u p g r a
-           0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73,   \\ d e - - - - u s
-           0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74,   \\ e r - a g e n t
-           0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79,   \\ - - - - v a r y
-           0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00,   \\ - - - - v i a -
-           0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69,   \\ - - - w a r n i
-           0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77,   \\ n g - - - - w w
-           0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e,   \\ w - a u t h e n
-           0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00,   \\ t i c a t e - -
-           0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64,   \\ - - m e t h o d
-           0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00,   \\ - - - - g e t -
-           0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75,   \\ - - - s t a t u
-           0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30,   \\ s - - - - 2 0 0
-           0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76,   \\ - O K - - - - v
-           0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00,   \\ e r s i o n - -
-           0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31,   \\ - - H T T P - 1
-           0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72,   \\ - 1 - - - - u r
-           0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62,   \\ l - - - - p u b
-           0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73,   \\ l i c - - - - s
-           0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69,   \\ e t - c o o k i
-           0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65,   \\ e - - - - k e e
-           0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00,   \\ p - a l i v e -
-           0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69,   \\ - - - o r i g i
-           0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32,   \\ n 1 0 0 1 0 1 2
-           0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35,   \\ 0 1 2 0 2 2 0 5
-           0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30,   \\ 2 0 6 3 0 0 3 0
-           0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33,   \\ 2 3 0 3 3 0 4 3
-           0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37,   \\ 0 5 3 0 6 3 0 7
-           0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30,   \\ 4 0 2 4 0 5 4 0
-           0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34,   \\ 6 4 0 7 4 0 8 4
-           0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31,   \\ 0 9 4 1 0 4 1 1
-           0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31,   \\ 4 1 2 4 1 3 4 1
-           0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34,   \\ 4 4 1 5 4 1 6 4
-           0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34,   \\ 1 7 5 0 2 5 0 4
-           0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e,   \\ 5 0 5 2 0 3 - N
-           0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f,   \\ o n - A u t h o
-           0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65,   \\ r i t a t i v e
-           0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61,   \\ - I n f o r m a
-           0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20,   \\ t i o n 2 0 4 -
-           0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65,   \\ N o - C o n t e
-           0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f,   \\ n t 3 0 1 - M o
-           0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d,   \\ v e d - P e r m
-           0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34,   \\ a n e n t l y 4
-           0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52,   \\ 0 0 - B a d - R
-           0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30,   \\ e q u e s t 4 0
-           0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68,   \\ 1 - U n a u t h
-           0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30,   \\ o r i z e d 4 0
-           0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64,   \\ 3 - F o r b i d
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 30]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-           0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e,   \\ d e n 4 0 4 - N
-           0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64,   \\ o t - F o u n d
-           0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65,   \\ 5 0 0 - I n t e
-           0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72,   \\ r n a l - S e r
-           0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f,   \\ v e r - E r r o
-           0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74,   \\ r 5 0 1 - N o t
-           0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65,   \\ - I m p l e m e
-           0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20,   \\ n t e d 5 0 3 -
-           0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20,   \\ S e r v i c e -
-           0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61,   \\ U n a v a i l a
-           0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46,   \\ b l e J a n - F
-           0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41,   \\ e b - M a r - A
-           0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a,   \\ p r - M a y - J
-           0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41,   \\ u n - J u l - A
-           0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20,   \\ u g - S e p t -
-           0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20,   \\ O c t - N o v -
-           0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30,   \\ D e c - 0 0 - 0
-           0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e,   \\ 0 - 0 0 - M o n
-           0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57,   \\ - - T u e - - W
-           0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c,   \\ e d - - T h u -
-           0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61,   \\ - F r i - - S a
-           0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20,   \\ t - - S u n - -
-           0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b,   \\ G M T c h u n k
-           0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f,   \\ e d - t e x t -
-           0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61,   \\ h t m l - i m a
-           0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69,   \\ g e - p n g - i
-           0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67,   \\ m a g e - j p g
-           0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67,   \\ - i m a g e - g
-           0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69,   \\ i f - a p p l i
-           0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78,   \\ c a t i o n - x
-           0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69,   \\ m l - a p p l i
-           0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78,   \\ c a t i o n - x
-           0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c,   \\ h t m l - x m l
-           0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c,   \\ - t e x t - p l
-           0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74,   \\ a i n - t e x t
-           0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72,   \\ - j a v a s c r
-           0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c,   \\ i p t - p u b l
-           0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74,   \\ i c p r i v a t
-           0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65,   \\ e m a x - a g e
-           0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65,   \\ - g z i p - d e
-           0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64,   \\ f l a t e - s d
-           0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65,   \\ c h c h a r s e
-           0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63,   \\ t - u t f - 8 c
-           0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69,   \\ h a r s e t - i
-           0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d,   \\ s o - 8 8 5 9 -
-           0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a,   \\ 1 - u t f - - -
-           0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e          \\ - e n q - 0 -
-   };
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 31]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   The entire contents of the name/value header block is compressed
-   using zlib.  There is a single zlib stream for all name value pairs
-   in one direction on a connection.  SPDY uses a SYNC_FLUSH between
-   each compressed frame.
-
-   Implementation notes: the compression engine can be tuned to favor
-   speed or size.  Optimizing for size increases memory use and CPU
-   consumption.  Because header blocks are generally small, implementors
-   may want to reduce the window-size of the compression engine from the
-   default 15bits (a 32KB window) to more like 11bits (a 2KB window).
-   The exact setting is chosen by the compressor, the decompressor will
-   work with any setting.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 32]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-3.  HTTP Layering over SPDY
-
-   SPDY is intended to be as compatible as possible with current web-
-   based applications.  This means that, from the perspective of the
-   server business logic or application API, the features of HTTP are
-   unchanged.  To achieve this, all of the application request and
-   response header semantics are preserved, although the syntax of
-   conveying those semantics has changed.  Thus, the rules from the
-   HTTP/1.1 specification in RFC2616 [RFC2616] apply with the changes in
-   the sections below.
-
-3.1.  Connection Management
-
-   Clients SHOULD NOT open more than one SPDY session to a given origin
-   [RFC6454] concurrently.
-
-   Note that it is possible for one SPDY session to be finishing (e.g. a
-   GOAWAY message has been sent, but not all streams have finished),
-   while another SPDY session is starting.
-
-3.1.1.  Use of GOAWAY
-
-   SPDY provides a GOAWAY message which can be used when closing a
-   connection from either the client or server.  Without a server GOAWAY
-   message, HTTP has a race condition where the client sends a request
-   (a new SYN_STREAM) just as the server is closing the connection, and
-   the client cannot know if the server received the stream or not.  By
-   using the last-stream-id in the GOAWAY, servers can indicate to the
-   client if a request was processed or not.
-
-   Note that some servers will choose to send the GOAWAY and immediately
-   terminate the connection without waiting for active streams to
-   finish.  The client will be able to determine this because SPDY
-   streams are determinstically closed.  This abrupt termination will
-   force the client to heuristically decide whether to retry the pending
-   requests.  Clients always need to be capable of dealing with this
-   case because they must deal with accidental connection termination
-   cases, which are the same as the server never having sent a GOAWAY.
-
-   More sophisticated servers will use GOAWAY to implement a graceful
-   teardown.  They will send the GOAWAY and provide some time for the
-   active streams to finish before terminating the connection.
-
-   If a SPDY client closes the connection, it should also send a GOAWAY
-   message.  This allows the server to know if any server-push streams
-   were received by the client.
-
-   If the endpoint closing the connection has not received any
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 33]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   SYN_STREAMs from the remote, the GOAWAY will contain a last-stream-id
-   of 0.
-
-3.2.  HTTP Request/Response
-
-3.2.1.  Request
-
-   The client initiates a request by sending a SYN_STREAM frame.  For
-   requests which do not contain a body, the SYN_STREAM frame MUST set
-   the FLAG_FIN, indicating that the client intends to send no further
-   data on this stream.  For requests which do contain a body, the
-   SYN_STREAM will not contain the FLAG_FIN, and the body will follow
-   the SYN_STREAM in a series of DATA frames.  The last DATA frame will
-   set the FLAG_FIN to indicate the end of the body.
-
-   The SYN_STREAM Name/Value section will contain all of the HTTP
-   headers which are associated with an HTTP request.  The header block
-   in SPDY is mostly unchanged from today's HTTP header block, with the
-   following differences:
-
-      The first line of the request is unfolded into name/value pairs
-      like other HTTP headers and MUST be present:
-
-         ":method" - the HTTP method for this request (e.g.  "GET",
-         "POST", "HEAD", etc)
-
-         ":path" - the url-path for this url with "/" prefixed.  (See
-         RFC1738 [RFC1738]).  For example, for
-         "http://www.google.com/search?q=dogs" the path would be
-         "/search?q=dogs".
-
-         ":version" - the HTTP version of this request (e.g.
-         "HTTP/1.1")
-
-      In addition, the following two name/value pairs must also be
-      present in every request:
-
-         ":host" - the hostport (See RFC1738 [RFC1738]) portion of the
-         URL for this request (e.g. "www.google.com:1234").  This header
-         is the same as the HTTP 'Host' header.
-
-         ":scheme" - the scheme portion of the URL for this request
-         (e.g. "https"))
-
-      Header names are all lowercase.
-
-      The Connection, Host, Keep-Alive, Proxy-Connection, and Transfer-
-      Encoding headers are not valid and MUST not be sent.
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 34]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-      User-agents MUST support gzip compression.  Regardless of the
-      Accept-Encoding sent by the user-agent, the server may always send
-      content encoded with gzip or deflate encoding.
-
-      If a server receives a request where the sum of the data frame
-      payload lengths does not equal the size of the Content-Length
-      header, the server MUST return a 400 (Bad Request) error.
-
-      POST-specific changes:
-
-         Although POSTs are inherently chunked, POST requests SHOULD
-         also be accompanied by a Content-Length header.  There are two
-         reasons for this: First, it assists with upload progress meters
-         for an improved user experience.  But second, we know from
-         early versions of SPDY that failure to send a content length
-         header is incompatible with many existing HTTP server
-         implementations.  Existing user-agents do not omit the Content-
-         Length header, and server implementations have come to depend
-         upon this.
-
-   The user-agent is free to prioritize requests as it sees fit.  If the
-   user-agent cannot make progress without receiving a resource, it
-   should attempt to raise the priority of that resource.  Resources
-   such as images, SHOULD generally use the lowest priority.
-
-   If a client sends a SYN_STREAM without all of the method, host, path,
-   scheme, and version headers, the server MUST reply with a HTTP 400
-   Bad Request reply.
-
-3.2.2.  Response
-
-   The server responds to a client request with a SYN_REPLY frame.
-   Symmetric to the client's upload stream, server will send data after
-   the SYN_REPLY frame via a series of DATA frames, and the last data
-   frame will contain the FLAG_FIN to indicate successful end-of-stream.
-   If a response (like a 202 or 204 response) contains no body, the
-   SYN_REPLY frame may contain the FLAG_FIN flag to indicate no further
-   data will be sent on the stream.
-
-      The response status line is unfolded into name/value pairs like
-      other HTTP headers and must be present:
-
-         ":status" - The HTTP response status code (e.g. "200" or "200
-         OK")
-
-         ":version" - The HTTP response version (e.g.  "HTTP/1.1")
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 35]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-      All header names must be lowercase.
-
-      The Connection, Keep-Alive, Proxy-Connection, and Transfer-
-      Encoding headers are not valid and MUST not be sent.
-
-      Responses MAY be accompanied by a Content-Length header for
-      advisory purposes. (e.g. for UI progress meters)
-
-      If a client receives a response where the sum of the data frame
-      payload lengths does not equal the size of the Content-Length
-      header, the client MUST ignore the content length header.
-
-   If a client receives a SYN_REPLY without a status or without a
-   version header, the client must reply with a RST_STREAM frame
-   indicating a PROTOCOL ERROR.
-
-3.2.3.  Authentication
-
-   When a client sends a request to an origin server that requires
-   authentication, the server can reply with a "401 Unauthorized"
-   response, and include a WWW-Authenticate challenge header that
-   defines the authentication scheme to be used.  The client then
-   retries the request with an Authorization header appropriate to the
-   specified authentication scheme.
-
-   There are four options for proxy authentication, Basic, Digest, NTLM
-   and Negotiate (SPNEGO).  The first two options were defined in
-   RFC2617 [RFC2617], and are stateless.  The second two options were
-   developed by Microsoft and specified in RFC4559 [RFC4559], and are
-   stateful; otherwise known as multi-round authentication, or
-   connection authentication.
-
-3.2.3.1.  Stateless Authentication
-
-   Stateless Authentication over SPDY is identical to how it is
-   performed over HTTP.  If multiple SPDY streams are concurrently sent
-   to a single server, each will authenticate independently, similar to
-   how two HTTP connections would independently authenticate to a proxy
-   server.
-
-3.2.3.2.  Stateful Authentication
-
-   Unfortunately, the stateful authentication mechanisms were
-   implemented and defined in a such a way that directly violates
-   RFC2617 - they do not include a "realm" as part of the request.  This
-   is problematic in SPDY because it makes it impossible for a client to
-   disambiguate two concurrent server authentication challenges.
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 36]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   To deal with this case, SPDY servers using Stateful Authentication
-   MUST implement one of two changes:
-
-      Servers can add a "realm=<desired realm>" header so that the two
-      authentication requests can be disambiguated and run concurrently.
-      Unfortunately, given how these mechanisms work, this is probably
-      not practical.
-
-      Upon sending the first stateful challenge response, the server
-      MUST buffer and defer all further frames which are not part of
-      completing the challenge until the challenge has completed.
-      Completing the authentication challenge may take multiple round
-      trips.  Once the client receives a "401 Authenticate" response for
-      a stateful authentication type, it MUST stop sending new requests
-      to the server until the authentication has completed by receiving
-      a non-401 response on at least one stream.
-
-3.3.  Server Push Transactions
-
-   SPDY enables a server to send multiple replies to a client for a
-   single request.  The rationale for this feature is that sometimes a
-   server knows that it will need to send multiple resources in response
-   to a single request.  Without server push features, the client must
-   first download the primary resource, then discover the secondary
-   resource(s), and request them.  Pushing of resources avoids the
-   round-trip delay, but also creates a potential race where a server
-   can be pushing content which a user-agent is in the process of
-   requesting.  The following mechanics attempt to prevent the race
-   condition while enabling the performance benefit.
-
-   Browsers receiving a pushed response MUST validate that the server is
-   authorized to push the URL using the browser same-origin [RFC6454]
-   policy.  For example, a SPDY connection to www.foo.com is generally
-   not permitted to push a response for www.evil.com.
-
-   If the browser accepts a pushed response (e.g. it does not send a
-   RST_STREAM), the browser MUST attempt to cache the pushed response in
-   same way that it would cache any other response.  This means
-   validating the response headers and inserting into the disk cache.
-
-   Because pushed responses have no request, they have no request
-   headers associated with them.  At the framing layer, SPDY pushed
-   streams contain an "associated-stream-id" which indicates the
-   requested stream for which the pushed stream is related.  The pushed
-   stream inherits all of the headers from the associated-stream-id with
-   the exception of ":host", ":scheme", and ":path", which are provided
-   as part of the pushed response stream headers.  The browser MUST
-   store these inherited and implied request headers with the cached
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 37]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   resource.
-
-   Implementation note: With server push, it is theoretically possible
-   for servers to push unreasonable amounts of content or resources to
-   the user-agent.  Browsers MUST implement throttles to protect against
-   unreasonable push attacks.
-
-3.3.1.  Server implementation
-
-   When the server intends to push a resource to the user-agent, it
-   opens a new stream by sending a unidirectional SYN_STREAM.  The
-   SYN_STREAM MUST include an Associated-To-Stream-ID, and MUST set the
-   FLAG_UNIDIRECTIONAL flag.  The SYN_STREAM MUST include headers for
-   ":scheme", ":host", ":path", which represent the URL for the resource
-   being pushed.  Subsequent headers may follow in HEADERS frames.  The
-   purpose of the association is so that the user-agent can
-   differentiate which request induced the pushed stream; without it, if
-   the user-agent had two tabs open to the same page, each pushing
-   unique content under a fixed URL, the user-agent would not be able to
-   differentiate the requests.
-
-   The Associated-To-Stream-ID must be the ID of an existing, open
-   stream.  The reason for this restriction is to have a clear endpoint
-   for pushed content.  If the user-agent requested a resource on stream
-   11, the server replies on stream 11.  It can push any number of
-   additional streams to the client before sending a FLAG_FIN on stream
-   11.  However, once the originating stream is closed no further push
-   streams may be associated with it.  The pushed streams do not need to
-   be closed (FIN set) before the originating stream is closed, they
-   only need to be created before the originating stream closes.
-
-   It is illegal for a server to push a resource with the Associated-To-
-   Stream-ID of 0.
-
-   To minimize race conditions with the client, the SYN_STREAM for the
-   pushed resources MUST be sent prior to sending any content which
-   could allow the client to discover the pushed resource and request
-   it.
-
-   The server MUST only push resources which would have been returned
-   from a GET request.
-
-   Note: If the server does not have all of the Name/Value Response
-   headers available at the time it issues the HEADERS frame for the
-   pushed resource, it may later use an additional HEADERS frame to
-   augment the name/value pairs to be associated with the pushed stream.
-   The subsequent HEADERS frame(s) must not contain a header for
-   ':host', ':scheme', or ':path' (e.g. the server can't change the
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 38]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   identity of the resource to be pushed).  The HEADERS frame must not
-   contain duplicate headers with a previously sent HEADERS frame.  The
-   server must send a HEADERS frame including the scheme/host/port
-   headers before sending any data frames on the stream.
-
-3.3.2.  Client implementation
-
-   When fetching a resource the client has 3 possibilities:
-
-      the resource is not being pushed
-
-      the resource is being pushed, but the data has not yet arrived
-
-      the resource is being pushed, and the data has started to arrive
-
-   When a SYN_STREAM and HEADERS frame which contains an Associated-To-
-   Stream-ID is received, the client must not issue GET requests for the
-   resource in the pushed stream, and instead wait for the pushed stream
-   to arrive.
-
-   If a client receives a server push stream with stream-id 0, it MUST
-   issue a session error (Section 2.4.1) with the status code
-   PROTOCOL_ERROR.
-
-   When a client receives a SYN_STREAM from the server without a the
-   ':host', ':scheme', and ':path' headers in the Name/Value section, it
-   MUST reply with a RST_STREAM with error code HTTP_PROTOCOL_ERROR.
-
-   To cancel individual server push streams, the client can issue a
-   stream error (Section 2.4.2) with error code CANCEL.  Upon receipt,
-   the server MUST stop sending on this stream immediately (this is an
-   Abrupt termination).
-
-   To cancel all server push streams related to a request, the client
-   may issue a stream error (Section 2.4.2) with error code CANCEL on
-   the associated-stream-id.  By cancelling that stream, the server MUST
-   immediately stop sending frames for any streams with
-   in-association-to for the original stream.
-
-   If the server sends a HEADER frame containing duplicate headers with
-   a previous HEADERS frame for the same stream, the client must issue a
-   stream error (Section 2.4.2) with error code PROTOCOL ERROR.
-
-   If the server sends a HEADERS frame after sending a data frame for
-   the same stream, the client MAY ignore the HEADERS frame.  Ignoring
-   the HEADERS frame after a data frame prevents handling of HTTP's
-   trailing headers
-   (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.40).
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 39]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-4.  Design Rationale and Notes
-
-   Authors' notes: The notes in this section have no bearing on the SPDY
-   protocol as specified within this document, and none of these notes
-   should be considered authoritative about how the protocol works.
-   However, these notes may prove useful in future debates about how to
-   resolve protocol ambiguities or how to evolve the protocol going
-   forward.  They may be removed before the final draft.
-
-4.1.  Separation of Framing Layer and Application Layer
-
-   Readers may note that this specification sometimes blends the framing
-   layer (Section 2) with requirements of a specific application - HTTP
-   (Section 3).  This is reflected in the request/response nature of the
-   streams, the definition of the HEADERS and compression contexts which
-   are very similar to HTTP, and other areas as well.
-
-   This blending is intentional - the primary goal of this protocol is
-   to create a low-latency protocol for use with HTTP.  Isolating the
-   two layers is convenient for description of the protocol and how it
-   relates to existing HTTP implementations.  However, the ability to
-   reuse the SPDY framing layer is a non goal.
-
-4.2.  Error handling - Framing Layer
-
-   Error handling at the SPDY layer splits errors into two groups: Those
-   that affect an individual SPDY stream, and those that do not.
-
-   When an error is confined to a single stream, but general framing is
-   in tact, SPDY attempts to use the RST_STREAM as a mechanism to
-   invalidate the stream but move forward without aborting the
-   connection altogether.
-
-   For errors occuring outside of a single stream context, SPDY assumes
-   the entire session is hosed.  In this case, the endpoint detecting
-   the error should initiate a connection close.
-
-4.3.  One Connection Per Domain
-
-   SPDY attempts to use fewer connections than other protocols have
-   traditionally used.  The rationale for this behavior is because it is
-   very difficult to provide a consistent level of service (e.g.  TCP
-   slow-start), prioritization, or optimal compression when the client
-   is connecting to the server through multiple channels.
-
-   Through lab measurements, we have seen consistent latency benefits by
-   using fewer connections from the client.  The overall number of
-   packets sent by SPDY can be as much as 40% less than HTTP.  Handling
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 40]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   large numbers of concurrent connections on the server also does
-   become a scalability problem, and SPDY reduces this load.
-
-   The use of multiple connections is not without benefit, however.
-   Because SPDY multiplexes multiple, independent streams onto a single
-   stream, it creates a potential for head-of-line blocking problems at
-   the transport level.  In tests so far, the negative effects of head-
-   of-line blocking (especially in the presence of packet loss) is
-   outweighed by the benefits of compression and prioritization.
-
-4.4.  Fixed vs Variable Length Fields
-
-   SPDY favors use of fixed length 32bit fields in cases where smaller,
-   variable length encodings could have been used.  To some, this seems
-   like a tragic waste of bandwidth.  SPDY choses the simple encoding
-   for speed and simplicity.
-
-   The goal of SPDY is to reduce latency on the network.  The overhead
-   of SPDY frames is generally quite low.  Each data frame is only an 8
-   byte overhead for a 1452 byte payload (~0.6%).  At the time of this
-   writing, bandwidth is already plentiful, and there is a strong trend
-   indicating that bandwidth will continue to increase.  With an average
-   worldwide bandwidth of 1Mbps, and assuming that a variable length
-   encoding could reduce the overhead by 50%, the latency saved by using
-   a variable length encoding would be less than 100 nanoseconds.  More
-   interesting are the effects when the larger encodings force a packet
-   boundary, in which case a round-trip could be induced.  However, by
-   addressing other aspects of SPDY and TCP interactions, we believe
-   this is completely mitigated.
-
-4.5.  Compression Context(s)
-
-   When isolating the compression contexts used for communicating with
-   multiple origins, we had a few choices to make.  We could have
-   maintained a map (or list) of compression contexts usable for each
-   origin.  The basic case is easy - each HEADERS frame would need to
-   identify the context to use for that frame.  However, compression
-   contexts are not cheap, so the lifecycle of each context would need
-   to be bounded.  For proxy servers, where we could churn through many
-   contexts, this would be a concern.  We considered using a static set
-   of contexts, say 16 of them, which would bound the memory use.  We
-   also considered dynamic contexts, which could be created on the fly,
-   and would need to be subsequently destroyed.  All of these are
-   complicated, and ultimately we decided that such a mechanism creates
-   too many problems to solve.
-
-   Alternatively, we've chosen the simple approach, which is to simply
-   provide a flag for resetting the compression context.  For the common
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 41]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   case (no proxy), this fine because most requests are to the same
-   origin and we never need to reset the context.  For cases where we
-   are using two different origins over a single SPDY session, we simply
-   reset the compression state between each transition.
-
-4.6.  Unidirectional streams
-
-   Many readers notice that unidirectional streams are both a bit
-   confusing in concept and also somewhat redundant.  If the recipient
-   of a stream doesn't wish to send data on a stream, it could simply
-   send a SYN_REPLY with the FLAG_FIN bit set.  The FLAG_UNIDIRECTIONAL
-   is, therefore, not necessary.
-
-   It is true that we don't need the UNIDIRECTIONAL markings.  It is
-   added because it avoids the recipient of pushed streams from needing
-   to send a set of empty frames (e.g. the SYN_STREAM w/ FLAG_FIN) which
-   otherwise serve no purpose.
-
-4.7.  Data Compression
-
-   Generic compression of data portion of the streams (as opposed to
-   compression of the headers) without knowing the content of the stream
-   is redundant.  There is no value in compressing a stream which is
-   already compressed.  Because of this, SPDY does allow data
-   compression to be optional.  We included it because study of existing
-   websites shows that many sites are not using compression as they
-   should, and users suffer because of it.  We wanted a mechanism where,
-   at the SPDY layer, site administrators could simply force compression
-   - it is better to compress twice than to not compress.
-
-   Overall, however, with this feature being optional and sometimes
-   redundant, it is unclear if it is useful at all.  We will likely
-   remove it from the specification.
-
-4.8.  Server Push
-
-   A subtle but important point is that server push streams must be
-   declared before the associated stream is closed.  The reason for this
-   is so that proxies have a lifetime for which they can discard
-   information about previous streams.  If a pushed stream could
-   associate itself with an already-closed stream, then endpoints would
-   not have a specific lifecycle for when they could disavow knowledge
-   of the streams which went before.
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 42]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-5.  Security Considerations
-
-5.1.  Use of Same-origin constraints
-
-   This specification uses the same-origin policy [RFC6454] in all cases
-   where verification of content is required.
-
-5.2.  HTTP Headers and SPDY Headers
-
-   At the application level, HTTP uses name/value pairs in its headers.
-   Because SPDY merges the existing HTTP headers with SPDY headers,
-   there is a possibility that some HTTP applications already use a
-   particular header name.  To avoid any conflicts, all headers
-   introduced for layering HTTP over SPDY are prefixed with ":". ":" is
-   not a valid sequence in HTTP header naming, preventing any possible
-   conflict.
-
-5.3.  Cross-Protocol Attacks
-
-   By utilizing TLS, we believe that SPDY introduces no new cross-
-   protocol attacks.  TLS encrypts the contents of all transmission
-   (except the handshake itself), making it difficult for attackers to
-   control the data which could be used in a cross-protocol attack.
-
-5.4.  Server Push Implicit Headers
-
-   Pushed resources do not have an associated request.  In order for
-   existing HTTP cache control validations (such as the Vary header) to
-   work, however, all cached resources must have a set of request
-   headers.  For this reason, browsers MUST be careful to inherit
-   request headers from the associated stream for the push.  This
-   includes the 'Cookie' header.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 43]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-6.  Privacy Considerations
-
-6.1.  Long Lived Connections
-
-   SPDY aims to keep connections open longer between clients and servers
-   in order to reduce the latency when a user makes a request.  The
-   maintenance of these connections over time could be used to expose
-   private information.  For example, a user using a browser hours after
-   the previous user stopped using that browser may be able to learn
-   about what the previous user was doing.  This is a problem with HTTP
-   in its current form as well, however the short lived connections make
-   it less of a risk.
-
-6.2.  SETTINGS frame
-
-   The SPDY SETTINGS frame allows servers to store out-of-band
-   transmitted information about the communication between client and
-   server on the client.  Although this is intended only to be used to
-   reduce latency, renegade servers could use it as a mechanism to store
-   identifying information about the client in future requests.
-
-   Clients implementing privacy modes, such as Google Chrome's
-   "incognito mode", may wish to disable client-persisted SETTINGS
-   storage.
-
-   Clients MUST clear persisted SETTINGS information when clearing the
-   cookies.
-
-   TODO: Put range maximums on each type of setting to limit
-   inappropriate uses.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 44]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-7.  Incompatibilities with SPDY draft #2
-
-   Here is a list of the major changes between this draft and draft #2.
-
-      Addition of flow control
-
-      Increased 16 bit length fields in SYN_STREAM and SYN_REPLY to 32
-      bits.
-
-      Changed definition of compression for DATA frames
-
-      Updated compression dictionary
-
-      Fixed off-by-one on the compression dictionary for headers
-
-      Increased priority field from 2bits to 3bits.
-
-      Removed NOOP frame
-
-      Split the request "url" into "scheme", "host", and "path"
-
-      Added the requirement that POSTs contain content-length.
-
-      Removed wasted 16bits of unused space from the end of the
-      SYN_REPLY and HEADERS frames.
-
-      Fixed bug: Priorities were described backward (0 was lowest
-      instead of highest).
-
-      Fixed bug: Name/Value header counts were duplicated in both the
-      Name Value header block and also the containing frame.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 45]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-8.  Requirements Notation
-
-   The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
-   "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
-   document are to be interpreted as described in RFC 2119 [RFC2119].
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 46]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-9.  Acknowledgements
-
-   Many individuals have contributed to the design and evolution of
-   SPDY: Adam Langley, Wan-Teh Chang, Jim Morrison, Mark Nottingham,
-   Alyssa Wilk, Costin Manolache, William Chan, Vitaliy Lvin, Joe Chan,
-   Adam Barth, Ryan Hamilton, Gavin Peters, Kent Alstad, Kevin Lindsay,
-   Paul Amer, Fan Yang, Jonathan Leighton
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 47]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-10.  Normative References
-
-   [RFC0793]  Postel, J., "Transmission Control Protocol", STD 7,
-              RFC 793, September 1981.
-
-   [RFC1738]  Berners-Lee, T., Masinter, L., and M. McCahill, "Uniform
-              Resource Locators (URL)", RFC 1738, December 1994.
-
-   [RFC1950]  Deutsch, L. and J-L. Gailly, "ZLIB Compressed Data Format
-              Specification version 3.3", RFC 1950, May 1996.
-
-   [RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
-              Requirement Levels", BCP 14, RFC 2119, March 1997.
-
-   [RFC2285]  Mandeville, R., "Benchmarking Terminology for LAN
-              Switching Devices", RFC 2285, February 1998.
-
-   [RFC2616]  Fielding, R., Gettys, J., Mogul, J., Frystyk, H.,
-              Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext
-              Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999.
-
-   [RFC2617]  Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S.,
-              Leach, P., Luotonen, A., and L. Stewart, "HTTP
-              Authentication: Basic and Digest Access Authentication",
-              RFC 2617, June 1999.
-
-   [RFC4559]  Jaganathan, K., Zhu, L., and J. Brezak, "SPNEGO-based
-              Kerberos and NTLM HTTP Authentication in Microsoft
-              Windows", RFC 4559, June 2006.
-
-   [RFC4366]  Blake-Wilson, S., Nystrom, M., Hopwood, D., Mikkelsen, J.,
-              and T. Wright, "Transport Layer Security (TLS)
-              Extensions", RFC 4366, April 2006.
-
-   [RFC5246]  Dierks, T. and E. Rescorla, "The Transport Layer Security
-              (TLS) Protocol Version 1.2", RFC 5246, August 2008.
-
-   [RFC6454]  Barth, A., "The Web Origin Concept", RFC 6454,
-              December 2011.
-
-   [TLSNPN]   Langley, A., "TLS Next Protocol Negotiation",
-              <http://tools.ietf.org/html/
-              draft-agl-tls-nextprotoneg-01>.
-
-   [ASCII]    "US-ASCII. Coded Character Set - 7-Bit American Standard
-              Code for Information Interchange. Standard ANSI X3.4-1986,
-              ANSI, 1986.".
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 48]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-   [UDELCOMPRESSION]
-              Yang, F., Amer, P., and J. Leighton, "A Methodology to
-              Derive SPDY's Initial Dictionary for Zlib Compression",
-              <http://www.eecis.udel.edu/~amer/PEL/poc/pdf/
-              SPDY-Fan.pdf>.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 49]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-Appendix A.  Changes
-
-   To be removed by RFC Editor before publication
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 50]
-
-Internet-Draft                    SPDY                          Feb 2012
-
-
-Authors' Addresses
-
-   Mike Belshe
-   Twist
-
-   Email: mbelshe@chromium.org
-
-
-   Roberto Peon
-   Google, Inc
-
-   Email: fenix@google.com
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Belshe & Peon            Expires August 4, 2012                [Page 51]
-
diff --git a/src/examples/.gitignore b/src/examples/.gitignore
new file mode 100644
index 0000000..7a64ff4
--- /dev/null
+++ b/src/examples/.gitignore
@@ -0,0 +1,40 @@
+/demo_https
+/chunked_example
+/benchmark_https
+/benchmark
+/demo
+/dual_stack_example
+/post_example.gcno
+/minimal_example.gcda
+/post_example
+/digest_auth_example.gcno
+/fileserver_example_dirs.gcno
+/digest_auth_example
+/fileserver_example_dirs
+/minimal_example.gcno
+/querystring_example.gcno
+/authorization_example.gcno
+/minimal_example_comet
+/https_fileserver_example.gcno
+/refuse_post_example.gcno
+/https_fileserver_example
+/fileserver_example.gcno
+/fileserver_example_external_select.gcno
+/refuse_post_example
+/minimal_example_comet.gcno
+/X.509
+/https_server_example
+/querystring_example
+/minimal_example
+/fileserver_example
+/fileserver_example_external_select
+/https_echo_server_example.c
+/https_echo_client_example.c
+/authorization_example
+upgrade_example
+websocket_threaded_example
+/timeout
+http_chunked_compression
+http_compression
+minimal_example_empty
+minimal_example_empty_tls
diff --git a/src/examples/Makefile.am b/src/examples/Makefile.am
index edc80dc..e22fe7e 100644
--- a/src/examples/Makefile.am
+++ b/src/examples/Makefile.am
@@ -3,26 +3,24 @@
 
 AM_CPPFLAGS = \
   -I$(top_srcdir)/src/include \
+  $(CPPFLAGS_ac) \
   -DDATA_DIR=\"$(top_srcdir)/src/datadir/\"
 
-AM_CFLAGS = @LIBGCRYPT_CFLAGS@
+AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@
 
-CPU_COUNT_DEF = -DCPU_COUNT=$(CPU_COUNT)
+AM_LDFLAGS = $(LDFLAGS_ac)
+
+MHD_CPU_COUNT_DEF = -DMHD_CPU_COUNT=$(CPU_COUNT)
+
+AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac)
 
 if USE_COVERAGE
   AM_CFLAGS += --coverage
 endif
 
-if ENABLE_SPDY
-spdyex = \
-  spdy_event_loop \
-  spdy_fileserver \
-  spdy_response_with_callback
-
-if HAVE_SPDYLAY
-spdyex += mhd2spdy
-endif
-endif
+$(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile
+	@echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \
+	$(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la
 
 
 # example programs
@@ -31,26 +29,42 @@
  benchmark_https \
  chunked_example \
  minimal_example \
+ minimal_example_empty \
  dual_stack_example \
  minimal_example_comet \
  querystring_example \
+ timeout \
  fileserver_example \
  fileserver_example_dirs \
  fileserver_example_external_select \
- refuse_post_example \
- $(spdyex)
+ refuse_post_example
 
+if HAVE_EXPERIMENTAL
+noinst_PROGRAMS += \
+  websocket_chatserver_example
+endif
+
+if MHD_HAVE_EPOLL
+noinst_PROGRAMS += \
+  suspend_resume_epoll
+endif
+
+EXTRA_DIST = msgs_i18n.c
+noinst_EXTRA_DIST = msgs_i18n.c
 
 if ENABLE_HTTPS
-noinst_PROGRAMS += https_fileserver_example
+noinst_PROGRAMS += \
+ https_fileserver_example \
+ minimal_example_empty_tls
 endif
 if HAVE_POSTPROCESSOR
 noinst_PROGRAMS += \
   post_example
-if HAVE_MAGIC
-noinst_PROGRAMS += \
-  demo \
-  demo_https
+if HAVE_POSIX_THREADS
+noinst_PROGRAMS += demo
+if ENABLE_HTTPS
+noinst_PROGRAMS += demo_https
+endif
 endif
 endif
 
@@ -64,6 +78,20 @@
  authorization_example
 endif
 
+if HAVE_POSIX_THREADS
+if ENABLE_UPGRADE
+noinst_PROGRAMS += \
+ upgrade_example \
+ websocket_threaded_example
+endif
+endif
+
+if HAVE_ZLIB
+noinst_PROGRAMS += \
+ http_compression \
+ http_chunked_compression
+endif
+
 if HAVE_W32
 AM_CFLAGS += -DWINDOWS
 endif
@@ -73,51 +101,92 @@
 minimal_example_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la
 
+minimal_example_empty_SOURCES = \
+ minimal_example_empty.c
+minimal_example_empty_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+
+minimal_example_empty_tls_SOURCES = \
+ minimal_example_empty_tls.c
+minimal_example_empty_tls_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+
+upgrade_example_SOURCES = \
+ upgrade_example.c
+upgrade_example_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+upgrade_example_LDADD = \
+  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
+  $(PTHREAD_LIBS)
+
+websocket_threaded_example_SOURCES = \
+ websocket_threaded_example.c
+websocket_threaded_example_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+websocket_threaded_example_LDADD = \
+  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
+  $(PTHREAD_LIBS)
+
+timeout_SOURCES = \
+ timeout.c
+timeout_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+
 chunked_example_SOURCES = \
  chunked_example.c
 chunked_example_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la
 
+websocket_chatserver_example_SOURCES = \
+ websocket_chatserver_example.c
+websocket_chatserver_example_LDADD = \
+ $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+
 demo_SOURCES = \
  demo.c
 demo_CFLAGS = \
  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
 demo_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
+ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF)
 demo_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la  \
- $(PTHREAD_LIBS) -lmagic
+ $(PTHREAD_LIBS)
+if MHD_HAVE_LIBMAGIC
+demo_LDADD += -lmagic
+endif
 
 demo_https_SOURCES = \
  demo_https.c
 demo_https_CFLAGS = \
  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
 demo_https_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
+ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF)
 demo_https_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la  \
- $(PTHREAD_LIBS) -lmagic
-
-mhd2spdy_SOURCES = \
- mhd2spdy.c \
- mhd2spdy_spdy.c mhd2spdy_spdy.h \
- mhd2spdy_http.c mhd2spdy_http.h \
- mhd2spdy_structures.c mhd2spdy_structures.h
-mhd2spdy_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la  \
- -lssl -lcrypto -lspdylay
+ $(PTHREAD_LIBS)
+if MHD_HAVE_LIBMAGIC
+demo_https_LDADD += -lmagic
+endif
 
 benchmark_SOURCES = \
  benchmark.c
 benchmark_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
+ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF)
 benchmark_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la
 
+suspend_resume_epoll_SOURCES = \
+ suspend_resume_epoll.c
+suspend_resume_epoll_CPPFLAGS = \
+ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF)
+suspend_resume_epoll_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+
 benchmark_https_SOURCES = \
  benchmark_https.c
 benchmark_https_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
+ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF)
 benchmark_https_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la
 
@@ -178,21 +247,15 @@
 https_fileserver_example_LDADD = \
  $(top_builddir)/src/microhttpd/libmicrohttpd.la
 
-
-spdy_event_loop_SOURCES = \
- spdy_event_loop.c
-spdy_event_loop_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-spdy_fileserver_SOURCES = \
- spdy_fileserver.c
-spdy_fileserver_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-spdy_response_with_callback_SOURCES = \
- spdy_response_with_callback.c
-spdy_response_with_callback_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
+http_compression_SOURCES = \
+ http_compression.c
+http_chunked_compression_SOURCES = \
+ http_chunked_compression.c
+http_compression_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+http_chunked_compression_LDADD = \
+ $(top_builddir)/src/microhttpd/libmicrohttpd.la
+if HAVE_ZLIB
+ http_compression_LDADD += -lz
+ http_chunked_compression_LDADD += -lz
+endif
diff --git a/src/examples/Makefile.in b/src/examples/Makefile.in
deleted file mode 100644
index 5643f96..0000000
--- a/src/examples/Makefile.in
+++ /dev/null
@@ -1,1246 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@USE_COVERAGE_TRUE@am__append_1 = --coverage
-@ENABLE_SPDY_TRUE@@HAVE_SPDYLAY_TRUE@am__append_2 = mhd2spdy
-noinst_PROGRAMS = benchmark$(EXEEXT) benchmark_https$(EXEEXT) \
-	chunked_example$(EXEEXT) minimal_example$(EXEEXT) \
-	dual_stack_example$(EXEEXT) minimal_example_comet$(EXEEXT) \
-	querystring_example$(EXEEXT) fileserver_example$(EXEEXT) \
-	fileserver_example_dirs$(EXEEXT) \
-	fileserver_example_external_select$(EXEEXT) \
-	refuse_post_example$(EXEEXT) $(am__EXEEXT_2) $(am__EXEEXT_3) \
-	$(am__EXEEXT_4) $(am__EXEEXT_5) $(am__EXEEXT_6) \
-	$(am__EXEEXT_7)
-@ENABLE_HTTPS_TRUE@am__append_3 = https_fileserver_example
-@HAVE_POSTPROCESSOR_TRUE@am__append_4 = \
-@HAVE_POSTPROCESSOR_TRUE@  post_example
-
-@HAVE_MAGIC_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__append_5 = \
-@HAVE_MAGIC_TRUE@@HAVE_POSTPROCESSOR_TRUE@  demo \
-@HAVE_MAGIC_TRUE@@HAVE_POSTPROCESSOR_TRUE@  demo_https
-
-@ENABLE_DAUTH_TRUE@am__append_6 = \
-@ENABLE_DAUTH_TRUE@ digest_auth_example
-
-@ENABLE_BAUTH_TRUE@am__append_7 = \
-@ENABLE_BAUTH_TRUE@ authorization_example
-
-@HAVE_W32_TRUE@am__append_8 = -DWINDOWS
-subdir = src/examples
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-@ENABLE_SPDY_TRUE@@HAVE_SPDYLAY_TRUE@am__EXEEXT_1 = mhd2spdy$(EXEEXT)
-@ENABLE_SPDY_TRUE@am__EXEEXT_2 = spdy_event_loop$(EXEEXT) \
-@ENABLE_SPDY_TRUE@	spdy_fileserver$(EXEEXT) \
-@ENABLE_SPDY_TRUE@	spdy_response_with_callback$(EXEEXT) \
-@ENABLE_SPDY_TRUE@	$(am__EXEEXT_1)
-@ENABLE_HTTPS_TRUE@am__EXEEXT_3 = https_fileserver_example$(EXEEXT)
-@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_4 = post_example$(EXEEXT)
-@HAVE_MAGIC_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_5 =  \
-@HAVE_MAGIC_TRUE@@HAVE_POSTPROCESSOR_TRUE@	demo$(EXEEXT) \
-@HAVE_MAGIC_TRUE@@HAVE_POSTPROCESSOR_TRUE@	demo_https$(EXEEXT)
-@ENABLE_DAUTH_TRUE@am__EXEEXT_6 = digest_auth_example$(EXEEXT)
-@ENABLE_BAUTH_TRUE@am__EXEEXT_7 = authorization_example$(EXEEXT)
-PROGRAMS = $(noinst_PROGRAMS)
-am_authorization_example_OBJECTS = authorization_example.$(OBJEXT)
-authorization_example_OBJECTS = $(am_authorization_example_OBJECTS)
-authorization_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-am_benchmark_OBJECTS = benchmark-benchmark.$(OBJEXT)
-benchmark_OBJECTS = $(am_benchmark_OBJECTS)
-benchmark_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_benchmark_https_OBJECTS =  \
-	benchmark_https-benchmark_https.$(OBJEXT)
-benchmark_https_OBJECTS = $(am_benchmark_https_OBJECTS)
-benchmark_https_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_chunked_example_OBJECTS = chunked_example.$(OBJEXT)
-chunked_example_OBJECTS = $(am_chunked_example_OBJECTS)
-chunked_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_demo_OBJECTS = demo-demo.$(OBJEXT)
-demo_OBJECTS = $(am_demo_OBJECTS)
-am__DEPENDENCIES_1 =
-demo_DEPENDENCIES = $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1)
-demo_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(demo_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-am_demo_https_OBJECTS = demo_https-demo_https.$(OBJEXT)
-demo_https_OBJECTS = $(am_demo_https_OBJECTS)
-demo_https_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1)
-demo_https_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(demo_https_CFLAGS) \
-	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
-am_digest_auth_example_OBJECTS = digest_auth_example.$(OBJEXT)
-digest_auth_example_OBJECTS = $(am_digest_auth_example_OBJECTS)
-digest_auth_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_dual_stack_example_OBJECTS = dual_stack_example.$(OBJEXT)
-dual_stack_example_OBJECTS = $(am_dual_stack_example_OBJECTS)
-dual_stack_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_fileserver_example_OBJECTS = fileserver_example.$(OBJEXT)
-fileserver_example_OBJECTS = $(am_fileserver_example_OBJECTS)
-fileserver_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_fileserver_example_dirs_OBJECTS =  \
-	fileserver_example_dirs.$(OBJEXT)
-fileserver_example_dirs_OBJECTS =  \
-	$(am_fileserver_example_dirs_OBJECTS)
-fileserver_example_dirs_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_fileserver_example_external_select_OBJECTS =  \
-	fileserver_example_external_select.$(OBJEXT)
-fileserver_example_external_select_OBJECTS =  \
-	$(am_fileserver_example_external_select_OBJECTS)
-fileserver_example_external_select_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_https_fileserver_example_OBJECTS =  \
-	https_fileserver_example-https_fileserver_example.$(OBJEXT)
-https_fileserver_example_OBJECTS =  \
-	$(am_https_fileserver_example_OBJECTS)
-https_fileserver_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_mhd2spdy_OBJECTS = mhd2spdy.$(OBJEXT) mhd2spdy_spdy.$(OBJEXT) \
-	mhd2spdy_http.$(OBJEXT) mhd2spdy_structures.$(OBJEXT)
-mhd2spdy_OBJECTS = $(am_mhd2spdy_OBJECTS)
-mhd2spdy_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_minimal_example_OBJECTS = minimal_example.$(OBJEXT)
-minimal_example_OBJECTS = $(am_minimal_example_OBJECTS)
-minimal_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_minimal_example_comet_OBJECTS = minimal_example_comet.$(OBJEXT)
-minimal_example_comet_OBJECTS = $(am_minimal_example_comet_OBJECTS)
-minimal_example_comet_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_post_example_OBJECTS = post_example.$(OBJEXT)
-post_example_OBJECTS = $(am_post_example_OBJECTS)
-post_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_querystring_example_OBJECTS = querystring_example.$(OBJEXT)
-querystring_example_OBJECTS = $(am_querystring_example_OBJECTS)
-querystring_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_refuse_post_example_OBJECTS = refuse_post_example.$(OBJEXT)
-refuse_post_example_OBJECTS = $(am_refuse_post_example_OBJECTS)
-refuse_post_example_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_spdy_event_loop_OBJECTS = spdy_event_loop.$(OBJEXT)
-spdy_event_loop_OBJECTS = $(am_spdy_event_loop_OBJECTS)
-spdy_event_loop_DEPENDENCIES =  \
-	$(top_builddir)/src/microspdy/libmicrospdy.la
-am_spdy_fileserver_OBJECTS = spdy_fileserver.$(OBJEXT)
-spdy_fileserver_OBJECTS = $(am_spdy_fileserver_OBJECTS)
-spdy_fileserver_DEPENDENCIES =  \
-	$(top_builddir)/src/microspdy/libmicrospdy.la
-am_spdy_response_with_callback_OBJECTS =  \
-	spdy_response_with_callback.$(OBJEXT)
-spdy_response_with_callback_OBJECTS =  \
-	$(am_spdy_response_with_callback_OBJECTS)
-spdy_response_with_callback_DEPENDENCIES =  \
-	$(top_builddir)/src/microspdy/libmicrospdy.la
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(authorization_example_SOURCES) $(benchmark_SOURCES) \
-	$(benchmark_https_SOURCES) $(chunked_example_SOURCES) \
-	$(demo_SOURCES) $(demo_https_SOURCES) \
-	$(digest_auth_example_SOURCES) $(dual_stack_example_SOURCES) \
-	$(fileserver_example_SOURCES) \
-	$(fileserver_example_dirs_SOURCES) \
-	$(fileserver_example_external_select_SOURCES) \
-	$(https_fileserver_example_SOURCES) $(mhd2spdy_SOURCES) \
-	$(minimal_example_SOURCES) $(minimal_example_comet_SOURCES) \
-	$(post_example_SOURCES) $(querystring_example_SOURCES) \
-	$(refuse_post_example_SOURCES) $(spdy_event_loop_SOURCES) \
-	$(spdy_fileserver_SOURCES) \
-	$(spdy_response_with_callback_SOURCES)
-DIST_SOURCES = $(authorization_example_SOURCES) $(benchmark_SOURCES) \
-	$(benchmark_https_SOURCES) $(chunked_example_SOURCES) \
-	$(demo_SOURCES) $(demo_https_SOURCES) \
-	$(digest_auth_example_SOURCES) $(dual_stack_example_SOURCES) \
-	$(fileserver_example_SOURCES) \
-	$(fileserver_example_dirs_SOURCES) \
-	$(fileserver_example_external_select_SOURCES) \
-	$(https_fileserver_example_SOURCES) $(mhd2spdy_SOURCES) \
-	$(minimal_example_SOURCES) $(minimal_example_comet_SOURCES) \
-	$(post_example_SOURCES) $(querystring_example_SOURCES) \
-	$(refuse_post_example_SOURCES) $(spdy_event_loop_SOURCES) \
-	$(spdy_fileserver_SOURCES) \
-	$(spdy_response_with_callback_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include \
-  -DDATA_DIR=\"$(top_srcdir)/src/datadir/\"
-
-AM_CFLAGS = @LIBGCRYPT_CFLAGS@ $(am__append_1) $(am__append_8)
-CPU_COUNT_DEF = -DCPU_COUNT=$(CPU_COUNT)
-@ENABLE_SPDY_TRUE@spdyex = spdy_event_loop spdy_fileserver \
-@ENABLE_SPDY_TRUE@	spdy_response_with_callback $(am__append_2)
-minimal_example_SOURCES = \
- minimal_example.c
-
-minimal_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-chunked_example_SOURCES = \
- chunked_example.c
-
-chunked_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-demo_SOURCES = \
- demo.c
-
-demo_CFLAGS = \
- $(PTHREAD_CFLAGS) $(AM_CFLAGS)
-
-demo_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
-
-demo_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la  \
- $(PTHREAD_LIBS) -lmagic
-
-demo_https_SOURCES = \
- demo_https.c
-
-demo_https_CFLAGS = \
- $(PTHREAD_CFLAGS) $(AM_CFLAGS)
-
-demo_https_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
-
-demo_https_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la  \
- $(PTHREAD_LIBS) -lmagic
-
-mhd2spdy_SOURCES = \
- mhd2spdy.c \
- mhd2spdy_spdy.c mhd2spdy_spdy.h \
- mhd2spdy_http.c mhd2spdy_http.h \
- mhd2spdy_structures.c mhd2spdy_structures.h
-
-mhd2spdy_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la  \
- -lssl -lcrypto -lspdylay
-
-benchmark_SOURCES = \
- benchmark.c
-
-benchmark_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
-
-benchmark_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-benchmark_https_SOURCES = \
- benchmark_https.c
-
-benchmark_https_CPPFLAGS = \
- $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
-
-benchmark_https_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-dual_stack_example_SOURCES = \
- dual_stack_example.c
-
-dual_stack_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-post_example_SOURCES = \
- post_example.c
-
-post_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-minimal_example_comet_SOURCES = \
- minimal_example_comet.c
-
-minimal_example_comet_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-authorization_example_SOURCES = \
- authorization_example.c
-
-authorization_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-digest_auth_example_SOURCES = \
- digest_auth_example.c
-
-digest_auth_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-refuse_post_example_SOURCES = \
- refuse_post_example.c
-
-refuse_post_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-querystring_example_SOURCES = \
- querystring_example.c
-
-querystring_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-fileserver_example_SOURCES = \
- fileserver_example.c
-
-fileserver_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-fileserver_example_dirs_SOURCES = \
- fileserver_example_dirs.c
-
-fileserver_example_dirs_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-fileserver_example_external_select_SOURCES = \
- fileserver_example_external_select.c
-
-fileserver_example_external_select_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-https_fileserver_example_SOURCES = \
-https_fileserver_example.c
-
-https_fileserver_example_CPPFLAGS = \
- $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
-
-https_fileserver_example_LDADD = \
- $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-spdy_event_loop_SOURCES = \
- spdy_event_loop.c
-
-spdy_event_loop_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-spdy_fileserver_SOURCES = \
- spdy_fileserver.c
-
-spdy_fileserver_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-spdy_response_with_callback_SOURCES = \
- spdy_response_with_callback.c
-
-spdy_response_with_callback_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/examples/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/examples/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-noinstPROGRAMS:
-	@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-authorization_example$(EXEEXT): $(authorization_example_OBJECTS) $(authorization_example_DEPENDENCIES) $(EXTRA_authorization_example_DEPENDENCIES) 
-	@rm -f authorization_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(authorization_example_OBJECTS) $(authorization_example_LDADD) $(LIBS)
-
-benchmark$(EXEEXT): $(benchmark_OBJECTS) $(benchmark_DEPENDENCIES) $(EXTRA_benchmark_DEPENDENCIES) 
-	@rm -f benchmark$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(benchmark_OBJECTS) $(benchmark_LDADD) $(LIBS)
-
-benchmark_https$(EXEEXT): $(benchmark_https_OBJECTS) $(benchmark_https_DEPENDENCIES) $(EXTRA_benchmark_https_DEPENDENCIES) 
-	@rm -f benchmark_https$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(benchmark_https_OBJECTS) $(benchmark_https_LDADD) $(LIBS)
-
-chunked_example$(EXEEXT): $(chunked_example_OBJECTS) $(chunked_example_DEPENDENCIES) $(EXTRA_chunked_example_DEPENDENCIES) 
-	@rm -f chunked_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(chunked_example_OBJECTS) $(chunked_example_LDADD) $(LIBS)
-
-demo$(EXEEXT): $(demo_OBJECTS) $(demo_DEPENDENCIES) $(EXTRA_demo_DEPENDENCIES) 
-	@rm -f demo$(EXEEXT)
-	$(AM_V_CCLD)$(demo_LINK) $(demo_OBJECTS) $(demo_LDADD) $(LIBS)
-
-demo_https$(EXEEXT): $(demo_https_OBJECTS) $(demo_https_DEPENDENCIES) $(EXTRA_demo_https_DEPENDENCIES) 
-	@rm -f demo_https$(EXEEXT)
-	$(AM_V_CCLD)$(demo_https_LINK) $(demo_https_OBJECTS) $(demo_https_LDADD) $(LIBS)
-
-digest_auth_example$(EXEEXT): $(digest_auth_example_OBJECTS) $(digest_auth_example_DEPENDENCIES) $(EXTRA_digest_auth_example_DEPENDENCIES) 
-	@rm -f digest_auth_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(digest_auth_example_OBJECTS) $(digest_auth_example_LDADD) $(LIBS)
-
-dual_stack_example$(EXEEXT): $(dual_stack_example_OBJECTS) $(dual_stack_example_DEPENDENCIES) $(EXTRA_dual_stack_example_DEPENDENCIES) 
-	@rm -f dual_stack_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(dual_stack_example_OBJECTS) $(dual_stack_example_LDADD) $(LIBS)
-
-fileserver_example$(EXEEXT): $(fileserver_example_OBJECTS) $(fileserver_example_DEPENDENCIES) $(EXTRA_fileserver_example_DEPENDENCIES) 
-	@rm -f fileserver_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(fileserver_example_OBJECTS) $(fileserver_example_LDADD) $(LIBS)
-
-fileserver_example_dirs$(EXEEXT): $(fileserver_example_dirs_OBJECTS) $(fileserver_example_dirs_DEPENDENCIES) $(EXTRA_fileserver_example_dirs_DEPENDENCIES) 
-	@rm -f fileserver_example_dirs$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(fileserver_example_dirs_OBJECTS) $(fileserver_example_dirs_LDADD) $(LIBS)
-
-fileserver_example_external_select$(EXEEXT): $(fileserver_example_external_select_OBJECTS) $(fileserver_example_external_select_DEPENDENCIES) $(EXTRA_fileserver_example_external_select_DEPENDENCIES) 
-	@rm -f fileserver_example_external_select$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(fileserver_example_external_select_OBJECTS) $(fileserver_example_external_select_LDADD) $(LIBS)
-
-https_fileserver_example$(EXEEXT): $(https_fileserver_example_OBJECTS) $(https_fileserver_example_DEPENDENCIES) $(EXTRA_https_fileserver_example_DEPENDENCIES) 
-	@rm -f https_fileserver_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(https_fileserver_example_OBJECTS) $(https_fileserver_example_LDADD) $(LIBS)
-
-mhd2spdy$(EXEEXT): $(mhd2spdy_OBJECTS) $(mhd2spdy_DEPENDENCIES) $(EXTRA_mhd2spdy_DEPENDENCIES) 
-	@rm -f mhd2spdy$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(mhd2spdy_OBJECTS) $(mhd2spdy_LDADD) $(LIBS)
-
-minimal_example$(EXEEXT): $(minimal_example_OBJECTS) $(minimal_example_DEPENDENCIES) $(EXTRA_minimal_example_DEPENDENCIES) 
-	@rm -f minimal_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(minimal_example_OBJECTS) $(minimal_example_LDADD) $(LIBS)
-
-minimal_example_comet$(EXEEXT): $(minimal_example_comet_OBJECTS) $(minimal_example_comet_DEPENDENCIES) $(EXTRA_minimal_example_comet_DEPENDENCIES) 
-	@rm -f minimal_example_comet$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(minimal_example_comet_OBJECTS) $(minimal_example_comet_LDADD) $(LIBS)
-
-post_example$(EXEEXT): $(post_example_OBJECTS) $(post_example_DEPENDENCIES) $(EXTRA_post_example_DEPENDENCIES) 
-	@rm -f post_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(post_example_OBJECTS) $(post_example_LDADD) $(LIBS)
-
-querystring_example$(EXEEXT): $(querystring_example_OBJECTS) $(querystring_example_DEPENDENCIES) $(EXTRA_querystring_example_DEPENDENCIES) 
-	@rm -f querystring_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(querystring_example_OBJECTS) $(querystring_example_LDADD) $(LIBS)
-
-refuse_post_example$(EXEEXT): $(refuse_post_example_OBJECTS) $(refuse_post_example_DEPENDENCIES) $(EXTRA_refuse_post_example_DEPENDENCIES) 
-	@rm -f refuse_post_example$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(refuse_post_example_OBJECTS) $(refuse_post_example_LDADD) $(LIBS)
-
-spdy_event_loop$(EXEEXT): $(spdy_event_loop_OBJECTS) $(spdy_event_loop_DEPENDENCIES) $(EXTRA_spdy_event_loop_DEPENDENCIES) 
-	@rm -f spdy_event_loop$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(spdy_event_loop_OBJECTS) $(spdy_event_loop_LDADD) $(LIBS)
-
-spdy_fileserver$(EXEEXT): $(spdy_fileserver_OBJECTS) $(spdy_fileserver_DEPENDENCIES) $(EXTRA_spdy_fileserver_DEPENDENCIES) 
-	@rm -f spdy_fileserver$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(spdy_fileserver_OBJECTS) $(spdy_fileserver_LDADD) $(LIBS)
-
-spdy_response_with_callback$(EXEEXT): $(spdy_response_with_callback_OBJECTS) $(spdy_response_with_callback_DEPENDENCIES) $(EXTRA_spdy_response_with_callback_DEPENDENCIES) 
-	@rm -f spdy_response_with_callback$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(spdy_response_with_callback_OBJECTS) $(spdy_response_with_callback_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/authorization_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark-benchmark.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark_https-benchmark_https.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chunked_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo-demo.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_https-demo_https.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/digest_auth_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dual_stack_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example_dirs.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example_external_select.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd2spdy.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd2spdy_http.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd2spdy_spdy.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd2spdy_structures.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_comet.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/post_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/querystring_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/refuse_post_example.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spdy_event_loop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spdy_fileserver.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spdy_response_with_callback.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-benchmark-benchmark.o: benchmark.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark-benchmark.o -MD -MP -MF $(DEPDIR)/benchmark-benchmark.Tpo -c -o benchmark-benchmark.o `test -f 'benchmark.c' || echo '$(srcdir)/'`benchmark.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/benchmark-benchmark.Tpo $(DEPDIR)/benchmark-benchmark.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='benchmark.c' object='benchmark-benchmark.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark-benchmark.o `test -f 'benchmark.c' || echo '$(srcdir)/'`benchmark.c
-
-benchmark-benchmark.obj: benchmark.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark-benchmark.obj -MD -MP -MF $(DEPDIR)/benchmark-benchmark.Tpo -c -o benchmark-benchmark.obj `if test -f 'benchmark.c'; then $(CYGPATH_W) 'benchmark.c'; else $(CYGPATH_W) '$(srcdir)/benchmark.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/benchmark-benchmark.Tpo $(DEPDIR)/benchmark-benchmark.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='benchmark.c' object='benchmark-benchmark.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark-benchmark.obj `if test -f 'benchmark.c'; then $(CYGPATH_W) 'benchmark.c'; else $(CYGPATH_W) '$(srcdir)/benchmark.c'; fi`
-
-benchmark_https-benchmark_https.o: benchmark_https.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark_https-benchmark_https.o -MD -MP -MF $(DEPDIR)/benchmark_https-benchmark_https.Tpo -c -o benchmark_https-benchmark_https.o `test -f 'benchmark_https.c' || echo '$(srcdir)/'`benchmark_https.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/benchmark_https-benchmark_https.Tpo $(DEPDIR)/benchmark_https-benchmark_https.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='benchmark_https.c' object='benchmark_https-benchmark_https.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark_https-benchmark_https.o `test -f 'benchmark_https.c' || echo '$(srcdir)/'`benchmark_https.c
-
-benchmark_https-benchmark_https.obj: benchmark_https.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark_https-benchmark_https.obj -MD -MP -MF $(DEPDIR)/benchmark_https-benchmark_https.Tpo -c -o benchmark_https-benchmark_https.obj `if test -f 'benchmark_https.c'; then $(CYGPATH_W) 'benchmark_https.c'; else $(CYGPATH_W) '$(srcdir)/benchmark_https.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/benchmark_https-benchmark_https.Tpo $(DEPDIR)/benchmark_https-benchmark_https.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='benchmark_https.c' object='benchmark_https-benchmark_https.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark_https-benchmark_https.obj `if test -f 'benchmark_https.c'; then $(CYGPATH_W) 'benchmark_https.c'; else $(CYGPATH_W) '$(srcdir)/benchmark_https.c'; fi`
-
-demo-demo.o: demo.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -MT demo-demo.o -MD -MP -MF $(DEPDIR)/demo-demo.Tpo -c -o demo-demo.o `test -f 'demo.c' || echo '$(srcdir)/'`demo.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/demo-demo.Tpo $(DEPDIR)/demo-demo.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='demo.c' object='demo-demo.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -c -o demo-demo.o `test -f 'demo.c' || echo '$(srcdir)/'`demo.c
-
-demo-demo.obj: demo.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -MT demo-demo.obj -MD -MP -MF $(DEPDIR)/demo-demo.Tpo -c -o demo-demo.obj `if test -f 'demo.c'; then $(CYGPATH_W) 'demo.c'; else $(CYGPATH_W) '$(srcdir)/demo.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/demo-demo.Tpo $(DEPDIR)/demo-demo.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='demo.c' object='demo-demo.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -c -o demo-demo.obj `if test -f 'demo.c'; then $(CYGPATH_W) 'demo.c'; else $(CYGPATH_W) '$(srcdir)/demo.c'; fi`
-
-demo_https-demo_https.o: demo_https.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -MT demo_https-demo_https.o -MD -MP -MF $(DEPDIR)/demo_https-demo_https.Tpo -c -o demo_https-demo_https.o `test -f 'demo_https.c' || echo '$(srcdir)/'`demo_https.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/demo_https-demo_https.Tpo $(DEPDIR)/demo_https-demo_https.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='demo_https.c' object='demo_https-demo_https.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -c -o demo_https-demo_https.o `test -f 'demo_https.c' || echo '$(srcdir)/'`demo_https.c
-
-demo_https-demo_https.obj: demo_https.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -MT demo_https-demo_https.obj -MD -MP -MF $(DEPDIR)/demo_https-demo_https.Tpo -c -o demo_https-demo_https.obj `if test -f 'demo_https.c'; then $(CYGPATH_W) 'demo_https.c'; else $(CYGPATH_W) '$(srcdir)/demo_https.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/demo_https-demo_https.Tpo $(DEPDIR)/demo_https-demo_https.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='demo_https.c' object='demo_https-demo_https.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -c -o demo_https-demo_https.obj `if test -f 'demo_https.c'; then $(CYGPATH_W) 'demo_https.c'; else $(CYGPATH_W) '$(srcdir)/demo_https.c'; fi`
-
-https_fileserver_example-https_fileserver_example.o: https_fileserver_example.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT https_fileserver_example-https_fileserver_example.o -MD -MP -MF $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo -c -o https_fileserver_example-https_fileserver_example.o `test -f 'https_fileserver_example.c' || echo '$(srcdir)/'`https_fileserver_example.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo $(DEPDIR)/https_fileserver_example-https_fileserver_example.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='https_fileserver_example.c' object='https_fileserver_example-https_fileserver_example.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o https_fileserver_example-https_fileserver_example.o `test -f 'https_fileserver_example.c' || echo '$(srcdir)/'`https_fileserver_example.c
-
-https_fileserver_example-https_fileserver_example.obj: https_fileserver_example.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT https_fileserver_example-https_fileserver_example.obj -MD -MP -MF $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo -c -o https_fileserver_example-https_fileserver_example.obj `if test -f 'https_fileserver_example.c'; then $(CYGPATH_W) 'https_fileserver_example.c'; else $(CYGPATH_W) '$(srcdir)/https_fileserver_example.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo $(DEPDIR)/https_fileserver_example-https_fileserver_example.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='https_fileserver_example.c' object='https_fileserver_example-https_fileserver_example.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o https_fileserver_example-https_fileserver_example.obj `if test -f 'https_fileserver_example.c'; then $(CYGPATH_W) 'https_fileserver_example.c'; else $(CYGPATH_W) '$(srcdir)/https_fileserver_example.c'; fi`
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(PROGRAMS)
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \
-	mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-am clean clean-generic clean-libtool \
-	clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
-	uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/examples/authorization_example.c b/src/examples/authorization_example.c
index e6e69ad..fab6bd4 100644
--- a/src/examples/authorization_example.c
+++ b/src/examples/authorization_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,6 +22,7 @@
  * @file authorization_example.c
  * @brief example for how to use libmicrohttpd with HTTP authentication
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -32,77 +34,101 @@
 #include <windows.h>
 #endif
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
 
-#define DENIED "<html><head><title>Access denied</title></head><body>Access denied</body></html>"
+#define DENIED \
+  "<html><head><title>Access denied</title></head><body>Access denied</body></html>"
 
 
-
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
-  char *user;
-  char *pass;
+  enum MHD_Result ret;
+  struct MHD_BasicAuthInfo *auth_info;
   int fail;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
 
   /* require: "Aladdin" with password "open sesame" */
-  pass = NULL;
-  user = MHD_basic_auth_get_username_password (connection, &pass);
-  fail = ( (user == NULL) || (0 != strcmp (user, "Aladdin")) || (0 != strcmp (pass, "open sesame") ) );
+  auth_info = MHD_basic_auth_get_username_password3 (connection);
+  fail = ( (NULL == auth_info) ||
+           (strlen ("Aladdin") != auth_info->username_len) ||
+           (0 != memcmp (auth_info->username, "Aladdin",
+                         auth_info->username_len)) ||
+           /* The next check against NULL is optional,
+            * if 'password' is NULL then 'password_len' is always zero. */
+           (NULL == auth_info->password) ||
+           (strlen ("open sesame") != auth_info->password_len) ||
+           (0 != memcmp (auth_info->password, "open sesame",
+                         auth_info->password_len)) );
   if (fail)
   {
-      response = MHD_create_response_from_buffer (strlen (DENIED),
-						  (void *) DENIED, 
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_basic_auth_fail_response (connection,"TestRealm",response);
-    }
+    response =
+      MHD_create_response_from_buffer_static (strlen (DENIED),
+                                              (const void *) DENIED);
+    ret = MHD_queue_basic_auth_fail_response3 (connection,
+                                               "TestRealm",
+                                               MHD_NO,
+                                               response);
+  }
   else
-    {
-      response = MHD_create_response_from_buffer (strlen (me),
-						  (void *) me, 
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-    }
-
+  {
+    response =
+      MHD_create_response_from_buffer_static (strlen (PAGE),
+                                              (const void *) PAGE);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  }
+  if (NULL != auth_info)
+    MHD_free (auth_info);
   MHD_destroy_response (response);
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  unsigned int port;
 
-  if (argc != 3)
-    {
-      printf ("%s PORT SECONDS-TO-RUN\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE, MHD_OPTION_END);
+  if ( (argc != 2) ||
+       (1 != sscanf (argv[1], "%u", &port)) ||
+       (65535 < port) )
+  {
+    fprintf (stderr,
+             "%s PORT\n", argv[0]);
+    return 1;
+  }
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
-  sleep (atoi (argv[2]));
+  fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n");
+  (void) getc (stdin);
   MHD_stop_daemon (d);
   return 0;
 }
diff --git a/src/examples/benchmark.c b/src/examples/benchmark.c
index d287b2f..1e8361a 100644
--- a/src/examples/benchmark.c
+++ b/src/examples/benchmark.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2013 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,19 +21,28 @@
  * @file benchmark.c
  * @brief minimal code to benchmark MHD GET performance
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif /* HAVE_INTTYPES_H */
+#ifndef PRIu64
+#define PRIu64  "llu"
+#endif /* ! PRIu64 */
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
 
 
 #define SMALL (1024 * 128)
@@ -41,59 +51,58 @@
  * Number of threads to run in the thread pool.  Should (roughly) match
  * the number of cores on your system.
  */
-#define NUMBER_OF_THREADS CPU_COUNT
+#define NUMBER_OF_THREADS MHD_CPU_COUNT
 
 static unsigned int small_deltas[SMALL];
 
 static struct MHD_Response *response;
 
 
-
 /**
  * Signature of the callback used by MHD to notify the
  * application about completed requests.
  *
  * @param cls client-defined closure
  * @param connection connection handle
- * @param con_cls value as set by the last call to
+ * @param req_cls value as set by the last call to
  *        the MHD_AccessHandlerCallback
  * @param toe reason for request termination
  * @see MHD_OPTION_NOTIFY_COMPLETED
  */
 static void
 completed_callback (void *cls,
-		    struct MHD_Connection *connection,
-		    void **con_cls,
-		    enum MHD_RequestTerminationCode toe)
+                    struct MHD_Connection *connection,
+                    void **req_cls,
+                    enum MHD_RequestTerminationCode toe)
 {
-  struct timeval *tv = *con_cls;
+  struct timeval *tv = *req_cls;
   struct timeval tve;
   uint64_t delta;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == tv)
     return;
   gettimeofday (&tve, NULL);
 
-  delta = 0;
-  if (tve.tv_usec >= tv->tv_usec)
-    delta += (tve.tv_sec - tv->tv_sec) * 1000000LL
-      + (tve.tv_usec - tv->tv_usec);
-  else
-    delta += (tve.tv_sec - tv->tv_sec) * 1000000LL
-      - tv->tv_usec + tve.tv_usec;
+  delta = ((uint64_t) (tve.tv_sec - tv->tv_sec)) * 1000000LL
+          + (uint64_t) tve.tv_usec - (uint64_t) tv->tv_usec;
   if (delta < SMALL)
     small_deltas[delta]++;
   else
-    fprintf (stdout, "D: %llu 1\n", (unsigned long long) delta);
+    fprintf (stdout, "D: %" PRIu64 " 1\n", delta);
   free (tv);
 }
 
 
 static void *
 uri_logger_cb (void *cls,
-	       const char *uri)
+               const char *uri)
 {
   struct timeval *tv = malloc (sizeof (struct timeval));
+  (void) cls; /* Unused. Silent compiler warning. */
+  (void) uri; /* Unused. Silent compiler warning. */
 
   if (NULL != tv)
     gettimeofday (tv, NULL);
@@ -101,14 +110,21 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+  (void) req_cls;           /* Unused. Silent compiler warning. */
+
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
   return MHD_queue_response (connection, MHD_HTTP_OK, response);
@@ -120,40 +136,49 @@
 {
   struct MHD_Daemon *d;
   unsigned int i;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  response = MHD_create_response_from_buffer (strlen (PAGE),
-					      (void *) PAGE,
-					      MHD_RESPMEM_PERSISTENT);
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                     (const void *) PAGE);
 #if 0
   (void) MHD_add_response_header (response,
-				  MHD_HTTP_HEADER_CONNECTION,
-				  "close");
+                                  MHD_HTTP_HEADER_CONNECTION,
+                                  "close");
 #endif
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_SUPPRESS_DATE_NO_CLOCK
-#if EPOLL_SUPPORT
-			| MHD_USE_EPOLL_LINUX_ONLY | MHD_USE_EPOLL_TURBO
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_SUPPRESS_DATE_NO_CLOCK
+#ifdef EPOLL_SUPPORT
+                        | MHD_USE_EPOLL | MHD_USE_TURBO
 #endif
-			,
-                        atoi (argv[1]),
+                        ,
+                        (uint16_t) port,
                         NULL, NULL, &ahc_echo, NULL,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
-			MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS,
-			MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL,
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL,
-			MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000,
-			MHD_OPTION_END);
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_THREAD_POOL_SIZE, (unsigned
+                                                      int) NUMBER_OF_THREADS,
+                        MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL,
+                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
   (void) getc (stdin);
   MHD_stop_daemon (d);
   MHD_destroy_response (response);
-  for (i=0;i<SMALL;i++)
+  for (i = 0; i < SMALL; i++)
     if (0 != small_deltas[i])
-      fprintf (stdout, "D: %d %u\n", i, small_deltas[i]);
+      fprintf (stdout, "D: %u %u\n", i, small_deltas[i]);
   return 0;
 }
diff --git a/src/examples/benchmark_https.c b/src/examples/benchmark_https.c
index 735a913..3432552 100644
--- a/src/examples/benchmark_https.c
+++ b/src/examples/benchmark_https.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2013 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,19 +21,28 @@
  * @file benchmark_https.c
  * @brief minimal code to benchmark MHD GET performance with HTTPS
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif /* HAVE_INTTYPES_H */
+#ifndef PRIu64
+#define PRIu64  "llu"
+#endif /* ! PRIu64 */
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
 
 
 #define SMALL (1024 * 128)
@@ -41,59 +51,58 @@
  * Number of threads to run in the thread pool.  Should (roughly) match
  * the number of cores on your system.
  */
-#define NUMBER_OF_THREADS CPU_COUNT
+#define NUMBER_OF_THREADS MHD_CPU_COUNT
 
 static unsigned int small_deltas[SMALL];
 
 static struct MHD_Response *response;
 
 
-
 /**
  * Signature of the callback used by MHD to notify the
  * application about completed requests.
  *
  * @param cls client-defined closure
  * @param connection connection handle
- * @param con_cls value as set by the last call to
+ * @param req_cls value as set by the last call to
  *        the MHD_AccessHandlerCallback
  * @param toe reason for request termination
  * @see MHD_OPTION_NOTIFY_COMPLETED
  */
 static void
 completed_callback (void *cls,
-		    struct MHD_Connection *connection,
-		    void **con_cls,
-		    enum MHD_RequestTerminationCode toe)
+                    struct MHD_Connection *connection,
+                    void **req_cls,
+                    enum MHD_RequestTerminationCode toe)
 {
-  struct timeval *tv = *con_cls;
+  struct timeval *tv = *req_cls;
   struct timeval tve;
   uint64_t delta;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == tv)
     return;
   gettimeofday (&tve, NULL);
 
-  delta = 0;
-  if (tve.tv_usec >= tv->tv_usec)
-    delta += (tve.tv_sec - tv->tv_sec) * 1000000LL
-      + (tve.tv_usec - tv->tv_usec);
-  else
-    delta += (tve.tv_sec - tv->tv_sec) * 1000000LL
-      - tv->tv_usec + tve.tv_usec;
+  delta = ((uint64_t) (tve.tv_sec - tv->tv_sec)) * 1000000LL
+          + (uint64_t) tve.tv_usec - (uint64_t) tv->tv_usec;
   if (delta < SMALL)
     small_deltas[delta]++;
   else
-    fprintf (stdout, "D: %llu 1\n", (unsigned long long) delta);
+    fprintf (stdout, "D: %" PRIu64 " 1\n", delta);
   free (tv);
 }
 
 
 static void *
 uri_logger_cb (void *cls,
-	       const char *uri)
+               const char *uri)
 {
   struct timeval *tv = malloc (sizeof (struct timeval));
+  (void) cls; /* Unused. Silent compiler warning. */
+  (void) uri; /* Unused. Silent compiler warning. */
 
   if (NULL != tv)
     gettimeofday (tv, NULL);
@@ -101,14 +110,21 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+  (void) req_cls;           /* Unused. Silent compiler warning. */
+
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
   return MHD_queue_response (connection, MHD_HTTP_OK, response);
@@ -116,54 +132,69 @@
 
 
 /* test server key */
-const char srv_signed_key_pem[] = "-----BEGIN RSA PRIVATE KEY-----\n"
-  "MIIEowIBAAKCAQEAvfTdv+3fgvVTKRnP/HVNG81cr8TrUP/iiyuve/THMzvFXhCW\n"
-  "+K03KwEku55QvnUndwBfU/ROzLlv+5hotgiDRNFT3HxurmhouySBrJNJv7qWp8IL\n"
-  "q4sw32vo0fbMu5BZF49bUXK9L3kW2PdhTtSQPWHEzNrCxO+YgCilKHkY3vQNfdJ0\n"
-  "20Q5EAAEseD1YtWCIpRvJzYlZMpjYB1ubTl24kwrgOKUJYKqM4jmF4DVQp4oOK/6\n"
-  "QYGGh1QmHRPAy3CBII6sbb+sZT9cAqU6GYQVB35lm4XAgibXV6KgmpVxVQQ69U6x\n"
-  "yoOl204xuekZOaG9RUPId74Rtmwfi1TLbBzo2wIDAQABAoIBADu09WSICNq5cMe4\n"
-  "+NKCLlgAT1NiQpLls1gKRbDhKiHU9j8QWNvWWkJWrCya4QdUfLCfeddCMeiQmv3K\n"
-  "lJMvDs+5OjJSHFoOsGiuW2Ias7IjnIojaJalfBml6frhJ84G27IXmdz6gzOiTIer\n"
-  "DjeAgcwBaKH5WwIay2TxIaScl7AwHBauQkrLcyb4hTmZuQh6ArVIN6+pzoVuORXM\n"
-  "bpeNWl2l/HSN3VtUN6aCAKbN/X3o0GavCCMn5Fa85uJFsab4ss/uP+2PusU71+zP\n"
-  "sBm6p/2IbGvF5k3VPDA7X5YX61sukRjRBihY8xSnNYx1UcoOsX6AiPnbhifD8+xQ\n"
-  "Tlf8oJUCgYEA0BTfzqNpr9Wxw5/QXaSdw7S/0eP5a0C/nwURvmfSzuTD4equzbEN\n"
-  "d+dI/s2JMxrdj/I4uoAfUXRGaabevQIjFzC9uyE3LaOyR2zhuvAzX+vVcs6bSXeU\n"
-  "pKpCAcN+3Z3evMaX2f+z/nfSUAl2i4J2R+/LQAWJW4KwRky/m+cxpfUCgYEA6bN1\n"
-  "b73bMgM8wpNt6+fcmS+5n0iZihygQ2U2DEud8nZJL4Nrm1dwTnfZfJBnkGj6+0Q0\n"
-  "cOwj2KS0/wcEdJBP0jucU4v60VMhp75AQeHqidIde0bTViSRo3HWKXHBIFGYoU3T\n"
-  "LyPyKndbqsOObnsFXHn56Nwhr2HLf6nw4taGQY8CgYBoSW36FLCNbd6QGvLFXBGt\n"
-  "2lMhEM8az/K58kJ4WXSwOLtr6MD/WjNT2tkcy0puEJLm6BFCd6A6pLn9jaKou/92\n"
-  "SfltZjJPb3GUlp9zn5tAAeSSi7YMViBrfuFiHObij5LorefBXISLjuYbMwL03MgH\n"
-  "Ocl2JtA2ywMp2KFXs8GQWQKBgFyIVv5ogQrbZ0pvj31xr9HjqK6d01VxIi+tOmpB\n"
-  "4ocnOLEcaxX12BzprW55ytfOCVpF1jHD/imAhb3YrHXu0fwe6DXYXfZV4SSG2vB7\n"
-  "IB9z14KBN5qLHjNGFpMQXHSMek+b/ftTU0ZnPh9uEM5D3YqRLVd7GcdUhHvG8P8Q\n"
-  "C9aXAoGBAJtID6h8wOGMP0XYX5YYnhlC7dOLfk8UYrzlp3xhqVkzKthTQTj6wx9R\n"
-  "GtC4k7U1ki8oJsfcIlBNXd768fqDVWjYju5rzShMpo8OCTS6ipAblKjCxPPVhIpv\n"
-  "tWPlbSn1qj6wylstJ5/3Z+ZW5H4wIKp5jmLiioDhcP0L/Ex3Zx8O\n"
-  "-----END RSA PRIVATE KEY-----\n";
+static const char srv_signed_key_pem[] =
+  "-----BEGIN PRIVATE KEY-----\n\
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\
+rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\
+UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\
++sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\
+HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\
+CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\
+dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\
++SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\
+XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\
+znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\
+pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\
+D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\
+Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\
+pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\
+zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\
+pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\
+KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\
+W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\
+OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\
+XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\
+wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\
+ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\
+0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\
+ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\
+QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\
+qdJNJ1DkyUc9dN2cliX4R+rG\n\
+-----END PRIVATE KEY-----";
 
 /* test server CA signed certificates */
-const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n"
-  "MIIDGzCCAgWgAwIBAgIES0KCvTALBgkqhkiG9w0BAQUwFzEVMBMGA1UEAxMMdGVz\n"
-  "dF9jYV9jZXJ0MB4XDTEwMDEwNTAwMDcyNVoXDTQ1MDMxMjAwMDcyNVowFzEVMBMG\n"
-  "A1UEAxMMdGVzdF9jYV9jZXJ0MIIBHzALBgkqhkiG9w0BAQEDggEOADCCAQkCggEA\n"
-  "vfTdv+3fgvVTKRnP/HVNG81cr8TrUP/iiyuve/THMzvFXhCW+K03KwEku55QvnUn\n"
-  "dwBfU/ROzLlv+5hotgiDRNFT3HxurmhouySBrJNJv7qWp8ILq4sw32vo0fbMu5BZ\n"
-  "F49bUXK9L3kW2PdhTtSQPWHEzNrCxO+YgCilKHkY3vQNfdJ020Q5EAAEseD1YtWC\n"
-  "IpRvJzYlZMpjYB1ubTl24kwrgOKUJYKqM4jmF4DVQp4oOK/6QYGGh1QmHRPAy3CB\n"
-  "II6sbb+sZT9cAqU6GYQVB35lm4XAgibXV6KgmpVxVQQ69U6xyoOl204xuekZOaG9\n"
-  "RUPId74Rtmwfi1TLbBzo2wIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQM\n"
-  "MAoGCCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHIAAwHQYDVR0OBBYEFOFi4ilKOP1d\n"
-  "XHlWCMwmVKr7mgy8MB8GA1UdIwQYMBaAFP2olB4s2T/xuoQ5pT2RKojFwZo2MAsG\n"
-  "CSqGSIb3DQEBBQOCAQEAHVWPxazupbOkG7Did+dY9z2z6RjTzYvurTtEKQgzM2Vz\n"
-  "GQBA+3pZ3c5mS97fPIs9hZXfnQeelMeZ2XP1a+9vp35bJjZBBhVH+pqxjCgiUflg\n"
-  "A3Zqy0XwwVCgQLE2HyaU3DLUD/aeIFK5gJaOSdNTXZLv43K8kl4cqDbMeRpVTbkt\n"
-  "YmG4AyEOYRNKGTqMEJXJoxD5E3rBUNrVI/XyTjYrulxbNPcMWEHKNeeqWpKDYTFo\n"
-  "Bb01PCthGXiq/4A2RLAFosadzRa8SBpoSjPPfZ0b2w4MJpReHqKbR5+T2t6hzml6\n"
-  "4ToyOKPDmamiTuN5KzLN3cw7DQlvWMvqSOChPLnA3Q==\n"
-  "-----END CERTIFICATE-----\n";
+static const char srv_signed_cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n\
+MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\
+NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\
+c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\
+psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\
+atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\
+7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\
+n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\
+qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\
+kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\
+AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\
+c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\
+8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\
+IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\
+Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\
+X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\
+aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\
+HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\
+hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\
+18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\
+UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\
+B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\
+SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\
+WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\
+OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\
+/w0gW9EVWzFhsFeGEssi\n\
+-----END CERTIFICATE-----";
 
 
 int
@@ -171,37 +202,47 @@
 {
   struct MHD_Daemon *d;
   unsigned int i;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  response = MHD_create_response_from_buffer (strlen (PAGE),
-					      (void *) PAGE,
-					      MHD_RESPMEM_PERSISTENT);
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL
-#if EPOLL_SUPPORT
-			| MHD_USE_EPOLL_LINUX_ONLY  | MHD_USE_EPOLL_TURBO
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                     (const void *) PAGE);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+#ifdef EPOLL_SUPPORT
+                        | MHD_USE_EPOLL | MHD_USE_TURBO
 #endif
-			,
-                        atoi (argv[1]),
+                        ,
+                        (uint16_t) port,
                         NULL, NULL, &ahc_echo, NULL,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
-			MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS,
-			MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL,
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL,
-			MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_THREAD_POOL_SIZE, (unsigned
+                                                      int) NUMBER_OF_THREADS,
+                        MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL,
+                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000,
+                        /* Optionally, the gnutls_load_file() can be used to
+                           load the key and the certificate from file. */
                         MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
-			MHD_OPTION_END);
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
   (void) getc (stdin);
   MHD_stop_daemon (d);
   MHD_destroy_response (response);
-  for (i=0;i<SMALL;i++)
+  for (i = 0; i < SMALL; i++)
     if (0 != small_deltas[i])
-      fprintf (stdout, "D: %d %u\n", i, small_deltas[i]);
+      fprintf (stdout, "D: %u %u\n", i, small_deltas[i]);
   return 0;
 }
diff --git a/src/examples/chunked_example.c b/src/examples/chunked_example.c
index 08bb82d..12d07d9 100644
--- a/src/examples/chunked_example.c
+++ b/src/examples/chunked_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2015 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,73 +21,171 @@
  * @file chunked_example.c
  * @brief example for generating chunked encoding with libmicrohttpd
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 
+struct ResponseContentCallbackParam
+{
+  const char *response_data;
+  size_t response_size;
+};
+
 
 static ssize_t
 callback (void *cls,
           uint64_t pos,
           char *buf,
-          size_t max)
+          size_t buf_size)
 {
-  return MHD_CONTENT_READER_END_OF_STREAM;
+  size_t size_to_copy;
+  struct ResponseContentCallbackParam *const param =
+    (struct ResponseContentCallbackParam *) cls;
+
+  /* Note: 'pos' will never exceed size of transmitted data. */
+  /* You can use 'pos == param->response_size' in next check. */
+  if (pos >= param->response_size)
+  {   /* Whole response was sent. Signal end of response. */
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  }
+
+  /* Pseudo code.        *
+  if (data_not_ready)
+    {
+      // Callback will be called again on next loop.
+      // Consider suspending connection until data will be ready.
+      return 0;
+    }
+   * End of pseudo code. */
+  if (buf_size < (param->response_size - pos))
+    size_to_copy = buf_size;
+  else
+    size_to_copy = param->response_size - pos;
+
+  memcpy (buf, param->response_data + pos, size_to_copy);
+
+  /* Pseudo code.        *
+  if (error_preparing_response)
+    {
+      // Close connection with error.
+      return MHD_CONTENT_READER_END_WITH_ERROR;
+    }
+   * End of pseudo code. */
+  /* Return amount of data copied to buffer. */
+  /* The 'buf_size' is always smaller than SSIZE_MAX therefore it's safe
+   * to cast 'size_to_copy' to 'ssize_t'. */
+  /* assert (size_to_copy <= buf_size); */
+  return (ssize_t) size_to_copy;
 }
 
 
+static void
+free_callback_param (void *cls)
+{
+  free (cls);
+}
 
-static int
+
+static const char simple_response_text[] =
+  "<html><head><title>Simple response</title></head>"
+  "<body>Simple response text</body></html>";
+
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
 {
   static int aptr;
+  struct ResponseContentCallbackParam *callback_param;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+
+  callback_param = malloc (sizeof(struct ResponseContentCallbackParam));
+  if (NULL == callback_param)
+    return MHD_NO; /* Not enough memory. */
+
+  callback_param->response_data = simple_response_text;
+  callback_param->response_size = (sizeof(simple_response_text)
+                                   / sizeof(char)) - 1;
+
+  *req_cls = NULL;                  /* reset when done */
   response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
                                                 1024,
                                                 &callback,
-                                                NULL,
-                                                NULL);
+                                                callback_param,
+                                                &free_callback_param);
+  if (NULL == response)
+  {
+    free (callback_param);
+    return MHD_NO;
+  }
+  /* Enforce chunked response, even for non-keep-alive connection. */
+  if (MHD_NO == MHD_add_response_header (response,
+                                         MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                         "chunked"))
+  {
+    free (callback_param);
+    MHD_destroy_response (response);
+    return MHD_NO;
+  }
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (// MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | MHD_USE_POLL,
-			MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-			// MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG | MHD_USE_POLL,
-			// MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, NULL,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
-			MHD_OPTION_END);
-  if (d == NULL)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) ||
+       (port > UINT16_MAX) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+    /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    (uint16_t) port,
+    NULL, NULL,
+    &ahc_echo, NULL,
+    MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+    MHD_OPTION_END);
+  if (NULL == d)
     return 1;
   (void) getc (stdin);
   MHD_stop_daemon (d);
diff --git a/src/examples/connection_close.c b/src/examples/connection_close.c
new file mode 100644
index 0000000..de79d9f
--- /dev/null
+++ b/src/examples/connection_close.c
@@ -0,0 +1,128 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007 Christian Grothoff (and other contributing authors)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file connection_close.c
+ * @brief minimal example for connection close notifications
+ * @author Christian Grothoff
+ */
+
+#include "platform.h"
+#include <microhttpd.h>
+
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif /* HAVE_INTTYPES_H */
+#ifndef PRIu64
+#define PRIu64  "llu"
+#endif /* ! PRIu64 */
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+
+static int
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
+{
+  static int aptr;
+  const char *me = cls;
+  struct MHD_Response *response;
+  int ret;
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response = MHD_create_response_from_buffer_static (strlen (me),
+                                                     me);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+#include <x86intrin.h>
+
+static void
+request_completed (void *cls,
+                   struct MHD_Connection *connection,
+                   void **req_cls,
+                   enum MHD_RequestTerminationCode toe)
+{
+  fprintf (stderr,
+           "%" PRIu64 " - RC: %d\n",
+           (uint64_t) __rdtsc (),
+           toe);
+}
+
+
+static void
+connection_completed (void *cls,
+                      struct MHD_Connection *connection,
+                      void **socket_context,
+                      enum MHD_ConnectionNotificationCode toe)
+{
+  fprintf (stderr,
+           "%" PRIu64 " - CC: %d\n",
+           (uint64_t) __rdtsc (),
+           toe);
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  struct MHD_Daemon *d;
+
+  if (argc != 2)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    /* MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD
+    | MHD_USE_ERROR_LOG | MHD_USE_POLL, // | MHD_USE_ITC,
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    atoi (argv[1]),
+    NULL, NULL, &ahc_echo, PAGE,
+    MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL,
+    MHD_OPTION_NOTIFY_CONNECTION, &connection_completed, NULL,
+    MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+    MHD_OPTION_CLIENT_DISCIPLINE_LVL, (int) 1,
+    MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/examples/demo.c b/src/examples/demo.c
index 80ca09c..edce395 100644
--- a/src/examples/demo.c
+++ b/src/examples/demo.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2013 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -27,7 +28,9 @@
  *        run tests against.  Note that the number of threads may need
  *        to be adjusted depending on the number of available cores.
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
+#include "MHD_config.h"
 #include "platform.h"
 #include <microhttpd.h>
 #include <unistd.h>
@@ -35,74 +38,88 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <dirent.h>
+#ifdef MHD_HAVE_LIBMAGIC
 #include <magic.h>
+#endif /* MHD_HAVE_LIBMAGIC */
 #include <limits.h>
 #include <ctype.h>
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+#ifndef PATH_MAX
+/* Some platforms (namely: GNU Hurd) do no define PATH_MAX.
+   As it is only example for MHD, just use reasonable value for PATH_MAX. */
+#define PATH_MAX 16384
 #endif
 
 /**
  * Number of threads to run in the thread pool.  Should (roughly) match
  * the number of cores on your system.
  */
-#define NUMBER_OF_THREADS CPU_COUNT
+#define NUMBER_OF_THREADS MHD_CPU_COUNT
 
+#ifdef MHD_HAVE_LIBMAGIC
 /**
  * How many bytes of a file do we give to libmagic to determine the mime type?
  * 16k might be a bit excessive, but ought not hurt performance much anyway,
  * and should definitively be on the safe side.
  */
 #define MAGIC_HEADER_SIZE (16 * 1024)
+#endif /* MHD_HAVE_LIBMAGIC */
 
 
 /**
  * Page returned for file-not-found.
  */
-#define FILE_NOT_FOUND_PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
+#define FILE_NOT_FOUND_PAGE \
+  "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
 
 /**
  * Page returned for internal errors.
  */
-#define INTERNAL_ERROR_PAGE "<html><head><title>Internal error</title></head><body>Internal error</body></html>"
+#define INTERNAL_ERROR_PAGE \
+  "<html><head><title>Internal error</title></head><body>Internal error</body></html>"
 
 
 /**
  * Page returned for refused requests.
  */
-#define REQUEST_REFUSED_PAGE "<html><head><title>Request refused</title></head><body>Request refused (file exists?)</body></html>"
+#define REQUEST_REFUSED_PAGE \
+  "<html><head><title>Request refused</title></head><body>Request refused (file exists?)</body></html>"
 
 
 /**
  * Head of index page.
  */
-#define INDEX_PAGE_HEADER "<html>\n<head><title>Welcome</title></head>\n<body>\n"\
-   "<h1>Upload</h1>\n"\
-   "<form method=\"POST\" enctype=\"multipart/form-data\" action=\"/\">\n"\
-   "<dl><dt>Content type:</dt><dd>"\
-   "<input type=\"radio\" name=\"category\" value=\"books\">Book</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"images\">Image</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"music\">Music</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"software\">Software</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"videos\">Videos</input>\n"\
-   "<input type=\"radio\" name=\"category\" value=\"other\" checked>Other</input></dd>"\
-   "<dt>Language:</dt><dd>"\
-   "<input type=\"radio\" name=\"language\" value=\"no-lang\" checked>none</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"en\">English</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"de\">German</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"fr\">French</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"es\">Spanish</input></dd>\n"\
-   "<dt>File:</dt><dd>"\
-   "<input type=\"file\" name=\"upload\"/></dd></dl>"\
-   "<input type=\"submit\" value=\"Send!\"/>\n"\
-   "</form>\n"\
-   "<h1>Download</h1>\n"\
-   "<ol>\n"
+#define INDEX_PAGE_HEADER \
+  "<html>\n<head><title>Welcome</title></head>\n<body>\n" \
+  "<h1>Upload</h1>\n" \
+  "<form method=\"POST\" enctype=\"multipart/form-data\" action=\"/\">\n" \
+  "<dl><dt>Content type:</dt><dd>" \
+  "<input type=\"radio\" name=\"category\" value=\"books\">Book</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"images\">Image</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"music\">Music</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"software\">Software</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"videos\">Videos</input>\n" \
+  "<input type=\"radio\" name=\"category\" value=\"other\" checked>Other</input></dd>" \
+  "<dt>Language:</dt><dd>" \
+  "<input type=\"radio\" name=\"language\" value=\"no-lang\" checked>none</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"en\">English</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"de\">German</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"fr\">French</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"es\">Spanish</input></dd>\n" \
+  "<dt>File:</dt><dd>" \
+  "<input type=\"file\" name=\"upload\"/></dd></dl>" \
+  "<input type=\"submit\" value=\"Send!\"/>\n" \
+  "</form>\n" \
+  "<h1>Download</h1>\n" \
+  "<ol>\n"
 
 /**
  * Footer of index page.
@@ -114,16 +131,15 @@
  * NULL-terminated array of supported upload categories.  Should match HTML
  * in the form.
  */
-static const char * const categories[] =
-  {
-    "books",
-    "images",
-    "music",
-    "software",
-    "videos",
-    "other",
-    NULL,
-  };
+static const char *const categories[] = {
+  "books",
+  "images",
+  "music",
+  "software",
+  "videos",
+  "other",
+  NULL,
+};
 
 
 /**
@@ -147,15 +163,14 @@
  * NULL-terminated array of supported upload categories.  Should match HTML
  * in the form.
  */
-static const struct Language languages[] =
-  {
-    { "no-lang", "No language specified" },
-    { "en", "English" },
-    { "de", "German" },
-    { "fr", "French" },
-    { "es", "Spanish" },
-    { NULL, NULL },
-  };
+static const struct Language languages[] = {
+  { "no-lang", "No language specified" },
+  { "en", "English" },
+  { "de", "German" },
+  { "fr", "French" },
+  { "es", "Spanish" },
+  { NULL, NULL },
+};
 
 
 /**
@@ -183,14 +198,16 @@
  */
 static pthread_mutex_t mutex;
 
+#ifdef MHD_HAVE_LIBMAGIC
 /**
  * Global handle to MAGIC data.
  */
 static magic_t magic;
+#endif /* MHD_HAVE_LIBMAGIC */
 
 
 /**
- * Mark the given response as HTML for the brower.
+ * Mark the given response as HTML for the browser.
  *
  * @param response response to mark
  */
@@ -198,8 +215,8 @@
 mark_as_html (struct MHD_Response *response)
 {
   (void) MHD_add_response_header (response,
-				  MHD_HTTP_HEADER_CONTENT_TYPE,
-				  "text/html");
+                                  MHD_HTTP_HEADER_CONTENT_TYPE,
+                                  "text/html");
 }
 
 
@@ -248,11 +265,11 @@
  *
  * @param rdc where to store the list of files
  * @param dirname name of the directory to list
- * @return MHD_YES on success, MHD_NO on error
+ * @return #MHD_YES on success, #MHD_NO on error
  */
-static int
+static enum MHD_Result
 list_directory (struct ResponseDataContext *rdc,
-		const char *dirname)
+                const char *dirname)
 {
   char fullname[PATH_MAX];
   struct stat sbuf;
@@ -262,35 +279,41 @@
   if (NULL == (dir = opendir (dirname)))
     return MHD_NO;
   while (NULL != (de = readdir (dir)))
+  {
+    int res;
+    if ('.' == de->d_name[0])
+      continue;
+    if (sizeof (fullname) <= (unsigned int)
+        snprintf (fullname, sizeof (fullname),
+                  "%s/%s",
+                  dirname, de->d_name))
+      continue;  /* ugh, file too long? how can this be!? */
+    if (0 != stat (fullname, &sbuf))
+      continue;  /* ugh, failed to 'stat' */
+    if (! S_ISREG (sbuf.st_mode))
+      continue;  /* not a regular file, skip */
+    if (rdc->off + 1024 > rdc->buf_len)
     {
-      if ('.' == de->d_name[0])
-	continue;
-      if (sizeof (fullname) <= (size_t)
-	  snprintf (fullname, sizeof (fullname),
-		    "%s/%s",
-		    dirname, de->d_name))
-	continue; /* ugh, file too long? how can this be!? */
-      if (0 != stat (fullname, &sbuf))
-	continue; /* ugh, failed to 'stat' */
-      if (! S_ISREG (sbuf.st_mode))
-	continue; /* not a regular file, skip */
-      if (rdc->off + 1024 > rdc->buf_len)
-	{
-	  void *r;
+      void *r;
 
-	  if ( (2 * rdc->buf_len + 1024) < rdc->buf_len)
-	    break; /* more than SIZE_T _index_ size? Too big for us */
-	  rdc->buf_len = 2 * rdc->buf_len + 1024;
-	  if (NULL == (r = realloc (rdc->buf, rdc->buf_len)))
-	    break; /* out of memory */
-	  rdc->buf = r;
-	}
-      rdc->off += snprintf (&rdc->buf[rdc->off],
-			    rdc->buf_len - rdc->off,
-			    "<li><a href=\"/%s\">%s</a></li>\n",
-			    fullname,
-			    de->d_name);
+      if ( (2 * rdc->buf_len + 1024) < rdc->buf_len)
+        break; /* more than SIZE_T _index_ size? Too big for us */
+      rdc->buf_len = 2 * rdc->buf_len + 1024;
+      if (NULL == (r = realloc (rdc->buf, rdc->buf_len)))
+        break; /* out of memory */
+      rdc->buf = r;
     }
+    res = snprintf (&rdc->buf[rdc->off],
+                    rdc->buf_len - rdc->off,
+                    "<li><a href=\"/%s\">%s</a></li>\n",
+                    fullname,
+                    de->d_name);
+    if (0 >= res)
+      continue;  /* snprintf() error */
+    if (rdc->buf_len - rdc->off <= (size_t) res)
+      continue;  /* buffer too small?? */
+    rdc->off += (size_t) res;
+  }
   (void) closedir (dir);
   return MHD_YES;
 }
@@ -300,7 +323,7 @@
  * Re-scan our local directory and re-build the index.
  */
 static void
-update_directory ()
+update_directory (void)
 {
   static size_t initial_allocation = 32 * 1024; /* initial size for response buffer */
   struct MHD_Response *response;
@@ -311,68 +334,96 @@
   const char *category;
   char dir_name[128];
   struct stat sbuf;
+  int res;
+  size_t len;
 
   rdc.buf_len = initial_allocation;
   if (NULL == (rdc.buf = malloc (rdc.buf_len)))
-    {
-      update_cached_response (NULL);
-      return;
-    }
-  rdc.off = snprintf (rdc.buf, rdc.buf_len,
-		      "%s",
-		      INDEX_PAGE_HEADER);
-  for (language_idx = 0; NULL != languages[language_idx].dirname; language_idx++)
-    {
-      language = &languages[language_idx];
+  {
+    update_cached_response (NULL);
+    return;
+  }
+  len = strlen (INDEX_PAGE_HEADER);
+  if (rdc.buf_len <= len)
+  { /* buffer too small */
+    free (rdc.buf);
+    update_cached_response (NULL);
+    return;
+  }
+  memcpy (rdc.buf, INDEX_PAGE_HEADER, len);
+  rdc.off = len;
+  for (language_idx = 0; NULL != languages[language_idx].dirname;
+       language_idx++)
+  {
+    language = &languages[language_idx];
 
-      if (0 != stat (language->dirname, &sbuf))
-	continue; /* empty */
+    if (0 != stat (language->dirname, &sbuf))
+      continue; /* empty */
+    /* we ensured always +1k room, filenames are ~256 bytes,
+       so there is always still enough space for the header
+       without need for an additional reallocation check. */
+    res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
+                    "<h2>%s</h2>\n",
+                    language->longname);
+    if (0 >= res)
+      continue;  /* snprintf() error */
+    if (rdc.buf_len - rdc.off <= (size_t) res)
+      continue;  /* buffer too small?? */
+    rdc.off += (size_t) res;
+    for (category_idx = 0; NULL != categories[category_idx]; category_idx++)
+    {
+      category = categories[category_idx];
+      res = snprintf (dir_name, sizeof (dir_name),
+                      "%s/%s",
+                      language->dirname,
+                      category);
+      if ((0 >= res) || (sizeof (dir_name) <= (size_t) res))
+        continue;  /* cannot print dir name */
+      if (0 != stat (dir_name, &sbuf))
+        continue;  /* empty */
+
       /* we ensured always +1k room, filenames are ~256 bytes,
-	 so there is always still enough space for the header
-	 without need for an additional reallocation check. */
-      rdc.off += snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
-			   "<h2>%s</h2>\n",
-			   language->longname);
-      for (category_idx = 0; NULL != categories[category_idx]; category_idx++)
-	{
-	  category = categories[category_idx];
-	  snprintf (dir_name, sizeof (dir_name),
-		    "%s/%s",
-		    language->dirname,
-		    category);
-	  if (0 != stat (dir_name, &sbuf))
-	    continue; /* empty */
+         so there is always still enough space for the header
+         without need for an additional reallocation check. */
+      res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
+                      "<h3>%s</h3>\n",
+                      category);
+      if (0 >= res)
+        continue;  /* snprintf() error */
+      if (rdc.buf_len - rdc.off <= (size_t) res)
+        continue;  /* buffer too small?? */
+      rdc.off += (size_t) res;
 
-	  /* we ensured always +1k room, filenames are ~256 bytes,
-	     so there is always still enough space for the header
-	     without need for an additional reallocation check. */
-	  rdc.off += snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
-			       "<h3>%s</h3>\n",
-			       category);
-
-	  if (MHD_NO == list_directory (&rdc, dir_name))
-	    {
-	      free (rdc.buf);
-	      update_cached_response (NULL);
-	      return;
-	    }
-	}
+      if (MHD_NO == list_directory (&rdc, dir_name))
+      {
+        free (rdc.buf);
+        update_cached_response (NULL);
+        return;
+      }
     }
+  }
   /* we ensured always +1k room, filenames are ~256 bytes,
      so there is always still enough space for the footer
      without need for a final reallocation check. */
-  rdc.off += snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
-		       "%s",
-		       INDEX_PAGE_FOOTER);
+  len = strlen (INDEX_PAGE_FOOTER);
+  if (rdc.buf_len - rdc.off <= len)
+  { /* buffer too small */
+    free (rdc.buf);
+    update_cached_response (NULL);
+    return;
+  }
+  memcpy (rdc.buf, INDEX_PAGE_FOOTER, len);
+  rdc.off += len;
   initial_allocation = rdc.buf_len; /* remember for next time */
-  response = MHD_create_response_from_buffer (rdc.off,
-					      rdc.buf,
-					      MHD_RESPMEM_MUST_FREE);
+  response =
+    MHD_create_response_from_buffer_with_free_callback (rdc.off,
+                                                        rdc.buf,
+                                                        &free);
   mark_as_html (response);
-#if FORCE_CLOSE
+#ifdef FORCE_CLOSE
   (void) MHD_add_response_header (response,
-				  MHD_HTTP_HEADER_CONNECTION,
-				  "close");
+                                  MHD_HTTP_HEADER_CONNECTION,
+                                  "close");
 #endif
   update_cached_response (response);
 }
@@ -427,12 +478,12 @@
  * @param ret string to update, NULL or 0-terminated
  * @param data data to append
  * @param size number of bytes in 'data'
- * @return MHD_NO on allocation failure, MHD_YES on success
+ * @return #MHD_NO on allocation failure, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 do_append (char **ret,
-	   const char *data,
-	   size_t size)
+           const char *data,
+           size_t size)
 {
   char *buf;
   size_t old_len;
@@ -441,13 +492,18 @@
     old_len = 0;
   else
     old_len = strlen (*ret);
-  buf = malloc (old_len + size + 1);
-  if (NULL == buf)
+  if (NULL == (buf = malloc (old_len + size + 1)))
     return MHD_NO;
-  memcpy (buf, *ret, old_len);
   if (NULL != *ret)
+  {
+    memcpy (buf,
+            *ret,
+            old_len);
     free (*ret);
-  memcpy (&buf[old_len], data, size);
+  }
+  memcpy (&buf[old_len],
+          data,
+          size);
   buf[old_len + size] = '\0';
   *ret = buf;
   return MHD_YES;
@@ -470,120 +526,135 @@
  *              specified offset
  * @param off offset of data in the overall value
  * @param size number of bytes in data available
- * @return MHD_YES to continue iterating,
- *         MHD_NO to abort the iteration
+ * @return #MHD_YES to continue iterating,
+ *         #MHD_NO to abort the iteration
  */
-static int
+static enum MHD_Result
 process_upload_data (void *cls,
-		     enum MHD_ValueKind kind,
-		     const char *key,
-		     const char *filename,
-		     const char *content_type,
-		     const char *transfer_encoding,
-		     const char *data,
-		     uint64_t off,
-		     size_t size)
+                     enum MHD_ValueKind kind,
+                     const char *key,
+                     const char *filename,
+                     const char *content_type,
+                     const char *transfer_encoding,
+                     const char *data,
+                     uint64_t off,
+                     size_t size)
 {
   struct UploadContext *uc = cls;
-  int i;
+  size_t i;
+  int res;
+  (void) kind;              /* Unused. Silent compiler warning. */
+  (void) content_type;      /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; /* Unused. Silent compiler warning. */
+  (void) off;               /* Unused. Silent compiler warning. */
 
   if (0 == strcmp (key, "category"))
     return do_append (&uc->category, data, size);
   if (0 == strcmp (key, "language"))
     return do_append (&uc->language, data, size);
   if (0 != strcmp (key, "upload"))
-    {
-      fprintf (stderr,
-	       "Ignoring unexpected form value `%s'\n",
-	       key);
-      return MHD_YES; /* ignore */
-    }
+  {
+    fprintf (stderr,
+             "Ignoring unexpected form value `%s'\n",
+             key);
+    return MHD_YES;   /* ignore */
+  }
   if (NULL == filename)
-    {
-      fprintf (stderr, "No filename, aborting upload\n");
-      return MHD_NO; /* no filename, error */
-    }
+  {
+    fprintf (stderr, "No filename, aborting upload.\n");
+    return MHD_NO;   /* no filename, error */
+  }
   if ( (NULL == uc->category) ||
        (NULL == uc->language) )
+  {
+    fprintf (stderr,
+             "Missing form data for upload `%s'\n",
+             filename);
+    uc->response = request_refused_response;
+    return MHD_NO;
+  }
+  if (-1 == uc->fd)
+  {
+    char fn[PATH_MAX];
+
+    if ( (NULL != strstr (filename, "..")) ||
+         (NULL != strchr (filename, '/')) ||
+         (NULL != strchr (filename, '\\')) )
     {
-      fprintf (stderr,
-	       "Missing form data for upload `%s'\n",
-	       filename);
       uc->response = request_refused_response;
       return MHD_NO;
     }
-  if (-1 == uc->fd)
-    {
-      char fn[PATH_MAX];
-
-      if ( (NULL != strstr (filename, "..")) ||
-	   (NULL != strchr (filename, '/')) ||
-	   (NULL != strchr (filename, '\\')) )
-	{
-	  uc->response = request_refused_response;
-	  return MHD_NO;
-	}
-      /* create directories -- if they don't exist already */
+    /* create directories -- if they don't exist already */
 #ifdef WINDOWS
-      (void) mkdir (uc->language);
+    (void) mkdir (uc->language);
 #else
-      (void) mkdir (uc->language, S_IRWXU);
+    (void) mkdir (uc->language, S_IRWXU);
 #endif
-      snprintf (fn, sizeof (fn),
-		"%s/%s",
-		uc->language,
-		uc->category);
+    snprintf (fn, sizeof (fn),
+              "%s/%s",
+              uc->language,
+              uc->category);
 #ifdef WINDOWS
-      (void) mkdir (fn);
+    (void) mkdir (fn);
 #else
-      (void) mkdir (fn, S_IRWXU);
+    (void) mkdir (fn, S_IRWXU);
 #endif
-      /* open file */
-      snprintf (fn, sizeof (fn),
-		"%s/%s/%s",
-		uc->language,
-		uc->category,
-		filename);
-      for (i=strlen (fn)-1;i>=0;i--)
-	if (! isprint ((int) fn[i]))
-	  fn[i] = '_';
-      uc->fd = open (fn,
-		     O_CREAT | O_EXCL
-#if O_LARGEFILE
-		     | O_LARGEFILE
-#endif
-		     | O_WRONLY,
-		     S_IRUSR | S_IWUSR);
-      if (-1 == uc->fd)
-	{
-	  fprintf (stderr,
-		   "Error opening file `%s' for upload: %s\n",
-		   fn,
-		   strerror (errno));
-	  uc->response = request_refused_response;
-	  return MHD_NO;
-	}
-      uc->filename = strdup (fn);
-    }
-  if ( (0 != size) &&
-       (size != (size_t) write (uc->fd, data, size)) )
+    /* open file */
+    res = snprintf (fn, sizeof (fn),
+                    "%s/%s/%s",
+                    uc->language,
+                    uc->category,
+                    filename);
+    if ((0 >= res) || (sizeof (fn) <= (size_t) res))
     {
-      /* write failed; likely: disk full */
-      fprintf (stderr,
-	       "Error writing to file `%s': %s\n",
-	       uc->filename,
-	       strerror (errno));
-      uc->response = internal_error_response;
-      close (uc->fd);
-      uc->fd = -1;
-      if (NULL != uc->filename)
-	{
-	  unlink (uc->filename);
-	  free (uc->filename);
-	  uc->filename = NULL;
-	}
+      uc->response = request_refused_response;
       return MHD_NO;
     }
+    for (i = 0; i < (size_t) res; i++)
+      if (! isprint ((unsigned char) fn[i]))
+        fn[i] = '_';
+    uc->fd = open (fn,
+                   O_CREAT | O_EXCL
+#ifdef O_LARGEFILE
+                   | O_LARGEFILE
+#endif
+                   | O_WRONLY,
+                   S_IRUSR | S_IWUSR);
+    if (-1 == uc->fd)
+    {
+      fprintf (stderr,
+               "Error opening file `%s' for upload: %s\n",
+               fn,
+               strerror (errno));
+      uc->response = request_refused_response;
+      return MHD_NO;
+    }
+    uc->filename = strdup (fn);
+  }
+  if ( (0 != size) &&
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+       (size != (size_t) write (uc->fd, data, size))
+#else  /* Native W32 */
+       (size != (size_t) write (uc->fd, data, (unsigned int) size))
+#endif /* Native W32 */
+       )
+  {
+    /* write failed; likely: disk full */
+    fprintf (stderr,
+             "Error writing to file `%s': %s\n",
+             uc->filename,
+             strerror (errno));
+    uc->response = internal_error_response;
+    (void) close (uc->fd);
+    uc->fd = -1;
+    if (NULL != uc->filename)
+    {
+      unlink (uc->filename);
+      free (uc->filename);
+      uc->filename = NULL;
+    }
+    return MHD_NO;
+  }
   return MHD_YES;
 }
 
@@ -594,36 +665,39 @@
  *
  * @param cls client-defined closure, NULL
  * @param connection connection handle
- * @param con_cls value as set by the last call to
+ * @param req_cls value as set by the last call to
  *        the MHD_AccessHandlerCallback, points to NULL if this was
  *            not an upload
  * @param toe reason for request termination
  */
 static void
 response_completed_callback (void *cls,
-			     struct MHD_Connection *connection,
-			     void **con_cls,
-			     enum MHD_RequestTerminationCode toe)
+                             struct MHD_Connection *connection,
+                             void **req_cls,
+                             enum MHD_RequestTerminationCode toe)
 {
-  struct UploadContext *uc = *con_cls;
+  struct UploadContext *uc = *req_cls;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == uc)
     return; /* this request wasn't an upload request */
   if (NULL != uc->pp)
-    {
-      MHD_destroy_post_processor (uc->pp);
-      uc->pp = NULL;
-    }
+  {
+    MHD_destroy_post_processor (uc->pp);
+    uc->pp = NULL;
+  }
   if (-1 != uc->fd)
   {
     (void) close (uc->fd);
     if (NULL != uc->filename)
-      {
-	fprintf (stderr,
-		 "Upload of file `%s' failed (incomplete or aborted), removing file.\n",
-		 uc->filename);
-	(void) unlink (uc->filename);
-      }
+    {
+      fprintf (stderr,
+               "Upload of file `%s' failed (incomplete or aborted), removing file.\n",
+               uc->filename);
+      (void) unlink (uc->filename);
+    }
   }
   if (NULL != uc->filename)
     free (uc->filename);
@@ -635,22 +709,22 @@
  * Return the current directory listing.
  *
  * @param connection connection to return the directory for
- * @return MHD_YES on success, MHD_NO on error
+ * @return #MHD_YES on success, #MHD_NO on error
  */
-static int
+static enum MHD_Result
 return_directory_response (struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
 
   (void) pthread_mutex_lock (&mutex);
   if (NULL == cached_directory_response)
     ret = MHD_queue_response (connection,
-			      MHD_HTTP_INTERNAL_SERVER_ERROR,
-			      internal_error_response);
+                              MHD_HTTP_INTERNAL_SERVER_ERROR,
+                              internal_error_response);
   else
     ret = MHD_queue_response (connection,
-			      MHD_HTTP_OK,
-			      cached_directory_response);
+                              MHD_HTTP_OK,
+                              cached_directory_response);
   (void) pthread_mutex_unlock (&mutex);
   return ret;
 }
@@ -665,136 +739,173 @@
  * @param method GET, PUT, POST, etc.
  * @param version HTTP version
  * @param upload_data data from upload (PUT/POST)
- * @param upload_data_size number of bytes in "upload_data"
- * @param ptr our context
- * @return MHD_YES on success, MHD_NO to drop connection
+ * @param upload_data_size number of bytes in @a upload_data
+ * @param req_cls our context
+ * @return #MHD_YES on success, #MHD_NO to drop connection
  */
-static int
+static enum MHD_Result
 generate_page (void *cls,
-	       struct MHD_Connection *connection,
-	       const char *url,
-	       const char *method,
-	       const char *version,
-	       const char *upload_data,
-	       size_t *upload_data_size, void **ptr)
+               struct MHD_Connection *connection,
+               const char *url,
+               const char *method,
+               const char *version,
+               const char *upload_data,
+               size_t *upload_data_size, void **req_cls)
 {
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   int fd;
   struct stat buf;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (url, "/"))
+  {
+    /* should be file download */
+#ifdef MHD_HAVE_LIBMAGIC
+    char file_data[MAGIC_HEADER_SIZE];
+    ssize_t got;
+#endif /* MHD_HAVE_LIBMAGIC */
+    const char *mime;
+
+    if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) &&
+         (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) )
+      return MHD_NO;    /* unexpected method (we're not polite...) */
+    fd = -1;
+    if ( (NULL == strstr (&url[1], "..")) &&
+         ('/' != url[1]) )
     {
-      /* should be file download */
-      char file_data[MAGIC_HEADER_SIZE];
-      ssize_t got;
-      const char *mime;
-
-      if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
-	return MHD_NO;  /* unexpected method (we're not polite...) */
-      if ( (0 == stat (&url[1], &buf)) &&
-	   (NULL == strstr (&url[1], "..")) &&
-	   ('/' != url[1]))
-	fd = open (&url[1], O_RDONLY);
-      else
-	fd = -1;
-      if (-1 == fd)
-	return MHD_queue_response (connection,
-				   MHD_HTTP_NOT_FOUND,
-				   file_not_found_response);
-      /* read beginning of the file to determine mime type  */
-      got = read (fd, file_data, sizeof (file_data));
-      if (-1 != got)
-	mime = magic_buffer (magic, file_data, got);
-      else
-	mime = NULL;
-      (void) lseek (fd, 0, SEEK_SET);
-
-      if (NULL == (response = MHD_create_response_from_fd (buf.st_size,
-							   fd)))
-	{
-	  /* internal error (i.e. out of memory) */
-	  (void) close (fd);
-	  return MHD_NO;
-	}
-
-      /* add mime type if we had one */
-      if (NULL != mime)
-	(void) MHD_add_response_header (response,
-					MHD_HTTP_HEADER_CONTENT_TYPE,
-					mime);
-      ret = MHD_queue_response (connection,
-				MHD_HTTP_OK,
-				response);
-      MHD_destroy_response (response);
-      return ret;
+      fd = open (&url[1], O_RDONLY);
+      if ( (-1 != fd) &&
+           ( (0 != fstat (fd, &buf)) ||
+             (! S_ISREG (buf.st_mode)) ) )
+      {
+        (void) close (fd);
+        fd = -1;
+      }
     }
+    if (-1 == fd)
+      return MHD_queue_response (connection,
+                                 MHD_HTTP_NOT_FOUND,
+                                 file_not_found_response);
+#ifdef MHD_HAVE_LIBMAGIC
+    /* read beginning of the file to determine mime type  */
+    got = read (fd, file_data, sizeof (file_data));
+    (void) lseek (fd, 0, SEEK_SET);
+    if (-1 != got)
+      mime = magic_buffer (magic, file_data, got);
+    else
+#endif /* MHD_HAVE_LIBMAGIC */
+    mime = NULL;
+    {
+      /* Set mime-type by file-extension in some cases */
+      const char *ldot = strrchr (&url[1], '.');
+
+      if (NULL != ldot)
+      {
+        if (0 == strcasecmp (ldot,
+                             ".html"))
+          mime = "text/html";
+        if (0 == strcasecmp (ldot,
+                             ".css"))
+          mime = "text/css";
+        if (0 == strcasecmp (ldot,
+                             ".css3"))
+          mime = "text/css";
+        if (0 == strcasecmp (ldot,
+                             ".js"))
+          mime = "application/javascript";
+      }
+
+    }
+
+    if (NULL == (response = MHD_create_response_from_fd ((size_t) buf.st_size,
+                                                         fd)))
+    {
+      /* internal error (i.e. out of memory) */
+      (void) close (fd);
+      return MHD_NO;
+    }
+
+    /* add mime type if we had one */
+    if (NULL != mime)
+      (void) MHD_add_response_header (response,
+                                      MHD_HTTP_HEADER_CONTENT_TYPE,
+                                      mime);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+    return ret;
+  }
 
   if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-    {
-      /* upload! */
-      struct UploadContext *uc = *ptr;
+  {
+    /* upload! */
+    struct UploadContext *uc = *req_cls;
 
-      if (NULL == uc)
-	{
-	  if (NULL == (uc = malloc (sizeof (struct UploadContext))))
-	    return MHD_NO; /* out of memory, close connection */
-	  memset (uc, 0, sizeof (struct UploadContext));
-          uc->fd = -1;
-	  uc->connection = connection;
-	  uc->pp = MHD_create_post_processor (connection,
-					      64 * 1024 /* buffer size */,
-					      &process_upload_data, uc);
-	  if (NULL == uc->pp)
-	    {
-	      /* out of memory, close connection */
-	      free (uc);
-	      return MHD_NO;
-	    }
-	  *ptr = uc;
-	  return MHD_YES;
-	}
-      if (0 != *upload_data_size)
-	{
-	  if (NULL == uc->response)
-	    (void) MHD_post_process (uc->pp,
-				     upload_data,
-				     *upload_data_size);
-	  *upload_data_size = 0;
-	  return MHD_YES;
-	}
-      /* end of upload, finish it! */
-      MHD_destroy_post_processor (uc->pp);
-      uc->pp = NULL;
-      if (-1 != uc->fd)
-	{
-	  close (uc->fd);
-	  uc->fd = -1;
-	}
-      if (NULL != uc->response)
-	{
-	  return MHD_queue_response (connection,
-				     MHD_HTTP_FORBIDDEN,
-				     uc->response);
-	}
-      else
-	{
-	  update_directory ();
-	  return return_directory_response (connection);
-	}
+    if (NULL == uc)
+    {
+      if (NULL == (uc = malloc (sizeof (struct UploadContext))))
+        return MHD_NO; /* out of memory, close connection */
+      memset (uc, 0, sizeof (struct UploadContext));
+      uc->fd = -1;
+      uc->connection = connection;
+      uc->pp = MHD_create_post_processor (connection,
+                                          64 * 1024 /* buffer size */,
+                                          &process_upload_data, uc);
+      if (NULL == uc->pp)
+      {
+        /* out of memory, close connection */
+        free (uc);
+        return MHD_NO;
+      }
+      *req_cls = uc;
+      return MHD_YES;
     }
-  if (0 == strcmp (method, MHD_HTTP_METHOD_GET))
+    if (0 != *upload_data_size)
+    {
+      if (NULL == uc->response)
+        (void) MHD_post_process (uc->pp,
+                                 upload_data,
+                                 *upload_data_size);
+      *upload_data_size = 0;
+      return MHD_YES;
+    }
+    /* end of upload, finish it! */
+    MHD_destroy_post_processor (uc->pp);
+    uc->pp = NULL;
+    if (-1 != uc->fd)
+    {
+      close (uc->fd);
+      uc->fd = -1;
+    }
+    if (NULL != uc->response)
+    {
+      return MHD_queue_response (connection,
+                                 MHD_HTTP_FORBIDDEN,
+                                 uc->response);
+    }
+    else
+    {
+      update_directory ();
+      return return_directory_response (connection);
+    }
+  }
+  if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) ||
+       (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) )
   {
     return return_directory_response (connection);
   }
 
   /* unexpected request, refuse */
   return MHD_queue_response (connection,
-			     MHD_HTTP_FORBIDDEN,
-			     request_refused_response);
+                             MHD_HTTP_FORBIDDEN,
+                             request_refused_response);
 }
 
 
+#ifndef MINGW
 /**
  * Function called if we get a SIGPIPE. Does nothing.
  *
@@ -803,6 +914,7 @@
 static void
 catcher (int sig)
 {
+  (void) sig;  /* Unused. Silent compiler warning. */
   /* do nothing */
 }
 
@@ -810,9 +922,8 @@
 /**
  * setup handlers to ignore SIGPIPE.
  */
-#ifndef MINGW
 static void
-ignore_sigpipe ()
+ignore_sigpipe (void)
 {
   struct sigaction oldsig;
   struct sigaction sig;
@@ -828,6 +939,8 @@
     fprintf (stderr,
              "Failed to install SIGPIPE handler: %s\n", strerror (errno));
 }
+
+
 #endif
 
 
@@ -849,50 +962,54 @@
   if ( (argc != 2) ||
        (1 != sscanf (argv[1], "%u", &port)) ||
        (UINT16_MAX < port) )
-    {
-      fprintf (stderr,
-	       "%s PORT\n", argv[0]);
-      return 1;
-    }
-  #ifndef MINGW
+  {
+    fprintf (stderr,
+             "%s PORT\n", argv[0]);
+    return 1;
+  }
+#ifndef MINGW
   ignore_sigpipe ();
-  #endif
+#endif
+#ifdef MHD_HAVE_LIBMAGIC
   magic = magic_open (MAGIC_MIME_TYPE);
   (void) magic_load (magic, NULL);
+#endif /* MHD_HAVE_LIBMAGIC */
 
   (void) pthread_mutex_init (&mutex, NULL);
-  file_not_found_response = MHD_create_response_from_buffer (strlen (FILE_NOT_FOUND_PAGE),
-							     (void *) FILE_NOT_FOUND_PAGE,
-							     MHD_RESPMEM_PERSISTENT);
+  file_not_found_response =
+    MHD_create_response_from_buffer_static (strlen (FILE_NOT_FOUND_PAGE),
+                                            (const void *) FILE_NOT_FOUND_PAGE);
   mark_as_html (file_not_found_response);
-  request_refused_response = MHD_create_response_from_buffer (strlen (REQUEST_REFUSED_PAGE),
-							     (void *) REQUEST_REFUSED_PAGE,
-							     MHD_RESPMEM_PERSISTENT);
+  request_refused_response =
+    MHD_create_response_from_buffer_static (strlen (REQUEST_REFUSED_PAGE),
+                                            (const void *)
+                                            REQUEST_REFUSED_PAGE);
   mark_as_html (request_refused_response);
-  internal_error_response = MHD_create_response_from_buffer (strlen (INTERNAL_ERROR_PAGE),
-							     (void *) INTERNAL_ERROR_PAGE,
-							     MHD_RESPMEM_PERSISTENT);
+  internal_error_response =
+    MHD_create_response_from_buffer_static (strlen (INTERNAL_ERROR_PAGE),
+                                            (const void *) INTERNAL_ERROR_PAGE);
   mark_as_html (internal_error_response);
   update_directory ();
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG
-#if EPOLL_SUPPORT
-			| MHD_USE_EPOLL_LINUX_ONLY
-#endif
-			,
-                        port,
+  d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
                         NULL, NULL,
-			&generate_page, NULL,
-			MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024),
-#if PRODUCTION
-			MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64),
+                        &generate_page, NULL,
+                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256
+                                                                      * 1024),
+#ifdef PRODUCTION
+                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64),
 #endif
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */),
-			MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS,
-			MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL,
-			MHD_OPTION_END);
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned
+                                                        int) (120 /* seconds */),
+                        MHD_OPTION_THREAD_POOL_SIZE, (unsigned
+                                                      int) NUMBER_OF_THREADS,
+                        MHD_OPTION_NOTIFY_COMPLETED,
+                        &response_completed_callback, NULL,
+                        MHD_OPTION_END);
   if (NULL == d)
     return 1;
-  fprintf (stderr, "HTTP server running. Press ENTER to stop the server\n");
+  fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n");
   (void) getc (stdin);
   MHD_stop_daemon (d);
   MHD_destroy_response (file_not_found_response);
@@ -900,8 +1017,11 @@
   MHD_destroy_response (internal_error_response);
   update_cached_response (NULL);
   (void) pthread_mutex_destroy (&mutex);
+#ifdef MHD_HAVE_LIBMAGIC
   magic_close (magic);
+#endif /* MHD_HAVE_LIBMAGIC */
   return 0;
 }
 
+
 /* end of demo.c */
diff --git a/src/examples/demo_https.c b/src/examples/demo_https.c
index f34a715..56c746c 100644
--- a/src/examples/demo_https.c
+++ b/src/examples/demo_https.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2013 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -27,7 +28,10 @@
  *        run tests against.  Note that the number of threads may need
  *        to be adjusted depending on the number of available cores.
  *        Logic is identical to demo.c, just adds HTTPS support.
+ *        This demonstration uses key/cert stored in static string. Optionally,
+ *        use gnutls_load_file() to load them from file.
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "platform.h"
 #include <microhttpd.h>
@@ -36,74 +40,88 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <dirent.h>
+#ifdef MHD_HAVE_LIBMAGIC
 #include <magic.h>
+#endif /* MHD_HAVE_LIBMAGIC */
 #include <limits.h>
 #include <ctype.h>
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+#ifndef PATH_MAX
+/* Some platforms (namely: GNU Hurd) do no define PATH_MAX.
+   As it is only example for MHD, just use reasonable value for PATH_MAX. */
+#define PATH_MAX 16384
 #endif
 
 /**
  * Number of threads to run in the thread pool.  Should (roughly) match
  * the number of cores on your system.
  */
-#define NUMBER_OF_THREADS CPU_COUNT
+#define NUMBER_OF_THREADS MHD_CPU_COUNT
 
+#ifdef MHD_HAVE_LIBMAGIC
 /**
  * How many bytes of a file do we give to libmagic to determine the mime type?
  * 16k might be a bit excessive, but ought not hurt performance much anyway,
  * and should definitively be on the safe side.
  */
 #define MAGIC_HEADER_SIZE (16 * 1024)
+#endif /* MHD_HAVE_LIBMAGIC */
 
 
 /**
  * Page returned for file-not-found.
  */
-#define FILE_NOT_FOUND_PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
+#define FILE_NOT_FOUND_PAGE \
+  "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
 
 /**
  * Page returned for internal errors.
  */
-#define INTERNAL_ERROR_PAGE "<html><head><title>Internal error</title></head><body>Internal error</body></html>"
+#define INTERNAL_ERROR_PAGE \
+  "<html><head><title>Internal error</title></head><body>Internal error</body></html>"
 
 
 /**
  * Page returned for refused requests.
  */
-#define REQUEST_REFUSED_PAGE "<html><head><title>Request refused</title></head><body>Request refused (file exists?)</body></html>"
+#define REQUEST_REFUSED_PAGE \
+  "<html><head><title>Request refused</title></head><body>Request refused (file exists?)</body></html>"
 
 
 /**
  * Head of index page.
  */
-#define INDEX_PAGE_HEADER "<html>\n<head><title>Welcome</title></head>\n<body>\n"\
-   "<h1>Upload</h1>\n"\
-   "<form method=\"POST\" enctype=\"multipart/form-data\" action=\"/\">\n"\
-   "<dl><dt>Content type:</dt><dd>"\
-   "<input type=\"radio\" name=\"category\" value=\"books\">Book</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"images\">Image</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"music\">Music</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"software\">Software</input>"\
-   "<input type=\"radio\" name=\"category\" value=\"videos\">Videos</input>\n"\
-   "<input type=\"radio\" name=\"category\" value=\"other\" checked>Other</input></dd>"\
-   "<dt>Language:</dt><dd>"\
-   "<input type=\"radio\" name=\"language\" value=\"no-lang\" checked>none</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"en\">English</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"de\">German</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"fr\">French</input>"\
-   "<input type=\"radio\" name=\"language\" value=\"es\">Spanish</input></dd>\n"\
-   "<dt>File:</dt><dd>"\
-   "<input type=\"file\" name=\"upload\"/></dd></dl>"\
-   "<input type=\"submit\" value=\"Send!\"/>\n"\
-   "</form>\n"\
-   "<h1>Download</h1>\n"\
-   "<ol>\n"
+#define INDEX_PAGE_HEADER \
+  "<html>\n<head><title>Welcome</title></head>\n<body>\n" \
+  "<h1>Upload</h1>\n" \
+  "<form method=\"POST\" enctype=\"multipart/form-data\" action=\"/\">\n" \
+  "<dl><dt>Content type:</dt><dd>" \
+  "<input type=\"radio\" name=\"category\" value=\"books\">Book</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"images\">Image</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"music\">Music</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"software\">Software</input>" \
+  "<input type=\"radio\" name=\"category\" value=\"videos\">Videos</input>\n" \
+  "<input type=\"radio\" name=\"category\" value=\"other\" checked>Other</input></dd>" \
+  "<dt>Language:</dt><dd>" \
+  "<input type=\"radio\" name=\"language\" value=\"no-lang\" checked>none</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"en\">English</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"de\">German</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"fr\">French</input>" \
+  "<input type=\"radio\" name=\"language\" value=\"es\">Spanish</input></dd>\n" \
+  "<dt>File:</dt><dd>" \
+  "<input type=\"file\" name=\"upload\"/></dd></dl>" \
+  "<input type=\"submit\" value=\"Send!\"/>\n" \
+  "</form>\n" \
+  "<h1>Download</h1>\n" \
+  "<ol>\n"
 
 /**
  * Footer of index page.
@@ -115,16 +133,15 @@
  * NULL-terminated array of supported upload categories.  Should match HTML
  * in the form.
  */
-static const char * const categories[] =
-  {
-    "books",
-    "images",
-    "music",
-    "software",
-    "videos",
-    "other",
-    NULL,
-  };
+static const char *const categories[] = {
+  "books",
+  "images",
+  "music",
+  "software",
+  "videos",
+  "other",
+  NULL,
+};
 
 
 /**
@@ -148,15 +165,14 @@
  * NULL-terminated array of supported upload categories.  Should match HTML
  * in the form.
  */
-static const struct Language languages[] =
-  {
-    { "no-lang", "No language specified" },
-    { "en", "English" },
-    { "de", "German" },
-    { "fr", "French" },
-    { "es", "Spanish" },
-    { NULL, NULL },
-  };
+static const struct Language languages[] = {
+  { "no-lang", "No language specified" },
+  { "en", "English" },
+  { "de", "German" },
+  { "fr", "French" },
+  { "es", "Spanish" },
+  { NULL, NULL },
+};
 
 
 /**
@@ -184,14 +200,16 @@
  */
 static pthread_mutex_t mutex;
 
+#ifdef MHD_HAVE_LIBMAGIC
 /**
  * Global handle to MAGIC data.
  */
 static magic_t magic;
+#endif /* MHD_HAVE_LIBMAGIC */
 
 
 /**
- * Mark the given response as HTML for the brower.
+ * Mark the given response as HTML for the browser.
  *
  * @param response response to mark
  */
@@ -199,8 +217,8 @@
 mark_as_html (struct MHD_Response *response)
 {
   (void) MHD_add_response_header (response,
-				  MHD_HTTP_HEADER_CONTENT_TYPE,
-				  "text/html");
+                                  MHD_HTTP_HEADER_CONTENT_TYPE,
+                                  "text/html");
 }
 
 
@@ -251,9 +269,9 @@
  * @param dirname name of the directory to list
  * @return MHD_YES on success, MHD_NO on error
  */
-static int
+static enum MHD_Result
 list_directory (struct ResponseDataContext *rdc,
-		const char *dirname)
+                const char *dirname)
 {
   char fullname[PATH_MAX];
   struct stat sbuf;
@@ -263,35 +281,41 @@
   if (NULL == (dir = opendir (dirname)))
     return MHD_NO;
   while (NULL != (de = readdir (dir)))
+  {
+    int res;
+    if ('.' == de->d_name[0])
+      continue;
+    if (sizeof (fullname) <= (size_t)
+        snprintf (fullname, sizeof (fullname),
+                  "%s/%s",
+                  dirname, de->d_name))
+      continue;  /* ugh, file too long? how can this be!? */
+    if (0 != stat (fullname, &sbuf))
+      continue;  /* ugh, failed to 'stat' */
+    if (! S_ISREG (sbuf.st_mode))
+      continue;  /* not a regular file, skip */
+    if (rdc->off + 1024 > rdc->buf_len)
     {
-      if ('.' == de->d_name[0])
-	continue;
-      if (sizeof (fullname) <= (size_t)
-	  snprintf (fullname, sizeof (fullname),
-		    "%s/%s",
-		    dirname, de->d_name))
-	continue; /* ugh, file too long? how can this be!? */
-      if (0 != stat (fullname, &sbuf))
-	continue; /* ugh, failed to 'stat' */
-      if (! S_ISREG (sbuf.st_mode))
-	continue; /* not a regular file, skip */
-      if (rdc->off + 1024 > rdc->buf_len)
-	{
-	  void *r;
+      void *r;
 
-	  if ( (2 * rdc->buf_len + 1024) < rdc->buf_len)
-	    break; /* more than SIZE_T _index_ size? Too big for us */
-	  rdc->buf_len = 2 * rdc->buf_len + 1024;
-	  if (NULL == (r = realloc (rdc->buf, rdc->buf_len)))
-	    break; /* out of memory */
-	  rdc->buf = r;
-	}
-      rdc->off += snprintf (&rdc->buf[rdc->off],
-			    rdc->buf_len - rdc->off,
-			    "<li><a href=\"/%s\">%s</a></li>\n",
-			    fullname,
-			    de->d_name);
+      if ( (2 * rdc->buf_len + 1024) < rdc->buf_len)
+        break; /* more than SIZE_T _index_ size? Too big for us */
+      rdc->buf_len = 2 * rdc->buf_len + 1024;
+      if (NULL == (r = realloc (rdc->buf, rdc->buf_len)))
+        break; /* out of memory */
+      rdc->buf = r;
     }
+    res = snprintf (&rdc->buf[rdc->off],
+                    rdc->buf_len - rdc->off,
+                    "<li><a href=\"/%s\">%s</a></li>\n",
+                    fullname,
+                    de->d_name);
+    if (0 >= res)
+      continue;  /* snprintf() error */
+    if (rdc->buf_len - rdc->off <= (size_t) res)
+      continue;  /* buffer too small?? */
+    rdc->off += (size_t) res;
+  }
   (void) closedir (dir);
   return MHD_YES;
 }
@@ -301,7 +325,7 @@
  * Re-scan our local directory and re-build the index.
  */
 static void
-update_directory ()
+update_directory (void)
 {
   static size_t initial_allocation = 32 * 1024; /* initial size for response buffer */
   struct MHD_Response *response;
@@ -312,68 +336,96 @@
   const char *category;
   char dir_name[128];
   struct stat sbuf;
+  int res;
+  size_t len;
 
   rdc.buf_len = initial_allocation;
   if (NULL == (rdc.buf = malloc (rdc.buf_len)))
-    {
-      update_cached_response (NULL);
-      return;
-    }
-  rdc.off = snprintf (rdc.buf, rdc.buf_len,
-		      "%s",
-		      INDEX_PAGE_HEADER);
-  for (language_idx = 0; NULL != languages[language_idx].dirname; language_idx++)
-    {
-      language = &languages[language_idx];
+  {
+    update_cached_response (NULL);
+    return;
+  }
+  len = strlen (INDEX_PAGE_HEADER);
+  if (rdc.buf_len <= len)
+  { /* buffer too small */
+    free (rdc.buf);
+    update_cached_response (NULL);
+    return;
+  }
+  memcpy (rdc.buf, INDEX_PAGE_HEADER, len);
+  rdc.off = len;
+  for (language_idx = 0; NULL != languages[language_idx].dirname;
+       language_idx++)
+  {
+    language = &languages[language_idx];
 
-      if (0 != stat (language->dirname, &sbuf))
-	continue; /* empty */
+    if (0 != stat (language->dirname, &sbuf))
+      continue; /* empty */
+    /* we ensured always +1k room, filenames are ~256 bytes,
+       so there is always still enough space for the header
+       without need for an additional reallocation check. */
+    res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
+                    "<h2>%s</h2>\n",
+                    language->longname);
+    if (0 >= res)
+      continue;  /* snprintf() error */
+    if (rdc.buf_len - rdc.off <= (size_t) res)
+      continue;  /* buffer too small?? */
+    rdc.off += (size_t) res;
+    for (category_idx = 0; NULL != categories[category_idx]; category_idx++)
+    {
+      category = categories[category_idx];
+      res = snprintf (dir_name, sizeof (dir_name),
+                      "%s/%s",
+                      language->dirname,
+                      category);
+      if ((0 >= res) || (sizeof (dir_name) <= (size_t) res))
+        continue;  /* cannot print dir name */
+      if (0 != stat (dir_name, &sbuf))
+        continue;  /* empty */
+
       /* we ensured always +1k room, filenames are ~256 bytes,
-	 so there is always still enough space for the header
-	 without need for an additional reallocation check. */
-      rdc.off += snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
-			   "<h2>%s</h2>\n",
-			   language->longname);
-      for (category_idx = 0; NULL != categories[category_idx]; category_idx++)
-	{
-	  category = categories[category_idx];
-	  snprintf (dir_name, sizeof (dir_name),
-		    "%s/%s",
-		    language->dirname,
-		    category);
-	  if (0 != stat (dir_name, &sbuf))
-	    continue; /* empty */
+         so there is always still enough space for the header
+         without need for an additional reallocation check. */
+      res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
+                      "<h3>%s</h3>\n",
+                      category);
+      if (0 >= res)
+        continue;  /* snprintf() error */
+      if (rdc.buf_len - rdc.off <= (size_t) res)
+        continue;  /* buffer too small?? */
+      rdc.off += (size_t) res;
 
-	  /* we ensured always +1k room, filenames are ~256 bytes,
-	     so there is always still enough space for the header
-	     without need for an additional reallocation check. */
-	  rdc.off += snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
-			       "<h3>%s</h3>\n",
-			       category);
-
-	  if (MHD_NO == list_directory (&rdc, dir_name))
-	    {
-	      free (rdc.buf);
-	      update_cached_response (NULL);
-	      return;
-	    }
-	}
+      if (MHD_NO == list_directory (&rdc, dir_name))
+      {
+        free (rdc.buf);
+        update_cached_response (NULL);
+        return;
+      }
     }
+  }
   /* we ensured always +1k room, filenames are ~256 bytes,
      so there is always still enough space for the footer
      without need for a final reallocation check. */
-  rdc.off += snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off,
-		       "%s",
-		       INDEX_PAGE_FOOTER);
+  len = strlen (INDEX_PAGE_FOOTER);
+  if (rdc.buf_len - rdc.off <= len)
+  { /* buffer too small */
+    free (rdc.buf);
+    update_cached_response (NULL);
+    return;
+  }
+  memcpy (rdc.buf, INDEX_PAGE_FOOTER, len);
+  rdc.off += len;
   initial_allocation = rdc.buf_len; /* remember for next time */
-  response = MHD_create_response_from_buffer (rdc.off,
-					      rdc.buf,
-					      MHD_RESPMEM_MUST_FREE);
+  response =
+    MHD_create_response_from_buffer_with_free_callback (rdc.off,
+                                                        rdc.buf,
+                                                        &free);
   mark_as_html (response);
-#if FORCE_CLOSE
+#ifdef FORCE_CLOSE
   (void) MHD_add_response_header (response,
-				  MHD_HTTP_HEADER_CONNECTION,
-				  "close");
+                                  MHD_HTTP_HEADER_CONNECTION,
+                                  "close");
 #endif
   update_cached_response (response);
 }
@@ -428,12 +480,12 @@
  * @param ret string to update, NULL or 0-terminated
  * @param data data to append
  * @param size number of bytes in 'data'
- * @return MHD_NO on allocation failure, MHD_YES on success
+ * @return #MHD_NO on allocation failure, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 do_append (char **ret,
-	   const char *data,
-	   size_t size)
+           const char *data,
+           size_t size)
 {
   char *buf;
   size_t old_len;
@@ -442,13 +494,18 @@
     old_len = 0;
   else
     old_len = strlen (*ret);
-  buf = malloc (old_len + size + 1);
-  if (NULL == buf)
+  if (NULL == (buf = malloc (old_len + size + 1)))
     return MHD_NO;
-  memcpy (buf, *ret, old_len);
   if (NULL != *ret)
+  {
+    memcpy (buf,
+            *ret,
+            old_len);
     free (*ret);
-  memcpy (&buf[old_len], data, size);
+  }
+  memcpy (&buf[old_len],
+          data,
+          size);
   buf[old_len + size] = '\0';
   *ret = buf;
   return MHD_YES;
@@ -471,120 +528,135 @@
  *              specified offset
  * @param off offset of data in the overall value
  * @param size number of bytes in data available
- * @return MHD_YES to continue iterating,
- *         MHD_NO to abort the iteration
+ * @return #MHD_YES to continue iterating,
+ *         #MHD_NO to abort the iteration
  */
-static int
+static enum MHD_Result
 process_upload_data (void *cls,
-		     enum MHD_ValueKind kind,
-		     const char *key,
-		     const char *filename,
-		     const char *content_type,
-		     const char *transfer_encoding,
-		     const char *data,
-		     uint64_t off,
-		     size_t size)
+                     enum MHD_ValueKind kind,
+                     const char *key,
+                     const char *filename,
+                     const char *content_type,
+                     const char *transfer_encoding,
+                     const char *data,
+                     uint64_t off,
+                     size_t size)
 {
   struct UploadContext *uc = cls;
-  int i;
+  size_t i;
+  int res;
+  (void) kind;              /* Unused. Silent compiler warning. */
+  (void) content_type;      /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; /* Unused. Silent compiler warning. */
+  (void) off;               /* Unused. Silent compiler warning. */
 
   if (0 == strcmp (key, "category"))
     return do_append (&uc->category, data, size);
   if (0 == strcmp (key, "language"))
     return do_append (&uc->language, data, size);
   if (0 != strcmp (key, "upload"))
-    {
-      fprintf (stderr,
-	       "Ignoring unexpected form value `%s'\n",
-	       key);
-      return MHD_YES; /* ignore */
-    }
+  {
+    fprintf (stderr,
+             "Ignoring unexpected form value `%s'\n",
+             key);
+    return MHD_YES;   /* ignore */
+  }
   if (NULL == filename)
-    {
-      fprintf (stderr, "No filename, aborting upload\n");
-      return MHD_NO; /* no filename, error */
-    }
+  {
+    fprintf (stderr, "No filename, aborting upload.\n");
+    return MHD_NO;   /* no filename, error */
+  }
   if ( (NULL == uc->category) ||
        (NULL == uc->language) )
+  {
+    fprintf (stderr,
+             "Missing form data for upload `%s'\n",
+             filename);
+    uc->response = request_refused_response;
+    return MHD_NO;
+  }
+  if (-1 == uc->fd)
+  {
+    char fn[PATH_MAX];
+
+    if ( (NULL != strstr (filename, "..")) ||
+         (NULL != strchr (filename, '/')) ||
+         (NULL != strchr (filename, '\\')) )
     {
-      fprintf (stderr,
-	       "Missing form data for upload `%s'\n",
-	       filename);
       uc->response = request_refused_response;
       return MHD_NO;
     }
-  if (-1 == uc->fd)
-    {
-      char fn[PATH_MAX];
-
-      if ( (NULL != strstr (filename, "..")) ||
-	   (NULL != strchr (filename, '/')) ||
-	   (NULL != strchr (filename, '\\')) )
-	{
-	  uc->response = request_refused_response;
-	  return MHD_NO;
-	}
-      /* create directories -- if they don't exist already */
+    /* create directories -- if they don't exist already */
 #ifdef WINDOWS
-      (void) mkdir (uc->language);
+    (void) mkdir (uc->language);
 #else
-      (void) mkdir (uc->language, S_IRWXU);
+    (void) mkdir (uc->language, S_IRWXU);
 #endif
-      snprintf (fn, sizeof (fn),
-		"%s/%s",
-		uc->language,
-		uc->category);
+    snprintf (fn, sizeof (fn),
+              "%s/%s",
+              uc->language,
+              uc->category);
 #ifdef WINDOWS
-      (void) mkdir (fn);
+    (void) mkdir (fn);
 #else
-      (void) mkdir (fn, S_IRWXU);
+    (void) mkdir (fn, S_IRWXU);
 #endif
-      /* open file */
-      snprintf (fn, sizeof (fn),
-		"%s/%s/%s",
-		uc->language,
-		uc->category,
-		filename);
-      for (i=strlen (fn)-1;i>=0;i--)
-	if (! isprint ((int) fn[i]))
-	  fn[i] = '_';
-      uc->fd = open (fn,
-		     O_CREAT | O_EXCL
-#if O_LARGEFILE
-		     | O_LARGEFILE
-#endif
-		     | O_WRONLY,
-		     S_IRUSR | S_IWUSR);
-      if (-1 == uc->fd)
-	{
-	  fprintf (stderr,
-		   "Error opening file `%s' for upload: %s\n",
-		   fn,
-		   strerror (errno));
-	  uc->response = request_refused_response;
-	  return MHD_NO;
-	}
-      uc->filename = strdup (fn);
-    }
-  if ( (0 != size) &&
-       (size != (size_t) write (uc->fd, data, size)) )
+    /* open file */
+    res = snprintf (fn, sizeof (fn),
+                    "%s/%s/%s",
+                    uc->language,
+                    uc->category,
+                    filename);
+    if ((0 >= res) || (sizeof (fn) <= (size_t) res))
     {
-      /* write failed; likely: disk full */
-      fprintf (stderr,
-	       "Error writing to file `%s': %s\n",
-	       uc->filename,
-	       strerror (errno));
-      uc->response = internal_error_response;
-      close (uc->fd);
-      uc->fd = -1;
-      if (NULL != uc->filename)
-	{
-	  unlink (uc->filename);
-	  free (uc->filename);
-	  uc->filename = NULL;
-	}
+      uc->response = request_refused_response;
       return MHD_NO;
     }
+    for (i = 0; i < (size_t) res; i++)
+      if (! isprint ((unsigned char) fn[i]))
+        fn[i] = '_';
+    uc->fd = open (fn,
+                   O_CREAT | O_EXCL
+#ifdef O_LARGEFILE
+                   | O_LARGEFILE
+#endif
+                   | O_WRONLY,
+                   S_IRUSR | S_IWUSR);
+    if (-1 == uc->fd)
+    {
+      fprintf (stderr,
+               "Error opening file `%s' for upload: %s\n",
+               fn,
+               strerror (errno));
+      uc->response = request_refused_response;
+      return MHD_NO;
+    }
+    uc->filename = strdup (fn);
+  }
+  if ( (0 != size) &&
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+       (size != (size_t) write (uc->fd, data, size))
+#else  /* Native W32 */
+       (size != (size_t) write (uc->fd, data, (unsigned int) size))
+#endif /* Native W32 */
+       )
+  {
+    /* write failed; likely: disk full */
+    fprintf (stderr,
+             "Error writing to file `%s': %s\n",
+             uc->filename,
+             strerror (errno));
+    uc->response = internal_error_response;
+    (void) close (uc->fd);
+    uc->fd = -1;
+    if (NULL != uc->filename)
+    {
+      unlink (uc->filename);
+      free (uc->filename);
+      uc->filename = NULL;
+    }
+    return MHD_NO;
+  }
   return MHD_YES;
 }
 
@@ -595,36 +667,39 @@
  *
  * @param cls client-defined closure, NULL
  * @param connection connection handle
- * @param con_cls value as set by the last call to
+ * @param req_cls value as set by the last call to
  *        the MHD_AccessHandlerCallback, points to NULL if this was
  *            not an upload
  * @param toe reason for request termination
  */
 static void
 response_completed_callback (void *cls,
-			     struct MHD_Connection *connection,
-			     void **con_cls,
-			     enum MHD_RequestTerminationCode toe)
+                             struct MHD_Connection *connection,
+                             void **req_cls,
+                             enum MHD_RequestTerminationCode toe)
 {
-  struct UploadContext *uc = *con_cls;
+  struct UploadContext *uc = *req_cls;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == uc)
     return; /* this request wasn't an upload request */
   if (NULL != uc->pp)
-    {
-      MHD_destroy_post_processor (uc->pp);
-      uc->pp = NULL;
-    }
+  {
+    MHD_destroy_post_processor (uc->pp);
+    uc->pp = NULL;
+  }
   if (-1 != uc->fd)
   {
     (void) close (uc->fd);
     if (NULL != uc->filename)
-      {
-	fprintf (stderr,
-		 "Upload of file `%s' failed (incomplete or aborted), removing file.\n",
-		 uc->filename);
-	(void) unlink (uc->filename);
-      }
+    {
+      fprintf (stderr,
+               "Upload of file `%s' failed (incomplete or aborted), removing file.\n",
+               uc->filename);
+      (void) unlink (uc->filename);
+    }
   }
   if (NULL != uc->filename)
     free (uc->filename);
@@ -638,20 +713,20 @@
  * @param connection connection to return the directory for
  * @return MHD_YES on success, MHD_NO on error
  */
-static int
+static enum MHD_Result
 return_directory_response (struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
 
   (void) pthread_mutex_lock (&mutex);
   if (NULL == cached_directory_response)
     ret = MHD_queue_response (connection,
-			      MHD_HTTP_INTERNAL_SERVER_ERROR,
-			      internal_error_response);
+                              MHD_HTTP_INTERNAL_SERVER_ERROR,
+                              internal_error_response);
   else
     ret = MHD_queue_response (connection,
-			      MHD_HTTP_OK,
-			      cached_directory_response);
+                              MHD_HTTP_OK,
+                              cached_directory_response);
   (void) pthread_mutex_unlock (&mutex);
   return ret;
 }
@@ -667,123 +742,136 @@
  * @param version HTTP version
  * @param upload_data data from upload (PUT/POST)
  * @param upload_data_size number of bytes in "upload_data"
- * @param ptr our context
- * @return MHD_YES on success, MHD_NO to drop connection
+ * @param req_cls our context
+ * @return #MHD_YES on success, #MHD_NO to drop connection
  */
-static int
+static enum MHD_Result
 generate_page (void *cls,
-	       struct MHD_Connection *connection,
-	       const char *url,
-	       const char *method,
-	       const char *version,
-	       const char *upload_data,
-	       size_t *upload_data_size, void **ptr)
+               struct MHD_Connection *connection,
+               const char *url,
+               const char *method,
+               const char *version,
+               const char *upload_data,
+               size_t *upload_data_size, void **req_cls)
 {
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   int fd;
   struct stat buf;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (url, "/"))
+  {
+    /* should be file download */
+#ifdef MHD_HAVE_LIBMAGIC
+    char file_data[MAGIC_HEADER_SIZE];
+    ssize_t got;
+#endif /* MHD_HAVE_LIBMAGIC */
+    const char *mime;
+
+    if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+      return MHD_NO; /* unexpected method (we're not polite...) */
+    fd = -1;
+    if ( (NULL == strstr (&url[1], "..")) &&
+         ('/' != url[1]) )
     {
-      /* should be file download */
-      char file_data[MAGIC_HEADER_SIZE];
-      ssize_t got;
-      const char *mime;
-
-      if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
-	return MHD_NO;  /* unexpected method (we're not polite...) */
-      if ( (0 == stat (&url[1], &buf)) &&
-	   (NULL == strstr (&url[1], "..")) &&
-	   ('/' != url[1]))
-	fd = open (&url[1], O_RDONLY);
-      else
-	fd = -1;
-      if (-1 == fd)
-	return MHD_queue_response (connection,
-				   MHD_HTTP_NOT_FOUND,
-				   file_not_found_response);
-      /* read beginning of the file to determine mime type  */
-      got = read (fd, file_data, sizeof (file_data));
-      if (-1 != got)
-	mime = magic_buffer (magic, file_data, got);
-      else
-	mime = NULL;
-      (void) lseek (fd, 0, SEEK_SET);
-
-      if (NULL == (response = MHD_create_response_from_fd (buf.st_size,
-							   fd)))
-	{
-	  /* internal error (i.e. out of memory) */
-	  (void) close (fd);
-	  return MHD_NO;
-	}
-
-      /* add mime type if we had one */
-      if (NULL != mime)
-	(void) MHD_add_response_header (response,
-					MHD_HTTP_HEADER_CONTENT_TYPE,
-					mime);
-      ret = MHD_queue_response (connection,
-				MHD_HTTP_OK,
-				response);
-      MHD_destroy_response (response);
-      return ret;
+      fd = open (&url[1], O_RDONLY);
+      if ( (-1 != fd) &&
+           ( (0 != fstat (fd, &buf)) ||
+             (! S_ISREG (buf.st_mode)) ) )
+      {
+        (void) close (fd);
+        fd = -1;
+      }
     }
+    if (-1 == fd)
+      return MHD_queue_response (connection,
+                                 MHD_HTTP_NOT_FOUND,
+                                 file_not_found_response);
+#ifdef MHD_HAVE_LIBMAGIC
+    /* read beginning of the file to determine mime type  */
+    got = read (fd, file_data, sizeof (file_data));
+    (void) lseek (fd, 0, SEEK_SET);
+    if (-1 != got)
+      mime = magic_buffer (magic, file_data, got);
+    else
+#endif /* MHD_HAVE_LIBMAGIC */
+    mime = NULL;
+
+    if (NULL == (response = MHD_create_response_from_fd ((size_t) buf.st_size,
+                                                         fd)))
+    {
+      /* internal error (i.e. out of memory) */
+      (void) close (fd);
+      return MHD_NO;
+    }
+
+    /* add mime type if we had one */
+    if (NULL != mime)
+      (void) MHD_add_response_header (response,
+                                      MHD_HTTP_HEADER_CONTENT_TYPE,
+                                      mime);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+    return ret;
+  }
 
   if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-    {
-      /* upload! */
-      struct UploadContext *uc = *ptr;
+  {
+    /* upload! */
+    struct UploadContext *uc = *req_cls;
 
-      if (NULL == uc)
-	{
-	  if (NULL == (uc = malloc (sizeof (struct UploadContext))))
-	    return MHD_NO; /* out of memory, close connection */
-	  memset (uc, 0, sizeof (struct UploadContext));
-          uc->fd = -1;
-	  uc->connection = connection;
-	  uc->pp = MHD_create_post_processor (connection,
-					      64 * 1024 /* buffer size */,
-					      &process_upload_data, uc);
-	  if (NULL == uc->pp)
-	    {
-	      /* out of memory, close connection */
-	      free (uc);
-	      return MHD_NO;
-	    }
-	  *ptr = uc;
-	  return MHD_YES;
-	}
-      if (0 != *upload_data_size)
-	{
-	  if (NULL == uc->response)
-	    (void) MHD_post_process (uc->pp,
-				     upload_data,
-				     *upload_data_size);
-	  *upload_data_size = 0;
-	  return MHD_YES;
-	}
-      /* end of upload, finish it! */
-      MHD_destroy_post_processor (uc->pp);
-      uc->pp = NULL;
-      if (-1 != uc->fd)
-	{
-	  close (uc->fd);
-	  uc->fd = -1;
-	}
-      if (NULL != uc->response)
-	{
-	  return MHD_queue_response (connection,
-				     MHD_HTTP_FORBIDDEN,
-				     uc->response);
-	}
-      else
-	{
-	  update_directory ();
-	  return return_directory_response (connection);
-	}
+    if (NULL == uc)
+    {
+      if (NULL == (uc = malloc (sizeof (struct UploadContext))))
+        return MHD_NO; /* out of memory, close connection */
+      memset (uc, 0, sizeof (struct UploadContext));
+      uc->fd = -1;
+      uc->connection = connection;
+      uc->pp = MHD_create_post_processor (connection,
+                                          64 * 1024 /* buffer size */,
+                                          &process_upload_data, uc);
+      if (NULL == uc->pp)
+      {
+        /* out of memory, close connection */
+        free (uc);
+        return MHD_NO;
+      }
+      *req_cls = uc;
+      return MHD_YES;
     }
+    if (0 != *upload_data_size)
+    {
+      if (NULL == uc->response)
+        (void) MHD_post_process (uc->pp,
+                                 upload_data,
+                                 *upload_data_size);
+      *upload_data_size = 0;
+      return MHD_YES;
+    }
+    /* end of upload, finish it! */
+    MHD_destroy_post_processor (uc->pp);
+    uc->pp = NULL;
+    if (-1 != uc->fd)
+    {
+      close (uc->fd);
+      uc->fd = -1;
+    }
+    if (NULL != uc->response)
+    {
+      return MHD_queue_response (connection,
+                                 MHD_HTTP_FORBIDDEN,
+                                 uc->response);
+    }
+    else
+    {
+      update_directory ();
+      return return_directory_response (connection);
+    }
+  }
   if (0 == strcmp (method, MHD_HTTP_METHOD_GET))
   {
     return return_directory_response (connection);
@@ -791,11 +879,12 @@
 
   /* unexpected request, refuse */
   return MHD_queue_response (connection,
-			     MHD_HTTP_FORBIDDEN,
-			     request_refused_response);
+                             MHD_HTTP_FORBIDDEN,
+                             request_refused_response);
 }
 
 
+#ifndef MINGW
 /**
  * Function called if we get a SIGPIPE. Does nothing.
  *
@@ -804,6 +893,7 @@
 static void
 catcher (int sig)
 {
+  (void) sig;  /* Unused. Silent compiler warning. */
   /* do nothing */
 }
 
@@ -811,9 +901,8 @@
 /**
  * setup handlers to ignore SIGPIPE.
  */
-#ifndef MINGW
 static void
-ignore_sigpipe ()
+ignore_sigpipe (void)
 {
   struct sigaction oldsig;
   struct sigaction sig;
@@ -829,57 +918,74 @@
     fprintf (stderr,
              "Failed to install SIGPIPE handler: %s\n", strerror (errno));
 }
+
+
 #endif
 
 /* test server key */
-const char srv_signed_key_pem[] = "-----BEGIN RSA PRIVATE KEY-----\n"
-  "MIIEowIBAAKCAQEAvfTdv+3fgvVTKRnP/HVNG81cr8TrUP/iiyuve/THMzvFXhCW\n"
-  "+K03KwEku55QvnUndwBfU/ROzLlv+5hotgiDRNFT3HxurmhouySBrJNJv7qWp8IL\n"
-  "q4sw32vo0fbMu5BZF49bUXK9L3kW2PdhTtSQPWHEzNrCxO+YgCilKHkY3vQNfdJ0\n"
-  "20Q5EAAEseD1YtWCIpRvJzYlZMpjYB1ubTl24kwrgOKUJYKqM4jmF4DVQp4oOK/6\n"
-  "QYGGh1QmHRPAy3CBII6sbb+sZT9cAqU6GYQVB35lm4XAgibXV6KgmpVxVQQ69U6x\n"
-  "yoOl204xuekZOaG9RUPId74Rtmwfi1TLbBzo2wIDAQABAoIBADu09WSICNq5cMe4\n"
-  "+NKCLlgAT1NiQpLls1gKRbDhKiHU9j8QWNvWWkJWrCya4QdUfLCfeddCMeiQmv3K\n"
-  "lJMvDs+5OjJSHFoOsGiuW2Ias7IjnIojaJalfBml6frhJ84G27IXmdz6gzOiTIer\n"
-  "DjeAgcwBaKH5WwIay2TxIaScl7AwHBauQkrLcyb4hTmZuQh6ArVIN6+pzoVuORXM\n"
-  "bpeNWl2l/HSN3VtUN6aCAKbN/X3o0GavCCMn5Fa85uJFsab4ss/uP+2PusU71+zP\n"
-  "sBm6p/2IbGvF5k3VPDA7X5YX61sukRjRBihY8xSnNYx1UcoOsX6AiPnbhifD8+xQ\n"
-  "Tlf8oJUCgYEA0BTfzqNpr9Wxw5/QXaSdw7S/0eP5a0C/nwURvmfSzuTD4equzbEN\n"
-  "d+dI/s2JMxrdj/I4uoAfUXRGaabevQIjFzC9uyE3LaOyR2zhuvAzX+vVcs6bSXeU\n"
-  "pKpCAcN+3Z3evMaX2f+z/nfSUAl2i4J2R+/LQAWJW4KwRky/m+cxpfUCgYEA6bN1\n"
-  "b73bMgM8wpNt6+fcmS+5n0iZihygQ2U2DEud8nZJL4Nrm1dwTnfZfJBnkGj6+0Q0\n"
-  "cOwj2KS0/wcEdJBP0jucU4v60VMhp75AQeHqidIde0bTViSRo3HWKXHBIFGYoU3T\n"
-  "LyPyKndbqsOObnsFXHn56Nwhr2HLf6nw4taGQY8CgYBoSW36FLCNbd6QGvLFXBGt\n"
-  "2lMhEM8az/K58kJ4WXSwOLtr6MD/WjNT2tkcy0puEJLm6BFCd6A6pLn9jaKou/92\n"
-  "SfltZjJPb3GUlp9zn5tAAeSSi7YMViBrfuFiHObij5LorefBXISLjuYbMwL03MgH\n"
-  "Ocl2JtA2ywMp2KFXs8GQWQKBgFyIVv5ogQrbZ0pvj31xr9HjqK6d01VxIi+tOmpB\n"
-  "4ocnOLEcaxX12BzprW55ytfOCVpF1jHD/imAhb3YrHXu0fwe6DXYXfZV4SSG2vB7\n"
-  "IB9z14KBN5qLHjNGFpMQXHSMek+b/ftTU0ZnPh9uEM5D3YqRLVd7GcdUhHvG8P8Q\n"
-  "C9aXAoGBAJtID6h8wOGMP0XYX5YYnhlC7dOLfk8UYrzlp3xhqVkzKthTQTj6wx9R\n"
-  "GtC4k7U1ki8oJsfcIlBNXd768fqDVWjYju5rzShMpo8OCTS6ipAblKjCxPPVhIpv\n"
-  "tWPlbSn1qj6wylstJ5/3Z+ZW5H4wIKp5jmLiioDhcP0L/Ex3Zx8O\n"
-  "-----END RSA PRIVATE KEY-----\n";
+static const char srv_signed_key_pem[] =
+  "-----BEGIN PRIVATE KEY-----\n\
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\
+rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\
+UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\
++sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\
+HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\
+CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\
+dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\
++SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\
+XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\
+znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\
+pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\
+D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\
+Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\
+pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\
+zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\
+pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\
+KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\
+W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\
+OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\
+XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\
+wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\
+ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\
+0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\
+ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\
+QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\
+qdJNJ1DkyUc9dN2cliX4R+rG\n\
+-----END PRIVATE KEY-----";
 
 /* test server CA signed certificates */
-const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n"
-  "MIIDGzCCAgWgAwIBAgIES0KCvTALBgkqhkiG9w0BAQUwFzEVMBMGA1UEAxMMdGVz\n"
-  "dF9jYV9jZXJ0MB4XDTEwMDEwNTAwMDcyNVoXDTQ1MDMxMjAwMDcyNVowFzEVMBMG\n"
-  "A1UEAxMMdGVzdF9jYV9jZXJ0MIIBHzALBgkqhkiG9w0BAQEDggEOADCCAQkCggEA\n"
-  "vfTdv+3fgvVTKRnP/HVNG81cr8TrUP/iiyuve/THMzvFXhCW+K03KwEku55QvnUn\n"
-  "dwBfU/ROzLlv+5hotgiDRNFT3HxurmhouySBrJNJv7qWp8ILq4sw32vo0fbMu5BZ\n"
-  "F49bUXK9L3kW2PdhTtSQPWHEzNrCxO+YgCilKHkY3vQNfdJ020Q5EAAEseD1YtWC\n"
-  "IpRvJzYlZMpjYB1ubTl24kwrgOKUJYKqM4jmF4DVQp4oOK/6QYGGh1QmHRPAy3CB\n"
-  "II6sbb+sZT9cAqU6GYQVB35lm4XAgibXV6KgmpVxVQQ69U6xyoOl204xuekZOaG9\n"
-  "RUPId74Rtmwfi1TLbBzo2wIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQM\n"
-  "MAoGCCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHIAAwHQYDVR0OBBYEFOFi4ilKOP1d\n"
-  "XHlWCMwmVKr7mgy8MB8GA1UdIwQYMBaAFP2olB4s2T/xuoQ5pT2RKojFwZo2MAsG\n"
-  "CSqGSIb3DQEBBQOCAQEAHVWPxazupbOkG7Did+dY9z2z6RjTzYvurTtEKQgzM2Vz\n"
-  "GQBA+3pZ3c5mS97fPIs9hZXfnQeelMeZ2XP1a+9vp35bJjZBBhVH+pqxjCgiUflg\n"
-  "A3Zqy0XwwVCgQLE2HyaU3DLUD/aeIFK5gJaOSdNTXZLv43K8kl4cqDbMeRpVTbkt\n"
-  "YmG4AyEOYRNKGTqMEJXJoxD5E3rBUNrVI/XyTjYrulxbNPcMWEHKNeeqWpKDYTFo\n"
-  "Bb01PCthGXiq/4A2RLAFosadzRa8SBpoSjPPfZ0b2w4MJpReHqKbR5+T2t6hzml6\n"
-  "4ToyOKPDmamiTuN5KzLN3cw7DQlvWMvqSOChPLnA3Q==\n"
-  "-----END CERTIFICATE-----\n";
+static const char srv_signed_cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n\
+MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\
+NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\
+c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\
+psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\
+atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\
+7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\
+n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\
+qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\
+kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\
+AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\
+c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\
+8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\
+IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\
+Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\
+X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\
+aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\
+HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\
+hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\
+18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\
+UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\
+B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\
+SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\
+WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\
+OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\
+/w0gW9EVWzFhsFeGEssi\n\
+-----END CERTIFICATE-----";
 
 
 /**
@@ -900,52 +1006,58 @@
   if ( (argc != 2) ||
        (1 != sscanf (argv[1], "%u", &port)) ||
        (UINT16_MAX < port) )
-    {
-      fprintf (stderr,
-	       "%s PORT\n", argv[0]);
-      return 1;
-    }
+  {
+    fprintf (stderr,
+             "%s PORT\n", argv[0]);
+    return 1;
+  }
   #ifndef MINGW
   ignore_sigpipe ();
   #endif
+#ifdef MHD_HAVE_LIBMAGIC
   magic = magic_open (MAGIC_MIME_TYPE);
   (void) magic_load (magic, NULL);
+#endif /* MHD_HAVE_LIBMAGIC */
 
   (void) pthread_mutex_init (&mutex, NULL);
-  file_not_found_response = MHD_create_response_from_buffer (strlen (FILE_NOT_FOUND_PAGE),
-							     (void *) FILE_NOT_FOUND_PAGE,
-							     MHD_RESPMEM_PERSISTENT);
+  file_not_found_response =
+    MHD_create_response_from_buffer_static (strlen (FILE_NOT_FOUND_PAGE),
+                                            (const void *) FILE_NOT_FOUND_PAGE);
   mark_as_html (file_not_found_response);
-  request_refused_response = MHD_create_response_from_buffer (strlen (REQUEST_REFUSED_PAGE),
-							     (void *) REQUEST_REFUSED_PAGE,
-							     MHD_RESPMEM_PERSISTENT);
+  request_refused_response =
+    MHD_create_response_from_buffer_static (strlen (REQUEST_REFUSED_PAGE),
+                                            (const void *)
+                                            REQUEST_REFUSED_PAGE);
   mark_as_html (request_refused_response);
-  internal_error_response = MHD_create_response_from_buffer (strlen (INTERNAL_ERROR_PAGE),
-							     (void *) INTERNAL_ERROR_PAGE,
-							     MHD_RESPMEM_PERSISTENT);
+  internal_error_response =
+    MHD_create_response_from_buffer_static (strlen (INTERNAL_ERROR_PAGE),
+                                            (const void *) INTERNAL_ERROR_PAGE);
   mark_as_html (internal_error_response);
   update_directory ();
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | MHD_USE_SSL
-#if EPOLL_SUPPORT
-			| MHD_USE_EPOLL_LINUX_ONLY
-#endif
-			,
-                        port,
+  d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_ERROR_LOG | MHD_USE_TLS,
+                        (uint16_t) port,
                         NULL, NULL,
-			&generate_page, NULL,
-			MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024),
-#if PRODUCTION
-			MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64),
+                        &generate_page, NULL,
+                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256
+                                                                      * 1024),
+#ifdef PRODUCTION
+                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64),
 #endif
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */),
-			MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS,
-			MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned
+                                                        int) (120 /* seconds */),
+                        MHD_OPTION_THREAD_POOL_SIZE, (unsigned
+                                                      int) NUMBER_OF_THREADS,
+                        MHD_OPTION_NOTIFY_COMPLETED,
+                        &response_completed_callback, NULL,
+                        /* Optionally, the gnutls_load_file() can be used to
+                           load the key and the certificate from file. */
                         MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
-			MHD_OPTION_END);
+                        MHD_OPTION_END);
   if (NULL == d)
     return 1;
-  fprintf (stderr, "HTTP server running. Press ENTER to stop the server\n");
+  fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n");
   (void) getc (stdin);
   MHD_stop_daemon (d);
   MHD_destroy_response (file_not_found_response);
@@ -953,8 +1065,11 @@
   MHD_destroy_response (internal_error_response);
   update_cached_response (NULL);
   (void) pthread_mutex_destroy (&mutex);
+#ifdef MHD_HAVE_LIBMAGIC
   magic_close (magic);
+#endif /* MHD_HAVE_LIBMAGIC */
   return 0;
 }
 
+
 /* end of demo_https.c */
diff --git a/src/examples/digest_auth_example.c b/src/examples/digest_auth_example.c
index 62c99cf..db8a1f2 100644
--- a/src/examples/digest_auth_example.c
+++ b/src/examples/digest_auth_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2010 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,72 +21,95 @@
  * @file digest_auth_example.c
  * @brief minimal example for how to use digest auth with libmicrohttpd
  * @author Amr Ali
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 #include <stdlib.h>
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head>" \
+  "<body>Access granted</body></html>"
 
-#define DENIED "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
+#define DENIED \
+  "<html><head><title>libmicrohttpd demo</title></head>" \
+  "<body>Access denied</body></html>"
 
 #define MY_OPAQUE_STR "11733b200778ce33060f31c9af70a870ba96ddd4"
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   struct MHD_Response *response;
   char *username;
   const char *password = "testpass";
   const char *realm = "test@example.com";
-  int ret;
+  enum MHD_DigestAuthResult res_e;
+  enum MHD_Result ret;
+  static int already_called_marker;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) method;            /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
-  username = MHD_digest_auth_get_username(connection);
-  if (username == NULL)
-    {
-      response = MHD_create_response_from_buffer(strlen (DENIED),
-						 DENIED,
-						 MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 MY_OPAQUE_STR,
-					 response,
-					 MHD_NO);
-      MHD_destroy_response(response);
-      return ret;
-    }
-  ret = MHD_digest_auth_check(connection, realm,
-			      username,
-			      password,
-			      300);
-  free(username);
-  if ( (ret == MHD_INVALID_NONCE) ||
-       (ret == MHD_NO) )
-    {
-      response = MHD_create_response_from_buffer(strlen (DENIED),
-						 DENIED,
-						 MHD_RESPMEM_PERSISTENT);
-      if (NULL == response)
-	return MHD_NO;
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 MY_OPAQUE_STR,
-					 response,
-					 (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO);
-      MHD_destroy_response(response);
-      return ret;
-    }
-  response = MHD_create_response_from_buffer(strlen(PAGE), PAGE,
-					     MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
-  MHD_destroy_response(response);
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  username = MHD_digest_auth_get_username (connection);
+  if (NULL == username)
+  {
+    response =
+      MHD_create_response_from_buffer_static (strlen (DENIED),
+                                              DENIED);
+    ret = MHD_queue_auth_fail_response2 (connection, realm,
+                                         MY_OPAQUE_STR,
+                                         response,
+                                         MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    MHD_destroy_response (response);
+    return ret;
+  }
+  res_e = MHD_digest_auth_check3 (connection, realm,
+                                  username,
+                                  password,
+                                  300, 60, MHD_DIGEST_AUTH_MULT_QOP_AUTH,
+                                  MHD_DIGEST_AUTH_MULT_ALGO3_MD5);
+  MHD_free (username);
+  if (res_e != MHD_DAUTH_OK)
+  {
+    response =
+      MHD_create_response_from_buffer_static (strlen (DENIED),
+                                              DENIED);
+    if (NULL == response)
+      return MHD_NO;
+    ret = MHD_queue_auth_fail_response2 (connection, realm,
+                                         MY_OPAQUE_STR,
+                                         response,
+                                         (res_e == MHD_DAUTH_NONCE_STALE) ?
+                                         MHD_YES : MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    MHD_destroy_response (response);
+    return ret;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
@@ -94,42 +118,47 @@
   ssize_t len;
   size_t off;
   struct MHD_Daemon *d;
+  unsigned int port;
 
-  if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  fd = open("/dev/urandom", O_RDONLY);
+  if ( (argc != 2) ||
+       (1 != sscanf (argv[1], "%u", &port)) ||
+       (65535 < port) )
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+
+  fd = open ("/dev/urandom", O_RDONLY);
   if (-1 == fd)
-    {
-      fprintf (stderr, "Failed to open `%s': %s\n",
-	       "/dev/urandom",
-	       strerror (errno));
-      return 1;
-    }
+  {
+    fprintf (stderr, "Failed to open `%s': %s\n",
+             "/dev/urandom",
+             strerror (errno));
+    return 1;
+  }
   off = 0;
   while (off < 8)
+  {
+    len = read (fd, rnd, 8);
+    if (0 > len)
     {
-      len = read(fd, rnd, 8);
-      if (len == -1)
-	{
-	  fprintf (stderr, "Failed to read `%s': %s\n",
-		   "/dev/urandom",
-		   strerror (errno));
-	  (void) close (fd);
-	  return 1;
-	}
-      off += len;
+      fprintf (stderr, "Failed to read `%s': %s\n",
+               "/dev/urandom",
+               strerror (errno));
+      (void) close (fd);
+      return 1;
     }
-  (void) close(fd);
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE,
-			MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rnd), rnd,
-			MHD_OPTION_NONCE_NC_SIZE, 300,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
-			MHD_OPTION_END);
+    off += (size_t) len;
+  }
+  (void) close (fd);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rnd), rnd,
+                        MHD_OPTION_NONCE_NC_SIZE, 300,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
   (void) getc (stdin);
@@ -137,4 +166,5 @@
   return 0;
 }
 
+
 /* end of digest_auth_example.c */
diff --git a/src/examples/dual_stack_example.c b/src/examples/dual_stack_example.c
index 12d50f4..57a3b55 100644
--- a/src/examples/dual_stack_example.c
+++ b/src/examples/dual_stack_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2012 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,38 +21,49 @@
  * @file dual_stack_example.c
  * @brief how to use MHD with both IPv4 and IPv6 support (dual-stack)
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
 
-static int
+struct handler_param
+{
+  const char *response_page;
+};
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
-  const char *me = cls;
+  struct handler_param *param = (struct handler_param *) cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
-  response = MHD_create_response_from_buffer (strlen (me),
-					      (void *) me,
-					      MHD_RESPMEM_PERSISTENT);
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response =
+    MHD_create_response_from_buffer_static (strlen (param->response_page),
+                                            param->response_page);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
@@ -62,17 +74,28 @@
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  struct handler_param data_for_handler;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | MHD_USE_DUAL_STACK,
-			atoi (argv[1]),
-			NULL, NULL, &ahc_echo, PAGE,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
-			MHD_OPTION_END);
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  data_for_handler.response_page = PAGE;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | MHD_USE_DUAL_STACK,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, &data_for_handler,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_END);
   (void) getc (stdin);
   MHD_stop_daemon (d);
   return 0;
diff --git a/src/examples/fileserver_example.c b/src/examples/fileserver_example.c
index 8f5223a..ee80d63 100644
--- a/src/examples/fileserver_example.c
+++ b/src/examples/fileserver_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -16,101 +17,126 @@
      License along with this library; if not, write to the Free Software
      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
-
 /**
  * @file fileserver_example.c
  * @brief minimal example for how to use libmicrohttpd to serve files
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif /* HAVE_SYS_STAT_H */
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif /* HAVE_FCNTL_H */
 
-#define PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
+#define PAGE \
+  "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
-static ssize_t
-file_reader (void *cls, uint64_t pos, char *buf, size_t max)
-{
-  FILE *file = cls;
+#ifndef S_ISREG
+#define S_ISREG(x) (S_IFREG == (x & S_IFREG))
+#endif /* S_ISREG */
 
-  (void)  fseek (file, pos, SEEK_SET);
-  return fread (buf, 1, max, file);
-}
-
-static void
-free_callback (void *cls)
-{
-  FILE *file = cls;
-  fclose (file);
-}
-
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data,
-	  size_t *upload_data_size, void **ptr)
+          size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
   struct MHD_Response *response;
-  int ret;
-  FILE *file;
+  enum MHD_Result ret;
+  int fd;
   struct stat buf;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+  if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) &&
+       (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) )
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
-  if (0 == stat (&url[1], &buf))
-    file = fopen (&url[1], "rb");
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                 /* reset when done */
+  /* WARNING: direct usage of url as filename is for example only!
+   * NEVER pass received data directly as parameter to file manipulation
+   * functions. Always check validity of data before using.
+   */
+  if (NULL != strstr (url, "../")) /* Very simplified check! */
+    fd = -1;                       /* Do not allow usage of parent directories. */
   else
-    file = NULL;
-  if (file == NULL)
+    fd = open (url + 1, O_RDONLY);
+  if (-1 != fd)
+  {
+    if ( (0 != fstat (fd, &buf)) ||
+         (! S_ISREG (buf.st_mode)) )
     {
-      response = MHD_create_response_from_buffer (strlen (PAGE),
-						  (void *) PAGE,
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);
-      MHD_destroy_response (response);
+      /* not a regular file, refuse to serve */
+      if (0 != close (fd))
+        abort ();
+      fd = -1;
     }
+  }
+  if (-1 == fd)
+  {
+    response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                       PAGE);
+    ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);
+    MHD_destroy_response (response);
+  }
   else
+  {
+    response = MHD_create_response_from_fd64 ((uint64_t) buf.st_size, fd);
+    if (NULL == response)
     {
-      response = MHD_create_response_from_callback (buf.st_size, 32 * 1024,     /* 32k page size */
-                                                    &file_reader,
-                                                    file,
-                                                    &free_callback);
-      if (response == NULL)
-	{
-	  fclose (file);
-	  return MHD_NO;
-	}
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
+      if (0 != close (fd))
+        abort ();
+      return MHD_NO;
     }
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+  }
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE, MHD_OPTION_END);
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
   (void) getc (stdin);
diff --git a/src/examples/fileserver_example_dirs.c b/src/examples/fileserver_example_dirs.c
index 9d4a193..5ec6042 100644
--- a/src/examples/fileserver_example_dirs.c
+++ b/src/examples/fileserver_example_dirs.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -18,27 +19,39 @@
 */
 
 /**
- * @file fileserver_example.c
+ * @file fileserver_example_dirs.c
  * @brief example for how to use libmicrohttpd to serve files (with directory support)
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <dirent.h>
 #include <microhttpd.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
 
-#define PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
 static ssize_t
 file_reader (void *cls, uint64_t pos, char *buf, size_t max)
 {
-  FILE *file = cls;
+  FILE *file = (FILE *) cls;
+  size_t bytes_read;
 
-  (void) fseek (file, pos, SEEK_SET);
-  return fread (buf, 1, max, file);
+  /* 'fseek' may not support files larger 2GiB, depending on platform.
+   * For production code, make sure that 'pos' has valid values, supported by
+   * 'fseek', or use 'fseeko' or similar function. */
+  if (0 != fseek (file, (long) pos, SEEK_SET))
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  bytes_read = fread (buf, 1, max, file);
+  if (0 == bytes_read)
+    return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR :
+           MHD_CONTENT_READER_END_OF_STREAM;
+  return (ssize_t) bytes_read;
 }
 
+
 static void
 file_free_callback (void *cls)
 {
@@ -46,6 +59,7 @@
   fclose (file);
 }
 
+
 static void
 dir_free_callback (void *cls)
 {
@@ -54,124 +68,164 @@
     closedir (dir);
 }
 
+
 static ssize_t
 dir_reader (void *cls, uint64_t pos, char *buf, size_t max)
 {
   DIR *dir = cls;
   struct dirent *e;
+  int res;
 
   if (max < 512)
     return 0;
+  (void) pos; /* 'pos' is ignored as function return next one single entry per call. */
   do
-    {
-      e = readdir (dir);
-      if (e == NULL)
-        return MHD_CONTENT_READER_END_OF_STREAM;
+  {
+    e = readdir (dir);
+    if (e == NULL)
+      return MHD_CONTENT_READER_END_OF_STREAM;
   } while (e->d_name[0] == '.');
-  return snprintf (buf, max,
-		   "<a href=\"/%s\">%s</a><br>",
-		   e->d_name,
-		   e->d_name);
+  res = snprintf (buf, max,
+                  "<a href=\"/%s\">%s</a><br>",
+                  e->d_name,
+                  e->d_name);
+  if (0 >= res)
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  if (max < (size_t) res)
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  return (ssize_t) res;
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data,
-	  size_t *upload_data_size, void **ptr)
+          size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   FILE *file;
+  int fd;
   DIR *dir;
   struct stat buf;
   char emsg[1024];
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+
+  file = fopen (&url[1], "rb");
+  if (NULL != file)
+  {
+    fd = fileno (file);
+    if (-1 == fd)
     {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
+      (void) fclose (file);
+      return MHD_NO;     /* internal error */
     }
-  *ptr = NULL;                  /* reset when done */
-  if ( (0 == stat (&url[1], &buf)) &&
-       (S_ISREG (buf.st_mode)) )
-    file = fopen (&url[1], "rb");
-  else
-    file = NULL;
-  if (file == NULL)
+    if ( (0 != fstat (fd, &buf)) ||
+         (! S_ISREG (buf.st_mode)) )
     {
-      dir = opendir (".");
-      if (dir == NULL)
-	{
-	  /* most likely cause: more concurrent requests than  
-	     available file descriptors / 2 */
-	  snprintf (emsg,
-		    sizeof (emsg),
-		    "Failed to open directory `.': %s\n",
-		    strerror (errno));
-	  response = MHD_create_response_from_buffer (strlen (emsg),
-						      emsg,
-						      MHD_RESPMEM_MUST_COPY);
-	  if (response == NULL)
-	    return MHD_NO;	    
-	  ret = MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE, response);
-	  MHD_destroy_response (response);
-	}
-      else
-	{
-	  response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
-							32 * 1024,
-							&dir_reader,
-							dir,
-							&dir_free_callback);
-	  if (response == NULL)
-	    {
-	      closedir (dir);
-	      return MHD_NO;
-	    }
-	  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-	  MHD_destroy_response (response);
-	}
+      /* not a regular file, refuse to serve */
+      fclose (file);
+      file = NULL;
     }
-  else
+  }
+
+  if (NULL == file)
+  {
+    dir = opendir (".");
+    if (NULL == dir)
     {
-      response = MHD_create_response_from_callback (buf.st_size, 32 * 1024,     /* 32k page size */
-                                                    &file_reader,
-                                                    file,
-                                                    &file_free_callback);
-      if (response == NULL)
-	{
-	  fclose (file);
-	  return MHD_NO;
-	}
+      /* most likely cause: more concurrent requests than
+         available file descriptors / 2 */
+      snprintf (emsg,
+                sizeof (emsg),
+                "Failed to open directory `.': %s\n",
+                strerror (errno));
+      response = MHD_create_response_from_buffer (strlen (emsg),
+                                                  emsg,
+                                                  MHD_RESPMEM_MUST_COPY);
+      if (NULL == response)
+        return MHD_NO;
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_SERVICE_UNAVAILABLE,
+                                response);
+      MHD_destroy_response (response);
+    }
+    else
+    {
+      response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
+                                                    32 * 1024,
+                                                    &dir_reader,
+                                                    dir,
+                                                    &dir_free_callback);
+      if (NULL == response)
+      {
+        closedir (dir);
+        return MHD_NO;
+      }
       ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
       MHD_destroy_response (response);
     }
+  }
+  else
+  {
+    response = MHD_create_response_from_callback ((size_t) buf.st_size,
+                                                  32 * 1024, /* 32k page size */
+                                                  &file_reader,
+                                                  file,
+                                                  &file_free_callback);
+    if (NULL == response)
+    {
+      fclose (file);
+      return MHD_NO;
+    }
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+  }
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE, MHD_OPTION_END);
-  if (d == NULL)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  if (NULL == d)
     return 1;
   (void) getc (stdin);
   MHD_stop_daemon (d);
diff --git a/src/examples/fileserver_example_external_select.c b/src/examples/fileserver_example_external_select.c
index 7a27061..192e00d 100644
--- a/src/examples/fileserver_example_external_select.c
+++ b/src/examples/fileserver_example_external_select.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,6 +21,7 @@
  * @file fileserver_example_external_select.c
  * @brief minimal example for how to use libmicrohttpd to server files
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -27,17 +29,28 @@
 #include <sys/stat.h>
 #include <unistd.h>
 
-#define PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
+#define PAGE \
+  "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
 static ssize_t
 file_reader (void *cls, uint64_t pos, char *buf, size_t max)
 {
-  FILE *file = cls;
+  FILE *file = (FILE *) cls;
+  size_t bytes_read;
 
-  (void) fseek (file, pos, SEEK_SET);
-  return fread (buf, 1, max, file);
+  /* 'fseek' may not support files larger 2GiB, depending on platform.
+   * For production code, make sure that 'pos' has valid values, supported by
+   * 'fseek', or use 'fseeko' or similar function. */
+  if (0 != fseek (file, (long) pos, SEEK_SET))
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  bytes_read = fread (buf, 1, max, file);
+  if (0 == bytes_read)
+    return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR :
+           MHD_CONTENT_READER_END_OF_STREAM;
+  return (ssize_t) bytes_read;
 }
 
+
 static void
 free_callback (void *cls)
 {
@@ -45,60 +58,81 @@
   fclose (file);
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data,
-	  size_t *upload_data_size, void **ptr)
+          size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   FILE *file;
+  int fd;
   struct stat buf;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+
+  file = fopen (&url[1], "rb");
+  if (NULL != file)
+  {
+    fd = fileno (file);
+    if (-1 == fd)
     {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
+      (void) fclose (file);
+      return MHD_NO;     /* internal error */
     }
-  *ptr = NULL;                  /* reset when done */
-  if ( (0 == stat (&url[1], &buf)) &&
-       (S_ISREG (buf.st_mode)) )
-    file = fopen (&url[1], "rb");
+    if ( (0 != fstat (fd, &buf)) ||
+         (! S_ISREG (buf.st_mode)) )
+    {
+      /* not a regular file, refuse to serve */
+      fclose (file);
+      file = NULL;
+    }
+  }
+
+  if (NULL == file)
+  {
+    response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                       PAGE);
+    ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);
+    MHD_destroy_response (response);
+  }
   else
-    file = NULL;
-  if (file == NULL)
+  {
+    response = MHD_create_response_from_callback ((size_t) buf.st_size,
+                                                  32 * 1024, /* 32k page size */
+                                                  &file_reader,
+                                                  file,
+                                                  &free_callback);
+    if (NULL == response)
     {
-      response = MHD_create_response_from_buffer (strlen (PAGE),
-						  (void *) PAGE,
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);
-      MHD_destroy_response (response);
+      fclose (file);
+      return MHD_NO;
     }
-  else
-    {
-      response = MHD_create_response_from_callback (buf.st_size, 32 * 1024,     /* 32k page size */
-                                                    &file_reader,
-                                                    file,
-                                                    &free_callback);
-      if (response == NULL)
-	{
-	  fclose (file);
-	  return MHD_NO;
-	}
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
-    }
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+  }
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
@@ -110,40 +144,61 @@
   fd_set ws;
   fd_set es;
   MHD_socket max;
-  MHD_UNSIGNED_LONG_LONG mhd_timeout;
+  uint64_t mhd_timeout;
+  int port;
 
   if (argc != 3)
-    {
-      printf ("%s PORT SECONDS-TO-RUN\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE, MHD_OPTION_END);
+  {
+    printf ("%s PORT SECONDS-TO-RUN\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
   end = time (NULL) + atoi (argv[2]);
   while ((t = time (NULL)) < end)
+  {
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    tv.tv_sec = end - t;
+#else  /* Native W32 */
+    tv.tv_sec = (long) (end - t);
+#endif /* Native W32 */
+    tv.tv_usec = 0;
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      break; /* fatal internal error */
+    if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES)
     {
-      tv.tv_sec = end - t;
-      tv.tv_usec = 0;
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-	break; /* fatal internal error */
-      if (MHD_get_timeout (d, &mhd_timeout) == MHD_YES)
-        {
-          if (((MHD_UNSIGNED_LONG_LONG)tv.tv_sec) < mhd_timeout / 1000LL)
-            {
-              tv.tv_sec = mhd_timeout / 1000LL;
-              tv.tv_usec = (mhd_timeout - (tv.tv_sec * 1000LL)) * 1000LL;
-            }
-        }
-      select (max + 1, &rs, &ws, &es, &tv);
-      MHD_run (d);
+      if (((uint64_t) tv.tv_sec) < mhd_timeout / 1000LL)
+      {
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+        tv.tv_sec = (time_t) (mhd_timeout / 1000LL);
+#else  /* Native W32 */
+        tv.tv_sec = (long) (mhd_timeout / 1000LL);
+#endif /* Native W32 */
+        tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000;
+      }
     }
+    if (-1 == select ((int) max + 1, &rs, &ws, &es, &tv))
+    {
+      if (EINTR != errno)
+        abort ();
+    }
+    MHD_run (d);
+  }
   MHD_stop_daemon (d);
   return 0;
 }
diff --git a/src/examples/http_chunked_compression.c b/src/examples/http_chunked_compression.c
new file mode 100644
index 0000000..6c52f60
--- /dev/null
+++ b/src/examples/http_chunked_compression.c
@@ -0,0 +1,244 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2019-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file http_chunked_compression.c
+ * @brief example for how to compress a chunked HTTP response
+ * @author Silvio Clecio (silvioprog)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "platform.h"
+#ifndef ZLIB_CONST
+/* Correct API with const pointer for input data is required */
+#define ZLIB_CONST 1
+#endif /* ! ZLIB_CONST */
+#include <zlib.h>
+#include <microhttpd.h>
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+#include <stddef.h>
+#include <stdint.h>
+
+#ifndef SSIZE_MAX
+#ifdef __SSIZE_MAX__
+#define SSIZE_MAX __SSIZE_MAX__
+#elif defined(PTRDIFF_MAX)
+#define SSIZE_MAX PTRDIFF_MAX
+#elif defined(INTPTR_MAX)
+#define SSIZE_MAX INTPTR_MAX
+#else
+#define SSIZE_MAX ((ssize_t) (((size_t) -1) >> 1))
+#endif
+#endif /* ! SSIZE_MAX */
+
+#define CHUNK 16384
+
+struct Holder
+{
+  FILE *file;
+  z_stream stream;
+  void *buf;
+};
+
+static enum MHD_Result
+compress_buf (z_stream *strm, const void *src, size_t src_size, size_t *offset,
+              void **dest, size_t *dest_size,
+              void *tmp)
+{
+  unsigned int have;
+  enum MHD_Result ret;
+  int flush;
+  void *tmp_dest;
+  *dest = NULL;
+  *dest_size = 0;
+  do
+  {
+    if (src_size > CHUNK)
+    {
+      strm->avail_in = CHUNK;
+      src_size -= CHUNK;
+      flush = Z_NO_FLUSH;
+    }
+    else
+    {
+      strm->avail_in = (uInt) src_size;
+      flush = Z_SYNC_FLUSH;
+    }
+    *offset += strm->avail_in;
+    strm->next_in = (const Bytef *) src;
+    do
+    {
+      strm->avail_out = CHUNK;
+      strm->next_out = tmp;
+      ret = (Z_OK == deflate (strm, flush)) ? MHD_YES : MHD_NO;
+      have = CHUNK - strm->avail_out;
+      *dest_size += have;
+      tmp_dest = realloc (*dest, *dest_size);
+      if (NULL == tmp_dest)
+      {
+        free (*dest);
+        *dest = NULL;
+        return MHD_NO;
+      }
+      *dest = tmp_dest;
+      memcpy (((uint8_t *) (*dest)) + ((*dest_size) - have), tmp, have);
+    }
+    while (0 == strm->avail_out);
+  }
+  while (flush != Z_SYNC_FLUSH);
+  return ret;
+}
+
+
+static ssize_t
+read_cb (void *cls, uint64_t pos, char *mem, size_t size)
+{
+  struct Holder *holder = cls;
+  void *src;
+  void *buf;
+  ssize_t ret;
+  size_t offset;
+  size_t r_size;
+
+  if (pos > SSIZE_MAX)
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  offset = (size_t) pos;
+  src = malloc (size);
+  if (NULL == src)
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  r_size = fread (src, 1, size, holder->file);
+  if (0 == r_size)
+  {
+    ret = (0 != ferror (holder->file)) ?
+          MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM;
+    goto done;
+  }
+  if (MHD_YES != compress_buf (&holder->stream, src, r_size, &offset, &buf,
+                               &size, holder->buf))
+    ret = MHD_CONTENT_READER_END_WITH_ERROR;
+  else
+  {
+    memcpy (mem, buf, size);
+    ret = (ssize_t) size;
+  }
+  free (buf); /* Buf may be set even on error return. */
+done:
+  free (src);
+  return ret;
+}
+
+
+static void
+free_cb (void *cls)
+{
+  struct Holder *holder = cls;
+  fclose (holder->file);
+  deflateEnd (&holder->stream);
+  free (holder->buf);
+  free (holder);
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls, struct MHD_Connection *con, const char *url, const
+          char *method, const char *version,
+          const char *upload_data, size_t *upload_size, void **req_cls)
+{
+  struct Holder *holder;
+  struct MHD_Response *res;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url;
+  (void) method;
+  (void) version;
+  (void) upload_data;
+  (void) upload_size;
+  if (NULL == *req_cls)
+  {
+    *req_cls = (void *) 1;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  holder = calloc (1, sizeof (struct Holder));
+  if (! holder)
+    return MHD_NO;
+  holder->file = fopen (__FILE__, "rb");
+  if (NULL == holder->file)
+    goto file_error;
+  if (Z_OK != deflateInit (&holder->stream, Z_BEST_COMPRESSION))
+    goto stream_error;
+  holder->buf = malloc (CHUNK);
+  if (NULL == holder->buf)
+    goto buf_error;
+  res = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &read_cb,
+                                           holder, &free_cb);
+  if (NULL == res)
+    goto error;
+  ret = MHD_add_response_header (res, MHD_HTTP_HEADER_CONTENT_ENCODING,
+                                 "deflate");
+  if (MHD_YES != ret)
+    goto res_error;
+  ret = MHD_add_response_header (res, MHD_HTTP_HEADER_CONTENT_TYPE, "text/x-c");
+  if (MHD_YES != ret)
+    goto res_error;
+  ret = MHD_queue_response (con, MHD_HTTP_OK, res);
+res_error:
+  MHD_destroy_response (res);
+  return ret;
+error:
+  free (holder->buf);
+buf_error:
+  deflateEnd (&holder->stream);
+stream_error:
+  fclose (holder->file);
+file_error:
+  free (holder);
+  return MHD_NO;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  struct MHD_Daemon *d;
+  unsigned int port;
+  if ((argc != 2) ||
+      (1 != sscanf (argv[1], "%u", &port)) ||
+      (UINT16_MAX < port))
+  {
+    fprintf (stderr, "%s PORT\n", argv[0]);
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                        (uint16_t) port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
+  if (NULL == d)
+    return 1;
+  if (0 == port)
+    MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT, &port);
+  fprintf (stdout,
+           "HTTP server running at http://localhost:%u\n\nPress ENTER to stop the server ...\n",
+           port);
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/examples/http_compression.c b/src/examples/http_compression.c
new file mode 100644
index 0000000..244266e
--- /dev/null
+++ b/src/examples/http_compression.c
@@ -0,0 +1,189 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2019-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file http_compression.c
+ * @brief minimal example for how to compress HTTP response
+ * @author Silvio Clecio (silvioprog)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "platform.h"
+#include <zlib.h>
+#include <microhttpd.h>
+
+#define PAGE                                                        \
+  "<html><head><title>HTTP compression</title></head><body>Hello, " \
+  "hello, hello. This is a 'hello world' message for the world, "   \
+  "repeat, for the world.</body></html>"
+
+static enum MHD_Result
+can_compress (struct MHD_Connection *con)
+{
+  const char *ae;
+  const char *de;
+
+  ae = MHD_lookup_connection_value (con,
+                                    MHD_HEADER_KIND,
+                                    MHD_HTTP_HEADER_ACCEPT_ENCODING);
+  if (NULL == ae)
+    return MHD_NO;
+  if (0 == strcmp (ae,
+                   "*"))
+    return MHD_YES;
+  de = strstr (ae,
+               "deflate");
+  if (NULL == de)
+    return MHD_NO;
+  if (((de == ae) ||
+       (de[-1] == ',') ||
+       (de[-1] == ' ')) &&
+      ((de[strlen ("deflate")] == '\0') ||
+       (de[strlen ("deflate")] == ',') ||
+       (de[strlen ("deflate")] == ';')))
+    return MHD_YES;
+  return MHD_NO;
+}
+
+
+static enum MHD_Result
+body_compress (void **buf,
+               size_t *buf_size)
+{
+  Bytef *cbuf;
+  uLongf cbuf_size;
+  int ret;
+
+  cbuf_size = compressBound ((uLong) * buf_size);
+  cbuf = malloc (cbuf_size);
+  if (NULL == cbuf)
+    return MHD_NO;
+  ret = compress (cbuf,
+                  &cbuf_size,
+                  (const Bytef *) *buf,
+                  (uLong) * buf_size);
+  if ((Z_OK != ret) ||
+      (cbuf_size >= *buf_size))
+  {
+    /* compression failed */
+    free (cbuf);
+    return MHD_NO;
+  }
+  free (*buf);
+  *buf = (void *) cbuf;
+  *buf_size = (size_t) cbuf_size;
+  return MHD_YES;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
+{
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  enum MHD_Result comp;
+  size_t body_len;
+  char *body_str;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO; /* unexpected method */
+  if (! *req_cls)
+  {
+    *req_cls = (void *) 1;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  body_str = strdup (PAGE);
+  if (NULL == body_str)
+  {
+    return MHD_NO;
+  }
+  body_len = strlen (body_str);
+  /* try to compress the body */
+  comp = MHD_NO;
+  if (MHD_YES ==
+      can_compress (connection))
+    comp = body_compress ((void **) &body_str,
+                          &body_len);
+  response =
+    MHD_create_response_from_buffer_with_free_callback (body_len,
+                                                        body_str,
+                                                        &free);
+
+  if (NULL == response)
+  {
+    free (body_str);
+    return MHD_NO;
+  }
+
+  if (MHD_YES == comp)
+  {
+    /* Need to indicate to client that body is compressed */
+    if (MHD_NO ==
+        MHD_add_response_header (response,
+                                 MHD_HTTP_HEADER_CONTENT_ENCODING,
+                                 "deflate"))
+    {
+      MHD_destroy_response (response);
+      return MHD_NO;
+    }
+  }
+  ret = MHD_queue_response (connection,
+                            200,
+                            response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  struct MHD_Daemon *d;
+  unsigned int port;
+
+  if ( (argc != 2) ||
+       (1 != sscanf (argv[1], "%u", &port)) ||
+       (65535 < port) )
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_ERROR_LOG,
+                        (uint16_t) port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
+  if (NULL == d)
+    return 1;
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/examples/https_fileserver_example.c b/src/examples/https_fileserver_example.c
index fe0c2de..7fac39b 100644
--- a/src/examples/https_fileserver_example.c
+++ b/src/examples/https_fileserver_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -24,86 +25,109 @@
  *
  *  'http_fileserver_example HTTP-PORT SECONDS-TO-RUN'
  *
- * The certificate & key are required by the server to operate,  Omitting the
+ * The certificate & key are required by the server to operate, omitting the
  * path arguments will cause the server to use the hard coded example certificate & key.
  *
  * 'certtool' may be used to generate these if required.
  *
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 #include <sys/stat.h>
-#include <gnutls/gnutls.h>
-#include <gcrypt.h>
 
 #define BUF_SIZE 1024
 #define MAX_URL_LEN 255
 
-// TODO remove if unused
-#define CAFILE "ca.pem"
-#define CRLFILE "crl.pem"
+#define EMPTY_PAGE \
+  "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
-#define EMPTY_PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
+/* test server key */
+static const char key_pem[] =
+  "-----BEGIN PRIVATE KEY-----\n\
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\
+rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\
+UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\
++sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\
+HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\
+CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\
+dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\
++SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\
+XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\
+znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\
+pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\
+D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\
+Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\
+pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\
+zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\
+pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\
+KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\
+W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\
+OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\
+XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\
+wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\
+ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\
+0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\
+ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\
+QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\
+qdJNJ1DkyUc9dN2cliX4R+rG\n\
+-----END PRIVATE KEY-----";
 
-/* Test Certificate */
-const char cert_pem[] =
-  "-----BEGIN CERTIFICATE-----\n"
-  "MIICpjCCAZCgAwIBAgIESEPtjjALBgkqhkiG9w0BAQUwADAeFw0wODA2MDIxMjU0\n"
-  "MzhaFw0wOTA2MDIxMjU0NDZaMAAwggEfMAsGCSqGSIb3DQEBAQOCAQ4AMIIBCQKC\n"
-  "AQC03TyUvK5HmUAirRp067taIEO4bibh5nqolUoUdo/LeblMQV+qnrv/RNAMTx5X\n"
-  "fNLZ45/kbM9geF8qY0vsPyQvP4jumzK0LOJYuIwmHaUm9vbXnYieILiwCuTgjaud\n"
-  "3VkZDoQ9fteIo+6we9UTpVqZpxpbLulBMh/VsvX0cPJ1VFC7rT59o9hAUlFf9jX/\n"
-  "GmKdYI79MtgVx0OPBjmmSD6kicBBfmfgkO7bIGwlRtsIyMznxbHu6VuoX/eVxrTv\n"
-  "rmCwgEXLWRZ6ru8MQl5YfqeGXXRVwMeXU961KefbuvmEPccgCxm8FZ1C1cnDHFXh\n"
-  "siSgAzMBjC/b6KVhNQ4KnUdZAgMBAAGjLzAtMAwGA1UdEwEB/wQCMAAwHQYDVR0O\n"
-  "BBYEFJcUvpjvE5fF/yzUshkWDpdYiQh/MAsGCSqGSIb3DQEBBQOCAQEARP7eKSB2\n"
-  "RNd6XjEjK0SrxtoTnxS3nw9sfcS7/qD1+XHdObtDFqGNSjGYFB3Gpx8fpQhCXdoN\n"
-  "8QUs3/5ZVa5yjZMQewWBgz8kNbnbH40F2y81MHITxxCe1Y+qqHWwVaYLsiOTqj2/\n"
-  "0S3QjEJ9tvklmg7JX09HC4m5QRYfWBeQLD1u8ZjA1Sf1xJriomFVyRLI2VPO2bNe\n"
-  "JDMXWuP+8kMC7gEvUnJ7A92Y2yrhu3QI3bjPk8uSpHea19Q77tul1UVBJ5g+zpH3\n"
-  "OsF5p0MyaVf09GTzcLds5nE/osTdXGUyHJapWReVmPm3Zn6gqYlnzD99z+DPIgIV\n"
-  "RhZvQx74NQnS6g==\n" "-----END CERTIFICATE-----\n";
-
-const char key_pem[] =
-  "-----BEGIN RSA PRIVATE KEY-----\n"
-  "MIIEowIBAAKCAQEAtN08lLyuR5lAIq0adOu7WiBDuG4m4eZ6qJVKFHaPy3m5TEFf\n"
-  "qp67/0TQDE8eV3zS2eOf5GzPYHhfKmNL7D8kLz+I7psytCziWLiMJh2lJvb2152I\n"
-  "niC4sArk4I2rnd1ZGQ6EPX7XiKPusHvVE6VamacaWy7pQTIf1bL19HDydVRQu60+\n"
-  "faPYQFJRX/Y1/xpinWCO/TLYFcdDjwY5pkg+pInAQX5n4JDu2yBsJUbbCMjM58Wx\n"
-  "7ulbqF/3lca0765gsIBFy1kWeq7vDEJeWH6nhl10VcDHl1PetSnn27r5hD3HIAsZ\n"
-  "vBWdQtXJwxxV4bIkoAMzAYwv2+ilYTUOCp1HWQIDAQABAoIBAArOQv3R7gmqDspj\n"
-  "lDaTFOz0C4e70QfjGMX0sWnakYnDGn6DU19iv3GnX1S072ejtgc9kcJ4e8VUO79R\n"
-  "EmqpdRR7k8dJr3RTUCyjzf/C+qiCzcmhCFYGN3KRHA6MeEnkvRuBogX4i5EG1k5l\n"
-  "/5t+YBTZBnqXKWlzQLKoUAiMLPg0eRWh+6q7H4N7kdWWBmTpako7TEqpIwuEnPGx\n"
-  "u3EPuTR+LN6lF55WBePbCHccUHUQaXuav18NuDkcJmCiMArK9SKb+h0RqLD6oMI/\n"
-  "dKD6n8cZXeMBkK+C8U/K0sN2hFHACsu30b9XfdnljgP9v+BP8GhnB0nCB6tNBCPo\n"
-  "32srOwECgYEAxWh3iBT4lWqL6bZavVbnhmvtif4nHv2t2/hOs/CAq8iLAw0oWGZc\n"
-  "+JEZTUDMvFRlulr0kcaWra+4fN3OmJnjeuFXZq52lfMgXBIKBmoSaZpIh2aDY1Rd\n"
-  "RbEse7nQl9hTEPmYspiXLGtnAXW7HuWqVfFFP3ya8rUS3t4d07Hig8ECgYEA6ou6\n"
-  "OHiBRTbtDqLIv8NghARc/AqwNWgEc9PelCPe5bdCOLBEyFjqKiT2MttnSSUc2Zob\n"
-  "XhYkHC6zN1Mlq30N0e3Q61YK9LxMdU1vsluXxNq2rfK1Scb1oOlOOtlbV3zA3VRF\n"
-  "hV3t1nOA9tFmUrwZi0CUMWJE/zbPAyhwWotKyZkCgYEAh0kFicPdbABdrCglXVae\n"
-  "SnfSjVwYkVuGd5Ze0WADvjYsVkYBHTvhgRNnRJMg+/vWz3Sf4Ps4rgUbqK8Vc20b\n"
-  "AU5G6H6tlCvPRGm0ZxrwTWDHTcuKRVs+pJE8C/qWoklE/AAhjluWVoGwUMbPGuiH\n"
-  "6Gf1bgHF6oj/Sq7rv/VLZ8ECgYBeq7ml05YyLuJutuwa4yzQ/MXfghzv4aVyb0F3\n"
-  "QCdXR6o2IYgR6jnSewrZKlA9aPqFJrwHNR6sNXlnSmt5Fcf/RWO/qgJQGLUv3+rG\n"
-  "7kuLTNDR05azSdiZc7J89ID3Bkb+z2YkV+6JUiPq/Ei1+nDBEXb/m+/HqALU/nyj\n"
-  "P3gXeQKBgBusb8Rbd+KgxSA0hwY6aoRTPRt8LNvXdsB9vRcKKHUFQvxUWiUSS+L9\n"
-  "/Qu1sJbrUquKOHqksV5wCnWnAKyJNJlhHuBToqQTgKXjuNmVdYSe631saiI7PHyC\n"
-  "eRJ6DxULPxABytJrYCRrNqmXi5TCiqR2mtfalEMOPxz8rUU8dYyx\n"
-  "-----END RSA PRIVATE KEY-----\n";
+/* test server CA signed certificates */
+static const char cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n\
+MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\
+NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\
+c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\
+psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\
+atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\
+7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\
+n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\
+qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\
+kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\
+AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\
+c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\
+8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\
+IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\
+Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\
+X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\
+aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\
+HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\
+hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\
+18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\
+UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\
+B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\
+SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\
+WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\
+OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\
+/w0gW9EVWzFhsFeGEssi\n\
+-----END CERTIFICATE-----";
 
 static ssize_t
 file_reader (void *cls, uint64_t pos, char *buf, size_t max)
 {
-  FILE *file = cls;
+  FILE *file = (FILE *) cls;
+  size_t bytes_read;
 
-  (void) fseek (file, pos, SEEK_SET);
-  return fread (buf, 1, max, file);
+  /* 'fseek' may not support files larger 2GiB, depending on platform.
+   * For production code, make sure that 'pos' has valid values, supported by
+   * 'fseek', or use 'fseeko' or similar function. */
+  if (0 != fseek (file, (long) pos, SEEK_SET))
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  bytes_read = fread (buf, 1, max, file);
+  if (0 == bytes_read)
+    return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR :
+           MHD_CONTENT_READER_END_OF_STREAM;
+  return (ssize_t) bytes_read;
 }
 
+
 static void
 file_free_callback (void *cls)
 {
@@ -111,97 +135,123 @@
   fclose (file);
 }
 
+
 /* HTTP access handler call back */
-static int
+static enum MHD_Result
 http_ahc (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data,
-	  size_t *upload_data_size, void **ptr)
+          size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   FILE *file;
+  int fd;
   struct stat buf;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
 
-  if ( (0 == stat (&url[1], &buf)) &&
-       (S_ISREG (buf.st_mode)) )
-    file = fopen (&url[1], "rb");
-  else
-    file = NULL;
-  if (file == NULL)
+  file = fopen (&url[1], "rb");
+  if (NULL != file)
+  {
+    fd = fileno (file);
+    if (-1 == fd)
     {
-      response = MHD_create_response_from_buffer (strlen (EMPTY_PAGE),
-						  (void *) EMPTY_PAGE,
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);
-      MHD_destroy_response (response);
+      (void) fclose (file);
+      return MHD_NO;     /* internal error */
     }
-  else
+    if ( (0 != fstat (fd, &buf)) ||
+         (! S_ISREG (buf.st_mode)) )
     {
-      response = MHD_create_response_from_callback (buf.st_size, 32 * 1024,     /* 32k PAGE_NOT_FOUND size */
-                                                    &file_reader, file,
-                                                    &file_free_callback);
-      if (response == NULL)
-	{
-	  fclose (file);
-	  return MHD_NO;
-	}
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
+      /* not a regular file, refuse to serve */
+      fclose (file);
+      file = NULL;
     }
+  }
+
+  if (NULL == file)
+  {
+    response =
+      MHD_create_response_from_buffer_static (strlen (EMPTY_PAGE),
+                                              (const void *) EMPTY_PAGE);
+    ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);
+    MHD_destroy_response (response);
+  }
+  else
+  {
+    response = MHD_create_response_from_callback ((size_t) buf.st_size,
+                                                  32 * 1024,   /* 32k page size */
+                                                  &file_reader, file,
+                                                  &file_free_callback);
+    if (NULL == response)
+    {
+      fclose (file);
+      return MHD_NO;
+    }
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+  }
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *TLS_daemon;
+  int port;
 
-  if (argc == 2)
-    {
-      /* TODO check if this is truly necessary -  disallow usage of the blocking /dev/random */
-      /* gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0); */
-      TLS_daemon =
-        MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG |
-                          MHD_USE_SSL, atoi (argv[1]), NULL, NULL, &http_ahc,
-                          NULL, MHD_OPTION_CONNECTION_TIMEOUT, 256,
-                          MHD_OPTION_HTTPS_MEM_KEY, key_pem,
-                          MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
-                          MHD_OPTION_END);
-    }
-  else
-    {
-      printf ("Usage: %s HTTP-PORT\n", argv[0]);
-      return 1;
-    }
+  if (argc != 2)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) ||
+       (port > UINT16_MAX) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535\n");
+    return 1;
+  }
 
-  if (TLS_daemon == NULL)
-    {
-      fprintf (stderr, "Error: failed to start TLS_daemon\n");
-      return 1;
-    }
-  else
-    {
-      printf ("MHD daemon listening on port %d\n", atoi (argv[1]));
-    }
+  TLS_daemon =
+    MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                      | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                      | MHD_USE_TLS,
+                      (uint16_t) port,
+                      NULL, NULL,
+                      &http_ahc, NULL,
+                      MHD_OPTION_CONNECTION_TIMEOUT, 256,
+                      MHD_OPTION_HTTPS_MEM_KEY, key_pem,
+                      MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
+                      MHD_OPTION_END);
+  if (NULL == TLS_daemon)
+  {
+    fprintf (stderr, "Error: failed to start TLS_daemon.\n");
+    return 1;
+  }
+  printf ("MHD daemon listening on port %u\n",
+          (unsigned int) port);
 
   (void) getc (stdin);
 
   MHD_stop_daemon (TLS_daemon);
-
   return 0;
 }
diff --git a/src/examples/mhd2spdy.c b/src/examples/mhd2spdy.c
deleted file mode 100644
index a227508..0000000
--- a/src/examples/mhd2spdy.c
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file mhd2spdy.c
- * @brief  The main file of the HTTP-to-SPDY proxy with the 'main' function
- *         and event loop. No threads are used.
- *         Currently only GET is supported.
- *         TODOs:
- *         - non blocking SSL connect
- *         - check certificate
- *         - on closing spdy session, close sockets for all requests
- * @author Andrey Uzunov
- */
- 
- 
-#include "mhd2spdy_structures.h"
-#include "mhd2spdy_spdy.h"
-#include "mhd2spdy_http.h"
-
-
-static int run = 1;
-//static int spdy_close = 0;
-
-
-static void
-catch_signal(int signal)
-{
-  (void)signal;
-  //spdy_close = 1;
-  run = 0;
-}
-
-
-void
-print_stat()
-{
-  if(!glob_opt.statistics)
-    return;
-  
-  printf("--------------------------\n");
-  printf("Statistics (TLS overhead is ignored when used):\n");
-  //printf("HTTP bytes received: %lld\n", glob_stat.http_bytes_received);
-  //printf("HTTP bytes sent: %lld\n", glob_stat.http_bytes_sent);
-  printf("SPDY bytes sent: %lld\n", glob_stat.spdy_bytes_sent);
-  printf("SPDY bytes received: %lld\n", glob_stat.spdy_bytes_received);
-  printf("SPDY bytes received and dropped: %lld\n", glob_stat.spdy_bytes_received_and_dropped);
-}
-
-
-int
-run_everything ()
-{	
-  unsigned long long timeoutlong=0;
-  struct timeval timeout;
-  int ret;
-  fd_set rs;
-  fd_set ws;
-  fd_set es;
-  int maxfd = -1;
-  int maxfd_s = -1;
-  struct MHD_Daemon *daemon;
-  nfds_t spdy_npollfds = 1;
-  struct URI * spdy2http_uri = NULL;
-  struct SPDY_Connection *connection;
-  struct SPDY_Connection *connections[MAX_SPDY_CONNECTIONS];
-  struct SPDY_Connection *connection_for_delete;
-
-  if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
-    PRINT_INFO("signal failed");
-    
-  if (signal(SIGINT, catch_signal) == SIG_ERR)
-    PRINT_INFO("signal failed");
-
-  glob_opt.streams_opened = 0;
-  glob_opt.responses_pending = 0;
-  //glob_opt.global_memory = 0;
-
-  srand(time(NULL));
-  
-  if(init_parse_uri(&glob_opt.uri_preg))
-    DIE("Regexp compilation failed");
-    
-  if(NULL != glob_opt.spdy2http_str)
-  {
-    ret = parse_uri(&glob_opt.uri_preg, glob_opt.spdy2http_str, &spdy2http_uri);
-    if(ret != 0)
-      DIE("spdy_parse_uri failed");
-  }
-
-  SSL_load_error_strings();
-  SSL_library_init();
-  glob_opt.ssl_ctx = SSL_CTX_new(SSLv23_client_method());
-  if(glob_opt.ssl_ctx == NULL) {
-    PRINT_INFO2("SSL_CTX_new %s", ERR_error_string(ERR_get_error(), NULL));
-    abort();
-  }
-  spdy_ssl_init_ssl_ctx(glob_opt.ssl_ctx, &glob_opt.spdy_proto_version);
-
-  daemon = MHD_start_daemon ( 
-          MHD_SUPPRESS_DATE_NO_CLOCK,
-          glob_opt.listen_port,
-          NULL, NULL, &http_cb_request, NULL,
-          MHD_OPTION_URI_LOG_CALLBACK, &http_cb_log, NULL,
-          MHD_OPTION_NOTIFY_COMPLETED, &http_cb_request_completed, NULL,
-          MHD_OPTION_END);
-  if(NULL==daemon)
-    DIE("MHD_start_daemon failed");
-
-  do
-  {
-    timeout.tv_sec = 0;
-    timeout.tv_usec = 0;
-  
-    if(NULL == glob_opt.spdy_connection && NULL != glob_opt.spdy2http_str)
-    {
-      glob_opt.spdy_connection = spdy_connect(spdy2http_uri, spdy2http_uri->port, strcmp("https", spdy2http_uri->scheme)==0);
-      if(NULL == glob_opt.spdy_connection && glob_opt.only_proxy)
-        PRINT_INFO("cannot connect to the proxy");
-    }
-
-    FD_ZERO(&rs);
-    FD_ZERO(&ws);
-    FD_ZERO(&es);
-
-    ret = MHD_get_timeout(daemon, &timeoutlong);
-    if(MHD_NO == ret || timeoutlong > 5000)
-      timeout.tv_sec = 5;
-    else
-    {
-      timeout.tv_sec = timeoutlong / 1000;
-      timeout.tv_usec = (timeoutlong % 1000) * 1000;
-    }
-    
-    if(MHD_NO == MHD_get_fdset (daemon,
-                                  &rs,
-                                  &ws, 
-                                  &es,
-                                  &maxfd))
-    {
-      PRINT_INFO("MHD_get_fdset error");
-    }
-    assert(-1 != maxfd);
-    
-    maxfd_s = spdy_get_selectfdset(
-                                  &rs,
-                                  &ws, 
-                                  &es,
-                                  connections, MAX_SPDY_CONNECTIONS, &spdy_npollfds);
-    if(maxfd_s > maxfd) 
-      maxfd = maxfd_s;
- 
-    PRINT_INFO2("MHD timeout %lld %lld", (unsigned long long)timeout.tv_sec, (unsigned long long)timeout.tv_usec);
-
-    glob_opt.spdy_data_received = false;
-      
-    ret = select(maxfd+1, &rs, &ws, &es, &timeout);
-    PRINT_INFO2("timeout now %lld %lld ret is %i", (unsigned long long)timeout.tv_sec, (unsigned long long)timeout.tv_usec, ret);
-
-    switch(ret)
-    {
-      case -1:
-        PRINT_INFO2("select error: %i", errno);
-        break;
-      case 0:
-        //break;
-      default:
-      PRINT_INFO("run");
-        //MHD_run_from_select(daemon,&rs, &ws, &es); //not closing FDs at some time in past
-        MHD_run(daemon);
-        spdy_run_select(&rs, &ws, &es, connections, spdy_npollfds);
-        if(glob_opt.spdy_data_received)
-        {
-          PRINT_INFO("MHD run again");
-          //MHD_run_from_select(daemon,&rs, &ws, &es); //not closing FDs at some time in past
-          MHD_run(daemon);
-        }
-        break;
-    }
-  }
-  while(run);
-
-  MHD_stop_daemon (daemon);
-  
-  //TODO SSL_free brakes
-  spdy_free_connection(glob_opt.spdy_connection);
-  
-  connection = glob_opt.spdy_connections_head;
-  while(NULL != connection)
-  {    
-    connection_for_delete = connection;
-    connection = connection_for_delete->next;
-    glob_opt.streams_opened -= connection_for_delete->streams_opened;
-    DLL_remove(glob_opt.spdy_connections_head, glob_opt.spdy_connections_tail, connection_for_delete);
-    spdy_free_connection(connection_for_delete);
-  }
-  
-  free_uri(spdy2http_uri);
-  
-  deinit_parse_uri(&glob_opt.uri_preg);
-  
-  SSL_CTX_free(glob_opt.ssl_ctx);
-  ERR_free_strings();
-  EVP_cleanup();
-    
-  PRINT_INFO2("spdy streams: %i; http requests: %i", glob_opt.streams_opened, glob_opt.responses_pending);
-  //PRINT_INFO2("memory allocated %zu bytes", glob_opt.global_memory);
-  
-  print_stat();
-
-  return 0;
-}
-
-
-void
-display_usage()
-{
-  printf(
-    "Usage: mhd2spdy [-ovs] [-b <SPDY2HTTP-PROXY>] -p <PORT>\n\n"
-    "OPTIONS:\n"
-    "    -p, --port            Listening port.\n"
-    "    -b, --backend-proxy   If set, he proxy will send requests to\n"
-    "                          that SPDY server or proxy. Set the address\n"
-    "                          in the form 'http://host:port'. Use 'https'\n"
-    "                          for SPDY over TLS, or 'http' for plain SPDY\n"
-    "                          communication with the backend.\n"
-    "    -o, --only-proxy      If set, the proxy will always forward the\n"
-    "                          requests to the backend proxy. If not set,\n"
-    "                          the proxy will first try to establsh SPDY\n"
-    "                          connection to the requested server. If the\n"
-    "                          server does not support SPDY and TLS, the\n"
-    "                          backend proxy will be used for the request.\n"
-    "    -v, --verbose         Print debug information.\n"
-    "    -s, --statistics      Print simple statistics on exit.\n\n"
-
-  );
-}
-
-
-int
-main (int argc,
-      char *const *argv)
-{   
-  int getopt_ret;
-  int option_index;
-  struct option long_options[] = {
-    {"port",  required_argument, 0, 'p'},
-    {"backend-proxy",  required_argument, 0, 'b'},
-    {"verbose",  no_argument, 0, 'v'},
-    {"only-proxy",  no_argument, 0, 'o'},
-    {"statistics",  no_argument, 0, 's'},
-    {0, 0, 0, 0}
-  };
-  
-  while (1)
-  {
-    getopt_ret = getopt_long( argc, argv, "p:b:vos", long_options, &option_index);
-    if (getopt_ret == -1)
-      break;
-
-    switch(getopt_ret)
-    {
-      case 'p':
-        glob_opt.listen_port = atoi(optarg);
-        break;
-        
-      case 'b':
-        glob_opt.spdy2http_str = strdup(optarg);
-        if(NULL == glob_opt.spdy2http_str)
-          return 1;
-        break;
-        
-      case 'v':
-        glob_opt.verbose = true;
-        break;
-        
-      case 'o':
-        glob_opt.only_proxy = true;
-        break;
-        
-      case 's':
-        glob_opt.statistics = true;
-        break;
-        
-      case 0:
-        PRINT_INFO("0 from getopt");
-        break;
-        
-      case '?':
-        display_usage();
-        return 1;
-        
-      default:
-        DIE("default from getopt");
-    }
-  }
-  
-  if(
-    0 == glob_opt.listen_port
-    || (glob_opt.only_proxy && NULL == glob_opt.spdy2http_str)
-    )
-  {
-    display_usage();
-    return 1;
-  }
-    
-  return run_everything();
-}
diff --git a/src/examples/mhd2spdy_http.c b/src/examples/mhd2spdy_http.c
deleted file mode 100644
index 895f07f..0000000
--- a/src/examples/mhd2spdy_http.c
+++ /dev/null
@@ -1,422 +0,0 @@
-/*
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file mhd2spdy_http.c
- * @brief  HTTP part of the proxy. libmicrohttpd is used for the server side.
- * @author Andrey Uzunov
- */
- 
-#include "mhd2spdy_structures.h"
-#include "mhd2spdy_http.h"
-#include "mhd2spdy_spdy.h"
-
-
-void *
-http_cb_log(void * cls,
-const char * uri)
-{
-  (void)cls;
-  
-  struct HTTP_URI * http_uri;
-  
-  PRINT_INFO2("log uri '%s'\n", uri);
-  
-  //TODO not freed once in a while
-  if(NULL == (http_uri = au_malloc(sizeof(struct HTTP_URI ))))
-    return NULL;
-  http_uri->uri = strdup(uri);
-  return http_uri;
-}
-
-
-static int
-http_cb_iterate(void *cls,
-                 enum MHD_ValueKind kind,
-                 const char *name,
-                 const char *value)
-{
-  (void)kind;
-  
-  static char * const forbidden[] = {"Transfer-Encoding",
-    "Proxy-Connection",
-    "Keep-Alive",
-    "Connection"};
-  static int forbidden_size = 4;
-  int i;
-	struct SPDY_Headers *spdy_headers = (struct SPDY_Headers *)cls;
-	
-	if(0 == strcasecmp(name, "Host"))
-    spdy_headers->nv[9] = (char *)value;
-  else
-  {
-    for(i=0; i<forbidden_size; ++i)
-      if(0 == strcasecmp(forbidden[i], name))
-        return MHD_YES;
-    spdy_headers->nv[spdy_headers->cnt++] = (char *)name;
-    spdy_headers->nv[spdy_headers->cnt++] = (char *)value;
-  }
-	
-	return MHD_YES;
-}
-
-
-static ssize_t
-http_cb_response (void *cls,
-                        uint64_t pos,
-                        char *buffer,
-                        size_t max)
-{
-  (void)pos;
-  
-	int ret;
-	struct Proxy *proxy = (struct Proxy *)cls;
-	void *newbody;
-  const union MHD_ConnectionInfo *info;
-  int val = 1;
-  
-  PRINT_INFO2("http_cb_response for %s", proxy->url);
-  
-  if(proxy->spdy_error)
-    return MHD_CONTENT_READER_END_WITH_ERROR;
-  
-	if(0 == proxy->http_body_size && (proxy->done || !proxy->spdy_active))
-  {
-    PRINT_INFO("sent end of stream");
-    return MHD_CONTENT_READER_END_OF_STREAM;
-  }
-	
-	if(!proxy->http_body_size)//nothing to write now
-  {
-    //flush data
-    info = MHD_get_connection_info (proxy->http_connection,
-         MHD_CONNECTION_INFO_CONNECTION_FD);
-    ret = setsockopt(info->connect_fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
-    if(ret == -1) {
-      DIE("setsockopt");
-    }
-    
-    PRINT_INFO("FLUSH data");
-		return 0;
-  }
-	
-	if(max >= proxy->http_body_size)
-	{
-		ret = proxy->http_body_size;
-		newbody = NULL;
-	}
-	else
-	{
-		ret = max;
-		if(NULL == (newbody = au_malloc(proxy->http_body_size - max)))
-		{
-			PRINT_INFO("no memory");
-			return MHD_CONTENT_READER_END_WITH_ERROR;
-		}
-		memcpy(newbody, proxy->http_body + max, proxy->http_body_size - max);
-	}
-	memcpy(buffer, proxy->http_body, ret);
-	free(proxy->http_body);
-	proxy->http_body = newbody;
-	proxy->http_body_size -= ret;
-	
-	if(proxy->length >= 0)
-	{
-		proxy->length -= ret;
-	}
-	
-	PRINT_INFO2("response_callback, size: %i",ret);
-	
-	return ret;
-}
-
-
-static void
-http_cb_response_done(void *cls)
-{
-  (void)cls;
-  //TODO remove
-}
-
-int
-http_cb_request (void *cls,
-                struct MHD_Connection *connection,
-                const char *url,
-                const char *method,
-                const char *version,
-                const char *upload_data,
-                size_t *upload_data_size,
-                void **ptr)
-{
-  (void)cls;
-  (void)url;
-  (void)upload_data;
-  (void)upload_data_size;
-  
-  int ret;
-  struct Proxy *proxy;
-  struct SPDY_Headers spdy_headers;
-  bool with_body = false;
-  struct HTTP_URI *http_uri;
-  const char *header_value;
-
-  if (NULL == ptr || NULL == *ptr)
-    return MHD_NO;
-    
-  http_uri = (struct HTTP_URI *)*ptr;
-    
-  if(NULL == http_uri->proxy)
-  {
-    //first call for this request
-    if (0 != strcmp (method, MHD_HTTP_METHOD_GET) && 0 != strcmp (method, MHD_HTTP_METHOD_POST))
-    {
-      free(http_uri->uri);
-      free(http_uri);
-      PRINT_INFO2("unexpected method %s", method);
-      return MHD_NO;
-    }
-    
-    if(NULL == (proxy = au_malloc(sizeof(struct Proxy))))
-    {
-      free(http_uri->uri);
-      free(http_uri);
-      PRINT_INFO("No memory");
-      return MHD_NO; 
-    }
-    
-    ++glob_opt.responses_pending;
-    proxy->id = rand();
-    proxy->http_active = true;
-    proxy->http_connection = connection;
-    http_uri->proxy = proxy;
-    return MHD_YES;
-  }
-  
-  proxy = http_uri->proxy;
-  
-  if(proxy->spdy_error || proxy->http_error)
-    return MHD_NO; // handled at different place TODO? leaks?
-
-  if(proxy->spdy_active)
-  {
-    if(0 == strcmp (method, MHD_HTTP_METHOD_POST))
-    {
-      PRINT_INFO("POST processing");
-        
-      int rc= spdylay_session_resume_data(proxy->spdy_connection->session, proxy->stream_id);
-      PRINT_INFO2("rc is %i stream is %i", rc, proxy->stream_id);
-      proxy->spdy_connection->want_io |= WANT_WRITE;
-      
-      if(0 == *upload_data_size)
-      {
-      PRINT_INFO("POST http EOF");
-        proxy->receiving_done = true;
-        return MHD_YES;
-      }
-      
-      if(!copy_buffer(upload_data, *upload_data_size, &proxy->received_body, &proxy->received_body_size))
-      {
-        //TODO handle it better?
-        PRINT_INFO("not enough memory (malloc/realloc returned NULL)");
-        return MHD_NO;
-      }
-      
-      *upload_data_size = 0;
-                               
-      return MHD_YES;
-    }
-  
-    //already handled
-    PRINT_INFO("unnecessary call to http_cb_request");
-    return MHD_YES;
-  }
-  
-  //second call for this request
-
-  PRINT_INFO2("received request for '%s %s %s'", method, http_uri->uri, version);
-
-  proxy->url = http_uri->uri;
-  
-  header_value = MHD_lookup_connection_value(connection,
-    MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
-  
-  with_body = 0 == strcmp (method, MHD_HTTP_METHOD_POST)
-    && (NULL == header_value || 0 != strcmp ("0", header_value));
-    
-  PRINT_INFO2("body will be sent %i", with_body);
-    
-  ret = parse_uri(&glob_opt.uri_preg, proxy->url, &proxy->uri);
-  if(ret != 0)
-    DIE("parse_uri failed");
-  proxy->http_uri = http_uri;
-
-  spdy_headers.num = MHD_get_connection_values (connection,
-                       MHD_HEADER_KIND,
-                       NULL,
-                       NULL);
-  if(NULL == (spdy_headers.nv = au_malloc(((spdy_headers.num + 5) * 2 + 1) * sizeof(char *))))
-    DIE("no memory");
-  spdy_headers.nv[0] = ":method";     spdy_headers.nv[1] = method;
-  spdy_headers.nv[2] = ":path";       spdy_headers.nv[3] = proxy->uri->path_and_more;
-  spdy_headers.nv[4] = ":version";    spdy_headers.nv[5] = (char *)version;
-  spdy_headers.nv[6] = ":scheme";     spdy_headers.nv[7] = proxy->uri->scheme;
-  spdy_headers.nv[8] = ":host";       spdy_headers.nv[9] = NULL;
-  //nv[14] = NULL;
-  spdy_headers.cnt = 10;
-  MHD_get_connection_values (connection,
-                       MHD_HEADER_KIND,
-                       &http_cb_iterate,
-                       &spdy_headers);
-                       
-  spdy_headers.nv[spdy_headers.cnt] = NULL;
-  if(NULL == spdy_headers.nv[9])
-    spdy_headers.nv[9] = proxy->uri->host_and_port;
-
-  if(0 != spdy_request(spdy_headers.nv, proxy, with_body))
-  {
-    free(spdy_headers.nv);
-    //free_proxy(proxy);
-    
-    return MHD_NO;
-  }
-  free(spdy_headers.nv);
-  
-  proxy->http_response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
-                         4096,
-                         &http_cb_response,
-                         proxy,
-                         &http_cb_response_done);
-
-  if (NULL == proxy->http_response)
-    DIE("no response");
-  
-  if(MHD_NO == MHD_add_response_header (proxy->http_response,
-                 "Proxy-Connection", "keep-alive"))
-    PRINT_INFO("SPDY_name_value_add failed: ");
-  if(MHD_NO == MHD_add_response_header (proxy->http_response,
-                 "Connection", "Keep-Alive"))
-    PRINT_INFO("SPDY_name_value_add failed: ");
-  if(MHD_NO == MHD_add_response_header (proxy->http_response,
-                 "Keep-Alive", "timeout=5, max=100"))
-    PRINT_INFO("SPDY_name_value_add failed: ");
-    
-  proxy->spdy_active = true;
-  
-  return MHD_YES;
-}
-
-
-void
-http_create_response(struct Proxy* proxy,
-                     char **nv)
-{
-  size_t i;
-  
-  if(!proxy->http_active)
-    return;
-  
-  for(i = 0; nv[i]; i += 2) {
-    if(0 == strcmp(":status", nv[i]))
-    {
-      char tmp[4];
-      memcpy(&tmp,nv[i+1],3);
-      tmp[3]=0;
-      proxy->status = atoi(tmp);
-      continue;
-    }
-    else if(0 == strcmp(":version", nv[i]))
-    {
-      proxy->version = nv[i+1];
-      continue;
-    }
-    else if(0 == strcmp("content-length", nv[i]))
-    {
-      continue;
-    }
-
-    char *header = *(nv+i);
-    if(MHD_NO == MHD_add_response_header (proxy->http_response,
-                   header, nv[i+1]))
-    {
-      PRINT_INFO2("SPDY_name_value_add failed: '%s' '%s'", header, nv[i+1]);
-    }
-    PRINT_INFO2("adding '%s: %s'",header, nv[i+1]);
-  }
-  
-  if(MHD_NO == MHD_queue_response (proxy->http_connection, proxy->status, proxy->http_response)){
-    PRINT_INFO("No queue");
-    //TODO
-    //abort();
-    proxy->http_error = true;
-  }
-  
-  MHD_destroy_response (proxy->http_response);
-  proxy->http_response = NULL;
-}
-
-void
-http_cb_request_completed (void *cls,
-                                   struct MHD_Connection *connection,
-                                   void **con_cls,
-                                   enum MHD_RequestTerminationCode toe)
-{
-  (void)cls;
-  (void)connection;
-  struct HTTP_URI *http_uri;
-  struct Proxy *proxy;
-  
-  http_uri = (struct HTTP_URI *)*con_cls;
-  if(NULL == http_uri)
-    return;
-  proxy = (struct Proxy *)http_uri->proxy;
-  assert(NULL != proxy);
-  
-  PRINT_INFO2("http_cb_request_completed %i for %s; id %i",toe, http_uri->uri, proxy->id);
-  
-  if(NULL != proxy->http_response)
-  {
-    MHD_destroy_response (proxy->http_response);
-    proxy->http_response = NULL;
-  }
-  
-  if(proxy->spdy_active)
-  {
-    proxy->http_active = false;
-    if(MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
-    {
-      proxy->http_error = true;
-      if(proxy->stream_id > 0 /*&& NULL != proxy->spdy_connection->session*/)
-      {
-        //send RST_STREAM_STATUS_CANCEL
-        PRINT_INFO2("send rst_stream %i %i",proxy->spdy_active, proxy->stream_id );
-        spdylay_submit_rst_stream(proxy->spdy_connection->session, proxy->stream_id, 5);
-      }
-      /*else
-      {
-        DLL_remove(proxy->spdy_connection->proxies_head, proxy->spdy_connection->proxies_tail, proxy); 
-        free_proxy(proxy);
-      }*/
-    }
-  }
-  else
-  {
-    PRINT_INFO2("proxy free http id %i ", proxy->id);
-    free_proxy(proxy);
-  }
-    
-  --glob_opt.responses_pending;
-}
diff --git a/src/examples/mhd2spdy_http.h b/src/examples/mhd2spdy_http.h
deleted file mode 100644
index 89d3889..0000000
--- a/src/examples/mhd2spdy_http.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file mhd2spdy_http.h
- * @brief  HTTP part of the proxy. libmicrohttpd is used for the server side.
- * @author Andrey Uzunov
- */
- 
-#ifndef HTTP_H
-#define HTTP_H
-
-#include "mhd2spdy_structures.h"
-
-
-int
-http_cb_request (void *cls,
-                struct MHD_Connection *connection,
-                const char *url,
-                const char *method,
-                const char *version,
-                const char *upload_data,
-                size_t *upload_data_size,
-                void **ptr);
-
-
-void * http_cb_log(void * cls, const char * uri);
-
-
-void
-http_create_response(struct Proxy* proxy, char **nv);
-
-
-void
-http_cb_request_completed (void *cls,
-                                   struct MHD_Connection *connection,
-                                   void **con_cls,
-                                   enum MHD_RequestTerminationCode toe);
-
-#endif
diff --git a/src/examples/mhd2spdy_spdy.c b/src/examples/mhd2spdy_spdy.c
deleted file mode 100644
index 95ec43c..0000000
--- a/src/examples/mhd2spdy_spdy.c
+++ /dev/null
@@ -1,1150 +0,0 @@
-/*
- *
- * Copyright (c) 2012 Tatsuhiro Tsujikawa
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/**
- * @file mhd2spdy_spdy.c
- * @brief  SPDY part of the proxy. libspdylay is used for the client side.
- *         The example spdycli.c from spdylay was used as basis;
- *         however, multiple changes were made.
- * @author Tatsuhiro Tsujikawa
- * @author Andrey Uzunov
- */
-
-#include "mhd2spdy_structures.h"
-#include "mhd2spdy_spdy.h"
-#include "mhd2spdy_http.h"
-
-
-/*
- * Prints error containing the function name |func| and message |msg|
- * and exit.
- */
-static void
-spdy_dief(const char *func,
-          const char *msg)
-{
-  fprintf(stderr, "FATAL: %s: %s\n", func, msg);
-  exit(EXIT_FAILURE);
-}
-
-
-/*
- * Prints error containing the function name |func| and error code
- * |error_code| and exit.
- */
-void
-spdy_diec(const char *func,
-          int error_code)
-{
-  fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
-          spdylay_strerror(error_code));
-  exit(EXIT_FAILURE);
-}
-
-
-static ssize_t
-spdy_cb_data_source_read(spdylay_session *session, int32_t stream_id, uint8_t *buf, size_t length, int *eof, spdylay_data_source *source, void *user_data)
-{
-  (void)session;
-  (void)stream_id;
-  (void)user_data;
-  
-  ssize_t ret;
-  assert(NULL != source);
-  assert(NULL != source->ptr);
-	struct Proxy *proxy = (struct Proxy *)(source->ptr);
-	void *newbody;
-  
- 
-  if(length < 1)
-  {
-    PRINT_INFO("spdy_cb_data_source_read: length is 0");
-    return 0;
-	}
-  
-	if(!proxy->received_body_size)//nothing to write now
-  {
-    if(proxy->receiving_done)
-    {
-      PRINT_INFO("POST spdy EOF");
-      *eof = 1;
-    }
-      PRINT_INFO("POST SPDYLAY_ERR_DEFERRED");
-		return SPDYLAY_ERR_DEFERRED;//TODO SPDYLAY_ERR_DEFERRED should be used
-  }
-	
-	if(length >= proxy->received_body_size)
-	{
-		ret = proxy->received_body_size;
-		newbody = NULL;
-	}
-	else
-	{
-		ret = length;
-		if(NULL == (newbody = malloc(proxy->received_body_size - length)))
-		{
-			PRINT_INFO("no memory");
-			return SPDYLAY_ERR_TEMPORAL_CALLBACK_FAILURE;
-		}
-		memcpy(newbody, proxy->received_body + length, proxy->received_body_size - length);
-	}
-	memcpy(buf, proxy->received_body, ret);
-	free(proxy->received_body);
-	proxy->received_body = newbody;
-	proxy->received_body_size -= ret;
-  
-  if(0 == proxy->received_body_size && proxy->receiving_done)
-    {
-      PRINT_INFO("POST spdy EOF");
-    *eof = 1;
-  }
-  
-  PRINT_INFO2("given POST bytes to spdylay: %zd", ret);
-  
-  return ret;
-}
-
-
-/*
- * The implementation of spdylay_send_callback type. Here we write
- * |data| with size |length| to the network and return the number of
- * bytes actually written. See the documentation of
- * spdylay_send_callback for the details.
- */
-static ssize_t
-spdy_cb_send(spdylay_session *session,
-             const uint8_t *data,
-             size_t length,
-             int flags,
-             void *user_data)
-{
-  (void)session;
-  (void)flags;
-  
-  //PRINT_INFO("spdy_cb_send called");
-  struct SPDY_Connection *connection;
-  ssize_t rv;
-  connection = (struct SPDY_Connection*)user_data;
-  connection->want_io = IO_NONE;
-  
-  if(glob_opt.ignore_rst_stream
-    && 16 == length
-    && 0x80 == data[0]
-    && 0x00 == data[2]
-    && 0x03 == data[3]
-    )
-  {
-    PRINT_INFO2("ignoring RST_STREAM for stream_id %i %i %i %i", data[8], data[9], data[10], data[11]);
-    glob_opt.ignore_rst_stream = false;
-    return 16;
-  }
-  glob_opt.ignore_rst_stream = false;
-  
-  if(connection->is_tls)
-  {
-    ERR_clear_error();
-    rv = SSL_write(connection->ssl, data, length);
-    if(rv < 0) {
-      int err = SSL_get_error(connection->ssl, rv);
-      if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
-        connection->want_io |= (err == SSL_ERROR_WANT_READ ?
-                               WANT_READ : WANT_WRITE);
-        rv = SPDYLAY_ERR_WOULDBLOCK;
-      } else {
-        rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-      }
-    }
-  }
-  else
-  {
-    rv = write(connection->fd, 
-            data,
-            length);
-            
-    if (rv < 0)
-    {
-      switch(errno)
-      {				
-        case EAGAIN:
-  #if EAGAIN != EWOULDBLOCK
-        case EWOULDBLOCK:
-  #endif
-          connection->want_io |= WANT_WRITE;
-          rv = SPDYLAY_ERR_WOULDBLOCK;
-          break;
-          
-        default:
-          rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-      }
-    }
-  }
-  
-  PRINT_INFO2("%zd bytes written by spdy", rv);
-  
-  if(rv > 0)
-    UPDATE_STAT(glob_stat.spdy_bytes_sent, rv);
-  
-  return rv;
-}
-
-
-/*
- * The implementation of spdylay_recv_callback type. Here we read data
- * from the network and write them in |buf|. The capacity of |buf| is
- * |length| bytes. Returns the number of bytes stored in |buf|. See
- * the documentation of spdylay_recv_callback for the details.
- */
-static ssize_t
-spdy_cb_recv(spdylay_session *session,
-             uint8_t *buf,
-             size_t length, 
-             int flags,
-             void *user_data)
-{
-  (void)session;
-  (void)flags;
-  
-  struct SPDY_Connection *connection;
-  ssize_t rv;
-  
-  connection = (struct SPDY_Connection*)user_data;
-  //prevent monopolizing everything
-  if(!(++connection->counter % 10)) return SPDYLAY_ERR_WOULDBLOCK;
-  connection->want_io = IO_NONE;
-  if(connection->is_tls)
-  {
-    ERR_clear_error();
-    rv = SSL_read(connection->ssl, buf, length);
-    if(rv < 0) {
-      int err = SSL_get_error(connection->ssl, rv);
-      if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
-        connection->want_io |= (err == SSL_ERROR_WANT_READ ?
-                               WANT_READ : WANT_WRITE);
-        rv = SPDYLAY_ERR_WOULDBLOCK;
-      } else {
-        rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-      }
-    } else if(rv == 0) {
-      rv = SPDYLAY_ERR_EOF;
-    }
-  }
-  else
-  {
-    rv = read(connection->fd, 
-            buf,
-            length);
-            
-    if (rv < 0)
-    {
-      switch(errno)
-      {				
-        case EAGAIN:
-  #if EAGAIN != EWOULDBLOCK
-        case EWOULDBLOCK:
-  #endif
-          connection->want_io |= WANT_READ;
-          rv = SPDYLAY_ERR_WOULDBLOCK;
-          break;
-          
-        default:
-          rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-      }
-    }
-    else if(rv == 0)
-      rv = SPDYLAY_ERR_EOF;
-  }
-  
-  if(rv > 0)
-    UPDATE_STAT(glob_stat.spdy_bytes_received, rv);
-  
-  return rv;
-}
-
-
-static void
-spdy_cb_before_ctrl_send(spdylay_session *session,
-                    spdylay_frame_type type,
-                    spdylay_frame *frame,
-                    void *user_data)
-{
-  (void)user_data;
-  
-  int32_t stream_id;
-  struct Proxy *proxy;
-  
-  switch(type) {
-    case SPDYLAY_SYN_STREAM:
-      stream_id = frame->syn_stream.stream_id;
-      proxy = spdylay_session_get_stream_user_data(session, stream_id);
-      proxy->stream_id = stream_id;
-      ++glob_opt.streams_opened;
-      ++proxy->spdy_connection->streams_opened;
-      PRINT_INFO2("opening stream: str open %i; %s", glob_opt.streams_opened, proxy->url);
-      break;
-    case SPDYLAY_RST_STREAM:
-      //try to ignore duplicate RST_STREAMs
-      //TODO this will ignore RST_STREAMs also for bogus data
-      glob_opt.ignore_rst_stream = NULL==spdylay_session_get_stream_user_data(session, frame->rst_stream.stream_id);
-      PRINT_INFO2("sending RST_STREAM for %i; ignore %i; status %i",
-        frame->rst_stream.stream_id,
-        glob_opt.ignore_rst_stream,
-        frame->rst_stream.status_code);
-    break;
-    default:
-      break;
-  }
-}
-
-
-void
-spdy_cb_on_ctrl_recv(spdylay_session *session,
-                    spdylay_frame_type type,
-                    spdylay_frame *frame,
-                    void *user_data)
-{
-  (void)user_data;
-  
-  char **nv;
-  int32_t stream_id;
-  struct Proxy * proxy;
-
-  switch(type) {
-    case SPDYLAY_SYN_REPLY:
-      nv = frame->syn_reply.nv;
-      stream_id = frame->syn_reply.stream_id;
-    break;
-    case SPDYLAY_RST_STREAM:
-      stream_id = frame->rst_stream.stream_id;
-    break;
-    case SPDYLAY_HEADERS:
-      nv = frame->headers.nv;
-      stream_id = frame->headers.stream_id;
-    break;
-    default:
-      return;
-    break;
-  }
-
-  proxy = spdylay_session_get_stream_user_data(session, stream_id);
-  if(NULL == proxy)
-  {
-    PRINT_INFO2("received frame type %i for unkonwn stream id %i", type, stream_id);
-    return;
-    //DIE("no proxy obj");
-  }
-
-  switch(type) {
-    case SPDYLAY_SYN_REPLY:
-      PRINT_INFO2("received headers for %s", proxy->url);
-      http_create_response(proxy, nv);
-    break;
-    case SPDYLAY_RST_STREAM:
-      PRINT_INFO2("received reset stream for %s", proxy->url);
-      proxy->spdy_error = true;
-    break;
-    case SPDYLAY_HEADERS:
-      PRINT_INFO2("received headers for %s", proxy->url);
-      http_create_response(proxy, nv);
-    break;
-    default:
-      return;
-    break;
-  }
-  
-  glob_opt.spdy_data_received = true;
-}
-
-
-/*
- * The implementation of spdylay_on_stream_close_callback type. We use
- * this function to know the response is fully received. Since we just
- * fetch 1 resource in this program, after reception of the response,
- * we submit GOAWAY and close the session.
- */
-static void
-spdy_cb_on_stream_close(spdylay_session *session,
-                       int32_t stream_id,
-                       spdylay_status_code status_code,
-                       void *user_data)
-{
-  (void)status_code;
-  (void)user_data;
-  
-  struct Proxy * proxy = spdylay_session_get_stream_user_data(session, stream_id);
-  
-  assert(NULL != proxy);
-  
-  --glob_opt.streams_opened;
-  --proxy->spdy_connection->streams_opened;
-  PRINT_INFO2("closing stream: str opened %i; remove proxy %i", glob_opt.streams_opened, proxy->id);
-   
-  DLL_remove(proxy->spdy_connection->proxies_head, proxy->spdy_connection->proxies_tail, proxy); 
-  if(proxy->http_active)
-  {
-    proxy->spdy_active = false;
-  }
-  else
-  {
-    free_proxy(proxy);
-  }
-}
-
-
-/*
- * The implementation of spdylay_on_data_chunk_recv_callback type. We
- * use this function to print the received response body.
- */
-static void
-spdy_cb_on_data_chunk_recv(spdylay_session *session,
-                          uint8_t flags,
-                          int32_t stream_id,
-                          const uint8_t *data,
-                          size_t len,
-                          void *user_data)
-{
-  (void)flags;
-  (void)user_data;
-  
-  struct Proxy *proxy;
-  proxy = spdylay_session_get_stream_user_data(session, stream_id);
-  
-  if(NULL == proxy)
-  {
-    PRINT_INFO("proxy in spdy_cb_on_data_chunk_recv is NULL)");
-    return;
-	}
-  
-  if(!copy_buffer(data, len, &proxy->http_body, &proxy->http_body_size))
-  {
-    //TODO handle it better?
-    PRINT_INFO("not enough memory (malloc/realloc returned NULL)");
-    return;
-  }
-  /*
-	if(NULL == proxy->http_body)
-		proxy->http_body = au_malloc(len);
-  else
-		proxy->http_body = realloc(proxy->http_body, proxy->http_body_size + len);
-	if(NULL == proxy->http_body)
-	{
-		PRINT_INFO("not enough memory (realloc returned NULL)");
-		return ;
-	}
-
-	memcpy(proxy->http_body + proxy->http_body_size, data, len);
-	proxy->http_body_size += len;
-  */
-  PRINT_INFO2("received data for %s; %zu bytes", proxy->url, len);
-  glob_opt.spdy_data_received = true;
-}
-
-
-static void
-spdy_cb_on_data_recv(spdylay_session *session,
-		                 uint8_t flags,
-                     int32_t stream_id,
-                     int32_t length,
-                     void *user_data)
-{
-  (void)length;
-  (void)user_data;
-  
-	if(flags & SPDYLAY_DATA_FLAG_FIN)
-	{
-    struct Proxy *proxy;
-    proxy = spdylay_session_get_stream_user_data(session, stream_id);
-    proxy->done = true;
-    PRINT_INFO2("last data frame received for %s", proxy->url);
-	}
-}
-
-
-/*
- * Setup callback functions. Spdylay API offers many callback
- * functions, but most of them are optional. The send_callback is
- * always required. Since we use spdylay_session_recv(), the
- * recv_callback is also required.
- */
-static void
-spdy_setup_spdylay_callbacks(spdylay_session_callbacks *callbacks)
-{
-  memset(callbacks, 0, sizeof(spdylay_session_callbacks));
-  callbacks->send_callback = spdy_cb_send;
-  callbacks->recv_callback = spdy_cb_recv;
-  callbacks->before_ctrl_send_callback = spdy_cb_before_ctrl_send;
-  callbacks->on_ctrl_recv_callback = spdy_cb_on_ctrl_recv;
-  callbacks->on_stream_close_callback = spdy_cb_on_stream_close;
-  callbacks->on_data_chunk_recv_callback = spdy_cb_on_data_chunk_recv;
-  callbacks->on_data_recv_callback = spdy_cb_on_data_recv;
-}
-
-
-/*
- * Callback function for SSL/TLS NPN. Since this program only supports
- * SPDY protocol, if server does not offer SPDY protocol the Spdylay
- * library supports, we terminate program.
- */
-static int
-spdy_cb_ssl_select_next_proto(SSL* ssl,
-                                unsigned char **out,
-                                unsigned char *outlen,
-                                const unsigned char *in,
-                                unsigned int inlen,
-                                void *arg)
-{
-  (void)ssl;
-  
-  int rv;
-  uint16_t *spdy_proto_version;
-  
-  /* spdylay_select_next_protocol() selects SPDY protocol version the
-     Spdylay library supports. */
-  rv = spdylay_select_next_protocol(out, outlen, in, inlen);
-  if(rv <= 0) {
-    PRINT_INFO("Server did not advertise spdy/2 or spdy/3 protocol.");
-    return rv;
-  }
-  spdy_proto_version = (uint16_t*)arg;
-  *spdy_proto_version = rv;
-  return SSL_TLSEXT_ERR_OK;
-}
-
-
-/*
- * Setup SSL context. We pass |spdy_proto_version| to get negotiated
- * SPDY protocol version in NPN callback.
- */
-void
-spdy_ssl_init_ssl_ctx(SSL_CTX *ssl_ctx,
-                      uint16_t *spdy_proto_version)
-{
-  /* Disable SSLv2 and enable all workarounds for buggy servers */
-  SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2 | SSL_OP_NO_COMPRESSION);
-  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
-  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
-  /* Set NPN callback */
-  SSL_CTX_set_next_proto_select_cb(ssl_ctx, spdy_cb_ssl_select_next_proto,
-                                   spdy_proto_version);
-}
-
-
-static int
-spdy_ssl_handshake(SSL *ssl,
-                   int fd)
-{
-  int rv;
-  
-  if(SSL_set_fd(ssl, fd) == 0)
-    spdy_dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
-
-  ERR_clear_error();
-  rv = SSL_connect(ssl);
-  if(rv <= 0)
-    PRINT_INFO2("SSL_connect %s", ERR_error_string(ERR_get_error(), NULL));
-  
-  return rv;
-}
-
-
-/*
- * Connects to the host |host| and port |port|.  This function returns
- * the file descriptor of the client socket.
- */
-static int
-spdy_socket_connect_to(const char *host,
-                       uint16_t port)
-{
-  struct addrinfo hints;
-  int fd = -1;
-  int rv;
-  char service[NI_MAXSERV];
-  struct addrinfo *res, *rp;
-  
-  //TODO checks
-  snprintf(service, sizeof(service), "%u", port);
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;
-  hints.ai_socktype = SOCK_STREAM;
-  rv = getaddrinfo(host, service, &hints, &res);
-  if(rv != 0)
-  {
-	  printf("%s\n",host);
-    spdy_dief("getaddrinfo", gai_strerror(rv));
-  }
-  for(rp = res; rp; rp = rp->ai_next)
-  {
-    fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
-    if(fd == -1)
-      continue;
-    while((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
-          errno == EINTR);
-    if(rv == 0)
-      break;
-    close(fd);
-    fd = -1;
-  }
-  freeaddrinfo(res);
-  
-  return fd;
-}
-
-
-static void
-spdy_socket_make_non_block(int fd)
-{
-  int flags;
-  int rv;
-  
-  while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
-  
-  if(flags == -1)
-    spdy_dief("fcntl", strerror(errno));
-    
-  while((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR);
- 
-  if(rv == -1)
-    spdy_dief("fcntl", strerror(errno));
-}
-
-
-/*
- * Setting TCP_NODELAY is not mandatory for the SPDY protocol.
- */
-static void
-spdy_socket_set_tcp_nodelay(int fd)
-{
-  int val = 1;
-  int rv;
-  
-  rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
-  if(rv == -1)
-    spdy_dief("setsockopt", strerror(errno));
-}
-
-/*
- * Update |pollfd| based on the state of |connection|.
- */
- /*
-void
-spdy_ctl_poll(struct pollfd *pollfd,
-              struct SPDY_Connection *connection)
-{
-  pollfd->events = 0;
-  if(spdylay_session_want_read(connection->session) ||
-     connection->want_io & WANT_READ)
-  {
-    pollfd->events |= POLLIN;
-  }
-  if(spdylay_session_want_write(connection->session) ||
-     connection->want_io & WANT_WRITE)
-  {
-    pollfd->events |= POLLOUT;
-  }
-}*/
-
-
-/*
- * Update |selectfd| based on the state of |connection|.
- */
-bool
-spdy_ctl_select(fd_set * read_fd_set,
-                fd_set * write_fd_set, 
-                fd_set * except_fd_set,
-                struct SPDY_Connection *connection)
-{
-  (void)except_fd_set;
-  
-  bool ret = false;
-  
-  if(spdylay_session_want_read(connection->session) ||
-     connection->want_io & WANT_READ)
-  {
-    FD_SET(connection->fd, read_fd_set);
-    ret = true;
-  }
-  if(spdylay_session_want_write(connection->session) ||
-     connection->want_io & WANT_WRITE)
-  {
-    FD_SET(connection->fd, write_fd_set);
-    ret = true;
-  }
-  
-  return ret;
-}
-
-
-/*
- * Performs the network I/O.
- */
-int
-spdy_exec_io(struct SPDY_Connection *connection)
-{
-  int rv;
-  
-  rv = spdylay_session_recv(connection->session);
-  if(rv != 0)
-  {
-    PRINT_INFO2("spdylay_session_recv %i", rv);
-    return rv;
-  }
-  rv = spdylay_session_send(connection->session);
-  if(rv != 0)
-    PRINT_INFO2("spdylay_session_send %i", rv);
-    
-  return rv;
-}
-
-
-/*
- * Fetches the resource denoted by |uri|.
- */
-struct SPDY_Connection *
-spdy_connect(const struct URI *uri,
-             uint16_t port,
-             bool is_tls)
-{
-  spdylay_session_callbacks callbacks;
-  int fd;
-  SSL *ssl=NULL;
-  struct SPDY_Connection * connection = NULL;
-  int rv;
-
-  spdy_setup_spdylay_callbacks(&callbacks);
-
-  /* Establish connection and setup SSL */
-  PRINT_INFO2("connecting to %s:%i", uri->host, port);
-  fd = spdy_socket_connect_to(uri->host, port);
-  if(fd == -1)
-  {
-    PRINT_INFO("Could not open file descriptor");
-    return NULL;
-  }
-  
-  if(is_tls)
-  {
-    ssl = SSL_new(glob_opt.ssl_ctx);
-    if(ssl == NULL) {
-      spdy_dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
-    }
-    
-    //TODO non-blocking
-    /* To simplify the program, we perform SSL/TLS handshake in blocking
-       I/O. */
-    glob_opt.spdy_proto_version = 0;
-    rv = spdy_ssl_handshake(ssl, fd);
-    if(rv <= 0 || (glob_opt.spdy_proto_version != 3 && glob_opt.spdy_proto_version != 2))
-    {
-      PRINT_INFO("Closing SSL");
-      //no spdy on the other side
-      goto free_and_fail;
-    }
-  }
-  else
-  {
-    glob_opt.spdy_proto_version = 3;
-  }
-
-  if(NULL == (connection = au_malloc(sizeof(struct SPDY_Connection))))
-    goto free_and_fail;
-  
-  connection->is_tls = is_tls;
-  connection->ssl = ssl;
-  connection->want_io = IO_NONE;
-  if(NULL == (connection->host = strdup(uri->host)))
-    goto free_and_fail;
-
-  /* Here make file descriptor non-block */
-  spdy_socket_make_non_block(fd);
-  spdy_socket_set_tcp_nodelay(fd);
-
-  PRINT_INFO2("[INFO] SPDY protocol version = %d\n", glob_opt.spdy_proto_version);
-  rv = spdylay_session_client_new(&(connection->session), glob_opt.spdy_proto_version,
-                                  &callbacks, connection);
-  if(rv != 0) {
-    spdy_diec("spdylay_session_client_new", rv);
-  }
-  
-  connection->fd = fd;
-
-	return connection;
-  
-	//for GOTO
-	free_and_fail:
-  if(NULL != connection)
-  {
-    free(connection->host);
-    free(connection);
-  }
-  
-  if(is_tls)
-    SSL_shutdown(ssl);
-    
-  close(fd);
-  
-  if(is_tls)
-    SSL_free(ssl);
-  
-  return NULL;
-}
-
-
-void
-spdy_free_connection(struct SPDY_Connection * connection)
-{
-  struct Proxy *proxy;
-  struct Proxy *proxy_next;
-  
-  if(NULL != connection)
-  {
-    for(proxy = connection->proxies_head; NULL != proxy; proxy=proxy_next)
-    {
-      proxy_next = proxy->next;
-      DLL_remove(connection->proxies_head, connection->proxies_tail, proxy);
-      proxy->spdy_active = false;
-      proxy->spdy_error = true;
-      PRINT_INFO2("spdy_free_connection for id %i", proxy->id);
-      if(!proxy->http_active)
-      {
-        free_proxy(proxy);
-      }
-    }
-    spdylay_session_del(connection->session);
-    SSL_free(connection->ssl);
-    free(connection->host);
-    free(connection);
-    //connection->session = NULL;
-  }
-}
-
-
-int
-spdy_request(const char **nv,
-             struct Proxy *proxy,
-             bool with_body)
-{
-  int ret;
-  uint16_t port;
-  struct SPDY_Connection *connection;
-  spdylay_data_provider post_data;
-  
-  if(glob_opt.only_proxy)
-  {
-    connection = glob_opt.spdy_connection;
-  }
-  else
-  {
-    connection = glob_opt.spdy_connections_head;
-    while(NULL != connection)
-    {
-      if(0 == strcasecmp(proxy->uri->host, connection->host))
-        break;
-      connection = connection->next;
-    }
-  
-    if(NULL == connection)
-    {
-      //connect to host
-      port = proxy->uri->port;
-      if(0 == port) port = 443;
-      connection = spdy_connect(proxy->uri, port, true);
-      if(NULL != connection)
-      {
-        DLL_insert(glob_opt.spdy_connections_head, glob_opt.spdy_connections_tail, connection);
-        glob_opt.total_spdy_connections++;
-      }
-      else
-        connection = glob_opt.spdy_connection;
-    }
-  }
-  
-  if(NULL == connection)
-  {
-    PRINT_INFO("there is no proxy!");
-    return -1;
-  }
-  
-  proxy->spdy_connection = connection;
-  if(with_body)
-  {
-    post_data.source.ptr = proxy;
-    post_data.read_callback = &spdy_cb_data_source_read;
-    ret = spdylay_submit_request(connection->session, 0, nv, &post_data, proxy);
-  }
-  else
-    ret = spdylay_submit_request(connection->session, 0, nv, NULL, proxy);
-  
-  if(ret != 0) {
-    spdy_diec("spdylay_spdy_submit_request", ret);
-  }
-  PRINT_INFO2("adding proxy %i", proxy->id);
-  if(NULL != connection->proxies_head)
-    PRINT_INFO2("before proxy %i", connection->proxies_head->id);
-  DLL_insert(connection->proxies_head, connection->proxies_tail, proxy);
-  
-  return ret;
-}
-
-/*
-void
-spdy_get_pollfdset(struct pollfd fds[],
-                   struct SPDY_Connection *connections[],
-                   unsigned int max_size,
-                   nfds_t *real_size)
-{
-  struct SPDY_Connection *connection;
-  struct Proxy *proxy;
-  
-  *real_size = 0;
-  if(max_size<1)
-    return;
-    
-  if(NULL != glob_opt.spdy_connection)
-  {
-    spdy_ctl_poll(&(fds[*real_size]), glob_opt.spdy_connection);
-    if(!fds[*real_size].events)
-    {
-      //PRINT_INFO("TODO drop connection");
-      glob_opt.streams_opened -= glob_opt.spdy_connection->streams_opened;
-      
-      for(proxy = glob_opt.spdy_connection->proxies_head; NULL != proxy; proxy=proxy->next)
-      {
-        abort();
-        DLL_remove(glob_opt.spdy_connection->proxies_head, glob_opt.spdy_connection->proxies_tail, proxy);
-        proxy->spdy_active = false;
-      }
-      spdy_free_connection(glob_opt.spdy_connection);
-      glob_opt.spdy_connection = NULL;
-    }
-    else
-    {
-      fds[*real_size].fd = glob_opt.spdy_connection->fd;
-      connections[*real_size] = glob_opt.spdy_connection;
-      ++(*real_size);
-    }
-  }
-  
-  connection = glob_opt.spdy_connections_head;
-  
-  while(NULL != connection && *real_size < max_size)
-  {
-    assert(!glob_opt.only_proxy);
-    spdy_ctl_poll(&(fds[*real_size]), connection);
-    if(!fds[*real_size].events)
-    {
-      //PRINT_INFO("TODO drop connection");
-      glob_opt.streams_opened -= connection->streams_opened;
-      DLL_remove(glob_opt.spdy_connections_head, glob_opt.spdy_connections_tail, connection);
-      glob_opt.total_spdy_connections--;
-      
-      for(proxy = connection->proxies_head; NULL != proxy; proxy=proxy->next)
-      {
-        abort();
-        DLL_remove(connection->proxies_head, connection->proxies_tail, proxy);
-        proxy->spdy_active = false;
-      }
-      spdy_free_connection(connection);
-    }
-    else
-    {
-      fds[*real_size].fd = connection->fd;
-      connections[*real_size] = connection;
-      ++(*real_size);
-    }
-    connection = connection->next;
-  }
-  
-  //, "TODO max num of conn reached; close something"
-  assert(NULL == connection);
-}
-*/
-
-int
-spdy_get_selectfdset(fd_set * read_fd_set,
-                      fd_set * write_fd_set, 
-                      fd_set * except_fd_set,
-                      struct SPDY_Connection *connections[],
-                      unsigned int max_size,
-                      nfds_t *real_size)
-{
-  struct SPDY_Connection *connection;
-  struct SPDY_Connection *next_connection;
-  bool ret;
-  int maxfd = 0;
-  
-  *real_size = 0;
-  if(max_size<1)
-    return 0;
-    
-  if(NULL != glob_opt.spdy_connection)
-  {
-    ret = spdy_ctl_select(read_fd_set,
-				 write_fd_set, 
-				 except_fd_set, glob_opt.spdy_connection);
-    if(!ret)
-    {
-      glob_opt.streams_opened -= glob_opt.spdy_connection->streams_opened;
-      
-      PRINT_INFO("spdy_free_connection in spdy_get_selectfdset");
-      spdy_free_connection(glob_opt.spdy_connection);
-      glob_opt.spdy_connection = NULL;
-    }
-    else
-    {
-      connections[*real_size] = glob_opt.spdy_connection;
-      ++(*real_size);
-      if(maxfd < glob_opt.spdy_connection->fd) maxfd = glob_opt.spdy_connection->fd;
-    }
-  }
-  
-  connection = glob_opt.spdy_connections_head;
-  
-  while(NULL != connection && *real_size < max_size)
-  {
-    assert(!glob_opt.only_proxy);
-    ret = spdy_ctl_select(read_fd_set,
-				 write_fd_set, 
-				 except_fd_set, connection);
-         
-    next_connection = connection->next;
-    if(!ret)
-    {
-      glob_opt.streams_opened -= connection->streams_opened;
-      DLL_remove(glob_opt.spdy_connections_head, glob_opt.spdy_connections_tail, connection);
-      glob_opt.total_spdy_connections--;
-      
-      PRINT_INFO("spdy_free_connection in spdy_get_selectfdset");
-      spdy_free_connection(connection);
-    }
-    else
-    {
-      connections[*real_size] = connection;
-      ++(*real_size);
-      if(maxfd < connection->fd) maxfd = connection->fd;
-    }
-    connection = next_connection;
-  }
-  
-  //, "TODO max num of conn reached; close something"
-  assert(NULL == connection);
-  
-  return maxfd;
-}
-
-/*
-void
-spdy_run(struct pollfd fds[],
-         struct SPDY_Connection *connections[],
-         int size)
-{
-  int i;
-  int ret;
-  struct Proxy *proxy;
-  
-  for(i=0; i<size; ++i)
-  {
-    //  PRINT_INFO2("exec about to be called for %s", connections[i]->host);
-    if(fds[i].revents & (POLLIN | POLLOUT))
-    {
-      ret = spdy_exec_io(connections[i]);
-      //PRINT_INFO2("%i",ret);
-      //if((spdy_pollfds[i].revents & POLLHUP) || (spdy_pollfds[0].revents & POLLERR))
-      //  PRINT_INFO("SPDY SPDY_Connection error");
-      
-      //TODO POLLRDHUP
-      // always close on ret != 0?
-        
-      if(0 != ret)
-      {
-        glob_opt.streams_opened -= connections[i]->streams_opened;
-        if(connections[i] == glob_opt.spdy_connection)
-        {
-          glob_opt.spdy_connection = NULL;
-        }
-        else
-        {
-          DLL_remove(glob_opt.spdy_connections_head, glob_opt.spdy_connections_tail, connections[i]);
-          glob_opt.total_spdy_connections--;
-        }
-        for(proxy = connections[i]->proxies_head; NULL != proxy; proxy=proxy->next)
-        {
-        abort();
-          DLL_remove(connections[i]->proxies_head, connections[i]->proxies_tail, proxy);
-          proxy->spdy_active = false;
-          proxy->spdy_error = true;
-          PRINT_INFO2("spdy_free_connection for id %i", proxy->id);
-        }
-        PRINT_INFO("spdy_free_connection in loop");
-        spdy_free_connection(connections[i]);
-      }
-    }
-    else
-      PRINT_INFO("not called");
-  }
-}
-*/
-
-void
-spdy_run_select(fd_set * read_fd_set,
-                fd_set * write_fd_set, 
-                fd_set * except_fd_set,
-                struct SPDY_Connection *connections[],
-                int size)
-{
-  int i;
-  int ret;
-  
-  for(i=0; i<size; ++i)
-  {
-    //  PRINT_INFO2("exec about to be called for %s", connections[i]->host);
-    if(FD_ISSET(connections[i]->fd, read_fd_set) || FD_ISSET(connections[i]->fd, write_fd_set) || FD_ISSET(connections[i]->fd, except_fd_set))
-    {
-      //raise(SIGINT);
-      ret = spdy_exec_io(connections[i]);
-        
-      if(0 != ret)
-      {
-        glob_opt.streams_opened -= connections[i]->streams_opened;
-        if(connections[i] == glob_opt.spdy_connection)
-        {
-          glob_opt.spdy_connection = NULL;
-        }
-        else
-        {
-          DLL_remove(glob_opt.spdy_connections_head, glob_opt.spdy_connections_tail, connections[i]);
-          glob_opt.total_spdy_connections--;
-        }
-        PRINT_INFO("in spdy_run_select");
-        spdy_free_connection(connections[i]);
-      }
-    }
-    else
-    {
-      PRINT_INFO("not called");
-      //PRINT_INFO2("connection->want_io %i",connections[i]->want_io);
-      //PRINT_INFO2("read %i",spdylay_session_want_read(connections[i]->session));
-      //PRINT_INFO2("write %i",spdylay_session_want_write(connections[i]->session));
-      //raise(SIGINT);
-    }
-  }
-}
diff --git a/src/examples/mhd2spdy_spdy.h b/src/examples/mhd2spdy_spdy.h
deleted file mode 100644
index 4207c62..0000000
--- a/src/examples/mhd2spdy_spdy.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file mhd2spdy_spdy.h
- * @brief  SPDY part of the proxy. libspdylay is used for the client side.
- * @author Andrey Uzunov
- */
- 
-#ifndef SPDY_H
-#define SPDY_H
-
-#include "mhd2spdy_structures.h"
-
-
-struct SPDY_Connection *
-spdy_connect(const struct URI *uri,
-             uint16_t port,
-             bool is_tls);
-
-
-void
-spdy_ctl_poll(struct pollfd *pollfd,
-              struct SPDY_Connection *connection);
-
-
-bool
-spdy_ctl_select(fd_set * read_fd_set,
-                fd_set * write_fd_set, 
-                fd_set * except_fd_set,
-                struct SPDY_Connection *connection);
-
-
-int
-spdy_exec_io(struct SPDY_Connection *connection);
-
-
-void
-spdy_diec(const char *func,
-          int error_code);
-
-
-int 
-spdy_request(const char **nv,
-             struct Proxy *proxy,
-             bool with_body);
-
-
-void
-spdy_ssl_init_ssl_ctx(SSL_CTX *ssl_ctx,
-                      uint16_t *spdy_proto_version);
-
-
-void
-spdy_free_connection(struct SPDY_Connection * connection);
-
-
-void
-spdy_get_pollfdset(struct pollfd fds[],
-                   struct SPDY_Connection *connections[],
-                   unsigned int max_size,
-                   nfds_t *real_size);
-
-
-int
-spdy_get_selectfdset(fd_set * read_fd_set,
-                    fd_set * write_fd_set, 
-                    fd_set * except_fd_set,
-                    struct SPDY_Connection *connections[],
-                    unsigned int max_size,
-                    nfds_t *real_size);
-
-
-void
-spdy_run(struct pollfd fds[],
-        struct SPDY_Connection *connections[],
-        int size);
-
-
-void
-spdy_run_select(fd_set * read_fd_set,
-                fd_set * write_fd_set, 
-                fd_set * except_fd_set,
-                struct SPDY_Connection *connections[],
-                int size);
-
-
-#endif
diff --git a/src/examples/mhd2spdy_structures.c b/src/examples/mhd2spdy_structures.c
deleted file mode 100644
index 6d4a407..0000000
--- a/src/examples/mhd2spdy_structures.c
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file mhd2spdy_structures.h
- * @brief  Common functions, macros.
- * @author Andrey Uzunov
- */
- 
-#include "mhd2spdy_structures.h"
-
-
-void
-free_uri(struct URI * uri)
-{
-  if(NULL != uri)
-  {
-    free(uri->full_uri);
-    free(uri->scheme);
-    free(uri->host_and_port);
-    free(uri->host);
-    free(uri->path);
-    free(uri->path_and_more);
-    free(uri->query);
-    free(uri->fragment);
-    uri->port = 0;
-    free(uri);
-  }
-}
-
-
-int
-init_parse_uri(regex_t * preg)
-{
-  // RFC 2396
-  // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
-      /*
-        scheme    = $2
-      authority = $4
-      path      = $5
-      query     = $7
-      fragment  = $9
-      */
-  
-  return regcomp(preg, "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", REG_EXTENDED);
-}
-
-void
-deinit_parse_uri(regex_t * preg)
-{
-  regfree(preg);
-}
-  
-int
-parse_uri(regex_t * preg,
-          char * full_uri,
-          struct URI ** uri)
-{
-  int ret;
-  char *colon;
-  long long port;
-  size_t nmatch = 10;
-  regmatch_t pmatch[10];
-
-  if (0 != (ret = regexec(preg, full_uri, nmatch, pmatch, 0)))
-    return ret;
-    
-  *uri = au_malloc(sizeof(struct URI));
-  if(NULL == *uri)
-    return -200;
-    
-  (*uri)->full_uri = strdup(full_uri);
-  
-  asprintf(&((*uri)->scheme), "%.*s",pmatch[2].rm_eo - pmatch[2].rm_so, &full_uri[pmatch[2].rm_so]);
-  asprintf(&((*uri)->host_and_port), "%.*s",pmatch[4].rm_eo - pmatch[4].rm_so, &full_uri[pmatch[4].rm_so]);
-  asprintf(&((*uri)->path), "%.*s",pmatch[5].rm_eo - pmatch[5].rm_so, &full_uri[pmatch[5].rm_so]);
-  asprintf(&((*uri)->path_and_more), "%.*s",pmatch[9].rm_eo - pmatch[5].rm_so, &full_uri[pmatch[5].rm_so]);
-  asprintf(&((*uri)->query), "%.*s",pmatch[7].rm_eo - pmatch[7].rm_so, &full_uri[pmatch[7].rm_so]);
-  asprintf(&((*uri)->fragment), "%.*s",pmatch[9].rm_eo - pmatch[9].rm_so, &full_uri[pmatch[9].rm_so]);
-  
-  colon = strrchr((*uri)->host_and_port, ':');
-  if(NULL == colon)
-  {
-    (*uri)->host = strdup((*uri)->host_and_port);
-    (*uri)->port = 0;
-   
-    return 0;
-  }
-  
-  port = atoi(colon  + 1);
-  if(port<1 || port >= 256 * 256)
-  {
-    free_uri(*uri);
-    return -100;
-  }
-  (*uri)->port = port;
-  asprintf(&((*uri)->host), "%.*s", (int)(colon - (*uri)->host_and_port), (*uri)->host_and_port);
-  
-  return 0;
-}
-
-
-void
-free_proxy(struct Proxy *proxy)
-{
-  PRINT_INFO2("free proxy called for '%s'", proxy->url);
-  if(NULL != proxy->http_body && proxy->http_body_size > 0)
-    UPDATE_STAT(glob_stat.spdy_bytes_received_and_dropped, proxy->http_body_size);
-  free(proxy->http_body);
-  free_uri(proxy->uri);
-	free(proxy->url);
-	free(proxy->http_uri);
-	free(proxy);
-}
-
-
-void *au_malloc(size_t size)
-{
-  void *new_memory;
-  
-  new_memory = malloc(size);
-  if(NULL != new_memory)
-  {
-    glob_opt.global_memory += size;
-    memset(new_memory, 0, size);
-  }
-  return new_memory;
-}
-
-
-bool
-copy_buffer(const void *src, size_t src_size, void **dst, size_t *dst_size)
-{
-  if(0 == src_size)
-    return true;
-  
-  if(NULL == *dst)
-		*dst = malloc(src_size);
-	else
-		*dst = realloc(*dst, src_size + *dst_size);
-	if(NULL == *dst)
-		return false;
-
-	memcpy(*dst + *dst_size, src, src_size);
-	*dst_size += src_size;
-  
-  return true;
-}
diff --git a/src/examples/mhd2spdy_structures.h b/src/examples/mhd2spdy_structures.h
deleted file mode 100644
index f567934..0000000
--- a/src/examples/mhd2spdy_structures.h
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file mhd2spdy_structures.h
- * @brief  Common structures, functions, macros and global variables.
- * @author Andrey Uzunov
- */
-#ifndef STRUCTURES_H
-#define STRUCTURES_H
-
-#define _GNU_SOURCE
- 
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <errno.h>
-#include <assert.h>
-#include <microhttpd.h>
-#include <signal.h>
-#include <poll.h>
-#include <fcntl.h>
-#include <regex.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <openssl/ssl.h>
-#include <openssl/err.h>
-#include <spdylay/spdylay.h>
-#include <getopt.h>
-
-
-/* WANT_READ if SSL connection needs more input; or WANT_WRITE if it
-   needs more output; or IO_NONE. This is necessary because SSL/TLS
-   re-negotiation is possible at any time. Spdylay API offers
-   similar functions like spdylay_session_want_read() and
-   spdylay_session_want_write() but they do not take into account
-   SSL connection. */
-enum
-{
-  IO_NONE,
-  WANT_READ,
-  WANT_WRITE
-};
-
-
-struct Proxy;
-
-
-struct SPDY_Connection {
-  SSL *ssl;
-  spdylay_session *session;
-  struct SPDY_Connection *prev;
-  struct SPDY_Connection *next;
-  struct Proxy *proxies_head;
-  struct Proxy *proxies_tail;
-  char *host;
-  int fd;
-  int want_io;
-  uint counter;
-  uint streams_opened;
-  bool is_tls;
-};
-
-
-struct URI
-{
-  char * full_uri;
-  char * scheme;
-  char * host_and_port;
-  char * host;
-  char * path;
-  char * path_and_more;
-  char * query;
-  char * fragment;
-  uint16_t port;
-};
-
-
-struct HTTP_URI;
-
-
-struct Proxy
-{
-	struct MHD_Connection *http_connection;
-	struct MHD_Response *http_response;
-	struct URI *uri;
-  struct HTTP_URI *http_uri;
-  struct SPDY_Connection *spdy_connection;
-  struct Proxy *next;
-  struct Proxy *prev;
-	char *url;
-	char *version;
-	void *http_body;
-	void *received_body;
-	size_t http_body_size;
-	size_t received_body_size;
-	ssize_t length;
-	int status;
-	int id;
-  int32_t stream_id;
-	bool done;
-	bool http_error;
-	bool spdy_error;
-  bool http_active;
-  bool spdy_active;
-  bool receiving_done;
-};
-
-
-struct HTTP_URI
-{
-  char * uri;
-  struct Proxy * proxy;
-};
-
-
-struct SPDY_Headers
-{
-  const char **nv;
-  int num;
-  int cnt;
-};
-
-
-struct global_options
-{
-  char *spdy2http_str;
-  struct SPDY_Connection *spdy_connection;
-  struct SPDY_Connection *spdy_connections_head;
-  struct SPDY_Connection *spdy_connections_tail;
-  int streams_opened;
-  int responses_pending;
-  regex_t uri_preg;
-  size_t global_memory;
-  SSL_CTX *ssl_ctx;
-  uint32_t total_spdy_connections;
-  uint16_t spdy_proto_version;
-  uint16_t listen_port;
-  bool verbose;
-  bool only_proxy;
-  bool spdy_data_received;
-  bool statistics;
-  bool ignore_rst_stream;
-}
-glob_opt;
-
-
-struct global_statistics
-{
-  //unsigned long long http_bytes_sent;
-  //unsigned long long http_bytes_received;
-  unsigned long long spdy_bytes_sent;
-  unsigned long long spdy_bytes_received;
-  unsigned long long spdy_bytes_received_and_dropped;
-}
-glob_stat;
-
-
-//forbidden headers
-#define SPDY_HTTP_HEADER_TRANSFER_ENCODING "transfer-encoding"
-#define SPDY_HTTP_HEADER_PROXY_CONNECTION "proxy-connection"
-#define SPDY_HTTP_HEADER_KEEP_ALIVE "keep-alive"
-#define SPDY_HTTP_HEADER_CONNECTION "connection"
-
-#define MAX_SPDY_CONNECTIONS 100
-
-#define SPDY_MAX_OUTLEN 4096
-
-/**
- * Insert an element at the head of a DLL. Assumes that head, tail and
- * element are structs with prev and next fields.
- *
- * @param head pointer to the head of the DLL (struct ? *)
- * @param tail pointer to the tail of the DLL (struct ? *)
- * @param element element to insert (struct ? *)
- */
-#define DLL_insert(head,tail,element) do { \
-	(element)->next = (head); \
-	(element)->prev = NULL; \
-	if ((tail) == NULL) \
-		(tail) = element; \
-	else \
-		(head)->prev = element; \
-	(head) = (element); } while (0)
-
-
-/**
- * Remove an element from a DLL. Assumes
- * that head, tail and element are structs
- * with prev and next fields.
- *
- * @param head pointer to the head of the DLL (struct ? *)
- * @param tail pointer to the tail of the DLL (struct ? *)
- * @param element element to remove (struct ? *)
- */
-#define DLL_remove(head,tail,element) do { \
-	if ((element)->prev == NULL) \
-		(head) = (element)->next;  \
-	else \
-		(element)->prev->next = (element)->next; \
-	if ((element)->next == NULL) \
-		(tail) = (element)->prev;  \
-	else \
-		(element)->next->prev = (element)->prev; \
-	(element)->next = NULL; \
-	(element)->prev = NULL; } while (0)
-
-
-#define PRINT_INFO(msg) do{\
-  if(glob_opt.verbose){\
-	printf("%i:%s\n", __LINE__, msg);\
-	fflush(stdout);\
-	}\
-  }\
-	while(0)
-
-
-#define PRINT_INFO2(fmt, ...) do{\
-  if(glob_opt.verbose){\
-	printf("%i\n", __LINE__);\
-	printf(fmt,##__VA_ARGS__);\
-	printf("\n");\
-	fflush(stdout);\
-	}\
-	}\
-	while(0)
-  
-
-#define DIE(msg) do{\
-	printf("FATAL ERROR (line %i): %s\n", __LINE__, msg);\
-	fflush(stdout);\
-  exit(EXIT_FAILURE);\
-	}\
-	while(0)
-  
-  
-#define UPDATE_STAT(stat, value) do{\
-  if(glob_opt.statistics)\
-  {\
-    stat += value;\
-  }\
-  }\
-  while(0)
-
-
-void
-free_uri(struct URI * uri);
-
-
-int
-init_parse_uri(regex_t * preg);
-
-
-void
-deinit_parse_uri(regex_t * preg);
-
-
-int
-parse_uri(regex_t * preg,
-          char * full_uri,
-          struct URI ** uri);
-
-
-void
-free_proxy(struct Proxy *proxy);
-
-
-void *
-au_malloc(size_t size);
-
-
-bool
-copy_buffer(const void *src, size_t src_size, void **dst, size_t *dst_size);
-
-#endif
diff --git a/src/examples/minimal_example.c b/src/examples/minimal_example.c
index 313651c..f3fb1c8 100644
--- a/src/examples/minimal_example.c
+++ b/src/examples/minimal_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,61 +21,91 @@
  * @file minimal_example.c
  * @brief minimal example for how to use libmicrohttpd
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head>" \
+  "<body>libmicrohttpd demo</body></html>"
 
-static int
+struct handler_param
+{
+  const char *response_page;
+};
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
 {
   static int aptr;
-  const char *me = cls;
+  struct handler_param *param = (struct handler_param *) cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
-  response = MHD_create_response_from_buffer (strlen (me),
-					      (void *) me,
-					      MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response =
+    MHD_create_response_from_buffer_static (strlen (param->response_page),
+                                            param->response_page);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
 
+
 int
-main (int argc, char *const *argv)
+main (int argc,
+      char *const *argv)
 {
   struct MHD_Daemon *d;
+  struct handler_param data_for_handler;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (// MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | MHD_USE_POLL,
-			MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-			// MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG | MHD_USE_POLL,
-			// MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
-			MHD_OPTION_END);
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  data_for_handler.response_page = PAGE;
+  d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+    /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    (uint16_t) port,
+    NULL, NULL, &ahc_echo, &data_for_handler,
+    MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+    MHD_OPTION_END);
   if (d == NULL)
     return 1;
   (void) getc (stdin);
diff --git a/src/examples/minimal_example_comet.c b/src/examples/minimal_example_comet.c
index 0c9d264..193c605 100644
--- a/src/examples/minimal_example_comet.c
+++ b/src/examples/minimal_example_comet.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,6 +21,7 @@
  * @file minimal_example.c
  * @brief minimal example for how to generate an infinite stream with libmicrohttpd
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -28,6 +30,8 @@
 static ssize_t
 data_generator (void *cls, uint64_t pos, char *buf, size_t max)
 {
+  (void) cls; /* Unused. Silent compiler warning. */
+  (void) pos; /* Unused. Silent compiler warning. */
   if (max < 80)
     return 0;
   memset (buf, 'A', max - 1);
@@ -35,27 +39,33 @@
   return 80;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
   response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
                                                 80,
                                                 &data_generator, NULL, NULL);
@@ -64,18 +74,28 @@
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
                         NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
diff --git a/src/examples/minimal_example_empty.c b/src/examples/minimal_example_empty.c
new file mode 100644
index 0000000..2c76654
--- /dev/null
+++ b/src/examples/minimal_example_empty.c
@@ -0,0 +1,102 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file minimal_example.c
+ * @brief minimal example for how to use libmicrohttpd
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "platform.h"
+#include <microhttpd.h>
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_NO_CONTENT,
+                            response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  struct MHD_Daemon *d;
+  int port;
+
+  if (argc != 2)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+    /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    (uint16_t) port,
+    NULL, NULL, &ahc_echo, NULL,
+    MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+    MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/examples/minimal_example_empty_tls.c b/src/examples/minimal_example_empty_tls.c
new file mode 100644
index 0000000..d0a4d6f
--- /dev/null
+++ b/src/examples/minimal_example_empty_tls.c
@@ -0,0 +1,174 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2021-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file minimal_example_empty_tls.c
+ * @brief minimal example for how to use libmicrohttpd
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "platform.h"
+#include <microhttpd.h>
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_NO_CONTENT,
+                            response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+/* test server key */
+static const char srv_signed_key_pem[] =
+  "-----BEGIN PRIVATE KEY-----\n\
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\
+rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\
+UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\
++sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\
+HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\
+CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\
+dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\
++SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\
+XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\
+znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\
+pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\
+D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\
+Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\
+pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\
+zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\
+pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\
+KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\
+W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\
+OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\
+XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\
+wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\
+ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\
+0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\
+ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\
+QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\
+qdJNJ1DkyUc9dN2cliX4R+rG\n\
+-----END PRIVATE KEY-----";
+
+/* test server CA signed certificates */
+static const char srv_signed_cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n\
+MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\
+NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\
+c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\
+psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\
+atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\
+7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\
+n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\
+qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\
+kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\
+AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\
+c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\
+8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\
+IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\
+Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\
+X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\
+aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\
+HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\
+hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\
+18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\
+UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\
+B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\
+SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\
+WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\
+OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\
+/w0gW9EVWzFhsFeGEssi\n\
+-----END CERTIFICATE-----";
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  struct MHD_Daemon *d;
+  int port;
+
+  if (argc != 2)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+    | MHD_USE_TLS,
+    /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */
+    /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */
+    (uint16_t) port,
+    NULL, NULL, &ahc_echo, NULL,
+    MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+    MHD_OPTION_CLIENT_DISCIPLINE_LVL, (int) 1,
+    /* Optionally, the gnutls_load_file() can be used to
+       load the key and the certificate from file. */
+    MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
+    MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
+    MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/examples/msgs_i18n.c b/src/examples/msgs_i18n.c
new file mode 100644
index 0000000..5d563e4
--- /dev/null
+++ b/src/examples/msgs_i18n.c
@@ -0,0 +1,96 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2017 Christian Grothoff, Silvio Clecio (silvioprog)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file msgs_i18n.c
+ * @brief example for how to use translate libmicrohttpd messages
+ * @author Christian Grothoff
+ * @author Silvio Clecio (silvioprog)
+ */
+
+/*
+ * supposing you are in Brazil:
+ *
+ * # generate the PO file
+ * $ msginit --input=po/libmicrohttpd.pot --locale=pt_BR --output=libmicrohttpd.po
+ * # open the generated .po in any program like Poedit and translate the MHD messages; once done, let's go to the test:
+ * mkdir -p src/examples/locale/pt_BR/LC_MESSAGES
+ * mv libmicrohttpd.mo libmicrohttpd.po src/examples/locale/pt_BR/LC_MESSAGES
+ * cd src/examples/
+ * gcc -o msgs_i18n msgs_i18n.c -lmicrohttpd
+ * export LANGUAGE=pt_BR
+ * ./msgs_i18n
+ * # it may print: Opção inválida 4196490! (Você terminou a lista com MHD_OPTION_END?)
+ */
+#include <stdio.h>
+#include <locale.h>
+#include <libintl.h>
+#include <microhttpd.h>
+
+
+static int
+ahc_echo (void *cls,
+          struct MHD_Connection *cnc,
+          const char *url,
+          const char *mt,
+          const char *ver,
+          const char *upd,
+          size_t *upsz,
+          void **req_cls)
+{
+  return MHD_NO;
+}
+
+
+static void
+error_handler (void *cls,
+               const char *fm,
+               va_list ap)
+{
+  /* Here we do the translation using GNU gettext.
+     As the error message is from libmicrohttpd, we specify
+     "libmicrohttpd" as the translation domain here. */
+  vprintf (dgettext ("libmicrohttpd",
+                     fm),
+           ap);
+}
+
+
+int
+main (int argc,
+      char **argv)
+{
+  setlocale (LC_ALL, "");
+
+  /* The example uses PO files in the directory
+     "libmicrohttpd/src/examples/locale".  This
+     needs to be adapted to match
+     where the MHD PO files are installed. */
+  bindtextdomain ("libmicrohttpd",
+                  "locale");
+  MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_FEATURE_MESSAGES
+                    | MHD_USE_ERROR_LOG,
+                    8080,
+                    NULL, NULL,
+                    &ahc_echo, NULL,
+                    MHD_OPTION_EXTERNAL_LOGGER, &error_handler, NULL,
+                    99999 /* invalid option, to raise the error
+           "Invalid option ..." which we are going
+           to translate */);
+  return 1; /* This program won't "succeed"... */
+}
diff --git a/src/examples/post_example.c b/src/examples/post_example.c
index d8d13f9..f49b49f 100644
--- a/src/examples/post_example.c
+++ b/src/examples/post_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2011 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,6 +21,7 @@
  * @file post_example.c
  * @brief example for processing POST requests using libmicrohttpd
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include <stdlib.h>
@@ -32,32 +34,38 @@
 /**
  * Invalid method page.
  */
-#define METHOD_ERROR "<html><head><title>Illegal request</title></head><body>Go away.</body></html>"
+#define METHOD_ERROR \
+  "<html><head><title>Illegal request</title></head><body>Go away.</body></html>"
 
 /**
  * Invalid URL page.
  */
-#define NOT_FOUND_ERROR "<html><head><title>Not found</title></head><body>Go away.</body></html>"
+#define NOT_FOUND_ERROR \
+  "<html><head><title>Not found</title></head><body>Go away.</body></html>"
 
 /**
  * Front page. (/)
  */
-#define MAIN_PAGE "<html><head><title>Welcome</title></head><body><form action=\"/2\" method=\"post\">What is your name? <input type=\"text\" name=\"v1\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
+#define MAIN_PAGE \
+  "<html><head><title>Welcome</title></head><body><form action=\"/2\" method=\"post\">What is your name? <input type=\"text\" name=\"v1\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></form></body></html>"
 
 /**
  * Second page. (/2)
  */
-#define SECOND_PAGE "<html><head><title>Tell me more</title></head><body><a href=\"/\">previous</a> <form action=\"/S\" method=\"post\">%s, what is your job? <input type=\"text\" name=\"v2\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></body></html>"
+#define SECOND_PAGE \
+  "<html><head><title>Tell me more</title></head><body><a href=\"/\">previous</a> <form action=\"/S\" method=\"post\">%s, what is your job? <input type=\"text\" name=\"v2\" value=\"%s\" /><input type=\"submit\" value=\"Next\" /></form></body></html>"
 
 /**
  * Second page (/S)
  */
-#define SUBMIT_PAGE "<html><head><title>Ready to submit?</title></head><body><form action=\"/F\" method=\"post\"><a href=\"/2\">previous </a> <input type=\"hidden\" name=\"DONE\" value=\"yes\" /><input type=\"submit\" value=\"Submit\" /></body></html>"
+#define SUBMIT_PAGE \
+  "<html><head><title>Ready to submit?</title></head><body><form action=\"/F\" method=\"post\"><a href=\"/2\">previous </a> <input type=\"hidden\" name=\"DONE\" value=\"yes\" /><input type=\"submit\" value=\"Submit\" /></form></body></html>"
 
 /**
  * Last page.
  */
-#define LAST_PAGE "<html><head><title>Thank you</title></head><body>Thank you.</body></html>"
+#define LAST_PAGE \
+  "<html><head><title>Thank you</title></head><body>Thank you.</body></html>"
 
 /**
  * Name of our cookie.
@@ -137,8 +145,6 @@
 static struct Session *sessions;
 
 
-
-
 /**
  * Return the session handle for this connection, or
  * create one if this is a new user.
@@ -150,40 +156,40 @@
   const char *cookie;
 
   cookie = MHD_lookup_connection_value (connection,
-					MHD_COOKIE_KIND,
-					COOKIE_NAME);
+                                        MHD_COOKIE_KIND,
+                                        COOKIE_NAME);
   if (cookie != NULL)
+  {
+    /* find existing session */
+    ret = sessions;
+    while (NULL != ret)
     {
-      /* find existing session */
-      ret = sessions;
-      while (NULL != ret)
-	{
-	  if (0 == strcmp (cookie, ret->sid))
-	    break;
-	  ret = ret->next;
-	}
-      if (NULL != ret)
-	{
-	  ret->rc++;
-	  return ret;
-	}
+      if (0 == strcmp (cookie, ret->sid))
+        break;
+      ret = ret->next;
     }
+    if (NULL != ret)
+    {
+      ret->rc++;
+      return ret;
+    }
+  }
   /* create fresh session */
   ret = calloc (1, sizeof (struct Session));
   if (NULL == ret)
-    {
-      fprintf (stderr, "calloc error: %s\n", strerror (errno));
-      return NULL;
-    }
+  {
+    fprintf (stderr, "calloc error: %s\n", strerror (errno));
+    return NULL;
+  }
   /* not a super-secure way to generate a random session ID,
      but should do for a simple example... */
   snprintf (ret->sid,
-	    sizeof (ret->sid),
-	    "%X%X%X%X",
-	    (unsigned int) rand (),
-	    (unsigned int) rand (),
-	    (unsigned int) rand (),
-	    (unsigned int) rand ());
+            sizeof (ret->sid),
+            "%X%X%X%X",
+            (unsigned int) rand (),
+            (unsigned int) rand (),
+            (unsigned int) rand (),
+            (unsigned int) rand ());
   ret->rc++;
   ret->start = time (NULL);
   ret->next = sessions;
@@ -201,10 +207,10 @@
  * @param connection connection to process
  * @param MHD_YES on success, MHD_NO on failure
  */
-typedef int (*PageHandler)(const void *cls,
-			   const char *mime,
-			   struct Session *session,
-			   struct MHD_Connection *connection);
+typedef enum MHD_Result (*PageHandler)(const void *cls,
+                                       const char *mime,
+                                       struct Session *session,
+                                       struct MHD_Connection *connection);
 
 
 /**
@@ -242,22 +248,22 @@
  */
 static void
 add_session_cookie (struct Session *session,
-		    struct MHD_Response *response)
+                    struct MHD_Response *response)
 {
   char cstr[256];
   snprintf (cstr,
-	    sizeof (cstr),
-	    "%s=%s",
-	    COOKIE_NAME,
-	    session->sid);
+            sizeof (cstr),
+            "%s=%s",
+            COOKIE_NAME,
+            session->sid);
   if (MHD_NO ==
       MHD_add_response_header (response,
-			       MHD_HTTP_HEADER_SET_COOKIE,
-			       cstr))
-    {
-      fprintf (stderr,
-	       "Failed to set session cookie header!\n");
-    }
+                               MHD_HTTP_HEADER_SET_COOKIE,
+                               cstr))
+  {
+    fprintf (stderr,
+             "Failed to set session cookie header!\n");
+  }
 }
 
 
@@ -270,29 +276,28 @@
  * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 serve_simple_form (const void *cls,
-		   const char *mime,
-		   struct Session *session,
-		   struct MHD_Connection *connection)
+                   const char *mime,
+                   struct Session *session,
+                   struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
   const char *form = cls;
   struct MHD_Response *response;
 
   /* return static form */
-  response = MHD_create_response_from_buffer (strlen (form),
-					      (void *) form,
-					      MHD_RESPMEM_PERSISTENT);
+  response = MHD_create_response_from_buffer_static (strlen (form),
+                                                     (const void *) form);
   if (NULL == response)
     return MHD_NO;
   add_session_cookie (session, response);
   MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
+                           MHD_HTTP_HEADER_CONTENT_ENCODING,
+                           mime);
   ret = MHD_queue_response (connection,
-			    MHD_HTTP_OK,
-			    response);
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
@@ -306,36 +311,43 @@
  * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 fill_v1_form (const void *cls,
-	      const char *mime,
-	      struct Session *session,
-	      struct MHD_Connection *connection)
+              const char *mime,
+              struct Session *session,
+              struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
+  size_t slen;
   char *reply;
   struct MHD_Response *response;
+  (void) cls; /* Unused. Silent compiler warning. */
 
-  reply = malloc (strlen (MAIN_PAGE) + strlen (session->value_1) + 1);
+  slen = strlen (MAIN_PAGE) + strlen (session->value_1);
+  reply = malloc (slen + 1);
   if (NULL == reply)
     return MHD_NO;
   snprintf (reply,
-	    strlen (MAIN_PAGE) + strlen (session->value_1) + 1,
-	    MAIN_PAGE,
-	    session->value_1);
+            slen + 1,
+            MAIN_PAGE,
+            session->value_1);
   /* return static form */
-  response = MHD_create_response_from_buffer (strlen (reply),
-					      (void *) reply,
-					      MHD_RESPMEM_MUST_FREE);
+  response =
+    MHD_create_response_from_buffer_with_free_callback (slen,
+                                                        (void *) reply,
+                                                        &free);
   if (NULL == response)
+  {
+    free (reply);
     return MHD_NO;
+  }
   add_session_cookie (session, response);
   MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
+                           MHD_HTTP_HEADER_CONTENT_ENCODING,
+                           mime);
   ret = MHD_queue_response (connection,
-			    MHD_HTTP_OK,
-			    response);
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
@@ -349,37 +361,45 @@
  * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 fill_v1_v2_form (const void *cls,
-		 const char *mime,
-		 struct Session *session,
-		 struct MHD_Connection *connection)
+                 const char *mime,
+                 struct Session *session,
+                 struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
   char *reply;
   struct MHD_Response *response;
+  size_t slen;
+  (void) cls; /* Unused. Silent compiler warning. */
 
-  reply = malloc (strlen (SECOND_PAGE) + strlen (session->value_1) + strlen (session->value_2) + 1);
+  slen = strlen (SECOND_PAGE) + strlen (session->value_1)
+         + strlen (session->value_2);
+  reply = malloc (slen + 1);
   if (NULL == reply)
     return MHD_NO;
   snprintf (reply,
-	    strlen (SECOND_PAGE) + strlen (session->value_1) + strlen (session->value_2) + 1,
-	    SECOND_PAGE,
-	    session->value_1,
+            slen + 1,
+            SECOND_PAGE,
+            session->value_1,
             session->value_2);
   /* return static form */
-  response = MHD_create_response_from_buffer (strlen (reply),
-					      (void *) reply,
-					      MHD_RESPMEM_MUST_FREE);
+  response =
+    MHD_create_response_from_buffer_with_free_callback (slen,
+                                                        (void *) reply,
+                                                        &free);
   if (NULL == response)
+  {
+    free (reply);
     return MHD_NO;
+  }
   add_session_cookie (session, response);
   MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
+                           MHD_HTTP_HEADER_CONTENT_ENCODING,
+                           mime);
   ret = MHD_queue_response (connection,
-			    MHD_HTTP_OK,
-			    response);
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
@@ -393,27 +413,29 @@
  * @param session session handle
  * @param connection connection to use
  */
-static int
+static enum MHD_Result
 not_found_page (const void *cls,
-		const char *mime,
-		struct Session *session,
-		struct MHD_Connection *connection)
+                const char *mime,
+                struct Session *session,
+                struct MHD_Connection *connection)
 {
-  int ret;
+  enum MHD_Result ret;
   struct MHD_Response *response;
+  (void) cls;     /* Unused. Silent compiler warning. */
+  (void) session; /* Unused. Silent compiler warning. */
 
   /* unsupported HTTP method */
-  response = MHD_create_response_from_buffer (strlen (NOT_FOUND_ERROR),
-					      (void *) NOT_FOUND_ERROR,
-					      MHD_RESPMEM_PERSISTENT);
+  response =
+    MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR),
+                                            (const void *) NOT_FOUND_ERROR);
   if (NULL == response)
     return MHD_NO;
   ret = MHD_queue_response (connection,
-			    MHD_HTTP_NOT_FOUND,
-			    response);
+                            MHD_HTTP_NOT_FOUND,
+                            response);
   MHD_add_response_header (response,
-			   MHD_HTTP_HEADER_CONTENT_ENCODING,
-			   mime);
+                           MHD_HTTP_HEADER_CONTENT_ENCODING,
+                           mime);
   MHD_destroy_response (response);
   return ret;
 }
@@ -422,15 +444,13 @@
 /**
  * List of all pages served by this HTTP server.
  */
-static struct Page pages[] =
-  {
-    { "/", "text/html",  &fill_v1_form, NULL },
-    { "/2", "text/html", &fill_v1_v2_form, NULL },
-    { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE },
-    { "/F", "text/html", &serve_simple_form, LAST_PAGE },
-    { NULL, NULL, &not_found_page, NULL } /* 404 */
-  };
-
+static struct Page pages[] = {
+  { "/", "text/html",  &fill_v1_form, NULL },
+  { "/2", "text/html", &fill_v1_v2_form, NULL },
+  { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE },
+  { "/F", "text/html", &serve_simple_form, LAST_PAGE },
+  { NULL, NULL, &not_found_page, NULL }   /* 404 */
+};
 
 
 /**
@@ -452,47 +472,51 @@
  * @return MHD_YES to continue iterating,
  *         MHD_NO to abort the iteration
  */
-static int
+static enum MHD_Result
 post_iterator (void *cls,
-	       enum MHD_ValueKind kind,
-	       const char *key,
-	       const char *filename,
-	       const char *content_type,
-	       const char *transfer_encoding,
-	       const char *data, uint64_t off, size_t size)
+               enum MHD_ValueKind kind,
+               const char *key,
+               const char *filename,
+               const char *content_type,
+               const char *transfer_encoding,
+               const char *data, uint64_t off, size_t size)
 {
   struct Request *request = cls;
   struct Session *session = request->session;
+  (void) kind;              /* Unused. Silent compiler warning. */
+  (void) filename;          /* Unused. Silent compiler warning. */
+  (void) content_type;      /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; /* Unused. Silent compiler warning. */
 
   if (0 == strcmp ("DONE", key))
-    {
-      fprintf (stdout,
-	       "Session `%s' submitted `%s', `%s'\n",
-	       session->sid,
-	       session->value_1,
-	       session->value_2);
-      return MHD_YES;
-    }
+  {
+    fprintf (stdout,
+             "Session `%s' submitted `%s', `%s'\n",
+             session->sid,
+             session->value_1,
+             session->value_2);
+    return MHD_YES;
+  }
   if (0 == strcmp ("v1", key))
-    {
-      if (size + off >= sizeof(session->value_1))
-	size = sizeof (session->value_1) - off - 1;
-      memcpy (&session->value_1[off],
-	      data,
-	      size);
-      session->value_1[size+off] = '\0';
-      return MHD_YES;
-    }
+  {
+    if (size + off >= sizeof(session->value_1))
+      size = sizeof (session->value_1) - off - 1;
+    memcpy (&session->value_1[off],
+            data,
+            size);
+    session->value_1[size + off] = '\0';
+    return MHD_YES;
+  }
   if (0 == strcmp ("v2", key))
-    {
-      if (size + off >= sizeof(session->value_2))
-	size = sizeof (session->value_2) - off - 1;
-      memcpy (&session->value_2[off],
-	      data,
-	      size);
-      session->value_2[size+off] = '\0';
-      return MHD_YES;
-    }
+  {
+    if (size + off >= sizeof(session->value_2))
+      size = sizeof (session->value_2) - off - 1;
+    memcpy (&session->value_2[off],
+            data,
+            size);
+    session->value_2[size + off] = '\0';
+    return MHD_YES;
+  }
   fprintf (stderr,
            "Unsupported form value `%s'\n",
            key);
@@ -519,7 +543,7 @@
  * @param upload_data_size set initially to the size of the
  *        upload_data provided; the method must update this
  *        value to the number of bytes NOT processed;
- * @param ptr pointer that the callback can set to some
+ * @param req_cls pointer that the callback can set to some
  *        address and that will be preserved by MHD for future
  *        calls for this request; since the access handler may
  *        be called many times (i.e., for a PUT/POST operation
@@ -528,104 +552,106 @@
  *        If necessary, this state can be cleaned up in the
  *        global "MHD_RequestCompleted" callback (which
  *        can be set with the MHD_OPTION_NOTIFY_COMPLETED).
- *        Initially, <tt>*con_cls</tt> will be NULL.
+ *        Initially, <tt>*req_cls</tt> will be NULL.
  * @return MHS_YES if the connection was handled successfully,
- *         MHS_NO if the socket must be closed due to a serios
+ *         MHS_NO if the socket must be closed due to a serious
  *         error while handling the request
  */
-static int
+static enum MHD_Result
 create_response (void *cls,
-		 struct MHD_Connection *connection,
-		 const char *url,
-		 const char *method,
-		 const char *version,
-		 const char *upload_data,
-		 size_t *upload_data_size,
-		 void **ptr)
+                 struct MHD_Connection *connection,
+                 const char *url,
+                 const char *method,
+                 const char *version,
+                 const char *upload_data,
+                 size_t *upload_data_size,
+                 void **req_cls)
 {
   struct MHD_Response *response;
   struct Request *request;
   struct Session *session;
-  int ret;
+  enum MHD_Result ret;
   unsigned int i;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
 
-  request = *ptr;
+  request = *req_cls;
   if (NULL == request)
+  {
+    request = calloc (1, sizeof (struct Request));
+    if (NULL == request)
     {
-      request = calloc (1, sizeof (struct Request));
-      if (NULL == request)
-	{
-	  fprintf (stderr, "calloc error: %s\n", strerror (errno));
-	  return MHD_NO;
-	}
-      *ptr = request;
-      if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
-	{
-	  request->pp = MHD_create_post_processor (connection, 1024,
-						   &post_iterator, request);
-	  if (NULL == request->pp)
-	    {
-	      fprintf (stderr, "Failed to setup post processor for `%s'\n",
-		       url);
-	      return MHD_NO; /* internal error */
-	    }
-	}
-      return MHD_YES;
+      fprintf (stderr, "calloc error: %s\n", strerror (errno));
+      return MHD_NO;
     }
+    *req_cls = request;
+    if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
+    {
+      request->pp = MHD_create_post_processor (connection, 1024,
+                                               &post_iterator, request);
+      if (NULL == request->pp)
+      {
+        fprintf (stderr, "Failed to setup post processor for `%s'\n",
+                 url);
+        return MHD_NO; /* internal error */
+      }
+    }
+    return MHD_YES;
+  }
   if (NULL == request->session)
+  {
+    request->session = get_session (connection);
+    if (NULL == request->session)
     {
-      request->session = get_session (connection);
-      if (NULL == request->session)
-	{
-	  fprintf (stderr, "Failed to setup session for `%s'\n",
-		   url);
-	  return MHD_NO; /* internal error */
-	}
+      fprintf (stderr, "Failed to setup session for `%s'\n",
+               url);
+      return MHD_NO; /* internal error */
     }
+  }
   session = request->session;
   session->start = time (NULL);
   if (0 == strcmp (method, MHD_HTTP_METHOD_POST))
+  {
+    /* evaluate POST data */
+    MHD_post_process (request->pp,
+                      upload_data,
+                      *upload_data_size);
+    if (0 != *upload_data_size)
     {
-      /* evaluate POST data */
-      MHD_post_process (request->pp,
-			upload_data,
-			*upload_data_size);
-      if (0 != *upload_data_size)
-	{
-	  *upload_data_size = 0;
-	  return MHD_YES;
-	}
-      /* done with POST data, serve response */
-      MHD_destroy_post_processor (request->pp);
-      request->pp = NULL;
-      method = MHD_HTTP_METHOD_GET; /* fake 'GET' */
-      if (NULL != request->post_url)
-	url = request->post_url;
+      *upload_data_size = 0;
+      return MHD_YES;
     }
+    /* done with POST data, serve response */
+    MHD_destroy_post_processor (request->pp);
+    request->pp = NULL;
+    method = MHD_HTTP_METHOD_GET;   /* fake 'GET' */
+    if (NULL != request->post_url)
+      url = request->post_url;
+  }
 
   if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) ||
        (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) )
-    {
-      /* find out which page to serve */
-      i=0;
-      while ( (pages[i].url != NULL) &&
-	      (0 != strcmp (pages[i].url, url)) )
-	i++;
-      ret = pages[i].handler (pages[i].handler_cls,
-			      pages[i].mime,
-			      session, connection);
-      if (ret != MHD_YES)
-	fprintf (stderr, "Failed to create page for `%s'\n",
-		 url);
-      return ret;
-    }
+  {
+    /* find out which page to serve */
+    i = 0;
+    while ( (pages[i].url != NULL) &&
+            (0 != strcmp (pages[i].url, url)) )
+      i++;
+    ret = pages[i].handler (pages[i].handler_cls,
+                            pages[i].mime,
+                            session, connection);
+    if (ret != MHD_YES)
+      fprintf (stderr, "Failed to create page for `%s'\n",
+               url);
+    return ret;
+  }
   /* unsupported HTTP method */
-  response = MHD_create_response_from_buffer (strlen (METHOD_ERROR),
-					      (void *) METHOD_ERROR,
-					      MHD_RESPMEM_PERSISTENT);
+  response =
+    MHD_create_response_from_buffer_static (strlen (METHOD_ERROR),
+                                            (const void *) METHOD_ERROR);
   ret = MHD_queue_response (connection,
-			    MHD_HTTP_METHOD_NOT_ACCEPTABLE,
-			    response);
+                            MHD_HTTP_NOT_ACCEPTABLE,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
@@ -637,16 +663,19 @@
  *
  * @param cls not used
  * @param connection connection that completed
- * @param con_cls session handle
+ * @param req_cls session handle
  * @param toe status code
  */
 static void
 request_completed_callback (void *cls,
-			    struct MHD_Connection *connection,
-			    void **con_cls,
-			    enum MHD_RequestTerminationCode toe)
+                            struct MHD_Connection *connection,
+                            void **req_cls,
+                            enum MHD_RequestTerminationCode toe)
 {
-  struct Request *request = *con_cls;
+  struct Request *request = *req_cls;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) toe;         /* Unused. Silent compiler warning. */
 
   if (NULL == request)
     return;
@@ -663,7 +692,7 @@
  * too long.
  */
 static void
-expire_sessions ()
+expire_sessions (void)
 {
   struct Session *pos;
   struct Session *prev;
@@ -674,21 +703,21 @@
   prev = NULL;
   pos = sessions;
   while (NULL != pos)
+  {
+    next = pos->next;
+    if (now - pos->start > 60 * 60)
     {
-      next = pos->next;
-      if (now - pos->start > 60 * 60)
-	{
-	  /* expire sessions after 1h */
-	  if (NULL == prev)
-	    sessions = pos->next;
-	  else
-	    prev->next = next;
-	  free (pos);
-	}
+      /* expire sessions after 1h */
+      if (NULL == prev)
+        sessions = pos->next;
       else
-        prev = pos;
-      pos = next;
+        prev->next = next;
+      free (pos);
     }
+    else
+      prev = pos;
+    pos = next;
+  }
 }
 
 
@@ -706,45 +735,61 @@
   fd_set ws;
   fd_set es;
   MHD_socket max;
-  MHD_UNSIGNED_LONG_LONG mhd_timeout;
+  uint64_t mhd_timeout;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
   /* initialize PRNG */
   srand ((unsigned int) time (NULL));
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        atoi (argv[1]),
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
                         NULL, NULL,
-			&create_response, NULL,
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15,
-			MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL,
-			MHD_OPTION_END);
+                        &create_response, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15,
+                        MHD_OPTION_NOTIFY_COMPLETED,
+                        &request_completed_callback, NULL,
+                        MHD_OPTION_END);
   if (NULL == d)
     return 1;
   while (1)
+  {
+    expire_sessions ();
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      break; /* fatal internal error */
+    if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES)
     {
-      expire_sessions ();
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-	break; /* fatal internal error */
-      if (MHD_get_timeout (d, &mhd_timeout) == MHD_YES)
-	{
-	  tv.tv_sec = mhd_timeout / 1000;
-	  tv.tv_usec = (mhd_timeout - (tv.tv_sec * 1000)) * 1000;
-	  tvp = &tv;
-	}
-      else
-	tvp = NULL;
-      select (max + 1, &rs, &ws, &es, tvp);
-      MHD_run (d);
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+      tv.tv_sec = (time_t) (mhd_timeout / 1000LL);
+#else  /* Native W32 */
+      tv.tv_sec = (long) (mhd_timeout / 1000LL);
+#endif /* Native W32 */
+      tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000;
+      tvp = &tv;
     }
+    else
+      tvp = NULL;
+    if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp))
+    {
+      if (EINTR != errno)
+        abort ();
+    }
+    MHD_run (d);
+  }
   MHD_stop_daemon (d);
   return 0;
 }
-
diff --git a/src/examples/pthread_windows.c b/src/examples/pthread_windows.c
new file mode 100644
index 0000000..6709243
--- /dev/null
+++ b/src/examples/pthread_windows.c
@@ -0,0 +1,252 @@
+#include "pthread_windows.h"

+#include <Windows.h>

+

+struct _pthread_t

+{

+  HANDLE thread;

+};

+

+struct _pthread_cond_t

+{

+  HANDLE event;

+};

+

+struct _pthread_mutex_t

+{

+  HANDLE mutex;

+};

+

+struct StdCallThread

+{

+  void *(__cdecl *start) (void *);

+  void *arg;

+};

+

+DWORD WINAPI

+ThreadProc (LPVOID lpParameter)

+{

+  struct StdCallThread st = *((struct StdCallThread *) lpParameter);

+  free (lpParameter);

+  st.start (st.arg);

+  return 0;

+}

+

+

+int

+pthread_create (pthread_t *pt,

+                const void *attr,

+                void *(__cdecl *start)(void *),

+                void *arg)

+{

+  pthread_t pt_ = (pthread_t) malloc (sizeof(struct _pthread_t));

+  if (NULL == pt_)

+    return 1;

+  struct StdCallThread *sct;

+  sct = (struct StdCallThread *) malloc (sizeof(struct StdCallThread));

+  if (NULL == sct)

+  {

+    free (pt_);

+    return 1;

+  }

+

+  sct->start = start;

+  sct->arg   = arg;

+  pt_->thread = CreateThread (NULL, 0, ThreadProc, sct, 0, NULL);

+  if (NULL == pt_->thread)

+  {

+    free (sct);

+    free (pt_);

+    return 1;

+  }

+  *pt = pt_;

+

+  return 0;

+}

+

+

+int

+pthread_detach (pthread_t pt)

+{

+  if (pt)

+  {

+    CloseHandle (pt->thread);

+    free (pt);

+  }

+  return 0;

+}

+

+

+int

+pthread_join (pthread_t pt,

+              void **value_ptr)

+{

+  if (NULL == pt)

+    return 1;

+

+  if (value_ptr)

+  {

+    *value_ptr = NULL;

+  }

+  WaitForSingleObject (pt->thread, INFINITE);

+  CloseHandle (pt->thread);

+  free (pt);

+

+  return 0;

+}

+

+

+int

+pthread_mutex_init (pthread_mutex_t *mutex,

+                    const void *attr)

+{

+  pthread_mutex_t mutex_ = (pthread_mutex_t) malloc (sizeof(struct

+                                                            _pthread_mutex_t));

+  if (NULL == mutex_)

+    return 1;

+  mutex_->mutex = CreateMutex (NULL, FALSE, NULL);

+  if (NULL == mutex_->mutex)

+  {

+    free (mutex_);

+    return 1;

+  }

+  *mutex = mutex_;

+

+  return 0;

+}

+

+

+int

+pthread_mutex_destroy (pthread_mutex_t *mutex)

+{

+  if (NULL == mutex)

+    return 1;

+  if ((NULL == *mutex) || (PTHREAD_MUTEX_INITIALIZER == *mutex))

+    return 0;

+

+  CloseHandle ((*mutex)->mutex);

+  free (*mutex);

+  *mutex = NULL;

+

+  return 0;

+}

+

+

+int

+pthread_mutex_lock (pthread_mutex_t *mutex)

+{

+  if (NULL == mutex)

+    return 1;

+  if (NULL == *mutex)

+    return 1;

+  if (PTHREAD_MUTEX_INITIALIZER == *mutex)

+  {

+    int ret = pthread_mutex_init (mutex, NULL);

+    if (0 != ret)

+      return ret;

+  }

+  if (WAIT_OBJECT_0 != WaitForSingleObject ((*mutex)->mutex, INFINITE))

+    return 1;

+  return 0;

+}

+

+

+int

+pthread_mutex_unlock (pthread_mutex_t *mutex)

+{

+  if (NULL == mutex)

+    return 1;

+  if ((NULL == *mutex) || (PTHREAD_MUTEX_INITIALIZER == *mutex))

+    return 1;

+

+  if (0 == ReleaseMutex ((*mutex)->mutex))

+    return 1;

+

+  return 0;

+}

+

+

+int

+pthread_cond_init (pthread_cond_t *cond,

+                   const void *attr)

+{

+  pthread_cond_t cond_ = (pthread_cond_t) malloc (sizeof(struct

+                                                         _pthread_cond_t));

+  if (NULL == cond_)

+    return 1;

+  cond_->event = CreateEvent (NULL, FALSE, FALSE, NULL);

+  if (NULL == cond_->event)

+  {

+    free (cond_);

+    return 1;

+  }

+  *cond = cond_;

+

+  return 0;

+}

+

+

+int

+pthread_cond_destroy (pthread_cond_t *cond)

+{

+  if (NULL == cond)

+    return 1;

+  if ((NULL == *cond) || (PTHREAD_COND_INITIALIZER == *cond))

+    return 1;

+

+  CloseHandle ((*cond)->event);

+  free (*cond);

+

+  return 0;

+}

+

+

+int

+pthread_cond_wait (pthread_cond_t *cond,

+                   pthread_mutex_t *mutex)

+{

+  if ((NULL == cond) || (NULL == mutex))

+    return 1;

+  if ((NULL == *cond) || (NULL == *mutex))

+    return 1;

+  if (PTHREAD_COND_INITIALIZER == *cond)

+  {

+    int ret = pthread_cond_init (cond, NULL);

+    if (0 != ret)

+      return ret;

+  }

+  if (PTHREAD_MUTEX_INITIALIZER == *mutex)

+  {

+    int ret = pthread_mutex_init (mutex, NULL);

+    if (0 != ret)

+      return ret;

+  }

+  ReleaseMutex ((*mutex)->mutex);

+  if (WAIT_OBJECT_0 != WaitForSingleObject ((*cond)->event, INFINITE))

+    return 1;

+  if (WAIT_OBJECT_0 != WaitForSingleObject ((*mutex)->mutex, INFINITE))

+    return 1;

+

+  return 0;

+}

+

+

+int

+pthread_cond_signal (pthread_cond_t *cond)

+{

+  if (NULL == cond)

+    return 1;

+  if ((NULL == *cond) || (PTHREAD_COND_INITIALIZER == *cond))

+    return 1;

+

+  if (0 == SetEvent ((*cond)->event))

+    return 1;

+

+  return 0;

+}

+

+

+int

+pthread_cond_broadcast (pthread_cond_t *cond)

+{

+  return pthread_cond_signal (cond);

+}

diff --git a/src/examples/pthread_windows.h b/src/examples/pthread_windows.h
new file mode 100644
index 0000000..412d40b
--- /dev/null
+++ b/src/examples/pthread_windows.h
@@ -0,0 +1,46 @@
+#ifndef pthread_windows_H

+#define pthread_windows_H

+

+struct _pthread_t;

+struct _pthread_cond_t;

+struct _pthread_mutex_t;

+

+typedef struct _pthread_t *pthread_t;

+typedef struct _pthread_cond_t *pthread_cond_t;

+typedef struct _pthread_mutex_t *pthread_mutex_t;

+

+#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -1)

+#define PTHREAD_COND_INITIALIZER ((pthread_cond_t)(size_t) -1)

+

+int pthread_create (pthread_t * pt,

+                    const void *attr,

+                    void *(__cdecl * start)(void *),

+                    void *arg);

+

+int pthread_detach (pthread_t pt);

+

+int pthread_join (pthread_t pt,

+                  void **value_ptr);

+

+int pthread_mutex_init (pthread_mutex_t *mutex,

+                        const void *attr);

+

+int pthread_mutex_destroy (pthread_mutex_t *mutex);

+

+int pthread_mutex_lock (pthread_mutex_t *mutex);

+

+int pthread_mutex_unlock (pthread_mutex_t *mutex);

+

+int pthread_cond_init (pthread_cond_t *cond,

+                       const void *attr);

+

+int pthread_cond_destroy (pthread_cond_t *cond);

+

+int pthread_cond_wait (pthread_cond_t *cond,

+                       pthread_mutex_t *mutex);

+

+int pthread_cond_signal (pthread_cond_t *cond);

+

+int pthread_cond_broadcast (pthread_cond_t *cond);

+

+#endif // !pthread_windows_H

diff --git a/src/examples/querystring_example.c b/src/examples/querystring_example.c
index 24f8ae4..50b6293 100644
--- a/src/examples/querystring_example.c
+++ b/src/examples/querystring_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,68 +22,98 @@
  * @brief example for how to get the query string from libmicrohttpd
  *        Call with an URI ending with something like "?q=QUERY"
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include <microhttpd.h>
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>Query string for &quot;%s&quot; was &quot;%s&quot;</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Query string for &quot;%s&quot; was &quot;%s&quot;</body></html>"
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
-  const char *fmt = cls;
   const char *val;
   char *me;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  int resp_len;
+  size_t buf_size;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, "GET"))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;  /* reset when done */
   val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "q");
-  me = malloc (snprintf (NULL, 0, fmt, "q", val) + 1);
+  if (NULL == val)
+    return MHD_NO;  /* No "q" argument was found */
+  resp_len = snprintf (NULL, 0, PAGE, "q", val);
+  if (0 >= resp_len)
+    return MHD_NO;  /* Error calculating response size */
+  buf_size = (size_t) resp_len + 1; /* Add one byte for zero-termination */
+  me = malloc (buf_size);
   if (me == NULL)
-    return MHD_NO;
-  sprintf (me, fmt, "q", val);
-  response = MHD_create_response_from_buffer (strlen (me), me,
-					      MHD_RESPMEM_MUST_FREE);
+    return MHD_NO;  /* Error allocating memory */
+  if (resp_len != snprintf (me, buf_size, PAGE, "q", val))
+  {
+    free (me);
+    return MHD_NO;  /* Error forming the response body */
+  }
+  response =
+    MHD_create_response_from_buffer_with_free_callback (buf_size - 1,
+                                                        (void *) me,
+                                                        &free);
   if (response == NULL)
-    {
-      free (me);
-      return MHD_NO;
-    }
+  {
+    free (me);
+    return MHD_NO;
+  }
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, PAGE, MHD_OPTION_END);
-  if (d == NULL)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (port < 0) ||
+       (port > UINT16_MAX) )
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  if (NULL == d)
     return 1;
   (void) getc (stdin);
   MHD_stop_daemon (d);
diff --git a/src/examples/refuse_post_example.c b/src/examples/refuse_post_example.c
index 846546c..aafa665 100644
--- a/src/examples/refuse_post_example.c
+++ b/src/examples/refuse_post_example.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -20,75 +21,102 @@
  * @file refuse_post_example.c
  * @brief example for how to refuse a POST request properly
  * @author Christian Grothoff and Sebastian Gerhardt
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "platform.h"
 #include <microhttpd.h>
 
-const char *askpage = "<html><body>\n\
-                       Upload a file, please!<br>\n\
-                       <form action=\"/filepost\" method=\"post\" enctype=\"multipart/form-data\">\n\
-                       <input name=\"file\" type=\"file\">\n\
-                       <input type=\"submit\" value=\" Send \"></form>\n\
-                       </body></html>";
+struct handler_param
+{
+  const char *response_page;
+};
 
-#define BUSYPAGE "<html><head><title>Webserver busy</title></head><body>We are too busy to process POSTs right now.</body></html>"
+static const char *askpage =
+  "<html><body>\n\
+ Upload a file, please!<br>\n\
+ <form action=\"/filepost\" method=\"post\" enctype=\"multipart/form-data\">\n\
+ <input name=\"file\" type=\"file\">\n\
+ <input type=\"submit\" value=\" Send \"></form>\n\
+ </body></html>";
 
-static int
+#define BUSYPAGE \
+  "<html><head><title>Webserver busy</title></head>" \
+  "<body>We are too busy to process POSTs right now.</body></html>"
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
-  const char *me = cls;
+  struct handler_param *param = (struct handler_param *) cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
 
   if ((0 != strcmp (method, "GET")) && (0 != strcmp (method, "POST")))
     return MHD_NO;              /* unexpected method */
 
-  if (&aptr != *ptr)
+  if (&aptr != *req_cls)
+  {
+    *req_cls = &aptr;
+
+    /* always to busy for POST requests */
+    if (0 == strcmp (method, "POST"))
     {
-      *ptr = &aptr;
-
-      /* always to busy for POST requests */
-      if (0 == strcmp (method, "POST"))
-        {
-          response = MHD_create_response_from_buffer (strlen (BUSYPAGE),
-						      (void *) BUSYPAGE, 
-						      MHD_RESPMEM_PERSISTENT);
-          ret =
-            MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE,
-                                response);
-          MHD_destroy_response (response);
-          return ret;
-        }
+      response =
+        MHD_create_response_from_buffer_static (strlen (BUSYPAGE),
+                                                (const void *) BUSYPAGE);
+      ret =
+        MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE,
+                            response);
+      MHD_destroy_response (response);
+      return ret;
     }
+  }
 
-  *ptr = NULL;                  /* reset when done */
-  response = MHD_create_response_from_buffer (strlen (me),
-					      (void *) me,
-					      MHD_RESPMEM_PERSISTENT);
+  *req_cls = NULL;                  /* reset when done */
+  response =
+    MHD_create_response_from_buffer_static (strlen (param->response_page),
+                                            (const void *)
+                                            param->response_page);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   struct MHD_Daemon *d;
+  struct handler_param data_for_handler;
+  int port;
 
   if (argc != 2)
-    {
-      printf ("%s PORT\n", argv[0]);
-      return 1;
-    }
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        atoi (argv[1]),
-                        NULL, NULL, &ahc_echo, (void *) askpage,
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  data_for_handler.response_page = askpage;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, &data_for_handler,
                         MHD_OPTION_END);
   if (d == NULL)
     return 1;
@@ -97,4 +125,5 @@
   return 0;
 }
 
+
 /* end of refuse_post_example.c */
diff --git a/src/examples/spdy_event_loop.c b/src/examples/spdy_event_loop.c
deleted file mode 100644
index 6b7192c..0000000
--- a/src/examples/spdy_event_loop.c
+++ /dev/null
@@ -1,487 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file event_loop.c
- * @brief  shows how to use the daemon. THIS IS MAINLY A TEST AND DEBUG
- * 		 PROGRAM
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <errno.h>
-#include "microspdy.h"
-#include <sys/time.h>
-#include <time.h>
-#ifndef MINGW
-#include <arpa/inet.h>
-#endif
-//#include "../framinglayer/structures.h"
-//#include "../applicationlayer/alstructures.h"
-
-static int run = 1;
-
-static int run2 = 1;
-
-	
-static uint64_t loops;
-
-static time_t start;
-
-
-static void
-new_session_callback (void *cls,
-						struct SPDY_Session * session)
-{
-  (void)cls;
-  
-	char ipstr[1024];
-		
-	struct sockaddr *addr;
-	socklen_t addr_len = SPDY_get_remote_addr(session, &addr);	
-	
-	if(!addr_len)
-	{
-		printf("SPDY_get_remote_addr");
-		abort();
-	}
-	
-	if(AF_INET == addr->sa_family)
-	{
-		struct sockaddr_in * addr4 = (struct sockaddr_in *) addr;
-		if(NULL == inet_ntop(AF_INET, &(addr4->sin_addr), ipstr, sizeof(ipstr)))
-		{
-			printf("inet_ntop");
-			abort();
-		}
-		printf("New connection from: %s:%i\n", ipstr, ntohs(addr4->sin_port));
-		
-	}
-	else if(AF_INET6 == addr->sa_family)
-	{
-		struct sockaddr_in6 * addr6 = (struct sockaddr_in6 *) addr;
-		if(NULL == inet_ntop(AF_INET6, &(addr6->sin6_addr), ipstr, sizeof(ipstr)))
-		{
-			printf("inet_ntop");
-			abort();
-		}
-		printf("New connection from: %s:%i\n", ipstr, ntohs(addr6->sin6_port));
-		
-	}
-}
-
-
-static void
-session_closed_handler (void *cls,
-						struct SPDY_Session * session,
-						int by_client)
-{
-  (void)cls;
-  (void)session;
-  
-	//printf("session_closed_handler called\n");
-	
-	if(SPDY_YES != by_client)
-	{
-		//killchild(child,"wrong by_client");
-		printf("session closed by server\n");
-	}
-	else
-	{
-		printf("session closed by client\n");
-	}
-	
-	//session_closed_called = 1;
-}
-
-
-static void
-response_done_callback(void *cls,
-						struct SPDY_Response *response,
-						struct SPDY_Request *request,
-						enum SPDY_RESPONSE_RESULT status,
-						bool streamopened)
-{
-	(void)streamopened;
-	if(strcmp(cls, "/close (daemon1)") == 0)
-		run = 0;
-	else {
-		if(strcmp(cls, "/close (daemon2)") == 0) run2 = 0;
-		loops = 0;
-		start = time(NULL);
-	}
-	if(SPDY_RESPONSE_RESULT_SUCCESS != status)
-	{
-		printf("not sent frame cause %i", status);
-	}
-	printf("answer for %s was sent\n", (char*)cls);
-	//printf("raw sent headers %s\n", (char *)(response->headers)+8);
-	
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-	free(cls);
-}
-
-/*
-static int
-print_headers (void *cls,
-                           const char *name, const char *value)
-{
-	(void)cls;
-	printf("%s: %s\n",name,value);
-	return SPDY_YES;
-}
- */
- 
- 
-/*       
-void
-new_request_cb (void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers)
-{
-	(void)cls;
-	(void)request;
-	printf("Priority: %i\nHTTP headers, scheme: %s\n\n%s %s %s\nHost: %s\n", priority,scheme,method,path,version,host);
-	SPDY_name_value_iterate(headers, &print_headers, NULL);
-}
-*/
-
-
-static int
-append_headers_to_data (void *cls,
-                           const char *name, const char * const *value, int num_values)
-{
-	char **data = cls;
-	void *tofree = *data;
-	int i;
-	
-	if(num_values)
-	for(i=0;i<num_values;++i)
-	{
-	asprintf(data,"%s%s: %s\n", *data,name,value[i]);
-	}
-	else
-	asprintf(data,"%s%s: \n", *data,name);
-	
-	free(tofree);
-	return SPDY_YES;
-}  
-
-
-static void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-  (void)more;
-  
-	char *html;
-	char *data;
-	struct SPDY_Response *response=NULL;
-	
-	printf("received request for '%s %s %s'\n", method, path, version);
-	if(strcmp(path,"/main.css")==0)
-	{
-		if(NULL != cls)
-			asprintf(&html,"body{color:green;}");
-		else
-			asprintf(&html,"body{color:red;}");
-				
-		//struct SPDY_NameValue *headers=SPDY_name_value_create();
-		//SPDY_name_value_add(headers,"content-type","text/css");
-		
-		response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,html,strlen(html));
-		free(html);
-	}
-	else
-	{
-		asprintf(&data,"Priority: %i\nHTTP headers, scheme: %s\n\n%s %s %s\nHost: %s\n", priority,scheme,method,path,version,host);
-		
-		SPDY_name_value_iterate(headers, &append_headers_to_data, &data);
-		
-		if(strcmp(path,"/close")==0)
-		{
-			asprintf(&html,"<html>"
-		"<body><b>Closing now!<br>This is an answer to the following "
-		"request:</b><br><br><pre>%s</pre></body></html>",data);
-		}
-		else
-		{
-			asprintf(&html,"<html><link href=\"main.css\" rel=\"stylesheet\" type=\"text/css\" />"
-		"<body><b>This is an answer to the following "
-		"request:</b><br><br><pre>%s</pre></body></html>",data);
-		}
-		
-		free(data);
-		
-		response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,html,strlen(html));
-		free(html);
-	}
-	
-	if(NULL==response){
-		fprintf(stdout,"no response obj\n");
-		abort();
-	}
-	
-	char *pathcls;
-	asprintf(&pathcls, "%s (daemon%i)",path,NULL==cls ? 1 : 2);
-	if(SPDY_queue_response(request,response,true,false,&response_done_callback,pathcls)!=SPDY_YES)
-	{
-		fprintf(stdout,"queue\n");
-		abort();
-	}
-}
-
-
-static int
-new_post_data_cb (void * cls,
-					 struct SPDY_Request *request,
-					 const void * buf,
-					 size_t size,
-					 bool more)
-{
-  (void)cls;
-  (void)request;
-  (void)more;
-  
-	printf("DATA:\n===============================\n");
-  write(0, buf, size);
-	printf("\n===============================\n");
-  return SPDY_YES;
-}
-
-
-static void 
-sig_handler(int signo)
-{
-  (void)signo;
-  
-  printf("received signal\n");
-}
-
-
-int
-main (int argc, char *const *argv)
-{	
-	if(argc != 2) return 1;
-	
-	#ifndef MINGW
-	if (signal(SIGPIPE, sig_handler) == SIG_ERR)
-		printf("\ncan't catch SIGPIPE\n");
-	#endif
-	
-	SPDY_init();
-	
-	/*
-  struct sockaddr_in addr4;
-	struct in_addr inaddr4;
-	inaddr4.s_addr = htonl(INADDR_ANY);
-	addr4.sin_family = AF_INET;
-	addr4.sin_addr = inaddr4;
-	addr4.sin_port = htons(atoi(argv[1]));
-	*/
-  
-	struct SPDY_Daemon *daemon = SPDY_start_daemon(atoi(argv[1]),
-	 DATA_DIR "cert-and-key.pem",
-	 DATA_DIR "cert-and-key.pem",
-	&new_session_callback,&session_closed_handler,&standard_request_handler,&new_post_data_cb,NULL,
-	SPDY_DAEMON_OPTION_SESSION_TIMEOUT, 10,
-	//SPDY_DAEMON_OPTION_SOCK_ADDR,  (struct sockaddr *)&addr4,
-	SPDY_DAEMON_OPTION_END);
-	
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-	
-  /*
-	struct sockaddr_in6 addr6;
-	addr6.sin6_family = AF_INET6;
-	addr6.sin6_addr = in6addr_any;
-	addr6.sin6_port = htons(atoi(argv[1]) + 1);
-	*/
-  
-	struct SPDY_Daemon *daemon2 = SPDY_start_daemon(atoi(argv[1]) + 1,
-	 DATA_DIR "cert-and-key.pem",
-	 DATA_DIR "cert-and-key.pem",
-	&new_session_callback,NULL,&standard_request_handler,&new_post_data_cb,&main,
-	//SPDY_DAEMON_OPTION_SESSION_TIMEOUT, 0,
-	//SPDY_DAEMON_OPTION_SOCK_ADDR,  (struct sockaddr *)&addr6,
-	//SPDY_DAEMON_OPTION_FLAGS, SPDY_DAEMON_FLAG_ONLY_IPV6,
-	SPDY_DAEMON_OPTION_END);
-	
-	if(NULL==daemon2){
-		printf("no daemon\n");
-		return 1;
-	}
-	
-	do
-	{
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	volatile int rc; /* select() return code */ 
-	volatile int ret;
-
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-
-	if(run && daemon != NULL)
-	{
-		loops++;
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-    
-		printf("ret=%i; timeoutlong=%llu; sec=%llu; usec=%llu\n", ret, timeoutlong, (long long unsigned)timeout.tv_sec, (long long unsigned)timeout.tv_usec);
-		//raise(SIGINT);
-
-		/* get file descriptors from the transfers */ 
-		maxfd = SPDY_get_fdset (daemon,
-		&read_fd_set,
-		&write_fd_set, 
-		&except_fd_set);
-
-//struct timeval ts1,ts2;
-    //gettimeofday(&ts1, NULL);
-		rc = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-    //gettimeofday(&ts2, NULL);
-    printf("rc %i\n",rc);
-   // printf("time for select %i\n",ts2.tv_usec - ts1.tv_usec);
-   // printf("%i %i %i %i\n",ts1.tv_sec, ts1.tv_usec,ts2.tv_sec, ts2.tv_usec);
-
-		switch(rc) {
-			case -1:
-				/* select error */ 
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	else if(daemon != NULL){
-	
-	printf("%lu loops in %llu secs\n", loops, (long long unsigned)(time(NULL) - start));
-		SPDY_stop_daemon(daemon);
-		daemon=NULL;
-	}
-
-	if(run2)
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon2, &timeoutlong);
-		//printf("tout %i\n",timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1)
-		{ 
-			//do sth else
-			//sleep(1);
-
-			//try new connection
-			timeout.tv_sec = 1;
-			timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong;
-			timeout.tv_usec = 0;//(timeoutlong % 1000) * 1000;
-		}
-
-		//printf("ret=%i; timeoutlong=%i; sec=%i; usec=%i\n", ret, timeoutlong, timeout.tv_sec, timeout.tv_usec);
-		//raise(SIGINT);
-
-		/* get file descriptors from the transfers */ 
-		maxfd = SPDY_get_fdset (daemon2,
-		&read_fd_set,
-		&write_fd_set, 
-		&except_fd_set);
-
-		rc = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(rc) {
-			case -1:
-				/* select error */ 
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon2);
-
-				break;
-		}
-	}
-	else if(daemon2 != NULL){
-		SPDY_stop_daemon(daemon2);
-		daemon2=NULL;
-	}
-	}
-	while(run || run2);
-
-	if(daemon != NULL){
-		SPDY_stop_daemon(daemon);
-	}
-	if(daemon2 != NULL){
-		SPDY_stop_daemon(daemon2);
-	}
-	
-	SPDY_deinit();
-	
-	return 0;
-}
-
diff --git a/src/examples/spdy_fileserver.c b/src/examples/spdy_fileserver.c
deleted file mode 100644
index 0a0254f..0000000
--- a/src/examples/spdy_fileserver.c
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file fileserver.c
- * @brief   Simple example how the lib can be used for serving
- * 			files directly read from the system
- * @author Andrey Uzunov
- */
-
-//for asprintf
-#define _GNU_SOURCE
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <errno.h>
-#include "microspdy.h"
-#include "time.h"
-
-
-int run = 1;
-char* basedir;
-
-
-#define GET_MIME_TYPE(fname, mime)	do {\
-		unsigned int __len = strlen(fname);\
-		if (__len < 4 || '.' != (fname)[__len - 4]) \
-		{	\
-			(mime) = strdup("application/octet-stream");\
-			printf("MIME for %s is applic...\n", (fname));\
-		}\
-    else {\
-      const char * __ext = &(fname)[__len - 3];\
-      if(0 == strcmp(__ext, "jpg")) (mime) = strdup("image/jpeg");\
-      else if(0 == strcmp(__ext, "png")) (mime) = strdup("image/png");\
-      else if(0 == strcmp(__ext, "css")) (mime) = strdup("text/css");\
-      else if(0 == strcmp(__ext, "gif")) (mime) = strdup("image/gif");\
-      else if(0 == strcmp(__ext, "htm")) (mime) = strdup("text/html");\
-      else \
-      {	\
-        (mime) = strdup("application/octet-stream");\
-        printf("MIME for %s is applic...\n", (fname));\
-      }\
-    }\
-		if(NULL == (mime))\
-		{\
-			printf("no memory\n");\
-			abort();\
-		}\
-	} while (0)
-
-
-static const char *DAY_NAMES[] =
-  { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
-
-static const char *MONTH_NAMES[] =
-  { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
-
-//taken from http://stackoverflow.com/questions/2726975/how-can-i-generate-an-rfc1123-date-string-from-c-code-win32
-//and modified for linux
-char *Rfc1123_DateTimeNow()
-{
-    const int RFC1123_TIME_LEN = 29;
-    time_t t;
-    struct tm tm;
-    char * buf = malloc(RFC1123_TIME_LEN+1);
-
-    if (NULL == buf)
-      return NULL;
-    time(&t);
-    gmtime_r( &t, &tm);
-
-    strftime(buf, RFC1123_TIME_LEN+1, "---, %d --- %Y %H:%M:%S GMT", &tm);
-    memcpy(buf, DAY_NAMES[tm.tm_wday], 3);
-    memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
-
-    return buf;
-}
-
-
-ssize_t
-response_callback (void *cls,
-						void *buffer,
-						size_t max,
-						bool *more)
-{
-	FILE *fd =(FILE*)cls;
-
-	int ret = fread(buffer,1,max,fd);
-	*more = feof(fd) == 0;
-
-	//if(!(*more))
-	//	fclose(fd);
-
-	return ret;
-}
-
-
-void
-response_done_callback(void *cls,
-						struct SPDY_Response *response,
-						struct SPDY_Request *request,
-						enum SPDY_RESPONSE_RESULT status,
-						bool streamopened)
-{
-	(void)streamopened;
-	(void)status;
-	//printf("answer for %s was sent\n", (char *)cls);
-
-	/*if(SPDY_RESPONSE_RESULT_SUCCESS != status)
-	{
-		printf("answer for %s was NOT sent, %i\n", (char *)cls,status);
-	}*/
-
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-	if(NULL!=cls)fclose(cls);
-}
-
-void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-	(void)cls;
-	(void)request;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-	(void)headers;
-	(void)method;
-	(void)version;
-	(void)more;
-
-	struct SPDY_Response *response=NULL;
-	struct SPDY_NameValue *resp_headers;
-	char *fname;
-	char *fsize;
-	char *mime=NULL;
-	char *date=NULL;
-	ssize_t filesize = -666;
-	FILE *fd = NULL;
-	int ret = -666;
-
-	//printf("received request for '%s %s %s'\n", method, path, version);
-	if(strlen(path) > 1 && NULL == strstr(path, "..") && '/' == path[0])
-	{
-		asprintf(&fname,"%s%s",basedir,path);
-		if(0 == access(fname, R_OK))
-		{
-			if(NULL == (fd = fopen(fname,"r"))
-				|| 0 != (ret = fseek(fd, 0L, SEEK_END))
-				|| -1 == (filesize = ftell(fd))
-				|| 0 != (ret = fseek(fd, 0L, SEEK_SET)))
-			{
-				printf("Error on opening %s\n%p %i %zd\n",fname, fd, ret, filesize);
-				response = SPDY_build_response(SPDY_HTTP_INTERNAL_SERVER_ERROR,NULL,SPDY_HTTP_VERSION_1_1,NULL,NULL,0);
-			}
-			else
-			{
-				if(NULL == (resp_headers = SPDY_name_value_create()))
-				{
-					printf("SPDY_name_value_create failed\n");
-					abort();
-				}
-
-				date = Rfc1123_DateTimeNow();
-				if(NULL == date
-					|| SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_DATE,date))
-				{
-					printf("SPDY_name_value_add or Rfc1123_DateTimeNow failed\n");
-					abort();
-				}
-				free(date);
-
-				if(-1 == asprintf(&fsize, "%zd", filesize)
-					|| SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_CONTENT_LENGTH,fsize))
-				{
-					printf("SPDY_name_value_add or asprintf failed\n");
-					abort();
-				}
-				free(fsize);
-
-				GET_MIME_TYPE(path,mime);
-				if(SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_CONTENT_TYPE,mime))
-				{
-					printf("SPDY_name_value_add failed\n");
-					abort();
-				}
-				free(mime);
-
-				if(SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_SERVER,"libmicrospdy/fileserver"))
-				{
-					printf("SPDY_name_value_add failed\n");
-					abort();
-				}
-
-				response = SPDY_build_response_with_callback(200,NULL,
-					SPDY_HTTP_VERSION_1_1,resp_headers,&response_callback,fd,SPDY_MAX_SUPPORTED_FRAME_SIZE);
-				SPDY_name_value_destroy(resp_headers);
-			}
-
-			if(NULL==response){
-				printf("no response obj\n");
-				abort();
-			}
-
-			if(SPDY_queue_response(request,response,true,false,&response_done_callback,fd)!=SPDY_YES)
-			{
-				printf("queue\n");
-				abort();
-			}
-
-			free(fname);
-			return;
-		}
-		free(fname);
-	}
-
-	if(strcmp(path,"/close")==0)
-	{
-		run = 0;
-	}
-
-	response = SPDY_build_response(SPDY_HTTP_NOT_FOUND,NULL,SPDY_HTTP_VERSION_1_1,NULL,NULL,0);
-	printf("Not found %s\n",path);
-
-	if(NULL==response){
-		printf("no response obj\n");
-		abort();
-	}
-
-	if(SPDY_queue_response(request,response,true,false,&response_done_callback,NULL)!=SPDY_YES)
-	{
-		printf("queue\n");
-		abort();
-	}
-}
-
-int
-main (int argc, char *const *argv)
-{
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-
-	if(argc != 5)
-	{
-		printf("Usage: %s cert-file key-file base-dir port\n", argv[0]);
-		return 1;
-	}
-
-	SPDY_init();
-
-	daemon = SPDY_start_daemon(atoi(argv[4]),
-								argv[1],
-								argv[2],
-								NULL,
-								NULL,
-								&standard_request_handler,
-								NULL,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								1800,
-								SPDY_DAEMON_OPTION_END);
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	basedir = argv[3];
-
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set,
-								&except_fd_set);
-
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(run);
-
-	SPDY_stop_daemon(daemon);
-
-	SPDY_deinit();
-
-	return 0;
-}
-
diff --git a/src/examples/spdy_response_with_callback.c b/src/examples/spdy_response_with_callback.c
deleted file mode 100644
index 5bd452d..0000000
--- a/src/examples/spdy_response_with_callback.c
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file response_with_callback.c
- * @brief  shows how to create responses with callbacks
- * @author Andrey Uzunov
- */
- 
-//for asprintf
-#define _GNU_SOURCE 
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <errno.h>
-#include "microspdy.h"
-
-static int run = 1;
-
-
-static ssize_t
-response_callback (void *cls,
-						void *buffer,
-						size_t max,
-						bool *more)
-{
-	FILE *fd =(FILE*)cls;
-	
-	int ret = fread(buffer,1,max,fd);
-	*more = feof(fd) == 0;
-	
-	if(!(*more))
-		fclose(fd);
-	
-	return ret;
-}
-
-
-static void
-response_done_callback(void *cls,
-		       struct SPDY_Response *response,
-		       struct SPDY_Request *request,
-		       enum SPDY_RESPONSE_RESULT status,
-		       bool streamopened)
-{
-	(void)streamopened;
-	(void)status;
-  
-	printf("answer for %s was sent\n", (char *)cls);
-	
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-	free(cls);
-}
-
-
-static void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-	(void)cls;
-	(void)request;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-	(void)headers;
-	(void)more;
-	
-	char *html;
-	struct SPDY_Response *response=NULL;
-	struct SPDY_NameValue *resp_headers;
-	
-	printf("received request for '%s %s %s'\n", method, path, version);
-	if(strcmp(path,"/spdy-draft.txt")==0)
-	{
-		FILE *fd = fopen(DATA_DIR "spdy-draft.txt","r");
-		
-		if(NULL == (resp_headers = SPDY_name_value_create()))
-		{
-			fprintf(stdout,"SPDY_name_value_create failed\n");
-			abort();
-		}
-		if(SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_CONTENT_TYPE,"text/plain"))
-		{
-			fprintf(stdout,"SPDY_name_value_add failed\n");
-			abort();
-		}
-		
-		response = SPDY_build_response_with_callback(200,NULL,
-			SPDY_HTTP_VERSION_1_1,resp_headers,&response_callback,fd,SPDY_MAX_SUPPORTED_FRAME_SIZE);
-		SPDY_name_value_destroy(resp_headers);
-	}
-	else
-	{
-		if(strcmp(path,"/close")==0)
-		{
-			asprintf(&html,"<html>"
-		"<body><b>Closing now!</body></html>");
-			run = 0;
-		}
-		else
-		{
-			asprintf(&html,"<html>"
-		"<body><a href=\"/spdy-draft.txt\">/spdy-draft.txt</a><br></body></html>");
-		}
-		
-		response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,html,strlen(html));
-		free(html);
-	}
-	
-	if(NULL==response){
-		fprintf(stdout,"no response obj\n");
-		abort();
-	}
-	
-	void *clspath = strdup(path);
-	
-	if(SPDY_queue_response(request,response,true,false,&response_done_callback,clspath)!=SPDY_YES)
-	{
-		fprintf(stdout,"queue\n");
-		abort();
-	}
-}
-
-
-int
-main (int argc, char *const *argv)
-{	
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-	
-	if(argc != 2)
-	{
-		return 1;
-	}
-
-	SPDY_init();
-	
-	daemon = SPDY_start_daemon(atoi(argv[1]),
-								DATA_DIR "cert-and-key.pem",
-								DATA_DIR "cert-and-key.pem",
-								NULL,
-								NULL,
-								&standard_request_handler,
-								NULL,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								1800,
-								SPDY_DAEMON_OPTION_END);
-	
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-	
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-		
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set, 
-								&except_fd_set);
-								
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-		
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(run);
-
-	SPDY_stop_daemon(daemon);
-	
-	SPDY_deinit();
-	
-	return 0;
-}
-
diff --git a/src/examples/suspend_resume_epoll.c b/src/examples/suspend_resume_epoll.c
new file mode 100644
index 0000000..c85d9b7
--- /dev/null
+++ b/src/examples/suspend_resume_epoll.c
@@ -0,0 +1,218 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2018 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file suspend_resume_epoll.c
+ * @brief example for how to use libmicrohttpd with epoll() and
+ *        resume a suspended connection
+ * @author Robert D Kocisko
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "platform.h"
+#include <microhttpd.h>
+#include <sys/epoll.h>
+#include <sys/timerfd.h>
+#include <limits.h>
+
+#define TIMEOUT_INFINITE -1
+
+struct Request
+{
+  struct MHD_Connection *connection;
+  int timerfd;
+};
+
+
+static int epfd;
+
+static struct epoll_event evt;
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
+{
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct Request *req;
+  struct itimerspec ts;
+
+  (void) cls;
+  (void) method;
+  (void) version;           /* Unused. Silence compiler warning. */
+  (void) upload_data;       /* Unused. Silence compiler warning. */
+  (void) upload_data_size;  /* Unused. Silence compiler warning. */
+  req = *req_cls;
+  if (NULL == req)
+  {
+
+    req = malloc (sizeof(struct Request));
+    if (NULL == req)
+      return MHD_NO;
+    req->connection = connection;
+    req->timerfd = -1;
+    *req_cls = req;
+    return MHD_YES;
+  }
+
+  if (-1 != req->timerfd)
+  {
+    /* send response (echo request url) */
+    response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                     (const void *) url);
+    if (NULL == response)
+      return MHD_NO;
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+    return ret;
+  }
+  /* create timer and suspend connection */
+  req->timerfd = timerfd_create (CLOCK_MONOTONIC, TFD_NONBLOCK);
+  if (-1 == req->timerfd)
+  {
+    printf ("timerfd_create: %s", strerror (errno));
+    return MHD_NO;
+  }
+  evt.events = EPOLLIN;
+  evt.data.ptr = req;
+  if (-1 == epoll_ctl (epfd, EPOLL_CTL_ADD, req->timerfd, &evt))
+  {
+    printf ("epoll_ctl: %s", strerror (errno));
+    return MHD_NO;
+  }
+  ts.it_value.tv_sec = 1;
+  ts.it_value.tv_nsec = 0;
+  ts.it_interval.tv_sec = 0;
+  ts.it_interval.tv_nsec = 0;
+  if (-1 == timerfd_settime (req->timerfd, 0, &ts, NULL))
+  {
+    printf ("timerfd_settime: %s", strerror (errno));
+    return MHD_NO;
+  }
+  MHD_suspend_connection (connection);
+  return MHD_YES;
+}
+
+
+static void
+connection_done (void *cls,
+                 struct MHD_Connection *connection,
+                 void **req_cls,
+                 enum MHD_RequestTerminationCode toe)
+{
+  struct Request *req = *req_cls;
+
+  (void) cls;
+  (void) connection;
+  (void) toe;
+  if (-1 != req->timerfd)
+    if (0 != close (req->timerfd))
+      abort ();
+  free (req);
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *info;
+  int current_event_count;
+  struct epoll_event events_list[1];
+  struct Request *req;
+  uint64_t timer_expirations;
+  int port;
+
+  if (argc != 2)
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  port = atoi (argv[1]);
+  if ( (1 > port) || (port > 65535) )
+  {
+    fprintf (stderr,
+             "Port must be a number between 1 and 65535.\n");
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_USE_EPOLL | MHD_ALLOW_SUSPEND_RESUME,
+                        (uint16_t) port,
+                        NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &connection_done, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+
+  info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_EPOLL_FD);
+  if (info == NULL)
+    return 1;
+
+  epfd = epoll_create1 (EPOLL_CLOEXEC);
+  if (-1 == epfd)
+    return 1;
+
+  evt.events = EPOLLIN;
+  evt.data.ptr = NULL;
+  if (-1 == epoll_ctl (epfd, EPOLL_CTL_ADD, info->epoll_fd, &evt))
+    return 1;
+
+  while (1)
+  {
+    current_event_count = epoll_wait (epfd, events_list, 1,
+                                      MHD_get_timeout_i (d));
+
+    if (1 == current_event_count)
+    {
+      if (events_list[0].data.ptr)
+      {
+        /*  A timer has timed out */
+        req = events_list[0].data.ptr;
+        /* read from the fd so the system knows we heard the notice */
+        if (-1 == read (req->timerfd, &timer_expirations,
+                        sizeof(timer_expirations)))
+        {
+          return 1;
+        }
+        /*  Now resume the connection */
+        MHD_resume_connection (req->connection);
+      }
+    }
+    else if (0 == current_event_count)
+    {
+      /* no events: continue */
+    }
+    else
+    {
+      /* error */
+      return 1;
+    }
+    if (! MHD_run (d))
+      return 1;
+  }
+
+  return 0;
+}
diff --git a/src/examples/timeout.c b/src/examples/timeout.c
new file mode 100644
index 0000000..dacc93f
--- /dev/null
+++ b/src/examples/timeout.c
@@ -0,0 +1,85 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2016-2017 Christian Grothoff,
+     Silvio Clecio (silvioprog), Evgeny Grin (Karlson2k)
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file timeout.c
+ * @brief example for how to use libmicrohttpd request timeout
+ * @author Christian Grothoff, Silvio Clecio (silvioprog), Karlson2k (Evgeny Grin)
+ */
+
+#include <microhttpd.h>
+#include <stdio.h>
+#include <string.h>
+
+#define PORT 8080
+
+static enum MHD_Result
+answer_to_connection (void *cls,
+                      struct MHD_Connection *connection,
+                      const char *url,
+                      const char *method,
+                      const char *version,
+                      const char *upload_data,
+                      size_t *upload_data_size,
+                      void **req_cls)
+{
+  const char *page = "<html><body>Hello timeout!</body></html>";
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) method;            /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+  (void) req_cls;           /* Unused. Silent compiler warning. */
+
+  response = MHD_create_response_from_buffer_static (strlen (page),
+                                                     (const void *) page);
+  MHD_add_response_header (response,
+                           MHD_HTTP_HEADER_CONTENT_TYPE,
+                           "text/html");
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+int
+main (void)
+{
+  struct MHD_Daemon *daemon;
+
+  daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                             | MHD_USE_INTERNAL_POLLING_THREAD,
+                             PORT,
+                             NULL, NULL,
+                             &answer_to_connection, NULL,
+                             /* 3 seconds */
+                             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 3,
+                             MHD_OPTION_END);
+  if (NULL == daemon)
+    return 1;
+  (void) getchar ();
+  MHD_stop_daemon (daemon);
+  return 0;
+}
diff --git a/src/examples/upgrade_example.c b/src/examples/upgrade_example.c
new file mode 100644
index 0000000..5b57d24
--- /dev/null
+++ b/src/examples/upgrade_example.c
@@ -0,0 +1,316 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2016 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file upgrade_example.c
+ * @brief example for how to use libmicrohttpd upgrade
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Telnet to the HTTP server, use this in the request:
+ * GET / http/1.1
+ * Connection: Upgrade
+ *
+ * After this, whatever you type will be echo'ed back to you.
+ */
+
+#include "platform.h"
+#include <microhttpd.h>
+#include <pthread.h>
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
+
+
+/**
+ * Change socket to blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    abort ();
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      abort ();
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    abort ();
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+static void
+send_all (MHD_socket sock,
+          const char *buf,
+          size_t len)
+{
+  ssize_t ret;
+  size_t off;
+
+  make_blocking (sock);
+  for (off = 0; off < len; off += (size_t) ret)
+  {
+    ret = send (sock,
+                &buf[off],
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+                len - off,
+#else  /* Native W32 */
+                (int) (len - off),
+#endif /* Native W32 */
+                0);
+    if (0 > ret)
+    {
+      if (EAGAIN == errno)
+      {
+        ret = 0;
+        continue;
+      }
+      break;
+    }
+    if (0 == ret)
+      break;
+  }
+}
+
+
+struct MyData
+{
+  struct MHD_UpgradeResponseHandle *urh;
+  char *extra_in;
+  size_t extra_in_size;
+  MHD_socket sock;
+};
+
+
+/**
+ * Main function for the thread that runs the interaction with
+ * the upgraded socket.  Writes what it reads.
+ *
+ * @param cls the `struct MyData`
+ */
+static void *
+run_usock (void *cls)
+{
+  struct MyData *md = cls;
+  struct MHD_UpgradeResponseHandle *urh = md->urh;
+  char buf[128];
+  ssize_t got;
+
+  make_blocking (md->sock);
+  /* start by sending extra data MHD may have already read, if any */
+  if (0 != md->extra_in_size)
+  {
+    send_all (md->sock,
+              md->extra_in,
+              md->extra_in_size);
+    free (md->extra_in);
+  }
+  /* now echo in a loop */
+  while (1)
+  {
+    got = recv (md->sock,
+                buf,
+                sizeof (buf),
+                0);
+    if (0 >= got)
+      break;
+    send_all (md->sock,
+              buf,
+              (size_t) got);
+  }
+  free (md);
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+  return NULL;
+}
+
+
+/**
+ * Function called after a protocol "upgrade" response was sent
+ * successfully and the socket should now be controlled by some
+ * protocol other than HTTP.
+ *
+ * Any data already received on the socket will be made available in
+ * @e extra_in.  This can happen if the application sent extra data
+ * before MHD send the upgrade response.  The application should
+ * treat data from @a extra_in as if it had read it from the socket.
+ *
+ * Note that the application must not close() @a sock directly,
+ * but instead use #MHD_upgrade_action() for special operations
+ * on @a sock.
+ *
+ * Data forwarding to "upgraded" @a sock will be started as soon
+ * as this function return.
+ *
+ * Except when in 'thread-per-connection' mode, implementations
+ * of this function should never block (as it will still be called
+ * from within the main event loop).
+ *
+ * @param cls closure, whatever was given to #MHD_create_response_for_upgrade().
+ * @param connection original HTTP connection handle,
+ *                   giving the function a last chance
+ *                   to inspect the original HTTP request
+ * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback`
+ * @param extra_in if we happened to have read bytes after the
+ *                 HTTP header already (because the client sent
+ *                 more than the HTTP header of the request before
+ *                 we sent the upgrade response),
+ *                 these are the extra bytes already read from @a sock
+ *                 by MHD.  The application should treat these as if
+ *                 it had read them from @a sock.
+ * @param extra_in_size number of bytes in @a extra_in
+ * @param sock socket to use for bi-directional communication
+ *        with the client.  For HTTPS, this may not be a socket
+ *        that is directly connected to the client and thus certain
+ *        operations (TCP-specific setsockopt(), getsockopt(), etc.)
+ *        may not work as expected (as the socket could be from a
+ *        socketpair() or a TCP-loopback).  The application is expected
+ *        to perform read()/recv() and write()/send() calls on the socket.
+ *        The application may also call shutdown(), but must not call
+ *        close() directly.
+ * @param urh argument for #MHD_upgrade_action()s on this @a connection.
+ *        Applications must eventually use this callback to (indirectly)
+ *        perform the close() action on the @a sock.
+ */
+static void
+uh_cb (void *cls,
+       struct MHD_Connection *connection,
+       void *req_cls,
+       const char *extra_in,
+       size_t extra_in_size,
+       MHD_socket sock,
+       struct MHD_UpgradeResponseHandle *urh)
+{
+  struct MyData *md;
+  pthread_t pt;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) req_cls;     /* Unused. Silent compiler warning. */
+
+  md = malloc (sizeof (struct MyData));
+  if (NULL == md)
+    abort ();
+  memset (md, 0, sizeof (struct MyData));
+  if (0 != extra_in_size)
+  {
+    md->extra_in = malloc (extra_in_size);
+    if (NULL == md->extra_in)
+      abort ();
+    memcpy (md->extra_in,
+            extra_in,
+            extra_in_size);
+  }
+  md->extra_in_size = extra_in_size;
+  md->sock = sock;
+  md->urh = urh;
+  if (0 != pthread_create (&pt,
+                           NULL,
+                           &run_usock,
+                           md))
+    abort ();
+  /* Note that by detaching like this we make it impossible to ensure
+     a clean shutdown, as the we stop the daemon even if a worker thread
+     is still running. Alas, this is a simple example... */
+  pthread_detach (pt);
+
+  /* This callback must return as soon as possible. */
+
+  /* Data forwarding to "upgraded" socket will be started
+   * after return from this callback. */
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response = MHD_create_response_for_upgrade (&uh_cb,
+                                              NULL);
+
+  MHD_add_response_header (response,
+                           MHD_HTTP_HEADER_UPGRADE,
+                           "Echo Server");
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_SWITCHING_PROTOCOLS,
+                            response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  struct MHD_Daemon *d;
+  unsigned int port;
+
+  if ( (argc != 2) ||
+       (1 != sscanf (argv[1], "%u", &port)) ||
+       (65535 < port) )
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        (uint16_t) port,
+                        NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/examples/websocket_chatserver_example.c b/src/examples/websocket_chatserver_example.c
new file mode 100644
index 0000000..f01ada4
--- /dev/null
+++ b/src/examples/websocket_chatserver_example.c
@@ -0,0 +1,2356 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021 David Gausmann (and other contributing authors)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file websocket_chatserver_example.c
+ * @brief example for how to use websockets
+ * @author David Gausmann
+ *
+ * Access the HTTP server with your webbrowser.
+ * The webbrowser must support JavaScript and WebSockets.
+ * The websocket access will be initiated via the JavaScript on the website.
+ * You will get an example chat room, which uses websockets.
+ * For testing with multiple users, just start several instances of your webbrowser.
+ *
+ */
+
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+#include "platform.h"
+#include <microhttpd.h>
+#include <microhttpd_ws.h>
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
+/*
+  Workaround for Windows systems, because the NuGet version of pthreads is buggy.
+  This is a simple replacement. It doesn't offer all functions of pthread, but
+  has everything, what is required for this example.
+  See: https://github.com/coapp-packages/pthreads/issues/2
+*/
+#include "pthread_windows.h"
+
+/*
+  On Windows we will use stricmp instead of strcasecmp (strcasecmp is undefined there).
+*/
+#define strcasecmp stricmp
+
+#else
+/*
+  On Unix systems we can use pthread.
+*/
+#include <pthread.h>
+#endif
+
+
+/*
+ * Specify with this constant whether or not to use HTTPS.
+ * 0 means HTTP, 1 means HTTPS.
+ * Please note that you must enter a valid private key/certificate pair
+ * in the main procedure to running this example with HTTPS.
+ */
+#define USE_HTTPS 0
+
+/**
+ * This is the main website.
+ * The HTML, CSS and JavaScript code is all in there.
+ */
+#define PAGE \
+  "<!DOCTYPE html>" \
+  "<html>" \
+  "<head>" \
+  "<meta charset='UTF-8'>" \
+  "<title>libmicrohttpd websocket chatserver demo</title>" \
+  "<style>" \
+  "  html" \
+  "  {\n" \
+  "    font: 11pt sans-serif;\n" \
+  "  }\n" \
+  "  html, body" \
+  "  {\n" \
+  "    margin: 0;\n" \
+  "    width:  100vw;\n" \
+  "    height: 100vh;\n" \
+  "  }\n" \
+  "  div#Chat\n" \
+  "  {\n" \
+  "    display:        flex;\n" \
+  "    flex-direction: row;\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput\n" \
+  "  {\n" \
+  "    flex:             1 1 auto;" \
+  "    display:          flex;\n" \
+  "    flex-direction:   column;\n" \
+  "    width:            calc(100vw - 20em);\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div#Messages\n" \
+  "  {\n" \
+  "    flex:             1 1 auto;" \
+  "    display:          flex;\n" \
+  "    flex-direction:   column;\n" \
+  "    justify-content:  flex-start;\n" \
+  "    box-sizing:       border-box;\n" \
+  "    overflow-y:       scroll;\n" \
+  "    border:           2pt solid #888;\n" \
+  "    background-color: #eee;\n" \
+  "    height:           calc(100vh - 2em);\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div#Messages > div.Message > span\n" \
+  "  {\n" \
+  "    white-space: pre\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div#Messages > div.Message.error > span\n" \
+  "  {\n" \
+  "    color: red;\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div#Messages > div.Message.system > span\n" \
+  "  {\n" \
+  "    color: green;\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div#Messages > div.Message.moderator > span\n" \
+  "  {\n" \
+  "    color: #808000;\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div#Messages > div.Message.private > span\n" \
+  "  {\n" \
+  "    color: blue;\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div.Input\n" \
+  "  {\n" \
+  "    flex:             0 0 auto;" \
+  "    height:           2em;" \
+  "    display:          flex;" \
+  "    flex-direction:   row;" \
+  "    background-color: #eee;\n" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div.Input > input#InputMessage\n" \
+  "  {\n" \
+  "    flex:             1 1 auto;" \
+  "  }\n" \
+  "  div#Chat > div.MessagesAndInput > div.Input > button\n" \
+  "  {\n" \
+  "    flex:             0 0 auto;" \
+  "    width:            5em;" \
+  "    margin-left:      4pt;" \
+  "  }\n" \
+  "  div#Chat > div#Users\n" \
+  "  {\n" \
+  "    flex:             0 0 auto;" \
+  "    width:            20em;" \
+  "    display:          flex;\n" \
+  "    flex-direction:   column;\n" \
+  "    justify-content:  flex-start;\n" \
+  "    box-sizing:       border-box;\n" \
+  "    overflow-y:       scroll;\n" \
+  "    border:           2pt solid #888;\n" \
+  "    background-color: #eee;\n" \
+  "  }\n" \
+  "  div#Chat > div#Users > div\n" \
+  "  {\n" \
+  "    cursor: pointer;\n" \
+  "    user-select: none;\n" \
+  "    -webkit-user-select: none;\n" \
+  "  }\n" \
+  "  div#Chat > div#Users > div.selected\n" \
+  "  {\n" \
+  "    background-color: #7bf;\n" \
+  "  }\n" \
+  "</style>" \
+  "<script>\n" \
+  "  'use strict'\n;" \
+  "\n" \
+  "  let baseUrl;\n" \
+  "  let socket;\n" \
+  "  let connectedUsers = new Map();\n" \
+  "\n" \
+  "  window.addEventListener('load', window_onload);\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the main procedure which initializes the chat and connects the first socket\n" \
+  "  */\n" \
+  "  function window_onload(event)\n" \
+  "  {\n" \
+  " /* Determine the base url (for http:/" "/ this is ws:/" "/ for https:/" \
+                                  "/ this must be wss:/" "/) */\n" \
+  "    baseUrl = 'ws' + (window.location.protocol === 'https:' ? 's' : '') + ':/" "/' + window.location.host + '/ChatServerWebSocket';\n" \
+  "    chat_generate();\n" \
+  "    chat_connect();\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This function generates the chat using DOM\n" \
+  "  */\n" \
+  "  function chat_generate()\n" \
+  "  {\n" \
+  "    document.body.innerHTML = '';\n" \
+  "    let chat = document.createElement('div');\n" \
+  "    document.body.appendChild(chat);\n" \
+  "    chat.id = 'Chat';\n" \
+  "    let messagesAndInput = document.createElement('div');\n" \
+  "    chat.appendChild(messagesAndInput);\n" \
+  "    messagesAndInput.classList.add('MessagesAndInput');\n" \
+  "    let messages = document.createElement('div');\n" \
+  "    messagesAndInput.appendChild(messages);\n" \
+  "    messages.id = 'Messages';\n" \
+  "    let input = document.createElement('div');\n" \
+  "    messagesAndInput.appendChild(input);\n" \
+  "    input.classList.add('Input');\n" \
+  "    let inputMessage = document.createElement('input');\n" \
+  "    input.appendChild(inputMessage);\n" \
+  "    inputMessage.type = 'text';\n" \
+  "    inputMessage.id = 'InputMessage';\n" \
+  "    inputMessage.disabled = true;\n" \
+  "    inputMessage.addEventListener('keydown', chat_onKeyDown);\n" \
+  "    let inputMessageSend = document.createElement('button');\n" \
+  "    input.appendChild(inputMessageSend);\n" \
+  "    inputMessageSend.id = 'InputMessageButton';\n" \
+  "    inputMessageSend.disabled = true;\n" \
+  "    inputMessageSend.innerText = 'send';\n" \
+  "    inputMessageSend.addEventListener('click', chat_onSendClicked);\n" \
+  "    let inputImage = document.createElement('input');\n" \
+  "    input.appendChild(inputImage);\n" \
+  "    inputImage.id = 'InputImage';\n" \
+  "    inputImage.type = 'file';\n" \
+  "    inputImage.accept = 'image /*';\n" \
+  "    inputImage.style.display = 'none';\n" \
+  "    inputImage.addEventListener('change', chat_onImageSelected);\n" \
+  "    let inputImageButton = document.createElement('button');\n" \
+  "    input.appendChild(inputImageButton);\n" \
+  "    inputImageButton.id = 'InputImageButton';\n" \
+  "    inputImageButton.disabled = true;\n" \
+  "    inputImageButton.innerText = 'image';\n" \
+  "    inputImageButton.addEventListener('click', chat_onImageClicked);\n" \
+  "    let users = document.createElement('div');\n" \
+  "    chat.appendChild(users);\n" \
+  "    users.id = 'Users';\n" \
+  "    users.addEventListener('click', chat_onUserClicked);\n" \
+  "    let allUsers = document.createElement('div');\n" \
+  "    users.appendChild(allUsers);\n" \
+  "    allUsers.classList.add('selected');\n" \
+  "    allUsers.innerText = '<everyone>';\n" \
+  "    allUsers.setAttribute('data-user', '0');\n" \
+  "  }\n" \
+  "\n" \
+  "  /**\n" \
+  "    This function creates and connects a WebSocket\n" \
+  "  */\n" \
+  "  function chat_connect()\n" \
+  "  {\n" \
+  "    chat_addMessage(`Connecting to libmicrohttpd chat server demo (${baseUrl})...`, { type: 'system' });\n" \
+  "    socket = new WebSocket(baseUrl);\n" \
+  "    socket.binaryType = 'arraybuffer';\n" \
+  "    socket.onopen    = socket_onopen;\n" \
+  "    socket.onclose   = socket_onclose;\n" \
+  "    socket.onerror   = socket_onerror;\n" \
+  "    socket.onmessage = socket_onmessage;\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This function adds new text to the chat list\n" \
+  "  */\n" \
+  "  function chat_addMessage(text, options)\n" \
+  "  {\n" \
+  "    let type = options && options.type || 'regular';\n" \
+  "    if(!/^(?:regular|system|error|private|moderator)$/.test(type))\n" \
+  "      type = 'regular';\n" \
+  "    let message = document.createElement('div');\n" \
+  "    message.classList.add('Message');\n" \
+  "    message.classList.add(type);\n" \
+  "    if(typeof(text) === 'string')\n" \
+  "    {\n" \
+  "      let content = document.createElement('span');\n" \
+  "      message.appendChild(content);\n" \
+  "      if(options && options.from)\n" \
+  "        content.innerText = `${options.from}: ${text}`;\n" \
+  "      else\n" \
+  "        content.innerText = text;\n" \
+  "      if(options && options.reconnect)\n" \
+  "      {\n" \
+  "        let span = document.createElement('span');\n" \
+  "        span.appendChild(document.createTextNode(' ('));\n" \
+  "        let reconnect = document.createElement('a');\n" \
+  "        reconnect.href = 'javascript:chat_connect()';\n" \
+  "        reconnect.innerText = 'reconnect';\n" \
+  "        span.appendChild(reconnect);\n" \
+  "        span.appendChild(document.createTextNode(')'));\n" \
+  "        message.appendChild(span);\n" \
+  "      }\n" \
+  "    }\n" \
+  "    else\n" \
+  "    {\n" \
+  "      let content = document.createElement('span');\n" \
+  "      message.appendChild(content);\n" \
+  "      if(options && options.from)\n" \
+  "      {\n" \
+  "        content.innerText = `${options.from}:\\n`;\n" \
+  "      }\n" \
+  "      if(options && options.pictureType && text instanceof Uint8Array)\n" \
+  "      {\n" \
+  "        let img = document.createElement('img');\n" \
+  "        content.appendChild(img);\n" \
+  "        img.src = URL.createObjectURL(new Blob([ text.buffer ], { type: options.pictureType }));\n" \
+  "      }\n" \
+  "    }\n" \
+  "    document.getElementById('Messages').appendChild(message);\n" \
+  "    message.scrollIntoView();\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is a keydown event handler, which allows that you can just press enter instead of clicking the 'send' button\n" \
+  "  */\n" \
+  "  function chat_onKeyDown(event)\n" \
+  "  {\n" \
+  "    if(event.key == 'Enter')\n" \
+  "      chat_onSendClicked();\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the code to send a message or command, when clicking the 'send' button\n" \
+  "  */\n" \
+  "  function chat_onSendClicked(event)\n" \
+  "  {\n" \
+  "    let message = document.getElementById('InputMessage').value;\n" \
+  "    if(message.length == 0)\n" \
+  "      return;\n" \
+  "    if(message.substr(0, 1) == '/')\n" \
+  "    {\n" \
+  " /* command */ \n"     \
+  "      let match;\n" \
+  "      if(/^\\/disconnect\\s*$/.test(message))\n" \
+  "      {\n" \
+  "        socket.close(1000);\n" \
+  "      }\n" \
+  "      else if((match = /^\\/m\\s+(\\S+)\\s+/.exec(message)))\n" \
+  "      {\n" \
+  "        message = message.substr(match[0].length);\n" \
+  "        let userId = chat_getUserIdByName(match[1]);\n" \
+  "        if(userId !== null)\n" \
+  "        {\n" \
+  "          socket.send(`private|${userId}|${message}`);\n" \
+  "        }\n" \
+  "        else\n" \
+  "        {\n" \
+  "          chat_addMessage(`Unknown user \"${match[1]}\" for private message: ${message}`, { type: 'error' });\n" \
+  "        }\n" \
+  "      }\n" \
+  "      else if((match = /^\\/ping\\s+(\\S+)\\s*$/.exec(message)))\n" \
+  "      {\n" \
+  "        let userId = chat_getUserIdByName(match[1]);\n" \
+  "        if(userId !== null)\n" \
+  "        {\n" \
+  "          socket.send(`ping|${userId}|`);\n" \
+  "        }\n" \
+  "        else\n" \
+  "        {\n" \
+  "          chat_addMessage(`Unknown user \"${match[1]}\" for ping`, { type: 'error' });\n" \
+  "        }\n" \
+  "      }\n" \
+  "      else if((match = /^\\/name\\s+(\\S+)\\s*$/.exec(message)))\n" \
+  "      {\n" \
+  "        socket.send(`name||${match[1]}`);\n" \
+  "      }\n" \
+  "      else\n" \
+  "      {\n" \
+  "        chat_addMessage(`Unsupported command or invalid syntax: ${message}`, { type: 'error' });\n" \
+  "      }\n" \
+  "    }\n" \
+  "    else\n" \
+  "    {\n" \
+  " /* regular chat message to the selected user */ \n"     \
+  "      let selectedUser = document.querySelector('div#Users > div.selected');\n" \
+  "      let selectedUserId = parseInt(selectedUser.getAttribute('data-user') || '0', 10);\n" \
+  "      if(selectedUserId == 0)\n" \
+  "        socket.send(`||${message}`);\n" \
+  "      else\n" \
+  "        socket.send(`private|${selectedUserId}|${message}`);\n" \
+  "    }\n" \
+  "    document.getElementById('InputMessage').value = '';\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the user hits the 'image' button\n" \
+  "  */\n" \
+  "  function chat_onImageClicked(event)\n" \
+  "  {\n" \
+  "    document.getElementById('InputImage').click();\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the user selected an image.\n" \
+  "    The image will be read with the FileReader (allowed in web, because the user selected the file).\n" \
+  "  */\n" \
+  "  function chat_onImageSelected(event)\n" \
+  "  {\n" \
+  "    let file = event.target.files[0];\n" \
+  "    if(!file || !/^image\\/" "/.test(file.type))\n" \
+  "      return;\n" \
+  "    let selectedUser = document.querySelector('div#Users > div.selected');\n" \
+  "    let selectedUserId = parseInt(selectedUser.getAttribute('data-user') || '0', 10);\n" \
+  "    let reader = new FileReader();\n" \
+  "    reader.onload = function(event) {\n" \
+  "      chat_onImageRead(event, file.type, selectedUserId);\n" \
+  "    };\n" \
+  "    reader.readAsArrayBuffer(file);\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the user selected image has been read.\n" \
+  "    This will add our chat protocol prefix and send it via the websocket.\n" \
+  "  */\n" \
+  "  function chat_onImageRead(event, fileType, selectedUserId)\n" \
+  "  {\n" \
+  "    let encoder = new TextEncoder();\n" \
+  "    let prefix = ((selectedUserId == 0 ? '||' : `private|${selectedUserId}|`) + fileType + '|');\n" \
+  "    prefix = encoder.encode(prefix);\n" \
+  "    let byteData = new Uint8Array(event.target.result);\n" \
+  "    let totalLength = prefix.length + byteData.length;\n" \
+  "    let resultByteData = new Uint8Array(totalLength);\n" \
+  "    resultByteData.set(prefix, 0);\n" \
+  "    resultByteData.set(byteData, prefix.length);\n" \
+  "    socket.send(resultByteData);\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the user clicked a name in the user list.\n" \
+  "    This is useful to send private messages or images without needing to add the /m prefix.\n" \
+  "  */\n" \
+  "  function chat_onUserClicked(event, selectedUserId)\n" \
+  "  {\n" \
+  "    let newSelected = event.target.closest('div#Users > div');\n" \
+  "    if(newSelected === null)\n" \
+  "      return;\n" \
+  "    for(let div of this.querySelectorAll(':scope > div.selected'))\n" \
+  "      div.classList.remove('selected');\n" \
+  "    newSelected.classList.add('selected');\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This functions returns the current id of a user identified by its name.\n" \
+  "  */\n" \
+  "  function chat_getUserIdByName(name)\n" \
+  "  {\n" \
+  "    let nameUpper = name.toUpperCase();\n" \
+  "    for(let pair of connectedUsers)\n" \
+  "    {\n" \
+  "      if(pair[1].toUpperCase() == nameUpper)\n" \
+  "        return pair[0];\n" \
+  "    }\n" \
+  "    return null;\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This functions clears the entire user list (needed for reconnecting).\n" \
+  "  */\n" \
+  "  function chat_clearUserList()\n" \
+  "  {\n" \
+  "    let users = document.getElementById('Users');\n" \
+  "    for(let div of users.querySelectorAll(':scope > div'))\n" \
+  "    {\n" \
+  "      if(div.getAttribute('data-user') === '0')\n" \
+  "      {\n" \
+  "        div.classList.add('selected');\n" \
+  "      }\n" \
+  "      else\n" \
+  "      {\n" \
+  "        div.parentNode.removeChild(div);\n" \
+  "      }\n" \
+  "    }\n" \
+  "    return null;\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the socket has established a connection.\n" \
+  "    This will initialize an empty chat and enable the controls.\n" \
+  "  */\n" \
+  "  function socket_onopen(event)\n" \
+  "  {\n" \
+  "    connectedUsers.clear();\n" \
+  "    chat_clearUserList();\n" \
+  "    chat_addMessage('Connected!', { type: 'system' });\n" \
+  "    document.getElementById('InputMessage').disabled       = false;\n" \
+  "    document.getElementById('InputMessageButton').disabled = false;\n" \
+  "    document.getElementById('InputImageButton').disabled   = false;\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the socket has been closed.\n" \
+  "    This will lock the controls.\n" \
+  "  */\n" \
+  "  function socket_onclose(event)\n" \
+  "  {\n" \
+  "    chat_addMessage('Connection closed!', { type: 'system', reconnect: true });\n" \
+  "    document.getElementById('InputMessage').disabled       = true;\n" \
+  "    document.getElementById('InputMessageButton').disabled = true;\n" \
+  "    document.getElementById('InputImageButton').disabled   = true;\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the socket reported an error.\n" \
+  "    This will just make an output.\n" \
+  "    In the web browser console (F12 on many browsers) will show you more detailed error information.\n" \
+  "  */\n" \
+  "  function socket_onerror(event)\n" \
+  "  {\n" \
+  "    console.error('WebSocket error reported: ', event);\n" \
+  "    chat_addMessage('The socket reported an error!', { type: 'error' });\n" \
+  "  }\n" \
+  "\n" \
+  " /**\n" \
+  "    This is the event when the socket has received a message.\n" \
+  "    This will parse the message and execute the corresponding command (or add the message).\n" \
+  "  */\n" \
+  "  function socket_onmessage(event)\n" \
+  "  {\n" \
+  "    if(typeof(event.data) === 'string')\n" \
+  "    {\n" \
+  " /* text message or command */ \n"     \
+  "      let message = event.data.split('|', 3);\n" \
+  "      switch(message[0])\n" \
+  "      {\n" \
+  "      case 'userinit':\n" \
+  "        connectedUsers.set(message[1], message[2]);\n" \
+  "        {\n" \
+  "          let users = document.getElementById('Users');\n" \
+  "          let div = document.createElement('div');\n" \
+  "          users.appendChild(div);\n" \
+  "          div.innerText = message[2];\n" \
+  "          div.setAttribute('data-user', message[1]);\n" \
+  "        }\n" \
+  "        break;\n" \
+  "      case 'useradd':\n" \
+  "        connectedUsers.set(message[1], message[2]);\n" \
+  "        chat_addMessage(`The user '${message[2]}' has joined our lovely chatroom.`, { type: 'moderator' });\n" \
+  "        {\n" \
+  "          let users = document.getElementById('Users');\n" \
+  "          let div = document.createElement('div');\n" \
+  "          users.appendChild(div);\n" \
+  "          div.innerText = message[2];\n" \
+  "          div.setAttribute('data-user', message[1]);\n" \
+  "        }\n" \
+  "        break;\n" \
+  "      case 'userdel':\n" \
+  "        chat_addMessage(`The user '${connectedUsers.get(message[1])}' has left our chatroom. We will miss you.`, { type: 'moderator' });\n" \
+  "        connectedUsers.delete(message[1]);\n" \
+  "        {\n" \
+  "          let users = document.getElementById('Users');\n" \
+  "          let div = users.querySelector(`div[data-user='${message[1]}']`);\n" \
+  "          if(div !== null)\n" \
+  "          {\n" \
+  "            users.removeChild(div);\n" \
+  "            if(div.classList.contains('selected'))\n" \
+  "              users.querySelector('div[data-user=\\'0\\']').classList.add('selected');\n" \
+  "          }\n" \
+  "        }\n" \
+  "        break;\n" \
+  "      case 'username':\n" \
+  "        chat_addMessage(`The user '${connectedUsers.get(message[1])}' has changed his name to '${message[2]}'.`, { type: 'moderator' });\n" \
+  "        connectedUsers.set(message[1], message[2]);\n" \
+  "        {\n" \
+  "          let users = document.getElementById('Users');\n" \
+  "          let div = users.querySelector(`div[data-user='${message[1]}']`);\n" \
+  "          if(div !== null)\n" \
+  "          {\n" \
+  "            div.innerText = message[2];\n" \
+  "          }\n" \
+  "        }\n" \
+  "        break;\n" \
+  "      case 'ping':\n" \
+  "        chat_addMessage(`The user '${connectedUsers.get(message[1])}' has a ping of ${message[2]} ms.`, { type: 'moderator' });\n" \
+  "        break;\n" \
+  "      default:\n" \
+  "        chat_addMessage(message[2], { type: message[0], from: connectedUsers.get(message[1]) });\n" \
+  "        break;\n" \
+  "      }\n" \
+  "    }\n" \
+  "    else\n" \
+  "    {\n" \
+  " /* We received a binary frame, which means a picture here */ \n"     \
+  "      let byteData = new Uint8Array(event.data);\n" \
+  "      let decoder = new TextDecoder();\n" \
+  "      let message  = [ ];\n" \
+  " /* message type */ \n"     \
+  "      let j = 0;\n" \
+  "      let i = byteData.indexOf(0x7C, j); /* | = 0x7C;*/ \n"\
+  "      if(i < 0)\n" \
+  "        return;\n" \
+  "      message.push(decoder.decode(byteData.slice(0, i)));\n" \
+  " /* picture from */ \n"     \
+  "      j = i + 1;\n" \
+  "      i = byteData.indexOf(0x7C, j);\n" \
+  "      if(i < 0)\n" \
+  "        return;\n" \
+  "      message.push(decoder.decode(byteData.slice(j, i)));\n" \
+  " /* picture encoding */ \n"     \
+  "      j = i + 1;\n" \
+  "      i = byteData.indexOf(0x7C, j);\n" \
+  "      if(i < 0)\n" \
+  "        return;\n" \
+  "      message.push(decoder.decode(byteData.slice(j, i)));\n" \
+  " /* picture */ \n"     \
+  "      byteData = byteData.slice(i + 1);\n" \
+  "      chat_addMessage(byteData, { type: message[0], from: connectedUsers.get(message[1]), pictureType: message[2] });\n" \
+  "    }\n" \
+  "  }\n" \
+  "</script>" \
+  "</head>" \
+  "<body><noscript>Please enable JavaScript to test the libmicrohttpd Websocket chatserver demo!</noscript></body>" \
+  "</html>"
+
+#define PAGE_NOT_FOUND \
+  "404 Not Found"
+
+#define PAGE_INVALID_WEBSOCKET_REQUEST \
+  "Invalid WebSocket request!"
+
+/**
+ * This struct is used to keep the data of a connected chat user.
+ * It is passed to the socket-receive thread (connecteduser_receive_messages) as well as to
+ * the socket-send thread (connecteduser_send_messages).
+ * It can also be accessed via the global array users (mutex protected).
+ */
+struct ConnectedUser
+{
+  /* the TCP/IP socket for reading/writing */
+  MHD_socket fd;
+  /* the UpgradeResponseHandle of libmicrohttpd (needed for closing the socket) */
+  struct MHD_UpgradeResponseHandle *urh;
+  /* the websocket encode/decode stream */
+  struct MHD_WebSocketStream *ws;
+  /* the possibly read data at the start (only used once) */
+  char *extra_in;
+  size_t extra_in_size;
+  /* the unique user id (counting from 1, ids will never be re-used) */
+  size_t user_id;
+  /* the current user name */
+  char *user_name;
+  size_t user_name_len;
+  /* the zero-based index of the next message;
+     may be decremented when old messages are deleted */
+  size_t next_message_index;
+  /* specifies whether the websocket shall be closed (1) or not (0) */
+  int disconnect;
+  /* condition variable to wake up the sender of this connection */
+  pthread_cond_t wake_up_sender;
+  /* mutex to ensure that no send actions are mixed
+     (sending can be done by send and recv thread;
+      may not be simultaneously locked with chat_mutex by the same thread) */
+  pthread_mutex_t send_mutex;
+  /* specifies whether a ping shall be executed (1), is being executed (2) or
+     no ping is pending (0) */
+  int ping_status;
+  /* the start time of the ping, if a ping is running */
+  struct timespec ping_start;
+  /* the message used for the ping (must match the pong response)*/
+  char ping_message[128];
+  /* the length of the ping message (may not exceed 125) */
+  size_t ping_message_len;
+  /* the numeric ping message suffix to detect ping messages, which are too old */
+  int ping_counter;
+};
+
+/**
+ * A single message, which has been send via the chat.
+ * This can be text, an image or a command.
+ */
+struct Message
+{
+  /* The user id of the sender. This is 0 if it is a system message- */
+  size_t from_user_id;
+  /* The user id of the recipient. This is 0 if every connected user shall receive it */
+  size_t to_user_id;
+  /* The data of the message. */
+  char *data;
+  size_t data_len;
+  /* Specifies whether the data is UTF-8 encoded text (0) or binary data (1) */
+  int is_binary;
+};
+
+/* the unique user counter for new users (only accessed by main thread) */
+size_t unique_user_id = 0;
+
+/* the chat data (users and messages; may be accessed by all threads, but is protected by mutex) */
+pthread_mutex_t chat_mutex;
+struct ConnectedUser **users = NULL;
+size_t user_count = 0;
+struct Message **messages = NULL;
+size_t message_count = 0;
+/* specifies whether all websockets must close (1) or not (0) */
+volatile int disconnect_all = 0;
+/* a counter for cleaning old messages (each 10 messages we will try to clean the list */
+int clean_count = 0;
+#define CLEANUP_LIMIT 10
+
+/**
+ * Change socket to blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    abort ();
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      abort ();
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    abort ();
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+/**
+ * Sends all data of the given buffer via the TCP/IP socket
+ *
+ * @param fd  The TCP/IP socket which is used for sending
+ * @param buf The buffer with the data to send
+ * @param len The length in bytes of the data in the buffer
+ */
+static void
+send_all (struct ConnectedUser *cu,
+          const char *buf,
+          size_t len)
+{
+  ssize_t ret;
+  size_t off;
+
+  if (0 == pthread_mutex_lock (&cu->send_mutex))
+  {
+    for (off = 0; off < len; off += ret)
+    {
+      ret = send (cu->fd,
+                  &buf[off],
+                  (int) (len - off),
+                  0);
+      if (0 > ret)
+      {
+        if (EAGAIN == errno)
+        {
+          ret = 0;
+          continue;
+        }
+        break;
+      }
+      if (0 == ret)
+        break;
+    }
+    pthread_mutex_unlock (&cu->send_mutex);
+  }
+}
+
+
+/**
+ * Adds a new chat message to the list of messages.
+ *
+ * @param from_user_id the user id of the sender (0 means system)
+ * @param to_user_id   the user id of the recipiend (0 means everyone)
+ * @param data         the data to send (UTF-8 text or binary; will be copied)
+ * @param data_len     the length of the data to send
+ * @param is_binary    specifies whether the data is UTF-8 text (0) or binary (1)
+ * @param needs_lock   specifies whether the caller has already locked the global chat mutex (0) or
+ *                     if this procedure needs to lock it (1)
+ *
+ * @return             0 on success, other values on error
+ */
+static int
+chat_addmessage (size_t from_user_id,
+                 size_t to_user_id,
+                 char *data,
+                 size_t data_len,
+                 int is_binary,
+                 int needs_lock)
+{
+  /* allocate the buffer and fill it with data */
+  struct Message *message = (struct Message *) malloc (sizeof (struct Message));
+  if (NULL == message)
+    return 1;
+
+  memset (message, 0, sizeof (struct Message));
+  message->from_user_id = from_user_id;
+  message->to_user_id   = to_user_id;
+  message->is_binary    = is_binary;
+  message->data_len     = data_len;
+  message->data = malloc (data_len + 1);
+  if (NULL == message->data)
+  {
+    free (message);
+    return 1;
+  }
+  memcpy (message->data, data, data_len);
+  message->data[data_len] = 0;
+
+  /* lock the global mutex if needed */
+  if (0 != needs_lock)
+  {
+    if (0 != pthread_mutex_lock (&chat_mutex))
+      return 1;
+  }
+
+  /* add the new message to the global message list */
+  size_t message_count_ = message_count + 1;
+  struct Message **messages_ = (struct Message **) realloc (messages,
+                                                            message_count_
+                                                            * sizeof (struct
+                                                                      Message *));
+  if (NULL == messages_)
+  {
+    free (message);
+    if (0 != needs_lock)
+      pthread_mutex_unlock (&chat_mutex);
+    return 1;
+  }
+  messages_[message_count] = message;
+  messages = messages_;
+  message_count = message_count_;
+
+  /* inform the sender threads about the new message */
+  for (size_t i = 0; i < user_count; ++i)
+    pthread_cond_signal (&users[i]->wake_up_sender);
+
+  /* unlock the global mutex if needed */
+  if (0 != needs_lock)
+  {
+    if (0 != needs_lock)
+      pthread_mutex_unlock (&chat_mutex);
+  }
+  return 0;
+}
+
+
+/**
+ * Cleans up old messages
+ *
+ * @param needs_lock   specifies whether the caller has already locked the global chat mutex (0) or
+ *                     if this procedure needs to lock it (1)
+ * @return             0 on success, other values on error
+ */
+static int
+chat_clearmessages (int needs_lock)
+{
+  /* lock the global mutex if needed */
+  if (0 != needs_lock)
+  {
+    if (0 != pthread_mutex_lock (&chat_mutex))
+      return 1;
+  }
+
+  /* update the clean counter and check whether we need cleaning */
+  ++clean_count;
+  if (CLEANUP_LIMIT > clean_count)
+  {
+    /* no cleanup required */
+    if (0 != needs_lock)
+    {
+      pthread_mutex_unlock (&chat_mutex);
+    }
+    return 0;
+  }
+  clean_count = 0;
+
+  /* check whether we got any messages (without them no cleaning is required */
+  if (0 < message_count)
+  {
+    /* then check whether we got any connected users */
+    if (0 < user_count)
+    {
+      /* determine the minimum index for the next message of all connected users */
+      size_t min_message = users[0]->next_message_index;
+      for (size_t i = 1; i < user_count; ++i)
+      {
+        if (min_message > users[i]->next_message_index)
+          min_message = users[i]->next_message_index;
+      }
+      if (0 < min_message)
+      {
+        /* remove all messages with index below min_message and update
+           the message indices of the users */
+        for (size_t i = 0; i < min_message; ++i)
+        {
+          free (messages[i]->data);
+          free (messages[i]);
+        }
+        for (size_t i = min_message; i < message_count; ++i)
+          messages[i - min_message] = messages[i];
+        message_count -= min_message;
+        for (size_t i = 0; i < user_count; ++i)
+          users[i]->next_message_index -= min_message;
+      }
+    }
+    else
+    {
+      /* without connected users, simply remove all messages */
+      for (size_t i = 0; i < message_count; ++i)
+      {
+        free (messages[i]->data);
+        free (messages[i]);
+      }
+      free (messages);
+      messages = NULL;
+      message_count = 0;
+    }
+  }
+
+  /* unlock the global mutex if needed */
+  if (0 != needs_lock)
+  {
+    pthread_mutex_unlock (&chat_mutex);
+  }
+  return 0;
+}
+
+
+/**
+ * Adds a new chat user to the global user list.
+ * This will be called at the start of connecteduser_receive_messages.
+ *
+ * @param cu The connected user
+ * @return   0 on success, other values on error
+ */
+static int
+chat_adduser (struct ConnectedUser *cu)
+{
+  /* initialize the notification message of the new user */
+  char user_index[32];
+  snprintf (user_index, 32, "%d", (int) cu->user_id);
+  size_t user_index_len = strlen (user_index);
+  size_t data_len = user_index_len + cu->user_name_len + 9;
+  char *data = (char *) malloc (data_len + 1);
+  if (NULL == data)
+    return 1;
+  strcpy (data, "useradd|");
+  strcat (data, user_index);
+  strcat (data, "|");
+  strcat (data, cu->user_name);
+
+  /* lock the mutex */
+  if (0 != pthread_mutex_lock (&chat_mutex))
+  {
+    free (data);
+    return 1;
+  }
+  /* inform the other chat users about the new user */
+  if (0 != chat_addmessage (0,
+                            0,
+                            data,
+                            data_len,
+                            0,
+                            0))
+  {
+    free (data);
+    pthread_mutex_unlock (&chat_mutex);
+    return 1;
+  }
+  free (data);
+
+  /* add the new user to the list */
+  size_t user_count_ = user_count + 1;
+  struct ConnectedUser **users_ =
+    (struct ConnectedUser **) realloc (users, user_count_
+                                       * sizeof (struct ConnectedUser *));
+  if (NULL == users_)
+  {
+    /* realloc failed */
+    pthread_mutex_unlock (&chat_mutex);
+    return 1;
+  }
+  users_[user_count] = cu;
+  users      = users_;
+  user_count = user_count_;
+
+  /* Initialize the next message index to the current message count. */
+  /* This will skip all old messages for this new connected user. */
+  cu->next_message_index = message_count;
+
+  /* unlock the mutex */
+  pthread_mutex_unlock (&chat_mutex);
+  return 0;
+}
+
+
+/**
+ * Removes a chat user from the global user list.
+ *
+ * @param cu The connected user
+ * @return   0 on success, other values on error
+ */
+static int
+chat_removeuser (struct ConnectedUser *cu)
+{
+  char user_index[32];
+
+  /* initialize the chat message for the removed user */
+  snprintf (user_index, 32, "%d", (int) cu->user_id);
+  size_t user_index_len = strlen (user_index);
+  size_t data_len = user_index_len + 9;
+  char *data = (char *) malloc (data_len + 1);
+  if (NULL == data)
+    return 1;
+  strcpy (data, "userdel|");
+  strcat (data, user_index);
+  strcat (data, "|");
+
+  /* lock the mutex */
+  if (0 != pthread_mutex_lock (&chat_mutex))
+  {
+    free (data);
+    return 1;
+  }
+  /* inform the other chat users that the user is gone */
+  int got_error = 0;
+  if (0 != chat_addmessage (0, 0, data, data_len, 0, 0))
+  {
+    free (data);
+    got_error = 1;
+  }
+
+  /* remove the user from the list */
+  int found = 0;
+  for (size_t i = 0; i < user_count; ++i)
+  {
+    if (cu == users[i])
+    {
+      found = 1;
+      for (size_t j = i + 1; j < user_count; ++j)
+      {
+        users[j - 1] = users[j];
+      }
+      --user_count;
+      break;
+    }
+  }
+  if (0 == found)
+    got_error = 1;
+
+  /* unlock the mutex */
+  pthread_mutex_unlock (&chat_mutex);
+
+  return got_error;
+}
+
+
+/**
+ * Renames a chat user
+ *
+ * @param cu           The connected user
+ * @param new_name     The new user name. On success this pointer will be taken.
+ * @param new_name_len The length of the new name
+ * @return             0 on success, other values on error. 2 means name already in use.
+ */
+static int
+chat_renameuser (struct ConnectedUser *cu,
+                 char *new_name,
+                 size_t new_name_len)
+{
+  /* lock the mutex */
+  if (0 != pthread_mutex_lock (&chat_mutex))
+  {
+    return 1;
+  }
+
+  /* check whether the name is already in use */
+  for (size_t i = 0; i < user_count; ++i)
+  {
+    if (cu != users[i])
+    {
+      if ((users[i]->user_name_len == new_name_len) &&
+          (0 == strcasecmp (users[i]->user_name, new_name)))
+      {
+        pthread_mutex_unlock (&chat_mutex);
+        return 2;
+      }
+    }
+  }
+
+  /* generate the notification message */
+  char user_index[32];
+  snprintf (user_index, 32, "%d", (int) cu->user_id);
+  size_t user_index_len = strlen (user_index);
+  size_t data_len = user_index_len + new_name_len + 10;
+  char *data = (char *) malloc (data_len + 1);
+  if (NULL == data)
+    return 1;
+  strcpy (data, "username|");
+  strcat (data, user_index);
+  strcat (data, "|");
+  strcat (data, new_name);
+
+  /* inform the other chat users about the new name */
+  if (0 != chat_addmessage (0, 0, data, data_len, 0, 0))
+  {
+    free (data);
+    pthread_mutex_unlock (&chat_mutex);
+    return 1;
+  }
+  free (data);
+
+  /* accept the new user name */
+  free (cu->user_name);
+  cu->user_name = new_name;
+  cu->user_name_len = new_name_len;
+
+  /* unlock the mutex */
+  pthread_mutex_unlock (&chat_mutex);
+
+  return 0;
+}
+
+
+/**
+* Parses received data from the TCP/IP socket with the websocket stream
+*
+* @param cu           The connected user
+* @param new_name     The new user name
+* @param new_name_len The length of the new name
+* @return             0 on success, other values on error
+*/
+static int
+connecteduser_parse_received_websocket_stream (struct ConnectedUser *cu,
+                                               char *buf,
+                                               size_t buf_len)
+{
+  size_t buf_offset = 0;
+  while (buf_offset < buf_len)
+  {
+    size_t new_offset = 0;
+    char *frame_data = NULL;
+    size_t frame_len  = 0;
+    int status = MHD_websocket_decode (cu->ws,
+                                       buf + buf_offset,
+                                       buf_len - buf_offset,
+                                       &new_offset,
+                                       &frame_data,
+                                       &frame_len);
+    if (0 > status)
+    {
+      /* an error occurred and the connection must be closed */
+      if (NULL != frame_data)
+      {
+        /* depending on the WebSocket flag */
+        /* MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR */
+        /* close frames might be generated on errors */
+        send_all (cu,
+                  frame_data,
+                  frame_len);
+        MHD_websocket_free (cu->ws, frame_data);
+      }
+      return 1;
+    }
+    else
+    {
+      buf_offset += new_offset;
+
+      if (0 < status)
+      {
+        /* the frame is complete */
+        switch (status)
+        {
+        case MHD_WEBSOCKET_STATUS_TEXT_FRAME:
+        case MHD_WEBSOCKET_STATUS_BINARY_FRAME:
+          /**
+           * a text or binary frame has been received.
+           * in this chat server example we use a simple protocol where
+           * the JavaScript added a prefix like "<command>|<to_user_id>|data".
+           * Some examples:
+           * "||test" means a regular chat message to everyone with the message "test".
+           * "private|1|secret" means a private chat message to user with id 1 with the message "secret".
+           * "name||MyNewName" means that the user requests a rename to "MyNewName"
+           * "ping|1|" means that the user with id 1 shall get a ping
+           *
+           * Binary data is handled here like text data.
+           * The difference in the data is only checked by the JavaScript.
+           */
+          {
+            size_t command      = 1000;
+            size_t from_user_id = cu->user_id;
+            size_t to_user_id   = 0;
+            size_t i;
+
+            /* parse the command */
+            for (i = 0; i < frame_len; ++i)
+            {
+              if ('|' == frame_data[i])
+              {
+                frame_data[i] = 0;
+                ++i;
+                break;
+              }
+            }
+            if (0 < i)
+            {
+              if (i == 1)
+              {
+                /* no command means regular message */
+                command = 0;
+              }
+              else if (0 == strcasecmp (frame_data, "private"))
+              {
+                /* private means private message */
+                command = 1;
+              }
+              else if (0 == strcasecmp (frame_data, "name"))
+              {
+                /* name means chat user rename */
+                command = 2;
+              }
+              else if (0 == strcasecmp (frame_data, "ping"))
+              {
+                /* ping means a ping request */
+                command = 3;
+              }
+              else
+              {
+                /* no other commands supported, so this means invalid */
+                command = 1000;
+              }
+            }
+
+            /* parse the to_user_id, if given */
+            size_t j = i;
+            for (; j < frame_len; ++j)
+            {
+              if ('|' == frame_data[j])
+              {
+                frame_data[j] = 0;
+                ++j;
+                break;
+              }
+            }
+            if (i + 1 < j)
+            {
+              to_user_id = (size_t) atoi (frame_data + i);
+            }
+
+            /* decide via the command what action to do */
+            if (frame_len >= j)
+            {
+              int is_binary = (MHD_WEBSOCKET_STATUS_BINARY_FRAME == status ? 1 :
+                               0);
+              switch (command)
+              {
+              case 0:
+                /* regular chat message */
+                {
+                  /**
+                  * Generate the message for the message list.
+                  * Regular chat messages get the command "regular".
+                  * After that we add the from_user_id, followed by the content.
+                  * The content must always be copied with memcpy instead of strcat,
+                  * because the data (binary as well as UTF-8 encoded) is allowed
+                  * to contain the NUL character.
+                  * However we will add a terminating NUL character,
+                  * which is not included in the data length
+                  * (and thus will not be send to the recipients).
+                  * This is useful for debugging with an IDE.
+                  */
+                  char user_index[32];
+                  snprintf (user_index, 32, "%d", (int) cu->user_id);
+                  size_t user_index_len = strlen (user_index);
+                  size_t data_len = user_index_len + frame_len - j + 9;
+                  char *data = (char *) malloc (data_len + 1);
+                  if (NULL != data)
+                  {
+                    strcpy (data, "regular|");
+                    strcat (data, user_index);
+                    strcat (data, "|");
+                    size_t offset = strlen (data);
+                    memcpy (data + offset,
+                            frame_data + j,
+                            frame_len - j);
+                    data[data_len] = 0;
+
+                    /* add the chat message to the global list */
+                    chat_addmessage (from_user_id,
+                                     0,
+                                     data,
+                                     data_len,
+                                     is_binary,
+                                     1);
+                    free (data);
+                  }
+                }
+                break;
+
+              case 1:
+                /* private chat message */
+                if (0 != to_user_id)
+                {
+                  /**
+                   * Generate the message for the message list.
+                   * This is similar to the code for regular messages above.
+                   * The difference is the prefix "private"
+                  */
+                  char user_index[32];
+                  snprintf (user_index, 32, "%d", (int) cu->user_id);
+                  size_t user_index_len = strlen (user_index);
+                  size_t data_len = user_index_len + frame_len - j + 9;
+                  char *data = (char *) malloc (data_len + 1);
+                  if (NULL != data)
+                  {
+
+                    strcpy (data, "private|");
+                    strcat (data, user_index);
+                    strcat (data, "|");
+                    size_t offset = strlen (data);
+                    memcpy (data + offset,
+                            frame_data + j,
+                            frame_len - j);
+                    data[data_len] = 0;
+
+                    /* add the chat message to the global list */
+                    chat_addmessage (from_user_id,
+                                     to_user_id,
+                                     data,
+                                     data_len,
+                                     is_binary,
+                                     1);
+                    free (data);
+                  }
+                }
+                break;
+
+              case 2:
+                /* rename */
+                {
+                  /* check whether the new name is valid and allocate a new buffer for it */
+                  size_t new_name_len = frame_len - j;
+                  if (0 == new_name_len)
+                  {
+                    chat_addmessage (0,
+                                     from_user_id,
+                                     "error||Your new name is invalid. You haven't been renamed.",
+                                     58,
+                                     0,
+                                     1);
+                    break;
+                  }
+                  char *new_name = (char *) malloc (new_name_len + 1);
+                  if (NULL == new_name)
+                  {
+                    chat_addmessage (0,
+                                     from_user_id,
+                                     "error||Error while renaming. You haven't been renamed.",
+                                     54,
+                                     0,
+                                     1);
+                    break;
+                  }
+                  new_name[new_name_len] = 0;
+                  for (size_t k = 0; k < new_name_len; ++k)
+                  {
+                    char c = frame_data[j + k];
+                    if ((32 >= c) || (c >= 127))
+                    {
+                      free (new_name);
+                      new_name = NULL;
+                      chat_addmessage (0,
+                                       from_user_id,
+                                       "error||Your new name contains invalid characters. You haven't been renamed.",
+                                       75,
+                                       0,
+                                       1);
+                      break;
+                    }
+                    new_name[k] = c;
+                  }
+                  if (NULL == new_name)
+                    break;
+
+                  /* rename the user */
+                  int rename_result = chat_renameuser (cu,
+                                                       new_name,
+                                                       new_name_len);
+                  if (0 != rename_result)
+                  {
+                    /* the buffer will only be freed if no rename was possible */
+                    free (new_name);
+                    if (2 == rename_result)
+                    {
+                      chat_addmessage (0,
+                                       from_user_id,
+                                       "error||Your new name is already in use by another user. You haven't been renamed.",
+                                       81,
+                                       0,
+                                       1);
+                    }
+                    else
+                    {
+                      chat_addmessage (0,
+                                       from_user_id,
+                                       "error||Error while renaming. You haven't been renamed.",
+                                       54,
+                                       0,
+                                       1);
+                    }
+                  }
+                }
+                break;
+
+              case 3:
+                /* ping */
+                {
+                  if (0 == pthread_mutex_lock (&chat_mutex))
+                  {
+                    /* check whether the to_user exists */
+                    struct ConnectedUser *ping_user = NULL;
+                    for (size_t k = 0; k < user_count; ++k)
+                    {
+                      if (users[k]->user_id == to_user_id)
+                      {
+                        ping_user = users[k];
+                        break;
+                      }
+                    }
+                    if (NULL == ping_user)
+                    {
+                      chat_addmessage (0,
+                                       from_user_id,
+                                       "error||Couldn't find the specified user for pinging.",
+                                       52,
+                                       0,
+                                       0);
+                    }
+                    else
+                    {
+                      /* if pinging is requested, */
+                      /* we mark the user and inform the sender about this */
+                      if (0 == ping_user->ping_status)
+                      {
+                        ping_user->ping_status = 1;
+                        pthread_cond_signal (&ping_user->wake_up_sender);
+                      }
+                    }
+                    pthread_mutex_unlock (&chat_mutex);
+                  }
+                  else
+                  {
+                    chat_addmessage (0,
+                                     from_user_id,
+                                     "error||Error while pinging.",
+                                     27,
+                                     0,
+                                     1);
+                  }
+                }
+                break;
+
+              default:
+                /* invalid command */
+                chat_addmessage (0,
+                                 from_user_id,
+                                 "error||You sent an invalid command.",
+                                 35,
+                                 0,
+                                 1);
+                break;
+              }
+            }
+          }
+          MHD_websocket_free (cu->ws,
+                              frame_data);
+          return 0;
+
+        case MHD_WEBSOCKET_STATUS_CLOSE_FRAME:
+          /* if we receive a close frame, we will respond with one */
+          MHD_websocket_free (cu->ws,
+                              frame_data);
+          {
+            char *result = NULL;
+            size_t result_len = 0;
+            int er = MHD_websocket_encode_close (cu->ws,
+                                                 MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                                 NULL,
+                                                 0,
+                                                 &result,
+                                                 &result_len);
+            if (MHD_WEBSOCKET_STATUS_OK == er)
+            {
+              send_all (cu,
+                        result,
+                        result_len);
+              MHD_websocket_free (cu->ws, result);
+            }
+          }
+          return 1;
+
+        case MHD_WEBSOCKET_STATUS_PING_FRAME:
+          /* if we receive a ping frame, we will respond */
+          /* with the corresponding pong frame */
+          {
+            char *pong = NULL;
+            size_t pong_len = 0;
+            int er = MHD_websocket_encode_pong (cu->ws,
+                                                frame_data,
+                                                frame_len,
+                                                &pong,
+                                                &pong_len);
+
+            MHD_websocket_free (cu->ws,
+                                frame_data);
+            if (MHD_WEBSOCKET_STATUS_OK == er)
+            {
+              send_all (cu,
+                        pong,
+                        pong_len);
+              MHD_websocket_free (cu->ws,
+                                  pong);
+            }
+          }
+          return 0;
+
+        case MHD_WEBSOCKET_STATUS_PONG_FRAME:
+          /* if we receive a pong frame, */
+          /* we will check whether we requested this frame and */
+          /* whether it is the last requested pong */
+          if (2 == cu->ping_status)
+          {
+            cu->ping_status = 0;
+            struct timespec now;
+            timespec_get (&now, TIME_UTC);
+            if ((cu->ping_message_len == frame_len) &&
+                (0 == strcmp (frame_data,
+                              cu->ping_message)))
+            {
+              int ping = (int) (((int64_t) (now.tv_sec
+                                            - cu->ping_start.tv_sec))  * 1000
+                                + ((int64_t) (now.tv_nsec
+                                              - cu->ping_start.tv_nsec))
+                                / 1000000);
+              char result_text[240];
+              strcpy (result_text,
+                      "ping|");
+              snprintf (result_text + 5, 235, "%d", (int) cu->user_id);
+              strcat (result_text,
+                      "|");
+              snprintf (result_text + strlen (result_text), 240
+                        - strlen (result_text), "%d", (int) ping);
+              chat_addmessage (0,
+                               0,
+                               result_text,
+                               strlen (result_text),
+                               0,
+                               1);
+            }
+          }
+          MHD_websocket_free (cu->ws,
+                              frame_data);
+          return 0;
+
+        default:
+          /* This case should really never happen, */
+          /* because there are only five types of (finished) websocket frames. */
+          /* If it is ever reached, it means that there is memory corruption. */
+          MHD_websocket_free (cu->ws,
+                              frame_data);
+          return 1;
+        }
+      }
+    }
+  }
+
+  return 0;
+}
+
+
+/**
+ * Sends messages from the message list over the TCP/IP socket
+ * after encoding it with the websocket stream.
+ * This is also used for server-side actions,
+ * because the thread for receiving messages waits for
+ * incoming data and cannot be woken up.
+ * But the sender thread can be woken up easily.
+ *
+ * @param cls          The connected user
+ * @return             Always NULL
+ */
+static void *
+connecteduser_send_messages (void *cls)
+{
+  struct ConnectedUser *cu = cls;
+
+  /* the main loop of sending messages requires to lock the mutex */
+  if (0 == pthread_mutex_lock (&chat_mutex))
+  {
+    for (;;)
+    {
+      /* loop while not all messages processed */
+      int all_messages_read = 0;
+      while (0 == all_messages_read)
+      {
+        if (1 == disconnect_all)
+        {
+          /* the application closes and want that we disconnect all users */
+          struct MHD_UpgradeResponseHandle *urh = cu->urh;
+          if (NULL != urh)
+          {
+            /* Close the TCP/IP socket. */
+            /* This will also wake-up the waiting receive-thread for this connected user. */
+            cu->urh = NULL;
+            MHD_upgrade_action (urh,
+                                MHD_UPGRADE_ACTION_CLOSE);
+          }
+          pthread_mutex_unlock (&chat_mutex);
+          return NULL;
+        }
+        else if (1 == cu->disconnect)
+        {
+          /* The sender thread shall close. */
+          /* This is only requested by the receive thread, so we can just leave. */
+          pthread_mutex_unlock (&chat_mutex);
+          return NULL;
+        }
+        else if (1 == cu->ping_status)
+        {
+          /* A pending ping is requested */
+          ++cu->ping_counter;
+          strcpy (cu->ping_message,
+                  "libmicrohttpdchatserverpingdata");
+          snprintf (cu->ping_message + 31, 97, "%d", (int) cu->ping_counter);
+          cu->ping_message_len = strlen (cu->ping_message);
+          char *frame_data = NULL;
+          size_t frame_len = 0;
+          int er = MHD_websocket_encode_ping (cu->ws,
+                                              cu->ping_message,
+                                              cu->ping_message_len,
+                                              &frame_data,
+                                              &frame_len);
+          if (MHD_WEBSOCKET_STATUS_OK == er)
+          {
+            cu->ping_status = 2;
+            timespec_get (&cu->ping_start, TIME_UTC);
+
+            /* send the data via the TCP/IP socket and */
+            /* unlock the mutex while sending */
+            pthread_mutex_unlock (&chat_mutex);
+            send_all (cu,
+                      frame_data,
+                      frame_len);
+            if (0 != pthread_mutex_lock (&chat_mutex))
+            {
+              return NULL;
+            }
+          }
+          MHD_websocket_free (cu->ws, frame_data);
+        }
+        else if (cu->next_message_index < message_count)
+        {
+          /* a chat message or command is pending */
+          char *frame_data = NULL;
+          size_t frame_len = 0;
+          int er = 0;
+          {
+            struct Message *msg = messages[cu->next_message_index];
+            if ((0 == msg->to_user_id) ||
+                (cu->user_id == msg->to_user_id) ||
+                (cu->user_id == msg->from_user_id) )
+            {
+              if (0 == msg->is_binary)
+              {
+                er = MHD_websocket_encode_text (cu->ws,
+                                                msg->data,
+                                                msg->data_len,
+                                                MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                                &frame_data,
+                                                &frame_len,
+                                                NULL);
+              }
+              else
+              {
+                er = MHD_websocket_encode_binary (cu->ws,
+                                                  msg->data,
+                                                  msg->data_len,
+                                                  MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                                  &frame_data,
+                                                  &frame_len);
+              }
+            }
+          }
+          ++cu->next_message_index;
+
+          /* send the data via the TCP/IP socket and */
+          /* unlock the mutex while sending */
+          pthread_mutex_unlock (&chat_mutex);
+          if (MHD_WEBSOCKET_STATUS_OK == er)
+          {
+            send_all (cu,
+                      frame_data,
+                      frame_len);
+          }
+          MHD_websocket_free (cu->ws,
+                              frame_data);
+          if (0 != pthread_mutex_lock (&chat_mutex))
+          {
+            return NULL;
+          }
+          /* check whether there are still pending messages */
+          all_messages_read = (cu->next_message_index < message_count) ? 0 : 1;
+        }
+        else
+        {
+          all_messages_read = 1;
+        }
+      }
+      /* clear old messages */
+      chat_clearmessages (0);
+
+      /* Wait for wake up. */
+      /* This will automatically unlock the mutex while waiting and */
+      /* lock the mutex after waiting */
+      pthread_cond_wait (&cu->wake_up_sender, &chat_mutex);
+    }
+  }
+
+  return NULL;
+}
+
+
+/**
+ * Receives messages from the TCP/IP socket and
+ * initializes the connected user.
+ *
+ * @param cls The connected user
+ * @return    Always NULL
+ */
+static void *
+connecteduser_receive_messages (void *cls)
+{
+  struct ConnectedUser *cu = cls;
+  char buf[128];
+  ssize_t got;
+  int result;
+
+  /* make the socket blocking */
+  make_blocking (cu->fd);
+
+  /* generate the user name */
+  {
+    char user_name[32];
+    strcpy (user_name, "User");
+    snprintf (user_name + 4, 28, "%d", (int) cu->user_id);
+    cu->user_name_len = strlen (user_name);
+    cu->user_name = malloc (cu->user_name_len + 1);
+    if (NULL == cu->user_name)
+    {
+      free (cu->extra_in);
+      free (cu);
+      MHD_upgrade_action (cu->urh,
+                          MHD_UPGRADE_ACTION_CLOSE);
+      return NULL;
+    }
+    strcpy (cu->user_name, user_name);
+  }
+
+  /* initialize the wake-up-sender condition variable */
+  if (0 != pthread_cond_init (&cu->wake_up_sender, NULL))
+  {
+    MHD_upgrade_action (cu->urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+    free (cu->user_name);
+    free (cu->extra_in);
+    free (cu);
+    return NULL;
+  }
+
+  /* initialize the send mutex */
+  if (0 != pthread_mutex_init (&cu->send_mutex, NULL))
+  {
+    MHD_upgrade_action (cu->urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+    pthread_cond_destroy (&cu->wake_up_sender);
+    free (cu->user_name);
+    free (cu->extra_in);
+    free (cu);
+    return NULL;
+  }
+
+  /* add the user to the chat user list */
+  chat_adduser (cu);
+
+  /* initialize the web socket stream for encoding/decoding */
+  result = MHD_websocket_stream_init (&cu->ws,
+                                      MHD_WEBSOCKET_FLAG_SERVER
+                                      | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                      0);
+  if (MHD_WEBSOCKET_STATUS_OK != result)
+  {
+    chat_removeuser (cu);
+    pthread_cond_destroy (&cu->wake_up_sender);
+    pthread_mutex_destroy (&cu->send_mutex);
+    MHD_upgrade_action (cu->urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+    free (cu->user_name);
+    free (cu->extra_in);
+    free (cu);
+    return NULL;
+  }
+
+  /* send a list of all currently connected users (bypassing the messaging system) */
+  {
+    struct UserInit
+    {
+      char *user_init;
+      size_t user_init_len;
+    };
+    struct UserInit *init_users = NULL;
+    size_t init_users_len = 0;
+
+    /* first collect all users without sending (so the mutex isn't locked too long) */
+    if (0 == pthread_mutex_lock (&chat_mutex))
+    {
+      if (0 < user_count)
+      {
+        init_users = (struct UserInit *) malloc (user_count * sizeof (struct
+                                                                      UserInit));
+        if (NULL != init_users)
+        {
+          init_users_len = user_count;
+          for (size_t i = 0; i < user_count; ++i)
+          {
+            char user_index[32];
+            snprintf (user_index, 32, "%d", (int) users[i]->user_id);
+            size_t user_index_len = strlen (user_index);
+            struct UserInit iu;
+            iu.user_init_len = user_index_len + users[i]->user_name_len + 10;
+            iu.user_init = (char *) malloc (iu.user_init_len + 1);
+            if (NULL != iu.user_init)
+            {
+              strcpy (iu.user_init, "userinit|");
+              strcat (iu.user_init, user_index);
+              strcat (iu.user_init, "|");
+              if (0 < users[i]->user_name_len)
+                strcat (iu.user_init, users[i]->user_name);
+            }
+            init_users[i] = iu;
+          }
+        }
+      }
+      pthread_mutex_unlock (&chat_mutex);
+    }
+
+    /* then send all users to the connected client */
+    for (size_t i = 0; i < init_users_len; ++i)
+    {
+      char *frame_data = NULL;
+      size_t frame_len = 0;
+      if ((0 < init_users[i].user_init_len) && (NULL !=
+                                                init_users[i].user_init) )
+      {
+        int status = MHD_websocket_encode_text (cu->ws,
+                                                init_users[i].user_init,
+                                                init_users[i].user_init_len,
+                                                MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                                &frame_data,
+                                                &frame_len,
+                                                NULL);
+        if (MHD_WEBSOCKET_STATUS_OK == status)
+        {
+          send_all (cu,
+                    frame_data,
+                    frame_len);
+          MHD_websocket_free (cu->ws,
+                              frame_data);
+        }
+        free (init_users[i].user_init);
+      }
+    }
+    free (init_users);
+  }
+
+  /* send the welcome message to the user (bypassing the messaging system) */
+  {
+    char *frame_data = NULL;
+    size_t frame_len = 0;
+    const char *welcome_msg = "moderator||" \
+                              "Welcome to the libmicrohttpd WebSocket chatserver example.\n" \
+                              "Supported commands are:\n" \
+                              "  /m <user> <text> - sends a private message to the specified user\n" \
+                              "  /ping <user> - sends a ping to the specified user\n" \
+                              "  /name <name> - changes your name to the specified name\n" \
+                              "  /disconnect - disconnects your websocket\n\n" \
+                              "All messages, which does not start with a slash, " \
+                              "are regular messages and will be sent to the selected user.\n\n" \
+                              "Have fun!";
+    MHD_websocket_encode_text (cu->ws,
+                               welcome_msg,
+                               strlen (welcome_msg),
+                               MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                               &frame_data,
+                               &frame_len,
+                               NULL);
+    send_all (cu,
+              frame_data,
+              frame_len);
+    MHD_websocket_free (cu->ws,
+                        frame_data);
+  }
+
+  /* start the message-send thread */
+  pthread_t pt;
+  if (0 != pthread_create (&pt,
+                           NULL,
+                           &connecteduser_send_messages,
+                           cu))
+    abort ();
+
+  /* start by parsing extra data MHD may have already read, if any */
+  if (0 != cu->extra_in_size)
+  {
+    if (0 != connecteduser_parse_received_websocket_stream (cu,
+                                                            cu->extra_in,
+                                                            cu->extra_in_size))
+    {
+      chat_removeuser (cu);
+      if (0 == pthread_mutex_lock (&chat_mutex))
+      {
+        cu->disconnect = 1;
+        pthread_cond_signal (&cu->wake_up_sender);
+        pthread_mutex_unlock (&chat_mutex);
+        pthread_join (pt, NULL);
+      }
+      struct MHD_UpgradeResponseHandle *urh = cu->urh;
+      if (NULL != urh)
+      {
+        cu->urh = NULL;
+        MHD_upgrade_action (urh,
+                            MHD_UPGRADE_ACTION_CLOSE);
+      }
+      pthread_cond_destroy (&cu->wake_up_sender);
+      pthread_mutex_destroy (&cu->send_mutex);
+      MHD_websocket_stream_free (cu->ws);
+      free (cu->user_name);
+      free (cu->extra_in);
+      free (cu);
+      return NULL;
+    }
+    free (cu->extra_in);
+    cu->extra_in = NULL;
+  }
+
+  /* the main loop for receiving data */
+  while (1)
+  {
+    got = recv (cu->fd,
+                buf,
+                sizeof (buf),
+                0);
+    if (0 >= got)
+    {
+      /* the TCP/IP socket has been closed */
+      break;
+    }
+    if (0 < got)
+    {
+      if (0 != connecteduser_parse_received_websocket_stream (cu, buf,
+                                                              (size_t) got))
+      {
+        /* A websocket protocol error occurred */
+        chat_removeuser (cu);
+        if (0 == pthread_mutex_lock (&chat_mutex))
+        {
+          cu->disconnect = 1;
+          pthread_cond_signal (&cu->wake_up_sender);
+          pthread_mutex_unlock (&chat_mutex);
+          pthread_join (pt, NULL);
+        }
+        struct MHD_UpgradeResponseHandle *urh = cu->urh;
+        if (NULL != urh)
+        {
+          cu->urh = NULL;
+          MHD_upgrade_action (urh,
+                              MHD_UPGRADE_ACTION_CLOSE);
+        }
+        pthread_cond_destroy (&cu->wake_up_sender);
+        pthread_mutex_destroy (&cu->send_mutex);
+        MHD_websocket_stream_free (cu->ws);
+        free (cu->user_name);
+        free (cu);
+        return NULL;
+      }
+    }
+  }
+
+  /* cleanup */
+  chat_removeuser (cu);
+  if (0 == pthread_mutex_lock (&chat_mutex))
+  {
+    cu->disconnect = 1;
+    pthread_cond_signal (&cu->wake_up_sender);
+    pthread_mutex_unlock (&chat_mutex);
+    pthread_join (pt, NULL);
+  }
+  struct MHD_UpgradeResponseHandle *urh = cu->urh;
+  if (NULL != urh)
+  {
+    cu->urh = NULL;
+    MHD_upgrade_action (urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+  }
+  pthread_cond_destroy (&cu->wake_up_sender);
+  pthread_mutex_destroy (&cu->send_mutex);
+  MHD_websocket_stream_free (cu->ws);
+  free (cu->user_name);
+  free (cu);
+
+  return NULL;
+}
+
+
+/**
+ * Function called after a protocol "upgrade" response was sent
+ * successfully and the socket should now be controlled by some
+ * protocol other than HTTP.
+ *
+ * Any data already received on the socket will be made available in
+ * @e extra_in.  This can happen if the application sent extra data
+ * before MHD send the upgrade response.  The application should
+ * treat data from @a extra_in as if it had read it from the socket.
+ *
+ * Note that the application must not close() @a sock directly,
+ * but instead use #MHD_upgrade_action() for special operations
+ * on @a sock.
+ *
+ * Data forwarding to "upgraded" @a sock will be started as soon
+ * as this function return.
+ *
+ * Except when in 'thread-per-connection' mode, implementations
+ * of this function should never block (as it will still be called
+ * from within the main event loop).
+ *
+ * @param cls closure, whatever was given to #MHD_create_response_for_upgrade().
+ * @param connection original HTTP connection handle,
+ *                   giving the function a last chance
+ *                   to inspect the original HTTP request
+ * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback`
+ * @param extra_in if we happened to have read bytes after the
+ *                 HTTP header already (because the client sent
+ *                 more than the HTTP header of the request before
+ *                 we sent the upgrade response),
+ *                 these are the extra bytes already read from @a sock
+ *                 by MHD.  The application should treat these as if
+ *                 it had read them from @a sock.
+ * @param extra_in_size number of bytes in @a extra_in
+ * @param sock socket to use for bi-directional communication
+ *        with the client.  For HTTPS, this may not be a socket
+ *        that is directly connected to the client and thus certain
+ *        operations (TCP-specific setsockopt(), getsockopt(), etc.)
+ *        may not work as expected (as the socket could be from a
+ *        socketpair() or a TCP-loopback).  The application is expected
+ *        to perform read()/recv() and write()/send() calls on the socket.
+ *        The application may also call shutdown(), but must not call
+ *        close() directly.
+ * @param urh argument for #MHD_upgrade_action()s on this @a connection.
+ *        Applications must eventually use this callback to (indirectly)
+ *        perform the close() action on the @a sock.
+ */
+static void
+upgrade_handler (void *cls,
+                 struct MHD_Connection *connection,
+                 void *req_cls,
+                 const char *extra_in,
+                 size_t extra_in_size,
+                 MHD_socket fd,
+                 struct MHD_UpgradeResponseHandle *urh)
+{
+  struct ConnectedUser *cu;
+  pthread_t pt;
+  (void) cls;         /* Unused. Silent compiler warning. */
+  (void) connection;  /* Unused. Silent compiler warning. */
+  (void) req_cls;     /* Unused. Silent compiler warning. */
+
+  /* This callback must return as soon as possible. */
+
+  /* allocate new connected user */
+  cu = malloc (sizeof (struct ConnectedUser));
+  if (NULL == cu)
+    abort ();
+  memset (cu, 0, sizeof (struct ConnectedUser));
+  if (0 != extra_in_size)
+  {
+    cu->extra_in = malloc (extra_in_size);
+    if (NULL == cu->extra_in)
+      abort ();
+    memcpy (cu->extra_in,
+            extra_in,
+            extra_in_size);
+  }
+  cu->extra_in_size = extra_in_size;
+  cu->fd = fd;
+  cu->urh = urh;
+  cu->user_id = ++unique_user_id;
+  cu->user_name = NULL;
+  cu->user_name_len = 0;
+
+  /* create thread for the new connected user */
+  if (0 != pthread_create (&pt,
+                           NULL,
+                           &connecteduser_receive_messages,
+                           cu))
+    abort ();
+  pthread_detach (pt);
+}
+
+
+/**
+ * Function called by the MHD_daemon when the client tries to access a page.
+ *
+ * This is used to provide the main page
+ * (in this example HTML + CSS + JavaScript is all in the same file)
+ * and to initialize a websocket connection.
+ * The rules for the initialization of a websocket connection
+ * are listed near the URL check of "/ChatServerWebSocket".
+ *
+ * @param cls closure, whatever was given to #MHD_start_daemon().
+ * @param connection The HTTP connection handle
+ * @param url The requested URL
+ * @param method The request method (typically "GET")
+ * @param version The HTTP version
+ * @param upload_data Given upload data for POST requests
+ * @param upload_data_size The size of the upload data
+ * @param req_cls A pointer for request specific data
+ * @return MHD_YES on success or MHD_NO on error.
+ */
+static enum MHD_Result
+access_handler (void *cls,
+                struct MHD_Connection *connection,
+                const char *url,
+                const char *method,
+                const char *version,
+                const char *upload_data,
+                size_t *upload_data_size,
+                void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  int ret;
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) version;           /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  if (0 == strcmp (url, "/"))
+  {
+    /* Default page for visiting the server */
+    struct MHD_Response *response;
+    response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                       PAGE);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else if (0 == strcmp (url, "/ChatServerWebSocket"))
+  {
+    /**
+     * The path for the chat has been accessed.
+     * For a valid WebSocket request, at least five headers are required:
+     * 1. "Host: <name>"
+     * 2. "Connection: Upgrade"
+     * 3. "Upgrade: websocket"
+     * 4. "Sec-WebSocket-Version: 13"
+     * 5. "Sec-WebSocket-Key: <base64 encoded value>"
+     * Values are compared in a case-insensitive manner.
+     * Furthermore it must be a HTTP/1.1 or higher GET request.
+     * See: https://tools.ietf.org/html/rfc6455#section-4.2.1
+     *
+     * To make this example portable we skip the Host check
+     */
+
+    char is_valid = 1;
+    const char *value = NULL;
+    char sec_websocket_accept[29];
+
+    /* check whether an websocket upgrade is requested */
+    if (0 != MHD_websocket_check_http_version (version))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_CONNECTION);
+    if (0 != MHD_websocket_check_connection_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_UPGRADE);
+    if (0 != MHD_websocket_check_upgrade_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION);
+    if (0 != MHD_websocket_check_version_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY);
+    if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept))
+    {
+      is_valid = 0;
+    }
+
+    if (1 == is_valid)
+    {
+      /* create the response for upgrade */
+      response = MHD_create_response_for_upgrade (&upgrade_handler,
+                                                  NULL);
+
+      /**
+       * For the response we need at least the following headers:
+       * 1. "Connection: Upgrade"
+       * 2. "Upgrade: websocket"
+       * 3. "Sec-WebSocket-Accept: <base64value>"
+       * The value for Sec-WebSocket-Accept can be generated with MHD_websocket_create_accept_header.
+       * It requires the value of the Sec-WebSocket-Key header of the request.
+       * See also: https://tools.ietf.org/html/rfc6455#section-4.2.2
+       */
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_UPGRADE,
+                               "websocket");
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT,
+                               sec_websocket_accept);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_SWITCHING_PROTOCOLS,
+                                response);
+      MHD_destroy_response (response);
+    }
+    else
+    {
+      /* return error page */
+      struct MHD_Response *response;
+      response =
+        MHD_create_response_from_buffer_static ( \
+          strlen (PAGE_INVALID_WEBSOCKET_REQUEST),
+          PAGE_INVALID_WEBSOCKET_REQUEST);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_BAD_REQUEST,
+                                response);
+      MHD_destroy_response (response);
+    }
+  }
+  else
+  {
+    struct MHD_Response *response;
+    response = MHD_create_response_from_buffer_static (strlen (PAGE_NOT_FOUND),
+                                                       PAGE_NOT_FOUND);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_NOT_FOUND,
+                              response);
+    MHD_destroy_response (response);
+  }
+  return ret;
+}
+
+
+/**
+ * The main routine for this example
+ *
+ * This starts the daemon and waits for a key hit.
+ * After this it will shutdown the daemon.
+ */
+int
+main (int argc,
+      char *const *argv)
+{
+  (void) argc;               /* Unused. Silent compiler warning. */
+  (void) argv;               /* Unused. Silent compiler warning. */
+  struct MHD_Daemon *d;
+
+  if (0 != pthread_mutex_init (&chat_mutex, NULL))
+    return 1;
+
+#if USE_HTTPS == 1
+  const char private_key[] = "TODO: Enter your key in PEM format here";
+  const char certificate[] = "TODO: Enter your certificate in PEM format here";
+  d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | MHD_USE_TLS,
+                        443,
+                        NULL, NULL,
+                        &access_handler, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_HTTPS_MEM_KEY, private_key,
+                        MHD_OPTION_HTTPS_MEM_CERT, certificate,
+                        MHD_OPTION_END);
+#else
+  d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        80,
+                        NULL, NULL,
+                        &access_handler, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
+                        MHD_OPTION_END);
+#endif
+
+  if (NULL == d)
+    return 1;
+  (void) getc (stdin);
+
+  if (0 == pthread_mutex_lock (&chat_mutex))
+  {
+    disconnect_all = 1;
+    for (size_t i = 0; i < user_count; ++i)
+      pthread_cond_signal (&users[i]->wake_up_sender);
+    pthread_mutex_unlock (&chat_mutex);
+  }
+  sleep (2);
+  if (0 == pthread_mutex_lock (&chat_mutex))
+  {
+    for (size_t i = 0; i < user_count; ++i)
+    {
+      struct MHD_UpgradeResponseHandle *urh = users[i]->urh;
+      if (NULL != urh)
+      {
+        users[i]->urh = NULL;
+        MHD_upgrade_action (users[i]->urh,
+                            MHD_UPGRADE_ACTION_CLOSE);
+      }
+    }
+    pthread_mutex_unlock (&chat_mutex);
+  }
+  sleep (2);
+
+  /* usually we should wait here in a safe way for all threads to disconnect, */
+  /* but we skip this in the example */
+
+  pthread_mutex_destroy (&chat_mutex);
+
+  MHD_stop_daemon (d);
+
+  return 0;
+}
diff --git a/src/examples/websocket_threaded_example.c b/src/examples/websocket_threaded_example.c
new file mode 100644
index 0000000..af036d2
--- /dev/null
+++ b/src/examples/websocket_threaded_example.c
@@ -0,0 +1,921 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2020 Christian Grothoff, Silvio Clecio (and other
+     contributing authors)
+     Copyright (C) 2020-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file websocket_threaded_example.c
+ * @brief example for how to provide a tiny threaded websocket server
+ * @author Silvio Clecio (silvioprog)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+/* TODO: allow to send large messages. */
+
+#include "platform.h"
+#include <pthread.h>
+#include <microhttpd.h>
+
+#define CHAT_PAGE                                                             \
+  "<html>\n"                                                                  \
+  "<head>\n"                                                                  \
+  "<title>WebSocket chat</title>\n"                                           \
+  "<script>\n"                                                                \
+  "document.addEventListener('DOMContentLoaded', function() {\n"              \
+  "  const ws = new WebSocket('ws:/" "/ ' + window.location.host);\n"         \
+  "  const btn = document.getElementById('send');\n"                          \
+  "  const msg = document.getElementById('msg');\n"                           \
+  "  const log = document.getElementById('log');\n"                           \
+  "  ws.onopen = function() {\n"                                              \
+  "    log.value += 'Connected\\n';\n"                                        \
+  "  };\n"                                                                    \
+  "  ws.onclose = function() {\n"                                             \
+  "    log.value += 'Disconnected\\n';\n"                                     \
+  "  };\n"                                                                    \
+  "  ws.onmessage = function(ev) {\n"                                         \
+  "    log.value += ev.data + '\\n';\n"                                       \
+  "  };\n"                                                                    \
+  "  btn.onclick = function() {\n"                                            \
+  "    log.value += '<You>: ' + msg.value + '\\n';\n"                         \
+  "    ws.send(msg.value);\n"                                                 \
+  "  };\n"                                                                    \
+  "  msg.onkeyup = function(ev) {\n"                                          \
+  "    if (ev.keyCode === 13) {\n"                                            \
+  "      ev.preventDefault();\n"                                              \
+  "      ev.stopPropagation();\n"                                             \
+  "      btn.click();\n"                                                      \
+  "      msg.value = '';\n"                                                   \
+  "    }\n"                                                                   \
+  "  };\n"                                                                    \
+  "});\n"                                                                     \
+  "</script>\n"                                                               \
+  "</head>\n"                                                                 \
+  "<body>\n"                                                                  \
+  "<input type='text' id='msg' autofocus/>\n"                                 \
+  "<input type='button' id='send' value='Send' /><br /><br />\n"              \
+  "<textarea id='log' rows='20' cols='28'></textarea>\n"                      \
+  "</body>\n"                                                                 \
+  "</html>"
+#define BAD_REQUEST_PAGE                                                      \
+  "<html>\n"                                                                  \
+  "<head>\n"                                                                  \
+  "<title>WebSocket chat</title>\n"                                           \
+  "</head>\n"                                                                 \
+  "<body>\n"                                                                  \
+  "Bad Request\n"                                                             \
+  "</body>\n"                                                                 \
+  "</html>\n"
+#define UPGRADE_REQUIRED_PAGE                                                 \
+  "<html>\n"                                                                  \
+  "<head>\n"                                                                  \
+  "<title>WebSocket chat</title>\n"                                           \
+  "</head>\n"                                                                 \
+  "<body>\n"                                                                  \
+  "Upgrade required\n"                                                        \
+  "</body>\n"                                                                 \
+  "</html>\n"
+
+#define WS_SEC_WEBSOCKET_VERSION "13"
+#define WS_UPGRADE_VALUE "websocket"
+#define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+#define WS_GUID_LEN 36
+#define WS_KEY_LEN 24
+#define WS_KEY_GUID_LEN ((WS_KEY_LEN) + (WS_GUID_LEN))
+#define WS_FIN 128
+#define WS_OPCODE_TEXT_FRAME 1
+#define WS_OPCODE_CON_CLOSE_FRAME 8
+
+#define MAX_CLIENTS 10
+
+static MHD_socket CLIENT_SOCKS[MAX_CLIENTS];
+
+static pthread_mutex_t MUTEX = PTHREAD_MUTEX_INITIALIZER;
+
+struct WsData
+{
+  struct MHD_UpgradeResponseHandle *urh;
+  MHD_socket sock;
+};
+
+
+/********** begin SHA-1 **********/
+
+
+#define SHA1HashSize 20
+
+#define SHA1CircularShift(bits, word)                                         \
+  (((word) << (bits)) | ((word) >> (32 - (bits))))
+
+enum SHA1_RESULT
+{
+  SHA1_RESULT_SUCCESS = 0,
+  SHA1_RESULT_NULL = 1,
+  SHA1_RESULT_STATE_ERROR = 2
+};
+
+struct SHA1Context
+{
+  uint32_t intermediate_hash[SHA1HashSize / 4];
+  uint32_t length_low;
+  uint32_t length_high;
+  int_least16_t message_block_index;
+  unsigned char message_block[64];
+  int computed;
+  int corrupted;
+};
+
+static void
+SHA1ProcessMessageBlock (struct SHA1Context *context)
+{
+  const uint32_t K[] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 };
+  int i;
+  uint32_t temp;
+  uint32_t W[80];
+  uint32_t A, B, C, D, E;
+
+  for (i = 0; i < 16; i++)
+  {
+    W[i] = ((uint32_t) context->message_block[i * 4]) << 24;
+    W[i] |= ((uint32_t) context->message_block[i * 4 + 1]) << 16;
+    W[i] |= ((uint32_t) context->message_block[i * 4 + 2]) << 8;
+    W[i] |= context->message_block[i * 4 + 3];
+  }
+  for (i = 16; i < 80; i++)
+  {
+    W[i]
+      = SHA1CircularShift (1, W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]);
+  }
+  A = context->intermediate_hash[0];
+  B = context->intermediate_hash[1];
+  C = context->intermediate_hash[2];
+  D = context->intermediate_hash[3];
+  E = context->intermediate_hash[4];
+  for (i = 0; i < 20; i++)
+  {
+    temp = SHA1CircularShift (5, A) + ((B & C) | ((~B) & D)) + E + W[i]
+           + K[0];
+    E = D;
+    D = C;
+    C = SHA1CircularShift (30, B);
+    B = A;
+    A = temp;
+  }
+  for (i = 20; i < 40; i++)
+  {
+    temp = SHA1CircularShift (5, A) + (B ^ C ^ D) + E + W[i] + K[1];
+    E = D;
+    D = C;
+    C = SHA1CircularShift (30, B);
+    B = A;
+    A = temp;
+  }
+  for (i = 40; i < 60; i++)
+  {
+    temp = SHA1CircularShift (5, A) + ((B & C) | (B & D) | (C & D)) + E
+           + W[i] + K[2];
+    E = D;
+    D = C;
+    C = SHA1CircularShift (30, B);
+    B = A;
+    A = temp;
+  }
+  for (i = 60; i < 80; i++)
+  {
+    temp = SHA1CircularShift (5, A) + (B ^ C ^ D) + E + W[i] + K[3];
+    E = D;
+    D = C;
+    C = SHA1CircularShift (30, B);
+    B = A;
+    A = temp;
+  }
+  context->intermediate_hash[0] += A;
+  context->intermediate_hash[1] += B;
+  context->intermediate_hash[2] += C;
+  context->intermediate_hash[3] += D;
+  context->intermediate_hash[4] += E;
+  context->message_block_index = 0;
+}
+
+
+static void
+SHA1PadMessage (struct SHA1Context *context)
+{
+  if (context->message_block_index > 55)
+  {
+    context->message_block[context->message_block_index++] = 0x80;
+    while (context->message_block_index < 64)
+    {
+      context->message_block[context->message_block_index++] = 0;
+    }
+    SHA1ProcessMessageBlock (context);
+    while (context->message_block_index < 56)
+    {
+      context->message_block[context->message_block_index++] = 0;
+    }
+  }
+  else
+  {
+    context->message_block[context->message_block_index++] = 0x80;
+    while (context->message_block_index < 56)
+    {
+      context->message_block[context->message_block_index++] = 0;
+    }
+  }
+  context->message_block[56] = (unsigned char) (context->length_high >> 24);
+  context->message_block[57] = (unsigned char) (context->length_high >> 16);
+  context->message_block[58] = (unsigned char) (context->length_high >> 8);
+  context->message_block[59] = (unsigned char) (context->length_high);
+  context->message_block[60] = (unsigned char) (context->length_low >> 24);
+  context->message_block[61] = (unsigned char) (context->length_low >> 16);
+  context->message_block[62] = (unsigned char) (context->length_low >> 8);
+  context->message_block[63] = (unsigned char) (context->length_low);
+  SHA1ProcessMessageBlock (context);
+}
+
+
+static enum SHA1_RESULT
+SHA1Reset (struct SHA1Context *context)
+{
+  if (! context)
+  {
+    return SHA1_RESULT_NULL;
+  }
+  context->length_low = 0;
+  context->length_high = 0;
+  context->message_block_index = 0;
+  context->intermediate_hash[0] = 0x67452301;
+  context->intermediate_hash[1] = 0xEFCDAB89;
+  context->intermediate_hash[2] = 0x98BADCFE;
+  context->intermediate_hash[3] = 0x10325476;
+  context->intermediate_hash[4] = 0xC3D2E1F0;
+  context->computed = 0;
+  context->corrupted = 0;
+  return SHA1_RESULT_SUCCESS;
+}
+
+
+static enum SHA1_RESULT
+SHA1Result (struct SHA1Context *context, unsigned char
+            Message_Digest[SHA1HashSize])
+{
+  int i;
+
+  if (! context || ! Message_Digest)
+  {
+    return SHA1_RESULT_NULL;
+  }
+  if (context->corrupted)
+  {
+    return SHA1_RESULT_STATE_ERROR;
+  }
+  if (! context->computed)
+  {
+    SHA1PadMessage (context);
+    for (i = 0; i < 64; ++i)
+    {
+      context->message_block[i] = 0;
+    }
+    context->length_low = 0;
+    context->length_high = 0;
+    context->computed = 1;
+  }
+  for (i = 0; i < SHA1HashSize; ++i)
+  {
+    Message_Digest[i]
+      = (unsigned char) (context->intermediate_hash[i >> 2]
+                         >> 8 * (3 - (i & 0x03)));
+  }
+  return SHA1_RESULT_SUCCESS;
+}
+
+
+static enum SHA1_RESULT
+SHA1Input (struct SHA1Context *context, const unsigned char *message_array,
+           unsigned length)
+{
+  if (! length)
+  {
+    return SHA1_RESULT_SUCCESS;
+  }
+  if (! context || ! message_array)
+  {
+    return SHA1_RESULT_NULL;
+  }
+  if (context->computed)
+  {
+    context->corrupted = 1;
+    return SHA1_RESULT_STATE_ERROR;
+  }
+  if (context->corrupted)
+  {
+    return SHA1_RESULT_STATE_ERROR;
+  }
+  while (length-- && ! context->corrupted)
+  {
+    context->message_block[context->message_block_index++]
+      = (*message_array & 0xFF);
+    context->length_low += 8;
+    if (context->length_low == 0)
+    {
+      context->length_high++;
+      if (context->length_high == 0)
+      {
+        context->corrupted = 1;
+      }
+    }
+    if (context->message_block_index == 64)
+    {
+      SHA1ProcessMessageBlock (context);
+    }
+    message_array++;
+  }
+  return SHA1_RESULT_SUCCESS;
+}
+
+
+/********** end SHA-1 **********/
+
+
+/********** begin Base64 **********/
+
+
+static ssize_t
+BASE64Encode (const void *in, size_t len, char **output)
+{
+#define FILLCHAR '='
+  const char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                    "abcdefghijklmnopqrstuvwxyz"
+                    "0123456789+/";
+  const char *data = in;
+  char *opt;
+  ssize_t ret;
+  size_t i;
+  char c;
+  ret = 0;
+
+  opt = malloc (2 + (len * 4 / 3) + 8);
+  if (NULL == opt)
+  {
+    return -1;
+  }
+  for (i = 0; i < len; ++i)
+  {
+    c = (data[i] >> 2) & 0x3F;
+    opt[ret++] = cvt[(int) c];
+    c = (data[i] << 4) & 0x3F;
+    if (++i < len)
+    {
+      c |= (data[i] >> 4) & 0x0F;
+    }
+    opt[ret++] = cvt[(int) c];
+    if (i < len)
+    {
+      c = (data[i] << 2) & 0x3F;
+      if (++i < len)
+      {
+        c |= (data[i] >> 6) & 0x03;
+      }
+      opt[ret++] = cvt[(int) c];
+    }
+    else
+    {
+      ++i;
+      opt[ret++] = FILLCHAR;
+    }
+    if (i < len)
+    {
+      c = data[i] & 0x3F;
+      opt[ret++] = cvt[(int) c];
+    }
+    else
+    {
+      opt[ret++] = FILLCHAR;
+    }
+  }
+  *output = opt;
+  return ret;
+}
+
+
+/********** end Base64 **********/
+
+
+static enum MHD_Result
+is_websocket_request (struct MHD_Connection *con, const char *upg_header,
+                      const char *con_header)
+{
+
+  (void) con;  /* Unused. Silent compiler warning. */
+
+  return ((upg_header != NULL) && (con_header != NULL)
+          && (0 == strcmp (upg_header, WS_UPGRADE_VALUE))
+          && (NULL != strstr (con_header, "Upgrade")))
+         ? MHD_YES
+         : MHD_NO;
+}
+
+
+static enum MHD_Result
+send_chat_page (struct MHD_Connection *con)
+{
+  struct MHD_Response *res;
+  enum MHD_Result ret;
+
+  res = MHD_create_response_from_buffer_static (strlen (CHAT_PAGE),
+                                                (const void *) CHAT_PAGE);
+  ret = MHD_queue_response (con, MHD_HTTP_OK, res);
+  MHD_destroy_response (res);
+  return ret;
+}
+
+
+static enum MHD_Result
+send_bad_request (struct MHD_Connection *con)
+{
+  struct MHD_Response *res;
+  enum MHD_Result ret;
+
+  res =
+    MHD_create_response_from_buffer_static (strlen (BAD_REQUEST_PAGE),
+                                            (const void *) BAD_REQUEST_PAGE);
+  ret = MHD_queue_response (con, MHD_HTTP_BAD_REQUEST, res);
+  MHD_destroy_response (res);
+  return ret;
+}
+
+
+static enum MHD_Result
+send_upgrade_required (struct MHD_Connection *con)
+{
+  struct MHD_Response *res;
+  enum MHD_Result ret;
+
+  res =
+    MHD_create_response_from_buffer_static (strlen (UPGRADE_REQUIRED_PAGE),
+                                            (const void *)
+                                            UPGRADE_REQUIRED_PAGE);
+  MHD_add_response_header (res, MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION,
+                           WS_SEC_WEBSOCKET_VERSION);
+  ret = MHD_queue_response (con, MHD_HTTP_UPGRADE_REQUIRED, res);
+  MHD_destroy_response (res);
+  return ret;
+}
+
+
+static enum MHD_Result
+ws_get_accept_value (const char *key, char **val)
+{
+  struct SHA1Context ctx;
+  unsigned char hash[SHA1HashSize];
+  char *str;
+  ssize_t len;
+
+  if ( (NULL == key) || (WS_KEY_LEN != strlen (key)))
+  {
+    return MHD_NO;
+  }
+  str = malloc (WS_KEY_LEN + WS_GUID_LEN + 1);
+  if (NULL == str)
+  {
+    return MHD_NO;
+  }
+  strncpy (str, key, (WS_KEY_LEN + 1));
+  strncpy (str + WS_KEY_LEN, WS_GUID, WS_GUID_LEN + 1);
+  SHA1Reset (&ctx);
+  SHA1Input (&ctx, (const unsigned char *) str, WS_KEY_GUID_LEN);
+  if (SHA1_RESULT_SUCCESS != SHA1Result (&ctx, hash))
+  {
+    free (str);
+    return MHD_NO;
+  }
+  free (str);
+  len = BASE64Encode (hash, SHA1HashSize, val);
+  if (-1 == len)
+  {
+    return MHD_NO;
+  }
+  (*val)[len] = '\0';
+  return MHD_YES;
+}
+
+
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    abort ();
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      abort ();
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    abort ();
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+static size_t
+send_all (MHD_socket sock, const unsigned char *buf, size_t len)
+{
+  ssize_t ret;
+  size_t off;
+
+  for (off = 0; off < len; off += (size_t) ret)
+  {
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    ret = send (sock, (const void *) &buf[off], len - off, 0);
+#else  /* Native W32 */
+    ret = send (sock, (const void *) &buf[off], (int) (len - off), 0);
+#endif /* Native W32 */
+    if (0 > ret)
+    {
+      if (EAGAIN == errno)
+      {
+        ret = 0;
+        continue;
+      }
+      break;
+    }
+    if (0 == ret)
+    {
+      break;
+    }
+  }
+  return off;
+}
+
+
+static ssize_t
+ws_send_frame (MHD_socket sock, const char *msg, size_t length)
+{
+  unsigned char *response;
+  unsigned char frame[10];
+  unsigned char idx_first_rdata;
+  size_t idx_response;
+  size_t output;
+  MHD_socket isock;
+  size_t i;
+
+  frame[0] = (WS_FIN | WS_OPCODE_TEXT_FRAME);
+  if (length <= 125)
+  {
+    frame[1] = length & 0x7F;
+    idx_first_rdata = 2;
+  }
+#if SIZEOF_SIZE_T > 4
+  else if (0xFFFF < length)
+  {
+    frame[1] = 127;
+    frame[2] = (unsigned char) ((length >> 56) & 0xFF);
+    frame[3] = (unsigned char) ((length >> 48) & 0xFF);
+    frame[4] = (unsigned char) ((length >> 40) & 0xFF);
+    frame[5] = (unsigned char) ((length >> 32) & 0xFF);
+    frame[6] = (unsigned char) ((length >> 24) & 0xFF);
+    frame[7] = (unsigned char) ((length >> 16) & 0xFF);
+    frame[8] = (unsigned char) ((length >> 8) & 0xFF);
+    frame[9] = (unsigned char) (length & 0xFF);
+    idx_first_rdata = 10;
+  }
+#endif /* SIZEOF_SIZE_T > 4 */
+  else
+  {
+    frame[1] = 126;
+    frame[2] = (length >> 8) & 0xFF;
+    frame[3] = length & 0xFF;
+    idx_first_rdata = 4;
+  }
+  idx_response = 0;
+  response = malloc (idx_first_rdata + length + 1);
+  if (NULL == response)
+  {
+    return -1;
+  }
+  for (i = 0; i < idx_first_rdata; i++)
+  {
+    response[i] = frame[i];
+    idx_response++;
+  }
+  for (i = 0; i < length; i++)
+  {
+    response[idx_response] = (unsigned char) msg[i];
+    idx_response++;
+  }
+  response[idx_response] = '\0';
+  output = 0;
+  pthread_mutex_lock (&MUTEX);
+  for (i = 0; i < MAX_CLIENTS; i++)
+  {
+    isock = CLIENT_SOCKS[i];
+    if ((isock != MHD_INVALID_SOCKET) && (isock != sock))
+    {
+      output += send_all (isock, response, idx_response);
+    }
+  }
+  pthread_mutex_unlock (&MUTEX);
+  free (response);
+  return (ssize_t) output;
+}
+
+
+static unsigned char *
+ws_receive_frame (unsigned char *frame, ssize_t *length, int *type)
+{
+  unsigned char masks[4];
+  unsigned char mask;
+  unsigned char *msg;
+  unsigned char flength;
+  unsigned char idx_first_mask;
+  unsigned char idx_first_data;
+  size_t data_length;
+  int i;
+  int j;
+
+  msg = NULL;
+  if (frame[0] == (WS_FIN | WS_OPCODE_TEXT_FRAME))
+  {
+    *type = WS_OPCODE_TEXT_FRAME;
+    idx_first_mask = 2;
+    mask = frame[1];
+    flength = mask & 0x7F;
+    if (flength == 126)
+    {
+      idx_first_mask = 4;
+    }
+    else if (flength == 127)
+    {
+      idx_first_mask = 10;
+    }
+    idx_first_data = idx_first_mask + 4;
+    data_length = (size_t) *length - idx_first_data;
+    masks[0] = frame[idx_first_mask + 0];
+    masks[1] = frame[idx_first_mask + 1];
+    masks[2] = frame[idx_first_mask + 2];
+    masks[3] = frame[idx_first_mask + 3];
+    msg = malloc (data_length + 1);
+    if (NULL != msg)
+    {
+      for (i = idx_first_data, j = 0; i < *length; i++, j++)
+      {
+        msg[j] = frame[i] ^ masks[j % 4];
+      }
+      *length = (ssize_t) data_length;
+      msg[j] = '\0';
+    }
+  }
+  else if (frame[0] == (WS_FIN | WS_OPCODE_CON_CLOSE_FRAME))
+  {
+    *type = WS_OPCODE_CON_CLOSE_FRAME;
+  }
+  else
+  {
+    *type = frame[0] & 0x0F;
+  }
+  return msg;
+}
+
+
+static void *
+run_usock (void *cls)
+{
+  struct WsData *ws = cls;
+  struct MHD_UpgradeResponseHandle *urh = ws->urh;
+  unsigned char buf[2048];
+  unsigned char *msg;
+  char *text;
+  ssize_t got;
+  int type;
+  int i;
+
+  make_blocking (ws->sock);
+  while (1)
+  {
+    got = recv (ws->sock, (void *) buf, sizeof (buf), 0);
+    if (0 >= got)
+    {
+      break;
+    }
+    msg = ws_receive_frame (buf, &got, &type);
+    if (NULL == msg)
+    {
+      break;
+    }
+    if (type == WS_OPCODE_TEXT_FRAME)
+    {
+      ssize_t sent;
+      int buf_size;
+      buf_size = snprintf (NULL, 0, "User#%d: %s", (int) ws->sock, msg);
+      if (0 < buf_size)
+      {
+        text = malloc ((size_t) buf_size + 1);
+        if (NULL != text)
+        {
+          if (snprintf (text, (size_t) buf_size + 1,
+                        "User#%d: %s", (int) ws->sock, msg) == buf_size)
+            sent = ws_send_frame (ws->sock, text, (size_t) buf_size);
+          else
+            sent = -1;
+          free (text);
+        }
+        else
+          sent = -1;
+      }
+      else
+        sent = -1;
+      free (msg);
+      if (-1 == sent)
+      {
+        break;
+      }
+    }
+    else
+    {
+      if (type == WS_OPCODE_CON_CLOSE_FRAME)
+      {
+        free (msg);
+        break;
+      }
+    }
+  }
+  pthread_mutex_lock (&MUTEX);
+  for (i = 0; i < MAX_CLIENTS; i++)
+  {
+    if (CLIENT_SOCKS[i] == ws->sock)
+    {
+      CLIENT_SOCKS[i] = MHD_INVALID_SOCKET;
+      break;
+    }
+  }
+  pthread_mutex_unlock (&MUTEX);
+  free (ws);
+  MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE);
+  return NULL;
+}
+
+
+static void
+uh_cb (void *cls, struct MHD_Connection *con, void *req_cls,
+       const char *extra_in, size_t extra_in_size, MHD_socket sock,
+       struct MHD_UpgradeResponseHandle *urh)
+{
+  struct WsData *ws;
+  pthread_t pt;
+  int sock_overflow;
+  int i;
+
+  (void) cls;            /* Unused. Silent compiler warning. */
+  (void) con;            /* Unused. Silent compiler warning. */
+  (void) req_cls;        /* Unused. Silent compiler warning. */
+  (void) extra_in;       /* Unused. Silent compiler warning. */
+  (void) extra_in_size;  /* Unused. Silent compiler warning. */
+
+  ws = malloc (sizeof (struct WsData));
+  if (NULL == ws)
+    abort ();
+  memset (ws, 0, sizeof (struct WsData));
+  ws->sock = sock;
+  ws->urh = urh;
+  sock_overflow = MHD_YES;
+  pthread_mutex_lock (&MUTEX);
+  for (i = 0; i < MAX_CLIENTS; i++)
+  {
+    if (MHD_INVALID_SOCKET == CLIENT_SOCKS[i])
+    {
+      CLIENT_SOCKS[i] = ws->sock;
+      sock_overflow = MHD_NO;
+      break;
+    }
+  }
+  pthread_mutex_unlock (&MUTEX);
+  if (sock_overflow)
+  {
+    free (ws);
+    MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE);
+    return;
+  }
+  if (0 != pthread_create (&pt, NULL, &run_usock, ws))
+    abort ();
+  /* Note that by detaching like this we make it impossible to ensure
+     a clean shutdown, as the we stop the daemon even if a worker thread
+     is still running. Alas, this is a simple example... */
+  pthread_detach (pt);
+}
+
+
+static enum MHD_Result
+ahc_cb (void *cls, struct MHD_Connection *con, const char *url,
+        const char *method, const char *version, const char *upload_data,
+        size_t *upload_data_size, void **req_cls)
+{
+  struct MHD_Response *res;
+  const char *upg_header;
+  const char *con_header;
+  const char *ws_version_header;
+  const char *ws_key_header;
+  char *ws_ac_value;
+  enum MHD_Result ret;
+  size_t key_size;
+
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) url;               /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (NULL == *req_cls)
+  {
+    *req_cls = (void *) 1;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  upg_header = MHD_lookup_connection_value (con, MHD_HEADER_KIND,
+                                            MHD_HTTP_HEADER_UPGRADE);
+  con_header = MHD_lookup_connection_value (con, MHD_HEADER_KIND,
+                                            MHD_HTTP_HEADER_CONNECTION);
+  if (MHD_NO == is_websocket_request (con, upg_header, con_header))
+  {
+    return send_chat_page (con);
+  }
+  if ((0 != strcmp (method, MHD_HTTP_METHOD_GET))
+      || (0 != strcmp (version, MHD_HTTP_VERSION_1_1)))
+  {
+    return send_bad_request (con);
+  }
+  ws_version_header =
+    MHD_lookup_connection_value (con, MHD_HEADER_KIND,
+                                 MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION);
+  if ((NULL == ws_version_header)
+      || (0 != strcmp (ws_version_header, WS_SEC_WEBSOCKET_VERSION)))
+  {
+    return send_upgrade_required (con);
+  }
+  ret = MHD_lookup_connection_value_n (con, MHD_HEADER_KIND,
+                                       MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY,
+                                       strlen (
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY),
+                                       &ws_key_header, &key_size);
+  if ((MHD_NO == ret) || (key_size != WS_KEY_LEN))
+  {
+    return send_bad_request (con);
+  }
+  ret = ws_get_accept_value (ws_key_header, &ws_ac_value);
+  if (MHD_NO == ret)
+  {
+    return ret;
+  }
+  res = MHD_create_response_for_upgrade (&uh_cb, NULL);
+  MHD_add_response_header (res, MHD_HTTP_HEADER_UPGRADE, WS_UPGRADE_VALUE);
+  MHD_add_response_header (res, MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT,
+                           ws_ac_value);
+  free (ws_ac_value);
+  ret = MHD_queue_response (con, MHD_HTTP_SWITCHING_PROTOCOLS, res);
+  MHD_destroy_response (res);
+  return ret;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  struct MHD_Daemon *d;
+  unsigned int port;
+  size_t i;
+  if ( (argc != 2) ||
+       (1 != sscanf (argv[1], "%u", &port)) ||
+       (65535 < port) )
+  {
+    printf ("%s PORT\n", argv[0]);
+    return 1;
+  }
+  d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO_INTERNAL_THREAD
+                        | MHD_USE_ERROR_LOG,
+                        (uint16_t) port, NULL, NULL,
+                        &ahc_cb, NULL, MHD_OPTION_END);
+  if (NULL == d)
+    return 1;
+  for (i = 0; i < sizeof(CLIENT_SOCKS) / sizeof(CLIENT_SOCKS[0]); ++i)
+    CLIENT_SOCKS[i] = MHD_INVALID_SOCKET;
+  (void) getc (stdin);
+  MHD_stop_daemon (d);
+  return 0;
+}
diff --git a/src/gnutls/check_record_pending.c b/src/gnutls/check_record_pending.c
new file mode 100644
index 0000000..2069ca0
--- /dev/null
+++ b/src/gnutls/check_record_pending.c
@@ -0,0 +1,6 @@
+enum MHD_Bool
+(*check_record_pending)(void *cls,
+                        struct MHD_TLS_ConnectionState *cs);
+
+see:
+gnutls_record_check_pending (connection->tls_session)
diff --git a/src/gnutls/handshake.c b/src/gnutls/handshake.c
new file mode 100644
index 0000000..1de4dc3
--- /dev/null
+++ b/src/gnutls/handshake.c
@@ -0,0 +1,14 @@
+enum MHD_Bool
+(*handshake)(void *cls,
+             struct MHD_TLS_ConnectionState *cs) :
+
+
+  if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
+{     /* HTTPS connection. */
+  if (MHD_TLS_CONN_CONNECTED > connection->tls_state)
+  {
+    if (! MHD_run_tls_handshake_ (connection))
+      return MHD_FALSE;
+  }
+}
+return MHD_TRUE;
diff --git a/src/gnutls/idle_ready.c b/src/gnutls/idle_ready.c
new file mode 100644
index 0000000..ddc471a
--- /dev/null
+++ b/src/gnutls/idle_ready.c
@@ -0,0 +1,12 @@
+enum MHD_Bool
+(*idle_ready)(void *cls,
+              struct MHD_TLS_ConnectionState *cs);
+
+
+if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
+{         /* HTTPS connection. */
+  if ((MHD_TLS_CONN_INIT <= connection->tls_state) &&
+      (MHD_TLS_CONN_CONNECTED > connection->tls_state))
+    return false;
+}
+return true;
diff --git a/src/gnutls/init.c b/src/gnutls/init.c
new file mode 100644
index 0000000..4c47d16
--- /dev/null
+++ b/src/gnutls/init.c
@@ -0,0 +1,163 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file gnutls/init.c
+ * @brief gnutls-specific initialization routines
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "init.h"
+
+
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#if defined(HTTPS_SUPPORT) && GCRYPT_VERSION_NUMBER < 0x010600
+#if defined(MHD_USE_POSIX_THREADS)
+GCRY_THREAD_OPTION_PTHREAD_IMPL;
+#elif defined(MHD_W32_MUTEX_)
+
+
+static int
+gcry_w32_mutex_init (void **ppmtx)
+{
+  *ppmtx = malloc (sizeof (MHD_mutex_));
+
+  if (NULL == *ppmtx)
+    return ENOMEM;
+  if (! MHD_mutex_init_ ((MHD_mutex_ *) *ppmtx))
+  {
+    free (*ppmtx);
+    *ppmtx = NULL;
+    return EPERM;
+  }
+  return 0;
+}
+
+
+static int
+gcry_w32_mutex_destroy (void **ppmtx)
+{
+  int res = (MHD_mutex_destroy_ ((MHD_mutex_ *) *ppmtx)) ? 0 : EINVAL;
+  free (*ppmtx);
+  return res;
+}
+
+
+static int
+gcry_w32_mutex_lock (void **ppmtx)
+{
+  return MHD_mutex_lock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL;
+}
+
+
+static int
+gcry_w32_mutex_unlock (void **ppmtx)
+{
+  return MHD_mutex_unlock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL;
+}
+
+
+static struct gcry_thread_cbs gcry_threads_w32 = {
+  (GCRY_THREAD_OPTION_USER | (GCRY_THREAD_OPTION_VERSION << 8)),
+  NULL, gcry_w32_mutex_init, gcry_w32_mutex_destroy,
+  gcry_w32_mutex_lock, gcry_w32_mutex_unlock,
+  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+};
+
+#endif /* defined(MHD_W32_MUTEX_) */
+#endif /* HTTPS_SUPPORT && GCRYPT_VERSION_NUMBER < 0x010600 */
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+
+
+#ifndef _AUTOINIT_FUNCS_ARE_SUPPORTED
+
+/**
+ * Track global initialisation
+ */
+volatile int global_init_count = 0;
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+/**
+ * Global initialisation mutex
+ */
+MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+
+#endif
+
+
+/**
+ * Check whether global initialisation was performed
+ * and call initialiser if necessary.
+ */
+void
+MHD_TLS_check_global_init_ (void)
+{
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+  MHD_mutex_lock_chk_ (&global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+  if (0 == global_init_count++)
+    MHD_init ();
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+  MHD_mutex_unlock_chk_ (&global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+}
+
+
+/**
+ * Initialize do setup work.
+ */
+void
+MHD_TLS_init (void)
+{
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+  WSADATA wsd;
+#endif /* _WIN32 && ! __CYGWIN__ */
+
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#if GCRYPT_VERSION_NUMBER < 0x010600
+#if defined(MHD_USE_POSIX_THREADS)
+  if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS,
+                         &gcry_threads_pthread))
+    MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n"));
+#elif defined(MHD_W32_MUTEX_)
+  if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS,
+                         &gcry_threads_w32))
+    MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n"));
+#endif /* defined(MHD_W32_MUTEX_) */
+  gcry_check_version (NULL);
+#else
+  if (NULL == gcry_check_version ("1.6.0"))
+    MHD_PANIC (_ (
+                 "libgcrypt is too old. MHD was compiled for libgcrypt 1.6.0 or newer.\n"));
+#endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  gnutls_global_init ();
+}
+
+
+void
+MHD_TLS_fini (void)
+{
+  gnutls_global_deinit ();
+}
+
+
+#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
+_SET_INIT_AND_DEINIT_FUNCS (MHD_TLS_init, MHD_TLS_fini);
+#endif /* _AUTOINIT_FUNCS_ARE_SUPPORTED */
diff --git a/src/gnutls/init.h b/src/gnutls/init.h
new file mode 100644
index 0000000..6de5298
--- /dev/null
+++ b/src/gnutls/init.h
@@ -0,0 +1,46 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file gnutls/init.h
+ * @brief functions to initialize library
+ * @author Christian Grothoff
+ */
+#ifndef INIT_H
+#define INIT_H
+
+#include "internal.h"
+
+#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
+/**
+ * Do nothing - global initialisation is
+ * performed by library constructor.
+ */
+#define MHD_TLS_check_global_init_() (void) 0
+#else  /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
+/**
+ * Check whether global initialisation was performed
+ * and call initialiser if necessary.
+ */
+void
+MHD_TLS_check_global_init_ (void);
+
+#endif /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
+
+
+#endif  /* INIT_H */
diff --git a/src/gnutls/recv.c b/src/gnutls/recv.c
new file mode 100644
index 0000000..9c58cb6
--- /dev/null
+++ b/src/gnutls/recv.c
@@ -0,0 +1,5 @@
+recv :
+
+res = gnutls_record_recv (connection->tls_session,
+                          &urh->in_buffer[urh->in_buffer_used],
+                          buf_size);
diff --git a/src/gnutls/send.c b/src/gnutls/send.c
new file mode 100644
index 0000000..3fad99f
--- /dev/null
+++ b/src/gnutls/send.c
@@ -0,0 +1,11 @@
+ssize_t
+(*send)(void *cls,
+        struct MHD_TLS_ConnectionState *cs,
+        const void *buf,
+        size_t buf_size);
+
+
+see:
+res = gnutls_record_send (connection->tls_session,
+                          urh->out_buffer,
+                          data_size);
diff --git a/src/gnutls/setup_connection.c b/src/gnutls/setup_connection.c
new file mode 100644
index 0000000..3a45e49
--- /dev/null
+++ b/src/gnutls/setup_connection.c
@@ -0,0 +1,58 @@
+setup_connection ()
+{
+  connection->tls_state = MHD_TLS_CONN_INIT;
+  MHD_set_https_callbacks (connection);
+  gnutls_init (&connection->tls_session,
+               GNUTLS_SERVER
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030402)
+               | GNUTLS_NO_SIGNAL
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030402 */
+#if GNUTLS_VERSION_MAJOR >= 3
+               | GNUTLS_NONBLOCK
+#endif /* GNUTLS_VERSION_MAJOR >= 3*/
+               );
+  gnutls_priority_set (connection->tls_session,
+                       daemon->priority_cache);
+  switch (daemon->cred_type)
+  {
+  /* set needed credentials for certificate authentication. */
+  case GNUTLS_CRD_CERTIFICATE:
+    gnutls_credentials_set (connection->tls_session,
+                            GNUTLS_CRD_CERTIFICATE,
+                            daemon->x509_cred);
+    break;
+  default:
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ (
+                "Failed to setup TLS credentials: unknown credential type %d.\n"),
+              daemon->cred_type);
+#endif
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+    free (connection);
+    MHD_PANIC (_ ("Unknown credential type.\n"));
+#if EINVAL
+    errno = EINVAL;
+#endif
+    return MHD_NO;
+  }
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64)
+  gnutls_transport_set_int (connection->tls_session, (int) (client_socket));
+#else  /* GnuTLS before 3.1.9 or Win x64 */
+  gnutls_transport_set_ptr (connection->tls_session,
+                            (gnutls_transport_ptr_t) (intptr_t) (client_socket));
+#endif /* GnuTLS before 3.1.9 */
+#ifdef MHD_TLSLIB_NEED_PUSH_FUNC
+  gnutls_transport_set_push_function (connection->tls_session,
+                                      MHD_tls_push_func_);
+#endif /* MHD_TLSLIB_NEED_PUSH_FUNC */
+  if (daemon->https_mem_trust)
+    gnutls_certificate_server_set_request (connection->tls_session,
+                                           GNUTLS_CERT_REQUEST);
+#else  /* ! HTTPS_SUPPORT */
+  return NULL;
+
+}
diff --git a/src/gnutls/shutdown_connection.c b/src/gnutls/shutdown_connection.c
new file mode 100644
index 0000000..48db358
--- /dev/null
+++ b/src/gnutls/shutdown_connection.c
@@ -0,0 +1,5 @@
+enum MHD_Bool
+(*shutdown_connection)(void *cls,
+                       struct MHD_TLS_ConnectionState *cs);
+
+see: MHD_tls_connection_shutdown ()
diff --git a/src/gnutls/strerror.c b/src/gnutls/strerror.c
new file mode 100644
index 0000000..a233365
--- /dev/null
+++ b/src/gnutls/strerror.c
@@ -0,0 +1,6 @@
+const char *
+(*strerror)(void *cls,
+            int ec);
+
+see:
+gnutls_strerror (ec));
diff --git a/src/gnutls/teardown_connection.c b/src/gnutls/teardown_connection.c
new file mode 100644
index 0000000..0156955
--- /dev/null
+++ b/src/gnutls/teardown_connection.c
@@ -0,0 +1,4 @@
+teardown_connection ()
+{
+  gnutls_deinit (connection->tls_session);
+}
diff --git a/src/gnutls/update_event_loop_info.c b/src/gnutls/update_event_loop_info.c
new file mode 100644
index 0000000..3b7bc62
--- /dev/null
+++ b/src/gnutls/update_event_loop_info.c
@@ -0,0 +1,20 @@
+enum MHD_Bool
+(*update_event_loop_info)(void *cls,
+                          struct MHD_TLS_ConnectionState *cs,
+                          enum MHD_RequestEventLoopInfo *eli);
+
+
+switch (connection->tls_state)
+{
+case MHD_TLS_CONN_INIT:
+  *eli = MHD_EVENT_LOOP_INFO_READ;
+  return true;
+case MHD_TLS_CONN_HANDSHAKING:
+  if (0 == gnutls_record_get_direction (connection->tls_session))
+    *eli = MHD_EVENT_LOOP_INFO_READ;
+  else
+    *eli = MHD_EVENT_LOOP_INFO_WRITE;
+  return true;
+default:
+  return false;
+}
diff --git a/src/include/Makefile.am b/src/include/Makefile.am
index 437008f..3d73c59 100644
--- a/src/include/Makefile.am
+++ b/src/include/Makefile.am
@@ -1,10 +1,11 @@
 # This Makefile.am is in the public domain
 SUBDIRS = .
 
-if ENABLE_SPDY
-microspdy = microspdy.h
+include_HEADERS = microhttpd.h
+noinst_HEADERS = microhttpd2.h microhttpd_tls.h
+
+if HAVE_EXPERIMENTAL
+include_HEADERS += microhttpd_ws.h
 endif
 
-include_HEADERS = microhttpd.h $(microspdy)
-
-EXTRA_DIST = platform.h platform_interface.h w32functions.h autoinit_funcs.h
+EXTRA_DIST = platform.h autoinit_funcs.h mhd_options.h
diff --git a/src/include/Makefile.in b/src/include/Makefile.in
deleted file mode 100644
index 151ac48..0000000
--- a/src/include/Makefile.in
+++ /dev/null
@@ -1,723 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-subdir = src/include
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(am__include_HEADERS_DIST)
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__include_HEADERS_DIST = microhttpd.h microspdy.h
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(includedir)"
-HEADERS = $(include_HEADERS)
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-@ENABLE_SPDY_TRUE@microspdy = microspdy.h
-include_HEADERS = microhttpd.h $(microspdy)
-EXTRA_DIST = platform.h platform_interface.h w32functions.h autoinit_funcs.h
-all: all-recursive
-
-.SUFFIXES:
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/include/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/include/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-install-includeHEADERS: $(include_HEADERS)
-	@$(NORMAL_INSTALL)
-	@list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \
-	fi; \
-	for p in $$list; do \
-	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
-	  echo "$$d$$p"; \
-	done | $(am__base_list) | \
-	while read files; do \
-	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
-	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
-	done
-
-uninstall-includeHEADERS:
-	@$(NORMAL_UNINSTALL)
-	@list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
-	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
-	dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir)
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(HEADERS)
-installdirs: installdirs-recursive
-installdirs-am:
-	for dir in "$(DESTDIR)$(includedir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am: install-includeHEADERS
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-includeHEADERS
-
-.MAKE: $(am__recursive_targets) install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-am clean clean-generic clean-libtool cscopelist-am ctags \
-	ctags-am distclean distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-includeHEADERS install-info \
-	install-info-am install-man install-pdf install-pdf-am \
-	install-ps install-ps-am install-strip installcheck \
-	installcheck-am installdirs installdirs-am maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
-	uninstall-am uninstall-includeHEADERS
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/include/autoinit_funcs.h b/src/include/autoinit_funcs.h
index 2f309e1..0c2e47b 100644
--- a/src/include/autoinit_funcs.h
+++ b/src/include/autoinit_funcs.h
@@ -1,6 +1,6 @@
 /*
  *  AutoinitFuncs: Automatic Initialization and Deinitialization Functions
- *  CopyrightCopyright (C) 2014  Karlson2k (Evgeny Grin)
+ *  Copyright(C) 2014-2023 Karlson2k (Evgeny Grin)
  *
  *  This header is free software; you can redistribute it and / or
  *  modify it under the terms of the GNU Lesser General Public
@@ -20,11 +20,11 @@
 /*
    General usage is simple: include this header, declare or define two
    functions with zero parameters (void) and any return type: one for
-   initialization and one for deinitialization, add 
+   initialisation and one for deinitialisation, add
    _SET_INIT_AND_DEINIT_FUNCS(FuncInitName, FuncDeInitName) to the code
    and functions will be automatically called during application startup
    and shutdown.
-   This is useful for libraries as libraries doesn't have direct access
+   This is useful for libraries as libraries don't have direct access
    to main() functions.
    Example:
    -------------------------------------------------
@@ -47,13 +47,15 @@
 
    _SET_INIT_AND_DEINIT_FUNCS(libInit,libDeinit);
    -------------------------------------------------
-   
-   If initializer or deinitializer functions is not needed, just define
+
+   If initialiser or deinitialiser function is not needed, just define
    it as empty function.
-   
-   This header should work with GCC, clang, MSVC (2010 or later).
+
+   This header should work with GCC, clang, MSVC (2010 or later) and
+   SunPro / Sun Studio / Oracle Solaris Studio / Oracle Developer Studio
+   compiler.
    Supported C and C++ languages; application, static and dynamic (DLL)
-   libraries; non-optimized (Debug) and optimized (Release) compilation
+   libraries; non-optimized (Debug) and optimised (Release) compilation
    and linking.
 
    For more information see header code and comments in code.
@@ -62,33 +64,39 @@
 #define AUTOINIT_FUNCS_INCLUDED 1
 
 /**
-* Current version of the header.
+* Current version of the header in packed BCD form.
 * 0x01093001 = 1.9.30-1.
 */
-#define AUTOINIT_FUNCS_VERSION 0x01000001
+#define AUTOINIT_FUNCS_VERSION 0x01001000
 
-#if defined(__GNUC__)
-#/* if possible - check for supported attribute */
+#if defined(__GNUC__) || defined(__clang__)
+/* if possible - check for supported attribute */
 #ifdef __has_attribute
-#if !__has_attribute(constructor) || !__has_attribute(destructor)
+#if ! __has_attribute (constructor) || ! __has_attribute (destructor)
 #define _GNUC_ATTR_CONSTR_NOT_SUPPORTED 1
 #endif /* !__has_attribute(constructor) || !__has_attribute(destructor) */
 #endif /* __has_attribute */
 #endif /* __GNUC__ */
 
-#if defined(__GNUC__) && !defined(_GNUC_ATTR_CONSTR_NOT_SUPPORTED)
+/* "__has_attribute__ ((constructor))" is supported by GCC, clang and
+   Sun/Oracle compiler starting from version 12.1. */
+#if ((defined(__GNUC__) || defined(__clang__)) && \
+  ! defined(_GNUC_ATTR_CONSTR_NOT_SUPPORTED)) || \
+  (defined(__SUNPRO_C) && __SUNPRO_C + 0 >= 0x5100)
 
 #define GNUC_SET_INIT_AND_DEINIT(FI,FD) \
-  void __attribute__ ((constructor)) _GNUC_init_helper_##FI(void) \
-    { (void)(FI)(); } \
-  void __attribute__ ((destructor)) _GNUC_deinit_helper_##FD(void) \
-    { (void)(FD)(); } \
-  struct _GNUC_dummy_str_##FI{int i;}
+  void __attribute__ ((constructor)) _GNUC_init_helper_ ## FI (void);  \
+  void __attribute__ ((destructor)) _GNUC_deinit_helper_ ## FD (void); \
+  void __attribute__ ((constructor)) _GNUC_init_helper_ ## FI (void)   \
+  { (void) (FI) (); } \
+  void __attribute__ ((destructor)) _GNUC_deinit_helper_ ## FD (void)  \
+  { (void) (FD) (); } \
+  struct _GNUC_dummy_str_ ## FI {int i;}
 
-#define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) GNUC_SET_INIT_AND_DEINIT(FI,FD)
+#define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) GNUC_SET_INIT_AND_DEINIT (FI,FD)
 #define _AUTOINIT_FUNCS_ARE_SUPPORTED 1
 
-#elif defined (_MSC_FULL_VER) && _MSC_VER+0 >= 1600
+#elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1600
 
 /* Make sure that your project/sources define:
    _LIB if building a static library (_LIB is ignored if _CONSOLE is defined);
@@ -96,18 +104,16 @@
    not defined both _LIB and _USRDLL if building an application */
 
 /* Define AUTOINIT_FUNCS_DECLARE_STATIC_REG if you need macro declaration
-   for registering static initialization functions even if you building DLL */
+   for registering static initialisation functions even if you building DLL */
 /* Define AUTOINIT_FUNCS_FORCE_STATIC_REG if you want to set main macro
-   _SET_INIT_AND_DEINIT_FUNCS to static version even if building a DLL*/
+   _SET_INIT_AND_DEINIT_FUNCS to static version even if building a DLL */
 
 /* Stringify macros */
 #define _INSTRMACRO(a) #a
-#define _STRMACRO(a) _INSTRMACRO(a)
+#define _STRMACRO(a) _INSTRMACRO (a)
 
-#if !defined(_USRDLL) || defined(AUTOINIT_FUNCS_DECLARE_STATIC_REG)
-
-/* required for atexit() */
-#include <stdlib.h>
+#if ! defined(_USRDLL) || defined(AUTOINIT_FUNCS_DECLARE_STATIC_REG) \
+  || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG)
 
 /* Use "C" linkage for variable to simplify variable decoration */
 #ifdef __cplusplus
@@ -117,125 +123,180 @@
 #endif
 
 /* How variable is decorated by compiler */
-#if defined(_M_X64) || defined(_M_AMD64)
+#if (defined(_WIN32) || defined(_WIN64)) \
+  && ! defined(_M_IX86) && ! defined(_X86_)
+#if ! defined(_M_X64) && ! defined(_M_AMD64) && ! defined(_x86_64_) \
+  && ! defined(_M_ARM) && ! defined(_M_ARM64)
+#pragma message(__FILE__ "(" _STRMACRO(__LINE__) ") : warning AIFW001 : " \
+  "Untested architecture, linker may fail with unresolved symbol")
+#endif /* ! _M_X64 && ! _M_AMD64 && ! _x86_64_ && ! _M_ARM && ! _M_ARM64 */
 #define W32_VARDECORPREFIX
 #define W32_DECORVARNAME(v) v
-#define W32_VARDECORPEFIXSTR ""
-#elif defined(_M_IX86) || defined(_X86_)
+#define W32_VARDECORPREFIXSTR ""
+#elif defined(_WIN32) && (defined(_M_IX86) || defined(_X86_))
 #define W32_VARDECORPREFIX _
-#define W32_DECORVARNAME(v) _##v
-#define W32_VARDECORPEFIXSTR "_"
+#define W32_DECORVARNAME(v) _ ## v
+#define W32_VARDECORPREFIXSTR "_"
 #else
 #error Do not know how to decorate symbols for this architecture
 #endif
 
 /* Internal variable prefix (can be any) */
-#define W32_INITHELPERVARNAME(f) _initHelperDummy_##f
-#define W32_INITHELPERVARNAMEDECORSTR(f) W32_VARDECORPEFIXSTR _STRMACRO(W32_INITHELPERVARNAME(f))
+#define W32_INITHELPERVARNAME(f) _initHelperDummy_ ## f
+#define W32_INITHELPERVARNAMEDECORSTR(f) \
+  W32_VARDECORPREFIXSTR _STRMACRO (W32_INITHELPERVARNAME (f))
 
 /* Declare section (segment), put variable pointing to init function to chosen segment,
-   force linker to include variable to avoid omitting by optimizer */
-/* Initialization function must be declared as
+   force linker to always include variable to avoid omitting by optimiser */
+/* Initialisation function must be declared as
+   void __cdecl FuncName(void) */
+/* "extern" with initialisation value means that variable is declared AND defined. */
+#define W32_VFPTR_IN_SEG(S,F) \
+  __pragma (section (S,long,read)) \
+  __pragma (comment (linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR (F))) \
+  W32_INITVARDECL __declspec(allocate (S))void \
+    (__cdecl * W32_INITHELPERVARNAME (F))(void) = &F
+
+/* Sections (segments) for pointers to initialisers/deinitialisers */
+
+/* Semi-officially suggested section for early initialisers (called before
+   C++ objects initialisers), "void" return type */
+#define W32_SEG_INIT_EARLY      ".CRT$XCT"
+/* Semi-officially suggested section for late initialisers (called after
+   C++ objects initialisers), "void" return type */
+#define W32_SEG_INIT_LATE       ".CRT$XCV"
+
+/* Unsafe sections (segments) for pointers to initialisers/deinitialisers */
+
+/* C++ lib initialisers, "void" return type (reserved by the system!) */
+#define W32_SEG_INIT_CXX_LIB    ".CRT$XCL"
+/* C++ user initialisers, "void" return type (reserved by the system!) */
+#define W32_SEG_INIT_CXX_USER   ".CRT$XCU"
+
+
+/* Declare section (segment), put variable pointing to init function to chosen segment,
+   force linker to always include variable to avoid omitting by optimiser */
+/* Initialisation function must be declared as
    int __cdecl FuncName(void) */
-/* Return value is ignored for C++ initializers */
-/* For C initializers: startup process is aborted if initializer return non-zero */
-#define W32_FPTR_IN_SEG(S,F) \
-  __pragma(section(S,long,read)) \
-  __pragma(comment(linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR(F))) \
-  W32_INITVARDECL __declspec(allocate(S)) int(__cdecl *W32_INITHELPERVARNAME(F))(void) = &F
+/* Startup process is aborted if initialiser returns non-zero */
+/* "extern" with initialisation value means that variable is declared AND defined. */
+#define W32_IFPTR_IN_SEG(S,F) \
+  __pragma (section (S,long,read)) \
+  __pragma (comment (linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR (F))) \
+  W32_INITVARDECL __declspec(allocate (S))int \
+    (__cdecl * W32_INITHELPERVARNAME (F))(void) = &F
 
-/* Section (segment) names for pointers to initializers */
-#define W32_SEG_INIT_C_USER   ".CRT$XCU"
-#define W32_SEG_INIT_C_LIB    ".CRT$XCL"
-#define W32_SEG_INIT_CXX_USER ".CRT$XIU"
-#define W32_SEG_INIT_CXX_LIB  ".CRT$XIL"
+/* Unsafe sections (segments) for pointers to initialisers with
+   "int" return type */
 
-/* Declare macro for different initializers sections */
-/* Macro can be used several times to register several initializers */
-/* Once function is registered as initializer, it will be called automatically
+/* C lib initialisers, "int" return type (reserved by the system!).
+   These initialisers are called before others. */
+#define W32_SEG_INIT_C_LIB      ".CRT$XIL"
+/* C user initialisers, "int" return type (reserved by the system!).
+   These initialisers are called before others. */
+#define W32_SEG_INIT_C_USER     ".CRT$XIU"
+
+
+/* Declare macro for different initialisers sections */
+/* Macro can be used several times to register several initialisers */
+/* Once function is registered as initialiser, it will be called automatically
    during application startup */
-/* "lib" initializers are called before "user" initializers */
-/* "C" initializers are called before "C++" initializers */
-#define W32_REG_INIT_C_USER(F) W32_FPTR_IN_SEG(W32_SEG_INIT_C_USER,F)
-#define W32_REG_INIT_C_LIB(F) W32_FPTR_IN_SEG(W32_SEG_INIT_C_LIB,F)
-#define W32_REG_INIT_CXX_USER(F) W32_FPTR_IN_SEG(W32_SEG_INIT_CXX_USER,F)
-#define W32_REG_INIT_CXX_LIB(F) W32_FPTR_IN_SEG(W32_SEG_INIT_CXX_LIB,F)
+#define W32_REG_INIT_EARLY(F) W32_VFPTR_IN_SEG (W32_SEG_INIT_EARLY,F)
+#define W32_REG_INIT_LATE(F)  W32_VFPTR_IN_SEG (W32_SEG_INIT_LATE,F)
+
+
+/* Not recommended / unsafe */
+/* "lib" initialisers are called before "user" initialisers */
+/* "C" initialisers are called before "C++" initialisers */
+#define W32_REG_INIT_C_USER(F)   W32_FPTR_IN_SEG (W32_SEG_INIT_C_USER,F)
+#define W32_REG_INIT_C_LIB(F)    W32_FPTR_IN_SEG (W32_SEG_INIT_C_LIB,F)
+#define W32_REG_INIT_CXX_USER(F) W32_FPTR_IN_SEG (W32_SEG_INIT_CXX_USER,F)
+#define W32_REG_INIT_CXX_LIB(F)  W32_FPTR_IN_SEG (W32_SEG_INIT_CXX_LIB,F)
 
 /* Choose main register macro based on language and program type */
 /* Assuming that _LIB or _USRDLL is defined for static or DLL-library */
-/* Macro can be used several times to register several initializers */
-/* Once function is registered as initializer, it will be called automatically
+/* Macro can be used several times to register several initialisers */
+/* Once function is registered as initialiser, it will be called automatically
    during application startup */
-/* Define AUTOINIT_FUNCS_FORCE_USER_LVL_INIT to register initializers
-   at user level even if building library */
-#ifdef __cplusplus
-#if ((defined(_LIB) && !defined(_CONSOLE)) || defined(_USRDLL)) && !defined(AUTOINIT_FUNCS_FORCE_USER_LVL_INIT)
-#define W32_REGISTER_INIT(F) W32_REG_INIT_CXX_LIB(F)
-#else  /* ! _LIB && ! _DLL */
-#define W32_REGISTER_INIT(F) W32_REG_INIT_CXX_USER(F)
-#endif /* ! _LIB && ! _DLL */
-#else  /* !__cplusplus*/
-#if ((defined(_LIB) && !defined(_CONSOLE)) || defined(_USRDLL)) && !defined(AUTOINIT_FUNCS_FORCE_USER_LVL_INIT)
-#define W32_REGISTER_INIT(F) W32_REG_INIT_C_LIB(F)
-#else  /* ! _LIB && ! _DLL */
-#define W32_REGISTER_INIT(F) W32_REG_INIT_C_USER(F)
-#endif /* ! _LIB && ! _DLL */
-#endif /* !__cplusplus*/
+/* Define AUTOINIT_FUNCS_FORCE_EARLY_INIT to force register as early
+   initialiser */
+/* Define AUTOINIT_FUNCS_FORCE_LATE_INIT to force register as late
+   initialiser */
+/* By default C++ static or DLL-library code and any C code and will be
+   registered as early initialiser, while C++ non-library code will be
+   registered as late initialiser */
+#if (! defined(__cplusplus) || \
+  ((defined(_LIB) && ! defined(_CONSOLE)) || defined(_USRDLL)) || \
+  defined(AUTOINIT_FUNCS_FORCE_EARLY_INIT)) && \
+  ! defined(AUTOINIT_FUNCS_FORCE_LATE_INIT)
+#define W32_REGISTER_INIT(F) W32_REG_INIT_EARLY(F)
+#else
+#define W32_REGISTER_INIT(F) W32_REG_INIT_LATE(F)
+#endif
 
-#else /* _USRDLL */
+#endif /* ! _USRDLL || ! AUTOINIT_FUNCS_DECLARE_STATIC_REG
+          || AUTOINIT_FUNCS_FORCE_STATIC_REG */
+
+
+#if ! defined(_USRDLL) || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG)
+
+#include <stdlib.h> /* required for atexit() */
+
+#define W32_SET_INIT_AND_DEINIT(FI,FD) \
+  void __cdecl _W32_init_helper_ ## FI (void);    \
+  void __cdecl _W32_deinit_helper_ ## FD (void); \
+  void __cdecl _W32_init_helper_ ## FI (void)     \
+  { (void) (FI) (); atexit (_W32_deinit_helper_ ## FD); } \
+  void __cdecl _W32_deinit_helper_ ## FD (void)  \
+  { (void) (FD) (); } \
+  W32_REGISTER_INIT (_W32_init_helper_ ## FI)
+#else  /* _USRDLL */
 
 #ifndef WIN32_LEAN_AND_MEAN
 #define WIN32_LEAN_AND_MEAN 1
 #endif /* WIN32_LEAN_AND_MEAN */
-/* Required for DllMain */
-#include <Windows.h>
-#endif /* _USRDLL */
 
+#include <Windows.h> /* Required for DllMain */
 
-#if !defined(_USRDLL) || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG)
-#define W32_SET_INIT_AND_DEINIT(FI,FD) \
-  void __cdecl _W32_deinit_helper_##FD(void) \
-   { (void)(FD)(); } \
-  int __cdecl _W32_init_helper_##FI(void) \
-   { (void)(FI)(); atexit(_W32_deinit_helper_##FD); return 0; } \
-  W32_REGISTER_INIT(_W32_init_helper_##FI)
-#else  /* _USRDLL */
-
-/* If DllMain is already present in code, define AUTOINIT_FUNCS_CALL_USR_DLLMAIN 
+/* If DllMain is already present in code, define AUTOINIT_FUNCS_CALL_USR_DLLMAIN
    and rename DllMain to usr_DllMain */
 #ifndef AUTOINIT_FUNCS_CALL_USR_DLLMAIN
 #define W32_SET_INIT_AND_DEINIT(FI,FD) \
-  BOOL WINAPI DllMain(HINSTANCE hinst,DWORD reason,LPVOID unused) \
-    { if(DLL_PROCESS_ATTACH==reason) {(void)(FI)();} \
-      else if(DLL_PROCESS_DETACH==reason) {(void)(FD)();} \
-      return TRUE; \
-    } struct _W32_dummy_strc_##FI{int i;}
+  BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \
+  BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused)  \
+  { (void) hinst; (void) unused; \
+    if (DLL_PROCESS_ATTACH==reason) {(void) (FI) ();} \
+    else if (DLL_PROCESS_DETACH==reason) {(void) (FD) ();} \
+    return TRUE; \
+  } struct _W32_dummy_strc_ ## FI {int i;}
 #else  /* AUTOINIT_FUNCS_CALL_USR_DLLMAIN */
 #define W32_SET_INIT_AND_DEINIT(FI,FD) \
-  BOOL WINAPI usr_DllMain(HINSTANCE hinst,DWORD reason,LPVOID unused); \
-  BOOL WINAPI DllMain(HINSTANCE hinst,DWORD reason,LPVOID unused) \
-    { if(DLL_PROCESS_ATTACH==reason) {(void)(FI)();} \
-      else if(DLL_PROCESS_DETACH==reason) {(void)(FD)();} \
-      return usr_DllMain(hinst,reason,unused); \
-    } struct _W32_dummy_strc_##FI{int i;}
+  BOOL WINAPI usr_DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \
+  BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \
+  BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused)  \
+  { if (DLL_PROCESS_ATTACH==reason) {(void) (FI) ();} \
+    else if (DLL_PROCESS_DETACH==reason) {(void) (FD) ();} \
+    return usr_DllMain (hinst,reason,unused); \
+  } struct _W32_dummy_strc_ ## FI {int i;}
 #endif /* AUTOINIT_FUNCS_CALL_USR_DLLMAIN */
 #endif /* _USRDLL */
 
-#define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) W32_SET_INIT_AND_DEINIT(FI,FD)
-/* Indicate that automatic initializers/deinitializers are supported */
+#define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) W32_SET_INIT_AND_DEINIT (FI,FD)
+/* Indicate that automatic initialisers/deinitialisers are supported */
 #define _AUTOINIT_FUNCS_ARE_SUPPORTED 1
 
 #else  /* !__GNUC__ && !_MSC_FULL_VER */
 
 /* Define EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED before inclusion of header to
-   abort compilation if automatic initializers/deinitializers are not supported */
+   abort compilation if automatic initialisers/deinitialisers are not supported */
 #ifdef EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED
-#error Compiler/platform don not support automatic calls of user-defined initializer and deinitializer
+#error \
+  Compiler/platform does not support automatic calls of user-defined initializer and deinitializer
 #endif /* EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED */
 
 /* Do nothing */
 #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD)
-/* Indicate that automatic initializers/deinitializers are not supported */
+/* Indicate that automatic initialisers/deinitialisers are not supported */
 #define _AUTOINIT_FUNCS_ARE_NOT_SUPPORTED 1
 
 #endif /* !__GNUC__ && !_MSC_FULL_VER */
diff --git a/src/include/mhd_options.h b/src/include/mhd_options.h
new file mode 100644
index 0000000..a7fadfa
--- /dev/null
+++ b/src/include/mhd_options.h
@@ -0,0 +1,196 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016-2021 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file include/mhd_options.h
+ * @brief  additional automatic macros for MHD_config.h
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * This file includes MHD_config.h and adds automatic macros based on values
+ * in MHD_config.h, compiler built-in macros and commandline-defined macros
+ * (but not based on values defined in other headers). Works also as a guard
+ * to prevent double inclusion of MHD_config.h
+ */
+
+#ifndef MHD_OPTIONS_H
+#define MHD_OPTIONS_H 1
+
+#include "MHD_config.h"
+
+/**
+ * Macro to make it easy to mark text for translation. Note that
+ * we do not actually call gettext() in MHD, but we do make it
+ * easy to create a ".po" file so that applications that do want
+ * to translate error messages can do so.
+ */
+#define _(String) (String)
+
+#if defined(_MHD_EXTERN) && ! defined(BUILDING_MHD_LIB)
+#undef _MHD_EXTERN
+#endif /* _MHD_EXTERN && ! BUILDING_MHD_LIB */
+
+#ifndef _MHD_EXTERN
+#if defined(BUILDING_MHD_LIB) && defined(_WIN32) && \
+  (defined(DLL_EXPORT) || defined(MHD_W32DLL))
+#define _MHD_EXTERN __declspec(dllexport) extern
+#else   /* !BUILDING_MHD_LIB || !_WIN32 || (!DLL_EXPORT && !MHD_W32DLL) */
+#define _MHD_EXTERN extern
+#endif  /* !BUILDING_MHD_LIB || !_WIN32 || (!DLL_EXPORT && !MHD_W32DLL) */
+#endif  /* ! _MHD_EXTERN */
+
+/* Some platforms (FreeBSD, Solaris, W32) allow to override
+   default FD_SETSIZE by defining it before including
+   headers. */
+#ifdef FD_SETSIZE
+/* FD_SETSIZE defined in command line or in MHD_config.h */
+#elif defined(_WIN32) || defined(__CYGWIN__)
+/* Platform with WinSock and without overridden FD_SETSIZE */
+#define FD_SETSIZE 2048 /* Override default small value (64) */
+#else  /* !FD_SETSIZE && !W32 */
+/* System default value of FD_SETSIZE is used */
+#define _MHD_FD_SETSIZE_IS_DEFAULT 1
+#endif /* !FD_SETSIZE && !W32 */
+
+#if defined(HAVE_LINUX_SENDFILE) || defined(HAVE_FREEBSD_SENDFILE) || \
+  defined(HAVE_DARWIN_SENDFILE) || defined(HAVE_SOLARIS_SENDFILE)
+/* Have any supported sendfile() function. */
+#define _MHD_HAVE_SENDFILE
+#endif /* HAVE_LINUX_SENDFILE || HAVE_FREEBSD_SENDFILE ||
+          HAVE_DARWIN_SENDFILE || HAVE_SOLARIS_SENDFILE */
+#if defined(HAVE_LINUX_SENDFILE) || defined(HAVE_SOLARIS_SENDFILE)
+#define MHD_LINUX_SOLARIS_SENDFILE 1
+#endif /* HAVE_LINUX_SENDFILE || HAVE_SOLARIS_SENDFILE */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#  ifndef MHD_USE_THREADS
+#    define MHD_USE_THREADS 1
+#  endif
+#endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */
+
+#if defined(OS390)
+#define _OPEN_THREADS
+#define _OPEN_SYS_SOCK_IPV6
+#define _OPEN_MSGQ_EXT
+#define _LP64
+#endif
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+/* Declare POSIX-compatible names */
+#define _CRT_DECLARE_NONSTDC_NAMES 1
+/* Do not warn about POSIX name usage */
+#define _CRT_NONSTDC_NO_WARNINGS 1
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0600
+#else /* _WIN32_WINNT */
+#if _WIN32_WINNT < 0x0501
+#error "Headers for Windows XP or later are required"
+#endif /* _WIN32_WINNT < 0x0501 */
+#endif /* _WIN32_WINNT */
+#ifndef WIN32_LEAN_AND_MEAN
+/* Do not include unneeded parts of W32 headers. */
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#endif /* _WIN32 && ! __CYGWIN__ */
+
+#if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS)
+#define RESTRICT __restrict__
+#endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */
+
+#if defined(LINUX) && (defined(HAVE_SENDFILE64) || defined(HAVE_LSEEK64)) && \
+  ! defined(_LARGEFILE64_SOURCE)
+/* On Linux, special macro is required to enable definitions of some xxx64 functions */
+#define _LARGEFILE64_SOURCE 1
+#endif
+
+#ifdef HAVE_C11_GMTIME_S
+/* Special macro is required to enable C11 definition of gmtime_s() function */
+#define __STDC_WANT_LIB_EXT1__ 1
+#endif /* HAVE_C11_GMTIME_S */
+
+#if defined(MHD_FAVOR_FAST_CODE) && defined(MHD_FAVOR_SMALL_CODE)
+#error \
+  MHD_FAVOR_FAST_CODE and MHD_FAVOR_SMALL_CODE are both defined. Cannot favor speed and size at the same time.
+#endif /* MHD_FAVOR_FAST_CODE && MHD_FAVOR_SMALL_CODE */
+
+/* Define MHD_FAVOR_FAST_CODE to force fast code path or
+   define MHD_FAVOR_SMALL_CODE to choose compact code path */
+#if ! defined(MHD_FAVOR_FAST_CODE) && ! defined(MHD_FAVOR_SMALL_CODE)
+/* Try to detect user preferences */
+/* Defined by GCC and many compatible compilers */
+#if defined(__OPTIMIZE_SIZE__)
+#define MHD_FAVOR_SMALL_CODE 1
+#elif defined(__OPTIMIZE__)
+#define MHD_FAVOR_FAST_CODE 1
+#endif /* __OPTIMIZE__ */
+#endif /* !MHD_FAVOR_FAST_CODE && !MHD_FAVOR_SMALL_CODE */
+
+#if ! defined(MHD_FAVOR_FAST_CODE) && ! defined(MHD_FAVOR_SMALL_CODE)
+/* Use faster code by default */
+#define MHD_FAVOR_FAST_CODE 1
+#endif /* !MHD_FAVOR_FAST_CODE && !MHD_FAVOR_SMALL_CODE */
+
+#ifndef MHD_ASAN_ACTIVE
+#if (defined(__GNUC__) || defined(_MSC_VER)) && defined(__SANITIZE_ADDRESS__)
+#define MHD_ASAN_ACTIVE 1
+#elif defined(__has_feature)
+#if __has_feature (address_sanitizer)
+#define MHD_ASAN_ACTIVE 1
+#endif /* __has_feature(address_sanitizer) */
+#endif /* __has_feature */
+#endif /* MHD_ASAN_ACTIVE */
+
+#if defined(MHD_ASAN_ACTIVE) && defined(HAVE_SANITIZER_ASAN_INTERFACE_H) && \
+  (defined(FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS) || \
+  (defined(FUNC_ATTR_PTRCOMPARE_WORKS) && \
+  defined(FUNC_ATTR_PTRSUBTRACT_WORKS)) || \
+  defined(FUNC_ATTR_NOSANITIZE_WORKS))
+#ifndef MHD_ASAN_POISON_ACTIVE
+/* User ASAN poisoning could be used */
+#warning User memory poisoning is not active
+#endif /* ! MHD_ASAN_POISON_ACTIVE */
+#else  /* ! (MHD_ASAN_ACTIVE && HAVE_SANITIZER_ASAN_INTERFACE_H &&
+           (FUNC_ATTR_PTRCOMPARE_WORKS || FUNC_ATTR_NOSANITIZE_WORKS))   */
+#ifdef MHD_ASAN_POISON_ACTIVE
+#error User memory poisoning is active, but conditions are not suitable
+#endif /* MHD_ASAN_POISON_ACTIVE */
+#endif /* ! (MHD_ASAN_ACTIVE && HAVE_SANITIZER_ASAN_INTERFACE_H &&
+           (FUNC_ATTR_PTRCOMPARE_WORKS || FUNC_ATTR_NOSANITIZE_WORKS))   */
+
+
+/**
+ * Automatic string with the name of the current function
+ */
+#if defined(HAVE___FUNC__)
+#define MHD_FUNC_       __func__
+#define MHD_HAVE_MHD_FUNC_ 1
+#elif defined(HAVE___FUNCTION__)
+#define MHD_FUNC_       __FUNCTION__
+#define MHD_HAVE_MHD_FUNC_ 1
+#elif defined(HAVE___PRETTY_FUNCTION__)
+#define MHD_FUNC_       __PRETTY_FUNCTION__
+#define MHD_HAVE_MHD_FUNC_ 1
+#else
+#define MHD_FUNC_       "**name unavailable**"
+#ifdef MHD_HAVE_MHD_FUNC_
+#undef MHD_HAVE_MHD_FUNC_
+#endif /* MHD_HAVE_MHD_FUNC_ */
+#endif
+
+
+#endif /* MHD_OPTIONS_H */
diff --git a/src/include/microhttpd.h b/src/include/microhttpd.h
index b4ee0b7..64cb850 100644
--- a/src/include/microhttpd.h
+++ b/src/include/microhttpd.h
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2006-2015 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2006-2021 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,6 +22,7 @@
  * @file microhttpd.h
  * @brief public interface to libmicrohttpd
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  * @author Chris GauthierDickey
  *
  * All symbols defined in this header start with MHD.  MHD is a small
@@ -42,7 +44,7 @@
  *
  * MHD understands POST data and is able to decode certain formats
  * (at the moment only "application/x-www-form-urlencoded" and
- * "mulitpart/formdata"). Unsupported encodings and large POST
+ * "multipart/formdata"). Unsupported encodings and large POST
  * submissions may require the application to manually process
  * the stream, which is provided to the main application (and thus can be
  * processed, just not conveniently by MHD).
@@ -59,14 +61,6 @@
  * thread-safe (with the exception of #MHD_set_connection_value,
  * which must only be used in a particular context).
  *
- * NEW: Before including "microhttpd.h" you should add the necessary
- * includes to define the `uint64_t`, `size_t`, `fd_set`, `socklen_t`
- * and `struct sockaddr` data types (which headers are needed may
- * depend on your platform; for possible suggestions consult
- * "platform.h" in the MHD distribution).  If you have done so, you
- * should also have a line with "#define MHD_PLATFORM_H" which will
- * prevent this header from trying (and, depending on your platform,
- * failing) to include the right headers.
  *
  * @defgroup event event-loop control
  * MHD API to start and stop the HTTP server and manage the event loop.
@@ -94,58 +88,85 @@
 #endif
 #endif
 
-/* While we generally would like users to use a configure-driven
-   build process which detects which headers are present and
-   hence works on any platform, we use "standard" includes here
-   to build out-of-the-box for beginning users on common systems.
 
-   Once you have a proper build system and go for more exotic
-   platforms, you should define MHD_PLATFORM_H in some header that
-   you always include *before* "microhttpd.h".  Then the following
-   "standard" includes won't be used (which might be a good
-   idea, especially on platforms where they do not exist). */
+/**
+ * Current version of the library in packed BCD form.
+ * @note Version number components are coded as Simple Binary-Coded Decimal
+ * (also called Natural BCD or BCD 8421). While they are hexadecimal numbers,
+ * they are parsed as decimal numbers.
+ * Example: 0x01093001 = 1.9.30-1.
+ */
+#define MHD_VERSION 0x00097601
+
+/* If generic headers don't work on your platform, include headers
+   which define 'va_list', 'size_t', 'ssize_t', 'intptr_t', 'off_t',
+   'uint8_t', 'uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t',
+   'struct sockaddr', 'socklen_t', 'fd_set' and "#define MHD_PLATFORM_H" before
+   including "microhttpd.h". Then the following "standard"
+   includes won't be used (which might be a good idea, especially
+   on platforms where they do not exist).
+   */
 #ifndef MHD_PLATFORM_H
+#if defined(_WIN32) && ! defined(__CYGWIN__) && \
+  ! defined(_CRT_DECLARE_NONSTDC_NAMES)
+/* Declare POSIX-compatible names */
+#define _CRT_DECLARE_NONSTDC_NAMES 1
+#endif /* _WIN32 && ! __CYGWIN__ && ! _CRT_DECLARE_NONSTDC_NAMES */
 #include <stdarg.h>
 #include <stdint.h>
 #include <sys/types.h>
-#if defined(_WIN32) && !defined(__CYGWIN__)
-#include <ws2tcpip.h>
-#if defined(_MSC_FULL_VER) && !defined (_SSIZE_T_DEFINED)
-#define _SSIZE_T_DEFINED
-typedef intptr_t ssize_t;
-#endif // !_SSIZE_T_DEFINED */
-#else
+#if ! defined(_WIN32) || defined(__CYGWIN__)
 #include <unistd.h>
 #include <sys/time.h>
 #include <sys/socket.h>
-#endif
+#else  /* _WIN32 && ! __CYGWIN__ */
+#include <ws2tcpip.h>
+#if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED)
+#define _SSIZE_T_DEFINED
+typedef intptr_t ssize_t;
+#endif /* !_SSIZE_T_DEFINED */
+#endif /* _WIN32 && ! __CYGWIN__ */
 #endif
 
-#if defined(__CYGWIN__) && !defined(_SYS_TYPES_FD_SET)
+#if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET)
 /* Do not define __USE_W32_SOCKETS under Cygwin! */
 #error Cygwin with winsock fd_set is not supported
 #endif
 
-/**
- * Current version of the library.
- * 0x01093001 = 1.9.30-1.
- */
-#define MHD_VERSION 0x00094200
+#ifdef __has_attribute
+#if __has_attribute (flag_enum)
+#define _MHD_FLAGS_ENUM __attribute__((flag_enum))
+#endif /* flag_enum */
+#if __has_attribute (enum_extensibility)
+#define _MHD_FIXED_ENUM __attribute__((enum_extensibility (closed)))
+#endif /* enum_extensibility */
+#endif /* __has_attribute */
+
+#ifndef _MHD_FLAGS_ENUM
+#define _MHD_FLAGS_ENUM
+#endif /* _MHD_FLAGS_ENUM */
+#ifndef _MHD_FIXED_ENUM
+#define _MHD_FIXED_ENUM
+#endif /* _MHD_FIXED_ENUM */
+
+#define _MHD_FIXED_FLAGS_ENUM _MHD_FIXED_ENUM _MHD_FLAGS_ENUM
 
 /**
- * MHD-internal return code for "YES".
+ * Operational results from MHD calls.
  */
-#define MHD_YES 1
+enum MHD_Result
+{
+  /**
+   * MHD result code for "NO".
+   */
+  MHD_NO = 0,
 
-/**
- * MHD-internal return code for "NO".
- */
-#define MHD_NO 0
+  /**
+   * MHD result code for "YES".
+   */
+  MHD_YES = 1
 
-/**
- * MHD digest auth internal code for an invalid nonce.
- */
-#define MHD_INVALID_NONCE -1
+} _MHD_FIXED_ENUM;
 
 /**
  * Constant used to indicate unknown size (use when
@@ -157,18 +178,13 @@
 #define MHD_SIZE_UNKNOWN  ((uint64_t) -1LL)
 #endif
 
-#ifdef SIZE_MAX
-#define MHD_CONTENT_READER_END_OF_STREAM SIZE_MAX
-#define MHD_CONTENT_READER_END_WITH_ERROR (SIZE_MAX - 1)
-#else
-#define MHD_CONTENT_READER_END_OF_STREAM ((size_t) -1LL)
-#define MHD_CONTENT_READER_END_WITH_ERROR (((size_t) -1LL) - 1)
-#endif
+#define MHD_CONTENT_READER_END_OF_STREAM ((ssize_t) -1)
+#define MHD_CONTENT_READER_END_WITH_ERROR ((ssize_t) -2)
 
 #ifndef _MHD_EXTERN
 #if defined(_WIN32) && defined(MHD_W32LIB)
 #define _MHD_EXTERN extern
-#elif defined (_WIN32) && defined(MHD_W32DLL)
+#elif defined(_WIN32) && defined(MHD_W32DLL)
 /* Define MHD_W32DLL when using MHD as W32 .DLL to speed up linker a little */
 #define _MHD_EXTERN __declspec(dllimport)
 #else
@@ -180,7 +196,7 @@
 /**
  * MHD_socket is type for socket FDs
  */
-#if !defined(_WIN32) || defined(_SYS_TYPES_FD_SET)
+#if ! defined(_WIN32) || defined(_SYS_TYPES_FD_SET)
 #define MHD_POSIX_SOCKETS 1
 typedef int MHD_socket;
 #define MHD_INVALID_SOCKET (-1)
@@ -194,6 +210,89 @@
 #endif /* MHD_SOCKET_DEFINED */
 
 /**
+ * Define MHD_NO_DEPRECATION before including "microhttpd.h" to disable deprecation messages
+ */
+#ifdef MHD_NO_DEPRECATION
+#define _MHD_DEPR_MACRO(msg)
+#define _MHD_NO_DEPR_IN_MACRO 1
+#define _MHD_DEPR_IN_MACRO(msg)
+#define _MHD_NO_DEPR_FUNC 1
+#define _MHD_DEPR_FUNC(msg)
+#endif /* MHD_NO_DEPRECATION */
+
+#ifndef _MHD_DEPR_MACRO
+#if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1500
+/* VS 2008 or later */
+/* Stringify macros */
+#define _MHD_INSTRMACRO(a) #a
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+/* deprecation message */
+#define _MHD_DEPR_MACRO(msg) \
+  __pragma(message (__FILE__ "(" _MHD_STRMACRO ( __LINE__) "): warning: " msg))
+#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg)
+#elif defined(__clang__) || defined(__GNUC_PATCHLEVEL__)
+/* clang or GCC since 3.0 */
+#define _MHD_GCC_PRAG(x) _Pragma(#x)
+#if (defined(__clang__) && \
+  (__clang_major__ + 0 >= 5 || \
+   (! defined(__apple_build_version__) && \
+  (__clang_major__ + 0  > 3 || \
+   (__clang_major__ + 0 == 3 && __clang_minor__ >=  3))))) || \
+  __GNUC__ + 0 > 4 || (__GNUC__ + 0 == 4 && __GNUC_MINOR__ + 0 >= 8)
+/* clang >= 3.3 (or XCode's clang >= 5.0) or
+   GCC >= 4.8 */
+#define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (GCC warning msg)
+#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg)
+#else /* older clang or GCC */
+/* clang < 3.3, XCode's clang < 5.0, 3.0 <= GCC < 4.8 */
+#define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (message msg)
+#if (defined(__clang__) && \
+  (__clang_major__ + 0  > 2 || \
+   (__clang_major__ + 0 == 2 && __clang_minor__ >= 9)))  /* clang >= 2.9 */
+/* clang handles inline pragmas better than GCC */
+#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg)
+#endif /* clang >= 2.9 */
+#endif  /* older clang or GCC */
+/* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */
+#endif /* clang || GCC >= 3.0 */
+#endif /* !_MHD_DEPR_MACRO */
+
+#ifndef _MHD_DEPR_MACRO
+#define _MHD_DEPR_MACRO(msg)
+#endif /* !_MHD_DEPR_MACRO */
+
+#ifndef _MHD_DEPR_IN_MACRO
+#define _MHD_NO_DEPR_IN_MACRO 1
+#define _MHD_DEPR_IN_MACRO(msg)
+#endif /* !_MHD_DEPR_IN_MACRO */
+
+#ifndef _MHD_DEPR_FUNC
+#if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1400
+/* VS 2005 or later */
+#define _MHD_DEPR_FUNC(msg) __declspec(deprecated (msg))
+#elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1310
+/* VS .NET 2003 deprecation does not support custom messages */
+#define _MHD_DEPR_FUNC(msg) __declspec(deprecated)
+#elif (__GNUC__ + 0 >= 5) || (defined(__clang__) && \
+  (__clang_major__ + 0 > 2 || \
+   (__clang_major__ + 0 == 2 && __clang_minor__ >=  9)))
+/* GCC >= 5.0 or clang >= 2.9 */
+#define _MHD_DEPR_FUNC(msg) __attribute__((deprecated (msg)))
+#elif defined(__clang__) || __GNUC__ + 0 > 3 || \
+  (__GNUC__ + 0 == 3 && __GNUC_MINOR__ + 0 >= 1)
+/* 3.1 <= GCC < 5.0 or clang < 2.9 */
+/* old GCC-style deprecation does not support custom messages */
+#define _MHD_DEPR_FUNC(msg) __attribute__((__deprecated__))
+/* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */
+#endif /* clang < 2.9 || GCC >= 3.1 */
+#endif /* !_MHD_DEPR_FUNC */
+
+#ifndef _MHD_DEPR_FUNC
+#define _MHD_NO_DEPR_FUNC 1
+#define _MHD_DEPR_FUNC(msg)
+#endif /* !_MHD_DEPR_FUNC */
+
+/**
  * Not all architectures and `printf()`'s support the `long long` type.
  * This gives the ability to replace `long long` with just a `long`,
  * standard `int` or a `short`.
@@ -204,6 +303,9 @@
  */
 #define MHD_LONG_LONG long long
 #define MHD_UNSIGNED_LONG_LONG unsigned long long
+#else /* MHD_LONG_LONG */
+_MHD_DEPR_MACRO ( \
+  "Macro MHD_LONG_LONG is deprecated, use MHD_UNSIGNED_LONG_LONG")
 #endif
 /**
  * Format string for printing a variable of type #MHD_LONG_LONG.
@@ -215,146 +317,737 @@
  */
 #define MHD_LONG_LONG_PRINTF "ll"
 #define MHD_UNSIGNED_LONG_LONG_PRINTF "%llu"
+#else /* MHD_LONG_LONG_PRINTF */
+_MHD_DEPR_MACRO ( \
+  "Macro MHD_LONG_LONG_PRINTF is deprecated, use MHD_UNSIGNED_LONG_LONG_PRINTF")
 #endif
 
 
 /**
  * @defgroup httpcode HTTP response codes.
  * These are the status codes defined for HTTP responses.
+ * See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
+ * Registry export date: 2021-12-19
  * @{
  */
-#define MHD_HTTP_CONTINUE 100
-#define MHD_HTTP_SWITCHING_PROTOCOLS 101
-#define MHD_HTTP_PROCESSING 102
 
-#define MHD_HTTP_OK 200
-#define MHD_HTTP_CREATED 201
-#define MHD_HTTP_ACCEPTED 202
+/* 100 "Continue".            RFC-ietf-httpbis-semantics, Section 15.2.1. */
+#define MHD_HTTP_CONTINUE                    100
+/* 101 "Switching Protocols". RFC-ietf-httpbis-semantics, Section 15.2.2. */
+#define MHD_HTTP_SWITCHING_PROTOCOLS         101
+/* 102 "Processing".          RFC2518. */
+#define MHD_HTTP_PROCESSING                  102
+/* 103 "Early Hints".         RFC8297. */
+#define MHD_HTTP_EARLY_HINTS                 103
+
+/* 200 "OK".                  RFC-ietf-httpbis-semantics, Section 15.3.1. */
+#define MHD_HTTP_OK                          200
+/* 201 "Created".             RFC-ietf-httpbis-semantics, Section 15.3.2. */
+#define MHD_HTTP_CREATED                     201
+/* 202 "Accepted".            RFC-ietf-httpbis-semantics, Section 15.3.3. */
+#define MHD_HTTP_ACCEPTED                    202
+/* 203 "Non-Authoritative Information". RFC-ietf-httpbis-semantics, Section 15.3.4. */
 #define MHD_HTTP_NON_AUTHORITATIVE_INFORMATION 203
-#define MHD_HTTP_NO_CONTENT 204
-#define MHD_HTTP_RESET_CONTENT 205
-#define MHD_HTTP_PARTIAL_CONTENT 206
-#define MHD_HTTP_MULTI_STATUS 207
+/* 204 "No Content".          RFC-ietf-httpbis-semantics, Section 15.3.5. */
+#define MHD_HTTP_NO_CONTENT                  204
+/* 205 "Reset Content".       RFC-ietf-httpbis-semantics, Section 15.3.6. */
+#define MHD_HTTP_RESET_CONTENT               205
+/* 206 "Partial Content".     RFC-ietf-httpbis-semantics, Section 15.3.7. */
+#define MHD_HTTP_PARTIAL_CONTENT             206
+/* 207 "Multi-Status".        RFC4918. */
+#define MHD_HTTP_MULTI_STATUS                207
+/* 208 "Already Reported".    RFC5842. */
+#define MHD_HTTP_ALREADY_REPORTED            208
 
-#define MHD_HTTP_MULTIPLE_CHOICES 300
-#define MHD_HTTP_MOVED_PERMANENTLY 301
-#define MHD_HTTP_FOUND 302
-#define MHD_HTTP_SEE_OTHER 303
-#define MHD_HTTP_NOT_MODIFIED 304
-#define MHD_HTTP_USE_PROXY 305
-#define MHD_HTTP_SWITCH_PROXY 306
-#define MHD_HTTP_TEMPORARY_REDIRECT 307
+/* 226 "IM Used".             RFC3229. */
+#define MHD_HTTP_IM_USED                     226
 
-#define MHD_HTTP_BAD_REQUEST 400
-#define MHD_HTTP_UNAUTHORIZED 401
-#define MHD_HTTP_PAYMENT_REQUIRED 402
-#define MHD_HTTP_FORBIDDEN 403
-#define MHD_HTTP_NOT_FOUND 404
-#define MHD_HTTP_METHOD_NOT_ALLOWED 405
-#define MHD_HTTP_NOT_ACCEPTABLE 406
-/** @deprecated */
-#define MHD_HTTP_METHOD_NOT_ACCEPTABLE 406
+/* 300 "Multiple Choices".    RFC-ietf-httpbis-semantics, Section 15.4.1. */
+#define MHD_HTTP_MULTIPLE_CHOICES            300
+/* 301 "Moved Permanently".   RFC-ietf-httpbis-semantics, Section 15.4.2. */
+#define MHD_HTTP_MOVED_PERMANENTLY           301
+/* 302 "Found".               RFC-ietf-httpbis-semantics, Section 15.4.3. */
+#define MHD_HTTP_FOUND                       302
+/* 303 "See Other".           RFC-ietf-httpbis-semantics, Section 15.4.4. */
+#define MHD_HTTP_SEE_OTHER                   303
+/* 304 "Not Modified".        RFC-ietf-httpbis-semantics, Section 15.4.5. */
+#define MHD_HTTP_NOT_MODIFIED                304
+/* 305 "Use Proxy".           RFC-ietf-httpbis-semantics, Section 15.4.6. */
+#define MHD_HTTP_USE_PROXY                   305
+/* 306 "Switch Proxy".        Not used! RFC-ietf-httpbis-semantics, Section 15.4.7. */
+#define MHD_HTTP_SWITCH_PROXY                306
+/* 307 "Temporary Redirect".  RFC-ietf-httpbis-semantics, Section 15.4.8. */
+#define MHD_HTTP_TEMPORARY_REDIRECT          307
+/* 308 "Permanent Redirect".  RFC-ietf-httpbis-semantics, Section 15.4.9. */
+#define MHD_HTTP_PERMANENT_REDIRECT          308
+
+/* 400 "Bad Request".         RFC-ietf-httpbis-semantics, Section 15.5.1. */
+#define MHD_HTTP_BAD_REQUEST                 400
+/* 401 "Unauthorized".        RFC-ietf-httpbis-semantics, Section 15.5.2. */
+#define MHD_HTTP_UNAUTHORIZED                401
+/* 402 "Payment Required".    RFC-ietf-httpbis-semantics, Section 15.5.3. */
+#define MHD_HTTP_PAYMENT_REQUIRED            402
+/* 403 "Forbidden".           RFC-ietf-httpbis-semantics, Section 15.5.4. */
+#define MHD_HTTP_FORBIDDEN                   403
+/* 404 "Not Found".           RFC-ietf-httpbis-semantics, Section 15.5.5. */
+#define MHD_HTTP_NOT_FOUND                   404
+/* 405 "Method Not Allowed".  RFC-ietf-httpbis-semantics, Section 15.5.6. */
+#define MHD_HTTP_METHOD_NOT_ALLOWED          405
+/* 406 "Not Acceptable".      RFC-ietf-httpbis-semantics, Section 15.5.7. */
+#define MHD_HTTP_NOT_ACCEPTABLE              406
+/* 407 "Proxy Authentication Required". RFC-ietf-httpbis-semantics, Section 15.5.8. */
 #define MHD_HTTP_PROXY_AUTHENTICATION_REQUIRED 407
-#define MHD_HTTP_REQUEST_TIMEOUT 408
-#define MHD_HTTP_CONFLICT 409
-#define MHD_HTTP_GONE 410
-#define MHD_HTTP_LENGTH_REQUIRED 411
-#define MHD_HTTP_PRECONDITION_FAILED 412
-#define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE 413
-#define MHD_HTTP_REQUEST_URI_TOO_LONG 414
-#define MHD_HTTP_UNSUPPORTED_MEDIA_TYPE 415
-#define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE 416
-#define MHD_HTTP_EXPECTATION_FAILED 417
-#define MHD_HTTP_UNPROCESSABLE_ENTITY 422
-#define MHD_HTTP_LOCKED 423
-#define MHD_HTTP_FAILED_DEPENDENCY 424
-#define MHD_HTTP_UNORDERED_COLLECTION 425
-#define MHD_HTTP_UPGRADE_REQUIRED 426
-#define MHD_HTTP_NO_RESPONSE 444
-#define MHD_HTTP_RETRY_WITH 449
-#define MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450
+/* 408 "Request Timeout".     RFC-ietf-httpbis-semantics, Section 15.5.9. */
+#define MHD_HTTP_REQUEST_TIMEOUT             408
+/* 409 "Conflict".            RFC-ietf-httpbis-semantics, Section 15.5.10. */
+#define MHD_HTTP_CONFLICT                    409
+/* 410 "Gone".                RFC-ietf-httpbis-semantics, Section 15.5.11. */
+#define MHD_HTTP_GONE                        410
+/* 411 "Length Required".     RFC-ietf-httpbis-semantics, Section 15.5.12. */
+#define MHD_HTTP_LENGTH_REQUIRED             411
+/* 412 "Precondition Failed". RFC-ietf-httpbis-semantics, Section 15.5.13. */
+#define MHD_HTTP_PRECONDITION_FAILED         412
+/* 413 "Content Too Large".   RFC-ietf-httpbis-semantics, Section 15.5.14. */
+#define MHD_HTTP_CONTENT_TOO_LARGE           413
+/* 414 "URI Too Long".        RFC-ietf-httpbis-semantics, Section 15.5.15. */
+#define MHD_HTTP_URI_TOO_LONG                414
+/* 415 "Unsupported Media Type". RFC-ietf-httpbis-semantics, Section 15.5.16. */
+#define MHD_HTTP_UNSUPPORTED_MEDIA_TYPE      415
+/* 416 "Range Not Satisfiable". RFC-ietf-httpbis-semantics, Section 15.5.17. */
+#define MHD_HTTP_RANGE_NOT_SATISFIABLE       416
+/* 417 "Expectation Failed".  RFC-ietf-httpbis-semantics, Section 15.5.18. */
+#define MHD_HTTP_EXPECTATION_FAILED          417
+
+
+/* 421 "Misdirected Request". RFC-ietf-httpbis-semantics, Section 15.5.20. */
+#define MHD_HTTP_MISDIRECTED_REQUEST         421
+/* 422 "Unprocessable Content". RFC-ietf-httpbis-semantics, Section 15.5.21. */
+#define MHD_HTTP_UNPROCESSABLE_CONTENT       422
+/* 423 "Locked".              RFC4918. */
+#define MHD_HTTP_LOCKED                      423
+/* 424 "Failed Dependency".   RFC4918. */
+#define MHD_HTTP_FAILED_DEPENDENCY           424
+/* 425 "Too Early".           RFC8470. */
+#define MHD_HTTP_TOO_EARLY                   425
+/* 426 "Upgrade Required".    RFC-ietf-httpbis-semantics, Section 15.5.22. */
+#define MHD_HTTP_UPGRADE_REQUIRED            426
+
+/* 428 "Precondition Required". RFC6585. */
+#define MHD_HTTP_PRECONDITION_REQUIRED       428
+/* 429 "Too Many Requests".   RFC6585. */
+#define MHD_HTTP_TOO_MANY_REQUESTS           429
+
+/* 431 "Request Header Fields Too Large". RFC6585. */
+#define MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE 431
+
+/* 451 "Unavailable For Legal Reasons". RFC7725. */
 #define MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS 451
 
-#define MHD_HTTP_INTERNAL_SERVER_ERROR 500
-#define MHD_HTTP_NOT_IMPLEMENTED 501
-#define MHD_HTTP_BAD_GATEWAY 502
-#define MHD_HTTP_SERVICE_UNAVAILABLE 503
-#define MHD_HTTP_GATEWAY_TIMEOUT 504
-#define MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED 505
-#define MHD_HTTP_VARIANT_ALSO_NEGOTIATES 506
-#define MHD_HTTP_INSUFFICIENT_STORAGE 507
-#define MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED 509
-#define MHD_HTTP_NOT_EXTENDED 510
+/* 500 "Internal Server Error". RFC-ietf-httpbis-semantics, Section 15.6.1. */
+#define MHD_HTTP_INTERNAL_SERVER_ERROR       500
+/* 501 "Not Implemented".     RFC-ietf-httpbis-semantics, Section 15.6.2. */
+#define MHD_HTTP_NOT_IMPLEMENTED             501
+/* 502 "Bad Gateway".         RFC-ietf-httpbis-semantics, Section 15.6.3. */
+#define MHD_HTTP_BAD_GATEWAY                 502
+/* 503 "Service Unavailable". RFC-ietf-httpbis-semantics, Section 15.6.4. */
+#define MHD_HTTP_SERVICE_UNAVAILABLE         503
+/* 504 "Gateway Timeout".     RFC-ietf-httpbis-semantics, Section 15.6.5. */
+#define MHD_HTTP_GATEWAY_TIMEOUT             504
+/* 505 "HTTP Version Not Supported". RFC-ietf-httpbis-semantics, Section 15.6.6. */
+#define MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED  505
+/* 506 "Variant Also Negotiates". RFC2295. */
+#define MHD_HTTP_VARIANT_ALSO_NEGOTIATES     506
+/* 507 "Insufficient Storage". RFC4918. */
+#define MHD_HTTP_INSUFFICIENT_STORAGE        507
+/* 508 "Loop Detected".       RFC5842. */
+#define MHD_HTTP_LOOP_DETECTED               508
+
+/* 510 "Not Extended".        RFC2774. */
+#define MHD_HTTP_NOT_EXTENDED                510
+/* 511 "Network Authentication Required". RFC6585. */
+#define MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED 511
+
+
+/* Not registered non-standard codes */
+/* 449 "Reply With".          MS IIS extension. */
+#define MHD_HTTP_RETRY_WITH                  449
+
+/* 450 "Blocked by Windows Parental Controls". MS extension. */
+#define MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450
+
+/* 509 "Bandwidth Limit Exceeded". Apache extension. */
+#define MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED    509
+
+/* Deprecated names and codes */
+/** @deprecated */
+#define MHD_HTTP_METHOD_NOT_ACCEPTABLE \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_METHOD_NOT_ACCEPTABLE is deprecated, " \
+                      "use MHD_HTTP_NOT_ACCEPTABLE") \
+  406
+
+/** @deprecated */
+#define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_REQUEST_ENTITY_TOO_LARGE is deprecated, " \
+                      "use MHD_HTTP_CONTENT_TOO_LARGE") \
+  413
+
+/** @deprecated */
+#define MHD_HTTP_PAYLOAD_TOO_LARGE \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_PAYLOAD_TOO_LARGE is deprecated, " \
+                      "use MHD_HTTP_CONTENT_TOO_LARGE") \
+  413
+
+/** @deprecated */
+#define MHD_HTTP_REQUEST_URI_TOO_LONG \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_REQUEST_URI_TOO_LONG is deprecated, " \
+                      "use MHD_HTTP_URI_TOO_LONG") \
+  414
+
+/** @deprecated */
+#define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE is " \
+                      "deprecated, use MHD_HTTP_RANGE_NOT_SATISFIABLE") \
+  416
+
+/** @deprecated */
+#define MHD_HTTP_UNPROCESSABLE_ENTITY \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_UNPROCESSABLE_ENTITY is deprecated, " \
+                      "use MHD_HTTP_UNPROCESSABLE_CONTENT") \
+  422
+
+/** @deprecated */
+#define MHD_HTTP_UNORDERED_COLLECTION \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_UNORDERED_COLLECTION is deprecated " \
+                      "as it was removed from RFC") \
+  425
+
+/** @deprecated */
+#define MHD_HTTP_NO_RESPONSE \
+  _MHD_DEPR_IN_MACRO ("Value MHD_HTTP_NO_RESPONSE is deprecated as " \
+                      "it is nginx internal code for logs only") \
+  444
+
 
 /** @} */ /* end of group httpcode */
 
 /**
+ * Returns the string reason phrase for a response code.
+ *
+ * If message string is not available for a status code,
+ * "Unknown" string will be returned.
+ */
+_MHD_EXTERN const char *
+MHD_get_reason_phrase_for (unsigned int code);
+
+
+/**
+ * Returns the length of the string reason phrase for a response code.
+ *
+ * If message string is not available for a status code,
+ * 0 is returned.
+ */
+_MHD_EXTERN size_t
+MHD_get_reason_phrase_len_for (unsigned int code);
+
+/**
  * Flag to be or-ed with MHD_HTTP status code for
  * SHOUTcast.  This will cause the response to begin
- * with the SHOUTcast "ICY" line instad of "HTTP".
+ * with the SHOUTcast "ICY" line instead of "HTTP".
  * @ingroup specialized
  */
-#define MHD_ICY_FLAG ((uint32_t)(((uint32_t)1) << 31))
+#define MHD_ICY_FLAG ((uint32_t) (((uint32_t) 1) << 31))
 
 /**
  * @defgroup headers HTTP headers
  * These are the standard headers found in HTTP requests and responses.
+ * See: https://www.iana.org/assignments/http-fields/http-fields.xhtml
+ * Registry export date: 2021-12-19
  * @{
  */
-/* See also: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html */
-#define MHD_HTTP_HEADER_ACCEPT "Accept"
-#define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset"
-#define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding"
-#define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language"
-#define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges"
-#define MHD_HTTP_HEADER_AGE "Age"
-#define MHD_HTTP_HEADER_ALLOW "Allow"
-#define MHD_HTTP_HEADER_AUTHORIZATION "Authorization"
-#define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control"
-#define MHD_HTTP_HEADER_CONNECTION "Connection"
-#define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding"
-#define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language"
-#define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length"
-#define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location"
-#define MHD_HTTP_HEADER_CONTENT_MD5 "Content-MD5"
-#define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range"
-#define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type"
-#define MHD_HTTP_HEADER_COOKIE "Cookie"
-#define MHD_HTTP_HEADER_DATE "Date"
-#define MHD_HTTP_HEADER_ETAG "ETag"
-#define MHD_HTTP_HEADER_EXPECT "Expect"
-#define MHD_HTTP_HEADER_EXPIRES "Expires"
-#define MHD_HTTP_HEADER_FROM "From"
-#define MHD_HTTP_HEADER_HOST "Host"
-#define MHD_HTTP_HEADER_IF_MATCH "If-Match"
-#define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since"
-#define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match"
-#define MHD_HTTP_HEADER_IF_RANGE "If-Range"
-#define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since"
-#define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified"
-#define MHD_HTTP_HEADER_LOCATION "Location"
-#define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards"
-#define MHD_HTTP_HEADER_PRAGMA "Pragma"
-#define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate"
-#define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization"
-#define MHD_HTTP_HEADER_RANGE "Range"
-/* This is not a typo, see HTTP spec */
-#define MHD_HTTP_HEADER_REFERER "Referer"
-#define MHD_HTTP_HEADER_RETRY_AFTER "Retry-After"
-#define MHD_HTTP_HEADER_SERVER "Server"
-#define MHD_HTTP_HEADER_SET_COOKIE "Set-Cookie"
-#define MHD_HTTP_HEADER_SET_COOKIE2 "Set-Cookie2"
-#define MHD_HTTP_HEADER_TE "TE"
-#define MHD_HTTP_HEADER_TRAILER "Trailer"
-#define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding"
-#define MHD_HTTP_HEADER_UPGRADE "Upgrade"
-#define MHD_HTTP_HEADER_USER_AGENT "User-Agent"
-#define MHD_HTTP_HEADER_VARY "Vary"
-#define MHD_HTTP_HEADER_VIA "Via"
-#define MHD_HTTP_HEADER_WARNING "Warning"
-#define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate"
-#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN "Access-Control-Allow-Origin"
 
+/* Main HTTP headers. */
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 12.5.1 */
+#define MHD_HTTP_HEADER_ACCEPT       "Accept"
+/* Deprecated.    RFC-ietf-httpbis-semantics-19, Section 12.5.2 */
+#define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 12.5.3 */
+#define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 12.5.4 */
+#define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 14.3 */
+#define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges"
+/* Permanent.     RFC-ietf-httpbis-cache-19, Section 5.1 */
+#define MHD_HTTP_HEADER_AGE          "Age"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.2.1 */
+#define MHD_HTTP_HEADER_ALLOW        "Allow"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 11.6.3 */
+#define MHD_HTTP_HEADER_AUTHENTICATION_INFO "Authentication-Info"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 11.6.2 */
+#define MHD_HTTP_HEADER_AUTHORIZATION "Authorization"
+/* Permanent.     RFC-ietf-httpbis-cache-19, Section 5.2 */
+#define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control"
+/* Permanent.     RFC-ietf-httpbis-cache-header-10 */
+#define MHD_HTTP_HEADER_CACHE_STATUS "Cache-Status"
+/* Permanent.     RFC-ietf-httpbis-messaging-19, Section 9.6 */
+#define MHD_HTTP_HEADER_CLOSE        "Close"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 7.6.1 */
+#define MHD_HTTP_HEADER_CONNECTION   "Connection"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.4 */
+#define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.5 */
+#define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.6 */
+#define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.7 */
+#define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 14.4 */
+#define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.3 */
+#define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 6.6.1 */
+#define MHD_HTTP_HEADER_DATE         "Date"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.8.3 */
+#define MHD_HTTP_HEADER_ETAG         "ETag"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.1.1 */
+#define MHD_HTTP_HEADER_EXPECT       "Expect"
+/* Permanent.     RFC-ietf-httpbis-expect-ct-08 */
+#define MHD_HTTP_HEADER_EXPECT_CT    "Expect-CT"
+/* Permanent.     RFC-ietf-httpbis-cache-19, Section 5.3 */
+#define MHD_HTTP_HEADER_EXPIRES      "Expires"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.1.2 */
+#define MHD_HTTP_HEADER_FROM         "From"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 7.2 */
+#define MHD_HTTP_HEADER_HOST         "Host"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 13.1.1 */
+#define MHD_HTTP_HEADER_IF_MATCH     "If-Match"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 13.1.3 */
+#define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 13.1.2 */
+#define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 13.1.5 */
+#define MHD_HTTP_HEADER_IF_RANGE     "If-Range"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 13.1.4 */
+#define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 8.8.2 */
+#define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.2.2 */
+#define MHD_HTTP_HEADER_LOCATION     "Location"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 7.6.2 */
+#define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards"
+/* Permanent.     RFC-ietf-httpbis-messaging-19, Appendix B.1 */
+#define MHD_HTTP_HEADER_MIME_VERSION "MIME-Version"
+/* Permanent.     RFC-ietf-httpbis-cache-19, Section 5.4 */
+#define MHD_HTTP_HEADER_PRAGMA       "Pragma"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 11.7.1 */
+#define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 11.7.3 */
+#define MHD_HTTP_HEADER_PROXY_AUTHENTICATION_INFO "Proxy-Authentication-Info"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 11.7.2 */
+#define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization"
+/* Permanent.     RFC-ietf-httpbis-proxy-status-08 */
+#define MHD_HTTP_HEADER_PROXY_STATUS "Proxy-Status"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 14.2 */
+#define MHD_HTTP_HEADER_RANGE        "Range"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.1.3 */
+#define MHD_HTTP_HEADER_REFERER      "Referer"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.2.3 */
+#define MHD_HTTP_HEADER_RETRY_AFTER  "Retry-After"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.2.4 */
+#define MHD_HTTP_HEADER_SERVER       "Server"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.1.4 */
+#define MHD_HTTP_HEADER_TE           "TE"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 6.6.2 */
+#define MHD_HTTP_HEADER_TRAILER      "Trailer"
+/* Permanent.     RFC-ietf-httpbis-messaging-19, Section 6.1 */
+#define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 7.8 */
+#define MHD_HTTP_HEADER_UPGRADE      "Upgrade"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 10.1.5 */
+#define MHD_HTTP_HEADER_USER_AGENT   "User-Agent"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 12.5.5 */
+#define MHD_HTTP_HEADER_VARY         "Vary"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 7.6.3 */
+#define MHD_HTTP_HEADER_VIA          "Via"
+/* Obsoleted.     RFC-ietf-httpbis-cache-19, Section 5.5 */
+#define MHD_HTTP_HEADER_WARNING      "Warning"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 11.6.1 */
+#define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate"
+/* Permanent.     RFC-ietf-httpbis-semantics-19, Section 12.5.5 */
+#define MHD_HTTP_HEADER_ASTERISK     "*"
+
+/* Additional HTTP headers. */
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_A_IM         "A-IM"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_ACCEPT_ADDITIONS "Accept-Additions"
+/* Permanent.     RFC8942, Section 3.1 */
+#define MHD_HTTP_HEADER_ACCEPT_CH    "Accept-CH"
+/* Permanent.     RFC7089 */
+#define MHD_HTTP_HEADER_ACCEPT_DATETIME "Accept-Datetime"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_ACCEPT_FEATURES "Accept-Features"
+/* Permanent.     https://www.w3.org/TR/ldp/ */
+#define MHD_HTTP_HEADER_ACCEPT_POST  "Accept-Post"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-allow-credentials */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS \
+  "Access-Control-Allow-Credentials"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-allow-headers */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS \
+  "Access-Control-Allow-Headers"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-allow-methods */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_METHODS \
+  "Access-Control-Allow-Methods"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-allow-origin */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN \
+  "Access-Control-Allow-Origin"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-expose-headers */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS \
+  "Access-Control-Expose-Headers"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-max-age */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_MAX_AGE "Access-Control-Max-Age"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-request-headers */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_REQUEST_HEADERS \
+  "Access-Control-Request-Headers"
+/* Permanent.     https://fetch.spec.whatwg.org/#http-access-control-request-method */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_REQUEST_METHOD \
+  "Access-Control-Request-Method"
+/* Permanent.     RFC7639, Section 2 */
+#define MHD_HTTP_HEADER_ALPN         "ALPN"
+/* Permanent.     RFC7838 */
+#define MHD_HTTP_HEADER_ALT_SVC      "Alt-Svc"
+/* Permanent.     RFC7838 */
+#define MHD_HTTP_HEADER_ALT_USED     "Alt-Used"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_ALTERNATES   "Alternates"
+/* Permanent.     RFC4437 */
+#define MHD_HTTP_HEADER_APPLY_TO_REDIRECT_REF "Apply-To-Redirect-Ref"
+/* Permanent.     RFC8053, Section 4 */
+#define MHD_HTTP_HEADER_AUTHENTICATION_CONTROL "Authentication-Control"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_C_EXT        "C-Ext"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_C_MAN        "C-Man"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_C_OPT        "C-Opt"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_C_PEP        "C-PEP"
+/* Permanent.     RFC8607, Section 5.1 */
+#define MHD_HTTP_HEADER_CAL_MANAGED_ID "Cal-Managed-ID"
+/* Permanent.     RFC7809, Section 7.1 */
+#define MHD_HTTP_HEADER_CALDAV_TIMEZONES "CalDAV-Timezones"
+/* Permanent.     RFC8586 */
+#define MHD_HTTP_HEADER_CDN_LOOP     "CDN-Loop"
+/* Permanent.     RFC8739, Section 3.3 */
+#define MHD_HTTP_HEADER_CERT_NOT_AFTER "Cert-Not-After"
+/* Permanent.     RFC8739, Section 3.3 */
+#define MHD_HTTP_HEADER_CERT_NOT_BEFORE "Cert-Not-Before"
+/* Permanent.     RFC6266 */
+#define MHD_HTTP_HEADER_CONTENT_DISPOSITION "Content-Disposition"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_ID   "Content-ID"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_SCRIPT_TYPE "Content-Script-Type"
+/* Permanent.     https://www.w3.org/TR/CSP/#csp-header */
+#define MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY "Content-Security-Policy"
+/* Permanent.     https://www.w3.org/TR/CSP/#cspro-header */
+#define MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY_REPORT_ONLY \
+  "Content-Security-Policy-Report-Only"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_STYLE_TYPE "Content-Style-Type"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_VERSION "Content-Version"
+/* Permanent.     RFC6265 */
+#define MHD_HTTP_HEADER_COOKIE       "Cookie"
+/* Permanent.     https://html.spec.whatwg.org/multipage/origin.html#cross-origin-embedder-policy */
+#define MHD_HTTP_HEADER_CROSS_ORIGIN_EMBEDDER_POLICY \
+  "Cross-Origin-Embedder-Policy"
+/* Permanent.     https://html.spec.whatwg.org/multipage/origin.html#cross-origin-embedder-policy-report-only */
+#define MHD_HTTP_HEADER_CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY \
+  "Cross-Origin-Embedder-Policy-Report-Only"
+/* Permanent.     https://html.spec.whatwg.org/multipage/origin.html#cross-origin-opener-policy-2 */
+#define MHD_HTTP_HEADER_CROSS_ORIGIN_OPENER_POLICY "Cross-Origin-Opener-Policy"
+/* Permanent.     https://html.spec.whatwg.org/multipage/origin.html#cross-origin-opener-policy-report-only */
+#define MHD_HTTP_HEADER_CROSS_ORIGIN_OPENER_POLICY_REPORT_ONLY \
+  "Cross-Origin-Opener-Policy-Report-Only"
+/* Permanent.     https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header */
+#define MHD_HTTP_HEADER_CROSS_ORIGIN_RESOURCE_POLICY \
+  "Cross-Origin-Resource-Policy"
+/* Permanent.     RFC5323 */
+#define MHD_HTTP_HEADER_DASL         "DASL"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_DAV          "DAV"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_DEFAULT_STYLE "Default-Style"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_DELTA_BASE   "Delta-Base"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_DEPTH        "Depth"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_DERIVED_FROM "Derived-From"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_DESTINATION  "Destination"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_DIFFERENTIAL_ID "Differential-ID"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_DIGEST       "Digest"
+/* Permanent.     RFC8470 */
+#define MHD_HTTP_HEADER_EARLY_DATA   "Early-Data"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_EXT          "Ext"
+/* Permanent.     RFC7239 */
+#define MHD_HTTP_HEADER_FORWARDED    "Forwarded"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_GETPROFILE   "GetProfile"
+/* Permanent.     RFC7486, Section 6.1.1 */
+#define MHD_HTTP_HEADER_HOBAREG      "Hobareg"
+/* Permanent.     RFC7540, Section 3.2.1 */
+#define MHD_HTTP_HEADER_HTTP2_SETTINGS "HTTP2-Settings"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_IF           "If"
+/* Permanent.     RFC6638 */
+#define MHD_HTTP_HEADER_IF_SCHEDULE_TAG_MATCH "If-Schedule-Tag-Match"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_IM           "IM"
+/* Permanent.     RFC8473 */
+#define MHD_HTTP_HEADER_INCLUDE_REFERRED_TOKEN_BINDING_ID \
+  "Include-Referred-Token-Binding-ID"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_KEEP_ALIVE   "Keep-Alive"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_LABEL        "Label"
+/* Permanent.     https://html.spec.whatwg.org/multipage/server-sent-events.html#last-event-id */
+#define MHD_HTTP_HEADER_LAST_EVENT_ID "Last-Event-ID"
+/* Permanent.     RFC8288 */
+#define MHD_HTTP_HEADER_LINK         "Link"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_LOCK_TOKEN   "Lock-Token"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_MAN          "Man"
+/* Permanent.     RFC7089 */
+#define MHD_HTTP_HEADER_MEMENTO_DATETIME "Memento-Datetime"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_METER        "Meter"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_NEGOTIATE    "Negotiate"
+/* Permanent.     OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_ODATA_ENTITYID "OData-EntityId"
+/* Permanent.     OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_ODATA_ISOLATION "OData-Isolation"
+/* Permanent.     OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_ODATA_MAXVERSION "OData-MaxVersion"
+/* Permanent.     OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_ODATA_VERSION "OData-Version"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_OPT          "Opt"
+/* Permanent.     RFC8053, Section 3 */
+#define MHD_HTTP_HEADER_OPTIONAL_WWW_AUTHENTICATE "Optional-WWW-Authenticate"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_ORDERING_TYPE "Ordering-Type"
+/* Permanent.     RFC6454 */
+#define MHD_HTTP_HEADER_ORIGIN       "Origin"
+/* Permanent.     https://html.spec.whatwg.org/multipage/origin.html#origin-agent-cluster */
+#define MHD_HTTP_HEADER_ORIGIN_AGENT_CLUSTER "Origin-Agent-Cluster"
+/* Permanent.     RFC8613, Section 11.1 */
+#define MHD_HTTP_HEADER_OSCORE       "OSCORE"
+/* Permanent.     OASIS Project Specification 01; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_OSLC_CORE_VERSION "OSLC-Core-Version"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_OVERWRITE    "Overwrite"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_P3P          "P3P"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PEP          "PEP"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PEP_INFO     "Pep-Info"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PICS_LABEL   "PICS-Label"
+/* Permanent.     https://html.spec.whatwg.org/multipage/links.html#ping-from */
+#define MHD_HTTP_HEADER_PING_FROM    "Ping-From"
+/* Permanent.     https://html.spec.whatwg.org/multipage/links.html#ping-to */
+#define MHD_HTTP_HEADER_PING_TO      "Ping-To"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_POSITION     "Position"
+/* Permanent.     RFC7240 */
+#define MHD_HTTP_HEADER_PREFER       "Prefer"
+/* Permanent.     RFC7240 */
+#define MHD_HTTP_HEADER_PREFERENCE_APPLIED "Preference-Applied"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PROFILEOBJECT "ProfileObject"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL     "Protocol"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL_REQUEST "Protocol-Request"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PROXY_FEATURES "Proxy-Features"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PROXY_INSTRUCTION "Proxy-Instruction"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_PUBLIC       "Public"
+/* Permanent.     RFC7469 */
+#define MHD_HTTP_HEADER_PUBLIC_KEY_PINS "Public-Key-Pins"
+/* Permanent.     RFC7469 */
+#define MHD_HTTP_HEADER_PUBLIC_KEY_PINS_REPORT_ONLY \
+  "Public-Key-Pins-Report-Only"
+/* Permanent.     RFC4437 */
+#define MHD_HTTP_HEADER_REDIRECT_REF "Redirect-Ref"
+/* Permanent.     https://html.spec.whatwg.org/multipage/browsing-the-web.html#refresh */
+#define MHD_HTTP_HEADER_REFRESH      "Refresh"
+/* Permanent.     RFC8555, Section 6.5.1 */
+#define MHD_HTTP_HEADER_REPLAY_NONCE "Replay-Nonce"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_SAFE         "Safe"
+/* Permanent.     RFC6638 */
+#define MHD_HTTP_HEADER_SCHEDULE_REPLY "Schedule-Reply"
+/* Permanent.     RFC6638 */
+#define MHD_HTTP_HEADER_SCHEDULE_TAG "Schedule-Tag"
+/* Permanent.     RFC8473 */
+#define MHD_HTTP_HEADER_SEC_TOKEN_BINDING "Sec-Token-Binding"
+/* Permanent.     RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept"
+/* Permanent.     RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions"
+/* Permanent.     RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key"
+/* Permanent.     RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol"
+/* Permanent.     RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_SECURITY_SCHEME "Security-Scheme"
+/* Permanent.     https://www.w3.org/TR/server-timing/ */
+#define MHD_HTTP_HEADER_SERVER_TIMING "Server-Timing"
+/* Permanent.     RFC6265 */
+#define MHD_HTTP_HEADER_SET_COOKIE   "Set-Cookie"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_SETPROFILE   "SetProfile"
+/* Permanent.     RFC5023 */
+#define MHD_HTTP_HEADER_SLUG         "SLUG"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_SOAPACTION   "SoapAction"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_STATUS_URI   "Status-URI"
+/* Permanent.     RFC6797 */
+#define MHD_HTTP_HEADER_STRICT_TRANSPORT_SECURITY "Strict-Transport-Security"
+/* Permanent.     RFC8594 */
+#define MHD_HTTP_HEADER_SUNSET       "Sunset"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_SURROGATE_CAPABILITY "Surrogate-Capability"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_SURROGATE_CONTROL "Surrogate-Control"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_TCN          "TCN"
+/* Permanent.     RFC4918 */
+#define MHD_HTTP_HEADER_TIMEOUT      "Timeout"
+/* Permanent.     RFC8030, Section 5.4 */
+#define MHD_HTTP_HEADER_TOPIC        "Topic"
+/* Permanent.     RFC8030, Section 5.2 */
+#define MHD_HTTP_HEADER_TTL          "TTL"
+/* Permanent.     RFC8030, Section 5.3 */
+#define MHD_HTTP_HEADER_URGENCY      "Urgency"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_URI          "URI"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_VARIANT_VARY "Variant-Vary"
+/* Permanent.     RFC4229 */
+#define MHD_HTTP_HEADER_WANT_DIGEST  "Want-Digest"
+/* Permanent.     https://fetch.spec.whatwg.org/#x-content-type-options-header */
+#define MHD_HTTP_HEADER_X_CONTENT_TYPE_OPTIONS "X-Content-Type-Options"
+/* Permanent.     https://html.spec.whatwg.org/multipage/browsing-the-web.html#x-frame-options */
+#define MHD_HTTP_HEADER_X_FRAME_OPTIONS "X-Frame-Options"
+/* Provisional.   RFC5789 */
+#define MHD_HTTP_HEADER_ACCEPT_PATCH "Accept-Patch"
+/* Provisional.   https://github.com/ampproject/amphtml/blob/master/spec/amp-cache-transform.md */
+#define MHD_HTTP_HEADER_AMP_CACHE_TRANSFORM "AMP-Cache-Transform"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_COMPLIANCE   "Compliance"
+/* Provisional.   https://docs.oasis-open-projects.org/oslc-op/config/v1.0/psd01/config-resources.html#configcontext */
+#define MHD_HTTP_HEADER_CONFIGURATION_CONTEXT "Configuration-Context"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_TRANSFER_ENCODING "Content-Transfer-Encoding"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_COST         "Cost"
+/* Provisional.   RFC6017 */
+#define MHD_HTTP_HEADER_EDIINT_FEATURES "EDIINT-Features"
+/* Provisional.   OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_ISOLATION    "Isolation"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_MESSAGE_ID   "Message-ID"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_NON_COMPLIANCE "Non-Compliance"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_OPTIONAL     "Optional"
+/* Provisional.   Repeatable Requests Version 1.0; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_REPEATABILITY_CLIENT_ID "Repeatability-Client-ID"
+/* Provisional.   Repeatable Requests Version 1.0; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_REPEATABILITY_FIRST_SENT "Repeatability-First-Sent"
+/* Provisional.   Repeatable Requests Version 1.0; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_REPEATABILITY_REQUEST_ID "Repeatability-Request-ID"
+/* Provisional.   Repeatable Requests Version 1.0; OASIS; Chet_Ensign */
+#define MHD_HTTP_HEADER_REPEATABILITY_RESULT "Repeatability-Result"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_RESOLUTION_HINT "Resolution-Hint"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_RESOLVER_LOCATION "Resolver-Location"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_SUBOK        "SubOK"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_SUBST        "Subst"
+/* Provisional.   https://www.w3.org/TR/resource-timing-1/#timing-allow-origin */
+#define MHD_HTTP_HEADER_TIMING_ALLOW_ORIGIN "Timing-Allow-Origin"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_TITLE        "Title"
+/* Provisional.   https://www.w3.org/TR/trace-context/#traceparent-field */
+#define MHD_HTTP_HEADER_TRACEPARENT  "Traceparent"
+/* Provisional.   https://www.w3.org/TR/trace-context/#tracestate-field */
+#define MHD_HTTP_HEADER_TRACESTATE   "Tracestate"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_UA_COLOR     "UA-Color"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_UA_MEDIA     "UA-Media"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_UA_PIXELS    "UA-Pixels"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_UA_RESOLUTION "UA-Resolution"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_UA_WINDOWPIXELS "UA-Windowpixels"
+/* Provisional.   RFC4229 */
+#define MHD_HTTP_HEADER_VERSION      "Version"
+/* Provisional.   W3C Mobile Web Best Practices Working Group */
+#define MHD_HTTP_HEADER_X_DEVICE_ACCEPT "X-Device-Accept"
+/* Provisional.   W3C Mobile Web Best Practices Working Group */
+#define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_CHARSET "X-Device-Accept-Charset"
+/* Provisional.   W3C Mobile Web Best Practices Working Group */
+#define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_ENCODING "X-Device-Accept-Encoding"
+/* Provisional.   W3C Mobile Web Best Practices Working Group */
+#define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_LANGUAGE "X-Device-Accept-Language"
+/* Provisional.   W3C Mobile Web Best Practices Working Group */
+#define MHD_HTTP_HEADER_X_DEVICE_USER_AGENT "X-Device-User-Agent"
+/* Deprecated.    RFC4229 */
+#define MHD_HTTP_HEADER_C_PEP_INFO   "C-PEP-Info"
+/* Deprecated.    RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL_INFO "Protocol-Info"
+/* Deprecated.    RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL_QUERY "Protocol-Query"
+/* Obsoleted.     https://www.w3.org/TR/2007/WD-access-control-20071126/#access-control0 */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL "Access-Control"
+/* Obsoleted.     RFC2068; RFC2616 */
+#define MHD_HTTP_HEADER_CONTENT_BASE "Content-Base"
+/* Obsoleted.     RFC2616, Section 14.15; RFC7231, Appendix B */
+#define MHD_HTTP_HEADER_CONTENT_MD5  "Content-MD5"
+/* Obsoleted.     RFC2965; RFC6265 */
+#define MHD_HTTP_HEADER_COOKIE2      "Cookie2"
+/* Obsoleted.     https://www.w3.org/TR/2007/WD-access-control-20071126/#method-check */
+#define MHD_HTTP_HEADER_METHOD_CHECK "Method-Check"
+/* Obsoleted.     https://www.w3.org/TR/2007/WD-access-control-20071126/#method-check-expires */
+#define MHD_HTTP_HEADER_METHOD_CHECK_EXPIRES "Method-Check-Expires"
+/* Obsoleted.     https://www.w3.org/TR/2007/WD-access-control-20071126/#referer-root */
+#define MHD_HTTP_HEADER_REFERER_ROOT "Referer-Root"
+/* Obsoleted.     RFC2965; RFC6265 */
+#define MHD_HTTP_HEADER_SET_COOKIE2  "Set-Cookie2"
+
+/* Some provisional headers. */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN \
+  "Access-Control-Allow-Origin"
 /** @} */ /* end of group headers */
 
 /**
@@ -370,18 +1063,95 @@
 
 /**
  * @defgroup methods HTTP methods
- * Standard HTTP methods (as strings).
+ * HTTP methods (as strings).
+ * See: http://www.iana.org/assignments/http-methods/http-methods.xml
+ * Registry export date: 2021-12-19
  * @{
  */
-#define MHD_HTTP_METHOD_CONNECT "CONNECT"
-#define MHD_HTTP_METHOD_DELETE "DELETE"
-#define MHD_HTTP_METHOD_GET "GET"
-#define MHD_HTTP_METHOD_HEAD "HEAD"
-#define MHD_HTTP_METHOD_OPTIONS "OPTIONS"
-#define MHD_HTTP_METHOD_POST "POST"
-#define MHD_HTTP_METHOD_PUT "PUT"
-#define MHD_HTTP_METHOD_PATCH "PATCH"
-#define MHD_HTTP_METHOD_TRACE "TRACE"
+
+/* Main HTTP methods. */
+/* Not safe. Not idempotent. RFC-ietf-httpbis-semantics, Section 9.3.6. */
+#define MHD_HTTP_METHOD_CONNECT  "CONNECT"
+/* Not safe. Idempotent.     RFC-ietf-httpbis-semantics, Section 9.3.5. */
+#define MHD_HTTP_METHOD_DELETE   "DELETE"
+/* Safe.     Idempotent.     RFC-ietf-httpbis-semantics, Section 9.3.1. */
+#define MHD_HTTP_METHOD_GET      "GET"
+/* Safe.     Idempotent.     RFC-ietf-httpbis-semantics, Section 9.3.2. */
+#define MHD_HTTP_METHOD_HEAD     "HEAD"
+/* Safe.     Idempotent.     RFC-ietf-httpbis-semantics, Section 9.3.7. */
+#define MHD_HTTP_METHOD_OPTIONS  "OPTIONS"
+/* Not safe. Not idempotent. RFC-ietf-httpbis-semantics, Section 9.3.3. */
+#define MHD_HTTP_METHOD_POST     "POST"
+/* Not safe. Idempotent.     RFC-ietf-httpbis-semantics, Section 9.3.4. */
+#define MHD_HTTP_METHOD_PUT      "PUT"
+/* Safe.     Idempotent.     RFC-ietf-httpbis-semantics, Section 9.3.8. */
+#define MHD_HTTP_METHOD_TRACE    "TRACE"
+/* Not safe. Not idempotent. RFC-ietf-httpbis-semantics, Section 18.2. */
+#define MHD_HTTP_METHOD_ASTERISK "*"
+
+/* Additional HTTP methods. */
+/* Not safe. Idempotent.     RFC3744, Section 8.1. */
+#define MHD_HTTP_METHOD_ACL            "ACL"
+/* Not safe. Idempotent.     RFC3253, Section 12.6. */
+#define MHD_HTTP_METHOD_BASELINE_CONTROL "BASELINE-CONTROL"
+/* Not safe. Idempotent.     RFC5842, Section 4. */
+#define MHD_HTTP_METHOD_BIND           "BIND"
+/* Not safe. Idempotent.     RFC3253, Section 4.4, Section 9.4. */
+#define MHD_HTTP_METHOD_CHECKIN        "CHECKIN"
+/* Not safe. Idempotent.     RFC3253, Section 4.3, Section 8.8. */
+#define MHD_HTTP_METHOD_CHECKOUT       "CHECKOUT"
+/* Not safe. Idempotent.     RFC4918, Section 9.8. */
+#define MHD_HTTP_METHOD_COPY           "COPY"
+/* Not safe. Idempotent.     RFC3253, Section 8.2. */
+#define MHD_HTTP_METHOD_LABEL          "LABEL"
+/* Not safe. Idempotent.     RFC2068, Section 19.6.1.2. */
+#define MHD_HTTP_METHOD_LINK           "LINK"
+/* Not safe. Not idempotent. RFC4918, Section 9.10. */
+#define MHD_HTTP_METHOD_LOCK           "LOCK"
+/* Not safe. Idempotent.     RFC3253, Section 11.2. */
+#define MHD_HTTP_METHOD_MERGE          "MERGE"
+/* Not safe. Idempotent.     RFC3253, Section 13.5. */
+#define MHD_HTTP_METHOD_MKACTIVITY     "MKACTIVITY"
+/* Not safe. Idempotent.     RFC4791, Section 5.3.1; RFC8144, Section 2.3. */
+#define MHD_HTTP_METHOD_MKCALENDAR     "MKCALENDAR"
+/* Not safe. Idempotent.     RFC4918, Section 9.3; RFC5689, Section 3; RFC8144, Section 2.3. */
+#define MHD_HTTP_METHOD_MKCOL          "MKCOL"
+/* Not safe. Idempotent.     RFC4437, Section 6. */
+#define MHD_HTTP_METHOD_MKREDIRECTREF  "MKREDIRECTREF"
+/* Not safe. Idempotent.     RFC3253, Section 6.3. */
+#define MHD_HTTP_METHOD_MKWORKSPACE    "MKWORKSPACE"
+/* Not safe. Idempotent.     RFC4918, Section 9.9. */
+#define MHD_HTTP_METHOD_MOVE           "MOVE"
+/* Not safe. Idempotent.     RFC3648, Section 7. */
+#define MHD_HTTP_METHOD_ORDERPATCH     "ORDERPATCH"
+/* Not safe. Not idempotent. RFC5789, Section 2. */
+#define MHD_HTTP_METHOD_PATCH          "PATCH"
+/* Safe.     Idempotent.     RFC7540, Section 3.5. */
+#define MHD_HTTP_METHOD_PRI            "PRI"
+/* Safe.     Idempotent.     RFC4918, Section 9.1; RFC8144, Section 2.1. */
+#define MHD_HTTP_METHOD_PROPFIND       "PROPFIND"
+/* Not safe. Idempotent.     RFC4918, Section 9.2; RFC8144, Section 2.2. */
+#define MHD_HTTP_METHOD_PROPPATCH      "PROPPATCH"
+/* Not safe. Idempotent.     RFC5842, Section 6. */
+#define MHD_HTTP_METHOD_REBIND         "REBIND"
+/* Safe.     Idempotent.     RFC3253, Section 3.6; RFC8144, Section 2.1. */
+#define MHD_HTTP_METHOD_REPORT         "REPORT"
+/* Safe.     Idempotent.     RFC5323, Section 2. */
+#define MHD_HTTP_METHOD_SEARCH         "SEARCH"
+/* Not safe. Idempotent.     RFC5842, Section 5. */
+#define MHD_HTTP_METHOD_UNBIND         "UNBIND"
+/* Not safe. Idempotent.     RFC3253, Section 4.5. */
+#define MHD_HTTP_METHOD_UNCHECKOUT     "UNCHECKOUT"
+/* Not safe. Idempotent.     RFC2068, Section 19.6.1.3. */
+#define MHD_HTTP_METHOD_UNLINK         "UNLINK"
+/* Not safe. Idempotent.     RFC4918, Section 9.11. */
+#define MHD_HTTP_METHOD_UNLOCK         "UNLOCK"
+/* Not safe. Idempotent.     RFC3253, Section 7.1. */
+#define MHD_HTTP_METHOD_UPDATE         "UPDATE"
+/* Not safe. Idempotent.     RFC4437, Section 7. */
+#define MHD_HTTP_METHOD_UPDATEREDIRECTREF "UPDATEREDIRECTREF"
+/* Not safe. Idempotent.     RFC3253, Section 3.5. */
+#define MHD_HTTP_METHOD_VERSION_CONTROL "VERSION-CONTROL"
 
 /** @} */ /* end of group methods */
 
@@ -390,7 +1160,8 @@
  * See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
  * @{
  */
-#define MHD_HTTP_POST_ENCODING_FORM_URLENCODED "application/x-www-form-urlencoded"
+#define MHD_HTTP_POST_ENCODING_FORM_URLENCODED \
+  "application/x-www-form-urlencoded"
 #define MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data"
 
 /** @} */ /* end of group postenc */
@@ -428,13 +1199,14 @@
 /**
  * @brief Flags for the `struct MHD_Daemon`.
  *
- * Note that if neither #MHD_USE_THREAD_PER_CONNECTION nor
- * #MHD_USE_SELECT_INTERNALLY is used, the client wants control over
- * the process and will call the appropriate microhttpd callbacks.
+ * Note that MHD will run automatically in background thread(s) only
+ * if #MHD_USE_INTERNAL_POLLING_THREAD is used. Otherwise caller (application)
+ * must use #MHD_run() or #MHD_run_from_select() to have MHD processed
+ * network connections and data.
  *
  * Starting the daemon may also fail if a particular option is not
  * implemented or not supported on the target platform (i.e. no
- * support for SSL, threads or IPv6).
+ * support for TLS, epoll or IPv6).
  */
 enum MHD_FLAG
 {
@@ -444,25 +1216,63 @@
   MHD_NO_FLAG = 0,
 
   /**
+   * Print errors messages to custom error logger or to `stderr` if
+   * custom error logger is not set.
+   * @sa ::MHD_OPTION_EXTERNAL_LOGGER
+   */
+  MHD_USE_ERROR_LOG = 1,
+
+  /**
    * Run in debug mode.  If this flag is used, the library should
    * print error messages and warnings to `stderr`.
    */
   MHD_USE_DEBUG = 1,
 
   /**
-   * Run in HTTPS mode.
+   * Run in HTTPS mode.  The modern protocol is called TLS.
    */
+  MHD_USE_TLS = 2,
+
+  /** @deprecated */
   MHD_USE_SSL = 2,
+#if 0
+  /* let's do this later once versions that define MHD_USE_TLS a more widely deployed. */
+#define MHD_USE_SSL \
+  _MHD_DEPR_IN_MACRO ("Value MHD_USE_SSL is deprecated, use MHD_USE_TLS") \
+  MHD_USE_TLS
+#endif
 
   /**
    * Run using one thread per connection.
+   * Must be used only with #MHD_USE_INTERNAL_POLLING_THREAD.
+   *
+   * If #MHD_USE_ITC is also not used, closed and expired connections may only
+   * be cleaned up internally when a new connection is received.
+   * Consider adding of #MHD_USE_ITC flag to have faster internal cleanups
+   * at very minor increase in system resources usage.
    */
   MHD_USE_THREAD_PER_CONNECTION = 4,
 
   /**
-   * Run using an internal thread (or thread pool) doing `select()`.
+   * Run using an internal thread (or thread pool) for sockets sending
+   * and receiving and data processing. Without this flag MHD will not
+   * run automatically in background thread(s).
+   * If this flag is set, #MHD_run() and #MHD_run_from_select() couldn't
+   * be used.
+   * This flag is set explicitly by #MHD_USE_POLL_INTERNAL_THREAD and
+   * by #MHD_USE_EPOLL_INTERNAL_THREAD.
+   * When this flag is not set, MHD run in "external" polling mode.
    */
+  MHD_USE_INTERNAL_POLLING_THREAD = 8,
+
+  /** @deprecated */
   MHD_USE_SELECT_INTERNALLY = 8,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_SELECT_INTERNALLY \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_SELECT_INTERNALLY is deprecated, use MHD_USE_INTERNAL_POLLING_THREAD instead") \
+  MHD_USE_INTERNAL_POLLING_THREAD
+#endif /* 0 */
 
   /**
    * Run using the IPv6 protocol (otherwise, MHD will just support
@@ -481,22 +1291,42 @@
    * as liberal as possible in what you accept" norm.  It is
    * recommended to turn this ON if you are testing clients against
    * MHD, and OFF in production.
+   * @sa #MHD_OPTION_CLIENT_DISCIPLINE_LVL
    */
   MHD_USE_PEDANTIC_CHECKS = 32,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_PEDANTIC_CHECKS \
+  _MHD_DEPR_IN_MACRO ( \
+    "Flag MHD_USE_PEDANTIC_CHECKS is deprecated, " \
+    "use option MHD_OPTION_CLIENT_DISCIPLINE_LVL instead") \
+  32
+#endif /* 0 */
 
   /**
-   * Use `poll()` instead of `select()`. This allows sockets with `fd >=
-   * FD_SETSIZE`.  This option is not compatible with using an
-   * 'external' `select()` mode (as there is no API to get the file
-   * descriptors for the external select from MHD) and must also not
-   * be used in combination with #MHD_USE_EPOLL_LINUX_ONLY.
+   * Use `poll()` instead of `select()` for polling sockets.
+   * This allows sockets with `fd >= FD_SETSIZE`.
+   * This option is not compatible with an "external" polling mode
+   * (as there is no API to get the file descriptors for the external
+   * poll() from MHD) and must also not be used in combination
+   * with #MHD_USE_EPOLL.
+   * @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL_INTERNAL_THREAD
    */
   MHD_USE_POLL = 64,
 
   /**
    * Run using an internal thread (or thread pool) doing `poll()`.
+   * @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL, #MHD_USE_INTERNAL_POLLING_THREAD
    */
-  MHD_USE_POLL_INTERNALLY = MHD_USE_SELECT_INTERNALLY | MHD_USE_POLL,
+  MHD_USE_POLL_INTERNAL_THREAD = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD,
+
+  /** @deprecated */
+  MHD_USE_POLL_INTERNALLY = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_POLL_INTERNALLY \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_POLL_INTERNALLY is deprecated, use MHD_USE_POLL_INTERNAL_THREAD instead") \
+  MHD_USE_POLL_INTERNAL_THREAD
+#endif /* 0 */
 
   /**
    * Suppress (automatically) adding the 'Date:' header to HTTP responses.
@@ -504,7 +1334,16 @@
    * and that DO provide other mechanisms for cache control.  See also
    * RFC 2616, section 14.18 (exception 3).
    */
+  MHD_USE_SUPPRESS_DATE_NO_CLOCK = 128,
+
+  /** @deprecated */
   MHD_SUPPRESS_DATE_NO_CLOCK = 128,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_SUPPRESS_DATE_NO_CLOCK \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_SUPPRESS_DATE_NO_CLOCK is deprecated, use MHD_USE_SUPPRESS_DATE_NO_CLOCK instead") \
+  MHD_USE_SUPPRESS_DATE_NO_CLOCK
+#endif /* 0 */
 
   /**
    * Run without a listen socket.  This option only makes sense if
@@ -517,35 +1356,70 @@
 
   /**
    * Use `epoll()` instead of `select()` or `poll()` for the event loop.
-   * This option is only available on Linux; using the option on
-   * non-Linux systems will cause #MHD_start_daemon to fail.
+   * This option is only available on some systems; using the option on
+   * systems without epoll will cause #MHD_start_daemon to fail.  Using
+   * this option is not supported with #MHD_USE_THREAD_PER_CONNECTION.
+   * @sa ::MHD_FEATURE_EPOLL
    */
+  MHD_USE_EPOLL = 512,
+
+  /** @deprecated */
   MHD_USE_EPOLL_LINUX_ONLY = 512,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_EPOLL_LINUX_ONLY \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_EPOLL_LINUX_ONLY is deprecated, use MHD_USE_EPOLL") \
+  MHD_USE_EPOLL
+#endif /* 0 */
 
   /**
-   * Run using an internal thread (or thread pool) doing `epoll()`.
-   * This option is only available on Linux; using the option on
-   * non-Linux systems will cause #MHD_start_daemon to fail.
+   * Run using an internal thread (or thread pool) doing `epoll` polling.
+   * This option is only available on certain platforms; using the option on
+   * platform without `epoll` support will cause #MHD_start_daemon to fail.
+   * @sa ::MHD_FEATURE_EPOLL, #MHD_USE_EPOLL, #MHD_USE_INTERNAL_POLLING_THREAD
    */
-  MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY = MHD_USE_SELECT_INTERNALLY | MHD_USE_EPOLL_LINUX_ONLY,
+  MHD_USE_EPOLL_INTERNAL_THREAD = MHD_USE_EPOLL
+                                  | MHD_USE_INTERNAL_POLLING_THREAD,
+
+  /** @deprecated */
+  MHD_USE_EPOLL_INTERNALLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD,
+  /** @deprecated */
+  MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY = MHD_USE_EPOLL
+                                        | MHD_USE_INTERNAL_POLLING_THREAD,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_EPOLL_INTERNALLY \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_EPOLL_INTERNALLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \
+  MHD_USE_EPOLL_INTERNAL_THREAD
+  /** @deprecated */
+#define MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \
+  MHD_USE_EPOLL_INTERNAL_THREAD
+#endif /* 0 */
 
   /**
-   * Force MHD to use a signal pipe to notify the event loop (of
-   * threads) of our shutdown.  This is required if an appliction uses
-   * #MHD_USE_SELECT_INTERNALLY or #MHD_USE_THREAD_PER_CONNECTION and
-   * then performs #MHD_quiesce_daemon (which eliminates our ability
-   * to signal termination via the listen socket).  In these modes,
-   * #MHD_quiesce_daemon will fail if this option was not set.  Also,
-   * use of this option is automatic (as in, you do not even have to
-   * specify it), if #MHD_USE_NO_LISTEN_SOCKET is specified.  In
-   * "external" `select()` mode, this option is always simply ignored.
-   * MHD can be build for use a pair of sockets instead of a pipe.
-   * Pair of sockets is forced on W32.
-   *
-   * You must also use this option if you use internal select mode
-   * or a thread pool in conjunction with #MHD_add_connection.
+   * Use inter-thread communication channel.
+   * #MHD_USE_ITC can be used with #MHD_USE_INTERNAL_POLLING_THREAD
+   * and is ignored with any "external" sockets polling.
+   * It's required for use of #MHD_quiesce_daemon
+   * or #MHD_add_connection.
+   * This option is enforced by #MHD_ALLOW_SUSPEND_RESUME or
+   * #MHD_USE_NO_LISTEN_SOCKET.
+   * #MHD_USE_ITC is always used automatically on platforms
+   * where select()/poll()/other ignore shutdown of listen
+   * socket.
    */
+  MHD_USE_ITC = 1024,
+
+  /** @deprecated */
   MHD_USE_PIPE_FOR_SHUTDOWN = 1024,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_PIPE_FOR_SHUTDOWN \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_PIPE_FOR_SHUTDOWN is deprecated, use MHD_USE_ITC") \
+  MHD_USE_ITC
+#endif /* 0 */
 
   /**
    * Use a single socket for IPv4 and IPv6.
@@ -553,26 +1427,83 @@
   MHD_USE_DUAL_STACK = MHD_USE_IPv6 | 2048,
 
   /**
-   * Enable `epoll()` turbo.  Disables certain calls to `shutdown()`
-   * and enables aggressive non-blocking optimisitc reads.
-   * Most effects only happen with #MHD_USE_EPOLL_LINUX_ONLY.
-   * Enalbed always on W32 as winsock does not properly behave
-   * with `shutdown()` and this then fixes potential problems.
+   * Enable `turbo`.  Disables certain calls to `shutdown()`,
+   * enables aggressive non-blocking optimistic reads and
+   * other potentially unsafe optimizations.
+   * Most effects only happen with #MHD_USE_EPOLL.
    */
+  MHD_USE_TURBO = 4096,
+
+  /** @deprecated */
   MHD_USE_EPOLL_TURBO = 4096,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_EPOLL_TURBO \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_EPOLL_TURBO is deprecated, use MHD_USE_TURBO") \
+  MHD_USE_TURBO
+#endif /* 0 */
 
   /**
    * Enable suspend/resume functions, which also implies setting up
-   * pipes to signal resume.
+   * ITC to signal resume.
    */
-  MHD_USE_SUSPEND_RESUME = 8192 | MHD_USE_PIPE_FOR_SHUTDOWN,
+  MHD_ALLOW_SUSPEND_RESUME = 8192 | MHD_USE_ITC,
+
+  /** @deprecated */
+  MHD_USE_SUSPEND_RESUME = 8192 | MHD_USE_ITC,
+#if 0 /* Will be marked for real deprecation later. */
+#define MHD_USE_SUSPEND_RESUME \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_USE_SUSPEND_RESUME is deprecated, use MHD_ALLOW_SUSPEND_RESUME instead") \
+  MHD_ALLOW_SUSPEND_RESUME
+#endif /* 0 */
 
   /**
    * Enable TCP_FASTOPEN option.  This option is only available on Linux with a
    * kernel >= 3.6.  On other systems, using this option cases #MHD_start_daemon
    * to fail.
    */
-  MHD_USE_TCP_FASTOPEN = 16384
+  MHD_USE_TCP_FASTOPEN = 16384,
+
+  /**
+   * You need to set this option if you want to use HTTP "Upgrade".
+   * "Upgrade" may require usage of additional internal resources,
+   * which we do not want to use unless necessary.
+   */
+  MHD_ALLOW_UPGRADE = 32768,
+
+  /**
+   * Automatically use best available polling function.
+   * Choice of polling function is also depend on other daemon options.
+   * If #MHD_USE_INTERNAL_POLLING_THREAD is specified then epoll, poll() or
+   * select() will be used (listed in decreasing preference order, first
+   * function available on system will be used).
+   * If #MHD_USE_THREAD_PER_CONNECTION is specified then poll() or select()
+   * will be used.
+   * If those flags are not specified then epoll or select() will be
+   * used (as the only suitable for MHD_get_fdset())
+   */
+  MHD_USE_AUTO = 65536,
+
+  /**
+   * Run using an internal thread (or thread pool) with best available on
+   * system polling function.
+   * This is combination of #MHD_USE_AUTO and #MHD_USE_INTERNAL_POLLING_THREAD
+   * flags.
+   */
+  MHD_USE_AUTO_INTERNAL_THREAD = MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+
+  /**
+   * Flag set to enable post-handshake client authentication
+   * (only useful in combination with #MHD_USE_TLS).
+   */
+  MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT = 1U << 17,
+
+  /**
+   * Flag set to enable TLS 1.3 early data.  This has
+   * security implications, be VERY careful when using this.
+   */
+  MHD_USE_INSECURE_TLS_EARLY_DATA = 1U << 18
 
 };
 
@@ -585,10 +1516,97 @@
  * @param ap arguments to @a fm
  * @ingroup logging
  */
-typedef void (*MHD_LogCallback)(void *cls, const char *fm, va_list ap);
+typedef void
+(*MHD_LogCallback)(void *cls,
+                   const char *fm,
+                   va_list ap);
 
 
 /**
+ * Function called to lookup the pre shared key (@a psk) for a given
+ * HTTP connection based on the @a username.
+ *
+ * @param cls closure
+ * @param connection the HTTPS connection
+ * @param username the user name claimed by the other side
+ * @param[out] psk to be set to the pre-shared-key; should be allocated with malloc(),
+ *                 will be freed by MHD
+ * @param[out] psk_size to be set to the number of bytes in @a psk
+ * @return 0 on success, -1 on errors
+ */
+typedef int
+(*MHD_PskServerCredentialsCallback)(void *cls,
+                                    const struct MHD_Connection *connection,
+                                    const char *username,
+                                    void **psk,
+                                    size_t *psk_size);
+
+/**
+ * Values for #MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE.
+ *
+ * These values can limit the scope of validity of MHD-generated nonces.
+ * Values can be combined with bitwise OR.
+ * Any value, except #MHD_DAUTH_BIND_NONCE_NONE, enforce function
+ * #MHD_digest_auth_check3() (and similar functions) to check nonce by
+ * re-generating it again with the same parameters, which is CPU-intensive
+ * operation.
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DAuthBindNonce
+{
+  /**
+   * Generated nonces are valid for any request from any client until expired.
+   * This is default and recommended value.
+   * #MHD_digest_auth_check3() (and similar functions) would check only whether
+   * the nonce value that is used by client has been generated by MHD and not
+   * expired yet.
+   * It is recommended because RFC 7616 allows clients to use the same nonce
+   * for any request in the same "protection space".
+   * When checking client's authorisation requests CPU is loaded less if this
+   * value is used.
+   * This mode gives MHD maximum flexibility for nonces generation and can
+   * prevent possible nonce collisions (and corresponding log warning messages)
+   * when clients' requests are intensive.
+   * This value cannot be biwise-OR combined with other values.
+   */
+  MHD_DAUTH_BIND_NONCE_NONE = 0,
+
+  /**
+   * Generated nonces are valid only for the same realm.
+   */
+  MHD_DAUTH_BIND_NONCE_REALM = 1 << 0,
+
+  /**
+   * Generated nonces are valid only for the same URI (excluding parameters
+   * after '?' in URI) and request method (GET, POST etc).
+   * Not recommended unless "protection space" is limited to a single URI as
+   * RFC 7616 allows clients to re-use server-generated nonces for any URI
+   * in the same "protection space" which by default consists of all server
+   * URIs.
+   * Before #MHD_VERSION 0x00097601 this was default (and only supported)
+   * nonce bind type.
+   */
+  MHD_DAUTH_BIND_NONCE_URI = 1 << 1,
+
+  /**
+   * Generated nonces are valid only for the same URI including URI parameters
+   * and request method (GET, POST etc).
+   * This value implies #MHD_DAUTH_BIND_NONCE_URI.
+   * Not recommended for that same reasons as #MHD_DAUTH_BIND_NONCE_URI.
+   */
+  MHD_DAUTH_BIND_NONCE_URI_PARAMS = 1 << 2,
+
+  /**
+   * Generated nonces are valid only for the single client's IP.
+   * While it looks like security improvement, in practice the same client may
+   * jump from one IP to another (mobile or Wi-Fi handover, DHCP re-assignment,
+   * Multi-NAT, different proxy chain and other reasons), while IP address
+   * spoofing could be used relatively easily.
+   */
+  MHD_DAUTH_BIND_NONCE_CLIENT_IP = 1 << 3
+} _MHD_FLAGS_ENUM;
+
+/**
  * @brief MHD options.
  *
  * Passed in the varargs portion of #MHD_start_daemon.
@@ -621,6 +1639,8 @@
    * After how many seconds of inactivity should a
    * connection automatically be timed out? (followed
    * by an `unsigned int`; use zero for no timeout).
+   * Values larger than (UINT64_MAX / 2000 - 1) will
+   * be clipped to this number.
    */
   MHD_OPTION_CONNECTION_TIMEOUT = 3,
 
@@ -634,7 +1654,7 @@
    * This option should be followed by TWO pointers.  First a pointer
    * to a function of type #MHD_RequestCompletedCallback and second a
    * pointer to a closure to pass to the request completed callback.
-   * The second pointer maybe NULL.
+   * The second pointer may be NULL.
    */
   MHD_OPTION_NOTIFY_COMPLETED = 4,
 
@@ -669,20 +1689,24 @@
    *     void * my_logger(void *cls, const char *uri, struct MHD_Connection *con)
    *
    * where the return value will be passed as
-   * (`* con_cls`) in calls to the #MHD_AccessHandlerCallback
+   * (`* req_cls`) in calls to the #MHD_AccessHandlerCallback
    * when this request is processed later; returning a
    * value of NULL has no special significance (however,
    * note that if you return non-NULL, you can no longer
    * rely on the first call to the access handler having
-   * `NULL == *con_cls` on entry;)
+   * `NULL == *req_cls` on entry;)
    * "cls" will be set to the second argument following
    * #MHD_OPTION_URI_LOG_CALLBACK.  Finally, uri will
    * be the 0-terminated URI of the request.
    *
    * Note that during the time of this call, most of the connection's
-   * state is not initialized (as we have not yet parsed he headers).
+   * state is not initialized (as we have not yet parsed the headers).
    * However, information about the connecting client (IP, socket)
    * is available.
+   *
+   * The specified function is called only once per request, therefore some
+   * programmers may use it to instantiate their own request objects, freeing
+   * them in the notifier #MHD_OPTION_NOTIFY_COMPLETED.
    */
   MHD_OPTION_URI_LOG_CALLBACK = 7,
 
@@ -710,15 +1734,22 @@
   MHD_OPTION_HTTPS_CRED_TYPE = 10,
 
   /**
-   * Memory pointer to a `const char *` specifying the
-   * cipher algorithm (default: "NORMAL").
+   * Memory pointer to a `const char *` specifying the GnuTLS priorities string.
+   * If this options is not specified, then MHD will try the following strings:
+   * * "@LIBMICROHTTPD" (application-specific system-wide configuration)
+   * * "@SYSTEM"        (system-wide configuration)
+   * * default GnuTLS priorities string
+   * * "NORMAL"
+   * The first configuration accepted by GnuTLS will be used.
+   * For more details see GnuTLS documentation for "Application-specific
+   * priority strings".
    */
   MHD_OPTION_HTTPS_PRIORITIES = 11,
 
   /**
    * Pass a listen socket for MHD to use (systemd-style).  If this
    * option is used, MHD will not open its own listen socket(s). The
-   * argument passed must be of type `int` and refer to an
+   * argument passed must be of type `MHD_socket` and refer to an
    * existing socket that has been bound to a port and is listening.
    */
   MHD_OPTION_LISTEN_SOCKET = 12,
@@ -729,6 +1760,8 @@
    * a function of type #MHD_LogCallback and the second a pointer
    * `void *` which will be passed as the first argument to the log
    * callback.
+   * Should be specified as the first option, otherwise some messages
+   * may be printed by standard MHD logger during daemon startup.
    *
    * Note that MHD will not generate any log messages
    * if it was compiled without the "--enable-messages"
@@ -739,10 +1772,10 @@
   /**
    * Number (`unsigned int`) of threads in thread pool. Enable
    * thread pooling by setting this value to to something
-   * greater than 1. Currently, thread model must be
-   * #MHD_USE_SELECT_INTERNALLY if thread pooling is enabled
+   * greater than 1. Currently, thread mode must be
+   * #MHD_USE_INTERNAL_POLLING_THREAD if thread pooling is enabled
    * (#MHD_start_daemon returns NULL for an unsupported thread
-   * model).
+   * mode).
    */
   MHD_OPTION_THREAD_POOL_SIZE = 14,
 
@@ -779,10 +1812,12 @@
    *                         struct MHD_Connection *c,
    *                         char *s)
    *
-   * where the return value must be "strlen(s)" and "s" should be
-   * updated.  Note that the unescape function must not lengthen "s"
-   * (the result must be shorter than the input and still be
-   * 0-terminated).  "cls" will be set to the second argument
+   * where the return value must be the length of the value left in
+   * "s" (without the 0-terminator) and "s" should be updated.  Note
+   * that the unescape function must not lengthen "s" (the result must
+   * be shorter than the input and must still be 0-terminated).
+   * However, it may also include binary zeros before the
+   * 0-termination.  "cls" will be set to the second argument
    * following #MHD_OPTION_UNESCAPE_CALLBACK.
    */
   MHD_OPTION_UNESCAPE_CALLBACK = 16,
@@ -790,11 +1825,15 @@
   /**
    * Memory pointer for the random values to be used by the Digest
    * Auth module. This option should be followed by two arguments.
-   * First an integer of type  `size_t` which specifies the size
+   * First an integer of type `size_t` which specifies the size
    * of the buffer pointed to by the second argument in bytes.
+   * The recommended size is between 8 and 32. If size is four or less
+   * then security could be lowered. Sizes more then 32 (or, probably
+   * more than 16 - debatable) will not increase security.
    * Note that the application must ensure that the buffer of the
    * second argument remains allocated and unmodified while the
-   * deamon is running.
+   * daemon is running.
+   * @sa #MHD_OPTION_DIGEST_AUTH_RANDOM_COPY
    */
   MHD_OPTION_DIGEST_AUTH_RANDOM = 17,
 
@@ -802,6 +1841,11 @@
    * Size of the internal array holding the map of the nonce and
    * the nonce counter. This option should be followed by an `unsigend int`
    * argument.
+   * The map size is 4 by default, which is enough to communicate with
+   * a single client at any given moment of time, but not enough to
+   * handle several clients simultaneously.
+   * If Digest Auth is not used, this option can be set to zero to minimise
+   * memory allocation.
    */
   MHD_OPTION_NONCE_NC_SIZE = 18,
 
@@ -813,7 +1857,7 @@
 
   /**
    * Memory pointer for the certificate (ca.pem) to be used by the
-   * HTTPS daemon for client authentification.
+   * HTTPS daemon for client authentication.
    * This option should be followed by a `const char *` argument.
    */
   MHD_OPTION_HTTPS_MEM_TRUST = 20,
@@ -860,7 +1904,7 @@
    * If present and set to true, allow reusing address:port socket
    * (by using SO_REUSEPORT on most platform, or platform-specific ways).
    * If present and set to false, disallow reusing address:port socket
-   * (does nothing on most plaform, but uses SO_EXCLUSIVEADDRUSE on Windows).
+   * (does nothing on most platform, but uses SO_EXCLUSIVEADDRUSE on Windows).
    * This option must be followed by a `unsigned int` argument.
    */
   MHD_OPTION_LISTENING_ADDRESS_REUSE = 25,
@@ -881,11 +1925,186 @@
    * This option should be followed by TWO pointers.  First a pointer
    * to a function of type #MHD_NotifyConnectionCallback and second a
    * pointer to a closure to pass to the request completed callback.
-   * The second pointer maybe NULL.
+   * The second pointer may be NULL.
    */
-  MHD_OPTION_NOTIFY_CONNECTION = 27
+  MHD_OPTION_NOTIFY_CONNECTION = 27,
 
-};
+  /**
+   * Allow to change maximum length of the queue of pending connections on
+   * listen socket. If not present than default platform-specific SOMAXCONN
+   * value is used. This option should be followed by an `unsigned int`
+   * argument.
+   */
+  MHD_OPTION_LISTEN_BACKLOG_SIZE = 28,
+
+  /**
+   * If set to 1 - be strict about the protocol.  Use -1 to be
+   * as tolerant as possible.
+   *
+   * The more flexible option #MHD_OPTION_CLIENT_DISCIPLINE_LVL is recommended
+   * instead of this option.
+   *
+   * The values mapping table:
+   * #MHD_OPTION_STRICT_FOR_CLIENT | #MHD_OPTION_CLIENT_DISCIPLINE_LVL
+   * -----------------------------:|:---------------------------------
+   * 1                             | 1
+   * 0                             | 0
+   * -1                            | -3
+   *
+   * This option should be followed by an `int` argument.
+   * @sa #MHD_OPTION_CLIENT_DISCIPLINE_LVL
+   */
+  MHD_OPTION_STRICT_FOR_CLIENT = 29,
+
+  /**
+   * This should be a pointer to callback of type
+   * gnutls_psk_server_credentials_function that will be given to
+   * gnutls_psk_set_server_credentials_function. It is used to
+   * retrieve the shared key for a given username.
+   */
+  MHD_OPTION_GNUTLS_PSK_CRED_HANDLER = 30,
+
+  /**
+   * Use a callback to determine which X.509 certificate should be
+   * used for a given HTTPS connection.  This option should be
+   * followed by a argument of type `gnutls_certificate_retrieve_function3 *`.
+   * This option provides an
+   * alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK.
+   * You must use this version if you want to use OCSP stapling.
+   * Using this option requires GnuTLS 3.6.3 or higher.
+   */
+  MHD_OPTION_HTTPS_CERT_CALLBACK2 = 31,
+
+  /**
+   * Allows the application to disable certain sanity precautions
+   * in MHD. With these, the client can break the HTTP protocol,
+   * so this should never be used in production. The options are,
+   * however, useful for testing HTTP clients against "broken"
+   * server implementations.
+   * This argument must be followed by an "unsigned int", corresponding
+   * to an `enum MHD_DisableSanityCheck`.
+   */
+  MHD_OPTION_SERVER_INSANITY = 32,
+
+  /**
+   * If followed by value '1' informs MHD that SIGPIPE is suppressed or
+   * handled by application. Allows MHD to use network functions that could
+   * generate SIGPIPE, like `sendfile()`.
+   * Valid only for daemons without #MHD_USE_INTERNAL_POLLING_THREAD as
+   * MHD automatically suppresses SIGPIPE for threads started by MHD.
+   * This option should be followed by an `int` argument.
+   * @note Available since #MHD_VERSION 0x00097205
+   */
+  MHD_OPTION_SIGPIPE_HANDLED_BY_APP = 33,
+
+  /**
+   * If followed by 'int' with value '1' disables usage of ALPN for TLS
+   * connections even if supported by TLS library.
+   * Valid only for daemons with #MHD_USE_TLS.
+   * This option should be followed by an `int` argument.
+   * @note Available since #MHD_VERSION 0x00097207
+   */
+  MHD_OPTION_TLS_NO_ALPN = 34,
+
+  /**
+   * Memory pointer for the random values to be used by the Digest
+   * Auth module. This option should be followed by two arguments.
+   * First an integer of type `size_t` which specifies the size
+   * of the buffer pointed to by the second argument in bytes.
+   * The recommended size is between 8 and 32. If size is four or less
+   * then security could be lowered. Sizes more then 32 (or, probably
+   * more than 16 - debatable) will not increase security.
+   * An internal copy of the buffer will be made, the data do not
+   * need to be static.
+   * @sa #MHD_OPTION_DIGEST_AUTH_RANDOM
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_OPTION_DIGEST_AUTH_RANDOM_COPY = 35,
+
+  /**
+   * Allow to controls the scope of validity of MHD-generated nonces.
+   * This regulates how "nonces" are generated and how "nonces" are checked by
+   * #MHD_digest_auth_check3() and similar functions.
+   * This option should be followed by an 'unsigned int` argument with value
+   * formed as bitwise OR combination of #MHD_DAuthBindNonce values.
+   * When not specified, default value #MHD_DAUTH_BIND_NONCE_NONE is used.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE = 36,
+
+  /**
+   * Memory pointer to a `const char *` specifying the GnuTLS priorities to be
+   * appended to default priorities.
+   * This allow some specific options to be enabled/disabled, while leaving
+   * the rest of the settings to their defaults.
+   * The string does not have to start with a colon ':' character.
+   * See #MHD_OPTION_HTTPS_PRIORITIES description for details of automatic
+   * default priorities.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_OPTION_HTTPS_PRIORITIES_APPEND = 37,
+
+  /**
+   * Sets specified client discipline level (i.e. HTTP protocol parsing
+   * strictness level).
+   *
+   * The following basic values are supported:
+   *  0 - default MHD level, a balance between extra security and broader
+   *      compatibility, as allowed by RFCs for HTTP servers;
+   *  1 - more strict protocol interpretation, within the limits set by
+   *      RFCs for HTTP servers;
+   * -1 - more lenient protocol interpretation, within the limits set by
+   *      RFCs for HTTP servers.
+   * The following extended values could be used as well:
+   *  2 - stricter protocol interpretation, even stricter then allowed
+   *      by RFCs for HTTP servers, however it should be absolutely compatible
+   *      with clients following at least RFCs' "MUST" type of requirements
+   *      for HTTP clients;
+   *  3 - strictest protocol interpretation, even stricter then allowed
+   *      by RFCs for HTTP servers, however it should be absolutely compatible
+   *      with clients following RFCs' "SHOULD" and "MUST" types of requirements
+   *      for HTTP clients;
+   * -2 - more relaxed protocol interpretation, violating RFCs' "SHOULD" type
+   *      of requirements for HTTP servers;
+   * -3 - the most flexible protocol interpretation, beyond RFCs' "MUST" type of
+   *      requirements for HTTP server.
+   * Values higher than "3" or lower than "-3" are interpreted as "3" or "-3"
+   * respectively.
+   *
+   * Higher values are more secure, lower values are more compatible with
+   * various HTTP clients.
+   *
+   * The default value ("0") could be used in most cases.
+   * Value "1" is suitable for highly loaded public servers.
+   * Values "2" and "3" are generally recommended only for testing of HTTP
+   * clients against MHD.
+   * Value "2" may be used for security-centric application, however it is
+   * slight violation of RFCs' requirements.
+   * Negative values are not recommended for public servers.
+   * Values "-1" and "-2" could be used for servers in isolated environment.
+   * Value "-3" is not recommended unless it is absolutely necessary to
+   * communicate with some client(s) with badly broken HTTP implementation.
+   *
+   * This option should be followed by an `int` argument.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_OPTION_CLIENT_DISCIPLINE_LVL = 38
+
+} _MHD_FIXED_ENUM;
+
+
+/**
+ * Bitfield for the #MHD_OPTION_SERVER_INSANITY specifying
+ * which santiy checks should be disabled.
+ */
+enum MHD_DisableSanityCheck
+{
+  /**
+   * All sanity checks are enabled.
+   */
+  MHD_DSC_SANE = 0
+
+} _MHD_FIXED_FLAGS_ENUM;
 
 
 /**
@@ -924,11 +2143,16 @@
 
   /**
    * Response header
+   * @deprecated
    */
   MHD_RESPONSE_HEADER_KIND = 0,
+#define MHD_RESPONSE_HEADER_KIND \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_RESPONSE_HEADER_KIND is deprecated and not used") \
+  MHD_RESPONSE_HEADER_KIND
 
   /**
-   * HTTP header.
+   * HTTP header (request/response).
    */
   MHD_HEADER_KIND = 1,
 
@@ -957,7 +2181,7 @@
    * HTTP footer (only for HTTP 1.1 chunked encodings).
    */
   MHD_FOOTER_KIND = 16
-};
+} _MHD_FIXED_ENUM;
 
 
 /**
@@ -976,8 +2200,9 @@
 
   /**
    * Error handling the connection (resources
-   * exhausted, other side closed connection,
-   * application error accepting request, etc.)
+   * exhausted, application error accepting request,
+   * decrypt error (for HTTPS), connection died when
+   * sending the response etc.)
    * @ingroup request
    */
   MHD_REQUEST_TERMINATED_WITH_ERROR = 1,
@@ -998,24 +2223,23 @@
   MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN = 3,
 
   /**
-   * We tried to read additional data, but the other side closed the
-   * connection.  This error is similar to
-   * #MHD_REQUEST_TERMINATED_WITH_ERROR, but specific to the case where
-   * the connection died because the other side did not send expected
-   * data.
+   * We tried to read additional data, but the connection became broken or
+   * the other side hard closed the connection.
+   * This error is similar to #MHD_REQUEST_TERMINATED_WITH_ERROR, but
+   * specific to the case where the connection died before request completely
+   * received.
    * @ingroup request
    */
   MHD_REQUEST_TERMINATED_READ_ERROR = 4,
 
   /**
    * The client terminated the connection by closing the socket
-   * for writing (TCP half-closed); MHD aborted sending the
-   * response according to RFC 2616, section 8.1.4.
+   * for writing (TCP half-closed) while still sending request.
    * @ingroup request
    */
   MHD_REQUEST_TERMINATED_CLIENT_ABORT = 5
 
-};
+} _MHD_FIXED_ENUM;
 
 
 /**
@@ -1038,7 +2262,7 @@
    */
   MHD_CONNECTION_NOTIFY_CLOSED = 1
 
-};
+} _MHD_FIXED_ENUM;
 
 
 /**
@@ -1048,14 +2272,31 @@
 {
 
   /**
-   * Cipher algorithm used, as a string.
+   * Cipher algorithm used, of type "enum gnutls_cipher_algorithm".
    */
-  const char* cipher_algorithm;
+  int /* enum gnutls_cipher_algorithm */ cipher_algorithm;
 
   /**
-   * Protocol used, as a string.
+   * Protocol used, of type "enum gnutls_protocol".
    */
-  const char* protocol;
+  int /* enum gnutls_protocol */ protocol;
+
+  /**
+   * The suspended status of a connection.
+   */
+  int /* MHD_YES or MHD_NO */ suspended;
+
+  /**
+   * Amount of second that connection could spend in idle state
+   * before automatically disconnected.
+   * Zero for no timeout (unlimited idle time).
+   */
+  unsigned int connection_timeout;
+
+  /**
+   * HTTP status queued with the response, for #MHD_CONNECTION_INFO_HTTP_STATUS.
+   */
+  unsigned int http_status;
 
   /**
    * Connect socket
@@ -1063,14 +2304,19 @@
   MHD_socket connect_fd;
 
   /**
-   * TLS session handle, of type "SSL".
+   * Size of the client's HTTP header.
    */
-  void * /* SSL */ tls_session;
+  size_t header_size;
 
   /**
-   * TLS client certificate handle, of type "X509".
+   * GNUtls session handle, of type "gnutls_session_t".
    */
-  void * /* X509 */ client_cert;
+  void * /* gnutls_session_t */ tls_session;
+
+  /**
+   * GNUtls client certificate handle, of type "gnutls_x509_crt_t".
+   */
+  void * /* gnutls_x509_crt_t */ client_cert;
 
   /**
    * Address information for the client.
@@ -1087,7 +2333,25 @@
    * Socket-specific client context.  Points to the same address as
    * the "socket_context" of the #MHD_NotifyConnectionCallback.
    */
-  void **socket_context;
+  void *socket_context;
+};
+
+
+/**
+ * I/O vector type. Provided for use with #MHD_create_response_from_iovec().
+ * @note Available since #MHD_VERSION 0x00097204
+ */
+struct MHD_IoVec
+{
+  /**
+   * The pointer to the memory region for I/O.
+   */
+  const void *iov_base;
+
+  /**
+   * The size in bytes of the memory region for I/O.
+   */
+  size_t iov_len;
 };
 
 
@@ -1122,18 +2386,18 @@
   MHD_CONNECTION_INFO_CLIENT_ADDRESS,
 
   /**
-   * Get the TLS session handle.
+   * Get the gnuTLS session handle.
    * @ingroup request
    */
-  MHD_CONNECTION_INFO_TLS_SESSION,
+  MHD_CONNECTION_INFO_GNUTLS_SESSION,
 
   /**
    * Get the gnuTLS client certificate handle.  Dysfunctional (never
-   * implemented, deprecated).  Use #MHD_CONNECTION_INFO_TLS_SESSION
-   * to get the `SSL` and then call
-   * SSL_get_peer_certificate() or SSL_get_peer_cert_chain().
+   * implemented, deprecated).  Use #MHD_CONNECTION_INFO_GNUTLS_SESSION
+   * to get the `gnutls_session_t` and then call
+   * gnutls_certificate_get_peers().
    */
-  MHD_CONNECTION_INFO_TLS_CLIENT_CERT,
+  MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT,
 
   /**
    * Get the `struct MHD_Daemon *` responsible for managing this connection.
@@ -1142,7 +2406,8 @@
   MHD_CONNECTION_INFO_DAEMON,
 
   /**
-   * Request the file descriptor for the listening socket.
+   * Request the file descriptor for the connection socket.
+   * MHD sockets are always in non-blocking mode.
    * No extra arguments should be passed.
    * @ingroup request
    */
@@ -1151,19 +2416,43 @@
   /**
    * Returns the client-specific pointer to a `void *` that was (possibly)
    * set during a #MHD_NotifyConnectionCallback when the socket was
-   * first accepted.  Note that this is NOT the same as the "con_cls"
-   * argument of the #MHD_AccessHandlerCallback.  The "con_cls" is
-   * fresh for each HTTP request, while the "socket_context" is fresh
-   * for each socket.
+   * first accepted.
+   * Note that this is NOT the same as the "req_cls" argument of
+   * the #MHD_AccessHandlerCallback. The "req_cls" is fresh for each
+   * HTTP request, while the "socket_context" is fresh for each socket.
    */
-  MHD_CONNECTION_INFO_SOCKET_CONTEXT
+  MHD_CONNECTION_INFO_SOCKET_CONTEXT,
 
-};
+  /**
+   * Check whether the connection is suspended.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFO_CONNECTION_SUSPENDED,
+
+  /**
+   * Get connection timeout
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFO_CONNECTION_TIMEOUT,
+
+  /**
+   * Return length of the client's HTTP request header.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE,
+
+  /**
+   * Return HTTP status queued with the response. NULL
+   * if no HTTP response has been queued yet.
+   */
+  MHD_CONNECTION_INFO_HTTP_STATUS
+
+} _MHD_FIXED_ENUM;
 
 
 /**
  * Values of this enum are used to specify what
- * information about a deamon is desired.
+ * information about a daemon is desired.
  */
 enum MHD_DaemonInfoType
 {
@@ -1184,17 +2473,45 @@
   MHD_DAEMON_INFO_LISTEN_FD,
 
   /**
-   * Request the file descriptor for the external epoll.
+   * Request the file descriptor for the "external" sockets polling
+   * when 'epoll' mode is used.
    * No extra arguments should be passed.
+   *
+   * Waiting on epoll FD must not block longer than value
+   * returned by #MHD_get_timeout() otherwise connections
+   * will "hung" with unprocessed data in network buffers
+   * and timed-out connections will not be closed.
+   *
+   * @sa #MHD_get_timeout(), #MHD_run()
    */
   MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY,
+  MHD_DAEMON_INFO_EPOLL_FD = MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY,
 
   /**
    * Request the number of current connections handled by the daemon.
    * No extra arguments should be passed.
+   * Note: when using MHD in "external" polling mode, this type of request
+   * could be used only when #MHD_run()/#MHD_run_from_select is not
+   * working in other thread at the same time.
    */
-  MHD_DAEMON_INFO_CURRENT_CONNECTIONS
-};
+  MHD_DAEMON_INFO_CURRENT_CONNECTIONS,
+
+  /**
+   * Request the daemon flags.
+   * No extra arguments should be passed.
+   * Note: flags may differ from original 'flags' specified for
+   * daemon, especially if #MHD_USE_AUTO was set.
+   */
+  MHD_DAEMON_INFO_FLAGS,
+
+  /**
+   * Request the port number of daemon's listen socket.
+   * No extra arguments should be passed.
+   * Note: if port '0' was specified for #MHD_start_daemon(), returned
+   * value will be real port number.
+   */
+  MHD_DAEMON_INFO_BIND_PORT
+} _MHD_FIXED_ENUM;
 
 
 /**
@@ -1202,8 +2519,9 @@
  * an error message and `abort()`.
  *
  * @param cls user specified value
- * @param file where the error occured
- * @param line where the error occured
+ * @param file where the error occurred, may be NULL if MHD was built without
+ *             messages support
+ * @param line where the error occurred
  * @param reason error detail, may be NULL
  * @ingroup logging
  */
@@ -1221,22 +2539,45 @@
  * @param addrlen length of @a addr
  * @return #MHD_YES if connection is allowed, #MHD_NO if not
  */
-typedef int
-(*MHD_AcceptPolicyCallback) (void *cls,
-                             const struct sockaddr *addr,
-                             socklen_t addrlen);
+typedef enum MHD_Result
+(*MHD_AcceptPolicyCallback)(void *cls,
+                            const struct sockaddr *addr,
+                            socklen_t addrlen);
 
 
 /**
- * A client has requested the given url using the given method
- * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT,
- * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc).  The callback
- * must call MHD callbacks to provide content to give back to the
- * client and return an HTTP status code (i.e. #MHD_HTTP_OK,
- * #MHD_HTTP_NOT_FOUND, etc.).
+ * A client has requested the given @a url using the given @a method
+ * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT, #MHD_HTTP_METHOD_DELETE,
+ * #MHD_HTTP_METHOD_POST, etc).
+ *
+ * The callback must call MHD function MHD_queue_response() to provide content
+ * to give back to the client and return an HTTP status code (i.e.
+ * #MHD_HTTP_OK, #MHD_HTTP_NOT_FOUND, etc.). The response can be created
+ * in this callback or prepared in advance.
+ * Alternatively, callback may call MHD_suspend_connection() to temporarily
+ * suspend data processing for this connection.
+ *
+ * As soon as response is provided this callback will not be called anymore
+ * for the current request.
+ *
+ * For each HTTP request this callback is called several times:
+ * * after request headers are fully received and decoded,
+ * * for each received part of request body (optional, if request has body),
+ * * when request is fully received.
+ *
+ * If response is provided before request is fully received, the rest
+ * of the request is discarded and connection is automatically closed
+ * after sending response.
+ *
+ * If the request is fully received, but response hasn't been provided and
+ * connection is not suspended, the callback can be called again immediately.
+ *
+ * The response cannot be queued when this callback is called to process
+ * the client upload data (when @a upload_data is not NULL).
  *
  * @param cls argument given together with the function
  *        pointer when the handler was registered with MHD
+ * @param connection the connection handle
  * @param url the requested url
  * @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
  *        #MHD_HTTP_METHOD_PUT, etc.)
@@ -1249,10 +2590,10 @@
  *        part of #MHD_get_connection_values; very large POST
  *        data *will* be made available incrementally in
  *        @a upload_data)
- * @param upload_data_size set initially to the size of the
+ * @param[in,out] upload_data_size set initially to the size of the
  *        @a upload_data provided; the method must update this
  *        value to the number of bytes NOT processed;
- * @param con_cls pointer that the callback can set to some
+ * @param[in,out] req_cls pointer that the callback can set to some
  *        address and that will be preserved by MHD for future
  *        calls for this request; since the access handler may
  *        be called many times (i.e., for a PUT/POST operation
@@ -1261,20 +2602,22 @@
  *        If necessary, this state can be cleaned up in the
  *        global #MHD_RequestCompletedCallback (which
  *        can be set with the #MHD_OPTION_NOTIFY_COMPLETED).
- *        Initially, `*con_cls` will be NULL.
+ *        Initially, `*req_cls` will be NULL.
  * @return #MHD_YES if the connection was handled successfully,
- *         #MHD_NO if the socket must be closed due to a serios
+ *         #MHD_NO if the socket must be closed due to a serious
  *         error while handling the request
+ *
+ * @sa #MHD_queue_response()
  */
-typedef int
-(*MHD_AccessHandlerCallback) (void *cls,
-                              struct MHD_Connection *connection,
-                              const char *url,
-                              const char *method,
-                              const char *version,
-                              const char *upload_data,
-                              size_t *upload_data_size,
-                              void **con_cls);
+typedef enum MHD_Result
+(*MHD_AccessHandlerCallback)(void *cls,
+                             struct MHD_Connection *connection,
+                             const char *url,
+                             const char *method,
+                             const char *version,
+                             const char *upload_data,
+                             size_t *upload_data_size,
+                             void **req_cls);
 
 
 /**
@@ -1283,7 +2626,7 @@
  *
  * @param cls client-defined closure
  * @param connection connection handle
- * @param con_cls value as set by the last call to
+ * @param req_cls value as set by the last call to
  *        the #MHD_AccessHandlerCallback
  * @param toe reason for request termination
  * @see #MHD_OPTION_NOTIFY_COMPLETED
@@ -1292,9 +2635,10 @@
 typedef void
 (*MHD_RequestCompletedCallback) (void *cls,
                                  struct MHD_Connection *connection,
-                                 void **con_cls,
+                                 void **req_cls,
                                  enum MHD_RequestTerminationCode toe);
 
+
 /**
  * Signature of the callback used by MHD to notify the
  * application about started/stopped connections
@@ -1304,7 +2648,7 @@
  * @param socket_context socket-specific pointer where the
  *                       client can associate some state specific
  *                       to the TCP connection; note that this is
- *                       different from the "con_cls" which is per
+ *                       different from the "req_cls" which is per
  *                       HTTP request.  The client can initialize
  *                       during #MHD_CONNECTION_NOTIFY_STARTED and
  *                       cleanup during #MHD_CONNECTION_NOTIFY_CLOSED
@@ -1336,17 +2680,45 @@
  *         #MHD_NO to abort the iteration
  * @ingroup request
  */
-typedef int
-(*MHD_KeyValueIterator) (void *cls,
-                         enum MHD_ValueKind kind,
-                         const char *key,
-                         const char *value);
+typedef enum MHD_Result
+(*MHD_KeyValueIterator)(void *cls,
+                        enum MHD_ValueKind kind,
+                        const char *key,
+                        const char *value);
 
 
 /**
- * Callback used by libmicrohttpd in order to obtain content.  The
- * callback is to copy at most @a max bytes of content into @a buf.  The
- * total number of bytes that has been placed into @a buf should be
+ * Iterator over key-value pairs with size parameters.
+ * This iterator can be used to iterate over all of
+ * the cookies, headers, or POST-data fields of a
+ * request, and also to iterate over the headers that
+ * have been added to a response.
+ * @note Available since #MHD_VERSION 0x00096303
+ *
+ * @param cls closure
+ * @param kind kind of the header we are looking at
+ * @param key key for the value, can be an empty string
+ * @param value corresponding value, can be NULL
+ * @param value_size number of bytes in @a value;
+ *                   for C-strings, the length excludes the 0-terminator
+ * @return #MHD_YES to continue iterating,
+ *         #MHD_NO to abort the iteration
+ * @ingroup request
+ */
+typedef enum MHD_Result
+(*MHD_KeyValueIteratorN)(void *cls,
+                         enum MHD_ValueKind kind,
+                         const char *key,
+                         size_t key_size,
+                         const char *value,
+                         size_t value_size);
+
+
+/**
+ * Callback used by libmicrohttpd in order to obtain content.
+ *
+ * The callback is to copy at most @a max bytes of content into @a buf.
+ * The total number of bytes that has been placed into @a buf should be
  * returned.
  *
  * Note that returning zero will cause libmicrohttpd to try again.
@@ -1365,10 +2737,10 @@
  * @param buf where to copy the data
  * @param max maximum number of bytes to copy to @a buf (size of @a buf)
  * @return number of bytes written to @a buf;
- *  0 is legal unless we are running in internal select mode (since
- *    this would cause busy-waiting); 0 in external select mode
- *    will cause this function to be called again once the external
- *    select calls MHD again;
+ *  0 is legal unless MHD is started in "internal" sockets polling mode
+ *    (since this would cause busy-waiting); 0 in "external" sockets
+ *    polling mode will cause this function to be called again once
+ *    any MHD_run*() function is called;
  *  #MHD_CONTENT_READER_END_OF_STREAM (-1) for the regular
  *    end of transmission (with chunked encoding, MHD will then
  *    terminate the chunk and send any HTTP footers that might be
@@ -1409,13 +2781,14 @@
 
 /**
  * Iterator over key-value pairs where the value
- * maybe made available in increments and/or may
+ * may be made available in increments and/or may
  * not be zero-terminated.  Used for processing
  * POST data.
  *
  * @param cls user-specified closure
  * @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD
- * @param key 0-terminated key for the value
+ * @param key 0-terminated key for the value, NULL if not known. This value
+ *            is never NULL for url-encoded POST data.
  * @param filename name of the uploaded file, NULL if not known
  * @param content_type mime-type of the data, NULL if not known
  * @param transfer_encoding encoding of the data, NULL if not known
@@ -1426,16 +2799,16 @@
  * @return #MHD_YES to continue iterating,
  *         #MHD_NO to abort the iteration
  */
-typedef int
-(*MHD_PostDataIterator) (void *cls,
-                         enum MHD_ValueKind kind,
-                         const char *key,
-                         const char *filename,
-                         const char *content_type,
-                         const char *transfer_encoding,
-                         const char *data,
-                         uint64_t off,
-                         size_t size);
+typedef enum MHD_Result
+(*MHD_PostDataIterator)(void *cls,
+                        enum MHD_ValueKind kind,
+                        const char *key,
+                        const char *filename,
+                        const char *content_type,
+                        const char *transfer_encoding,
+                        const char *data,
+                        uint64_t off,
+                        size_t size);
 
 /* **************** Daemon handling functions ***************** */
 
@@ -1443,7 +2816,11 @@
  * Start a webserver on the given port.
  *
  * @param flags combination of `enum MHD_FLAG` values
- * @param port port to bind to (in host byte order)
+ * @param port port to bind to (in host byte order),
+ *        use '0' to bind to random free port,
+ *        ignored if MHD_OPTION_SOCK_ADDR or
+ *        MHD_OPTION_LISTEN_SOCKET is provided
+ *        or MHD_USE_NO_LISTEN_SOCKET is specified
  * @param apc callback to call to check which clients
  *        will be allowed to connect; you can pass NULL
  *        in which case connections from any IP will be
@@ -1458,10 +2835,10 @@
  */
 _MHD_EXTERN struct MHD_Daemon *
 MHD_start_daemon_va (unsigned int flags,
-		     uint16_t port,
-		     MHD_AcceptPolicyCallback apc, void *apc_cls,
-		     MHD_AccessHandlerCallback dh, void *dh_cls,
-		     va_list ap);
+                     uint16_t port,
+                     MHD_AcceptPolicyCallback apc, void *apc_cls,
+                     MHD_AccessHandlerCallback dh, void *dh_cls,
+                     va_list ap);
 
 
 /**
@@ -1469,7 +2846,11 @@
  * #MHD_start_daemon_va.
  *
  * @param flags combination of `enum MHD_FLAG` values
- * @param port port to bind to
+ * @param port port to bind to (in host byte order),
+ *        use '0' to bind to random free port,
+ *        ignored if MHD_OPTION_SOCK_ADDR or
+ *        MHD_OPTION_LISTEN_SOCKET is provided
+ *        or MHD_USE_NO_LISTEN_SOCKET is specified
  * @param apc callback to call to check which clients
  *        will be allowed to connect; you can pass NULL
  *        in which case connections from any IP will be
@@ -1482,10 +2863,10 @@
  */
 _MHD_EXTERN struct MHD_Daemon *
 MHD_start_daemon (unsigned int flags,
-		  uint16_t port,
-		  MHD_AcceptPolicyCallback apc, void *apc_cls,
-		  MHD_AccessHandlerCallback dh, void *dh_cls,
-		  ...);
+                  uint16_t port,
+                  MHD_AcceptPolicyCallback apc, void *apc_cls,
+                  MHD_AccessHandlerCallback dh, void *dh_cls,
+                  ...);
 
 
 /**
@@ -1493,12 +2874,12 @@
  * clients to continue processing, but stops accepting new
  * connections.  Note that the caller is responsible for closing the
  * returned socket; however, if MHD is run using threads (anything but
- * external select mode), it must not be closed until AFTER
+ * "external" sockets polling mode), it must not be closed until AFTER
  * #MHD_stop_daemon has been called (as it is theoretically possible
  * that an existing thread is still using it).
  *
  * Note that some thread modes require the caller to have passed
- * #MHD_USE_PIPE_FOR_SHUTDOWN when using this API.  If this daemon is
+ * #MHD_USE_ITC when using this API.  If this daemon is
  * in one of those modes and this option was not given to
  * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET.
  *
@@ -1528,17 +2909,14 @@
  * for example if your HTTP server is behind NAT and needs to connect
  * out to the HTTP client, or if you are building a proxy.
  *
- * If you use this API in conjunction with a internal select or a
- * thread pool, you must set the option
- * #MHD_USE_PIPE_FOR_SHUTDOWN to ensure that the freshly added
+ * If you use this API in conjunction with an "internal" socket polling,
+ * you must set the option #MHD_USE_ITC to ensure that the freshly added
  * connection is immediately processed by MHD.
  *
  * The given client socket will be managed (and closed!) by MHD after
  * this call and must no longer be used directly by the application
  * afterwards.
  *
- * Per-IP connection limits are ignored when using this API.
- *
  * @param daemon daemon that manages the connection
  * @param client_socket socket to manage (MHD will expect
  *        to receive an HTTP request from this socket next).
@@ -1550,11 +2928,11 @@
  *        set to indicate further details about the error.
  * @ingroup specialized
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_add_connection (struct MHD_Daemon *daemon,
-		    MHD_socket client_socket,
-		    const struct sockaddr *addr,
-		    socklen_t addrlen);
+                    MHD_socket client_socket,
+                    const struct sockaddr *addr,
+                    socklen_t addrlen);
 
 
 /**
@@ -1564,6 +2942,18 @@
  * before calling this function. FD_SETSIZE is assumed
  * to be platform's default.
  *
+ * This function should be called only when MHD is configured to
+ * use "external" sockets polling with 'select()' or with 'epoll'.
+ * In the latter case, it will only add the single 'epoll' file
+ * descriptor used by MHD to the sets.
+ * It's necessary to use #MHD_get_timeout() to get maximum timeout
+ * value for `select()`. Usage of `select()` with indefinite timeout
+ * (or timeout larger than returned by #MHD_get_timeout()) will
+ * violate MHD API and may results in pending unprocessed data.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
  * @param daemon daemon to get sets from
  * @param read_fd_set read set
  * @param write_fd_set write set
@@ -1576,21 +2966,34 @@
  *         fit fd_set.
  * @ingroup event
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_get_fdset (struct MHD_Daemon *daemon,
                fd_set *read_fd_set,
                fd_set *write_fd_set,
-	       fd_set *except_fd_set,
-	       MHD_socket *max_fd);
+               fd_set *except_fd_set,
+               MHD_socket *max_fd);
 
 
 /**
  * Obtain the `select()` sets for this daemon.
  * Daemon's FDs will be added to fd_sets. To get only
  * daemon FDs in fd_sets, call FD_ZERO for each fd_set
- * before calling this function. Passing custom FD_SETSIZE
- * as @a fd_setsize allow usage of larger/smaller than
- * platform's default fd_sets.
+ * before calling this function.
+ *
+ * Passing custom FD_SETSIZE as @a fd_setsize allow usage of
+ * larger/smaller than platform's default fd_sets.
+ *
+ * This function should be called only when MHD is configured to
+ * use "external" sockets polling with 'select()' or with 'epoll'.
+ * In the latter case, it will only add the single 'epoll' file
+ * descriptor used by MHD to the sets.
+ * It's necessary to use #MHD_get_timeout() to get maximum timeout
+ * value for `select()`. Usage of `select()` with indefinite timeout
+ * (or timeout larger than returned by #MHD_get_timeout()) will
+ * violate MHD API and may results in pending unprocessed data.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
  *
  * @param daemon daemon to get sets from
  * @param read_fd_set read set
@@ -1605,13 +3008,13 @@
  *         fit fd_set.
  * @ingroup event
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_get_fdset2 (struct MHD_Daemon *daemon,
-               fd_set *read_fd_set,
-               fd_set *write_fd_set,
-               fd_set *except_fd_set,
-               MHD_socket *max_fd,
-               unsigned int fd_setsize);
+                fd_set *read_fd_set,
+                fd_set *write_fd_set,
+                fd_set *except_fd_set,
+                MHD_socket *max_fd,
+                unsigned int fd_setsize);
 
 
 /**
@@ -1621,6 +3024,18 @@
  * before calling this function. Size of fd_set is
  * determined by current value of FD_SETSIZE.
  *
+ * This function should be called only when MHD is configured to
+ * use "external" sockets polling with 'select()' or with 'epoll'.
+ * In the latter case, it will only add the single 'epoll' file
+ * descriptor used by MHD to the sets.
+ * It's necessary to use #MHD_get_timeout() to get maximum timeout
+ * value for `select()`. Usage of `select()` with indefinite timeout
+ * (or timeout larger than returned by #MHD_get_timeout()) will
+ * violate MHD API and may results in pending unprocessed data.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
  * @param daemon daemon to get sets from
  * @param read_fd_set read set
  * @param write_fd_set write set
@@ -1634,40 +3049,203 @@
  * @ingroup event
  */
 #define MHD_get_fdset(daemon,read_fd_set,write_fd_set,except_fd_set,max_fd) \
-  MHD_get_fdset2((daemon),(read_fd_set),(write_fd_set),(except_fd_set),(max_fd),FD_SETSIZE)
+  MHD_get_fdset2 ((daemon),(read_fd_set),(write_fd_set),(except_fd_set), \
+                  (max_fd),FD_SETSIZE)
 
 
 /**
- * Obtain timeout value for `select()` for this daemon (only needed if
- * connection timeout is used).  The returned value is how many milliseconds
- * `select()` or `poll()` should at most block, not the timeout value set for
- * connections.  This function MUST NOT be called if MHD is running with
- * #MHD_USE_THREAD_PER_CONNECTION.
+ * Obtain timeout value for polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function. Smaller timeout values can be used for
+ * polling function if it is required for any reason, but using larger
+ * timeout value or no timeout (indefinite timeout) when this function
+ * return #MHD_YES will break MHD processing logic and result in "hung"
+ * connections with data pending in network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout64(),
+ * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external"
+ * polling is used.
+ * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select())
+ * must be called right after return from polling function, regardless of
+ * the states of MHD FDs.
+ *
+ * In practice, if #MHD_YES is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than @a timeout
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
  *
  * @param daemon daemon to query for timeout
- * @param timeout set to the timeout (in milliseconds)
+ * @param[out] timeout set to the timeout (in milliseconds)
  * @return #MHD_YES on success, #MHD_NO if timeouts are
- *        not used (or no connections exist that would
- *        necessiate the use of a timeout right now).
+ *         not used and no data processing is pending.
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_get_timeout (struct MHD_Daemon *daemon,
+                 MHD_UNSIGNED_LONG_LONG *timeout);
+
+
+/**
+ * Free the memory allocated by MHD.
+ *
+ * If any MHD function explicitly mentions that returned pointer must be
+ * freed by this function, then no other method must be used to free
+ * the memory.
+ *
+ * @param ptr the pointer to free.
+ * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3()
+ * @sa #MHD_basic_auth_get_username_password()
+ * @note Available since #MHD_VERSION 0x00095600
+ * @ingroup specialized
+ */
+_MHD_EXTERN void
+MHD_free (void *ptr);
+
+/**
+ * Obtain timeout value for external polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function. Smaller timeout values can be used for
+ * polling function if it is required for any reason, but using larger
+ * timeout value or no timeout (indefinite timeout) when this function
+ * return #MHD_YES will break MHD processing logic and result in "hung"
+ * connections with data pending in network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout(),
+ * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external"
+ * polling is used.
+ * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select())
+ * must be called right after return from polling function, regardless of
+ * the states of MHD FDs.
+ *
+ * In practice, if #MHD_YES is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than @a timeout
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ *
+ * @param daemon daemon to query for timeout
+ * @param[out] timeout64 the pointer to the variable to be set to the
+ *                  timeout (in milliseconds)
+ * @return #MHD_YES if timeout value has been set,
+ *         #MHD_NO if timeouts are not used and no data processing is pending.
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_get_timeout64 (struct MHD_Daemon *daemon,
+                   uint64_t *timeout);
+
+
+/**
+ * Obtain timeout value for external polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function (if returned value is non-negative).
+ * Smaller timeout values can be used for polling function if it is required
+ * for any reason, but using larger timeout value or no timeout (indefinite
+ * timeout) when this function returns non-negative value will break MHD
+ * processing logic and result in "hung" connections with data pending in
+ * network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout(),
+ * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external"
+ * polling is used.
+ * If this function returns non-negative value then #MHD_run() (or
+ * #MHD_run_from_select()) must be called right after return from polling
+ * function, regardless of the states of MHD FDs.
+ *
+ * In practice, if zero or positive value is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than returned amount of
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ *
+ * @param daemon the daemon to query for timeout
+ * @return -1 if connections' timeouts are not set and no data processing
+ *         is pending, so external polling function may wait for sockets
+ *         activity for indefinite amount of time,
+ *         otherwise returned value is the the maximum amount of millisecond
+ *         that external polling function must wait for the activity of FDs.
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup event
+ */
+_MHD_EXTERN int64_t
+MHD_get_timeout64s (struct MHD_Daemon *daemon);
+
+
+/**
+ * Obtain timeout value for external polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function (if returned value is non-negative).
+ * Smaller timeout values can be used for polling function if it is required
+ * for any reason, but using larger timeout value or no timeout (indefinite
+ * timeout) when this function returns non-negative value will break MHD
+ * processing logic and result in "hung" connections with data pending in
+ * network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout(),
+ * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external"
+ * polling is used.
+ * If this function returns non-negative value then #MHD_run() (or
+ * #MHD_run_from_select()) must be called right after return from polling
+ * function, regardless of the states of MHD FDs.
+ *
+ * In practice, if zero or positive value is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than returned amount of
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ *
+ * @param daemon the daemon to query for timeout
+ * @return -1 if connections' timeouts are not set and no data processing
+ *         is pending, so external polling function may wait for sockets
+ *         activity for indefinite amount of time,
+ *         otherwise returned value is the the maximum amount of millisecond
+ *         (capped at INT_MAX) that external polling function must wait
+ *         for the activity of FDs.
+ * @note Available since #MHD_VERSION 0x00097601
  * @ingroup event
  */
 _MHD_EXTERN int
-MHD_get_timeout (struct MHD_Daemon *daemon,
-		 MHD_UNSIGNED_LONG_LONG *timeout);
+MHD_get_timeout_i (struct MHD_Daemon *daemon);
 
 
 /**
- * Run webserver operations (without blocking unless in client
- * callbacks).  This method should be called by clients in combination
- * with #MHD_get_fdset if the client-controlled select method is used.
+ * Run webserver operations (without blocking unless in client callbacks).
+ *
+ * This method should be called by clients in combination with
+ * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD
+ * if epoll is used) and #MHD_get_timeout() if the client-controlled
+ * connection polling method is used (i.e. daemon was started without
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag).
  *
  * This function is a convenience method, which is useful if the
  * fd_sets from #MHD_get_fdset were not directly passed to `select()`;
  * with this function, MHD will internally do the appropriate `select()`
- * call itself again.  While it is always safe to call #MHD_run (in
- * external select mode), you should call #MHD_run_from_select if
- * performance is important (as it saves an expensive call to
- * `select()`).
+ * call itself again.  While it is acceptable to call #MHD_run (if
+ * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should
+ * call #MHD_run_from_select() if performance is important (as it saves an
+ * expensive call to `select()`).
+ *
+ * If #MHD_get_timeout() returned #MHD_YES, than this function must be called
+ * right after polling function returns regardless of detected activity on
+ * the daemon's FDs.
  *
  * @param daemon daemon to run
  * @return #MHD_YES on success, #MHD_NO if this
@@ -1675,14 +3253,57 @@
  *         options for this call.
  * @ingroup event
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_run (struct MHD_Daemon *daemon);
 
 
 /**
+ * Run websever operation with possible blocking.
+ *
+ * This function does the following: waits for any network event not more than
+ * specified number of milliseconds, processes all incoming and outgoing data,
+ * processes new connections, processes any timed-out connection, and does
+ * other things required to run webserver.
+ * Once all connections are processed, function returns.
+ *
+ * This function is useful for quick and simple (lazy) webserver implementation
+ * if application needs to run a single thread only and does not have any other
+ * network activity.
+ *
+ * This function calls MHD_get_timeout() internally and use returned value as
+ * maximum wait time if it less than value of @a millisec parameter.
+ *
+ * It is expected that the "external" socket polling function is not used in
+ * conjunction with this function unless the @a millisec is set to zero.
+ *
+ * @param daemon the daemon to run
+ * @param millisec the maximum time in milliseconds to wait for network and
+ *                 other events. Note: there is no guarantee that function
+ *                 blocks for the specified amount of time. The real processing
+ *                 time can be shorter (if some data or connection timeout
+ *                 comes earlier) or longer (if data processing requires more
+ *                 time, especially in user callbacks).
+ *                 If set to '0' then function does not block and processes
+ *                 only already available data (if any).
+ *                 If set to '-1' then function waits for events
+ *                 indefinitely (blocks until next network activity or
+ *                 connection timeout).
+ * @return #MHD_YES on success, #MHD_NO if this
+ *         daemon was not started with the right
+ *         options for this call or some serious
+ *         unrecoverable error occurs.
+ * @note Available since #MHD_VERSION 0x00097206
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_run_wait (struct MHD_Daemon *daemon,
+              int32_t millisec);
+
+
+/**
  * Run webserver operations. This method should be called by clients
- * in combination with #MHD_get_fdset if the client-controlled select
- * method is used.
+ * in combination with #MHD_get_fdset and #MHD_get_timeout() if the
+ * client-controlled select method is used.
  *
  * You can use this function instead of #MHD_run if you called
  * `select()` on the result from #MHD_get_fdset.  File descriptors in
@@ -1691,20 +3312,25 @@
  * not have to call `select()` again to determine which operations are
  * ready.
  *
+ * If #MHD_get_timeout() returned #MHD_YES, than this function must be
+ * called right after `select()` returns regardless of detected activity
+ * on the daemon's FDs.
+ *
+ * This function cannot be used with daemon started with
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
  * @param daemon daemon to run select loop for
  * @param read_fd_set read set
  * @param write_fd_set write set
- * @param except_fd_set except set (not used, can be NULL)
+ * @param except_fd_set except set
  * @return #MHD_NO on serious errors, #MHD_YES on success
  * @ingroup event
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_run_from_select (struct MHD_Daemon *daemon,
-		     const fd_set *read_fd_set,
-		     const fd_set *write_fd_set,
-		     const fd_set *except_fd_set);
-
-
+                     const fd_set *read_fd_set,
+                     const fd_set *write_fd_set,
+                     const fd_set *except_fd_set);
 
 
 /* **************** Connection handling functions ***************** */
@@ -1713,17 +3339,39 @@
  * Get all of the headers from the request.
  *
  * @param connection connection to get values from
- * @param kind types of values to iterate over
+ * @param kind types of values to iterate over, can be a bitmask
  * @param iterator callback to call on each header;
- *        maybe NULL (then just count headers)
+ *        may be NULL (then just count headers)
  * @param iterator_cls extra argument to @a iterator
- * @return number of entries iterated over
+ * @return number of entries iterated over,
+ *         -1 if connection is NULL.
  * @ingroup request
  */
 _MHD_EXTERN int
 MHD_get_connection_values (struct MHD_Connection *connection,
                            enum MHD_ValueKind kind,
-                           MHD_KeyValueIterator iterator, void *iterator_cls);
+                           MHD_KeyValueIterator iterator,
+                           void *iterator_cls);
+
+
+/**
+ * Get all of the headers from the request.
+ *
+ * @param connection connection to get values from
+ * @param kind types of values to iterate over, can be a bitmask
+ * @param iterator callback to call on each header;
+ *        may be NULL (then just count headers)
+ * @param iterator_cls extra argument to @a iterator
+ * @return number of entries iterated over,
+ *         -1 if connection is NULL.
+ * @note Available since #MHD_VERSION 0x00096400
+ * @ingroup request
+ */
+_MHD_EXTERN int
+MHD_get_connection_values_n (struct MHD_Connection *connection,
+                             enum MHD_ValueKind kind,
+                             MHD_KeyValueIteratorN iterator,
+                             void *iterator_cls);
 
 
 /**
@@ -1751,26 +3399,63 @@
  *         #MHD_YES on success
  * @ingroup request
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_set_connection_value (struct MHD_Connection *connection,
                           enum MHD_ValueKind kind,
                           const char *key,
-			  const char *value);
+                          const char *value);
 
 
 /**
- * Sets the global error handler to a different implementation.  @a cb
- * will only be called in the case of typically fatal, serious
- * internal consistency issues.  These issues should only arise in the
- * case of serious memory corruption or similar problems with the
- * architecture.  While @a cb is allowed to return and MHD will then
- * try to continue, this is never safe.
+ * This function can be used to add an arbitrary entry to connection.
+ * This function could add entry with binary zero, which is allowed
+ * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is
+ * recommended to use #MHD_set_connection_value.
  *
- * The default implementation that is used if no panic function is set
- * simply prints an error message and calls `abort()`.  Alternative
- * implementations might call `exit()` or other similar functions.
+ * This function MUST only be called from within the
+ * #MHD_AccessHandlerCallback (otherwise, access maybe improperly
+ * synchronized).  Furthermore, the client must guarantee that the key
+ * and value arguments are 0-terminated strings that are NOT freed
+ * until the connection is closed.  (The easiest way to do this is by
+ * passing only arguments to permanently allocated strings.).
  *
- * @param cb new error handler
+ * @param connection the connection for which a
+ *  value should be set
+ * @param kind kind of the value
+ * @param key key for the value, must be zero-terminated
+ * @param key_size number of bytes in @a key (excluding 0-terminator)
+ * @param value the value itself, must be zero-terminated
+ * @param value_size number of bytes in @a value (excluding 0-terminator)
+ * @return #MHD_NO if the operation could not be
+ *         performed due to insufficient memory;
+ *         #MHD_YES on success
+ * @note Available since #MHD_VERSION 0x00096400
+ * @ingroup request
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_set_connection_value_n (struct MHD_Connection *connection,
+                            enum MHD_ValueKind kind,
+                            const char *key,
+                            size_t key_size,
+                            const char *value,
+                            size_t value_size);
+
+
+/**
+ * Sets the global error handler to a different implementation.
+ *
+ * @a cb will only be called in the case of typically fatal, serious internal
+ * consistency issues or serious system failures like failed lock of mutex.
+ *
+ * These issues should only arise in the case of serious memory corruption or
+ * similar problems with the architecture, there is no safe way to continue
+ * even for closing of the application.
+ *
+ * The default implementation that is used if no panic function is set simply
+ * prints an error message and calls `abort()`.
+ * Alternative implementations might call `exit()` or other similar functions.
+ *
+ * @param cb new error handler or NULL to use default handler
  * @param cls passed to @a cb
  * @ingroup logging
  */
@@ -1780,8 +3465,8 @@
 
 /**
  * Process escape sequences ('%HH') Updates val in place; the
- * result should be UTF-8 encoded and cannot be larger than the input.
- * The result must also still be 0-terminated.
+ * result cannot be larger than the input.
+ * The result is still be 0-terminated.
  *
  * @param val value to unescape (modified in the process)
  * @return length of the resulting val (`strlen(val)` may be
@@ -1803,36 +3488,91 @@
  */
 _MHD_EXTERN const char *
 MHD_lookup_connection_value (struct MHD_Connection *connection,
-			     enum MHD_ValueKind kind,
-			     const char *key);
+                             enum MHD_ValueKind kind,
+                             const char *key);
+
+
+/**
+ * Get a particular header value.  If multiple
+ * values match the kind, return any one of them.
+ * @note Since MHD_VERSION 0x00096304
+ *
+ * @param connection connection to get values from
+ * @param kind what kind of value are we looking for
+ * @param key the header to look for, NULL to lookup 'trailing' value without a key
+ * @param key_size the length of @a key in bytes
+ * @param[out] value_ptr the pointer to variable, which will be set to found value,
+ *                       will not be updated if key not found,
+ *                       could be NULL to just check for presence of @a key
+ * @param[out] value_size_ptr the pointer variable, which will set to found value,
+ *                            will not be updated if key not found,
+ *                            could be NULL
+ * @return #MHD_YES if key is found,
+ *         #MHD_NO otherwise.
+ * @ingroup request
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_lookup_connection_value_n (struct MHD_Connection *connection,
+                               enum MHD_ValueKind kind,
+                               const char *key,
+                               size_t key_size,
+                               const char **value_ptr,
+                               size_t *value_size_ptr);
 
 
 /**
  * Queue a response to be transmitted to the client (as soon as
  * possible but after #MHD_AccessHandlerCallback returns).
  *
+ * For any active connection this function must be called
+ * only by #MHD_AccessHandlerCallback callback.
+ * For suspended connection this function can be called at any moment. Response
+ * will be sent as soon as connection is resumed.
+ *
+ * If HTTP specifications require use no body in reply, like @a status_code with
+ * value 1xx, the response body is automatically not sent even if it is present
+ * in the response. No "Content-Length" or "Transfer-Encoding" headers are
+ * generated and added.
+ *
+ * When the response is used to respond HEAD request or used with @a status_code
+ * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length"
+ * header is added automatically based the size of the body in the response.
+ * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced
+ * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead
+ * of "Content-Length" header. For example, if response with zero-size body is
+ * used for HEAD request, then "Content-Length: 0" is added automatically to
+ * reply headers.
+ * @sa #MHD_RF_HEAD_ONLY_RESPONSE
+ *
+ * In situations, where reply body is required, like answer for the GET request
+ * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body
+ * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1)
+ * are added automatically.
+ * In practice, the same response object can be used to respond to both HEAD and
+ * GET requests.
+ *
  * @param connection the connection identifying the client
  * @param status_code HTTP status code (i.e. #MHD_HTTP_OK)
- * @param response response to transmit
- * @return #MHD_NO on error (i.e. reply already sent),
+ * @param response response to transmit, the NULL is tolerated
+ * @return #MHD_NO on error (reply already sent, response is NULL),
  *         #MHD_YES on success or if message has been queued
  * @ingroup response
+ * @sa #MHD_AccessHandlerCallback
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_queue_response (struct MHD_Connection *connection,
                     unsigned int status_code,
-		    struct MHD_Response *response);
+                    struct MHD_Response *response);
 
 
 /**
- * Suspend handling of network data for a given connection.  This can
- * be used to dequeue a connection from MHD's event loop (external
- * select, internal select or thread pool; not applicable to
- * thread-per-connection!) for a while.
+ * Suspend handling of network data for a given connection.
+ * This can be used to dequeue a connection from MHD's event loop
+ * (not applicable to thread-per-connection!) for a while.
  *
- * If you use this API in conjunction with a internal select or a
- * thread pool, you must set the option #MHD_USE_PIPE_FOR_SHUTDOWN to
- * ensure that a resumed connection is immediately processed by MHD.
+ * If you use this API in conjunction with an "internal" socket polling,
+ * you must set the option #MHD_USE_ITC to ensure that a resumed
+ * connection is immediately processed by MHD.
  *
  * Suspended connections continue to count against the total number of
  * connections allowed (per daemon, as well as per IP, if such limits
@@ -1841,8 +3581,8 @@
  * connection is suspended, MHD will not detect disconnects by the
  * client.
  *
- * The only safe time to suspend a connection is from the
- * #MHD_AccessHandlerCallback.
+ * The only safe way to call this function is to call it from the
+ * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback.
  *
  * Finally, it is an API violation to call #MHD_stop_daemon while
  * having suspended connections (this will at least create memory and
@@ -1850,6 +3590,8 @@
  * resume all connections before stopping the daemon.
  *
  * @param connection the connection to suspend
+ *
+ * @sa #MHD_AccessHandlerCallback
  */
 _MHD_EXTERN void
 MHD_suspend_connection (struct MHD_Connection *connection);
@@ -1861,6 +3603,12 @@
  * function on a connection that was not previously suspended will
  * result in undefined behavior.
  *
+ * If you are using this function in "external" sockets polling mode, you must
+ * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before
+ * again calling #MHD_get_fdset()), as otherwise the change may not be
+ * reflected in the set returned by #MHD_get_fdset() and you may end up
+ * with a connection that is stuck until the next network activity.
+ *
  * @param connection the connection to resume
  */
 _MHD_EXTERN void
@@ -1877,17 +3625,84 @@
 {
   /**
    * Default: no special flags.
+   * @note Available since #MHD_VERSION 0x00093701
    */
   MHD_RF_NONE = 0,
 
   /**
-   * Only respond in conservative HTTP 1.0-mode.   In particular,
-   * do not (automatically) sent "Connection" headers and always
-   * close the connection after generating the response.
+   * Only respond in conservative (dumb) HTTP/1.0-compatible mode.
+   * Response still use HTTP/1.1 version in header, but always close
+   * the connection after sending the response and do not use chunked
+   * encoding for the response.
+   * You can also set the #MHD_RF_HTTP_1_0_SERVER flag to force
+   * HTTP/1.0 version in the response.
+   * Responses are still compatible with HTTP/1.1.
+   * This option can be used to communicate with some broken client, which
+   * does not implement HTTP/1.1 features, but advertises HTTP/1.1 support.
+   * @note Available since #MHD_VERSION 0x00097308
    */
-  MHD_RF_HTTP_VERSION_1_0_ONLY = 1
+  MHD_RF_HTTP_1_0_COMPATIBLE_STRICT = 1 << 0,
+  /**
+   * The same as #MHD_RF_HTTP_1_0_COMPATIBLE_STRICT
+   * @note Available since #MHD_VERSION 0x00093701
+   */
+  MHD_RF_HTTP_VERSION_1_0_ONLY = 1 << 0,
 
-};
+  /**
+   * Only respond in HTTP 1.0-mode.
+   * Contrary to the #MHD_RF_HTTP_1_0_COMPATIBLE_STRICT flag, the response's
+   * HTTP version will always be set to 1.0 and keep-alive connections
+   * will be used if explicitly requested by the client.
+   * The "Connection:" header will be added for both "close" and "keep-alive"
+   * connections.
+   * Chunked encoding will not be used for the response.
+   * Due to backward compatibility, responses still can be used with
+   * HTTP/1.1 clients.
+   * This option can be used to emulate HTTP/1.0 server (for response part
+   * only as chunked encoding in requests (if any) is processed by MHD).
+   * @note Available since #MHD_VERSION 0x00097308
+   */
+  MHD_RF_HTTP_1_0_SERVER = 1 << 1,
+  /**
+   * The same as #MHD_RF_HTTP_1_0_SERVER
+   * @note Available since #MHD_VERSION 0x00096000
+   */
+  MHD_RF_HTTP_VERSION_1_0_RESPONSE = 1 << 1,
+
+  /**
+   * Disable sanity check preventing clients from manually
+   * setting the HTTP content length option.
+   * Allow to set several "Content-Length" headers. These headers will
+   * be used even with replies without body.
+   * @note Available since #MHD_VERSION 0x00096702
+   */
+  MHD_RF_INSANITY_HEADER_CONTENT_LENGTH = 1 << 2,
+
+  /**
+   * Enable sending of "Connection: keep-alive" header even for
+   * HTTP/1.1 clients when "Keep-Alive" connection is used.
+   * Disabled by default for HTTP/1.1 clients as per RFC.
+   * @note Available since #MHD_VERSION 0x00097310
+   */
+  MHD_RF_SEND_KEEP_ALIVE_HEADER = 1 << 3,
+
+  /**
+   * Enable special processing of the response as body-less (with undefined
+   * body size). No automatic "Content-Length" or "Transfer-Encoding: chunked"
+   * headers are added when the response is used with #MHD_HTTP_NOT_MODIFIED
+   * code or to respond to HEAD request.
+   * The flag also allow to set arbitrary "Content-Length" by
+   * MHD_add_response_header() function.
+   * This flag value can be used only with responses created without body
+   * (zero-size body).
+   * Responses with this flag enabled cannot be used in situations where
+   * reply body must be sent to the client.
+   * This flag is primarily intended to be used when automatic "Content-Length"
+   * header is undesirable in response to HEAD requests.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_RF_HEAD_ONLY_RESPONSE = 1 << 4
+} _MHD_FIXED_FLAGS_ENUM;
 
 
 /**
@@ -1899,7 +3714,7 @@
    * End of the list of options.
    */
   MHD_RO_END = 0
-};
+} _MHD_FIXED_ENUM;
 
 
 /**
@@ -1910,15 +3725,20 @@
  * @param ... #MHD_RO_END terminated list of options
  * @return #MHD_YES on success, #MHD_NO on error
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_set_response_options (struct MHD_Response *response,
                           enum MHD_ResponseFlags flags,
                           ...);
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object.
+ * The response object can be extended with header information and then be used
+ * any number of times.
+ *
+ * If response object is used to answer HEAD request then the body of the
+ * response is not used, while all headers (including automatic headers) are
+ * used.
  *
  * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown
  * @param block_size preferred block size for querying crc (advisory only,
@@ -1934,30 +3754,37 @@
  */
 _MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_callback (uint64_t size,
-				   size_t block_size,
-				   MHD_ContentReaderCallback crc, void *crc_cls,
-				   MHD_ContentReaderFreeCallback crfc);
+                                   size_t block_size,
+                                   MHD_ContentReaderCallback crc, void *crc_cls,
+                                   MHD_ContentReaderFreeCallback crfc);
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object.
+ * The response object can be extended with header information and then be used
+ * any number of times.
+ *
+ * If response object is used to answer HEAD request then the body of the
+ * response is not used, while all headers (including automatic headers) are
+ * used.
  *
  * @param size size of the @a data portion of the response
  * @param data the data itself
  * @param must_free libmicrohttpd should free data when done
  * @param must_copy libmicrohttpd must make a copy of @a data
- *        right away, the data maybe released anytime after
+ *        right away, the data may be released anytime after
  *        this call returns
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @deprecated use #MHD_create_response_from_buffer instead
  * @ingroup response
  */
-_MHD_EXTERN struct MHD_Response *
+_MHD_DEPR_FUNC ("MHD_create_response_from_data() is deprecated, " \
+                "use MHD_create_response_from_buffer()") \
+  _MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_data (size_t size,
-			       void *data,
-			       int must_free,
-			       int must_copy);
+                               void *data,
+                               int must_free,
+                               int must_copy);
 
 
 /**
@@ -1980,6 +3807,12 @@
    * Buffer is heap-allocated with `malloc()` (or equivalent) and
    * should be freed by MHD after processing the response has
    * concluded (response reference counter reaches zero).
+   * The more portable way to automatically free the buffer is function
+   * MHD_create_response_from_buffer_with_free_callback() with '&free' as
+   * crfc parameter as it does not require to use the same runtime library.
+   * @warning It is critical to make sure that the same C-runtime library
+   *          is used by both application and MHD (especially
+   *          important for W32).
    * @ingroup response
    */
   MHD_RESPMEM_MUST_FREE,
@@ -1993,12 +3826,19 @@
    */
   MHD_RESPMEM_MUST_COPY
 
-};
+} _MHD_FIXED_ENUM;
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the content of provided buffer used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
  *
  * @param size size of the data portion of the response
  * @param buffer size bytes containing the response's data portion
@@ -2008,13 +3848,127 @@
  */
 _MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_buffer (size_t size,
-				 void *buffer,
-				 enum MHD_ResponseMemoryMode mode);
+                                 void *buffer,
+                                 enum MHD_ResponseMemoryMode mode);
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the content of provided statically allocated
+ * buffer used as the response body.
+ *
+ * The buffer must be valid for the lifetime of the response. The easiest way
+ * to achieve this is to use a statically allocated buffer.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size the size of the data in @a buffer, can be zero
+ * @param buffer the buffer with the data for the response body, can be NULL
+ *               if @a size is zero
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_static (size_t size,
+                                        const void *buffer);
+
+
+/**
+ * Create a response object with the content of provided temporal buffer
+ * used as the response body.
+ *
+ * An internal copy of the buffer will be made automatically, so buffer have
+ * to be valid only during the call of this function (as a typical example:
+ * buffer is a local (non-static) array).
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size the size of the data in @a buffer, can be zero
+ * @param buffer the buffer with the data for the response body, can be NULL
+ *               if @a size is zero
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_copy (size_t size,
+                                      const void *buffer);
+
+
+/**
+ * Create a response object with the content of provided buffer used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response
+ * @param buffer size bytes containing the response's data portion
+ * @param crfc function to call to free the @a buffer
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00096000
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_with_free_callback (size_t size,
+                                                    void *buffer,
+                                                    MHD_ContentReaderFreeCallback
+                                                    crfc);
+
+
+/**
+ * Create a response object with the content of provided buffer used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response
+ * @param buffer size bytes containing the response's data portion
+ * @param crfc function to call to cleanup, if set to NULL then callback
+ *             is not called
+ * @param crfc_cls an argument for @a crfc
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097302
+ * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097601
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_with_free_callback_cls (size_t size,
+                                                        const void *buffer,
+                                                        MHD_ContentReaderFreeCallback
+                                                        crfc,
+                                                        void *crfc_cls);
+
+
+/**
+ * Create a response object with the content of provided file used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
  *
  * @param size size of the data portion of the response
  * @param fd file descriptor referring to a file on disk with the
@@ -2025,12 +3979,66 @@
  */
 _MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_fd (size_t size,
-			     int fd);
+                             int fd);
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the response body created by reading
+ * the provided pipe.
+ *
+ * The response object can be extended with header information and
+ * then be used ONLY ONCE.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param fd file descriptor referring to a read-end of a pipe with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097102
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_pipe (int fd);
+
+
+/**
+ * Create a response object with the content of provided file used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response;
+ *        sizes larger than 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @param fd file descriptor referring to a file on disk with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_fd64 (uint64_t size,
+                               int fd);
+
+
+/**
+ * Create a response object with the content of provided file with
+ * specified offset used as the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
  *
  * @param size size of the data portion of the response
  * @param fd file descriptor referring to a file on disk with the
@@ -2044,13 +4052,99 @@
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @ingroup response
  */
-_MHD_EXTERN struct MHD_Response *
+_MHD_DEPR_FUNC ("Function MHD_create_response_from_fd_at_offset() is " \
+                "deprecated, use MHD_create_response_from_fd_at_offset64()") \
+  _MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_fd_at_offset (size_t size,
-				       int fd,
-				       off_t offset);
+                                       int fd,
+                                       off_t offset);
+
+#if ! defined(_MHD_NO_DEPR_IN_MACRO) || defined(_MHD_NO_DEPR_FUNC)
+/* Substitute MHD_create_response_from_fd_at_offset64() instead of MHD_create_response_from_fd_at_offset()
+   to minimize potential problems with different off_t sizes */
+#define MHD_create_response_from_fd_at_offset(size,fd,offset) \
+  _MHD_DEPR_IN_MACRO ( \
+    "Usage of MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()") \
+  MHD_create_response_from_fd_at_offset64 ((size),(fd),(offset))
+#endif /* !_MHD_NO_DEPR_IN_MACRO || _MHD_NO_DEPR_FUNC */
 
 
-#if 0
+/**
+ * Create a response object with the content of provided file with
+ * specified offset used as the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response;
+ *        sizes larger than 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @param fd file descriptor referring to a file on disk with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @param offset offset to start reading from in the file;
+ *        reading file beyond 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_fd_at_offset64 (uint64_t size,
+                                         int fd,
+                                         uint64_t offset);
+
+
+/**
+ * Create a response object with an array of memory buffers
+ * used as the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param iov the array for response data buffers, an internal copy of this
+ *        will be made
+ * @param iovcnt the number of elements in @a iov
+ * @param free_cb the callback to clean up any data associated with @a iov when
+ *        the response is destroyed.
+ * @param cls the argument passed to @a free_cb
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097204
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_iovec (const struct MHD_IoVec *iov,
+                                unsigned int iovcnt,
+                                MHD_ContentReaderFreeCallback free_cb,
+                                void *cls);
+
+
+/**
+ * Create a response object with empty (zero size) body.
+ *
+ * The response object can be extended with header information and then be used
+ * any number of times.
+ *
+ * This function is a faster equivalent of #MHD_create_response_from_buffer call
+ * with zero size combined with call of #MHD_set_response_options.
+ *
+ * @param flags the flags for the new response object
+ * @return NULL on error (i.e. invalid arguments, out of memory),
+ *         the pointer to the created response object otherwise
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_empty (enum MHD_ResponseFlags flags);
+
+
 /**
  * Enumeration for actions MHD should perform on the underlying socket
  * of the upgrade.  This API is not finalized, and in particular
@@ -2064,24 +4158,28 @@
    * Close the socket, the application is done with it.
    *
    * Takes no extra arguments.
-   *
-   * NOTE: it is unclear if we want to have this in the
-   * "final" API, this is all just ideas.
    */
   MHD_UPGRADE_ACTION_CLOSE = 0,
 
   /**
-   * Uncork the TCP write buffer (that is, tell the OS to transmit all
-   * bytes in the buffer now, and to not use TCP-CORKing).
-   *
-   * Takes no extra arguments.
-   *
-   * NOTE: it is unclear if we want to have this in the
-   * "final" API, this is all just ideas.
+   * Enable CORKing on the underlying socket.
    */
-  MHD_UPGRADE_ACTION_CORK
+  MHD_UPGRADE_ACTION_CORK_ON = 1,
 
-};
+  /**
+   * Disable CORKing on the underlying socket.
+   */
+  MHD_UPGRADE_ACTION_CORK_OFF = 2
+
+} _MHD_FIXED_ENUM;
+
+
+/**
+ * Handle given to the application to manage special
+ * actions relating to MHD responses that "upgrade"
+ * the HTTP protocol (i.e. to WebSockets).
+ */
+struct MHD_UpgradeResponseHandle;
 
 
 /**
@@ -2090,67 +4188,73 @@
  * It allows applications to perform 'special' actions on
  * the underlying socket from the upgrade.
  *
- * @param cls the closure (from `upgrade_action_cls`)
+ * @param urh the handle identifying the connection to perform
+ *            the upgrade @a action on.
  * @param action which action should be performed
  * @param ... arguments to the action (depends on the action)
  * @return #MHD_NO on error, #MHD_YES on success
  */
-typedef int
-(*MHD_UpgradeActionCallback)(void *cls,
-                             enum MHD_UpgradeAction action,
-                             ...);
+_MHD_EXTERN enum MHD_Result
+MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh,
+                    enum MHD_UpgradeAction action,
+                    ...);
+
 
 /**
  * Function called after a protocol "upgrade" response was sent
  * successfully and the socket should now be controlled by some
  * protocol other than HTTP.
  *
- * Any data received on the socket will be made available in
- * 'data_in'.  The function should update 'data_in_size' to
- * reflect the number of bytes consumed from 'data_in' (the remaining
- * bytes will be made available in the next call to the handler).
+ * Any data already received on the socket will be made available in
+ * @e extra_in.  This can happen if the application sent extra data
+ * before MHD send the upgrade response.  The application should
+ * treat data from @a extra_in as if it had read it from the socket.
  *
- * Any data that should be transmitted on the socket should be
- * stored in 'data_out'.  '*data_out_size' is initially set to
- * the available buffer space in 'data_out'.  It should be set to
- * the number of bytes stored in 'data_out' (which can be zero).
+ * Note that the application must not close() @a sock directly,
+ * but instead use #MHD_upgrade_action() for special operations
+ * on @a sock.
  *
- * The return value is a BITMASK that indicates how the function
- * intends to interact with the event loop.  It can request to be
- * notified for reading, writing, request to UNCORK the send buffer
- * (which MHD is allowed to ignore, if it is not possible to uncork on
- * the local platform), to wait for the 'external' select loop to
- * trigger another round.  It is also possible to specify "no events"
- * to terminate the connection; in this case, the
- * #MHD_RequestCompletedCallback will be called and all resources of
- * the connection will be released.
+ * Data forwarding to "upgraded" @a sock will be started as soon
+ * as this function return.
  *
  * Except when in 'thread-per-connection' mode, implementations
  * of this function should never block (as it will still be called
  * from within the main event loop).
  *
- * @param cls closure
+ * @param cls closure, whatever was given to #MHD_create_response_for_upgrade().
  * @param connection original HTTP connection handle,
  *                   giving the function a last chance
  *                   to inspect the original HTTP request
+ * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback`
+ * @param extra_in if we happened to have read bytes after the
+ *                 HTTP header already (because the client sent
+ *                 more than the HTTP header of the request before
+ *                 we sent the upgrade response),
+ *                 these are the extra bytes already read from @a sock
+ *                 by MHD.  The application should treat these as if
+ *                 it had read them from @a sock.
+ * @param extra_in_size number of bytes in @a extra_in
  * @param sock socket to use for bi-directional communication
  *        with the client.  For HTTPS, this may not be a socket
  *        that is directly connected to the client and thus certain
  *        operations (TCP-specific setsockopt(), getsockopt(), etc.)
  *        may not work as expected (as the socket could be from a
- *        socketpair() or a TCP-loopback)
- * @param upgrade_action function that can be used to perform actions
- *        on the @a sock (like those that cannot be done explicitly).
- *        Applications must use this callback to perform the
- *        close() action on the @a sock.
- * @param upgrade_action_cls closure that must be passed to @a upgrade_action
+ *        socketpair() or a TCP-loopback).  The application is expected
+ *        to perform read()/recv() and write()/send() calls on the socket.
+ *        The application may also call shutdown(), but must not call
+ *        close() directly.
+ * @param urh argument for #MHD_upgrade_action()s on this @a connection.
+ *        Applications must eventually use this callback to (indirectly)
+ *        perform the close() action on the @a sock.
  */
 typedef void
 (*MHD_UpgradeHandler)(void *cls,
                       struct MHD_Connection *connection,
-                      MHD_SOCKET sock,
-                      MHD_UpgradeActionCallback upgrade_action,
-                      void *upgrade_action_cls);
+                      void *req_cls,
+                      const char *extra_in,
+                      size_t extra_in_size,
+                      MHD_socket sock,
+                      struct MHD_UpgradeResponseHandle *urh);
 
 
 /**
@@ -2178,20 +4282,20 @@
  * information and then be used any number of times (as long as the
  * header information is not connection-specific).
  *
- * @param upgrade_handler function to call with the 'upgraded' socket
+ * @param upgrade_handler function to call with the "upgraded" socket
  * @param upgrade_handler_cls closure for @a upgrade_handler
  * @return NULL on error (i.e. invalid arguments, out of memory)
  */
-struct MHD_Response *
+_MHD_EXTERN struct MHD_Response *
 MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler,
-				 void *upgrade_handler_cls);
-#endif
+                                 void *upgrade_handler_cls);
+
 
 /**
  * Destroy a response object and associated resources.  Note that
  * libmicrohttpd may keep some of the resources around if the response
  * is still in the queue for some clients, so the memory may not
- * necessarily be freed immediatley.
+ * necessarily be freed immediately.
  *
  * @param response response to destroy
  * @ingroup response
@@ -2203,17 +4307,56 @@
 /**
  * Add a header line to the response.
  *
- * @param response response to add a header to
- * @param header the header to add
- * @param content value to add
- * @return #MHD_NO on error (i.e. invalid header or content format),
+ * When reply is generated with queued response, some headers are generated
+ * automatically. Automatically generated headers are only sent to the client,
+ * but not added back to the response object.
+ *
+ * The list of automatic headers:
+ * + "Date" header is added automatically unless already set by
+ *   this function
+ *   @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK
+ * + "Content-Length" is added automatically when required, attempt to set
+ *   it manually by this function is ignored.
+ *   @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH
+ * + "Transfer-Encoding" with value "chunked" is added automatically,
+ *   when chunked transfer encoding is used automatically. Same header with
+ *   the same value can be set manually by this function to enforce chunked
+ *   encoding, however for HTTP/1.0 clients chunked encoding will not be used
+ *   and manually set "Transfer-Encoding" header is automatically removed
+ *   for HTTP/1.0 clients
+ * + "Connection" may be added automatically with value "Keep-Alive" (only
+ *   for HTTP/1.0 clients) or "Close". The header "Connection" with value
+ *   "Close" could be set by this function to enforce closure of
+ *   the connection after sending this response. "Keep-Alive" cannot be
+ *   enforced and will be removed automatically.
+ *   @see #MHD_RF_SEND_KEEP_ALIVE_HEADER
+ *
+ * Some headers are pre-processed by this function:
+ * * "Connection" headers are combined into single header entry, value is
+ *   normilised, "Keep-Alive" tokens are removed.
+ * * "Transfer-Encoding" header: the only one header is allowed, the only
+ *   allowed value is "chunked".
+ * * "Date" header: the only one header is allowed, the second added header
+ *   replaces the first one.
+ * * "Content-Length" application-defined header is not allowed.
+ *   @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH
+ *
+ * Headers are used in order as they were added.
+ *
+ * @param response the response to add a header to
+ * @param header the header name to add, no need to be static, an internal copy
+ *               will be created automatically
+ * @param content the header value to add, no need to be static, an internal
+ *                copy will be created automatically
+ * @return #MHD_YES on success,
+ *         #MHD_NO on error (i.e. invalid header or content format),
  *         or out of memory
  * @ingroup response
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_add_response_header (struct MHD_Response *response,
                          const char *header,
-			 const char *content);
+                         const char *content);
 
 
 /**
@@ -2225,25 +4368,30 @@
  * @return #MHD_NO on error (i.e. invalid footer or content format).
  * @ingroup response
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_add_response_footer (struct MHD_Response *response,
                          const char *footer,
-			 const char *content);
+                         const char *content);
 
 
 /**
  * Delete a header (or footer) line from the response.
  *
+ * For "Connection" headers this function remove all tokens from existing
+ * value. Successful result means that at least one token has been removed.
+ * If all tokens are removed from "Connection" header, the empty "Connection"
+ * header removed.
+ *
  * @param response response to remove a header from
  * @param header the header to delete
  * @param content value to delete
  * @return #MHD_NO on error (no such header known)
  * @ingroup response
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_del_response_header (struct MHD_Response *response,
                          const char *header,
-			 const char *content);
+                         const char *content);
 
 
 /**
@@ -2251,14 +4399,15 @@
  *
  * @param response response to query
  * @param iterator callback to call on each header;
- *        maybe NULL (then just count headers)
+ *        may be NULL (then just count headers)
  * @param iterator_cls extra argument to @a iterator
  * @return number of entries iterated over
  * @ingroup response
  */
 _MHD_EXTERN int
 MHD_get_response_headers (struct MHD_Response *response,
-                          MHD_KeyValueIterator iterator, void *iterator_cls);
+                          MHD_KeyValueIterator iterator,
+                          void *iterator_cls);
 
 
 /**
@@ -2271,7 +4420,7 @@
  */
 _MHD_EXTERN const char *
 MHD_get_response_header (struct MHD_Response *response,
-			 const char *key);
+                         const char *key);
 
 
 /* ********************** PostProcessor functions ********************** */
@@ -2303,8 +4452,8 @@
  */
 _MHD_EXTERN struct MHD_PostProcessor *
 MHD_create_post_processor (struct MHD_Connection *connection,
-			   size_t buffer_size,
-			   MHD_PostDataIterator iter, void *iter_cls);
+                           size_t buffer_size,
+                           MHD_PostDataIterator iter, void *iter_cls);
 
 
 /**
@@ -2320,9 +4469,10 @@
  *         (out-of-memory, iterator aborted, parse error)
  * @ingroup request
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_post_process (struct MHD_PostProcessor *pp,
-                  const char *post_data, size_t post_data_len);
+                  const char *post_data,
+                  size_t post_data_len);
 
 
 /**
@@ -2335,7 +4485,7 @@
  *                value of this function
  * @ingroup request
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_destroy_post_processor (struct MHD_PostProcessor *pp);
 
 
@@ -2343,8 +4493,1028 @@
 
 
 /**
+ * Length of the binary output of the MD5 hash function.
+ * @sa #MHD_digest_get_hash_size()
+ * @ingroup authentication
+ */
+#define MHD_MD5_DIGEST_SIZE 16
+
+/**
+ * Length of the binary output of the SHA-256 hash function.
+ * @sa #MHD_digest_get_hash_size()
+ * @ingroup authentication
+ */
+#define MHD_SHA256_DIGEST_SIZE 32
+
+/**
+ * Length of the binary output of the SHA-512/256 hash function.
+ * @warning While this value is the same as the #MHD_SHA256_DIGEST_SIZE,
+ *          the calculated digests for SHA-256 and SHA-512/256 are different.
+ * @sa #MHD_digest_get_hash_size()
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+#define MHD_SHA512_256_DIGEST_SIZE 32
+
+/**
+ * Base type of hash calculation.
+ * Used as part of #MHD_DigestAuthAlgo3 values.
+ *
+ * @warning Not used directly by MHD API.
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestBaseAlgo
+{
+  /**
+   * Invalid hash algorithm value
+   */
+  MHD_DIGEST_BASE_ALGO_INVALID = 0,
+
+  /**
+   * MD5 hash algorithm.
+   * As specified by RFC1321
+   */
+  MHD_DIGEST_BASE_ALGO_MD5 = (1 << 0),
+
+  /**
+   * SHA-256 hash algorithm.
+   * As specified by FIPS PUB 180-4
+   */
+  MHD_DIGEST_BASE_ALGO_SHA256 = (1 << 1),
+
+  /**
+   * SHA-512/256 hash algorithm.
+   * As specified by FIPS PUB 180-4
+   */
+  MHD_DIGEST_BASE_ALGO_SHA512_256 = (1 << 2)
+} _MHD_FIXED_FLAGS_ENUM;
+
+/**
+ * The flag indicating non-session algorithm types,
+ * like 'MD5', 'SHA-256' or 'SHA-512-256'.
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+#define MHD_DIGEST_AUTH_ALGO3_NON_SESSION    (1 << 6)
+
+/**
+ * The flag indicating session algorithm types,
+ * like 'MD5-sess', 'SHA-256-sess' or 'SHA-512-256-sess'.
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+#define MHD_DIGEST_AUTH_ALGO3_SESSION        (1 << 7)
+
+/**
+ * Digest algorithm identification
+ * @warning Do not be confused with #MHD_DigestAuthAlgorithm,
+ *          which uses other values!
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestAuthAlgo3
+{
+  /**
+   * Unknown or wrong algorithm type.
+   * Used in struct MHD_DigestAuthInfo to indicate client value that
+   * cannot by identified.
+   */
+  MHD_DIGEST_AUTH_ALGO3_INVALID = 0,
+
+  /**
+   * The 'MD5' algorithm, non-session version.
+   */
+  MHD_DIGEST_AUTH_ALGO3_MD5 =
+    MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION,
+
+  /**
+   * The 'MD5-sess' algorithm.
+   * Not supported by MHD for authentication.
+   */
+  MHD_DIGEST_AUTH_ALGO3_MD5_SESSION =
+    MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_SESSION,
+
+  /**
+   * The 'SHA-256' algorithm, non-session version.
+   */
+  MHD_DIGEST_AUTH_ALGO3_SHA256 =
+    MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION,
+
+  /**
+   * The 'SHA-256-sess' algorithm.
+   * Not supported by MHD for authentication.
+   */
+  MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION =
+    MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_SESSION,
+
+  /**
+   * The 'SHA-512-256' (SHA-512/256) algorithm.
+   */
+  MHD_DIGEST_AUTH_ALGO3_SHA512_256 =
+    MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION,
+
+  /**
+   * The 'SHA-512-256-sess' (SHA-512/256 session) algorithm.
+   * Not supported by MHD for authentication.
+   */
+  MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION =
+    MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_SESSION,
+};
+
+
+/**
+ * Get digest size for specified algorithm.
+ *
+ * The size of the digest specifies the size of the userhash, userdigest
+ * and other parameters which size depends on used hash algorithm.
+ * @param algo3 the algorithm to check
+ * @return the size of the digest (either #MHD_MD5_DIGEST_SIZE or
+ *         #MHD_SHA256_DIGEST_SIZE/MHD_SHA512_256_DIGEST_SIZE)
+ *         or zero if the input value is not supported or not valid
+ * @sa #MHD_digest_auth_calc_userdigest()
+ * @sa #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_calc_userhash_hex()
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN size_t
+MHD_digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3);
+
+/**
+ * Digest algorithm identification, allow multiple selection.
+ *
+ * #MHD_DigestAuthAlgo3 always can be casted to #MHD_DigestAuthMultiAlgo3, but
+ * not vice versa.
+ *
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestAuthMultiAlgo3
+{
+  /**
+   * Unknown or wrong algorithm type.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_INVALID = MHD_DIGEST_AUTH_ALGO3_INVALID,
+
+  /**
+   * The 'MD5' algorithm, non-session version.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_MD5 = MHD_DIGEST_AUTH_ALGO3_MD5,
+
+  /**
+   * The 'MD5-sess' algorithm.
+   * Not supported by MHD for authentication.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_MD5_SESSION = MHD_DIGEST_AUTH_ALGO3_MD5_SESSION,
+
+  /**
+   * The 'SHA-256' algorithm, non-session version.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_SHA256 = MHD_DIGEST_AUTH_ALGO3_SHA256,
+
+  /**
+   * The 'SHA-256-sess' algorithm.
+   * Not supported by MHD for authentication.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_SESSION =
+    MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION,
+
+  /**
+   * The 'SHA-512-256' (SHA-512/256) algorithm.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256 = MHD_DIGEST_AUTH_ALGO3_SHA512_256,
+
+  /**
+   * The 'SHA-512-256-sess' (SHA-512/256 session) algorithm.
+   * Not supported by MHD for authentication.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_SESSION =
+    MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION,
+
+  /**
+   * Any non-session algorithm, MHD will choose.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION =
+    (0x3F) | MHD_DIGEST_AUTH_ALGO3_NON_SESSION,
+
+  /**
+   * Any session algorithm, MHD will choose.
+   * Not supported by MHD.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_ANY_SESSION =
+    (0x3F) | MHD_DIGEST_AUTH_ALGO3_SESSION,
+
+  /**
+   * The 'MD5' algorithm, session or non-session.
+   * Not supported by MHD.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_MD5_ANY =
+    MHD_DIGEST_AUTH_MULT_ALGO3_MD5 | MHD_DIGEST_AUTH_MULT_ALGO3_MD5_SESSION,
+
+  /**
+   * The 'SHA-256' algorithm, session or non-session.
+   * Not supported by MHD.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_ANY =
+    MHD_DIGEST_AUTH_MULT_ALGO3_SHA256
+    | MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_SESSION,
+
+  /**
+   * The 'SHA-512/256' algorithm, session or non-session.
+   * Not supported by MHD.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_ANY =
+    MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256
+    | MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_SESSION,
+
+  /**
+   * Any algorithm, MHD will choose.
+   */
+  MHD_DIGEST_AUTH_MULT_ALGO3_ANY =
+    (0x3F) | MHD_DIGEST_AUTH_ALGO3_NON_SESSION | MHD_DIGEST_AUTH_ALGO3_SESSION
+};
+
+
+/**
+ * Calculate "userhash", return it as binary data.
+ *
+ * The "userhash" is the hash of the string "username:realm".
+ *
+ * The "Userhash" could be used to avoid sending username in cleartext in Digest
+ * Authorization client's header.
+ *
+ * Userhash is not designed to hide the username in local database or files,
+ * as username in cleartext is required for #MHD_digest_auth_check3() function
+ * to check the response, but it can be used to hide username in HTTP headers.
+ *
+ * This function could be used when the new username is added to the username
+ * database to save the "userhash" alongside with the username (preferably) or
+ * when loading list of the usernames to generate the userhash for every loaded
+ * username (this will cause delays at the start with the long lists).
+ *
+ * Once "userhash" is generated it could be used to identify users for clients
+ * with "userhash" support.
+ * Avoid repetitive usage of this function for the same username/realm
+ * combination as it will cause excessive CPU load; save and re-use the result
+ * instead.
+ *
+ * @param algo3 the algorithm for userhash calculations
+ * @param username the username
+ * @param realm the realm
+ * @param[out] userhash_bin the output buffer for userhash as binary data;
+ *                          if this function succeeds, then this buffer has
+ *                          #MHD_digest_get_hash_size(algo3) bytes of userhash
+ *                          upon return
+ * @param bin_buf_size the size of the @a userhash_bin buffer, must be
+ *                     at least #MHD_digest_get_hash_size(algo3) bytes long
+ * @return MHD_YES on success,
+ *         MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is
+ *         not supported (or external error has occurred,
+ *         see #MHD_FEATURE_EXTERN_HASH)
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_digest_auth_calc_userhash (enum MHD_DigestAuthAlgo3 algo3,
+                               const char *username,
+                               const char *realm,
+                               void *userhash_bin,
+                               size_t bin_buf_size);
+
+
+/**
+ * Calculate "userhash", return it as hexadecimal data.
+ *
+ * The "userhash" is the hash of the string "username:realm".
+ *
+ * The "Userhash" could be used to avoid sending username in cleartext in Digest
+ * Authorization client's header.
+ *
+ * Userhash is not designed to hide the username in local database or files,
+ * as username in cleartext is required for #MHD_digest_auth_check3() function
+ * to check the response, but it can be used to hide username in HTTP headers.
+ *
+ * This function could be used when the new username is added to the username
+ * database to save the "userhash" alongside with the username (preferably) or
+ * when loading list of the usernames to generate the userhash for every loaded
+ * username (this will cause delays at the start with the long lists).
+ *
+ * Once "userhash" is generated it could be used to identify users for clients
+ * with "userhash" support.
+ * Avoid repetitive usage of this function for the same username/realm
+ * combination as it will cause excessive CPU load; save and re-use the result
+ * instead.
+ *
+ * @param algo3 the algorithm for userhash calculations
+ * @param username the username
+ * @param realm the realm
+ * @param[out] userhash_hex the output buffer for userhash as hex data;
+ *                          if this function succeeds, then this buffer has
+ *                          #MHD_digest_get_hash_size(algo3)*2 chars long
+ *                          userhash string
+ * @param bin_buf_size the size of the @a userhash_bin buffer, must be
+ *                     at least #MHD_digest_get_hash_size(algo3)*2+1 chars long
+ * @return MHD_YES on success,
+ *         MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is
+ *         not supported (or external error has occurred,
+ *         see #MHD_FEATURE_EXTERN_HASH).
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_digest_auth_calc_userhash_hex (enum MHD_DigestAuthAlgo3 algo3,
+                                   const char *username,
+                                   const char *realm,
+                                   char *userhash_hex,
+                                   size_t hex_buf_size);
+
+
+/**
+ * The type of username used by client in Digest Authorization header
+ *
+ * Values are sorted so simplified checks could be used.
+ * For example:
+ * * (value <= MHD_DIGEST_AUTH_UNAME_TYPE_INVALID) is true if no valid username
+ *   is provided by the client
+ * * (value >= MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH) is true if username is
+ *   provided in any form
+ * * (value >= MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD) is true if username is
+ *   provided in clear text (not userhash matching is needed)
+ *
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestAuthUsernameType
+{
+  /**
+   * No username parameter in in Digest Authorization header.
+   * This should be treated as an error.
+   */
+  MHD_DIGEST_AUTH_UNAME_TYPE_MISSING = 0,
+
+  /**
+   * The 'username' parameter is used to specify the username.
+   */
+  MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD = (1 << 2),
+
+  /**
+   * The username is specified by 'username*' parameter with
+   * the extended notation (see RFC 5987 #section-3.2.1).
+   * The only difference between standard and extended types is
+   * the way how username value is encoded in the header.
+   */
+  MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED = (1 << 3),
+
+  /**
+   * The username provided in form of 'userhash' as
+   * specified by RFC 7616 #section-3.4.4.
+   * @sa #MHD_digest_auth_calc_userhash_hex(), #MHD_digest_auth_calc_userhash()
+   */
+  MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH = (1 << 1),
+
+  /**
+   * The invalid combination of username parameters are used by client.
+   * Either:
+   * * both 'username' and 'username*' are used
+   * * 'username*' is used with 'userhash=true'
+   * * 'username*' used with invalid extended notation
+   * * 'username' is not hexadecimal digits, while 'userhash' set to 'true'
+   */
+  MHD_DIGEST_AUTH_UNAME_TYPE_INVALID = (1 << 0)
+} _MHD_FIXED_ENUM;
+
+/**
+ * The QOP ('quality of protection') types.
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestAuthQOP
+{
+  /**
+   * Invalid/unknown QOP.
+   * Used in struct MHD_DigestAuthInfo to indicate client value that
+   * cannot by identified.
+   */
+  MHD_DIGEST_AUTH_QOP_INVALID = 0,
+
+  /**
+   * No QOP parameter.
+   * As described in old RFC 2069 original specification.
+   * This mode is not allowed by latest RFCs and should be used only to
+   * communicate with clients that do not support more modern modes (with QOP
+   * parameter).
+   * This mode is less secure than other modes and inefficient.
+   */
+  MHD_DIGEST_AUTH_QOP_NONE = 1 << 0,
+
+  /**
+   * The 'auth' QOP type.
+   */
+  MHD_DIGEST_AUTH_QOP_AUTH = 1 << 1,
+
+  /**
+   * The 'auth-int' QOP type.
+   * Not supported by MHD for authentication.
+   */
+  MHD_DIGEST_AUTH_QOP_AUTH_INT = 1 << 2
+} _MHD_FIXED_FLAGS_ENUM;
+
+/**
+ * The QOP ('quality of protection') types, multiple selection.
+ *
+ * #MHD_DigestAuthQOP always can be casted to #MHD_DigestAuthMultiQOP, but
+ * not vice versa.
+ *
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestAuthMultiQOP
+{
+  /**
+   * Invalid/unknown QOP.
+   */
+  MHD_DIGEST_AUTH_MULT_QOP_INVALID = MHD_DIGEST_AUTH_QOP_INVALID,
+
+  /**
+   * No QOP parameter.
+   * As described in old RFC 2069 original specification.
+   * This mode is not allowed by latest RFCs and should be used only to
+   * communicate with clients that do not support more modern modes (with QOP
+   * parameter).
+   * This mode is less secure than other modes and inefficient.
+   */
+  MHD_DIGEST_AUTH_MULT_QOP_NONE = MHD_DIGEST_AUTH_QOP_NONE,
+
+  /**
+   * The 'auth' QOP type.
+   */
+  MHD_DIGEST_AUTH_MULT_QOP_AUTH = MHD_DIGEST_AUTH_QOP_AUTH,
+
+  /**
+   * The 'auth-int' QOP type.
+   * Not supported by MHD.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_QOP_AUTH_INT = MHD_DIGEST_AUTH_QOP_AUTH_INT,
+
+  /**
+   * The 'auth' QOP type OR the old RFC2069 (no QOP) type.
+   * In other words: any types except 'auth-int'.
+   * RFC2069-compatible mode is allowed, thus this value should be used only
+   * when it is really necessary.
+   */
+  MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT =
+    MHD_DIGEST_AUTH_QOP_NONE | MHD_DIGEST_AUTH_QOP_AUTH,
+
+  /**
+   * Any 'auth' QOP type ('auth' or 'auth-int').
+   * Not supported by MHD.
+   * Reserved value.
+   */
+  MHD_DIGEST_AUTH_MULT_QOP_AUTH_ANY =
+    MHD_DIGEST_AUTH_QOP_AUTH | MHD_DIGEST_AUTH_QOP_AUTH_INT
+} _MHD_FIXED_ENUM;
+
+/**
+ * The invalid value of 'nc' parameter in client Digest Authorization header.
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+#define MHD_DIGEST_AUTH_INVALID_NC_VALUE        (0)
+
+/**
+ * Information from Digest Authorization client's header.
+ *
+ * All buffers pointed by any struct members are freed when #MHD_free() is
+ * called for pointer to this structure.
+ *
+ * Application may modify buffers as needed until #MHD_free() is called for
+ * pointer to this structure
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+struct MHD_DigestAuthInfo
+{
+  /**
+   * The algorithm as defined by client.
+   * Set automatically to MD5 if not specified by client.
+   * @warning Do not be confused with #MHD_DigestAuthAlgorithm,
+   *          which uses other values!
+   */
+  enum MHD_DigestAuthAlgo3 algo3;
+
+  /**
+   * The type of username used by client.
+   */
+  enum MHD_DigestAuthUsernameType uname_type;
+
+  /**
+   * The username string.
+   * Used only if username type is standard or extended, always NULL otherwise.
+   * If extended notation is used, this string is pct-decoded string
+   * with charset and language tag removed (i.e. it is original username
+   * extracted from the extended notation).
+   * When userhash is used by the client, this member is NULL and
+   * @a userhash_hex is set.
+   */
+  char *username;
+
+  /**
+   * The length of the @a username.
+   * When the @a username is NULL, this member is always zero.
+   */
+  size_t username_len;
+
+  /**
+   * The userhash string.
+   * Valid only if username type is userhash.
+   * This is unqoted string without decoding of the hexadecimal
+   * digits (as provided by the client).
+   * @sa #MHD_digest_auth_calc_userhash_hex()
+   */
+  char *userhash_hex;
+
+  /**
+   * The length of the @a userhash_hex in characters.
+   * The valid size should be #MHD_digest_get_hash_size(algo3) * 2 characters.
+   * When the @a userhash_hex is NULL, this member is always zero.
+   */
+  size_t userhash_hex_len;
+
+  /**
+   * The userhash decoded to binary form.
+   * Used only if username type is userhash, always NULL otherwise.
+   * When not NULL, this points to binary sequence @a userhash_hex_len /2 bytes
+   * long.
+   * The valid size should be #MHD_digest_get_hash_size(algo3) bytes.
+   * @warning This is binary data, no zero termination.
+   * @warning To avoid buffer overruns, always check the size of the data before
+   *          use, because @a userhash_bin can point even to zero-sized
+   *          data.
+   * @sa #MHD_digest_auth_calc_userhash()
+   */
+  uint8_t *userhash_bin;
+
+  /**
+   * The 'opaque' parameter value, as specified by client.
+   * NULL if not specified by client.
+   */
+  char *opaque;
+
+  /**
+   * The length of the @a opaque.
+   * When the @a opaque is NULL, this member is always zero.
+   */
+  size_t opaque_len;
+
+  /**
+   * The 'realm' parameter value, as specified by client.
+   * NULL if not specified by client.
+   */
+  char *realm;
+
+  /**
+   * The length of the @a realm.
+   * When the @a realm is NULL, this member is always zero.
+   */
+  size_t realm_len;
+
+  /**
+   * The 'qop' parameter value.
+   */
+  enum MHD_DigestAuthQOP qop;
+
+  /**
+   * The length of the 'cnonce' parameter value, including possible
+   * backslash-escape characters.
+   * 'cnonce' is used in hash calculation, which is CPU-intensive procedure.
+   * An application may want to reject too large cnonces to limit the CPU load.
+   * A few kilobytes is a reasonable limit, typically cnonce is just 32-160
+   * characters long.
+   */
+  size_t cnonce_len;
+
+  /**
+   * The nc parameter value.
+   * Can be used by application to limit the number of nonce re-uses. If @a nc
+   * is higher than application wants to allow, then auth required response with
+   * 'stale=true' could be used to force client to retry with the fresh 'nonce'.
+   * If not specified by client or does not have hexadecimal digits only, the
+   * value is #MHD_DIGEST_AUTH_INVALID_NC_VALUE.
+   */
+  uint32_t nc;
+};
+
+
+/**
+ * Get information about Digest Authorization client's header.
+ *
+ * @param connection The MHD connection structure
+ * @return NULL if no valid Digest Authorization header is used in the request;
+ *         a pointer to the structure with information if the valid request
+ *         header found, free using #MHD_free().
+ * @sa #MHD_digest_auth_get_username3()
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN struct MHD_DigestAuthInfo *
+MHD_digest_auth_get_request_info3 (struct MHD_Connection *connection);
+
+
+/**
+ * Information from Digest Authorization client's header.
+ *
+ * All buffers pointed by any struct members are freed when #MHD_free() is
+ * called for pointer to this structure.
+ *
+ * Application may modify buffers as needed until #MHD_free() is called for
+ * pointer to this structure
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+struct MHD_DigestAuthUsernameInfo
+{
+  /**
+   * The algorithm as defined by client.
+   * Set automatically to MD5 if not specified by client.
+   * @warning Do not be confused with #MHD_DigestAuthAlgorithm,
+   *          which uses other values!
+   */
+  enum MHD_DigestAuthAlgo3 algo3;
+
+  /**
+   * The type of username used by client.
+   * The 'invalid' and 'missing' types are not used in this structure,
+   * instead NULL is returned by #MHD_digest_auth_get_username3().
+   */
+  enum MHD_DigestAuthUsernameType uname_type;
+
+  /**
+   * The username string.
+   * Used only if username type is standard or extended, always NULL otherwise.
+   * If extended notation is used, this string is pct-decoded string
+   * with charset and language tag removed (i.e. it is original username
+   * extracted from the extended notation).
+   * When userhash is used by the client, this member is NULL and
+   * @a userhash_hex is set.
+   */
+  char *username;
+
+  /**
+   * The length of the @a username.
+   * When the @a username is NULL, this member is always zero.
+   */
+  size_t username_len;
+
+  /**
+   * The userhash string.
+   * Valid only if username type is userhash.
+   * This is unqoted string without decoding of the hexadecimal
+   * digits (as provided by the client).
+   * @sa #MHD_digest_auth_calc_userhash_hex()
+   */
+  char *userhash_hex;
+
+  /**
+   * The length of the @a userhash_hex in characters.
+   * The valid size should be #MHD_digest_get_hash_size(algo3) * 2 characters.
+   * When the @a userhash_hex is NULL, this member is always zero.
+   */
+  size_t userhash_hex_len;
+
+  /**
+   * The userhash decoded to binary form.
+   * Used only if username type is userhash, always NULL otherwise.
+   * When not NULL, this points to binary sequence @a userhash_hex_len /2 bytes
+   * long.
+   * The valid size should be #MHD_digest_get_hash_size(algo3) bytes.
+   * @warning This is binary data, no zero termination.
+   * @warning To avoid buffer overruns, always check the size of the data before
+   *          use, because @a userhash_bin can point even to zero-sized
+   *          data.
+   * @sa #MHD_digest_auth_calc_userhash()
+   */
+  uint8_t *userhash_bin;
+};
+
+
+/**
+ * Get the username from Digest Authorization client's header.
+ *
+ * @param connection The MHD connection structure
+ * @return NULL if no valid Digest Authorization header is used in the request,
+ *         or no username parameter is present in the header, or username is
+ *         provided incorrectly by client (see description for
+ *         #MHD_DIGEST_AUTH_UNAME_TYPE_INVALID);
+ *         a pointer structure with information if the valid request header
+ *         found, free using #MHD_free().
+ * @sa #MHD_digest_auth_get_request_info3() provides more complete information
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN struct MHD_DigestAuthUsernameInfo *
+MHD_digest_auth_get_username3 (struct MHD_Connection *connection);
+
+
+/**
+ * The result of digest authentication of the client.
+ *
+ * All error values are zero or negative.
+ *
+ * @note Available since #MHD_VERSION 0x00097601
+ */
+enum MHD_DigestAuthResult
+{
+  /**
+   * Authentication OK.
+   */
+  MHD_DAUTH_OK = 1,
+
+  /**
+   * General error, like "out of memory".
+   */
+  MHD_DAUTH_ERROR = 0,
+
+  /**
+   * No "Authorization" header or wrong format of the header.
+   * Also may be returned if required parameters in client Authorisation header
+   * are missing or broken (in invalid format).
+   */
+  MHD_DAUTH_WRONG_HEADER = -1,
+
+  /**
+   * Wrong 'username'.
+   */
+  MHD_DAUTH_WRONG_USERNAME = -2,
+
+  /**
+   * Wrong 'realm'.
+   */
+  MHD_DAUTH_WRONG_REALM = -3,
+
+  /**
+   * Wrong 'URI' (or URI parameters).
+   */
+  MHD_DAUTH_WRONG_URI = -4,
+
+  /**
+   * Wrong 'qop'.
+   */
+  MHD_DAUTH_WRONG_QOP = -5,
+
+  /**
+   * Wrong 'algorithm'.
+   */
+  MHD_DAUTH_WRONG_ALGO = -6,
+
+  /**
+   * Too large (>64 KiB) Authorization parameter value.
+   */
+  MHD_DAUTH_TOO_LARGE = -15,
+
+  /* The different form of naming is intentionally used for the results below,
+   * as they are more important */
+
+  /**
+   * The 'nonce' is too old. Suggest the client to retry with the same
+   * username and password to get the fresh 'nonce'.
+   * The validity of the 'nonce' may be not checked.
+   */
+  MHD_DAUTH_NONCE_STALE = -17,
+
+  /**
+   * The 'nonce' was generated by MHD for other conditions.
+   * This value is only returned if #MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE
+   * is set to anything other than #MHD_DAUTH_BIND_NONCE_NONE.
+   * The interpretation of this code could be different. For example, if
+   * #MHD_DAUTH_BIND_NONCE_URI is set and client just used the same 'nonce' for
+   * another URI, the code could be handled as #MHD_DAUTH_NONCE_STALE as
+   * it is allowed to re-use nonces for other URIs in the same "protection
+   * space". However, if only #MHD_DAUTH_BIND_NONCE_CLIENT_IP bit is set and
+   * it is know that clients have fixed IP addresses, this return code could
+   * be handled like #MHD_DAUTH_NONCE_WRONG.
+   */
+  MHD_DAUTH_NONCE_OTHER_COND = -18,
+
+  /**
+   * The 'nonce' is wrong. May indicate an attack attempt.
+   */
+  MHD_DAUTH_NONCE_WRONG = -33,
+
+  /**
+   * The 'response' is wrong. May indicate an attack attempt.
+   */
+  MHD_DAUTH_RESPONSE_WRONG = -34,
+};
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ *
+ * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in
+ * @a mqop and the client uses this mode, then server generated nonces are
+ * used as one-time nonces because nonce-count is not supported in this old RFC.
+ * Communication in this mode is very inefficient, especially if the client
+ * requests several resources one-by-one as for every request new nonce must be
+ * generated and client repeat all requests twice (first time to get a new
+ * nonce and second time to perform an authorised request).
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm to be used for authorization of the client
+ * @param username the username needs to be authenticated, must be in clear text
+ *                 even if userhash is used by the client
+ * @param password the password used in the authentication
+ * @param nonce_timeout the nonce validity duration in seconds
+ * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc
+ *               exceeds the specified value then MHD_DAUTH_NONCE_STALE is
+ *               returned;
+ *               zero for no limit
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithms allowed to use, fail if algorithm used
+ *               by the client is not allowed by this parameter
+ * @return #MHD_DAUTH_OK if authenticated,
+ *         the error code otherwise
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_DigestAuthResult
+MHD_digest_auth_check3 (struct MHD_Connection *connection,
+                        const char *realm,
+                        const char *username,
+                        const char *password,
+                        unsigned int nonce_timeout,
+                        uint32_t max_nc,
+                        enum MHD_DigestAuthMultiQOP mqop,
+                        enum MHD_DigestAuthMultiAlgo3 malgo3);
+
+
+/**
+ * Calculate userdigest, return it as binary data.
+ *
+ * The "userdigest" is the hash of the "username:realm:password" string.
+ *
+ * The "userdigest" can be used to avoid storing the password in clear text
+ * in database/files
+ *
+ * This function is designed to improve security of stored credentials,
+ * the "userdigest" does not improve security of the authentication process.
+ *
+ * The results can be used to store username & userdigest pairs instead of
+ * username & password pairs. To further improve security, application may
+ * store username & userhash & userdigest triplets.
+ *
+ * @param algo3 the digest algorithm
+ * @param username the username
+ * @param realm the realm
+ * @param password the password, must be zero-terminated
+ * @param[out] userdigest_bin the output buffer for userdigest;
+ *                            if this function succeeds, then this buffer has
+ *                            #MHD_digest_get_hash_size(algo3) bytes of
+ *                            userdigest upon return
+ * @param userdigest_bin the size of the @a userdigest_bin buffer, must be
+ *                       at least #MHD_digest_get_hash_size(algo3) bytes long
+ * @return MHD_YES on success,
+ *         MHD_NO if @a userdigest_bin is too small or if @a algo3 algorithm is
+ *         not supported (or external error has occurred,
+ *         see #MHD_FEATURE_EXTERN_HASH).
+ * @sa #MHD_digest_auth_check_digest3()
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_digest_auth_calc_userdigest (enum MHD_DigestAuthAlgo3 algo3,
+                                 const char *username,
+                                 const char *realm,
+                                 const char *password,
+                                 void *userdigest_bin,
+                                 size_t bin_buf_size);
+
+
+/**
+ * Authenticates the authorization header sent by the client by using
+ * hash of "username:realm:password".
+ *
+ * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in
+ * @a mqop and the client uses this mode, then server generated nonces are
+ * used as one-time nonces because nonce-count is not supported in this old RFC.
+ * Communication in this mode is very inefficient, especially if the client
+ * requests several resources one-by-one as for every request new nonce must be
+ * generated and client repeat all requests twice (first time to get a new
+ * nonce and second time to perform an authorised request).
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm to be used for authorization of the client
+ * @param username the username needs to be authenticated, must be in clear text
+ *                 even if userhash is used by the client
+ * @param userdigest the precalculated binary hash of the string
+ *                   "username:realm:password",
+ *                   see #MHD_digest_auth_calc_userdigest()
+ * @param userdigest_size the size of the @a userdigest in bytes, must match the
+ *                        hashing algorithm (see #MHD_MD5_DIGEST_SIZE,
+ *                        #MHD_SHA256_DIGEST_SIZE, #MHD_SHA512_256_DIGEST_SIZE,
+ *                        #MHD_digest_get_hash_size())
+ * @param nonce_timeout the period of seconds since nonce generation, when
+ *                      the nonce is recognised as valid and not stale.
+ * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc
+ *               exceeds the specified value then MHD_DAUTH_NONCE_STALE is
+ *               returned;
+ *               zero for no limit
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithms allowed to use, fail if algorithm used
+ *               by the client is not allowed by this parameter;
+ *               more than one base algorithms (MD5, SHA-256, SHA-512/256)
+ *               cannot be used at the same time for this function
+ *               as @a userdigest must match specified algorithm
+ * @return #MHD_DAUTH_OK if authenticated,
+ *         the error code otherwise
+ * @sa #MHD_digest_auth_calc_userdigest()
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_DigestAuthResult
+MHD_digest_auth_check_digest3 (struct MHD_Connection *connection,
+                               const char *realm,
+                               const char *username,
+                               const void *userdigest,
+                               size_t userdigest_size,
+                               unsigned int nonce_timeout,
+                               uint32_t max_nc,
+                               enum MHD_DigestAuthMultiQOP mqop,
+                               enum MHD_DigestAuthMultiAlgo3 malgo3);
+
+
+/**
+ * Queues a response to request authentication from the client
+ *
+ * This function modifies provided @a response. The @a response must not be
+ * reused and should be destroyed (by #MHD_destroy_response()) after call of
+ * this function.
+ *
+ * If @a mqop allows both RFC 2069 (MHD_DIGEST_AUTH_QOP_NONE) and QOP with
+ * value, then response is formed like if MHD_DIGEST_AUTH_QOP_NONE bit was
+ * not set, because such response should be backward-compatible with RFC 2069.
+ *
+ * If @a mqop allows only MHD_DIGEST_AUTH_MULT_QOP_NONE, then the response is
+ * formed in strict accordance with RFC 2069 (no 'qop', no 'userhash', no
+ * 'charset'). For better compatibility with clients, it is recommended (but
+ * not required) to set @a domain to NULL in this mode.
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param opaque the string for opaque value, can be NULL, but NULL is
+ *               not recommended for better compatibility with clients;
+ *               the recommended format is hex or Base64 encoded string
+ * @param domain the optional space-separated list of URIs for which the
+ *               same authorisation could be used, URIs can be in form
+ *               "path-absolute" (the path for the same host with initial slash)
+ *               or in form "absolute-URI" (the full path with protocol), in
+ *               any case client may assume that URI is in the same "protection
+ *               space" if it starts with any of values specified here;
+ *               could be NULL (clients typically assume that the same
+ *               credentials could be used for any URI on the same host)
+ * @param response the reply to send; should contain the "access denied"
+ *                 body; note that this function sets the "WWW Authenticate"
+ *                 header and that the caller should not do this;
+ *                 the NULL is tolerated
+ * @param signal_stale set to #MHD_YES if the nonce is stale to add 'stale=true'
+ *                     to the authentication header, this instructs the client
+ *                     to retry immediately with the new nonce and the same
+ *                     credentials, without asking user for the new password
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithm to use, MHD selects; if several algorithms
+ *               are allowed then MD5 is preferred (currently, may be changed
+ *               in next versions)
+ * @param userhash_support if set to non-zero value (#MHD_YES) then support of
+ *                         userhash is indicated, the client may provide
+ *                         hash("username:realm") instead of username in
+ *                         clear text;
+ *                         note that clients are allowed to provide the username
+ *                         in cleartext even if this parameter set to non-zero;
+ *                         when userhash is used, application must be ready to
+ *                         identify users by provided userhash value instead of
+ *                         username; see #MHD_digest_auth_calc_userhash() and
+ *                         #MHD_digest_auth_calc_userhash_hex()
+ * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is
+ *                    added, indicating for the client that UTF-8 encoding
+ *                    is preferred
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_queue_auth_required_response3 (struct MHD_Connection *connection,
+                                   const char *realm,
+                                   const char *opaque,
+                                   const char *domain,
+                                   struct MHD_Response *response,
+                                   int signal_stale,
+                                   enum MHD_DigestAuthMultiQOP qop,
+                                   enum MHD_DigestAuthMultiAlgo3 algo,
+                                   int userhash_support,
+                                   int prefer_utf8);
+
+
+/**
  * Constant to indicate that the nonce of the provided
  * authentication code was wrong.
+ * Used as return code by #MHD_digest_auth_check(), #MHD_digest_auth_check2(),
+ * #MHD_digest_auth_check_digest(), #MHD_digest_auth_check_digest2().
  * @ingroup authentication
  */
 #define MHD_INVALID_NONCE -1
@@ -2353,9 +5523,16 @@
 /**
  * Get the username from the authorization header sent by the client
  *
+ * This function supports username in standard and extended notations.
+ * "userhash" is not supported by this function.
+ *
  * @param connection The MHD connection structure
- * @return NULL if no username could be found, a pointer
- * 			to the username if found
+ * @return NULL if no username could be found, username provided as
+ *         "userhash", extended notation broken or memory allocation error
+ *         occurs;
+ *         a pointer to the username if found, free using #MHD_free().
+ * @warning Returned value must be freed by #MHD_free().
+ * @sa #MHD_digest_auth_get_username3()
  * @ingroup authentication
  */
 _MHD_EXTERN char *
@@ -2363,60 +5540,301 @@
 
 
 /**
- * Authenticates the authorization header sent by the client
+ * MHD digest auth internal code for an invalid nonce.
+ */
+#define MHD_INVALID_NONCE -1
+
+
+/**
+ * Which digest algorithm should MHD use for HTTP digest authentication?
+ * Used as parameter for #MHD_digest_auth_check2(),
+ * #MHD_digest_auth_check_digest2(), #MHD_queue_auth_fail_response2().
+ */
+enum MHD_DigestAuthAlgorithm
+{
+
+  /**
+   * MHD should pick (currently defaults to MD5).
+   */
+  MHD_DIGEST_ALG_AUTO = 0,
+
+  /**
+   * Force use of MD5.
+   */
+  MHD_DIGEST_ALG_MD5,
+
+  /**
+   * Force use of SHA-256.
+   */
+  MHD_DIGEST_ALG_SHA256
+
+} _MHD_FIXED_ENUM;
+
+
+/**
+ * Authenticates the authorization header sent by the client.
  *
  * @param connection The MHD connection structure
  * @param realm The realm presented to the client
  * @param username The username needs to be authenticated
  * @param password The password used in the authentication
  * @param nonce_timeout The amount of time for a nonce to be
- * 			invalid in seconds
+ *      invalid in seconds
+ * @param algo digest algorithms allowed for verification
  * @return #MHD_YES if authenticated, #MHD_NO if not,
- * 			#MHD_INVALID_NONCE if nonce is invalid
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @note Available since #MHD_VERSION 0x00096200
+ * @deprecated use MHD_digest_auth_check3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check2 (struct MHD_Connection *connection,
+                        const char *realm,
+                        const char *username,
+                        const char *password,
+                        unsigned int nonce_timeout,
+                        enum MHD_DigestAuthAlgorithm algo);
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ * Uses #MHD_DIGEST_ALG_MD5 (for now, for backwards-compatibility).
+ * Note that this MAY change to #MHD_DIGEST_ALG_AUTO in the future.
+ * If you want to be sure you get MD5, use #MHD_digest_auth_check2()
+ * and specify MD5 explicitly.
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param password The password used in the authentication
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @deprecated use MHD_digest_auth_check3()
  * @ingroup authentication
  */
 _MHD_EXTERN int
 MHD_digest_auth_check (struct MHD_Connection *connection,
-		       const char *realm,
-		       const char *username,
-		       const char *password,
-		       unsigned int nonce_timeout);
+                       const char *realm,
+                       const char *username,
+                       const char *password,
+                       unsigned int nonce_timeout);
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param digest An `unsigned char *' pointer to the binary MD5 sum
+ *      for the precalculated hash value "username:realm:password"
+ *      of @a digest_size bytes
+ * @param digest_size number of bytes in @a digest (size must match @a algo!)
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @param algo digest algorithms allowed for verification
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @note Available since #MHD_VERSION 0x00096200
+ * @deprecated use MHD_digest_auth_check_digest3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check_digest2 (struct MHD_Connection *connection,
+                               const char *realm,
+                               const char *username,
+                               const uint8_t *digest,
+                               size_t digest_size,
+                               unsigned int nonce_timeout,
+                               enum MHD_DigestAuthAlgorithm algo);
+
+
+/**
+ * Authenticates the authorization header sent by the client
+ * Uses #MHD_DIGEST_ALG_MD5 (required, as @a digest is of fixed
+ * size).
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param digest An `unsigned char *' pointer to the binary hash
+ *    for the precalculated hash value "username:realm:password";
+ *    length must be #MHD_MD5_DIGEST_SIZE bytes
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @note Available since #MHD_VERSION 0x00096000
+ * @deprecated use #MHD_digest_auth_check_digest3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check_digest (struct MHD_Connection *connection,
+                              const char *realm,
+                              const char *username,
+                              const uint8_t digest[MHD_MD5_DIGEST_SIZE],
+                              unsigned int nonce_timeout);
 
 
 /**
  * Queues a response to request authentication from the client
  *
+ * This function modifies provided @a response. The @a response must not be
+ * reused and should be destroyed after call of this function.
+ *
  * @param connection The MHD connection structure
- * @param realm The realm presented to the client
+ * @param realm the realm presented to the client
  * @param opaque string to user for opaque value
  * @param response reply to send; should contain the "access denied"
  *        body; note that this function will set the "WWW Authenticate"
- *        header and that the caller should not do this
- * @param signal_stale #MHD_YES if the nonce is invalid to add
- * 			'stale=true' to the authentication header
+ *        header and that the caller should not do this; the NULL is tolerated
+ * @param signal_stale #MHD_YES if the nonce is stale to add
+ *        'stale=true' to the authentication header
+ * @param algo digest algorithm to use
  * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00096200
+ * @deprecated use MHD_queue_auth_required_response3()
  * @ingroup authentication
  */
-_MHD_EXTERN int
-MHD_queue_auth_fail_response (struct MHD_Connection *connection,
-			      const char *realm,
-			      const char *opaque,
-			      struct MHD_Response *response,
-			      int signal_stale);
+_MHD_EXTERN enum MHD_Result
+MHD_queue_auth_fail_response2 (struct MHD_Connection *connection,
+                               const char *realm,
+                               const char *opaque,
+                               struct MHD_Response *response,
+                               int signal_stale,
+                               enum MHD_DigestAuthAlgorithm algo);
 
 
 /**
+ * Queues a response to request authentication from the client.
+ * For now uses MD5 (for backwards-compatibility). Still, if you
+ * need to be sure, use #MHD_queue_auth_fail_response2().
+ *
+ * This function modifies provided @a response. The @a response must not be
+ * reused and should be destroyed after call of this function.
+ *
+ * @param connection The MHD connection structure
+ * @param realm the realm presented to the client
+ * @param opaque string to user for opaque value
+ * @param response reply to send; should contain the "access denied"
+ *        body; note that this function will set the "WWW Authenticate"
+ *        header and that the caller should not do this; the NULL is tolerated
+ * @param signal_stale #MHD_YES if the nonce is stale to add
+ *        'stale=true' to the authentication header
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @deprecated use MHD_queue_auth_required_response3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_queue_auth_fail_response (struct MHD_Connection *connection,
+                              const char *realm,
+                              const char *opaque,
+                              struct MHD_Response *response,
+                              int signal_stale);
+
+
+/* ********************* Basic Authentication functions *************** */
+
+
+/**
+ * Information decoded from Basic Authentication client's header.
+ *
+ * The username and the password are technically allowed to have binary zeros,
+ * username_len and password_len could be used to detect such situations.
+ *
+ * The buffers pointed by username and password members are freed
+ * when #MHD_free() is called for pointer to this structure.
+ *
+ * Application may modify buffers as needed until #MHD_free() is called for
+ * pointer to this structure
+ */
+struct MHD_BasicAuthInfo
+{
+  /**
+   * The username, cannot be NULL
+   */
+  char *username;
+
+  /**
+   * The length of the @a username, not including zero-termination
+   */
+  size_t username_len;
+
+  /**
+   * The password, may be NULL if password is not encoded by the client
+   */
+  char *password;
+
+  /**
+   * The length of the @a password, not including zero-termination;
+   * when the @a password is NULL, the length is always zero.
+   */
+  size_t password_len;
+};
+
+/**
+ * Get the username and password from the Basic Authorisation header
+ * sent by the client
+ *
+ * @param connection the MHD connection structure
+ * @return NULL if no valid Basic Authentication header is present in
+ *         current request, or
+ *         pointer to structure with username and password, which must be
+ *         freed by #MHD_free().
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN struct MHD_BasicAuthInfo *
+MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection);
+
+/**
  * Get the username and password from the basic authorization header sent by the client
  *
  * @param connection The MHD connection structure
- * @param password a pointer for the password
+ * @param[out] password a pointer for the password, free using #MHD_free().
  * @return NULL if no username could be found, a pointer
- * 			to the username if found
+ *      to the username if found, free using #MHD_free().
+ * @deprecated use #MHD_basic_auth_get_username_password3()
  * @ingroup authentication
  */
 _MHD_EXTERN char *
 MHD_basic_auth_get_username_password (struct MHD_Connection *connection,
-				      char** password);
+                                      char **password);
+
+
+/**
+ * Queues a response to request basic authentication from the client.
+ *
+ * The given response object is expected to include the payload for
+ * the response; the "WWW-Authenticate" header will be added and the
+ * response queued with the 'UNAUTHORIZED' status code.
+ *
+ * See RFC 7617#section-2 for details.
+ *
+ * The @a response is modified by this function. The modified response object
+ * can be used to respond subsequent requests by #MHD_queue_response()
+ * function with status code #MHD_HTTP_UNAUTHORIZED and must not be used again
+ * with MHD_queue_basic_auth_fail_response3() function. The response could
+ * be destroyed right after call of this function.
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param prefer_utf8 if not set to #MHD_NO, parameter'charset="UTF-8"' will
+ *                    be added, indicating for client that UTF-8 encoding
+ *                    is preferred
+ * @param response the response object to modify and queue; the NULL
+ *                 is tolerated
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_queue_basic_auth_fail_response3 (struct MHD_Connection *connection,
+                                     const char *realm,
+                                     int prefer_utf8,
+                                     struct MHD_Response *response);
 
 
 /**
@@ -2427,20 +5845,23 @@
  *
  * @param connection The MHD connection structure
  * @param realm the realm presented to the client
- * @param response response object to modify and queue
+ * @param response response object to modify and queue; the NULL is tolerated
  * @return #MHD_YES on success, #MHD_NO otherwise
+ * @deprecated use MHD_queue_basic_auth_fail_response3()
  * @ingroup authentication
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection,
-				    const char *realm,
-				    struct MHD_Response *response);
+                                    const char *realm,
+                                    struct MHD_Response *response);
 
 /* ********************** generic query functions ********************** */
 
 
 /**
  * Obtain information about the given connection.
+ * The returned pointer is invalidated with the next call of this function or
+ * when the connection is closed.
  *
  * @param connection what connection to get information about
  * @param info_type what information is desired?
@@ -2451,8 +5872,8 @@
  */
 _MHD_EXTERN const union MHD_ConnectionInfo *
 MHD_get_connection_info (struct MHD_Connection *connection,
-			 enum MHD_ConnectionInfoType info_type,
-			 ...);
+                         enum MHD_ConnectionInfoType info_type,
+                         ...);
 
 
 /**
@@ -2466,10 +5887,14 @@
    * Set a custom timeout for the given connection.  Specified
    * as the number of seconds, given as an `unsigned int`.  Use
    * zero for no timeout.
+   * If timeout was set to zero (or unset) before, setup of new value by
+   * MHD_set_connection_option() will reset timeout timer.
+   * Values larger than (UINT64_MAX / 2000 - 1) will
+   * be clipped to this number.
    */
   MHD_CONNECTION_OPTION_TIMEOUT
 
-};
+} _MHD_FIXED_ENUM;
 
 
 /**
@@ -2481,10 +5906,10 @@
  * @return #MHD_YES on success, #MHD_NO if setting the option failed
  * @ingroup specialized
  */
-_MHD_EXTERN int
+_MHD_EXTERN enum MHD_Result
 MHD_set_connection_option (struct MHD_Connection *connection,
-			   enum MHD_CONNECTION_OPTION option,
-			   ...);
+                           enum MHD_CONNECTION_OPTION option,
+                           ...);
 
 
 /**
@@ -2505,21 +5930,39 @@
   size_t mac_key_size;
 
   /**
-   * Listen socket file descriptor, for #MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY
-   * and #MHD_DAEMON_INFO_LISTEN_FD.
+   * Socket, returned for #MHD_DAEMON_INFO_LISTEN_FD.
    */
   MHD_socket listen_fd;
 
   /**
+   * Bind port number, returned for #MHD_DAEMON_INFO_BIND_PORT.
+   */
+  uint16_t port;
+
+  /**
+   * epoll FD, returned for #MHD_DAEMON_INFO_EPOLL_FD.
+   */
+  int epoll_fd;
+
+  /**
    * Number of active connections, for #MHD_DAEMON_INFO_CURRENT_CONNECTIONS.
    */
   unsigned int num_connections;
+
+  /**
+   * Combination of #MHD_FLAG values, for #MHD_DAEMON_INFO_FLAGS.
+   * This value is actually a bitfield.
+   * Note: flags may differ from original 'flags' specified for
+   * daemon, especially if #MHD_USE_AUTO was set.
+   */
+  enum MHD_FLAG flags;
 };
 
 
 /**
- * Obtain information about the given daemon
- * (not fully implemented!).
+ * Obtain information about the given daemon.
+ * The returned pointer is invalidated with the next call of this function or
+ * when the daemon is stopped.
  *
  * @param daemon what daemon to get information about
  * @param info_type what information is desired?
@@ -2530,8 +5973,8 @@
  */
 _MHD_EXTERN const union MHD_DaemonInfo *
 MHD_get_daemon_info (struct MHD_Daemon *daemon,
-		     enum MHD_DaemonInfoType info_type,
-		     ...);
+                     enum MHD_DaemonInfoType info_type,
+                     ...);
 
 
 /**
@@ -2540,11 +5983,23 @@
  * @return static version string, e.g. "0.9.9"
  * @ingroup specialized
  */
-_MHD_EXTERN const char*
+_MHD_EXTERN const char *
 MHD_get_version (void);
 
 
 /**
+ * Obtain the version of this library as a binary value.
+ *
+ * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of
+ *         compiled MHD binary)
+ * @note Available since #MHD_VERSION 0x00097601
+ * @ingroup specialized
+ */
+_MHD_EXTERN uint32_t
+MHD_get_version_bin (void);
+
+
+/**
  * Types of information about MHD features,
  * used by #MHD_is_feature_supported().
  */
@@ -2554,15 +6009,16 @@
    * Get whether messages are supported. If supported then in debug
    * mode messages can be printed to stderr or to external logger.
    */
-  MHD_FEATURE_MESSGES = 1,
+  MHD_FEATURE_MESSAGES = 1,
 
   /**
    * Get whether HTTPS is supported.  If supported then flag
-   * #MHD_USE_SSL and options #MHD_OPTION_HTTPS_MEM_KEY,
+   * #MHD_USE_TLS and options #MHD_OPTION_HTTPS_MEM_KEY,
    * #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST,
    * #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_CRED_TYPE,
    * #MHD_OPTION_HTTPS_PRIORITIES can be used.
    */
+  MHD_FEATURE_TLS = 2,
   MHD_FEATURE_SSL = 2,
 
   /**
@@ -2580,7 +6036,7 @@
   /**
    * Get whether IPv6 without IPv4 is supported. If not supported
    * then IPv4 is always enabled in IPv6 sockets and
-   * flag #MHD_USE_DUAL_STACK if always used when #MHD_USE_IPv6 is
+   * flag #MHD_USE_DUAL_STACK is always used when #MHD_USE_IPv6 is
    * specified.
    */
   MHD_FEATURE_IPv6_ONLY = 5,
@@ -2593,15 +6049,15 @@
 
   /**
    * Get whether `epoll()` is supported. If supported then Flags
-   * #MHD_USE_EPOLL_LINUX_ONLY and
-   * #MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY can be used.
+   * #MHD_USE_EPOLL and
+   * #MHD_USE_EPOLL_INTERNAL_THREAD can be used.
    */
   MHD_FEATURE_EPOLL = 7,
 
   /**
    * Get whether shutdown on listen socket to signal other
    * threads is supported. If not supported flag
-   * #MHD_USE_PIPE_FOR_SHUTDOWN is automatically forced.
+   * #MHD_USE_ITC is automatically forced.
    */
   MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET = 8,
 
@@ -2646,7 +6102,164 @@
   * supported. If supported then option
   * ::MHD_OPTION_HTTPS_KEY_PASSWORD can be used.
   */
-  MHD_FEATURE_HTTPS_KEY_PASSWORD = 14
+  MHD_FEATURE_HTTPS_KEY_PASSWORD = 14,
+
+  /**
+   * Get whether reading files beyond 2 GiB boundary is supported.
+   * If supported then #MHD_create_response_from_fd(),
+   * #MHD_create_response_from_fd64 #MHD_create_response_from_fd_at_offset()
+   * and #MHD_create_response_from_fd_at_offset64() can be used with sizes and
+   * offsets larger than 2 GiB. If not supported value of size+offset is
+   * limited to 2 GiB.
+   */
+  MHD_FEATURE_LARGE_FILE = 15,
+
+  /**
+   * Get whether MHD set names on generated threads.
+   */
+  MHD_FEATURE_THREAD_NAMES = 16,
+  MHD_THREAD_NAMES = 16,
+
+  /**
+   * Get whether HTTP "Upgrade" is supported.
+   * If supported then #MHD_ALLOW_UPGRADE, #MHD_upgrade_action() and
+   * #MHD_create_response_for_upgrade() can be used.
+   */
+  MHD_FEATURE_UPGRADE = 17,
+
+  /**
+   * Get whether it's safe to use same FD for multiple calls of
+   * #MHD_create_response_from_fd() and whether it's safe to use single
+   * response generated by #MHD_create_response_from_fd() with multiple
+   * connections at same time.
+   * If #MHD_is_feature_supported() return #MHD_NO for this feature then
+   * usage of responses with same file FD in multiple parallel threads may
+   * results in incorrect data sent to remote client.
+   * It's always safe to use same file FD in multiple responses if MHD
+   * is run in any single thread mode.
+   */
+  MHD_FEATURE_RESPONSES_SHARED_FD = 18,
+
+  /**
+   * Get whether MHD support automatic detection of bind port number.
+   * @sa #MHD_DAEMON_INFO_BIND_PORT
+   */
+  MHD_FEATURE_AUTODETECT_BIND_PORT = 19,
+
+  /**
+   * Get whether MHD supports automatic SIGPIPE suppression.
+   * If SIGPIPE suppression is not supported, application must handle
+   * SIGPIPE signal by itself.
+   */
+  MHD_FEATURE_AUTOSUPPRESS_SIGPIPE = 20,
+
+  /**
+   * Get whether MHD use system's sendfile() function to send
+   * file-FD based responses over non-TLS connections.
+   * @note Since v0.9.56
+   */
+  MHD_FEATURE_SENDFILE = 21,
+
+  /**
+   * Get whether MHD supports threads.
+   */
+  MHD_FEATURE_THREADS = 22,
+
+  /**
+   * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK2 is
+   * supported.
+   */
+  MHD_FEATURE_HTTPS_CERT_CALLBACK2 = 23,
+
+  /**
+   * Get whether automatic parsing of HTTP Cookie header is supported.
+   * If disabled, no MHD_COOKIE_KIND will be generated by MHD.
+   * MHD versions before 0x00097601 always support cookie parsing.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_HTTPS_COOKIE_PARSING = 24,
+
+  /**
+   * Get whether the early version the Digest Authorization (RFC 2069) is
+   * supported (digest authorisation without QOP parameter).
+   * Since #MHD_VERSION 0x00097601 it is always supported if Digest Auth
+   * module is built.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_RFC2069 = 25,
+
+  /**
+   * Get whether the MD5-based hashing algorithms are supported for Digest
+   * Authorization.
+   * Currently it is always supported if Digest Auth module is built
+   * unless manually disabled in a custom build.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_MD5 = 26,
+
+  /**
+   * Get whether the SHA-256-based hashing algorithms are supported for Digest
+   * Authorization.
+   * It it always supported since #MHD_VERSION 0x00096200 if Digest Auth
+   * module is built unless manually disabled in a custom build.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_SHA256 = 27,
+
+  /**
+   * Get whether the SHA-512/256-based hashing algorithms are supported
+   * for Digest Authorization.
+   * It it always supported since #MHD_VERSION 0x00097601 if Digest Auth
+   * module is built unless manually disabled in a custom build.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_SHA512_256 = 28,
+
+  /**
+   * Get whether QOP with value 'auth-int' (authentication with integrity
+   * protection) is supported for Digest Authorization.
+   * Currently it is always not supported.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_AUTH_INT = 29,
+
+  /**
+   * Get whether 'session' algorithms (like 'MD5-sess') are supported for Digest
+   * Authorization.
+   * Currently it is always not supported.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION = 30,
+
+  /**
+   * Get whether 'userhash' is supported for Digest Authorization.
+   * It is always supported since #MHD_VERSION 0x00097601 if Digest Auth
+   * module is built.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DIGEST_AUTH_USERHASH = 31,
+
+  /**
+   * Get whether any of hashing algorithms is implemented by external
+   * function (like TLS library) and may fail due to external conditions,
+   * like "out-of-memory".
+   *
+   * If result is #MHD_YES then functions which use hash calculations
+   * like #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_check3() and others
+   * potentially may fail even with valid input because of out-of-memory error
+   * or crypto accelerator device failure, however in practice such fails are
+   * unlikely.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_EXTERN_HASH = 32,
+
+  /**
+   * Get whether MHD was built with asserts enabled.
+   * For debug builds the error log is always enabled even if #MHD_USE_ERROR_LOG
+   * is not specified for daemon.
+   * @note Available since #MHD_VERSION 0x00097601
+   */
+  MHD_FEATURE_DEBUG_BUILD = 33
 };
 
 
@@ -2661,14 +6274,14 @@
  * feature is not supported or feature is unknown.
  * @ingroup specialized
  */
-_MHD_EXTERN int
-MHD_is_feature_supported(enum MHD_FEATURE feature);
+_MHD_EXTERN enum MHD_Result
+MHD_is_feature_supported (enum MHD_FEATURE feature);
 
 
+#ifdef __cplusplus
 #if 0                           /* keep Emacsens' auto-indent happy */
 {
 #endif
-#ifdef __cplusplus
 }
 #endif
 
diff --git a/src/include/microhttpd2.h b/src/include/microhttpd2.h
new file mode 100644
index 0000000..4a4541f
--- /dev/null
+++ b/src/include/microhttpd2.h
@@ -0,0 +1,4250 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2006-2018 Christian Grothoff, Karlson2k (Evgeny Grin)
+     (and other contributing authors)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * Just includes the NEW definitions for the NG-API.
+ * Note that we do not indicate which of the OLD APIs
+ * simply need to be kept vs. deprecated.
+ *
+ *
+ * The goal is to provide a basis for discussion!
+ * Little of this is implemented yet.
+ *
+ * Main goals:
+ * - simplify application callbacks by splitting header/upload/post
+ *   functionality currently provided by calling the same
+ *   MHD_AccessHandlerCallback 3+ times into separate callbacks.
+ * - keep the API very simple for simple requests, but allow
+ *   more complex logic to be incrementally introduced
+ *   (via new struct MHD_Action construction)
+ * - avoid repeated scans for URL matches via the new
+ *   struct MHD_Action construction
+ * - provide default logarithmic implementation of URL scan
+ *   => reduce strcmp(url) from >= 3n operations to "log n"
+ *      per request.
+ * - better types, in particular avoid varargs for options
+ * - make it harder to pass inconsistent options
+ * - combine options and flags into more uniform API (at least
+ *   exterally!)
+ * - simplify API use by using sane defaults (benefiting from
+ *   breaking backwards compatibility) and making all options
+ *   really optional, and where applicable avoid having options
+ *   where the default works if nothing is specified
+ * - simplify API by moving rarely used http_version into
+ *   MHD_request_get_information()
+ * - avoid 'int' for MHD_YES/MHD_NO by introducing `enum MHD_Bool`
+ * - improve terminology by eliminating confusion between
+ *   'request' and 'connection'
+ * - prepare API for having multiple TLS backends
+ * - use more consistent prefixes for related functions
+ *   by using MHD_subject_verb_object naming convention, also
+ *   at the same time avoid symbol conflict with legacy names
+ *   (so we can have one binary implementing old and new
+ *   library API at the same time via compatibility layer).
+ * - make it impossible to queue a response at the wrong time
+ * - make it impossible to suspend a connection/request at the
+ *   wrong time (improves thread-safety)
+ * - make it clear which response status codes are "properly"
+ *   supported (include the descriptive string) by using an enum;
+ * - simplify API for common-case of one-shot responses by
+ *   eliminating need for destroy response in most cases;
+ *
+ * TODO:
+ * - varargs in upgrade is still there and ugly (and not even used!)
+ * - migrate event loop apis (get fdset, timeout, MHD_run(), etc.)
+ */
+#ifndef MICROHTTPD2_H
+#define MICROHTTPD2_H
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#if 0                           /* keep Emacsens' auto-indent happy */
+}
+#endif
+#endif
+
+/* While we generally would like users to use a configure-driven
+   build process which detects which headers are present and
+   hence works on any platform, we use "standard" includes here
+   to build out-of-the-box for beginning users on common systems.
+
+   If generic headers don't work on your platform, include headers
+   which define 'va_list', 'size_t', 'ssize_t', 'intptr_t',
+   'uint16_t', 'uint32_t', 'uint64_t', 'off_t', 'struct sockaddr',
+   'socklen_t', 'fd_set' and "#define MHD_PLATFORM_H" before
+   including "microhttpd.h". Then the following "standard"
+   includes won't be used (which might be a good idea, especially
+   on platforms where they do not exist).
+   */
+#ifndef MHD_PLATFORM_H
+#include <stdarg.h>
+#include <stdint.h>
+#include <sys/types.h>
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#include <ws2tcpip.h>
+#if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED)
+#define _SSIZE_T_DEFINED
+typedef intptr_t ssize_t;
+#endif /* !_SSIZE_T_DEFINED */
+#else
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#endif
+#endif
+
+#if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET)
+/* Do not define __USE_W32_SOCKETS under Cygwin! */
+#error Cygwin with winsock fd_set is not supported
+#endif
+
+/**
+ * Current version of the library.
+ * 0x01093001 = 1.9.30-1.
+ */
+#define MHD_VERSION 0x01000000
+
+
+/**
+ * Representation of 'bool' in the public API as stdbool.h may not
+ * always be available.
+ */
+enum MHD_Bool
+{
+
+  /**
+   * MHD-internal return code for "NO".
+   */
+  MHD_NO = 0,
+
+  /**
+   * MHD-internal return code for "YES".  All non-zero values
+   * will be interpreted as "YES", but MHD will only ever
+   * return #MHD_YES or #MHD_NO.
+   */
+  MHD_YES = 1
+};
+
+
+/**
+ * Constant used to indicate unknown size (use when
+ * creating a response).
+ */
+#ifdef UINT64_MAX
+#define MHD_SIZE_UNKNOWN UINT64_MAX
+#else
+#define MHD_SIZE_UNKNOWN  ((uint64_t) -1LL)
+#endif
+
+#ifdef SIZE_MAX
+#define MHD_CONTENT_READER_END_OF_STREAM SIZE_MAX
+#define MHD_CONTENT_READER_END_WITH_ERROR (SIZE_MAX - 1)
+#else
+#define MHD_CONTENT_READER_END_OF_STREAM ((size_t) -1LL)
+#define MHD_CONTENT_READER_END_WITH_ERROR (((size_t) -1LL) - 1)
+#endif
+
+#ifndef _MHD_EXTERN
+#if defined(_WIN32) && defined(MHD_W32LIB)
+#define _MHD_EXTERN extern
+#elif defined(_WIN32) && defined(MHD_W32DLL)
+/* Define MHD_W32DLL when using MHD as W32 .DLL to speed up linker a little */
+#define _MHD_EXTERN __declspec(dllimport)
+#else
+#define _MHD_EXTERN extern
+#endif
+#endif
+
+#ifndef MHD_SOCKET_DEFINED
+/**
+ * MHD_socket is type for socket FDs
+ */
+#if ! defined(_WIN32) || defined(_SYS_TYPES_FD_SET)
+#define MHD_POSIX_SOCKETS 1
+typedef int MHD_socket;
+#define MHD_INVALID_SOCKET (-1)
+#else /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */
+#define MHD_WINSOCK_SOCKETS 1
+#include <winsock2.h>
+typedef SOCKET MHD_socket;
+#define MHD_INVALID_SOCKET (INVALID_SOCKET)
+#endif /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */
+#define MHD_SOCKET_DEFINED 1
+#endif /* MHD_SOCKET_DEFINED */
+
+/**
+ * Define MHD_NO_DEPRECATION before including "microhttpd.h" to disable deprecation messages
+ */
+#ifdef MHD_NO_DEPRECATION
+#define _MHD_DEPR_MACRO(msg)
+#define _MHD_NO_DEPR_IN_MACRO 1
+#define _MHD_DEPR_IN_MACRO(msg)
+#define _MHD_NO_DEPR_FUNC 1
+#define _MHD_DEPR_FUNC(msg)
+#endif /* MHD_NO_DEPRECATION */
+
+#ifndef _MHD_DEPR_MACRO
+#if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1500
+/* VS 2008 or later */
+/* Stringify macros */
+#define _MHD_INSTRMACRO(a) #a
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+/* deprecation message */
+#define _MHD_DEPR_MACRO(msg) __pragma(message (__FILE__ "(" _MHD_STRMACRO ( \
+  __LINE__) "): warning: " msg))
+#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg)
+#elif defined(__clang__) || defined(__GNUC_PATCHLEVEL__)
+/* clang or GCC since 3.0 */
+#define _MHD_GCC_PRAG(x) _Pragma(#x)
+#if (defined(__clang__) && (__clang_major__ + 0 >= 5 ||     \
+                            (! defined(__apple_build_version__) && \
+  (__clang_major__ + 0  > 3 || (__clang_major__ + 0 == 3 && __clang_minor__ >= \
+                                3))))) || \
+  __GNUC__ + 0 > 4 || (__GNUC__ + 0 == 4 && __GNUC_MINOR__ + 0 >= 8)
+/* clang >= 3.3 (or XCode's clang >= 5.0) or
+   GCC >= 4.8 */
+#define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (GCC warning msg)
+#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg)
+#else /* older clang or GCC */
+/* clang < 3.3, XCode's clang < 5.0, 3.0 <= GCC < 4.8 */
+#define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (message msg)
+#if (defined(__clang__) && (__clang_major__ + 0  > 2 || (__clang_major__ + 0 == \
+                                                         2 && __clang_minor__ >= \
+                                                         9)))                                            /* FIXME: clang >= 2.9, earlier versions not tested */
+/* clang handles inline pragmas better than GCC */
+#define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg)
+#endif /* clang >= 2.9 */
+#endif  /* older clang or GCC */
+/* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */
+#endif /* clang || GCC >= 3.0 */
+#endif /* !_MHD_DEPR_MACRO */
+
+#ifndef _MHD_DEPR_MACRO
+#define _MHD_DEPR_MACRO(msg)
+#endif /* !_MHD_DEPR_MACRO */
+
+#ifndef _MHD_DEPR_IN_MACRO
+#define _MHD_NO_DEPR_IN_MACRO 1
+#define _MHD_DEPR_IN_MACRO(msg)
+#endif /* !_MHD_DEPR_IN_MACRO */
+
+#ifndef _MHD_DEPR_FUNC
+#if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1400
+/* VS 2005 or later */
+#define _MHD_DEPR_FUNC(msg) __declspec(deprecated (msg))
+#elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1310
+/* VS .NET 2003 deprecation do not support custom messages */
+#define _MHD_DEPR_FUNC(msg) __declspec(deprecated)
+#elif (__GNUC__ + 0 >= 5) || (defined(__clang__) && \
+  (__clang_major__ + 0 > 2 || (__clang_major__ + 0 == 2 && __clang_minor__ >= \
+                               9)))                                             /* FIXME: earlier versions not tested */
+/* GCC >= 5.0 or clang >= 2.9 */
+#define _MHD_DEPR_FUNC(msg) __attribute__((deprecated (msg)))
+#elif defined(__clang__) || __GNUC__ + 0 > 3 || (__GNUC__ + 0 == 3 && \
+                                                 __GNUC_MINOR__ + 0 >= 1)
+/* 3.1 <= GCC < 5.0 or clang < 2.9 */
+/* old GCC-style deprecation do not support custom messages */
+#define _MHD_DEPR_FUNC(msg) __attribute__((__deprecated__))
+/* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */
+#endif /* clang < 2.9 || GCC >= 3.1 */
+#endif /* !_MHD_DEPR_FUNC */
+
+#ifndef _MHD_DEPR_FUNC
+#define _MHD_NO_DEPR_FUNC 1
+#define _MHD_DEPR_FUNC(msg)
+#endif /* !_MHD_DEPR_FUNC */
+
+
+/* Define MHD_NONNULL attribute */
+
+/**
+ * Macro to indicate that certain parameters must be
+ * non-null.  Todo: port to non-gcc platforms.
+ */
+#if defined(__CYGWIN__) || defined(_WIN32) || defined(MHD_W32LIB) || \
+  defined(__clang__) || ! defined(__GNUC__)
+#define MHD_NONNULL(...) /* empty */
+#else
+#define MHD_NONNULL(...) __THROW __nonnull ((__VA_ARGS__))
+#endif
+
+/**
+ * Not all architectures and `printf()`'s support the `long long` type.
+ * This gives the ability to replace `long long` with just a `long`,
+ * standard `int` or a `short`.
+ */
+#ifndef MHD_UNSIGNED_LONG_LONG
+#define MHD_UNSIGNED_LONG_LONG unsigned long long
+#endif
+/**
+ * Format string for printing a variable of type #MHD_LONG_LONG.
+ * You should only redefine this if you also define #MHD_LONG_LONG.
+ */
+#ifndef MHD_UNSIGNED_LONG_LONG_PRINTF
+#define MHD_UNSIGNED_LONG_LONG_PRINTF "%llu"
+#endif
+
+
+/**
+ * @brief Handle for a connection / HTTP request.
+ *
+ * With HTTP/1.1, multiple requests can be run over the same
+ * connection.  However, MHD will only show one request per TCP
+ * connection to the client at any given time.
+ *
+ * Replaces `struct MHD_Connection`, renamed to better reflect
+ * what this object truly represents to the application using
+ * MHD.
+ *
+ * @ingroup request
+ */
+struct MHD_Request;
+
+
+/**
+ * A connection corresponds to the network/stream abstraction.
+ * A single network (i.e. TCP) stream may be used for multiple
+ * requests, which in HTTP/1.1 must be processed sequentially.
+ */
+struct MHD_Connection;
+
+
+/**
+ * Return values for reporting errors, also used
+ * for logging.
+ *
+ * A value of 0 indicates success (as a return value).
+ * Values between 0 and 10000 must be handled explicitly by the app.
+ * Values from 10000-19999 are informational.
+ * Values from 20000-29999 indicate successful operations.
+ * Values from 30000-39999 indicate unsuccessful (normal) operations.
+ * Values from 40000-49999 indicate client errors.
+ * Values from 50000-59999 indicate MHD server errors.
+ * Values from 60000-69999 indicate application errors.
+ */
+enum MHD_StatusCode
+{
+
+  /* 00000-level status codes indicate return values
+     the application must act on. */
+
+  /**
+   * Successful operation (not used for logging).
+   */
+  MHD_SC_OK = 0,
+
+  /**
+   * We were asked to return a timeout, but, there is no timeout.
+   */
+  MHD_SC_NO_TIMEOUT = 1,
+
+
+  /* 10000-level status codes indicate intermediate
+     results of some kind. */
+
+  /**
+   * Informational event, MHD started.
+   */
+  MHD_SC_DAEMON_STARTED = 10000,
+
+  /**
+   * Informational event, we accepted a connection.
+   */
+  MHD_SC_CONNECTION_ACCEPTED = 10001,
+
+  /**
+   * Informational event, thread processing connection termiantes.
+   */
+  MHD_SC_THREAD_TERMINATING = 10002,
+
+  /**
+   * Informational event, state machine status for a connection.
+   */
+  MHD_SC_STATE_MACHINE_STATUS_REPORT = 10003,
+
+  /**
+   * accept() returned transient error.
+   */
+  MHD_SC_ACCEPT_FAILED_EAGAIN = 10004,
+
+
+  /* 20000-level status codes indicate success of some kind. */
+
+  /**
+   * MHD is closing a connection after the client closed it
+   * (perfectly normal end).
+   */
+  MHD_SC_CONNECTION_CLOSED = 20000,
+
+  /**
+   * MHD is closing a connection because the application
+   * logic to generate the response data completed.
+   */
+  MHD_SC_APPLICATION_DATA_GENERATION_FINISHED = 20001,
+
+
+  /* 30000-level status codes indicate transient failures
+     that might go away if the client tries again. */
+
+
+  /**
+   * Resource limit in terms of number of parallel connections
+   * hit.
+   */
+  MHD_SC_LIMIT_CONNECTIONS_REACHED = 30000,
+
+  /**
+   * We failed to allocate memory for poll() syscall.
+   * (May be transient.)
+   */
+  MHD_SC_POLL_MALLOC_FAILURE = 30001,
+
+  /**
+   * The operation failed because the respective
+   * daemon is already too deep inside of the shutdown
+   * activity.
+   */
+  MHD_SC_DAEMON_ALREADY_SHUTDOWN = 30002,
+
+  /**
+   * We failed to start a thread.
+   */
+  MHD_SC_THREAD_LAUNCH_FAILURE = 30003,
+
+  /**
+   * The operation failed because we either have no
+   * listen socket or were already quiesced.
+   */
+  MHD_SC_DAEMON_ALREADY_QUIESCED = 30004,
+
+  /**
+   * The operation failed because client disconnected
+   * faster than we could accept().
+   */
+  MHD_SC_ACCEPT_FAST_DISCONNECT = 30005,
+
+  /**
+   * Operating resource limits hit on accept().
+   */
+  MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED = 30006,
+
+  /**
+   * Connection was refused by accept policy callback.
+   */
+  MHD_SC_ACCEPT_POLICY_REJECTED = 30007,
+
+  /**
+   * We failed to allocate memory for the connection.
+   * (May be transient.)
+   */
+  MHD_SC_CONNECTION_MALLOC_FAILURE = 30008,
+
+  /**
+   * We failed to allocate memory for the connection's memory pool.
+   * (May be transient.)
+   */
+  MHD_SC_POOL_MALLOC_FAILURE = 30009,
+
+  /**
+   * We failed to forward data from a Web socket to the
+   * application to the remote side due to the socket
+   * being closed prematurely. (May be transient.)
+   */
+  MHD_SC_UPGRADE_FORWARD_INCOMPLETE = 30010,
+
+  /**
+   * We failed to allocate memory for generating the response from our
+   * memory pool.  Likely the request header was too large to leave
+   * enough room.
+   */
+  MHD_SC_CONNECTION_POOL_MALLOC_FAILURE = 30011,
+
+
+  /* 40000-level errors are caused by the HTTP client
+     (or the network) */
+
+  /**
+   * MHD is closing a connection because parsing the
+   * request failed.
+   */
+  MHD_SC_CONNECTION_PARSE_FAIL_CLOSED = 40000,
+
+  /**
+   * MHD is closing a connection because it was reset.
+   */
+  MHD_SC_CONNECTION_RESET_CLOSED = 40001,
+
+  /**
+   * MHD is closing a connection because reading the
+   * request failed.
+   */
+  MHD_SC_CONNECTION_READ_FAIL_CLOSED = 40002,
+
+  /**
+   * MHD is closing a connection because writing the response failed.
+   */
+  MHD_SC_CONNECTION_WRITE_FAIL_CLOSED = 40003,
+
+  /**
+   * MHD is returning an error because the header provided
+   * by the client is too big.
+   */
+  MHD_SC_CLIENT_HEADER_TOO_BIG = 40004,
+
+  /**
+   * An HTTP/1.1 request was sent without the "Host:" header.
+   */
+  MHD_SC_HOST_HEADER_MISSING = 40005,
+
+  /**
+   * The given content length was not a number.
+   */
+  MHD_SC_CONTENT_LENGTH_MALFORMED = 40006,
+
+  /**
+   * The given uploaded, chunked-encoded body was malformed.
+   */
+  MHD_SC_CHUNKED_ENCODING_MALFORMED = 40007,
+
+
+  /* 50000-level errors are because of an error internal
+     to the MHD logic, possibly including our interaction
+     with the operating system (but not the application) */
+
+  /**
+   * This build of MHD does not support TLS, but the application
+   * requested TLS.
+   */
+  MHD_SC_TLS_DISABLED = 50000,
+
+  /**
+   * The application attempted to setup TLS parameters before
+   * enabling TLS.
+   */
+  MHD_SC_TLS_BACKEND_UNINITIALIZED = 50003,
+
+  /**
+   * The selected TLS backend does not yet support this operation.
+   */
+  MHD_SC_TLS_BACKEND_OPERATION_UNSUPPORTED = 50004,
+
+  /**
+   * Failed to setup ITC channel.
+   */
+  MHD_SC_ITC_INITIALIZATION_FAILED = 50005,
+
+  /**
+   * File descriptor for ITC channel too large.
+   */
+  MHD_SC_ITC_DESCRIPTOR_TOO_LARGE = 50006,
+
+  /**
+   * The specified value for the NC length is way too large
+   * for this platform (integer overflow on `size_t`).
+   */
+  MHD_SC_DIGEST_AUTH_NC_LENGTH_TOO_BIG = 50007,
+
+  /**
+   * We failed to allocate memory for the specified nonce
+   * counter array.  The option was not set.
+   */
+  MHD_SC_DIGEST_AUTH_NC_ALLOCATION_FAILURE = 50008,
+
+  /**
+   * This build of the library does not support
+   * digest authentication.
+   */
+  MHD_SC_DIGEST_AUTH_NOT_SUPPORTED_BY_BUILD = 50009,
+
+  /**
+   * IPv6 requested but not supported by this build.
+   */
+  MHD_SC_IPV6_NOT_SUPPORTED_BY_BUILD = 50010,
+
+  /**
+   * We failed to open the listen socket. Maybe the build
+   * supports IPv6, but your kernel does not?
+   */
+  MHD_SC_FAILED_TO_OPEN_LISTEN_SOCKET = 50011,
+
+  /**
+   * Specified address family is not supported by this build.
+   */
+  MHD_SC_AF_NOT_SUPPORTED_BY_BUILD = 50012,
+
+  /**
+   * Failed to enable listen address reuse.
+   */
+  MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_FAILED = 50013,
+
+  /**
+   * Enabling listen address reuse is not supported by this platform.
+   */
+  MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_NOT_SUPPORTED = 50014,
+
+  /**
+   * Failed to disable listen address reuse.
+   */
+  MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_FAILED = 50015,
+
+  /**
+   * Disabling listen address reuse is not supported by this platform.
+   */
+  MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_NOT_SUPPORTED = 50016,
+
+  /**
+   * We failed to explicitly enable or disable dual stack for
+   * the IPv6 listen socket.  The socket will be used in whatever
+   * the default is the OS gives us.
+   */
+  MHD_SC_LISTEN_DUAL_STACK_CONFIGURATION_FAILED = 50017,
+
+  /**
+   * On this platform, MHD does not support explicitly configuring
+   * dual stack behavior.
+   */
+  MHD_SC_LISTEN_DUAL_STACK_CONFIGURATION_NOT_SUPPORTED = 50018,
+
+  /**
+   * Failed to enable TCP FAST OPEN option.
+   */
+  MHD_SC_FAST_OPEN_FAILURE = 50020,
+
+  /**
+   * Failed to start listening on listen socket.
+   */
+  MHD_SC_LISTEN_FAILURE = 50021,
+
+  /**
+   * Failed to obtain our listen port via introspection.
+   */
+  MHD_SC_LISTEN_PORT_INTROSPECTION_FAILURE = 50022,
+
+  /**
+   * Failed to obtain our listen port via introspection
+   * due to unsupported address family being used.
+   */
+  MHD_SC_LISTEN_PORT_INTROSPECTION_UNKNOWN_AF = 50023,
+
+  /**
+   * We failed to set the listen socket to non-blocking.
+   */
+  MHD_SC_LISTEN_SOCKET_NONBLOCKING_FAILURE = 50024,
+
+  /**
+   * Listen socket value is too large (for use with select()).
+   */
+  MHD_SC_LISTEN_SOCKET_TOO_LARGE = 50025,
+
+  /**
+   * We failed to allocate memory for the thread pool.
+   */
+  MHD_SC_THREAD_POOL_MALLOC_FAILURE = 50026,
+
+  /**
+   * We failed to allocate mutex for thread pool worker.
+   */
+  MHD_SC_THREAD_POOL_CREATE_MUTEX_FAILURE = 50027,
+
+  /**
+   * There was an attempt to upgrade a connection on
+   * a daemon where upgrades are disallowed.
+   */
+  MHD_SC_UPGRADE_ON_DAEMON_WITH_UPGRADE_DISALLOWED = 50028,
+
+  /**
+   * Failed to signal via ITC channel.
+   */
+  MHD_SC_ITC_USE_FAILED = 50029,
+
+  /**
+   * We failed to initialize the main thread for listening.
+   */
+  MHD_SC_THREAD_MAIN_LAUNCH_FAILURE = 50030,
+
+  /**
+   * We failed to initialize the threads for the worker pool.
+   */
+  MHD_SC_THREAD_POOL_LAUNCH_FAILURE = 50031,
+
+  /**
+   * We failed to add a socket to the epoll() set.
+   */
+  MHD_SC_EPOLL_CTL_ADD_FAILED = 50032,
+
+  /**
+   * We failed to create control socket for the epoll().
+   */
+  MHD_SC_EPOLL_CTL_CREATE_FAILED = 50034,
+
+  /**
+   * We failed to configure control socket for the epoll()
+   * to be non-inheritable.
+   */
+  MHD_SC_EPOLL_CTL_CONFIGURE_NOINHERIT_FAILED = 50035,
+
+  /**
+   * We failed to build the FD set because a socket was
+   * outside of the permitted range.
+   */
+  MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE = 50036,
+
+  /**
+   * This daemon was not configured with options that
+   * would allow us to build an FD set for select().
+   */
+  MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_FDSET = 50037,
+
+  /**
+   * This daemon was not configured with options that
+   * would allow us to obtain a meaningful timeout.
+   */
+  MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_TIMEOUT = 50038,
+
+  /**
+   * This daemon was not configured with options that
+   * would allow us to run with select() data.
+   */
+  MHD_SC_CONFIGURATION_MISMATCH_FOR_RUN_SELECT = 50039,
+
+  /**
+   * This daemon was not configured to run with an
+   * external event loop.
+   */
+  MHD_SC_CONFIGURATION_MISMATCH_FOR_RUN_EXTERNAL = 50040,
+
+  /**
+   * Encountered an unexpected event loop style
+   * (should never happen).
+   */
+  MHD_SC_CONFIGURATION_UNEXPECTED_ELS = 50041,
+
+  /**
+   * Encountered an unexpected error from select()
+   * (should never happen).
+   */
+  MHD_SC_UNEXPECTED_SELECT_ERROR = 50042,
+
+  /**
+   * poll() is not supported.
+   */
+  MHD_SC_POLL_NOT_SUPPORTED = 50043,
+
+  /**
+   * Encountered an unexpected error from poll()
+   * (should never happen).
+   */
+  MHD_SC_UNEXPECTED_POLL_ERROR = 50044,
+
+  /**
+   * We failed to configure accepted socket
+   * to not use a signal pipe.
+   */
+  MHD_SC_ACCEPT_CONFIGURE_NOSIGPIPE_FAILED = 50045,
+
+  /**
+   * Encountered an unexpected error from epoll_wait()
+   * (should never happen).
+   */
+  MHD_SC_UNEXPECTED_EPOLL_WAIT_ERROR = 50046,
+
+  /**
+   * epoll file descriptor is invalid (strange)
+   */
+  MHD_SC_EPOLL_FD_INVALID = 50047,
+
+  /**
+   * We failed to configure accepted socket
+   * to be non-inheritable.
+   */
+  MHD_SC_ACCEPT_CONFIGURE_NOINHERIT_FAILED = 50048,
+
+  /**
+   * We failed to configure accepted socket
+   * to be non-blocking.
+   */
+  MHD_SC_ACCEPT_CONFIGURE_NONBLOCKING_FAILED = 50049,
+
+  /**
+   * accept() returned non-transient error.
+   */
+  MHD_SC_ACCEPT_FAILED_UNEXPECTEDLY = 50050,
+
+  /**
+   * Operating resource limits hit on accept() while
+   * zero connections are active. Oopsie.
+   */
+  MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED_INSTANTLY = 50051,
+
+  /**
+   * Failed to add IP address to per-IP counter for
+   * some reason.
+   */
+  MHD_SC_IP_COUNTER_FAILURE = 50052,
+
+  /**
+   * Application violated our API by calling shutdown
+   * while having an upgrade connection still open.
+   */
+  MHD_SC_SHUTDOWN_WITH_OPEN_UPGRADED_CONNECTION = 50053,
+
+  /**
+   * Due to an unexpected internal error with the
+   * state machine, we closed the connection.
+   */
+  MHD_SC_STATEMACHINE_FAILURE_CONNECTION_CLOSED = 50054,
+
+  /**
+   * Failed to allocate memory in connection's pool
+   * to parse the cookie header.
+   */
+  MHD_SC_COOKIE_POOL_ALLOCATION_FAILURE = 50055,
+
+  /**
+   * MHD failed to build the response header.
+   */
+  MHD_SC_FAILED_RESPONSE_HEADER_GENERATION = 50056,
+
+
+  /* 60000-level errors are because the application
+     logic did something wrong or generated an error. */
+
+  /**
+   * MHD does not support the requested combination of
+   * EPOLL with thread-per-connection mode.
+   */
+  MHD_SC_SYSCALL_THREAD_COMBINATION_INVALID = 60000,
+
+  /**
+   * MHD does not support quiescing if ITC was disabled
+   * and threads are used.
+   */
+  MHD_SC_SYSCALL_QUIESCE_REQUIRES_ITC = 60001,
+
+  /**
+   * We failed to bind the listen socket.
+   */
+  MHD_SC_LISTEN_SOCKET_BIND_FAILED = 60002,
+
+  /**
+   * The application requested an unsupported TLS backend to be used.
+   */
+  MHD_SC_TLS_BACKEND_UNSUPPORTED = 60003,
+
+  /**
+   * The application requested a TLS cipher suite which is not
+   * supported by the selected backend.
+   */
+  MHD_SC_TLS_CIPHERS_INVALID = 60004,
+
+  /**
+   * MHD is closing a connection because the application
+   * logic to generate the response data failed.
+   */
+  MHD_SC_APPLICATION_DATA_GENERATION_FAILURE_CLOSED = 60005,
+
+  /**
+   * MHD is closing a connection because the application
+   * callback told it to do so.
+   */
+  MHD_SC_APPLICATION_CALLBACK_FAILURE_CLOSED = 60006,
+
+  /**
+   * Application only partially processed upload and did
+   * not suspend connection. This may result in a hung
+   * connection.
+   */
+  MHD_SC_APPLICATION_HUNG_CONNECTION = 60007,
+
+  /**
+   * Application only partially processed upload and did
+   * not suspend connection and the read buffer was maxxed
+   * out, so MHD closed the connection.
+   */
+  MHD_SC_APPLICATION_HUNG_CONNECTION_CLOSED = 60008,
+
+
+};
+
+
+/**
+ * Actions are returned by the application to drive the request
+ * handling of MHD.
+ */
+struct MHD_Action;
+
+
+/**
+ * HTTP methods explicitly supported by MHD.  Note that for
+ * non-canonical methods, MHD will return #MHD_METHOD_UNKNOWN
+ * and you can use #MHD_REQUEST_INFORMATION_HTTP_METHOD to get
+ * the original string.
+ *
+ * However, applications must check for "#MHD_METHOD_UNKNOWN" *or* any
+ * enum-value above those in this list, as future versions of MHD may
+ * add additional methods (as per IANA registry), thus even if the API
+ * returns "unknown" today, it may return a method-specific header in
+ * the future!
+ *
+ * @defgroup methods HTTP methods
+ * HTTP methods (as strings).
+ * See: http://www.iana.org/assignments/http-methods/http-methods.xml
+ * Registry Version 2015-05-19
+ * @{
+ */
+enum MHD_Method
+{
+
+  /**
+   * Method did not match any of the methods given below.
+   */
+  MHD_METHOD_UNKNOWN = 0,
+
+  /**
+   * "OPTIONS" method.
+   * Safe.     Idempotent.     RFC7231, Section 4.3.7.
+   */
+  MHD_METHOD_OPTIONS = 1,
+
+  /**
+   * "GET" method.
+   * Safe.     Idempotent.     RFC7231, Section 4.3.1.
+   */
+  MHD_METHOD_GET = 2,
+
+  /**
+   * "HEAD" method.
+   * Safe.     Idempotent.     RFC7231, Section 4.3.2.
+   */
+  MHD_METHOD_HEAD = 3,
+
+  /**
+   * "POST" method.
+   * Not safe. Not idempotent. RFC7231, Section 4.3.3.
+   */
+  MHD_METHOD_POST = 4,
+
+  /**
+   * "PUT" method.
+   * Not safe. Idempotent.     RFC7231, Section 4.3.4.
+   */
+  MHD_METHOD_PUT = 5,
+
+  /**
+   * "DELETE" method.
+   * Not safe. Idempotent.     RFC7231, Section 4.3.5.
+   */
+  MHD_METHOD_DELETE = 6,
+
+  /**
+   * "TRACE" method.
+   */
+  MHD_METHOD_TRACE = 7,
+
+  /**
+   * "CONNECT" method.
+   */
+  MHD_METHOD_CONNECT = 8,
+
+  /**
+   * "ACL" method.
+   */
+  MHD_METHOD_ACL = 9,
+
+  /**
+   * "BASELINE-CONTROL" method.
+   */
+  MHD_METHOD_BASELINE_CONTROL = 10,
+
+  /**
+   * "BIND" method.
+   */
+  MHD_METHOD_BIND = 11,
+
+  /**
+   * "CHECKIN" method.
+   */
+  MHD_METHOD_CHECKIN = 12,
+
+  /**
+   * "CHECKOUT" method.
+   */
+  MHD_METHOD_CHECKOUT = 13,
+
+  /**
+   * "COPY" method.
+   */
+  MHD_METHOD_COPY = 14,
+
+  /**
+   * "LABEL" method.
+   */
+  MHD_METHOD_LABEL = 15,
+
+  /**
+   * "LINK" method.
+   */
+  MHD_METHOD_LINK = 16,
+
+  /**
+   * "LOCK" method.
+   */
+  MHD_METHOD_LOCK = 17,
+
+  /**
+   * "MERGE" method.
+   */
+  MHD_METHOD_MERGE = 18,
+
+  /**
+   * "MKACTIVITY" method.
+   */
+  MHD_METHOD_MKACTIVITY = 19,
+
+  /**
+   * "MKCOL" method.
+   */
+  MHD_METHOD_MKCOL = 20,
+
+  /**
+   * "MKREDIRECTREF" method.
+   */
+  MHD_METHOD_MKREDIRECTREF = 21,
+
+  /**
+   * "MKWORKSPACE" method.
+   */
+  MHD_METHOD_MKWORKSPACE = 22,
+
+  /**
+   * "MOVE" method.
+   */
+  MHD_METHOD_MOVE = 23,
+
+  /**
+   * "ORDERPATCH" method.
+   */
+  MHD_METHOD_ORDERPATCH = 24,
+
+  /**
+   * "PATCH" method.
+   */
+  MHD_METHOD_PATH = 25,
+
+  /**
+   * "PRI" method.
+   */
+  MHD_METHOD_PRI = 26,
+
+  /**
+   * "PROPFIND" method.
+   */
+  MHD_METHOD_PROPFIND = 27,
+
+  /**
+   * "PROPPATCH" method.
+   */
+  MHD_METHOD_PROPPATCH = 28,
+
+  /**
+   * "REBIND" method.
+   */
+  MHD_METHOD_REBIND = 29,
+
+  /**
+   * "REPORT" method.
+   */
+  MHD_METHOD_REPORT = 30,
+
+  /**
+   * "SEARCH" method.
+   */
+  MHD_METHOD_SEARCH = 31,
+
+  /**
+   * "UNBIND" method.
+   */
+  MHD_METHOD_UNBIND = 32,
+
+  /**
+   * "UNCHECKOUT" method.
+   */
+  MHD_METHOD_UNCHECKOUT = 33,
+
+  /**
+   * "UNLINK" method.
+   */
+  MHD_METHOD_UNLINK = 34,
+
+  /**
+   * "UNLOCK" method.
+   */
+  MHD_METHOD_UNLOCK = 35,
+
+  /**
+   * "UPDATE" method.
+   */
+  MHD_METHOD_UPDATE = 36,
+
+  /**
+   * "UPDATEDIRECTREF" method.
+   */
+  MHD_METHOD_UPDATEDIRECTREF = 37,
+
+  /**
+   * "VERSION-CONTROL" method.
+   */
+  MHD_METHOD_VERSION_CONTROL = 38
+
+                               /* For more, check:
+                                  https://www.iana.org/assignments/http-methods/http-methods.xhtml */
+
+};
+
+/** @} */ /* end of group methods */
+
+
+/**
+ * @defgroup postenc HTTP POST encodings
+ * See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
+ * @{
+ */
+#define MHD_HTTP_POST_ENCODING_FORM_URLENCODED \
+  "application/x-www-form-urlencoded"
+#define MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data"
+
+/** @} */ /* end of group postenc */
+
+
+/**
+ * @defgroup headers HTTP headers
+ * These are the standard headers found in HTTP requests and responses.
+ * See: http://www.iana.org/assignments/message-headers/message-headers.xml
+ * Registry Version 2017-01-27
+ * @{
+ */
+
+/* Main HTTP headers. */
+/* Standard.      RFC7231, Section 5.3.2 */
+#define MHD_HTTP_HEADER_ACCEPT "Accept"
+/* Standard.      RFC7231, Section 5.3.3 */
+#define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset"
+/* Standard.      RFC7231, Section 5.3.4; RFC7694, Section 3 */
+#define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding"
+/* Standard.      RFC7231, Section 5.3.5 */
+#define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language"
+/* Standard.      RFC7233, Section 2.3 */
+#define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges"
+/* Standard.      RFC7234, Section 5.1 */
+#define MHD_HTTP_HEADER_AGE "Age"
+/* Standard.      RFC7231, Section 7.4.1 */
+#define MHD_HTTP_HEADER_ALLOW "Allow"
+/* Standard.      RFC7235, Section 4.2 */
+#define MHD_HTTP_HEADER_AUTHORIZATION "Authorization"
+/* Standard.      RFC7234, Section 5.2 */
+#define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control"
+/* Reserved.      RFC7230, Section 8.1 */
+#define MHD_HTTP_HEADER_CLOSE "Close"
+/* Standard.      RFC7230, Section 6.1 */
+#define MHD_HTTP_HEADER_CONNECTION "Connection"
+/* Standard.      RFC7231, Section 3.1.2.2 */
+#define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding"
+/* Standard.      RFC7231, Section 3.1.3.2 */
+#define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language"
+/* Standard.      RFC7230, Section 3.3.2 */
+#define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length"
+/* Standard.      RFC7231, Section 3.1.4.2 */
+#define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location"
+/* Standard.      RFC7233, Section 4.2 */
+#define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range"
+/* Standard.      RFC7231, Section 3.1.1.5 */
+#define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type"
+/* Standard.      RFC7231, Section 7.1.1.2 */
+#define MHD_HTTP_HEADER_DATE "Date"
+/* Standard.      RFC7232, Section 2.3 */
+#define MHD_HTTP_HEADER_ETAG "ETag"
+/* Standard.      RFC7231, Section 5.1.1 */
+#define MHD_HTTP_HEADER_EXPECT "Expect"
+/* Standard.      RFC7234, Section 5.3 */
+#define MHD_HTTP_HEADER_EXPIRES "Expires"
+/* Standard.      RFC7231, Section 5.5.1 */
+#define MHD_HTTP_HEADER_FROM "From"
+/* Standard.      RFC7230, Section 5.4 */
+#define MHD_HTTP_HEADER_HOST "Host"
+/* Standard.      RFC7232, Section 3.1 */
+#define MHD_HTTP_HEADER_IF_MATCH "If-Match"
+/* Standard.      RFC7232, Section 3.3 */
+#define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since"
+/* Standard.      RFC7232, Section 3.2 */
+#define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match"
+/* Standard.      RFC7233, Section 3.2 */
+#define MHD_HTTP_HEADER_IF_RANGE "If-Range"
+/* Standard.      RFC7232, Section 3.4 */
+#define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since"
+/* Standard.      RFC7232, Section 2.2 */
+#define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified"
+/* Standard.      RFC7231, Section 7.1.2 */
+#define MHD_HTTP_HEADER_LOCATION "Location"
+/* Standard.      RFC7231, Section 5.1.2 */
+#define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards"
+/* Standard.      RFC7231, Appendix A.1 */
+#define MHD_HTTP_HEADER_MIME_VERSION "MIME-Version"
+/* Standard.      RFC7234, Section 5.4 */
+#define MHD_HTTP_HEADER_PRAGMA "Pragma"
+/* Standard.      RFC7235, Section 4.3 */
+#define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate"
+/* Standard.      RFC7235, Section 4.4 */
+#define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization"
+/* Standard.      RFC7233, Section 3.1 */
+#define MHD_HTTP_HEADER_RANGE "Range"
+/* Standard.      RFC7231, Section 5.5.2 */
+#define MHD_HTTP_HEADER_REFERER "Referer"
+/* Standard.      RFC7231, Section 7.1.3 */
+#define MHD_HTTP_HEADER_RETRY_AFTER "Retry-After"
+/* Standard.      RFC7231, Section 7.4.2 */
+#define MHD_HTTP_HEADER_SERVER "Server"
+/* Standard.      RFC7230, Section 4.3 */
+#define MHD_HTTP_HEADER_TE "TE"
+/* Standard.      RFC7230, Section 4.4 */
+#define MHD_HTTP_HEADER_TRAILER "Trailer"
+/* Standard.      RFC7230, Section 3.3.1 */
+#define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding"
+/* Standard.      RFC7230, Section 6.7 */
+#define MHD_HTTP_HEADER_UPGRADE "Upgrade"
+/* Standard.      RFC7231, Section 5.5.3 */
+#define MHD_HTTP_HEADER_USER_AGENT "User-Agent"
+/* Standard.      RFC7231, Section 7.1.4 */
+#define MHD_HTTP_HEADER_VARY "Vary"
+/* Standard.      RFC7230, Section 5.7.1 */
+#define MHD_HTTP_HEADER_VIA "Via"
+/* Standard.      RFC7235, Section 4.1 */
+#define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate"
+/* Standard.      RFC7234, Section 5.5 */
+#define MHD_HTTP_HEADER_WARNING "Warning"
+
+/* Additional HTTP headers. */
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_A_IM "A-IM"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_ACCEPT_ADDITIONS "Accept-Additions"
+/* Informational. RFC7089 */
+#define MHD_HTTP_HEADER_ACCEPT_DATETIME "Accept-Datetime"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_ACCEPT_FEATURES "Accept-Features"
+/* No category.   RFC5789 */
+#define MHD_HTTP_HEADER_ACCEPT_PATCH "Accept-Patch"
+/* Standard.      RFC7639, Section 2 */
+#define MHD_HTTP_HEADER_ALPN "ALPN"
+/* Standard.      RFC7838 */
+#define MHD_HTTP_HEADER_ALT_SVC "Alt-Svc"
+/* Standard.      RFC7838 */
+#define MHD_HTTP_HEADER_ALT_USED "Alt-Used"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_ALTERNATES "Alternates"
+/* No category.   RFC4437 */
+#define MHD_HTTP_HEADER_APPLY_TO_REDIRECT_REF "Apply-To-Redirect-Ref"
+/* Experimental.  RFC8053, Section 4 */
+#define MHD_HTTP_HEADER_AUTHENTICATION_CONTROL "Authentication-Control"
+/* Standard.      RFC7615, Section 3 */
+#define MHD_HTTP_HEADER_AUTHENTICATION_INFO "Authentication-Info"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_C_EXT "C-Ext"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_C_MAN "C-Man"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_C_OPT "C-Opt"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_C_PEP "C-PEP"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_C_PEP_INFO "C-PEP-Info"
+/* Standard.      RFC7809, Section 7.1 */
+#define MHD_HTTP_HEADER_CALDAV_TIMEZONES "CalDAV-Timezones"
+/* Obsoleted.     RFC2068; RFC2616 */
+#define MHD_HTTP_HEADER_CONTENT_BASE "Content-Base"
+/* Standard.      RFC6266 */
+#define MHD_HTTP_HEADER_CONTENT_DISPOSITION "Content-Disposition"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_ID "Content-ID"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_MD5 "Content-MD5"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_SCRIPT_TYPE "Content-Script-Type"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_STYLE_TYPE "Content-Style-Type"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_CONTENT_VERSION "Content-Version"
+/* Standard.      RFC6265 */
+#define MHD_HTTP_HEADER_COOKIE "Cookie"
+/* Obsoleted.     RFC2965; RFC6265 */
+#define MHD_HTTP_HEADER_COOKIE2 "Cookie2"
+/* Standard.      RFC5323 */
+#define MHD_HTTP_HEADER_DASL "DASL"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_DAV "DAV"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_DEFAULT_STYLE "Default-Style"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_DELTA_BASE "Delta-Base"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_DEPTH "Depth"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_DERIVED_FROM "Derived-From"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_DESTINATION "Destination"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_DIFFERENTIAL_ID "Differential-ID"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_DIGEST "Digest"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_EXT "Ext"
+/* Standard.      RFC7239 */
+#define MHD_HTTP_HEADER_FORWARDED "Forwarded"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_GETPROFILE "GetProfile"
+/* Experimental.  RFC7486, Section 6.1.1 */
+#define MHD_HTTP_HEADER_HOBAREG "Hobareg"
+/* Standard.      RFC7540, Section 3.2.1 */
+#define MHD_HTTP_HEADER_HTTP2_SETTINGS "HTTP2-Settings"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_IM "IM"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_IF "If"
+/* Standard.      RFC6638 */
+#define MHD_HTTP_HEADER_IF_SCHEDULE_TAG_MATCH "If-Schedule-Tag-Match"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_KEEP_ALIVE "Keep-Alive"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_LABEL "Label"
+/* No category.   RFC5988 */
+#define MHD_HTTP_HEADER_LINK "Link"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_LOCK_TOKEN "Lock-Token"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_MAN "Man"
+/* Informational. RFC7089 */
+#define MHD_HTTP_HEADER_MEMENTO_DATETIME "Memento-Datetime"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_METER "Meter"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_NEGOTIATE "Negotiate"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_OPT "Opt"
+/* Experimental.  RFC8053, Section 3 */
+#define MHD_HTTP_HEADER_OPTIONAL_WWW_AUTHENTICATE "Optional-WWW-Authenticate"
+/* Standard.      RFC4229 */
+#define MHD_HTTP_HEADER_ORDERING_TYPE "Ordering-Type"
+/* Standard.      RFC6454 */
+#define MHD_HTTP_HEADER_ORIGIN "Origin"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_OVERWRITE "Overwrite"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_P3P "P3P"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PEP "PEP"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PICS_LABEL "PICS-Label"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PEP_INFO "Pep-Info"
+/* Standard.      RFC4229 */
+#define MHD_HTTP_HEADER_POSITION "Position"
+/* Standard.      RFC7240 */
+#define MHD_HTTP_HEADER_PREFER "Prefer"
+/* Standard.      RFC7240 */
+#define MHD_HTTP_HEADER_PREFERENCE_APPLIED "Preference-Applied"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROFILEOBJECT "ProfileObject"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL "Protocol"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL_INFO "Protocol-Info"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL_QUERY "Protocol-Query"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROTOCOL_REQUEST "Protocol-Request"
+/* Standard.      RFC7615, Section 4 */
+#define MHD_HTTP_HEADER_PROXY_AUTHENTICATION_INFO "Proxy-Authentication-Info"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROXY_FEATURES "Proxy-Features"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PROXY_INSTRUCTION "Proxy-Instruction"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_PUBLIC "Public"
+/* Standard.      RFC7469 */
+#define MHD_HTTP_HEADER_PUBLIC_KEY_PINS "Public-Key-Pins"
+/* Standard.      RFC7469 */
+#define MHD_HTTP_HEADER_PUBLIC_KEY_PINS_REPORT_ONLY \
+  "Public-Key-Pins-Report-Only"
+/* No category.   RFC4437 */
+#define MHD_HTTP_HEADER_REDIRECT_REF "Redirect-Ref"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_SAFE "Safe"
+/* Standard.      RFC6638 */
+#define MHD_HTTP_HEADER_SCHEDULE_REPLY "Schedule-Reply"
+/* Standard.      RFC6638 */
+#define MHD_HTTP_HEADER_SCHEDULE_TAG "Schedule-Tag"
+/* Standard.      RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept"
+/* Standard.      RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions"
+/* Standard.      RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key"
+/* Standard.      RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol"
+/* Standard.      RFC6455 */
+#define MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_SECURITY_SCHEME "Security-Scheme"
+/* Standard.      RFC6265 */
+#define MHD_HTTP_HEADER_SET_COOKIE "Set-Cookie"
+/* Obsoleted.     RFC2965; RFC6265 */
+#define MHD_HTTP_HEADER_SET_COOKIE2 "Set-Cookie2"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_SETPROFILE "SetProfile"
+/* Standard.      RFC5023 */
+#define MHD_HTTP_HEADER_SLUG "SLUG"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_SOAPACTION "SoapAction"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_STATUS_URI "Status-URI"
+/* Standard.      RFC6797 */
+#define MHD_HTTP_HEADER_STRICT_TRANSPORT_SECURITY "Strict-Transport-Security"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_SURROGATE_CAPABILITY "Surrogate-Capability"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_SURROGATE_CONTROL "Surrogate-Control"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_TCN "TCN"
+/* Standard.      RFC4918 */
+#define MHD_HTTP_HEADER_TIMEOUT "Timeout"
+/* Standard.      RFC8030, Section 5.4 */
+#define MHD_HTTP_HEADER_TOPIC "Topic"
+/* Standard.      RFC8030, Section 5.2 */
+#define MHD_HTTP_HEADER_TTL "TTL"
+/* Standard.      RFC8030, Section 5.3 */
+#define MHD_HTTP_HEADER_URGENCY "Urgency"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_URI "URI"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_VARIANT_VARY "Variant-Vary"
+/* No category.   RFC4229 */
+#define MHD_HTTP_HEADER_WANT_DIGEST "Want-Digest"
+/* Informational. RFC7034 */
+#define MHD_HTTP_HEADER_X_FRAME_OPTIONS "X-Frame-Options"
+
+/* Some provisional headers. */
+#define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN \
+  "Access-Control-Allow-Origin"
+/** @} */ /* end of group headers */
+
+
+/**
+ * A client has requested the given url using the given method
+ * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT,
+ * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc).  The callback
+ * must initialize @a rhp to provide further callbacks which will
+ * process the request further and ultimately to provide the response
+ * to give back to the client, or return #MHD_NO.
+ *
+ * @param cls argument given together with the function
+ *        pointer when the handler was registered with MHD
+ * @param url the requested url (without arguments after "?")
+ * @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
+ *        #MHD_HTTP_METHOD_PUT, etc.)
+ * @return action how to proceed, NULL
+ *         if the socket must be closed due to a serious
+ *         error while handling the request
+ */
+typedef const struct MHD_Action *
+(*MHD_RequestCallback) (void *cls,
+                        struct MHD_Request *request,
+                        const char *url,
+                        enum MHD_Method method);
+
+
+/**
+ * Create (but do not yet start) an MHD daemon.
+ * Usually, you will want to set various options before
+ * starting the daemon with #MHD_daemon_start().
+ *
+ * @param cb function to be called for incoming requests
+ * @param cb_cls closure for @a cb
+ * @return NULL on error
+ */
+_MHD_EXTERN struct MHD_Daemon *
+MHD_daemon_create (MHD_RequestCallback cb,
+                   void *cb_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Start a webserver.
+ *
+ * @param daemon daemon to start; you can no longer set
+ *        options on this daemon after this call!
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_start (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Stop accepting connections from the listening socket.  Allows
+ * clients to continue processing, but stops accepting new
+ * connections.  Note that the caller is responsible for closing the
+ * returned socket; however, if MHD is run using threads (anything but
+ * external select mode), it must not be closed until AFTER
+ * #MHD_stop_daemon has been called (as it is theoretically possible
+ * that an existing thread is still using it).
+ *
+ * Note that some thread modes require the caller to have passed
+ * #MHD_USE_ITC when using this API.  If this daemon is
+ * in one of those modes and this option was not given to
+ * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET.
+ *
+ * @param daemon daemon to stop accepting new connections for
+ * @return old listen socket on success, #MHD_INVALID_SOCKET if
+ *         the daemon was already not listening anymore, or
+ *         was never started
+ * @ingroup specialized
+ */
+_MHD_EXTERN MHD_socket
+MHD_daemon_quiesce (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Shutdown and destroy an HTTP daemon.
+ *
+ * @param daemon daemon to stop
+ * @ingroup event
+ */
+_MHD_EXTERN void
+MHD_daemon_destroy (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Add another client connection to the set of connections managed by
+ * MHD.  This API is usually not needed (since MHD will accept inbound
+ * connections on the server socket).  Use this API in special cases,
+ * for example if your HTTP server is behind NAT and needs to connect
+ * out to the HTTP client, or if you are building a proxy.
+ *
+ * If you use this API in conjunction with a internal select or a
+ * thread pool, you must set the option #MHD_USE_ITC to ensure that
+ * the freshly added connection is immediately processed by MHD.
+ *
+ * The given client socket will be managed (and closed!) by MHD after
+ * this call and must no longer be used directly by the application
+ * afterwards.
+ *
+ * @param daemon daemon that manages the connection
+ * @param client_socket socket to manage (MHD will expect
+ *        to receive an HTTP request from this socket next).
+ * @param addr IP address of the client
+ * @param addrlen number of bytes in @a addr
+ * @return #MHD_SC_OK on success
+ *        The socket will be closed in any case; `errno` is
+ *        set to indicate further details about the error.
+ * @ingroup specialized
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_add_connection (struct MHD_Daemon *daemon,
+                           MHD_socket client_socket,
+                           const struct sockaddr *addr,
+                           socklen_t addrlen)
+MHD_NONNULL (1);
+
+
+/**
+ * Obtain the `select()` sets for this daemon.  Daemon's FDs will be
+ * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO
+ * for each fd_set before calling this function. FD_SETSIZE is assumed
+ * to be platform's default.
+ *
+ * This function should only be called in when MHD is configured to
+ * use external select with 'select()' or with 'epoll'.  In the latter
+ * case, it will only add the single 'epoll()' file descriptor used by
+ * MHD to the sets.  It's necessary to use #MHD_get_timeout() in
+ * combination with this function.
+ *
+ * This function must be called only for daemon started without
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @return #MHD_SC_OK on success, otherwise error code
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_get_fdset (struct MHD_Daemon *daemon,
+                      fd_set *read_fd_set,
+                      fd_set *write_fd_set,
+                      fd_set *except_fd_set,
+                      MHD_socket *max_fd)
+MHD_NONNULL (1,2,3,4);
+
+
+/**
+ * Obtain the `select()` sets for this daemon.  Daemon's FDs will be
+ * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO
+ * for each fd_set before calling this function.
+ *
+ * Passing custom FD_SETSIZE as @a fd_setsize allow usage of
+ * larger/smaller than platform's default fd_sets.
+ *
+ * This function should only be called in when MHD is configured to
+ * use external select with 'select()' or with 'epoll'.  In the latter
+ * case, it will only add the single 'epoll' file descriptor used by
+ * MHD to the sets.  It's necessary to use #MHD_get_timeout() in
+ * combination with this function.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @param fd_setsize value of FD_SETSIZE
+ * @return #MHD_SC_OK on success, otherwise error code
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_get_fdset2 (struct MHD_Daemon *daemon,
+                       fd_set *read_fd_set,
+                       fd_set *write_fd_set,
+                       fd_set *except_fd_set,
+                       MHD_socket *max_fd,
+                       unsigned int fd_setsize)
+MHD_NONNULL (1,2,3,4);
+
+
+/**
+ * Obtain the `select()` sets for this daemon.  Daemon's FDs will be
+ * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO
+ * for each fd_set before calling this function. Size of fd_set is
+ * determined by current value of FD_SETSIZE.  It's necessary to use
+ * #MHD_get_timeout() in combination with this function.
+ *
+ * This function could be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @return #MHD_YES on success, #MHD_NO if this
+ *         daemon was not started with the right
+ *         options for this call or any FD didn't
+ *         fit fd_set.
+ * @ingroup event
+ */
+#define MHD_daemon_get_fdset(daemon,read_fd_set,write_fd_set,except_fd_set, \
+                             max_fd) \
+  MHD_get_fdset2 ((daemon),(read_fd_set),(write_fd_set),(except_fd_set), \
+                  (max_fd),FD_SETSIZE)
+
+
+/**
+ * Obtain timeout value for polling function for this daemon.
+ * This function set value to amount of milliseconds for which polling
+ * function (`select()` or `poll()`) should at most block, not the
+ * timeout value set for connections.
+ * It is important to always use this function, even if connection
+ * timeout is not set, as in some cases MHD may already have more
+ * data to process on next turn (data pending in TLS buffers,
+ * connections are already ready with epoll etc.) and returned timeout
+ * will be zero.
+ *
+ * @param daemon daemon to query for timeout
+ * @param timeout set to the timeout (in milliseconds)
+ * @return #MHD_SC_OK on success, #MHD_SC_NO_TIMEOUT if timeouts are
+ *        not used (or no connections exist that would
+ *        necessitate the use of a timeout right now), otherwise
+ *        an error code
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_get_timeout (struct MHD_Daemon *daemon,
+                        MHD_UNSIGNED_LONG_LONG *timeout)
+MHD_NONNULL (1,2);
+
+
+/**
+ * Run webserver operations (without blocking unless in client
+ * callbacks).  This method should be called by clients in combination
+ * with #MHD_get_fdset if the client-controlled select method is used
+ * and #MHD_get_timeout().
+ *
+ * This function is a convenience method, which is useful if the
+ * fd_sets from #MHD_get_fdset were not directly passed to `select()`;
+ * with this function, MHD will internally do the appropriate `select()`
+ * call itself again.  While it is always safe to call #MHD_run (if
+ * #MHD_USE_INTERNAL_POLLING_THREAD is not set), you should call
+ * #MHD_run_from_select if performance is important (as it saves an
+ * expensive call to `select()`).
+ *
+ * @param daemon daemon to run
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_run (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Run webserver operations. This method should be called by clients
+ * in combination with #MHD_get_fdset and #MHD_get_timeout() if the
+ * client-controlled select method is used.
+ *
+ * You can use this function instead of #MHD_run if you called
+ * `select()` on the result from #MHD_get_fdset.  File descriptors in
+ * the sets that are not controlled by MHD will be ignored.  Calling
+ * this function instead of #MHD_run is more efficient as MHD will not
+ * have to call `select()` again to determine which operations are
+ * ready.
+ *
+ * This function cannot be used with daemon started with
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to run select loop for
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_run_from_select (struct MHD_Daemon *daemon,
+                            const fd_set *read_fd_set,
+                            const fd_set *write_fd_set,
+                            const fd_set *except_fd_set)
+MHD_NONNULL (1,2,3,4);
+
+
+/* ********************* daemon options ************** */
+
+
+/**
+ * Type of a callback function used for logging by MHD.
+ *
+ * @param cls closure
+ * @param sc status code of the event
+ * @param fm format string (`printf()`-style)
+ * @param ap arguments to @a fm
+ * @ingroup logging
+ */
+typedef void
+(*MHD_LoggingCallback)(void *cls,
+                       enum MHD_StatusCode sc,
+                       const char *fm,
+                       va_list ap);
+
+
+/**
+ * Set logging method.  Specify NULL to disable logging entirely.  By
+ * default (if this option is not given), we log error messages to
+ * stderr.
+ *
+ * @param daemon which instance to setup logging for
+ * @param logger function to invoke
+ * @param logger_cls closure for @a logger
+ */
+_MHD_EXTERN void
+MHD_daemon_set_logger (struct MHD_Daemon *daemon,
+                       MHD_LoggingCallback logger,
+                       void *logger_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Convenience macro used to disable logging.
+ *
+ * @param daemon which instance to disable logging for
+ */
+#define MHD_daemon_disable_logging(daemon) MHD_daemon_set_logger (daemon, NULL, \
+                                                                  NULL)
+
+
+/**
+ * Suppress use of "Date" header as this system has no RTC.
+ *
+ * @param daemon which instance to disable clock for.
+ */
+_MHD_EXTERN void
+MHD_daemon_suppress_date_no_clock (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Disable use of inter-thread communication channel.
+ * #MHD_daemon_disable_itc() can be used with
+ * #MHD_daemon_thread_internal() to perform some additional
+ * optimizations (in particular, not creating a pipe for IPC
+ * signalling).  If it is used, certain functions like
+ * #MHD_daemon_quiesce() or #MHD_connection_add() or
+ * #MHD_action_suspend() cannot be used anymore.
+ * #MHD_daemon_disable_itc() is not beneficial on platforms where
+ * select()/poll()/other signal shutdown() of a listen socket.
+ *
+ * You should only use this function if you are sure you do
+ * satisfy all of its requirements and need a generally minor
+ * boost in performance.
+ *
+ * @param daemon which instance to disable itc for
+ */
+_MHD_EXTERN void
+MHD_daemon_disable_itc (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Enable `turbo`.  Disables certain calls to `shutdown()`,
+ * enables aggressive non-blocking optimistic reads and
+ * other potentially unsafe optimizations.
+ * Most effects only happen with #MHD_ELS_EPOLL.
+ *
+ * @param daemon which instance to enable turbo for
+ */
+_MHD_EXTERN void
+MHD_daemon_enable_turbo (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Disable #MHD_action_suspend() functionality.
+ *
+ * You should only use this function if you are sure you do
+ * satisfy all of its requirements and need a generally minor
+ * boost in performance.
+ *
+ * @param daemon which instance to disable suspend for
+ */
+_MHD_EXTERN void
+MHD_daemon_disallow_suspend_resume (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * You need to set this option if you want to disable use of HTTP "Upgrade".
+ * "Upgrade" may require usage of additional internal resources,
+ * which we can avoid providing if they will not be used.
+ *
+ * You should only use this function if you are sure you do
+ * satisfy all of its requirements and need a generally minor
+ * boost in performance.
+ *
+ * @param daemon which instance to enable suspend/resume for
+ */
+_MHD_EXTERN void
+MHD_daemon_disallow_upgrade (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Possible levels of enforcement for TCP_FASTOPEN.
+ */
+enum MHD_FastOpenMethod
+{
+  /**
+   * Disable use of TCP_FASTOPEN.
+   */
+  MHD_FOM_DISABLE = -1,
+
+  /**
+   * Enable TCP_FASTOPEN where supported (Linux with a kernel >= 3.6).
+   * This is the default.
+   */
+  MHD_FOM_AUTO = 0,
+
+  /**
+   * If TCP_FASTOPEN is not available, return #MHD_NO.
+   * Also causes #MHD_daemon_start() to fail if setting
+   * the option fails later.
+   */
+  MHD_FOM_REQUIRE = 1
+};
+
+
+/**
+ * Configure TCP_FASTOPEN option, including setting a
+ * custom @a queue_length.
+ *
+ * Note that having a larger queue size can cause resource exhaustion
+ * attack as the TCP stack has to now allocate resources for the SYN
+ * packet along with its DATA.
+ *
+ * @param daemon which instance to configure TCP_FASTOPEN for
+ * @param fom under which conditions should we use TCP_FASTOPEN?
+ * @param queue_length queue length to use, default is 50 if this
+ *        option is never given.
+ * @return #MHD_YES upon success, #MHD_NO if #MHD_FOM_REQUIRE was
+ *         given, but TCP_FASTOPEN is not available on the platform
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_daemon_tcp_fastopen (struct MHD_Daemon *daemon,
+                         enum MHD_FastOpenMethod fom,
+                         unsigned int queue_length)
+MHD_NONNULL (1);
+
+
+/**
+ * Address family to be used by MHD.
+ */
+enum MHD_AddressFamily
+{
+  /**
+   * Option not given, do not listen at all
+   * (unless listen socket or address specified by
+   * other means).
+   */
+  MHD_AF_NONE = 0,
+
+  /**
+   * Pick "best" available method automatically.
+   */
+  MHD_AF_AUTO,
+
+  /**
+   * Use IPv4.
+   */
+  MHD_AF_INET4,
+
+  /**
+   * Use IPv6.
+   */
+  MHD_AF_INET6,
+
+  /**
+   * Use dual stack.
+   */
+  MHD_AF_DUAL
+};
+
+
+/**
+ * Bind to the given TCP port and address family.
+ *
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ * Ineffective in conjunction with #MHD_daemon_bind_sa().
+ *
+ * If neither this option nor the other two mentioned above
+ * is specified, MHD will simply not listen on any socket!
+ *
+ * @param daemon which instance to configure the TCP port for
+ * @param af address family to use
+ * @param port port to use, 0 to bind to a random (free) port
+ */
+_MHD_EXTERN void
+MHD_daemon_bind_port (struct MHD_Daemon *daemon,
+                      enum MHD_AddressFamily af,
+                      uint16_t port)
+MHD_NONNULL (1);
+
+
+/**
+ * Bind to the given socket address.
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ *
+ * @param daemon which instance to configure the binding address for
+ * @param sa address to bind to; can be IPv4 (AF_INET), IPv6 (AF_INET6)
+ *        or even a UNIX domain socket (AF_UNIX)
+ * @param sa_len number of bytes in @a sa
+ */
+_MHD_EXTERN void
+MHD_daemon_bind_socket_address (struct MHD_Daemon *daemon,
+                                const struct sockaddr *sa,
+                                size_t sa_len)
+MHD_NONNULL (1);
+
+
+/**
+ * Use the given backlog for the listen() call.
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ *
+ * @param daemon which instance to configure the backlog for
+ * @param listen_backlog backlog to use
+ */
+_MHD_EXTERN void
+MHD_daemon_listen_backlog (struct MHD_Daemon *daemon,
+                           int listen_backlog)
+MHD_NONNULL (1);
+
+
+/**
+ * If present true, allow reusing address:port socket (by using
+ * SO_REUSEPORT on most platform, or platform-specific ways).  If
+ * present and set to false, disallow reusing address:port socket
+ * (does nothing on most platform, but uses SO_EXCLUSIVEADDRUSE on
+ * Windows).
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ *
+ * @param daemon daemon to configure address reuse for
+ */
+_MHD_EXTERN void
+MHD_daemon_listen_allow_address_reuse (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Accept connections from the given socket.  Socket
+ * must be a TCP or UNIX domain (stream) socket.
+ *
+ * Unless -1 is given, this disables other listen options, including
+ * #MHD_daemon_bind_sa(), #MHD_daemon_bind_port(),
+ * #MHD_daemon_listen_queue() and
+ * #MHD_daemon_listen_allow_address_reuse().
+ *
+ * @param daemon daemon to set listen socket for
+ * @param listen_socket listen socket to use,
+ *        MHD_INVALID_SOCKET value will cause this call to be
+ *        ignored (other binding options may still be effective)
+ */
+_MHD_EXTERN void
+MHD_daemon_listen_socket (struct MHD_Daemon *daemon,
+                          MHD_socket listen_socket)
+MHD_NONNULL (1);
+
+
+/**
+ * Event loop syscalls supported by MHD.
+ */
+enum MHD_EventLoopSyscall
+{
+  /**
+   * Automatic selection of best-available method. This is also the
+   * default.
+   */
+  MHD_ELS_AUTO = 0,
+
+  /**
+   * Use select().
+   */
+  MHD_ELS_SELECT = 1,
+
+  /**
+   * Use poll().
+   */
+  MHD_ELS_POLL = 2,
+
+  /**
+   * Use epoll().
+   */
+  MHD_ELS_EPOLL = 3
+};
+
+
+/**
+ * Force use of a particular event loop system call.
+ *
+ * @param daemon daemon to set event loop style for
+ * @param els event loop syscall to use
+ * @return #MHD_NO on failure, #MHD_YES on success
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_daemon_event_loop (struct MHD_Daemon *daemon,
+                       enum MHD_EventLoopSyscall els)
+MHD_NONNULL (1);
+
+
+/**
+ * Protocol strictness enforced by MHD on clients.
+ */
+enum MHD_ProtocolStrictLevel
+{
+  /**
+   * Be particularly permissive about the protocol, allowing slight
+   * deviations that are technically not allowed by the
+   * RFC. Specifically, at the moment, this flag causes MHD to allow
+   * spaces in header field names. This is disallowed by the standard.
+   * It is not recommended to set this value on publicly available
+   * servers as it may potentially lower level of protection.
+   */
+  MHD_PSL_PERMISSIVE = -1,
+
+  /**
+   * Sane level of protocol enforcement for production use.
+   */
+  MHD_PSL_DEFAULT = 0,
+
+  /**
+   * Be strict about the protocol (as opposed to as tolerant as
+   * possible).  Specifically, at the moment, this flag causes MHD to
+   * reject HTTP 1.1 connections without a "Host" header.  This is
+   * required by the standard, but of course in violation of the "be
+   * as liberal as possible in what you accept" norm.  It is
+   * recommended to set this if you are testing clients against
+   * MHD, and to use default in production.
+   */
+  MHD_PSL_STRICT = 1
+};
+
+
+/**
+ * Set how strictly MHD will enforce the HTTP protocol.
+ *
+ * @param daemon daemon to configure strictness for
+ * @param sl how strict should we be
+ */
+_MHD_EXTERN void
+MHD_daemon_protocol_strict_level (struct MHD_Daemon *daemon,
+                                  enum MHD_ProtocolStrictLevel sl)
+MHD_NONNULL (1);
+
+
+/**
+ * Use SHOUTcast.  This will cause the response to begin
+ * with the SHOUTcast "ICY" line instead of "HTTP".
+ *
+ * @param daemon daemon to set SHOUTcast option for
+ */
+_MHD_EXTERN void
+MHD_daemon_enable_shoutcast (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+
+/**
+ * Enable and configure TLS.
+ *
+ * @param daemon which instance should be configured
+ * @param tls_backend which TLS backend should be used,
+ *    currently only "gnutls" is supported.  You can
+ *    also specify NULL for best-available (which is the default).
+ * @param ciphers which ciphers should be used by TLS, default is
+ *     "NORMAL"
+ * @return status code, #MHD_SC_OK upon success
+ *     #MHD_TLS_BACKEND_UNSUPPORTED if the @a backend is unknown
+ *     #MHD_TLS_DISABLED if this build of MHD does not support TLS
+ *     #MHD_TLS_CIPHERS_INVALID if the given @a ciphers are not supported
+ *     by this backend
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_set_tls_backend (struct MHD_Daemon *daemon,
+                            const char *tls_backend,
+                            const char *ciphers)
+MHD_NONNULL (1);
+
+
+/**
+ * Provide TLS key and certificate data in-memory.
+ *
+ * @param daemon which instance should be configured
+ * @param mem_key private key (key.pem) to be used by the
+ *     HTTPS daemon.  Must be the actual data in-memory, not a filename.
+ * @param mem_cert certificate (cert.pem) to be used by the
+ *     HTTPS daemon.  Must be the actual data in-memory, not a filename.
+ * @param pass passphrase phrase to decrypt 'key.pem', NULL
+ *     if @param mem_key is in cleartext already
+ * @return #MHD_SC_OK upon success; TODO: define failure modes
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_tls_key_and_cert_from_memory (struct MHD_Daemon *daemon,
+                                         const char *mem_key,
+                                         const char *mem_cert,
+                                         const char *pass)
+MHD_NONNULL (1,2,3);
+
+
+/**
+ * Configure DH parameters (dh.pem) to use for the TLS key
+ * exchange.
+ *
+ * @param daemon daemon to configure tls for
+ * @param dh parameters to use
+ * @return #MHD_SC_OK upon success; TODO: define failure modes
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_tls_mem_dhparams (struct MHD_Daemon *daemon,
+                             const char *dh)
+MHD_NONNULL (1);
+
+
+/**
+ * Function called to lookup the pre shared key (@a psk) for a given
+ * HTTP connection based on the @a username.
+ *
+ * @param cls closure
+ * @param connection the HTTPS connection
+ * @param username the user name claimed by the other side
+ * @param[out] psk to be set to the pre-shared-key; should be allocated with malloc(),
+ *                 will be freed by MHD
+ * @param[out] psk_size to be set to the number of bytes in @a psk
+ * @return 0 on success, -1 on errors
+ */
+typedef int
+(*MHD_PskServerCredentialsCallback)(void *cls,
+                                    const struct MHD_Connection *connection,
+                                    const char *username,
+                                    void **psk,
+                                    size_t *psk_size);
+
+
+/**
+ * Configure PSK to use for the TLS key exchange.
+ *
+ * @param daemon daemon to configure tls for
+ * @param psk_cb function to call to obtain pre-shared key
+ * @param psk_cb_cls closure for @a psk_cb
+ * @return #MHD_SC_OK upon success; TODO: define failure modes
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_set_tls_psk_callback (struct MHD_Daemon *daemon,
+                                 MHD_PskServerCredentialsCallback psk_cb,
+                                 void *psk_cb_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Memory pointer for the certificate (ca.pem) to be used by the
+ * HTTPS daemon for client authentication.
+ *
+ * @param daemon daemon to configure tls for
+ * @param mem_trust memory pointer to the certificate
+ * @return #MHD_SC_OK upon success; TODO: define failure modes
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_tls_mem_trust (struct MHD_Daemon *daemon,
+                          const char *mem_trust)
+MHD_NONNULL (1);
+
+
+/**
+ * Configure daemon credentials type for GnuTLS.
+ *
+ * @param gnutls_credentials must be a value of
+ *   type `gnutls_credentials_type_t`
+ * @return #MHD_SC_OK upon success; TODO: define failure modes
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_gnutls_credentials (struct MHD_Daemon *daemon,
+                               int gnutls_credentials)
+MHD_NONNULL (1);
+
+
+/**
+ * Provide TLS key and certificate data via callback.
+ *
+ * Use a callback to determine which X.509 certificate should be used
+ * for a given HTTPS connection.  This option provides an alternative
+ * to #MHD_daemon_tls_key_and_cert_from_memory().  You must use this
+ * version if multiple domains are to be hosted at the same IP address
+ * using TLS's Server Name Indication (SNI) extension.  In this case,
+ * the callback is expected to select the correct certificate based on
+ * the SNI information provided.  The callback is expected to access
+ * the SNI data using `gnutls_server_name_get()`.  Using this option
+ * requires GnuTLS 3.0 or higher.
+ *
+ * @param daemon daemon to configure callback for
+ * @param cb must be of type `gnutls_certificate_retrieve_function2 *`.
+ * @return #MHD_SC_OK on success
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_gnutls_key_and_cert_from_callback (struct MHD_Daemon *daemon,
+                                              void *cb)
+MHD_NONNULL (1);
+
+
+/**
+ * Which threading mode should be used by MHD?
+ */
+enum MHD_ThreadingMode
+{
+
+  /**
+   * MHD should create its own thread for listening and furthermore
+   * create another thread per connection to handle requests.  Use
+   * this if handling requests is CPU-intensive or blocking, your
+   * application is thread-safe and you have plenty of memory (per
+   * request).
+   */
+  MHD_TM_THREAD_PER_CONNECTION = -1,
+
+  /**
+   * Use an external event loop. This is the default.
+   */
+  MHD_TM_EXTERNAL_EVENT_LOOP = 0,
+
+  /**
+   * Run with one or more worker threads.  Any positive value
+   * means that MHD should start that number of worker threads
+   * (so > 1 is a thread pool) and distributed processing of
+   * requests among the workers.
+   *
+   * A good way to express the use of a thread pool
+   * in your code would be to write "MHD_TM_THREAD_POOL(4)"
+   * to indicate four threads.
+   *
+   * If a positive value is set, * #MHD_daemon_run() and
+   * #MHD_daemon_run_from_select() cannot be used.
+   */
+  MHD_TM_WORKER_THREADS = 1
+
+};
+
+
+/**
+ * Use a thread pool of size @a n.
+ *
+ * @return an `enum MHD_ThreadingMode` for a thread pool of size @a n
+ */
+#define MHD_TM_THREAD_POOL(n) ((enum MHD_ThreadingMode) (n))
+
+
+/**
+ * Specify threading mode to use.
+ *
+ * @param daemon daemon to configure
+ * @param tm mode to use (positive values indicate the
+ *        number of worker threads to be used)
+ */
+_MHD_EXTERN void
+MHD_daemon_threading_mode (struct MHD_Daemon *daemon,
+                           enum MHD_ThreadingMode tm)
+MHD_NONNULL (1);
+
+
+/**
+ * Allow or deny a client to connect.
+ *
+ * @param cls closure
+ * @param addr address information from the client
+ * @param addrlen length of @a addr
+ * @see #MHD_daemon_accept_policy()
+ * @return #MHD_YES if connection is allowed, #MHD_NO if not
+ */
+typedef enum MHD_Bool
+(*MHD_AcceptPolicyCallback)(void *cls,
+                            const struct sockaddr *addr,
+                            size_t addrlen);
+
+
+/**
+ * Set  a policy callback that accepts/rejects connections
+ * based on the client's IP address.  This function will be called
+ * before a connection object is created.
+ *
+ * @param daemon daemon to set policy for
+ * @param apc function to call to check the policy
+ * @param apc_cls closure for @a apc
+ */
+_MHD_EXTERN void
+MHD_daemon_accept_policy (struct MHD_Daemon *daemon,
+                          MHD_AcceptPolicyCallback apc,
+                          void *apc_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Function called by MHD to allow the application to log
+ * the full @a uri of a @a request.
+ *
+ * @param cls client-defined closure
+ * @param uri the full URI from the HTTP request
+ * @param request the HTTP request handle (headers are
+ *         not yet available)
+ * @return value to set for the "request_context" of @a request
+ */
+typedef void *
+(*MHD_EarlyUriLogCallback)(void *cls,
+                           const char *uri,
+                           struct MHD_Request *request);
+
+
+/**
+ * Register a callback to be called first for every request
+ * (before any parsing of the header).  Makes it easy to
+ * log the full URL.
+ *
+ * @param daemon daemon for which to set the logger
+ * @param cb function to call
+ * @param cb_cls closure for @a cb
+ */
+_MHD_EXTERN void
+MHD_daemon_set_early_uri_logger (struct MHD_Daemon *daemon,
+                                 MHD_EarlyUriLogCallback cb,
+                                 void *cb_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * The `enum MHD_ConnectionNotificationCode` specifies types
+ * of connection notifications.
+ * @ingroup request
+ */
+enum MHD_ConnectionNotificationCode
+{
+
+  /**
+   * A new connection has been started.
+   * @ingroup request
+   */
+  MHD_CONNECTION_NOTIFY_STARTED = 0,
+
+  /**
+   * A connection is closed.
+   * @ingroup request
+   */
+  MHD_CONNECTION_NOTIFY_CLOSED = 1
+
+};
+
+
+/**
+ * Signature of the callback used by MHD to notify the
+ * application about started/stopped connections
+ *
+ * @param cls client-defined closure
+ * @param connection connection handle
+ * @param socket_context socket-specific pointer where the
+ *                       client can associate some state specific
+ *                       to the TCP connection; note that this is
+ *                       different from the "req_cls" which is per
+ *                       HTTP request.  The client can initialize
+ *                       during #MHD_CONNECTION_NOTIFY_STARTED and
+ *                       cleanup during #MHD_CONNECTION_NOTIFY_CLOSED
+ *                       and access in the meantime using
+ *                       #MHD_CONNECTION_INFO_SOCKET_CONTEXT.
+ * @param toe reason for connection notification
+ * @see #MHD_OPTION_NOTIFY_CONNECTION
+ * @ingroup request
+ */
+typedef void
+(*MHD_NotifyConnectionCallback) (void *cls,
+                                 struct MHD_Connection *connection,
+                                 enum MHD_ConnectionNotificationCode toe);
+
+
+/**
+ * Register a function that should be called whenever a connection is
+ * started or closed.
+ *
+ * @param daemon daemon to set callback for
+ * @param ncc function to call to check the policy
+ * @param ncc_cls closure for @a apc
+ */
+_MHD_EXTERN void
+MHD_daemon_set_notify_connection (struct MHD_Daemon *daemon,
+                                  MHD_NotifyConnectionCallback ncc,
+                                  void *ncc_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Maximum memory size per connection.
+ * Default is 32 kb (#MHD_POOL_SIZE_DEFAULT).
+ * Values above 128k are unlikely to result in much benefit, as half
+ * of the memory will be typically used for IO, and TCP buffers are
+ * unlikely to support window sizes above 64k on most systems.
+ *
+ * @param daemon daemon to configure
+ * @param memory_limit_b connection memory limit to use in bytes
+ * @param memory_increment_b increment to use when growing the read buffer, must be smaller than @a memory_limit_b
+ */
+_MHD_EXTERN void
+MHD_daemon_connection_memory_limit (struct MHD_Daemon *daemon,
+                                    size_t memory_limit_b,
+                                    size_t memory_increment_b)
+MHD_NONNULL (1);
+
+
+/**
+ * Desired size of the stack for threads created by MHD.  Use 0 for
+ * system default.  Only useful if the selected threading mode
+ * is not #MHD_TM_EXTERNAL_EVENT_LOOP.
+ *
+ * @param daemon daemon to configure
+ * @param stack_limit_b stack size to use in bytes
+ */
+_MHD_EXTERN void
+MHD_daemon_thread_stack_size (struct MHD_Daemon *daemon,
+                              size_t stack_limit_b)
+MHD_NONNULL (1);
+
+
+/**
+ * Set maximum number of concurrent connections to accept.  If not
+ * given, MHD will not enforce any limits (modulo running into
+ * OS limits).  Values of 0 mean no limit.
+ *
+ * @param daemon daemon to configure
+ * @param global_connection_limit maximum number of (concurrent)
+          connections
+ * @param ip_connection_limit limit on the number of (concurrent)
+ *        connections made to the server from the same IP address.
+ *        Can be used to prevent one IP from taking over all of
+ *        the allowed connections.  If the same IP tries to
+ *        establish more than the specified number of
+ *        connections, they will be immediately rejected.
+ */
+_MHD_EXTERN void
+MHD_daemon_connection_limits (struct MHD_Daemon *daemon,
+                              unsigned int global_connection_limit,
+                              unsigned int ip_connection_limit)
+MHD_NONNULL (1);
+
+
+/**
+ * After how many seconds of inactivity should a
+ * connection automatically be timed out?
+ * Use zero for no timeout, which is also the (unsafe!) default.
+ *
+ * @param daemon daemon to configure
+ * @param timeout_s number of seconds of timeout to use
+ */
+_MHD_EXTERN void
+MHD_daemon_connection_default_timeout (struct MHD_Daemon *daemon,
+                                       unsigned int timeout_s)
+MHD_NONNULL (1);
+
+
+/**
+ * Signature of functions performing unescaping of strings.
+ * The return value must be "strlen(s)" and @a s  should be
+ * updated.  Note that the unescape function must not lengthen @a s
+ * (the result must be shorter than the input and still be
+ * 0-terminated).
+ *
+ * @param cls closure
+ * @param req the request for which unescaping is performed
+ * @param[in,out] s string to unescape
+ * @return number of characters in @a s (excluding 0-terminator)
+ */
+typedef size_t
+(*MHD_UnescapeCallback) (void *cls,
+                         struct MHD_Request *req,
+                         char *s);
+
+
+/**
+ * Specify a function that should be called for unescaping escape
+ * sequences in URIs and URI arguments.  Note that this function
+ * will NOT be used by the `struct MHD_PostProcessor`.  If this
+ * option is not specified, the default method will be used which
+ * decodes escape sequences of the form "%HH".
+ *
+ * @param daemon daemon to configure
+ * @param unescape_cb function to use, NULL for default
+ * @param unescape_cb_cls closure for @a unescape_cb
+ */
+_MHD_EXTERN void
+MHD_daemon_unescape_cb (struct MHD_Daemon *daemon,
+                        MHD_UnescapeCallback unescape_cb,
+                        void *unescape_cb_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Set random values to be used by the Digest Auth module.  Note that
+ * the application must ensure that @a buf remains allocated and
+ * unmodified while the daemon is running.
+ *
+ * @param daemon daemon to configure
+ * @param buf_size number of bytes in @a buf
+ * @param buf entropy buffer
+ */
+_MHD_EXTERN void
+MHD_daemon_digest_auth_random (struct MHD_Daemon *daemon,
+                               size_t buf_size,
+                               const void *buf)
+MHD_NONNULL (1,3);
+
+
+/**
+ * Length of the internal array holding the map of the nonce and
+ * the nonce counter.
+ *
+ * @param daemon daemon to configure
+ * @param nc_length desired array length
+ */
+_MHD_EXTERN enum MHD_StatusCode
+MHD_daemon_digest_auth_nc_length (struct MHD_Daemon *daemon,
+                                  size_t nc_length)
+MHD_NONNULL (1);
+
+
+/* ********************* connection options ************** */
+
+
+/**
+ * Set custom timeout for the given connection.
+ * Specified as the number of seconds.  Use zero for no timeout.
+ * Calling this function will reset timeout timer.
+ *
+ * @param connection connection to configure timeout for
+ * @param timeout_s new timeout in seconds
+ */
+_MHD_EXTERN void
+MHD_connection_set_timeout (struct MHD_Connection *connection,
+                            unsigned int timeout_s)
+MHD_NONNULL (1);
+
+
+/* **************** Request handling functions ***************** */
+
+
+/**
+ * The `enum MHD_ValueKind` specifies the source of
+ * the key-value pairs in the HTTP protocol.
+ */
+enum MHD_ValueKind
+{
+
+  /**
+   * HTTP header (request/response).
+   */
+  MHD_HEADER_KIND = 1,
+
+  /**
+   * Cookies.  Note that the original HTTP header containing
+   * the cookie(s) will still be available and intact.
+   */
+  MHD_COOKIE_KIND = 2,
+
+  /**
+   * POST data.  This is available only if a content encoding
+   * supported by MHD is used (currently only URL encoding),
+   * and only if the posted content fits within the available
+   * memory pool.  Note that in that case, the upload data
+   * given to the #MHD_AccessHandlerCallback will be
+   * empty (since it has already been processed).
+   */
+  MHD_POSTDATA_KIND = 4,
+
+  /**
+   * GET (URI) arguments.
+   */
+  MHD_GET_ARGUMENT_KIND = 8,
+
+  /**
+   * HTTP footer (only for HTTP 1.1 chunked encodings).
+   */
+  MHD_FOOTER_KIND = 16
+};
+
+
+/**
+ * Iterator over key-value pairs.  This iterator can be used to
+ * iterate over all of the cookies, headers, or POST-data fields of a
+ * request, and also to iterate over the headers that have been added
+ * to a response.
+ *
+ * @param cls closure
+ * @param kind kind of the header we are looking at
+ * @param key key for the value, can be an empty string
+ * @param value corresponding value, can be NULL
+ * @return #MHD_YES to continue iterating,
+ *         #MHD_NO to abort the iteration
+ * @ingroup request
+ */
+typedef int
+(*MHD_KeyValueIterator) (void *cls,
+                         enum MHD_ValueKind kind,
+                         const char *key,
+                         const char *value);
+
+
+/**
+ * Get all of the headers from the request.
+ *
+ * @param request request to get values from
+ * @param kind types of values to iterate over, can be a bitmask
+ * @param iterator callback to call on each header;
+ *        maybe NULL (then just count headers)
+ * @param iterator_cls extra argument to @a iterator
+ * @return number of entries iterated over
+ * @ingroup request
+ */
+_MHD_EXTERN unsigned int
+MHD_request_get_values (struct MHD_Request *request,
+                        enum MHD_ValueKind kind,
+                        MHD_KeyValueIterator iterator,
+                        void *iterator_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * This function can be used to add an entry to the HTTP headers of a
+ * request (so that the #MHD_request_get_values function will
+ * return them -- and the `struct MHD_PostProcessor` will also see
+ * them).  This maybe required in certain situations (see Mantis
+ * #1399) where (broken) HTTP implementations fail to supply values
+ * needed by the post processor (or other parts of the application).
+ *
+ * This function MUST only be called from within the
+ * request callbacks (otherwise, access maybe improperly
+ * synchronized).  Furthermore, the client must guarantee that the key
+ * and value arguments are 0-terminated strings that are NOT freed
+ * until the connection is closed.  (The easiest way to do this is by
+ * passing only arguments to permanently allocated strings.).
+ *
+ * @param request the request for which a
+ *  value should be set
+ * @param kind kind of the value
+ * @param key key for the value
+ * @param value the value itself
+ * @return #MHD_NO if the operation could not be
+ *         performed due to insufficient memory;
+ *         #MHD_YES on success
+ * @ingroup request
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_request_set_value (struct MHD_Request *request,
+                       enum MHD_ValueKind kind,
+                       const char *key,
+                       const char *value)
+MHD_NONNULL (1,3,4);
+
+
+/**
+ * Get a particular header value.  If multiple
+ * values match the kind, return any one of them.
+ *
+ * @param request request to get values from
+ * @param kind what kind of value are we looking for
+ * @param key the header to look for, NULL to lookup 'trailing' value without a key
+ * @return NULL if no such item was found
+ * @ingroup request
+ */
+_MHD_EXTERN const char *
+MHD_request_lookup_value (struct MHD_Request *request,
+                          enum MHD_ValueKind kind,
+                          const char *key)
+MHD_NONNULL (1);
+
+
+/**
+ * @defgroup httpcode HTTP response codes.
+ * These are the status codes defined for HTTP responses.
+ * @{
+ */
+/* See http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml */
+enum MHD_HTTP_StatusCode
+{
+  MHD_HTTP_CONTINUE = 100,
+  MHD_HTTP_SWITCHING_PROTOCOLS = 101,
+  MHD_HTTP_PROCESSING = 102,
+
+  MHD_HTTP_OK = 200,
+  MHD_HTTP_CREATED = 201,
+  MHD_HTTP_ACCEPTED = 202,
+  MHD_HTTP_NON_AUTHORITATIVE_INFORMATION = 203,
+  MHD_HTTP_NO_CONTENT = 204,
+  MHD_HTTP_RESET_CONTENT = 205,
+  MHD_HTTP_PARTIAL_CONTENT = 206,
+  MHD_HTTP_MULTI_STATUS = 207,
+  MHD_HTTP_ALREADY_REPORTED = 208,
+
+  MHD_HTTP_IM_USED = 226,
+
+  MHD_HTTP_MULTIPLE_CHOICES = 300,
+  MHD_HTTP_MOVED_PERMANENTLY = 301,
+  MHD_HTTP_FOUND = 302,
+  MHD_HTTP_SEE_OTHER = 303,
+  MHD_HTTP_NOT_MODIFIED = 304,
+  MHD_HTTP_USE_PROXY = 305,
+  MHD_HTTP_SWITCH_PROXY = 306, /* IANA: unused */
+  MHD_HTTP_TEMPORARY_REDIRECT = 307,
+  MHD_HTTP_PERMANENT_REDIRECT = 308,
+
+  MHD_HTTP_BAD_REQUEST = 400,
+  MHD_HTTP_UNAUTHORIZED = 401,
+  MHD_HTTP_PAYMENT_REQUIRED = 402,
+  MHD_HTTP_FORBIDDEN = 403,
+  MHD_HTTP_NOT_FOUND = 404,
+  MHD_HTTP_METHOD_NOT_ALLOWED = 405,
+  MHD_HTTP_NOT_ACCEPTABLE = 406,
+/** @deprecated */
+#define MHD_HTTP_METHOD_NOT_ACCEPTABLE \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_HTTP_METHOD_NOT_ACCEPTABLE is deprecated, use MHD_HTTP_NOT_ACCEPTABLE") \
+  MHD_HTTP_NOT_ACCEPTABLE
+  MHD_HTTP_PROXY_AUTHENTICATION_REQUIRED = 407,
+  MHD_HTTP_REQUEST_TIMEOUT = 408,
+  MHD_HTTP_CONFLICT = 409,
+  MHD_HTTP_GONE = 410,
+  MHD_HTTP_LENGTH_REQUIRED = 411,
+  MHD_HTTP_PRECONDITION_FAILED = 412,
+  MHD_HTTP_PAYLOAD_TOO_LARGE = 413,
+/** @deprecated */
+#define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_HTTP_REQUEST_ENTITY_TOO_LARGE is deprecated, use MHD_HTTP_PAYLOAD_TOO_LARGE") \
+  MHD_HTTP_PAYLOAD_TOO_LARGE
+  MHD_HTTP_URI_TOO_LONG = 414,
+/** @deprecated */
+#define MHD_HTTP_REQUEST_URI_TOO_LONG \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_HTTP_REQUEST_URI_TOO_LONG is deprecated, use MHD_HTTP_URI_TOO_LONG") \
+  MHD_HTTP_URI_TOO_LONG
+  MHD_HTTP_UNSUPPORTED_MEDIA_TYPE = 415,
+  MHD_HTTP_RANGE_NOT_SATISFIABLE = 416,
+/** @deprecated */
+#define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE \
+  _MHD_DEPR_IN_MACRO ( \
+    "Value MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE is deprecated, use MHD_HTTP_RANGE_NOT_SATISFIABLE") \
+  MHD_HTTP_RANGE_NOT_SATISFIABLE
+  MHD_HTTP_EXPECTATION_FAILED = 417,
+
+  MHD_HTTP_MISDIRECTED_REQUEST = 421,
+  MHD_HTTP_UNPROCESSABLE_ENTITY = 422,
+  MHD_HTTP_LOCKED = 423,
+  MHD_HTTP_FAILED_DEPENDENCY = 424,
+  MHD_HTTP_UNORDERED_COLLECTION = 425, /* IANA: unused */
+  MHD_HTTP_UPGRADE_REQUIRED = 426,
+
+  MHD_HTTP_PRECONDITION_REQUIRED = 428,
+  MHD_HTTP_TOO_MANY_REQUESTS = 429,
+  MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
+
+  MHD_HTTP_NO_RESPONSE = 444, /* IANA: unused */
+
+  MHD_HTTP_RETRY_WITH = 449, /* IANA: unused */
+  MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450,  /* IANA: unused */
+  MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451,
+
+  MHD_HTTP_INTERNAL_SERVER_ERROR = 500,
+  MHD_HTTP_NOT_IMPLEMENTED = 501,
+  MHD_HTTP_BAD_GATEWAY = 502,
+  MHD_HTTP_SERVICE_UNAVAILABLE = 503,
+  MHD_HTTP_GATEWAY_TIMEOUT = 504,
+  MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED = 505,
+  MHD_HTTP_VARIANT_ALSO_NEGOTIATES = 506,
+  MHD_HTTP_INSUFFICIENT_STORAGE = 507,
+  MHD_HTTP_LOOP_DETECTED = 508,
+  MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED = 509,  /* IANA: unused */
+  MHD_HTTP_NOT_EXTENDED = 510,
+  MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511
+
+};
+
+
+/**
+ * Returns the string reason phrase for a response code.
+ *
+ * If we don't have a string for a status code, we give the first
+ * message in that status code class.
+ */
+_MHD_EXTERN const char *
+MHD_get_reason_phrase_for (enum MHD_HTTP_StatusCode code);
+
+/** @} */ /* end of group httpcode */
+
+
+/**
+ * @defgroup versions HTTP versions
+ * These strings should be used to match against the first line of the
+ * HTTP header.
+ * @{
+ */
+#define MHD_HTTP_VERSION_1_0 "HTTP/1.0"
+#define MHD_HTTP_VERSION_1_1 "HTTP/1.1"
+
+/** @} */ /* end of group versions */
+
+
+/**
+ * Suspend handling of network data for a given request.  This can
+ * be used to dequeue a request from MHD's event loop for a while.
+ *
+ * If you use this API in conjunction with a internal select or a
+ * thread pool, you must set the option #MHD_USE_ITC to
+ * ensure that a resumed request is immediately processed by MHD.
+ *
+ * Suspended requests continue to count against the total number of
+ * requests allowed (per daemon, as well as per IP, if such limits
+ * are set).  Suspended requests will NOT time out; timeouts will
+ * restart when the request handling is resumed.  While a
+ * request is suspended, MHD will not detect disconnects by the
+ * client.
+ *
+ * The only safe time to suspend a request is from either a
+ * #MHD_RequestHeaderCallback, #MHD_UploadCallback, or a
+ * #MHD_RequestfetchResponseCallback.  Suspending a request
+ * at any other time will cause an assertion failure.
+ *
+ * Finally, it is an API violation to call #MHD_daemon_stop() while
+ * having suspended requests (this will at least create memory and
+ * socket leaks or lead to undefined behavior).  You must explicitly
+ * resume all requests before stopping the daemon.
+ *
+ * @return action to cause a request to be suspended.
+ */
+_MHD_EXTERN const struct MHD_Action *
+MHD_action_suspend (void);
+
+
+/**
+ * Resume handling of network data for suspended request.  It is
+ * safe to resume a suspended request at any time.  Calling this
+ * function on a request that was not previously suspended will
+ * result in undefined behavior.
+ *
+ * If you are using this function in ``external'' select mode, you must
+ * make sure to run #MHD_run() afterwards (before again calling
+ * #MHD_get_fdset(), as otherwise the change may not be reflected in
+ * the set returned by #MHD_get_fdset() and you may end up with a
+ * request that is stuck until the next network activity.
+ *
+ * @param request the request to resume
+ */
+_MHD_EXTERN void
+MHD_request_resume (struct MHD_Request *request)
+MHD_NONNULL (1);
+
+
+/* **************** Response manipulation functions ***************** */
+
+
+/**
+ * Data transmitted in response to an HTTP request.
+ * Usually the final action taken in response to
+ * receiving a request.
+ */
+struct MHD_Response;
+
+
+/**
+ * Converts a @a response to an action.  If @a destroy_after_use
+ * is set, the reference to the @a response is consumed
+ * by the conversion. If @a consume is #MHD_NO, then
+ * the @a response can be converted to actions in the future.
+ * However, the @a response is frozen by this step and
+ * must no longer be modified (i.e. by setting headers).
+ *
+ * @param response response to convert, not NULL
+ * @param destroy_after_use should the response object be consumed?
+ * @return corresponding action, never returns NULL
+ *
+ * Implementation note: internally, this is largely just
+ * a cast (and possibly an RC increment operation),
+ * as a response *is* an action.  As no memory is
+ * allocated, this operation cannot fail.
+ */
+_MHD_EXTERN const struct MHD_Action *
+MHD_action_from_response (struct MHD_Response *response,
+                          enum MHD_Bool destroy_after_use)
+MHD_NONNULL (1);
+
+
+/**
+ * Only respond in conservative HTTP 1.0-mode.  In
+ * particular, do not (automatically) sent "Connection" headers and
+ * always close the connection after generating the response.
+ *
+ * @param request the request for which we force HTTP 1.0 to be used
+ */
+_MHD_EXTERN void
+MHD_response_option_v10_only (struct MHD_Response *response)
+MHD_NONNULL (1);
+
+
+/**
+ * The `enum MHD_RequestTerminationCode` specifies reasons
+ * why a request has been terminated (or completed).
+ * @ingroup request
+ */
+enum MHD_RequestTerminationCode
+{
+
+  /**
+   * We finished sending the response.
+   * @ingroup request
+   */
+  MHD_REQUEST_TERMINATED_COMPLETED_OK = 0,
+
+  /**
+   * Error handling the connection (resources
+   * exhausted, other side closed connection,
+   * application error accepting request, etc.)
+   * @ingroup request
+   */
+  MHD_REQUEST_TERMINATED_WITH_ERROR = 1,
+
+  /**
+   * No activity on the connection for the number
+   * of seconds specified using
+   * #MHD_OPTION_CONNECTION_TIMEOUT.
+   * @ingroup request
+   */
+  MHD_REQUEST_TERMINATED_TIMEOUT_REACHED = 2,
+
+  /**
+   * We had to close the session since MHD was being
+   * shut down.
+   * @ingroup request
+   */
+  MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN = 3,
+
+  /**
+   * We tried to read additional data, but the other side closed the
+   * connection.  This error is similar to
+   * #MHD_REQUEST_TERMINATED_WITH_ERROR, but specific to the case where
+   * the connection died because the other side did not send expected
+   * data.
+   * @ingroup request
+   */
+  MHD_REQUEST_TERMINATED_READ_ERROR = 4,
+
+  /**
+   * The client terminated the connection by closing the socket
+   * for writing (TCP half-closed); MHD aborted sending the
+   * response according to RFC 2616, section 8.1.4.
+   * @ingroup request
+   */
+  MHD_REQUEST_TERMINATED_CLIENT_ABORT = 5
+
+};
+
+
+/**
+ * Signature of the callback used by MHD to notify the application
+ * about completed requests.
+ *
+ * @param cls client-defined closure
+ * @param toe reason for request termination
+ * @param request_context request context value, as originally
+ *         returned by the #MHD_EarlyUriLogCallback
+ * @see #MHD_option_request_completion()
+ * @ingroup request
+ */
+typedef void
+(*MHD_RequestTerminationCallback) (void *cls,
+                                   enum MHD_RequestTerminationCode toe,
+                                   void *request_context);
+
+
+/**
+ * Set a function to be called once MHD is finished with the
+ * request.
+ *
+ * @param response which response to set the callback for
+ * @param termination_cb function to call
+ * @param termination_cb_cls closure for @e termination_cb
+ */
+_MHD_EXTERN void
+MHD_response_option_termination_callback (struct MHD_Response *response,
+                                          MHD_RequestTerminationCallback
+                                          termination_cb,
+                                          void *termination_cb_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Callback used by libmicrohttpd in order to obtain content.  The
+ * callback is to copy at most @a max bytes of content into @a buf.  The
+ * total number of bytes that has been placed into @a buf should be
+ * returned.
+ *
+ * Note that returning zero will cause libmicrohttpd to try again.
+ * Thus, returning zero should only be used in conjunction
+ * with MHD_suspend_connection() to avoid busy waiting.
+ *
+ * @param cls extra argument to the callback
+ * @param pos position in the datastream to access;
+ *        note that if a `struct MHD_Response` object is re-used,
+ *        it is possible for the same content reader to
+ *        be queried multiple times for the same data;
+ *        however, if a `struct MHD_Response` is not re-used,
+ *        libmicrohttpd guarantees that "pos" will be
+ *        the sum of all non-negative return values
+ *        obtained from the content reader so far.
+ * @param buf where to copy the data
+ * @param max maximum number of bytes to copy to @a buf (size of @a buf)
+ * @return number of bytes written to @a buf;
+ *  0 is legal unless we are running in internal select mode (since
+ *    this would cause busy-waiting); 0 in external select mode
+ *    will cause this function to be called again once the external
+ *    select calls MHD again;
+ *  #MHD_CONTENT_READER_END_OF_STREAM (-1) for the regular
+ *    end of transmission (with chunked encoding, MHD will then
+ *    terminate the chunk and send any HTTP footers that might be
+ *    present; without chunked encoding and given an unknown
+ *    response size, MHD will simply close the connection; note
+ *    that while returning #MHD_CONTENT_READER_END_OF_STREAM is not technically
+ *    legal if a response size was specified, MHD accepts this
+ *    and treats it just as #MHD_CONTENT_READER_END_WITH_ERROR;
+ *  #MHD_CONTENT_READER_END_WITH_ERROR (-2) to indicate a server
+ *    error generating the response; this will cause MHD to simply
+ *    close the connection immediately.  If a response size was
+ *    given or if chunked encoding is in use, this will indicate
+ *    an error to the client.  Note, however, that if the client
+ *    does not know a response size and chunked encoding is not in
+ *    use, then clients will not be able to tell the difference between
+ *    #MHD_CONTENT_READER_END_WITH_ERROR and #MHD_CONTENT_READER_END_OF_STREAM.
+ *    This is not a limitation of MHD but rather of the HTTP protocol.
+ */
+typedef ssize_t
+(*MHD_ContentReaderCallback) (void *cls,
+                              uint64_t pos,
+                              char *buf,
+                              size_t max);
+
+
+/**
+ * This method is called by libmicrohttpd if we are done with a
+ * content reader.  It should be used to free resources associated
+ * with the content reader.
+ *
+ * @param cls closure
+ * @ingroup response
+ */
+typedef void
+(*MHD_ContentReaderFreeCallback) (void *cls);
+
+
+/**
+ * Create a response action.  The response object can be extended with
+ * header information and then be used any number of times.
+ *
+ * @param sc status code to return
+ * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown
+ * @param block_size preferred block size for querying crc (advisory only,
+ *                   MHD may still call @a crc using smaller chunks); this
+ *                   is essentially the buffer size used for IO, clients
+ *                   should pick a value that is appropriate for IO and
+ *                   memory performance requirements
+ * @param crc callback to use to obtain response data
+ * @param crc_cls extra argument to @a crc
+ * @param crfc callback to call to free @a crc_cls resources
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_response_from_callback (enum MHD_HTTP_StatusCode sc,
+                            uint64_t size,
+                            size_t block_size,
+                            MHD_ContentReaderCallback crc,
+                            void *crc_cls,
+                            MHD_ContentReaderFreeCallback crfc);
+
+
+/**
+ * Specification for how MHD should treat the memory buffer
+ * given for the response.
+ * @ingroup response
+ */
+enum MHD_ResponseMemoryMode
+{
+
+  /**
+   * Buffer is a persistent (static/global) buffer that won't change
+   * for at least the lifetime of the response, MHD should just use
+   * it, not free it, not copy it, just keep an alias to it.
+   * @ingroup response
+   */
+  MHD_RESPMEM_PERSISTENT,
+
+  /**
+   * Buffer is heap-allocated with `malloc()` (or equivalent) and
+   * should be freed by MHD after processing the response has
+   * concluded (response reference counter reaches zero).
+   * @ingroup response
+   */
+  MHD_RESPMEM_MUST_FREE,
+
+  /**
+   * Buffer is in transient memory, but not on the heap (for example,
+   * on the stack or non-`malloc()` allocated) and only valid during the
+   * call to #MHD_create_response_from_buffer.  MHD must make its
+   * own private copy of the data for processing.
+   * @ingroup response
+   */
+  MHD_RESPMEM_MUST_COPY
+
+};
+
+
+/**
+ * Create a response object.  The response object can be extended with
+ * header information and then be used any number of times.
+ *
+ * @param sc status code to use for the response;
+ *           #MHD_HTTP_NO_CONTENT is only valid if @a size is 0;
+ * @param size size of the data portion of the response
+ * @param buffer size bytes containing the response's data portion
+ * @param mode flags for buffer management
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_response_from_buffer (enum MHD_HTTP_StatusCode sc,
+                          size_t size,
+                          void *buffer,
+                          enum MHD_ResponseMemoryMode mode);
+
+
+/**
+ * Create a response object based on an @a fd from which
+ * data is read.  The response object can be extended with
+ * header information and then be used any number of times.
+ *
+ * @param sc status code to return
+ * @param fd file descriptor referring to a file on disk with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @param offset offset to start reading from in the file;
+ *        reading file beyond 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @param size size of the data portion of the response;
+ *        sizes larger than 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_response_from_fd (enum MHD_HTTP_StatusCode sc,
+                      int fd,
+                      uint64_t offset,
+                      uint64_t size);
+
+
+/**
+ * Enumeration for operations MHD should perform on the underlying socket
+ * of the upgrade.  This API is not finalized, and in particular
+ * the final set of actions is yet to be decided. This is just an
+ * idea for what we might want.
+ */
+enum MHD_UpgradeOperation
+{
+
+  /**
+   * Close the socket, the application is done with it.
+   *
+   * Takes no extra arguments.
+   */
+  MHD_UPGRADE_OPERATION_CLOSE = 0
+
+};
+
+
+/**
+ * Handle given to the application to manage special
+ * actions relating to MHD responses that "upgrade"
+ * the HTTP protocol (i.e. to WebSockets).
+ */
+struct MHD_UpgradeResponseHandle;
+
+
+/**
+ * This connection-specific callback is provided by MHD to
+ * applications (unusual) during the #MHD_UpgradeHandler.
+ * It allows applications to perform 'special' actions on
+ * the underlying socket from the upgrade.
+ *
+ * FIXME: this API still uses the untyped, ugly varargs.
+ * Should we not modernize this one as well?
+ *
+ * @param urh the handle identifying the connection to perform
+ *            the upgrade @a action on.
+ * @param operation which operation should be performed
+ * @param ... arguments to the action (depends on the action)
+ * @return #MHD_NO on error, #MHD_YES on success
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_upgrade_operation (struct MHD_UpgradeResponseHandle *urh,
+                       enum MHD_UpgradeOperation operation,
+                       ...)
+MHD_NONNULL (1);
+
+
+/**
+ * Function called after a protocol "upgrade" response was sent
+ * successfully and the socket should now be controlled by some
+ * protocol other than HTTP.
+ *
+ * Any data already received on the socket will be made available in
+ * @e extra_in.  This can happen if the application sent extra data
+ * before MHD send the upgrade response.  The application should
+ * treat data from @a extra_in as if it had read it from the socket.
+ *
+ * Note that the application must not close() @a sock directly,
+ * but instead use #MHD_upgrade_action() for special operations
+ * on @a sock.
+ *
+ * Data forwarding to "upgraded" @a sock will be started as soon
+ * as this function return.
+ *
+ * Except when in 'thread-per-connection' mode, implementations
+ * of this function should never block (as it will still be called
+ * from within the main event loop).
+ *
+ * @param cls closure, whatever was given to #MHD_response_create_for_upgrade().
+ * @param connection original HTTP connection handle,
+ *                   giving the function a last chance
+ *                   to inspect the original HTTP request
+ * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback`
+ * @param extra_in if we happened to have read bytes after the
+ *                 HTTP header already (because the client sent
+ *                 more than the HTTP header of the request before
+ *                 we sent the upgrade response),
+ *                 these are the extra bytes already read from @a sock
+ *                 by MHD.  The application should treat these as if
+ *                 it had read them from @a sock.
+ * @param extra_in_size number of bytes in @a extra_in
+ * @param sock socket to use for bi-directional communication
+ *        with the client.  For HTTPS, this may not be a socket
+ *        that is directly connected to the client and thus certain
+ *        operations (TCP-specific setsockopt(), getsockopt(), etc.)
+ *        may not work as expected (as the socket could be from a
+ *        socketpair() or a TCP-loopback).  The application is expected
+ *        to perform read()/recv() and write()/send() calls on the socket.
+ *        The application may also call shutdown(), but must not call
+ *        close() directly.
+ * @param urh argument for #MHD_upgrade_action()s on this @a connection.
+ *        Applications must eventually use this callback to (indirectly)
+ *        perform the close() action on the @a sock.
+ */
+typedef void
+(*MHD_UpgradeHandler)(void *cls,
+                      struct MHD_Connection *connection,
+                      void *req_cls,
+                      const char *extra_in,
+                      size_t extra_in_size,
+                      MHD_socket sock,
+                      struct MHD_UpgradeResponseHandle *urh);
+
+
+/**
+ * Create a response object that can be used for 101 UPGRADE
+ * responses, for example to implement WebSockets.  After sending the
+ * response, control over the data stream is given to the callback (which
+ * can then, for example, start some bi-directional communication).
+ * If the response is queued for multiple connections, the callback
+ * will be called for each connection.  The callback
+ * will ONLY be called after the response header was successfully passed
+ * to the OS; if there are communication errors before, the usual MHD
+ * connection error handling code will be performed.
+ *
+ * MHD will automatically set the correct HTTP status
+ * code (#MHD_HTTP_SWITCHING_PROTOCOLS).
+ * Setting correct HTTP headers for the upgrade must be done
+ * manually (this way, it is possible to implement most existing
+ * WebSocket versions using this API; in fact, this API might be useful
+ * for any protocol switch, not just WebSockets).  Note that
+ * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this
+ * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake"
+ * cannot be generated; instead, MHD will always produce "HTTP/1.1 101
+ * Switching Protocols" (if the response code 101 is used).
+ *
+ * As usual, the response object can be extended with header
+ * information and then be used any number of times (as long as the
+ * header information is not connection-specific).
+ *
+ * @param upgrade_handler function to call with the "upgraded" socket
+ * @param upgrade_handler_cls closure for @a upgrade_handler
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_response_for_upgrade (MHD_UpgradeHandler upgrade_handler,
+                          void *upgrade_handler_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Explicitly decrease reference counter of a response object.  If the
+ * counter hits zero, destroys a response object and associated
+ * resources.  Usually, this is implicitly done by converting a
+ * response to an action and returning the action to MHD.
+ *
+ * @param response response to decrement RC of
+ * @ingroup response
+ */
+_MHD_EXTERN void
+MHD_response_queue_for_destroy (struct MHD_Response *response)
+MHD_NONNULL (1);
+
+
+/**
+ * Add a header line to the response.
+ *
+ * @param response response to add a header to
+ * @param header the header to add
+ * @param content value to add
+ * @return #MHD_NO on error (i.e. invalid header or content format),
+ *         or out of memory
+ * @ingroup response
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_response_add_header (struct MHD_Response *response,
+                         const char *header,
+                         const char *content)
+MHD_NONNULL (1,2,3);
+
+
+/**
+ * Add a tailer line to the response.
+ *
+ * @param response response to add a footer to
+ * @param footer the footer to add
+ * @param content value to add
+ * @return #MHD_NO on error (i.e. invalid footer or content format),
+ *         or out of memory
+ * @ingroup response
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_response_add_trailer (struct MHD_Response *response,
+                          const char *footer,
+                          const char *content)
+MHD_NONNULL (1,2,3);
+
+
+/**
+ * Delete a header (or footer) line from the response.
+ *
+ * @param response response to remove a header from
+ * @param header the header to delete
+ * @param content value to delete
+ * @return #MHD_NO on error (no such header known)
+ * @ingroup response
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_response_del_header (struct MHD_Response *response,
+                         const char *header,
+                         const char *content)
+MHD_NONNULL (1,2,3);
+
+
+/**
+ * Get all of the headers (and footers) added to a response.
+ *
+ * @param response response to query
+ * @param iterator callback to call on each header;
+ *        maybe NULL (then just count headers)
+ * @param iterator_cls extra argument to @a iterator
+ * @return number of entries iterated over
+ * @ingroup response
+ */
+_MHD_EXTERN unsigned int
+MHD_response_get_headers (struct MHD_Response *response,
+                          MHD_KeyValueIterator iterator,
+                          void *iterator_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Get a particular header (or footer) from the response.
+ *
+ * @param response response to query
+ * @param key which header to get
+ * @return NULL if header does not exist
+ * @ingroup response
+ */
+_MHD_EXTERN const char *
+MHD_response_get_header (struct MHD_Response *response,
+                         const char *key)
+MHD_NONNULL (1,2);
+
+
+/* ************Upload and PostProcessor functions ********************** */
+
+
+/**
+ * Action telling MHD to continue processing the upload.
+ *
+ * @return action operation, never NULL
+ */
+_MHD_EXTERN const struct MHD_Action *
+MHD_action_continue (void);
+
+
+/**
+ * Function to process data uploaded by a client.
+ *
+ * @param cls argument given together with the function
+ *        pointer when the handler was registered with MHD
+ * @param upload_data the data being uploaded (excluding headers)
+ *        POST data will typically be made available incrementally via
+ *        multiple callbacks
+ * @param[in,out] upload_data_size set initially to the size of the
+ *        @a upload_data provided; the method must update this
+ *        value to the number of bytes NOT processed;
+ * @return action specifying how to proceed, often
+ *         #MHD_action_continue() if all is well,
+ *         #MHD_action_suspend() to stop reading the upload until
+ *              the request is resumed,
+ *         NULL to close the socket, or a response
+ *         to discard the rest of the upload and return the data given
+ */
+typedef const struct MHD_Action *
+(*MHD_UploadCallback) (void *cls,
+                       const char *upload_data,
+                       size_t *upload_data_size);
+
+
+/**
+ * Create an action that handles an upload.
+ *
+ * @param uc function to call with uploaded data
+ * @param uc_cls closure for @a uc
+ * @return NULL on error (out of memory)
+ * @ingroup action
+ */
+_MHD_EXTERN const struct MHD_Action *
+MHD_action_process_upload (MHD_UploadCallback uc,
+                           void *uc_cls)
+MHD_NONNULL (1);
+
+
+/**
+ * Iterator over key-value pairs where the value maybe made available
+ * in increments and/or may not be zero-terminated.  Used for
+ * MHD parsing POST data.  To access "raw" data from POST or PUT
+ * requests, use #MHD_action_process_upload() instead.
+ *
+ * @param cls user-specified closure
+ * @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD
+ * @param key 0-terminated key for the value
+ * @param filename name of the uploaded file, NULL if not known
+ * @param content_type mime-type of the data, NULL if not known
+ * @param transfer_encoding encoding of the data, NULL if not known
+ * @param data pointer to @a size bytes of data at the
+ *              specified offset
+ * @param off offset of data in the overall value
+ * @param size number of bytes in @a data available
+ * @return action specifying how to proceed, often
+ *         #MHD_action_continue() if all is well,
+ *         #MHD_action_suspend() to stop reading the upload until
+ *              the request is resumed,
+ *         NULL to close the socket, or a response
+ *         to discard the rest of the upload and return the data given
+ */
+typedef const struct MHD_Action *
+(*MHD_PostDataIterator) (void *cls,
+                         enum MHD_ValueKind kind,
+                         const char *key,
+                         const char *filename,
+                         const char *content_type,
+                         const char *transfer_encoding,
+                         const char *data,
+                         uint64_t off,
+                         size_t size);
+
+
+/**
+ * Create an action that parses a POST request.
+ *
+ * This action can be used to (incrementally) parse the data portion
+ * of a POST request.  Note that some buggy browsers fail to set the
+ * encoding type.  If you want to support those, you may have to call
+ * #MHD_set_connection_value with the proper encoding type before
+ * returning this action (if no supported encoding type is detected,
+ * returning this action will cause a bad request to be returned to
+ * the client).
+ *
+ * @param buffer_size maximum number of bytes to use for
+ *        internal buffering (used only for the parsing,
+ *        specifically the parsing of the keys).  A
+ *        tiny value (256-1024) should be sufficient.
+ *        Do NOT use a value smaller than 256.  For good
+ *        performance, use 32 or 64k (i.e. 65536).
+ * @param iter iterator to be called with the parsed data,
+ *        Must NOT be NULL.
+ * @param iter_cls first argument to @a iter
+ * @return NULL on error (out of memory, unsupported encoding),
+ *         otherwise a PP handle
+ * @ingroup request
+ */
+_MHD_EXTERN const struct MHD_Action *
+MHD_action_parse_post (size_t buffer_size,
+                       MHD_PostDataIterator iter,
+                       void *iter_cls)
+MHD_NONNULL (2);
+
+
+/* ********************** generic query functions ********************** */
+
+
+/**
+ * Select which member of the `struct ConnectionInformation`
+ * union is desired to be returned by #MHD_connection_get_info().
+ */
+enum MHD_ConnectionInformationType
+{
+  /**
+   * What cipher algorithm is being used.
+   * Takes no extra arguments.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_CIPHER_ALGO,
+
+  /**
+   *
+   * Takes no extra arguments.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_PROTOCOL,
+
+  /**
+   * Obtain IP address of the client.  Takes no extra arguments.
+   * Returns essentially a `struct sockaddr **` (since the API returns
+   * a `union MHD_ConnectionInfo *` and that union contains a `struct
+   * sockaddr *`).
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_CLIENT_ADDRESS,
+
+  /**
+   * Get the gnuTLS session handle.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_GNUTLS_SESSION,
+
+  /**
+   * Get the gnuTLS client certificate handle.  Dysfunctional (never
+   * implemented, deprecated).  Use #MHD_CONNECTION_INFORMATION_GNUTLS_SESSION
+   * to get the `gnutls_session_t` and then call
+   * gnutls_certificate_get_peers().
+   */
+  MHD_CONNECTION_INFORMATION_GNUTLS_CLIENT_CERT,
+
+  /**
+   * Get the `struct MHD_Daemon *` responsible for managing this connection.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_DAEMON,
+
+  /**
+   * Request the file descriptor for the connection socket.
+   * No extra arguments should be passed.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_CONNECTION_FD,
+
+  /**
+   * Returns the client-specific pointer to a `void *` that was (possibly)
+   * set during a #MHD_NotifyConnectionCallback when the socket was
+   * first accepted.  Note that this is NOT the same as the "req_cls"
+   * argument of the #MHD_AccessHandlerCallback.  The "req_cls" is
+   * fresh for each HTTP request, while the "socket_context" is fresh
+   * for each socket.
+   */
+  MHD_CONNECTION_INFORMATION_SOCKET_CONTEXT,
+
+  /**
+   * Get connection timeout
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_CONNECTION_TIMEOUT,
+
+  /**
+   * Check whether the connection is suspended.
+   * @ingroup request
+   */
+  MHD_CONNECTION_INFORMATION_CONNECTION_SUSPENDED
+
+
+};
+
+
+/**
+ * Information about a connection.
+ */
+union MHD_ConnectionInformation
+{
+
+  /**
+   * Cipher algorithm used, of type "enum gnutls_cipher_algorithm".
+   */
+  int /* enum gnutls_cipher_algorithm */ cipher_algorithm;
+
+  /**
+   * Protocol used, of type "enum gnutls_protocol".
+   */
+  int /* enum gnutls_protocol */ protocol;
+
+  /**
+   * Amount of second that connection could spend in idle state
+   * before automatically disconnected.
+   * Zero for no timeout (unlimited idle time).
+   */
+  unsigned int connection_timeout;
+
+  /**
+   * Connect socket
+   */
+  MHD_socket connect_fd;
+
+  /**
+   * GNUtls session handle, of type "gnutls_session_t".
+   */
+  void * /* gnutls_session_t */ tls_session;
+
+  /**
+   * GNUtls client certificate handle, of type "gnutls_x509_crt_t".
+   */
+  void * /* gnutls_x509_crt_t */ client_cert;
+
+  /**
+   * Address information for the client.
+   */
+  const struct sockaddr *client_addr;
+
+  /**
+   * Which daemon manages this connection (useful in case there are many
+   * daemons running).
+   */
+  struct MHD_Daemon *daemon;
+
+  /**
+   * Pointer to connection-specific client context.  Points to the
+   * same address as the "socket_context" of the
+   * #MHD_NotifyConnectionCallback.
+   */
+  void **socket_context;
+
+  /**
+   * Is this connection right now suspended?
+   */
+  enum MHD_Bool suspended;
+};
+
+
+/**
+ * Obtain information about the given connection.
+ * Use wrapper macro #MHD_connection_get_information() instead of direct use
+ * of this function.
+ *
+ * @param connection what connection to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @param return_value_size size of union MHD_ConnectionInformation at compile
+ *                          time
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_connection_get_information_sz (struct MHD_Connection *connection,
+                                   enum MHD_ConnectionInformationType info_type,
+                                   union MHD_ConnectionInformation *return_value,
+                                   size_t return_value_size)
+MHD_NONNULL (1,3);
+
+
+/**
+ * Obtain information about the given connection.
+ *
+ * @param connection what connection to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+#define MHD_connection_get_information(connection,   \
+                                       info_type,    \
+                                       return_value) \
+  MHD_connection_get_information_sz ((connection),(info_type),(return_value), \
+                                     sizeof(union MHD_ConnectionInformation))
+
+
+/**
+ * Information we return about a request.
+ */
+union MHD_RequestInformation
+{
+
+  /**
+   * Connection via which we received the request.
+   */
+  struct MHD_Connection *connection;
+
+  /**
+   * Pointer to client context.  Will also be given to
+   * the application in a #MHD_RequestTerminationCallback.
+   */
+  void **request_context;
+
+  /**
+   * HTTP version requested by the client.
+   */
+  const char *http_version;
+
+  /**
+   * HTTP method of the request, as a string.  Particularly useful if
+   * #MHD_HTTP_METHOD_UNKNOWN was given.
+   */
+  const char *http_method;
+
+  /**
+   * Size of the client's HTTP header.
+   */
+  size_t header_size;
+
+};
+
+
+/**
+ * Select which member of the `struct RequestInformation`
+ * union is desired to be returned by #MHD_request_get_info().
+ */
+enum MHD_RequestInformationType
+{
+  /**
+   * Return which connection the request is associated with.
+   */
+  MHD_REQUEST_INFORMATION_CONNECTION,
+
+  /**
+   * Returns the client-specific pointer to a `void *` that
+   * is specific to this request.
+   */
+  MHD_REQUEST_INFORMATION_CLIENT_CONTEXT,
+
+  /**
+   * Return the HTTP version string given by the client.
+   * @ingroup request
+   */
+  MHD_REQUEST_INFORMATION_HTTP_VERSION,
+
+  /**
+   * Return the HTTP method used by the request.
+   * @ingroup request
+   */
+  MHD_REQUEST_INFORMATION_HTTP_METHOD,
+
+  /**
+   * Return length of the client's HTTP request header.
+   * @ingroup request
+   */
+  MHD_REQUEST_INFORMATION_HEADER_SIZE
+};
+
+
+/**
+ * Obtain information about the given request.
+ * Use wrapper macro #MHD_request_get_information() instead of direct use
+ * of this function.
+ *
+ * @param request what request to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @param return_value_size size of union MHD_RequestInformation at compile
+ *                          time
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_request_get_information_sz (struct MHD_Request *request,
+                                enum MHD_RequestInformationType info_type,
+                                union MHD_RequestInformation *return_value,
+                                size_t return_value_size)
+MHD_NONNULL (1,3);
+
+
+/**
+ * Obtain information about the given request.
+ *
+ * @param request what request to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+#define MHD_request_get_information (request,      \
+                                     info_type,    \
+                                     return_value) \
+  MHD_request_get_information_sz ((request), (info_type), (return_value), \
+                                  sizeof(union MHD_RequestInformation))
+
+
+/**
+ * Values of this enum are used to specify what
+ * information about a daemon is desired.
+ */
+enum MHD_DaemonInformationType
+{
+
+  /**
+   * Request the file descriptor for the listening socket.
+   * No extra arguments should be passed.
+   */
+  MHD_DAEMON_INFORMATION_LISTEN_SOCKET,
+
+  /**
+   * Request the file descriptor for the external epoll.
+   * No extra arguments should be passed.
+   */
+  MHD_DAEMON_INFORMATION_EPOLL_FD,
+
+  /**
+   * Request the number of current connections handled by the daemon.
+   * No extra arguments should be passed.
+   * Note: when using MHD in external polling mode, this type of request
+   * could be used only when #MHD_run()/#MHD_run_from_select is not
+   * working in other thread at the same time.
+   */
+  MHD_DAEMON_INFORMATION_CURRENT_CONNECTIONS,
+
+  /**
+   * Request the port number of daemon's listen socket.
+   * No extra arguments should be passed.
+   * Note: if port '0' was specified for #MHD_option_port(), returned
+   * value will be real port number.
+   */
+  MHD_DAEMON_INFORMATION_BIND_PORT
+};
+
+
+/**
+ * Information about an MHD daemon.
+ */
+union MHD_DaemonInformation
+{
+
+  /**
+   * Socket, returned for #MHD_DAEMON_INFORMATION_LISTEN_SOCKET.
+   */
+  MHD_socket listen_socket;
+
+  /**
+   * Bind port number, returned for #MHD_DAEMON_INFORMATION_BIND_PORT.
+   */
+  uint16_t port;
+
+  /**
+   * epoll FD, returned for #MHD_DAEMON_INFORMATION_EPOLL_FD.
+   */
+  int epoll_fd;
+
+  /**
+   * Number of active connections, for #MHD_DAEMON_INFORMATION_CURRENT_CONNECTIONS.
+   */
+  unsigned int num_connections;
+
+};
+
+
+/**
+ * Obtain information about the given daemon.
+ * Use wrapper macro #MHD_daemon_get_information() instead of direct use
+ * of this function.
+ *
+ * @param daemon what daemon to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @param return_value_size size of union MHD_DaemonInformation at compile
+ *                          time
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_daemon_get_information_sz (struct MHD_Daemon *daemon,
+                               enum MHD_DaemonInformationType info_type,
+                               union MHD_DaemonInformation *return_value,
+                               size_t return_value_size)
+MHD_NONNULL (1,3);
+
+/**
+ * Obtain information about the given daemon.
+ *
+ * @param daemon what daemon to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+#define MHD_daemon_get_information(daemon,       \
+                                   info_type,    \
+                                   return_value) \
+  MHD_daemon_get_information_sz ((daemon), (info_type), (return_value), \
+                                 sizeof(union MHD_DaemonInformation));
+
+
+/**
+ * Callback for serious error condition. The default action is to print
+ * an error message and `abort()`.
+ *
+ * @param cls user specified value
+ * @param file where the error occurred
+ * @param line where the error occurred
+ * @param reason error detail, may be NULL
+ * @ingroup logging
+ */
+typedef void
+(*MHD_PanicCallback) (void *cls,
+                      const char *file,
+                      unsigned int line,
+                      const char *reason);
+
+
+/**
+ * Sets the global error handler to a different implementation.  @a cb
+ * will only be called in the case of typically fatal, serious
+ * internal consistency issues.  These issues should only arise in the
+ * case of serious memory corruption or similar problems with the
+ * architecture.  While @a cb is allowed to return and MHD will then
+ * try to continue, this is never safe.
+ *
+ * The default implementation that is used if no panic function is set
+ * simply prints an error message and calls `abort()`.  Alternative
+ * implementations might call `exit()` or other similar functions.
+ *
+ * @param cb new error handler
+ * @param cls passed to @a cb
+ * @ingroup logging
+ */
+_MHD_EXTERN void
+MHD_set_panic_func (MHD_PanicCallback cb,
+                    void *cls);
+
+
+/**
+ * Process escape sequences ('%HH') Updates val in place; the
+ * result should be UTF-8 encoded and cannot be larger than the input.
+ * The result must also still be 0-terminated.
+ *
+ * @param val value to unescape (modified in the process)
+ * @return length of the resulting val (`strlen(val)` may be
+ *  shorter afterwards due to elimination of escape sequences)
+ */
+_MHD_EXTERN size_t
+MHD_http_unescape (char *val)
+MHD_NONNULL (1);
+
+
+/**
+ * Types of information about MHD features,
+ * used by #MHD_is_feature_supported().
+ */
+enum MHD_Feature
+{
+  /**
+   * Get whether messages are supported. If supported then in debug
+   * mode messages can be printed to stderr or to external logger.
+   */
+  MHD_FEATURE_MESSAGES = 1,
+
+  /**
+   * Get whether HTTPS is supported.  If supported then flag
+   * #MHD_USE_TLS and options #MHD_OPTION_HTTPS_MEM_KEY,
+   * #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST,
+   * #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_CRED_TYPE,
+   * #MHD_OPTION_HTTPS_PRIORITIES can be used.
+   */
+  MHD_FEATURE_TLS = 2,
+
+  /**
+   * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is
+   * supported.
+   */
+  MHD_FEATURE_HTTPS_CERT_CALLBACK = 3,
+
+  /**
+   * Get whether IPv6 is supported. If supported then flag
+   * #MHD_USE_IPv6 can be used.
+   */
+  MHD_FEATURE_IPv6 = 4,
+
+  /**
+   * Get whether IPv6 without IPv4 is supported. If not supported
+   * then IPv4 is always enabled in IPv6 sockets and
+   * flag #MHD_USE_DUAL_STACK if always used when #MHD_USE_IPv6 is
+   * specified.
+   */
+  MHD_FEATURE_IPv6_ONLY = 5,
+
+  /**
+   * Get whether `poll()` is supported. If supported then flag
+   * #MHD_USE_POLL can be used.
+   */
+  MHD_FEATURE_POLL = 6,
+
+  /**
+   * Get whether `epoll()` is supported. If supported then Flags
+   * #MHD_USE_EPOLL and
+   * #MHD_USE_EPOLL_INTERNAL_THREAD can be used.
+   */
+  MHD_FEATURE_EPOLL = 7,
+
+  /**
+   * Get whether shutdown on listen socket to signal other
+   * threads is supported. If not supported flag
+   * #MHD_USE_ITC is automatically forced.
+   */
+  MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET = 8,
+
+  /**
+   * Get whether socketpair is used internally instead of pipe to
+   * signal other threads.
+   */
+  MHD_FEATURE_SOCKETPAIR = 9,
+
+  /**
+   * Get whether TCP Fast Open is supported. If supported then
+   * flag #MHD_USE_TCP_FASTOPEN and option
+   * #MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used.
+   */
+  MHD_FEATURE_TCP_FASTOPEN = 10,
+
+  /**
+   * Get whether HTTP Basic authorization is supported. If supported
+   * then functions #MHD_basic_auth_get_username_password and
+   * #MHD_queue_basic_auth_fail_response can be used.
+   */
+  MHD_FEATURE_BASIC_AUTH = 11,
+
+  /**
+   * Get whether HTTP Digest authorization is supported. If
+   * supported then options #MHD_OPTION_DIGEST_AUTH_RANDOM,
+   * #MHD_OPTION_NONCE_NC_SIZE and
+   * #MHD_digest_auth_check() can be used.
+   */
+  MHD_FEATURE_DIGEST_AUTH = 12,
+
+  /**
+   * Get whether postprocessor is supported. If supported then
+   * functions #MHD_create_post_processor(), #MHD_post_process() and
+   * #MHD_destroy_post_processor() can
+   * be used.
+   */
+  MHD_FEATURE_POSTPROCESSOR = 13,
+
+  /**
+  * Get whether password encrypted private key for HTTPS daemon is
+  * supported. If supported then option
+  * ::MHD_OPTION_HTTPS_KEY_PASSWORD can be used.
+  */
+  MHD_FEATURE_HTTPS_KEY_PASSWORD = 14,
+
+  /**
+   * Get whether reading files beyond 2 GiB boundary is supported.
+   * If supported then #MHD_create_response_from_fd(),
+   * #MHD_create_response_from_fd64 #MHD_create_response_from_fd_at_offset()
+   * and #MHD_create_response_from_fd_at_offset64() can be used with sizes and
+   * offsets larger than 2 GiB. If not supported value of size+offset is
+   * limited to 2 GiB.
+   */
+  MHD_FEATURE_LARGE_FILE = 15,
+
+  /**
+   * Get whether MHD set names on generated threads.
+   */
+  MHD_FEATURE_THREAD_NAMES = 16,
+
+  /**
+   * Get whether HTTP "Upgrade" is supported.
+   * If supported then #MHD_ALLOW_UPGRADE, #MHD_upgrade_action() and
+   * #MHD_create_response_for_upgrade() can be used.
+   */
+  MHD_FEATURE_UPGRADE = 17,
+
+  /**
+   * Get whether it's safe to use same FD for multiple calls of
+   * #MHD_create_response_from_fd() and whether it's safe to use single
+   * response generated by #MHD_create_response_from_fd() with multiple
+   * connections at same time.
+   * If #MHD_is_feature_supported() return #MHD_NO for this feature then
+   * usage of responses with same file FD in multiple parallel threads may
+   * results in incorrect data sent to remote client.
+   * It's always safe to use same file FD in multiple responses if MHD
+   * is run in any single thread mode.
+   */
+  MHD_FEATURE_RESPONSES_SHARED_FD = 18,
+
+  /**
+   * Get whether MHD support automatic detection of bind port number.
+   * @sa #MHD_DAEMON_INFO_BIND_PORT
+   */
+  MHD_FEATURE_AUTODETECT_BIND_PORT = 19,
+
+  /**
+   * Get whether MHD support SIGPIPE suppression.
+   * If SIGPIPE suppression is not supported, application must handle
+   * SIGPIPE signal by itself.
+   */
+  MHD_FEATURE_AUTOSUPPRESS_SIGPIPE = 20,
+
+  /**
+   * Get whether MHD use system's sendfile() function to send
+   * file-FD based responses over non-TLS connections.
+   * @note Since v0.9.56
+   */
+  MHD_FEATURE_SENDFILE = 21
+};
+
+
+/**
+ * Get information about supported MHD features.
+ * Indicate that MHD was compiled with or without support for
+ * particular feature. Some features require additional support
+ * by kernel. Kernel support is not checked by this function.
+ *
+ * @param feature type of requested information
+ * @return #MHD_YES if feature is supported by MHD, #MHD_NO if
+ * feature is not supported or feature is unknown.
+ * @ingroup specialized
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_is_feature_supported (enum MHD_Feature feature);
+
+
+/**
+ * What is this request waiting for?
+ */
+enum MHD_RequestEventLoopInfo
+{
+  /**
+   * We are waiting to be able to read.
+   */
+  MHD_EVENT_LOOP_INFO_READ = 0,
+
+  /**
+   * We are waiting to be able to write.
+   */
+  MHD_EVENT_LOOP_INFO_WRITE = 1,
+
+  /**
+   * We are waiting for the application to provide data.
+   */
+  MHD_EVENT_LOOP_INFO_BLOCK = 2,
+
+  /**
+   * We are finished and are awaiting cleanup.
+   */
+  MHD_EVENT_LOOP_INFO_CLEANUP = 3
+};
+
+
+#endif
diff --git a/src/include/microhttpd_tls.h b/src/include/microhttpd_tls.h
new file mode 100644
index 0000000..2834f33
--- /dev/null
+++ b/src/include/microhttpd_tls.h
@@ -0,0 +1,196 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2018 Christian Grothoff (and other contributing authors)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd_tls.h
+ * @brief interface for TLS plugins of libmicrohttpd
+ * @author Christian Grothoff
+ */
+
+#ifndef MICROHTTPD_TLS_H
+#define MICROHTTPD_TLS_H
+
+#include <microhttpd2.h>
+
+/**
+ * Version of the TLS ABI.
+ */
+#define MHD_TLS_ABI_VERSION 0
+
+/**
+ * Version of the TLS ABI as a string.
+ * Must match #MHD_TLS_ABI_VERSION!
+ */
+#define MHD_TLS_ABI_VERSION_STR "0"
+
+
+/**
+ * Data structure kept per TLS client by the plugin.
+ */
+struct MHD_TLS_ConnectionState;
+
+
+/**
+ * Callback functions to use for TLS operations.
+ */
+struct MHD_TLS_Plugin
+{
+  /**
+   * Closure with plugin's internal state, opaque to MHD.
+   */
+  void *cls;
+
+  /**
+   * Destroy the plugin, we are done with it.
+   */
+  void
+  (*done)(struct MHD_TLS_Plugin *plugin);
+
+  /**
+   * Initialize key and certificate data from memory.
+   *
+   * @param cls the @e cls of this struct
+   * @param mem_key private key (key.pem) to be used by the
+   *     HTTPS daemon.  Must be the actual data in-memory, not a filename.
+   * @param mem_cert certificate (cert.pem) to be used by the
+   *     HTTPS daemon.  Must be the actual data in-memory, not a filename.
+   * @param pass passphrase phrase to decrypt 'key.pem', NULL
+   *     if @param mem_key is in cleartext already
+   * @return #MHD_SC_OK upon success; TODO: define failure modes
+   */
+  enum MHD_StatusCode
+  (*init_kcp)(void *cls,
+              const char *mem_key,
+              const char *mem_cert,
+              const char *pass);
+
+
+  /**
+   * Initialize DH parameters.
+   *
+   * @param cls the @e cls of this struct
+   * @param dh parameters to use
+   * @return #MHD_SC_OK upon success; TODO: define failure modes
+   */
+  enum MHD_StatusCode
+  (*init_dhparams)(void *cls,
+                   const char *dh);
+
+
+  /**
+   * Initialize certificate to use for client authentication.
+   *
+   * @param cls the @e cls of this struct
+   * @param mem_trust client certificate
+   * @return #MHD_SC_OK upon success; TODO: define failure modes
+   */
+  enum MHD_StatusCode
+  (*init_mem_trust)(void *cls,
+                    const char *mem_trust);
+
+
+  /**
+   * Function called when we receive a connection and need
+   * to initialize our TLS state for it.
+   *
+   * @param cls the @e cls of this struct
+   * @param ... TBD
+   * @return NULL on error
+   */
+  struct MHD_TLS_ConnectionState *
+  (*setup_connection)(void *cls,
+                      ...);
+
+
+  enum MHD_Bool
+  (*handshake)(void *cls,
+               struct MHD_TLS_ConnectionState *cs);
+
+
+  enum MHD_Bool
+  (*idle_ready)(void *cls,
+                struct MHD_TLS_ConnectionState *cs);
+
+
+  enum MHD_Bool
+  (*update_event_loop_info)(void *cls,
+                            struct MHD_TLS_ConnectionState *cs,
+                            enum MHD_RequestEventLoopInfo *eli);
+
+  ssize_t
+  (*send)(void *cls,
+          struct MHD_TLS_ConnectionState *cs,
+          const void *buf,
+          size_t buf_size);
+
+
+  ssize_t
+  (*recv)(void *cls,
+          struct MHD_TLS_ConnectionState *cs,
+          void *buf,
+          size_t buf_size);
+
+
+  const char *
+  (*strerror)(void *cls,
+              int ec);
+
+  enum MHD_Bool
+  (*check_record_pending)(void *cls,
+                          struct MHD_TLS_ConnectionState *cs);
+
+  enum MHD_Bool
+  (*shutdown_connection)(void *cls,
+                         struct MHD_TLS_ConnectionState *cs);
+
+
+  void
+  (*teardown_connection)(void *cls,
+                         struct MHD_TLS_ConnectionState *cs);
+
+  /**
+   * TODO: More functions here....
+   */
+
+};
+
+
+/**
+ * Signature of the initialization function each TLS plugin must
+ * export.
+ *
+ * @param ciphers desired cipher suite
+ * @return NULL on errors (in particular, invalid cipher suite)
+ */
+typedef struct MHD_TLS_Plugin *
+(*MHD_TLS_PluginInit) (const char *ciphers);
+
+
+/**
+ * Define function to be exported from the TLS plugin.
+ *
+ * @a body function body that receives `ciphers` argument
+ *    and must return the plugin API, or NULL on error.
+ */
+#define MHD_TLS_INIT(body) \
+  struct MHD_TLS_Plugin * \
+    MHD_TLS_init_ ## MHD_TLS_ABI_VERSION (const char *ciphers) \ \
+  {  body  }
+
+#endif
diff --git a/src/include/microhttpd_ws.h b/src/include/microhttpd_ws.h
new file mode 100644
index 0000000..a132238
--- /dev/null
+++ b/src/include/microhttpd_ws.h
@@ -0,0 +1,1124 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021 Christian Grothoff (and other contributing authors)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file microhttpd_ws.h
+ * @brief interface for experimental web socket extension to libmicrohttpd
+ * @author David Gausmann
+ */
+/*
+ *                            *** WARNING! ***
+ * *   The websockets interface is currently in "experimental" stage.   *
+ * * It does not work on architectures with endianness different from  *
+ * * big endian and little endian and may have some portability issues.*
+ * * API and ABI are not yet stable.                                   *
+ */
+#ifndef MHD_MICROHTTPD_WS_H
+#define MHD_MICROHTTPD_WS_H
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#if 0                           /* keep Emacsens' auto-indent happy */
+}
+#endif
+#endif
+
+
+/**
+ * @brief Handle for the encoding/decoding of websocket data
+ *        (one stream is used per websocket)
+ * @ingroup websocket
+ */
+struct MHD_WebSocketStream;
+
+/**
+ * @brief Flags for the initialization of a websocket stream
+ *        `struct MHD_WebSocketStream` used by
+ *        #MHD_websocket_stream_init() or
+ *        #MHD_websocket_stream_init2().
+ * @ingroup websocket
+ */
+enum MHD_WEBSOCKET_FLAG
+{
+  /**
+   * The websocket stream is initialized in server mode (default).
+   * Thus all outgoing payload will not be "masked".
+   * All incoming payload must be masked.
+   * This flag cannot be used together with #MHD_WEBSOCKET_FLAG_CLIENT
+   */
+  MHD_WEBSOCKET_FLAG_SERVER = 0,
+  /**
+   * The websocket stream is initialized in client mode.
+   * You will usually never use that mode in combination with libmicrohttpd,
+   * because libmicrohttpd provides a server and not a client.
+   * In client mode all outgoing payload will be "masked"
+   * (XOR-ed with random values).
+   * All incoming payload must be unmasked.
+   * If you use this mode, you must always call #MHD_websocket_stream_init2()
+   * instead of #MHD_websocket_stream_init(), because you need
+   * to pass a random number generator callback function for masking.
+   * This flag cannot be used together with #MHD_WEBSOCKET_FLAG_SERVER
+   */
+  MHD_WEBSOCKET_FLAG_CLIENT = 1,
+  /**
+   * You don't want to get fragmented data while decoding (default).
+   * Fragmented frames will be internally put together until
+   * they are complete.
+   * Whether or not data is fragmented is decided
+   * by the sender of the data during encoding.
+   * This cannot be used together with #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+   */
+  MHD_WEBSOCKET_FLAG_NO_FRAGMENTS = 0,
+  /**
+   * You want fragmented data, if it appears while decoding.
+   * You will receive the content of the fragmented frame,
+   * but if you are decoding text, you will never get an unfinished
+   * UTF-8 sequence (if the sequence appears between two fragments).
+   * Instead the text will end before the unfinished UTF-8 sequence.
+   * With the next fragment, which finishes the UTF-8 sequence,
+   * you will get the complete UTF-8 sequence.
+   * This cannot be used together with #MHD_WEBSOCKET_FLAG_NO_FRAGMENTS
+   */
+  MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS = 2,
+  /**
+   * If the websocket stream becomes invalid during decoding due to
+   * protocol errors, a matching close frame will automatically
+   * be generated.
+   * The close frame will be returned via the parameters
+   * `payload` and `payload_len` of #MHD_websocket_decode() and
+   * the return value is negative
+   * (a value of `enum MHD_WEBSOCKET_STATUS`).
+   * The generated close frame must be freed by the caller
+   * with #MHD_websocket_free().
+   */
+  MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR = 4
+};
+
+/**
+ * @brief Enum to specify the fragmenting behavior
+ *        while encoding with #MHD_websocket_encode_text() or
+ *        #MHD_websocket_encode_binary().
+ * @ingroup websocket
+ */
+enum MHD_WEBSOCKET_FRAGMENTATION
+{
+  /**
+   * You don't want to use fragmentation.
+   * The encoded frame consists of only one frame.
+   */
+  MHD_WEBSOCKET_FRAGMENTATION_NONE = 0,
+  /**
+   * You want to use fragmentation.
+   * The encoded frame is the first frame of
+   * a series of data frames of the same type
+   * (text or binary).
+   * You may send control frames (ping, pong or close)
+   * between these data frames.
+   */
+  MHD_WEBSOCKET_FRAGMENTATION_FIRST = 1,
+  /**
+   * You want to use fragmentation.
+   * The encoded frame is not the first frame of
+   * the series of data frames, but also not the last one.
+   * You may send control frames (ping, pong or close)
+   * between these data frames.
+   */
+  MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING = 2,
+  /**
+   * You want to use fragmentation.
+   * The encoded frame is the last frame of
+   * the series of data frames, but also not the first one.
+   * After this frame, you may send all types of frames again.
+   */
+  MHD_WEBSOCKET_FRAGMENTATION_LAST = 3
+};
+
+/**
+ * @brief Enum of the return value for almost every MHD_websocket function.
+ *        Errors are negative and values equal to or above zero mean a success.
+ *        Positive values are only used by #MHD_websocket_decode().
+ * @ingroup websocket
+ */
+enum MHD_WEBSOCKET_STATUS
+{
+  /**
+   * The call succeeded.
+   * For #MHD_websocket_decode() this means that no error occurred,
+   * but also no frame has been completed yet.
+   * For other functions this means simply a success.
+   */
+  MHD_WEBSOCKET_STATUS_OK = 0,
+  /**
+   * #MHD_websocket_decode() has decoded a text frame.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded text (if any).
+   */
+  MHD_WEBSOCKET_STATUS_TEXT_FRAME = 0x1,
+  /**
+   * #MHD_websocket_decode() has decoded a binary frame.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded binary data (if any).
+   */
+  MHD_WEBSOCKET_STATUS_BINARY_FRAME = 0x2,
+  /**
+   * #MHD_websocket_decode() has decoded a close frame.
+   * This means you must close the socket using #MHD_upgrade_action()
+   * with #MHD_UPGRADE_ACTION_CLOSE.
+   * You may respond with a close frame before closing.
+   * The parameters `payload` and `payload_len` are filled with
+   * the close reason (if any).
+   * The close reason starts with a two byte sequence of close code
+   * in network byte order (see `enum MHD_WEBSOCKET_CLOSEREASON`).
+   * After these two bytes a UTF-8 encoded close reason may follow.
+   * You can call #MHD_websocket_split_close_reason() to split that
+   * close reason.
+   */
+  MHD_WEBSOCKET_STATUS_CLOSE_FRAME = 0x8,
+  /**
+   * #MHD_websocket_decode() has decoded a ping frame.
+   * You should respond to this with a pong frame.
+   * The pong frame must contain the same binary data as
+   * the corresponding ping frame (if it had any).
+   * The parameters `payload` and `payload_len` are filled with
+   * the binary ping data (if any).
+   */
+  MHD_WEBSOCKET_STATUS_PING_FRAME = 0x9,
+  /**
+   * #MHD_websocket_decode() has decoded a pong frame.
+   * You should usually only receive pong frames if you sent
+   * a ping frame before.
+   * The binary data should be equal to your ping frame and can be
+   * used to distinguish the response if you sent multiple ping frames.
+   * The parameters `payload` and `payload_len` are filled with
+   * the binary pong data (if any).
+   */
+  MHD_WEBSOCKET_STATUS_PONG_FRAME = 0xA,
+  /**
+   * #MHD_websocket_decode() has decoded a text frame fragment.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded text (if any).
+   * This is like #MHD_WEBSOCKET_STATUS_TEXT_FRAME, but it can only
+   * appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS during
+   * the call of #MHD_websocket_stream_init() or
+   * #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT = 0x11,
+  /**
+   * #MHD_websocket_decode() has decoded a binary frame fragment.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded binary data (if any).
+   * This is like #MHD_WEBSOCKET_STATUS_BINARY_FRAME, but it can only
+   * appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS during
+   * the call of #MHD_websocket_stream_init() or
+   * #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT = 0x12,
+  /**
+   * #MHD_websocket_decode() has decoded the next text frame fragment.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded text (if any).
+   * This is like #MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, but it appears
+   * only after the first and before the last fragment of a series of fragments.
+   * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+   * during the call of #MHD_websocket_stream_init() or
+   * #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_STATUS_TEXT_NEXT_FRAGMENT = 0x21,
+  /**
+   * #MHD_websocket_decode() has decoded the next binary frame fragment.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded binary data (if any).
+   * This is like #MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, but it appears
+   * only after the first and before the last fragment of a series of fragments.
+   * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+   * during the call of #MHD_websocket_stream_init() or
+   * #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT = 0x22,
+  /**
+   * #MHD_websocket_decode() has decoded the last text frame fragment.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded text (if any).
+   * This is like #MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT, but it appears
+   * only for the last fragment of a series of fragments.
+   * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+   * during the call of #MHD_websocket_stream_init() or
+   * #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT = 0x41,
+  /**
+   * #MHD_websocket_decode() has decoded the last binary frame fragment.
+   * The parameters `payload` and `payload_len` are filled with
+   * the decoded binary data (if any).
+   * This is like #MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT, but it appears
+   * only for the last fragment of a series of fragments.
+   * It can only appear if you specified #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+   * during the call of #MHD_websocket_stream_init() or
+   * #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT = 0x42,
+  /**
+   * The call failed and the stream is invalid now for decoding.
+   * You must close the websocket now using #MHD_upgrade_action()
+   * with #MHD_UPGRADE_ACTION_CLOSE.
+   * You may send a close frame before closing.
+   * This is only used by #MHD_websocket_decode() and happens
+   * if the stream contains errors (i. e. invalid byte data).
+   */
+  MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR = -1,
+  /**
+   * You tried to decode something, but the stream has already
+   * been marked invalid.
+   * You must close the websocket now using #MHD_upgrade_action()
+   * with #MHD_UPGRADE_ACTION_CLOSE.
+   * You may send a close frame before closing.
+   * This is only used by #MHD_websocket_decode() and happens
+   * if you call #MDM_websocket_decode() again after
+   * has been invalidated.
+   * You can call #MHD_websocket_stream_is_valid() at any time
+   * to check whether a stream is invalid or not.
+   */
+  MHD_WEBSOCKET_STATUS_STREAM_BROKEN = -2,
+  /**
+   * A memory allocation failed. The stream remains valid.
+   * If this occurred while decoding, the decoding could be
+   * possible later if enough memory is available.
+   * This could happen while decoding if you received a too big data frame.
+   * You could try to specify max_payload_size during the call of
+   * #MHD_websocket_stream_init() or #MHD_websocket_stream_init2() to
+   * avoid this and close the websocket instead.
+   */
+  MHD_WEBSOCKET_STATUS_MEMORY_ERROR = -3,
+  /**
+   * You passed invalid parameters during the function call
+   * (i. e. a NULL pointer for a required parameter).
+   * The stream remains valid.
+   */
+  MHD_WEBSOCKET_STATUS_PARAMETER_ERROR = -4,
+  /**
+   * The maximum payload size has been exceeded.
+   * If you got this return code from #MHD_websocket_decode() then
+   * the stream becomes invalid and the websocket must be closed
+   * using #MHD_upgrade_action() with #MHD_UPGRADE_ACTION_CLOSE.
+   * You may send a close frame before closing.
+   * The maximum payload size is specified during the call of
+   * #MHD_websocket_stream_init() or #MHD_websocket_stream_init2().
+   * This can also appear if you specified 0 as maximum payload size
+   * when the message is greater than the maximum allocatable memory size
+   * (i. e. more than 4 GiB on 32 bit systems).
+   * If you got this return code from #MHD_websocket_encode_close(),
+   * #MHD_websocket_encode_ping() or #MHD_websocket_encode_pong() then
+   * you passed to much payload data. The stream remains valid then.
+   */
+  MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED = -5,
+  /**
+   * An UTF-8 sequence is invalid.
+   * If you got this return code from #MHD_websocket_decode() then
+   * the stream becomes invalid and you must close the websocket
+   * using #MHD_upgrade_action() with #MHD_UPGRADE_ACTION_CLOSE.
+   * You may send a close frame before closing.
+   * If you got this from #MHD_websocket_encode_text() or
+   * #MHD_websocket_encode_close() then you passed invalid UTF-8 text.
+   * The stream remains valid then.
+   */
+  MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR = -6,
+  /**
+   * A check routine for the HTTP headers came to the conclusion that
+   * the header value isn't valid for a websocket handshake request.
+   * This value can only be returned from the following functions:
+   * * #MHD_websocket_check_http_version()
+   * * #MHD_websocket_check_connection_header()
+   * * #MHD_websocket_check_upgrade_header()
+   * * #MHD_websocket_check_version_header()
+   * * #MHD_websocket_create_accept_header()
+   */
+  MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER = -7
+};
+
+/**
+ * @brief Enumeration of possible close reasons for close frames.
+ *
+ * The possible values are specified in RFC 6455 7.4.1
+ * These close reasons here are the default set specified by RFC 6455,
+ * but also other close reasons could be used.
+ *
+ * The definition is for short:
+ * 0-999 are never used (if you pass 0 in
+ *   #MHD_websocket_encode_close() then no close reason is used).
+ * 1000-2999 are specified by RFC 6455.
+ * 3000-3999 are specified by libraries, etc. but must be registered by IANA.
+ * 4000-4999 are reserved for private use.
+ *
+ * @ingroup websocket
+ */
+enum MHD_WEBSOCKET_CLOSEREASON
+{
+  /**
+   * This value is used as placeholder for #MHD_websocket_encode_close()
+   * to tell that you don't want to specify any reason.
+   * If you use this value then no reason text may be used.
+   * This value cannot be a result of decoding, because this value
+   * is not a valid close reason for the websocket protocol.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_NO_REASON = 0,
+  /**
+   * You close the websocket because it fulfilled its purpose and shall
+   * now be closed in a normal, planned way.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_REGULAR = 1000,
+  /**
+   * You close the websocket because you are shutting down the server or
+   * something similar.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_GOING_AWAY = 1001,
+  /**
+   * You close the websocket because a protocol error occurred
+   * during decoding (i. e. invalid byte data).
+   */
+  MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR = 1002,
+  /**
+   * You close the websocket because you received data which you don't accept.
+   * For example if you received a binary frame,
+   * but your application only expects text frames.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_UNSUPPORTED_DATATYPE = 1003,
+  /**
+   * You close the websocket because it contains malformed UTF-8.
+   * The UTF-8 validity is automatically checked by #MHD_websocket_decode(),
+   * so you don't need to check it on your own.
+   * UTF-8 is specified in RFC 3629.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_MALFORMED_UTF8 = 1007,
+  /**
+   * You close the websocket because of any reason.
+   * Usually this close reason is used if no other close reason
+   * is more specific or if you don't want to use any other close reason.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_POLICY_VIOLATED = 1008,
+  /**
+   * You close the websocket because you received a frame which is too big
+   * to process.
+   * You can specify the maximum allowed payload size during the call of
+   * #MHD_websocket_stream_init() or #MHD_websocket_stream_init2().
+   */
+  MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED = 1009,
+  /**
+   * This status code can be sent by the client if it
+   * expected a specific extension, but this extension hasn't been negotiated.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_MISSING_EXTENSION = 1010,
+  /**
+   * The server closes the websocket because it encountered
+   * an unexpected condition that prevented it from fulfilling the request.
+   */
+  MHD_WEBSOCKET_CLOSEREASON_UNEXPECTED_CONDITION = 1011
+};
+
+/**
+ * @brief Enumeration of possible UTF-8 check steps
+ *
+ * These values are used during the encoding of fragmented text frames
+ * or for error analysis while encoding text frames.
+ * Its values specify the next step of the UTF-8 check.
+ * UTF-8 sequences consist of one to four bytes.
+ * This enumeration just says how long the current UTF-8 sequence is
+ * and what is the next expected byte.
+ *
+ * @ingroup websocket
+ */
+enum MHD_WEBSOCKET_UTF8STEP
+{
+  /**
+   * There is no open UTF-8 sequence.
+   * The next byte must be 0x00-0x7F or 0xC2-0xF4.
+   */
+  MHD_WEBSOCKET_UTF8STEP_NORMAL   = 0,
+  /**
+   * The second byte of a two byte UTF-8 sequence.
+   * The first byte was 0xC2-0xDF.
+   * The next byte must be 0x80-0xBF.
+   */
+  MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1 = 1,
+  /**
+   * The second byte of a three byte UTF-8 sequence.
+   * The first byte was 0xE0.
+   * The next byte must be 0xA0-0xBF.
+   */
+  MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2 = 2,
+  /**
+  * The second byte of a three byte UTF-8 sequence.
+  * The first byte was 0xED.
+  * The next byte must by 0x80-0x9F.
+  */
+  MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2 = 3,
+  /**
+  * The second byte of a three byte UTF-8 sequence.
+  * The first byte was 0xE1-0xEC or 0xEE-0xEF.
+  * The next byte must be 0x80-0xBF.
+  */
+  MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2 = 4,
+  /**
+  * The third byte of a three byte UTF-8 sequence.
+  * The next byte must be 0x80-0xBF.
+  */
+  MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2 = 5,
+  /**
+   * The second byte of a four byte UTF-8 sequence.
+   * The first byte was 0xF0.
+   * The next byte must be 0x90-0xBF.
+   */
+  MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3 = 6,
+  /**
+   * The second byte of a four byte UTF-8 sequence.
+   * The first byte was 0xF4.
+   * The next byte must be 0x80-0x8F.
+   */
+  MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3 = 7,
+  /**
+   * The second byte of a four byte UTF-8 sequence.
+   * The first byte was 0xF1-0xF3.
+   * The next byte must be 0x80-0xBF.
+   */
+  MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3 = 8,
+  /**
+   * The third byte of a four byte UTF-8 sequence.
+   * The next byte must be 0x80-0xBF.
+   */
+  MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3 = 9,
+  /**
+  * The fourth byte of a four byte UTF-8 sequence.
+  * The next byte must be 0x80-0xBF.
+  */
+  MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3 = 10
+};
+
+/**
+* @brief Enumeration of validity values
+*
+* These values are used for #MHD_websocket_stream_is_valid()
+* and specify the validity status.
+*
+* @ingroup websocket
+*/
+enum MHD_WEBSOCKET_VALIDITY
+{
+  /**
+  * The stream is invalid.
+  * It cannot be used for decoding anymore.
+  */
+  MHD_WEBSOCKET_VALIDITY_INVALID = 0,
+  /**
+   * The stream is valid.
+   * Decoding works as expected.
+   */
+  MHD_WEBSOCKET_VALIDITY_VALID   = 1,
+  /**
+   * The stream has received a close frame and
+   * is partly invalid.
+   * You can still use the stream for decoding,
+   * but if a data frame is received an error will be reported.
+   * After a close frame has been sent, no data frames
+   * may follow from the sender of the close frame.
+   */
+  MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES = 2
+};
+/**
+ * This callback function is used internally by many websocket functions
+ * for allocating data.
+ * By default `malloc()` is used.
+ * You can use your own allocation function with
+ * #MHD_websocket_stream_init2() if you wish to.
+ * This can be useful for operating systems like Windows
+ * where `malloc()`, `realloc()` and `free()` are compiler-dependent.
+ * You can call the associated `malloc()` callback of
+ * a websocket stream with #MHD_websocket_malloc().
+ *
+ * @param buf_len buffer size in bytes
+ * @return allocated memory
+ * @ingroup websocket
+ */
+typedef void *
+(*MHD_WebSocketMallocCallback) (size_t buf_len);
+/**
+ * This callback function is used internally by many websocket
+ * functions for reallocating data.
+ * By default `realloc()` is used.
+ * You can use your own reallocation function with
+ * #MHD_websocket_stream_init2() if you wish to.
+ * This can be useful for operating systems like Windows
+ * where `malloc()`, `realloc()` and `free()` are compiler-dependent.
+ * You can call the associated `realloc()` callback of
+ * a websocket stream with #MHD_websocket_realloc().
+ *
+ * @param buf buffer
+ * @param new_buf_len new buffer size in bytes
+ * @return reallocated memory
+ * @ingroup websocket
+ */
+typedef void *
+(*MHD_WebSocketReallocCallback) (void *buf, size_t new_buf_len);
+/**
+ * This callback function is used internally by many websocket
+ * functions for freeing data.
+ * By default `free()` is used.
+ * You can use your own free function with
+ * #MHD_websocket_stream_init2() if you wish to.
+ * This can be useful for operating systems like Windows
+ * where `malloc()`, `realloc()` and `free()` are compiler-dependent.
+ * You can call the associated `free()` callback of
+ * a websocket stream with #MHD_websocket_free().
+ *
+ * @param buf buffer
+ * @ingroup websocket
+ */
+typedef void
+(*MHD_WebSocketFreeCallback) (void *buf);
+/**
+ * This callback function is used for generating random numbers
+ * for masking payload data in client mode.
+ * If you use websockets in server mode with libmicrohttpd then
+ * you don't need a random number generator, because
+ * the server doesn't mask its outgoing messageses.
+ * However if you wish to use a websocket stream in client mode,
+ * you must pass this callback function to #MHD_websocket_stream_init2().
+ *
+ * @param cls closure specified in #MHD_websocket_stream_init2()
+ * @param buf buffer to fill with random values
+ * @param buf_len size of buffer in bytes
+ * @return The number of generated random bytes.
+ *         Should usually equal to buf_len.
+ * @ingroup websocket
+ */
+typedef size_t
+(*MHD_WebSocketRandomNumberGenerator) (void *cls, void *buf, size_t buf_len);
+
+/**
+ * Checks the HTTP version of the incoming request.
+ * Websocket requests are only allowed for HTTP/1.1 or above.
+ *
+ * @param http_version The value of the 'version' parameter of your
+ *                     access_handler callback
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         0 means the HTTP version is correct for a websocket request,
+ *         a value less than zero means that the HTTP version isn't
+ *         valid for a websocket request.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_http_version (const char *http_version);
+
+/**
+ * Checks the value of the 'Connection' HTTP request header.
+ * Websocket requests require the token 'Upgrade' in
+ * the 'Connection' HTTP request header.
+ *
+ * @param connection_header The value of the 'Connection' request header.
+ *                          You can get this request header value by passing
+ *                          #MHD_HTTP_HEADER_CONNECTION to
+ *                          #MHD_lookup_connection_value().
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         0 means the 'Connection' request header is correct
+ *         for a websocket request,
+ *         a value less than zero means that the 'Connection' header isn't
+ *         valid for a websocket request.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_connection_header (const char *connection_header);
+
+/**
+ * Checks the value of the 'Upgrade' HTTP request header.
+ * Websocket requests require the value 'websocket' in
+ * the 'Upgrade' HTTP request header.
+ *
+ * @param upgrade_header The value of the 'Upgrade' request header.
+ *                       You can get this request header value by passing
+ *                       #MHD_HTTP_HEADER_UPGRADE to
+ *                       #MHD_lookup_connection_value().
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         0 means the 'Upgrade' request header is correct
+ *         for a websocket request,
+ *         a value less than zero means that the 'Upgrade' header isn't
+ *         valid for a websocket request.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_upgrade_header (const char *upgrade_header);
+
+/**
+ * Checks the value of the 'Sec-WebSocket-Version' HTTP request header.
+ * Websocket requests require the value '13'
+ * in the 'Sec-WebSocket-Version' HTTP request header.
+ *
+ * @param version_header The value of the 'Sec-WebSocket-Version'
+ *                       request header.
+ *                       You can get this request header value by passing
+ *                       #MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION to
+ *                       #MHD_lookup_connection_value().
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         0 means the 'Sec-WebSocket-Version' request header is correct
+ *         for a websocket request,
+ *         a value less than zero means that the 'Sec-WebSocket-Version'
+ *         header isn't valid for a websocket request.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_version_header (const char *version_header);
+
+/**
+ * Creates the response value for the 'Sec-WebSocket-Key' HTTP request header.
+ * The generated value must be sent to the client
+ * as 'Sec-WebSocket-Accept' HTTP response header.
+ *
+ * @param sec_websocket_key The value of the 'Sec-WebSocket-Key'
+ *                          request header.
+ *                          You can get this request header value by passing
+ *                          #MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY to
+ *                          #MHD_lookup_connection_value().
+ * @param[out] sec_websocket_accept The response buffer, which will receive
+ *                                  the generated 'Sec-WebSocket-Accept' header.
+ *                                  This buffer must be at least 29 bytes long and
+ *                                  will contain the response value plus
+ *                                  a terminating NUL on success.
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         Typically 0 on success or less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_create_accept_header (const char *sec_websocket_key,
+                                    char *sec_websocket_accept);
+
+/**
+ * Creates a new websocket stream, used for decoding/encoding.
+ *
+ * @param[out] ws The websocket stream
+ * @param flags Combination of `enum MHD_WEBSOCKET_FLAG` values
+ *              to modify the behavior of the websocket stream.
+ * @param max_payload_size The maximum size for incoming payload
+ *                         data in bytes. Use 0 to allow each size.
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         Typically 0 on success or less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_init (struct MHD_WebSocketStream **ws,
+                           int flags,
+                           size_t max_payload_size);
+
+/**
+ * Creates a new websocket stream, used for decoding/encoding,
+ * but with custom memory functions for malloc, realloc and free.
+ * Also a random number generator can be specified for client mode.
+ *
+ * @param[out] ws The websocket stream
+ * @param flags Combination of `enum MHD_WEBSOCKET_FLAG` values
+ *              to modify the behavior of the websocket stream.
+ * @param max_payload_size The maximum size for incoming payload
+ *                         data in bytes. Use 0 to allow each size.
+ * @param callback_malloc  The callback function for `malloc()`.
+ * @param callback_realloc The callback function for `realloc()`.
+ * @param callback_free    The callback function for `free()`.
+ * @param cls_rng          A closure for the random number generator callback.
+ *                         This is only required when
+ *                         MHD_WEBSOCKET_FLAG_CLIENT is passed in `flags`.
+ *                         The given value is passed to
+ *                         the random number generator.
+ *                         May be NULL if not needed.
+ *                         Should be NULL when you are
+ *                         not using MHD_WEBSOCKET_FLAG_CLIENT.
+ * @param callback_rng     A callback function for a
+ *                         secure random number generator.
+ *                         This is only required when
+ *                         MHD_WEBSOCKET_FLAG_CLIENT is passed in `flags`.
+ *                         Should be NULL otherwise.
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         Typically 0 on success or less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_init2 (struct MHD_WebSocketStream **ws,
+                            int flags,
+                            size_t max_payload_size,
+                            MHD_WebSocketMallocCallback callback_malloc,
+                            MHD_WebSocketReallocCallback callback_realloc,
+                            MHD_WebSocketFreeCallback callback_free,
+                            void *cls_rng,
+                            MHD_WebSocketRandomNumberGenerator callback_rng);
+
+/**
+ * Frees a websocket stream
+ *
+ * @param ws The websocket stream. This value may be NULL.
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         Typically 0 on success or less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_free (struct MHD_WebSocketStream *ws);
+
+/**
+ * Invalidates a websocket stream.
+ * After invalidation a websocket stream cannot be used for decoding anymore.
+ * Encoding is still possible.
+ *
+ * @param ws The websocket stream.
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         Typically 0 on success or less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_invalidate (struct MHD_WebSocketStream *ws);
+
+/**
+ * Queries whether a websocket stream is valid.
+ * Invalidated websocket streams cannot be used for decoding anymore.
+ * Encoding is still possible.
+ *
+ * @param ws The websocket stream.
+ * @return A value of `enum MHD_WEBSOCKET_VALIDITY`.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_VALIDITY
+MHD_websocket_stream_is_valid (struct MHD_WebSocketStream *ws);
+
+/**
+ * Decodes a byte sequence for a websocket stream.
+ * Decoding is done until either a frame is complete or
+ * the end of the byte sequence is reached.
+ *
+ * @param ws The websocket stream.
+ * @param streambuf The byte sequence for decoding.
+ *                  Typically that what you received via `recv()`.
+ * @param streambuf_len The length of the byte sequence @a streambuf
+ * @param[out] streambuf_read_len The number of bytes which has been processed
+ *                                by this call. This value may be less
+ *                                than @a streambuf_len when a frame is decoded
+ *                                before the end of the buffer is reached.
+ *                                The remaining bytes of @a buf must be passed
+ *                                to the next call of this function.
+ * @param[out] payload Pointer to a variable, which receives a buffer
+ *                     with the decoded payload data.
+ *                     If no decoded data is available this is NULL.
+ *                     When the returned value is not NULL then
+ *                     the buffer contains always @a payload_len bytes plus
+ *                     one terminating NUL character.
+ *                     The caller must free this buffer
+ *                     using #MHD_websocket_free().
+ *                     If you passed the flag
+ *                     #MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR
+ *                     upon creation of this websocket stream and
+ *                     a decoding error occurred
+ *                     (function return value less than 0), then this
+ *                     buffer contains a generated close frame
+ *                     which must be sent via the socket to the recipient.
+ *                     If you passed the flag #MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+ *                     upon creation of the websocket stream then
+ *                     this payload may only be a part of the complete message.
+ *                     Only complete UTF-8 sequences are returned
+ *                     for fragmented text frames.
+ *                     If necessary the UTF-8 sequence will be completed
+ *                     with the next text fragment.
+ * @param[out] payload_len The length of the result payload buffer in bytes.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is greater than 0 if a frame has is complete,
+ *         equal to 0 if more data is needed an less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_decode (struct MHD_WebSocketStream *ws,
+                      const char *streambuf,
+                      size_t streambuf_len,
+                      size_t *streambuf_read_len,
+                      char **payload,
+                      size_t *payload_len);
+
+/**
+ * Splits the payload of a decoded close frame.
+ *
+ * @param payload The payload of the close frame.
+ *                This parameter may only be NULL if @a payload_len is 0.
+ * @param payload_len The length of @a payload.
+ * @param[out] reason_code The numeric close reason.
+ *                         If there was no close reason, this is
+ *                         #MHD_WEBSOCKET_CLOSEREASON_NO_REASON.
+ *                         Compare with `enum MHD_WEBSOCKET_CLOSEREASON`.
+ *                         This parameter is optional and may be NULL.
+ * @param[out] reason_utf8 The literal close reason.
+ *                         If there was no literal close reason, this is NULL.
+ *                         This parameter is optional and may be NULL.
+ *                         Please note that no memory is allocated
+ *                         in this function.
+ *                         If not NULL the returned value of this parameter
+ *                         points to a position in the specified @a payload.
+ * @param[out] reason_utf8_len The length of the literal close reason.
+ *                             If there was no literal close reason, this is 0.
+ *                             This parameter is optional and may be NULL.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_split_close_reason (const char *payload,
+                                  size_t payload_len,
+                                  unsigned short *reason_code,
+                                  const char **reason_utf8,
+                                  size_t *reason_utf8_len);
+
+/**
+ * Encodes an UTF-8 encoded text into websocket text frame.
+ *
+ * @param ws The websocket stream.
+ * @param payload_utf8 The UTF-8 encoded text to send.
+ *                     This may be NULL if payload_utf8_len is 0.
+ * @param payload_utf8_len The length of the UTF-8 encoded text in bytes.
+ * @param fragmentation A value of `enum MHD_WEBSOCKET_FRAGMENTATION`
+ *                      to specify the fragmentation behavior.
+ *                      Specify MHD_WEBSOCKET_FRAGMENTATION_NONE
+ *                      if you don't want to use fragmentation.
+ * @param[out] frame This variable receives a buffer with the encoded frame.
+ *                   This is what you typically send via `send()` to the recipient.
+ *                   If no encoded data is available this is NULL.
+ *                   When this variable is not NULL then the buffer contains always
+ *                   @a frame_len bytes plus one terminating NUL character.
+ *                   The caller must free this buffer using #MHD_websocket_free().
+ * @param[out] frame_len The length of the encoded frame in bytes.
+ * @param[out] utf8_step This parameter is required for fragmentation and
+ *                       should be NULL if no fragmentation is used.
+ *                       It contains information about the last encoded
+ *                       UTF-8 sequence and is required to continue a previous
+ *                       UTF-8 sequence when fragmentation is used.
+ *                       `enum MHD_WEBSOCKET_UTF8STEP` is for this value.
+ *                       If you start a new fragment using
+ *                       MHD_WEBSOCKET_FRAGMENTATION_NONE or
+ *                       MHD_WEBSOCKET_FRAGMENTATION_FIRST the value
+ *                       of this variable will be initialized
+ *                       to MHD_WEBSOCKET_UTF8STEP_NORMAL.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_text (struct MHD_WebSocketStream *ws,
+                           const char *payload_utf8,
+                           size_t payload_utf8_len,
+                           int fragmentation,
+                           char **frame,
+                           size_t *frame_len,
+                           int *utf8_step);
+
+/**
+ * Encodes binary data into websocket binary frame.
+ *
+ * @param ws The websocket stream.
+ * @param payload The binary data to send.
+ * @param payload_len The length of the binary data in bytes.
+ * @param fragmentation A value of `enum MHD_WEBSOCKET_FRAGMENTATION`
+ *                      to specify the fragmentation behavior.
+ *                      Specify MHD_WEBSOCKET_FRAGMENTATION_NONE
+ *                      if you don't want to use fragmentation.
+ * @param[out] frame This variable receives a buffer with
+ *                   the encoded binary frame.
+ *                   This is what you typically send via `send()`
+ *                   to the recipient.
+ *                   If no encoded frame is available this is NULL.
+ *                   When this variable is not NULL then the allocated buffer
+ *                   contains always @a frame_len bytes plus one terminating
+ *                   NUL character.
+ *                   The caller must free this buffer using #MHD_websocket_free().
+ * @param[out] frame_len The length of the result frame buffer in bytes.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_binary (struct MHD_WebSocketStream *ws,
+                             const char *payload,
+                             size_t payload_len,
+                             int fragmentation,
+                             char **frame,
+                             size_t *frame_len);
+
+/**
+ * Encodes a websocket ping frame
+ *
+ * @param ws The websocket stream.
+ * @param payload The binary ping payload data to send.
+ *                This may be NULL if @a payload_len is 0.
+ * @param payload_len The length of the payload data in bytes.
+ *                    This may not exceed 125 bytes.
+ * @param[out] frame This variable receives a buffer with the encoded ping frame data.
+ *                   This is what you typically send via `send()` to the recipient.
+ *                   If no encoded frame is available this is NULL.
+ *                   When this variable is not NULL then the buffer contains always
+ *                   @a frame_len bytes plus one terminating NUL character.
+ *                   The caller must free this buffer using #MHD_websocket_free().
+ * @param[out] frame_len The length of the result frame buffer in bytes.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_ping (struct MHD_WebSocketStream *ws,
+                           const char *payload,
+                           size_t payload_len,
+                           char **frame,
+                           size_t *frame_len);
+
+/**
+ * Encodes a websocket pong frame
+ *
+ * @param ws The websocket stream.
+ * @param payload The binary pong payload data, which should be
+ *                the decoded payload from the received ping frame.
+ *                This may be NULL if @a payload_len is 0.
+ * @param payload_len The length of the payload data in bytes.
+ *                    This may not exceed 125 bytes.
+ * @param[out] frame This variable receives a buffer with
+ *                   the encoded pong frame data.
+ *                   This is what you typically send via `send()`
+ *                   to the recipient.
+ *                   If no encoded frame is available this is NULL.
+ *                   When this variable is not NULL then the buffer
+ *                   contains always @a frame_len bytes plus one
+ *                   terminating NUL character.
+ *                   The caller must free this buffer
+ *                   using #MHD_websocket_free().
+ * @param[out] frame_len The length of the result frame buffer in bytes.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_pong (struct MHD_WebSocketStream *ws,
+                           const char *payload,
+                           size_t payload_len,
+                           char **frame,
+                           size_t *frame_len);
+
+/**
+ * Encodes a websocket close frame
+ *
+ * @param ws The websocket stream.
+ * @param reason_code The reason for close.
+ *                    You can use `enum MHD_WEBSOCKET_CLOSEREASON`
+ *                    for typical reasons,
+ *                    but you are not limited to these values.
+ *                    The allowed values are specified in RFC 6455 7.4.
+ *                    If you don't want to enter a reason, you can specify
+ *                    #MHD_WEBSOCKET_CLOSEREASON_NO_REASON then
+ *                    no reason is encoded.
+ * @param reason_utf8 An UTF-8 encoded text reason why the connection is closed.
+ *                    This may be NULL if @a reason_utf8_len is 0.
+ *                    This must be NULL if @a reason_code is
+ *                    #MHD_WEBSOCKET_CLOSEREASON_NO_REASON (= 0).
+ * @param reason_utf8_len The length of the UTF-8 encoded text reason in bytes.
+ *                        This may not exceed 123 bytes.
+ * @param[out] frame This variable receives a buffer with
+ *                   the encoded close frame.
+ *                   This is what you typically send via `send()`
+ *                   to the recipient.
+ *                   If no encoded frame is available this is NULL.
+ *                   When this variable is not NULL then the buffer
+ *                   contains always @a frame_len bytes plus
+ *                   one terminating NUL character.
+ *                   The caller must free this buffer
+ *                   using #MHD_websocket_free().
+ * @param[out] frame_len The length of the result frame buffer in bytes.
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_close (struct MHD_WebSocketStream *ws,
+                            unsigned short reason_code,
+                            const char *reason_utf8,
+                            size_t reason_utf8_len,
+                            char **frame,
+                            size_t *frame_len);
+
+/**
+ * Allocates memory with the associated 'malloc' function
+ * of the websocket stream
+ *
+ * @param ws The websocket stream.
+ * @param buf_len The length of the memory to allocate in bytes
+ *
+ * @return The allocated memory on success or NULL on failure.
+ * @ingroup websocket
+ */
+_MHD_EXTERN void *
+MHD_websocket_malloc (struct MHD_WebSocketStream *ws,
+                      size_t buf_len);
+
+/**
+ * Reallocates memory with the associated 'realloc' function
+ * of the websocket stream
+ *
+ * @param ws The websocket stream.
+ * @param buf The previously allocated memory or NULL
+ * @param new_buf_len The new length of the memory in bytes
+ *
+ * @return The allocated memory on success or NULL on failure.
+ *         If NULL is returned the previously allocated buffer
+ *         remains valid.
+ * @ingroup websocket
+ */
+_MHD_EXTERN void *
+MHD_websocket_realloc (struct MHD_WebSocketStream *ws,
+                       void *buf,
+                       size_t new_buf_len);
+
+/**
+ * Frees memory with the associated 'free' function
+ * of the websocket stream
+ *
+ * @param ws The websocket stream.
+ * @param buf The previously allocated memory or NULL
+ *
+ * @return A value of `enum MHD_WEBSOCKET_STATUS`.
+ *         This is #MHD_WEBSOCKET_STATUS_OK (= 0) on success
+ *         or a value less than 0 on errors.
+ * @ingroup websocket
+ */
+_MHD_EXTERN int
+MHD_websocket_free (struct MHD_WebSocketStream *ws,
+                    void *buf);
+
+#if 0                           /* keep Emacsens' auto-indent happy */
+{
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/include/microspdy.h b/src/include/microspdy.h
deleted file mode 100644
index 7da5fbe..0000000
--- a/src/include/microspdy.h
+++ /dev/null
@@ -1,1380 +0,0 @@
-/*

-    This file is part of libmicrospdy

-    Copyright Copyright (C) 2012, 2013 Christian Grothoff

-

-    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/>.

-*/

-

-/**

- * @file microspdy.h

- * @brief public interface to libmicrospdy

- * @author Andrey Uzunov

- * @author Christian Grothoff

- *

- * All symbols defined in this header start with SPDY_.  libmisrospdy is a small

- * SPDY daemon library. The application can start multiple daemons

- * and they are independent.<p>

- *

- * The header file defines various constants used by the SPDY and the HTTP protocol.

- * This does not mean that the lib actually interprets all of these

- * values. Not everything is implemented. The provided constants are exported as a convenience

- * for users of the library.  The lib does not verify that provided

- * HTTP headers and if their values conform to the SPDY protocol,

- * it only checks if the required headers for the SPDY requests and

- * responses are provided.<p>

- *

- * The library uses just a single thread.<p>

- *

- * Before including "microspdy.h" you should add the necessary

- * includes to define the types used in this file (which headers are needed may

- * depend on your platform; for possible suggestions consult

- * "platform.h" in the libmicrospdy distribution).<p>

- *

- * All of the functions returning SPDY_YES/SPDY_NO return

- * SPDY_INPUT_ERROR when any of the parameters are invalid, e.g.

- * required parameter is NULL.<p>

- *

- * The library does not check if anything at the application layer --

- * requests and responses -- is correct. For example, it

- * is up to the user to check if a client is sending HTTP body but the

- * method is GET.<p>

- *

- * The SPDY flow control is just partially implemented: the receiving

- * window is updated, and the client is notified, to prevent a client

- * from stop sending POST body data, for example.

- */

-#ifndef SPDY_MICROSPDY_H

-#define SPDY_MICROSPDY_H

-

-#include <zlib.h>

-#include <stdbool.h>

-

-/* While we generally would like users to use a configure-driven

-   build process which detects which headers are present and

-   hence works on any platform, we use "standard" includes here

-   to build out-of-the-box for beginning users on common systems.

-

-   Once you have a proper build system and go for more exotic

-   platforms, you should define MHD_PLATFORM_H in some header that

-   you always include *before* "microhttpd.h".  Then the following

-   "standard" includes won't be used (which might be a good

-   idea, especially on platforms where they do not exist). */

-#ifndef MHD_PLATFORM_H

-#include <unistd.h>

-#include <stdarg.h>

-#include <stdint.h>

-#ifdef __MINGW32__

-#include <ws2tcpip.h>

-#else

-#include <sys/time.h>

-#include <sys/types.h>

-#include <sys/socket.h>

-#endif

-#endif

-

-#ifndef _MHD_EXTERN

-#define _MHD_EXTERN extern

-#endif

-

-/**

- * return code for "YES".

- */

-#define SPDY_YES 1

-

-/**

- * return code for "NO".

- */

-#define SPDY_NO 0

-

-/**

- * return code for error when input parameters are wrong. To be returned

- * only by functions which return int. The others will return NULL on

- * input error.

- */

-#define SPDY_INPUT_ERROR -1

-

-/**

- * SPDY version supported by the lib.

- */

-#define SPDY_VERSION 3

-

-/**

- * The maximum allowed size (without 8 byte headers) of

- * SPDY frames (value length) is 8192. The lib will accept and

- * send frames with length at most this value here.

- */

-#define SPDY_MAX_SUPPORTED_FRAME_SIZE 8192

-

-/**

- * HTTP response codes.

- */

-#define SPDY_HTTP_CONTINUE 100

-#define SPDY_HTTP_SWITCHING_PROTOCOLS 101

-#define SPDY_HTTP_PROCESSING 102

-

-#define SPDY_HTTP_OK 200

-#define SPDY_HTTP_CREATED 201

-#define SPDY_HTTP_ACCEPTED 202

-#define SPDY_HTTP_NON_AUTHORITATIVE_INFORMATION 203

-#define SPDY_HTTP_NO_CONTENT 204

-#define SPDY_HTTP_RESET_CONTENT 205

-#define SPDY_HTTP_PARTIAL_CONTENT 206

-#define SPDY_HTTP_MULTI_STATUS 207

-

-#define SPDY_HTTP_MULTIPLE_CHOICES 300

-#define SPDY_HTTP_MOVED_PERMANENTLY 301

-#define SPDY_HTTP_FOUND 302

-#define SPDY_HTTP_SEE_OTHER 303

-#define SPDY_HTTP_NOT_MODIFIED 304

-#define SPDY_HTTP_USE_PROXY 305

-#define SPDY_HTTP_SWITCH_PROXY 306

-#define SPDY_HTTP_TEMPORARY_REDIRECT 307

-

-#define SPDY_HTTP_BAD_REQUEST 400

-#define SPDY_HTTP_UNAUTHORIZED 401

-#define SPDY_HTTP_PAYMENT_REQUIRED 402

-#define SPDY_HTTP_FORBIDDEN 403

-#define SPDY_HTTP_NOT_FOUND 404

-#define SPDY_HTTP_METHOD_NOT_ALLOWED 405

-#define SPDY_HTTP_METHOD_NOT_ACCEPTABLE 406

-#define SPDY_HTTP_PROXY_AUTHENTICATION_REQUIRED 407

-#define SPDY_HTTP_REQUEST_TIMEOUT 408

-#define SPDY_HTTP_CONFLICT 409

-#define SPDY_HTTP_GONE 410

-#define SPDY_HTTP_LENGTH_REQUIRED 411

-#define SPDY_HTTP_PRECONDITION_FAILED 412

-#define SPDY_HTTP_REQUEST_ENTITY_TOO_LARGE 413

-#define SPDY_HTTP_REQUEST_URI_TOO_LONG 414

-#define SPDY_HTTP_UNSUPPORTED_MEDIA_TYPE 415

-#define SPDY_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE 416

-#define SPDY_HTTP_EXPECTATION_FAILED 417

-#define SPDY_HTTP_UNPROCESSABLE_ENTITY 422

-#define SPDY_HTTP_LOCKED 423

-#define SPDY_HTTP_FAILED_DEPENDENCY 424

-#define SPDY_HTTP_UNORDERED_COLLECTION 425

-#define SPDY_HTTP_UPGRADE_REQUIRED 426

-#define SPDY_HTTP_NO_RESPONSE 444

-#define SPDY_HTTP_RETRY_WITH 449

-#define SPDY_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450

-#define SPDY_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS 451

-

-#define SPDY_HTTP_INTERNAL_SERVER_ERROR 500

-#define SPDY_HTTP_NOT_IMPLEMENTED 501

-#define SPDY_HTTP_BAD_GATEWAY 502

-#define SPDY_HTTP_SERVICE_UNAVAILABLE 503

-#define SPDY_HTTP_GATEWAY_TIMEOUT 504

-#define SPDY_HTTP_HTTP_VERSION_NOT_SUPPORTED 505

-#define SPDY_HTTP_VARIANT_ALSO_NEGOTIATES 506

-#define SPDY_HTTP_INSUFFICIENT_STORAGE 507

-#define SPDY_HTTP_BANDWIDTH_LIMIT_EXCEEDED 509

-#define SPDY_HTTP_NOT_EXTENDED 510

-

-/**

- * HTTP headers are used in SPDY, but all of them MUST be lowercase.

- * Some are not valid in SPDY and MUST not be used

- */

-#define SPDY_HTTP_HEADER_ACCEPT "accept"

-#define SPDY_HTTP_HEADER_ACCEPT_CHARSET "accept-charset"

-#define SPDY_HTTP_HEADER_ACCEPT_ENCODING "accept-encoding"

-#define SPDY_HTTP_HEADER_ACCEPT_LANGUAGE "accept-language"

-#define SPDY_HTTP_HEADER_ACCEPT_RANGES "accept-ranges"

-#define SPDY_HTTP_HEADER_AGE "age"

-#define SPDY_HTTP_HEADER_ALLOW "allow"

-#define SPDY_HTTP_HEADER_AUTHORIZATION "authorization"

-#define SPDY_HTTP_HEADER_CACHE_CONTROL "cache-control"

-/* Connection header is forbidden in SPDY */

-#define SPDY_HTTP_HEADER_CONNECTION "connection"

-#define SPDY_HTTP_HEADER_CONTENT_ENCODING "content-encoding"

-#define SPDY_HTTP_HEADER_CONTENT_LANGUAGE "content-language"

-#define SPDY_HTTP_HEADER_CONTENT_LENGTH "content-length"

-#define SPDY_HTTP_HEADER_CONTENT_LOCATION "content-location"

-#define SPDY_HTTP_HEADER_CONTENT_MD5 "content-md5"

-#define SPDY_HTTP_HEADER_CONTENT_RANGE "content-range"

-#define SPDY_HTTP_HEADER_CONTENT_TYPE "content-type"

-#define SPDY_HTTP_HEADER_COOKIE "cookie"

-#define SPDY_HTTP_HEADER_DATE "date"

-#define SPDY_HTTP_HEADER_ETAG "etag"

-#define SPDY_HTTP_HEADER_EXPECT "expect"

-#define SPDY_HTTP_HEADER_EXPIRES "expires"

-#define SPDY_HTTP_HEADER_FROM "from"

-/* Host header is forbidden in SPDY */

-#define SPDY_HTTP_HEADER_HOST "host"

-#define SPDY_HTTP_HEADER_IF_MATCH "if-match"

-#define SPDY_HTTP_HEADER_IF_MODIFIED_SINCE "if-modified-since"

-#define SPDY_HTTP_HEADER_IF_NONE_MATCH "if-none-match"

-#define SPDY_HTTP_HEADER_IF_RANGE "if-range"

-#define SPDY_HTTP_HEADER_IF_UNMODIFIED_SINCE "if-unmodified-since"

-/* Keep-Alive header is forbidden in SPDY */

-#define SPDY_HTTP_HEADER_KEEP_ALIVE "keep-alive"

-#define SPDY_HTTP_HEADER_LAST_MODIFIED "last-modified"

-#define SPDY_HTTP_HEADER_LOCATION "location"

-#define SPDY_HTTP_HEADER_MAX_FORWARDS "max-forwards"

-#define SPDY_HTTP_HEADER_PRAGMA "pragma"

-#define SPDY_HTTP_HEADER_PROXY_AUTHENTICATE "proxy-authenticate"

-#define SPDY_HTTP_HEADER_PROXY_AUTHORIZATION "proxy-authorization"

-/* Proxy-Connection header is forbidden in SPDY */

-#define SPDY_HTTP_HEADER_PROXY_CONNECTION "proxy-connection"

-#define SPDY_HTTP_HEADER_RANGE "range"

-#define SPDY_HTTP_HEADER_REFERER "referer"

-#define SPDY_HTTP_HEADER_RETRY_AFTER "retry-after"

-#define SPDY_HTTP_HEADER_SERVER "server"

-#define SPDY_HTTP_HEADER_SET_COOKIE "set-cookie"

-#define SPDY_HTTP_HEADER_SET_COOKIE2 "set-cookie2"

-#define SPDY_HTTP_HEADER_TE "te"

-#define SPDY_HTTP_HEADER_TRAILER "trailer"

-/* Transfer-Encoding header is forbidden in SPDY */

-#define SPDY_HTTP_HEADER_TRANSFER_ENCODING "transfer-encoding"

-#define SPDY_HTTP_HEADER_UPGRADE "upgrade"

-#define SPDY_HTTP_HEADER_USER_AGENT "user-agent"

-#define SPDY_HTTP_HEADER_VARY "vary"

-#define SPDY_HTTP_HEADER_VIA "via"

-#define SPDY_HTTP_HEADER_WARNING "warning"

-#define SPDY_HTTP_HEADER_WWW_AUTHENTICATE "www-authenticate"

-

-/**

- * HTTP versions (a value must be provided in SPDY requests/responses).

- */

-#define SPDY_HTTP_VERSION_1_0 "HTTP/1.0"

-#define SPDY_HTTP_VERSION_1_1 "HTTP/1.1"

-

-/**

- * HTTP methods

- */

-#define SPDY_HTTP_METHOD_CONNECT "CONNECT"

-#define SPDY_HTTP_METHOD_DELETE "DELETE"

-#define SPDY_HTTP_METHOD_GET "GET"

-#define SPDY_HTTP_METHOD_HEAD "HEAD"

-#define SPDY_HTTP_METHOD_OPTIONS "OPTIONS"

-#define SPDY_HTTP_METHOD_POST "POST"

-#define SPDY_HTTP_METHOD_PUT "PUT"

-#define SPDY_HTTP_METHOD_TRACE "TRACE"

-

-/**

- * HTTP POST encodings, see also

- * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4

- */

-#define SPDY_HTTP_POST_ENCODING_FORM_URLENCODED "application/x-www-form-urlencoded"

-#define SPDY_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data"

-

-

-/**

- * Handle for the daemon (listening on a socket).

- */

-struct SPDY_Daemon;

-

-

-/**

- * Handle for a SPDY session/connection.

- */

-struct SPDY_Session;

-

-

-/**

- * Handle for a SPDY request sent by a client. The structure has pointer

- * to the session's handler

- */

-struct SPDY_Request;

-

-

-/**

- * Handle for a response containing HTTP headers and data to be sent.

- * The structure has pointer to the session's handler

- * for this response.

- */

-struct SPDY_Response;

-

-

-/**

- * Collection of tuples of an HTTP header and values used in requests

- * and responses.

- */

-struct SPDY_NameValue;

-

-

-/**

- * Collection of tuples of a SPDY setting ID, value

- * and flags used to control the sessions.

- */

-struct SPDY_Settings;

-

-

-/**

- * SPDY IO sybsystem flags used by SPDY_init() and SPDY_deinit().<p>

- *

- * The values are used internally as flags, that is why they must be

- * powers of 2.

- */

-enum SPDY_IO_SUBSYSTEM

-{

-

-  /**

-   * No subsystem. For internal use.

-   */

-  SPDY_IO_SUBSYSTEM_NONE = 0,

-

-  /**

-   * Default TLS implementation provided by openSSL/libssl.

-   */

-  SPDY_IO_SUBSYSTEM_OPENSSL = 1,

-

-  /**

-   * No TLS is used.

-   */

-  SPDY_IO_SUBSYSTEM_RAW = 2

-};

-

-

-/**

- * SPDY daemon options. Passed in the varargs portion of

- * SPDY_start_daemon to customize the daemon. Each option must

- * be followed by a value of a specific type.<p>

- *

- * The values are used internally as flags, that is why they must be

- * powers of 2.

- */

-enum SPDY_DAEMON_OPTION

-{

-

-  /**

-   * No more options / last option.  This is used

-   * to terminate the VARARGs list.

-   */

-  SPDY_DAEMON_OPTION_END = 0,

-

-  /**

-   * Set a custom timeout for all connections.  Must be followed by

-   * a number of seconds, given as an 'unsigned int'.  Use

-   * zero for no timeout.

-   */

-  SPDY_DAEMON_OPTION_SESSION_TIMEOUT = 1,

-

-  /**

-   * Bind daemon to the supplied sockaddr. This option must be

-   * followed by a 'struct sockaddr *'.  The 'struct sockaddr*'

-   * should point to a 'struct sockaddr_in6' or to a

-   * 'struct sockaddr_in'.

-   */

-  SPDY_DAEMON_OPTION_SOCK_ADDR = 2,

-

-  /**

-   * Flags for the daemon. Must be followed by a SPDY_DAEMON_FLAG value

-   * which is the result of bitwise OR of desired flags.

-   */

-  SPDY_DAEMON_OPTION_FLAGS = 4,

-

-  /**

-   * IO subsystem type used by daemon and all its sessions. If not set,

-   * TLS provided by openssl is used. Must be followed by a

-   * SPDY_IO_SUBSYSTEM value.

-   */

-  SPDY_DAEMON_OPTION_IO_SUBSYSTEM = 8,

-

-  /**

-   * Maximum number of frames to be written to the socket at once. The

-   * library tries to send max_num_frames in a single call to SPDY_run

-   * for a single session. This means no requests can be received nor

-   * other sessions can send data as long the current one has enough

-   * frames to send and there is no error on writing. Thus, a big value

-   * will affect the performance. Small value gives fairnes for sessions.

-   * Must be followed by a positive integer (uin32_t). If not set, the

-   * default value 10 will be used.

-   */

-  SPDY_DAEMON_OPTION_MAX_NUM_FRAMES = 16

-};

-

-

-/**

- * Flags for starting SPDY daemon. They are used to set some settings

- * for the daemon, which do not require values.

- */

-enum SPDY_DAEMON_FLAG

-{

-  /**

-   * No flags selected.

-   */

-  SPDY_DAEMON_FLAG_NO = 0,

-

-  /**

-   * The server will bind only on IPv6 addresses. If the flag is set and

-   * the daemon is provided with IPv4 address or IPv6 is not supported,

-   * starting daemon will fail.

-   */

-  SPDY_DAEMON_FLAG_ONLY_IPV6 = 1,

-

-  /**

-   * All sessions' sockets will be set with TCP_NODELAY if the flag is

-   * used. Option considered only by SPDY_IO_SUBSYSTEM_RAW.

-   */

-  SPDY_DAEMON_FLAG_NO_DELAY = 2

-};

-

-

-/**

- * SPDY settings IDs sent by both client and server in SPDY SETTINGS frame.

- * They affect the whole SPDY session. Defined in SPDY Protocol - Draft 3.

- */

-enum SPDY_SETTINGS

-{

-

-  /**

-   * Allows the sender to send its expected upload bandwidth on this

-   * channel. This number is an estimate. The value should be the

-   * integral number of kilobytes per second that the sender predicts

-   * as an expected maximum upload channel capacity.

-   */

-  SPDY_SETTINGS_UPLOAD_BANDWIDTH = 1,

-

-  /**

-   * Allows the sender to send its expected download bandwidth on this

-   * channel. This number is an estimate. The value should be the

-   * integral number of kilobytes per second that the sender predicts as

-   * an expected maximum download channel capacity.

-   */

-  SPDY_SETTINGS_DOWNLOAD_BANDWIDTH = 2,

-

-  /**

-   * Allows the sender to send its expected round-trip-time on this

-   * channel. The round trip time is defined as the minimum amount of

-   * time to send a control frame from this client to the remote and

-   * receive a response. The value is represented in milliseconds.

-   */

-  SPDY_SETTINGS_ROUND_TRIP_TIME = 3,

-

-  /**

-   * Allows the sender to inform the remote endpoint the maximum number

-   * of concurrent streams which it will allow. By default there is no

-   * limit. For implementors it is recommended that this value be no

-   * smaller than 100.

-   */

-  SPDY_SETTINGS_MAX_CONCURRENT_STREAMS = 4,

-

-  /**

-   * Allows the sender to inform the remote endpoint of the current TCP

-   * CWND value.

-   */

-  SPDY_SETTINGS_CURRENT_CWND = 5,

-

-  /**

-   * Allows the sender to inform the remote endpoint the retransmission

-   * rate (bytes retransmitted / total bytes transmitted).

-   */

-  SPDY_SETTINGS_DOWNLOAD_RETRANS_RATE = 6,

-

-  /**

-   * Allows the sender to inform the remote endpoint the initial window

-   * size (in bytes) for new streams.

-   */

-  SPDY_SETTINGS_INITIAL_WINDOW_SIZE = 7,

-

-  /**

-   * Allows the server to inform the client if the new size of the

-   * client certificate vector.

-   */

-  SPDY_SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE = 8

-};

-

-

-/**

- * Flags for each individual SPDY setting in the SPDY SETTINGS frame.

- * They affect only one setting to which they are set.

- * Defined in SPDY Protocol - Draft 3.

- */

-enum SPDY_FLAG_SETTINGS

-{

-

-  /**

-   * When set, the sender of this SETTINGS frame is requesting that the

-   * recipient persist the ID/Value and return it in future SETTINGS

-   * frames sent from the sender to this recipient. Because persistence

-   * is only implemented on the client, this flag is only sent by the

-   * server.

-   */

-  SPDY_FLAG_SETTINGS_PERSIST_VALUE = 1,

-

-  /**

-   * When set, the sender is notifying the recipient that this ID/Value

-   * pair was previously sent to the sender by the recipient with the

-   * #SPDY_FLAG_SETTINGS_PERSIST_VALUE, and the sender is returning it.

-   * Because persistence is only implemented on the client, this flag is

-   * only sent by the client.

-   */

-  SPDY_FLAG_SETTINGS_PERSISTED = 2

-};

-

-

-/**

- * Flag associated with a whole SPDY SETTINGS frame. Affect all the

- * settings in the frame. Defined in SPDY Protocol - Draft 3.

- */

-enum SPDY_FLAG_SETTINGS_FRAME

-{

-

-  /**

-   * When set, the client should clear any previously persisted SETTINGS

-   * ID/Value pairs. If this frame contains ID/Value pairs with the

-   * #SPDY_FLAG_SETTINGS_PERSIST_VALUE set, then the client will first

-   * clear its existing, persisted settings, and then persist the values

-   * with the flag set which are contained within this frame. Because

-   * persistence is only implemented on the client, this flag can only

-   * be used when the sender is the server.

-   */

-  SPDY_FLAG_SETTINGS_CLEAR_SETTINGS = 1

-};

-

-

-/**

- * SPDY settings function options. Passed in the varargs portion of

- * SPDY_SettingsReceivedCallback and SPDY_send_settings to customize

- * more the settings handling. Each option must

- * be followed by a value of a specific type.<p>

- *

- * The values are used internally as flags, that is why they must be

- * powers of 2.

- */

-enum SPDY_SETTINGS_OPTION

-{

-

-  /**

-   * No more options / last option.  This is used

-   * to terminate the VARARGs list.

-   */

-  SPDY_SETTINGS_OPTION_END = 0

-};

-

-

-/**

- * Used as a parameter for SPDY_ResponseResultCallback and shows if the

- * response was actually written to the TLS socket or discarded by the

- * lib for any reason (and respectively the reason).

- */

-enum SPDY_RESPONSE_RESULT

-{

-

-  /**

-   * The lib has written the full response to the TLS socket.

-   */

-  SPDY_RESPONSE_RESULT_SUCCESS = 0,

-

-  /**

-   * The session is being closed, so the data is being discarded

-   */

-  SPDY_RESPONSE_RESULT_SESSION_CLOSED = 1,

-

-  /**

-   * The stream for this response has been closed. May happen when the

-   * sender had sent first SYN_STREAM and after that RST_STREAM.

-   */

-  SPDY_RESPONSE_RESULT_STREAM_CLOSED = 2

-};

-

-

-/**

- * Callback for serious error condition. The default action is to print

- * an error message and abort().

- *

- * @param cls user specified value

- * @param file where the error occured

- * @param line where the error occured

- * @param reason error details message, may be NULL

- */

-typedef void

-(*SPDY_PanicCallback) (void * cls,

-                       const char *file,

-                       unsigned int line,

-                       const char *reason);

-

-

-/**

- * Callback for new SPDY session established by a client. Called

- * immediately after the TCP connection was established.

- *

- * @param cls client-defined closure

- * @param session handler for the new SPDY session

- */

-typedef void

-(*SPDY_NewSessionCallback) (void * cls,

-                            struct SPDY_Session * session);

-

-

-/**

- * Callback for closed session. Called after the TCP connection was

- * closed. In this callback function the user has the last

- * chance to access the SPDY_Session structure. After that the latter

- * will be cleaned!

- *

- * @param cls client-defined closure

- * @param session handler for the closed SPDY session

- * @param by_client #SPDY_YES if the session close was initiated by the

- * 					client;

- * 		    #SPDY_NO if closed by the server

- */

-typedef void

-(*SPDY_SessionClosedCallback) (void *cls,

-                               struct SPDY_Session *session,

-                               int by_client);

-

-

-/**

- * Iterator over name-value pairs.

- *

- * @param cls client-defined closure

- * @param name of the pair

- * @param value of the pair

- * @return #SPDY_YES to continue iterating,

- *         #SPDY_NO to abort the iteration

- */

-typedef int

-(*SPDY_NameValueIterator) (void *cls,

-                           const char *name,

-                           const char * const * value,

-                           int num_values);

-

-

-/**

- * Callback for received SPDY request. The functions is called whenever

- * a reqest comes, but will also be called if more headers/trailers are

- * received.

- *

- * @param cls client-defined closure

- * @param request handler. The request object is required for

- * 			sending responses.

- * @param priority of the SPDY stream which the request was

- * 			sent over

- * @param method HTTP method

- * @param path HTTP path

- * @param version HTTP version just like in HTTP request/response:

- * 			"HTTP/1.0" or "HTTP/1.1" currently

- * @param host called host as in HTTP

- * @param scheme used ("http" or "https"). In SPDY 3 it is only "https".

- * @param headers other HTTP headers from the request

- * @param more a flag saying if more data related to the request is

- *        expected to be received. HTTP body may arrive (e.g. POST data);

- *        then SPDY_NewDataCallback will be called for the connection.

- *        It is also possible that more headers/trailers arrive;

- *        then the same callback will be invoked. The user should detect

- *        that it is not the first invocation of the function for that

- *        request.

- */

-typedef void

-(*SPDY_NewRequestCallback) (void *cls,

-                            struct SPDY_Request *request,

-                            uint8_t priority,

-                            const char *method,

-                            const char *path,

-                            const char *version,

-                            const char *host,

-                            const char *scheme,

-                            struct SPDY_NameValue *headers,

-                            bool more);

-

-

-/**

- * Callback for received new data chunk (HTTP body) from a given

- * request (e.g. POST data).

- *

- * @param cls client-defined closure

- * @param request handler

- * @param buf data chunk from the POST data

- * @param size the size of the data chunk 'buf' in bytes. Note that it

- *             may be 0.

- * @param more false if this is the last chunk from the data. Note:

- *             true does not mean that more data will come, exceptional

- *             situation is possible

- * @return #SPDY_YES to continue calling the function,

- *         #SPDY_NO to stop calling the function for this request

- */

-typedef int

-(*SPDY_NewDataCallback) (void *cls,

-                         struct SPDY_Request *request,

-                         const void *buf,

-                         size_t size,

-                         bool more);

-// How about passing POST encoding information

-// here as well?

-//TODO

-

-

-/**

- * Callback to be used with SPDY_build_response_with_callback. The

- * callback will be called when the lib wants to write to the TLS socket.

- * The application should provide the data to be sent.

- *

- * @param cls client-defined closure

- * @param max maximum number of bytes that are allowed to be written

- * 			to the buffer.

- * @param more true if more data will be sent (i.e. the function must

- * 				be calleed again),

- *             false if this is the last chunk, the lib will close

- * 				the stream

- * @return number of bytes written to buffer. On error the call MUST

- * 			return value less than 0 to indicate the library.

- */

-typedef ssize_t

-(*SPDY_ResponseCallback) (void *cls,

-                          void *buffer,

-                          size_t max,

-                          bool *more);

-

-

-/**

- * Callback to be called when the last bytes from the response was sent

- * to the client or when the response was discarded from the lib. This

- * callback is a very good place to discard the request and the response

- * objects, if they will not be reused (e.g., sending the same response

- * again). If the stream is closed it is safe to discard the request

- * object.

- *

- * @param cls client-defined closure

- * @param response handler to the response that was just sent

- * @param request handler to the request for which the response was sent

- * @param status shows if actually the response was sent or it was

- * 			discarded by the lib for any reason (e.g., closing session,

- * 			closing stream, stopping daemon, etc.). It is possible that

- * 			status indicates an error but parts of the response headers

- * 			and/or body (in one

- * 			or several frames) were already sent to the client.

- * @param streamopened indicates if the the stream for this request/

- * 			response pair is still opened. If yes, the server may want

- * 			to use SPDY push to send something additional to the client

- * 			and/or close the stream.

- */

-typedef void

-(*SPDY_ResponseResultCallback) (void * cls,

-                                struct SPDY_Response *response,

-                                struct SPDY_Request *request,

-                                enum SPDY_RESPONSE_RESULT status,

-                                bool streamopened);

-

-

-/**

- * Callback to notify when SPDY ping response is received.

- *

- * @param session handler for which the ping request was sent

- * @param rtt the timespan between sending ping request and receiving it

- * 			from the library

- */

-typedef void

-(*SPDY_PingCallback) (void * cls,

-                      struct SPDY_Session *session,

-                      struct timeval *rtt);

-

-

-/**

- * Iterator over settings ID/Value/Flags tuples.

- *

- * @param cls client-defined closure

- * @param id SPDY settings ID

- * @param value value for this setting

- * @param flags flags for this tuple; use

- * 			`enum SPDY_FLAG_SETTINGS`

- * @return #SPDY_YES to continue iterating,

- *         #SPDY_NO to abort the iteration

- */

-typedef int

-(*SPDY_SettingsIterator) (void *cls,

-                          enum SPDY_SETTINGS id,

-                          int32_t value,

-                          uint8_t flags);

-

-

-/**

- * Callback to notify when SPDY SETTINGS are received from the client.

- *

- * @param session handler for which settings are received

- * @param settings ID/value/flags tuples of the settings

- * @param flags for the whole settings frame; use

- * 			enum SPDY_FLAG_SETTINGS_FRAME

- * @param ... list of options (type-value pairs,

- *        terminated with #SPDY_SETTINGS_OPTION_END).

- */

-typedef void

-(*SPDY_SettingsReceivedCallback) (struct SPDY_Session *session,

-                                  struct SPDY_Settings *settings,

-                                  uint8_t flags,

-                                  ...);

-

-

-/* Global functions for the library */

-

-

-/**

- * Init function for the whole library. It MUST be called before any

- * other function of the library to initialize things like TLS context

- * and possibly other stuff needed by the lib. Currently the call

- * always returns #SPDY_YES.

- *

- * @param io_subsystem the IO subsystem that will

- *        be initialized. Several can be used with bitwise OR. If no

- *        parameter is set, the default openssl subsystem will be used.

- * @return #SPDY_YES if the library was correctly initialized and its

- * 			functions can be used now;

- * 			#SPDY_NO on error

- */

-_MHD_EXTERN int

-(SPDY_init) (enum SPDY_IO_SUBSYSTEM io_subsystem, ...);

-#define SPDY_init() SPDY_init (SPDY_IO_SUBSYSTEM_OPENSSL)

-

-

-/**

- * Deinit function for the whole lib. It can be called after finishing

- * using the library. It frees and cleans up resources allocated in

- * SPDY_init. Currently the function does not do anything.

- */

-_MHD_EXTERN void

-SPDY_deinit (void);

-

-

-/**

- * Sets the global error handler to a different implementation. "cb"

- * will only be called in the case of typically fatal, serious

- * internal consistency issues.  These issues should only arise in the

- * case of serious memory corruption or similar problems with the

- * architecture as well as failed assertions.  While "cb" is allowed to

- * return and the lib will then try to continue, this is never safe.

- *

- * The default implementation that is used if no panic function is set

- * simply prints an error message and calls "abort".  Alternative

- * implementations might call "exit" or other similar functions.

- *

- * @param cb new error handler

- * @param cls passed to error handler

- */

-_MHD_EXTERN void

-SPDY_set_panic_func (SPDY_PanicCallback cb,

-                     void *cls);

-

-

-/* Daemon functions */

-

-

-/**

- * Start a SPDY webserver on the given port.

- *

- * @param port to bind to. The value is ignored if address structure

- * 			is passed as daemon option

- * @param certfile path to the certificate that will be used by server

- * @param keyfile path to the keyfile for the certificate

- * @param nscb callback called when a new SPDY session is

- * 			established	by a client

- * @param sccb callback called when a session is closed

- * @param nrcb callback called when a client sends request

- * @param npdcb callback called when HTTP body (POST data) is received

- * 			after request

- * @param cls common extra argument to all of the callbacks

- * @param ... list of options (type-value pairs,

- *        terminated with #SPDY_DAEMON_OPTION_END).

- * @return NULL on error, handle to daemon on success

- */

-_MHD_EXTERN struct SPDY_Daemon *

-SPDY_start_daemon (uint16_t port,

-                   const char *certfile,

-                   const char *keyfile,

-                   SPDY_NewSessionCallback nscb,

-                   SPDY_SessionClosedCallback sccb,

-                   SPDY_NewRequestCallback nrcb,

-                   SPDY_NewDataCallback npdcb,

-                   void *cls,

-                   ...);

-

-

-/**

- * Shutdown the daemon. First all sessions are closed. It is NOT safe

- * to call this function in user callbacks.

- *

- * @param daemon to stop

- */

-_MHD_EXTERN void

-SPDY_stop_daemon (struct SPDY_Daemon *daemon);

-

-

-/**

- * Obtain the select sets for this daemon. Only those are retrieved,

- * which some processing should be done for, i.e. not all sockets are

- * added to write_fd_set.<p>

- *

- * It is possible that there is

- * nothing to be read from a socket but there is data either in the

- * TLS subsystem's read buffers or in libmicrospdy's read buffers, which

- * waits for being processed. In such case the file descriptor will be

- * added to write_fd_set. Since it is very likely for the socket to be

- * ready for writing, the select used in the application's event loop

- * will return with success, SPDY_run will be called, the data will be

- * processed and maybe something will be written to the socket. Without

- * this behaviour, considering a proper event loop, data may stay in the

- * buffers, but run is never called.

- *

- * @param daemon to get sets from

- * @param read_fd_set read set

- * @param write_fd_set write set

- * @param except_fd_set except set

- * @return largest FD added to any of the sets

- */

-_MHD_EXTERN int

-SPDY_get_fdset (struct SPDY_Daemon *daemon,

-                fd_set *read_fd_set,

-                fd_set *write_fd_set,

-                fd_set *except_fd_set);

-

-

-/**

- * Obtain timeout value for select for this daemon. The returned value

- * is how long select

- * should at most block, not the timeout value set for connections.

- *

- * @param daemon to query for timeout

- * @param timeout will be set to the timeout value (in milliseconds)

- * @return #SPDY_YES on success

- *         #SPDY_NO if no connections exist that

- * 			would necessiate the use of a timeout right now

- */

-_MHD_EXTERN int

-SPDY_get_timeout (struct SPDY_Daemon *daemon,

-                  unsigned long long *timeout);

-

-

-/**

- * Run webserver operations. This method must be called in

- * the client event loop.

- *

- * @param daemon to run

- */

-_MHD_EXTERN void

-SPDY_run (struct SPDY_Daemon *daemon);

-

-

-/* SPDY Session handling functions */

-

-

-/**

- * Closes a SPDY session. SPDY clients and servers are expected to keep

- * sessions opened as long as possible. However, the server may want to

- * close some connections, e.g. if there are too many, to free some

- * resources. The function can also be used to close a specific session

- * if the client is not desired.

- *

- * @param session handler to be closed

- */

-_MHD_EXTERN void

-SPDY_close_session (struct SPDY_Session * session);

-

-

-/**

- * Associate a void pointer with a session. The data accessible by the

- * pointer can later be used wherever the session handler is available.

- *

- * @param session handler

- * @param cls any data pointed by a pointer to be accessible later

- */

-_MHD_EXTERN void

-SPDY_set_cls_to_session (struct SPDY_Session *session,

-                         void *cls);

-

-

-/**

- * Retrieves the pointer associated with SPDY_set_cls_to_session().

- *

- * @param session handler to get its cls

- * @return same pointer added by SPDY_set_cls_to_session() or

- * 			NULL when nothing was associated

- */

-_MHD_EXTERN void *

-SPDY_get_cls_from_session (struct SPDY_Session *session);

-

-

-/**

- * Retrieves the remote address of a given session.

- *

- * @param session handler to get its remote address

- * @param addr out parameter; pointing to remote address

- * @return length of the address structure

- */

-_MHD_EXTERN socklen_t

-SPDY_get_remote_addr (struct SPDY_Session *session,

-                      struct sockaddr **addr);

-

-

-/* SPDY name/value data structure handling functions */

-

-

-/**

- * Create a new NameValue structure. It is needed for putting inside the

- * HTTP headers and their values for a response. The user should later

- * destroy alone the structure.

- *

- * @return handler to the new empty structure or NULL on error

- */

-_MHD_EXTERN struct SPDY_NameValue *

-SPDY_name_value_create (void);

-

-

-/**

- * Add name/value pair to a NameValue structure. SPDY_NO will be returned

- * if the name/value pair is already in the structure. It is legal to

- * add different values for the same name.

- *

- * @param container structure to which the new pair is added

- * @param name for the value. Null-terminated string.

- * @param value the value itself. Null-terminated string.

- * @return #SPDY_NO on error or #SPDY_YES on success

- */

-_MHD_EXTERN int

-SPDY_name_value_add (struct SPDY_NameValue *container,

-                     const char *name,

-                     const char *value);

-

-

-/**

- * Lookup value for a name in a name/value structure.

- *

- * @param container structure in which to lookup

- * @param name the name to look for

- * @param num_values length of the returned array with values

- * @return NULL if no such item was found, or an array containing the

- * 			values

- */

-_MHD_EXTERN const char * const *

-SPDY_name_value_lookup (struct SPDY_NameValue *container,

-                        const char *name,

-                        int *num_values);

-

-

-/**

- * Iterate over name/value structure.

- *

- * @param container structure which to iterate over

- * @param iterator callback to call on each name/value pair;

- *        maybe NULL (then just count headers)

- * @param iterator_cls extra argument to @a iterator

- * @return number of entries iterated over

- */

-_MHD_EXTERN int

-SPDY_name_value_iterate (struct SPDY_NameValue *container,

-                         SPDY_NameValueIterator iterator,

-                         void *iterator_cls);

-

-

-/**

- * Destroy a NameValue structure. Use this function to destroy only

- * objects which, after passed to, will not be destroied by other

- * functions.

- *

- */

-_MHD_EXTERN void

-SPDY_name_value_destroy (struct SPDY_NameValue *container);

-

-

-/* SPDY request handling functions */

-

-

-/**

- * Gets the session responsible for the given

- * request.

- *

- * @param request for which the session is wanted

- * @return session handler for the request

- */

-_MHD_EXTERN struct SPDY_Session *

-SPDY_get_session_for_request (const struct SPDY_Request *request);

-

-

-/**

- * Associate a void pointer with a request. The data accessible by the

- * pointer can later be used wherever the request handler is available.

- *

- * @param request with which to associate a pointer

- * @param cls any data pointed by a pointer to be accessible later

- */

-_MHD_EXTERN void

-SPDY_set_cls_to_request (struct SPDY_Request *request,

-                         void *cls);

-

-

-/**

- * Retrieves the pointer associated with the request by

- * SPDY_set_cls_to_request().

- *

- * @param request to get its cls

- * @return same pointer added by SPDY_set_cls_to_request() or

- * 			NULL when nothing was associated

- */

-_MHD_EXTERN void *

-SPDY_get_cls_from_request (struct SPDY_Request *request);

-

-

-/* SPDY response handling functions */

-

-

-/**

- * Create response object containing all needed headers and data. The

- * response object is not bound to a request, so it can be used multiple

- * times with SPDY_queue_response() and schould be

- * destroied by calling the SPDY_destroy_response().<p>

- *

- * Currently the library does not provide compression of the body data.

- * It is up to the user to pass already compressed data and the

- * appropriate headers to this function when desired.

- *

- * @param status HTTP status code for the response (e.g. 404)

- * @param statustext HTTP status message for the response, which will

- * 			be appended to the status code (e.g. "OK"). Can be NULL

- * @param version HTTP version for the response (e.g. "http/1.1")

- * @param headers name/value structure containing additional HTTP headers.

- *                Can be NULL. Can be used multiple times, it is up to

- *                the user to destoy the object when not needed anymore.

- * @param data the body of the response. The lib will make a copy of it,

- *             so it is up to the user to take care of the memory

- *             pointed by data

- * @param size length of @a data. It can be 0, then the lib will send only

- * 				headers

- * @return NULL on error, handle to response object on success

- */

-_MHD_EXTERN struct SPDY_Response *

-SPDY_build_response (int status,

-                     const char *statustext,

-                     const char *version,

-                     struct SPDY_NameValue *headers,

-                     const void *data,

-                     size_t size);

-

-

-/**

- * Create response object containing all needed headers. The data will

- * be provided later when the lib calls the callback function (just

- * before writing it to the TLS socket). The

- * response object is not bound to a request, so it can be used multiple

- * times with SPDY_queue_response() and schould be

- * destroied by calling the SPDY_destroy_response().<p>

- *

- * Currently the library does not provide compression of the body data.

- * It is up to the user to pass already compressed data and the

- * appropriate headers to this function and the callback when desired.

- *

- * @param status HTTP status code for the response (e.g. 404)

- * @param statustext HTTP status message for the response, which will

- * 			be appended to the status code (e.g. "OK"). Can be NULL

- * @param version HTTP version for the response (e.g. "http/1.1")

- * @param headers name/value structure containing additional HTTP headers.

- *                Can be NULL. Can be used multiple times, it is up to

- *                the user to destoy the object when not needed anymore.

- * @param rcb callback to use to obtain response data

- * @param rcb_cls extra argument to @a rcb

- * @param block_size preferred block size for querying rcb (advisory only,

- *                   the lib will call rcb specifying the block size); clients

- *                   should pick a value that is appropriate for IO and

- *                   memory performance requirements. The function will

- *                   fail if the value is bigger than the maximum

- *                   supported value (SPDY_MAX_SUPPORTED_FRAME_SIZE).

- *                   Can be 0, then the lib will use

- *                   #SPDY_MAX_SUPPORTED_FRAME_SIZE instead.

- * @return NULL on error, handle to response object on success

- */

-_MHD_EXTERN struct SPDY_Response *

-SPDY_build_response_with_callback(int status,

-                                  const char *statustext,

-                                  const char *version,

-                                  struct SPDY_NameValue *headers,

-                                  SPDY_ResponseCallback rcb,

-                                  void *rcb_cls,

-                                  uint32_t block_size);

-

-

-/**

- * Queue response object to be sent to the client. A successfully queued

- * response may never be sent, e.g. when the stream gets closed. The

- * data will be added to the output queue. The call will fail, if the

- * output for this session

- * is closed (i.e. the session is closed, half or full) or the output

- * channel for the stream, on which the request was received, is closed

- * (i.e. the stream is closed, half or full).

- *

- * @param request object identifying the request to which the

- * 			response is returned

- * @param response object containg headers and data to be sent

- * @param closestream TRUE if the server does NOT intend to PUSH

- * 			something more associated to this request/response later,

- * 			FALSE otherwise

- * @param consider_priority if FALSE, the response will be added to the

- * 			end of the queue. If TRUE, the response will be added after

- * 			the last previously added response with priority of the

- * 			request grater or equal to that of the current one. This

- * 			means that the function should be called with TRUE each time

- * 			if one wants to be sure that the output queue behaves like

- * 			a priority queue

- * @param rrcb callback called when all the data was sent (last frame

- * 			from response) or when that frame was discarded (e.g. the

- * 			stream has been closed meanwhile)

- * @param rrcb_cls extra argument to @a rrcb

- * @return #SPDY_NO on error or #SPDY_YES on success

- */

-_MHD_EXTERN int

-SPDY_queue_response (struct SPDY_Request *request,

-                     struct SPDY_Response *response,

-                     bool closestream,

-                     bool consider_priority,

-                     SPDY_ResponseResultCallback rrcb,

-                     void *rrcb_cls);

-

-

-/**

- * Destroy a response structure. It should be called for all objects

- * returned by SPDY_build_response*() functions to free the memory

- * associated with the prepared response. It is safe to call this

- * function not before being sure that the response will not be used by

- * the lib anymore, this means after SPDY_ResponseResultCallback

- * callbacks were called for all calls to SPDY_queue_response() passing

- * this response.

- *

- * @param response to destroy

- */

-_MHD_EXTERN void

-SPDY_destroy_response (struct SPDY_Response *response);

-

-

-/* SPDY settings ID/value data structure handling functions */

-

-

-/**

- * Create a new SettingsIDValue structure. It is needed for putting

- * inside tuples of SPDY option, flags and value for sending to the

- * client.

- *

- * @return hendler to the new empty structure or NULL on error

- */

-_MHD_EXTERN const struct SPDY_Settings *

-SPDY_settings_create (void);

-

-

-/**

- * Add or update a tuple to a SettingsIDValue structure.

- *

- * @param container structure to which the new tuple is added

- * @param id SPDY settings ID that will be sent. If this ID already in

- *           container, the tupple for it will be updated (value and/or

- *           flags). If it is not in the container, a new tupple will be

- *           added.

- * @param flags SPDY settings flags applied only to this setting

- * @param value of the setting

- * @return #SPDY_NO on error

- * 			or #SPDY_YES if a new setting was added

- */

-_MHD_EXTERN int

-SPDY_settings_add (struct SPDY_Settings *container,

-                   enum SPDY_SETTINGS id,

-                   enum SPDY_FLAG_SETTINGS flags,

-                   int32_t value);

-

-

-/**

- * Lookup value and flags for an ID in a settings ID/value structure.

- *

- * @param container structure in which to lookup

- * @param id SPDY settings ID to search for

- * @param flags out param for SPDY settings flags for this setting;

- * 			check it against the flags in enum SPDY_FLAG_SETTINGS

- * @param value out param for the value of this setting

- * @return #SPDY_NO if the setting is not into the structure

- * 			or #SPDY_YES if it is into it

- */

-_MHD_EXTERN int

-SPDY_settings_lookup (const struct SPDY_Settings *container,

-                      enum SPDY_SETTINGS id,

-                      enum SPDY_FLAG_SETTINGS *flags,

-                      int32_t *value);

-

-

-/**

- * Iterate over settings ID/value structure.

- *

- * @param container structure which to iterate over

- * @param iterator callback to call on each ID/value pair;

- *        maybe NULL (then just count number of settings)

- * @param iterator_cls extra argument to iterator

- * @return number of entries iterated over

- */

-_MHD_EXTERN int

-SPDY_settings_iterate (const struct SPDY_Settings *container,

-                       SPDY_SettingsIterator iterator,

-                       void *iterator_cls);

-

-

-/**

- * Destroy a settings ID/value structure. Use this function to destroy

- * only objects which, after passed to, will not be destroied by other

- * functions.

- *

- * @param container structure which to detroy

- */

-_MHD_EXTERN void

-SPDY_settings_destroy (struct SPDY_Settings * container);

-

-

-/* SPDY SETTINGS handling functions */

-

-

-/**

- * Send SPDY SETTINGS to the client. The call will return fail if there

- * in invald setting into the settings container (e.g. invalid setting

- * ID).

- *

- * @param session SPDY_Session handler for which settings are being sent

- * @param settings ID/value pairs of the settings to be sent.

- * 			Can be used multiple times, it is up to the user to destoy

- * 			the object when not needed anymore.

- * @param flags for the whole settings frame. They are valid for all tuples

- * @param ... list of options (type-value pairs,

- *        terminated with #SPDY_SETTINGS_OPTION_END).

- * @return SPDY_NO on error or SPDY_YES on

- * 			success

- */

-_MHD_EXTERN int

-SPDY_send_settings (struct SPDY_Session *session,

-                    struct SPDY_Settings *settings,

-                    enum SPDY_FLAG_SETTINGS_FRAME flags,

-                    ...);

-

-

-/* SPDY misc functions */

-

-

-/**

- * Destroy a request structure. It should be called for all objects

- * received as a parameter in SPDY_NewRequestCallback to free the memory

- * associated with the request. It is safe to call this

- * function not before being sure that the request will not be used by

- * the lib anymore, this means after the stream, on which this request

- * had been sent, was closed and all SPDY_ResponseResultCallback

- * callbacks were called for all calls to SPDY_queue_response() passing

- * this request object.

- *

- * @param request to destroy

- */

-_MHD_EXTERN void

-SPDY_destroy_request (struct SPDY_Request * request);

-

-

-/**

- * Send SPDY ping to the client

- *

- * @param session handler for which the ping request is sent

- * @param rttcb callback called when ping response to the request is

- * 			received

- * @param rttcb_cls extra argument to @a rttcb

- * @return #SPDY_NO on error or #SPDY_YES on success

- */

-_MHD_EXTERN int

-SPDY_send_ping (struct SPDY_Session *session,

-                SPDY_PingCallback rttcb,

-                void *rttcb_cls);

-

-#endif

diff --git a/src/include/platform.h b/src/include/platform.h
index 22ddddd..1db1e4e 100644
--- a/src/include/platform.h
+++ b/src/include/platform.h
@@ -34,52 +34,12 @@
 #ifndef MHD_PLATFORM_H
 #define MHD_PLATFORM_H
 
-#include "MHD_config.h"
-
-#ifndef BUILDING_MHD_LIB
-#ifdef _MHD_EXTERN
-#undef _MHD_EXTERN
-#endif /* _MHD_EXTERN */
-#if defined(_WIN32) && defined(MHD_W32LIB)
-#define _MHD_EXTERN extern
-#elif defined (_WIN32) && defined(MHD_W32DLL)
-#define _MHD_EXTERN __declspec(dllimport) 
-#else
-#define _MHD_EXTERN extern
-#endif
-#elif !defined(_MHD_EXTERN) /* && BUILDING_MHD_LIB */
-#if defined(_WIN32) && defined(MHD_W32LIB)
-#define _MHD_EXTERN extern
-#elif defined (_WIN32) && defined(MHD_W32DLL)
-#define _MHD_EXTERN extern __declspec(dllexport) 
-#else
-#define _MHD_EXTERN extern
-#endif
-#endif /* BUILDING_MHD_LIB */
-
-#define _XOPEN_SOURCE_EXTENDED  1
-#if OS390
-#define _OPEN_THREADS
-#define _OPEN_SYS_SOCK_IPV6
-#define _OPEN_MSGQ_EXT
-#define _LP64
-#endif
-
-#if defined(_WIN32)
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0501
-#else // _WIN32_WINNT
-#if _WIN32_WINNT < 0x0501
-#error "Headers for Windows XP or later are required"
-#endif // _WIN32_WINNT < 0x0501
-#endif // _WIN32_WINNT
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN 1
-#endif /* !WIN32_LEAN_AND_MEAN */
-#endif // _WIN32
+#include "mhd_options.h"
 
 #include <stdio.h>
+#ifdef HAVE_STDLIB_H
 #include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
 #include <stdint.h>
 #include <string.h>
 #ifdef HAVE_UNISTD_H
@@ -89,12 +49,9 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <signal.h>
+#ifdef HAVE_STDDEF_H
 #include <stddef.h>
-#ifdef MHD_USE_POSIX_THREADS
-#undef HAVE_CONFIG_H
-#include <pthread.h>
-#define HAVE_CONFIG_H 1
-#endif // MHD_USE_POSIX_THREADS
+#endif /* HAVE_STDDEF_H */
 
 /* different OSes have fd_set in
    a broad range of header files;
@@ -102,102 +59,76 @@
    are available) */
 
 
-#ifdef OS_VXWORKS
-#include <sockLib.h>
-#include <netinet/in.h>
+#if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS)
 #include <stdarg.h>
 #include <sys/mman.h>
-#define RESTRICT __restrict__
-#endif
-#if HAVE_MEMORY_H
+#ifdef HAVE_SOCKLIB_H
+#include <sockLib.h>
+#endif /* HAVE_SOCKLIB_H */
+#ifdef HAVE_INETLIB_H
+#include <inetLib.h>
+#endif /* HAVE_INETLIB_H */
+#endif /* __VXWORKS__ */
+
+#ifdef HAVE_MEMORY_H
 #include <memory.h>
 #endif
 
-#if HAVE_SYS_SELECT_H
+#ifdef HAVE_SYS_SELECT_H
 #include <sys/select.h>
 #endif
-#if HAVE_SYS_TYPES_H
+#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
-#if HAVE_SYS_TIME_H
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
-#if HAVE_SYS_STAT_H
+#ifdef HAVE_SYS_STAT_H
 #include <sys/stat.h>
 #endif
-#if HAVE_SYS_MSG_H
+#ifdef HAVE_SYS_MSG_H
 #include <sys/msg.h>
 #endif
-#if HAVE_SYS_MMAN_H
+#ifdef HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #endif
-#if HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#if HAVE_NETINET_IN_H
-#include <netinet/in.h>
-#endif
-#if HAVE_TIME_H
+#ifdef HAVE_TIME_H
 #include <time.h>
 #endif
-#if HAVE_SYS_SOCKET_H
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-#if HAVE_ARPA_INET_H
-#include <arpa/inet.h>
-#endif
-
-
-#if defined(_WIN32) && !defined(__CYGWIN__)
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#ifndef WIN32_LEAN_AND_MEAN
+/* Do not include unneeded parts of W32 headers. */
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <winsock2.h>
 #include <ws2tcpip.h>
-#define sleep(seconds) (SleepEx((seconds)*1000, 1)/1000)
-#define usleep(useconds) (void)SleepEx((useconds)/1000, 1)
+#endif /* _WIN32 && !__CYGWIN__ */
+
+#if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET)
+/* Do not define __USE_W32_SOCKETS under Cygwin! */
+#error Cygwin with winsock fd_set is not supported
 #endif
 
-#if !defined(SHUT_WR) && defined(SD_SEND)
-#define SHUT_WR SD_SEND
-#endif
-#if !defined(SHUT_RD) && defined(SD_RECEIVE)
-#define SHUT_RD SD_RECEIVE
-#endif
-#if !defined(SHUT_RDWR) && defined(SD_BOTH)
-#define SHUT_RDWR SD_BOTH
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#define sleep(seconds) ((SleepEx ((seconds) * 1000, 1)==0) ? 0 : (seconds))
+#define usleep(useconds) ((SleepEx ((useconds) / 1000, 1)==0) ? 0 : -1)
 #endif
 
-#if defined(_MSC_FULL_VER) && !defined (_SSIZE_T_DEFINED)
+#if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED)
 #define _SSIZE_T_DEFINED
 typedef intptr_t ssize_t;
-#endif // !_SSIZE_T_DEFINED */
-#ifndef MHD_SOCKET_DEFINED
-/**
- * MHD_socket is type for socket FDs
- */
-#if !defined(_WIN32) || defined(_SYS_TYPES_FD_SET)
-#define MHD_POSIX_SOCKETS 1
-typedef int MHD_socket;
-#define MHD_INVALID_SOCKET (-1)
-#else /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */
-#define MHD_WINSOCK_SOCKETS 1
-#include <winsock2.h>
-typedef SOCKET MHD_socket;
-#define MHD_INVALID_SOCKET (INVALID_SOCKET)
-#endif /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */
-#define MHD_SOCKET_DEFINED 1
-#endif /* MHD_SOCKET_DEFINED */
+#endif /* !_SSIZE_T_DEFINED */
 
-/* Force don't use pipes on W32 */
-#if defined(_WIN32) && !defined(MHD_DONT_USE_PIPES)
-#define MHD_DONT_USE_PIPES 1
-#endif /* defined(_WIN32) && !defined(MHD_DONT_USE_PIPES) */
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+typedef time_t _MHD_TIMEVAL_TV_SEC_TYPE;
+#else  /* _WIN32 && ! __CYGWIN__ */
+typedef long _MHD_TIMEVAL_TV_SEC_TYPE;
+#endif /* _WIN32 && ! __CYGWIN__ */
 
-/* MHD_pipe is type for pipe FDs*/
-#ifndef MHD_DONT_USE_PIPES
-typedef int MHD_pipe;
-#else /* ! MHD_DONT_USE_PIPES */
-typedef MHD_socket MHD_pipe;
-#endif /* ! MHD_DONT_USE_PIPES */
-
-#if !defined(IPPROTO_IPV6) && defined(_MSC_FULL_VER) && _WIN32_WINNT >= 0x0501
+#if ! defined(IPPROTO_IPV6) && defined(_MSC_FULL_VER) && _WIN32_WINNT >= 0x0501
 /* VC use IPPROTO_IPV6 as part of enum */
 #define IPPROTO_IPV6 IPPROTO_IPV6
 #endif
diff --git a/src/include/platform_interface.h b/src/include/platform_interface.h
deleted file mode 100644
index 9e63f7a..0000000
--- a/src/include/platform_interface.h
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
-  This file is part of libmicrohttpd
-  Copyright (C) 2014 Karlson2k (Evgeny Grin)
-
-  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 2.1 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/>.
-*/
-
-/**
- * @file include/platform_interface.h
- * @brief  internal platform abstraction functions
- * @author Karlson2k (Evgeny Grin)
- */
-
-#ifndef MHD_PLATFORM_INTERFACE_H
-#define MHD_PLATFORM_INTERFACE_H
-
-#include "platform.h"
-#if defined(_WIN32) && !defined(__CYGWIN__)
-#include "w32functions.h"
-#endif
-
-/* ***************************** 
-     General function mapping 
-   *****************************/
-#if !defined(_WIN32) || defined(__CYGWIN__)
-/**
- * Check two strings case-insensitive equality
- * @param a first string to check
- * @param b second string to check
- * @return boolean true if strings are equal, boolean false if strings are unequal
- */
-#define MHD_str_equal_caseless_(a,b) (0==strcasecmp((a),(b)))
-#else
-/**
- * Check two strings case-insensitive equality
- * @param a first string to check
- * @param b second string to check
- * @return boolean true if strings are equal, boolean false if strings are unequal
- */
-#define MHD_str_equal_caseless_(a,b) (0==_stricmp((a),(b)))
-#endif
-
-#if !defined(_WIN32) || defined(__CYGWIN__)
-/**
- * Check not more than n chars in two strings case-insensitive equality
- * @param a first string to check
- * @param b second string to check
- * @param n maximum number of chars to check
- * @return boolean true if strings are equal, boolean false if strings are unequal
- */
-#define MHD_str_equal_caseless_n_(a,b,n) (0==strncasecmp((a),(b),(n)))
-#else
-/**
- * Check not more than n chars in two strings case-insensitive equality
- * @param a first string to check
- * @param b second string to check
- * @param n maximum number of chars to check
- * @return boolean true if strings are equal, boolean false if strings are unequal
- */
-#define MHD_str_equal_caseless_n_(a,b,n) (0==_strnicmp((a),(b),(n)))
-#endif
-
-/* Platform-independent snprintf name */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_snprintf_ snprintf
-#else
-#define MHD_snprintf_ W32_snprintf
-#endif
-
-
-
-/* MHD_socket_close_(fd) close any FDs (non-W32) / close only socket FDs (W32) */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_socket_close_(fd) close((fd))
-#else
-#define MHD_socket_close_(fd) closesocket((fd))
-#endif
-
-/* MHD_socket_errno_ is errno of last function (non-W32) / errno of last socket function (W32) */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_socket_errno_ errno
-#else
-#define MHD_socket_errno_ MHD_W32_errno_from_winsock_()
-#endif
-
-/* MHD_socket_last_strerr_ is description string of last errno (non-W32) /
- *                            description string of last socket error (W32) */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_socket_last_strerr_() strerror(errno)
-#else
-#define MHD_socket_last_strerr_() MHD_W32_strerror_last_winsock_()
-#endif
-
-/* MHD_strerror_ is strerror (both non-W32/W32) */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_strerror_(errnum) strerror((errnum))
-#else
-#define MHD_strerror_(errnum) MHD_W32_strerror_((errnum))
-#endif
-
-/* MHD_set_socket_errno_ set errno to errnum (non-W32) / set socket last error to errnum (W32) */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_set_socket_errno_(errnum) errno=(errnum)
-#else
-#define MHD_set_socket_errno_(errnum) MHD_W32_set_last_winsock_error_((errnum))
-#endif
-
-/* MHD_SYS_select_ is wrapper macro for system select() function */
-#if !defined(MHD_WINSOCK_SOCKETS)
-#define MHD_SYS_select_(n,r,w,e,t) select((n),(r),(w),(e),(t))
-#else
-#define MHD_SYS_select_(n,r,w,e,t) select((int)0,(r),(w),(e),(t))
-#endif
-
-#if defined(HAVE_POLL)
-/* MHD_sys_poll_ is wrapper macro for system poll() function */
-#if !defined(MHD_WINSOCK_SOCKETS)
-#define MHD_sys_poll_ poll
-#else  /* MHD_WINSOCK_SOCKETS */
-#define MHD_sys_poll_ WSAPoll
-#endif /* MHD_WINSOCK_SOCKETS */
-#endif /* HAVE_POLL */
-
-/* MHD_pipe_ create pipe (!MHD_DONT_USE_PIPES) /
- *           create two connected sockets (MHD_DONT_USE_PIPES) */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_pipe_(fdarr) pipe((fdarr))
-#else /* MHD_DONT_USE_PIPES */
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_pipe_(fdarr) socketpair(AF_LOCAL, SOCK_STREAM, 0, (fdarr))
-#else /* !defined(_WIN32) || defined(__CYGWIN__) */
-#define MHD_pipe_(fdarr) MHD_W32_pair_of_sockets_((fdarr))
-#endif /* !defined(_WIN32) || defined(__CYGWIN__) */
-#endif /* MHD_DONT_USE_PIPES */
-
-/* MHD_pipe_errno_ is errno of last function (!MHD_DONT_USE_PIPES) /
- *                    errno of last emulated pipe function (MHD_DONT_USE_PIPES) */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_pipe_errno_ errno
-#else
-#define MHD_pipe_errno_ MHD_socket_errno_
-#endif
-
-/* MHD_pipe_last_strerror_ is description string of last errno (!MHD_DONT_USE_PIPES) /
- *                            description string of last pipe error (MHD_DONT_USE_PIPES) */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_pipe_last_strerror_() strerror(errno)
-#else
-#define MHD_pipe_last_strerror_() MHD_socket_last_strerr_()
-#endif
-
-/* MHD_pipe_write_ write data to real pipe (!MHD_DONT_USE_PIPES) /
- *                 write data to emulated pipe (MHD_DONT_USE_PIPES) */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_pipe_write_(fd, ptr, sz) write((fd), (const void*)(ptr), (sz))
-#else
-#define MHD_pipe_write_(fd, ptr, sz) send((fd), (const char*)(ptr), (sz), 0)
-#endif
-
-/* MHD_pipe_read_ read data from real pipe (!MHD_DONT_USE_PIPES) /
- *                read data from emulated pipe (MHD_DONT_USE_PIPES) */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_pipe_read_(fd, ptr, sz) read((fd), (void*)(ptr), (sz))
-#else
-#define MHD_pipe_read_(fd, ptr, sz) recv((fd), (char*)(ptr), (sz), 0)
-#endif
-
-/* MHD_pipe_close_(fd) close any FDs (non-W32) /
- *                     close emulated pipe FDs (W32) */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_pipe_close_(fd) close((fd))
-#else
-#define MHD_pipe_close_(fd) MHD_socket_close_((fd))
-#endif
-
-/* MHD_INVALID_PIPE_ is a value of bad pipe FD */
-#ifndef MHD_DONT_USE_PIPES
-#define MHD_INVALID_PIPE_ (-1)
-#else
-#define MHD_INVALID_PIPE_ MHD_INVALID_SOCKET
-#endif
-
-#if !defined(_WIN32) || defined(__CYGWIN__)
-#define MHD_random_() random()
-#else
-#define MHD_random_() MHD_W32_random_()
-#endif
-
-#if defined(MHD_USE_POSIX_THREADS)
-typedef pthread_t MHD_thread_handle_;
-#elif defined(MHD_USE_W32_THREADS)
-#include <windows.h>
-typedef HANDLE MHD_thread_handle_;
-#else
-#error "No threading API is available."
-#endif
-
-#if defined(MHD_USE_POSIX_THREADS)
-#define MHD_THRD_RTRN_TYPE_ void*
-#define MHD_THRD_CALL_SPEC_
-#elif defined(MHD_USE_W32_THREADS)
-#define MHD_THRD_RTRN_TYPE_ unsigned
-#define MHD_THRD_CALL_SPEC_ __stdcall
-#endif
-
-#if defined(MHD_USE_POSIX_THREADS)
-/**
- * Wait until specified thread is ended
- * @param thread ID to watch
- * @return zero on success, nonzero on failure
- */
-#define MHD_join_thread_(thread) pthread_join((thread), NULL)
-#elif defined(MHD_USE_W32_THREADS)
-/**
- * Wait until specified thread is ended
- * Close thread handle on success
- * @param thread handle to watch
- * @return zero on success, nonzero on failure
- */
-#define MHD_join_thread_(thread) (WAIT_OBJECT_0 == WaitForSingleObject((thread), INFINITE) ? (CloseHandle((thread)), 0) : 1 )
-#endif
-
-#if defined(MHD_USE_W32_THREADS)
-#define MHD_W32_MUTEX_ 1
-#include <windows.h>
-typedef CRITICAL_SECTION MHD_mutex_;
-#elif defined(HAVE_PTHREAD_H) && defined(MHD_USE_POSIX_THREADS)
-#define MHD_PTHREAD_MUTEX_ 1
-typedef pthread_mutex_t MHD_mutex_;
-#else
-#error "No base mutex API is available."
-#endif
-
-#if defined(MHD_PTHREAD_MUTEX_)
-/**
- * Create new mutex.
- * @param mutex pointer to the mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_create_(mutex) \
-  ((0 == pthread_mutex_init ((mutex), NULL)) ? MHD_YES : MHD_NO)
-#elif defined(MHD_W32_MUTEX_)
-/**
- * Create new mutex.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_create_(mutex) \
-  ((NULL != (mutex) && 0 != InitializeCriticalSectionAndSpinCount((mutex),2000)) ? MHD_YES : MHD_NO)
-#endif
-
-#if defined(MHD_PTHREAD_MUTEX_)
-/**
- * Destroy previously created mutex.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_destroy_(mutex) \
-  ((0 == pthread_mutex_destroy ((mutex))) ? MHD_YES : MHD_NO)
-#elif defined(MHD_W32_MUTEX_)
-/**
- * Destroy previously created mutex.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_destroy_(mutex) \
-  ((NULL != (mutex)) ? (DeleteCriticalSection(mutex), MHD_YES) : MHD_NO)
-#endif
-
-#if defined(MHD_PTHREAD_MUTEX_)
-/**
- * Acquire lock on previously created mutex.
- * If mutex was already locked by other thread, function
- * blocks until mutex becomes available.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_lock_(mutex) \
-  ((0 == pthread_mutex_lock((mutex))) ? MHD_YES : MHD_NO)
-#elif defined(MHD_W32_MUTEX_)
-/**
- * Acquire lock on previously created mutex.
- * If mutex was already locked by other thread, function
- * blocks until mutex becomes available.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_lock_(mutex) \
-  ((NULL != (mutex)) ? (EnterCriticalSection((mutex)), MHD_YES) : MHD_NO)
-#endif
-
-#if defined(MHD_PTHREAD_MUTEX_)
-/**
- * Try to acquire lock on previously created mutex.
- * Function returns immediately.
- * @param mutex pointer to mutex
- * @return #MHD_YES if mutex is locked, #MHD_NO if
- * mutex was not locked.
- */
-#define MHD_mutex_trylock_(mutex) \
-  ((0 == pthread_mutex_trylock((mutex))) ? MHD_YES : MHD_NO)
-#elif defined(MHD_W32_MUTEX_)
-/**
- * Try to acquire lock on previously created mutex.
- * Function returns immediately.
- * @param mutex pointer to mutex
- * @return #MHD_YES if mutex is locked, #MHD_NO if
- * mutex was not locked.
- */
-#define MHD_mutex_trylock_(mutex) \
-  ((NULL != (mutex) && 0 != TryEnterCriticalSection ((mutex))) ? MHD_YES : MHD_NO)
-#endif
-
-#if defined(MHD_PTHREAD_MUTEX_)
-/**
- * Unlock previously created and locked mutex.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_unlock_(mutex) \
-  ((0 == pthread_mutex_unlock((mutex))) ? MHD_YES : MHD_NO)
-#elif defined(MHD_W32_MUTEX_)
-/**
- * Unlock previously created and locked mutex.
- * @param mutex pointer to mutex
- * @return #MHD_YES on success, #MHD_NO on failure
- */
-#define MHD_mutex_unlock_(mutex) \
-  ((NULL != (mutex)) ? (LeaveCriticalSection((mutex)), MHD_YES) : MHD_NO)
-#endif
-
-#endif // MHD_PLATFORM_INTERFACE_H
diff --git a/src/include/w32functions.h b/src/include/w32functions.h
deleted file mode 100644
index a86c4b2..0000000
--- a/src/include/w32functions.h
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
-  This file is part of libmicrohttpd
-  Copyright (C) 2014 Karlson2k (Evgeny Grin)
-
-  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 2.1 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/>.
-*/
-
-/**
- * @file include/w32functions.h
- * @brief  internal functions for W32 systems
- * @author Karlson2k (Evgeny Grin)
- */
-
-#ifndef MHD_W32FUNCTIONS_H
-#define MHD_W32FUNCTIONS_H
-#ifndef _WIN32
-#error w32functions.h is designed only for W32 systems
-#endif
-
-#include "platform.h"
-#include <errno.h>
-#include <winsock2.h>
-#include "platform_interface.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-#define MHDW32ERRBASE 3300
-
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK (MHDW32ERRBASE+1)
-#endif
-#ifndef EINPROGRESS
-#define EINPROGRESS (MHDW32ERRBASE+2)
-#endif
-#ifndef EALREADY
-#define EALREADY (MHDW32ERRBASE+3)
-#endif
-#ifndef ENOTSOCK
-#define ENOTSOCK (MHDW32ERRBASE+4)
-#endif
-#ifndef EDESTADDRREQ
-#define EDESTADDRREQ (MHDW32ERRBASE+5)
-#endif
-#ifndef EMSGSIZE
-#define EMSGSIZE (MHDW32ERRBASE+6)
-#endif
-#ifndef EPROTOTYPE
-#define EPROTOTYPE (MHDW32ERRBASE+7)
-#endif
-#ifndef ENOPROTOOPT
-#define ENOPROTOOPT (MHDW32ERRBASE+8)
-#endif
-#ifndef EPROTONOSUPPORT
-#define EPROTONOSUPPORT (MHDW32ERRBASE+9)
-#endif
-#ifndef EOPNOTSUPP
-#define EOPNOTSUPP (MHDW32ERRBASE+10)
-#endif
-#ifndef EAFNOSUPPORT
-#define EAFNOSUPPORT (MHDW32ERRBASE+11)
-#endif
-#ifndef EADDRINUSE
-#define EADDRINUSE (MHDW32ERRBASE+12)
-#endif
-#ifndef EADDRNOTAVAIL
-#define EADDRNOTAVAIL (MHDW32ERRBASE+13)
-#endif
-#ifndef ENETDOWN
-#define ENETDOWN (MHDW32ERRBASE+14)
-#endif
-#ifndef ENETUNREACH
-#define ENETUNREACH (MHDW32ERRBASE+15)
-#endif
-#ifndef ENETRESET
-#define ENETRESET (MHDW32ERRBASE+16)
-#endif
-#ifndef ECONNABORTED
-#define ECONNABORTED (MHDW32ERRBASE+17)
-#endif
-#ifndef ECONNRESET
-#define ECONNRESET (MHDW32ERRBASE+18)
-#endif
-#ifndef ENOBUFS
-#define ENOBUFS (MHDW32ERRBASE+19)
-#endif
-#ifndef EISCONN
-#define EISCONN (MHDW32ERRBASE+20)
-#endif
-#ifndef ENOTCONN
-#define ENOTCONN (MHDW32ERRBASE+21)
-#endif
-#ifndef ETOOMANYREFS
-#define ETOOMANYREFS (MHDW32ERRBASE+22)
-#endif
-#ifndef ECONNREFUSED
-#define ECONNREFUSED (MHDW32ERRBASE+23)
-#endif
-#ifndef ELOOP
-#define ELOOP (MHDW32ERRBASE+24)
-#endif
-#ifndef EHOSTDOWN
-#define EHOSTDOWN (MHDW32ERRBASE+25)
-#endif
-#ifndef EHOSTUNREACH
-#define EHOSTUNREACH (MHDW32ERRBASE+26)
-#endif
-#ifndef EPROCLIM
-#define EPROCLIM (MHDW32ERRBASE+27)
-#endif
-#ifndef EUSERS
-#define EUSERS (MHDW32ERRBASE+28)
-#endif
-#ifndef EDQUOT
-#define EDQUOT (MHDW32ERRBASE+29)
-#endif
-#ifndef ESTALE
-#define ESTALE (MHDW32ERRBASE+30)
-#endif
-#ifndef EREMOTE
-#define EREMOTE (MHDW32ERRBASE+31)
-#endif
-#ifndef ESOCKTNOSUPPORT
-#define ESOCKTNOSUPPORT (MHDW32ERRBASE+32)
-#endif
-#ifndef EPFNOSUPPORT
-#define EPFNOSUPPORT (MHDW32ERRBASE+33)
-#endif
-#ifndef ESHUTDOWN
-#define ESHUTDOWN (MHDW32ERRBASE+34)
-#endif
-#ifndef ENODATA
-#define ENODATA (MHDW32ERRBASE+35)
-#endif
-#ifndef ETIMEDOUT
-#define ETIMEDOUT (MHDW32ERRBASE+36)
-#endif
-
-/**
- * Return errno equivalent of last winsock error
- * @return errno equivalent of last winsock error
- */
-int MHD_W32_errno_from_winsock_(void);
-
-/**
- * Return pointer to string description of errnum error
- * Works fine with both standard errno errnums
- * and errnums from MHD_W32_errno_from_winsock_
- * @param errnum the errno or value from MHD_W32_errno_from_winsock_()
- * @return pointer to string description of error
- */
-const char* MHD_W32_strerror_(int errnum);
-
-/**
- * Return pointer to string description of last winsock error
- * @return pointer to string description of last winsock error
- */
-const char* MHD_W32_strerror_last_winsock_(void);
-
-/**
- * Set last winsock error to equivalent of given errno value
- * @param errnum the errno value to set
- */
-void MHD_W32_set_last_winsock_error_(int errnum);
-
-/**
- * Create pair of mutually connected TCP/IP sockets on loopback address
- * @param sockets_pair array to receive resulted sockets
- * @return zero on success, -1 otherwise
- */
-int MHD_W32_pair_of_sockets_(SOCKET sockets_pair[2]);
-
-/**
- * Generate 31-bit pseudo random number.
- * Function initialize itself at first call to current time.
- * @return 31-bit pseudo random number.
- */
-int MHD_W32_random_(void);
-
-/* Emulate snprintf function on W32 */
-int W32_snprintf(char *__restrict s, size_t n, const char *__restrict format, ...);
-
-#ifndef _MSC_FULL_VER
-/* Thread name available only for VC-compiler */
-static void W32_SetThreadName(const DWORD thread_id, const char *thread_name)
-{ }
-#else  /* _MSC_FULL_VER */
-/**
- * Set thread name
- * @param thread_id ID of thread, -1 for current thread
- * @param thread_name name to set
- */
-void W32_SetThreadName(const DWORD thread_id, const char *thread_name);
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-#endif //MHD_W32FUNCTIONS_H
diff --git a/src/lib/Makefile.am b/src/lib/Makefile.am
new file mode 100644
index 0000000..33bfd03
--- /dev/null
+++ b/src/lib/Makefile.am
@@ -0,0 +1,182 @@
+# This Makefile.am is in the public domain
+AM_CPPFLAGS = \
+  -I$(top_srcdir)/src/include \
+  -I$(top_srcdir)/src/lib
+
+AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS)
+
+# Call "libmicrohttpd2" for now, but only while under
+# development. Once we have 'compat' working, this should be changed!
+noinst_LTLIBRARIES = \
+  libmicrohttpd2.la
+
+noinst_DATA =
+MOSTLYCLEANFILES =
+
+if W32_SHARED_LIB_EXP
+W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd2.def -XCClinker -static-libgcc
+noinst_DATA += $(lt_cv_objdir)/libmicrohttpd2.lib $(lt_cv_objdir)/libmicrohttpd2.def $(lt_cv_objdir)/libmicrohttpd2.exp
+MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd2.lib $(lt_cv_objdir)/libmicrohttpd2.def $(lt_cv_objdir)/libmicrohttpd2.exp
+
+$(lt_cv_objdir)/libmicrohttpd2.def: libmicrohttpd2.la
+
+$(lt_cv_objdir)/libmicrohttpd2.exp: $(lt_cv_objdir)/libmicrohttpd2.lib
+
+$(lt_cv_objdir)/libmicrohttpd2.lib: $(lt_cv_objdir)/libmicrohttpd2.def libmicrohttpd2.la $(libmicrohttpd2_la_OBJECTS)
+if USE_MS_LIB_TOOL
+	@echo Creating $@ and libmicrohttpd2.exp by $(MS_LIB_TOOL)... && \
+	dll_name=`$(EGREP) -o dlname=\'.+\' libmicrohttpd2.la` && \
+	dll_name=$${dll_name#*\'} && dll_name=$${dll_name%\'} && test -n "$$dll_name" && \
+	echo Creating $$dll_name by $(MS_LIB_TOOL).. && cd "$(lt_cv_objdir)" && \
+	$(MS_LIB_TOOL) -def:libmicrohttpd2.def -name:$$dll_name -out:libmicrohttpd2.lib $(libmicrohttpd2_la_OBJECTS:.lo=.o) && cd ..
+else
+	@echo Creating $@ and libmicrohttpd2.exp by $(DLLTOOL)... && \
+	dll_name=`$(EGREP) -o dlname=\'.+\' libmicrohttpd2.la` && \
+	dll_name=$${dll_name#*\'} && dll_name=$${dll_name%\'} && test -n "$$dll_name" && \
+	echo Creating $$dll_name by $(DLLTOOL).. && cd "$(lt_cv_objdir)" && \
+	$(DLLTOOL) -d ./libmicrohttpd2.def -D $$dll_name -l libmicrohttpd2.lib $(libmicrohttpd2_la_OBJECTS:.lo=.o) -e ./libmicrohttpd2.exp && cd .. &&\
+	echo Created libmicrohttpd2.exp and libmicrohttpd2.lib.
+endif
+else
+  W32_MHD_LIB_LDFLAGS =
+endif
+
+if W32_STATIC_LIB
+noinst_DATA += $(lt_cv_objdir)/libmicrohttpd2-static.lib
+MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd2-static.lib
+
+$(lt_cv_objdir)/libmicrohttpd2-static.lib: libmicrohttpd2.la $(libmicrohttpd2_la_OBJECTS)
+if USE_MS_LIB_TOOL
+	$(MS_LIB_TOOL) -out:$@ $(libmicrohttpd2_la_OBJECTS:.lo=.o)
+else
+	cp $(lt_cv_objdir)/libmicrohttpd2.a $@
+endif
+endif
+
+
+libmicrohttpd2_la_SOURCES = \
+  action_continue.c \
+  action_from_response.c \
+  action_parse_post.c \
+  action_process_upload.c \
+  action_suspend.c \
+  connection_add.c connection_add.h \
+  connection_call_handlers.c connection_call_handlers.h \
+  connection_cleanup.c connection_cleanup.h \
+  connection_close.c connection_close.h \
+  connection_finish_forward.c connection_finish_forward.h \
+  connection_info.c \
+  connection_options.c \
+  connection_update_last_activity.c connection_update_last_activity.h \
+  daemon_close_all_connections.c daemon_close_all_connections.h \
+  daemon_create.c \
+  daemon_destroy.c \
+  daemon_epoll.c daemon_epoll.h \
+  daemon_get_timeout.c \
+  daemon_info.c \
+  daemon_ip_limit.c daemon_ip_limit.h \
+  daemon_options.c \
+  daemon_poll.c daemon_poll.h \
+  daemon_run.c \
+  daemon_select.c daemon_select.h \
+  daemon_start.c \
+  daemon_quiesce.c \
+  init.c init.h \
+  internal.c internal.h \
+  memorypool.c memorypool.h \
+  mhd_assert.h \
+  mhd_byteorder.h \
+  mhd_compat.c mhd_compat.h \
+  mhd_itc.c mhd_itc.h mhd_itc_types.h \
+  mhd_limits.h \
+  mhd_locks.h \
+  mhd_mono_clock.c mhd_mono_clock.h \
+  mhd_str.c mhd_str.h \
+  mhd_sockets.c mhd_sockets.h \
+  mhd_threads.c mhd_threads.h \
+  response.c \
+  response_for_upgrade.c \
+  response_from_buffer.c \
+  response_from_callback.c \
+  response_from_fd.c \
+  response_options.c \
+  reason_phrase.c \
+  request.c \
+  request_info.c \
+  request_resume.c \
+  request_resume.h \
+  sysfdsetsize.c sysfdsetsize.h \
+  upgrade_process.c upgrade_process.h \
+  panic.c \
+  version.c
+
+libmicrohttpd2_la_CPPFLAGS = \
+  $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) \
+  -DBUILDING_MHD_LIB=1
+libmicrohttpd2_la_CFLAGS = \
+  $(AM_CFLAGS) $(MHD_LIB_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+libmicrohttpd2_la_LDFLAGS = \
+  $(MHD_LIB_LDFLAGS) \
+  $(W32_MHD_LIB_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) \
+  -version-info 0:0:0 # FIXME: fix once closer to release...
+if MHD_HAVE_TLS_PLUGIN
+libmicrohttpd2_la_LDFLAGS += \
+  -ldl
+endif
+
+libmicrohttpd2_la_LIBADD = \
+  $(MHD_LIBDEPS) $(MHD_TLS_LIBDEPS)
+
+if HAVE_W32
+MHD_DLL_RES_SRC = ../microhttpd/microhttpd_dll_res.rc
+MHD_DLL_RES_LO = libmicrohttpd2_la-$(MHD_DLL_RES_SRC:.rc=.lo)
+
+EXTRA_libmicrohttpd2_la_DEPENDENCIES = $(MHD_DLL_RES_LO)
+libmicrohttpd2_la_LIBADD += $(MHD_DLL_RES_LO)
+
+# General rule is not required, but keep it just in case
+.rc.lo:
+	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $< -o $@
+
+# To add dll resource only to .dll file and exclude it form static
+# lib, a little trick was used. Allow libtool to create file.lo,
+# file.o and .libs/file.lo, .libs/file.o files, then overwrite file.o
+# by empty object generated from empty c-file. Later libtool will
+# use .libs/file.o for shared lib and empty file.o for static lib.
+# This implementation is based on trick found in liblzma.
+# Note: windres does not understand '-isystem' flag, so all
+# possible '-isystem' flags are replaced by simple '-I' flags.
+$(MHD_DLL_RES_LO): $(MHD_DLL_RES_SRC)
+	RC_CPP_FLAGS=" $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd2_la_CPPFLAGS) $(CPPFLAGS) " && \
+	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_CPP_FLAGS// -isystem / -I } $< -o $@ && \
+	echo > $@-empty.c && $(CC) $(AM_CFLAGS) $(CFLAGS) -c $@-empty.c -o $(@:.lo=.o) && rm -f $@-empty.c
+endif
+
+if USE_COVERAGE
+  AM_CFLAGS += --coverage
+endif
+
+if !MHD_USE_SYS_TSEARCH
+libmicrohttpd2_la_SOURCES += \
+  tsearch.c tsearch.h
+endif
+
+# TBD!
+if HAVE_POSTPROCESSOR
+#libmicrohttpd2_la_SOURCES += \
+#  postprocessor.c
+endif
+
+# TBD!
+if ENABLE_DAUTH
+#libmicrohttpd2_la_SOURCES += \
+#  digestauth.c \
+#  md5.c md5.h
+endif
+
+# TBD!
+if ENABLE_BAUTH
+#libmicrohttpd2_la_SOURCES += \
+#  basicauth.c \
+#  base64.c base64.h
+endif
diff --git a/src/lib/action_continue.c b/src/lib/action_continue.c
new file mode 100644
index 0000000..2063f35
--- /dev/null
+++ b/src/lib/action_continue.c
@@ -0,0 +1,65 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/action_continue.c
+ * @brief implementation of MHD_action_continue()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * The continue action is being run.  Continue
+ * handling the upload.
+ *
+ * @param cls NULL
+ * @param request the request to apply the action to
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+cont_action (void *cls,
+             struct MHD_Request *request)
+{
+  (void) cls;
+  (void) request;
+  /* not sure yet, but this function body may
+     just legitimately stay empty... */
+  return MHD_SC_OK;
+}
+
+
+/**
+ * Action telling MHD to continue processing the upload.
+ *
+ * @return action operation, never NULL
+ */
+const struct MHD_Action *
+MHD_action_continue (void)
+{
+  static struct MHD_Action acont = {
+    .action = &cont_action,
+    .action_cls = NULL
+  };
+
+  return &acont;
+}
+
+
+/* end of action_continue.c */
diff --git a/src/lib/action_from_response.c b/src/lib/action_from_response.c
new file mode 100644
index 0000000..f12dcb9
--- /dev/null
+++ b/src/lib/action_from_response.c
@@ -0,0 +1,132 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/action_from_response.c
+ * @brief implementation of #MHD_action_from_response()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_call_handlers.h"
+
+
+/**
+ * A response was given as the desired action for a @a request.
+ * Queue the response for the request.
+ *
+ * @param cls the `struct MHD_Response`
+ * @param request the request we are processing
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+response_action (void *cls,
+                 struct MHD_Request *request)
+{
+  struct MHD_Response *response = cls;
+  struct MHD_Daemon *daemon = request->daemon;
+
+  /* If daemon was shut down in parallel,
+   * response will be aborted now or on later stage. */
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+
+#ifdef UPGRADE_SUPPORT
+  if ( (NULL != response->upgrade_handler) &&
+       daemon->disallow_upgrade)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_UPGRADE_ON_DAEMON_WITH_UPGRADE_DISALLOWED,
+              _ (
+                "Attempted 'upgrade' connection on daemon without MHD_ALLOW_UPGRADE option!\n"));
+#endif
+    return MHD_SC_UPGRADE_ON_DAEMON_WITH_UPGRADE_DISALLOWED;
+  }
+#endif /* UPGRADE_SUPPORT */
+  request->response = response;
+#if defined(_MHD_HAVE_SENDFILE)
+  if ( (-1 == response->fd)
+#if HTTPS_SUPPORT
+       || (NULL != daemon->tls_api)
+#endif
+       )
+    request->resp_sender = MHD_resp_sender_std;
+  else
+    request->resp_sender = MHD_resp_sender_sendfile;
+#endif /* _MHD_HAVE_SENDFILE */
+
+  if ( (MHD_METHOD_HEAD == request->method) ||
+       (MHD_HTTP_OK > response->status_code) ||
+       (MHD_HTTP_NO_CONTENT == response->status_code) ||
+       (MHD_HTTP_NOT_MODIFIED == response->status_code) )
+  {
+    /* if this is a "HEAD" request, or a status code for
+       which a body is not allowed, pretend that we
+       have already sent the full message body. */
+    request->response_write_position = response->total_size;
+  }
+  if ( (MHD_REQUEST_HEADERS_PROCESSED == request->state) &&
+       ( (MHD_METHOD_POST == request->method) ||
+         (MHD_METHOD_PUT == request->method) ) )
+  {
+    /* response was queued "early", refuse to read body / footers or
+       further requests! */
+    request->connection->read_closed = true;
+    request->state = MHD_REQUEST_FOOTERS_RECEIVED;
+  }
+  if (! request->in_idle)
+    (void) MHD_request_handle_idle_ (request);
+  return MHD_SC_OK;
+}
+
+
+/**
+ * Converts a @a response to an action.  If @a consume
+ * is set, the reference to the @a response is consumed
+ * by the conversion. If @a consume is #MHD_NO, then
+ * the response can be converted to actions in the future.
+ * However, the @a response is frozen by this step and
+ * must no longer be modified (i.e. by setting headers).
+ *
+ * @param response response to convert, not NULL
+ * @param destroy_after_use should the response object be consumed?
+ * @return corresponding action, never returns NULL
+ *
+ * Implementation note: internally, this is largely just
+ * a cast (and possibly an RC increment operation),
+ * as a response *is* an action.  As no memory is
+ * allocated, this operation cannot fail.
+ */
+_MHD_EXTERN const struct MHD_Action *
+MHD_action_from_response (struct MHD_Response *response,
+                          enum MHD_Bool destroy_after_use)
+{
+  response->action.action = &response_action;
+  response->action.action_cls = response;
+  if (! destroy_after_use)
+  {
+    MHD_mutex_lock_chk_ (&response->mutex);
+    response->reference_count++;
+    MHD_mutex_unlock_chk_ (&response->mutex);
+  }
+  return &response->action;
+}
+
+
+/* end of action_from_response */
diff --git a/src/lib/action_parse_post.c b/src/lib/action_parse_post.c
new file mode 100644
index 0000000..187caac
--- /dev/null
+++ b/src/lib/action_parse_post.c
@@ -0,0 +1,61 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/action_parse_post.c
+ * @brief implementation of MHD_action_parse_post()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Create an action that parses a POST request.
+ *
+ * This action can be used to (incrementally) parse the data portion
+ * of a POST request.  Note that some buggy browsers fail to set the
+ * encoding type.  If you want to support those, you may have to call
+ * #MHD_set_connection_value with the proper encoding type before
+ * returning this action (if no supported encoding type is detected,
+ * returning this action will cause a bad request to be returned to
+ * the client).
+ *
+ * @param buffer_size maximum number of bytes to use for
+ *        internal buffering (used only for the parsing,
+ *        specifically the parsing of the keys).  A
+ *        tiny value (256-1024) should be sufficient.
+ *        Do NOT use a value smaller than 256.  For good
+ *        performance, use 32 or 64k (i.e. 65536).
+ * @param iter iterator to be called with the parsed data,
+ *        Must NOT be NULL.
+ * @param iter_cls first argument to @a iter
+ * @return NULL on error (out of memory, unsupported encoding),
+ *         otherwise a PP handle
+ * @ingroup request
+ */
+const struct MHD_Action *
+MHD_action_parse_post (size_t buffer_size,
+                       MHD_PostDataIterator iter,
+                       void *iter_cls)
+{
+  return NULL; /* not yet implemented */
+}
+
+
+/* end of action_parse_post.c */
diff --git a/src/lib/action_process_upload.c b/src/lib/action_process_upload.c
new file mode 100644
index 0000000..0e9722c
--- /dev/null
+++ b/src/lib/action_process_upload.c
@@ -0,0 +1,92 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/action_process_upload.c
+ * @brief implementation of MHD_action_process_upload()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Internal details about an upload action.
+ */
+struct UploadAction
+{
+  /**
+   * An upload action is an action. This field
+   * must come first!
+   */
+  struct MHD_Action action;
+
+  MHD_UploadCallback uc;
+
+  void *uc_cls;
+
+};
+
+
+/**
+ * The application wants to process uploaded data for
+ * the given request. Do it!
+ *
+ * @param cls the `struct UploadAction` with the
+ *    function we are to call for upload data
+ * @param request the request for which we are to process
+ *    upload data
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+upload_action (void *cls,
+               struct MHD_Request *request)
+{
+  struct UploadAction *ua = cls;
+
+  (void) ua;
+  // FIXME: implement!
+  return -1;
+}
+
+
+/**
+ * Create an action that handles an upload.
+ *
+ * @param uc function to call with uploaded data
+ * @param uc_cls closure for @a uc
+ * @return NULL on error (out of memory)
+ * @ingroup action
+ */
+const struct MHD_Action *
+MHD_action_process_upload (MHD_UploadCallback uc,
+                           void *uc_cls)
+{
+  struct UploadAction *ua;
+
+  if (NULL == (ua = malloc (sizeof (struct UploadAction))))
+    return NULL;
+  ua->action.action = &upload_action;
+  ua->action.action_cls = ua;
+  ua->uc = uc;
+  ua->uc_cls = uc_cls;
+  return &ua->action;
+}
+
+
+/* end of action_process_upload.c */
diff --git a/src/lib/action_suspend.c b/src/lib/action_suspend.c
new file mode 100644
index 0000000..b9956d5
--- /dev/null
+++ b/src/lib/action_suspend.c
@@ -0,0 +1,138 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/action_suspend.c
+ * @brief implementation of MHD_action_suspend()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * The suspend action is being run.  Suspend handling
+ * of the given request.
+ *
+ * @param cls NULL
+ * @param request the request to apply the action to
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+suspend_action (void *cls,
+                struct MHD_Request *request)
+{
+  (void) cls;
+  struct MHD_Connection *connection = request->connection;
+  struct MHD_Daemon *daemon = connection->daemon;
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  if (connection->resuming)
+  {
+    /* suspending again while we didn't even complete resuming yet */
+    connection->resuming = false;
+    MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+    return MHD_SC_OK;
+  }
+  if (daemon->threading_mode != MHD_TM_THREAD_PER_CONNECTION)
+  {
+    if (connection->connection_timeout ==
+        daemon->connection_default_timeout)
+      XDLL_remove (daemon->normal_timeout_head,
+                   daemon->normal_timeout_tail,
+                   connection);
+    else
+      XDLL_remove (daemon->manual_timeout_head,
+                   daemon->manual_timeout_tail,
+                   connection);
+  }
+  DLL_remove (daemon->connections_head,
+              daemon->connections_tail,
+              connection);
+  mhd_assert (! connection->suspended);
+  DLL_insert (daemon->suspended_connections_head,
+              daemon->suspended_connections_tail,
+              connection);
+  connection->suspended = true;
+#ifdef EPOLL_SUPPORT
+  if (MHD_ELS_EPOLL == daemon->event_loop_syscall)
+  {
+    if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+    {
+      EDLL_remove (daemon->eready_head,
+                   daemon->eready_tail,
+                   connection);
+      connection->epoll_state &= ~MHD_EPOLL_STATE_IN_EREADY_EDLL;
+    }
+    if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET))
+    {
+      if (0 != epoll_ctl (daemon->epoll_fd,
+                          EPOLL_CTL_DEL,
+                          connection->socket_fd,
+                          NULL))
+        MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+      connection->epoll_state &= ~MHD_EPOLL_STATE_IN_EPOLL_SET;
+    }
+    connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED;
+  }
+#endif
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+  return MHD_SC_OK;
+}
+
+
+/**
+ * Suspend handling of network data for a given request.  This can
+ * be used to dequeue a request from MHD's event loop for a while.
+ *
+ * If you use this API in conjunction with a internal select or a
+ * thread pool, you must set the option #MHD_USE_ITC to
+ * ensure that a resumed request is immediately processed by MHD.
+ *
+ * Suspended requests continue to count against the total number of
+ * requests allowed (per daemon, as well as per IP, if such limits
+ * are set).  Suspended requests will NOT time out; timeouts will
+ * restart when the request handling is resumed.  While a
+ * request is suspended, MHD will not detect disconnects by the
+ * client.
+ *
+ * The only safe time to suspend a request is from either a
+ * #MHD_RequestHeaderCallback, #MHD_UploadCallback, or a
+ * #MHD_RequestfetchResponseCallback.  Suspending a request
+ * at any other time will cause an assertion failure.
+ *
+ * Finally, it is an API violation to call #MHD_daemon_stop() while
+ * having suspended requests (this will at least create memory and
+ * socket leaks or lead to undefined behavior).  You must explicitly
+ * resume all requests before stopping the daemon.
+ *
+ * @return action to cause a request to be suspended.
+ */
+const struct MHD_Action *
+MHD_action_suspend (void)
+{
+  static const struct MHD_Action suspend = {
+    .action = &suspend_action,
+    .action_cls = NULL
+  };
+
+  return &suspend;
+}
+
+
+/* end of action_suspend.c */
diff --git a/src/lib/base64.c b/src/lib/base64.c
new file mode 100644
index 0000000..51430c4
--- /dev/null
+++ b/src/lib/base64.c
@@ -0,0 +1,60 @@
+/*
+ * This code implements the BASE64 algorithm.
+ * This code is in the public domain; do with it what you wish.
+ *
+ * @file base64.c
+ * @brief This code implements the BASE64 algorithm
+ * @author Matthieu Speder
+ */
+#include "base64.h"
+
+static const char base64_digits[] =
+{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
+  0, 0, 0, -1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+  14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26,
+  27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
+  45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+
+
+char *
+BASE64Decode (const char *src)
+{
+  size_t in_len = strlen (src);
+  char *dest;
+  char *result;
+
+  if (in_len % 4)
+  {
+    /* Wrong base64 string length */
+    return NULL;
+  }
+  result = dest = malloc (in_len / 4 * 3 + 1);
+  if (NULL == result)
+    return NULL; /* out of memory */
+  while (*src)
+  {
+    char a = base64_digits[(unsigned char) *(src++)];
+    char b = base64_digits[(unsigned char) *(src++)];
+    char c = base64_digits[(unsigned char) *(src++)];
+    char d = base64_digits[(unsigned char) *(src++)];
+    *(dest++) = (a << 2) | ((b & 0x30) >> 4);
+    if (c == (char) -1)
+      break;
+    *(dest++) = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2);
+    if (d == (char) -1)
+      break;
+    *(dest++) = ((c & 0x03) << 6) | d;
+  }
+  *dest = 0;
+  return result;
+}
+
+
+/* end of base64.c */
diff --git a/src/microhttpd/base64.h b/src/lib/base64.h
similarity index 90%
rename from src/microhttpd/base64.h
rename to src/lib/base64.h
index ba96ca0..9d97c5b 100644
--- a/src/microhttpd/base64.h
+++ b/src/lib/base64.h
@@ -12,6 +12,6 @@
 #include "platform.h"
 
 char *
-BASE64Decode(const char* src);
+BASE64Decode (const char *src);
 
 #endif /* !BASE64_H */
diff --git a/src/lib/connection_add.c b/src/lib/connection_add.c
new file mode 100644
index 0000000..8875064
--- /dev/null
+++ b/src/lib/connection_add.c
@@ -0,0 +1,1140 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_add.c
+ * @brief functions to add connection to our active set
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_add.h"
+#include "connection_call_handlers.h"
+#include "connection_close.h"
+#include "connection_finish_forward.h"
+#include "connection_update_last_activity.h"
+#include "daemon_ip_limit.h"
+#include "daemon_select.h"
+#include "daemon_poll.h"
+#include "mhd_sockets.h"
+
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * Main function of the thread that handles an individual connection
+ * after it was "upgraded" when #MHD_USE_THREAD_PER_CONNECTION is set.
+ * @remark To be called only from thread that process
+ * connection's recv(), send() and response.
+ *
+ * @param con the connection this thread will handle
+ */
+static void
+thread_main_connection_upgrade (struct MHD_Connection *con)
+{
+#ifdef HTTPS_SUPPORT
+  struct MHD_Daemon *daemon = con->daemon;
+
+  /* Here, we need to bi-directionally forward
+     until the application tells us that it is done
+     with the socket; */
+  if ( (NULL != daemon->tls_api) &&
+       (MHD_ELS_POLL != daemon->event_loop_syscall) )
+  {
+    MHD_daemon_upgrade_connection_with_select_ (con);
+  }
+#ifdef HAVE_POLL
+  else if (NULL != daemon->tls_api)
+  {
+    MHD_daemon_upgrade_connection_with_poll_ (con);
+  }
+#endif
+  /* end HTTPS */
+#endif /* HTTPS_SUPPORT */
+  /* TLS forwarding was finished. Cleanup socketpair. */
+  MHD_connection_finish_forward_ (con);
+  /* Do not set 'urh->clean_ready' yet as 'urh' will be used
+   * in connection thread for a little while. */
+}
+
+
+#endif /* UPGRADE_SUPPORT */
+
+
+/**
+ * Main function of the thread that handles an individual
+ * connection when #MHD_USE_THREAD_PER_CONNECTION is set.
+ *
+ * @param data the `struct MHD_Connection` this thread will handle
+ * @return always 0
+ */
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+thread_main_handle_connection (void *data)
+{
+  struct MHD_Connection *con = data;
+  struct MHD_Daemon *daemon = con->daemon;
+  int num_ready;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket maxsock;
+  struct timeval tv;
+  struct timeval *tvp;
+  time_t now;
+#if WINDOWS
+#ifdef HAVE_POLL
+  int extra_slot;
+#endif /* HAVE_POLL */
+#define EXTRA_SLOTS 1
+#else  /* !WINDOWS */
+#define EXTRA_SLOTS 0
+#endif /* !WINDOWS */
+#ifdef HAVE_POLL
+  struct pollfd p[1 + EXTRA_SLOTS];
+#endif
+#undef EXTRA_SLOTS
+#ifdef HAVE_POLL
+  const bool use_poll = (MHD_ELS_POLL == daemon->event_loop_syscall);
+#else  /* ! HAVE_POLL */
+  const bool use_poll = false;
+#endif /* ! HAVE_POLL */
+  bool was_suspended = false;
+
+  MHD_thread_init_ (&con->pid);
+
+  while ( (! daemon->shutdown) &&
+          (MHD_REQUEST_CLOSED != con->request.state) )
+  {
+    const time_t timeout = daemon->connection_default_timeout;
+#ifdef UPGRADE_SUPPORT
+    struct MHD_UpgradeResponseHandle *const urh = con->request.urh;
+#else  /* ! UPGRADE_SUPPORT */
+    static const void *const urh = NULL;
+#endif /* ! UPGRADE_SUPPORT */
+
+    if ( (con->suspended) &&
+         (NULL == urh) )
+    {
+      /* Connection was suspended, wait for resume. */
+      was_suspended = true;
+      if (! use_poll)
+      {
+        FD_ZERO (&rs);
+        if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                                  &rs,
+                                  NULL,
+                                  FD_SETSIZE))
+        {
+  #ifdef HAVE_MESSAGES
+          MHD_DLOG (con->daemon,
+                    MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE,
+                    _ ("Failed to add FD to fd_set.\n"));
+  #endif
+          goto exit;
+        }
+        if (0 > MHD_SYS_select_ (MHD_itc_r_fd_ (daemon->itc) + 1,
+                                 &rs,
+                                 NULL,
+                                 NULL,
+                                 NULL))
+        {
+          const int err = MHD_socket_get_error_ ();
+
+          if (MHD_SCKT_ERR_IS_EINTR_ (err))
+            continue;
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (con->daemon,
+                    MHD_SC_UNEXPECTED_SELECT_ERROR,
+                    _ ("Error during select (%d): `%s'\n"),
+                    err,
+                    MHD_socket_strerr_ (err));
+#endif
+          break;
+        }
+      }
+#ifdef HAVE_POLL
+      else     /* use_poll */
+      {
+        p[0].events = POLLIN;
+        p[0].fd = MHD_itc_r_fd_ (daemon->itc);
+        p[0].revents = 0;
+        if (0 > MHD_sys_poll_ (p,
+                               1,
+                               -1))
+        {
+          if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_))
+            continue;
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (con->daemon,
+                    MHD_SC_UNEXPECTED_POLL_ERROR,
+                    _ ("Error during poll: `%s'\n"),
+                    MHD_socket_last_strerr_ ());
+#endif
+          break;
+        }
+      }
+#endif /* HAVE_POLL */
+      MHD_itc_clear_ (daemon->itc);
+      continue; /* Check again for resume. */
+    }           /* End of "suspended" branch. */
+
+    if (was_suspended)
+    {
+      MHD_connection_update_last_activity_ (con);     /* Reset timeout timer. */
+      /* Process response queued during suspend and update states. */
+      MHD_request_handle_idle_ (&con->request);
+      was_suspended = false;
+    }
+
+    tvp = NULL;
+
+    if ( (MHD_EVENT_LOOP_INFO_BLOCK == con->request.event_loop_info)
+#ifdef HTTPS_SUPPORT
+         || ( (con->tls_read_ready) &&
+              (MHD_EVENT_LOOP_INFO_READ == con->request.event_loop_info) )
+#endif /* HTTPS_SUPPORT */
+         )
+    {
+      /* do not block: more data may be inside of TLS buffers waiting or
+       * application must provide response data */
+      tv.tv_sec = 0;
+      tv.tv_usec = 0;
+      tvp = &tv;
+    }
+    if ( (NULL == tvp) &&
+         (timeout > 0) )
+    {
+      now = MHD_monotonic_sec_counter ();
+      if (now - con->last_activity > timeout)
+        tv.tv_sec = 0;
+      else
+      {
+        const time_t seconds_left = timeout - (now - con->last_activity);
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+        tv.tv_sec = seconds_left;
+#else  /* _WIN32 && !__CYGWIN__ */
+        if (seconds_left > TIMEVAL_TV_SEC_MAX)
+          tv.tv_sec = TIMEVAL_TV_SEC_MAX;
+        else
+          tv.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) seconds_left;
+#endif /* _WIN32 && ! __CYGWIN__  */
+      }
+      tv.tv_usec = 0;
+      tvp = &tv;
+    }
+    if (! use_poll)
+    {
+      /* use select */
+      bool err_state = false;
+
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      maxsock = MHD_INVALID_SOCKET;
+      switch (con->request.event_loop_info)
+      {
+      case MHD_EVENT_LOOP_INFO_READ:
+        if (! MHD_add_to_fd_set_ (con->socket_fd,
+                                  &rs,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = true;
+        break;
+      case MHD_EVENT_LOOP_INFO_WRITE:
+        if (! MHD_add_to_fd_set_ (con->socket_fd,
+                                  &ws,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = true;
+        break;
+      case MHD_EVENT_LOOP_INFO_BLOCK:
+        if (! MHD_add_to_fd_set_ (con->socket_fd,
+                                  &es,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = true;
+        break;
+      case MHD_EVENT_LOOP_INFO_CLEANUP:
+        /* how did we get here!? */
+        goto exit;
+      }
+#if WINDOWS
+      if (MHD_ITC_IS_VALID_ (daemon->itc) )
+      {
+        if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                                  &rs,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = 1;
+      }
+#endif
+      if (err_state)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE,
+                  _ ("Failed to add FD to fd_set.\n"));
+#endif
+        goto exit;
+      }
+
+      num_ready = MHD_SYS_select_ (maxsock + 1,
+                                   &rs,
+                                   &ws,
+                                   &es,
+                                   tvp);
+      if (num_ready < 0)
+      {
+        const int err = MHD_socket_get_error_ ();
+
+        if (MHD_SCKT_ERR_IS_EINTR_ (err))
+          continue;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  MHD_SC_UNEXPECTED_SELECT_ERROR,
+                  _ ("Error during select (%d): `%s'\n"),
+                  err,
+                  MHD_socket_strerr_ (err));
+#endif
+        break;
+      }
+#if WINDOWS
+      /* Clear ITC before other processing so additional
+       * signals will trigger select() again */
+      if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+           (FD_ISSET (MHD_itc_r_fd_ (daemon->itc),
+                      &rs)) )
+        MHD_itc_clear_ (daemon->itc);
+#endif
+      if (MHD_NO ==
+          MHD_connection_call_handlers_ (con,
+                                         FD_ISSET (con->socket_fd,
+                                                   &rs),
+                                         FD_ISSET (con->socket_fd,
+                                                   &ws),
+                                         FD_ISSET (con->socket_fd,
+                                                   &es)) )
+        goto exit;
+    }
+#ifdef HAVE_POLL
+    else
+    {
+      /* use poll */
+      memset (&p,
+              0,
+              sizeof (p));
+      p[0].fd = con->socket_fd;
+      switch (con->request.event_loop_info)
+      {
+      case MHD_EVENT_LOOP_INFO_READ:
+        p[0].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_WRITE:
+        p[0].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_BLOCK:
+        p[0].events |= MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_CLEANUP:
+        /* how did we get here!? */
+        goto exit;
+      }
+#if WINDOWS
+      extra_slot = 0;
+      if (MHD_ITC_IS_VALID_ (daemon->itc))
+      {
+        p[1].events |= POLLIN;
+        p[1].fd = MHD_itc_r_fd_ (daemon->itc);
+        p[1].revents = 0;
+        extra_slot = 1;
+      }
+#endif
+      if (MHD_sys_poll_ (p,
+#if WINDOWS
+                         1 + extra_slot,
+#else
+                         1,
+#endif
+                         (NULL == tvp) ? -1 : tv.tv_sec * 1000) < 0)
+      {
+        if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_))
+          continue;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  MHD_SC_UNEXPECTED_POLL_ERROR,
+                  _ ("Error during poll: `%s'\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+        break;
+      }
+#if WINDOWS
+      /* Clear ITC before other processing so additional
+       * signals will trigger poll() again */
+      if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+           (0 != (p[1].revents & (POLLERR | POLLHUP | POLLIN))) )
+        MHD_itc_clear_ (daemon->itc);
+#endif
+      if (MHD_NO ==
+          MHD_connection_call_handlers_ (con,
+                                         (0 != (p[0].revents & POLLIN)),
+                                         (0 != (p[0].revents & POLLOUT)),
+                                         (0 != (p[0].revents & (POLLERR
+                                                                |
+                                                                MHD_POLL_REVENTS_ERR_DISC))) ))
+        goto exit;
+    }
+#endif
+#ifdef UPGRADE_SUPPORT
+    if (MHD_REQUEST_UPGRADE == con->request.state)
+    {
+      /* Normal HTTP processing is finished,
+       * notify application. */
+      if (NULL != con->request.response->termination_cb)
+        con->request.response->termination_cb
+          (con->request.response->termination_cb_cls,
+          MHD_REQUEST_TERMINATED_COMPLETED_OK,
+          con->request.client_context);
+      thread_main_connection_upgrade (con);
+      /* MHD_connection_finish_forward_() was called by thread_main_connection_upgrade(). */
+
+      /* "Upgraded" data will not be used in this thread from this point. */
+      con->request.urh->clean_ready = true;
+      /* If 'urh->was_closed' set to true, connection will be
+       * moved immediately to cleanup list. Otherwise connection
+       * will stay in suspended list until 'urh' will be marked
+       * with 'was_closed' by application. */
+      MHD_request_resume (&con->request);
+
+      /* skip usual clean up  */
+      return (MHD_THRD_RTRN_TYPE_) 0;
+    }
+#endif /* UPGRADE_SUPPORT */
+  }
+#if DEBUG_CLOSE
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (con->daemon,
+            MHD_SC_THREAD_TERMINATING,
+            _ ("Processing thread terminating. Closing connection.\n"));
+#endif
+#endif
+  if (MHD_REQUEST_CLOSED != con->request.state)
+    MHD_connection_close_ (con,
+                           (daemon->shutdown) ?
+                           MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN :
+                           MHD_REQUEST_TERMINATED_WITH_ERROR);
+  MHD_request_handle_idle_ (&con->request);
+exit:
+  if (NULL != con->request.response)
+  {
+    MHD_response_queue_for_destroy (con->request.response);
+    con->request.response = NULL;
+  }
+
+  if (MHD_INVALID_SOCKET != con->socket_fd)
+  {
+    shutdown (con->socket_fd,
+              SHUT_WR);
+    /* 'socket_fd' can be used in other thread to signal shutdown.
+     * To avoid data races, do not close socket here. Daemon will
+     * use more connections only after cleanup anyway. */
+  }
+  return (MHD_THRD_RTRN_TYPE_) 0;
+}
+
+
+/**
+ * Callback for receiving data from the socket.
+ *
+ * @param connection the MHD connection structure
+ * @param other where to write received data to
+ * @param i maximum size of other (in bytes)
+ * @return positive value for number of bytes actually received or
+ *         negative value for error number MHD_ERR_xxx_
+ */
+static ssize_t
+recv_param_adapter (struct MHD_Connection *connection,
+                    void *other,
+                    size_t i)
+{
+  ssize_t ret;
+
+  if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
+       (MHD_REQUEST_CLOSED == connection->request.state) )
+  {
+    return MHD_ERR_NOTCONN_;
+  }
+  if (i > MHD_SCKT_SEND_MAX_SIZE_)
+    i = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */
+
+  ret = MHD_recv_ (connection->socket_fd,
+                   other,
+                   i);
+  if (0 > ret)
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* Got EAGAIN --- no longer read-ready */
+      connection->epoll_state &= ~MHD_EPOLL_STATE_READ_READY;
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ECONNRESET_))
+      return MHD_ERR_CONNRESET_;
+    /* Treat any other error as hard error. */
+    return MHD_ERR_NOTCONN_;
+  }
+#ifdef EPOLL_SUPPORT
+  else if (i > (size_t) ret)
+    connection->epoll_state &= ~MHD_EPOLL_STATE_READ_READY;
+#endif /* EPOLL_SUPPORT */
+  return ret;
+}
+
+
+/**
+ * Callback for writing data to the socket.
+ *
+ * @param connection the MHD connection structure
+ * @param other data to write
+ * @param i number of bytes to write
+ * @return positive value for number of bytes actually sent or
+ *         negative value for error number MHD_ERR_xxx_
+ */
+static ssize_t
+send_param_adapter (struct MHD_Connection *connection,
+                    const void *other,
+                    size_t i)
+{
+  ssize_t ret;
+
+  if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
+       (MHD_REQUEST_CLOSED == connection->request.state) )
+  {
+    return MHD_ERR_NOTCONN_;
+  }
+  if (i > MHD_SCKT_SEND_MAX_SIZE_)
+    i = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */
+
+  ret = MHD_send_ (connection->socket_fd,
+                   other,
+                   i);
+  if (0 > ret)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* EAGAIN --- no longer write-ready */
+      connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ECONNRESET_))
+      return MHD_ERR_CONNRESET_;
+    /* Treat any other error as hard error. */
+    return MHD_ERR_NOTCONN_;
+  }
+#ifdef EPOLL_SUPPORT
+  else if (i > (size_t) ret)
+    connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
+#endif /* EPOLL_SUPPORT */
+  return ret;
+}
+
+
+/**
+ * Add another client connection to the set of connections
+ * managed by MHD.  This API is usually not needed (since
+ * MHD will accept inbound connections on the server socket).
+ * Use this API in special cases, for example if your HTTP
+ * server is behind NAT and needs to connect out to the
+ * HTTP client.
+ *
+ * The given client socket will be managed (and closed!) by MHD after
+ * this call and must no longer be used directly by the application
+ * afterwards.
+ *
+ * @param daemon daemon that manages the connection
+ * @param client_socket socket to manage (MHD will expect
+ *        to receive an HTTP request from this socket next).
+ * @param addr IP address of the client
+ * @param addrlen number of bytes in @a addr
+ * @param external_add perform additional operations needed due
+ *        to the application calling us directly
+ * @param non_blck indicate that socket in non-blocking mode
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+internal_add_connection (struct MHD_Daemon *daemon,
+                         MHD_socket client_socket,
+                         const struct sockaddr *addr,
+                         socklen_t addrlen,
+                         bool external_add,
+                         bool non_blck)
+{
+  enum MHD_StatusCode sc;
+  struct MHD_Connection *connection;
+  int eno = 0;
+
+  /* Direct add to master daemon could happen only with "external" add mode. */
+  mhd_assert ( (NULL == daemon->worker_pool) ||
+               (external_add) );
+  if ( (external_add) &&
+       (NULL != daemon->worker_pool) )
+  {
+    unsigned int i;
+
+    /* have a pool, try to find a pool with capacity; we use the
+ socket as the initial offset into the pool for load
+ balancing */
+    for (i = 0; i < daemon->worker_pool_size; ++i)
+    {
+      struct MHD_Daemon *const worker =
+        &daemon->worker_pool[(i + client_socket) % daemon->worker_pool_size];
+      if (worker->connections < worker->global_connection_limit)
+        return internal_add_connection (worker,
+                                        client_socket,
+                                        addr,
+                                        addrlen,
+                                        true,
+                                        non_blck);
+    }
+    /* all pools are at their connection limit, must refuse */
+    MHD_socket_close_chk_ (client_socket);
+#if ENFILE
+    errno = ENFILE;
+#endif
+    return MHD_SC_LIMIT_CONNECTIONS_REACHED;
+  }
+
+  if ( (! MHD_SCKT_FD_FITS_FDSET_ (client_socket,
+                                   NULL)) &&
+       (MHD_ELS_SELECT == daemon->event_loop_syscall) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE,
+              _ ("Socket descriptor larger than FD_SETSIZE: %d > %d\n"),
+              (int) client_socket,
+              (int) FD_SETSIZE);
+#endif
+    MHD_socket_close_chk_ (client_socket);
+#if EINVAL
+    errno = EINVAL;
+#endif
+    return MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+  }
+
+#ifdef MHD_socket_nosignal_
+  if (! MHD_socket_nosignal_ (client_socket))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_CONFIGURE_NOSIGPIPE_FAILED,
+              _ ("Failed to set SO_NOSIGPIPE on accepted socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+#ifndef MSG_NOSIGNAL
+    /* Cannot use socket as it can produce SIGPIPE. */
+#ifdef ENOTSOCK
+    errno = ENOTSOCK;
+#endif /* ENOTSOCK */
+    return MHD_SC_ACCEPT_CONFIGURE_NOSIGPIPE_FAILED;
+#endif /* ! MSG_NOSIGNAL */
+  }
+#endif /* MHD_socket_nosignal_ */
+
+
+#ifdef HAVE_MESSAGES
+#if DEBUG_CONNECT
+  MHD_DLOG (daemon,
+            MHD_SC_CONNECTION_ACCEPTED,
+            _ ("Accepted connection on socket %d.\n"),
+            client_socket);
+#endif
+#endif
+  if ( (daemon->connections == daemon->global_connection_limit) ||
+       (MHD_NO == MHD_ip_limit_add (daemon,
+                                    addr,
+                                    addrlen)) )
+  {
+    /* above connection limit - reject */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LIMIT_CONNECTIONS_REACHED,
+              _ (
+                "Server reached connection limit. Closing inbound connection.\n"));
+#endif
+    MHD_socket_close_chk_ (client_socket);
+#if ENFILE
+    errno = ENFILE;
+#endif
+    return MHD_SC_LIMIT_CONNECTIONS_REACHED;
+  }
+
+  /* apply connection acceptance policy if present */
+  if ( (NULL != daemon->accept_policy_cb) &&
+       (MHD_NO ==
+        daemon->accept_policy_cb (daemon->accept_policy_cb_cls,
+                                  addr,
+                                  addrlen)) )
+  {
+#if DEBUG_CLOSE
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_POLICY_REJECTED,
+              _ ("Connection rejected by application. Closing connection.\n"));
+#endif
+#endif
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+#if EACCESS
+    errno = EACCESS;
+#endif
+    return MHD_SC_ACCEPT_POLICY_REJECTED;
+  }
+
+  if (NULL ==
+      (connection = MHD_calloc_ (1,
+                                 sizeof (struct MHD_Connection))))
+  {
+    eno = errno;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_CONNECTION_MALLOC_FAILURE,
+              "Error allocating memory: %s\n",
+              MHD_strerror_ (errno));
+#endif
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+    errno = eno;
+    return MHD_SC_CONNECTION_MALLOC_FAILURE;
+  }
+  connection->pool
+    = MHD_pool_create (daemon->connection_memory_limit_b);
+  if (NULL == connection->pool)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_POOL_MALLOC_FAILURE,
+              _ ("Error allocating memory: %s\n"),
+              MHD_strerror_ (errno));
+#endif
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+    free (connection);
+#if ENOMEM
+    errno = ENOMEM;
+#endif
+    return MHD_SC_POOL_MALLOC_FAILURE;
+  }
+
+  connection->connection_timeout = daemon->connection_default_timeout;
+  memcpy (&connection->addr,
+          addr,
+          addrlen);
+  connection->addr_len = addrlen;
+  connection->socket_fd = client_socket;
+  connection->sk_nonblck = non_blck;
+  connection->daemon = daemon;
+  connection->last_activity = MHD_monotonic_sec_counter ();
+
+#ifdef HTTPS_SUPPORT
+  if (NULL != daemon->tls_api)
+  {
+    connection->tls_cs
+      = daemon->tls_api->setup_connection (daemon->tls_api->cls,
+                                           NULL /* FIXME */);
+    if (NULL == connection->tls_cs)
+    {
+      eno = EINVAL;
+      sc = -1; // FIXME!
+      goto cleanup;
+    }
+  }
+  else
+#endif /* ! HTTPS_SUPPORT */
+  {
+    /* set default connection handlers  */
+    connection->recv_cls = &recv_param_adapter;
+    connection->send_cls = &send_param_adapter;
+  }
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  /* Firm check under lock. */
+  if (daemon->connections >= daemon->global_connection_limit)
+  {
+    MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+    /* above connection limit - reject */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LIMIT_CONNECTIONS_REACHED,
+              _ (
+                "Server reached connection limit. Closing inbound connection.\n"));
+#endif
+#if ENFILE
+    eno = ENFILE;
+#endif
+    sc = MHD_SC_LIMIT_CONNECTIONS_REACHED;
+    goto cleanup;
+  }
+  daemon->connections++;
+  if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+  {
+    XDLL_insert (daemon->normal_timeout_head,
+                 daemon->normal_timeout_tail,
+                 connection);
+  }
+  DLL_insert (daemon->connections_head,
+              daemon->connections_tail,
+              connection);
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+
+  if (NULL != daemon->notify_connection_cb)
+    daemon->notify_connection_cb (daemon->notify_connection_cb_cls,
+                                  connection,
+                                  MHD_CONNECTION_NOTIFY_STARTED);
+
+  /* attempt to create handler thread */
+  if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+  {
+    if (! MHD_create_named_thread_ (&connection->pid,
+                                    "MHD-connection",
+                                    daemon->thread_stack_limit_b,
+                                    &thread_main_handle_connection,
+                                    connection))
+    {
+      eno = errno;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_THREAD_LAUNCH_FAILURE,
+                "Failed to create a thread: %s\n",
+                MHD_strerror_ (eno));
+#endif
+      sc = MHD_SC_THREAD_LAUNCH_FAILURE;
+      goto cleanup;
+    }
+  }
+  else
+  {
+    connection->pid = daemon->pid;
+  }
+#ifdef EPOLL_SUPPORT
+  if (MHD_ELS_EPOLL == daemon->event_loop_syscall)
+  {
+    if ( (! daemon->enable_turbo) ||
+         (external_add))
+    { /* Do not manipulate EReady DL-list in 'external_add' mode. */
+      struct epoll_event event;
+
+      event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
+      event.data.ptr = connection;
+      if (0 != epoll_ctl (daemon->epoll_fd,
+                          EPOLL_CTL_ADD,
+                          client_socket,
+                          &event))
+      {
+        eno = errno;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  MHD_SC_EPOLL_CTL_ADD_FAILED,
+                  _ ("Call to epoll_ctl failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+        sc = MHD_SC_EPOLL_CTL_ADD_FAILED;
+        goto cleanup;
+      }
+      connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
+    }
+    else
+    {
+      connection->epoll_state |= MHD_EPOLL_STATE_READ_READY
+                                 | MHD_EPOLL_STATE_WRITE_READY
+                                 | MHD_EPOLL_STATE_IN_EREADY_EDLL;
+      EDLL_insert (daemon->eready_head,
+                   daemon->eready_tail,
+                   connection);
+    }
+  }
+  else /* This 'else' is combined with next 'if'. */
+#endif
+  if ( (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode) &&
+       (external_add) &&
+       (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc,
+                             "n")) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ITC_USE_FAILED,
+              _ (
+                "Failed to signal new connection via inter-thread communication channel (not necessarily fatal, continuing anyway).\n"));
+#endif
+  }
+  return MHD_SC_OK;
+
+cleanup:
+  if (NULL != daemon->notify_connection_cb)
+    daemon->notify_connection_cb (daemon->notify_connection_cb_cls,
+                                  connection,
+                                  MHD_CONNECTION_NOTIFY_CLOSED);
+#ifdef HTTPS_SUPPORT
+  if ( (NULL != daemon->tls_api) &&
+       (NULL != connection->tls_cs) )
+    daemon->tls_api->teardown_connection (daemon->tls_api->cls,
+                                          connection->tls_cs);
+#endif /* HTTPS_SUPPORT */
+  MHD_socket_close_chk_ (client_socket);
+  MHD_ip_limit_del (daemon,
+                    addr,
+                    addrlen);
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+  {
+    XDLL_remove (daemon->normal_timeout_head,
+                 daemon->normal_timeout_tail,
+                 connection);
+  }
+  DLL_remove (daemon->connections_head,
+              daemon->connections_tail,
+              connection);
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+  MHD_pool_destroy (connection->pool);
+  free (connection);
+  if (0 != eno)
+    errno = eno;
+  else
+    errno  = EINVAL;
+  return sc;
+}
+
+
+/**
+ * Add another client connection to the set of connections managed by
+ * MHD.  This API is usually not needed (since MHD will accept inbound
+ * connections on the server socket).  Use this API in special cases,
+ * for example if your HTTP server is behind NAT and needs to connect
+ * out to the HTTP client, or if you are building a proxy.
+ *
+ * If you use this API in conjunction with a internal select or a
+ * thread pool, you must set the option #MHD_USE_ITC to ensure that
+ * the freshly added connection is immediately processed by MHD.
+ *
+ * The given client socket will be managed (and closed!) by MHD after
+ * this call and must no longer be used directly by the application
+ * afterwards.
+ *
+ * @param daemon daemon that manages the connection
+ * @param client_socket socket to manage (MHD will expect
+ *        to receive an HTTP request from this socket next).
+ * @param addr IP address of the client
+ * @param addrlen number of bytes in @a addr
+ * @return #MHD_YES on success, #MHD_NO if this daemon could
+ *        not handle the connection (i.e. malloc() failed, etc).
+ *        The socket will be closed in any case; `errno` is
+ *        set to indicate further details about the error.
+ * @ingroup specialized
+ */
+enum MHD_StatusCode
+MHD_daemon_add_connection (struct MHD_Daemon *daemon,
+                           MHD_socket client_socket,
+                           const struct sockaddr *addr,
+                           socklen_t addrlen)
+{
+  bool sk_nonbl;
+
+  if (! MHD_socket_nonblocking_ (client_socket))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_CONFIGURE_NONBLOCKING_FAILED,
+              _ ("Failed to set nonblocking mode on new client socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    sk_nonbl = false;
+  }
+  else
+  {
+    sk_nonbl = true;
+  }
+
+  if ( (daemon->enable_turbo) &&
+       (! MHD_socket_noninheritable_ (client_socket)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_CONFIGURE_NOINHERIT_FAILED,
+              _ ("Failed to set noninheritable mode on new client socket.\n"));
+#endif
+  }
+  return internal_add_connection (daemon,
+                                  client_socket,
+                                  addr,
+                                  addrlen,
+                                  true,
+                                  sk_nonbl);
+}
+
+
+/**
+ * Accept an incoming connection and create the MHD_Connection object
+ * for it.  This function also enforces policy by way of checking with
+ * the accept policy callback.  @remark To be called only from thread
+ * that process daemon's select()/poll()/etc.
+ *
+ * @param daemon handle with the listen socket
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_accept_connection_ (struct MHD_Daemon *daemon)
+{
+  struct sockaddr_storage addrstorage;
+  struct sockaddr *addr = (struct sockaddr *) &addrstorage;
+  socklen_t addrlen;
+  MHD_socket s;
+  MHD_socket fd;
+  bool sk_nonbl;
+
+  addrlen = sizeof (addrstorage);
+  memset (addr,
+          0,
+          sizeof (addrstorage));
+  if ( (MHD_INVALID_SOCKET == (fd = daemon->listen_socket)) ||
+       (daemon->was_quiesced) )
+    return MHD_SC_DAEMON_ALREADY_QUIESCED;
+#ifdef USE_ACCEPT4
+  s = accept4 (fd,
+               addr,
+               &addrlen,
+               MAYBE_SOCK_CLOEXEC | MAYBE_SOCK_NONBLOCK);
+  sk_nonbl = (0 != MAYBE_SOCK_NONBLOCK);
+#else  /* ! USE_ACCEPT4 */
+  s = accept (fd,
+              addr,
+              &addrlen);
+  sk_nonbl = false;
+#endif /* ! USE_ACCEPT4 */
+  if ( (MHD_INVALID_SOCKET == s) ||
+       (addrlen <= 0) )
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    /* This could be a common occurrence with multiple worker threads */
+    if (MHD_SCKT_ERR_IS_ (err,
+                          MHD_SCKT_EINVAL_))
+      return MHD_SC_DAEMON_ALREADY_SHUTDOWN;  /* can happen during shutdown, let's hope this is the cause... */
+    if (MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_ (err))
+      return MHD_SC_ACCEPT_FAST_DISCONNECT;   /* do not print error if client just disconnected early */
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err) )
+      return MHD_SC_ACCEPT_FAILED_EAGAIN;
+    if (MHD_INVALID_SOCKET != s)
+    {
+      MHD_socket_close_chk_ (s);
+    }
+    if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err) )
+    {
+      /* system/process out of resources */
+      if (0 == daemon->connections)
+      {
+#ifdef HAVE_MESSAGES
+        /* Not setting 'at_limit' flag, as there is no way it
+           would ever be cleared.  Instead trying to produce
+           bit fat ugly warning. */
+        MHD_DLOG (daemon,
+                  MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED_INSTANTLY,
+                  _ (
+                    "Hit process or system resource limit at FIRST connection. This is really bad as there is no sane way to proceed. Will try busy waiting for system resources to become magically available.\n"));
+#endif
+        return MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED_INSTANTLY;
+      }
+      else
+      {
+        MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+        daemon->at_limit = true;
+        MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED,
+                  _ (
+                    "Hit process or system resource limit at %u connections, temporarily suspending accept(). Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"),
+                  (unsigned int) daemon->connections);
+#endif
+        return MHD_SC_ACCEPT_SYSTEM_LIMIT_REACHED;
+      }
+    }
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_FAILED_UNEXPECTEDLY,
+              _ ("Error accepting connection: %s\n"),
+              MHD_socket_strerr_ (err));
+#endif
+    return MHD_SC_ACCEPT_FAILED_UNEXPECTEDLY;
+  }
+#if ! defined(USE_ACCEPT4) || ! defined(HAVE_SOCK_NONBLOCK)
+  if (! MHD_socket_nonblocking_ (s))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_CONFIGURE_NONBLOCKING_FAILED,
+              _ (
+                "Failed to set nonblocking mode on incoming connection socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+  }
+  else
+    sk_nonbl = true;
+#endif /* !USE_ACCEPT4 || !HAVE_SOCK_NONBLOCK */
+#if ! defined(USE_ACCEPT4) || ! defined(SOCK_CLOEXEC)
+  if (! MHD_socket_noninheritable_ (s))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ACCEPT_CONFIGURE_NOINHERIT_FAILED,
+              _ (
+                "Failed to set noninheritable mode on incoming connection socket.\n"));
+#endif
+  }
+#endif /* !USE_ACCEPT4 || !SOCK_CLOEXEC */
+#ifdef HAVE_MESSAGES
+#if DEBUG_CONNECT
+  MHD_DLOG (daemon,
+            MHD_SC_CONNECTION_ACCEPTED,
+            _ ("Accepted connection on socket %d.\n"),
+            s);
+#endif
+#endif
+  return internal_add_connection (daemon,
+                                  s,
+                                  addr,
+                                  addrlen,
+                                  false,
+                                  sk_nonbl);
+}
+
+
+/* end of connection_add.c */
diff --git a/src/lib/connection_add.h b/src/lib/connection_add.h
new file mode 100644
index 0000000..de8abd9
--- /dev/null
+++ b/src/lib/connection_add.h
@@ -0,0 +1,41 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_add.h
+ * @brief functions to add connection to our active set
+ * @author Christian Grothoff
+ */
+
+#ifndef CONNECTION_ADD_H
+#define CONNECTION_ADD_H
+
+/**
+ * Accept an incoming connection and create the MHD_Connection object
+ * for it.  This function also enforces policy by way of checking with
+ * the accept policy callback.  @remark To be called only from thread
+ * that process daemon's select()/poll()/etc.
+ *
+ * @param daemon handle with the listen socket
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_accept_connection_ (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/connection_call_handlers.c b/src/lib/connection_call_handlers.c
new file mode 100644
index 0000000..561a1c2
--- /dev/null
+++ b/src/lib/connection_call_handlers.c
@@ -0,0 +1,3724 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_call_handlers.c
+ * @brief call the connection's handlers based on the event trigger
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_call_handlers.h"
+#include "connection_update_last_activity.h"
+#include "connection_close.h"
+
+
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#include <sys/sendfile.h>
+#endif /* MHD_LINUX_SOLARIS_SENDFILE */
+#if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE)
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+#endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */
+
+
+/**
+ * sendfile() chuck size
+ */
+#define MHD_SENFILE_CHUNK_         (0x20000)
+
+/**
+ * sendfile() chuck size for thread-per-connection
+ */
+#define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000)
+
+
+/**
+ * Response text used when the request (http header) is too big to
+ * be processed.
+ *
+ * Intentionally empty here to keep our memory footprint
+ * minimal.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_TOO_BIG \
+  "<html><head><title>Request too big</title></head><body>Your HTTP header was too big for the memory constraints of this webserver.</body></html>"
+#else
+#define REQUEST_TOO_BIG ""
+#endif
+
+/**
+ * Response text used when the request (http header) does not
+ * contain a "Host:" header and still claims to be HTTP 1.1.
+ *
+ * Intentionally empty here to keep our memory footprint
+ * minimal.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_LACKS_HOST \
+  "<html><head><title>&quot;Host:&quot; header required</title></head><body>In HTTP 1.1, requests must include a &quot;Host:&quot; header, and your HTTP 1.1 request lacked such a header.</body></html>"
+#else
+#define REQUEST_LACKS_HOST ""
+#endif
+
+/**
+ * Response text used when the request (http header) is
+ * malformed.
+ *
+ * Intentionally empty here to keep our memory footprint
+ * minimal.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_MALFORMED \
+  "<html><head><title>Request malformed</title></head><body>Your HTTP request was syntactically incorrect.</body></html>"
+#else
+#define REQUEST_MALFORMED ""
+#endif
+
+/**
+ * Response text used when there is an internal server error.
+ *
+ * Intentionally empty here to keep our memory footprint
+ * minimal.
+ */
+#ifdef HAVE_MESSAGES
+#define INTERNAL_ERROR \
+  "<html><head><title>Internal server error</title></head><body>Please ask the developer of this Web server to carefully read the GNU libmicrohttpd documentation about connection management and blocking.</body></html>"
+#else
+#define INTERNAL_ERROR ""
+#endif
+
+
+#ifdef HAVE_FREEBSD_SENDFILE
+#ifdef SF_FLAGS
+/**
+ * FreeBSD sendfile() flags
+ */
+static int freebsd_sendfile_flags_;
+
+/**
+ * FreeBSD sendfile() flags for thread-per-connection
+ */
+static int freebsd_sendfile_flags_thd_p_c_;
+#endif /* SF_FLAGS */
+
+
+/**
+ * Initialises static variables.
+ *
+ * FIXME: make sure its actually called!
+ */
+void
+MHD_conn_init_static_ (void)
+{
+/* FreeBSD 11 and later allow to specify read-ahead size
+ * and handles SF_NODISKIO differently.
+ * SF_FLAGS defined only on FreeBSD 11 and later. */
+#ifdef SF_FLAGS
+  long sys_page_size = sysconf (_SC_PAGESIZE);
+  if (0 > sys_page_size)
+  {   /* Failed to get page size. */
+    freebsd_sendfile_flags_ = SF_NODISKIO;
+    freebsd_sendfile_flags_thd_p_c_ = SF_NODISKIO;
+  }
+  else
+  {
+    freebsd_sendfile_flags_ =
+      SF_FLAGS ((uint16_t) (MHD_SENFILE_CHUNK_ / sys_page_size), SF_NODISKIO);
+    freebsd_sendfile_flags_thd_p_c_ =
+      SF_FLAGS ((uint16_t) (MHD_SENFILE_CHUNK_THR_P_C_ / sys_page_size),
+                SF_NODISKIO);
+  }
+#endif /* SF_FLAGS */
+}
+
+
+#endif /* HAVE_FREEBSD_SENDFILE */
+
+
+/**
+ * Message to transmit when http 1.1 request is received
+ */
+#define HTTP_100_CONTINUE "HTTP/1.1 100 Continue\r\n\r\n"
+
+
+/**
+ * A serious error occurred, close the
+ * connection (and notify the application).
+ *
+ * @param connection connection to close with error
+ * @param sc the reason for closing the connection
+ * @param emsg error message (can be NULL)
+ */
+static void
+connection_close_error (struct MHD_Connection *connection,
+                        enum MHD_StatusCode sc,
+                        const char *emsg)
+{
+#ifdef HAVE_MESSAGES
+  if (NULL != emsg)
+    MHD_DLOG (connection->daemon,
+              sc,
+              emsg);
+#else  /* ! HAVE_MESSAGES */
+  (void) emsg; /* Mute compiler warning. */
+  (void) sc;
+#endif /* ! HAVE_MESSAGES */
+  MHD_connection_close_ (connection,
+                         MHD_REQUEST_TERMINATED_WITH_ERROR);
+}
+
+
+/**
+ * Macro to only include error message in call to
+ * #connection_close_error() if we have HAVE_MESSAGES.
+ */
+#ifdef HAVE_MESSAGES
+#define CONNECTION_CLOSE_ERROR(c, sc, emsg) connection_close_error (c, sc, emsg)
+#else
+#define CONNECTION_CLOSE_ERROR(c, sc, emsg) connection_close_error (c, sc, NULL)
+#endif
+
+
+/**
+ * Try growing the read buffer.  We initially claim half the available
+ * buffer space for the read buffer (the other half being left for
+ * management data structures; the write buffer can in the end take
+ * virtually everything as the read buffer can be reduced to the
+ * minimum necessary at that point.
+ *
+ * @param request the request for which to grow the buffer
+ * @return true on success, false on failure
+ */
+static bool
+try_grow_read_buffer (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  void *buf;
+  size_t new_size;
+
+  if (0 == request->read_buffer_size)
+    new_size = daemon->connection_memory_limit_b / 2;
+  else
+    new_size = request->read_buffer_size
+               + daemon->connection_memory_increment_b;
+  buf = MHD_pool_reallocate (request->connection->pool,
+                             request->read_buffer,
+                             request->read_buffer_size,
+                             new_size);
+  if (NULL == buf)
+    return false;
+  /* we can actually grow the buffer, do it! */
+  request->read_buffer = buf;
+  request->read_buffer_size = new_size;
+  return true;
+}
+
+
+/**
+ * This function handles a particular request when it has been
+ * determined that there is data to be read off a socket.
+ *
+ * @param request request to handle
+ */
+static void
+MHD_request_handle_read_ (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Connection *connection = request->connection;
+  ssize_t bytes_read;
+
+  if ( (MHD_REQUEST_CLOSED == request->state) ||
+       (connection->suspended) )
+    return;
+#ifdef HTTPS_SUPPORT
+  {
+    struct MHD_TLS_Plugin *tls;
+
+    if ( (NULL != (tls = daemon->tls_api)) &&
+         (! tls->handshake (tls->cls,
+                            connection->tls_cs)) )
+      return;
+  }
+#endif /* HTTPS_SUPPORT */
+
+  /* make sure "read" has a reasonable number of bytes
+     in buffer to use per system call (if possible) */
+  if (request->read_buffer_offset
+      + daemon->connection_memory_increment_b >
+      request->read_buffer_size)
+    try_grow_read_buffer (request);
+
+  if (request->read_buffer_size == request->read_buffer_offset)
+    return; /* No space for receiving data. */
+  bytes_read = connection->recv_cls (connection,
+                                     &request->read_buffer
+                                     [request->read_buffer_offset],
+                                     request->read_buffer_size
+                                     - request->read_buffer_offset);
+  if (bytes_read < 0)
+  {
+    if (MHD_ERR_AGAIN_ == bytes_read)
+      return;     /* No new data to process. */
+    if (MHD_ERR_CONNRESET_ == bytes_read)
+    {
+      CONNECTION_CLOSE_ERROR (connection,
+                              (MHD_REQUEST_INIT == request->state)
+                              ? MHD_SC_CONNECTION_CLOSED
+                              : MHD_SC_CONNECTION_RESET_CLOSED,
+                              (MHD_REQUEST_INIT == request->state)
+                              ? NULL
+                              : _ (
+                                "Socket disconnected while reading request.\n"));
+      return;
+    }
+    CONNECTION_CLOSE_ERROR (connection,
+                            (MHD_REQUEST_INIT == request->state)
+                            ? MHD_SC_CONNECTION_CLOSED
+                            : MHD_SC_CONNECTION_READ_FAIL_CLOSED,
+                            (MHD_REQUEST_INIT == request->state)
+                            ? NULL
+                            : _ (
+                              "Connection socket is closed due to error when reading request.\n"));
+    return;
+  }
+
+  if (0 == bytes_read)
+  {   /* Remote side closed connection. */
+    connection->read_closed = true;
+    MHD_connection_close_ (connection,
+                           MHD_REQUEST_TERMINATED_CLIENT_ABORT);
+    return;
+  }
+  request->read_buffer_offset += bytes_read;
+  MHD_connection_update_last_activity_ (connection);
+#if DEBUG_STATES
+  MHD_DLOG (daemon,
+            MHD_SC_STATE_MACHINE_STATUS_REPORT,
+            _ ("In function %s handling connection at state: %s\n"),
+            __FUNCTION__,
+            MHD_state_to_string (request->state));
+#endif
+  switch (request->state)
+  {
+  case MHD_REQUEST_INIT:
+  case MHD_REQUEST_URL_RECEIVED:
+  case MHD_REQUEST_HEADER_PART_RECEIVED:
+  case MHD_REQUEST_HEADERS_RECEIVED:
+  case MHD_REQUEST_HEADERS_PROCESSED:
+  case MHD_REQUEST_CONTINUE_SENDING:
+  case MHD_REQUEST_CONTINUE_SENT:
+  case MHD_REQUEST_BODY_RECEIVED:
+  case MHD_REQUEST_FOOTER_PART_RECEIVED:
+    /* nothing to do but default action */
+    if (connection->read_closed)
+    {
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_READ_ERROR);
+    }
+    return;
+  case MHD_REQUEST_CLOSED:
+    return;
+#ifdef UPGRADE_SUPPORT
+  case MHD_REQUEST_UPGRADE:
+    mhd_assert (0);
+    return;
+#endif /* UPGRADE_SUPPORT */
+  default:
+    /* shrink read buffer to how much is actually used */
+    MHD_pool_reallocate (connection->pool,
+                         request->read_buffer,
+                         request->read_buffer_size + 1,
+                         request->read_buffer_offset);
+    break;
+  }
+  return;
+}
+
+
+#if defined(_MHD_HAVE_SENDFILE)
+/**
+ * Function for sending responses backed by file FD.
+ *
+ * @param connection the MHD connection structure
+ * @return actual number of bytes sent
+ */
+static ssize_t
+sendfile_adapter (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_Request *request = &connection->request;
+  struct MHD_Response *response = request->response;
+  ssize_t ret;
+  const int file_fd = response->fd;
+  uint64_t left;
+  uint64_t offsetu64;
+#ifndef HAVE_SENDFILE64
+  const uint64_t max_off_t = (uint64_t) OFF_T_MAX;
+#else  /* HAVE_SENDFILE64 */
+  const uint64_t max_off_t = (uint64_t) OFF64_T_MAX;
+#endif /* HAVE_SENDFILE64 */
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#ifndef HAVE_SENDFILE64
+  off_t offset;
+#else  /* HAVE_SENDFILE64 */
+  off64_t offset;
+#endif /* HAVE_SENDFILE64 */
+#endif /* MHD_LINUX_SOLARIS_SENDFILE */
+#ifdef HAVE_FREEBSD_SENDFILE
+  off_t sent_bytes;
+  int flags = 0;
+#endif
+#ifdef HAVE_DARWIN_SENDFILE
+  off_t len;
+#endif /* HAVE_DARWIN_SENDFILE */
+  const bool used_thr_p_c = (MHD_TM_THREAD_PER_CONNECTION ==
+                             daemon->threading_mode);
+  const size_t chunk_size = used_thr_p_c ? MHD_SENFILE_CHUNK_THR_P_C_ :
+                            MHD_SENFILE_CHUNK_;
+  size_t send_size = 0;
+
+  mhd_assert (MHD_resp_sender_sendfile == request->resp_sender);
+  offsetu64 = request->response_write_position + response->fd_off;
+  left = response->total_size - request->response_write_position;
+  /* Do not allow system to stick sending on single fast connection:
+   * use 128KiB chunks (2MiB for thread-per-connection). */
+  send_size = (left > chunk_size) ? chunk_size : (size_t) left;
+  if (max_off_t < offsetu64)
+  {   /* Retry to send with standard 'send()'. */
+    request->resp_sender = MHD_resp_sender_std;
+    return MHD_ERR_AGAIN_;
+  }
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#ifndef HAVE_SENDFILE64
+  offset = (off_t) offsetu64;
+  ret = sendfile (connection->socket_fd,
+                  file_fd,
+                  &offset,
+                  send_size);
+#else  /* HAVE_SENDFILE64 */
+  offset = (off64_t) offsetu64;
+  ret = sendfile64 (connection->socket_fd,
+                    file_fd,
+                    &offset,
+                    send_size);
+#endif /* HAVE_SENDFILE64 */
+  if (0 > ret)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* EAGAIN --- no longer write-ready */
+      connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+#ifdef HAVE_LINUX_SENDFILE
+    if (MHD_SCKT_ERR_IS_ (err,
+                          MHD_SCKT_EBADF_))
+      return MHD_ERR_BADF_;
+    /* sendfile() failed with EINVAL if mmap()-like operations are not
+       supported for FD or other 'unusual' errors occurred, so we should try
+       to fall back to 'SEND'; see also this thread for info on
+       odd libc/Linux behavior with sendfile:
+       http://lists.gnu.org/archive/html/libmicrohttpd/2011-02/msg00015.html */request->resp_sender = MHD_resp_sender_std;
+    return MHD_ERR_AGAIN_;
+#else  /* HAVE_SOLARIS_SENDFILE */
+    if ( (EAFNOSUPPORT == err) ||
+         (EINVAL == err) ||
+         (EOPNOTSUPP == err) )
+    {     /* Retry with standard file reader. */
+      request->resp_sender = MHD_resp_sender_std;
+      return MHD_ERR_AGAIN_;
+    }
+    if ( (ENOTCONN == err) ||
+         (EPIPE == err) )
+    {
+      return MHD_ERR_CONNRESET_;
+    }
+    return MHD_ERR_BADF_;   /* Fail hard */
+#endif /* HAVE_SOLARIS_SENDFILE */
+  }
+#ifdef EPOLL_SUPPORT
+  else if (send_size > (size_t) ret)
+    connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
+#endif /* EPOLL_SUPPORT */
+#elif defined(HAVE_FREEBSD_SENDFILE)
+#ifdef SF_FLAGS
+  flags = used_thr_p_c ?
+          freebsd_sendfile_flags_thd_p_c_ : freebsd_sendfile_flags_;
+#endif /* SF_FLAGS */
+  if (0 != sendfile (file_fd,
+                     connection->socket_fd,
+                     (off_t) offsetu64,
+                     send_size,
+                     NULL,
+                     &sent_bytes,
+                     flags))
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err) ||
+        MHD_SCKT_ERR_IS_EINTR_ (err) ||
+        (EBUSY == err) )
+    {
+      mhd_assert (SSIZE_MAX >= sent_bytes);
+      if (0 != sent_bytes)
+        return (ssize_t) sent_bytes;
+
+      return MHD_ERR_AGAIN_;
+    }
+    /* Some unrecoverable error. Possibly file FD is not suitable
+     * for sendfile(). Retry with standard send(). */
+    request->resp_sender = MHD_resp_sender_std;
+    return MHD_ERR_AGAIN_;
+  }
+  mhd_assert (0 < sent_bytes);
+  mhd_assert (SSIZE_MAX >= sent_bytes);
+  ret = (ssize_t) sent_bytes;
+#elif defined(HAVE_DARWIN_SENDFILE)
+  len = (off_t) send_size; /* chunk always fit */
+  if (0 != sendfile (file_fd,
+                     connection->socket_fd,
+                     (off_t) offsetu64,
+                     &len,
+                     NULL,
+                     0))
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err) ||
+        MHD_SCKT_ERR_IS_EINTR_ (err))
+    {
+      mhd_assert (0 <= len);
+      mhd_assert (SSIZE_MAX >= len);
+      mhd_assert (send_size >= (size_t) len);
+      if (0 != len)
+        return (ssize_t) len;
+
+      return MHD_ERR_AGAIN_;
+    }
+    if ((ENOTCONN == err) ||
+        (EPIPE == err) )
+      return MHD_ERR_CONNRESET_;
+    if ((ENOTSUP == err) ||
+        (EOPNOTSUPP == err) )
+    {     /* This file FD is not suitable for sendfile().
+           * Retry with standard send(). */
+      request->resp_sender = MHD_resp_sender_std;
+      return MHD_ERR_AGAIN_;
+    }
+    return MHD_ERR_BADF_;   /* Return hard error. */
+  }
+  mhd_assert (0 <= len);
+  mhd_assert (SSIZE_MAX >= len);
+  mhd_assert (send_size >= (size_t) len);
+  ret = (ssize_t) len;
+#endif /* HAVE_FREEBSD_SENDFILE */
+  return ret;
+}
+
+
+#endif /* _MHD_HAVE_SENDFILE */
+
+
+/**
+ * Check if we are done sending the write-buffer.  If so, transition
+ * into "next_state".
+ *
+ * @param connection connection to check write status for
+ * @param next_state the next state to transition to
+ * @return false if we are not done, true if we are
+ */
+static bool
+check_write_done (struct MHD_Request *request,
+                  enum MHD_REQUEST_STATE next_state)
+{
+  if (request->write_buffer_append_offset !=
+      request->write_buffer_send_offset)
+    return false;
+  request->write_buffer_append_offset = 0;
+  request->write_buffer_send_offset = 0;
+  request->state = next_state;
+  MHD_pool_reallocate (request->connection->pool,
+                       request->write_buffer,
+                       request->write_buffer_size,
+                       0);
+  request->write_buffer = NULL;
+  request->write_buffer_size = 0;
+  return true;
+}
+
+
+/**
+ * Prepare the response buffer of this request for sending.  Assumes
+ * that the response mutex is already held.  If the transmission is
+ * complete, this function may close the socket (and return false).
+ *
+ * @param request the request handle
+ * @return false if readying the response failed (the
+ *  lock on the response will have been released already
+ *  in this case).
+ */
+static bool
+try_ready_normal_body (struct MHD_Request *request)
+{
+  struct MHD_Response *response = request->response;
+  struct MHD_Connection *connection = request->connection;
+  ssize_t ret;
+
+  if (NULL == response->crc)
+    return true;
+  if ( (0 == response->total_size) ||
+       (request->response_write_position == response->total_size) )
+    return true; /* 0-byte response is always ready */
+  if ( (response->data_start <=
+        request->response_write_position) &&
+       (response->data_size + response->data_start >
+        request->response_write_position) )
+    return true; /* response already ready */
+#if defined(_MHD_HAVE_SENDFILE)
+  if (MHD_resp_sender_sendfile == request->resp_sender)
+  {
+    /* will use sendfile, no need to bother response crc */
+    return true;
+  }
+#endif /* _MHD_HAVE_SENDFILE */
+
+  ret = response->crc (response->crc_cls,
+                       request->response_write_position,
+                       response->data,
+                       (size_t) MHD_MIN ((uint64_t) response->data_buffer_size,
+                                         response->total_size
+                                         - request->response_write_position));
+  if ( (((ssize_t) MHD_CONTENT_READER_END_OF_STREAM) == ret) ||
+       (((ssize_t) MHD_CONTENT_READER_END_WITH_ERROR) == ret) )
+  {
+    /* either error or http 1.0 transfer, close socket! */
+    response->total_size = request->response_write_position;
+    MHD_mutex_unlock_chk_ (&response->mutex);
+    if ( ((ssize_t) MHD_CONTENT_READER_END_OF_STREAM) == ret)
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_COMPLETED_OK);
+    else
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_APPLICATION_DATA_GENERATION_FAILURE_CLOSED,
+                              _ (
+                                "Closing connection (application reported error generating data).\n"));
+    return false;
+  }
+  response->data_start = request->response_write_position;
+  response->data_size = ret;
+  if (0 == ret)
+  {
+    request->state = MHD_REQUEST_NORMAL_BODY_UNREADY;
+    MHD_mutex_unlock_chk_ (&response->mutex);
+    return false;
+  }
+  return true;
+}
+
+
+/**
+ * Prepare the response buffer of this request for sending.  Assumes
+ * that the response mutex is already held.  If the transmission is
+ * complete, this function may close the socket (and return false).
+ *
+ * @param connection the connection
+ * @return false if readying the response failed
+ */
+static bool
+try_ready_chunked_body (struct MHD_Request *request)
+{
+  struct MHD_Connection *connection = request->connection;
+  struct MHD_Response *response = request->response;
+  struct MHD_Daemon *daemon = request->daemon;
+  ssize_t ret;
+  char *buf;
+  size_t size;
+  char cbuf[10];                /* 10: max strlen of "%x\r\n" */
+  int cblen;
+
+  if (NULL == response->crc)
+    return true;
+  if (0 == request->write_buffer_size)
+  {
+    size = MHD_MIN (daemon->connection_memory_limit_b,
+                    2 * (0xFFFFFF + sizeof(cbuf) + 2));
+    do
+    {
+      size /= 2;
+      if (size < 128)
+      {
+        MHD_mutex_unlock_chk_ (&response->mutex);
+        /* not enough memory */
+        CONNECTION_CLOSE_ERROR (connection,
+                                MHD_SC_CONNECTION_POOL_MALLOC_FAILURE,
+                                _ ("Closing connection (out of memory).\n"));
+        return false;
+      }
+      buf = MHD_pool_allocate (connection->pool,
+                               size,
+                               MHD_NO);
+    }
+    while (NULL == buf);
+    request->write_buffer_size = size;
+    request->write_buffer = buf;
+  }
+
+  if (0 == response->total_size)
+    ret = 0; /* response must be empty, don't bother calling crc */
+  else if ( (response->data_start <=
+             request->response_write_position) &&
+            (response->data_start + response->data_size >
+             request->response_write_position) )
+  {
+    /* difference between response_write_position and data_start is less
+       than data_size which is size_t type, no need to check for overflow */
+    const size_t data_write_offset
+      = (size_t) (request->response_write_position - response->data_start);
+    /* buffer already ready, use what is there for the chunk */
+    ret = response->data_size - data_write_offset;
+    if ( ((size_t) ret) > request->write_buffer_size - sizeof (cbuf) - 2)
+      ret = request->write_buffer_size - sizeof (cbuf) - 2;
+    memcpy (&request->write_buffer[sizeof (cbuf)],
+            &response->data[data_write_offset],
+            ret);
+  }
+  else
+  {
+    /* buffer not in range, try to fill it */
+    ret = response->crc (response->crc_cls,
+                         request->response_write_position,
+                         &request->write_buffer[sizeof (cbuf)],
+                         request->write_buffer_size - sizeof (cbuf) - 2);
+  }
+  if ( ((ssize_t) MHD_CONTENT_READER_END_WITH_ERROR) == ret)
+  {
+    /* error, close socket! */
+    response->total_size = request->response_write_position;
+    MHD_mutex_unlock_chk_ (&response->mutex);
+    CONNECTION_CLOSE_ERROR (connection,
+                            MHD_SC_APPLICATION_DATA_GENERATION_FAILURE_CLOSED,
+                            _ (
+                              "Closing connection (application error generating response).\n"));
+    return false;
+  }
+  if ( (((ssize_t) MHD_CONTENT_READER_END_OF_STREAM) == ret) ||
+       (0 == response->total_size) )
+  {
+    /* end of message, signal other side! */
+    memcpy (request->write_buffer,
+            "0\r\n",
+            3);
+    request->write_buffer_append_offset = 3;
+    request->write_buffer_send_offset = 0;
+    response->total_size = request->response_write_position;
+    return true;
+  }
+  if (0 == ret)
+  {
+    request->state = MHD_REQUEST_CHUNKED_BODY_UNREADY;
+    MHD_mutex_unlock_chk_ (&response->mutex);
+    return false;
+  }
+  if (ret > 0xFFFFFF)
+    ret = 0xFFFFFF;
+  cblen = MHD_snprintf_ (cbuf,
+                         sizeof (cbuf),
+                         "%X\r\n",
+                         (unsigned int) ret);
+  mhd_assert (cblen > 0);
+  mhd_assert ((size_t) cblen < sizeof(cbuf));
+  memcpy (&request->write_buffer[sizeof (cbuf) - cblen],
+          cbuf,
+          cblen);
+  memcpy (&request->write_buffer[sizeof (cbuf) + ret],
+          "\r\n",
+          2);
+  request->response_write_position += ret;
+  request->write_buffer_send_offset = sizeof (cbuf) - cblen;
+  request->write_buffer_append_offset = sizeof (cbuf) + ret + 2;
+  return true;
+}
+
+
+/**
+ * This function was created to handle writes to sockets when it has
+ * been determined that the socket can be written to.
+ *
+ * @param request the request to handle
+ */
+static void
+MHD_request_handle_write_ (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Connection *connection = request->connection;
+  struct MHD_Response *response;
+  ssize_t ret;
+
+  if (connection->suspended)
+    return;
+#ifdef HTTPS_SUPPORT
+  {
+    struct MHD_TLS_Plugin *tls;
+
+    if ( (NULL != (tls = daemon->tls_api)) &&
+         (! tls->handshake (tls->cls,
+                            connection->tls_cs)) )
+      return;
+  }
+#endif /* HTTPS_SUPPORT */
+
+#if DEBUG_STATES
+  MHD_DLOG (daemon,
+            MHD_SC_STATE_MACHINE_STATUS_REPORT,
+            _ ("In function %s handling connection at state: %s\n"),
+            __FUNCTION__,
+            MHD_state_to_string (request->state));
+#endif
+  switch (request->state)
+  {
+  case MHD_REQUEST_INIT:
+  case MHD_REQUEST_URL_RECEIVED:
+  case MHD_REQUEST_HEADER_PART_RECEIVED:
+  case MHD_REQUEST_HEADERS_RECEIVED:
+    mhd_assert (0);
+    return;
+  case MHD_REQUEST_HEADERS_PROCESSED:
+    return;
+  case MHD_REQUEST_CONTINUE_SENDING:
+    ret = connection->send_cls (connection,
+                                &HTTP_100_CONTINUE
+                                [request->continue_message_write_offset],
+                                MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE)
+                                - request->continue_message_write_offset);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                _ ("Failed to send data in request for %s.\n"),
+                request->url);
+#endif
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                              NULL);
+      return;
+    }
+    request->continue_message_write_offset += ret;
+    MHD_connection_update_last_activity_ (connection);
+    return;
+  case MHD_REQUEST_CONTINUE_SENT:
+  case MHD_REQUEST_BODY_RECEIVED:
+  case MHD_REQUEST_FOOTER_PART_RECEIVED:
+  case MHD_REQUEST_FOOTERS_RECEIVED:
+    mhd_assert (0);
+    return;
+  case MHD_REQUEST_HEADERS_SENDING:
+    ret = connection->send_cls (connection,
+                                &request->write_buffer
+                                [request->write_buffer_send_offset],
+                                request->write_buffer_append_offset
+                                - request->write_buffer_send_offset);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                              _ (
+                                "Connection was closed while sending response headers.\n"));
+      return;
+    }
+    request->write_buffer_send_offset += ret;
+    MHD_connection_update_last_activity_ (connection);
+    if (MHD_REQUEST_HEADERS_SENDING != request->state)
+      return;
+    check_write_done (request,
+                      MHD_REQUEST_HEADERS_SENT);
+    return;
+  case MHD_REQUEST_HEADERS_SENT:
+    return;
+  case MHD_REQUEST_NORMAL_BODY_READY:
+    response = request->response;
+    if (request->response_write_position <
+        request->response->total_size)
+    {
+      uint64_t data_write_offset;
+
+      if (NULL != response->crc)
+        MHD_mutex_lock_chk_ (&response->mutex);
+      if (! try_ready_normal_body (request))
+      {
+        /* mutex was already unlocked by try_ready_normal_body */
+        return;
+      }
+#if defined(_MHD_HAVE_SENDFILE)
+      if (MHD_resp_sender_sendfile == request->resp_sender)
+      {
+        ret = sendfile_adapter (connection);
+      }
+      else
+#else  /* ! _MHD_HAVE_SENDFILE */
+      if (1)
+#endif /* ! _MHD_HAVE_SENDFILE */
+      {
+        data_write_offset = request->response_write_position
+                            - response->data_start;
+        if (data_write_offset > (uint64_t) SIZE_MAX)
+          MHD_PANIC (_ ("Data offset exceeds limit.\n"));
+        ret = connection->send_cls (connection,
+                                    &response->data
+                                    [(size_t) data_write_offset],
+                                    response->data_size
+                                    - (size_t) data_write_offset);
+#if DEBUG_SEND_DATA
+        if (ret > 0)
+          fprintf (stderr,
+                   _ ("Sent %d-byte DATA response: `%.*s'\n"),
+                   (int) ret,
+                   (int) ret,
+                   &response->data[request->response_write_position
+                                   - response->data_start]);
+#endif
+      }
+      if (NULL != response->crc)
+        MHD_mutex_unlock_chk_ (&response->mutex);
+      if (ret < 0)
+      {
+        if (MHD_ERR_AGAIN_ == ret)
+          return;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                  _ ("Failed to send data in request for `%s'.\n"),
+                  request->url);
+#endif
+        CONNECTION_CLOSE_ERROR (connection,
+                                MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                                NULL);
+        return;
+      }
+      request->response_write_position += ret;
+      MHD_connection_update_last_activity_ (connection);
+    }
+    if (request->response_write_position ==
+        request->response->total_size)
+      request->state = MHD_REQUEST_FOOTERS_SENT;   /* have no footers */
+    return;
+  case MHD_REQUEST_NORMAL_BODY_UNREADY:
+    mhd_assert (0);
+    return;
+  case MHD_REQUEST_CHUNKED_BODY_READY:
+    ret = connection->send_cls (connection,
+                                &request->write_buffer
+                                [request->write_buffer_send_offset],
+                                request->write_buffer_append_offset
+                                - request->write_buffer_send_offset);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                              _ (
+                                "Connection was closed while sending response body.\n"));
+      return;
+    }
+    request->write_buffer_send_offset += ret;
+    MHD_connection_update_last_activity_ (connection);
+    if (MHD_REQUEST_CHUNKED_BODY_READY != request->state)
+      return;
+    check_write_done (request,
+                      (request->response->total_size ==
+                       request->response_write_position) ?
+                      MHD_REQUEST_BODY_SENT :
+                      MHD_REQUEST_CHUNKED_BODY_UNREADY);
+    return;
+  case MHD_REQUEST_CHUNKED_BODY_UNREADY:
+  case MHD_REQUEST_BODY_SENT:
+    mhd_assert (0);
+    return;
+  case MHD_REQUEST_FOOTERS_SENDING:
+    ret = connection->send_cls (connection,
+                                &request->write_buffer
+                                [request->write_buffer_send_offset],
+                                request->write_buffer_append_offset
+                                - request->write_buffer_send_offset);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_CONNECTION_WRITE_FAIL_CLOSED,
+                              _ (
+                                "Connection was closed while sending response body.\n"));
+      return;
+    }
+    request->write_buffer_send_offset += ret;
+    MHD_connection_update_last_activity_ (connection);
+    if (MHD_REQUEST_FOOTERS_SENDING != request->state)
+      return;
+    check_write_done (request,
+                      MHD_REQUEST_FOOTERS_SENT);
+    return;
+  case MHD_REQUEST_FOOTERS_SENT:
+    mhd_assert (0);
+    return;
+  case MHD_REQUEST_CLOSED:
+    return;
+#ifdef UPGRADE_SUPPORT
+  case MHD_REQUEST_UPGRADE:
+    mhd_assert (0);
+    return;
+#endif /* UPGRADE_SUPPORT */
+  default:
+    mhd_assert (0);
+    CONNECTION_CLOSE_ERROR (connection,
+                            MHD_SC_STATEMACHINE_FAILURE_CONNECTION_CLOSED,
+                            _ ("Internal error.\n"));
+    break;
+  }
+}
+
+
+/**
+ * Check whether request header contains particular token.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param request    the request to get values from
+ * @param header     the header name
+ * @param token      the token to find
+ * @param token_len  the length of token, not including optional
+ *                   terminating null-character.
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+static bool
+MHD_lookup_header_token_ci (const struct MHD_Request *request,
+                            const char *header,
+                            const char *token,
+                            size_t token_len)
+{
+  struct MHD_HTTP_Header *pos;
+
+  if ( (NULL == request) || /* FIXME: require non-null? */
+       (NULL == header) || /* FIXME: require non-null? */
+       (0 == header[0]) ||
+       (NULL == token) ||
+       (0 == token[0]) )
+    return false;
+  for (pos = request->headers_received; NULL != pos; pos = pos->next)
+  {
+    if ( (0 != (pos->kind & MHD_HEADER_KIND)) &&
+         ( (header == pos->header) ||
+           (MHD_str_equal_caseless_ (header,
+                                     pos->header)) ) &&
+         (MHD_str_has_token_caseless_ (pos->value,
+                                       token,
+                                       token_len)) )
+      return true;
+  }
+  return false;
+}
+
+
+/**
+ * Check whether request header contains particular static @a tkn.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param r   the request to get values from
+ * @param h   the header name
+ * @param tkn the static string of token to find
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+#define MHD_lookup_header_s_token_ci(r,h,tkn) \
+  MHD_lookup_header_token_ci ((r),(h),(tkn),MHD_STATICSTR_LEN_ (tkn))
+
+
+/**
+ * Are we allowed to keep the given connection alive?  We can use the
+ * TCP stream for a second request if the connection is HTTP 1.1 and
+ * the "Connection" header either does not exist or is not set to
+ * "close", or if the connection is HTTP 1.0 and the "Connection"
+ * header is explicitly set to "keep-alive".  If no HTTP version is
+ * specified (or if it is not 1.0 or 1.1), we definitively close the
+ * connection.  If the "Connection" header is not exactly "close" or
+ * "keep-alive", we proceed to use the default for the respective HTTP
+ * version (which is conservative for HTTP 1.0, but might be a bit
+ * optimistic for HTTP 1.1).
+ *
+ * @param request the request to check for keepalive
+ * @return #MHD_YES if (based on the request), a keepalive is
+ *        legal
+ */
+static bool
+keepalive_possible (struct MHD_Request *request)
+{
+  if (MHD_CONN_MUST_CLOSE == request->keepalive)
+    return false;
+  if (NULL == request->version_s)
+    return false;
+  if ( (NULL != request->response) &&
+       (request->response->v10_only) )
+    return false;
+
+  if (MHD_str_equal_caseless_ (request->version_s,
+                               MHD_HTTP_VERSION_1_1))
+  {
+    if (MHD_lookup_header_s_token_ci (request,
+                                      MHD_HTTP_HEADER_CONNECTION,
+                                      "upgrade"))
+      return false;
+    if (MHD_lookup_header_s_token_ci (request,
+                                      MHD_HTTP_HEADER_CONNECTION,
+                                      "close"))
+      return false;
+    return true;
+  }
+  if (MHD_str_equal_caseless_ (request->version_s,
+                               MHD_HTTP_VERSION_1_0))
+  {
+    if (MHD_lookup_header_s_token_ci (request,
+                                      MHD_HTTP_HEADER_CONNECTION,
+                                      "Keep-Alive"))
+      return true;
+    return false;
+  }
+  return false;
+}
+
+
+/**
+ * Produce HTTP time stamp.
+ *
+ * @param date where to write the header, with
+ *        at least 128 bytes available space.
+ * @param date_len number of bytes in @a date
+ */
+static void
+get_date_string (char *date,
+                 size_t date_len)
+{
+  static const char *const days[] = {
+    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+  };
+  static const char *const mons[] = {
+    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+  };
+  struct tm now;
+  time_t t;
+#if ! defined(HAVE_C11_GMTIME_S) && ! defined(HAVE_W32_GMTIME_S) && \
+  ! defined(HAVE_GMTIME_R)
+  struct tm *pNow;
+#endif
+
+  date[0] = 0;
+  time (&t);
+#if defined(HAVE_C11_GMTIME_S)
+  if (NULL == gmtime_s (&t,
+                        &now))
+    return;
+#elif defined(HAVE_W32_GMTIME_S)
+  if (0 != gmtime_s (&now,
+                     &t))
+    return;
+#elif defined(HAVE_GMTIME_R)
+  if (NULL == gmtime_r (&t,
+                        &now))
+    return;
+#else
+  pNow = gmtime (&t);
+  if (NULL == pNow)
+    return;
+  now = *pNow;
+#endif
+  MHD_snprintf_ (date,
+                 date_len,
+                 "Date: %3s, %02u %3s %04u %02u:%02u:%02u GMT\r\n",
+                 days[now.tm_wday % 7],
+                 (unsigned int) now.tm_mday,
+                 mons[now.tm_mon % 12],
+                 (unsigned int) (1900 + now.tm_year),
+                 (unsigned int) now.tm_hour,
+                 (unsigned int) now.tm_min,
+                 (unsigned int) now.tm_sec);
+}
+
+
+/**
+ * Check whether response header contains particular @a token.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param response  the response to query
+ * @param key       header name
+ * @param token     the token to find
+ * @param token_len the length of token, not including optional
+ *                  terminating null-character.
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+static bool
+check_response_header_token_ci (const struct MHD_Response *response,
+                                const char *key,
+                                const char *token,
+                                size_t token_len)
+{
+  struct MHD_HTTP_Header *pos;
+
+  if ( (NULL == key) ||
+       ('\0' == key[0]) ||
+       (NULL == token) ||
+       ('\0' == token[0]) )
+    return false;
+
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if ( (pos->kind == MHD_HEADER_KIND) &&
+         MHD_str_equal_caseless_ (pos->header,
+                                  key) &&
+         MHD_str_has_token_caseless_ (pos->value,
+                                      token,
+                                      token_len) )
+      return true;
+  }
+  return false;
+}
+
+
+/**
+ * Check whether response header contains particular static @a tkn.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param r   the response to query
+ * @param k   header name
+ * @param tkn the static string of token to find
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+#define check_response_header_s_token_ci(r,k,tkn) \
+  check_response_header_token_ci ((r),(k),(tkn),MHD_STATICSTR_LEN_ (tkn))
+
+
+/**
+ * Allocate the connection's write buffer and fill it with all of the
+ * headers (or footers, if we have already sent the body) from the
+ * HTTPd's response.  If headers are missing in the response supplied
+ * by the application, additional headers may be added here.
+ *
+ * @param request the request for which to build the response header
+ * @return true on success, false on failure (out of memory)
+ */
+static bool
+build_header_response (struct MHD_Request *request)
+{
+  struct MHD_Connection *connection = request->connection;
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Response *response = request->response;
+  size_t size;
+  size_t off;
+  struct MHD_HTTP_Header *pos;
+  char code[256];
+  char date[128];
+  size_t datelen;
+  char content_length_buf[128];
+  size_t content_length_len;
+  char *data;
+  enum MHD_ValueKind kind;
+  bool client_requested_close;
+  bool response_has_close;
+  bool response_has_keepalive;
+  const char *have_encoding;
+  const char *have_content_length;
+  bool must_add_close;
+  bool must_add_chunked_encoding;
+  bool must_add_keep_alive;
+  bool must_add_content_length;
+
+  mhd_assert (NULL != request->version_s);
+  if (0 == request->version_s[0])
+  {
+    data = MHD_pool_allocate (connection->pool,
+                              0,
+                              MHD_YES);
+    request->write_buffer = data;
+    request->write_buffer_append_offset = 0;
+    request->write_buffer_send_offset = 0;
+    request->write_buffer_size = 0;
+    return true;
+  }
+  if (MHD_REQUEST_FOOTERS_RECEIVED == request->state)
+  {
+    const char *reason_phrase;
+    const char *version;
+
+    reason_phrase
+      = MHD_get_reason_phrase_for (response->status_code);
+    version
+      = (response->icy)
+        ? "ICY"
+        : ( (MHD_str_equal_caseless_ (MHD_HTTP_VERSION_1_0,
+                                      request->version_s))
+            ? MHD_HTTP_VERSION_1_0
+            : MHD_HTTP_VERSION_1_1);
+    MHD_snprintf_ (code,
+                   sizeof (code),
+                   "%s %u %s\r\n",
+                   version,
+                   response->status_code,
+                   reason_phrase);
+    off = strlen (code);
+    /* estimate size */
+    size = off + 2;             /* +2 for extra "\r\n" at the end */
+    kind = MHD_HEADER_KIND;
+    if ( (! daemon->suppress_date) &&
+         (NULL == MHD_response_get_header (response,
+                                           MHD_HTTP_HEADER_DATE)) )
+      get_date_string (date,
+                       sizeof (date));
+    else
+      date[0] = '\0';
+    datelen = strlen (date);
+    size += datelen;
+  }
+  else
+  {
+    /* 2 bytes for final CRLF of a Chunked-Body */
+    size = 2;
+    kind = MHD_FOOTER_KIND;
+    off = 0;
+    datelen = 0;
+  }
+
+  /* calculate extra headers we need to add, such as 'Connection: close',
+     first see what was explicitly requested by the application */
+  must_add_close = false;
+  must_add_chunked_encoding = false;
+  must_add_keep_alive = false;
+  must_add_content_length = false;
+  response_has_close = false;
+  switch (request->state)
+  {
+  case MHD_REQUEST_FOOTERS_RECEIVED:
+    response_has_close
+      = check_response_header_s_token_ci (response,
+                                          MHD_HTTP_HEADER_CONNECTION,
+                                          "close");
+    response_has_keepalive
+      = check_response_header_s_token_ci (response,
+                                          MHD_HTTP_HEADER_CONNECTION,
+                                          "Keep-Alive");
+    client_requested_close
+      = MHD_lookup_header_s_token_ci (request,
+                                      MHD_HTTP_HEADER_CONNECTION,
+                                      "close");
+
+    if (response->v10_only)
+      request->keepalive = MHD_CONN_MUST_CLOSE;
+#ifdef UPGRADE_SUPPORT
+    else if (NULL != response->upgrade_handler)
+      /* If this connection will not be "upgraded", it must be closed. */
+      request->keepalive = MHD_CONN_MUST_CLOSE;
+#endif /* UPGRADE_SUPPORT */
+
+    /* now analyze chunked encoding situation */
+    request->have_chunked_upload = false;
+
+    if ( (MHD_SIZE_UNKNOWN == response->total_size) &&
+#ifdef UPGRADE_SUPPORT
+         (NULL == response->upgrade_handler) &&
+#endif /* UPGRADE_SUPPORT */
+         (! response_has_close) &&
+         (! client_requested_close) )
+    {
+      /* size is unknown, and close was not explicitly requested;
+         need to either to HTTP 1.1 chunked encoding or
+         close the connection */
+      /* 'close' header doesn't exist yet, see if we need to add one;
+         if the client asked for a close, no need to start chunk'ing */
+      if ( (keepalive_possible (request)) &&
+           (MHD_str_equal_caseless_ (MHD_HTTP_VERSION_1_1,
+                                     request->version_s)) )
+      {
+        have_encoding
+          = MHD_response_get_header (response,
+                                     MHD_HTTP_HEADER_TRANSFER_ENCODING);
+        if (NULL == have_encoding)
+        {
+          must_add_chunked_encoding = true;
+          request->have_chunked_upload = true;
+        }
+        else if (MHD_str_equal_caseless_ (have_encoding,
+                                          "identity"))
+        {
+          /* application forced identity encoding, can't do 'chunked' */
+          must_add_close = true;
+        }
+        else
+        {
+          request->have_chunked_upload = true;
+        }
+      }
+      else
+      {
+        /* Keep alive or chunking not possible
+           => set close header if not present */
+        if (! response_has_close)
+          must_add_close = true;
+      }
+    }
+
+    /* check for other reasons to add 'close' header */
+    if ( ( (client_requested_close) ||
+           (connection->read_closed) ||
+           (MHD_CONN_MUST_CLOSE == request->keepalive)) &&
+         (! response_has_close) &&
+#ifdef UPGRADE_SUPPORT
+         (NULL == response->upgrade_handler) &&
+#endif /* UPGRADE_SUPPORT */
+         (! response->v10_only) )
+      must_add_close = true;
+
+    /* check if we should add a 'content length' header */
+    have_content_length
+      = MHD_response_get_header (response,
+                                 MHD_HTTP_HEADER_CONTENT_LENGTH);
+
+    /* MHD_HTTP_NO_CONTENT, MHD_HTTP_NOT_MODIFIED and 1xx-status
+       codes SHOULD NOT have a Content-Length according to spec;
+       also chunked encoding / unknown length or CONNECT... */
+    if ( (MHD_SIZE_UNKNOWN != response->total_size) &&
+         (MHD_HTTP_NO_CONTENT != response->status_code) &&
+         (MHD_HTTP_NOT_MODIFIED != response->status_code) &&
+         (MHD_HTTP_OK <= response->status_code) &&
+         (NULL == have_content_length) &&
+         (request->method != MHD_METHOD_CONNECT) )
+    {
+      /*
+        Here we add a content-length if one is missing; however,
+        for 'connect' methods, the responses MUST NOT include a
+        content-length header *if* the response code is 2xx (in
+        which case we expect there to be no body).  Still,
+        as we don't know the response code here in some cases, we
+        simply only force adding a content-length header if this
+        is not a 'connect' or if the response is not empty
+        (which is kind of more sane, because if some crazy
+        application did return content with a 2xx status code,
+        then having a content-length might again be a good idea).
+
+        Note that the change from 'SHOULD NOT' to 'MUST NOT' is
+        a recent development of the HTTP 1.1 specification.
+      */content_length_len
+        = MHD_snprintf_ (content_length_buf,
+                         sizeof (content_length_buf),
+                         MHD_HTTP_HEADER_CONTENT_LENGTH ": "
+                         MHD_UNSIGNED_LONG_LONG_PRINTF "\r\n",
+                         (MHD_UNSIGNED_LONG_LONG) response->total_size);
+      must_add_content_length = true;
+    }
+
+    /* check for adding keep alive */
+    if ( (! response_has_keepalive) &&
+         (! response_has_close) &&
+         (! must_add_close) &&
+         (MHD_CONN_MUST_CLOSE != request->keepalive) &&
+#ifdef UPGRADE_SUPPORT
+         (NULL == response->upgrade_handler) &&
+#endif /* UPGRADE_SUPPORT */
+         (keepalive_possible (request)) )
+      must_add_keep_alive = true;
+    break;
+  case MHD_REQUEST_BODY_SENT:
+    response_has_keepalive = false;
+    break;
+  default:
+    mhd_assert (0);
+    return MHD_NO;
+  }
+
+  if (MHD_CONN_MUST_CLOSE != request->keepalive)
+  {
+    if ( (must_add_close) ||
+         (response_has_close) )
+      request->keepalive = MHD_CONN_MUST_CLOSE;
+    else if ( (must_add_keep_alive) ||
+              (response_has_keepalive) )
+      request->keepalive = MHD_CONN_USE_KEEPALIVE;
+  }
+
+  if (must_add_close)
+    size += MHD_STATICSTR_LEN_ ("Connection: close\r\n");
+  if (must_add_keep_alive)
+    size += MHD_STATICSTR_LEN_ ("Connection: Keep-Alive\r\n");
+  if (must_add_chunked_encoding)
+    size += MHD_STATICSTR_LEN_ ("Transfer-Encoding: chunked\r\n");
+  if (must_add_content_length)
+    size += content_length_len;
+  mhd_assert (! (must_add_close && must_add_keep_alive) );
+  mhd_assert (! (must_add_chunked_encoding && must_add_content_length) );
+
+  for (pos = response->first_header; NULL != pos; pos = pos->next)
+  {
+    /* TODO: add proper support for excluding "Keep-Alive" token. */
+    if ( (pos->kind == kind) &&
+         (! ( (must_add_close) &&
+              (response_has_keepalive) &&
+              (MHD_str_equal_caseless_ (pos->header,
+                                        MHD_HTTP_HEADER_CONNECTION)) &&
+              (MHD_str_equal_caseless_ (pos->value,
+                                        "Keep-Alive")) ) ) )
+      size += strlen (pos->header) + strlen (pos->value) + 4;   /* colon, space, linefeeds */
+  }
+  /* produce data */
+  data = MHD_pool_allocate (connection->pool,
+                            size + 1,
+                            MHD_NO);
+  if (NULL == data)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_CONNECTION_POOL_MALLOC_FAILURE,
+              "Not enough memory for write!\n");
+#endif
+    return false;
+  }
+  if (MHD_REQUEST_FOOTERS_RECEIVED == request->state)
+  {
+    memcpy (data,
+            code,
+            off);
+  }
+  if (must_add_close)
+  {
+    /* we must add the 'Connection: close' header */
+    memcpy (&data[off],
+            "Connection: close\r\n",
+            MHD_STATICSTR_LEN_ ("Connection: close\r\n"));
+    off += MHD_STATICSTR_LEN_ ("Connection: close\r\n");
+  }
+  if (must_add_keep_alive)
+  {
+    /* we must add the 'Connection: Keep-Alive' header */
+    memcpy (&data[off],
+            "Connection: Keep-Alive\r\n",
+            MHD_STATICSTR_LEN_ ("Connection: Keep-Alive\r\n"));
+    off += MHD_STATICSTR_LEN_ ("Connection: Keep-Alive\r\n");
+  }
+  if (must_add_chunked_encoding)
+  {
+    /* we must add the 'Transfer-Encoding: chunked' header */
+    memcpy (&data[off],
+            "Transfer-Encoding: chunked\r\n",
+            MHD_STATICSTR_LEN_ ("Transfer-Encoding: chunked\r\n"));
+    off += MHD_STATICSTR_LEN_ ("Transfer-Encoding: chunked\r\n");
+  }
+  if (must_add_content_length)
+  {
+    /* we must add the 'Content-Length' header */
+    memcpy (&data[off],
+            content_length_buf,
+            content_length_len);
+    off += content_length_len;
+  }
+  for (pos = response->first_header; NULL != pos; pos = pos->next)
+  {
+    /* TODO: add proper support for excluding "Keep-Alive" token. */
+    if ( (pos->kind == kind) &&
+         (! ( (must_add_close) &&
+              (response_has_keepalive) &&
+              (MHD_str_equal_caseless_ (pos->header,
+                                        MHD_HTTP_HEADER_CONNECTION)) &&
+              (MHD_str_equal_caseless_ (pos->value,
+                                        "Keep-Alive")) ) ) )
+      off += MHD_snprintf_ (&data[off],
+                            size - off,
+                            "%s: %s\r\n",
+                            pos->header,
+                            pos->value);
+  }
+  if (MHD_REQUEST_FOOTERS_RECEIVED == request->state)
+  {
+    memcpy (&data[off],
+            date,
+            datelen);
+    off += datelen;
+  }
+  memcpy (&data[off],
+          "\r\n",
+          2);
+  off += 2;
+
+  if (off != size)
+    mhd_panic (mhd_panic_cls,
+               __FILE__,
+               __LINE__,
+               NULL);
+  request->write_buffer = data;
+  request->write_buffer_append_offset = size;
+  request->write_buffer_send_offset = 0;
+  request->write_buffer_size = size + 1;
+  return true;
+}
+
+
+/**
+ * We encountered an error processing the request.  Handle it properly
+ * by stopping to read data and sending the indicated response code
+ * and message.
+ *
+ * @param request the request
+ * @param ec error code for MHD
+ * @param status_code the response code to send (400, 413 or 414)
+ * @param message the error message to send
+ */
+static void
+transmit_error_response (struct MHD_Request *request,
+                         enum MHD_StatusCode ec,
+                         enum MHD_HTTP_StatusCode status_code,
+                         const char *message)
+{
+  struct MHD_Response *response;
+
+  if (NULL == request->version_s)
+  {
+    /* we were unable to process the full header line, so we don't
+ really know what version the client speaks; assume 1.0 */
+    request->version_s = MHD_HTTP_VERSION_1_0;
+  }
+  request->state = MHD_REQUEST_FOOTERS_RECEIVED;
+  request->connection->read_closed = true;
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (request->daemon,
+            ec,
+            _ (
+              "Error processing request (HTTP response code is %u (`%s')). Closing connection.\n"),
+            status_code,
+            message);
+#endif
+  if (NULL != request->response)
+  {
+    MHD_response_queue_for_destroy (request->response);
+    request->response = NULL;
+  }
+  response = MHD_response_from_buffer (status_code,
+                                       strlen (message),
+                                       (void *) message,
+                                       MHD_RESPMEM_PERSISTENT);
+  request->response = response;
+  /* Do not reuse this connection. */
+  request->keepalive = MHD_CONN_MUST_CLOSE;
+  if (! build_header_response (request))
+  {
+    /* oops - close! */
+    CONNECTION_CLOSE_ERROR (request->connection,
+                            ec,
+                            _ (
+                              "Closing connection (failed to create response header).\n"));
+  }
+  else
+  {
+    request->state = MHD_REQUEST_HEADERS_SENDING;
+  }
+}
+
+
+/**
+ * Convert @a method to the respective enum value.
+ *
+ * @param method the method string to look up enum value for
+ * @return resulting enum, or generic value for "unknown"
+ */
+static enum MHD_Method
+method_string_to_enum (const char *method)
+{
+  static const struct
+  {
+    const char *key;
+    enum MHD_Method value;
+  } methods[] = {
+    { "OPTIONS", MHD_METHOD_OPTIONS },
+    { "GET", MHD_METHOD_GET },
+    { "HEAD", MHD_METHOD_HEAD },
+    { "POST", MHD_METHOD_POST },
+    { "PUT", MHD_METHOD_PUT },
+    { "DELETE", MHD_METHOD_DELETE },
+    { "TRACE", MHD_METHOD_TRACE },
+    { "CONNECT", MHD_METHOD_CONNECT },
+    { "ACL", MHD_METHOD_ACL },
+    { "BASELINE_CONTROL", MHD_METHOD_BASELINE_CONTROL },
+    { "BIND", MHD_METHOD_BIND },
+    { "CHECKIN", MHD_METHOD_CHECKIN },
+    { "CHECKOUT", MHD_METHOD_CHECKOUT },
+    { "COPY", MHD_METHOD_COPY },
+    { "LABEL", MHD_METHOD_LABEL },
+    { "LINK", MHD_METHOD_LINK },
+    { "LOCK", MHD_METHOD_LOCK },
+    { "MERGE", MHD_METHOD_MERGE },
+    { "MKACTIVITY", MHD_METHOD_MKACTIVITY },
+    { "MKCOL", MHD_METHOD_MKCOL },
+    { "MKREDIRECTREF", MHD_METHOD_MKREDIRECTREF },
+    { "MKWORKSPACE", MHD_METHOD_MKWORKSPACE },
+    { "MOVE", MHD_METHOD_MOVE },
+    { "ORDERPATCH", MHD_METHOD_ORDERPATCH },
+    { "PRI", MHD_METHOD_PRI },
+    { "PROPFIND", MHD_METHOD_PROPFIND },
+    { "PROPPATCH", MHD_METHOD_PROPPATCH },
+    { "REBIND", MHD_METHOD_REBIND },
+    { "REPORT", MHD_METHOD_REPORT },
+    { "SEARCH", MHD_METHOD_SEARCH },
+    { "UNBIND", MHD_METHOD_UNBIND },
+    { "UNCHECKOUT", MHD_METHOD_UNCHECKOUT },
+    { "UNLINK", MHD_METHOD_UNLINK },
+    { "UNLOCK", MHD_METHOD_UNLOCK },
+    { "UPDATE", MHD_METHOD_UPDATE },
+    { "UPDATEDIRECTREF", MHD_METHOD_UPDATEDIRECTREF },
+    { "VERSION-CONTROL", MHD_METHOD_VERSION_CONTROL },
+    { NULL, MHD_METHOD_UNKNOWN } /* must be last! */
+  };
+  unsigned int i;
+
+  for (i = 0; NULL != methods[i].key; i++)
+    if (0 ==
+        MHD_str_equal_caseless_ (method,
+                                 methods[i].key))
+      return methods[i].value;
+  return MHD_METHOD_UNKNOWN;
+}
+
+
+/**
+ * Add an entry to the HTTP headers of a request.  If this fails,
+ * transmit an error response (request too big).
+ *
+ * @param request the request for which a value should be set
+ * @param kind kind of the value
+ * @param key key for the value
+ * @param value the value itself
+ * @return false on failure (out of memory), true for success
+ */
+static bool
+request_add_header (struct MHD_Request *request,
+                    const char *key,
+                    const char *value,
+                    enum MHD_ValueKind kind)
+{
+  if (MHD_NO ==
+      MHD_request_set_value (request,
+                             kind,
+                             key,
+                             value))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (request->daemon,
+              MHD_SC_CONNECTION_POOL_MALLOC_FAILURE,
+              _ ("Not enough memory in pool to allocate header record!\n"));
+#endif
+    transmit_error_response (request,
+                             MHD_SC_CLIENT_HEADER_TOO_BIG,
+                             MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                             REQUEST_TOO_BIG);
+    return false;
+  }
+  return true;
+}
+
+
+/**
+ * Parse the first line of the HTTP HEADER.
+ *
+ * @param connection the connection (updated)
+ * @param line the first line, not 0-terminated
+ * @param line_len length of the first @a line
+ * @return true if the line is ok, false if it is malformed
+ */
+static bool
+parse_initial_message_line (struct MHD_Request *request,
+                            char *line,
+                            size_t line_len)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  const char *curi;
+  char *uri;
+  char *http_version;
+  char *args;
+  unsigned int unused_num_headers;
+  size_t url_end;
+
+  if (NULL == (uri = memchr (line,
+                             ' ',
+                             line_len)))
+    return false;              /* serious error */
+  uri[0] = '\0';
+  request->method_s = line;
+  request->method = method_string_to_enum (line);
+  uri++;
+  /* Skip any spaces. Not required by standard but allow
+     to be more tolerant. */
+  while ( (' ' == uri[0]) &&
+          ( (size_t) (uri - line) < line_len) )
+    uri++;
+  if ((size_t) (uri - line) == line_len)
+  {
+    curi = "";
+    uri = NULL;
+    request->version_s = "";
+    args = NULL;
+    url_end = line_len - (line - uri);   // EH, this is garbage. FIXME!
+  }
+  else
+  {
+    curi = uri;
+    /* Search from back to accept malformed URI with space */
+    http_version = line + line_len - 1;
+    /* Skip any trailing spaces */
+    while ( (' ' == http_version[0]) &&
+            (http_version > uri) )
+      http_version--;
+    /* Find first space in reverse direction */
+    while ( (' ' != http_version[0]) &&
+            (http_version > uri) )
+      http_version--;
+    if (http_version > uri)
+    {
+      http_version[0] = '\0';
+      request->version_s = http_version + 1;
+      args = memchr (uri,
+                     '?',
+                     http_version - uri);
+    }
+    else
+    {
+      request->version_s = "";
+      args = memchr (uri,
+                     '?',
+                     line_len - (uri - line));
+    }
+    url_end = http_version - uri;
+  }
+  if ( (MHD_PSL_STRICT == daemon->protocol_strict_level) &&
+       (NULL != memchr (curi,
+                        ' ',
+                        url_end)) )
+  {
+    /* space exists in URI and we are supposed to be strict, reject */
+    return MHD_NO;
+  }
+  if (NULL != daemon->early_uri_logger_cb)
+  {
+    request->client_context
+      = daemon->early_uri_logger_cb (daemon->early_uri_logger_cb_cls,
+                                     curi,
+                                     request);
+  }
+  if (NULL != args)
+  {
+    args[0] = '\0';
+    args++;
+    /* note that this call clobbers 'args' */
+    MHD_parse_arguments_ (request,
+                          MHD_GET_ARGUMENT_KIND,
+                          args,
+                          &request_add_header,
+                          &unused_num_headers);
+  }
+  if (NULL != uri)
+    daemon->unescape_cb (daemon->unescape_cb_cls,
+                         request,
+                         uri);
+  request->url = curi;
+  return true;
+}
+
+
+/**
+ * We have received (possibly the beginning of) a line in the
+ * header (or footer).  Validate (check for ":") and prepare
+ * to process.
+ *
+ * @param request the request we're processing
+ * @param line line from the header to process
+ * @return true on success, false on error (malformed @a line)
+ */
+static bool
+process_header_line (struct MHD_Request *request,
+                     char *line)
+{
+  struct MHD_Connection *connection = request->connection;
+  char *colon;
+
+  /* line should be normal header line, find colon */
+  colon = strchr (line,
+                  ':');
+  if (NULL == colon)
+  {
+    /* error in header line, die hard */
+    CONNECTION_CLOSE_ERROR (connection,
+                            MHD_SC_CONNECTION_PARSE_FAIL_CLOSED,
+                            _ (
+                              "Received malformed line (no colon). Closing connection.\n"));
+    return false;
+  }
+  if (MHD_PSL_PERMISSIVE != request->daemon->protocol_strict_level)
+  {
+    /* check for whitespace before colon, which is not allowed
+ by RFC 7230 section 3.2.4; we count space ' ' and
+ tab '\t', but not '\r\n' as those would have ended the line. */
+    const char *white;
+
+    white = strchr (line,
+                    (unsigned char) ' ');
+    if ( (NULL != white) &&
+         (white < colon) )
+    {
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_CONNECTION_PARSE_FAIL_CLOSED,
+                              _ (
+                                "Whitespace before colon forbidden by RFC 7230. Closing connection.\n"));
+      return false;
+    }
+    white = strchr (line,
+                    (unsigned char) '\t');
+    if ( (NULL != white) &&
+         (white < colon) )
+    {
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_CONNECTION_PARSE_FAIL_CLOSED,
+                              _ (
+                                "Tab before colon forbidden by RFC 7230. Closing connection.\n"));
+      return false;
+    }
+  }
+  /* zero-terminate header */
+  colon[0] = '\0';
+  colon++;                      /* advance to value */
+  while ( ('\0' != colon[0]) &&
+          ( (' ' == colon[0]) ||
+            ('\t' == colon[0]) ) )
+    colon++;
+  /* we do the actual adding of the connection
+     header at the beginning of the while
+     loop since we need to be able to inspect
+     the *next* header line (in case it starts
+     with a space...) */request->last = line;
+  request->colon = colon;
+  return true;
+}
+
+
+/**
+ * Process a header value that spans multiple lines.
+ * The previous line(s) are in connection->last.
+ *
+ * @param request the request we're processing
+ * @param line the current input line
+ * @param kind if the line is complete, add a header
+ *        of the given kind
+ * @return true if the line was processed successfully
+ */
+static bool
+process_broken_line (struct MHD_Request *request,
+                     char *line,
+                     enum MHD_ValueKind kind)
+{
+  struct MHD_Connection *connection = request->connection;
+  char *last;
+  char *tmp;
+  size_t last_len;
+  size_t tmp_len;
+
+  last = request->last;
+  if ( (' ' == line[0]) ||
+       ('\t' == line[0]) )
+  {
+    /* value was continued on the next line, see
+       http://www.jmarshall.com/easy/http/ */
+    last_len = strlen (last);
+    /* skip whitespace at start of 2nd line */
+    tmp = line;
+    while ( (' ' == tmp[0]) ||
+            ('\t' == tmp[0]) )
+      tmp++;
+    tmp_len = strlen (tmp);
+    /* FIXME: we might be able to do this better (faster!), as most
+ likely 'last' and 'line' should already be adjacent in
+ memory; however, doing this right gets tricky if we have a
+ value continued over multiple lines (in which case we need to
+ record how often we have done this so we can check for
+ adjacency); also, in the case where these are not adjacent
+ (not sure how it can happen!), we would want to allocate from
+ the end of the pool, so as to not destroy the read-buffer's
+ ability to grow nicely. */last = MHD_pool_reallocate (connection->pool,
+                                last,
+                                last_len + 1,
+                                last_len + tmp_len + 1);
+    if (NULL == last)
+    {
+      transmit_error_response (request,
+                               MHD_SC_CLIENT_HEADER_TOO_BIG,
+                               MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                               REQUEST_TOO_BIG);
+      return MHD_NO;
+    }
+    memcpy (&last[last_len],
+            tmp,
+            tmp_len + 1);
+    request->last = last;
+    return MHD_YES;             /* possibly more than 2 lines... */
+  }
+  mhd_assert ( (NULL != last) &&
+               (NULL != request->colon) );
+  if (! request_add_header (request,
+                            last,
+                            request->colon,
+                            kind))
+  {
+    transmit_error_response (request,
+                             MHD_SC_CLIENT_HEADER_TOO_BIG,
+                             MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                             REQUEST_TOO_BIG);
+    return false;
+  }
+  /* we still have the current line to deal with... */
+  if ('\0' != line[0])
+  {
+    if (! process_header_line (request,
+                               line))
+    {
+      transmit_error_response (request,
+                               MHD_SC_CONNECTION_PARSE_FAIL_CLOSED,
+                               MHD_HTTP_BAD_REQUEST,
+                               REQUEST_MALFORMED);
+      return false;
+    }
+  }
+  return true;
+}
+
+
+/**
+ * Parse a single line of the HTTP header.  Advance read_buffer (!)
+ * appropriately.  If the current line does not fit, consider growing
+ * the buffer.  If the line is far too long, close the connection.  If
+ * no line is found (incomplete, buffer too small, line too long),
+ * return NULL.  Otherwise return a pointer to the line.
+ *
+ * @param request request we're processing
+ * @param[out] line_len pointer to variable that receive
+ *             length of line or NULL
+ * @return NULL if no full line is available; note that the returned
+ *         string will not be 0-termianted
+ */
+static char *
+get_next_header_line (struct MHD_Request *request,
+                      size_t *line_len)
+{
+  char *rbuf;
+  size_t pos;
+
+  if (0 == request->read_buffer_offset)
+    return NULL;
+  pos = 0;
+  rbuf = request->read_buffer;
+  while ( (pos < request->read_buffer_offset - 1) &&
+          ('\r' != rbuf[pos]) &&
+          ('\n' != rbuf[pos]) )
+    pos++;
+  if ( (pos == request->read_buffer_offset - 1) &&
+       ('\n' != rbuf[pos]) )
+  {
+    /* not found, consider growing... */
+    if ( (request->read_buffer_offset == request->read_buffer_size) &&
+         (! try_grow_read_buffer (request)) )
+    {
+      transmit_error_response (request,
+                               MHD_SC_CLIENT_HEADER_TOO_BIG,
+                               (NULL != request->url)
+                               ? MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE
+                               : MHD_HTTP_URI_TOO_LONG,
+                               REQUEST_TOO_BIG);
+    }
+    if (line_len)
+      *line_len = 0;
+    return NULL;
+  }
+
+  if (line_len)
+    *line_len = pos;
+  /* found, check if we have proper LFCR */
+  if ( ('\r' == rbuf[pos]) &&
+       ('\n' == rbuf[pos + 1]) )
+    rbuf[pos++] = '\0';         /* skip both r and n */
+  rbuf[pos++] = '\0';
+  request->read_buffer += pos;
+  request->read_buffer_size -= pos;
+  request->read_buffer_offset -= pos;
+  return rbuf;
+}
+
+
+/**
+ * Check whether is possible to force push socket buffer content as
+ * partial packet.
+ * MHD use different buffering logic depending on whether flushing of
+ * socket buffer is possible or not.
+ * If flushing IS possible than MHD activates extra buffering before
+ * sending data to prevent sending partial packets and flush pending
+ * data in socket buffer to push last partial packet to client after
+ * sending logical completed part of data (for example: after sending
+ * full response header or full response message).
+ * If flushing IS NOT possible than MHD activates no buffering (no
+ * delay sending) when it going to send formed fully completed logical
+ * part of data and activate normal buffering after sending.
+ * For idled keep-alive connection MHD always activate normal
+ * buffering.
+ *
+ * @param connection connection to check
+ * @return true if force push is possible, false otherwise
+ */
+static bool
+socket_flush_possible (struct MHD_Connection *connection)
+{
+  (void) connection; /* Mute compiler warning. */
+#if defined(TCP_CORK) || defined(TCP_PUSH)
+  return true;
+#else  /* !TCP_CORK && !TCP_PUSH */
+  return false;
+#endif /* !TCP_CORK && !TCP_PUSH */
+}
+
+
+/**
+ * Activate extra buffering mode on connection socket to prevent
+ * sending of partial packets.
+ *
+ * @param connection connection to be processed
+ * @return true on success, false otherwise
+ */
+static bool
+socket_start_extra_buffering (struct MHD_Connection *connection)
+{
+  bool res = false;
+  (void) connection; /* Mute compiler warning. */
+#if defined(TCP_CORK) || defined(TCP_NOPUSH)
+  const MHD_SCKT_OPT_BOOL_ on_val = 1;
+#if defined(TCP_NODELAY)
+  const MHD_SCKT_OPT_BOOL_ off_val = 0;
+#endif /* TCP_NODELAY */
+  mhd_assert (NULL != connection);
+#if defined(TCP_NOPUSH) && ! defined(TCP_CORK)
+  /* Buffer data before sending */
+  res = (0 == setsockopt (connection->socket_fd,
+                          IPPROTO_TCP,
+                          TCP_NOPUSH,
+                          (const void *) &on_val,
+                          sizeof (on_val)))
+        ? true : false;
+#if defined(TCP_NODELAY)
+  /* Enable Nagle's algorithm */
+  /* TCP_NODELAY may interfere with TCP_NOPUSH */
+  res &= (0 == setsockopt (connection->socket_fd,
+                           IPPROTO_TCP,
+                           TCP_NODELAY,
+                           (const void *) &off_val,
+                           sizeof (off_val)))
+         ? true : false;
+#endif /* TCP_NODELAY */
+#else /* TCP_CORK */
+#if defined(TCP_NODELAY)
+  /* Enable Nagle's algorithm */
+  /* TCP_NODELAY may prevent enabling TCP_CORK. Resulting buffering mode depends
+     solely on TCP_CORK result, so ignoring return code here. */
+  (void) setsockopt (connection->socket_fd,
+                     IPPROTO_TCP,
+                     TCP_NODELAY,
+                     (const void *) &off_val,
+                     sizeof (off_val));
+#endif /* TCP_NODELAY */
+  /* Send only full packets */
+  res = (0 == setsockopt (connection->socket_fd,
+                          IPPROTO_TCP,
+                          TCP_CORK,
+                          (const void *) &on_val,
+                          sizeof (on_val)))
+        ? true : false;
+#endif /* TCP_CORK */
+#endif /* TCP_CORK || TCP_NOPUSH */
+  return res;
+}
+
+
+/**
+ * Activate no buffering mode (no delay sending) on connection socket.
+ *
+ * @param connection connection to be processed
+ * @return true on success, false otherwise
+ */
+static bool
+socket_start_no_buffering (struct MHD_Connection *connection)
+{
+#if defined(TCP_NODELAY)
+  bool res = true;
+  const MHD_SCKT_OPT_BOOL_ on_val = 1;
+#if defined(TCP_CORK) || defined(TCP_NOPUSH)
+  const MHD_SCKT_OPT_BOOL_ off_val = 0;
+#endif /* TCP_CORK || TCP_NOPUSH */
+
+  (void) connection; /* Mute compiler warning. */
+  mhd_assert (NULL != connection);
+#if defined(TCP_CORK)
+  /* Allow partial packets */
+  res &= (0 == setsockopt (connection->socket_fd,
+                           IPPROTO_TCP,
+                           TCP_CORK,
+                           (const void *) &off_val,
+                           sizeof (off_val)))
+         ? true : false;
+#endif /* TCP_CORK */
+#if defined(TCP_NODELAY)
+  /* Disable Nagle's algorithm for sending packets without delay */
+  res &= (0 == setsockopt (connection->socket_fd,
+                           IPPROTO_TCP,
+                           TCP_NODELAY,
+                           (const void *) &on_val,
+                           sizeof (on_val)))
+         ? true : false;
+#endif /* TCP_NODELAY */
+#if defined(TCP_NOPUSH) && ! defined(TCP_CORK)
+  /* Disable extra buffering */
+  res &= (0 == setsockopt (connection->socket_fd,
+                           IPPROTO_TCP,
+                           TCP_NOPUSH,
+                           (const void *) &off_val,
+                           sizeof (off_val)))
+         ? true : false;
+#endif /* TCP_NOPUSH  && !TCP_CORK */
+  return res;
+#else  /* !TCP_NODELAY */
+  return false;
+#endif /* !TCP_NODELAY */
+}
+
+
+/**
+ * Activate no buffering mode (no delay sending) on connection socket
+ * and push to client data pending in socket buffer.
+ *
+ * @param connection connection to be processed
+ * @return true on success, false otherwise
+ */
+static bool
+socket_start_no_buffering_flush (struct MHD_Connection *connection)
+{
+  bool res = true;
+#if defined(TCP_NOPUSH) && ! defined(TCP_CORK)
+  const int dummy = 0;
+#endif /* !TCP_CORK */
+
+  if (NULL == connection)
+    return false; /* FIXME: use MHD_NONNULL? */
+  res = socket_start_no_buffering (connection);
+#if defined(TCP_NOPUSH) && ! defined(TCP_CORK)
+  /* Force flush data with zero send otherwise Darwin and some BSD systems
+     will add 5 seconds delay. Not required with TCP_CORK as switching off
+     TCP_CORK always flushes socket buffer. */
+  res &= (0 <= MHD_send_ (connection->socket_fd,
+                          &dummy,
+                          0))
+         ? true : false;
+#endif /* TCP_NOPUSH && !TCP_CORK*/
+  return res;
+}
+
+
+/**
+ * Activate normal buffering mode on connection socket.
+ *
+ * @param connection connection to be processed
+ * @return true on success, false otherwise
+ */
+static bool
+socket_start_normal_buffering (struct MHD_Connection *connection)
+{
+#if defined(TCP_NODELAY)
+  bool res = true;
+  const MHD_SCKT_OPT_BOOL_ off_val = 0;
+#if defined(TCP_CORK)
+  MHD_SCKT_OPT_BOOL_ cork_val = 0;
+  socklen_t param_size = sizeof (cork_val);
+#endif /* TCP_CORK */
+
+  mhd_assert (NULL != connection);
+#if defined(TCP_CORK)
+  /* Allow partial packets */
+  /* Disabling TCP_CORK will flush partial packet even if TCP_CORK wasn't enabled before
+     so try to check current value of TCP_CORK to prevent unrequested flushing */
+  if ( (0 != getsockopt (connection->socket_fd,
+                         IPPROTO_TCP,
+                         TCP_CORK,
+                         (void *) &cork_val,
+                         &param_size)) ||
+       (0 != cork_val))
+    res &= (0 == setsockopt (connection->socket_fd,
+                             IPPROTO_TCP,
+                             TCP_CORK,
+                             (const void *) &off_val,
+                             sizeof (off_val)))
+           ? true : false;
+#elif defined(TCP_NOPUSH)
+  /* Disable extra buffering */
+  /* No need to check current value as disabling TCP_NOPUSH will not flush partial
+     packet if TCP_NOPUSH wasn't enabled before */
+  res &= (0 == setsockopt (connection->socket_fd,
+                           IPPROTO_TCP,
+                           TCP_NOPUSH,
+                           (const void *) &off_val,
+                           sizeof (off_val)))
+         ? true : false;
+#endif /* TCP_NOPUSH && !TCP_CORK */
+  /* Enable Nagle's algorithm for normal buffering */
+  res &= (0 == setsockopt (connection->socket_fd,
+                           IPPROTO_TCP,
+                           TCP_NODELAY,
+                           (const void *) &off_val,
+                           sizeof (off_val)))
+         ? true : false;
+  return res;
+#else  /* !TCP_NODELAY */
+  return false;
+#endif /* !TCP_NODELAY */
+}
+
+
+/**
+ * Do we (still) need to send a 100 continue
+ * message for this request?
+ *
+ * @param request the request to test
+ * @return false if we don't need 100 CONTINUE, true if we do
+ */
+static bool
+need_100_continue (struct MHD_Request *request)
+{
+  const char *expect;
+
+  return ( (NULL == request->response) &&
+           (NULL != request->version_s) &&
+           (MHD_str_equal_caseless_ (request->version_s,
+                                     MHD_HTTP_VERSION_1_1)) &&
+           (NULL != (expect = MHD_request_lookup_value (request,
+                                                        MHD_HEADER_KIND,
+                                                        MHD_HTTP_HEADER_EXPECT)))
+           &&
+           (MHD_str_equal_caseless_ (expect,
+                                     "100-continue")) &&
+           (request->continue_message_write_offset <
+            MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE)) );
+}
+
+
+/**
+ * Parse the cookie header (see RFC 2109).
+ *
+ * @param request request to parse header of
+ * @return true for success, false for failure (malformed, out of memory)
+ */
+static int
+parse_cookie_header (struct MHD_Request *request)
+{
+  const char *hdr;
+  char *cpy;
+  char *pos;
+  char *sce;
+  char *semicolon;
+  char *equals;
+  char *ekill;
+  char old;
+  int quotes;
+
+  hdr = MHD_request_lookup_value (request,
+                                  MHD_HEADER_KIND,
+                                  MHD_HTTP_HEADER_COOKIE);
+  if (NULL == hdr)
+    return true;
+  cpy = MHD_pool_allocate (request->connection->pool,
+                           strlen (hdr) + 1,
+                           MHD_YES);
+  if (NULL == cpy)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (request->daemon,
+              MHD_SC_COOKIE_POOL_ALLOCATION_FAILURE,
+              _ ("Not enough memory in pool to parse cookies!\n"));
+#endif
+    transmit_error_response (request,
+                             MHD_SC_COOKIE_POOL_ALLOCATION_FAILURE,
+                             MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                             REQUEST_TOO_BIG);
+    return false;
+  }
+  memcpy (cpy,
+          hdr,
+          strlen (hdr) + 1);
+  pos = cpy;
+  while (NULL != pos)
+  {
+    while (' ' == *pos)
+      pos++;                    /* skip spaces */
+
+    sce = pos;
+    while ( ((*sce) != '\0') &&
+            ((*sce) != ',') &&
+            ((*sce) != ';') &&
+            ((*sce) != '=') )
+      sce++;
+    /* remove tailing whitespace (if any) from key */
+    ekill = sce - 1;
+    while ( (*ekill == ' ') &&
+            (ekill >= pos) )
+      *(ekill--) = '\0';
+    old = *sce;
+    *sce = '\0';
+    if (old != '=')
+    {
+      /* value part omitted, use empty string... */
+      if (! request_add_header (request,
+                                pos,
+                                "",
+                                MHD_COOKIE_KIND))
+        return false;
+      if (old == '\0')
+        break;
+      pos = sce + 1;
+      continue;
+    }
+    equals = sce + 1;
+    quotes = 0;
+    semicolon = equals;
+    while ( ('\0' != semicolon[0]) &&
+            ( (0 != quotes) ||
+              ( (';' != semicolon[0]) &&
+                (',' != semicolon[0]) ) ) )
+    {
+      if ('"' == semicolon[0])
+        quotes = (quotes + 1) & 1;
+      semicolon++;
+    }
+    if ('\0' == semicolon[0])
+      semicolon = NULL;
+    if (NULL != semicolon)
+    {
+      semicolon[0] = '\0';
+      semicolon++;
+    }
+    /* remove quotes */
+    if ( ('"' == equals[0]) &&
+         ('"' == equals[strlen (equals) - 1]) )
+    {
+      equals[strlen (equals) - 1] = '\0';
+      equals++;
+    }
+    if (! request_add_header (request,
+                              pos,
+                              equals,
+                              MHD_COOKIE_KIND))
+      return false;
+    pos = semicolon;
+  }
+  return true;
+}
+
+
+/**
+ * Parse the various headers; figure out the size
+ * of the upload and make sure the headers follow
+ * the protocol.  Advance to the appropriate state.
+ *
+ * @param request request we're processing
+ */
+static void
+parse_request_headers (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Connection *connection = request->connection;
+  const char *clen;
+  struct MHD_Response *response;
+  const char *enc;
+  const char *end;
+
+  parse_cookie_header (request); /* FIXME: return value ignored! */
+  if ( (MHD_PSL_STRICT == daemon->protocol_strict_level) &&
+       (NULL != request->version_s) &&
+       (MHD_str_equal_caseless_ (MHD_HTTP_VERSION_1_1,
+                                 request->version_s)) &&
+       (NULL ==
+        MHD_request_lookup_value (request,
+                                  MHD_HEADER_KIND,
+                                  MHD_HTTP_HEADER_HOST)) )
+  {
+    /* die, http 1.1 request without host and we are pedantic */
+    request->state = MHD_REQUEST_FOOTERS_RECEIVED;
+    connection->read_closed = true;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_HOST_HEADER_MISSING,
+              _ ("Received HTTP 1.1 request without `Host' header.\n"));
+#endif
+    mhd_assert (NULL == request->response);
+    response =
+      MHD_response_from_buffer (MHD_HTTP_BAD_REQUEST,
+                                MHD_STATICSTR_LEN_ (REQUEST_LACKS_HOST),
+                                REQUEST_LACKS_HOST,
+                                MHD_RESPMEM_PERSISTENT);
+    request->response = response;
+    // FIXME: state machine advance?
+    return;
+  }
+
+  request->remaining_upload_size = 0;
+  enc = MHD_request_lookup_value (request,
+                                  MHD_HEADER_KIND,
+                                  MHD_HTTP_HEADER_TRANSFER_ENCODING);
+  if (NULL != enc)
+  {
+    request->remaining_upload_size = MHD_SIZE_UNKNOWN;
+    if (MHD_str_equal_caseless_ (enc,
+                                 "chunked"))
+      request->have_chunked_upload = true;
+    return;
+  }
+  clen = MHD_request_lookup_value (request,
+                                   MHD_HEADER_KIND,
+                                   MHD_HTTP_HEADER_CONTENT_LENGTH);
+  if (NULL == clen)
+    return;
+  end = clen + MHD_str_to_uint64_ (clen,
+                                   &request->remaining_upload_size);
+  if ( (clen == end) ||
+       ('\0' != *end) )
+  {
+    request->remaining_upload_size = 0;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (request->daemon,
+              MHD_SC_CONTENT_LENGTH_MALFORMED,
+              "Failed to parse `Content-Length' header. Closing connection.\n");
+#endif
+    CONNECTION_CLOSE_ERROR (connection,
+                            MHD_SC_CONTENT_LENGTH_MALFORMED,
+                            NULL);
+  }
+}
+
+
+/**
+ * Call the handler of the application for this
+ * request.
+ *
+ * @param request request we're processing
+ */
+static void
+call_request_handler (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Connection *connection = request->connection;
+  const struct MHD_Action *action;
+
+  if (NULL != request->response)
+    return;                     /* already queued a response */
+  if (NULL == (action =
+                 daemon->rc (daemon->rc_cls,
+                             request,
+                             request->url,
+                             request->method)))
+  {
+    /* serious internal error, close connection */
+    CONNECTION_CLOSE_ERROR (connection,
+                            MHD_SC_APPLICATION_CALLBACK_FAILURE_CLOSED,
+                            _ (
+                              "Application reported internal error, closing connection.\n"));
+    return;
+  }
+  action->action (action->action_cls,
+                  request);
+}
+
+
+/**
+ * Call the handler of the application for this request.  Handles
+ * chunking of the upload as well as normal uploads.
+ *
+ * @param request request we're processing
+ */
+static void
+process_request_body (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Connection *connection = request->connection;
+  size_t available;
+  bool instant_retry;
+  char *buffer_head;
+
+  if (NULL != request->response)
+    return;                     /* already queued a response */
+
+  buffer_head = request->read_buffer;
+  available = request->read_buffer_offset;
+  do
+  {
+    size_t to_be_processed;
+    size_t left_unprocessed;
+    size_t processed_size;
+
+    instant_retry = false;
+    if ( (request->have_chunked_upload) &&
+         (MHD_SIZE_UNKNOWN == request->remaining_upload_size) )
+    {
+      if ( (request->current_chunk_offset == request->current_chunk_size) &&
+           (0LLU != request->current_chunk_offset) &&
+           (available >= 2) )
+      {
+        size_t i;
+
+        /* skip new line at the *end* of a chunk */
+        i = 0;
+        if ( ('\r' == buffer_head[i]) ||
+             ('\n' == buffer_head[i]) )
+          i++;                  /* skip 1st part of line feed */
+        if ( ('\r' == buffer_head[i]) ||
+             ('\n' == buffer_head[i]) )
+          i++;                  /* skip 2nd part of line feed */
+        if (0 == i)
+        {
+          /* malformed encoding */
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CHUNKED_ENCODING_MALFORMED,
+                                  _ (
+                                    "Received malformed HTTP request (bad chunked encoding). Closing connection.\n"));
+          return;
+        }
+        available -= i;
+        buffer_head += i;
+        request->current_chunk_offset = 0;
+        request->current_chunk_size = 0;
+      }
+      if (request->current_chunk_offset <
+          request->current_chunk_size)
+      {
+        uint64_t cur_chunk_left;
+
+        /* we are in the middle of a chunk, give
+           as much as possible to the client (without
+           crossing chunk boundaries) */
+        cur_chunk_left
+          = request->current_chunk_size - request->current_chunk_offset;
+        if (cur_chunk_left > available)
+        {
+          to_be_processed = available;
+        }
+        else
+        {         /* cur_chunk_left <= (size_t)available */
+          to_be_processed = (size_t) cur_chunk_left;
+          if (available > to_be_processed)
+            instant_retry = true;
+        }
+      }
+      else
+      {
+        size_t i;
+        size_t end_size;
+        bool malformed;
+
+        /* we need to read chunk boundaries */
+        i = 0;
+        while (i < available)
+        {
+          if ( ('\r' == buffer_head[i]) ||
+               ('\n' == buffer_head[i]) ||
+               (';' == buffer_head[i]) )
+            break;
+          i++;
+          if (i >= 16)
+            break;
+        }
+        end_size = i;
+        /* find beginning of CRLF (skip over chunk extensions) */
+        if (';' == buffer_head[i])
+        {
+          while (i < available)
+          {
+            if ( ('\r' == buffer_head[i]) ||
+                 ('\n' == buffer_head[i]) )
+              break;
+            i++;
+          }
+        }
+        /* take '\n' into account; if '\n' is the unavailable
+           character, we will need to wait until we have it
+           before going further */
+        if ( (i + 1 >= available) &&
+             ! ( (1 == i) &&
+                 (2 == available) &&
+                 ('0' == buffer_head[0]) ) )
+          break;                /* need more data... */
+        i++;
+        malformed = (end_size >= 16);
+        if (! malformed)
+        {
+          size_t num_dig = MHD_strx_to_uint64_n_ (buffer_head,
+                                                  end_size,
+                                                  &request->current_chunk_size);
+          malformed = (end_size != num_dig);
+        }
+        if (malformed)
+        {
+          /* malformed encoding */
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CHUNKED_ENCODING_MALFORMED,
+                                  _ (
+                                    "Received malformed HTTP request (bad chunked encoding). Closing connection.\n"));
+          return;
+        }
+        /* skip 2nd part of line feed */
+        if ( (i < available) &&
+             ( ('\r' == buffer_head[i]) ||
+               ('\n' == buffer_head[i]) ) )
+          i++;
+
+        buffer_head += i;
+        available -= i;
+        request->current_chunk_offset = 0;
+
+        if (available > 0)
+          instant_retry = true;
+        if (0LLU == request->current_chunk_size)
+        {
+          request->remaining_upload_size = 0;
+          break;
+        }
+        continue;
+      }
+    }
+    else
+    {
+      /* no chunked encoding, give all to the client */
+      if ( (0 != request->remaining_upload_size) &&
+           (MHD_SIZE_UNKNOWN != request->remaining_upload_size) &&
+           (request->remaining_upload_size < available) )
+      {
+        to_be_processed = (size_t) request->remaining_upload_size;
+      }
+      else
+      {
+        /**
+         * 1. no chunked encoding, give all to the client
+         * 2. client may send large chunked data, but only a smaller part is available at one time.
+         */
+        to_be_processed = available;
+      }
+    }
+    left_unprocessed = to_be_processed;
+#if FIXME_OLD_STYLE
+    if (MHD_NO ==
+        daemon->rc (daemon->rc_cls,
+                    request,
+                    request->url,
+                    request->method,
+                    request->version,
+                    buffer_head,
+                    &left_unprocessed,
+                    &request->client_context))
+    {
+      /* serious internal error, close connection */
+      CONNECTION_CLOSE_ERROR (connection,
+                              MHD_SC_APPLICATION_CALLBACK_FAILURE_CLOSED,
+                              _ (
+                                "Application reported internal error, closing connection.\n"));
+      return;
+    }
+#endif
+    if (left_unprocessed > to_be_processed)
+      mhd_panic (mhd_panic_cls,
+                 __FILE__,
+                 __LINE__
+#ifdef HAVE_MESSAGES
+                 , _ ("libmicrohttpd API violation.\n")
+#else
+                 , NULL
+#endif
+                 );
+    if (0 != left_unprocessed)
+    {
+      instant_retry = false; /* client did not process everything */
+#ifdef HAVE_MESSAGES
+      /* client did not process all upload data, complain if
+         the setup was incorrect, which may prevent us from
+         handling the rest of the request */
+      if ( (MHD_TM_EXTERNAL_EVENT_LOOP == daemon->threading_mode) &&
+           (! connection->suspended) )
+        MHD_DLOG (daemon,
+                  MHD_SC_APPLICATION_HUNG_CONNECTION,
+                  _ (
+                    "WARNING: incomplete upload processing and connection not suspended may result in hung connection.\n"));
+#endif
+    }
+    processed_size = to_be_processed - left_unprocessed;
+    if (request->have_chunked_upload)
+      request->current_chunk_offset += processed_size;
+    /* dh left "processed" bytes in buffer for next time... */
+    buffer_head += processed_size;
+    available -= processed_size;
+    if (MHD_SIZE_UNKNOWN != request->remaining_upload_size)
+      request->remaining_upload_size -= processed_size;
+  }
+  while (instant_retry);
+  if (available > 0)
+    memmove (request->read_buffer,
+             buffer_head,
+             available);
+  request->read_buffer_offset = available;
+}
+
+
+/**
+ * Clean up the state of the given connection and move it into the
+ * clean up queue for final disposal.
+ * @remark To be called only from thread that process connection's
+ * recv(), send() and response.
+ *
+ * @param connection handle for the connection to clean up
+ */
+static void
+cleanup_connection (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+
+  if (connection->request.in_cleanup)
+    return; /* Prevent double cleanup. */
+  connection->request.in_cleanup = true;
+  if (NULL != connection->request.response)
+  {
+    MHD_response_queue_for_destroy (connection->request.response);
+    connection->request.response = NULL;
+  }
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  if (connection->suspended)
+  {
+    DLL_remove (daemon->suspended_connections_head,
+                daemon->suspended_connections_tail,
+                connection);
+    connection->suspended = false;
+  }
+  else
+  {
+    if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+    {
+      if (connection->connection_timeout ==
+          daemon->connection_default_timeout)
+        XDLL_remove (daemon->normal_timeout_head,
+                     daemon->normal_timeout_tail,
+                     connection);
+      else
+        XDLL_remove (daemon->manual_timeout_head,
+                     daemon->manual_timeout_tail,
+                     connection);
+    }
+    DLL_remove (daemon->connections_head,
+                daemon->connections_tail,
+                connection);
+  }
+  DLL_insert (daemon->cleanup_head,
+              daemon->cleanup_tail,
+              connection);
+  connection->resuming = false;
+  connection->request.in_idle = false;
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+  if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+  {
+    /* if we were at the connection limit before and are in
+       thread-per-connection mode, signal the main thread
+       to resume accepting connections */
+    if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+         (! MHD_itc_activate_ (daemon->itc,
+                               "c")) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_ITC_USE_FAILED,
+                _ (
+                  "Failed to signal end of connection via inter-thread communication channel.\n"));
+#endif
+    }
+  }
+}
+
+
+#ifdef EPOLL_SUPPORT
+/**
+ * Perform epoll() processing, possibly moving the connection back into
+ * the epoll() set if needed.
+ *
+ * @param connection connection to process
+ * @return true if we should continue to process the
+ *         connection (not dead yet), false if it died
+ */
+static bool
+connection_epoll_update_ (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+
+  if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+       (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) &&
+       (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) &&
+       ( ( (MHD_EVENT_LOOP_INFO_WRITE == connection->request.event_loop_info) &&
+           (0 == (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY))) ||
+         ( (MHD_EVENT_LOOP_INFO_READ == connection->request.event_loop_info) &&
+           (0 == (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ) )
+  {
+    /* add to epoll set */
+    struct epoll_event event;
+
+    event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
+    event.data.ptr = connection;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        connection->socket_fd,
+                        &event))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_EPOLL_CTL_ADD_FAILED,
+                _ ("Call to epoll_ctl failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      connection->request.state = MHD_REQUEST_CLOSED;
+      cleanup_connection (connection);
+      return false;
+    }
+    connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
+  }
+  return true;
+}
+
+
+#endif
+
+
+/**
+ * Update the 'event_loop_info' field of this connection based on the
+ * state that the connection is now in.  May also close the connection
+ * or perform other updates to the connection if needed to prepare for
+ * the next round of the event loop.
+ *
+ * @param connection connection to get poll set for
+ */
+static void
+connection_update_event_loop_info (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_Request *request = &connection->request;
+
+  /* Do not update states of suspended connection */
+  if (connection->suspended)
+    return; /* States will be updated after resume. */
+#ifdef HTTPS_SUPPORT
+  {
+    struct MHD_TLS_Plugin *tls;
+
+    if ( (NULL != (tls = daemon->tls_api)) &&
+         (tls->update_event_loop_info (tls->cls,
+                                       connection->tls_cs,
+                                       &request->event_loop_info)) )
+      return; /* TLS has decided what to do */
+  }
+#endif /* HTTPS_SUPPORT */
+  while (1)
+  {
+#if DEBUG_STATES
+    MHD_DLOG (daemon,
+              MHD_SC_STATE_MACHINE_STATUS_REPORT,
+              _ ("In function %s handling connection at state: %s\n"),
+              __FUNCTION__,
+              MHD_state_to_string (request->state));
+#endif
+    switch (request->state)
+    {
+    case MHD_REQUEST_INIT:
+    case MHD_REQUEST_URL_RECEIVED:
+    case MHD_REQUEST_HEADER_PART_RECEIVED:
+      /* while reading headers, we always grow the
+         read buffer if needed, no size-check required */
+      if ( (request->read_buffer_offset == request->read_buffer_size) &&
+           (! try_grow_read_buffer (request)) )
+      {
+        transmit_error_response (request,
+                                 MHD_SC_CLIENT_HEADER_TOO_BIG,
+                                 (NULL != request->url)
+                                 ? MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE
+                                 : MHD_HTTP_URI_TOO_LONG,
+                                 REQUEST_TOO_BIG);
+        continue;
+      }
+      if (! connection->read_closed)
+        request->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      else
+        request->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
+      break;
+    case MHD_REQUEST_HEADERS_RECEIVED:
+      mhd_assert (0);
+      break;
+    case MHD_REQUEST_HEADERS_PROCESSED:
+      mhd_assert (0);
+      break;
+    case MHD_REQUEST_CONTINUE_SENDING:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_REQUEST_CONTINUE_SENT:
+      if (request->read_buffer_offset == request->read_buffer_size)
+      {
+        if ( (! try_grow_read_buffer (request)) &&
+             (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode) )
+        {
+          /* failed to grow the read buffer, and the client
+             which is supposed to handle the received data in
+             a *blocking* fashion (in this mode) did not
+             handle the data as it was supposed to!
+
+             => we would either have to do busy-waiting
+             (on the client, which would likely fail),
+             or if we do nothing, we would just timeout
+             on the connection (if a timeout is even set!).
+
+             Solution: we kill the connection with an error */transmit_error_response (request,
+                                   MHD_SC_APPLICATION_HUNG_CONNECTION_CLOSED,
+                                   MHD_HTTP_INTERNAL_SERVER_ERROR,
+                                   INTERNAL_ERROR);
+          continue;
+        }
+      }
+      if ( (request->read_buffer_offset < request->read_buffer_size) &&
+           (! connection->read_closed) )
+        request->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      else
+        request->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
+      break;
+    case MHD_REQUEST_BODY_RECEIVED:
+    case MHD_REQUEST_FOOTER_PART_RECEIVED:
+      /* while reading footers, we always grow the
+         read buffer if needed, no size-check required */
+      if (connection->read_closed)
+      {
+        CONNECTION_CLOSE_ERROR (connection,
+                                MHD_SC_CONNECTION_READ_FAIL_CLOSED,
+                                NULL);
+        continue;
+      }
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      /* transition to FOOTERS_RECEIVED
+         happens in read handler */
+      break;
+    case MHD_REQUEST_FOOTERS_RECEIVED:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
+      break;
+    case MHD_REQUEST_HEADERS_SENDING:
+      /* headers in buffer, keep writing */
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_REQUEST_HEADERS_SENT:
+      mhd_assert (0);
+      break;
+    case MHD_REQUEST_NORMAL_BODY_READY:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_REQUEST_NORMAL_BODY_UNREADY:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
+      break;
+    case MHD_REQUEST_CHUNKED_BODY_READY:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_REQUEST_CHUNKED_BODY_UNREADY:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
+      break;
+    case MHD_REQUEST_BODY_SENT:
+      mhd_assert (0);
+      break;
+    case MHD_REQUEST_FOOTERS_SENDING:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_REQUEST_FOOTERS_SENT:
+      mhd_assert (0);
+      break;
+    case MHD_REQUEST_CLOSED:
+      request->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
+      return;           /* do nothing, not even reading */
+#ifdef UPGRADE_SUPPORT
+    case MHD_REQUEST_UPGRADE:
+      mhd_assert (0);
+      break;
+#endif /* UPGRADE_SUPPORT */
+    default:
+      mhd_assert (0);
+    }
+    break;
+  }
+}
+
+
+/**
+ * This function was created to handle per-request processing that
+ * has to happen even if the socket cannot be read or written to.
+ * @remark To be called only from thread that process request's
+ * recv(), send() and response.
+ *
+ * @param request the request to handle
+ * @return true if we should continue to process the
+ *         request (not dead yet), false if it died
+ */
+bool
+MHD_request_handle_idle_ (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  struct MHD_Connection *connection = request->connection;
+  char *line;
+  size_t line_len;
+  bool ret;
+
+  request->in_idle = true;
+  while (! connection->suspended)
+  {
+#ifdef HTTPS_SUPPORT
+    struct MHD_TLS_Plugin *tls;
+
+    if ( (NULL != (tls = daemon->tls_api)) &&
+         (! tls->idle_ready (tls->cls,
+                             connection->tls_cs)) )
+      break;
+#endif /* HTTPS_SUPPORT */
+#if DEBUG_STATES
+    MHD_DLOG (daemon,
+              MHD_SC_STATE_MACHINE_STATUS_REPORT,
+              _ ("In function %s handling connection at state: %s\n"),
+              __FUNCTION__,
+              MHD_state_to_string (request->state));
+#endif
+    switch (request->state)
+    {
+    case MHD_REQUEST_INIT:
+      line = get_next_header_line (request,
+                                   &line_len);
+      /* Check for empty string, as we might want
+         to tolerate 'spurious' empty lines; also
+         NULL means we didn't get a full line yet;
+         line is not 0-terminated here. */
+      if ( (NULL == line) ||
+           (0 == line[0]) )
+      {
+        if (MHD_REQUEST_INIT != request->state)
+          continue;
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CONNECTION_READ_FAIL_CLOSED,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (MHD_NO ==
+          parse_initial_message_line (request,
+                                      line,
+                                      line_len))
+        CONNECTION_CLOSE_ERROR (connection,
+                                MHD_SC_CONNECTION_CLOSED,
+                                NULL);
+      else
+        request->state = MHD_REQUEST_URL_RECEIVED;
+      continue;
+    case MHD_REQUEST_URL_RECEIVED:
+      line = get_next_header_line (request,
+                                   NULL);
+      if (NULL == line)
+      {
+        if (MHD_REQUEST_URL_RECEIVED != request->state)
+          continue;
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CONNECTION_READ_FAIL_CLOSED,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (0 == line[0])
+      {
+        request->state = MHD_REQUEST_HEADERS_RECEIVED;
+        request->header_size = (size_t) (line - request->read_buffer);
+        continue;
+      }
+      if (! process_header_line (request,
+                                 line))
+      {
+        transmit_error_response (request,
+                                 MHD_SC_CONNECTION_PARSE_FAIL_CLOSED,
+                                 MHD_HTTP_BAD_REQUEST,
+                                 REQUEST_MALFORMED);
+        break;
+      }
+      request->state = MHD_REQUEST_HEADER_PART_RECEIVED;
+      continue;
+    case MHD_REQUEST_HEADER_PART_RECEIVED:
+      line = get_next_header_line (request,
+                                   NULL);
+      if (NULL == line)
+      {
+        if (request->state != MHD_REQUEST_HEADER_PART_RECEIVED)
+          continue;
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CONNECTION_READ_FAIL_CLOSED,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (MHD_NO ==
+          process_broken_line (request,
+                               line,
+                               MHD_HEADER_KIND))
+        continue;
+      if (0 == line[0])
+      {
+        request->state = MHD_REQUEST_HEADERS_RECEIVED;
+        request->header_size = (size_t) (line - request->read_buffer);
+        continue;
+      }
+      continue;
+    case MHD_REQUEST_HEADERS_RECEIVED:
+      parse_request_headers (request);
+      if (MHD_REQUEST_CLOSED == request->state)
+        continue;
+      request->state = MHD_REQUEST_HEADERS_PROCESSED;
+      if (connection->suspended)
+        break;
+      continue;
+    case MHD_REQUEST_HEADERS_PROCESSED:
+      call_request_handler (request);     /* first call */
+      if (MHD_REQUEST_CLOSED == request->state)
+        continue;
+      if (need_100_continue (request))
+      {
+        request->state = MHD_REQUEST_CONTINUE_SENDING;
+        if (socket_flush_possible (connection))
+          socket_start_extra_buffering (connection);
+        else
+          socket_start_no_buffering (connection);
+        break;
+      }
+      if ( (NULL != request->response) &&
+           ( (MHD_METHOD_POST == request->method) ||
+             (MHD_METHOD_PUT == request->method) ) )
+      {
+        /* we refused (no upload allowed!) */
+        request->remaining_upload_size = 0;
+        /* force close, in case client still tries to upload... */
+        connection->read_closed = true;
+      }
+      request->state = (0 == request->remaining_upload_size)
+                       ? MHD_REQUEST_FOOTERS_RECEIVED
+                       : MHD_REQUEST_CONTINUE_SENT;
+      if (connection->suspended)
+        break;
+      continue;
+    case MHD_REQUEST_CONTINUE_SENDING:
+      if (request->continue_message_write_offset ==
+          MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE))
+      {
+        request->state = MHD_REQUEST_CONTINUE_SENT;
+        if (! socket_flush_possible (connection))
+          socket_start_no_buffering_flush (connection);
+        else
+          socket_start_normal_buffering (connection);
+        continue;
+      }
+      break;
+    case MHD_REQUEST_CONTINUE_SENT:
+      if (0 != request->read_buffer_offset)
+      {
+        process_request_body (request);           /* loop call */
+        if (MHD_REQUEST_CLOSED == request->state)
+          continue;
+      }
+      if ( (0 == request->remaining_upload_size) ||
+           ( (MHD_SIZE_UNKNOWN == request->remaining_upload_size) &&
+             (0 == request->read_buffer_offset) &&
+             (connection->read_closed) ) )
+      {
+        if ( (request->have_chunked_upload) &&
+             (! connection->read_closed) )
+          request->state = MHD_REQUEST_BODY_RECEIVED;
+        else
+          request->state = MHD_REQUEST_FOOTERS_RECEIVED;
+        if (connection->suspended)
+          break;
+        continue;
+      }
+      break;
+    case MHD_REQUEST_BODY_RECEIVED:
+      line = get_next_header_line (request,
+                                   NULL);
+      if (NULL == line)
+      {
+        if (request->state != MHD_REQUEST_BODY_RECEIVED)
+          continue;
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CONNECTION_CLOSED,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (0 == line[0])
+      {
+        request->state = MHD_REQUEST_FOOTERS_RECEIVED;
+        if (connection->suspended)
+          break;
+        continue;
+      }
+      if (MHD_NO == process_header_line (request,
+                                         line))
+      {
+        transmit_error_response (request,
+                                 MHD_SC_CONNECTION_PARSE_FAIL_CLOSED,
+                                 MHD_HTTP_BAD_REQUEST,
+                                 REQUEST_MALFORMED);
+        break;
+      }
+      request->state = MHD_REQUEST_FOOTER_PART_RECEIVED;
+      continue;
+    case MHD_REQUEST_FOOTER_PART_RECEIVED:
+      line = get_next_header_line (request,
+                                   NULL);
+      if (NULL == line)
+      {
+        if (request->state != MHD_REQUEST_FOOTER_PART_RECEIVED)
+          continue;
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CONNECTION_CLOSED,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (MHD_NO ==
+          process_broken_line (request,
+                               line,
+                               MHD_FOOTER_KIND))
+        continue;
+      if (0 == line[0])
+      {
+        request->state = MHD_REQUEST_FOOTERS_RECEIVED;
+        if (connection->suspended)
+          break;
+        continue;
+      }
+      continue;
+    case MHD_REQUEST_FOOTERS_RECEIVED:
+      call_request_handler (request);     /* "final" call */
+      if (request->state == MHD_REQUEST_CLOSED)
+        continue;
+      if (NULL == request->response)
+        break;                  /* try again next time */
+      if (! build_header_response (request))
+      {
+        /* oops - close! */
+        CONNECTION_CLOSE_ERROR (connection,
+                                MHD_SC_FAILED_RESPONSE_HEADER_GENERATION,
+                                _ (
+                                  "Closing connection (failed to create response header).\n"));
+        continue;
+      }
+      request->state = MHD_REQUEST_HEADERS_SENDING;
+      if (MHD_NO != socket_flush_possible (connection))
+        socket_start_extra_buffering (connection);
+      else
+        socket_start_no_buffering (connection);
+
+      break;
+    case MHD_REQUEST_HEADERS_SENDING:
+      /* no default action */
+      break;
+    case MHD_REQUEST_HEADERS_SENT:
+      /* Some clients may take some actions right after header receive */
+      if (MHD_NO != socket_flush_possible (connection))
+        socket_start_no_buffering_flush (connection);
+
+#ifdef UPGRADE_SUPPORT
+      if (NULL != request->response->upgrade_handler)
+      {
+        socket_start_normal_buffering (connection);
+        request->state = MHD_REQUEST_UPGRADE;
+#if FIXME_LEGACY_STYLE
+        /* This request is "upgraded".  Pass socket to application. */
+        if (! MHD_response_execute_upgrade_ (request->response,
+                                             request))
+        {
+          /* upgrade failed, fail hard */
+          CONNECTION_CLOSE_ERROR (connection,
+                                  MHD_SC_CONNECTION_CLOSED,
+                                  NULL);
+          continue;
+        }
+#endif
+        /* Response is not required anymore for this request. */
+        {
+          struct MHD_Response *const resp = request->response;
+
+          request->response = NULL;
+          MHD_response_queue_for_destroy (resp);
+        }
+        continue;
+      }
+#endif /* UPGRADE_SUPPORT */
+      if (MHD_NO != socket_flush_possible (connection))
+        socket_start_extra_buffering (connection);
+      else
+        socket_start_normal_buffering (connection);
+
+      if (request->have_chunked_upload)
+        request->state = MHD_REQUEST_CHUNKED_BODY_UNREADY;
+      else
+        request->state = MHD_REQUEST_NORMAL_BODY_UNREADY;
+      continue;
+    case MHD_REQUEST_NORMAL_BODY_READY:
+      /* nothing to do here */
+      break;
+    case MHD_REQUEST_NORMAL_BODY_UNREADY:
+      if (NULL != request->response->crc)
+        MHD_mutex_lock_chk_ (&request->response->mutex);
+      if (0 == request->response->total_size)
+      {
+        if (NULL != request->response->crc)
+          MHD_mutex_unlock_chk_ (&request->response->mutex);
+        request->state = MHD_REQUEST_BODY_SENT;
+        continue;
+      }
+      if (try_ready_normal_body (request))
+      {
+        if (NULL != request->response->crc)
+          MHD_mutex_unlock_chk_ (&request->response->mutex);
+        request->state = MHD_REQUEST_NORMAL_BODY_READY;
+        /* Buffering for flushable socket was already enabled*/
+        if (MHD_NO == socket_flush_possible (connection))
+          socket_start_no_buffering (connection);
+        break;
+      }
+      /* mutex was already unlocked by "try_ready_normal_body */
+      /* not ready, no socket action */
+      break;
+    case MHD_REQUEST_CHUNKED_BODY_READY:
+      /* nothing to do here */
+      break;
+    case MHD_REQUEST_CHUNKED_BODY_UNREADY:
+      if (NULL != request->response->crc)
+        MHD_mutex_lock_chk_ (&request->response->mutex);
+      if ( (0 == request->response->total_size) ||
+           (request->response_write_position ==
+            request->response->total_size) )
+      {
+        if (NULL != request->response->crc)
+          MHD_mutex_unlock_chk_ (&request->response->mutex);
+        request->state = MHD_REQUEST_BODY_SENT;
+        continue;
+      }
+      if (try_ready_chunked_body (request))
+      {
+        if (NULL != request->response->crc)
+          MHD_mutex_unlock_chk_ (&request->response->mutex);
+        request->state = MHD_REQUEST_CHUNKED_BODY_READY;
+        /* Buffering for flushable socket was already enabled */
+        if (MHD_NO == socket_flush_possible (connection))
+          socket_start_no_buffering (connection);
+        continue;
+      }
+      /* mutex was already unlocked by try_ready_chunked_body */
+      break;
+    case MHD_REQUEST_BODY_SENT:
+      if (! build_header_response (request))
+      {
+        /* oops - close! */
+        CONNECTION_CLOSE_ERROR (connection,
+                                MHD_SC_FAILED_RESPONSE_HEADER_GENERATION,
+                                _ (
+                                  "Closing connection (failed to create response header).\n"));
+        continue;
+      }
+      if ( (! request->have_chunked_upload) ||
+           (request->write_buffer_send_offset ==
+            request->write_buffer_append_offset) )
+        request->state = MHD_REQUEST_FOOTERS_SENT;
+      else
+        request->state = MHD_REQUEST_FOOTERS_SENDING;
+      continue;
+    case MHD_REQUEST_FOOTERS_SENDING:
+      /* no default action */
+      break;
+    case MHD_REQUEST_FOOTERS_SENT:
+      {
+        struct MHD_Response *response = request->response;
+
+        if (MHD_HTTP_PROCESSING == response->status_code)
+        {
+          /* After this type of response, we allow sending another! */
+          request->state = MHD_REQUEST_HEADERS_PROCESSED;
+          MHD_response_queue_for_destroy (response);
+          request->response = NULL;
+          /* FIXME: maybe partially reset memory pool? */
+          continue;
+        }
+        if (socket_flush_possible (connection))
+          socket_start_no_buffering_flush (connection);
+        else
+          socket_start_normal_buffering (connection);
+
+        if (NULL != response->termination_cb)
+        {
+          response->termination_cb (response->termination_cb_cls,
+                                    MHD_REQUEST_TERMINATED_COMPLETED_OK,
+                                    request->client_context);
+        }
+        MHD_response_queue_for_destroy (response);
+        request->response = NULL;
+      }
+      if ( (MHD_CONN_USE_KEEPALIVE != request->keepalive) ||
+           (connection->read_closed) )
+      {
+        /* have to close for some reason */
+        MHD_connection_close_ (connection,
+                               MHD_REQUEST_TERMINATED_COMPLETED_OK);
+        MHD_pool_destroy (connection->pool);
+        connection->pool = NULL;
+        request->read_buffer = NULL;
+        request->read_buffer_size = 0;
+        request->read_buffer_offset = 0;
+      }
+      else
+      {
+        /* can try to keep-alive */
+        if (socket_flush_possible (connection))
+          socket_start_normal_buffering (connection);
+        request->version_s = NULL;
+        request->state = MHD_REQUEST_INIT;
+        request->last = NULL;
+        request->colon = NULL;
+        request->header_size = 0;
+        request->keepalive = MHD_CONN_KEEPALIVE_UNKOWN;
+        /* Reset the read buffer to the starting size,
+           preserving the bytes we have already read. */
+        request->read_buffer
+          = MHD_pool_reset (connection->pool,
+                            request->read_buffer,
+                            request->read_buffer_offset,
+                            daemon->connection_memory_limit_b / 2);
+        request->read_buffer_size
+          = daemon->connection_memory_limit_b / 2;
+      }
+      // FIXME: this is too much, NULLs out some of the things
+      // initialized above...
+      memset (request,
+              0,
+              sizeof (struct MHD_Request));
+      request->daemon = daemon;
+      request->connection = connection;
+      continue;
+    case MHD_REQUEST_CLOSED:
+      cleanup_connection (connection);
+      request->in_idle = false;
+      return false;
+#ifdef UPGRADE_SUPPORT
+    case MHD_REQUEST_UPGRADE:
+      request->in_idle = false;
+      return true;     /* keep open */
+#endif /* UPGRADE_SUPPORT */
+    default:
+      mhd_assert (0);
+      break;
+    }
+    break;
+  }
+  if (! connection->suspended)
+  {
+    time_t timeout;
+    timeout = connection->connection_timeout;
+    if ( (0 != timeout) &&
+         (timeout <= (MHD_monotonic_sec_counter ()
+                      - connection->last_activity)) )
+    {
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_TIMEOUT_REACHED);
+      request->in_idle = false;
+      return true;
+    }
+  }
+  connection_update_event_loop_info (connection);
+  ret = true;
+#ifdef EPOLL_SUPPORT
+  if ( (! connection->suspended) &&
+       (MHD_ELS_EPOLL == daemon->event_loop_syscall) )
+  {
+    ret = connection_epoll_update_ (connection);
+  }
+#endif /* EPOLL_SUPPORT */
+  request->in_idle = false;
+  return ret;
+}
+
+
+/**
+ * Call the handlers for a connection in the appropriate order based
+ * on the readiness as detected by the event loop.
+ *
+ * @param con connection to handle
+ * @param read_ready set if the socket is ready for reading
+ * @param write_ready set if the socket is ready for writing
+ * @param force_close set if a hard error was detected on the socket;
+ *        if this information is not available, simply pass #MHD_NO
+ * @return #MHD_YES to continue normally,
+ *         #MHD_NO if a serious error was encountered and the
+ *         connection is to be closed.
+ */
+// FIXME: rename connection->request?
+int
+MHD_connection_call_handlers_ (struct MHD_Connection *con,
+                               bool read_ready,
+                               bool write_ready,
+                               bool force_close)
+{
+  struct MHD_Daemon *daemon = con->daemon;
+  int ret;
+  bool states_info_processed = false;
+  /* Fast track flag */
+  bool on_fasttrack = (con->request.state == MHD_REQUEST_INIT);
+
+#ifdef HTTPS_SUPPORT
+  if (con->tls_read_ready)
+    read_ready = true;
+#endif /* HTTPS_SUPPORT */
+  if (! force_close)
+  {
+    if ( (MHD_EVENT_LOOP_INFO_READ ==
+          con->request.event_loop_info) &&
+         read_ready)
+    {
+      MHD_request_handle_read_ (&con->request);
+      ret = MHD_request_handle_idle_ (&con->request);
+      states_info_processed = true;
+    }
+    /* No need to check value of 'ret' here as closed connection
+     * cannot be in MHD_EVENT_LOOP_INFO_WRITE state. */
+    if ( (MHD_EVENT_LOOP_INFO_WRITE ==
+          con->request.event_loop_info) &&
+         write_ready)
+    {
+      MHD_request_handle_write_ (&con->request);
+      ret = MHD_request_handle_idle_ (&con->request);
+      states_info_processed = true;
+    }
+  }
+  else
+  {
+    MHD_connection_close_ (con,
+                           MHD_REQUEST_TERMINATED_WITH_ERROR);
+    return MHD_request_handle_idle_ (&con->request);
+  }
+
+  if (! states_info_processed)
+  {   /* Connection is not read or write ready, but external conditions
+       * may be changed and need to be processed. */
+    ret = MHD_request_handle_idle_ (&con->request);
+  }
+  /* Fast track for fast connections. */
+  /* If full request was read by single read_handler() invocation
+     and headers were completely prepared by single MHD_request_handle_idle_()
+     then try not to wait for next sockets polling and send response
+     immediately.
+     As writeability of socket was not checked and it may have
+     some data pending in system buffers, use this optimization
+     only for non-blocking sockets. *//* No need to check 'ret' as connection is always in
+   * MHD_CONNECTION_CLOSED state if 'ret' is equal 'MHD_NO'. */else if (on_fasttrack &&
+           con->sk_nonblck)
+  {
+    if (MHD_REQUEST_HEADERS_SENDING == con->request.state)
+    {
+      MHD_request_handle_write_ (&con->request);
+      /* Always call 'MHD_request_handle_idle_()' after each read/write. */
+      ret = MHD_request_handle_idle_ (&con->request);
+    }
+    /* If all headers were sent by single write_handler() and
+     * response body is prepared by single MHD_request_handle_idle_()
+     * call - continue. */
+    if ((MHD_REQUEST_NORMAL_BODY_READY == con->request.state) ||
+        (MHD_REQUEST_CHUNKED_BODY_READY == con->request.state))
+    {
+      MHD_request_handle_write_ (&con->request);
+      ret = MHD_request_handle_idle_ (&con->request);
+    }
+  }
+
+  /* All connection's data and states are processed for this turn.
+   * If connection already has more data to be processed - use
+   * zero timeout for next select()/poll(). */
+  /* Thread-per-connection do not need global zero timeout as
+   * connections are processed individually. */
+  /* Note: no need to check for read buffer availability for
+   * TLS read-ready connection in 'read info' state as connection
+   * without space in read buffer will be market as 'info block'. */
+  if ( (! daemon->data_already_pending) &&
+       (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode) )
+  {
+    if (MHD_EVENT_LOOP_INFO_BLOCK ==
+        con->request.event_loop_info)
+      daemon->data_already_pending = true;
+#ifdef HTTPS_SUPPORT
+    else if ( (con->tls_read_ready) &&
+              (MHD_EVENT_LOOP_INFO_READ ==
+               con->request.event_loop_info) )
+      daemon->data_already_pending = true;
+#endif /* HTTPS_SUPPORT */
+  }
+  return ret;
+}
+
+
+/* end of connection_call_handlers.c */
diff --git a/src/lib/connection_call_handlers.h b/src/lib/connection_call_handlers.h
new file mode 100644
index 0000000..6297bb9
--- /dev/null
+++ b/src/lib/connection_call_handlers.h
@@ -0,0 +1,64 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_call_handlers.h
+ * @brief function to call event handlers based on event mask
+ * @author Christian Grothoff
+ */
+
+#ifndef CONNECTION_CALL_HANDLERS_H
+#define CONNECTION_CALL_HANDLERS_H
+
+/**
+ * Call the handlers for a connection in the appropriate order based
+ * on the readiness as detected by the event loop.
+ *
+ * @param con connection to handle
+ * @param read_ready set if the socket is ready for reading
+ * @param write_ready set if the socket is ready for writing
+ * @param force_close set if a hard error was detected on the socket;
+ *        if this information is not available, simply pass #MHD_NO
+ * @return #MHD_YES to continue normally,
+ *         #MHD_NO if a serious error was encountered and the
+ *         connection is to be closed.
+ */
+int
+MHD_connection_call_handlers_ (struct MHD_Connection *con,
+                               bool read_ready,
+                               bool write_ready,
+                               bool force_close)
+MHD_NONNULL (1);
+
+
+/**
+ * This function was created to handle per-request processing that
+ * has to happen even if the socket cannot be read or written to.
+ * @remark To be called only from thread that process request's
+ * recv(), send() and response.
+ *
+ * @param request the request to handle
+ * @return true if we should continue to process the
+ *         request (not dead yet), false if it died
+ */
+bool
+MHD_request_handle_idle_ (struct MHD_Request *request)
+MHD_NONNULL (1);
+
+
+#endif
diff --git a/src/lib/connection_cleanup.c b/src/lib/connection_cleanup.c
new file mode 100644
index 0000000..a922452
--- /dev/null
+++ b/src/lib/connection_cleanup.c
@@ -0,0 +1,160 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_cleanup.c
+ * @brief function to clean up completed connections
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_cleanup.h"
+#include "daemon_ip_limit.h"
+
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * Finally cleanup upgrade-related resources. It should
+ * be called when TLS buffers have been drained and
+ * application signaled MHD by #MHD_UPGRADE_ACTION_CLOSE.
+ *
+ * @param connection handle to the upgraded connection to clean
+ */
+static void
+connection_cleanup_upgraded (struct MHD_Connection *connection)
+{
+  struct MHD_UpgradeResponseHandle *urh = connection->request.urh;
+
+  if (NULL == urh)
+    return;
+#ifdef HTTPS_SUPPORT
+  /* Signal remote client the end of TLS connection by
+   * gracefully closing TLS session. */
+  {
+    struct MHD_TLS_Plugin *tls;
+
+    if (NULL != (tls = connection->daemon->tls_api))
+      (void) tls->shutdown_connection (tls->cls,
+                                       connection->tls_cs);
+  }
+  if (MHD_INVALID_SOCKET != urh->mhd.socket)
+    MHD_socket_close_chk_ (urh->mhd.socket);
+  if (MHD_INVALID_SOCKET != urh->app.socket)
+    MHD_socket_close_chk_ (urh->app.socket);
+#endif /* HTTPS_SUPPORT */
+  connection->request.urh = NULL;
+  free (urh);
+}
+
+
+#endif /* UPGRADE_SUPPORT */
+
+
+/**
+ * Free resources associated with all closed connections.  (destroy
+ * responses, free buffers, etc.).  All closed connections are kept in
+ * the "cleanup" doubly-linked list.
+ *
+ * @remark To be called only from thread that process daemon's
+ * select()/poll()/etc.
+ *
+ * @param daemon daemon to clean up
+ */
+void
+MHD_connection_cleanup_ (struct MHD_Daemon *daemon)
+{
+  struct MHD_Connection *pos;
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  while (NULL != (pos = daemon->cleanup_tail))
+  {
+    DLL_remove (daemon->cleanup_head,
+                daemon->cleanup_tail,
+                pos);
+    MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+
+    if ( (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode) &&
+         (! pos->thread_joined) &&
+         (! MHD_join_thread_ (pos->pid.handle)) )
+      MHD_PANIC (_ ("Failed to join a thread.\n"));
+#ifdef UPGRADE_SUPPORT
+    connection_cleanup_upgraded (pos);
+#endif /* UPGRADE_SUPPORT */
+    MHD_pool_destroy (pos->pool);
+#ifdef HTTPS_SUPPORT
+    {
+      struct MHD_TLS_Plugin *tls;
+
+      if (NULL != (tls = daemon->tls_api))
+        tls->teardown_connection (tls->cls,
+                                  pos->tls_cs);
+    }
+#endif /* HTTPS_SUPPORT */
+
+    /* clean up the connection */
+    if (NULL != daemon->notify_connection_cb)
+      daemon->notify_connection_cb (daemon->notify_connection_cb_cls,
+                                    pos,
+                                    MHD_CONNECTION_NOTIFY_CLOSED);
+    MHD_ip_limit_del (daemon,
+                      (const struct sockaddr *) &pos->addr,
+                      pos->addr_len);
+#ifdef EPOLL_SUPPORT
+    if (MHD_ELS_EPOLL == daemon->event_loop_syscall)
+    {
+      if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+      {
+        EDLL_remove (daemon->eready_head,
+                     daemon->eready_tail,
+                     pos);
+        pos->epoll_state &= ~MHD_EPOLL_STATE_IN_EREADY_EDLL;
+      }
+      if ( (-1 != daemon->epoll_fd) &&
+           (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) )
+      {
+        /* epoll documentation suggests that closing a FD
+           automatically removes it from the epoll set; however,
+           this is not true as if we fail to do manually remove it,
+           we are still seeing an event for this fd in epoll,
+           causing grief (use-after-free...) --- at least on my
+           system. */if (0 != epoll_ctl (daemon->epoll_fd,
+                            EPOLL_CTL_DEL,
+                            pos->socket_fd,
+                            NULL))
+          MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+        pos->epoll_state &= ~MHD_EPOLL_STATE_IN_EPOLL_SET;
+      }
+    }
+#endif
+    if (NULL != pos->request.response)
+    {
+      MHD_response_queue_for_destroy (pos->request.response);
+      pos->request.response = NULL;
+    }
+    if (MHD_INVALID_SOCKET != pos->socket_fd)
+      MHD_socket_close_chk_ (pos->socket_fd);
+    free (pos);
+
+    MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+    daemon->connections--;
+    daemon->at_limit = false;
+  }
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+}
+
+
+/* end of connection_cleanup.c */
diff --git a/src/lib/connection_cleanup.h b/src/lib/connection_cleanup.h
new file mode 100644
index 0000000..c6beeee
--- /dev/null
+++ b/src/lib/connection_cleanup.h
@@ -0,0 +1,42 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_cleanup.h
+ * @brief functions to cleanup completed connection
+ * @author Christian Grothoff
+ */
+#ifndef CONNECTION_CLEANUP_H
+#define CONNECTION_CLEANUP_H
+
+
+/**
+ * Free resources associated with all closed connections.  (destroy
+ * responses, free buffers, etc.).  All closed connections are kept in
+ * the "cleanup" doubly-linked list.
+ *
+ * @remark To be called only from thread that process daemon's
+ * select()/poll()/etc.
+ *
+ * @param daemon daemon to clean up
+ */
+void
+MHD_connection_cleanup_ (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/connection_close.c b/src/lib/connection_close.c
new file mode 100644
index 0000000..1effe4b
--- /dev/null
+++ b/src/lib/connection_close.c
@@ -0,0 +1,103 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_close.c
+ * @brief functions to close a connection
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_close.h"
+
+
+/**
+ * Mark connection as "closed".
+ *
+ * @remark To be called from any thread.
+ *
+ * @param connection connection to close
+ */
+void
+MHD_connection_mark_closed_ (struct MHD_Connection *connection)
+{
+  const struct MHD_Daemon *daemon = connection->daemon;
+
+  connection->request.state = MHD_REQUEST_CLOSED;
+  connection->request.event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
+  if (! daemon->enable_turbo)
+  {
+#ifdef HTTPS_SUPPORT
+    struct MHD_TLS_Plugin *tls;
+
+    /* For TLS connection use shutdown of TLS layer
+     * and do not shutdown TCP socket. This give more
+     * chances to send TLS closure data to remote side.
+     * Closure of TLS layer will be interpreted by
+     * remote side as end of transmission. */if (NULL != (tls = daemon->tls_api))
+    {
+      if (MHD_YES !=
+          tls->shutdown_connection (tls->cls,
+                                    connection->tls_cs))
+      {
+        (void) shutdown (connection->socket_fd,
+                         SHUT_WR);
+        /* FIXME: log errors */
+      }
+    }
+    else   /* Combined with next 'shutdown()'. */
+#endif /* HTTPS_SUPPORT */
+    {
+      (void) shutdown (connection->socket_fd,
+                       SHUT_WR); /* FIXME: log errors */
+    }
+  }
+}
+
+
+/**
+ * Close the given connection and give the specified termination code
+ * to the user.
+ *
+ * @remark To be called only from thread that process
+ * connection's recv(), send() and response.
+ *
+ * @param connection connection to close
+ * @param rtc termination reason to give
+ */
+void
+MHD_connection_close_ (struct MHD_Connection *connection,
+                       enum MHD_RequestTerminationCode rtc)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_Response *resp = connection->request.response;
+
+  (void) rtc; // FIXME
+  MHD_connection_mark_closed_ (connection);
+  if (NULL != resp)
+  {
+    connection->request.response = NULL;
+    MHD_response_queue_for_destroy (resp);
+  }
+  if (NULL != daemon->notify_connection_cb)
+    daemon->notify_connection_cb (daemon->notify_connection_cb_cls,
+                                  connection,
+                                  MHD_CONNECTION_NOTIFY_CLOSED);
+}
+
+
+/* end of connection_close.c */
diff --git a/src/lib/connection_close.h b/src/lib/connection_close.h
new file mode 100644
index 0000000..c8e159e
--- /dev/null
+++ b/src/lib/connection_close.h
@@ -0,0 +1,56 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_close.h
+ * @brief functions to close connection
+ * @author Christian Grothoff
+ */
+#ifndef CONNECTION_CLOSE_H
+#define CONNECTION_CLOSE_H
+
+#include "microhttpd2.h"
+
+/**
+ * Mark connection as "closed".
+ *
+ * @remark To be called from any thread.
+ *
+ * @param connection connection to close
+ */
+void
+MHD_connection_mark_closed_ (struct MHD_Connection *connection)
+MHD_NONNULL (1);
+
+
+/**
+ * Close the given connection and give the specified termination code
+ * to the user.
+ *
+ * @remark To be called only from thread that process
+ * connection's recv(), send() and response.
+ *
+ * @param connection connection to close
+ * @param rtc termination reason to give
+ */
+void
+MHD_connection_close_ (struct MHD_Connection *connection,
+                       enum MHD_RequestTerminationCode rtc)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/connection_finish_forward.c b/src/lib/connection_finish_forward.c
new file mode 100644
index 0000000..74b5b48
--- /dev/null
+++ b/src/lib/connection_finish_forward.c
@@ -0,0 +1,95 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_finish_forward.c
+ * @brief complete upgrade socket forwarding operation in TLS mode
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_finish_forward.h"
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Stop TLS forwarding on upgraded connection and
+ * reflect remote disconnect state to socketpair.
+ * @remark In thread-per-connection mode this function
+ * can be called from any thread, in other modes this
+ * function must be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param connection the upgraded connection
+ */
+void
+MHD_connection_finish_forward_ (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_UpgradeResponseHandle *urh = connection->request.urh;
+
+  if (NULL == daemon->tls_api)
+    return; /* Nothing to do with non-TLS connection. */
+
+  if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+    DLL_remove (daemon->urh_head,
+                daemon->urh_tail,
+                urh);
+#if EPOLL_SUPPORT
+  if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+       (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                        EPOLL_CTL_DEL,
+                        connection->socket_fd,
+                        NULL)) )
+  {
+    MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+  }
+  if (urh->in_eready_list)
+  {
+    EDLL_remove (daemon->eready_urh_head,
+                 daemon->eready_urh_tail,
+                 urh);
+    urh->in_eready_list = false;
+  }
+#endif /* EPOLL_SUPPORT */
+  if (MHD_INVALID_SOCKET != urh->mhd.socket)
+  {
+#if EPOLL_SUPPORT
+    if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+         (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                          EPOLL_CTL_DEL,
+                          urh->mhd.socket,
+                          NULL)) )
+    {
+      MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+    }
+#endif /* EPOLL_SUPPORT */
+    /* Reflect remote disconnect to application by breaking
+     * socketpair connection. */
+    shutdown (urh->mhd.socket,
+              SHUT_RDWR);
+  }
+  /* Socketpair sockets will remain open as they will be
+   * used with MHD_UPGRADE_ACTION_CLOSE. They will be
+   * closed by MHD_cleanup_upgraded_connection_() during
+   * connection's final cleanup.
+   */}
+
+
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT*/
+
+/* end of connection_finish_forward.c */
diff --git a/src/lib/connection_finish_forward.h b/src/lib/connection_finish_forward.h
new file mode 100644
index 0000000..ebb77d1
--- /dev/null
+++ b/src/lib/connection_finish_forward.h
@@ -0,0 +1,44 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_finish_forward.h
+ * @brief complete upgrade socket forwarding operation in TLS mode
+ * @author Christian Grothoff
+ */
+
+#ifndef CONNECTION_FINISH_FORWARD_H
+#define CONNECTION_FINISH_FORWARD_H
+
+
+/**
+ * Stop TLS forwarding on upgraded connection and
+ * reflect remote disconnect state to socketpair.
+ *
+ * @remark In thread-per-connection mode this function
+ * can be called from any thread, in other modes this
+ * function must be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param connection the upgraded connection
+ */
+void
+MHD_connection_finish_forward_ (struct MHD_Connection *connection)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/connection_info.c b/src/lib/connection_info.c
new file mode 100644
index 0000000..45f1406
--- /dev/null
+++ b/src/lib/connection_info.c
@@ -0,0 +1,111 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/connection_info.c
+ * @brief implementation of MHD_connection_get_information_sz()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Obtain information about the given connection.
+ * Use wrapper macro #MHD_connection_get_information() instead of direct use
+ * of this function.
+ *
+ * @param connection what connection to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @param return_value_size size of union MHD_ConnectionInformation at compile
+ *                          time
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+enum MHD_Bool
+MHD_connection_get_information_sz (struct MHD_Connection *connection,
+                                   enum MHD_ConnectionInformationType info_type,
+                                   union MHD_ConnectionInformation *return_value,
+                                   size_t return_value_size)
+{
+#define CHECK_SIZE(type) if (sizeof(type) < return_value_size) \
+    return MHD_NO
+
+  switch (info_type)
+  {
+#ifdef HTTPS_SUPPORT
+  case MHD_CONNECTION_INFORMATION_CIPHER_ALGO:
+    CHECK_SIZE (int);
+    if (NULL == connection->tls_cs)
+      return MHD_NO;
+    // return_value->cipher_algorithm
+    //  = gnutls_cipher_get (connection->tls_session);
+    return MHD_NO; // FIXME: to be implemented
+  case MHD_CONNECTION_INFORMATION_PROTOCOL:
+    CHECK_SIZE (int);
+    if (NULL == connection->tls_cs)
+      return MHD_NO;
+    // return_value->protocol
+    //  = gnutls_protocol_get_version (connection->tls_session);
+    return MHD_NO; // FIXME: to be implemented
+  case MHD_CONNECTION_INFORMATION_GNUTLS_SESSION:
+    CHECK_SIZE (void *);
+    if (NULL == connection->tls_cs)
+      return MHD_NO;
+    // return_value->tls_session = connection->tls_session;
+    return MHD_NO; // FIXME: to be implemented
+#endif /* HTTPS_SUPPORT */
+  case MHD_CONNECTION_INFORMATION_CLIENT_ADDRESS:
+    CHECK_SIZE (struct sockaddr *);
+    return_value->client_addr
+      = (const struct sockaddr *) &connection->addr;
+    return MHD_YES;
+  case MHD_CONNECTION_INFORMATION_DAEMON:
+    CHECK_SIZE (struct MHD_Daemon *);
+    return_value->daemon = connection->daemon;
+    return MHD_YES;
+  case MHD_CONNECTION_INFORMATION_CONNECTION_FD:
+    CHECK_SIZE (MHD_socket);
+    return_value->connect_fd = connection->socket_fd;
+    return MHD_YES;
+  case MHD_CONNECTION_INFORMATION_SOCKET_CONTEXT:
+    CHECK_SIZE (void **);
+    return_value->socket_context = &connection->socket_context;
+    return MHD_YES;
+  case MHD_CONNECTION_INFORMATION_CONNECTION_SUSPENDED:
+    CHECK_SIZE (enum MHD_Bool);
+    return_value->suspended
+      = connection->suspended ? MHD_YES : MHD_NO;
+    return MHD_YES;
+  case MHD_CONNECTION_INFORMATION_CONNECTION_TIMEOUT:
+    CHECK_SIZE (unsigned int);
+    return_value->connection_timeout
+      = (unsigned int) connection->connection_timeout;
+    return MHD_YES;
+  default:
+    return MHD_NO;
+  }
+
+#undef CHECK_SIZE
+}
+
+
+/* end of connection_info.c */
diff --git a/src/lib/connection_options.c b/src/lib/connection_options.c
new file mode 100644
index 0000000..ad6a0fa
--- /dev/null
+++ b/src/lib/connection_options.c
@@ -0,0 +1,118 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/connection_options.c
+ * @brief functions to set per-connection options
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Set custom timeout for the given connection.  Specified as the
+ * number of seconds.  Use zero for no timeout.  Calling this function
+ * will reset timeout timer.
+ *
+ * @param connection connection to configure timeout for
+ * @param timeout_s new timeout in seconds
+ */
+void
+MHD_connection_set_timeout (struct MHD_Connection *connection,
+                            unsigned int timeout_s)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+
+  connection->last_activity = MHD_monotonic_sec_counter ();
+  if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+  {
+    /* Simple case, no need to lock to update DLLs */
+    connection->connection_timeout = (time_t) timeout_s;
+    return;
+  }
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  if (! connection->suspended)
+  {
+    if (connection->connection_timeout ==
+        daemon->connection_default_timeout)
+      XDLL_remove (daemon->normal_timeout_head,
+                   daemon->normal_timeout_tail,
+                   connection);
+    else
+      XDLL_remove (daemon->manual_timeout_head,
+                   daemon->manual_timeout_tail,
+                   connection);
+  }
+  connection->connection_timeout = (time_t) timeout_s;
+  if (! connection->suspended)
+  {
+    if (connection->connection_timeout ==
+        daemon->connection_default_timeout)
+      XDLL_insert (daemon->normal_timeout_head,
+                   daemon->normal_timeout_tail,
+                   connection);
+    else
+      XDLL_insert (daemon->manual_timeout_head,
+                   daemon->manual_timeout_tail,
+                   connection);
+  }
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+}
+
+
+/**
+ * Update the 'last_activity' field of the connection to the current
+ * time and move the connection to the head of the 'normal_timeout'
+ * list if the timeout for the connection uses the default value.
+ *
+ * @param connection the connection that saw some activity
+ */
+void
+MHD_update_last_activity_ (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+
+  if (0 == connection->connection_timeout)
+    return;  /* Skip update of activity for connections
+               without timeout timer. */
+  if (connection->suspended)
+    return;  /* no activity on suspended connections */
+
+  connection->last_activity = MHD_monotonic_sec_counter ();
+  if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+    return; /* each connection has personal timeout */
+
+  if (connection->connection_timeout !=
+      daemon->connection_default_timeout)
+    return; /* custom timeout, no need to move it in "normal" DLL */
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  /* move connection to head of timeout list (by remove + add operation) */
+  XDLL_remove (daemon->normal_timeout_head,
+               daemon->normal_timeout_tail,
+               connection);
+  XDLL_insert (daemon->normal_timeout_head,
+               daemon->normal_timeout_tail,
+               connection);
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+}
+
+
+/* end of connection_options.c */
diff --git a/src/lib/connection_update_last_activity.c b/src/lib/connection_update_last_activity.c
new file mode 100644
index 0000000..326b5b3
--- /dev/null
+++ b/src/lib/connection_update_last_activity.c
@@ -0,0 +1,65 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_update_last_activity.c
+ * @brief functions to add connection to our active set
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_update_last_activity.h"
+
+
+/**
+ * Update the 'last_activity' field of the connection to the current time
+ * and move the connection to the head of the 'normal_timeout' list if
+ * the timeout for the connection uses the default value.
+ *
+ * @param connection the connection that saw some activity
+ */
+void
+MHD_connection_update_last_activity_ (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+
+  if (0 == connection->connection_timeout)
+    return;  /* Skip update of activity for connections
+               without timeout timer. */
+  if (connection->suspended)
+    return;  /* no activity on suspended connections */
+
+  connection->last_activity = MHD_monotonic_sec_counter ();
+  if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+    return; /* each connection has personal timeout */
+
+  if (connection->connection_timeout != daemon->connection_default_timeout)
+    return; /* custom timeout, no need to move it in "normal" DLL */
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  /* move connection to head of timeout list (by remove + add operation) */
+  XDLL_remove (daemon->normal_timeout_head,
+               daemon->normal_timeout_tail,
+               connection);
+  XDLL_insert (daemon->normal_timeout_head,
+               daemon->normal_timeout_tail,
+               connection);
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+}
+
+
+/* end of connection_update_last_activity.c */
diff --git a/src/lib/connection_update_last_activity.h b/src/lib/connection_update_last_activity.h
new file mode 100644
index 0000000..ee9f997
--- /dev/null
+++ b/src/lib/connection_update_last_activity.h
@@ -0,0 +1,40 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/connection_update_last_activity.h
+ * @brief function to update last activity of a connection
+ * @author Christian Grothoff
+ */
+
+#ifndef CONNECTION_UPDATE_LAST_ACTIVITY_H
+#define CONNECTION_UPDATE_LAST_ACTIVITY_H
+
+
+/**
+ * Update the 'last_activity' field of the connection to the current time
+ * and move the connection to the head of the 'normal_timeout' list if
+ * the timeout for the connection uses the default value.
+ *
+ * @param connection the connection that saw some activity
+ */
+void
+MHD_connection_update_last_activity_ (struct MHD_Connection *connection)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/daemon_close_all_connections.c b/src/lib/daemon_close_all_connections.c
new file mode 100644
index 0000000..6d19240
--- /dev/null
+++ b/src/lib/daemon_close_all_connections.c
@@ -0,0 +1,237 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_close_all_connections.c
+ * @brief function to close all connections open at a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_cleanup.h"
+#include "connection_close.h"
+#include "connection_finish_forward.h"
+#include "daemon_close_all_connections.h"
+#include "request_resume.h"
+#include "upgrade_process.h"
+
+
+/**
+ * Close the given connection, remove it from all of its
+ * DLLs and move it into the cleanup queue.
+ * @remark To be called only from thread that
+ * process daemon's select()/poll()/etc.
+ *
+ * @param pos connection to move to cleanup
+ */
+static void
+close_connection (struct MHD_Connection *pos)
+{
+  struct MHD_Daemon *daemon = pos->daemon;
+
+  if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+  {
+    MHD_connection_mark_closed_ (pos);
+    return;   /* must let thread to do the rest */
+  }
+  MHD_connection_close_ (pos,
+                         MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN);
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+
+  mhd_assert (! pos->suspended);
+  mhd_assert (! pos->resuming);
+  if (pos->connection_timeout ==
+      pos->daemon->connection_default_timeout)
+    XDLL_remove (daemon->normal_timeout_head,
+                 daemon->normal_timeout_tail,
+                 pos);
+  else
+    XDLL_remove (daemon->manual_timeout_head,
+                 daemon->manual_timeout_tail,
+                 pos);
+  DLL_remove (daemon->connections_head,
+              daemon->connections_tail,
+              pos);
+  DLL_insert (daemon->cleanup_head,
+              daemon->cleanup_tail,
+              pos);
+
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+}
+
+
+/**
+ * Close all connections for the daemon.  Must only be called when
+ * MHD_Daemon::shutdown was set to true.
+ *
+ * @remark To be called only from thread that process daemon's
+ * select()/poll()/etc.
+ *
+ * @param daemon daemon to close down
+ */
+void
+MHD_daemon_close_all_connections_ (struct MHD_Daemon *daemon)
+{
+  struct MHD_Connection *pos;
+  const bool used_thr_p_c = (MHD_TM_THREAD_PER_CONNECTION ==
+                             daemon->threading_mode);
+#ifdef UPGRADE_SUPPORT
+  const bool upg_allowed = (! daemon->disallow_upgrade);
+#endif /* UPGRADE_SUPPORT */
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  struct MHD_UpgradeResponseHandle *urh;
+  struct MHD_UpgradeResponseHandle *urhn;
+  const bool used_tls = (NULL != daemon->tls_api);
+
+  mhd_assert (NULL == daemon->worker_pool);
+  mhd_assert (daemon->shutdown);
+  /* give upgraded HTTPS connections a chance to finish */
+  /* 'daemon->urh_head' is not used in thread-per-connection mode. */
+  for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
+  {
+    urhn = urh->prev;
+    /* call generic forwarding function for passing data
+       with chance to detect that application is done. */
+    MHD_upgrade_response_handle_process_ (urh);
+    MHD_connection_finish_forward_ (urh->connection);
+    urh->clean_ready = true;
+    /* Resuming will move connection to cleanup list. */
+    MHD_request_resume (&urh->connection->request);
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+  /* Give suspended connections a chance to resume to avoid
+     running into the check for there not being any suspended
+     connections left in case of a tight race with a recently
+     resumed connection. */
+  if (! daemon->disallow_suspend_resume)
+  {
+    daemon->resuming = true;   /* Force check for pending resume. */
+    MHD_resume_suspended_connections_ (daemon);
+  }
+  /* first, make sure all threads are aware of shutdown; need to
+     traverse DLLs in peace... */
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#ifdef UPGRADE_SUPPORT
+  if (upg_allowed)
+  {
+    struct MHD_Connection *susp;
+
+    susp = daemon->suspended_connections_tail;
+    while (NULL != susp)
+    {
+      if (NULL == susp->request.urh)     /* "Upgraded" connection? */
+        MHD_PANIC (_ (
+                     "MHD_stop_daemon() called while we have suspended connections.\n"));
+#ifdef HTTPS_SUPPORT
+      else if (used_tls &&
+               used_thr_p_c &&
+               (! susp->request.urh->clean_ready) )
+        shutdown (susp->request.urh->app.socket,
+                  SHUT_RDWR);     /* Wake thread by shutdown of app socket. */
+#endif /* HTTPS_SUPPORT */
+      else
+      {
+#ifdef HAVE_MESSAGES
+        if (! susp->request.urh->was_closed)
+          MHD_DLOG (daemon,
+                    MHD_SC_SHUTDOWN_WITH_OPEN_UPGRADED_CONNECTION,
+                    _ (
+                      "Initiated daemon shutdown while \"upgraded\" connection was not closed.\n"));
+#endif
+        susp->request.urh->was_closed = true;
+        /* If thread-per-connection is used, connection's thread
+         * may still processing "upgrade" (exiting). */
+        if (! used_thr_p_c)
+          MHD_connection_finish_forward_ (susp);
+        /* Do not use MHD_resume_connection() as mutex is
+         * already locked. */
+        susp->resuming = true;
+        daemon->resuming = true;
+      }
+      susp = susp->prev;
+    }
+  }
+  else /* This 'else' is combined with next 'if' */
+#endif /* UPGRADE_SUPPORT */
+  if (NULL != daemon->suspended_connections_head)
+    MHD_PANIC (_ (
+                 "MHD_stop_daemon() called while we have suspended connections.\n"));
+  for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev)
+  {
+    shutdown (pos->socket_fd,
+              SHUT_RDWR);
+#if MHD_WINSOCK_SOCKETS
+    if ( (used_thr_p_c) &&
+         (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+         (! MHD_itc_activate_ (daemon->itc,
+                               "e")) )
+      MHD_PANIC (_ (
+                   "Failed to signal shutdown via inter-thread communication channel.\n"));
+#endif
+  }
+
+  /* now, collect per-connection threads */
+  if (used_thr_p_c)
+  {
+    pos = daemon->connections_tail;
+    while (NULL != pos)
+    {
+      if (! pos->thread_joined)
+      {
+        MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+        if (! MHD_join_thread_ (pos->pid.handle))
+          MHD_PANIC (_ ("Failed to join a thread.\n"));
+        MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+        pos->thread_joined = true;
+        /* The thread may have concurrently modified the DLL,
+           need to restart from the beginning */
+        pos = daemon->connections_tail;
+        continue;
+      }
+      pos = pos->prev;
+    }
+  }
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+
+#ifdef UPGRADE_SUPPORT
+  /* Finished threads with "upgraded" connections need to be moved
+   * to cleanup list by resume_suspended_connections(). */
+  /* "Upgraded" connections that were not closed explicitly by
+   * application should be moved to cleanup list too. */
+  if (upg_allowed)
+  {
+    daemon->resuming = true;   /* Force check for pending resume. */
+    MHD_resume_suspended_connections_ (daemon);
+  }
+#endif /* UPGRADE_SUPPORT */
+
+  /* now that we're alone, move everyone to cleanup */
+  while (NULL != (pos = daemon->connections_tail))
+  {
+    if ( (used_thr_p_c) &&
+         (! pos->thread_joined) )
+      MHD_PANIC (_ ("Failed to join a thread.\n"));
+    close_connection (pos);
+  }
+  MHD_connection_cleanup_ (daemon);
+}
+
+
+/* end of daemon_close_all_connections.c */
diff --git a/src/lib/daemon_close_all_connections.h b/src/lib/daemon_close_all_connections.h
new file mode 100644
index 0000000..2716f9b
--- /dev/null
+++ b/src/lib/daemon_close_all_connections.h
@@ -0,0 +1,42 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_close_all_connections.h
+ * @brief function to close all connections open at a daemon
+ * @author Christian Grothoff
+ */
+#ifndef DAEMON_CLOSE_ALL_CONNECTIONS_H
+#define DAEMON_CLOSE_ALL_CONNECTIONS_H
+
+
+/**
+ * Close all connections for the daemon.  Must only be called when
+ * MHD_Daemon::shutdown was set to true.
+ *
+ * @remark To be called only from thread that process daemon's
+ * select()/poll()/etc.
+ *
+ * @param daemon daemon to close down
+ */
+void
+MHD_daemon_close_all_connections_ (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/daemon_create.c b/src/lib/daemon_create.c
new file mode 100644
index 0000000..cd3d0ec
--- /dev/null
+++ b/src/lib/daemon_create.c
@@ -0,0 +1,138 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_create.c
+ * @brief main functions to create a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "init.h"
+
+
+/**
+ * Logging implementation that logs to a file given
+ * as the @a cls.
+ *
+ * @param cls a `FILE *` to log to
+ * @param sc status code of the event (ignored)
+ * @param fm format string (`printf()`-style)
+ * @param ap arguments to @a fm
+ * @ingroup logging
+ */
+static void
+file_logger (void *cls,
+             enum MHD_StatusCode sc,
+             const char *fm,
+             va_list ap)
+{
+  FILE *f = cls;
+
+  (void) sc;
+  (void) vfprintf (f,
+                   fm,
+                   ap);
+}
+
+
+/**
+ * Process escape sequences ('%HH') Updates val in place; the
+ * result should be UTF-8 encoded and cannot be larger than the input.
+ * The result must also still be 0-terminated.
+ *
+ * @param cls closure (use NULL)
+ * @param req handle to request, not used
+ * @param val value to unescape (modified in the process)
+ * @return length of the resulting val (strlen(val) maybe
+ *  shorter afterwards due to elimination of escape sequences)
+ */
+static size_t
+unescape_wrapper (void *cls,
+                  struct MHD_Request *req,
+                  char *val)
+{
+  (void) cls; /* Mute compiler warning. */
+  (void) req; /* Mute compiler warning. */
+  return MHD_http_unescape (val);
+}
+
+
+/**
+ * Create (but do not yet start) an MHD daemon.
+ * Usually, you will want to set various options before
+ * starting the daemon with #MHD_daemon_start().
+ *
+ * @param cb function to be called for incoming requests
+ * @param cb_cls closure for @a cb
+ * @return NULL on error
+ */
+struct MHD_Daemon *
+MHD_daemon_create (MHD_RequestCallback cb,
+                   void *cb_cls)
+{
+  struct MHD_Daemon *daemon;
+
+  MHD_check_global_init_ ();
+  if (NULL == (daemon = malloc (sizeof (struct MHD_Daemon))))
+    return NULL;
+  memset (daemon,
+          0,
+          sizeof (struct MHD_Daemon));
+#ifdef EPOLL_SUPPORT
+  daemon->epoll_itc_marker = "itc_marker";
+#endif
+  daemon->rc = cb;
+  daemon->rc_cls = cb_cls;
+  daemon->logger = &file_logger;
+  daemon->logger_cls = stderr;
+  daemon->unescape_cb = &unescape_wrapper;
+  daemon->connection_memory_limit_b = POOL_SIZE_DEFAULT;
+  daemon->connection_memory_increment_b = BUF_INC_SIZE_DEFAULT;
+#if ENABLE_DAUTH
+  daemon->digest_nc_length = DIGEST_NC_LENGTH_DEFAULT;
+#endif
+  daemon->listen_backlog = LISTEN_BACKLOG_DEFAULT;
+  daemon->fo_queue_length = FO_QUEUE_LENGTH_DEFAULT;
+  daemon->listen_socket = MHD_INVALID_SOCKET;
+
+  if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex))
+  {
+    free (daemon);
+    return NULL;
+  }
+  if (! MHD_mutex_init_ (&daemon->per_ip_connection_mutex))
+  {
+    (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
+    free (daemon);
+    return NULL;
+  }
+#ifdef DAUTH_SUPPORT
+  if (! MHD_mutex_init_ (&daemon->nnc_lock))
+  {
+    (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
+    (void) MHD_mutex_destroy_ (&daemon->per_ip_connection_mutex);
+    free (daemon);
+    return NULL;
+  }
+#endif
+  return daemon;
+}
+
+
+/* end of daemon_create.c */
diff --git a/src/lib/daemon_destroy.c b/src/lib/daemon_destroy.c
new file mode 100644
index 0000000..07cd715
--- /dev/null
+++ b/src/lib/daemon_destroy.c
@@ -0,0 +1,203 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_destroy.c
+ * @brief main functions to destroy a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "request_resume.h"
+#include "daemon_close_all_connections.h"
+
+
+/**
+ * Stop all worker threads from the worker pool.
+ *
+ * @param daemon master daemon controlling the workers
+ */
+static void
+stop_workers (struct MHD_Daemon *daemon)
+{
+  MHD_socket fd;
+  unsigned int i;
+
+  mhd_assert (1 < daemon->worker_pool_size);
+  mhd_assert (1 < daemon->threading_mode);
+  if (daemon->was_quiesced)
+    fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */
+  else
+    fd = daemon->listen_socket;
+  /* Let workers shutdown in parallel. */
+  for (i = 0; i < daemon->worker_pool_size; i++)
+  {
+    daemon->worker_pool[i].shutdown = true;
+    if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc))
+    {
+      if (! MHD_itc_activate_ (daemon->worker_pool[i].itc,
+                               "e"))
+        MHD_PANIC (_ (
+                     "Failed to signal shutdown via inter-thread communication channel.\n"));
+    }
+    else
+    {
+      /* Better hope shutdown() works... */
+      mhd_assert (MHD_INVALID_SOCKET != fd);
+    }
+  }
+#ifdef HAVE_LISTEN_SHUTDOWN
+  if (MHD_INVALID_SOCKET != fd)
+  {
+    (void) shutdown (fd,
+                     SHUT_RDWR);
+  }
+#endif /* HAVE_LISTEN_SHUTDOWN */
+  for (i = 0; i < daemon->worker_pool_size; ++i)
+  {
+    MHD_daemon_destroy (&daemon->worker_pool[i]);
+  }
+  free (daemon->worker_pool);
+  daemon->worker_pool = NULL;
+  /* FIXME: does this still hold? */
+  mhd_assert (MHD_ITC_IS_INVALID_ (daemon->itc));
+#ifdef EPOLL_SUPPORT
+  mhd_assert (-1 == daemon->epoll_fd);
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  mhd_assert (-1 == daemon->epoll_upgrade_fd);
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
+}
+
+
+/**
+ * Shutdown and destroy an HTTP daemon.
+ *
+ * @param daemon daemon to stop
+ * @ingroup event
+ */
+void
+MHD_daemon_destroy (struct MHD_Daemon *daemon)
+{
+  MHD_socket fd;
+
+  daemon->shutdown = true;
+  if (daemon->was_quiesced)
+    fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */
+  else
+    fd = daemon->listen_socket;
+
+  /* FIXME: convert from here to microhttpd2-style API! */
+
+  if (NULL != daemon->worker_pool)
+  {   /* Master daemon with worker pool. */
+    stop_workers (daemon);
+  }
+  else
+  {
+    mhd_assert (0 == daemon->worker_pool_size);
+    /* Worker daemon or single-thread daemon. */
+    if (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode)
+    {
+      /* Worker daemon or single daemon with internal thread(s). */
+      /* Separate thread(s) is used for polling sockets. */
+      if (MHD_ITC_IS_VALID_ (daemon->itc))
+      {
+        if (! MHD_itc_activate_ (daemon->itc,
+                                 "e"))
+          MHD_PANIC (_ (
+                       "Failed to signal shutdown via inter-thread communication channel.\n"));
+      }
+      else
+      {
+#ifdef HAVE_LISTEN_SHUTDOWN
+        if (MHD_INVALID_SOCKET != fd)
+        {
+          if (NULL == daemon->master)
+            (void) shutdown (fd,
+                             SHUT_RDWR);
+        }
+        else
+#endif /* HAVE_LISTEN_SHUTDOWN */
+        mhd_assert (false); /* Should never happen */
+      }
+
+      if (! MHD_join_thread_ (daemon->pid.handle))
+      {
+        MHD_PANIC (_ ("Failed to join a thread.\n"));
+      }
+      /* close_all_connections() was called in daemon thread. */
+    }
+    else
+    {
+      /* No internal threads are used for polling sockets
+   (external event loop) */
+      MHD_daemon_close_all_connections_ (daemon);
+    }
+    if (MHD_ITC_IS_VALID_ (daemon->itc))
+      MHD_itc_destroy_chk_ (daemon->itc);
+
+#ifdef EPOLL_SUPPORT
+    if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+         (-1 != daemon->epoll_fd) )
+      MHD_socket_close_chk_ (daemon->epoll_fd);
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+         (-1 != daemon->epoll_upgrade_fd) )
+      MHD_socket_close_chk_ (daemon->epoll_upgrade_fd);
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
+
+    MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
+  }
+
+  if (NULL != daemon->master)
+    return;
+  /* Cleanup that should be done only one time in master/single daemon.
+   * Do not perform this cleanup in worker daemons. */
+
+  if (MHD_INVALID_SOCKET != fd)
+    MHD_socket_close_chk_ (fd);
+
+  /* TLS clean up */
+#ifdef HTTPS_SUPPORT
+  if (NULL != daemon->tls_api)
+  {
+#if FIXME_TLS_API
+    if (daemon->have_dhparams)
+    {
+      gnutls_dh_params_deinit (daemon->https_mem_dhparams);
+      daemon->have_dhparams = false;
+    }
+    gnutls_priority_deinit (daemon->priority_cache);
+    if (daemon->x509_cred)
+      gnutls_certificate_free_credentials (daemon->x509_cred);
+#endif
+  }
+#endif /* HTTPS_SUPPORT */
+
+#ifdef DAUTH_SUPPORT
+  free (daemon->nnc);
+  MHD_mutex_destroy_chk_ (&daemon->nnc_lock);
+#endif
+  MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+  free (daemon);
+}
+
+
+/* end of daemon_destroy.c */
diff --git a/src/lib/daemon_epoll.c b/src/lib/daemon_epoll.c
new file mode 100644
index 0000000..91af12a
--- /dev/null
+++ b/src/lib/daemon_epoll.c
@@ -0,0 +1,517 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_epoll.c
+ * @brief functions to run epoll()-based event loop
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_add.h"
+#include "connection_call_handlers.h"
+#include "connection_finish_forward.h"
+#include "daemon_epoll.h"
+#include "upgrade_process.h"
+#include "request_resume.h"
+
+#ifdef EPOLL_SUPPORT
+
+/**
+ * How many events to we process at most per epoll() call?  Trade-off
+ * between required stack-size and number of system calls we have to
+ * make; 128 should be way enough to avoid more than one system call
+ * for most scenarios, and still be moderate in stack size
+ * consumption.  Embedded systems might want to choose a smaller value
+ * --- but why use epoll() on such a system in the first place?
+ */
+#define MAX_EVENTS 128
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+
+/**
+ * Checks whether @a urh has some data to process.
+ *
+ * @param urh upgrade handler to analyse
+ * @return 'true' if @a urh has some data to process,
+ *         'false' otherwise
+ */
+static bool
+is_urh_ready (struct MHD_UpgradeResponseHandle *const urh)
+{
+  const struct MHD_Connection *const connection = urh->connection;
+
+  if ( (0 == urh->in_buffer_size) &&
+       (0 == urh->out_buffer_size) &&
+       (0 == urh->in_buffer_used) &&
+       (0 == urh->out_buffer_used) )
+    return false;
+
+  if (connection->daemon->shutdown)
+    return true;
+
+  if ( ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->app.celi)) ||
+         (connection->tls_read_ready) ) &&
+       (urh->in_buffer_used < urh->in_buffer_size) )
+    return true;
+
+  if ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->mhd.celi)) &&
+       (urh->out_buffer_used < urh->out_buffer_size) )
+    return true;
+
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) &&
+       (urh->out_buffer_used > 0) )
+    return true;
+
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) &&
+       (urh->in_buffer_used > 0) )
+    return true;
+
+  return false;
+}
+
+
+/**
+ * Do epoll()-based processing for TLS connections that have been
+ * upgraded.  This requires a separate epoll() invocation as we
+ * cannot use the `struct MHD_Connection` data structures for
+ * the `union epoll_data` in this case.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon the daemmon for which we process connections
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+run_epoll_for_upgrade (struct MHD_Daemon *daemon)
+{
+  struct epoll_event events[MAX_EVENTS];
+  int num_events;
+  struct MHD_UpgradeResponseHandle *pos;
+  struct MHD_UpgradeResponseHandle *prev;
+
+  num_events = MAX_EVENTS;
+  while (MAX_EVENTS == num_events)
+  {
+    unsigned int i;
+
+    /* update event masks */
+    num_events = epoll_wait (daemon->epoll_upgrade_fd,
+                             events,
+                             MAX_EVENTS,
+                             0);
+    if (-1 == num_events)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        return MHD_SC_OK;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_UNEXPECTED_EPOLL_WAIT_ERROR,
+                _ ("Call to epoll_wait failed: %s\n"),
+                MHD_socket_strerr_ (err));
+#endif
+      return MHD_SC_UNEXPECTED_EPOLL_WAIT_ERROR;
+    }
+    for (i = 0; i < (unsigned int) num_events; i++)
+    {
+      struct UpgradeEpollHandle *const ueh = events[i].data.ptr;
+      struct MHD_UpgradeResponseHandle *const urh = ueh->urh;
+      bool new_err_state = false;
+
+      if (urh->clean_ready)
+        continue;
+
+      /* Update ueh state based on what is ready according to epoll() */
+      if (0 != (events[i].events & EPOLLIN))
+        ueh->celi |= MHD_EPOLL_STATE_READ_READY;
+      if (0 != (events[i].events & EPOLLOUT))
+        ueh->celi |= MHD_EPOLL_STATE_WRITE_READY;
+      if (0 != (events[i].events & EPOLLHUP))
+        ueh->celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY;
+
+      if ( (0 == (ueh->celi & MHD_EPOLL_STATE_ERROR)) &&
+           (0 != (events[i].events & (EPOLLERR | EPOLLPRI))) )
+      {
+        /* Process new error state only one time
+         * and avoid continuously marking this connection
+         * as 'ready'. */
+        ueh->celi |= MHD_EPOLL_STATE_ERROR;
+        new_err_state = true;
+      }
+
+      if (! urh->in_eready_list)
+      {
+        if (new_err_state ||
+            is_urh_ready (urh))
+        {
+          EDLL_insert (daemon->eready_urh_head,
+                       daemon->eready_urh_tail,
+                       urh);
+          urh->in_eready_list = true;
+        }
+      }
+    }
+  }
+  prev = daemon->eready_urh_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevE;
+    MHD_upgrade_response_handle_process_ (pos);
+    if (! is_urh_ready (pos))
+    {
+      EDLL_remove (daemon->eready_urh_head,
+                   daemon->eready_urh_tail,
+                   pos);
+      pos->in_eready_list = false;
+    }
+    /* Finished forwarding? */
+    if ( (0 == pos->in_buffer_size) &&
+         (0 == pos->out_buffer_size) &&
+         (0 == pos->in_buffer_used) &&
+         (0 == pos->out_buffer_used) )
+    {
+      MHD_connection_finish_forward_ (pos->connection);
+      pos->clean_ready = true;
+      /* If 'pos->was_closed' already was set to true, connection
+       * will be moved immediately to cleanup list. Otherwise
+       * connection will stay in suspended list until 'pos' will
+       * be marked with 'was_closed' by application. */
+      MHD_request_resume (&pos->connection->request);
+    }
+  }
+
+  return MHD_SC_OK;
+}
+
+
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+
+/**
+ * Do epoll()-based processing (this function is allowed to
+ * block if @a may_block is set to #MHD_YES).
+ *
+ * @param daemon daemon to run poll loop for
+ * @param may_block true if blocking, false if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_epoll_ (struct MHD_Daemon *daemon,
+                   bool may_block)
+{
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  static const char *const upgrade_marker = "upgrade_ptr";
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  struct MHD_Connection *pos;
+  struct MHD_Connection *prev;
+  struct epoll_event events[MAX_EVENTS];
+  struct epoll_event event;
+  int timeout_ms;
+  MHD_UNSIGNED_LONG_LONG timeout_ll;
+  int num_events;
+  unsigned int i;
+  MHD_socket ls;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  bool run_upgraded = false;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+  if (-1 == daemon->epoll_fd)
+    return MHD_SC_EPOLL_FD_INVALID; /* we're down! */
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_socket)) &&
+       (! daemon->was_quiesced) &&
+       (daemon->connections < daemon->global_connection_limit) &&
+       (! daemon->listen_socket_in_epoll) &&
+       (! daemon->at_limit) )
+  {
+    event.events = EPOLLIN;
+    event.data.ptr = daemon;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        ls,
+                        &event))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_EPOLL_CTL_ADD_FAILED,
+                _ ("Call to epoll_ctl failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      return MHD_SC_EPOLL_CTL_ADD_FAILED;
+    }
+    daemon->listen_socket_in_epoll = true;
+  }
+  if ( (daemon->was_quiesced) &&
+       (daemon->listen_socket_in_epoll) )
+  {
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_DEL,
+                        ls,
+                        NULL))
+      MHD_PANIC ("Failed to remove listen FD from epoll set.\n");
+    daemon->listen_socket_in_epoll = false;
+  }
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if ( (! daemon->upgrade_fd_in_epoll) &&
+       (-1 != daemon->epoll_upgrade_fd) )
+  {
+    event.events = EPOLLIN | EPOLLOUT;
+    event.data.ptr = (void *) upgrade_marker;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        daemon->epoll_upgrade_fd,
+                        &event))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_EPOLL_CTL_ADD_FAILED,
+                _ ("Call to epoll_ctl failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      return MHD_SC_EPOLL_CTL_ADD_FAILED;
+    }
+    daemon->upgrade_fd_in_epoll = true;
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  if ( (daemon->listen_socket_in_epoll) &&
+       ( (daemon->connections == daemon->global_connection_limit) ||
+         (daemon->at_limit) ||
+         (daemon->was_quiesced) ) )
+  {
+    /* we're at the connection limit, disable listen socket
+ for event loop for now */
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_DEL,
+                        ls,
+                        NULL))
+      MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n"));
+    daemon->listen_socket_in_epoll = false;
+  }
+
+  if ( (! daemon->disallow_suspend_resume) &&
+       (MHD_resume_suspended_connections_ (daemon)) )
+    may_block = false;
+
+  if (may_block)
+  {
+    if (MHD_SC_OK ==   /* FIXME: distinguish between NO_TIMEOUT and errors */
+        MHD_daemon_get_timeout (daemon,
+                                &timeout_ll))
+    {
+      if (timeout_ll >= (MHD_UNSIGNED_LONG_LONG) INT_MAX)
+        timeout_ms = INT_MAX;
+      else
+        timeout_ms = (int) timeout_ll;
+    }
+    else
+      timeout_ms = -1;
+  }
+  else
+    timeout_ms = 0;
+
+  /* Reset. New value will be set when connections are processed. */
+  /* Note: Used mostly for uniformity here as same situation is
+   * signaled in epoll mode by non-empty eready DLL. */
+  daemon->data_already_pending = false;
+
+  /* drain 'epoll' event queue; need to iterate as we get at most
+     MAX_EVENTS in one system call here; in practice this should
+     pretty much mean only one round, but better an extra loop here
+     than unfair behavior... */
+  num_events = MAX_EVENTS;
+  while (MAX_EVENTS == num_events)
+  {
+    /* update event masks */
+    num_events = epoll_wait (daemon->epoll_fd,
+                             events,
+                             MAX_EVENTS,
+                             timeout_ms);
+    if (-1 == num_events)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        return MHD_SC_OK;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_UNEXPECTED_EPOLL_WAIT_ERROR,
+                _ ("Call to epoll_wait failed: %s\n"),
+                MHD_socket_strerr_ (err));
+#endif
+      return MHD_SC_UNEXPECTED_EPOLL_WAIT_ERROR;
+    }
+    for (i = 0; i < (unsigned int) num_events; i++)
+    {
+      /* First, check for the values of `ptr` that would indicate
+         that this event is not about a normal connection. */
+      if (NULL == events[i].data.ptr)
+        continue; /* shutdown signal! */
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+      if (upgrade_marker == events[i].data.ptr)
+      {
+        /* activity on an upgraded connection, we process
+           those in a separate epoll() */
+        run_upgraded = true;
+        continue;
+      }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+      if (daemon->epoll_itc_marker == events[i].data.ptr)
+      {
+        /* It's OK to clear ITC here as all external
+           conditions will be processed later. */
+        MHD_itc_clear_ (daemon->itc);
+        continue;
+      }
+      if (daemon == events[i].data.ptr)
+      {
+        /* Check for error conditions on listen socket. */
+        /* FIXME: Initiate MHD_quiesce_daemon() to prevent busy waiting? */
+        if (0 == (events[i].events & (EPOLLERR | EPOLLHUP)))
+        {
+          unsigned int series_length = 0;
+          /* Run 'accept' until it fails or daemon at limit of connections.
+           * Do not accept more then 10 connections at once. The rest will
+           * be accepted on next turn (level trigger is used for listen
+           * socket). */
+          while ( (MHD_SC_OK ==
+                   MHD_accept_connection_ (daemon)) &&
+                  (series_length < 10) &&
+                  (daemon->connections < daemon->global_connection_limit) &&
+                  (! daemon->at_limit) )
+            series_length++;
+        }
+        continue;
+      }
+      /* this is an event relating to a 'normal' connection,
+         remember the event and if appropriate mark the
+         connection as 'eready'. */
+      pos = events[i].data.ptr;
+      /* normal processing: update read/write data */
+      if (0 != (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP)))
+      {
+        pos->epoll_state |= MHD_EPOLL_STATE_ERROR;
+        if (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+        {
+          EDLL_insert (daemon->eready_head,
+                       daemon->eready_tail,
+                       pos);
+          pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+        }
+      }
+      else
+      {
+        if (0 != (events[i].events & EPOLLIN))
+        {
+          pos->epoll_state |= MHD_EPOLL_STATE_READ_READY;
+          if ( ( (MHD_EVENT_LOOP_INFO_READ == pos->request.event_loop_info) ||
+                 (pos->request.read_buffer_size >
+                  pos->request.read_buffer_offset) ) &&
+               (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
+          {
+            EDLL_insert (daemon->eready_head,
+                         daemon->eready_tail,
+                         pos);
+            pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+          }
+        }
+        if (0 != (events[i].events & EPOLLOUT))
+        {
+          pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY;
+          if ( (MHD_EVENT_LOOP_INFO_WRITE == pos->request.event_loop_info) &&
+               (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
+          {
+            EDLL_insert (daemon->eready_head,
+                         daemon->eready_tail,
+                         pos);
+            pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+          }
+        }
+      }
+    }
+  }
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if (run_upgraded)
+    run_epoll_for_upgrade (daemon); /* FIXME: return value? */
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+  /* process events for connections */
+  prev = daemon->eready_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevE;
+    MHD_connection_call_handlers_ (pos,
+                                   0 != (pos->epoll_state
+                                         & MHD_EPOLL_STATE_READ_READY),
+                                   0 != (pos->epoll_state
+                                         & MHD_EPOLL_STATE_WRITE_READY),
+                                   0 != (pos->epoll_state
+                                         & MHD_EPOLL_STATE_ERROR));
+    if (MHD_EPOLL_STATE_IN_EREADY_EDLL ==
+        (pos->epoll_state & (MHD_EPOLL_STATE_SUSPENDED
+                             | MHD_EPOLL_STATE_IN_EREADY_EDLL)))
+    {
+      if ( ((MHD_EVENT_LOOP_INFO_READ == pos->request.event_loop_info) &&
+            (0 == (pos->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ||
+           ((MHD_EVENT_LOOP_INFO_WRITE == pos->request.event_loop_info) &&
+            (0 == (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ) ||
+           (MHD_EVENT_LOOP_INFO_CLEANUP == pos->request.event_loop_info) )
+      {
+        EDLL_remove (daemon->eready_head,
+                     daemon->eready_tail,
+                     pos);
+        pos->epoll_state &= ~MHD_EPOLL_STATE_IN_EREADY_EDLL;
+      }
+    }
+  }
+
+  /* Finally, handle timed-out connections; we need to do this here
+     as the epoll mechanism won't call the 'MHD_request_handle_idle_()' on everything,
+     as the other event loops do.  As timeouts do not get an explicit
+     event, we need to find those connections that might have timed out
+     here.
+
+     Connections with custom timeouts must all be looked at, as we
+     do not bother to sort that (presumably very short) list. */prev = daemon->manual_timeout_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevX;
+    MHD_request_handle_idle_ (&pos->request);
+  }
+  /* Connections with the default timeout are sorted by prepending
+     them to the head of the list whenever we touch the connection;
+     thus it suffices to iterate from the tail until the first
+     connection is NOT timed out */
+  prev = daemon->normal_timeout_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevX;
+    MHD_request_handle_idle_ (&pos->request);
+    if (MHD_REQUEST_CLOSED != pos->request.state)
+      break; /* sorted by timeout, no need to visit the rest! */
+  }
+  return MHD_SC_OK;
+}
+
+
+#endif
+
+/* end of daemon_epoll.c */
diff --git a/src/lib/daemon_epoll.h b/src/lib/daemon_epoll.h
new file mode 100644
index 0000000..37d0e42
--- /dev/null
+++ b/src/lib/daemon_epoll.h
@@ -0,0 +1,46 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_epoll.h
+ * @brief  non-public functions provided by daemon_epoll.c
+ * @author Christian Grothoff
+ */
+
+#ifndef DAEMON_EPOLL_H
+#define DAEMON_EPOLL_H
+
+#ifdef EPOLL_SUPPORT
+
+/**
+ * Do epoll()-based processing (this function is allowed to
+ * block if @a may_block is set to #MHD_YES).
+ *
+ * @param daemon daemon to run poll loop for
+ * @param may_block true if blocking, false if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_epoll_ (struct MHD_Daemon *daemon,
+                   bool may_block)
+MHD_NONNULL (1);
+
+#endif
+
+#endif
diff --git a/src/lib/daemon_get_timeout.c b/src/lib/daemon_get_timeout.c
new file mode 100644
index 0000000..6fa7247
--- /dev/null
+++ b/src/lib/daemon_get_timeout.c
@@ -0,0 +1,127 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_get_timeout.c
+ * @brief function to obtain timeout for event loop
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Obtain timeout value for polling function for this daemon.
+ * This function set value to amount of milliseconds for which polling
+ * function (`select()` or `poll()`) should at most block, not the
+ * timeout value set for connections.
+ * It is important to always use this function, even if connection
+ * timeout is not set, as in some cases MHD may already have more
+ * data to process on next turn (data pending in TLS buffers,
+ * connections are already ready with epoll etc.) and returned timeout
+ * will be zero.
+ *
+ * @param daemon daemon to query for timeout
+ * @param timeout set to the timeout (in milliseconds)
+ * @return #MHD_SC_OK on success, #MHD_SC_NO_TIMEOUT if timeouts are
+ *        not used (or no connections exist that would
+ *        necessitate the use of a timeout right now), otherwise
+ *        an error code
+ * @ingroup event
+ */
+enum MHD_StatusCode
+MHD_daemon_get_timeout (struct MHD_Daemon *daemon,
+                        MHD_UNSIGNED_LONG_LONG *timeout)
+{
+  time_t earliest_deadline;
+  time_t now;
+  struct MHD_Connection *pos;
+  bool have_timeout;
+
+  if (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_TIMEOUT,
+              _ ("Illegal call to MHD_get_timeout.\n"));
+#endif
+    return MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_TIMEOUT;
+  }
+
+  if (daemon->data_already_pending)
+  {
+    /* Some data already waiting to be processed. */
+    *timeout = 0;
+    return MHD_SC_OK;
+  }
+
+#ifdef EPOLL_SUPPORT
+  if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+       ((NULL != daemon->eready_head)
+#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
+        || (NULL != daemon->eready_urh_head)
+#endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */
+       ) )
+  {
+    /* Some connection(s) already have some data pending. */
+    *timeout = 0;
+    return MHD_SC_OK;
+  }
+#endif /* EPOLL_SUPPORT */
+
+  have_timeout = false;
+  earliest_deadline = 0; /* avoid compiler warnings */
+  for (pos = daemon->manual_timeout_tail; NULL != pos; pos = pos->prevX)
+  {
+    if (0 != pos->connection_timeout)
+    {
+      if ( (! have_timeout) ||
+           (earliest_deadline - pos->last_activity > pos->connection_timeout) )
+        earliest_deadline = pos->last_activity + pos->connection_timeout;
+      have_timeout = true;
+    }
+  }
+  /* normal timeouts are sorted, so we only need to look at the 'tail' (oldest) */
+  pos = daemon->normal_timeout_tail;
+  if ( (NULL != pos) &&
+       (0 != pos->connection_timeout) )
+  {
+    if ( (! have_timeout) ||
+         (earliest_deadline - pos->connection_timeout > pos->last_activity) )
+      earliest_deadline = pos->last_activity + pos->connection_timeout;
+    have_timeout = true;
+  }
+
+  if (! have_timeout)
+    return MHD_SC_NO_TIMEOUT;
+  now = MHD_monotonic_sec_counter ();
+  if (earliest_deadline < now)
+    *timeout = 0;
+  else
+  {
+    const time_t second_left = earliest_deadline - now;
+    if (second_left > ULLONG_MAX / 1000)   /* Ignore compiler warning: 'second_left' is always positive. */
+      *timeout = ULLONG_MAX;
+    else
+      *timeout = 1000LL * second_left;
+  }
+  return MHD_SC_OK;
+}
+
+
+/* end of daemon_get_timeout.c */
diff --git a/src/lib/daemon_info.c b/src/lib/daemon_info.c
new file mode 100644
index 0000000..fe5e8d2
--- /dev/null
+++ b/src/lib/daemon_info.c
@@ -0,0 +1,106 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_info.c
+ * @brief implementation of MHD_daemon_get_information_sz()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_cleanup.h"
+
+
+/**
+ * Obtain information about the given daemon.
+ * Use wrapper macro #MHD_daemon_get_information() instead of direct use
+ * of this function.
+ *
+ * @param daemon what daemon to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @param return_value_size size of union MHD_DaemonInformation at compile
+ *                          time
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+enum MHD_Bool
+MHD_daemon_get_information_sz (struct MHD_Daemon *daemon,
+                               enum MHD_DaemonInformationType info_type,
+                               union MHD_DaemonInformation *return_value,
+                               size_t return_value_size)
+{
+#define CHECK_SIZE(type) if (sizeof(type) < return_value_size)  \
+    return MHD_NO
+
+  switch (info_type)
+  {
+  case MHD_DAEMON_INFORMATION_LISTEN_SOCKET:
+    CHECK_SIZE (MHD_socket);
+    return_value->listen_socket
+      = daemon->listen_socket;
+    return MHD_YES;
+#ifdef EPOLL_SUPPORT
+  case MHD_DAEMON_INFORMATION_EPOLL_FD:
+    CHECK_SIZE (int);
+    // FIXME: maybe return MHD_NO if we are not using EPOLL?
+    return_value->epoll_fd = daemon->epoll_fd;
+    return MHD_YES;
+#endif
+  case MHD_DAEMON_INFORMATION_CURRENT_CONNECTIONS:
+    CHECK_SIZE (unsigned int);
+    if (MHD_TM_EXTERNAL_EVENT_LOOP == daemon->threading_mode)
+    {
+      /* Assumes that MHD_run() in not called in other thread
+   (of the application) at the same time. */
+      MHD_connection_cleanup_ (daemon);
+      return_value->num_connections
+        = daemon->connections;
+    }
+    else if (daemon->worker_pool)
+    {
+      unsigned int i;
+      /* Collect the connection information stored in the workers. */
+      return_value->num_connections = 0;
+      for (i = 0; i < daemon->worker_pool_size; i++)
+      {
+        /* FIXME: next line is thread-safe only if read is atomic. */
+        return_value->num_connections
+          += daemon->worker_pool[i].connections;
+      }
+    }
+    else
+      return_value->num_connections
+        = daemon->connections;
+    return MHD_YES;
+  case MHD_DAEMON_INFORMATION_BIND_PORT:
+    CHECK_SIZE (uint16_t);
+    // FIXME: return MHD_NO if port is not known/UNIX?
+    return_value->port = daemon->listen_port;
+    return MHD_YES;
+  default:
+    return MHD_NO;
+  }
+
+#undef CHECK_SIZE
+}
+
+
+/* end of daemon_info.c */
diff --git a/src/lib/daemon_ip_limit.c b/src/lib/daemon_ip_limit.c
new file mode 100644
index 0000000..91fc06e
--- /dev/null
+++ b/src/lib/daemon_ip_limit.c
@@ -0,0 +1,303 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_ip_limit.c
+ * @brief counting of connections per IP
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "daemon_ip_limit.h"
+#ifdef HAVE_SEARCH_H
+#include <search.h>
+#else
+#include "tsearch.h"
+#endif
+
+
+/**
+ * Maintain connection count for single address.
+ */
+struct MHD_IPCount
+{
+  /**
+   * Address family. AF_INET or AF_INET6 for now.
+   */
+  int family;
+
+  /**
+   * Actual address.
+   */
+  union
+  {
+    /**
+     * IPv4 address.
+     */
+    struct in_addr ipv4;
+#ifdef HAVE_INET6
+    /**
+     * IPv6 address.
+     */
+    struct in6_addr ipv6;
+#endif
+  } addr;
+
+  /**
+   * Counter.
+   */
+  unsigned int count;
+};
+
+
+/**
+ * Trace up to and return master daemon. If the supplied daemon
+ * is a master, then return the daemon itself.
+ *
+ * @param daemon handle to a daemon
+ * @return master daemon handle
+ */
+static struct MHD_Daemon *
+get_master (struct MHD_Daemon *daemon)
+{
+  while (NULL != daemon->master)
+    daemon = daemon->master;
+  return daemon;
+}
+
+
+/**
+ * Lock shared structure for IP connection counts and connection DLLs.
+ *
+ * @param daemon handle to daemon where lock is
+ */
+static void
+MHD_ip_count_lock (struct MHD_Daemon *daemon)
+{
+  MHD_mutex_lock_chk_ (&daemon->per_ip_connection_mutex);
+}
+
+
+/**
+ * Unlock shared structure for IP connection counts and connection DLLs.
+ *
+ * @param daemon handle to daemon where lock is
+ */
+static void
+MHD_ip_count_unlock (struct MHD_Daemon *daemon)
+{
+  MHD_mutex_unlock_chk_ (&daemon->per_ip_connection_mutex);
+}
+
+
+/**
+ * Tree comparison function for IP addresses (supplied to tsearch() family).
+ * We compare everything in the struct up through the beginning of the
+ * 'count' field.
+ *
+ * @param a1 first address to compare
+ * @param a2 second address to compare
+ * @return -1, 0 or 1 depending on result of compare
+ */
+static int
+MHD_ip_addr_compare (const void *a1,
+                     const void *a2)
+{
+  return memcmp (a1,
+                 a2,
+                 offsetof (struct MHD_IPCount,
+                           count));
+}
+
+
+/**
+ * Parse address and initialize @a key using the address.
+ *
+ * @param addr address to parse
+ * @param addrlen number of bytes in @a addr
+ * @param key where to store the parsed address
+ * @return #MHD_YES on success and #MHD_NO otherwise (e.g., invalid address type)
+ */
+static int
+MHD_ip_addr_to_key (const struct sockaddr *addr,
+                    socklen_t addrlen,
+                    struct MHD_IPCount *key)
+{
+  memset (key,
+          0,
+          sizeof(*key));
+
+  /* IPv4 addresses */
+  if (sizeof (struct sockaddr_in) == addrlen)
+  {
+    const struct sockaddr_in *addr4 = (const struct sockaddr_in *) addr;
+
+    key->family = AF_INET;
+    memcpy (&key->addr.ipv4,
+            &addr4->sin_addr,
+            sizeof(addr4->sin_addr));
+    return MHD_YES;
+  }
+
+#ifdef HAVE_INET6
+  /* IPv6 addresses */
+  if (sizeof (struct sockaddr_in6) == addrlen)
+  {
+    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *) addr;
+
+    key->family = AF_INET6;
+    memcpy (&key->addr.ipv6,
+            &addr6->sin6_addr,
+            sizeof(addr6->sin6_addr));
+    return MHD_YES;
+  }
+#endif
+
+  /* Some other address */
+  return MHD_NO;
+}
+
+
+/**
+ * Check if IP address is over its limit in terms of the number
+ * of allowed concurrent connections.  If the IP is still allowed,
+ * increments the connection counter.
+ *
+ * @param daemon handle to daemon where connection counts are tracked
+ * @param addr address to add (or increment counter)
+ * @param addrlen number of bytes in @a addr
+ * @return Return #MHD_YES if IP below limit, #MHD_NO if IP has surpassed limit.
+ *   Also returns #MHD_NO if fails to allocate memory.
+ */
+int
+MHD_ip_limit_add (struct MHD_Daemon *daemon,
+                  const struct sockaddr *addr,
+                  socklen_t addrlen)
+{
+  struct MHD_IPCount *key;
+  void **nodep;
+  void *node;
+  int result;
+
+  daemon = get_master (daemon);
+  /* Ignore if no connection limit assigned */
+  if (0 == daemon->ip_connection_limit)
+    return MHD_YES;
+
+  if (NULL == (key = malloc (sizeof(*key))))
+    return MHD_NO;
+
+  /* Initialize key */
+  if (MHD_NO == MHD_ip_addr_to_key (addr,
+                                    addrlen,
+                                    key))
+  {
+    /* Allow unhandled address types through */
+    free (key);
+    return MHD_YES;
+  }
+  MHD_ip_count_lock (daemon);
+
+  /* Search for the IP address */
+  if (NULL == (nodep = tsearch (key,
+                                &daemon->per_ip_connection_count,
+                                &MHD_ip_addr_compare)))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_IP_COUNTER_FAILURE,
+              _ ("Failed to add IP connection count node.\n"));
+#endif
+    MHD_ip_count_unlock (daemon);
+    free (key);
+    return MHD_NO;
+  }
+  node = *nodep;
+  /* If we got an existing node back, free the one we created */
+  if (node != key)
+    free (key);
+  key = (struct MHD_IPCount *) node;
+  /* Test if there is room for another connection; if so,
+   * increment count */
+  result = (key->count < daemon->ip_connection_limit) ? MHD_YES : MHD_NO;
+  if (MHD_YES == result)
+    ++key->count;
+
+  MHD_ip_count_unlock (daemon);
+  return result;
+}
+
+
+/**
+ * Decrement connection count for IP address, removing from table
+ * count reaches 0.
+ *
+ * @param daemon handle to daemon where connection counts are tracked
+ * @param addr address to remove (or decrement counter)
+ * @param addrlen number of bytes in @a addr
+ */
+void
+MHD_ip_limit_del (struct MHD_Daemon *daemon,
+                  const struct sockaddr *addr,
+                  socklen_t addrlen)
+{
+  struct MHD_IPCount search_key;
+  struct MHD_IPCount *found_key;
+  void **nodep;
+
+  daemon = get_master (daemon);
+  /* Ignore if no connection limit assigned */
+  if (0 == daemon->ip_connection_limit)
+    return;
+  /* Initialize search key */
+  if (MHD_NO == MHD_ip_addr_to_key (addr,
+                                    addrlen,
+                                    &search_key))
+    return;
+
+  MHD_ip_count_lock (daemon);
+
+  /* Search for the IP address */
+  if (NULL == (nodep = tfind (&search_key,
+                              &daemon->per_ip_connection_count,
+                              &MHD_ip_addr_compare)))
+  {
+    /* Something's wrong if we couldn't find an IP address
+     * that was previously added */
+    MHD_PANIC (_ ("Failed to find previously-added IP address.\n"));
+  }
+  found_key = (struct MHD_IPCount *) *nodep;
+  /* Validate existing count for IP address */
+  if (0 == found_key->count)
+  {
+    MHD_PANIC (_ ("Previously-added IP address had counter of zero.\n"));
+  }
+  /* Remove the node entirely if count reduces to 0 */
+  if (0 == --found_key->count)
+  {
+    tdelete (found_key,
+             &daemon->per_ip_connection_count,
+             &MHD_ip_addr_compare);
+    free (found_key);
+  }
+
+  MHD_ip_count_unlock (daemon);
+}
+
+
+/* end of daemon_ip_limit.c */
diff --git a/src/lib/daemon_ip_limit.h b/src/lib/daemon_ip_limit.h
new file mode 100644
index 0000000..9c58782
--- /dev/null
+++ b/src/lib/daemon_ip_limit.h
@@ -0,0 +1,60 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/daemon_ip_limit.h
+ * @brief counting of connections per IP
+ * @author Christian Grothoff
+ */
+
+#ifndef DAEMON_IP_LIMIT_H
+#define DAEMON_IP_LIMIT_H
+
+/**
+ * Check if IP address is over its limit in terms of the number
+ * of allowed concurrent connections.  If the IP is still allowed,
+ * increments the connection counter.
+ *
+ * @param daemon handle to daemon where connection counts are tracked
+ * @param addr address to add (or increment counter)
+ * @param addrlen number of bytes in @a addr
+ * @return Return #MHD_YES if IP below limit, #MHD_NO if IP has surpassed limit.
+ *   Also returns #MHD_NO if fails to allocate memory.
+ */
+int
+MHD_ip_limit_add (struct MHD_Daemon *daemon,
+                  const struct sockaddr *addr,
+                  socklen_t addrlen)
+MHD_NONNULL (1,2);
+
+
+/**
+ * Decrement connection count for IP address, removing from table
+ * count reaches 0.
+ *
+ * @param daemon handle to daemon where connection counts are tracked
+ * @param addr address to remove (or decrement counter)
+ * @param addrlen number of bytes in @a addr
+ */
+void
+MHD_ip_limit_del (struct MHD_Daemon *daemon,
+                  const struct sockaddr *addr,
+                  socklen_t addrlen)
+MHD_NONNULL (1,2);
+
+#endif
diff --git a/src/lib/daemon_options.c b/src/lib/daemon_options.c
new file mode 100644
index 0000000..531e422
--- /dev/null
+++ b/src/lib/daemon_options.c
@@ -0,0 +1,780 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_options.c
+ * @brief boring functions to manipulate daemon options
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#ifdef HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+/**
+ * Set logging method.  Specify NULL to disable logging entirely.  By
+ * default (if this option is not given), we log error messages to
+ * stderr.
+ *
+ * @param daemon which instance to setup logging for
+ * @param logger function to invoke
+ * @param logger_cls closure for @a logger
+ */
+void
+MHD_daemon_set_logger (struct MHD_Daemon *daemon,
+                       MHD_LoggingCallback logger,
+                       void *logger_cls)
+{
+  daemon->logger = logger;
+  daemon->logger_cls = logger_cls;
+}
+
+
+/**
+ * Suppress use of "Date" header as this system has no RTC.
+ *
+ * @param daemon which instance to disable clock for.
+ */
+void
+MHD_daemon_suppress_date_no_clock (struct MHD_Daemon *daemon)
+{
+  daemon->suppress_date = true;
+}
+
+
+/**
+ * Disable use of inter-thread communication channel.
+ * #MHD_daemon_disable_itc() can be used with
+ * #MHD_daemon_thread_internal() to perform some additional
+ * optimizations (in particular, not creating a pipe for IPC
+ * signalling).  If it is used, certain functions like
+ * #MHD_daemon_quiesce() or #MHD_connection_add() or
+ * #MHD_action_suspend() cannot be used anymore.
+ * #MHD_daemon_disable_itc() is not beneficial on platforms where
+ * select()/poll()/other signal shutdown() of a listen socket.
+ *
+ * You should only use this function if you are sure you do
+ * satisfy all of its requirements and need a generally minor
+ * boost in performance.
+ *
+ * @param daemon which instance to disable itc for
+ */
+void
+MHD_daemon_disable_itc (struct MHD_Daemon *daemon)
+{
+  daemon->disable_itc = true;
+}
+
+
+/**
+ * Enable `turbo`.  Disables certain calls to `shutdown()`,
+ * enables aggressive non-blocking optimistic reads and
+ * other potentially unsafe optimizations.
+ * Most effects only happen with #MHD_ELS_EPOLL.
+ *
+ * @param daemon which instance to enable turbo for
+ */
+void
+MHD_daemon_enable_turbo (struct MHD_Daemon *daemon)
+{
+  daemon->enable_turbo = true;
+}
+
+
+/**
+ * Disable #MHD_action_suspend() functionality.
+ *
+ * You should only use this function if you are sure you do
+ * satisfy all of its requirements and need a generally minor
+ * boost in performance.
+ *
+ * @param daemon which instance to disable suspend for
+ */
+void
+MHD_daemon_disallow_suspend_resume (struct MHD_Daemon *daemon)
+{
+  daemon->disallow_suspend_resume = true;
+}
+
+
+/**
+ * You need to set this option if you want to disable use of HTTP "Upgrade".
+ * "Upgrade" may require usage of additional internal resources,
+ * which we can avoid providing if they will not be used.
+ *
+ * You should only use this function if you are sure you do
+ * satisfy all of its requirements and need a generally minor
+ * boost in performance.
+ *
+ * @param daemon which instance to enable suspend/resume for
+ */
+void
+MHD_daemon_disallow_upgrade (struct MHD_Daemon *daemon)
+{
+  daemon->disallow_upgrade = true;
+}
+
+
+/**
+ * Configure TCP_FASTOPEN option, including setting a
+ * custom @a queue_length.
+ *
+ * Note that having a larger queue size can cause resource exhaustion
+ * attack as the TCP stack has to now allocate resources for the SYN
+ * packet along with its DATA.
+ *
+ * @param daemon which instance to configure TCP_FASTOPEN for
+ * @param fom under which conditions should we use TCP_FASTOPEN?
+ * @param queue_length queue length to use, default is 50 if this
+ *        option is never given.
+ * @return #MHD_YES upon success, #MHD_NO if #MHD_FOM_REQUIRE was
+ *         given, but TCP_FASTOPEN is not available on the platform
+ */
+enum MHD_Bool
+MHD_daemon_tcp_fastopen (struct MHD_Daemon *daemon,
+                         enum MHD_FastOpenMethod fom,
+                         unsigned int queue_length)
+{
+  daemon->fast_open_method = fom;
+  daemon->fo_queue_length = queue_length;
+  switch (fom)
+  {
+  case MHD_FOM_DISABLE:
+    return MHD_YES;
+  case MHD_FOM_AUTO:
+    return MHD_YES;
+  case MHD_FOM_REQUIRE:
+#ifdef TCP_FASTOPEN
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  }
+  return MHD_NO;
+}
+
+
+/**
+ * Bind to the given TCP port and address family.
+ *
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ * Ineffective in conjunction with #MHD_daemon_bind_sa().
+ *
+ * If neither this option nor the other two mentioned above
+ * is specified, MHD will simply not listen on any socket!
+ *
+ * @param daemon which instance to configure the TCP port for
+ * @param af address family to use
+ * @param port port to use, 0 to bind to a random (free) port
+ */
+void
+MHD_daemon_bind_port (struct MHD_Daemon *daemon,
+                      enum MHD_AddressFamily af,
+                      uint16_t port)
+{
+  daemon->listen_af = af;
+  daemon->listen_port = port;
+}
+
+
+/**
+ * Bind to the given socket address.
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ *
+ * @param daemon which instance to configure the binding address for
+ * @param sa address to bind to; can be IPv4 (AF_INET), IPv6 (AF_INET6)
+ *        or even a UNIX domain socket (AF_UNIX)
+ * @param sa_len number of bytes in @a sa
+ */
+void
+MHD_daemon_bind_socket_address (struct MHD_Daemon *daemon,
+                                const struct sockaddr *sa,
+                                size_t sa_len)
+{
+  memcpy (&daemon->listen_sa,
+          sa,
+          sa_len);
+  daemon->listen_sa_len = sa_len;
+}
+
+
+/**
+ * Use the given backlog for the listen() call.
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ *
+ * @param daemon which instance to configure the backlog for
+ * @param listen_backlog backlog to use
+ */
+void
+MHD_daemon_listen_backlog (struct MHD_Daemon *daemon,
+                           int listen_backlog)
+{
+  daemon->listen_backlog = listen_backlog;
+}
+
+
+/**
+ * If present true, allow reusing address:port socket (by using
+ * SO_REUSEPORT on most platform, or platform-specific ways).  If
+ * present and set to false, disallow reusing address:port socket
+ * (does nothing on most platform, but uses SO_EXCLUSIVEADDRUSE on
+ * Windows).
+ * Ineffective in conjunction with #MHD_daemon_listen_socket().
+ *
+ * @param daemon daemon to configure address reuse for
+ */
+void
+MHD_daemon_listen_allow_address_reuse (struct MHD_Daemon *daemon)
+{
+  daemon->allow_address_reuse = true;
+}
+
+
+/**
+ * Use SHOUTcast.  This will cause the response to begin
+ * with the SHOUTcast "ICY" line instead of "HTTP".
+ *
+ * @param daemon daemon to set SHOUTcast option for
+ */
+_MHD_EXTERN void
+MHD_daemon_enable_shoutcast (struct MHD_Daemon *daemon)
+{
+  daemon->enable_shoutcast = true;
+}
+
+
+/**
+ * Accept connections from the given socket.  Socket
+ * must be a TCP or UNIX domain (stream) socket.
+ *
+ * Unless -1 is given, this disables other listen options, including
+ * #MHD_daemon_bind_sa(), #MHD_daemon_bind_port(),
+ * #MHD_daemon_listen_queue() and
+ * #MHD_daemon_listen_allow_address_reuse().
+ *
+ * @param daemon daemon to set listen socket for
+ * @param listen_socket listen socket to use,
+ *        MHD_INVALID_SOCKET value will cause this call to be
+ *        ignored (other binding options may still be effective)
+ */
+void
+MHD_daemon_listen_socket (struct MHD_Daemon *daemon,
+                          MHD_socket listen_socket)
+{
+  daemon->listen_socket = listen_socket;
+}
+
+
+/**
+ * Force use of a particular event loop system call.
+ *
+ * @param daemon daemon to set event loop style for
+ * @param els event loop syscall to use
+ * @return #MHD_NO on failure, #MHD_YES on success
+ */
+enum MHD_Bool
+MHD_daemon_event_loop (struct MHD_Daemon *daemon,
+                       enum MHD_EventLoopSyscall els)
+{
+  switch (els)
+  {
+  case MHD_ELS_AUTO:
+    break; /* should always be OK */
+  case MHD_ELS_SELECT:
+    break; /* should always be OK */
+  case MHD_ELS_POLL:
+#ifdef HAVE_POLL
+    break;
+#else
+    return MHD_NO; /* not supported */
+#endif
+  case MHD_ELS_EPOLL:
+#ifdef EPOLL_SUPPORT
+    break;
+#else
+    return MHD_NO; /* not supported */
+#endif
+  default:
+    return MHD_NO; /* not supported (presumably future ABI extension) */
+  }
+  daemon->event_loop_syscall = els;
+  return MHD_YES;
+}
+
+
+/**
+ * Set how strictly MHD will enforce the HTTP protocol.
+ *
+ * @param daemon daemon to configure strictness for
+ * @param sl how strict should we be
+ */
+void
+MHD_daemon_protocol_strict_level (struct MHD_Daemon *daemon,
+                                  enum MHD_ProtocolStrictLevel sl)
+{
+  daemon->protocol_strict_level = sl;
+}
+
+
+/**
+ * Enable and configure TLS.
+ *
+ * @param daemon which instance should be configured
+ * @param tls_backend which TLS backend should be used,
+ *    currently only "gnutls" is supported.  You can
+ *    also specify NULL for best-available (which is the default).
+ * @param ciphers which ciphers should be used by TLS, default is
+ *     "NORMAL"
+ * @return status code, #MHD_SC_OK upon success
+ *     #MHD_TLS_BACKEND_UNSUPPORTED if the @a backend is unknown
+ *     #MHD_TLS_DISABLED if this build of MHD does not support TLS
+ *     #MHD_TLS_CIPHERS_INVALID if the given @a ciphers are not supported
+ *     by this backend
+ */
+enum MHD_StatusCode
+MHD_daemon_set_tls_backend (struct MHD_Daemon *daemon,
+                            const char *tls_backend,
+                            const char *ciphers)
+{
+#if ! (defined(HTTPS_SUPPORT) && defined (HAVE_DLFCN_H))
+  return MHD_SC_TLS_DISABLED;
+#else
+  char filename[1024];
+  int res;
+  MHD_TLS_PluginInit init;
+
+  /* todo: .dll on W32? */
+  res = MHD_snprintf_ (filename,
+                       sizeof (filename),
+                       "%s/libmicrohttpd_tls_%s.so",
+                       MHD_PLUGIN_INSTALL_PREFIX,
+                       tls_backend);
+  if (0 >= res)
+    return MHD_SC_TLS_BACKEND_UNSUPPORTED; /* string too long? */
+  if (NULL ==
+      (daemon->tls_backend_lib = dlopen (filename,
+                                         RTLD_NOW | RTLD_LOCAL)))
+    return MHD_SC_TLS_BACKEND_UNSUPPORTED; /* plugin not found */
+  if (NULL == (init = dlsym (daemon->tls_backend_lib,
+                             "MHD_TLS_init_" MHD_TLS_ABI_VERSION_STR)))
+
+  {
+    dlclose (daemon->tls_backend_lib);
+    daemon->tls_backend_lib = NULL;
+    return MHD_SC_TLS_BACKEND_UNSUPPORTED; /* possibly wrong version installed */
+  }
+  if (NULL == (daemon->tls_api = init (ciphers)))
+  {
+    dlclose (daemon->tls_backend_lib);
+    daemon->tls_backend_lib = NULL;
+    return MHD_SC_TLS_CIPHERS_INVALID; /* possibly wrong version installed */
+  }
+  return MHD_SC_OK;
+#endif
+}
+
+
+/**
+ * Provide TLS key and certificate data in-memory.
+ *
+ * @param daemon which instance should be configured
+ * @param mem_key private key (key.pem) to be used by the
+ *     HTTPS daemon.  Must be the actual data in-memory, not a filename.
+ * @param mem_cert certificate (cert.pem) to be used by the
+ *     HTTPS daemon.  Must be the actual data in-memory, not a filename.
+ * @param pass passphrase phrase to decrypt 'key.pem', NULL
+ *     if @param mem_key is in cleartext already
+ * @return #MHD_SC_OK upon success; MHD_BACKEND_UNINITIALIZED
+ *     if the TLS backend is not yet setup.
+ */
+enum MHD_StatusCode
+MHD_daemon_tls_key_and_cert_from_memory (struct MHD_Daemon *daemon,
+                                         const char *mem_key,
+                                         const char *mem_cert,
+                                         const char *pass)
+{
+#ifndef HTTPS_SUPPORT
+  return MHD_SC_TLS_DISABLED;
+#else
+  struct MHD_TLS_Plugin *plugin;
+
+  if (NULL == (plugin = daemon->tls_api))
+    return MHD_SC_TLS_BACKEND_UNINITIALIZED;
+  return plugin->init_kcp (plugin->cls,
+                           mem_key,
+                           mem_cert,
+                           pass);
+#endif
+}
+
+
+/**
+ * Configure DH parameters (dh.pem) to use for the TLS key
+ * exchange.
+ *
+ * @param daemon daemon to configure tls for
+ * @param dh parameters to use
+ * @return #MHD_SC_OK upon success; MHD_BACKEND_UNINITIALIZED
+ *     if the TLS backend is not yet setup.
+ */
+enum MHD_StatusCode
+MHD_daemon_tls_mem_dhparams (struct MHD_Daemon *daemon,
+                             const char *dh)
+{
+#ifndef HTTPS_SUPPORT
+  return MHD_SC_TLS_DISABLED;
+#else
+  struct MHD_TLS_Plugin *plugin;
+
+  if (NULL == (plugin = daemon->tls_api))
+    return MHD_SC_TLS_BACKEND_UNINITIALIZED;
+  return plugin->init_dhparams (plugin->cls,
+                                dh);
+#endif
+}
+
+
+/**
+ * Memory pointer for the certificate (ca.pem) to be used by the
+ * HTTPS daemon for client authentication.
+ *
+ * @param daemon daemon to configure tls for
+ * @param mem_trust memory pointer to the certificate
+ * @return #MHD_SC_OK upon success; MHD_BACKEND_UNINITIALIZED
+ *     if the TLS backend is not yet setup.
+ */
+enum MHD_StatusCode
+MHD_daemon_tls_mem_trust (struct MHD_Daemon *daemon,
+                          const char *mem_trust)
+{
+#ifndef HTTPS_SUPPORT
+  return MHD_SC_TLS_DISABLED;
+#else
+  struct MHD_TLS_Plugin *plugin;
+
+  if (NULL == (plugin = daemon->tls_api))
+    return MHD_SC_TLS_BACKEND_UNINITIALIZED;
+  return plugin->init_mem_trust (plugin->cls,
+                                 mem_trust);
+#endif
+}
+
+
+/**
+ * Configure daemon credentials type for GnuTLS.
+ *
+ * @param gnutls_credentials must be a value of
+ *   type `gnutls_credentials_type_t`
+ * @return #MHD_SC_OK upon success; TODO: define failure modes
+ */
+enum MHD_StatusCode
+MHD_daemon_gnutls_credentials (struct MHD_Daemon *daemon,
+                               int gnutls_credentials)
+{
+#ifndef HTTPS_SUPPORT
+  return MHD_SC_TLS_DISABLED;
+#else
+  struct MHD_TLS_Plugin *plugin;
+
+  if (NULL == (plugin = daemon->tls_api))
+    return MHD_SC_TLS_BACKEND_UNINITIALIZED;
+  return MHD_SC_TLS_BACKEND_OPERATION_UNSUPPORTED;
+#endif
+}
+
+
+/**
+ * Provide TLS key and certificate data via callback.
+ *
+ * Use a callback to determine which X.509 certificate should be used
+ * for a given HTTPS connection.  This option provides an alternative
+ * to #MHD_daemon_tls_key_and_cert_from_memory().  You must use this
+ * version if multiple domains are to be hosted at the same IP address
+ * using TLS's Server Name Indication (SNI) extension.  In this case,
+ * the callback is expected to select the correct certificate based on
+ * the SNI information provided.  The callback is expected to access
+ * the SNI data using `gnutls_server_name_get()`.  Using this option
+ * requires GnuTLS 3.0 or higher.
+ *
+ * @param daemon daemon to configure callback for
+ * @param cb must be of type `gnutls_certificate_retrieve_function2 *`.
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_gnutls_key_and_cert_from_callback (struct MHD_Daemon *daemon,
+                                              void *cb)
+{
+#ifndef HTTPS_SUPPORT
+  return MHD_SC_TLS_DISABLED;
+#else
+  struct MHD_TLS_Plugin *plugin;
+
+  if (NULL == (plugin = daemon->tls_api))
+    return MHD_SC_TLS_BACKEND_UNINITIALIZED;
+  return MHD_SC_TLS_BACKEND_OPERATION_UNSUPPORTED;
+#endif
+}
+
+
+/**
+ * Specify threading mode to use.
+ *
+ * @param daemon daemon to configure
+ * @param tm mode to use (positive values indicate the
+ *        number of worker threads to be used)
+ */
+void
+MHD_daemon_threading_mode (struct MHD_Daemon *daemon,
+                           enum MHD_ThreadingMode tm)
+{
+  daemon->threading_mode = tm;
+}
+
+
+/**
+ * Set  a policy callback that accepts/rejects connections
+ * based on the client's IP address.  This function will be called
+ * before a connection object is created.
+ *
+ * @param daemon daemon to set policy for
+ * @param apc function to call to check the policy
+ * @param apc_cls closure for @a apc
+ */
+void
+MHD_daemon_accept_policy (struct MHD_Daemon *daemon,
+                          MHD_AcceptPolicyCallback apc,
+                          void *apc_cls)
+{
+  daemon->accept_policy_cb = apc;
+  daemon->accept_policy_cb_cls = apc_cls;
+}
+
+
+/**
+ * Register a callback to be called first for every request
+ * (before any parsing of the header).  Makes it easy to
+ * log the full URL.
+ *
+ * @param daemon daemon for which to set the logger
+ * @param cb function to call
+ * @param cb_cls closure for @a cb
+ */
+void
+MHD_daemon_set_early_uri_logger (struct MHD_Daemon *daemon,
+                                 MHD_EarlyUriLogCallback cb,
+                                 void *cb_cls)
+{
+  daemon->early_uri_logger_cb = cb;
+  daemon->early_uri_logger_cb_cls = cb_cls;
+}
+
+
+/**
+ * Register a function that should be called whenever a connection is
+ * started or closed.
+ *
+ * @param daemon daemon to set callback for
+ * @param ncc function to call to check the policy
+ * @param ncc_cls closure for @a apc
+ */
+void
+MHD_daemon_set_notify_connection (struct MHD_Daemon *daemon,
+                                  MHD_NotifyConnectionCallback ncc,
+                                  void *ncc_cls)
+{
+  daemon->notify_connection_cb = ncc;
+  daemon->notify_connection_cb_cls = ncc_cls;
+}
+
+
+/**
+ * Maximum memory size per connection.
+ * Default is 32 kb (#MHD_POOL_SIZE_DEFAULT).
+ * Values above 128k are unlikely to result in much benefit, as half
+ * of the memory will be typically used for IO, and TCP buffers are
+ * unlikely to support window sizes above 64k on most systems.
+ *
+ * @param daemon daemon to configure
+ * @param memory_limit_b connection memory limit to use in bytes
+ * @param memory_increment_b increment to use when growing the read buffer, must be smaller than @a memory_limit_b
+ */
+void
+MHD_daemon_connection_memory_limit (struct MHD_Daemon *daemon,
+                                    size_t memory_limit_b,
+                                    size_t memory_increment_b)
+{
+  if (memory_increment_b >= memory_limit_b)
+    MHD_PANIC ("Sane memory increment must be below memory limit.\n");
+  daemon->connection_memory_limit_b = memory_limit_b;
+  daemon->connection_memory_increment_b = memory_increment_b;
+}
+
+
+/**
+ * Desired size of the stack for threads created by MHD.  Use 0 for
+ * system default.  Only useful if the selected threading mode
+ * is not #MHD_TM_EXTERNAL_EVENT_LOOP.
+ *
+ * @param daemon daemon to configure
+ * @param stack_limit_b stack size to use in bytes
+ */
+void
+MHD_daemon_thread_stack_size (struct MHD_Daemon *daemon,
+                              size_t stack_limit_b)
+{
+  daemon->thread_stack_limit_b = stack_limit_b;
+}
+
+
+/**
+ * Set maximum number of concurrent connections to accept.  If not
+ * given, MHD will not enforce any limits (modulo running into
+ * OS limits).  Values of 0 mean no limit.
+ *
+ * @param daemon daemon to configure
+ * @param global_connection_limit maximum number of (concurrent)
+          connections
+ * @param ip_connection_limit limit on the number of (concurrent)
+ *        connections made to the server from the same IP address.
+ *        Can be used to prevent one IP from taking over all of
+ *        the allowed connections.  If the same IP tries to
+ *        establish more than the specified number of
+ *        connections, they will be immediately rejected.
+ */
+void
+MHD_daemon_connection_limits (struct MHD_Daemon *daemon,
+                              unsigned int global_connection_limit,
+                              unsigned int ip_connection_limit)
+{
+  daemon->global_connection_limit = global_connection_limit;
+  daemon->ip_connection_limit = ip_connection_limit;
+}
+
+
+/**
+ * After how many seconds of inactivity should a
+ * connection automatically be timed out?
+ * Use zero for no timeout, which is also the (unsafe!) default.
+ *
+ * @param daemon daemon to configure
+ * @param timeout_s number of seconds of timeout to use
+ */
+void
+MHD_daemon_connection_default_timeout (struct MHD_Daemon *daemon,
+                                       unsigned int timeout_s)
+{
+  daemon->connection_default_timeout = (time_t) timeout_s;
+}
+
+
+/**
+ * Specify a function that should be called for unescaping escape
+ * sequences in URIs and URI arguments.  Note that this function
+ * will NOT be used by the `struct MHD_PostProcessor`.  If this
+ * option is not specified, the default method will be used which
+ * decodes escape sequences of the form "%HH".
+ *
+ * @param daemon daemon to configure
+ * @param unescape_cb function to use, NULL for default
+ * @param unescape_cb_cls closure for @a unescape_cb
+ */
+void
+MHD_daemon_unescape_cb (struct MHD_Daemon *daemon,
+                        MHD_UnescapeCallback unescape_cb,
+                        void *unescape_cb_cls)
+{
+  daemon->unescape_cb = unescape_cb;
+  daemon->unescape_cb_cls = unescape_cb_cls;
+}
+
+
+/**
+ * Set random values to be used by the Digest Auth module.  Note that
+ * the application must ensure that @a buf remains allocated and
+ * unmodified while the daemon is running.
+ *
+ * @param daemon daemon to configure
+ * @param buf_size number of bytes in @a buf
+ * @param buf entropy buffer
+ */
+void
+MHD_daemon_digest_auth_random (struct MHD_Daemon *daemon,
+                               size_t buf_size,
+                               const void *buf)
+{
+#if ENABLE_DAUTH
+  daemon->digest_auth_random_buf = buf;
+  daemon->digest_auth_random_buf_size = buf_size;
+#else
+  (void) daemon;
+  (void) buf_size;
+  (void) buf;
+  MHD_PANIC ("Digest authentication not supported by this build.\n");
+#endif
+}
+
+
+/**
+ * Length of the internal array holding the map of the nonce and
+ * the nonce counter.
+ *
+ * @param daemon daemon to configure
+ * @param nc_length desired array length
+ */
+enum MHD_StatusCode
+MHD_daemon_digest_auth_nc_length (struct MHD_Daemon *daemon,
+                                  size_t nc_length)
+{
+#if ENABLE_DAUTH
+  if ( ( (size_t) (nc_length * sizeof (struct MHD_NonceNc)))
+       / sizeof (struct MHD_NonceNc) != nc_length)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Specified value for NC_SIZE too large.\n"));
+#endif
+    return MHD_SC_DIGEST_AUTH_NC_LENGTH_TOO_BIG;
+  }
+  if (0 < nc_length)
+  {
+    if (NULL != daemon->nnc)
+      free (daemon->nnc);
+    daemon->nnc = malloc (daemon->nonce_nc_size
+                          * sizeof (struct MHD_NonceNc));
+    if (NULL == daemon->nnc)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to allocate memory for nonce-nc map: %s\n"),
+                MHD_strerror_ (errno));
+#endif
+      return MHD_SC_DIGEST_AUTH_NC_ALLOCATION_FAILURE;
+    }
+  }
+  daemon->digest_nc_length = nc_length;
+  return MHD_SC_OK;
+#else
+  (void) daemon;
+  (void) nc_length;
+  return MHD_SC_DIGEST_AUTH_NOT_SUPPORTED_BY_BUILD;
+#endif
+}
+
+
+/* end of daemon_options.c */
diff --git a/src/lib/daemon_poll.c b/src/lib/daemon_poll.c
new file mode 100644
index 0000000..27cdd4c
--- /dev/null
+++ b/src/lib/daemon_poll.c
@@ -0,0 +1,528 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/daemon_poll.c
+ * @brief functions to run poll-based event loop
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_add.h"
+#include "connection_call_handlers.h"
+#include "connection_finish_forward.h"
+#include "daemon_poll.h"
+#include "upgrade_process.h"
+#include "request_resume.h"
+
+
+#ifdef HAVE_POLL
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+
+/**
+ * Set required 'event' members in 'pollfd' elements,
+ * assuming that @a p[0].fd is MHD side of socketpair
+ * and @a p[1].fd is TLS connected socket.
+ *
+ * @param urh upgrade handle to watch for
+ * @param p pollfd array to update
+ */
+static void
+urh_update_pollfd (struct MHD_UpgradeResponseHandle *urh,
+                   struct pollfd p[2])
+{
+  p[0].events = 0;
+  p[1].events = 0;
+
+  if (urh->in_buffer_used < urh->in_buffer_size)
+    p[0].events |= POLLIN;
+  if (0 != urh->out_buffer_used)
+    p[0].events |= POLLOUT;
+
+  /* Do not monitor again for errors if error was detected before as
+   * error state is remembered. */
+  if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) &&
+      ((0 != urh->in_buffer_size) ||
+       (0 != urh->out_buffer_size) ||
+       (0 != urh->out_buffer_used)))
+    p[0].events |= MHD_POLL_EVENTS_ERR_DISC;
+
+  if (urh->out_buffer_used < urh->out_buffer_size)
+    p[1].events |= POLLIN;
+  if (0 != urh->in_buffer_used)
+    p[1].events |= POLLOUT;
+
+  /* Do not monitor again for errors if error was detected before as
+   * error state is remembered. */
+  if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) &&
+      ((0 != urh->out_buffer_size) ||
+       (0 != urh->in_buffer_size) ||
+       (0 != urh->in_buffer_used)))
+    p[1].events |= MHD_POLL_EVENTS_ERR_DISC;
+}
+
+
+/**
+ * Set @a p to watch for @a urh.
+ *
+ * @param urh upgrade handle to watch for
+ * @param p pollfd array to set
+ */
+static void
+urh_to_pollfd (struct MHD_UpgradeResponseHandle *urh,
+               struct pollfd p[2])
+{
+  p[0].fd = urh->connection->socket_fd;
+  p[1].fd = urh->mhd.socket;
+  urh_update_pollfd (urh,
+                     p);
+}
+
+
+/**
+ * Update ready state in @a urh based on pollfd.
+ * @param urh upgrade handle to update
+ * @param p 'poll()' processed pollfd.
+ */
+static void
+urh_from_pollfd (struct MHD_UpgradeResponseHandle *urh,
+                 struct pollfd p[2])
+{
+  /* Reset read/write ready, preserve error state. */
+  urh->app.celi &= (~MHD_EPOLL_STATE_READ_READY & ~MHD_EPOLL_STATE_WRITE_READY);
+  urh->mhd.celi &= (~MHD_EPOLL_STATE_READ_READY & ~MHD_EPOLL_STATE_WRITE_READY);
+
+  if (0 != (p[0].revents & POLLIN))
+    urh->app.celi |= MHD_EPOLL_STATE_READ_READY;
+  if (0 != (p[0].revents & POLLOUT))
+    urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY;
+  if (0 != (p[0].revents & POLLHUP))
+    urh->app.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY;
+  if (0 != (p[0].revents & MHD_POLL_REVENTS_ERRROR))
+    urh->app.celi |= MHD_EPOLL_STATE_ERROR;
+  if (0 != (p[1].revents & POLLIN))
+    urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+  if (0 != (p[1].revents & POLLOUT))
+    urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY;
+  if (0 != (p[1].revents & POLLHUP))
+    urh->mhd.celi |= MHD_EPOLL_STATE_ERROR;
+  if (0 != (p[1].revents & MHD_POLL_REVENTS_ERRROR))
+    urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY;
+}
+
+
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+
+/**
+ * Process all of our connections and possibly the server
+ * socket using poll().
+ *
+ * @param daemon daemon to run poll loop for
+ * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_poll_all_ (struct MHD_Daemon *daemon,
+                      bool may_block)
+{
+  unsigned int num_connections;
+  struct MHD_Connection *pos;
+  struct MHD_Connection *prev;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  struct MHD_UpgradeResponseHandle *urh;
+  struct MHD_UpgradeResponseHandle *urhn;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+  if ( (! daemon->disallow_suspend_resume) &&
+       (MHD_resume_suspended_connections_ (daemon)) )
+    may_block = false;
+
+  /* count number of connections and thus determine poll set size */
+  num_connections = 0;
+  for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
+    num_connections++;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  for (urh = daemon->urh_head; NULL != urh; urh = urh->next)
+    num_connections += 2;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  {
+    MHD_UNSIGNED_LONG_LONG ltimeout;
+    unsigned int i;
+    int timeout;
+    unsigned int poll_server;
+    int poll_listen;
+    int poll_itc_idx;
+    struct pollfd *p;
+    MHD_socket ls;
+
+    p = MHD_calloc_ ((2 + num_connections),
+                     sizeof (struct pollfd));
+    if (NULL == p)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_POLL_MALLOC_FAILURE,
+                _ ("Error allocating memory: %s\n"),
+                MHD_strerror_ (errno));
+#endif
+      return MHD_SC_POLL_MALLOC_FAILURE;
+    }
+    poll_server = 0;
+    poll_listen = -1;
+    if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_socket)) &&
+         (! daemon->was_quiesced) &&
+         (daemon->connections < daemon->global_connection_limit) &&
+         (! daemon->at_limit) )
+    {
+      /* only listen if we are not at the connection limit */
+      p[poll_server].fd = ls;
+      p[poll_server].events = POLLIN;
+      p[poll_server].revents = 0;
+      poll_listen = (int) poll_server;
+      poll_server++;
+    }
+    poll_itc_idx = -1;
+    if (MHD_ITC_IS_VALID_ (daemon->itc))
+    {
+      p[poll_server].fd = MHD_itc_r_fd_ (daemon->itc);
+      p[poll_server].events = POLLIN;
+      p[poll_server].revents = 0;
+      poll_itc_idx = (int) poll_server;
+      poll_server++;
+    }
+    if (! may_block)
+      timeout = 0;
+    else if ( (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode) ||
+              (MHD_SC_OK != /* FIXME: distinguish between NO_TIMEOUT and errors! */
+               MHD_daemon_get_timeout (daemon,
+                                       &ltimeout)) )
+      timeout = -1;
+    else
+      timeout = (ltimeout > INT_MAX) ? INT_MAX : (int) ltimeout;
+
+    i = 0;
+    for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev)
+    {
+      p[poll_server + i].fd = pos->socket_fd;
+      switch (pos->request.event_loop_info)
+      {
+      case MHD_EVENT_LOOP_INFO_READ:
+        p[poll_server + i].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_WRITE:
+        p[poll_server + i].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_BLOCK:
+        p[poll_server + i].events |=  MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_CLEANUP:
+        timeout = 0; /* clean up "pos" immediately */
+        break;
+      }
+      i++;
+    }
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev)
+    {
+      urh_to_pollfd (urh,
+                     &(p[poll_server + i]));
+      i += 2;
+    }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+    if (0 == poll_server + num_connections)
+    {
+      free (p);
+      return MHD_SC_OK;
+    }
+    if (MHD_sys_poll_ (p,
+                       poll_server + num_connections,
+                       timeout) < 0)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      {
+        free (p);
+        return MHD_SC_OK;
+      }
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_UNEXPECTED_POLL_ERROR,
+                _ ("poll failed: %s\n"),
+                MHD_socket_strerr_ (err));
+#endif
+      free (p);
+      return MHD_SC_UNEXPECTED_POLL_ERROR;
+    }
+
+    /* Reset. New value will be set when connections are processed. */
+    daemon->data_already_pending = false;
+
+    /* handle ITC FD */
+    /* do it before any other processing so
+       new signals will be processed in next loop */
+    if ( (-1 != poll_itc_idx) &&
+         (0 != (p[poll_itc_idx].revents & POLLIN)) )
+      MHD_itc_clear_ (daemon->itc);
+
+    /* handle shutdown */
+    if (daemon->shutdown)
+    {
+      free (p);
+      return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+    }
+    i = 0;
+    prev = daemon->connections_tail;
+    while (NULL != (pos = prev))
+    {
+      prev = pos->prev;
+      /* first, sanity checks */
+      if (i >= num_connections)
+        break;     /* connection list changed somehow, retry later ... */
+      if (p[poll_server + i].fd != pos->socket_fd)
+        continue;  /* fd mismatch, something else happened, retry later ... */
+      MHD_connection_call_handlers_ (pos,
+                                     0 != (p[poll_server + i].revents & POLLIN),
+                                     0 != (p[poll_server + i].revents
+                                           & POLLOUT),
+                                     0 != (p[poll_server + i].revents
+                                           & MHD_POLL_REVENTS_ERR_DISC));
+      i++;
+    }
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
+    {
+      if (i >= num_connections)
+        break;   /* connection list changed somehow, retry later ... */
+
+      /* Get next connection here as connection can be removed
+       * from 'daemon->urh_head' list. */
+      urhn = urh->prev;
+      /* Check for fd mismatch. FIXME: required for safety? */
+      if ((p[poll_server + i].fd != urh->connection->socket_fd) ||
+          (p[poll_server + i + 1].fd != urh->mhd.socket))
+        break;
+      urh_from_pollfd (urh,
+                       &p[poll_server + i]);
+      i += 2;
+      MHD_upgrade_response_handle_process_ (urh);
+      /* Finished forwarding? */
+      if ( (0 == urh->in_buffer_size) &&
+           (0 == urh->out_buffer_size) &&
+           (0 == urh->in_buffer_used) &&
+           (0 == urh->out_buffer_used) )
+      {
+        /* MHD_connection_finish_forward_() will remove connection from
+         * 'daemon->urh_head' list. */
+        MHD_connection_finish_forward_ (urh->connection);
+        urh->clean_ready = true;
+        /* If 'urh->was_closed' already was set to true, connection will be
+         * moved immediately to cleanup list. Otherwise connection
+         * will stay in suspended list until 'urh' will be marked
+         * with 'was_closed' by application. */
+        MHD_request_resume (&urh->connection->request);
+      }
+    }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+    /* handle 'listen' FD */
+    if ( (-1 != poll_listen) &&
+         (0 != (p[poll_listen].revents & POLLIN)) )
+      (void) MHD_accept_connection_ (daemon);
+
+    free (p);
+  }
+  return MHD_SC_OK;
+}
+
+
+/**
+ * Process only the listen socket using poll().
+ *
+ * @param daemon daemon to run poll loop for
+ * @param may_block true if blocking, false if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_poll_listen_socket_ (struct MHD_Daemon *daemon,
+                                bool may_block)
+{
+  struct pollfd p[2];
+  int timeout;
+  unsigned int poll_count;
+  int poll_listen;
+  int poll_itc_idx;
+  MHD_socket ls;
+
+  memset (&p,
+          0,
+          sizeof (p));
+  poll_count = 0;
+  poll_listen = -1;
+  poll_itc_idx = -1;
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_socket)) &&
+       (! daemon->was_quiesced) )
+
+  {
+    p[poll_count].fd = ls;
+    p[poll_count].events = POLLIN;
+    p[poll_count].revents = 0;
+    poll_listen = poll_count;
+    poll_count++;
+  }
+  if (MHD_ITC_IS_VALID_ (daemon->itc))
+  {
+    p[poll_count].fd = MHD_itc_r_fd_ (daemon->itc);
+    p[poll_count].events = POLLIN;
+    p[poll_count].revents = 0;
+    poll_itc_idx = poll_count;
+    poll_count++;
+  }
+
+  if (! daemon->disallow_suspend_resume)
+    (void) MHD_resume_suspended_connections_ (daemon);
+
+  if (! may_block)
+    timeout = 0;
+  else
+    timeout = -1;
+  if (0 == poll_count)
+    return MHD_SC_OK;
+  if (MHD_sys_poll_ (p,
+                     poll_count,
+                     timeout) < 0)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_SC_OK;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_UNEXPECTED_POLL_ERROR,
+              _ ("poll failed: %s\n"),
+              MHD_socket_strerr_ (err));
+#endif
+    return MHD_SC_UNEXPECTED_POLL_ERROR;
+  }
+  if ( (-1 != poll_itc_idx) &&
+       (0 != (p[poll_itc_idx].revents & POLLIN)) )
+    MHD_itc_clear_ (daemon->itc);
+
+  /* handle shutdown */
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+  if ( (-1 != poll_listen) &&
+       (0 != (p[poll_listen].revents & POLLIN)) )
+    (void) MHD_accept_connection_ (daemon);
+  return MHD_SC_OK;
+}
+
+
+#endif
+
+
+/**
+ * Do poll()-based processing.
+ *
+ * @param daemon daemon to run poll()-loop for
+ * @param may_block true if blocking, false if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_poll_ (struct MHD_Daemon *daemon,
+                  bool may_block)
+{
+#ifdef HAVE_POLL
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+  if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+    return MHD_daemon_poll_all_ (daemon,
+                                 may_block);
+  return MHD_daemon_poll_listen_socket_ (daemon,
+                                         may_block);
+#else
+  /* This code should be dead, as we should have checked
+     this earlier... */
+  return MHD_SC_POLL_NOT_SUPPORTED;
+#endif
+}
+
+
+#ifdef HAVE_POLL
+#ifdef HTTPS_SUPPORT
+/**
+ * Process upgraded connection with a poll() loop.
+ * We are in our own thread, only processing @a con
+ *
+ * @param con connection to process
+ */
+void
+MHD_daemon_upgrade_connection_with_poll_ (struct MHD_Connection *con)
+{
+  struct MHD_UpgradeResponseHandle *urh = con->request.urh;
+  struct pollfd p[2];
+
+  memset (p,
+          0,
+          sizeof (p));
+  p[0].fd = urh->connection->socket_fd;
+  p[1].fd = urh->mhd.socket;
+
+  while ( (0 != urh->in_buffer_size) ||
+          (0 != urh->out_buffer_size) ||
+          (0 != urh->in_buffer_used) ||
+          (0 != urh->out_buffer_used) )
+  {
+    int timeout;
+
+    urh_update_pollfd (urh,
+                       p);
+
+    if ( (con->tls_read_ready) &&
+         (urh->in_buffer_used < urh->in_buffer_size))
+      timeout = 0; /* No need to wait if incoming data is already pending in TLS buffers. */
+    else
+      timeout = -1;
+
+    if (MHD_sys_poll_ (p,
+                       2,
+                       timeout) < 0)
+    {
+      const int err = MHD_socket_get_error_ ();
+
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        continue;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (con->daemon,
+                MHD_SC_UNEXPECTED_POLL_ERROR,
+                _ ("Error during poll: `%s'\n"),
+                MHD_socket_strerr_ (err));
+#endif
+      break;
+    }
+    urh_from_pollfd (urh,
+                     p);
+    MHD_upgrade_response_handle_process_ (urh);
+  }
+}
+
+
+#endif
+#endif
+
+/* end of daemon_poll.c */
diff --git a/src/lib/daemon_poll.h b/src/lib/daemon_poll.h
new file mode 100644
index 0000000..8cf548d
--- /dev/null
+++ b/src/lib/daemon_poll.h
@@ -0,0 +1,87 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_poll.h
+ * @brief  non-public functions provided by daemon_poll.c
+ * @author Christian Grothoff
+ */
+#ifndef DAEMON_POLL_H
+#define DAEMON_POLL_H
+
+
+#ifdef HAVE_POLL
+/**
+ * Process all of our connections and possibly the server
+ * socket using poll().
+ *
+ * @param daemon daemon to run poll loop for
+ * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_poll_all_ (struct MHD_Daemon *daemon,
+                      bool may_block)
+MHD_NONNULL (1);
+
+
+/**
+ * Process only the listen socket using poll().
+ *
+ * @param daemon daemon to run poll loop for
+ * @param may_block true if blocking, false if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_poll_listen_socket_ (struct MHD_Daemon *daemon,
+                                bool may_block)
+MHD_NONNULL (1);
+
+
+/**
+ * Do poll()-based processing.
+ *
+ * @param daemon daemon to run poll()-loop for
+ * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_poll_ (struct MHD_Daemon *daemon,
+                  bool may_block)
+MHD_NONNULL (1);
+
+#endif
+
+
+#ifdef HTTPS_SUPPORT
+#ifdef HAVE_POLL
+/**
+ * Process upgraded connection with a poll() loop.
+ * We are in our own thread, only processing @a con
+ *
+ * @param con connection to process
+ */
+void
+MHD_daemon_upgrade_connection_with_poll_ (struct MHD_Connection *con)
+MHD_NONNULL (1);
+
+#endif
+#endif
+
+#endif
diff --git a/src/lib/daemon_quiesce.c b/src/lib/daemon_quiesce.c
new file mode 100644
index 0000000..874536d
--- /dev/null
+++ b/src/lib/daemon_quiesce.c
@@ -0,0 +1,128 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_quiesce.c
+ * @brief main functions to quiesce a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Stop accepting connections from the listening socket.  Allows
+ * clients to continue processing, but stops accepting new
+ * connections.  Note that the caller is responsible for closing the
+ * returned socket; however, if MHD is run using threads (anything but
+ * external select mode), it must not be closed until AFTER
+ * #MHD_stop_daemon has been called (as it is theoretically possible
+ * that an existing thread is still using it).
+ *
+ * Note that some thread modes require the caller to have passed
+ * #MHD_USE_ITC when using this API.  If this daemon is
+ * in one of those modes and this option was not given to
+ * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET.
+ *
+ * @param daemon daemon to stop accepting new connections for
+ * @return old listen socket on success, #MHD_INVALID_SOCKET if
+ *         the daemon was already not listening anymore, or
+ *         was never started
+ * @ingroup specialized
+ */
+MHD_socket
+MHD_daemon_quiesce (struct MHD_Daemon *daemon)
+{
+  MHD_socket listen_socket;
+
+  if (MHD_INVALID_SOCKET == (listen_socket = daemon->listen_socket))
+    return MHD_INVALID_SOCKET;
+  if ( (daemon->disable_itc) &&
+       (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_SYSCALL_QUIESCE_REQUIRES_ITC,
+              "Using MHD_quiesce_daemon in this mode requires ITC.\n");
+#endif
+    return MHD_INVALID_SOCKET;
+  }
+
+  if (NULL != daemon->worker_pool)
+  {
+    unsigned int i;
+
+    for (i = 0; i < daemon->worker_pool_size; i++)
+    {
+      struct MHD_Daemon *worker = &daemon->worker_pool[i];
+
+      worker->was_quiesced = true;
+#ifdef EPOLL_SUPPORT
+      if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+           (-1 != worker->epoll_fd) &&
+           (worker->listen_socket_in_epoll) )
+      {
+        if (0 != epoll_ctl (worker->epoll_fd,
+                            EPOLL_CTL_DEL,
+                            listen_socket,
+                            NULL))
+          MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n"));
+        worker->listen_socket_in_epoll = false;
+      }
+      else
+#endif
+      if (MHD_ITC_IS_VALID_ (worker->itc))
+      {
+        if (! MHD_itc_activate_ (worker->itc,
+                                 "q"))
+          MHD_PANIC (_ (
+                       "Failed to signal quiesce via inter-thread communication channel.\n"));
+      }
+    }
+    daemon->was_quiesced = true;
+#ifdef EPOLL_SUPPORT
+    if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+         (-1 != daemon->epoll_fd) &&
+         (daemon->listen_socket_in_epoll) )
+    {
+      if (0 != epoll_ctl (daemon->epoll_fd,
+                          EPOLL_CTL_DEL,
+                          listen_socket,
+                          NULL))
+        MHD_PANIC ("Failed to remove listen FD from epoll set.\n");
+      daemon->listen_socket_in_epoll = false;
+    }
+#endif
+  }
+
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc,
+                             "q")) )
+    MHD_PANIC (_ (
+                 "Failed to signal quiesce via inter-thread communication channel.\n"));
+
+  /* FIXME: we might want some bi-directional communication here
+     (in both the thread-pool and single-thread case!)
+     to be sure that the threads have stopped using the listen
+     socket, otherwise there is still the possibility of a race
+     between a thread accept()ing and the caller closing and
+     re-binding the socket. */return listen_socket;
+}
+
+
+/* end of daemon_quiesce.c */
diff --git a/src/lib/daemon_run.c b/src/lib/daemon_run.c
new file mode 100644
index 0000000..9c68688
--- /dev/null
+++ b/src/lib/daemon_run.c
@@ -0,0 +1,83 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_run.c
+ * @brief generic function to run event loop of a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_cleanup.h"
+#include "daemon_epoll.h"
+#include "daemon_poll.h"
+#include "daemon_select.h"
+
+
+/**
+ * Run webserver operations (without blocking unless in client
+ * callbacks).  This method should be called by clients in combination
+ * with #MHD_get_fdset if the client-controlled select method is used
+ * and #MHD_get_timeout().
+ *
+ * This function is a convenience method, which is useful if the
+ * fd_sets from #MHD_get_fdset were not directly passed to `select()`;
+ * with this function, MHD will internally do the appropriate `select()`
+ * call itself again.  While it is always safe to call #MHD_run (if
+ * #MHD_USE_INTERNAL_POLLING_THREAD is not set), you should call
+ * #MHD_run_from_select if performance is important (as it saves an
+ * expensive call to `select()`).
+ *
+ * @param daemon daemon to run
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+enum MHD_StatusCode
+MHD_daemon_run (struct MHD_Daemon *daemon)
+{
+  enum MHD_StatusCode sc;
+
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+  if (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode)
+    return MHD_SC_CONFIGURATION_MISMATCH_FOR_RUN_EXTERNAL;
+  switch (daemon->event_loop_syscall)
+  {
+  case MHD_ELS_POLL:
+    sc = MHD_daemon_poll_ (daemon,
+                           MHD_NO);
+    MHD_connection_cleanup_ (daemon);
+    return sc;
+#ifdef EPOLL_SUPPORT
+  case MHD_ELS_EPOLL:
+    sc = MHD_daemon_epoll_ (daemon,
+                            MHD_NO);
+    MHD_connection_cleanup_ (daemon);
+    return sc;
+#endif
+  case MHD_ELS_SELECT:
+    return MHD_daemon_select_ (daemon,
+                               MHD_NO);
+  /* MHD_select does MHD_connection_cleanup_ already */
+  default:
+    return MHD_SC_CONFIGURATION_UNEXPECTED_ELS;
+  }
+}
+
+
+/* end of daemon_run.c */
diff --git a/src/lib/daemon_run_from_select.c b/src/lib/daemon_run_from_select.c
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/lib/daemon_run_from_select.c
diff --git a/src/lib/daemon_select.c b/src/lib/daemon_select.c
new file mode 100644
index 0000000..337c75d
--- /dev/null
+++ b/src/lib/daemon_select.c
@@ -0,0 +1,821 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_select.c
+ * @brief function to run select()-based event loop of a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_add.h"
+#include "connection_call_handlers.h"
+#include "connection_cleanup.h"
+#include "connection_finish_forward.h"
+#include "daemon_select.h"
+#include "daemon_epoll.h"
+#include "request_resume.h"
+#include "upgrade_process.h"
+
+
+/**
+ * We defined a macro with the same name as a function we
+ * are implementing here. Need to undef the macro to avoid
+ * causing a conflict.
+ */
+#undef MHD_daemon_get_fdset
+
+/**
+ * Obtain the `select()` sets for this daemon.  Daemon's FDs will be
+ * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO
+ * for each fd_set before calling this function. FD_SETSIZE is assumed
+ * to be platform's default.
+ *
+ * This function should only be called in when MHD is configured to
+ * use external select with 'select()' or with 'epoll'.  In the latter
+ * case, it will only add the single 'epoll()' file descriptor used by
+ * MHD to the sets.  It's necessary to use #MHD_daemon_get_timeout() in
+ * combination with this function.
+ *
+ * This function must be called only for daemon started without
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @return #MHD_SC_OK on success, otherwise error code
+ * @ingroup event
+ */
+enum MHD_StatusCode
+MHD_daemon_get_fdset (struct MHD_Daemon *daemon,
+                      fd_set *read_fd_set,
+                      fd_set *write_fd_set,
+                      fd_set *except_fd_set,
+                      MHD_socket *max_fd)
+{
+  return MHD_daemon_get_fdset2 (daemon,
+                                read_fd_set,
+                                write_fd_set,
+                                except_fd_set,
+                                max_fd,
+                                _MHD_SYS_DEFAULT_FD_SETSIZE);
+}
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Obtain the select() file descriptor sets for the
+ * given @a urh.
+ *
+ * @param urh upgrade handle to wait for
+ * @param[out] rs read set to initialize
+ * @param[out] ws write set to initialize
+ * @param[out] es except set to initialize
+ * @param[out] max_fd maximum FD to update
+ * @param fd_setsize value of FD_SETSIZE
+ * @return true on success, false on error
+ */
+static bool
+urh_to_fdset (struct MHD_UpgradeResponseHandle *urh,
+              fd_set *rs,
+              fd_set *ws,
+              fd_set *es,
+              MHD_socket *max_fd,
+              unsigned int fd_setsize)
+{
+  const MHD_socket conn_sckt = urh->connection->socket_fd;
+  const MHD_socket mhd_sckt = urh->mhd.socket;
+  bool res = true;
+
+  /* Do not add to 'es' only if socket is closed
+   * or not used anymore. */
+  if (MHD_INVALID_SOCKET != conn_sckt)
+  {
+    if ( (urh->in_buffer_used < urh->in_buffer_size) &&
+         (! MHD_add_to_fd_set_ (conn_sckt,
+                                rs,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    if ( (0 != urh->out_buffer_used) &&
+         (! MHD_add_to_fd_set_ (conn_sckt,
+                                ws,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    /* Do not monitor again for errors if error was detected before as
+     * error state is remembered. */
+    if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) &&
+        ((0 != urh->in_buffer_size) ||
+         (0 != urh->out_buffer_size) ||
+         (0 != urh->out_buffer_used)))
+      MHD_add_to_fd_set_ (conn_sckt,
+                          es,
+                          max_fd,
+                          fd_setsize);
+  }
+  if (MHD_INVALID_SOCKET != mhd_sckt)
+  {
+    if ( (urh->out_buffer_used < urh->out_buffer_size) &&
+         (! MHD_add_to_fd_set_ (mhd_sckt,
+                                rs,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    if ( (0 != urh->in_buffer_used) &&
+         (! MHD_add_to_fd_set_ (mhd_sckt,
+                                ws,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    /* Do not monitor again for errors if error was detected before as
+     * error state is remembered. */
+    if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) &&
+        ((0 != urh->out_buffer_size) ||
+         (0 != urh->in_buffer_size) ||
+         (0 != urh->in_buffer_used)))
+      MHD_add_to_fd_set_ (mhd_sckt,
+                          es,
+                          max_fd,
+                          fd_setsize);
+  }
+
+  return res;
+}
+
+
+#endif
+
+
+/**
+ * Internal version of #MHD_daemon_get_fdset2().
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @param fd_setsize value of FD_SETSIZE
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+static enum MHD_StatusCode
+internal_get_fdset2 (struct MHD_Daemon *daemon,
+                     fd_set *read_fd_set,
+                     fd_set *write_fd_set,
+                     fd_set *except_fd_set,
+                     MHD_socket *max_fd,
+                     unsigned int fd_setsize)
+
+{
+  struct MHD_Connection *pos;
+  struct MHD_Connection *posn;
+  enum MHD_StatusCode result = MHD_SC_OK;
+  MHD_socket ls;
+
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+
+  ls = daemon->listen_socket;
+  if ( (MHD_INVALID_SOCKET != ls) &&
+       (! daemon->was_quiesced) &&
+       (! MHD_add_to_fd_set_ (ls,
+                              read_fd_set,
+                              max_fd,
+                              fd_setsize)) )
+    result = MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+
+  /* Add all sockets to 'except_fd_set' as well to watch for
+   * out-of-band data. However, ignore errors if INFO_READ
+   * or INFO_WRITE sockets will not fit 'except_fd_set'. */
+  /* Start from oldest connections. Make sense for W32 FDSETs. */
+  for (pos = daemon->connections_tail; NULL != pos; pos = posn)
+  {
+    posn = pos->prev;
+
+    switch (pos->request.event_loop_info)
+    {
+    case MHD_EVENT_LOOP_INFO_READ:
+      if (! MHD_add_to_fd_set_ (pos->socket_fd,
+                                read_fd_set,
+                                max_fd,
+                                fd_setsize))
+        result = MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+#ifdef MHD_POSIX_SOCKETS
+      MHD_add_to_fd_set_ (pos->socket_fd,
+                          except_fd_set,
+                          max_fd,
+                          fd_setsize);
+#endif /* MHD_POSIX_SOCKETS */
+      break;
+    case MHD_EVENT_LOOP_INFO_WRITE:
+      if (! MHD_add_to_fd_set_ (pos->socket_fd,
+                                write_fd_set,
+                                max_fd,
+                                fd_setsize))
+        result = MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+#ifdef MHD_POSIX_SOCKETS
+      MHD_add_to_fd_set_ (pos->socket_fd,
+                          except_fd_set,
+                          max_fd,
+                          fd_setsize);
+#endif /* MHD_POSIX_SOCKETS */
+      break;
+    case MHD_EVENT_LOOP_INFO_BLOCK:
+      if ( (NULL == except_fd_set) ||
+           ! MHD_add_to_fd_set_ (pos->socket_fd,
+                                 except_fd_set,
+                                 max_fd,
+                                 fd_setsize))
+        result = MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+      break;
+    case MHD_EVENT_LOOP_INFO_CLEANUP:
+      /* this should never happen */
+      break;
+    }
+  }
+#ifdef MHD_WINSOCK_SOCKETS
+  /* W32 use limited array for fd_set so add INFO_READ/INFO_WRITE sockets
+   * only after INFO_BLOCK sockets to ensure that INFO_BLOCK sockets will
+   * not be pushed out. */
+  for (pos = daemon->connections_tail; NULL != pos; pos = posn)
+  {
+    posn = pos->prev;
+    MHD_add_to_fd_set_ (pos->socket_fd,
+                        except_fd_set,
+                        max_fd,
+                        fd_setsize);
+  }
+#endif /* MHD_WINSOCK_SOCKETS */
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  {
+    struct MHD_UpgradeResponseHandle *urh;
+
+    for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev)
+    {
+      if (! urh_to_fdset (urh,
+                          read_fd_set,
+                          write_fd_set,
+                          except_fd_set,
+                          max_fd,
+                          fd_setsize))
+        result = MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+    }
+  }
+#endif
+  return result;
+}
+
+
+/**
+ * Obtain the `select()` sets for this daemon.  Daemon's FDs will be
+ * added to fd_sets. To get only daemon FDs in fd_sets, call FD_ZERO
+ * for each fd_set before calling this function.
+ *
+ * Passing custom FD_SETSIZE as @a fd_setsize allow usage of
+ * larger/smaller than platform's default fd_sets.
+ *
+ * This function should only be called in when MHD is configured to
+ * use external select with 'select()' or with 'epoll'.  In the latter
+ * case, it will only add the single 'epoll' file descriptor used by
+ * MHD to the sets.  It's necessary to use #MHD_get_timeout() in
+ * combination with this function.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @param fd_setsize value of FD_SETSIZE
+ * @return #MHD_SC_OK on success, otherwise error code
+ * @ingroup event
+ */
+enum MHD_StatusCode
+MHD_daemon_get_fdset2 (struct MHD_Daemon *daemon,
+                       fd_set *read_fd_set,
+                       fd_set *write_fd_set,
+                       fd_set *except_fd_set,
+                       MHD_socket *max_fd,
+                       unsigned int fd_setsize)
+{
+  if ( (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode) ||
+       (MHD_ELS_POLL == daemon->event_loop_syscall) )
+    return MHD_SC_CONFIGURATION_MISMATCH_FOR_GET_FDSET;
+
+#ifdef EPOLL_SUPPORT
+  if (MHD_ELS_EPOLL == daemon->event_loop_syscall)
+  {
+    if (daemon->shutdown)
+      return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+
+    /* we're in epoll mode, use the epoll FD as a stand-in for
+       the entire event set */
+
+    return MHD_add_to_fd_set_ (daemon->epoll_fd,
+                               read_fd_set,
+                               max_fd,
+                               fd_setsize)
+           ? MHD_SC_OK
+           : MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+  }
+#endif
+
+  return internal_get_fdset2 (daemon,
+                              read_fd_set,
+                              write_fd_set,
+                              except_fd_set,
+                              max_fd,
+                              fd_setsize);
+}
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Update the @a urh based on the ready FDs in
+ * the @a rs, @a ws, and @a es.
+ *
+ * @param urh upgrade handle to update
+ * @param rs read result from select()
+ * @param ws write result from select()
+ * @param es except result from select()
+ */
+static void
+urh_from_fdset (struct MHD_UpgradeResponseHandle *urh,
+                const fd_set *rs,
+                const fd_set *ws,
+                const fd_set *es)
+{
+  const MHD_socket conn_sckt = urh->connection->socket_fd;
+  const MHD_socket mhd_sckt = urh->mhd.socket;
+
+  /* Reset read/write ready, preserve error state. */
+  urh->app.celi &= (~MHD_EPOLL_STATE_READ_READY & ~MHD_EPOLL_STATE_WRITE_READY);
+  urh->mhd.celi &= (~MHD_EPOLL_STATE_READ_READY & ~MHD_EPOLL_STATE_WRITE_READY);
+
+  if (MHD_INVALID_SOCKET != conn_sckt)
+  {
+    if (FD_ISSET (conn_sckt, rs))
+      urh->app.celi |= MHD_EPOLL_STATE_READ_READY;
+    if (FD_ISSET (conn_sckt, ws))
+      urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY;
+    if (FD_ISSET (conn_sckt, es))
+      urh->app.celi |= MHD_EPOLL_STATE_ERROR;
+  }
+  if ((MHD_INVALID_SOCKET != mhd_sckt))
+  {
+    if (FD_ISSET (mhd_sckt, rs))
+      urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+    if (FD_ISSET (mhd_sckt, ws))
+      urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY;
+    if (FD_ISSET (mhd_sckt, es))
+      urh->mhd.celi |= MHD_EPOLL_STATE_ERROR;
+  }
+}
+
+
+#endif
+
+
+/**
+ * Internal version of #MHD_run_from_select().
+ *
+ * @param daemon daemon to run select loop for
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+static enum MHD_StatusCode
+internal_run_from_select (struct MHD_Daemon *daemon,
+                          const fd_set *read_fd_set,
+                          const fd_set *write_fd_set,
+                          const fd_set *except_fd_set)
+{
+  MHD_socket ds;
+  struct MHD_Connection *pos;
+  struct MHD_Connection *prev;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  struct MHD_UpgradeResponseHandle *urh;
+  struct MHD_UpgradeResponseHandle *urhn;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  /* Reset. New value will be set when connections are processed. */
+  /* Note: no-op for thread-per-connection as it is always false in that mode. */
+  daemon->data_already_pending = false;
+
+  /* Clear ITC to avoid spinning select */
+  /* Do it before any other processing so new signals
+     will trigger select again and will be processed */
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (FD_ISSET (MHD_itc_r_fd_ (daemon->itc),
+                  read_fd_set)) )
+    MHD_itc_clear_ (daemon->itc);
+
+  /* select connection thread handling type */
+  if ( (MHD_INVALID_SOCKET != (ds = daemon->listen_socket)) &&
+       (! daemon->was_quiesced) &&
+       (FD_ISSET (ds,
+                  read_fd_set)) )
+    (void) MHD_accept_connection_ (daemon);
+
+  if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+  {
+    /* do not have a thread per connection, process all connections now */
+    prev = daemon->connections_tail;
+    while (NULL != (pos = prev))
+    {
+      prev = pos->prev;
+      ds = pos->socket_fd;
+      if (MHD_INVALID_SOCKET == ds)
+        continue;
+      MHD_connection_call_handlers_ (pos,
+                                     FD_ISSET (ds,
+                                               read_fd_set),
+                                     FD_ISSET (ds,
+                                               write_fd_set),
+                                     FD_ISSET (ds,
+                                               except_fd_set));
+    }
+  }
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  /* handle upgraded HTTPS connections */
+  for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
+  {
+    urhn = urh->prev;
+    /* update urh state based on select() output */
+    urh_from_fdset (urh,
+                    read_fd_set,
+                    write_fd_set,
+                    except_fd_set);
+    /* call generic forwarding function for passing data */
+    MHD_upgrade_response_handle_process_ (urh);
+    /* Finished forwarding? */
+    if ( (0 == urh->in_buffer_size) &&
+         (0 == urh->out_buffer_size) &&
+         (0 == urh->in_buffer_used) &&
+         (0 == urh->out_buffer_used) )
+    {
+      MHD_connection_finish_forward_ (urh->connection);
+      urh->clean_ready = true;
+      /* Resuming will move connection to cleanup list. */
+      MHD_request_resume (&urh->connection->request);
+    }
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  MHD_connection_cleanup_ (daemon);
+  return MHD_SC_OK;
+}
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Process upgraded connection with a select loop.
+ * We are in our own thread, only processing @a con
+ *
+ * @param con connection to process
+ */
+void
+MHD_daemon_upgrade_connection_with_select_ (struct MHD_Connection *con)
+{
+  struct MHD_UpgradeResponseHandle *urh = con->request.urh;
+
+  while ( (0 != urh->in_buffer_size) ||
+          (0 != urh->out_buffer_size) ||
+          (0 != urh->in_buffer_used) ||
+          (0 != urh->out_buffer_used) )
+  {
+    /* use select */
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket max_fd;
+    int num_ready;
+    bool result;
+
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    max_fd = MHD_INVALID_SOCKET;
+    result = urh_to_fdset (urh,
+                           &rs,
+                           &ws,
+                           &es,
+                           &max_fd,
+                           FD_SETSIZE);
+    if (! result)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (con->daemon,
+                MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE,
+                _ ("Error preparing select.\n"));
+#endif
+      break;
+    }
+    /* FIXME: does this check really needed? */
+    if (MHD_INVALID_SOCKET != max_fd)
+    {
+      struct timeval *tvp;
+      struct timeval tv;
+      if ( (con->tls_read_ready) &&
+           (urh->in_buffer_used < urh->in_buffer_size))
+      { /* No need to wait if incoming data is already pending in TLS buffers. */
+        tv.tv_sec = 0;
+        tv.tv_usec = 0;
+        tvp = &tv;
+      }
+      else
+        tvp = NULL;
+      num_ready = MHD_SYS_select_ (max_fd + 1,
+                                   &rs,
+                                   &ws,
+                                   &es,
+                                   tvp);
+    }
+    else
+      num_ready = 0;
+    if (num_ready < 0)
+    {
+      const int err = MHD_socket_get_error_ ();
+
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        continue;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (con->daemon,
+                MHD_SC_UNEXPECTED_SELECT_ERROR,
+                _ ("Error during select (%d): `%s'\n"),
+                err,
+                MHD_socket_strerr_ (err));
+#endif
+      break;
+    }
+    urh_from_fdset (urh,
+                    &rs,
+                    &ws,
+                    &es);
+    MHD_upgrade_response_handle_process_ (urh);
+  }
+}
+
+
+#endif
+
+
+/**
+ * Run webserver operations. This method should be called by clients
+ * in combination with #MHD_get_fdset and #MHD_get_timeout() if the
+ * client-controlled select method is used.
+ *
+ * You can use this function instead of #MHD_run if you called
+ * `select()` on the result from #MHD_get_fdset.  File descriptors in
+ * the sets that are not controlled by MHD will be ignored.  Calling
+ * this function instead of #MHD_run is more efficient as MHD will not
+ * have to call `select()` again to determine which operations are
+ * ready.
+ *
+ * This function cannot be used with daemon started with
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to run select loop for
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+enum MHD_StatusCode
+MHD_daemon_run_from_select (struct MHD_Daemon *daemon,
+                            const fd_set *read_fd_set,
+
+
+                            const fd_set *write_fd_set,
+                            const fd_set *except_fd_set)
+{
+  if ( (MHD_TM_EXTERNAL_EVENT_LOOP != daemon->threading_mode) ||
+       (MHD_ELS_POLL == daemon->event_loop_syscall) )
+    return MHD_SC_CONFIGURATION_MISMATCH_FOR_RUN_SELECT;
+  if (MHD_ELS_EPOLL == daemon->event_loop_syscall)
+  {
+#ifdef EPOLL_SUPPORT
+    enum MHD_StatusCode sc;
+
+    sc = MHD_daemon_epoll_ (daemon,
+                            MHD_NO);
+    MHD_connection_cleanup_ (daemon);
+    return sc;
+#else  /* ! EPOLL_SUPPORT */
+    return MHD_NO;
+#endif /* ! EPOLL_SUPPORT */
+  }
+
+  /* Resuming external connections when using an extern mainloop  */
+  if (! daemon->disallow_suspend_resume)
+    (void) MHD_resume_suspended_connections_ (daemon);
+
+  return internal_run_from_select (daemon,
+                                   read_fd_set,
+                                   write_fd_set,
+                                   except_fd_set);
+}
+
+
+/**
+ * Main internal select() call.  Will compute select sets, call
+ * select() and then #internal_run_from_select() with the result.
+ *
+ * @param daemon daemon to run select() loop for
+ * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_select_ (struct MHD_Daemon *daemon,
+                    int may_block)
+{
+  int num_ready;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket maxsock;
+  struct timeval timeout;
+  struct timeval *tv;
+  MHD_UNSIGNED_LONG_LONG ltimeout;
+  MHD_socket ls;
+  enum MHD_StatusCode sc;
+  enum MHD_StatusCode sc2;
+
+  timeout.tv_sec = 0;
+  timeout.tv_usec = 0;
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+  FD_ZERO (&rs);
+  FD_ZERO (&ws);
+  FD_ZERO (&es);
+  maxsock = MHD_INVALID_SOCKET;
+  sc = MHD_SC_OK;
+  if ( (! daemon->disallow_suspend_resume) &&
+       (MHD_resume_suspended_connections_ (daemon)) &&
+       (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode) )
+    may_block = MHD_NO;
+
+  if (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode)
+  {
+
+    /* single-threaded, go over everything */
+    if (MHD_SC_OK !=
+        (sc = internal_get_fdset2 (daemon,
+                                   &rs,
+                                   &ws,
+                                   &es,
+                                   &maxsock,
+                                   FD_SETSIZE)))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                sc,
+                _ ("Could not obtain daemon fdsets.\n"));
+#endif
+    }
+  }
+  else
+  {
+    /* accept only, have one thread per connection */
+    if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_socket)) &&
+         (! daemon->was_quiesced) &&
+         (! MHD_add_to_fd_set_ (ls,
+                                &rs,
+                                &maxsock,
+                                FD_SETSIZE)) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE,
+                _ ("Could not add listen socket to fdset.\n"));
+#endif
+      return MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+    }
+  }
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                              &rs,
+                              &maxsock,
+                              FD_SETSIZE)) )
+  {
+#if defined(MHD_WINSOCK_SOCKETS)
+    /* fdset limit reached, new connections
+       cannot be handled. Remove listen socket FD
+       from fdset and retry to add ITC FD. */
+    if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_socket)) &&
+         (! daemon->was_quiesced) )
+    {
+      FD_CLR (ls,
+              &rs);
+      if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                                &rs,
+                                &maxsock,
+                                FD_SETSIZE))
+      {
+#endif /* MHD_WINSOCK_SOCKETS */
+    sc = MHD_SC_SOCKET_OUTSIDE_OF_FDSET_RANGE;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              sc,
+              _ (
+                "Could not add control inter-thread communication channel FD to fdset.\n"));
+#endif
+#if defined(MHD_WINSOCK_SOCKETS)
+  }
+}
+
+
+#endif /* MHD_WINSOCK_SOCKETS */
+  }
+  /* Stop listening if we are at the configured connection limit */
+  /* If we're at the connection limit, no point in really
+     accepting new connections; however, make sure we do not miss
+     the shutdown OR the termination of an existing connection; so
+     only do this optimization if we have a signaling ITC in
+     place. */
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_socket)) &&
+       (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       ( (daemon->connections == daemon->global_connection_limit) ||
+         (daemon->at_limit) ) )
+  {
+    FD_CLR (ls,
+            &rs);
+  }
+  tv = NULL;
+  if (MHD_SC_OK != sc)
+    may_block = MHD_NO;
+  if (MHD_NO == may_block)
+  {
+    timeout.tv_usec = 0;
+    timeout.tv_sec = 0;
+    tv = &timeout;
+  }
+  else if ( (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode) &&
+            (MHD_SC_OK ==
+             MHD_daemon_get_timeout (daemon,
+                                     &ltimeout)) )
+  {
+    /* ltimeout is in ms */
+    timeout.tv_usec = (ltimeout % 1000) * 1000;
+    if (ltimeout / 1000 > TIMEVAL_TV_SEC_MAX)
+      timeout.tv_sec = TIMEVAL_TV_SEC_MAX;
+    else
+      timeout.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) (ltimeout / 1000);
+    tv = &timeout;
+  }
+  num_ready = MHD_SYS_select_ (maxsock + 1,
+                               &rs,
+                               &ws,
+                               &es,
+                               tv);
+  if (daemon->shutdown)
+    return MHD_SC_DAEMON_ALREADY_SHUTDOWN;
+  if (num_ready < 0)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return sc;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_UNEXPECTED_SELECT_ERROR,
+              _ ("select failed: %s\n"),
+              MHD_socket_strerr_ (err));
+#endif
+    return MHD_SC_UNEXPECTED_SELECT_ERROR;
+  }
+  if (MHD_SC_OK !=
+      (sc2 = internal_run_from_select (daemon,
+                                       &rs,
+                                       &ws,
+                                       &es)))
+    return sc2;
+  return sc;
+}
+
+/* end of daemon_select.c */
diff --git a/src/lib/daemon_select.h b/src/lib/daemon_select.h
new file mode 100644
index 0000000..a82725f
--- /dev/null
+++ b/src/lib/daemon_select.h
@@ -0,0 +1,56 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_select.h
+ * @brief  non-public functions provided by daemon_select.c
+ * @author Christian Grothoff
+ */
+
+#ifndef DAEMON_SELECT_H
+#define DAEMON_SELECT_H
+
+/**
+ * Main internal select() call.  Will compute select sets, call
+ * select() and then #internal_run_from_select() with the result.
+ *
+ * @param daemon daemon to run select() loop for
+ * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @return #MHD_SC_OK on success
+ */
+enum MHD_StatusCode
+MHD_daemon_select_ (struct MHD_Daemon *daemon,
+                    int may_block)
+MHD_NONNULL (1);
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Process upgraded connection with a select loop.
+ * We are in our own thread, only processing @a con
+ *
+ * @param con connection to process
+ */
+void
+MHD_daemon_upgrade_connection_with_select_ (struct MHD_Connection *con)
+MHD_NONNULL (1);
+
+#endif
+
+#endif
diff --git a/src/lib/daemon_start.c b/src/lib/daemon_start.c
new file mode 100644
index 0000000..be3191d
--- /dev/null
+++ b/src/lib/daemon_start.c
@@ -0,0 +1,975 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/daemon_start.c
+ * @brief functions to start a daemon
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_cleanup.h"
+#include "daemon_close_all_connections.h"
+#include "daemon_select.h"
+#include "daemon_poll.h"
+#include "daemon_epoll.h"
+#include "request_resume.h"
+
+
+/**
+ * Set listen socket options to allow port rebinding (or not)
+ * depending on how MHD was configured.
+ *
+ * @param[in,out] daemon the daemon with the listen socket to configure
+ * @return #MHD_SC_OK on success (or non-fatal errors)
+ */
+static enum MHD_StatusCode
+configure_listen_reuse (struct MHD_Daemon *daemon)
+{
+  const MHD_SCKT_OPT_BOOL_ on = 1;
+
+  /* Apply the socket options according to
+     listening_address_reuse. */
+  if (daemon->allow_address_reuse)
+  {
+    /* User requested to allow reusing listening address:port. */
+#ifndef MHD_WINSOCK_SOCKETS
+    /* Use SO_REUSEADDR on non-W32 platforms, and do not fail if
+     * it doesn't work. */
+    if (0 > setsockopt (daemon->listen_socket,
+                        SOL_SOCKET,
+                        SO_REUSEADDR,
+                        (void *) &on,
+                        sizeof (on)))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_FAILED,
+                _ ("setsockopt failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      return MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_FAILED;
+    }
+    return MHD_SC_OK;
+#endif /* ! MHD_WINSOCK_SOCKETS */
+    /* Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms.
+     * Fail if SO_REUSEPORT is not defined or setsockopt fails.
+     */
+    /* SO_REUSEADDR on W32 has the same semantics
+ as SO_REUSEPORT on BSD/Linux */
+#if defined(MHD_WINSOCK_SOCKETS) || defined(SO_REUSEPORT)
+    if (0 > setsockopt (daemon->listen_socket,
+                        SOL_SOCKET,
+#ifndef MHD_WINSOCK_SOCKETS
+                        SO_REUSEPORT,
+#else  /* MHD_WINSOCK_SOCKETS */
+                        SO_REUSEADDR,
+#endif /* MHD_WINSOCK_SOCKETS */
+                        (void *) &on,
+                        sizeof (on)))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_FAILED,
+                _ ("setsockopt failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      return MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_FAILED;
+    }
+    return MHD_SC_OK;
+#else  /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */
+    /* we're supposed to allow address:port re-use, but
+ on this platform we cannot; fail hard */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_NOT_SUPPORTED,
+              _ (
+                "Cannot allow listening address reuse: SO_REUSEPORT not defined.\n"));
+#endif
+    return MHD_SC_LISTEN_ADDRESS_REUSE_ENABLE_NOT_SUPPORTED;
+#endif /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */
+  }
+
+  /* if (! daemon->allow_address_reuse) */
+  /* User requested to disallow reusing listening address:port.
+   * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE
+   * is used and Solaris with SO_EXCLBIND.
+   * Fail if MHD was compiled for W32 without SO_EXCLUSIVEADDRUSE
+   * or setsockopt fails.
+   */
+#if (defined(MHD_WINSOCK_SOCKETS) && defined(SO_EXCLUSIVEADDRUSE)) || \
+  (defined(__sun) && defined(SO_EXCLBIND))
+  if (0 > setsockopt (daemon->listen_socket,
+                      SOL_SOCKET,
+#ifdef SO_EXCLUSIVEADDRUSE
+                      SO_EXCLUSIVEADDRUSE,
+#else  /* SO_EXCLBIND */
+                      SO_EXCLBIND,
+#endif /* SO_EXCLBIND */
+                      (void *) &on,
+                      sizeof (on)))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_FAILED,
+              _ ("setsockopt failed: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    return MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_FAILED;
+  }
+  return MHD_SC_OK;
+#elif defined(MHD_WINSOCK_SOCKETS) /* SO_EXCLUSIVEADDRUSE not defined on W32? */
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (daemon,
+            MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_NOT_SUPPORTED,
+            _ (
+              "Cannot disallow listening address reuse: SO_EXCLUSIVEADDRUSE not defined.\n"));
+#endif
+  return MHD_SC_LISTEN_ADDRESS_REUSE_DISABLE_NOT_SUPPORTED;
+#endif /* MHD_WINSOCK_SOCKETS */
+  /* Not on WINSOCK, simply doing nothing will do */
+  return MHD_SC_OK;
+}
+
+
+/**
+ * Open, configure and bind the listen socket (if required).
+ *
+ * @param[in,out] daemon daemon to open the socket for
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+open_listen_socket (struct MHD_Daemon *daemon)
+{
+  enum MHD_StatusCode sc;
+  socklen_t addrlen;
+  struct sockaddr_storage ss;
+  const struct sockaddr *sa;
+  int pf;
+  bool use_v6;
+
+  if (MHD_INVALID_SOCKET != daemon->listen_socket)
+    return MHD_SC_OK; /* application opened it for us! */
+  pf = -1;
+  /* Determine address family */
+  switch (daemon->listen_af)
+  {
+  case MHD_AF_NONE:
+    if (0 == daemon->listen_sa_len)
+    {
+      /* no listening desired, that's OK */
+      return MHD_SC_OK;
+    }
+    /* we have a listen address, get AF from there! */
+    switch (daemon->listen_sa.ss_family)
+    {
+    case AF_INET:
+      pf = PF_INET;
+      use_v6 = false;
+      break;
+#ifdef AF_INET6
+    case AF_INET6:
+      pf = PF_INET6;
+      use_v6 = true;
+      break;
+#endif
+#ifdef AF_UNIX
+    case AF_UNIX:
+      pf = PF_UNIX;
+      use_v6 = false;
+      break;
+#endif
+    default:
+      return MHD_SC_AF_NOT_SUPPORTED_BY_BUILD;
+    } /* switch on ss_family */
+    break;   /* MHD_AF_NONE */
+  case MHD_AF_AUTO:
+#ifdef HAVE_INET6
+    pf = PF_INET6;
+    use_v6 = true;
+#else
+    pf = PF_INET;
+    use_v6 = false;
+#endif
+    break;
+  case MHD_AF_INET4:
+    use_v6 = false;
+    pf = PF_INET;
+    break;
+  case MHD_AF_INET6:
+  case MHD_AF_DUAL:
+#ifdef HAVE_INET6
+    pf = PF_INET6;
+    use_v6 = true;
+    break;
+#else
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_IPV6_NOT_SUPPORTED_BY_BUILD,
+              _ ("IPv6 not supported by this build.\n"));
+#endif
+    return MHD_SC_IPV6_NOT_SUPPORTED_BY_BUILD;
+#endif
+  }
+  mhd_assert (-1 != pf);
+  /* try to open listen socket */
+try_open_listen_socket:
+  daemon->listen_socket = MHD_socket_create_listen_ (pf);
+  if ( (MHD_INVALID_SOCKET == daemon->listen_socket) &&
+       (MHD_AF_AUTO == daemon->listen_af) &&
+       (use_v6) )
+  {
+    use_v6 = false;
+    pf = PF_INET;
+    goto try_open_listen_socket;
+  }
+  if (MHD_INVALID_SOCKET == daemon->listen_socket)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_FAILED_TO_OPEN_LISTEN_SOCKET,
+              _ ("Failed to create socket for listening: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    return MHD_SC_FAILED_TO_OPEN_LISTEN_SOCKET;
+  }
+
+  if (MHD_SC_OK !=
+      (sc = configure_listen_reuse (daemon)))
+    return sc;
+
+  /* configure for dual stack (or not) */
+  if (use_v6)
+  {
+#if defined IPPROTO_IPV6 && defined IPV6_V6ONLY
+    /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options"
+ (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx);
+ and may also be missing on older POSIX systems; good luck if you have any of those,
+ your IPv6 socket may then also bind against IPv4 anyway... */
+    const MHD_SCKT_OPT_BOOL_ v6_only =
+      (MHD_AF_INET6 == daemon->listen_af);
+    if (0 > setsockopt (daemon->listen_socket,
+                        IPPROTO_IPV6,
+                        IPV6_V6ONLY,
+                        (const void *) &v6_only,
+                        sizeof (v6_only)))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_LISTEN_DUAL_STACK_CONFIGURATION_FAILED,
+                _ ("setsockopt failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+    }
+#else
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_DUAL_STACK_CONFIGURATION_NOT_SUPPORTED,
+              _ (
+                "Cannot explicitly setup dual stack behavior on this platform.\n"));
+#endif
+#endif
+  }
+
+  /* Determine address to bind to */
+  if (0 != daemon->listen_sa_len)
+  {
+    /* Bind address explicitly given */
+    sa = (const struct sockaddr *) &daemon->listen_sa;
+    addrlen = daemon->listen_sa_len;
+  }
+  else
+  {
+    /* Compute bind address based on port and AF */
+#ifdef HAVE_INET6
+    if (use_v6)
+    {
+#ifdef IN6ADDR_ANY_INIT
+      static const struct in6_addr static_in6any = IN6ADDR_ANY_INIT;
+#endif
+      struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &ss;
+
+      addrlen = sizeof (struct sockaddr_in6);
+      memset (sin6,
+              0,
+              sizeof (struct sockaddr_in6));
+      sin6->sin6_family = AF_INET6;
+      sin6->sin6_port = htons (daemon->listen_port);
+#ifdef IN6ADDR_ANY_INIT
+      sin6->sin6_addr = static_in6any;
+#endif
+#if HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+      sin6->sin6_len = sizeof (struct sockaddr_in6);
+#endif
+    }
+    else
+#endif
+    {
+      struct sockaddr_in *sin4 = (struct sockaddr_in *) &ss;
+
+      addrlen = sizeof (struct sockaddr_in);
+      memset (sin4,
+              0,
+              sizeof (struct sockaddr_in));
+      sin4->sin_family = AF_INET;
+      sin4->sin_port = htons (daemon->listen_port);
+      if (0 != INADDR_ANY)
+        sin4->sin_addr.s_addr = htonl (INADDR_ANY);
+#if HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+      sin4->sin_len = sizeof (struct sockaddr_in);
+#endif
+    }
+    sa = (const struct sockaddr *) &ss;
+  }
+
+  /* actually do the bind() */
+  if (-1 == bind (daemon->listen_socket,
+                  sa,
+                  addrlen))
+  {
+#ifdef HAVE_MESSAGES
+    unsigned int port = 0;
+
+    switch (sa->sa_family)
+    {
+    case AF_INET:
+      if (addrlen == sizeof (struct sockaddr_in))
+        port = ntohs (((const struct sockaddr_in *) sa)->sin_port);
+      else
+        port = UINT16_MAX + 1; /* indicate size error */
+      break;
+    case AF_INET6:
+      if (addrlen == sizeof (struct sockaddr_in6))
+        port = ntohs (((const struct sockaddr_in6 *) sa)->sin6_port);
+      else
+        port = UINT16_MAX + 1; /* indicate size error */
+      break;
+    default:
+      port = UINT_MAX; /* AF_UNIX? */
+      break;
+    }
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_SOCKET_BIND_FAILED,
+              _ ("Failed to bind to port %u: %s\n"),
+              port,
+              MHD_socket_last_strerr_ ());
+#endif
+    return MHD_SC_LISTEN_SOCKET_BIND_FAILED;
+  }
+
+  /* setup TCP_FASTOPEN */
+#ifdef TCP_FASTOPEN
+  if (MHD_FOM_DISABLE != daemon->fast_open_method)
+  {
+    if (0 != setsockopt (daemon->listen_socket,
+                         IPPROTO_TCP,
+                         TCP_FASTOPEN,
+                         &daemon->fo_queue_length,
+                         sizeof (daemon->fo_queue_length)))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_FAST_OPEN_FAILURE,
+                _ ("setsockopt failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      if (MHD_FOM_REQUIRE == daemon->fast_open_method)
+        return MHD_SC_FAST_OPEN_FAILURE;
+    }
+  }
+#endif
+
+  /* setup listening */
+  if (0 > listen (daemon->listen_socket,
+                  daemon->listen_backlog))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_FAILURE,
+              _ ("Failed to listen for connections: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    return MHD_SC_LISTEN_FAILURE;
+  }
+  return MHD_SC_OK;
+}
+
+
+/**
+ * Obtain the listen port number from the socket (if it
+ * was not explicitly set by us, i.e. if we were given
+ * a listen socket or if the port was 0 and the OS picked
+ * a free one).
+ *
+ * @param[in,out] daemon daemon to obtain the port number for
+ */
+static void
+get_listen_port_number (struct MHD_Daemon *daemon)
+{
+  struct sockaddr_storage servaddr;
+  socklen_t addrlen;
+
+  if ( (0 != daemon->listen_port) ||
+       (MHD_INVALID_SOCKET == daemon->listen_socket) )
+    return; /* nothing to be done */
+
+  memset (&servaddr,
+          0,
+          sizeof (struct sockaddr_storage));
+  addrlen = sizeof (servaddr);
+  if (0 != getsockname (daemon->listen_socket,
+                        (struct sockaddr *) &servaddr,
+                        &addrlen))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_PORT_INTROSPECTION_FAILURE,
+              _ ("Failed to get listen port number: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif /* HAVE_MESSAGES */
+    return;
+  }
+#ifdef MHD_POSIX_SOCKETS
+  if (sizeof (servaddr) < addrlen)
+  {
+    /* should be impossible with `struct sockaddr_storage` */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_PORT_INTROSPECTION_FAILURE,
+              _ (
+                "Failed to get listen port number (`struct sockaddr_storage` too small!?).\n"));
+#endif /* HAVE_MESSAGES */
+    return;
+  }
+#endif /* MHD_POSIX_SOCKETS */
+  switch (servaddr.ss_family)
+  {
+  case AF_INET:
+    {
+      struct sockaddr_in *s4 = (struct sockaddr_in *) &servaddr;
+
+      daemon->listen_port = ntohs (s4->sin_port);
+      break;
+    }
+#ifdef HAVE_INET6
+  case AF_INET6:
+    {
+      struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &servaddr;
+
+      daemon->listen_port = ntohs (s6->sin6_port);
+      break;
+    }
+#endif /* HAVE_INET6 */
+#ifdef AF_UNIX
+  case AF_UNIX:
+    daemon->listen_port = 0;   /* special value for UNIX domain sockets */
+    break;
+#endif
+  default:
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_PORT_INTROSPECTION_UNKNOWN_AF,
+              _ ("Unknown address family!\n"));
+#endif
+    daemon->listen_port = 0;   /* ugh */
+    break;
+  }
+}
+
+
+#ifdef EPOLL_SUPPORT
+/**
+ * Setup file descriptor to be used for epoll() control.
+ *
+ * @param daemon the daemon to setup epoll FD for
+ * @return the epoll() fd to use
+ */
+static int
+setup_epoll_fd (struct MHD_Daemon *daemon)
+{
+  int fd;
+
+#ifndef HAVE_MESSAGES
+  (void) daemon; /* Mute compiler warning. */
+#endif /* ! HAVE_MESSAGES */
+
+#ifdef USE_EPOLL_CREATE1
+  fd = epoll_create1 (EPOLL_CLOEXEC);
+#else  /* ! USE_EPOLL_CREATE1 */
+  fd = epoll_create (MAX_EVENTS);
+#endif /* ! USE_EPOLL_CREATE1 */
+  if (MHD_INVALID_SOCKET == fd)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_EPOLL_CTL_CREATE_FAILED,
+              _ ("Call to epoll_create1 failed: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    return MHD_INVALID_SOCKET;
+  }
+#if ! defined(USE_EPOLL_CREATE1)
+  if (! MHD_socket_noninheritable_ (fd))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_EPOLL_CTL_CONFIGURE_NOINHERIT_FAILED,
+              _ ("Failed to set noninheritable mode on epoll FD.\n"));
+#endif
+  }
+#endif /* ! USE_EPOLL_CREATE1 */
+  return fd;
+}
+
+
+/**
+ * Setup epoll() FD for the daemon and initialize it to listen
+ * on the listen FD.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon daemon to initialize for epoll()
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+setup_epoll_to_listen (struct MHD_Daemon *daemon)
+{
+  struct epoll_event event;
+  MHD_socket ls;
+
+  /* FIXME: update function! */
+  daemon->epoll_fd = setup_epoll_fd (daemon);
+  if (-1 == daemon->epoll_fd)
+    return MHD_SC_EPOLL_CTL_CREATE_FAILED;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if (! daemon->disallow_upgrade)
+  {
+    daemon->epoll_upgrade_fd = setup_epoll_fd (daemon);
+    if (MHD_INVALID_SOCKET == daemon->epoll_upgrade_fd)
+      return MHD_SC_EPOLL_CTL_CREATE_FAILED;
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  if ( (MHD_INVALID_SOCKET == (ls = daemon->listen_socket)) ||
+       (daemon->was_quiesced) )
+    return MHD_SC_OK; /* non-listening daemon */
+  event.events = EPOLLIN;
+  event.data.ptr = daemon;
+  if (0 != epoll_ctl (daemon->epoll_fd,
+                      EPOLL_CTL_ADD,
+                      ls,
+                      &event))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_EPOLL_CTL_ADD_FAILED,
+              _ ("Call to epoll_ctl failed: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    return MHD_SC_EPOLL_CTL_ADD_FAILED;
+  }
+  daemon->listen_socket_in_epoll = true;
+  if (MHD_ITC_IS_VALID_ (daemon->itc))
+  {
+    event.events = EPOLLIN;
+    event.data.ptr = (void *) daemon->epoll_itc_marker;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        MHD_itc_r_fd_ (daemon->itc),
+                        &event))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_EPOLL_CTL_ADD_FAILED,
+                _ ("Call to epoll_ctl failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      return MHD_SC_EPOLL_CTL_ADD_FAILED;
+    }
+  }
+  return MHD_SC_OK;
+}
+
+
+#endif
+
+
+/**
+ * Thread that runs the polling loop until the daemon
+ * is explicitly shut down.
+ *
+ * @param cls `struct MHD_Deamon` to run select loop in a thread for
+ * @return always 0 (on shutdown)
+ */
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+MHD_polling_thread (void *cls)
+{
+  struct MHD_Daemon *daemon = cls;
+
+  MHD_thread_init_ (&daemon->pid);
+  while (! daemon->shutdown)
+  {
+    switch (daemon->event_loop_syscall)
+    {
+    case MHD_ELS_AUTO:
+      MHD_PANIC ("MHD_ELS_AUTO should have been mapped to preferred style.\n");
+      break;
+    case MHD_ELS_SELECT:
+      MHD_daemon_select_ (daemon,
+                          MHD_YES);
+      break;
+    case MHD_ELS_POLL:
+#ifdef HAVE_POLL
+      MHD_daemon_poll_ (daemon,
+                        MHD_YES);
+#else
+      MHD_PANIC ("MHD_ELS_POLL not supported, should have failed earlier.\n");
+#endif
+      break;
+    case MHD_ELS_EPOLL:
+#ifdef EPOLL_SUPPORT
+      MHD_daemon_epoll_ (daemon,
+                         MHD_YES);
+#else
+      MHD_PANIC ("MHD_ELS_EPOLL not supported, should have failed earlier.\n");
+#endif
+      break;
+    }
+    MHD_connection_cleanup_ (daemon);
+  }
+  /* Resume any pending for resume connections, join
+   * all connection's threads (if any) and finally cleanup
+   * everything. */
+  if (! daemon->disallow_suspend_resume)
+    MHD_resume_suspended_connections_ (daemon);
+  MHD_daemon_close_all_connections_ (daemon);
+
+  return (MHD_THRD_RTRN_TYPE_) 0;
+}
+
+
+/**
+ * Setup the thread pool (if needed).
+ *
+ * @param[in,out] daemon daemon to setup thread pool for
+ * @return #MHD_SC_OK on success
+ */
+static enum MHD_StatusCode
+setup_thread_pool (struct MHD_Daemon *daemon)
+{
+  /* Coarse-grained count of connections per thread (note error
+   * due to integer division). Also keep track of how many
+   * connections are leftover after an equal split. */
+  unsigned int conns_per_thread = daemon->global_connection_limit
+                                  / daemon->threading_mode;
+  unsigned int leftover_conns = daemon->global_connection_limit
+                                % daemon->threading_mode;
+  int i;
+  enum MHD_StatusCode sc;
+
+  /* Allocate memory for pooled objects */
+  daemon->worker_pool = MHD_calloc_ (daemon->threading_mode,
+                                     sizeof (struct MHD_Daemon));
+  if (NULL == daemon->worker_pool)
+    return MHD_SC_THREAD_POOL_MALLOC_FAILURE;
+
+  /* Start the workers in the pool */
+  for (i = 0; i < daemon->threading_mode; i++)
+  {
+    /* Create copy of the Daemon object for each worker */
+    struct MHD_Daemon *d = &daemon->worker_pool[i];
+
+    memcpy (d,
+            daemon,
+            sizeof (struct MHD_Daemon));
+    /* Adjust pooling params for worker daemons; note that memcpy()
+ has already copied MHD_USE_INTERNAL_POLLING_THREAD thread mode into
+ the worker threads. */
+    d->master = daemon;
+    d->worker_pool_size = 0;
+    d->worker_pool = NULL;
+    /* Divide available connections evenly amongst the threads.
+     * Thread indexes in [0, leftover_conns) each get one of the
+     * leftover connections. */
+    d->global_connection_limit = conns_per_thread;
+    if (((unsigned int) i) < leftover_conns)
+      ++d->global_connection_limit;
+
+    if (! daemon->disable_itc)
+    {
+      if (! MHD_itc_init_ (d->itc))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  MHD_SC_ITC_INITIALIZATION_FAILED,
+                  _ (
+                    "Failed to create worker inter-thread communication channel: %s\n"),
+                  MHD_itc_last_strerror_ () );
+#endif
+        sc = MHD_SC_ITC_INITIALIZATION_FAILED;
+        goto thread_failed;
+      }
+      if ( (MHD_ELS_SELECT == daemon->event_loop_syscall) &&
+           (! MHD_SCKT_FD_FITS_FDSET_ (MHD_itc_r_fd_ (d->itc),
+                                       NULL)) )
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  MHD_SC_ITC_DESCRIPTOR_TOO_LARGE,
+                  _ (
+                    "File descriptor for inter-thread communication channel exceeds maximum value.\n"));
+#endif
+        MHD_itc_destroy_chk_ (d->itc);
+        sc = MHD_SC_ITC_DESCRIPTOR_TOO_LARGE;
+        goto thread_failed;
+      }
+    }
+    else
+    {
+      MHD_itc_set_invalid_ (d->itc);
+    }
+
+#ifdef EPOLL_SUPPORT
+    if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+         (MHD_SC_OK != (sc = setup_epoll_to_listen (d))) )
+      goto thread_failed;
+#endif
+
+    /* Must init cleanup connection mutex for each worker */
+    if (! MHD_mutex_init_ (&d->cleanup_connection_mutex))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_THREAD_POOL_CREATE_MUTEX_FAILURE,
+                _ ("MHD failed to initialize cleanup connection mutex.\n"));
+#endif
+      if (! daemon->disable_itc)
+        MHD_itc_destroy_chk_ (d->itc);
+      sc = MHD_SC_THREAD_POOL_CREATE_MUTEX_FAILURE;
+      goto thread_failed;
+    }
+
+    /* Spawn the worker thread */
+    if (! MHD_create_named_thread_ (&d->pid,
+                                    "MHD-worker",
+                                    daemon->thread_stack_limit_b,
+                                    &MHD_polling_thread,
+                                    d))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_THREAD_POOL_LAUNCH_FAILURE,
+                _ ("Failed to create pool thread: %s\n"),
+                MHD_strerror_ (errno));
+#endif
+      /* Free memory for this worker; cleanup below handles
+       * all previously-created workers. */
+      if (! daemon->disable_itc)
+        MHD_itc_destroy_chk_ (d->itc);
+      MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+      sc = MHD_SC_THREAD_POOL_LAUNCH_FAILURE;
+      goto thread_failed;
+    }
+  }   /* end for() */
+  return MHD_SC_OK;
+
+thread_failed:
+  /* If no worker threads created, then shut down normally. Calling
+     MHD_stop_daemon (as we do below) doesn't work here since it
+     assumes a 0-sized thread pool means we had been in the default
+     MHD_USE_INTERNAL_POLLING_THREAD mode. */
+  if (0 == i)
+  {
+    if (NULL != daemon->worker_pool)
+    {
+      free (daemon->worker_pool);
+      daemon->worker_pool = NULL;
+    }
+    return MHD_SC_THREAD_LAUNCH_FAILURE;
+  }
+  /* Shutdown worker threads we've already created. Pretend
+     as though we had fully initialized our daemon, but
+     with a smaller number of threads than had been
+     requested. */
+  daemon->worker_pool_size = i;
+  daemon->listen_socket = MHD_daemon_quiesce (daemon);
+  return sc;
+}
+
+
+/**
+ * Start a webserver.
+ *
+ * @param daemon daemon to start; you can no longer set
+ *        options on this daemon after this call!
+ * @return #MHD_SC_OK on success
+ * @ingroup event
+ */
+enum MHD_StatusCode
+MHD_daemon_start (struct MHD_Daemon *daemon)
+{
+  enum MHD_StatusCode sc;
+
+  if (MHD_ELS_AUTO == daemon->event_loop_syscall)
+  {
+#if EPOLL_SUPPORT
+    /* We do not support thread-per-connection in combination
+ with epoll, so use poll in this case, otherwise prefer
+ epoll. */
+    if (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode)
+      daemon->event_loop_syscall = MHD_ELS_POLL;
+    else
+      daemon->event_loop_syscall = MHD_ELS_EPOLL;
+#elif defined(HAVE_POLL)
+    daemon->event_loop_syscall = MHD_ELS_POLL;
+#else
+    daemon->event_loop_syscall = MHD_ELS_SELECT;
+#endif
+  }
+
+#ifdef EPOLL_SUPPORT
+  if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+       (0 == daemon->worker_pool_size) &&
+       (MHD_INVALID_SOCKET != daemon->listen_socket) &&
+       (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_SYSCALL_THREAD_COMBINATION_INVALID,
+              _ (
+                "Combining MHD_USE_THREAD_PER_CONNECTION and MHD_USE_EPOLL is not supported.\n"));
+#endif
+    return MHD_SC_SYSCALL_THREAD_COMBINATION_INVALID;
+  }
+#endif
+
+  /* Setup ITC */
+  if ( (! daemon->disable_itc) &&
+       (0 == daemon->worker_pool_size) )
+  {
+    if (! MHD_itc_init_ (daemon->itc))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_ITC_INITIALIZATION_FAILED,
+                _ ("Failed to create inter-thread communication channel: %s\n"),
+                MHD_itc_last_strerror_ ());
+#endif
+      return MHD_SC_ITC_INITIALIZATION_FAILED;
+    }
+    if ( (MHD_ELS_SELECT == daemon->event_loop_syscall) &&
+         (! MHD_SCKT_FD_FITS_FDSET_ (MHD_itc_r_fd_ (daemon->itc),
+                                     NULL)) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_ITC_DESCRIPTOR_TOO_LARGE,
+                _ (
+                  "File descriptor for inter-thread communication channel exceeds maximum value.\n"));
+#endif
+      return MHD_SC_ITC_DESCRIPTOR_TOO_LARGE;
+    }
+  }
+
+  if (MHD_SC_OK != (sc = open_listen_socket (daemon)))
+    return sc;
+
+  /* Check listen socket is in range (if we are limited) */
+  if ( (MHD_INVALID_SOCKET != daemon->listen_socket) &&
+       (MHD_ELS_SELECT == daemon->event_loop_syscall) &&
+       (! MHD_SCKT_FD_FITS_FDSET_ (daemon->listen_socket,
+                                   NULL)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_SOCKET_TOO_LARGE,
+              _ ("Socket descriptor larger than FD_SETSIZE: %d > %d\n"),
+              daemon->listen_socket,
+              FD_SETSIZE);
+#endif
+    return MHD_SC_LISTEN_SOCKET_TOO_LARGE;
+  }
+
+  /* set listen socket to non-blocking */
+  if ( (MHD_INVALID_SOCKET != daemon->listen_socket) &&
+       (! MHD_socket_nonblocking_ (daemon->listen_socket)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_LISTEN_SOCKET_NONBLOCKING_FAILURE,
+              _ ("Failed to set nonblocking mode on listening socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) ||
+         (daemon->worker_pool_size > 0) )
+    {
+      /* Accept must be non-blocking. Multiple children may wake
+       * up to handle a new connection, but only one will win the
+       * race.  The others must immediately return. As this is
+       * not possible, we must fail hard here. */
+      return MHD_SC_LISTEN_SOCKET_NONBLOCKING_FAILURE;
+    }
+  }
+
+#ifdef EPOLL_SUPPORT
+  /* Setup epoll */
+  if ( (MHD_ELS_EPOLL == daemon->event_loop_syscall) &&
+       (0 == daemon->worker_pool_size) &&
+       (MHD_INVALID_SOCKET != daemon->listen_socket) &&
+       (MHD_SC_OK != (sc = setup_epoll_to_listen (daemon))) )
+    return sc;
+#endif
+
+  /* Setup main listen thread (only if we have no thread pool or
+     external event loop and do have a listen socket) */
+  /* FIXME: why no worker thread if we have no listen socket? */
+  if ( ( (MHD_TM_THREAD_PER_CONNECTION == daemon->threading_mode) ||
+         (1 == daemon->threading_mode) ) &&
+       (MHD_INVALID_SOCKET != daemon->listen_socket) &&
+       (! MHD_create_named_thread_ (&daemon->pid,
+                                    (MHD_TM_THREAD_PER_CONNECTION ==
+                                     daemon->threading_mode)
+                                    ? "MHD-listen"
+                                    : "MHD-single",
+                                    daemon->thread_stack_limit_b,
+                                    &MHD_polling_thread,
+                                    daemon) ) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_THREAD_MAIN_LAUNCH_FAILURE,
+              _ ("Failed to create listen thread: %s\n"),
+              MHD_strerror_ (errno));
+#endif
+    return MHD_SC_THREAD_MAIN_LAUNCH_FAILURE;
+  }
+
+  /* Setup worker threads */
+  /* FIXME: why no thread pool if we have no listen socket? */
+  if ( (1 < daemon->threading_mode) &&
+       (MHD_INVALID_SOCKET != daemon->listen_socket) &&
+       (MHD_SC_OK != (sc = setup_thread_pool (daemon))) )
+    return sc;
+
+  /* make sure we know our listen port (if any) */
+  get_listen_port_number (daemon);
+
+  return MHD_SC_OK;
+}
+
+
+/* end of daemon_start.c */
diff --git a/src/lib/init.c b/src/lib/init.c
new file mode 100644
index 0000000..2bdc91b
--- /dev/null
+++ b/src/lib/init.c
@@ -0,0 +1,149 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/init.c
+ * @brief initialization routines
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "init.h"
+
+
+#ifndef _AUTOINIT_FUNCS_ARE_SUPPORTED
+/**
+ * Track global initialisation
+ */
+volatile unsigned int global_init_count = 0;
+
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+/**
+ * Global initialisation mutex
+ */
+MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+
+#endif
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+/**
+ * Track initialization of winsock
+ */
+static int mhd_winsock_inited_ = 0;
+#endif
+
+/**
+ * Default implementation of the panic function,
+ * prints an error message and aborts.
+ *
+ * @param cls unused
+ * @param file name of the file with the problem
+ * @param line line number with the problem
+ * @param reason error message with details
+ */
+static void
+mhd_panic_std (void *cls,
+               const char *file,
+               unsigned int line,
+               const char *reason)
+{
+  (void) cls; /* Mute compiler warning. */
+#ifdef HAVE_MESSAGES
+  fprintf (stderr,
+           _ ("Fatal error in GNU libmicrohttpd %s:%u: %s\n"),
+           file,
+           line,
+           reason);
+#else  /* ! HAVE_MESSAGES */
+  (void) file;   /* Mute compiler warning. */
+  (void) line;   /* Mute compiler warning. */
+  (void) reason; /* Mute compiler warning. */
+#endif
+  abort ();
+}
+
+
+/**
+ * Globally initialize library.
+ */
+void
+MHD_init (void)
+{
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+  WSADATA wsd;
+#endif /* _WIN32 && ! __CYGWIN__ */
+
+  if (NULL == mhd_panic)
+    mhd_panic = &mhd_panic_std;
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+  if (0 != WSAStartup (MAKEWORD (2, 2),
+                       &wsd))
+    MHD_PANIC (_ ("Failed to initialize winsock.\n"));
+  mhd_winsock_inited_ = 1;
+  if ( (2 != LOBYTE (wsd.wVersion)) &&
+       (2 != HIBYTE (wsd.wVersion)) )
+    MHD_PANIC (_ ("Winsock version 2.2 is not available.\n"));
+#endif
+  MHD_monotonic_sec_counter_init ();
+#ifdef HAVE_FREEBSD_SENDFILE
+  MHD_conn_init_static_ ();
+#endif /* HAVE_FREEBSD_SENDFILE */
+}
+
+
+/**
+ * Global teardown work.
+ */
+void
+MHD_fini (void)
+{
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+  if (mhd_winsock_inited_)
+    WSACleanup ();
+#endif
+  MHD_monotonic_sec_counter_finish ();
+}
+
+
+#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
+
+_SET_INIT_AND_DEINIT_FUNCS (MHD_init, MHD_fini);
+
+#else
+
+/**
+ * Check whether global initialisation was performed
+ * and call initialiser if necessary.
+ */
+void
+MHD_check_global_init_ (void)
+{
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+  MHD_mutex_lock_chk_ (&global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+  if (0 == global_init_count++)
+    MHD_init ();
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+  MHD_mutex_unlock_chk_ (&global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+}
+
+
+#endif
diff --git a/src/lib/init.h b/src/lib/init.h
new file mode 100644
index 0000000..b5671b2
--- /dev/null
+++ b/src/lib/init.h
@@ -0,0 +1,46 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/init.h
+ * @brief functions to initialize library
+ * @author Christian Grothoff
+ */
+#ifndef INIT_H
+#define INIT_H
+
+#include "internal.h"
+
+#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
+/**
+ * Do nothing - global initialisation is
+ * performed by library constructor.
+ */
+#define MHD_check_global_init_() (void) 0
+#else  /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
+/**
+ * Check whether global initialisation was performed
+ * and call initialiser if necessary.
+ */
+void
+MHD_check_global_init_ (void);
+
+#endif /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
+
+
+#endif  /* INIT_H */
diff --git a/src/lib/internal.c b/src/lib/internal.c
new file mode 100644
index 0000000..ade15e0
--- /dev/null
+++ b/src/lib/internal.c
@@ -0,0 +1,288 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/internal.c
+ * @brief  internal shared structures
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "mhd_str.h"
+
+#ifdef HAVE_MESSAGES
+#if DEBUG_STATES
+/**
+ * State to string dictionary.
+ */
+const char *
+MHD_state_to_string (enum MHD_CONNECTION_STATE state)
+{
+  switch (state)
+  {
+  case MHD_CONNECTION_INIT:
+    return "connection init";
+  case MHD_CONNECTION_URL_RECEIVED:
+    return "connection url received";
+  case MHD_CONNECTION_HEADER_PART_RECEIVED:
+    return "header partially received";
+  case MHD_CONNECTION_HEADERS_RECEIVED:
+    return "headers received";
+  case MHD_CONNECTION_HEADERS_PROCESSED:
+    return "headers processed";
+  case MHD_CONNECTION_CONTINUE_SENDING:
+    return "continue sending";
+  case MHD_CONNECTION_CONTINUE_SENT:
+    return "continue sent";
+  case MHD_CONNECTION_BODY_RECEIVED:
+    return "body received";
+  case MHD_CONNECTION_FOOTER_PART_RECEIVED:
+    return "footer partially received";
+  case MHD_CONNECTION_FOOTERS_RECEIVED:
+    return "footers received";
+  case MHD_CONNECTION_HEADERS_SENDING:
+    return "headers sending";
+  case MHD_CONNECTION_HEADERS_SENT:
+    return "headers sent";
+  case MHD_CONNECTION_NORMAL_BODY_READY:
+    return "normal body ready";
+  case MHD_CONNECTION_NORMAL_BODY_UNREADY:
+    return "normal body unready";
+  case MHD_CONNECTION_CHUNKED_BODY_READY:
+    return "chunked body ready";
+  case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
+    return "chunked body unready";
+  case MHD_CONNECTION_BODY_SENT:
+    return "body sent";
+  case MHD_CONNECTION_FOOTERS_SENDING:
+    return "footers sending";
+  case MHD_CONNECTION_FOOTERS_SENT:
+    return "footers sent";
+  case MHD_CONNECTION_CLOSED:
+    return "closed";
+  default:
+    return "unrecognized connection state";
+  }
+}
+
+
+#endif
+#endif
+
+
+#ifdef HAVE_MESSAGES
+/**
+ * fprintf-like helper function for logging debug
+ * messages.
+ */
+void
+MHD_DLOG (const struct MHD_Daemon *daemon,
+          enum MHD_StatusCode sc,
+          const char *format,
+          ...)
+{
+  va_list va;
+
+  if (NULL == daemon->logger)
+    return;
+  va_start (va,
+            format);
+  daemon->logger (daemon->logger_cls,
+                  sc,
+                  format,
+                  va);
+  va_end (va);
+}
+
+
+#endif
+
+
+/**
+ * Convert all occurrences of '+' to ' '.
+ *
+ * @param arg string that is modified (in place), must be 0-terminated
+ */
+void
+MHD_unescape_plus (char *arg)
+{
+  char *p;
+
+  for (p = strchr (arg, '+'); NULL != p; p = strchr (p + 1, '+'))
+    *p = ' ';
+}
+
+
+/**
+ * Process escape sequences ('%HH') Updates val in place; the
+ * result should be UTF-8 encoded and cannot be larger than the input.
+ * The result must also still be 0-terminated.
+ *
+ * @param val value to unescape (modified in the process)
+ * @return length of the resulting val (strlen(val) maybe
+ *  shorter afterwards due to elimination of escape sequences)
+ */
+size_t
+MHD_http_unescape (char *val)
+{
+  char *rpos = val;
+  char *wpos = val;
+
+  while ('\0' != *rpos)
+  {
+    uint32_t num;
+    switch (*rpos)
+    {
+    case '%':
+      if (2 == MHD_strx_to_uint32_n_ (rpos + 1,
+                                      2,
+                                      &num))
+      {
+        *wpos = (char) ((unsigned char) num);
+        wpos++;
+        rpos += 3;
+        break;
+      }
+    /* TODO: add bad sequence handling */
+    /* intentional fall through! */
+    default:
+      *wpos = *rpos;
+      wpos++;
+      rpos++;
+    }
+  }
+  *wpos = '\0'; /* add 0-terminator */
+  return wpos - val; /* = strlen(val) */
+}
+
+
+/**
+ * Parse and unescape the arguments given by the client
+ * as part of the HTTP request URI.
+ *
+ * @param request request to add headers to
+ * @param kind header kind to pass to @a cb
+ * @param[in,out] args argument URI string (after "?" in URI),
+ *        clobbered in the process!
+ * @param cb function to call on each key-value pair found
+ * @param[out] num_headers set to the number of headers found
+ * @return false on failure (@a cb returned false),
+ *         true for success (parsing succeeded, @a cb always
+ *                               returned true)
+ */
+bool
+MHD_parse_arguments_ (struct MHD_Request *request,
+                      enum MHD_ValueKind kind,
+                      char *args,
+                      MHD_ArgumentIterator_ cb,
+                      unsigned int *num_headers)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+  char *equals;
+  char *amper;
+
+  *num_headers = 0;
+  while ( (NULL != args) &&
+          ('\0' != args[0]) )
+  {
+    equals = strchr (args, '=');
+    amper = strchr (args, '&');
+    if (NULL == amper)
+    {
+      /* last argument */
+      if (NULL == equals)
+      {
+        /* last argument, without '=' */
+        MHD_unescape_plus (args);
+        daemon->unescape_cb (daemon->unescape_cb_cls,
+                             request,
+                             args);
+        if (! cb (request,
+                  args,
+                  NULL,
+                  kind))
+          return false;
+        (*num_headers)++;
+        break;
+      }
+      /* got 'foo=bar' */
+      equals[0] = '\0';
+      equals++;
+      MHD_unescape_plus (args);
+      daemon->unescape_cb (daemon->unescape_cb_cls,
+                           request,
+                           args);
+      MHD_unescape_plus (equals);
+      daemon->unescape_cb (daemon->unescape_cb_cls,
+                           request,
+                           equals);
+      if (! cb (request,
+                args,
+                equals,
+                kind))
+        return false;
+      (*num_headers)++;
+      break;
+    }
+    /* amper is non-NULL here */
+    amper[0] = '\0';
+    amper++;
+    if ( (NULL == equals) ||
+         (equals >= amper) )
+    {
+      /* got 'foo&bar' or 'foo&bar=val', add key 'foo' with NULL for value */
+      MHD_unescape_plus (args);
+      daemon->unescape_cb (daemon->unescape_cb_cls,
+                           request,
+                           args);
+      if (! cb (request,
+                args,
+                NULL,
+                kind))
+        return false;
+      /* continue with 'bar' */
+      (*num_headers)++;
+      args = amper;
+      continue;
+    }
+    /* equals and amper are non-NULL here, and equals < amper,
+ so we got regular 'foo=value&bar...'-kind of argument */
+    equals[0] = '\0';
+    equals++;
+    MHD_unescape_plus (args);
+    daemon->unescape_cb (daemon->unescape_cb_cls,
+                         request,
+                         args);
+    MHD_unescape_plus (equals);
+    daemon->unescape_cb (daemon->unescape_cb_cls,
+                         request,
+                         equals);
+    if (! cb (request,
+              args,
+              equals,
+              kind))
+      return false;
+    (*num_headers)++;
+    args = amper;
+  }
+  return true;
+}
+
+
+/* end of internal.c */
diff --git a/src/lib/internal.h b/src/lib/internal.h
new file mode 100644
index 0000000..ebd59d0
--- /dev/null
+++ b/src/lib/internal.h
@@ -0,0 +1,1892 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2017 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/internal.h
+ * @brief  internal shared structures
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ */
+
+#ifndef INTERNAL_H
+#define INTERNAL_H
+
+#include "mhd_options.h"
+#include "platform.h"
+#include "microhttpd2.h"
+#include "microhttpd_tls.h"
+#include "mhd_assert.h"
+#include "mhd_compat.h"
+#include "mhd_itc.h"
+#include "mhd_mono_clock.h"
+#include "memorypool.h"
+
+#ifdef HTTPS_SUPPORT
+#include <gnutls/gnutls.h>
+#if GNUTLS_VERSION_MAJOR >= 3
+#include <gnutls/abstract.h>
+#endif
+#endif /* HTTPS_SUPPORT */
+
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+#ifdef MHD_PANIC
+/* Override any defined MHD_PANIC macro with proper one */
+#undef MHD_PANIC
+#endif /* MHD_PANIC */
+
+#ifdef HAVE_MESSAGES
+/**
+ * Trigger 'panic' action based on fatal errors.
+ *
+ * @param msg error message (const char *)
+ */
+#define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, msg); \
+                            BUILTIN_NOT_REACHED; } while (0)
+#else
+/**
+ * Trigger 'panic' action based on fatal errors.
+ *
+ * @param msg error message (const char *)
+ */
+#define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL); \
+                            BUILTIN_NOT_REACHED; } while (0)
+#endif
+
+#include "mhd_threads.h"
+#include "mhd_locks.h"
+#include "mhd_sockets.h"
+#include "mhd_str.h"
+#include "mhd_itc_types.h"
+
+
+#ifdef HAVE_MESSAGES
+/**
+ * fprintf()-like helper function for logging debug
+ * messages.
+ */
+void
+MHD_DLOG (const struct MHD_Daemon *daemon,
+          enum MHD_StatusCode sc,
+          const char *format,
+          ...);
+
+#endif
+
+
+/**
+ * Close FD and abort execution if error is detected.
+ * @param fd the FD to close
+ */
+#define MHD_fd_close_chk_(fd) do {                      \
+    if ( (0 != close ((fd)) && (EBADF == errno)) )  \
+      MHD_PANIC (_ ("Failed to close FD.\n"));            \
+} while (0)
+
+/**
+ * Should we perform additional sanity checks at runtime (on our internal
+ * invariants)?  This may lead to aborts, but can be useful for debugging.
+ */
+#define EXTRA_CHECKS MHD_NO
+
+#define MHD_MAX(a,b) (((a)<(b)) ? (b) : (a))
+#define MHD_MIN(a,b) (((a)<(b)) ? (a) : (b))
+
+
+/**
+ * Minimum size by which MHD tries to increment read/write buffers.
+ * We usually begin with half the available pool space for the
+ * IO-buffer, but if absolutely needed we additively grow by the
+ * number of bytes given here (up to -- theoretically -- the full pool
+ * space).
+ */
+#define MHD_BUF_INC_SIZE 1024
+
+
+/**
+ * Handler for fatal errors.
+ */
+extern MHD_PanicCallback mhd_panic;
+
+/**
+ * Closure argument for "mhd_panic".
+ */
+extern void *mhd_panic_cls;
+
+/* If we have Clang or gcc >= 4.5, use __buildin_unreachable() */
+#if defined(__clang__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= \
+                                             5)
+#define BUILTIN_NOT_REACHED __builtin_unreachable ()
+#elif defined(_MSC_FULL_VER)
+#define BUILTIN_NOT_REACHED __assume (0)
+#else
+#define BUILTIN_NOT_REACHED
+#endif
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+/**
+ * Ability to use same connection for next request
+ */
+enum MHD_ConnKeepAlive
+{
+  /**
+   * Connection must be closed after sending response.
+   */
+  MHD_CONN_MUST_CLOSE = -1,
+
+  /**
+   * KeelAlive state is not yet determined
+   */
+  MHD_CONN_KEEPALIVE_UNKOWN = 0,
+
+  /**
+   * Connection can be used for serving next request
+   */
+  MHD_CONN_USE_KEEPALIVE = 1
+};
+
+
+/**
+ * Function to receive plaintext data.
+ *
+ * @param conn the connection struct
+ * @param write_to where to write received data
+ * @param max_bytes maximum number of bytes to receive
+ * @return number of bytes written to @a write_to
+ */
+typedef ssize_t
+(*ReceiveCallback) (struct MHD_Connection *conn,
+                    void *write_to,
+                    size_t max_bytes);
+
+
+/**
+ * Function to transmit plaintext data.
+ *
+ * @param conn the connection struct
+ * @param read_from where to read data to transmit
+ * @param max_bytes maximum number of bytes to transmit
+ * @return number of bytes transmitted
+ */
+typedef ssize_t
+(*TransmitCallback) (struct MHD_Connection *conn,
+                     const void *read_from,
+                     size_t max_bytes);
+
+
+/**
+ * States in a state machine for a request.
+ *
+ * The main transitions are any-state to #MHD_REQUEST_CLOSED, any
+ * state to state+1, #MHD_REQUEST_FOOTERS_SENT to
+ * #MHD_REQUEST_INIT.  #MHD_REQUEST_CLOSED is the terminal state
+ * and #MHD_REQUEST_INIT the initial state.
+ *
+ * Note that transitions for *reading* happen only after the input has
+ * been processed; transitions for *writing* happen after the
+ * respective data has been put into the write buffer (the write does
+ * not have to be completed yet).  A transition to
+ * #MHD_REQUEST_CLOSED or #MHD_REQUEST_INIT requires the write
+ * to be complete.
+ */
+enum MHD_REQUEST_STATE // FIXME: fix capitalization!
+{
+  /**
+   * Request just started (no headers received).
+   * Waiting for the line with the request type, URL and version.
+   */
+  MHD_REQUEST_INIT = 0,
+
+  /**
+   * 1: We got the URL (and request type and version).  Wait for a header line.
+   */
+  MHD_REQUEST_URL_RECEIVED = MHD_REQUEST_INIT + 1,
+
+  /**
+   * 2: We got part of a multi-line request header.  Wait for the rest.
+   */
+  MHD_REQUEST_HEADER_PART_RECEIVED = MHD_REQUEST_URL_RECEIVED + 1,
+
+  /**
+   * 3: We got the request headers.  Process them.
+   */
+  MHD_REQUEST_HEADERS_RECEIVED = MHD_REQUEST_HEADER_PART_RECEIVED + 1,
+
+  /**
+   * 4: We have processed the request headers.  Send 100 continue.
+   */
+  MHD_REQUEST_HEADERS_PROCESSED = MHD_REQUEST_HEADERS_RECEIVED + 1,
+
+  /**
+   * 5: We have processed the headers and need to send 100 CONTINUE.
+   */
+  MHD_REQUEST_CONTINUE_SENDING = MHD_REQUEST_HEADERS_PROCESSED + 1,
+
+  /**
+   * 6: We have sent 100 CONTINUE (or do not need to).  Read the message body.
+   */
+  MHD_REQUEST_CONTINUE_SENT = MHD_REQUEST_CONTINUE_SENDING + 1,
+
+  /**
+   * 7: We got the request body.  Wait for a line of the footer.
+   */
+  MHD_REQUEST_BODY_RECEIVED = MHD_REQUEST_CONTINUE_SENT + 1,
+
+  /**
+   * 8: We got part of a line of the footer.  Wait for the
+   * rest.
+   */
+  MHD_REQUEST_FOOTER_PART_RECEIVED = MHD_REQUEST_BODY_RECEIVED + 1,
+
+  /**
+   * 9: We received the entire footer.  Wait for a response to be queued
+   * and prepare the response headers.
+   */
+  MHD_REQUEST_FOOTERS_RECEIVED = MHD_REQUEST_FOOTER_PART_RECEIVED + 1,
+
+  /**
+   * 10: We have prepared the response headers in the writ buffer.
+   * Send the response headers.
+   */
+  MHD_REQUEST_HEADERS_SENDING = MHD_REQUEST_FOOTERS_RECEIVED + 1,
+
+  /**
+   * 11: We have sent the response headers.  Get ready to send the body.
+   */
+  MHD_REQUEST_HEADERS_SENT = MHD_REQUEST_HEADERS_SENDING + 1,
+
+  /**
+   * 12: We are ready to send a part of a non-chunked body.  Send it.
+   */
+  MHD_REQUEST_NORMAL_BODY_READY = MHD_REQUEST_HEADERS_SENT + 1,
+
+  /**
+   * 13: We are waiting for the client to provide more
+   * data of a non-chunked body.
+   */
+  MHD_REQUEST_NORMAL_BODY_UNREADY = MHD_REQUEST_NORMAL_BODY_READY + 1,
+
+  /**
+   * 14: We are ready to send a chunk.
+   */
+  MHD_REQUEST_CHUNKED_BODY_READY = MHD_REQUEST_NORMAL_BODY_UNREADY + 1,
+
+  /**
+   * 15: We are waiting for the client to provide a chunk of the body.
+   */
+  MHD_REQUEST_CHUNKED_BODY_UNREADY = MHD_REQUEST_CHUNKED_BODY_READY + 1,
+
+  /**
+   * 16: We have sent the response body. Prepare the footers.
+   */
+  MHD_REQUEST_BODY_SENT = MHD_REQUEST_CHUNKED_BODY_UNREADY + 1,
+
+  /**
+   * 17: We have prepared the response footer.  Send it.
+   */
+  MHD_REQUEST_FOOTERS_SENDING = MHD_REQUEST_BODY_SENT + 1,
+
+  /**
+   * 18: We have sent the response footer.  Shutdown or restart.
+   */
+  MHD_REQUEST_FOOTERS_SENT = MHD_REQUEST_FOOTERS_SENDING + 1,
+
+  /**
+   * 19: This request is to be closed.
+   */
+  MHD_REQUEST_CLOSED = MHD_REQUEST_FOOTERS_SENT + 1,
+
+#ifdef UPGRADE_SUPPORT
+  /**
+   * Request was "upgraded" and socket is now under the
+   * control of the application.
+   */
+  MHD_REQUEST_UPGRADE
+#endif /* UPGRADE_SUPPORT */
+
+};
+
+
+/**
+ * Header or cookie in HTTP request or response.
+ */
+struct MHD_HTTP_Header
+{
+  /**
+   * Headers are kept in a linked list.
+   */
+  struct MHD_HTTP_Header *next;
+
+  /**
+   * The name of the header (key), without the colon.
+   */
+  char *header;
+
+  /**
+   * The value of the header.
+   */
+  char *value;
+
+  /**
+   * Type of the header (where in the HTTP protocol is this header
+   * from).
+   */
+  enum MHD_ValueKind kind;
+
+};
+
+
+/**
+ * State kept for each HTTP request.
+ */
+struct MHD_Request
+{
+
+  /**
+   * Reference to the `struct MHD_Daemon`.
+   */
+  struct MHD_Daemon *daemon;
+
+  /**
+   * Connection this request is associated with.
+   */
+  struct MHD_Connection *connection;
+
+  /**
+   * Response to return for this request, set once
+   * it is available.
+   */
+  struct MHD_Response *response;
+
+  /**
+   * Linked list of parsed headers.
+   */
+  struct MHD_HTTP_Header *headers_received;
+
+  /**
+   * Tail of linked list of parsed headers.
+   */
+  struct MHD_HTTP_Header *headers_received_tail;
+
+  /**
+   * We allow the main application to associate some pointer with the
+   * HTTP request, which is passed to each #MHD_AccessHandlerCallback
+   * and some other API calls.  Here is where we store it.  (MHD does
+   * not know or care what it is).
+   */
+  void *client_context;
+
+  /**
+   * Request method as string.  Should be GET/POST/etc.  Allocated in
+   * pool.
+   */
+  char *method_s;
+
+  /**
+   * Requested URL (everything after "GET" only).  Allocated
+   * in pool.
+   */
+  const char *url;
+
+  /**
+   * HTTP version string (i.e. http/1.1).  Allocated
+   * in pool.
+   */
+  char *version_s;
+
+  /**
+   * Close connection after sending response?
+   * Functions may change value from "Unknown" or "KeepAlive" to "Must close",
+   * but no functions reset value "Must Close" to any other value.
+   */
+  enum MHD_ConnKeepAlive keepalive;
+
+  /**
+   * Buffer for reading requests.  Allocated in pool.  Actually one
+   * byte larger than @e read_buffer_size (if non-NULL) to allow for
+   * 0-termination.
+   */
+  char *read_buffer;
+
+  /**
+   * Buffer for writing response (headers only).  Allocated
+   * in pool.
+   */
+  char *write_buffer;
+
+  /**
+   * Last incomplete header line during parsing of headers.
+   * Allocated in pool.  Only valid if state is
+   * either #MHD_REQUEST_HEADER_PART_RECEIVED or
+   * #MHD_REQUEST_FOOTER_PART_RECEIVED.
+   */
+  char *last;
+
+  /**
+   * Position after the colon on the last incomplete header
+   * line during parsing of headers.
+   * Allocated in pool.  Only valid if state is
+   * either #MHD_REQUEST_HEADER_PART_RECEIVED or
+   * #MHD_REQUEST_FOOTER_PART_RECEIVED.
+   */
+  char *colon;
+
+#ifdef UPGRADE_SUPPORT
+  /**
+   * If this connection was upgraded, this points to
+   * the upgrade response details such that the
+   * #thread_main_connection_upgrade()-logic can perform the
+   * bi-directional forwarding.
+   */
+  struct MHD_UpgradeResponseHandle *urh;
+#endif /* UPGRADE_SUPPORT */
+
+  /**
+   * Size of @e read_buffer (in bytes).  This value indicates
+   * how many bytes we're willing to read into the buffer;
+   * the real buffer is one byte longer to allow for
+   * adding zero-termination (when needed).
+   */
+  size_t read_buffer_size;
+
+  /**
+   * Position where we currently append data in
+   * @e read_buffer (last valid position).
+   */
+  size_t read_buffer_offset;
+
+  /**
+   * Size of @e write_buffer (in bytes).
+   */
+  size_t write_buffer_size;
+
+  /**
+   * Offset where we are with sending from @e write_buffer.
+   */
+  size_t write_buffer_send_offset;
+
+  /**
+   * Last valid location in write_buffer (where do we
+   * append and up to where is it safe to send?)
+   */
+  size_t write_buffer_append_offset;
+
+  /**
+   * Number of bytes we had in the HTTP header, set once we
+   * pass #MHD_REQUEST_HEADERS_RECEIVED.
+   */
+  size_t header_size;
+
+  /**
+   * How many more bytes of the body do we expect
+   * to read? #MHD_SIZE_UNKNOWN for unknown.
+   */
+  uint64_t remaining_upload_size;
+
+  /**
+   * If we are receiving with chunked encoding, where are we right
+   * now?  Set to 0 if we are waiting to receive the chunk size;
+   * otherwise, this is the size of the current chunk.  A value of
+   * zero is also used when we're at the end of the chunks.
+   */
+  uint64_t current_chunk_size;
+
+  /**
+   * If we are receiving with chunked encoding, where are we currently
+   * with respect to the current chunk (at what offset / position)?
+   */
+  uint64_t current_chunk_offset;
+
+  /**
+   * Current write position in the actual response
+   * (excluding headers, content only; should be 0
+   * while sending headers).
+   */
+  uint64_t response_write_position;
+
+  #if defined(_MHD_HAVE_SENDFILE)
+  // FIXME: document, fix capitalization!
+  enum MHD_resp_sender_
+  {
+    MHD_resp_sender_std = 0,
+    MHD_resp_sender_sendfile
+  } resp_sender;
+#endif /* _MHD_HAVE_SENDFILE */
+
+  /**
+   * Position in the 100 CONTINUE message that
+   * we need to send when receiving http 1.1 requests.
+   */
+  size_t continue_message_write_offset;
+
+  /**
+   * State in the FSM for this request.
+   */
+  enum MHD_REQUEST_STATE state;
+
+  /**
+   * HTTP method, as an enum.
+   */
+  enum MHD_Method method;
+
+  /**
+   * What is this request waiting for?
+   */
+  enum MHD_RequestEventLoopInfo event_loop_info;
+
+  /**
+   * Are we currently inside the "idle" handler (to avoid recursively
+   * invoking it).
+   */
+  bool in_idle;
+
+  /**
+   * Are we currently inside the "idle" handler (to avoid recursively
+   * invoking it).
+   */
+  bool in_cleanup;
+
+  /**
+   * Are we receiving with chunked encoding?  This will be set to
+   * #MHD_YES after we parse the headers and are processing the body
+   * with chunks.  After we are done with the body and we are
+   * processing the footers; once the footers are also done, this will
+   * be set to #MHD_NO again (before the final call to the handler).
+   */
+  bool have_chunked_upload;
+};
+
+
+/**
+ * State of the socket with respect to epoll (bitmask).
+ */
+enum MHD_EpollState
+{
+
+  /**
+   * The socket is not involved with a defined state in epoll() right
+   * now.
+   */
+  MHD_EPOLL_STATE_UNREADY = 0,
+
+  /**
+   * epoll() told us that data was ready for reading, and we did
+   * not consume all of it yet.
+   */
+  MHD_EPOLL_STATE_READ_READY = 1,
+
+  /**
+   * epoll() told us that space was available for writing, and we did
+   * not consume all of it yet.
+   */
+  MHD_EPOLL_STATE_WRITE_READY = 2,
+
+  /**
+   * Is this connection currently in the 'eready' EDLL?
+   */
+  MHD_EPOLL_STATE_IN_EREADY_EDLL = 4,
+
+  /**
+   * Is this connection currently in the epoll() set?
+   */
+  MHD_EPOLL_STATE_IN_EPOLL_SET = 8,
+
+  /**
+   * Is this connection currently suspended?
+   */
+  MHD_EPOLL_STATE_SUSPENDED = 16,
+
+  /**
+   * Is this connection in some error state?
+   */
+  MHD_EPOLL_STATE_ERROR = 128
+};
+
+
+/**
+ * State kept per HTTP connection.
+ */
+struct MHD_Connection
+{
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * Next pointer for the EDLL listing connections that are epoll-ready.
+   */
+  struct MHD_Connection *nextE;
+
+  /**
+   * Previous pointer for the EDLL listing connections that are epoll-ready.
+   */
+  struct MHD_Connection *prevE;
+#endif
+
+  /**
+   * Next pointer for the DLL describing our IO state.
+   */
+  struct MHD_Connection *next;
+
+  /**
+   * Previous pointer for the DLL describing our IO state.
+   */
+  struct MHD_Connection *prev;
+
+  /**
+   * Next pointer for the XDLL organizing connections by timeout.
+   * This DLL can be either the
+   * 'manual_timeout_head/manual_timeout_tail' or the
+   * 'normal_timeout_head/normal_timeout_tail', depending on whether a
+   * custom timeout is set for the connection.
+   */
+  struct MHD_Connection *nextX;
+
+  /**
+   * Previous pointer for the XDLL organizing connections by timeout.
+   */
+  struct MHD_Connection *prevX;
+
+  /**
+   * Reference to the MHD_Daemon struct.
+   */
+  struct MHD_Daemon *daemon;
+
+  /**
+   * The memory pool is created whenever we first read from the TCP
+   * stream and destroyed at the end of each request (and re-created
+   * for the next request).  In the meantime, this pointer is NULL.
+   * The pool is used for all request-related data except for the
+   * response (which maybe shared between requests) and the IP
+   * address (which persists across individual requests).
+   */
+  struct MemoryPool *pool;
+
+  /**
+   * We allow the main application to associate some pointer with the
+   * TCP connection (which may span multiple HTTP requests).  Here is
+   * where we store it.  (MHD does not know or care what it is).
+   * The location is given to the #MHD_NotifyConnectionCallback and
+   * also accessible via #MHD_CONNECTION_INFO_SOCKET_CONTEXT.
+   */
+  void *socket_context;
+
+#ifdef HTTPS_SUPPORT
+  /**
+   * State kept per TLS connection. Plugin-specific.
+   */
+  struct MHD_TLS_ConnectionState *tls_cs;
+#endif
+
+  /**
+   * Function used for reading HTTP request stream.
+   */
+  ReceiveCallback recv_cls;
+
+  /**
+   * Function used for writing HTTP response stream.
+   */
+  TransmitCallback send_cls;
+
+  /**
+   * Information about the current request we are processing
+   * on this connection.
+   */
+  struct MHD_Request request;
+
+  /**
+   * Thread handle for this connection (if we are using
+   * one thread per connection).
+   */
+  MHD_thread_handle_ID_ pid;
+
+  /**
+   * Foreign address (of length @e addr_len).
+   */
+  struct sockaddr_storage addr;
+
+  /**
+   * Length of the foreign address.
+   */
+  socklen_t addr_len;
+
+  /**
+   * Last time this connection had any activity
+   * (reading or writing).
+   */
+  time_t last_activity;
+
+  /**
+   * After how many seconds of inactivity should
+   * this connection time out?  Zero for no timeout.
+   */
+  time_t connection_timeout;
+
+  /**
+   * Socket for this connection.  Set to #MHD_INVALID_SOCKET if
+   * this connection has died (daemon should clean
+   * up in that case).
+   */
+  MHD_socket socket_fd;
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * What is the state of this socket in relation to epoll?
+   */
+  enum MHD_EpollState epoll_state;
+#endif
+
+  /**
+   * Is the connection suspended?
+   */
+  bool suspended;
+
+  /**
+   * Are we ready to read from TLS for this connection?
+   */
+  bool tls_read_ready;
+
+  /**
+   * Is the connection wanting to resume?
+   */
+  bool resuming;
+
+  /**
+   * Set to `true` if the thread has been joined.
+   */
+  bool thread_joined;
+
+  /**
+   * true if #socket_fd is non-blocking, false otherwise.
+   */
+  bool sk_nonblck;
+
+  /**
+   * Has this socket been closed for reading (i.e.  other side closed
+   * the connection)?  If so, we must completely close the connection
+   * once we are done sending our response (and stop trying to read
+   * from this socket).
+   */
+  bool read_closed;
+
+};
+
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * Buffer we use for upgrade response handling in the unlikely
+ * case where the memory pool was so small it had no buffer
+ * capacity left.  Note that we don't expect to _ever_ use this
+ * buffer, so it's mostly wasted memory (except that it allows
+ * us to handle a tricky error condition nicely). So no need to
+ * make this one big.  Applications that want to perform well
+ * should just pick an adequate size for the memory pools.
+ */
+#define RESERVE_EBUF_SIZE 8
+
+/**
+ * Context we pass to epoll() for each of the two sockets
+ * of a `struct MHD_UpgradeResponseHandle`.  We need to do
+ * this so we can distinguish the two sockets when epoll()
+ * gives us event notifications.
+ */
+struct UpgradeEpollHandle
+{
+  /**
+   * Reference to the overall response handle this struct is
+   * included within.
+   */
+  struct MHD_UpgradeResponseHandle *urh;
+
+  /**
+   * The socket this event is kind-of about.  Note that this is NOT
+   * necessarily the socket we are polling on, as for when we read
+   * from TLS, we epoll() on the connection's socket
+   * (`urh->connection->socket_fd`), while this then the application's
+   * socket (where the application will read from).  Nevertheless, for
+   * the application to read, we need to first read from TLS, hence
+   * the two are related.
+   *
+   * Similarly, for writing to TLS, this epoll() will be on the
+   * connection's `socket_fd`, and this will merely be the FD which
+   * the application would write to.  Hence this struct must always be
+   * interpreted based on which field in `struct
+   * MHD_UpgradeResponseHandle` it is (`app` or `mhd`).
+   */
+  MHD_socket socket;
+
+  /**
+   * IO-state of the @e socket (or the connection's `socket_fd`).
+   */
+  enum MHD_EpollState celi;
+
+};
+
+
+/**
+ * Handle given to the application to manage special
+ * actions relating to MHD responses that "upgrade"
+ * the HTTP protocol (i.e. to WebSockets).
+ */
+struct MHD_UpgradeResponseHandle
+{
+  /**
+   * The connection for which this is an upgrade handle.  Note that
+   * because a response may be shared over many connections, this may
+   * not be the only upgrade handle for the response of this connection.
+   */
+  struct MHD_Connection *connection;
+
+#ifdef HTTPS_SUPPORT
+  /**
+   * Kept in a DLL per daemon.
+   */
+  struct MHD_UpgradeResponseHandle *next;
+
+  /**
+   * Kept in a DLL per daemon.
+   */
+  struct MHD_UpgradeResponseHandle *prev;
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * Next pointer for the EDLL listing urhs that are epoll-ready.
+   */
+  struct MHD_UpgradeResponseHandle *nextE;
+
+  /**
+   * Previous pointer for the EDLL listing urhs that are epoll-ready.
+   */
+  struct MHD_UpgradeResponseHandle *prevE;
+
+  /**
+   * Specifies whether urh already in EDLL list of ready connections.
+   */
+  bool in_eready_list;
+#endif
+
+  /**
+   * The buffer for receiving data from TLS to
+   * be passed to the application.  Contains @e in_buffer_size
+   * bytes (unless @e in_buffer_size is zero). Do not free!
+   */
+  char *in_buffer;
+
+  /**
+   * The buffer for receiving data from the application to
+   * be passed to TLS.  Contains @e out_buffer_size
+   * bytes (unless @e out_buffer_size is zero). Do not free!
+   */
+  char *out_buffer;
+
+  /**
+   * Size of the @e in_buffer.
+   * Set to 0 if the TLS connection went down for reading or socketpair
+   * went down for writing.
+   */
+  size_t in_buffer_size;
+
+  /**
+   * Size of the @e out_buffer.
+   * Set to 0 if the TLS connection went down for writing or socketpair
+   * went down for reading.
+   */
+  size_t out_buffer_size;
+
+  /**
+   * Number of bytes actually in use in the @e in_buffer.  Can be larger
+   * than @e in_buffer_size if and only if @a in_buffer_size is zero and
+   * we still have bytes that can be forwarded.
+   * Reset to zero if all data was forwarded to socketpair or
+   * if socketpair went down for writing.
+   */
+  size_t in_buffer_used;
+
+  /**
+   * Number of bytes actually in use in the @e out_buffer. Can be larger
+   * than @e out_buffer_size if and only if @a out_buffer_size is zero and
+   * we still have bytes that can be forwarded.
+   * Reset to zero if all data was forwarded to TLS connection or
+   * if TLS connection went down for writing.
+   */
+  size_t out_buffer_used;
+
+  /**
+   * The socket we gave to the application (r/w).
+   */
+  struct UpgradeEpollHandle app;
+
+  /**
+   * If @a app_sock was a socketpair, our end of it, otherwise
+   * #MHD_INVALID_SOCKET; (r/w).
+   */
+  struct UpgradeEpollHandle mhd;
+
+  /**
+   * Emergency IO buffer we use in case the memory pool has literally
+   * nothing left.
+   */
+  char e_buf[RESERVE_EBUF_SIZE];
+
+#endif /* HTTPS_SUPPORT */
+
+  /**
+   * Set to true after the application finished with the socket
+   * by #MHD_UPGRADE_ACTION_CLOSE.
+   *
+   * When BOTH @e was_closed (changed by command from application)
+   * AND @e clean_ready (changed internally by MHD) are set to
+   * #MHD_YES, function #MHD_resume_connection() will move this
+   * connection to cleanup list.
+   * @remark This flag could be changed from any thread.
+   */
+  volatile bool was_closed;
+
+  /**
+   * Set to true if connection is ready for cleanup.
+   *
+   * In TLS mode functions #MHD_connection_finish_forward_() must
+   * be called before setting this flag to true.
+   *
+   * In thread-per-connection mode, true in this flag means
+   * that connection's thread exited or about to exit and will
+   * not use MHD_Connection::urh data anymore.
+   *
+   * In any mode true in this flag also means that
+   * MHD_Connection::urh data will not be used for socketpair
+   * forwarding and forwarding itself is finished.
+   *
+   * When BOTH @e was_closed (changed by command from application)
+   * AND @e clean_ready (changed internally by MHD) are set to
+   * true, function #MHD_resume_connection() will move this
+   * connection to cleanup list.
+   * @remark This flag could be changed from thread that process
+   * connection's recv(), send() and response.
+   */
+  bool clean_ready;
+};
+#endif /* UPGRADE_SUPPORT */
+
+
+/**
+ * State kept for each MHD daemon.  All connections are kept in two
+ * doubly-linked lists.  The first one reflects the state of the
+ * connection in terms of what operations we are waiting for (read,
+ * write, locally blocked, cleanup) whereas the second is about its
+ * timeout state (default or custom).
+ */
+struct MHD_Daemon
+{
+  /**
+   * Function to call to handle incoming requests.
+   */
+  MHD_RequestCallback rc;
+
+  /**
+   * Closure for @e rc.
+   */
+  void *rc_cls;
+
+  /**
+   * Function to call for logging.
+   */
+  MHD_LoggingCallback logger;
+
+  /**
+   * Closure for @e logger.
+   */
+  void *logger_cls;
+
+  /**
+   * Function to call to accept/reject connections based on
+   * the client's IP address.
+   */
+  MHD_AcceptPolicyCallback accept_policy_cb;
+
+  /**
+   * Closure for @e accept_policy_cb.
+   */
+  void *accept_policy_cb_cls;
+
+  /**
+   * Function to call on the full URL early for logging.
+   */
+  MHD_EarlyUriLogCallback early_uri_logger_cb;
+
+  /**
+   * Closure for @e early_uri_logger_cb.
+   */
+  void *early_uri_logger_cb_cls;
+
+  /**
+   * Function to call whenever a connection is started or
+   * closed.
+   */
+  MHD_NotifyConnectionCallback notify_connection_cb;
+
+  /**
+   * Closure for @e notify_connection_cb.
+   */
+  void *notify_connection_cb_cls;
+
+  /**
+   * Function to call to unescape sequences in URIs and URI arguments.
+   * See #MHD_daemon_unescape_cb().
+   */
+  MHD_UnescapeCallback unescape_cb;
+
+  /**
+   * Closure for @e unescape_cb.
+   */
+  void *unescape_cb_cls;
+
+  /**
+   * Pointer to master daemon (NULL if this is the master)
+   */
+  struct MHD_Daemon *master;
+
+  /**
+   * Worker daemons (one per thread)
+   */
+  struct MHD_Daemon *worker_pool;
+
+
+#if HTTPS_SUPPORT
+#ifdef UPGRADE_SUPPORT
+  /**
+   * Head of DLL of upgrade response handles we are processing.
+   * Used for upgraded TLS connections when thread-per-connection
+   * is not used.
+   */
+  struct MHD_UpgradeResponseHandle *urh_head;
+
+  /**
+   * Tail of DLL of upgrade response handles we are processing.
+   * Used for upgraded TLS connections when thread-per-connection
+   * is not used.
+   */
+  struct MHD_UpgradeResponseHandle *urh_tail;
+#endif /* UPGRADE_SUPPORT */
+
+  /**
+   * Which TLS backend should be used. NULL for no TLS.
+   * This is merely the handle to the dlsym() object, not
+   * the API.
+   */
+  void *tls_backend_lib;
+
+  /**
+   * Callback functions to use for TLS operations.
+   */
+  struct MHD_TLS_Plugin *tls_api;
+#endif
+#if ENABLE_DAUTH
+
+  /**
+   * Random values to be used by digest authentication module.
+   * Size given in @e digest_auth_random_buf_size.
+   */
+  const void *digest_auth_random_buf;
+#endif
+
+  /**
+   * Head of the XDLL of ALL connections with a default ('normal')
+   * timeout, sorted by timeout (earliest at the tail, most recently
+   * used connection at the head).  MHD can just look at the tail of
+   * this list to determine the timeout for all of its elements;
+   * whenever there is an event of a connection, the connection is
+   * moved back to the tail of the list.
+   *
+   * All connections by default start in this list; if a custom
+   * timeout that does not match @e connection_timeout is set, they
+   * are moved to the @e manual_timeout_head-XDLL.
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode as each thread
+   * needs only one connection-specific timeout.
+   */
+  struct MHD_Connection *normal_timeout_head;
+
+  /**
+   * Tail of the XDLL of ALL connections with a default timeout,
+   * sorted by timeout (earliest timeout at the tail).
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
+   */
+  struct MHD_Connection *normal_timeout_tail;
+
+  /**
+   * Head of the XDLL of ALL connections with a non-default/custom
+   * timeout, unsorted.  MHD will do a O(n) scan over this list to
+   * determine the current timeout.
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
+   */
+  struct MHD_Connection *manual_timeout_head;
+
+  /**
+   * Tail of the XDLL of ALL connections with a non-default/custom
+   * timeout, unsorted.
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
+   */
+  struct MHD_Connection *manual_timeout_tail;
+
+  /**
+   * Head of doubly-linked list of our current, active connections.
+   */
+  struct MHD_Connection *connections_head;
+
+  /**
+   * Tail of doubly-linked list of our current, active connections.
+   */
+  struct MHD_Connection *connections_tail;
+
+  /**
+   * Head of doubly-linked list of our current but suspended
+   * connections.
+   */
+  struct MHD_Connection *suspended_connections_head;
+
+  /**
+   * Tail of doubly-linked list of our current but suspended
+   * connections.
+   */
+  struct MHD_Connection *suspended_connections_tail;
+
+  /**
+   * Head of doubly-linked list of connections to clean up.
+   */
+  struct MHD_Connection *cleanup_head;
+
+  /**
+   * Tail of doubly-linked list of connections to clean up.
+   */
+  struct MHD_Connection *cleanup_tail;
+
+  /**
+   * Table storing number of connections per IP
+   */
+  void *per_ip_connection_count;
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * Head of EDLL of connections ready for processing (in epoll mode).
+   */
+  struct MHD_Connection *eready_head;
+
+  /**
+   * Tail of EDLL of connections ready for processing (in epoll mode)
+   */
+  struct MHD_Connection *eready_tail;
+
+  /**
+   * Pointer to marker used to indicate ITC slot in epoll sets.
+   */
+  const char *epoll_itc_marker;
+#ifdef UPGRADE_SUPPORT
+  /**
+   * Head of EDLL of upgraded connections ready for processing (in epoll mode).
+   */
+  struct MHD_UpgradeResponseHandle *eready_urh_head;
+
+  /**
+   * Tail of EDLL of upgraded connections ready for processing (in epoll mode)
+   */
+  struct MHD_UpgradeResponseHandle *eready_urh_tail;
+#endif /* UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
+
+#ifdef DAUTH_SUPPORT
+
+  /**
+   * Character array of random values.
+   */
+  const char *digest_auth_random;
+
+  /**
+   * An array that contains the map nonce-nc.
+   */
+  struct MHD_NonceNc *nnc;
+
+  /**
+   * A rw-lock for synchronizing access to @e nnc.
+   */
+  MHD_mutex_ nnc_lock;
+
+  /**
+   * Size of `digest_auth_random.
+   */
+  size_t digest_auth_rand_size;
+
+  /**
+   * Size of the nonce-nc array.
+   */
+  unsigned int nonce_nc_size;
+
+#endif
+
+  /**
+   * The select thread handle (if we have internal select)
+   */
+  MHD_thread_handle_ID_ pid;
+
+  /**
+   * Socket address to bind to for the listen socket.
+   */
+  struct sockaddr_storage listen_sa;
+
+  /**
+   * Mutex for per-IP connection counts.
+   */
+  MHD_mutex_ per_ip_connection_mutex;
+
+  /**
+   * Mutex for (modifying) access to the "cleanup", "normal_timeout" and
+   * "manual_timeout" DLLs.
+   */
+  MHD_mutex_ cleanup_connection_mutex;
+
+  /**
+   * Number of (valid) bytes in @e listen_sa.  Zero
+   * if @e listen_sa is not initialized.
+   */
+  size_t listen_sa_len;
+
+/**
+ * Default size of the per-connection memory pool.
+ */
+#define POOL_SIZE_DEFAULT (32 * 1024)
+  /**
+   * Buffer size to use for each connection. Default
+   * is #POOL_SIZE_DEFAULT.
+   */
+  size_t connection_memory_limit_b;
+
+/**
+ * Default minimum size by which MHD tries to increment read/write
+ * buffers.  We usually begin with half the available pool space for
+ * the IO-buffer, but if absolutely needed we additively grow by the
+ * number of bytes given here (up to -- theoretically -- the full pool
+ * space).
+ */
+#define BUF_INC_SIZE_DEFAULT 1024
+
+  /**
+   * Increment to use when growing the read buffer. Smaller
+   * than @e connection_memory_limit_b.
+   */
+  size_t connection_memory_increment_b;
+
+  /**
+   * Desired size of the stack for threads created by MHD,
+   * 0 for system default.
+   */
+  size_t thread_stack_limit_b;
+
+#if ENABLE_DAUTH
+
+  /**
+   * Size of @e digest_auth_random_buf.
+   */
+  size_t digest_auth_random_buf_size;
+
+  /**
+   * Default value for @e digest_nc_length.
+   */
+#define DIGEST_NC_LENGTH_DEFAULT 4
+
+  /**
+   * Desired length of the internal array with the nonce and
+   * nonce counters for digest authentication.
+   */
+  size_t digest_nc_length;
+#endif
+
+  /**
+   * Default value we use for the listen backlog.
+   */
+#ifdef SOMAXCONN
+#define LISTEN_BACKLOG_DEFAULT SOMAXCONN
+#else  /* !SOMAXCONN */
+#define LISTEN_BACKLOG_DEFAULT 511
+#endif
+
+  /**
+   * Backlog argument to use for listen.  See
+   * #MHD_daemon_listen_backlog().
+   */
+  int listen_backlog;
+
+  /**
+   * Default queue length to use with fast open.
+   */
+#define FO_QUEUE_LENGTH_DEFAULT 50
+
+  /**
+   * Queue length to use with fast open.
+   */
+  unsigned int fo_queue_length;
+
+  /**
+   * Maximum number of connections MHD accepts. 0 for unlimited.
+   */
+  unsigned int global_connection_limit;
+
+  /**
+   * Maximum number of connections we accept per IP, 0 for unlimited.
+   */
+  unsigned int ip_connection_limit;
+
+  /**
+   * Number of active parallel connections.
+   */
+  unsigned int connections;
+
+  /**
+   * Number of worker daemons
+   */
+  unsigned int worker_pool_size;
+
+  /**
+   * Default timeout in seconds for idle connections.
+   */
+  time_t connection_default_timeout;
+
+  /**
+   * Listen socket we should use, MHD_INVALID_SOCKET means
+   * we are to initialize the socket from the other options given.
+   */
+  MHD_socket listen_socket;
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * File descriptor associated with our epoll loop.
+   */
+  int epoll_fd;
+
+  /**
+   * true if the listen socket is in the 'epoll' set,
+   * false if not.
+   */
+  bool listen_socket_in_epoll;
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  /**
+   * File descriptor associated with the #run_epoll_for_upgrade() loop.
+   * Only available if #MHD_USE_HTTPS_EPOLL_UPGRADE is set.
+   */
+  int epoll_upgrade_fd;
+
+  /**
+   * true if @e epoll_upgrade_fd is in the 'epoll' set,
+   * false if not.
+   */
+  bool upgrade_fd_in_epoll;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+#endif
+
+  /**
+   * Inter-thread communication channel.
+   */
+  struct MHD_itc_ itc;
+
+  /**
+   * Which threading mode do we use? Positive
+   * numbers indicate the number of worker threads to be used.
+   * Values larger than 1 imply a thread pool.
+   */
+  enum MHD_ThreadingMode threading_mode;
+
+  /**
+   * When should we use TCP_FASTOPEN?
+   * See #MHD_daemon_tcp_fastopen().
+   */
+  enum MHD_FastOpenMethod fast_open_method;
+
+  /**
+   * Address family to use when listening.
+   * Default is #MHD_AF_NONE (do not listen).
+   */
+  enum MHD_AddressFamily listen_af;
+
+  /**
+   * Sets active/desired style of the event loop.
+   * (Auto only possible during initialization, later set to
+   * the actual style we use.)
+   */
+  enum MHD_EventLoopSyscall event_loop_syscall;
+
+  /**
+   * How strictly do we enforce the HTTP protocol?
+   * See #MHD_daemon_protocol_strict_level().
+   */
+  enum MHD_ProtocolStrictLevel protocol_strict_level;
+
+  /**
+   * On which port should we listen on? Only effective if we were not
+   * given a listen socket or a full address via
+   * #MHD_daemon_bind_sa().  0 means to bind to random free port.
+   */
+  uint16_t listen_port;
+
+  /**
+   * Suppress generating the "Date:" header, this system
+   * lacks an RTC (or developer is hyper-optimizing).  See
+   * #MHD_daemon_suppress_date_no_clock().
+   */
+  bool suppress_date;
+
+  /**
+   * The use of the inter-thread communication channel is disabled.
+   * See #MHD_daemon_disable_itc().
+   */
+  bool disable_itc;
+
+  /**
+   * Disable #MHD_action_suspend() functionality.  See
+   * #MHD_daemon_disallow_suspend_resume().
+   */
+  bool disallow_suspend_resume;
+
+  /**
+   * Disable #MHD_action_upgrade() functionality.  See
+   * #MHD_daemon_disallow_upgrade().
+   */
+  bool disallow_upgrade;
+
+  /**
+   * Did we hit some system or process-wide resource limit while
+   * trying to accept() the last time? If so, we don't accept new
+   * connections until we close an existing one.  This effectively
+   * temporarily lowers the "connection_limit" to the current
+   * number of connections.
+   */
+  bool at_limit;
+
+  /**
+   * Disables optional calls to `shutdown()` and enables aggressive
+   * non-blocking optimistic reads and other potentially unsafe
+   * optimizations.  See #MHD_daemon_enable_turbo().
+   */
+  bool enable_turbo;
+
+  /**
+   * 'True' if some data is already waiting to be processed.  If set
+   * to 'true' - zero timeout for select()/poll*() is used.  Should be
+   * reset each time before processing connections and raised by any
+   * connection which require additional immediately processing
+   * (application does not provide data for response, data waiting in
+   * TLS buffers etc.)
+   */
+  bool data_already_pending;
+
+  /**
+   * MHD_daemon_quiesce() was run against this daemon.
+   */
+  bool was_quiesced;
+
+  /**
+   * Is some connection wanting to resume?
+   */
+  bool resuming;
+
+  /**
+   * Allow reusing the address:port combination when binding.
+   * See #MHD_daemon_listen_allow_address_reuse().
+   */
+  bool allow_address_reuse;
+
+  /**
+   * MHD should speak SHOUTcast instead of HTTP.
+   */
+  bool enable_shoutcast;
+
+  /**
+   * Are we shutting down?
+   */
+  volatile bool shutdown;
+
+};
+
+
+/**
+ * Action function implementing some action to be
+ * performed on a request.
+ *
+ * @param cls action-specfic closure
+ * @param request the request on which the action is to be performed
+ * @return #MHD_SC_OK on success, otherwise an error code
+ */
+typedef enum MHD_StatusCode
+(*ActionCallback)(void *cls,
+                  struct MHD_Request *request);
+
+
+/**
+ * Actions are returned by the application to drive the request
+ * handling of MHD.
+ */
+struct MHD_Action
+{
+
+  /**
+   * Function to call for the action.
+   */
+  ActionCallback action;
+
+  /**
+   * Closure for @a action
+   */
+  void *action_cls;
+
+};
+
+
+/**
+ * Representation of an HTTP response.
+ */
+struct MHD_Response
+{
+
+  /**
+   * A response *is* an action. See also
+   * #MHD_action_from_response().   Hence this field
+   * must be the first field in a response!
+   */
+  struct MHD_Action action;
+
+  /**
+   * Headers to send for the response.  Initially
+   * the linked list is created in inverse order;
+   * the order should be inverted before sending!
+   */
+  struct MHD_HTTP_Header *first_header;
+
+  /**
+   * Buffer pointing to data that we are supposed
+   * to send as a response.
+   */
+  char *data;
+
+  /**
+   * Closure to give to the content reader @e crc
+   * and content reader free callback @e crfc.
+   */
+  void *crc_cls;
+
+  /**
+   * How do we get more data?  NULL if we are
+   * given all of the data up front.
+   */
+  MHD_ContentReaderCallback crc;
+
+  /**
+   * NULL if data must not be freed, otherwise
+   * either user-specified callback or "&free".
+   */
+  MHD_ContentReaderFreeCallback crfc;
+
+  /**
+   * Function to call once MHD is finished with
+   * the request, may be NULL.
+   */
+  MHD_RequestTerminationCallback termination_cb;
+
+  /**
+   * Closure for @e termination_cb.
+   */
+  void *termination_cb_cls;
+
+#ifdef UPGRADE_SUPPORT
+  /**
+   * Application function to call once we are done sending the headers
+   * of the response; NULL unless this is a response created with
+   * #MHD_create_response_for_upgrade().
+   */
+  MHD_UpgradeHandler upgrade_handler;
+
+  /**
+   * Closure for @e uh.
+   */
+  void *upgrade_handler_cls;
+#endif /* UPGRADE_SUPPORT */
+
+  /**
+   * Mutex to synchronize access to @e data, @e size and
+   * @e reference_count.
+   */
+  MHD_mutex_ mutex;
+
+  /**
+   * Set to #MHD_SIZE_UNKNOWN if size is not known.
+   */
+  uint64_t total_size;
+
+  /**
+   * At what offset in the stream is the
+   * beginning of @e data located?
+   */
+  uint64_t data_start;
+
+  /**
+   * Offset to start reading from when using @e fd.
+   */
+  uint64_t fd_off;
+
+  /**
+   * Number of bytes ready in @e data (buffer may be larger
+   * than what is filled with payload).
+   */
+  size_t data_size;
+
+  /**
+   * Size of the data buffer @e data.
+   */
+  size_t data_buffer_size;
+
+  /**
+   * HTTP status code of the response.
+   */
+  enum MHD_HTTP_StatusCode status_code;
+
+  /**
+   * Reference count for this response.  Free once the counter hits
+   * zero.
+   */
+  unsigned int reference_count;
+
+  /**
+   * File-descriptor if this response is FD-backed.
+   */
+  int fd;
+
+  /**
+   * Only respond in HTTP 1.0 mode.
+   */
+  bool v10_only;
+
+  /**
+   * Use ShoutCAST format.
+   */
+  bool icy;
+
+};
+
+
+/**
+ * Callback invoked when iterating over @a key / @a value
+ * argument pairs during parsing.
+ *
+ * @param request context of the iteration
+ * @param key 0-terminated key string, never NULL
+ * @param value 0-terminated value string, may be NULL
+ * @param kind origin of the key-value pair
+ * @return true on success (continue to iterate)
+ *         false to signal failure (and abort iteration)
+ */
+typedef bool
+(*MHD_ArgumentIterator_)(struct MHD_Request *request,
+                         const char *key,
+                         const char *value,
+                         enum MHD_ValueKind kind);
+
+
+/**
+ * Parse and unescape the arguments given by the client
+ * as part of the HTTP request URI.
+ *
+ * @param request request to add headers to
+ * @param kind header kind to pass to @a cb
+ * @param[in,out] args argument URI string (after "?" in URI),
+ *        clobbered in the process!
+ * @param cb function to call on each key-value pair found
+ * @param[out] num_headers set to the number of headers found
+ * @return false on failure (@a cb returned false),
+ *         true for success (parsing succeeded, @a cb always
+ *                               returned true)
+ */
+bool
+MHD_parse_arguments_ (struct MHD_Request *request,
+                      enum MHD_ValueKind kind,
+                      char *args,
+                      MHD_ArgumentIterator_ cb,
+                      unsigned int *num_headers);
+
+
+/**
+ * Insert an element at the head of a DLL. Assumes that head, tail and
+ * element are structs with prev and next fields.
+ *
+ * @param head pointer to the head of the DLL
+ * @param tail pointer to the tail of the DLL
+ * @param element element to insert
+ */
+#define DLL_insert(head,tail,element) do { \
+    mhd_assert (NULL == (element)->next); \
+    mhd_assert (NULL == (element)->prev); \
+    (element)->next = (head); \
+    (element)->prev = NULL; \
+    if ((tail) == NULL) \
+      (tail) = element; \
+    else \
+      (head)->prev = element; \
+    (head) = (element); } while (0)
+
+
+/**
+ * Remove an element from a DLL. Assumes that head, tail and element
+ * are structs with prev and next fields.
+ *
+ * @param head pointer to the head of the DLL
+ * @param tail pointer to the tail of the DLL
+ * @param element element to remove
+ */
+#define DLL_remove(head,tail,element) do { \
+    mhd_assert ( (NULL != (element)->next) || ((element) == (tail)));  \
+    mhd_assert ( (NULL != (element)->prev) || ((element) == (head)));  \
+    if ((element)->prev == NULL) \
+      (head) = (element)->next;  \
+    else \
+      (element)->prev->next = (element)->next; \
+    if ((element)->next == NULL) \
+      (tail) = (element)->prev;  \
+    else \
+      (element)->next->prev = (element)->prev; \
+    (element)->next = NULL; \
+    (element)->prev = NULL; } while (0)
+
+
+/**
+ * Insert an element at the head of a XDLL. Assumes that head, tail and
+ * element are structs with prevX and nextX fields.
+ *
+ * @param head pointer to the head of the XDLL
+ * @param tail pointer to the tail of the XDLL
+ * @param element element to insert
+ */
+#define XDLL_insert(head,tail,element) do { \
+    mhd_assert (NULL == (element)->nextX); \
+    mhd_assert (NULL == (element)->prevX); \
+    (element)->nextX = (head); \
+    (element)->prevX = NULL; \
+    if (NULL == (tail)) \
+      (tail) = element; \
+    else \
+      (head)->prevX = element; \
+    (head) = (element); } while (0)
+
+
+/**
+ * Remove an element from a XDLL. Assumes that head, tail and element
+ * are structs with prevX and nextX fields.
+ *
+ * @param head pointer to the head of the XDLL
+ * @param tail pointer to the tail of the XDLL
+ * @param element element to remove
+ */
+#define XDLL_remove(head,tail,element) do { \
+    mhd_assert ( (NULL != (element)->nextX) || ((element) == (tail)));  \
+    mhd_assert ( (NULL != (element)->prevX) || ((element) == (head)));  \
+    if (NULL == (element)->prevX) \
+      (head) = (element)->nextX;  \
+    else \
+      (element)->prevX->nextX = (element)->nextX; \
+    if (NULL == (element)->nextX) \
+      (tail) = (element)->prevX;  \
+    else \
+      (element)->nextX->prevX = (element)->prevX; \
+    (element)->nextX = NULL; \
+    (element)->prevX = NULL; } while (0)
+
+
+/**
+ * Insert an element at the head of a EDLL. Assumes that head, tail and
+ * element are structs with prevE and nextE fields.
+ *
+ * @param head pointer to the head of the EDLL
+ * @param tail pointer to the tail of the EDLL
+ * @param element element to insert
+ */
+#define EDLL_insert(head,tail,element) do { \
+    (element)->nextE = (head); \
+    (element)->prevE = NULL; \
+    if ((tail) == NULL) \
+      (tail) = element; \
+    else \
+      (head)->prevE = element; \
+    (head) = (element); } while (0)
+
+
+/**
+ * Remove an element from a EDLL. Assumes that head, tail and element
+ * are structs with prevE and nextE fields.
+ *
+ * @param head pointer to the head of the EDLL
+ * @param tail pointer to the tail of the EDLL
+ * @param element element to remove
+ */
+#define EDLL_remove(head,tail,element) do { \
+    if ((element)->prevE == NULL) \
+      (head) = (element)->nextE;  \
+    else \
+      (element)->prevE->nextE = (element)->nextE; \
+    if ((element)->nextE == NULL) \
+      (tail) = (element)->prevE;  \
+    else \
+      (element)->nextE->prevE = (element)->prevE; \
+    (element)->nextE = NULL; \
+    (element)->prevE = NULL; } while (0)
+
+
+/**
+ * Error code similar to EGAIN or EINTR
+ */
+#define MHD_ERR_AGAIN_ (-3073)
+
+/**
+ * Connection was hard-closed by remote peer.
+ */
+#define MHD_ERR_CONNRESET_ (-3074)
+
+/**
+ * Connection is not connected anymore due to
+ * network error or any other reason.
+ */
+#define MHD_ERR_NOTCONN_ (-3075)
+
+/**
+ * "Not enough memory" error code
+ */
+#define MHD_ERR_NOMEM_ (-3076)
+
+/**
+ * "Bad FD" error code
+ */
+#define MHD_ERR_BADF_ (-3077)
+
+/**
+ * Error code similar to EINVAL
+ */
+#define MHD_ERR_INVAL_ (-3078)
+
+
+#endif
diff --git a/src/lib/md5.c b/src/lib/md5.c
new file mode 100644
index 0000000..08f5c1d
--- /dev/null
+++ b/src/lib/md5.c
@@ -0,0 +1,268 @@
+/*
+ * This code implements the MD5 message-digest algorithm.
+ * The algorithm is due to Ron Rivest.	This code was
+ * written by Colin Plumb in 1993, no copyright is claimed.
+ * This code is in the public domain; do with it what you wish.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is equivalent,
+ * except that you don't need to include two pages of legalese
+ * with every copy.
+ *
+ * To compute the message digest of a chunk of bytes, declare an
+ * MD5Context structure, pass it to MHD_MD5Init, call MHD_MD5Update as
+ * needed on buffers full of bytes, and then call MHD_MD5Final, which
+ * will fill a supplied 16-byte array with the digest.
+ */
+
+/* Based on OpenBSD modifications */
+
+#include "md5.h"
+#include "mhd_byteorder.h"
+
+#define PUT_64BIT_LE(cp, value) do {          \
+    (cp)[7] = (uint8_t) ((value) >> 56);       \
+    (cp)[6] = (uint8_t) ((value) >> 48);       \
+    (cp)[5] = (uint8_t) ((value) >> 40);       \
+    (cp)[4] = (uint8_t) ((value) >> 32);       \
+    (cp)[3] = (uint8_t) ((value) >> 24);       \
+    (cp)[2] = (uint8_t) ((value) >> 16);       \
+    (cp)[1] = (uint8_t) ((value) >> 8);        \
+    (cp)[0] = (uint8_t) ((value)); } while (0)
+
+#define PUT_32BIT_LE(cp, value) do {          \
+    (cp)[3] = (uint8_t) ((value) >> 24);       \
+    (cp)[2] = (uint8_t) ((value) >> 16);       \
+    (cp)[1] = (uint8_t) ((value) >> 8);        \
+    (cp)[0] = (uint8_t) ((value)); } while (0)
+
+static uint8_t PADDING[MD5_BLOCK_SIZE] = {
+  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/*
+ * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+void
+MHD_MD5Init (struct MD5Context *ctx)
+{
+  if (! ctx)
+    return;
+
+  ctx->count = 0;
+  ctx->state[0] = 0x67452301;
+  ctx->state[1] = 0xefcdab89;
+  ctx->state[2] = 0x98badcfe;
+  ctx->state[3] = 0x10325476;
+}
+
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+void
+MHD_MD5Update (struct MD5Context *ctx, const unsigned char *input, size_t len)
+{
+  size_t have, need;
+
+  if (! ctx || ! input)
+    return;
+
+  /* Check how many bytes we already have and how many more we need. */
+  have = (size_t) ((ctx->count >> 3) & (MD5_BLOCK_SIZE - 1));
+  need = MD5_BLOCK_SIZE - have;
+
+  /* Update bitcount */
+  ctx->count += (uint64_t) len << 3;
+
+  if (len >= need)
+  {
+    if (have != 0)
+    {
+      memcpy (ctx->buffer + have, input, need);
+      MD5Transform (ctx->state, ctx->buffer);
+      input += need;
+      len -= need;
+      have = 0;
+    }
+
+    /* Process data in MD5_BLOCK_SIZE-byte chunks. */
+    while (len >= MD5_BLOCK_SIZE)
+    {
+      MD5Transform (ctx->state, input);
+      input += MD5_BLOCK_SIZE;
+      len -= MD5_BLOCK_SIZE;
+    }
+  }
+
+  /* Handle any remaining bytes of data. */
+  if (len != 0)
+    memcpy (ctx->buffer + have, input, len);
+}
+
+
+/*
+ * Pad pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+void
+MD5Pad (struct MD5Context *ctx)
+{
+  uint8_t count[8];
+  size_t padlen;
+
+  if (! ctx)
+    return;
+
+  /* Convert count to 8 bytes in little endian order. */
+  PUT_64BIT_LE (count, ctx->count);
+
+  /* Pad out to 56 mod 64. */
+  padlen = MD5_BLOCK_SIZE
+           - ((ctx->count >> 3) & (MD5_BLOCK_SIZE - 1));
+  if (padlen < 1 + 8)
+    padlen += MD5_BLOCK_SIZE;
+  MHD_MD5Update (ctx, PADDING, padlen - 8);    /* padlen - 8 <= 64 */
+  MHD_MD5Update (ctx, count, 8);
+}
+
+
+/*
+ * Final wrapup--call MD5Pad, fill in digest and zero out ctx.
+ */
+void
+MHD_MD5Final (unsigned char digest[MD5_DIGEST_SIZE], struct MD5Context *ctx)
+{
+  int i;
+
+  if (! ctx || ! digest)
+    return;
+
+  MD5Pad (ctx);
+  for (i = 0; i < 4; i++)
+    PUT_32BIT_LE (digest + i * 4, ctx->state[i]);
+
+  memset (ctx, 0, sizeof(*ctx));
+}
+
+
+/* The four core functions - F1 is optimized somewhat */
+
+/* #define F1(x, y, z) (x & y | ~x & z) */
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1 (z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+/* This is the central step in the MD5 algorithm. */
+#define MD5STEP(f, w, x, y, z, data, s) \
+  (w += f (x, y, z) + data,  w = w << s | w >> (32 - s),  w += x)
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data.  MHD_MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+void
+MD5Transform (uint32_t state[4], const uint8_t block[MD5_BLOCK_SIZE])
+{
+  uint32_t a, b, c, d, in[MD5_BLOCK_SIZE / 4];
+
+#if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+  memcpy (in, block, sizeof(in));
+#else
+  for (a = 0; a < MD5_BLOCK_SIZE / 4; a++)
+  {
+    in[a] = (uint32_t) (
+      (uint32_t) (block[a * 4 + 0])
+      | (uint32_t) (block[a * 4 + 1]) << 8
+        | (uint32_t) (block[a * 4 + 2]) << 16
+        | (uint32_t) (block[a * 4 + 3]) << 24);
+  }
+#endif
+
+  a = state[0];
+  b = state[1];
+  c = state[2];
+  d = state[3];
+
+  MD5STEP (F1, a, b, c, d, in[0]  + 0xd76aa478, 7);
+  MD5STEP (F1, d, a, b, c, in[1]  + 0xe8c7b756, 12);
+  MD5STEP (F1, c, d, a, b, in[2]  + 0x242070db, 17);
+  MD5STEP (F1, b, c, d, a, in[3]  + 0xc1bdceee, 22);
+  MD5STEP (F1, a, b, c, d, in[4]  + 0xf57c0faf, 7);
+  MD5STEP (F1, d, a, b, c, in[5]  + 0x4787c62a, 12);
+  MD5STEP (F1, c, d, a, b, in[6]  + 0xa8304613, 17);
+  MD5STEP (F1, b, c, d, a, in[7]  + 0xfd469501, 22);
+  MD5STEP (F1, a, b, c, d, in[8]  + 0x698098d8, 7);
+  MD5STEP (F1, d, a, b, c, in[9]  + 0x8b44f7af, 12);
+  MD5STEP (F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+  MD5STEP (F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+  MD5STEP (F1, a, b, c, d, in[12] + 0x6b901122, 7);
+  MD5STEP (F1, d, a, b, c, in[13] + 0xfd987193, 12);
+  MD5STEP (F1, c, d, a, b, in[14] + 0xa679438e, 17);
+  MD5STEP (F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+  MD5STEP (F2, a, b, c, d, in[1]  + 0xf61e2562, 5);
+  MD5STEP (F2, d, a, b, c, in[6]  + 0xc040b340, 9);
+  MD5STEP (F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+  MD5STEP (F2, b, c, d, a, in[0]  + 0xe9b6c7aa, 20);
+  MD5STEP (F2, a, b, c, d, in[5]  + 0xd62f105d, 5);
+  MD5STEP (F2, d, a, b, c, in[10] + 0x02441453, 9);
+  MD5STEP (F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+  MD5STEP (F2, b, c, d, a, in[4]  + 0xe7d3fbc8, 20);
+  MD5STEP (F2, a, b, c, d, in[9]  + 0x21e1cde6, 5);
+  MD5STEP (F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+  MD5STEP (F2, c, d, a, b, in[3]  + 0xf4d50d87, 14);
+  MD5STEP (F2, b, c, d, a, in[8]  + 0x455a14ed, 20);
+  MD5STEP (F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+  MD5STEP (F2, d, a, b, c, in[2]  + 0xfcefa3f8, 9);
+  MD5STEP (F2, c, d, a, b, in[7]  + 0x676f02d9, 14);
+  MD5STEP (F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+  MD5STEP (F3, a, b, c, d, in[5]  + 0xfffa3942, 4);
+  MD5STEP (F3, d, a, b, c, in[8]  + 0x8771f681, 11);
+  MD5STEP (F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+  MD5STEP (F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+  MD5STEP (F3, a, b, c, d, in[1]  + 0xa4beea44, 4);
+  MD5STEP (F3, d, a, b, c, in[4]  + 0x4bdecfa9, 11);
+  MD5STEP (F3, c, d, a, b, in[7]  + 0xf6bb4b60, 16);
+  MD5STEP (F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+  MD5STEP (F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+  MD5STEP (F3, d, a, b, c, in[0]  + 0xeaa127fa, 11);
+  MD5STEP (F3, c, d, a, b, in[3]  + 0xd4ef3085, 16);
+  MD5STEP (F3, b, c, d, a, in[6]  + 0x04881d05, 23);
+  MD5STEP (F3, a, b, c, d, in[9]  + 0xd9d4d039, 4);
+  MD5STEP (F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+  MD5STEP (F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+  MD5STEP (F3, b, c, d, a, in[2]  + 0xc4ac5665, 23);
+
+  MD5STEP (F4, a, b, c, d, in[0]  + 0xf4292244, 6);
+  MD5STEP (F4, d, a, b, c, in[7]  + 0x432aff97, 10);
+  MD5STEP (F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+  MD5STEP (F4, b, c, d, a, in[5]  + 0xfc93a039, 21);
+  MD5STEP (F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+  MD5STEP (F4, d, a, b, c, in[3]  + 0x8f0ccc92, 10);
+  MD5STEP (F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+  MD5STEP (F4, b, c, d, a, in[1]  + 0x85845dd1, 21);
+  MD5STEP (F4, a, b, c, d, in[8]  + 0x6fa87e4f, 6);
+  MD5STEP (F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+  MD5STEP (F4, c, d, a, b, in[6]  + 0xa3014314, 15);
+  MD5STEP (F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+  MD5STEP (F4, a, b, c, d, in[4]  + 0xf7537e82, 6);
+  MD5STEP (F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+  MD5STEP (F4, c, d, a, b, in[2]  + 0x2ad7d2bb, 15);
+  MD5STEP (F4, b, c, d, a, in[9]  + 0xeb86d391, 21);
+
+  state[0] += a;
+  state[1] += b;
+  state[2] += c;
+  state[3] += d;
+}
+
+
+/* end of md5.c */
diff --git a/src/lib/md5.h b/src/lib/md5.h
new file mode 100644
index 0000000..8005b70
--- /dev/null
+++ b/src/lib/md5.h
@@ -0,0 +1,66 @@
+/*
+ * This code implements the MD5 message-digest algorithm.
+ * The algorithm is due to Ron Rivest.	This code was
+ * written by Colin Plumb in 1993, no copyright is claimed.
+ * This code is in the public domain; do with it what you wish.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is equivalent,
+ * except that you don't need to include two pages of legalese
+ * with every copy.
+ *
+ * To compute the message digest of a chunk of bytes, declare an
+ * MD5Context structure, pass it to MHD_MD5Init, call MHD_MD5Update as
+ * needed on buffers full of bytes, and then call MHD_MD5Final, which
+ * will fill a supplied 16-byte array with the digest.
+ */
+
+#ifndef MHD_MD5_H
+#define MHD_MD5_H
+
+#include "platform.h"
+
+#define MD5_BLOCK_SIZE              64
+#define MD5_DIGEST_SIZE             16
+#define MD5_DIGEST_STRING_LENGTH    (MD5_DIGEST_SIZE * 2 + 1)
+
+struct MD5Context
+{
+  uint32_t state[4];  /* state */
+  uint64_t count;     /* number of bits, mod 2^64 */
+  uint8_t buffer[MD5_BLOCK_SIZE]; /* input buffer */
+};
+
+/*
+ * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+void MHD_MD5Init (struct MD5Context *ctx);
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+void MHD_MD5Update (struct MD5Context *ctx, const unsigned char *input, size_t
+                    len);
+
+/*
+ * Pad pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+void MD5Pad (struct MD5Context *ctx);
+
+/*
+ * Final wrapup--call MD5Pad, fill in digest and zero out ctx.
+ */
+void MHD_MD5Final (unsigned char digest[MD5_DIGEST_SIZE], struct
+                   MD5Context *ctx);
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data.  MHD_MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+void MD5Transform (uint32_t state[4], const uint8_t block[MD5_BLOCK_SIZE]);
+
+#endif /* !MHD_MD5_H */
diff --git a/src/lib/memorypool.c b/src/lib/memorypool.c
new file mode 100644
index 0000000..9f7472e
--- /dev/null
+++ b/src/lib/memorypool.c
@@ -0,0 +1,340 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2009, 2010, 2018 Christian Grothoff
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file memorypool.c
+ * @brief memory pool
+ * @author Christian Grothoff
+ */
+#include "memorypool.h"
+
+/* define MAP_ANONYMOUS for Mac OS X */
+#if defined(MAP_ANON) && ! defined(MAP_ANONYMOUS)
+#define MAP_ANONYMOUS MAP_ANON
+#endif
+#ifndef MAP_FAILED
+#define MAP_FAILED ((void*) -1)
+#endif
+
+/**
+ * Align to 2x word size (as GNU libc does).
+ */
+#define ALIGN_SIZE (2 * sizeof(void*))
+
+/**
+ * Round up 'n' to a multiple of ALIGN_SIZE.
+ */
+#define ROUND_TO_ALIGN(n) ((n + (ALIGN_SIZE - 1)) & (~(ALIGN_SIZE - 1)))
+
+
+/**
+ * Handle for a memory pool.  Pools are not reentrant and must not be
+ * used by multiple threads.
+ */
+struct MemoryPool
+{
+
+  /**
+   * Pointer to the pool's memory
+   */
+  char *memory;
+
+  /**
+   * Size of the pool.
+   */
+  size_t size;
+
+  /**
+   * Offset of the first unallocated byte.
+   */
+  size_t pos;
+
+  /**
+   * Offset of the last unallocated byte.
+   */
+  size_t end;
+
+  /**
+   * false if pool was malloc'ed, true if mmapped (VirtualAlloc'ed for W32).
+   */
+  bool is_mmap;
+};
+
+
+/**
+ * Free the memory given by @a ptr. Calls "free(ptr)".  This function
+ * should be used to free the username returned by
+ * #MHD_digest_auth_get_username().
+ * @note Since v0.9.56
+ *
+ * @param ptr pointer to free.
+ */
+_MHD_EXTERN void
+MHD_free (void *ptr)
+{
+  free (ptr);
+}
+
+
+/**
+ * Create a memory pool.
+ *
+ * @param max maximum size of the pool
+ * @return NULL on error
+ */
+struct MemoryPool *
+MHD_pool_create (size_t max)
+{
+  struct MemoryPool *pool;
+
+  pool = malloc (sizeof (struct MemoryPool));
+  if (NULL == pool)
+    return NULL;
+#if defined(MAP_ANONYMOUS) || defined(_WIN32)
+  if (max <= 32 * 1024)
+    pool->memory = MAP_FAILED;
+  else
+#if defined(MAP_ANONYMOUS) && ! defined(_WIN32)
+    pool->memory = mmap (NULL,
+                         max,
+                         PROT_READ | PROT_WRITE,
+                         MAP_PRIVATE | MAP_ANONYMOUS,
+                         -1,
+                         0);
+#elif defined(_WIN32)
+    pool->memory = VirtualAlloc (NULL,
+                                 max,
+                                 MEM_COMMIT | MEM_RESERVE,
+                                 PAGE_READWRITE);
+#endif
+#else
+  pool->memory = MAP_FAILED;
+#endif
+  if ( (MAP_FAILED == pool->memory) ||
+       (NULL == pool->memory))
+  {
+    pool->memory = malloc (max);
+    if (NULL == pool->memory)
+    {
+      free (pool);
+      return NULL;
+    }
+    pool->is_mmap = false;
+  }
+  else
+  {
+    pool->is_mmap = true;
+  }
+  pool->pos = 0;
+  pool->end = max;
+  pool->size = max;
+  return pool;
+}
+
+
+/**
+ * Destroy a memory pool.
+ *
+ * @param pool memory pool to destroy
+ */
+void
+MHD_pool_destroy (struct MemoryPool *pool)
+{
+  if (NULL == pool)
+    return;
+  if (! pool->is_mmap)
+    free (pool->memory);
+  else
+#if defined(MAP_ANONYMOUS) && ! defined(_WIN32)
+    munmap (pool->memory,
+            pool->size);
+#elif defined(_WIN32)
+    VirtualFree (pool->memory,
+                 0,
+                 MEM_RELEASE);
+#else
+    abort ();
+#endif
+  free (pool);
+}
+
+
+/**
+ * Check how much memory is left in the @a pool
+ *
+ * @param pool pool to check
+ * @return number of bytes still available in @a pool
+ */
+size_t
+MHD_pool_get_free (struct MemoryPool *pool)
+{
+  return (pool->end - pool->pos);
+}
+
+
+/**
+ * Allocate size bytes from the pool.
+ *
+ * @param pool memory pool to use for the operation
+ * @param size number of bytes to allocate
+ * @param from_end allocate from end of pool (set to #MHD_YES);
+ *        use this for small, persistent allocations that
+ *        will never be reallocated
+ * @return NULL if the pool cannot support size more
+ *         bytes
+ */
+void *
+MHD_pool_allocate (struct MemoryPool *pool,
+                   size_t size,
+                   int from_end)
+{
+  void *ret;
+  size_t asize;
+
+  asize = ROUND_TO_ALIGN (size);
+  if ( (0 == asize) && (0 != size) )
+    return NULL; /* size too close to SIZE_MAX */
+  if ( (pool->pos + asize > pool->end) ||
+       (pool->pos + asize < pool->pos))
+    return NULL;
+  if (from_end == MHD_YES)
+  {
+    ret = &pool->memory[pool->end - asize];
+    pool->end -= asize;
+  }
+  else
+  {
+    ret = &pool->memory[pool->pos];
+    pool->pos += asize;
+  }
+  return ret;
+}
+
+
+/**
+ * Reallocate a block of memory obtained from the pool.
+ * This is particularly efficient when growing or
+ * shrinking the block that was last (re)allocated.
+ * If the given block is not the most recently
+ * (re)allocated block, the memory of the previous
+ * allocation may be leaked until the pool is
+ * destroyed (and copying the data maybe required).
+ *
+ * @param pool memory pool to use for the operation
+ * @param old the existing block
+ * @param old_size the size of the existing block
+ * @param new_size the new size of the block
+ * @return new address of the block, or
+ *         NULL if the pool cannot support @a new_size
+ *         bytes (old continues to be valid for @a old_size)
+ */
+void *
+MHD_pool_reallocate (struct MemoryPool *pool,
+                     void *old,
+                     size_t old_size,
+                     size_t new_size)
+{
+  void *ret;
+  size_t asize;
+
+  asize = ROUND_TO_ALIGN (new_size);
+  if ( (0 == asize) &&
+       (0 != new_size) )
+    return NULL; /* new_size too close to SIZE_MAX */
+  if ( (pool->end < old_size) ||
+       (pool->end < asize) )
+    return NULL;                /* unsatisfiable or bogus request */
+
+  if ( (pool->pos >= old_size) &&
+       (&pool->memory[pool->pos - old_size] == old) )
+  {
+    /* was the previous allocation - optimize! */
+    if (pool->pos + asize - old_size <= pool->end)
+    {
+      /* fits */
+      pool->pos += asize - old_size;
+      if (asize < old_size)          /* shrinking - zero again! */
+        memset (&pool->memory[pool->pos],
+                0,
+                old_size - asize);
+      return old;
+    }
+    /* does not fit */
+    return NULL;
+  }
+  if (asize <= old_size)
+    return old;                 /* cannot shrink, no need to move */
+  if ((pool->pos + asize >= pool->pos) &&
+      (pool->pos + asize <= pool->end))
+  {
+    /* fits */
+    ret = &pool->memory[pool->pos];
+    if (0 != old_size)
+      memmove (ret,
+               old,
+               old_size);
+    pool->pos += asize;
+    return ret;
+  }
+  /* does not fit */
+  return NULL;
+}
+
+
+/**
+ * Clear all entries from the memory pool except
+ * for @a keep of the given @a size. The pointer
+ * returned should be a buffer of @a new_size where
+ * the first @a copy_bytes are from @a keep.
+ *
+ * @param pool memory pool to use for the operation
+ * @param keep pointer to the entry to keep (maybe NULL)
+ * @param copy_bytes how many bytes need to be kept at this address
+ * @param new_size how many bytes should the allocation we return have?
+ *                 (should be larger or equal to @a copy_bytes)
+ * @return addr new address of @a keep (if it had to change)
+ */
+void *
+MHD_pool_reset (struct MemoryPool *pool,
+                void *keep,
+                size_t copy_bytes,
+                size_t new_size)
+{
+  if ( (NULL != keep) &&
+       (keep != pool->memory) )
+  {
+    if (0 != copy_bytes)
+      memmove (pool->memory,
+               keep,
+               copy_bytes);
+    keep = pool->memory;
+  }
+  pool->end = pool->size;
+  /* technically not needed, but safer to zero out */
+  if (pool->size > copy_bytes)
+    memset (&pool->memory[copy_bytes],
+            0,
+            pool->size - copy_bytes);
+  if (NULL != keep)
+    pool->pos = ROUND_TO_ALIGN (new_size);
+  return keep;
+}
+
+
+/* end of memorypool.c */
diff --git a/src/lib/memorypool.h b/src/lib/memorypool.h
new file mode 100644
index 0000000..774b05b
--- /dev/null
+++ b/src/lib/memorypool.h
@@ -0,0 +1,130 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2009 Daniel Pittman and Christian Grothoff
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file memorypool.h
+ * @brief memory pool; mostly used for efficient (de)allocation
+ *        for each connection and bounding memory use for each
+ *        request
+ * @author Christian Grothoff
+ */
+
+#ifndef MEMORYPOOL_H
+#define MEMORYPOOL_H
+
+#include "internal.h"
+
+/**
+ * Opaque handle for a memory pool.
+ * Pools are not reentrant and must not be used
+ * by multiple threads.
+ */
+struct MemoryPool;
+
+
+/**
+ * Create a memory pool.
+ *
+ * @param max maximum size of the pool
+ * @return NULL on error
+ */
+struct MemoryPool *
+MHD_pool_create (size_t max);
+
+
+/**
+ * Destroy a memory pool.
+ *
+ * @param pool memory pool to destroy
+ */
+void
+MHD_pool_destroy (struct MemoryPool *pool);
+
+
+/**
+ * Allocate size bytes from the pool.
+ *
+ * @param pool memory pool to use for the operation
+ * @param size number of bytes to allocate
+ * @param from_end allocate from end of pool (set to #MHD_YES);
+ *        use this for small, persistent allocations that
+ *        will never be reallocated
+ * @return NULL if the pool cannot support size more
+ *         bytes
+ */
+void *
+MHD_pool_allocate (struct MemoryPool *pool,
+                   size_t size,
+                   int from_end);
+
+
+/**
+ * Reallocate a block of memory obtained from the pool.
+ * This is particularly efficient when growing or
+ * shrinking the block that was last (re)allocated.
+ * If the given block is not the most recently
+ * (re)allocated block, the memory of the previous
+ * allocation may be leaked until the pool is
+ * destroyed (and copying the data maybe required).
+ *
+ * @param pool memory pool to use for the operation
+ * @param old the existing block
+ * @param old_size the size of the existing block
+ * @param new_size the new size of the block
+ * @return new address of the block, or
+ *         NULL if the pool cannot support new_size
+ *         bytes (old continues to be valid for old_size)
+ */
+void *
+MHD_pool_reallocate (struct MemoryPool *pool,
+                     void *old,
+                     size_t old_size,
+                     size_t new_size);
+
+
+/**
+ * Check how much memory is left in the @a pool
+ *
+ * @param pool pool to check
+ * @return number of bytes still available in @a pool
+ */
+size_t
+MHD_pool_get_free (struct MemoryPool *pool);
+
+
+/**
+ * Clear all entries from the memory pool except
+ * for @a keep of the given @a copy_bytes.  The pointer
+ * returned should be a buffer of @a new_size where
+ * the first @a copy_bytes are from @a keep.
+ *
+ * @param pool memory pool to use for the operation
+ * @param keep pointer to the entry to keep (maybe NULL)
+ * @param copy_bytes how many bytes need to be kept at this address
+ * @param new_size how many bytes should the allocation we return have?
+ *                 (should be larger or equal to @a copy_bytes)
+ * @return addr new address of @a keep (if it had to change)
+ */
+void *
+MHD_pool_reset (struct MemoryPool *pool,
+                void *keep,
+                size_t copy_bytes,
+                size_t new_size);
+
+#endif
diff --git a/src/lib/mhd_assert.h b/src/lib/mhd_assert.h
new file mode 100644
index 0000000..e99632d
--- /dev/null
+++ b/src/lib/mhd_assert.h
@@ -0,0 +1,49 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017 Karlson2k (Evgeny Grin)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/mhd_assert.h
+ * @brief  macros for mhd_assert()
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_ASSERT_H
+#define MHD_ASSERT_H 1
+
+#include "mhd_options.h"
+#ifdef NDEBUG
+#  define mhd_assert(ignore) ((void) 0)
+#else  /* _DEBUG */
+#  ifdef HAVE_ASSERT
+#    include <assert.h>
+#    define mhd_assert(CHK) assert (CHK)
+#  else  /* ! HAVE_ASSERT */
+#    include <stdio.h>
+#    include <stdlib.h>
+#    define mhd_assert(CHK) \
+  do { \
+    if (! (CHK)) { \
+      fprintf (stderr, "%s:%u Assertion failed: %s\nProgram aborted.\n", \
+               __FILE__, (unsigned) __LINE__, #CHK); \
+      fflush (stderr); abort (); } \
+  } while (0)
+#  endif /* ! HAVE_ASSERT */
+#endif /* _DEBUG */
+
+#endif /* ! MHD_ASSERT_H */
diff --git a/src/lib/mhd_byteorder.h b/src/lib/mhd_byteorder.h
new file mode 100644
index 0000000..5e6d972
--- /dev/null
+++ b/src/lib/mhd_byteorder.h
@@ -0,0 +1,167 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/mhd_byteorder.h
+ * @brief  macro definitions for host byte order
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_BYTEORDER_H
+#define MHD_BYTEORDER_H
+
+#include "platform.h"
+
+#ifdef HAVE_ENDIAN_H
+#include <endian.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef HAVE_MACHINE_ENDIAN_H
+#include <machine/endian.h>
+#endif
+
+#ifdef HAVE_SYS_ENDIAN_H
+#include <sys/endian.h>
+#endif
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#ifdef HAVE_SYS_BYTEORDER_H
+#include <sys/byteorder.h>
+#endif
+
+#ifdef HAVE_SYS_MACHINE_H
+#include <sys/machine.h>
+#endif
+
+#ifdef HAVE_MACHINE_PARAM_H
+#include <machine/param.h>
+#endif
+
+#ifdef HAVE_SYS_ISA_DEFS_H
+#include <sys/isa_defs.h>
+#endif
+
+#define _MHD_BIG_ENDIAN 1234
+#define _MHD_LITTLE_ENDIAN 4321
+#define _MHD_PDP_ENDIAN 2143
+
+#if defined(__BYTE_ORDER__)
+#if defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == \
+  __ORDER_LITTLE_ENDIAN__
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__ORDER_PDP_ENDIAN__) && __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ */
+#elif defined(__BYTE_ORDER)
+#if defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__PDP_ENDIAN) && __BYTE_ORDER == __PDP_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* __BYTE_ORDER == __PDP_ENDIAN */
+#elif defined (BYTE_ORDER)
+#if defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(LITTLE_ENDIAN) && BYTE_ORDER == LITTLE_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(PDP_ENDIAN) && BYTE_ORDER == PDP_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* __BYTE_ORDER == _PDP_ENDIAN */
+#elif defined (_BYTE_ORDER)
+#if defined(_BIG_ENDIAN) && _BYTE_ORDER == _BIG_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(_LITTLE_ENDIAN) && _BYTE_ORDER == _LITTLE_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(_PDP_ENDIAN) && _BYTE_ORDER == _PDP_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* _BYTE_ORDER == _PDP_ENDIAN */
+#endif /* _BYTE_ORDER */
+
+#ifndef _MHD_BYTE_ORDER
+/* Byte order specification didn't detected in system headers */
+/* Try some guessing */
+
+#if   (defined(__BIG_ENDIAN__) && ! defined(__LITTLE_ENDIAN__)) || \
+  (defined(_BIG_ENDIAN) && ! defined(_LITTLE_ENDIAN))
+/* Seems that we are on big endian platform */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif (defined(__LITTLE_ENDIAN__) && ! defined(__BIG_ENDIAN__)) || \
+  (defined(_LITTLE_ENDIAN) && ! defined(_BIG_ENDIAN))
+/* Seems that we are on little endian platform */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || \
+  defined(__x86_64) || \
+  defined(_M_X64) || defined(_M_AMD64) || defined(i386) || defined(__i386) || \
+  defined(__i386__) || defined(__i486__) || defined(__i586__) || \
+  defined(__i686__) || \
+  defined(_M_IX86) || defined(_X86_) || defined (__THW_INTEL__)
+/* x86 family is little endian */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
+  defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__)
+/* Looks like we are on ARM/MIPS in big endian mode */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \
+  defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)
+/* Looks like we are on ARM/MIPS in little endian mode */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__m68k__) || defined(M68000) || defined(__hppa__) || \
+  defined(__hppa) || \
+  defined(__HPPA__) || defined(__370__) || defined(__THW_370__) || \
+  defined(__s390__) || defined(__s390x__) || defined(__SYSC_ZARCH__)
+/* Looks like we are on big endian platform */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__ia64__) || defined(_IA64) || defined(__IA64__) || \
+  defined(__ia64) || \
+  defined(_M_IA64) || defined(__itanium__) || defined(__bfin__) || \
+  defined(__BFIN__) || defined(bfin) || defined(BFIN)
+/* Looks like we are on little endian platform */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(_WIN32)
+/* W32 is always little endian on all platforms */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(WORDS_BIGENDIAN)
+/* Use byte order detected by configure */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#endif /* _WIN32 */
+
+#endif /* !_MHD_BYTE_ORDER */
+
+#ifdef _MHD_BYTE_ORDER
+/* Some safety checks */
+#if defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN
+#error \
+  Configure detected big endian byte order but headers specify different byte order
+#elif ! defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#error \
+  Configure did not detect big endian byte order but headers specify big endian byte order
+#endif /* !WORDS_BIGENDIAN && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */
+#endif /* _MHD_BYTE_ORDER */
+
+#endif /* !MHD_BYTEORDER_H */
diff --git a/src/lib/mhd_compat.c b/src/lib/mhd_compat.c
new file mode 100644
index 0000000..fd8132a
--- /dev/null
+++ b/src/lib/mhd_compat.c
@@ -0,0 +1,118 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_compat.c
+ * @brief  Implementation of platform missing functions.
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_compat.h"
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#include <stdint.h>
+#include <time.h>
+#ifndef HAVE_SNPRINTF
+#include <stdio.h>
+#include <stdarg.h>
+#endif  /* HAVE_SNPRINTF */
+#endif /* _WIN32  && !__CYGWIN__ */
+
+#ifndef HAVE_CALLOC
+#include <string.h> /* for memset() */
+#endif /* ! HAVE_CALLOC */
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+
+#ifndef HAVE_SNPRINTF
+/* Emulate snprintf function on W32 */
+int
+W32_snprintf (char *__restrict s,
+              size_t n,
+              const char *__restrict format,
+              ...)
+{
+  int ret;
+  va_list args;
+
+  if ( (0 != n) &&
+       (NULL != s) )
+  {
+    va_start (args,
+              format);
+    ret = _vsnprintf (s,
+                      n,
+                      format,
+                      args);
+    va_end (args);
+    if ((int) n == ret)
+      s[n - 1] = 0;
+    if (ret >= 0)
+      return ret;
+  }
+  va_start (args,
+            format);
+  ret = _vscprintf (format,
+                    args);
+  va_end (args);
+  if ( (0 <= ret) &&
+       (0 != n) &&
+       (NULL == s) )
+    return -1;
+
+  return ret;
+}
+
+
+#endif  /* HAVE_SNPRINTF */
+#endif /* _WIN32  && !__CYGWIN__ */
+
+#ifndef HAVE_CALLOC
+
+#ifdef __has_builtin
+#  if __has_builtin (__builtin_mul_overflow)
+#    define MHD_HAVE_NUL_OVERFLOW 1
+#  endif
+#elif __GNUC__ + 0 >= 5
+#  define MHD_HAVE_NUL_OVERFLOW 1
+#endif /* __GNUC__ >= 5 */
+
+
+void *
+MHD_calloc_ (size_t nelem, size_t elsize)
+{
+  size_t alloc_size;
+  void *ptr;
+#ifdef MHD_HAVE_NUL_OVERFLOW
+  if (__builtin_mul_overflow (nelem, elsize, &alloc_size) || (0 == alloc_size))
+    return NULL;
+#else  /* ! MHD_HAVE_NUL_OVERFLOW */
+  alloc_size = nelem * elsize;
+  if ((0 == alloc_size) || (elsize != alloc_size / nelem))
+    return NULL;
+#endif /* ! MHD_HAVE_NUL_OVERFLOW */
+  ptr = malloc (alloc_size);
+  if (NULL == ptr)
+    return NULL;
+  memset (ptr, 0, alloc_size);
+  return ptr;
+}
+
+
+#endif /* ! HAVE_CALLOC */
diff --git a/src/lib/mhd_compat.h b/src/lib/mhd_compat.h
new file mode 100644
index 0000000..4062c10
--- /dev/null
+++ b/src/lib/mhd_compat.h
@@ -0,0 +1,91 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_compat.h
+ * @brief  Header for platform missing functions.
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Provides compatibility for platforms with some missing
+ * functionality.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ */
+
+#ifndef MHD_COMPAT_H
+#define MHD_COMPAT_H 1
+
+#include "mhd_options.h"
+#include <stdlib.h>
+#ifdef HAVE_STRING_H /* for strerror() */
+#include <string.h>
+#endif /* HAVE_STRING_H */
+
+/* MHD_strerror_ is strerror */
+#define MHD_strerror_(errnum) strerror ((errnum))
+
+/* Platform-independent snprintf name */
+#if defined(HAVE_SNPRINTF)
+#define MHD_snprintf_ snprintf
+#else  /* ! HAVE_SNPRINTF */
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+/* Emulate snprintf function on W32 */
+int W32_snprintf (char *__restrict s, size_t n, const char *__restrict format,
+                  ...);
+
+#define MHD_snprintf_ W32_snprintf
+#else  /* ! _WIN32 || __CYGWIN__ */
+#error \
+  Your platform does not support snprintf() and MHD does not know how to emulate it on your platform.
+#endif /* ! _WIN32 || __CYGWIN__ */
+#endif /* ! HAVE_SNPRINTF */
+
+#ifdef HAVE_RANDOM
+/**
+ * Generate pseudo random number at least 30-bit wide.
+ * @return pseudo random number at least 30-bit wide.
+ */
+#define MHD_random_() random ()
+#else  /* HAVE_RANDOM */
+#ifdef HAVE_RAND
+/**
+ * Generate pseudo random number at least 30-bit wide.
+ * @return pseudo random number at least 30-bit wide.
+ */
+#define MHD_random_() ( (((long) rand ()) << 15) + (long) rand () )
+#endif /* HAVE_RAND */
+#endif /* HAVE_RANDOM */
+
+#ifdef HAVE_CALLOC
+/**
+ * MHD_calloc_ is platform-independent calloc()
+ */
+#define MHD_calloc_(n,s) calloc ((n),(s))
+#else  /* ! HAVE_CALLOC */
+/**
+ * MHD_calloc_ is platform-independent calloc()
+ */
+void *MHD_calloc_ (size_t nelem, size_t elsize);
+
+#endif /* ! HAVE_CALLOC */
+
+#endif /* MHD_COMPAT_H */
diff --git a/src/lib/mhd_itc.c b/src/lib/mhd_itc.c
new file mode 100644
index 0000000..b3994fc
--- /dev/null
+++ b/src/lib/mhd_itc.c
@@ -0,0 +1,72 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_itc.c
+ * @brief  Implementation of inter-thread communication functions
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+
+#include "mhd_itc.h"
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#include <fcntl.h>
+#include "internal.h"
+
+
+#if defined(_MHD_ITC_PIPE)
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+
+#ifndef HAVE_PIPE2_FUNC
+/**
+ * Change itc FD options to be non-blocking.
+ *
+ * @param itc the inter-thread communication primitive to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_itc_nonblocking_ (struct MHD_itc_ itc)
+{
+  unsigned int i;
+
+  for (i = 0; i < 2; i++)
+  {
+    int flags;
+
+    flags = fcntl (itc.fd[i],
+                   F_GETFL);
+    if (-1 == flags)
+      return 0;
+
+    if ( ((flags | O_NONBLOCK) != flags) &&
+         (0 != fcntl (itc.fd[i],
+                      F_SETFL,
+                      flags | O_NONBLOCK)) )
+      return 0;
+  }
+  return ! 0;
+}
+
+
+#endif /* ! HAVE_PIPE2_FUNC */
+#endif /* !_WIN32 || __CYGWIN__ */
+#endif /* _MHD_ITC_EVENTFD ||  _MHD_ITC_PIPE */
diff --git a/src/lib/mhd_itc.h b/src/lib/mhd_itc.h
new file mode 100644
index 0000000..a7cad0e
--- /dev/null
+++ b/src/lib/mhd_itc.h
@@ -0,0 +1,369 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_itc.h
+ * @brief  Header for platform-independent inter-thread communication
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ *
+ * Provides basic abstraction for inter-thread communication.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ */
+#ifndef MHD_ITC_H
+#define MHD_ITC_H 1
+#include "mhd_itc_types.h"
+
+#include <fcntl.h>
+
+#ifndef MHD_PANIC
+#  include <stdio.h>
+#  include <stdlib.h>
+/* Simple implementation of MHD_PANIC, to be used outside lib */
+#  define MHD_PANIC(msg) do { fprintf (stderr,           \
+                                       "Abnormal termination at %d line in file %s: %s\n", \
+                                       (int) __LINE__, __FILE__, msg); abort (); \
+} while (0)
+#endif /* ! MHD_PANIC */
+
+#if defined(_MHD_ITC_EVENTFD)
+
+/* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */
+#include <sys/eventfd.h>
+#include <stdint.h>      /* for uint64_t */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>      /* for read(), write(), errno */
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_STRING_H
+#include <string.h> /* for strerror() */
+#endif
+
+
+/**
+ * Initialise ITC by generating eventFD
+ * @param itc the itc to initialise
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_init_(itc) (-1 != ((itc).fd = eventfd (0, EFD_CLOEXEC \
+                                                       | EFD_NONBLOCK)))
+
+/**
+ * Get description string of last errno for itc operations.
+ */
+#define MHD_itc_last_strerror_() strerror (errno)
+
+/**
+ * Internal static const helper for MHD_itc_activate_()
+ */
+static const uint64_t _MHD_itc_wr_data = 1;
+
+/**
+ * Activate signal on @a itc
+ * @param itc the itc to use
+ * @param str ignored
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_activate_(itc, str) \
+  ((write ((itc).fd, (const void*) &_MHD_itc_wr_data, 8) > 0) || (EAGAIN == \
+                                                                  errno))
+
+/**
+ * Return read FD of @a itc which can be used for poll(), select() etc.
+ * @param itc the itc to get FD
+ * @return FD of read side
+ */
+#define MHD_itc_r_fd_(itc) ((itc).fd)
+
+/**
+ * Return write FD of @a itc
+ * @param itc the itc to get FD
+ * @return FD of write side
+ */
+#define MHD_itc_w_fd_(itc) ((itc).fd)
+
+/**
+ * Clear signaled state on @a itc
+ * @param itc the itc to clear
+ */
+#define MHD_itc_clear_(itc)                  \
+  do { uint64_t __b; int __r;                \
+       __r = read ((itc).fd, &__b, sizeof(__b)); \
+       (void) __r; } while (0)
+
+/**
+ * Destroy previously initialised ITC.  Note that close()
+ * on some platforms returns odd errors, so we ONLY fail
+ * if the errno is EBADF.
+ * @param itc the itc to destroy
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_destroy_(itc) ((0 == close ((itc).fd)) || (EBADF != errno))
+
+/**
+ * Check whether ITC has valid value.
+ *
+ * Macro check whether @a itc value is valid (allowed),
+ * macro does not check whether @a itc was really initialised.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has valid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_VALID_(itc)  (-1 != ((itc).fd))
+
+/**
+ * Set @a itc to invalid value.
+ * @param itc the itc to set
+ */
+#define MHD_itc_set_invalid_(itc) ((itc).fd = -1)
+
+
+#elif defined(_MHD_ITC_PIPE)
+
+/* **************** Standard UNIX ITC implementation by pipe ********** */
+
+#if defined(HAVE_PIPE2_FUNC) && defined(HAVE_FCNTL_H)
+#  include <fcntl.h>     /* for O_CLOEXEC, O_NONBLOCK */
+#endif /* HAVE_PIPE2_FUNC && HAVE_FCNTL_H */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>      /* for read(), write(), errno */
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_STRING_H
+#include <string.h> /* for strerror() */
+#endif
+
+
+/**
+ * Initialise ITC by generating pipe
+ * @param itc the itc to initialise
+ * @return non-zero if succeeded, zero otherwise
+ */
+#ifdef HAVE_PIPE2_FUNC
+#  define MHD_itc_init_(itc) (! pipe2 ((itc).fd, O_CLOEXEC | O_NONBLOCK))
+#else  /* ! HAVE_PIPE2_FUNC */
+#  define MHD_itc_init_(itc)              \
+  ( (! pipe ((itc).fd)) ?                \
+    (MHD_itc_nonblocking_ ((itc)) ?   \
+     (! 0) :                         \
+     (MHD_itc_destroy_ ((itc)), 0) ) \
+    : (0) )
+#endif /* ! HAVE_PIPE2_FUNC */
+
+/**
+ * Get description string of last errno for itc operations.
+ */
+#define MHD_itc_last_strerror_() strerror (errno)
+
+/**
+ * Activate signal on @a itc
+ * @param itc the itc to use
+ * @param str one-symbol string, useful only for strace debug
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_activate_(itc, str) \
+  ((write ((itc).fd[1], (const void*) (str), 1) > 0) || (EAGAIN == errno))
+
+
+/**
+ * Return read FD of @a itc which can be used for poll(), select() etc.
+ * @param itc the itc to get FD
+ * @return FD of read side
+ */
+#define MHD_itc_r_fd_(itc) ((itc).fd[0])
+
+/**
+ * Return write FD of @a itc
+ * @param itc the itc to get FD
+ * @return FD of write side
+ */
+#define MHD_itc_w_fd_(itc) ((itc).fd[1])
+
+/**
+ * Clear signaled state on @a itc
+ * @param itc the itc to clear
+ */
+#define MHD_itc_clear_(itc) do                      \
+  { long __b;                                       \
+    while (0 < read ((itc).fd[0], &__b, sizeof(__b))) \
+    {} } while (0)
+
+/**
+ * Destroy previously initialised ITC
+ * @param itc the itc to destroy
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_destroy_(itc)      \
+  ( (0 == close ((itc).fd[0])) ?   \
+    (0 == close ((itc).fd[1])) : \
+    ((close ((itc).fd[1])), 0) )
+
+/**
+ * Check whether ITC has valid value.
+ *
+ * Macro check whether @a itc value is valid (allowed),
+ * macro does not check whether @a itc was really initialised.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has valid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_VALID_(itc)  (-1 != (itc).fd[0])
+
+/**
+ * Set @a itc to invalid value.
+ * @param itc the itc to set
+ */
+#define MHD_itc_set_invalid_(itc) ((itc).fd[0] = (itc).fd[1] = -1)
+
+#ifndef HAVE_PIPE2_FUNC
+/**
+ * Change itc FD options to be non-blocking.
+ *
+ * @param fd the FD to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_itc_nonblocking_ (struct MHD_itc_ itc);
+
+#endif /* ! HAVE_PIPE2_FUNC */
+
+
+#elif defined(_MHD_ITC_SOCKETPAIR)
+
+/* **************** ITC implementation by socket pair ********** */
+
+#include "mhd_sockets.h"
+
+
+/**
+ * Initialise ITC by generating socketpair
+ * @param itc the itc to initialise
+ * @return non-zero if succeeded, zero otherwise
+ */
+#ifdef MHD_socket_pair_nblk_
+#  define MHD_itc_init_(itc) MHD_socket_pair_nblk_ ((itc).sk)
+#else  /* ! MHD_socket_pair_nblk_ */
+#  define MHD_itc_init_(itc)            \
+  (MHD_socket_pair_ ((itc).sk) ?      \
+   (MHD_itc_nonblocking_ ((itc)) ?   \
+    (! 0) :                         \
+    (MHD_itc_destroy_ ((itc)), 0) ) \
+   : (0))
+#endif /* ! MHD_socket_pair_nblk_ */
+
+/**
+ * Get description string of last error for itc operations.
+ */
+#define MHD_itc_last_strerror_() MHD_socket_last_strerr_ ()
+
+/**
+ * Activate signal on @a itc
+ * @param itc the itc to use
+ * @param str one-symbol string, useful only for strace debug
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_activate_(itc, str)          \
+  ((MHD_send_ ((itc).sk[1], (str), 1) > 0) || \
+   (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ())))
+
+/**
+ * Return read FD of @a itc which can be used for poll(), select() etc.
+ * @param itc the itc to get FD
+ * @return FD of read side
+ */
+#define MHD_itc_r_fd_(itc) ((itc).sk[0])
+
+/**
+ * Return write FD of @a itc
+ * @param itc the itc to get FD
+ * @return FD of write side
+ */
+#define MHD_itc_w_fd_(itc) ((itc).sk[1])
+
+/**
+ * Clear signaled state on @a itc
+ * @param itc the itc to clear
+ */
+#define MHD_itc_clear_(itc) do      \
+  { long __b;                       \
+    while (0 < recv ((itc).sk[0],     \
+                     (char*) &__b,     \
+                     sizeof(__b), 0)) \
+    {} } while (0)
+
+/**
+ * Destroy previously initialised ITC
+ * @param itc the itc to destroy
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_destroy_(itc)          \
+  (MHD_socket_close_ ((itc).sk[0]) ?   \
+   MHD_socket_close_ ((itc).sk[1]) : \
+   ((void) MHD_socket_close_ ((itc).sk[1]), 0) )
+
+
+/**
+ * Check whether ITC has valid value.
+ *
+ * Macro check whether @a itc value is valid (allowed),
+ * macro does not check whether @a itc was really initialised.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has valid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_VALID_(itc)  (MHD_INVALID_SOCKET != (itc).sk[0])
+
+/**
+ * Set @a itc to invalid value.
+ * @param itc the itc to set
+ */
+#define MHD_itc_set_invalid_(itc) ((itc).sk[0] = (itc).sk[1] = \
+                                     MHD_INVALID_SOCKET)
+
+#ifndef MHD_socket_pair_nblk_
+#  define MHD_itc_nonblocking_(pip) (MHD_socket_nonblocking_ ((pip).sk[0]) && \
+                                     MHD_socket_nonblocking_ ((pip).sk[1]))
+#endif /* ! MHD_socket_pair_nblk_ */
+
+#endif /* _MHD_ITC_SOCKETPAIR */
+
+/**
+ * Destroy previously initialised ITC and abort execution
+ * if error is detected.
+ * @param itc the itc to destroy
+ */
+#define MHD_itc_destroy_chk_(itc) do {          \
+    if (! MHD_itc_destroy_ (itc))                 \
+      MHD_PANIC (_ ("Failed to destroy ITC.\n")); \
+} while (0)
+
+/**
+ * Check whether ITC has invalid value.
+ *
+ * Macro check whether @a itc value is invalid,
+ * macro does not check whether @a itc was destroyed.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has invalid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_INVALID_(itc)  (! MHD_ITC_IS_VALID_ (itc))
+
+#endif /* MHD_ITC_H */
diff --git a/src/lib/mhd_itc_types.h b/src/lib/mhd_itc_types.h
new file mode 100644
index 0000000..36d4218
--- /dev/null
+++ b/src/lib/mhd_itc_types.h
@@ -0,0 +1,77 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin), Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_itc_types.h
+ * @brief  Types for platform-independent inter-thread communication
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ *
+ * Provides basic types for inter-thread communication.
+ * Designed to be included by other headers.
+ */
+#ifndef MHD_ITC_TYPES_H
+#define MHD_ITC_TYPES_H 1
+#include "mhd_options.h"
+
+/* Force socketpair on native W32 */
+#if defined(_WIN32) && ! defined(__CYGWIN__) && ! defined(_MHD_ITC_SOCKETPAIR)
+#error _MHD_ITC_SOCKETPAIR is not defined on naitive W32 platform
+#endif /* _WIN32 && !__CYGWIN__ && !_MHD_ITC_SOCKETPAIR */
+
+#if defined(_MHD_ITC_EVENTFD)
+/* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */
+
+/**
+ * Data type for a MHD ITC.
+ */
+struct MHD_itc_
+{
+  int fd;
+};
+
+#elif defined(_MHD_ITC_PIPE)
+/* **************** Standard UNIX ITC implementation by pipe ********** */
+
+/**
+ * Data type for a MHD ITC.
+ */
+struct MHD_itc_
+{
+  int fd[2];
+};
+
+
+#elif defined(_MHD_ITC_SOCKETPAIR)
+/* **************** ITC implementation by socket pair ********** */
+
+#include "mhd_sockets.h"
+
+/**
+ * Data type for a MHD ITC.
+ */
+struct MHD_itc_
+{
+  MHD_socket sk[2];
+};
+
+#endif /* _MHD_ITC_SOCKETPAIR */
+
+#endif /* ! MHD_ITC_TYPES_H */
diff --git a/src/lib/mhd_limits.h b/src/lib/mhd_limits.h
new file mode 100644
index 0000000..87b4144
--- /dev/null
+++ b/src/lib/mhd_limits.h
@@ -0,0 +1,154 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_limits.h
+ * @brief  limits values definitions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_LIMITS_H
+#define MHD_LIMITS_H
+
+#include "platform.h"
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#define MHD_UNSIGNED_TYPE_MAX_(type) ((type) - 1)
+/* Assume 8 bits per byte, no padding bits. */
+#define MHD_SIGNED_TYPE_MAX_(type) \
+  ( (type) ((( ((type) 1) << (sizeof(type) * 8 - 2)) - 1) * 2 + 1) )
+#define MHD_TYPE_IS_SIGNED_(type) (((type) 0)>((type) - 1))
+
+#ifndef UINT_MAX
+#ifdef __UINT_MAX__
+#define UINT_MAX __UINT_MAX__
+#else  /* ! __UINT_MAX__ */
+#define UINT_MAX MHD_UNSIGNED_TYPE_MAX_ (unsigned int)
+#endif /* ! __UINT_MAX__ */
+#endif /* !UINT_MAX */
+
+#ifndef LONG_MAX
+#ifdef __LONG_MAX__
+#define LONG_MAX __LONG_MAX__
+#else  /* ! __LONG_MAX__ */
+#define LONG_MAX MHD_SIGNED_TYPE_MAX (long)
+#endif /* ! __LONG_MAX__ */
+#endif /* !OFF_T_MAX */
+
+#ifndef ULLONG_MAX
+#define ULLONG_MAX MHD_UNSIGNED_TYPE_MAX_ (MHD_UNSIGNED_LONG_LONG)
+#endif /* !ULLONG_MAX */
+
+#ifndef INT32_MAX
+#ifdef __INT32_MAX__
+#define INT32_MAX __INT32_MAX__
+#else  /* ! __INT32_MAX__ */
+#define INT32_MAX ((int32_t) 0x7FFFFFFF)
+#endif /* ! __INT32_MAX__ */
+#endif /* !INT32_MAX */
+
+#ifndef UINT32_MAX
+#ifdef __UINT32_MAX__
+#define UINT32_MAX __UINT32_MAX__
+#else  /* ! __UINT32_MAX__ */
+#define UINT32_MAX ((int32_t) 0xFFFFFFFF)
+#endif /* ! __UINT32_MAX__ */
+#endif /* !UINT32_MAX */
+
+#ifndef UINT64_MAX
+#ifdef __UINT64_MAX__
+#define UINT64_MAX __UINT64_MAX__
+#else  /* ! __UINT64_MAX__ */
+#define UINT64_MAX ((uint64_t) 0xFFFFFFFFFFFFFFFF)
+#endif /* ! __UINT64_MAX__ */
+#endif /* !UINT64_MAX */
+
+#ifndef INT64_MAX
+#ifdef __INT64_MAX__
+#define INT64_MAX __INT64_MAX__
+#else  /* ! __INT64_MAX__ */
+#define INT64_MAX ((int64_t) 0x7FFFFFFFFFFFFFFF)
+#endif /* ! __UINT64_MAX__ */
+#endif /* !INT64_MAX */
+
+#ifndef SIZE_MAX
+#ifdef __SIZE_MAX__
+#define SIZE_MAX __SIZE_MAX__
+#elif defined(UINTPTR_MAX)
+#define SIZE_MAX UINTPTR_MAX
+#else  /* ! __SIZE_MAX__ */
+#define SIZE_MAX MHD_UNSIGNED_TYPE_MAX_ (size_t)
+#endif /* ! __SIZE_MAX__ */
+#endif /* !SIZE_MAX */
+
+#ifndef SSIZE_MAX
+#ifdef __SSIZE_MAX__
+#define SSIZE_MAX __SSIZE_MAX__
+#elif defined(PTRDIFF_MAX)
+#define SSIZE_MAX PTRDIFF_MAX
+#elif defined(INTPTR_MAX)
+#define SSIZE_MAX INTPTR_MAX
+#else
+#define SSIZE_MAN MHD_SIGNED_TYPE_MAX_ (ssize_t)
+#endif
+#endif /* ! SSIZE_MAX */
+
+#ifndef OFF_T_MAX
+#ifdef OFF_MAX
+#define OFF_T_MAX OFF_MAX
+#elif defined(OFFT_MAX)
+#define OFF_T_MAX OFFT_MAX
+#elif defined(__APPLE__) && defined(__MACH__)
+#define OFF_T_MAX INT64_MAX
+#else
+#define OFF_T_MAX MHD_SIGNED_TYPE_MAX_ (off_t)
+#endif
+#endif /* !OFF_T_MAX */
+
+#if defined(_LARGEFILE64_SOURCE) && ! defined(OFF64_T_MAX)
+#define OFF64_T_MAX MHD_SIGNED_TYPE_MAX_ (uint64_t)
+#endif /* _LARGEFILE64_SOURCE && !OFF64_T_MAX */
+
+#ifndef TIME_T_MAX
+#define TIME_T_MAX ((time_t)              \
+                    (MHD_TYPE_IS_SIGNED_ (time_t) ?    \
+                     MHD_SIGNED_TYPE_MAX_ (time_t) : \
+                     MHD_UNSIGNED_TYPE_MAX_ (time_t)))
+#endif /* !TIME_T_MAX */
+
+#ifndef TIMEVAL_TV_SEC_MAX
+#ifndef _WIN32
+#define TIMEVAL_TV_SEC_MAX TIME_T_MAX
+#else  /* _WIN32 */
+#define TIMEVAL_TV_SEC_MAX LONG_MAX
+#endif /* _WIN32 */
+#endif /* !TIMEVAL_TV_SEC_MAX */
+
+#ifndef MHD_FD_BLOCK_SIZE
+#ifdef _WIN32
+#define MHD_FD_BLOCK_SIZE 16384 /* 16k */
+#else /* _WIN32 */
+#define MHD_FD_BLOCK_SIZE 4096 /* 4k */
+#endif /* _WIN32 */
+#endif /* !MHD_FD_BLOCK_SIZE */
+
+#endif /* MHD_LIMITS_H */
diff --git a/src/lib/mhd_locks.h b/src/lib/mhd_locks.h
new file mode 100644
index 0000000..8c9b084
--- /dev/null
+++ b/src/lib/mhd_locks.h
@@ -0,0 +1,186 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_locks.h
+ * @brief  Header for platform-independent locks abstraction
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ *
+ * Provides basic abstraction for locks/mutex.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ *
+ * @warning Unlike pthread functions, most of functions return
+ *          nonzero on success.
+ */
+
+#ifndef MHD_LOCKS_H
+#define MHD_LOCKS_H 1
+
+#include "mhd_options.h"
+
+#if defined(MHD_USE_W32_THREADS)
+#  define MHD_W32_MUTEX_ 1
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
+#  endif /* !WIN32_LEAN_AND_MEAN */
+#  include <windows.h>
+#elif defined(HAVE_PTHREAD_H) && defined(MHD_USE_POSIX_THREADS)
+#  define MHD_PTHREAD_MUTEX_ 1
+#  undef HAVE_CONFIG_H
+#  include <pthread.h>
+#  define HAVE_CONFIG_H 1
+#else
+#  error No base mutex API is available.
+#endif
+
+#ifndef MHD_PANIC
+#  include <stdio.h>
+#  include <stdlib.h>
+/* Simple implementation of MHD_PANIC, to be used outside lib */
+#  define MHD_PANIC(msg) do { fprintf (stderr,           \
+                                       "Abnormal termination at %d line in file %s: %s\n", \
+                                       (int) __LINE__, __FILE__, msg); abort (); \
+} while (0)
+#endif /* ! MHD_PANIC */
+
+#if defined(MHD_PTHREAD_MUTEX_)
+typedef pthread_mutex_t MHD_mutex_;
+#elif defined(MHD_W32_MUTEX_)
+typedef CRITICAL_SECTION MHD_mutex_;
+#endif
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Initialise new mutex.
+ * @param pmutex pointer to the mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_init_(pmutex) (! (pthread_mutex_init ((pmutex), NULL)))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Initialise new mutex.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_init_(pmutex) (InitializeCriticalSectionAndSpinCount ( \
+                                   (pmutex),16))
+#endif
+
+#if defined(MHD_PTHREAD_MUTEX_)
+#  if defined(PTHREAD_MUTEX_INITIALIZER)
+/**
+ *  Define static mutex and statically initialise it.
+ */
+#    define MHD_MUTEX_STATIC_DEFN_INIT_(m) static MHD_mutex_ m = \
+  PTHREAD_MUTEX_INITIALIZER
+#  endif /* PTHREAD_MUTEX_INITIALIZER */
+#endif
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Destroy previously initialised mutex.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_destroy_(pmutex) (! (pthread_mutex_destroy ((pmutex))))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Destroy previously initialised mutex.
+ * @param pmutex pointer to mutex
+ * @return Always nonzero
+ */
+#define MHD_mutex_destroy_(pmutex) (DeleteCriticalSection ((pmutex)), ! 0)
+#endif
+
+/**
+ * Destroy previously initialised mutex and abort execution
+ * if error is detected.
+ * @param pmutex pointer to mutex
+ */
+#define MHD_mutex_destroy_chk_(pmutex) do {       \
+    if (! MHD_mutex_destroy_ (pmutex))              \
+      MHD_PANIC (_ ("Failed to destroy mutex.\n")); \
+} while (0)
+
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Acquire lock on previously initialised mutex.
+ * If mutex was already locked by other thread, function
+ * blocks until mutex becomes available.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_lock_(pmutex) (! (pthread_mutex_lock ((pmutex))))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Acquire lock on previously initialised mutex.
+ * If mutex was already locked by other thread, function
+ * blocks until mutex becomes available.
+ * @param pmutex pointer to mutex
+ * @return Always nonzero
+ */
+#define MHD_mutex_lock_(pmutex) (EnterCriticalSection ((pmutex)), ! 0)
+#endif
+
+/**
+ * Acquire lock on previously initialised mutex.
+ * If mutex was already locked by other thread, function
+ * blocks until mutex becomes available.
+ * If error is detected, execution will be aborted.
+ * @param pmutex pointer to mutex
+ */
+#define MHD_mutex_lock_chk_(pmutex) do {       \
+    if (! MHD_mutex_lock_ (pmutex))              \
+      MHD_PANIC (_ ("Failed to lock mutex.\n")); \
+} while (0)
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Unlock previously initialised and locked mutex.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_unlock_(pmutex) (! (pthread_mutex_unlock ((pmutex))))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Unlock previously initialised and locked mutex.
+ * @param pmutex pointer to mutex
+ * @return Always nonzero
+ */
+#define MHD_mutex_unlock_(pmutex) (LeaveCriticalSection ((pmutex)), ! 0)
+#endif
+
+/**
+ * Unlock previously initialised and locked mutex.
+ * If error is detected, execution will be aborted.
+ * @param pmutex pointer to mutex
+ */
+#define MHD_mutex_unlock_chk_(pmutex) do {       \
+    if (! MHD_mutex_unlock_ (pmutex))              \
+      MHD_PANIC (_ ("Failed to unlock mutex.\n")); \
+} while (0)
+
+
+#endif /* ! MHD_LOCKS_H */
diff --git a/src/lib/mhd_mono_clock.c b/src/lib/mhd_mono_clock.c
new file mode 100644
index 0000000..0bd9984
--- /dev/null
+++ b/src/lib/mhd_mono_clock.c
@@ -0,0 +1,378 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_mono_clock.h
+ * @brief  internal monotonic clock functions implementations
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_mono_clock.h"
+
+#if defined(_WIN32) && ! defined(__CYGWIN__) && defined(HAVE_CLOCK_GETTIME)
+/* Prefer native clock source over wrappers */
+#undef HAVE_CLOCK_GETTIME
+#endif /* _WIN32 && ! __CYGWIN__ && HAVE_CLOCK_GETTIME */
+
+#ifdef HAVE_CLOCK_GETTIME
+#include <time.h>
+#endif /* HAVE_CLOCK_GETTIME */
+
+#ifdef HAVE_GETHRTIME
+#ifdef HAVE_SYS_TIME_H
+/* Solaris defines gethrtime() in sys/time.h */
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+#ifdef HAVE_TIME_H
+/* HP-UX defines gethrtime() in time.h */
+#include <time.h>
+#endif /* HAVE_TIME_H */
+#endif /* HAVE_GETHRTIME */
+
+#ifdef HAVE_CLOCK_GET_TIME
+#include <mach/mach.h>
+/* for host_get_clock_service(), mach_host_self(), mach_task_self() */
+#include <mach/clock.h>
+/* for clock_get_time() */
+
+#define _MHD_INVALID_CLOCK_SERV ((clock_serv_t) -2)
+
+static clock_serv_t mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+#endif /* HAVE_CLOCK_GET_TIME */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+/* Do not include unneeded parts of W32 headers. */
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#include <stdint.h>
+#endif /* _WIN32 */
+
+#ifdef HAVE_CLOCK_GETTIME
+#ifdef CLOCK_REALTIME
+#define _MHD_UNWANTED_CLOCK CLOCK_REALTIME
+#else  /* !CLOCK_REALTIME */
+#define _MHD_UNWANTED_CLOCK ((clockid_t) -2)
+#endif /* !CLOCK_REALTIME */
+
+static clockid_t mono_clock_id = _MHD_UNWANTED_CLOCK;
+#endif /* HAVE_CLOCK_GETTIME */
+
+/* sync clocks; reduce chance of value wrap */
+#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GET_TIME) || \
+  defined(HAVE_GETHRTIME)
+static time_t mono_clock_start;
+#endif /* HAVE_CLOCK_GETTIME || HAVE_CLOCK_GET_TIME || HAVE_GETHRTIME */
+static time_t sys_clock_start;
+#ifdef HAVE_GETHRTIME
+static hrtime_t hrtime_start;
+#endif /* HAVE_GETHRTIME */
+#ifdef _WIN32
+#if _WIN32_WINNT >= 0x0600
+static uint64_t tick_start;
+#else  /* _WIN32_WINNT < 0x0600 */
+static int64_t perf_freq;
+static int64_t perf_start;
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+
+
+/**
+ * Type of monotonic clock source
+ */
+enum _MHD_mono_clock_source
+{
+  /**
+   * No monotonic clock
+   */
+  _MHD_CLOCK_NO_SOURCE = 0,
+
+  /**
+   * clock_gettime() with specific clock
+   */
+  _MHD_CLOCK_GETTIME,
+
+  /**
+   * clock_get_time() with specific clock service
+   */
+  _MHD_CLOCK_GET_TIME,
+
+  /**
+   * gethrtime() / 1000000000
+   */
+  _MHD_CLOCK_GETHRTIME,
+
+  /**
+   * GetTickCount64() / 1000
+   */
+  _MHD_CLOCK_GETTICKCOUNT64,
+
+  /**
+   * QueryPerformanceCounter() / QueryPerformanceFrequency()
+   */
+  _MHD_CLOCK_PERFCOUNTER
+};
+
+
+/**
+ * Initialise monotonic seconds counter.
+ */
+void
+MHD_monotonic_sec_counter_init (void)
+{
+#ifdef HAVE_CLOCK_GET_TIME
+  mach_timespec_t cur_time;
+#endif /* HAVE_CLOCK_GET_TIME */
+  enum _MHD_mono_clock_source mono_clock_source = _MHD_CLOCK_NO_SOURCE;
+#ifdef HAVE_CLOCK_GETTIME
+  struct timespec ts;
+
+  mono_clock_id = _MHD_UNWANTED_CLOCK;
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+#endif /* HAVE_CLOCK_GET_TIME */
+
+  /* just a little syntactic trick to get the
+     various following ifdef's to work out nicely */
+  if (0)
+  {
+  }
+  else
+#ifdef HAVE_CLOCK_GETTIME
+#ifdef CLOCK_MONOTONIC_COARSE
+  /* Linux-specific fast value-getting clock */
+  /* Can be affected by frequency adjustment and don't count time in suspend, */
+  /* but preferred since it's fast */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_COARSE,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_COARSE;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_COARSE */
+#ifdef CLOCK_MONOTONIC_FAST
+  /* FreeBSD/DragonFly fast value-getting clock */
+  /* Can be affected by frequency adjustment, but preferred since it's fast */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_FAST,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_FAST;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_COARSE */
+#ifdef CLOCK_MONOTONIC_RAW
+  /* Linux-specific clock */
+  /* Not affected by frequency adjustment, but don't count time in suspend */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_RAW,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_RAW;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_RAW */
+#ifdef CLOCK_BOOTTIME
+  /* Linux-specific clock */
+  /* Count time in suspend so it's real monotonic on Linux, */
+  /* but can be slower value-getting than other clocks */
+  if (0 == clock_gettime (CLOCK_BOOTTIME,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_BOOTTIME;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_BOOTTIME */
+#ifdef CLOCK_MONOTONIC
+  /* Monotonic clock */
+  /* Widely supported, may be affected by frequency adjustment */
+  /* On Linux it's not truly monotonic as it doesn't count time in suspend */
+  if (0 == clock_gettime (CLOCK_MONOTONIC,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_BOOTTIME */
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  /* Darwin-specific monotonic clock */
+  /* Should be monotonic as clock_set_time function always unconditionally */
+  /* failed on latest kernels */
+  if ( (KERN_SUCCESS == host_get_clock_service (mach_host_self (),
+                                                SYSTEM_CLOCK,
+                                                &mono_clock_service)) &&
+       (KERN_SUCCESS == clock_get_time (mono_clock_service,
+                                        &cur_time)) )
+  {
+    mono_clock_start = cur_time.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GET_TIME;
+  }
+  else
+#endif /* HAVE_CLOCK_GET_TIME */
+#ifdef _WIN32
+#if _WIN32_WINNT >= 0x0600
+  /* W32 Vista or later specific monotonic clock */
+  /* Available since Vista, ~15ms accuracy */
+  if (1)
+  {
+    tick_start = GetTickCount64 ();
+    mono_clock_source = _MHD_CLOCK_GETTICKCOUNT64;
+  }
+  else
+#else  /* _WIN32_WINNT < 0x0600 */
+  /* W32 specific monotonic clock */
+  /* Available on Windows 2000 and later */
+  if (1)
+  {
+    LARGE_INTEGER freq;
+    LARGE_INTEGER perf_counter;
+
+    QueryPerformanceFrequency (&freq);       /* never fail on XP and later */
+    QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */
+    perf_freq = freq.QuadPart;
+    perf_start = perf_counter.QuadPart;
+    mono_clock_source = _MHD_CLOCK_PERFCOUNTER;
+  }
+  else
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+#ifdef HAVE_CLOCK_GETTIME
+#ifdef CLOCK_HIGHRES
+  /* Solaris-specific monotonic high-resolution clock */
+  /* Not preferred due to be potentially resource-hungry */
+  if (0 == clock_gettime (CLOCK_HIGHRES,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_HIGHRES;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_HIGHRES */
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_GETHRTIME
+  /* HP-UX and Solaris monotonic clock */
+  /* Not preferred due to be potentially resource-hungry */
+  if (1)
+  {
+    hrtime_start = gethrtime ();
+    mono_clock_source = _MHD_CLOCK_GETHRTIME;
+  }
+  else
+#endif /* HAVE_GETHRTIME */
+  {
+    /* no suitable clock source was found */
+    mono_clock_source = _MHD_CLOCK_NO_SOURCE;
+  }
+
+#ifdef HAVE_CLOCK_GET_TIME
+  if ( (_MHD_CLOCK_GET_TIME != mono_clock_source) &&
+       (_MHD_INVALID_CLOCK_SERV != mono_clock_service) )
+  {
+    /* clock service was initialised but clock_get_time failed */
+    mach_port_deallocate (mach_task_self (),
+                          mono_clock_service);
+    mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+  }
+#else
+  (void) mono_clock_source; /* avoid compiler warning */
+#endif /* HAVE_CLOCK_GET_TIME */
+
+  sys_clock_start = time (NULL);
+}
+
+
+/**
+ * Deinitialise monotonic seconds counter by freeing any allocated resources
+ */
+void
+MHD_monotonic_sec_counter_finish (void)
+{
+#ifdef HAVE_CLOCK_GET_TIME
+  if (_MHD_INVALID_CLOCK_SERV != mono_clock_service)
+  {
+    mach_port_deallocate (mach_task_self (),
+                          mono_clock_service);
+    mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+  }
+#endif /* HAVE_CLOCK_GET_TIME */
+}
+
+
+/**
+ * Monotonic seconds counter, useful for timeout calculation.
+ * Tries to be not affected by manually setting the system real time
+ * clock or adjustments by NTP synchronization.
+ *
+ * @return number of seconds from some fixed moment
+ */
+time_t
+MHD_monotonic_sec_counter (void)
+{
+#ifdef HAVE_CLOCK_GETTIME
+  struct timespec ts;
+
+  if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) &&
+       (0 == clock_gettime (mono_clock_id,
+                            &ts)) )
+    return ts.tv_sec - mono_clock_start;
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  if (_MHD_INVALID_CLOCK_SERV != mono_clock_service)
+  {
+    mach_timespec_t cur_time;
+
+    if (KERN_SUCCESS == clock_get_time (mono_clock_service,
+                                        &cur_time))
+      return cur_time.tv_sec - mono_clock_start;
+  }
+#endif /* HAVE_CLOCK_GET_TIME */
+#if defined(_WIN32)
+#if _WIN32_WINNT >= 0x0600
+  if (1)
+    return (time_t) (((uint64_t) (GetTickCount64 () - tick_start)) / 1000);
+#else  /* _WIN32_WINNT < 0x0600 */
+  if (0 != perf_freq)
+  {
+    LARGE_INTEGER perf_counter;
+
+    QueryPerformanceCounter (&perf_counter);   /* never fail on XP and later */
+    return (time_t) (((uint64_t) (perf_counter.QuadPart - perf_start))
+                     / perf_freq);
+  }
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+#ifdef HAVE_GETHRTIME
+  if (1)
+    return (time_t) (((uint64_t) (gethrtime () - hrtime_start)) / 1000000000);
+#endif /* HAVE_GETHRTIME */
+
+  return time (NULL) - sys_clock_start;
+}
diff --git a/src/lib/mhd_mono_clock.h b/src/lib/mhd_mono_clock.h
new file mode 100644
index 0000000..92485e0
--- /dev/null
+++ b/src/lib/mhd_mono_clock.h
@@ -0,0 +1,60 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_mono_clock.h
+ * @brief  internal monotonic clock functions declarations
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_MONO_CLOCK_H
+#define MHD_MONO_CLOCK_H 1
+#include "mhd_options.h"
+
+#if defined(HAVE_TIME_H)
+#include <time.h>
+#elif defined(HAVE_SYS_TYPES_H)
+#include <sys/types.h>
+#endif
+
+/**
+ * Initialise monotonic seconds counter.
+ */
+void
+MHD_monotonic_sec_counter_init (void);
+
+
+/**
+ * Deinitialise monotonic seconds counter by freeing any allocated resources
+ */
+void
+MHD_monotonic_sec_counter_finish (void);
+
+
+/**
+ * Monotonic seconds counter, useful for timeout calculation.
+ * Tries to be not affected by manually setting the system real time
+ * clock or adjustments by NTP synchronization.
+ *
+ * @return number of seconds from some fixed moment
+ */
+time_t
+MHD_monotonic_sec_counter (void);
+
+#endif /* MHD_MONO_CLOCK_H */
diff --git a/src/lib/mhd_sockets.c b/src/lib/mhd_sockets.c
new file mode 100644
index 0000000..decd2a0
--- /dev/null
+++ b/src/lib/mhd_sockets.c
@@ -0,0 +1,517 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_sockets.c
+ * @brief  Implementation for sockets functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_sockets.h"
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#include <fcntl.h>
+
+#ifdef MHD_WINSOCK_SOCKETS
+
+/**
+ * Return pointer to string description of specified WinSock error
+ * @param err the WinSock error code.
+ * @return pointer to string description of specified WinSock error.
+ */
+const char *
+MHD_W32_strerror_winsock_ (int err)
+{
+  switch (err)
+  {
+  case 0:
+    return "No error";
+  case WSA_INVALID_HANDLE:
+    return "Specified event object handle is invalid";
+  case WSA_NOT_ENOUGH_MEMORY:
+    return "Insufficient memory available";
+  case WSA_INVALID_PARAMETER:
+    return "One or more parameters are invalid";
+  case WSA_OPERATION_ABORTED:
+    return "Overlapped operation aborted";
+  case WSA_IO_INCOMPLETE:
+    return "Overlapped I/O event object not in signaled state";
+  case WSA_IO_PENDING:
+    return "Overlapped operations will complete later";
+  case WSAEINTR:
+    return "Interrupted function call";
+  case WSAEBADF:
+    return "File handle is not valid";
+  case WSAEACCES:
+    return "Permission denied";
+  case WSAEFAULT:
+    return "Bad address";
+  case WSAEINVAL:
+    return "Invalid argument";
+  case WSAEMFILE:
+    return "Too many open files";
+  case WSAEWOULDBLOCK:
+    return "Resource temporarily unavailable";
+  case WSAEINPROGRESS:
+    return "Operation now in progress";
+  case WSAEALREADY:
+    return "Operation already in progress";
+  case WSAENOTSOCK:
+    return "Socket operation on nonsocket";
+  case WSAEDESTADDRREQ:
+    return "Destination address required";
+  case WSAEMSGSIZE:
+    return "Message too long";
+  case WSAEPROTOTYPE:
+    return "Protocol wrong type for socket";
+  case WSAENOPROTOOPT:
+    return "Bad protocol option";
+  case WSAEPROTONOSUPPORT:
+    return "Protocol not supported";
+  case WSAESOCKTNOSUPPORT:
+    return "Socket type not supported";
+  case WSAEOPNOTSUPP:
+    return "Operation not supported";
+  case WSAEPFNOSUPPORT:
+    return "Protocol family not supported";
+  case WSAEAFNOSUPPORT:
+    return "Address family not supported by protocol family";
+  case WSAEADDRINUSE:
+    return "Address already in use";
+  case WSAEADDRNOTAVAIL:
+    return "Cannot assign requested address";
+  case WSAENETDOWN:
+    return "Network is down";
+  case WSAENETUNREACH:
+    return "Network is unreachable";
+  case WSAENETRESET:
+    return "Network dropped connection on reset";
+  case WSAECONNABORTED:
+    return "Software caused connection abort";
+  case WSAECONNRESET:
+    return "Connection reset by peer";
+  case WSAENOBUFS:
+    return "No buffer space available";
+  case WSAEISCONN:
+    return "Socket is already connected";
+  case WSAENOTCONN:
+    return "Socket is not connected";
+  case WSAESHUTDOWN:
+    return "Cannot send after socket shutdown";
+  case WSAETOOMANYREFS:
+    return "Too many references";
+  case WSAETIMEDOUT:
+    return "Connection timed out";
+  case WSAECONNREFUSED:
+    return "Connection refused";
+  case WSAELOOP:
+    return "Cannot translate name";
+  case WSAENAMETOOLONG:
+    return "Name too long";
+  case WSAEHOSTDOWN:
+    return "Host is down";
+  case WSAEHOSTUNREACH:
+    return "No route to host";
+  case WSAENOTEMPTY:
+    return "Directory not empty";
+  case WSAEPROCLIM:
+    return "Too many processes";
+  case WSAEUSERS:
+    return "User quota exceeded";
+  case WSAEDQUOT:
+    return "Disk quota exceeded";
+  case WSAESTALE:
+    return "Stale file handle reference";
+  case WSAEREMOTE:
+    return "Item is remote";
+  case WSASYSNOTREADY:
+    return "Network subsystem is unavailable";
+  case WSAVERNOTSUPPORTED:
+    return "Winsock.dll version out of range";
+  case WSANOTINITIALISED:
+    return "Successful WSAStartup not yet performed";
+  case WSAEDISCON:
+    return "Graceful shutdown in progress";
+  case WSAENOMORE:
+    return "No more results";
+  case WSAECANCELLED:
+    return "Call has been canceled";
+  case WSAEINVALIDPROCTABLE:
+    return "Procedure call table is invalid";
+  case WSAEINVALIDPROVIDER:
+    return "Service provider is invalid";
+  case WSAEPROVIDERFAILEDINIT:
+    return "Service provider failed to initialize";
+  case WSASYSCALLFAILURE:
+    return "System call failure";
+  case WSASERVICE_NOT_FOUND:
+    return "Service not found";
+  case WSATYPE_NOT_FOUND:
+    return "Class type not found";
+  case WSA_E_NO_MORE:
+    return "No more results";
+  case WSA_E_CANCELLED:
+    return "Call was canceled";
+  case WSAEREFUSED:
+    return "Database query was refused";
+  case WSAHOST_NOT_FOUND:
+    return "Host not found";
+  case WSATRY_AGAIN:
+    return "Nonauthoritative host not found";
+  case WSANO_RECOVERY:
+    return "This is a nonrecoverable error";
+  case WSANO_DATA:
+    return "Valid name, no data record of requested type";
+  case WSA_QOS_RECEIVERS:
+    return "QoS receivers";
+  case WSA_QOS_SENDERS:
+    return "QoS senders";
+  case WSA_QOS_NO_SENDERS:
+    return "No QoS senders";
+  case WSA_QOS_NO_RECEIVERS:
+    return "QoS no receivers";
+  case WSA_QOS_REQUEST_CONFIRMED:
+    return "QoS request confirmed";
+  case WSA_QOS_ADMISSION_FAILURE:
+    return "QoS admission error";
+  case WSA_QOS_POLICY_FAILURE:
+    return "QoS policy failure";
+  case WSA_QOS_BAD_STYLE:
+    return "QoS bad style";
+  case WSA_QOS_BAD_OBJECT:
+    return "QoS bad object";
+  case WSA_QOS_TRAFFIC_CTRL_ERROR:
+    return "QoS traffic control error";
+  case WSA_QOS_GENERIC_ERROR:
+    return "QoS generic error";
+  case WSA_QOS_ESERVICETYPE:
+    return "QoS service type error";
+  case WSA_QOS_EFLOWSPEC:
+    return "QoS flowspec error";
+  case WSA_QOS_EPROVSPECBUF:
+    return "Invalid QoS provider buffer";
+  case WSA_QOS_EFILTERSTYLE:
+    return "Invalid QoS filter style";
+  case WSA_QOS_EFILTERTYPE:
+    return "Invalid QoS filter type";
+  case WSA_QOS_EFILTERCOUNT:
+    return "Incorrect QoS filter count";
+  case WSA_QOS_EOBJLENGTH:
+    return "Invalid QoS object length";
+  case WSA_QOS_EFLOWCOUNT:
+    return "Incorrect QoS flow count";
+  case WSA_QOS_EUNKOWNPSOBJ:
+    return "Unrecognized QoS object";
+  case WSA_QOS_EPOLICYOBJ:
+    return "Invalid QoS policy object";
+  case WSA_QOS_EFLOWDESC:
+    return "Invalid QoS flow descriptor";
+  case WSA_QOS_EPSFLOWSPEC:
+    return "Invalid QoS provider-specific flowspec";
+  case WSA_QOS_EPSFILTERSPEC:
+    return "Invalid QoS provider-specific filterspec";
+  case WSA_QOS_ESDMODEOBJ:
+    return "Invalid QoS shape discard mode object";
+  case WSA_QOS_ESHAPERATEOBJ:
+    return "Invalid QoS shaping rate object";
+  case WSA_QOS_RESERVED_PETYPE:
+    return "Reserved policy QoS element type";
+  }
+  return "Unknown winsock error";
+}
+
+
+/**
+ * Create pair of mutually connected TCP/IP sockets on loopback address
+ * @param sockets_pair array to receive resulted sockets
+ * @param non_blk if set to non-zero value, sockets created in non-blocking mode
+ *                otherwise sockets will be in blocking mode
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk)
+{
+  int i;
+
+  if (! sockets_pair)
+  {
+    WSASetLastError (WSAEFAULT);
+    return 0;
+  }
+
+#define PAIRMAXTRYIES 800
+  for (i = 0; i < PAIRMAXTRYIES; i++)
+  {
+    struct sockaddr_in listen_addr;
+    SOCKET listen_s;
+    static const int c_addinlen = sizeof(struct sockaddr_in);   /* help compiler to optimize */
+    int addr_len = c_addinlen;
+    unsigned long on_val = 1;
+    unsigned long off_val = 0;
+
+    listen_s = socket (AF_INET,
+                       SOCK_STREAM,
+                       IPPROTO_TCP);
+    if (INVALID_SOCKET == listen_s)
+      break;   /* can't create even single socket */
+
+    listen_addr.sin_family = AF_INET;
+    listen_addr.sin_port = 0;   /* same as htons(0) */
+    listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+    if ( ((0 == bind (listen_s,
+                      (struct sockaddr *) &listen_addr,
+                      c_addinlen)) &&
+          (0 == listen (listen_s,
+                        1) ) &&
+          (0 == getsockname (listen_s,
+                             (struct sockaddr *) &listen_addr,
+                             &addr_len))) )
+    {
+      SOCKET client_s = socket (AF_INET,
+                                SOCK_STREAM,
+                                IPPROTO_TCP);
+      struct sockaddr_in accepted_from_addr;
+      struct sockaddr_in client_addr;
+      SOCKET server_s;
+
+      if (INVALID_SOCKET == client_s)
+      {
+        /* try again */
+        closesocket (listen_s);
+        continue;
+      }
+
+      if ( (0 != ioctlsocket (client_s,
+                              FIONBIO,
+                              &on_val)) ||
+           ( (0 != connect (client_s,
+                            (struct sockaddr *) &listen_addr,
+                            c_addinlen)) &&
+             (WSAGetLastError () != WSAEWOULDBLOCK)) )
+      {
+        /* try again */
+        closesocket (listen_s);
+        closesocket (client_s);
+        continue;
+      }
+
+      addr_len = c_addinlen;
+      server_s = accept (listen_s,
+                         (struct sockaddr *) &accepted_from_addr,
+                         &addr_len);
+      if (INVALID_SOCKET == server_s)
+      {
+        /* try again */
+        closesocket (listen_s);
+        closesocket (client_s);
+        continue;
+      }
+
+      addr_len = c_addinlen;
+      if ( (0 == getsockname (client_s,
+                              (struct sockaddr *) &client_addr,
+                              &addr_len)) &&
+           (accepted_from_addr.sin_family == client_addr.sin_family) &&
+           (accepted_from_addr.sin_port == client_addr.sin_port) &&
+           (accepted_from_addr.sin_addr.s_addr ==
+            client_addr.sin_addr.s_addr) &&
+           ( (0 != non_blk) ?
+             (0 == ioctlsocket (server_s,
+                                FIONBIO,
+                                &on_val)) :
+             (0 == ioctlsocket (client_s,
+                                FIONBIO,
+                                &off_val)) ) )
+      {
+        closesocket (listen_s);
+        sockets_pair[0] = server_s;
+        sockets_pair[1] = client_s;
+        return ! 0;
+      }
+      closesocket (server_s);
+      closesocket (client_s);
+    }
+    closesocket (listen_s);
+  }
+
+  sockets_pair[0] = INVALID_SOCKET;
+  sockets_pair[1] = INVALID_SOCKET;
+  WSASetLastError (WSAECONNREFUSED);
+
+  return 0;
+}
+
+
+#endif /* MHD_WINSOCK_SOCKETS */
+
+
+/**
+ * Add @a fd to the @a set.  If @a fd is
+ * greater than @a max_fd, set @a max_fd to @a fd.
+ *
+ * @param fd file descriptor to add to the @a set
+ * @param set set to modify
+ * @param max_fd maximum value to potentially update
+ * @param fd_setsize value of FD_SETSIZE
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_add_to_fd_set_ (MHD_socket fd,
+                    fd_set *set,
+                    MHD_socket *max_fd,
+                    unsigned int fd_setsize)
+{
+  if ( (NULL == set) ||
+       (MHD_INVALID_SOCKET == fd) )
+    return 0;
+  if (! MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (fd,
+                                         set,
+                                         fd_setsize))
+    return 0;
+  MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_ (fd,
+                                     set,
+                                     fd_setsize);
+  if ( (NULL != max_fd) &&
+       ( (fd > *max_fd) ||
+         (MHD_INVALID_SOCKET == *max_fd) ) )
+    *max_fd = fd;
+  return ! 0;
+}
+
+
+/**
+ * Change socket options to be non-blocking.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_socket_nonblocking_ (MHD_socket sock)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (sock,
+                 F_GETFL);
+  if (-1 == flags)
+    return 0;
+
+  if ( ((flags | O_NONBLOCK) != flags) &&
+       (0 != fcntl (sock,
+                    F_SETFL,
+                    flags | O_NONBLOCK)) )
+    return 0;
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 1;
+
+  if (0 != ioctlsocket (sock,
+                        FIONBIO,
+                        &flags))
+    return 0;
+#endif /* MHD_WINSOCK_SOCKETS */
+  return ! 0;
+}
+
+
+/**
+ * Change socket options to be non-inheritable.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ * @warning Does not set socket error on W32.
+ */
+int
+MHD_socket_noninheritable_ (MHD_socket sock)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (sock,
+                 F_GETFD);
+  if (-1 == flags)
+    return 0;
+
+  if ( ((flags | FD_CLOEXEC) != flags) &&
+       (0 != fcntl (sock,
+                    F_SETFD,
+                    flags | FD_CLOEXEC)) )
+    return 0;
+#elif defined(MHD_WINSOCK_SOCKETS)
+  if (! SetHandleInformation ((HANDLE) sock,
+                              HANDLE_FLAG_INHERIT,
+                              0))
+    return 0;
+#endif /* MHD_WINSOCK_SOCKETS */
+  return ! 0;
+}
+
+
+/**
+ * Create a listen socket, with noninheritable flag if possible.
+ *
+ * @param pf protocol family to use
+ * @return created socket or MHD_INVALID_SOCKET in case of errors
+ */
+MHD_socket
+MHD_socket_create_listen_ (int pf)
+{
+  MHD_socket fd;
+  int cloexec_set;
+
+#if defined(MHD_POSIX_SOCKETS) && defined(SOCK_CLOEXEC)
+  fd = socket (pf,
+               SOCK_STREAM | SOCK_CLOEXEC,
+               0);
+  cloexec_set = ! 0;
+#elif defined(MHD_WINSOCK_SOCKETS) && defined (WSA_FLAG_NO_HANDLE_INHERIT)
+  fd = WSASocketW (pf,
+                   SOCK_STREAM,
+                   0,
+                   NULL,
+                   0,
+                   WSA_FLAG_NO_HANDLE_INHERIT);
+  cloexec_set = ! 0;
+#else  /* !SOCK_CLOEXEC */
+  fd = MHD_INVALID_SOCKET;
+#endif /* !SOCK_CLOEXEC */
+  if (MHD_INVALID_SOCKET == fd)
+  {
+    fd = socket (pf,
+                 SOCK_STREAM,
+                 0);
+    cloexec_set = 0;
+  }
+  if (MHD_INVALID_SOCKET == fd)
+    return MHD_INVALID_SOCKET;
+#ifdef MHD_socket_nosignal_
+  if (! MHD_socket_nosignal_ (fd))
+  {
+    const int err = MHD_socket_get_error_ ();
+    (void) MHD_socket_close_ (fd);
+    MHD_socket_fset_error_ (err);
+    return MHD_INVALID_SOCKET;
+  }
+#endif /* MHD_socket_nosignal_ */
+  if (! cloexec_set)
+    (void) MHD_socket_noninheritable_ (fd);
+
+  return fd;
+}
diff --git a/src/lib/mhd_sockets.h b/src/lib/mhd_sockets.h
new file mode 100644
index 0000000..bba6e7d
--- /dev/null
+++ b/src/lib/mhd_sockets.h
@@ -0,0 +1,804 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_sockets.c
+ * @brief  Header for platform-independent sockets abstraction
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Provides basic abstraction for sockets.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ */
+
+#ifndef MHD_SOCKETS_H
+#define MHD_SOCKETS_H 1
+#include "mhd_options.h"
+
+#include <errno.h>
+
+#if ! defined(MHD_POSIX_SOCKETS) && ! defined(MHD_WINSOCK_SOCKETS)
+#  if ! defined(_WIN32) || defined(__CYGWIN__)
+#    define MHD_POSIX_SOCKETS 1
+#  else  /* defined(_WIN32) && !defined(__CYGWIN__) */
+#    define MHD_WINSOCK_SOCKETS 1
+#  endif /* defined(_WIN32) && !defined(__CYGWIN__) */
+#endif /* !MHD_POSIX_SOCKETS && !MHD_WINSOCK_SOCKETS */
+
+/*
+ * MHD require headers that define socket type, socket basic functions
+ * (socket(), accept(), listen(), bind(), send(), recv(), select()), socket
+ * parameters like SOCK_CLOEXEC, SOCK_NONBLOCK, additional socket functions
+ * (poll(), epoll(), accept4()), struct timeval and other types, required
+ * for socket function.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  ifdef HAVE_SYS_TYPES_H
+#    include <sys/types.h> /* required on old platforms */
+#  endif
+#  ifdef HAVE_SYS_SOCKET_H
+#    include <sys/socket.h>
+#  endif
+#  if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS)
+#    ifdef HAVE_SOCKLIB_H
+#      include <sockLib.h>
+#    endif /* HAVE_SOCKLIB_H */
+#    ifdef HAVE_INETLIB_H
+#      include <inetLib.h>
+#    endif /* HAVE_INETLIB_H */
+#    include <strings.h>  /* required for FD_SET (bzero() function) */
+#  endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */
+#  ifdef HAVE_NETINET_IN_H
+#    include <netinet/in.h>
+#  endif /* HAVE_NETINET_IN_H */
+#  ifdef HAVE_ARPA_INET_H
+#    include <arpa/inet.h>
+#  endif
+#  ifdef HAVE_NET_IF_H
+#    include <net/if.h>
+#  endif
+#  ifdef HAVE_SYS_TIME_H
+#    include <sys/time.h>
+#  endif
+#  ifdef HAVE_TIME_H
+#    include <time.h>
+#  endif
+#  ifdef HAVE_NETDB_H
+#    include <netdb.h>
+#  endif
+#  ifdef HAVE_SYS_SELECT_H
+#    include <sys/select.h>
+#  endif
+#  ifdef EPOLL_SUPPORT
+#    include <sys/epoll.h>
+#  endif
+#  ifdef HAVE_NETINET_TCP_H
+/* for TCP_FASTOPEN and TCP_CORK */
+#    include <netinet/tcp.h>
+#  endif
+#  ifdef HAVE_STRING_H
+#    include <string.h> /* for strerror() */
+#  endif
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
+#  endif /* !WIN32_LEAN_AND_MEAN */
+#  include <winsock2.h>
+#  include <ws2tcpip.h>
+#endif /* MHD_WINSOCK_SOCKETS */
+
+#if defined(HAVE_POLL_H) && defined(HAVE_POLL)
+#  include <poll.h>
+#endif
+
+#include <stddef.h>
+#if defined(_MSC_FULL_VER) && ! defined (_SSIZE_T_DEFINED)
+#  include <stdint.h>
+#  define _SSIZE_T_DEFINED
+typedef intptr_t ssize_t;
+#endif /* !_SSIZE_T_DEFINED */
+
+#include "mhd_limits.h"
+
+#ifdef _MHD_FD_SETSIZE_IS_DEFAULT
+#  define _MHD_SYS_DEFAULT_FD_SETSIZE FD_SETSIZE
+#else  /* ! _MHD_FD_SETSIZE_IS_DEFAULT */
+#  include "sysfdsetsize.h"
+#  define _MHD_SYS_DEFAULT_FD_SETSIZE get_system_fdsetsize_value ()
+#endif /* ! _MHD_FD_SETSIZE_IS_DEFAULT */
+
+#ifndef MHD_PANIC
+#  include <stdio.h>
+#  include <stdlib.h>
+/* Simple implementation of MHD_PANIC, to be used outside lib */
+#  define MHD_PANIC(msg) do { fprintf (stderr,           \
+                                       "Abnormal termination at %d line in file %s: %s\n", \
+                                       (int) __LINE__, __FILE__, msg); abort (); \
+} while (0)
+#endif /* ! MHD_PANIC */
+
+#ifndef MHD_SOCKET_DEFINED
+/**
+ * MHD_socket is type for socket FDs
+ */
+#  if defined(MHD_POSIX_SOCKETS)
+typedef int MHD_socket;
+#    define MHD_INVALID_SOCKET (-1)
+#  elif defined(MHD_WINSOCK_SOCKETS)
+typedef SOCKET MHD_socket;
+#    define MHD_INVALID_SOCKET (INVALID_SOCKET)
+#  endif /* MHD_WINSOCK_SOCKETS */
+
+#  define MHD_SOCKET_DEFINED 1
+#endif /* ! MHD_SOCKET_DEFINED */
+
+#ifdef SOCK_CLOEXEC
+#  define MAYBE_SOCK_CLOEXEC SOCK_CLOEXEC
+#else  /* ! SOCK_CLOEXEC */
+#  define MAYBE_SOCK_CLOEXEC 0
+#endif /* ! SOCK_CLOEXEC */
+
+#ifdef HAVE_SOCK_NONBLOCK
+#  define MAYBE_SOCK_NONBLOCK SOCK_NONBLOCK
+#else  /* ! HAVE_SOCK_NONBLOCK */
+#  define MAYBE_SOCK_NONBLOCK 0
+#endif /* ! HAVE_SOCK_NONBLOCK */
+
+#ifdef MSG_NOSIGNAL
+#  define MAYBE_MSG_NOSIGNAL MSG_NOSIGNAL
+#else  /* ! MSG_NOSIGNAL */
+#  define MAYBE_MSG_NOSIGNAL 0
+#endif /* ! MSG_NOSIGNAL */
+
+#if ! defined(SHUT_WR) && defined(SD_SEND)
+#  define SHUT_WR SD_SEND
+#endif
+#if ! defined(SHUT_RD) && defined(SD_RECEIVE)
+#  define SHUT_RD SD_RECEIVE
+#endif
+#if ! defined(SHUT_RDWR) && defined(SD_BOTH)
+#  define SHUT_RDWR SD_BOTH
+#endif
+
+#if HAVE_ACCEPT4 + 0 != 0 && (defined(HAVE_SOCK_NONBLOCK) || \
+  defined(SOCK_CLOEXEC))
+#  define USE_ACCEPT4 1
+#endif
+
+#if defined(HAVE_EPOLL_CREATE1) && defined(EPOLL_CLOEXEC)
+#  define USE_EPOLL_CREATE1 1
+#endif /* HAVE_EPOLL_CREATE1 && EPOLL_CLOEXEC */
+
+#ifdef TCP_FASTOPEN
+/**
+ * Default TCP fastopen queue size.
+ */
+#define MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT 10
+#endif
+
+
+/**
+ * MHD_SCKT_OPT_BOOL_ is type for bool parameters for setsockopt()/getsockopt()
+ */
+#ifdef MHD_POSIX_SOCKETS
+typedef int MHD_SCKT_OPT_BOOL_;
+#else /* MHD_WINSOCK_SOCKETS */
+typedef BOOL MHD_SCKT_OPT_BOOL_;
+#endif /* MHD_WINSOCK_SOCKETS */
+
+/**
+ * MHD_SCKT_SEND_SIZE_ is type used to specify size for send and recv
+ * functions
+ */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+typedef size_t MHD_SCKT_SEND_SIZE_;
+#else
+typedef int MHD_SCKT_SEND_SIZE_;
+#endif
+
+/**
+ * MHD_SCKT_SEND_MAX_SIZE_ is maximum send()/recv() size value.
+ */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_SEND_MAX_SIZE_ SSIZE_MAX
+#else
+#  define MHD_SCKT_SEND_MAX_SIZE_ INT_MAX
+#endif
+
+/**
+ * MHD_socket_close_(fd) close any FDs (non-W32) / close only socket
+ * FDs (W32).  Note that on HP-UNIX, this function may leak the FD if
+ * errno is set to EINTR.  Do not use HP-UNIX.
+ *
+ * @param fd descriptor to close
+ * @return boolean true on success (error codes like EINTR and EIO are
+ *         counted as success, only EBADF counts as an error!),
+ *         boolean false otherwise.
+ */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_close_(fd) ((0 == close ((fd))) || (EBADF != errno))
+#else
+#  define MHD_socket_close_(fd) (0 == closesocket ((fd)))
+#endif
+
+/**
+ * MHD_socket_close_chk_(fd) close socket and abort execution
+ * if error is detected.
+ * @param fd socket to close
+ */
+#define MHD_socket_close_chk_(fd) do {        \
+    if (! MHD_socket_close_ (fd))               \
+      MHD_PANIC (_ ("Close socket failed.\n")); \
+} while (0)
+
+
+/**
+ * MHD_send_ is wrapper for system's send()
+ * @param s the socket to use
+ * @param b the buffer with data to send
+ * @param l the length of data in @a b
+ * @return ssize_t type value
+ */
+#define MHD_send_(s,b,l) \
+  ((ssize_t) send ((s),(const void*) (b),((MHD_SCKT_SEND_SIZE_) l), \
+                   MAYBE_MSG_NOSIGNAL))
+
+
+/**
+ * MHD_recv_ is wrapper for system's recv()
+ * @param s the socket to use
+ * @param b the buffer for data to receive
+ * @param l the length of @a b
+ * @return ssize_t type value
+ */
+#define MHD_recv_(s,b,l) \
+  ((ssize_t) recv ((s),(void*) (b),((MHD_SCKT_SEND_SIZE_) l), 0))
+
+
+/**
+ * Check whether FD can be added to fd_set with specified FD_SETSIZE.
+ * @param fd   the fd to check
+ * @param pset the pointer to fd_set to check or NULL to check
+ *             whether FD can be used with fd_sets.
+ * @param setsize the value of FD_SETSIZE.
+ * @return boolean true if FD can be added to fd_set,
+ *         boolean false otherwise.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) ((fd) < \
+                                                            ((MHD_socket) \
+                                                             setsize))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) ( ((void*) (pset)== \
+                                                              (void*) 0) || \
+                                                             (((fd_set*) (pset)) \
+                                                              ->fd_count < \
+                                                              ((unsigned) \
+                                                               setsize)) || \
+                                                             (FD_ISSET ((fd), \
+                                                                        (pset))) )
+#endif
+
+/**
+ * Check whether FD can be added to fd_set with current FD_SETSIZE.
+ * @param fd   the fd to check
+ * @param pset the pointer to fd_set to check or NULL to check
+ *             whether FD can be used with fd_sets.
+ * @return boolean true if FD can be added to fd_set,
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_FD_FITS_FDSET_(fd,pset) MHD_SCKT_FD_FITS_FDSET_SETSIZE_ ((fd), \
+                                                                          (pset), \
+                                                                          FD_SETSIZE)
+
+/**
+ * Add FD to fd_set with specified FD_SETSIZE.
+ * @param fd   the fd to add
+ * @param pset the valid pointer to fd_set.
+ * @param setsize the value of FD_SETSIZE.
+ * @note  To work on W32 with value of FD_SETSIZE different from currently defined value,
+ *        system definition of FD_SET() is not used.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize) FD_SET ((fd), \
+                                                                     (pset))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize)                     \
+  do {                                                                     \
+    u_int _i_ = 0;                                                        \
+    fd_set*const _s_ = (fd_set*) (pset);                                  \
+    while ((_i_ < _s_->fd_count) && ((fd) != _s_->fd_array [_i_])) {++_i_;} \
+    if ((_i_ == _s_->fd_count)) {_s_->fd_array [_s_->fd_count ++] = (fd);}  \
+  } while (0)
+#endif
+
+/* MHD_SYS_select_ is wrapper macro for system select() function */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SYS_select_(n,r,w,e,t) select ((n),(r),(w),(e),(t))
+#else
+#  define MHD_SYS_select_(n,r,w,e,t) \
+  ( ( (((void*) (r) == (void*) 0) || ((fd_set*) (r))->fd_count == 0) &&  \
+      (((void*) (w) == (void*) 0) || ((fd_set*) (w))->fd_count == 0) &&  \
+      (((void*) (e) == (void*) 0) || ((fd_set*) (e))->fd_count == 0) ) ? \
+    ( ((void*) (t) == (void*) 0) ? 0 :                                  \
+      (Sleep (((struct timeval*) (t))->tv_sec * 1000                    \
+              + ((struct timeval*) (t))->tv_usec / 1000), 0) ) :          \
+    (select ((int) 0,(r),(w),(e),(t))) )
+#endif
+
+#if defined(HAVE_POLL)
+/* MHD_sys_poll_ is wrapper macro for system poll() function */
+#  if ! defined(MHD_WINSOCK_SOCKETS)
+#    define MHD_sys_poll_ poll
+#  else  /* MHD_WINSOCK_SOCKETS */
+#    define MHD_sys_poll_ WSAPoll
+#  endif /* MHD_WINSOCK_SOCKETS */
+
+#  ifdef POLLPRI
+#    define MHD_POLLPRI_OR_ZERO POLLPRI
+#  else  /* ! POLLPRI */
+#    define MHD_POLLPRI_OR_ZERO 0
+#  endif /* ! POLLPRI */
+#  ifdef POLLRDBAND
+#    define MHD_POLLRDBAND_OR_ZERO POLLRDBAND
+#  else  /* ! POLLRDBAND */
+#    define MHD_POLLRDBAND_OR_ZERO 0
+#  endif /* ! POLLRDBAND */
+#  ifdef POLLNVAL
+#    define MHD_POLLNVAL_OR_ZERO POLLNVAL
+#  else  /* ! POLLNVAL */
+#    define MHD_POLLNVAL_OR_ZERO 0
+#  endif /* ! POLLNVAL */
+
+/* MHD_POLL_EVENTS_ERR_DISC is 'events' mask for errors and disconnect.
+ * Note: Out-of-band data is treated as error. */
+#  if defined(_WIN32) && ! defined(__CYGWIN__)
+#    define MHD_POLL_EVENTS_ERR_DISC POLLRDBAND
+#  elif defined(__linux__)
+#    define MHD_POLL_EVENTS_ERR_DISC POLLPRI
+#  else /* ! __linux__ */
+#    define MHD_POLL_EVENTS_ERR_DISC (MHD_POLLPRI_OR_ZERO \
+                                      | MHD_POLLRDBAND_OR_ZERO)
+#  endif /* ! __linux__ */
+/* MHD_POLL_REVENTS_ERR_DISC is 'revents' mask for errors and disconnect.
+ * Note: Out-of-band data is treated as error. */
+#  define MHD_POLL_REVENTS_ERR_DISC \
+  (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \
+   | POLLERR | POLLHUP)
+/* MHD_POLL_REVENTS_ERRROR is 'revents' mask for errors.
+ * Note: Out-of-band data is treated as error. */
+#  define MHD_POLL_REVENTS_ERRROR \
+  (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \
+   | POLLERR)
+#endif /* HAVE_POLL */
+
+#define MHD_SCKT_MISSING_ERR_CODE_ 31450
+
+#if defined(MHD_POSIX_SOCKETS)
+#  if defined(EAGAIN)
+#    define MHD_SCKT_EAGAIN_      EAGAIN
+#  elif defined(EWOULDBLOCK)
+#    define MHD_SCKT_EAGAIN_      EWOULDBLOCK
+#  else  /* !EAGAIN && !EWOULDBLOCK */
+#    define MHD_SCKT_EAGAIN_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* !EAGAIN && !EWOULDBLOCK */
+#  if defined(EWOULDBLOCK)
+#    define MHD_SCKT_EWOULDBLOCK_ EWOULDBLOCK
+#  elif defined(EAGAIN)
+#    define MHD_SCKT_EWOULDBLOCK_ EAGAIN
+#  else  /* !EWOULDBLOCK && !EAGAIN */
+#    define MHD_SCKT_EWOULDBLOCK_ MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* !EWOULDBLOCK && !EAGAIN */
+#  ifdef EINTR
+#    define MHD_SCKT_EINTR_       EINTR
+#  else  /* ! EINTR */
+#    define MHD_SCKT_EINTR_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EINTR */
+#  ifdef ECONNRESET
+#    define MHD_SCKT_ECONNRESET_  ECONNRESET
+#  else  /* ! ECONNRESET */
+#    define MHD_SCKT_ECONNRESET_  MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ECONNRESET */
+#  ifdef ECONNABORTED
+#    define MHD_SCKT_ECONNABORTED_  ECONNABORTED
+#  else  /* ! ECONNABORTED */
+#    define MHD_SCKT_ECONNABORTED_  MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ECONNABORTED */
+#  ifdef ENOTCONN
+#    define MHD_SCKT_ENOTCONN_    ENOTCONN
+#  else  /* ! ENOTCONN */
+#    define MHD_SCKT_ENOTCONN_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOTCONN */
+#  ifdef EMFILE
+#    define MHD_SCKT_EMFILE_      EMFILE
+#  else  /* ! EMFILE */
+#    define MHD_SCKT_EMFILE_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EMFILE */
+#  ifdef ENFILE
+#    define MHD_SCKT_ENFILE_      ENFILE
+#  else  /* ! ENFILE */
+#    define MHD_SCKT_ENFILE_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENFILE */
+#  ifdef ENOMEM
+#    define MHD_SCKT_ENOMEM_      ENOMEM
+#  else  /* ! ENOMEM */
+#    define MHD_SCKT_ENOMEM_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOMEM */
+#  ifdef ENOBUFS
+#    define MHD_SCKT_ENOBUFS_     ENOBUFS
+#  else  /* ! ENOBUFS */
+#    define MHD_SCKT_ENOBUFS_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOBUFS */
+#  ifdef EBADF
+#    define MHD_SCKT_EBADF_       EBADF
+#  else  /* ! EBADF */
+#    define MHD_SCKT_EBADF_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EBADF */
+#  ifdef ENOTSOCK
+#    define MHD_SCKT_ENOTSOCK_    ENOTSOCK
+#  else  /* ! ENOTSOCK */
+#    define MHD_SCKT_ENOTSOCK_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOTSOCK */
+#  ifdef EINVAL
+#    define MHD_SCKT_EINVAL_      EINVAL
+#  else  /* ! EINVAL */
+#    define MHD_SCKT_EINVAL_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EINVAL */
+#  ifdef EFAULT
+#    define MHD_SCKT_EFAUL_       EFAULT
+#  else  /* ! EFAULT */
+#    define MHD_SCKT_EFAUL_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EFAULT */
+#  ifdef ENOSYS
+#    define MHD_SCKT_ENOSYS_      ENOSYS
+#  else  /* ! ENOSYS */
+#    define MHD_SCKT_ENOSYS_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOSYS */
+#  ifdef ENOTSUP
+#    define MHD_SCKT_ENOTSUP_     ENOTSUP
+#  else  /* ! ENOTSUP */
+#    define MHD_SCKT_ENOTSUP_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOTSUP */
+#  ifdef EOPNOTSUPP
+#    define MHD_SCKT_EOPNOTSUPP_  EOPNOTSUPP
+#  else  /* ! EOPNOTSUPP */
+#    define MHD_SCKT_EOPNOTSUPP_  MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EOPNOTSUPP */
+#  ifdef EACCES
+#    define MHD_SCKT_EACCESS_     EACCES
+#  else  /* ! EACCES */
+#    define MHD_SCKT_EACCESS_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EACCES */
+#  ifdef ENETDOWN
+#    define MHD_SCKT_ENETDOWN_    ENETDOWN
+#  else  /* ! ENETDOWN */
+#    define MHD_SCKT_ENETDOWN_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENETDOWN */
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_EAGAIN_        WSAEWOULDBLOCK
+#  define MHD_SCKT_EWOULDBLOCK_   WSAEWOULDBLOCK
+#  define MHD_SCKT_EINTR_         WSAEINTR
+#  define MHD_SCKT_ECONNRESET_    WSAECONNRESET
+#  define MHD_SCKT_ECONNABORTED_  WSAECONNABORTED
+#  define MHD_SCKT_ENOTCONN_      WSAENOTCONN
+#  define MHD_SCKT_EMFILE_        WSAEMFILE
+#  define MHD_SCKT_ENFILE_        MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_ENOMEM_        MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_ENOBUFS_       WSAENOBUFS
+#  define MHD_SCKT_EBADF_         WSAEBADF
+#  define MHD_SCKT_ENOTSOCK_      WSAENOTSOCK
+#  define MHD_SCKT_EINVAL_        WSAEINVAL
+#  define MHD_SCKT_EFAUL_         WSAEFAULT
+#  define MHD_SCKT_ENOSYS_        MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_ENOTSUP_       MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_EOPNOTSUPP_    WSAEOPNOTSUPP
+#  define MHD_SCKT_EACCESS_       WSAEACCES
+#  define MHD_SCKT_ENETDOWN_      WSAENETDOWN
+#endif
+
+/**
+ * MHD_socket_error_ return system native error code for last socket error.
+ * @return system error code for last socket error.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_socket_get_error_() (errno)
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_get_error_() WSAGetLastError ()
+#endif
+
+#ifdef MHD_WINSOCK_SOCKETS
+/* POSIX-W32 sockets compatibility functions */
+
+/**
+ * Return pointer to string description of specified WinSock error
+ * @param err the WinSock error code.
+ * @return pointer to string description of specified WinSock error.
+ */
+const char *MHD_W32_strerror_winsock_ (int err);
+
+#endif /* MHD_WINSOCK_SOCKETS */
+
+/* MHD_socket_last_strerr_ is description string of specified socket error code */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_socket_strerr_(err) strerror ((err))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_strerr_(err) MHD_W32_strerror_winsock_ ((err))
+#endif
+
+/* MHD_socket_last_strerr_ is description string of last errno (non-W32) /
+ *                            description string of last socket error (W32) */
+#define MHD_socket_last_strerr_() MHD_socket_strerr_ (MHD_socket_get_error_ ())
+
+/**
+ * MHD_socket_fset_error_() set socket system native error code.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_socket_fset_error_(err) (errno = (err))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_fset_error_(err) (WSASetLastError ((err)))
+#endif
+
+/**
+ * MHD_socket_try_set_error_() set socket system native error code if
+ * specified code is defined on system.
+ * @return non-zero if specified @a err code is defined on system
+ *         and error was set;
+ *         zero if specified @a err code is not defined on system
+ *         and error was not set.
+ */
+#define MHD_socket_try_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ != (err)) ? \
+                                         (MHD_socket_fset_error_ ((err)), ! 0) : \
+                                         0)
+
+/**
+ * MHD_socket_set_error_() set socket system native error code to
+ * specified code or replacement code if specified code is not
+ * defined on system.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  if defined(ENOSYS)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = ENOSYS) : (errno = (err)) )
+#  elif defined(EOPNOTSUPP)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = EOPNOTSUPP) : (errno = \
+                                                                   (err)) )
+#  elif defined (EFAULT)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = EFAULT) : (errno = (err)) )
+#  elif defined (EINVAL)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = EINVAL) : (errno = (err)) )
+#  else  /* !EOPNOTSUPP && !EFAULT && !EINVAL */
+#    warning \
+  No suitable replacement for missing socket error code is found. Edit this file and add replacement code which is defined on system.
+#    define MHD_socket_set_error_(err) (errno = (err))
+#  endif /* !EOPNOTSUPP && !EFAULT && !EINVAL*/
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                       (WSASetLastError ((WSAEOPNOTSUPP))) : \
+                                       (WSASetLastError ((err))) )
+#endif
+
+/**
+ * Check whether given socket error is equal to specified system
+ * native MHD_SCKT_E*_ code.
+ * If platform don't have specific error code, result is
+ * always boolean false.
+ * @return boolean true if @a code is real error code and
+ *         @a err equals to MHD_SCKT_E*_ @a code;
+ *         boolean false otherwise
+ */
+#define MHD_SCKT_ERR_IS_(err,code) ( (MHD_SCKT_MISSING_ERR_CODE_ != (code)) && \
+                                     ((code) == (err)) )
+
+/**
+ * Check whether last socket error is equal to specified system
+ * native MHD_SCKT_E*_ code.
+ * If platform don't have specific error code, result is
+ * always boolean false.
+ * @return boolean true if @a code is real error code and
+ *         last socket error equals to MHD_SCKT_E*_ @a code;
+ *         boolean false otherwise
+ */
+#define MHD_SCKT_LAST_ERR_IS_(code) MHD_SCKT_ERR_IS_ (MHD_socket_get_error_ (), \
+                                                      (code))
+
+/* Specific error code checks */
+
+/**
+ * Check whether given socket error is equal to system's
+ * socket error codes for EINTR.
+ * @return boolean true if @a err is equal to sockets' EINTR code;
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_ERR_IS_EINTR_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EINTR_)
+
+/**
+ * Check whether given socket error is equal to system's
+ * socket error codes for EAGAIN or EWOULDBLOCK.
+ * @return boolean true if @a err is equal to sockets' EAGAIN or EWOULDBLOCK codes;
+ *         boolean false otherwise.
+ */
+#if MHD_SCKT_EAGAIN_ == MHD_SCKT_EWOULDBLOCK_
+#  define MHD_SCKT_ERR_IS_EAGAIN_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EAGAIN_)
+#else  /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */
+#  define MHD_SCKT_ERR_IS_EAGAIN_(err) (MHD_SCKT_ERR_IS_ ((err), \
+                                                          MHD_SCKT_EAGAIN_) || \
+                                        MHD_SCKT_ERR_IS_ ((err), \
+                                                          MHD_SCKT_EWOULDBLOCK_) )
+#endif /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */
+
+/**
+ * Check whether given socket error is any kind of "low resource" error.
+ * @return boolean true if @a err is any kind of "low resource" error,
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_ERR_IS_LOW_RESOURCES_(err) (MHD_SCKT_ERR_IS_ ((err), \
+                                                               MHD_SCKT_EMFILE_) \
+                                             || \
+                                             MHD_SCKT_ERR_IS_ ((err), \
+                                                               MHD_SCKT_ENFILE_) \
+                                             || \
+                                             MHD_SCKT_ERR_IS_ ((err), \
+                                                               MHD_SCKT_ENOMEM_) \
+                                             || \
+                                             MHD_SCKT_ERR_IS_ ((err), \
+                                                               MHD_SCKT_ENOBUFS_) )
+
+/**
+ * Check whether is given socket error is type of "incoming connection
+ * was disconnected before 'accept()' is called".
+ * @return boolean true is @a err match described socket error code,
+ *         boolean false otherwise.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) MHD_SCKT_ERR_IS_ ((err), \
+                                                                       MHD_SCKT_ECONNABORTED_)
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) MHD_SCKT_ERR_IS_ ((err), \
+                                                                       MHD_SCKT_ECONNRESET_)
+#endif
+
+/**
+ * Check whether is given socket error is type of "connection was terminated
+ * by remote side".
+ * @return boolean true is @a err match described socket error code,
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_ERR_IS_REMOTE_DISCNN_(err) (MHD_SCKT_ERR_IS_ ((err), \
+                                                               MHD_SCKT_ECONNRESET_) \
+                                             || \
+                                             MHD_SCKT_ERR_IS_ ((err), \
+                                                               MHD_SCKT_ECONNABORTED_))
+
+/* Specific error code set */
+
+/**
+ * Set socket's error code to ENOMEM or equivalent if ENOMEM is not
+ * available on platform.
+ */
+#if MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOMEM_
+#  define MHD_socket_set_error_to_ENOMEM() MHD_socket_set_error_ ( \
+    MHD_SCKT_ENOMEM_)
+#elif MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOBUFS_
+#  define MHD_socket_set_error_to_ENOMEM() MHD_socket_set_error_ ( \
+    MHD_SCKT_ENOBUFS_)
+#else
+#  warning \
+  No suitable replacement for ENOMEM error codes is found. Edit this file and add replacement code which is defined on system.
+#  define MHD_socket_set_error_to_ENOMEM() MHD_socket_set_error_ ( \
+    MHD_SCKT_ENOMEM_)
+#endif
+
+/* Socket functions */
+
+#if defined(AF_LOCAL)
+#  define MHD_SCKT_LOCAL AF_LOCAL
+#elif defined(AF_UNIX)
+#  define MHD_SCKT_LOCAL AF_UNIX
+#endif /* AF_UNIX */
+
+#if defined(MHD_POSIX_SOCKETS) && defined(MHD_SCKT_LOCAL)
+#  define MHD_socket_pair_(fdarr) (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM, 0, \
+                                                 (fdarr)))
+#  if defined(HAVE_SOCK_NONBLOCK)
+#    define MHD_socket_pair_nblk_(fdarr) (! socketpair (MHD_SCKT_LOCAL, \
+                                                        SOCK_STREAM \
+                                                        | SOCK_NONBLOCK, 0, \
+                                                        (fdarr)))
+#  endif /* HAVE_SOCK_NONBLOCK*/
+#elif defined(MHD_WINSOCK_SOCKETS)
+/**
+ * Create pair of mutually connected TCP/IP sockets on loopback address
+ * @param sockets_pair array to receive resulted sockets
+ * @param non_blk if set to non-zero value, sockets created in non-blocking mode
+ *                otherwise sockets will be in blocking mode
+ * @return non-zero if succeeded, zero otherwise
+ */
+int MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk);
+
+#  define MHD_socket_pair_(fdarr) MHD_W32_socket_pair_ ((fdarr), 0)
+#  define MHD_socket_pair_nblk_(fdarr) MHD_W32_socket_pair_ ((fdarr), 1)
+#endif
+
+/**
+ * Add @a fd to the @a set.  If @a fd is
+ * greater than @a max_fd, set @a max_fd to @a fd.
+ *
+ * @param fd file descriptor to add to the @a set
+ * @param set set to modify
+ * @param max_fd maximum value to potentially update
+ * @param fd_setsize value of FD_SETSIZE
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_add_to_fd_set_ (MHD_socket fd,
+                    fd_set *set,
+                    MHD_socket *max_fd,
+                    unsigned int fd_setsize);
+
+
+/**
+ * Change socket options to be non-blocking.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_socket_nonblocking_ (MHD_socket sock);
+
+
+/**
+ * Change socket options to be non-inheritable.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ * @warning Does not set socket error on W32.
+ */
+int
+MHD_socket_noninheritable_ (MHD_socket sock);
+
+
+#if defined(SOL_SOCKET) && defined(SO_NOSIGPIPE)
+static const int _MHD_socket_int_one = 1;
+/**
+ * Change socket options to no signal on remote disconnect.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+#  define MHD_socket_nosignal_(sock) \
+  (! setsockopt ((sock),SOL_SOCKET,SO_NOSIGPIPE,&_MHD_socket_int_one, \
+                 sizeof(_MHD_socket_int_one)))
+#endif /* SOL_SOCKET && SO_NOSIGPIPE */
+
+/**
+ * Create a listen socket, with noninheritable flag if possible.
+ *
+ * @param pf protocol family to use
+ * @return created socket or MHD_INVALID_SOCKET in case of errors
+ */
+MHD_socket
+MHD_socket_create_listen_ (int pf);
+
+#endif /* ! MHD_SOCKETS_H */
diff --git a/src/lib/mhd_str.c b/src/lib/mhd_str.c
new file mode 100644
index 0000000..3232ea4
--- /dev/null
+++ b/src/lib/mhd_str.c
@@ -0,0 +1,788 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015, 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_str.c
+ * @brief  Functions implementations for string manipulating
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_str.h"
+
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+
+#include "mhd_limits.h"
+
+#ifdef MHD_FAVOR_SMALL_CODE
+#ifdef _MHD_static_inline
+#undef _MHD_static_inline
+#endif /* _MHD_static_inline */
+/* Do not force inlining and do not use macro functions, use normal static
+   functions instead.
+   This may give more flexibility for size optimizations. */
+#define _MHD_static_inline static
+#ifndef INLINE_FUNC
+#define INLINE_FUNC 1
+#endif /* !INLINE_FUNC */
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+/*
+ * Block of functions/macros that use US-ASCII charset as required by HTTP
+ * standards. Not affected by current locale settings.
+ */
+
+#ifdef INLINE_FUNC
+
+#if 0 /* Disable unused functions. */
+/**
+ * Check whether character is lower case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is lower case letter, zero otherwise
+ */
+_MHD_static_inline bool
+isasciilower (char c)
+{
+  return (c >= 'a') && (c <= 'z');
+}
+
+
+#endif /* Disable unused functions. */
+
+
+/**
+ * Check whether character is upper case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is upper case letter, zero otherwise
+ */
+_MHD_static_inline bool
+isasciiupper (char c)
+{
+  return (c >= 'A') && (c <= 'Z');
+}
+
+
+#if 0 /* Disable unused functions. */
+/**
+ * Check whether character is letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is letter in US-ASCII, zero otherwise
+ */
+_MHD_static_inline bool
+isasciialpha (char c)
+{
+  return isasciilower (c) || isasciiupper (c);
+}
+
+
+#endif /* Disable unused functions. */
+
+
+/**
+ * Check whether character is decimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is decimal digit, zero otherwise
+ */
+_MHD_static_inline bool
+isasciidigit (char c)
+{
+  return (c >= '0') && (c <= '9');
+}
+
+
+#if 0 /* Disable unused functions. */
+/**
+ * Check whether character is hexadecimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is decimal digit, zero otherwise
+ */
+_MHD_static_inline bool
+isasciixdigit (char c)
+{
+  return isasciidigit (c) ||
+         ( (c >= 'A') && (c <= 'F') ) ||
+         ( (c >= 'a') && (c <= 'f') );
+}
+
+
+/**
+ * Check whether character is decimal digit or letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is decimal digit or letter, zero otherwise
+ */
+_MHD_static_inline bool
+isasciialnum (char c)
+{
+  return isasciialpha (c) || isasciidigit (c);
+}
+
+
+#endif /* Disable unused functions. */
+
+
+/**
+ * Convert US-ASCII character to lower case.
+ * If character is upper case letter in US-ASCII than it's converted to lower
+ * case analog. If character is NOT upper case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to lower case character
+ */
+_MHD_static_inline char
+toasciilower (char c)
+{
+  return isasciiupper (c) ? (c - 'A' + 'a') : c;
+}
+
+
+#if 0 /* Disable unused functions. */
+/**
+ * Convert US-ASCII character to upper case.
+ * If character is lower case letter in US-ASCII than it's converted to upper
+ * case analog. If character is NOT lower case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to upper case character
+ */
+_MHD_static_inline char
+toasciiupper (char c)
+{
+  return isasciilower (c) ? (c - 'a' + 'A') : c;
+}
+
+
+#endif /* Disable unused functions. */
+
+
+#if defined(MHD_FAVOR_SMALL_CODE) /* Used only in MHD_str_to_uvalue_n_() */
+/**
+ * Convert US-ASCII decimal digit to its value.
+ *
+ * @param c character to convert
+ * @return value of decimal digit or -1 if @ c is not decimal digit
+ */
+_MHD_static_inline int
+todigitvalue (char c)
+{
+  if (isasciidigit (c))
+    return (unsigned char) (c - '0');
+
+  return -1;
+}
+
+
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Convert US-ASCII hexadecimal digit to its value.
+ *
+ * @param c character to convert
+ * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit
+ */
+_MHD_static_inline int
+toxdigitvalue (char c)
+{
+  if (isasciidigit (c))
+    return (unsigned char) (c - '0');
+  if ( (c >= 'A') && (c <= 'F') )
+    return (unsigned char) (c - 'A' + 10);
+  if ( (c >= 'a') && (c <= 'f') )
+    return (unsigned char) (c - 'a' + 10);
+
+  return -1;
+}
+
+
+#else  /* !INLINE_FUNC */
+
+
+/**
+ * Checks whether character is lower case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is lower case letter,
+ *         boolean false otherwise
+ */
+#define isasciilower(c) (((char) (c)) >= 'a' && ((char) (c)) <= 'z')
+
+
+/**
+ * Checks whether character is upper case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is upper case letter,
+ *         boolean false otherwise
+ */
+#define isasciiupper(c) (((char) (c)) >= 'A' && ((char) (c)) <= 'Z')
+
+
+/**
+ * Checks whether character is letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is letter, boolean false
+ *         otherwise
+ */
+#define isasciialpha(c) (isasciilower (c) || isasciiupper (c))
+
+
+/**
+ * Check whether character is decimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is decimal digit, boolean false
+ *         otherwise
+ */
+#define isasciidigit(c) (((char) (c)) >= '0' && ((char) (c)) <= '9')
+
+
+/**
+ * Check whether character is hexadecimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is hexadecimal digit,
+ *         boolean false otherwise
+ */
+#define isasciixdigit(c) (isasciidigit ((c)) || \
+                          (((char) (c)) >= 'A' && ((char) (c)) <= 'F') || \
+                          (((char) (c)) >= 'a' && ((char) (c)) <= 'f') )
+
+
+/**
+ * Check whether character is decimal digit or letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is decimal digit or letter,
+ *         boolean false otherwise
+ */
+#define isasciialnum(c) (isasciialpha (c) || isasciidigit (c))
+
+
+/**
+ * Convert US-ASCII character to lower case.
+ * If character is upper case letter in US-ASCII than it's converted to lower
+ * case analog. If character is NOT upper case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to lower case character
+ */
+#define toasciilower(c) ((isasciiupper (c)) ? (((char) (c)) - 'A' + 'a') : \
+                         ((char) (c)))
+
+
+/**
+ * Convert US-ASCII character to upper case.
+ * If character is lower case letter in US-ASCII than it's converted to upper
+ * case analog. If character is NOT lower case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to upper case character
+ */
+#define toasciiupper(c) ((isasciilower (c)) ? (((char) (c)) - 'a' + 'A') : \
+                         ((char) (c)))
+
+
+/**
+ * Convert US-ASCII decimal digit to its value.
+ *
+ * @param c character to convert
+ * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit
+ */
+#define todigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \
+                         (int) (-1))
+
+
+/**
+ * Convert US-ASCII hexadecimal digit to its value.
+ * @param c character to convert
+ * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit
+ */
+#define toxdigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \
+                          ( (((char) (c)) >= 'A' && ((char) (c)) <= 'F') ? \
+                            (int) (((unsigned char) (c)) - 'A' + 10) : \
+                            ( (((char) (c)) >= 'a' && ((char) (c)) <= 'f') ? \
+                              (int) (((unsigned char) (c)) - 'a' + 10) : \
+                              (int) (-1) )))
+#endif /* !INLINE_FUNC */
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters.
+ *
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_ (const char *str1,
+                         const char *str2)
+{
+  while (0 != (*str1))
+  {
+    const char c1 = *str1;
+    const char c2 = *str2;
+    if ( (c1 != c2) &&
+         (toasciilower (c1) != toasciilower (c2)) )
+      return 0;
+    str1++;
+    str2++;
+  }
+  return 0 == (*str2);
+}
+
+
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters and
+ * checking not more than @a maxlen characters.
+ * Compares up to first terminating null character, but not more than
+ * first @a maxlen characters.
+ *
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @param maxlen maximum number of characters to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_n_ (const char *const str1,
+                           const char *const str2,
+                           size_t maxlen)
+{
+  size_t i;
+
+  for (i = 0; i < maxlen; ++i)
+  {
+    const char c1 = str1[i];
+    const char c2 = str2[i];
+    if (0 == c2)
+      return 0 == c1;
+    if ( (c1 != c2) &&
+         (toasciilower (c1) != toasciilower (c2)) )
+      return 0;
+  }
+  return ! 0;
+}
+
+
+/**
+ * Check whether @a str has case-insensitive @a token.
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Match succeed if substring between start, end (of string) or comma
+ * contains only case-insensitive token and optional spaces and tabs.
+ * @warning token must not contain null-charters except optional
+ *          terminating null-character.
+ * @param str the string to check
+ * @param token the token to find
+ * @param token_len length of token, not including optional terminating
+ *                  null-character.
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+bool
+MHD_str_has_token_caseless_ (const char *str,
+                             const char *const token,
+                             size_t token_len)
+{
+  if (0 == token_len)
+    return false;
+
+  while (0 != *str)
+  {
+    size_t i;
+    /* Skip all whitespaces and empty tokens. */
+    while (' ' == *str || '\t' == *str || ',' == *str)
+      str++;
+
+    /* Check for token match. */
+    i = 0;
+    while (1)
+    {
+      const char sc = *(str++);
+      const char tc = token[i++];
+
+      if (0 == sc)
+        return false;
+      if ( (sc != tc) &&
+           (toasciilower (sc) != toasciilower (tc)) )
+        break;
+      if (i >= token_len)
+      {
+        /* Check whether substring match token fully or
+         * has additional unmatched chars at tail. */
+        while (' ' == *str || '\t' == *str)
+          str++;
+        /* End of (sub)string? */
+        if ((0 == *str) || (',' == *str) )
+          return true;
+        /* Unmatched chars at end of substring. */
+        break;
+      }
+    }
+    /* Find next substring. */
+    while (0 != *str && ',' != *str)
+      str++;
+  }
+  return false;
+}
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/* Use individual function for each case */
+
+/**
+ * Convert decimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_ (const char *str,
+                    uint64_t *out_val)
+{
+  const char *const start = str;
+  uint64_t res;
+
+  if (! str || ! out_val || ! isasciidigit (str[0]))
+    return 0;
+
+  res = 0;
+  do
+  {
+    const int digit = (unsigned char) (*str) - '0';
+    if ( (res > (UINT64_MAX / 10)) ||
+         ( (res == (UINT64_MAX / 10)) &&
+           ((uint64_t) digit > (UINT64_MAX % 10)) ) )
+      return 0;
+
+    res *= 10;
+    res += digit;
+    str++;
+  } while (isasciidigit (*str));
+
+  *out_val = res;
+  return str - start;
+}
+
+
+/**
+ * Convert not more then @a maxlen decimal US-ASCII digits in string to
+ * number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_n_ (const char *str,
+                      size_t maxlen,
+                      uint64_t *out_val)
+{
+  uint64_t res;
+  size_t i;
+
+  if (! str || ! maxlen || ! out_val || ! isasciidigit (str[0]))
+    return 0;
+
+  res = 0;
+  i = 0;
+  do
+  {
+    const int digit = (unsigned char) str[i] - '0';
+
+    if ( (res > (UINT64_MAX / 10)) ||
+         ( (res == (UINT64_MAX / 10)) &&
+           ((uint64_t) digit > (UINT64_MAX % 10)) ) )
+      return 0;
+
+    res *= 10;
+    res += digit;
+    i++;
+  } while ( (i < maxlen) &&
+            isasciidigit (str[i]) );
+
+  *out_val = res;
+  return i;
+}
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint32_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_ (const char *str,
+                     uint32_t *out_val)
+{
+  const char *const start = str;
+  uint32_t res;
+  int digit;
+
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  digit = toxdigitvalue (*str);
+  while (digit >= 0)
+  {
+    if ( (res < (UINT32_MAX / 16)) ||
+         ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit <= (UINT32_MAX
+                                                               % 16)) ) )
+    {
+      res *= 16;
+      res += digit;
+    }
+    else
+      return 0;
+    str++;
+    digit = toxdigitvalue (*str);
+  }
+
+  if (str - start > 0)
+    *out_val = res;
+  return str - start;
+}
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint32_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_n_ (const char *str,
+                       size_t maxlen,
+                       uint32_t *out_val)
+{
+  size_t i;
+  uint32_t res;
+  int digit;
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  i = 0;
+  while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0)
+  {
+    if ( (res > (UINT32_MAX / 16)) ||
+         ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit > (UINT32_MAX
+                                                              % 16)) ) )
+      return 0;
+
+    res *= 16;
+    res += digit;
+    i++;
+  }
+
+  if (i)
+    *out_val = res;
+  return i;
+}
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_ (const char *str,
+                     uint64_t *out_val)
+{
+  const char *const start = str;
+  uint64_t res;
+  int digit;
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  digit = toxdigitvalue (*str);
+  while (digit >= 0)
+  {
+    if ( (res < (UINT64_MAX / 16)) ||
+         ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit <= (UINT64_MAX
+                                                               % 16)) ) )
+    {
+      res *= 16;
+      res += digit;
+    }
+    else
+      return 0;
+    str++;
+    digit = toxdigitvalue (*str);
+  }
+
+  if (str - start > 0)
+    *out_val = res;
+  return str - start;
+}
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_n_ (const char *str,
+                       size_t maxlen,
+                       uint64_t *out_val)
+{
+  size_t i;
+  uint64_t res;
+  int digit;
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  i = 0;
+  while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0)
+  {
+    if ( (res > (UINT64_MAX / 16)) ||
+         ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit > (UINT64_MAX
+                                                              % 16)) ) )
+      return 0;
+
+    res *= 16;
+    res += digit;
+    i++;
+  }
+
+  if (i)
+    *out_val = res;
+  return i;
+}
+
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+
+/**
+ * Generic function for converting not more then @a maxlen
+ * hexadecimal or decimal US-ASCII digits in string to number.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * To be used only within macro.
+ *
+ * @param str the string to convert
+ * @param maxlen the maximum number of characters to process
+ * @param out_val the pointer to variable to store result of conversion
+ * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8
+ * @param max_val the maximum decoded number
+ * @param base the numeric base, 10 or 16
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then @max_val, @val_size is not 16/32 or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uvalue_n_ (const char *str,
+                      size_t maxlen,
+                      void *out_val,
+                      size_t val_size,
+                      uint64_t max_val,
+                      int base)
+{
+  size_t i;
+  uint64_t res;
+  int digit;
+  const uint64_t max_v_div_b = max_val / base;
+  const uint64_t max_v_mod_b = max_val % base;
+  /* 'digit->value' must be function, not macro */
+  int (*const dfunc)(char) = (base == 16) ?
+                             toxdigitvalue : todigitvalue;
+
+  if (! str || ! out_val ||
+      ((base != 16) && (base != 10)) )
+    return 0;
+
+  res = 0;
+  i = 0;
+  while (maxlen > i && 0 <= (digit = dfunc (str[i])))
+  {
+    if ( ((max_v_div_b) < res) ||
+         (( (max_v_div_b) == res) && ( (max_v_mod_b) < (uint64_t) digit) ) )
+      return 0;
+
+    res *= base;
+    res += digit;
+    i++;
+  }
+
+  if (i)
+  {
+    if (8 == val_size)
+      *(uint64_t *) out_val = res;
+    else if (4 == val_size)
+      *(uint32_t *) out_val = (uint32_t) res;
+    else
+      return 0;
+  }
+  return i;
+}
+
+
+#endif /* MHD_FAVOR_SMALL_CODE */
diff --git a/src/lib/mhd_str.h b/src/lib/mhd_str.h
new file mode 100644
index 0000000..b6355c3
--- /dev/null
+++ b/src/lib/mhd_str.h
@@ -0,0 +1,276 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015, 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_str.h
+ * @brief  Header for string manipulating helpers
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_STR_H
+#define MHD_STR_H 1
+
+#include "mhd_options.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+#ifdef MHD_FAVOR_SMALL_CODE
+#include "mhd_limits.h"
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+/*
+ * Block of functions/macros that use US-ASCII charset as required by HTTP
+ * standards. Not affected by current locale settings.
+ */
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters.
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_ (const char *str1,
+                         const char *str2);
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+/* Reuse MHD_str_equal_caseless_n_() to reduce size */
+#define MHD_str_equal_caseless_(s1,s2) MHD_str_equal_caseless_n_ ((s1),(s2), \
+                                                                  SIZE_MAX)
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters and
+ * checking not more than @a maxlen characters.
+ * Compares up to first terminating null character, but not more than
+ * first @a maxlen characters.
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @param maxlen maximum number of characters to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_n_ (const char *const str1,
+                           const char *const str2,
+                           size_t maxlen);
+
+
+/**
+ * Check whether @a str has case-insensitive @a token.
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Match succeed if substring between start, end of string or comma
+ * contains only case-insensitive token and optional spaces and tabs.
+ * @warning token must not contain null-charters except optional
+ *          terminating null-character.
+ * @param str the string to check
+ * @param token the token to find
+ * @param token_len length of token, not including optional terminating
+ *                  null-character.
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+bool
+MHD_str_has_token_caseless_ (const char *str,
+                             const char *const token,
+                             size_t token_len);
+
+/**
+ * Check whether @a str has case-insensitive static @a tkn.
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Match succeed if substring between start, end of string or comma
+ * contains only case-insensitive token and optional spaces and tabs.
+ * @warning tkn must be static string
+ * @param str the string to check
+ * @param tkn the static string of token to find
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+#define MHD_str_has_s_token_caseless_(str,tkn) \
+  MHD_str_has_token_caseless_ ((str),(tkn),MHD_STATICSTR_LEN_ (tkn))
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/* Use individual function for each case to improve speed */
+
+/**
+ * Convert decimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ * @param str string to convert
+ * @param out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_ (const char *str,
+                    uint64_t *out_val);
+
+/**
+ * Convert not more then @a maxlen decimal US-ASCII digits in string to
+ * number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_n_ (const char *str,
+                      size_t maxlen,
+                      uint64_t *out_val);
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint32_t.
+ * Conversion stopped at first non-digit character.
+ * @param str string to convert
+ * @param out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_ (const char *str,
+                     uint32_t *out_val);
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint32_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_n_ (const char *str,
+                       size_t maxlen,
+                       uint32_t *out_val);
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ * @param str string to convert
+ * @param out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_ (const char *str,
+                     uint64_t *out_val);
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_n_ (const char *str,
+                       size_t maxlen,
+                       uint64_t *out_val);
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+/* Use one universal function and macros to reduce size */
+
+/**
+ * Generic function for converting not more then @a maxlen
+ * hexadecimal or decimal US-ASCII digits in string to number.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * To be used only within macro.
+ * @param str the string to convert
+ * @param maxlen the maximum number of characters to process
+ * @param out_val the pointer to uint64_t to store result of conversion
+ * @param val_size the size of variable pointed by @a out_val
+ * @param max_val the maximum decoded number
+ * @param base the numeric base, 10 or 16
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then @ max_val or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uvalue_n_ (const char *str,
+                      size_t maxlen,
+                      void *out_val,
+                      size_t val_size,
+                      uint64_t max_val,
+                      int base);
+
+#define MHD_str_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                       sizeof(uint64_t), \
+                                                       UINT64_MAX,10)
+
+#define MHD_str_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                            sizeof(uint64_t), \
+                                                            UINT64_MAX,10)
+
+#define MHD_strx_to_sizet_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                       sizeof(size_t),SIZE_MAX, \
+                                                       16)
+
+#define MHD_strx_to_sizet_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                            sizeof(size_t), \
+                                                            SIZE_MAX,16)
+
+#define MHD_strx_to_uint32_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                        sizeof(uint32_t), \
+                                                        UINT32_MAX,16)
+
+#define MHD_strx_to_uint32_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                             sizeof(uint32_t), \
+                                                             UINT32_MAX,16)
+
+#define MHD_strx_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                        sizeof(uint64_t), \
+                                                        UINT64_MAX,16)
+
+#define MHD_strx_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                             sizeof(uint64_t), \
+                                                             UINT64_MAX,16)
+
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+#endif /* MHD_STR_H */
diff --git a/src/lib/mhd_threads.c b/src/lib/mhd_threads.c
new file mode 100644
index 0000000..b6188cb
--- /dev/null
+++ b/src/lib/mhd_threads.c
@@ -0,0 +1,368 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_threads.c
+ * @brief  Implementation for thread functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_threads.h"
+#ifdef MHD_USE_W32_THREADS
+#include "mhd_limits.h"
+#include <process.h>
+#endif
+#ifdef MHD_USE_THREAD_NAME_
+#include <stdlib.h>
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif /* HAVE_PTHREAD_NP_H */
+#endif /* MHD_USE_THREAD_NAME_ */
+#include <errno.h>
+
+
+#ifndef MHD_USE_THREAD_NAME_
+
+#define MHD_set_thread_name_(t, n) (void)
+#define MHD_set_cur_thread_name_(n) (void)
+
+#else  /* MHD_USE_THREAD_NAME_ */
+
+#if defined(MHD_USE_POSIX_THREADS)
+#if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \
+  defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI)
+#  define MHD_USE_THREAD_ATTR_SETNAME 1
+#endif \
+  /* HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD || HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI */
+
+#if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \
+  defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) \
+  || defined(HAVE_PTHREAD_SETNAME_NP_NETBSD)
+
+/**
+ * Set thread name
+ *
+ * @param thread_id ID of thread
+ * @param thread_name name to set
+ * @return non-zero on success, zero otherwise
+ */
+static int
+MHD_set_thread_name_ (const MHD_thread_ID_ thread_id,
+                      const char *thread_name)
+{
+  if (NULL == thread_name)
+    return 0;
+
+#if defined(HAVE_PTHREAD_SETNAME_NP_GNU)
+  return ! pthread_setname_np (thread_id, thread_name);
+#elif defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD)
+  /* FreeBSD and OpenBSD use different name and void return type */
+  pthread_set_name_np (thread_id, thread_name);
+  return ! 0;
+#elif defined(HAVE_PTHREAD_SETNAME_NP_NETBSD)
+  /* NetBSD use 3 arguments: second argument is string in printf-like format,
+   *                         third argument is single argument for printf;
+   * OSF1 use 3 arguments too, but last one always must be zero (NULL).
+   * MHD doesn't use '%' in thread names, so both form are used in same way.
+   */return ! pthread_setname_np (thread_id, thread_name, 0);
+#endif /* HAVE_PTHREAD_SETNAME_NP_NETBSD */
+}
+
+
+#ifndef __QNXNTO__
+/**
+ * Set current thread name
+ * @param n name to set
+ * @return non-zero on success, zero otherwise
+ */
+#define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (pthread_self (),(n))
+#else  /* __QNXNTO__ */
+/* Special case for QNX Neutrino - using zero for thread ID sets name faster. */
+#define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (0,(n))
+#endif /* __QNXNTO__ */
+#elif defined(HAVE_PTHREAD_SETNAME_NP_DARWIN)
+
+/**
+ * Set current thread name
+ * @param n name to set
+ * @return non-zero on success, zero otherwise
+ */
+#define MHD_set_cur_thread_name_(n) (! (pthread_setname_np ((n))))
+#endif /* HAVE_PTHREAD_SETNAME_NP_DARWIN */
+
+#elif defined(MHD_USE_W32_THREADS)
+#ifndef _MSC_FULL_VER
+/* Thread name available only for VC-compiler */
+#else  /* _MSC_FULL_VER */
+/**
+ * Set thread name
+ *
+ * @param thread_id ID of thread, -1 for current thread
+ * @param thread_name name to set
+ * @return non-zero on success, zero otherwise
+ */
+static int
+MHD_set_thread_name_ (const MHD_thread_ID_ thread_id,
+                      const char *thread_name)
+{
+  static const DWORD VC_SETNAME_EXC = 0x406D1388;
+#pragma pack(push,8)
+  struct thread_info_struct
+  {
+    DWORD type;   /* Must be 0x1000. */
+    LPCSTR name;  /* Pointer to name (in user address space). */
+    DWORD ID;     /* Thread ID (-1 = caller thread). */
+    DWORD flags;  /* Reserved for future use, must be zero. */
+  } thread_info;
+#pragma pack(pop)
+
+  if (NULL == thread_name)
+    return 0;
+
+  thread_info.type  = 0x1000;
+  thread_info.name  = thread_name;
+  thread_info.ID    = thread_id;
+  thread_info.flags = 0;
+
+  __try
+  { /* This exception is intercepted by debugger */
+    RaiseException (VC_SETNAME_EXC,
+                    0,
+                    sizeof (thread_info) / sizeof(ULONG_PTR),
+                    (ULONG_PTR *) &thread_info);
+  }
+  __except (EXCEPTION_EXECUTE_HANDLER)
+  {}
+
+  return ! 0;
+}
+
+
+/**
+ * Set current thread name
+ * @param n name to set
+ * @return non-zero on success, zero otherwise
+ */
+#define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (-1,(n))
+#endif /* _MSC_FULL_VER */
+#endif /* MHD_USE_W32_THREADS */
+
+#endif /* MHD_USE_THREAD_NAME_ */
+
+
+/**
+ * Create a thread and set the attributes according to our options.
+ *
+ * @param thread        handle to initialize
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise (with errno set)
+ */
+int
+MHD_create_thread_ (MHD_thread_handle_ID_ *thread,
+                    size_t stack_size,
+                    MHD_THREAD_START_ROUTINE_ start_routine,
+                    void *arg)
+{
+#if defined(MHD_USE_POSIX_THREADS)
+  int res;
+
+  if (0 != stack_size)
+  {
+    pthread_attr_t attr;
+    res = pthread_attr_init (&attr);
+    if (0 == res)
+    {
+      res = pthread_attr_setstacksize (&attr,
+                                       stack_size);
+      if (0 == res)
+        res = pthread_create (&(thread->handle),
+                              &attr,
+                              start_routine,
+                              arg);
+      pthread_attr_destroy (&attr);
+    }
+  }
+  else
+    res = pthread_create (&(thread->handle),
+                          NULL,
+                          start_routine,
+                          arg);
+
+  if (0 != res)
+    errno = res;
+
+  return ! res;
+#elif defined(MHD_USE_W32_THREADS)
+#if SIZE_MAX != UINT_MAX
+  if (stack_size > UINT_MAX)
+  {
+    errno = EINVAL;
+    return 0;
+  }
+#endif /* SIZE_MAX != UINT_MAX */
+
+  thread->handle = (MHD_thread_handle_)
+                   _beginthreadex (NULL,
+                                   (unsigned int) stack_size,
+                                   start_routine,
+                                   arg,
+                                   0,
+                                   NULL);
+
+  if ((MHD_thread_handle_) - 1 == thread->handle)
+    return 0;
+
+  return ! 0;
+#endif
+}
+
+
+#ifdef MHD_USE_THREAD_NAME_
+
+#ifndef MHD_USE_THREAD_ATTR_SETNAME
+struct MHD_named_helper_param_
+{
+  /**
+   * Real thread start routine
+   */
+  MHD_THREAD_START_ROUTINE_ start_routine;
+
+  /**
+   * Argument for thread start routine
+   */
+  void *arg;
+
+  /**
+   * Name for thread
+   */
+  const char *name;
+};
+
+
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+named_thread_starter (void *data)
+{
+  struct MHD_named_helper_param_ *const param =
+    (struct MHD_named_helper_param_ *) data;
+  void *arg;
+  MHD_THREAD_START_ROUTINE_ thr_func;
+
+  if (NULL == data)
+    return (MHD_THRD_RTRN_TYPE_) 0;
+
+  MHD_set_cur_thread_name_ (param->name);
+
+  arg = param->arg;
+  thr_func = param->start_routine;
+  free (data);
+
+  return thr_func (arg);
+}
+
+
+#endif /* ! MHD_USE_THREAD_ATTR_SETNAME */
+
+
+/**
+ * Create a named thread and set the attributes according to our options.
+ *
+ * @param thread        handle to initialize
+ * @param thread_name   name for new thread
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise (with errno set)
+ */
+int
+MHD_create_named_thread_ (MHD_thread_handle_ID_ *thread,
+                          const char *thread_name,
+                          size_t stack_size,
+                          MHD_THREAD_START_ROUTINE_ start_routine,
+                          void *arg)
+{
+#if defined(MHD_USE_THREAD_ATTR_SETNAME)
+  int res;
+  pthread_attr_t attr;
+
+  res = pthread_attr_init (&attr);
+  if (0 == res)
+  {
+#if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD)
+    /* NetBSD use 3 arguments: second argument is string in printf-like format,
+     *                         third argument is single argument for printf;
+     * OSF1 use 3 arguments too, but last one always must be zero (NULL).
+     * MHD doesn't use '%' in thread names, so both form are used in same way.
+     */res = pthread_attr_setname_np (&attr, thread_name, 0);
+#elif defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI)
+    res = pthread_attr_setname_np (&attr, thread_name);
+#else
+#error No pthread_attr_setname_np() function.
+#endif
+    if ((res == 0) && (0 != stack_size) )
+      res = pthread_attr_setstacksize (&attr,
+                                       stack_size);
+    if (0 == res)
+      res = pthread_create (&(thread->handle),
+                            &attr,
+                            start_routine,
+                            arg);
+    pthread_attr_destroy (&attr);
+  }
+  if (0 != res)
+    errno = res;
+
+  return ! res;
+#else  /* ! MHD_USE_THREAD_ATTR_SETNAME */
+  struct MHD_named_helper_param_ *param;
+
+  if (NULL == thread_name)
+  {
+    errno = EINVAL;
+    return 0;
+  }
+
+  param = malloc (sizeof (struct MHD_named_helper_param_));
+  if (NULL == param)
+    return 0;
+
+  param->start_routine = start_routine;
+  param->arg = arg;
+  param->name = thread_name;
+
+  /* Set thread name in thread itself to avoid problems with
+   * threads which terminated before name is set in other thread.
+   */
+  if (! MHD_create_thread_ (thread,
+                            stack_size,
+                            &named_thread_starter,
+                            (void *) param))
+  {
+    free (param);
+    return 0;
+  }
+
+  return ! 0;
+#endif /* ! MHD_USE_THREAD_ATTR_SETNAME */
+}
+
+
+#endif /* MHD_USE_THREAD_NAME_ */
diff --git a/src/lib/mhd_threads.h b/src/lib/mhd_threads.h
new file mode 100644
index 0000000..3bf2410
--- /dev/null
+++ b/src/lib/mhd_threads.h
@@ -0,0 +1,237 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_threads.h
+ * @brief  Header for platform-independent threads abstraction
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Provides basic abstraction for threads.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ *
+ * @warning Unlike pthread functions, most of functions return
+ *          nonzero on success.
+ */
+
+#ifndef MHD_THREADS_H
+#define MHD_THREADS_H 1
+
+#include "mhd_options.h"
+#ifdef HAVE_STDDEF_H
+#  include <stddef.h> /* for size_t */
+#else  /* ! HAVE_STDDEF_H */
+#  include <stdlib.h> /* for size_t */
+#endif /* ! HAVE_STDDEF_H */
+
+#if defined(MHD_USE_POSIX_THREADS)
+#  undef HAVE_CONFIG_H
+#  include <pthread.h>
+#  define HAVE_CONFIG_H 1
+#elif defined(MHD_USE_W32_THREADS)
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
+#  endif /* !WIN32_LEAN_AND_MEAN */
+#  include <windows.h>
+#else
+#  error No threading API is available.
+#endif
+
+#ifndef MHD_NO_THREAD_NAMES
+#  if defined(MHD_USE_POSIX_THREADS)
+#    if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \
+  defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) || \
+  defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) || \
+  defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) || \
+  defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \
+  defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI)
+#      define MHD_USE_THREAD_NAME_
+#    endif /* HAVE_PTHREAD_SETNAME_NP */
+#  elif defined(MHD_USE_W32_THREADS)
+#    ifdef _MSC_FULL_VER
+/* Thread names only available with VC compiler */
+#      define MHD_USE_THREAD_NAME_
+#    endif /* _MSC_FULL_VER */
+#  endif
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+typedef pthread_t MHD_thread_handle_;
+#elif defined(MHD_USE_W32_THREADS)
+typedef HANDLE MHD_thread_handle_;
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+#  define MHD_THRD_RTRN_TYPE_ void*
+#  define MHD_THRD_CALL_SPEC_
+#elif defined(MHD_USE_W32_THREADS)
+#  define MHD_THRD_RTRN_TYPE_ unsigned
+#  define MHD_THRD_CALL_SPEC_ __stdcall
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+typedef pthread_t MHD_thread_ID_;
+#elif defined(MHD_USE_W32_THREADS)
+typedef DWORD MHD_thread_ID_;
+#endif
+
+/* Depending on implementation, pthread_create() MAY set thread ID into
+ * provided pointer and after it start thread OR start thread and after
+ * if set thread ID. In latter case, to avoid data races, additional
+ * pthread_self() call is required in thread routine. Is some platform
+ * is known for setting thread ID BEFORE starting thread macro
+ * MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD could be defined
+ * to save some resources. */
+#if defined(MHD_USE_POSIX_THREADS)
+#  ifdef MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD
+union _MHD_thread_handle_ID_
+{
+  MHD_thread_handle_ handle;    /**< To be used in other threads */
+  MHD_thread_ID_ ID;            /**< To be used in thread itself */
+};
+typedef union _MHD_thread_handle_ID_ MHD_thread_handle_ID_;
+#  else  /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+struct _MHD_thread_handle_ID_
+{
+  MHD_thread_handle_ handle;    /**< To be used in other threads */
+  MHD_thread_ID_ ID;            /**< To be used in thread itself */
+};
+typedef struct _MHD_thread_handle_ID_ MHD_thread_handle_ID_;
+#  endif /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+#elif defined(MHD_USE_W32_THREADS)
+struct _MHD_thread_handle_ID_
+{
+  MHD_thread_handle_ handle;    /**< To be used in other threads */
+  MHD_thread_ID_ ID;            /**< To be used in thread itself */
+};
+typedef struct _MHD_thread_handle_ID_ MHD_thread_handle_ID_;
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+/**
+ * Wait until specified thread is ended and free thread handle on success.
+ * @param thread handle to watch
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_join_thread_(thread) (! pthread_join ((thread), NULL))
+#elif defined(MHD_USE_W32_THREADS)
+/**
+ * Wait until specified thread is ended and free thread handle on success.
+ * @param thread handle to watch
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_join_thread_(thread) (WAIT_OBJECT_0 == WaitForSingleObject ( \
+                                    (thread), INFINITE) ? (CloseHandle ( \
+                                                             (thread)), ! 0) : \
+                                  0)
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+/**
+ * Check whether provided thread ID match current thread.
+ * @param ID thread ID to match
+ * @return nonzero on match, zero otherwise
+ */
+#define MHD_thread_ID_match_current_(ID) (pthread_equal ((ID), pthread_self ()))
+#elif defined(MHD_USE_W32_THREADS)
+/**
+ * Check whether provided thread ID match current thread.
+ * @param ID thread ID to match
+ * @return nonzero on match, zero otherwise
+ */
+#define MHD_thread_ID_match_current_(ID) (GetCurrentThreadId () == (ID))
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+#  ifdef MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD
+/**
+ * Initialise thread ID.
+ * @param thread_handle_ID_ptr pointer to thread handle-ID
+ */
+#define MHD_thread_init_(thread_handle_ID_ptr) (void) 0
+#  else  /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+/**
+ * Initialise thread ID.
+ * @param thread_handle_ID_ptr pointer to thread handle-ID
+ */
+#define MHD_thread_init_(thread_handle_ID_ptr) ((thread_handle_ID_ptr)->ID = \
+                                                  pthread_self ())
+#  endif /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+#elif defined(MHD_USE_W32_THREADS)
+/**
+ * Initialise thread ID.
+ * @param thread_handle_ID_ptr pointer to thread handle-ID
+ */
+#define MHD_thread_init_(thread_handle_ID_ptr) ((thread_handle_ID_ptr)->ID = \
+                                                  GetCurrentThreadId ())
+#endif
+
+/**
+ * Signature of main function for a thread.
+ *
+ * @param cls closure argument for the function
+ * @return termination code from the thread
+ */
+typedef MHD_THRD_RTRN_TYPE_
+(MHD_THRD_CALL_SPEC_ *MHD_THREAD_START_ROUTINE_)(void *cls);
+
+
+/**
+ * Create a thread and set the attributes according to our options.
+ *
+ * If thread is created, thread handle must be freed by MHD_join_thread_().
+ *
+ * @param thread        handle to initialize
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise
+ */
+int
+MHD_create_thread_ (MHD_thread_handle_ID_ *thread,
+                    size_t stack_size,
+                    MHD_THREAD_START_ROUTINE_ start_routine,
+                    void *arg);
+
+#ifndef MHD_USE_THREAD_NAME_
+#define MHD_create_named_thread_(t,n,s,r,a) MHD_create_thread_ ((t),(s),(r),(a))
+#else  /* MHD_USE_THREAD_NAME_ */
+/**
+ * Create a named thread and set the attributes according to our options.
+ *
+ * @param thread        handle to initialize
+ * @param thread_name   name for new thread
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise
+ */
+int
+MHD_create_named_thread_ (MHD_thread_handle_ID_ *thread,
+                          const char *thread_name,
+                          size_t stack_size,
+                          MHD_THREAD_START_ROUTINE_ start_routine,
+                          void *arg);
+
+#endif /* MHD_USE_THREAD_NAME_ */
+
+#endif /* ! MHD_THREADS_H */
diff --git a/src/lib/panic.c b/src/lib/panic.c
new file mode 100644
index 0000000..0c2c794
--- /dev/null
+++ b/src/lib/panic.c
@@ -0,0 +1,61 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/panic.c
+ * @brief functions to panic (abort)
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Handler for fatal errors.
+ */
+MHD_PanicCallback mhd_panic = NULL;
+
+/**
+ * Closure argument for #mhd_panic.
+ */
+void *mhd_panic_cls = NULL;
+
+
+/**
+ * Sets the global error handler to a different implementation.  @a cb
+ * will only be called in the case of typically fatal, serious
+ * internal consistency issues.  These issues should only arise in the
+ * case of serious memory corruption or similar problems with the
+ * architecture.  While @a cb is allowed to return and MHD will then
+ * try to continue, this is never safe.
+ *
+ * The default implementation that is used if no panic function is set
+ * simply prints an error message and calls `abort()`.  Alternative
+ * implementations might call `exit()` or other similar functions.
+ *
+ * @param cb new error handler
+ * @param cls passed to @a cb
+ * @ingroup logging
+ */
+void
+MHD_set_panic_func (MHD_PanicCallback cb,
+                    void *cls)
+{
+  mhd_panic = cb;
+  mhd_panic_cls = cls;
+}
diff --git a/src/lib/reason_phrase.c b/src/lib/reason_phrase.c
new file mode 100644
index 0000000..4142167
--- /dev/null
+++ b/src/lib/reason_phrase.c
@@ -0,0 +1,182 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2011, 2017 Christian Grothoff, Karlson2k (Evgeny Grin)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+/**
+ * @file reason_phrase.c
+ * @brief  Tables of the string response phrases
+ * @author Elliot Glaysher
+ * @author Christian Grothoff (minor code clean up)
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "internal.h"
+
+#ifndef NULL
+#define NULL ((void*) 0)
+#endif
+
+static const char *const invalid_hundred[] = {
+  NULL
+};
+
+static const char *const one_hundred[] = {
+  "Continue",
+  "Switching Protocols",
+  "Processing"
+};
+
+static const char *const two_hundred[] = {
+  "OK",
+  "Created",
+  "Accepted",
+  "Non-Authoritative Information",
+  "No Content",
+  "Reset Content",
+  "Partial Content",
+  "Multi-Status",
+  "Already Reported",
+  "Unknown",
+  "Unknown", /* 210 */
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown", /* 215 */
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown", /* 220 */
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown", /* 225 */
+  "IM Used"
+};
+
+static const char *const three_hundred[] = {
+  "Multiple Choices",
+  "Moved Permanently",
+  "Found",
+  "See Other",
+  "Not Modified",
+  "Use Proxy",
+  "Switch Proxy",
+  "Temporary Redirect",
+  "Permanent Redirect"
+};
+
+static const char *const four_hundred[] = {
+  "Bad Request",
+  "Unauthorized",
+  "Payment Required",
+  "Forbidden",
+  "Not Found",
+  "Method Not Allowed",
+  "Not Acceptable",
+  "Proxy Authentication Required",
+  "Request Timeout",
+  "Conflict",
+  "Gone",
+  "Length Required",
+  "Precondition Failed",
+  "Payload Too Large",
+  "URI Too Long",
+  "Unsupported Media Type",
+  "Range Not Satisfiable",
+  "Expectation Failed",
+  "Unknown",
+  "Unknown",
+  "Unknown", /* 420 */
+  "Misdirected Request",
+  "Unprocessable Entity",
+  "Locked",
+  "Failed Dependency",
+  "Unordered Collection",
+  "Upgrade Required",
+  "Unknown",
+  "Precondition Required",
+  "Too Many Requests",
+  "Unknown", /* 430 */
+  "Request Header Fields Too Large",
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown", /* 435 */
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Unknown", /* 440 */
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "No Response",
+  "Unknown", /* 445 */
+  "Unknown",
+  "Unknown",
+  "Unknown",
+  "Retry With",
+  "Blocked by Windows Parental Controls", /* 450 */
+  "Unavailable For Legal Reasons"
+};
+
+static const char *const five_hundred[] = {
+  "Internal Server Error",
+  "Not Implemented",
+  "Bad Gateway",
+  "Service Unavailable",
+  "Gateway Timeout",
+  "HTTP Version Not Supported",
+  "Variant Also Negotiates",
+  "Insufficient Storage",
+  "Loop Detected",
+  "Bandwidth Limit Exceeded",
+  "Not Extended",
+  "Network Authentication Required"
+};
+
+
+struct MHD_Reason_Block
+{
+  size_t max;
+  const char *const *data;
+};
+
+#define BLOCK(m) { (sizeof(m) / sizeof(char*)), m }
+
+static const struct MHD_Reason_Block reasons[] = {
+  BLOCK (invalid_hundred),
+  BLOCK (one_hundred),
+  BLOCK (two_hundred),
+  BLOCK (three_hundred),
+  BLOCK (four_hundred),
+  BLOCK (five_hundred),
+};
+
+
+const char *
+MHD_get_reason_phrase_for (enum MHD_HTTP_StatusCode code)
+{
+  if ( (code >= 100) &&
+       (code < 600) &&
+       (reasons[code / 100].max > (code % 100)) )
+    return reasons[code / 100].data[code % 100];
+  return "Unknown";
+}
diff --git a/src/lib/request.c b/src/lib/request.c
new file mode 100644
index 0000000..5b932bf
--- /dev/null
+++ b/src/lib/request.c
@@ -0,0 +1,160 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+/**
+ * @file requests.c
+ * @brief  Methods for managing HTTP requests
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "internal.h"
+
+
+/**
+ * Get all of the headers from the request.
+ *
+ * @param request request to get values from
+ * @param kind types of values to iterate over, can be a bitmask
+ * @param iterator callback to call on each header;
+ *        maybe NULL (then just count headers)
+ * @param iterator_cls extra argument to @a iterator
+ * @return number of entries iterated over
+ * @ingroup request
+ */
+unsigned int
+MHD_request_get_values (struct MHD_Request *request,
+                        enum MHD_ValueKind kind,
+                        MHD_KeyValueIterator iterator,
+                        void *iterator_cls)
+{
+  int ret;
+  struct MHD_HTTP_Header *pos;
+
+  ret = 0;
+  for (pos = request->headers_received;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if (0 != (pos->kind & kind))
+    {
+      ret++;
+      if ( (NULL != iterator) &&
+           (MHD_YES != iterator (iterator_cls,
+                                 pos->kind,
+                                 pos->header,
+                                 pos->value)) )
+        return ret;
+    }
+  }
+  return ret;
+}
+
+
+/**
+ * This function can be used to add an entry to the HTTP headers of a
+ * request (so that the #MHD_request_get_values function will
+ * return them -- and the `struct MHD_PostProcessor` will also see
+ * them).  This maybe required in certain situations (see Mantis
+ * #1399) where (broken) HTTP implementations fail to supply values
+ * needed by the post processor (or other parts of the application).
+ *
+ * This function MUST only be called from within the
+ * request callbacks (otherwise, access maybe improperly
+ * synchronized).  Furthermore, the client must guarantee that the key
+ * and value arguments are 0-terminated strings that are NOT freed
+ * until the connection is closed.  (The easiest way to do this is by
+ * passing only arguments to permanently allocated strings.).
+ *
+ * @param request the request for which a
+ *  value should be set
+ * @param kind kind of the value
+ * @param key key for the value
+ * @param value the value itself
+ * @return #MHD_NO if the operation could not be
+ *         performed due to insufficient memory;
+ *         #MHD_YES on success
+ * @ingroup request
+ */
+enum MHD_Bool
+MHD_request_set_value (struct MHD_Request *request,
+                       enum MHD_ValueKind kind,
+                       const char *key,
+                       const char *value)
+{
+  struct MHD_HTTP_Header *pos;
+
+  pos = MHD_pool_allocate (request->connection->pool,
+                           sizeof (struct MHD_HTTP_Header),
+                           MHD_YES);
+  if (NULL == pos)
+    return MHD_NO;
+  pos->header = (char *) key;
+  pos->value = (char *) value;
+  pos->kind = kind;
+  pos->next = NULL;
+  /* append 'pos' to the linked list of headers */
+  if (NULL == request->headers_received_tail)
+  {
+    request->headers_received = pos;
+    request->headers_received_tail = pos;
+  }
+  else
+  {
+    request->headers_received_tail->next = pos;
+    request->headers_received_tail = pos;
+  }
+  return MHD_YES;
+}
+
+
+/**
+ * Get a particular header value.  If multiple
+ * values match the kind, return any one of them.
+ *
+ * @param request request to get values from
+ * @param kind what kind of value are we looking for
+ * @param key the header to look for, NULL to lookup 'trailing' value without a key
+ * @return NULL if no such item was found
+ * @ingroup request
+ */
+const char *
+MHD_request_lookup_value (struct MHD_Request *request,
+                          enum MHD_ValueKind kind,
+                          const char *key)
+{
+  struct MHD_HTTP_Header *pos;
+
+  for (pos = request->headers_received;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if ((0 != (pos->kind & kind)) &&
+        ( (key == pos->header) ||
+          ( (NULL != pos->header) &&
+            (NULL != key) &&
+            (MHD_str_equal_caseless_ (key,
+                                      pos->header)))))
+      return pos->value;
+  }
+  return NULL;
+}
+
+
+/* end of request.c */
diff --git a/src/lib/request_info.c b/src/lib/request_info.c
new file mode 100644
index 0000000..51aae07
--- /dev/null
+++ b/src/lib/request_info.c
@@ -0,0 +1,86 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/request_info.c
+ * @brief implementation of MHD_request_get_information_sz()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Obtain information about the given request.
+ * Use wrapper macro #MHD_request_get_information() instead of direct use
+ * of this function.
+ *
+ * @param request what request to get information about
+ * @param info_type what information is desired?
+ * @param[out] return_value pointer to union where requested information will
+ *                          be stored
+ * @param return_value_size size of union MHD_RequestInformation at compile
+ *                          time
+ * @return #MHD_YES on success, #MHD_NO on error
+ *         (@a info_type is unknown, NULL pointer etc.)
+ * @ingroup specialized
+ */
+enum MHD_Bool
+MHD_request_get_information_sz (struct MHD_Request *request,
+                                enum MHD_RequestInformationType info_type,
+                                union MHD_RequestInformation *return_value,
+                                size_t return_value_size)
+{
+#define CHECK_SIZE(type) if (sizeof(type) < return_value_size)  \
+    return MHD_NO
+
+  switch (info_type)
+  {
+  case MHD_REQUEST_INFORMATION_CONNECTION:
+    CHECK_SIZE (struct MHD_Connection *);
+    return_value->connection = request->connection;
+    return MHD_YES;
+  case MHD_REQUEST_INFORMATION_CLIENT_CONTEXT:
+    CHECK_SIZE (void **);
+    return_value->request_context = &request->client_context;
+    return MHD_YES;
+  case MHD_REQUEST_INFORMATION_HTTP_VERSION:
+    CHECK_SIZE (const char *);
+    return_value->http_version = request->version_s;
+    return MHD_YES;
+  case MHD_REQUEST_INFORMATION_HTTP_METHOD:
+    CHECK_SIZE (const char *);
+    return_value->http_method = request->method_s;
+    return MHD_YES;
+  case MHD_REQUEST_INFORMATION_HEADER_SIZE:
+    CHECK_SIZE (size_t);
+    if ( (MHD_REQUEST_HEADERS_RECEIVED > request->state) ||
+         (MHD_REQUEST_CLOSED == request->state) )
+      return MHD_NO;   /* invalid, too early! */
+    return_value->header_size = request->header_size;
+    return MHD_YES;
+
+  default:
+    return MHD_NO;
+  }
+
+#undef CHECK_SIZE
+}
+
+
+/* end of request_info.c */
diff --git a/src/lib/request_resume.c b/src/lib/request_resume.c
new file mode 100644
index 0000000..52dc237
--- /dev/null
+++ b/src/lib/request_resume.c
@@ -0,0 +1,201 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/request_resume.c
+ * @brief implementation of MHD_request_resume()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "connection_close.h"
+
+/**
+ * Resume handling of network data for suspended request.  It is
+ * safe to resume a suspended request at any time.  Calling this
+ * function on a request that was not previously suspended will
+ * result in undefined behavior.
+ *
+ * If you are using this function in ``external'' select mode, you must
+ * make sure to run #MHD_run() afterwards (before again calling
+ * #MHD_get_fdset(), as otherwise the change may not be reflected in
+ * the set returned by #MHD_get_fdset() and you may end up with a
+ * request that is stuck until the next network activity.
+ *
+ * @param request the request to resume
+ */
+void
+MHD_request_resume (struct MHD_Request *request)
+{
+  struct MHD_Daemon *daemon = request->daemon;
+
+  if (daemon->disallow_suspend_resume)
+    MHD_PANIC (_ (
+                 "Cannot resume connections without enabling MHD_ALLOW_SUSPEND_RESUME!\n"));
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  request->connection->resuming = true;
+  daemon->resuming = true;
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc,
+                             "r")) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              MHD_SC_ITC_USE_FAILED,
+              _ (
+                "Failed to signal resume via inter-thread communication channel.\n"));
+#endif
+  }
+}
+
+
+/**
+ * Run through the suspended connections and move any that are no
+ * longer suspended back to the active state.
+ *
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon daemon context
+ * @return true if a connection was actually resumed
+ */
+bool
+MHD_resume_suspended_connections_ (struct MHD_Daemon *daemon)
+/* FIXME: rename connections -> requests? */
+{
+  struct MHD_Connection *pos;
+  struct MHD_Connection *prev = NULL;
+  bool ret;
+  const bool used_thr_p_c = (MHD_TM_THREAD_PER_CONNECTION ==
+                             daemon->threading_mode);
+
+  mhd_assert (NULL == daemon->worker_pool);
+  ret = false;
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+
+  if (daemon->resuming)
+  {
+    prev = daemon->suspended_connections_tail;
+    /* During shutdown check for resuming is forced. */
+    mhd_assert ((NULL != prev) || (daemon->shutdown));
+  }
+
+  daemon->resuming = false;
+
+  while (NULL != (pos = prev))
+  {
+#ifdef UPGRADE_SUPPORT
+    struct MHD_UpgradeResponseHandle *const urh = pos->request.urh;
+#else  /* ! UPGRADE_SUPPORT */
+    static const void *const urh = NULL;
+#endif /* ! UPGRADE_SUPPORT */
+    prev = pos->prev;
+    if ( (! pos->resuming)
+#ifdef UPGRADE_SUPPORT
+         || ( (NULL != urh) &&
+              ( (! urh->was_closed) ||
+                (! urh->clean_ready) ) )
+#endif /* UPGRADE_SUPPORT */
+         )
+      continue;
+    ret = true;
+    mhd_assert (pos->suspended);
+    DLL_remove (daemon->suspended_connections_head,
+                daemon->suspended_connections_tail,
+                pos);
+    pos->suspended = false;
+    if (NULL == urh)
+    {
+      DLL_insert (daemon->connections_head,
+                  daemon->connections_tail,
+                  pos);
+      if (! used_thr_p_c)
+      {
+        /* Reset timeout timer on resume. */
+        if (0 != pos->connection_timeout)
+          pos->last_activity = MHD_monotonic_sec_counter ();
+
+        if (pos->connection_timeout == daemon->connection_default_timeout)
+          XDLL_insert (daemon->normal_timeout_head,
+                       daemon->normal_timeout_tail,
+                       pos);
+        else
+          XDLL_insert (daemon->manual_timeout_head,
+                       daemon->manual_timeout_tail,
+                       pos);
+      }
+#ifdef EPOLL_SUPPORT
+      if (MHD_ELS_EPOLL == daemon->event_loop_syscall)
+      {
+        if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+          MHD_PANIC ("Resumed connection was already in EREADY set.\n");
+        /* we always mark resumed connections as ready, as we
+           might have missed the edge poll event during suspension */
+        EDLL_insert (daemon->eready_head,
+                     daemon->eready_tail,
+                     pos);
+        pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL   \
+                            | MHD_EPOLL_STATE_READ_READY
+                            | MHD_EPOLL_STATE_WRITE_READY;
+        pos->epoll_state &= ~MHD_EPOLL_STATE_SUSPENDED;
+      }
+#endif
+    }
+#ifdef UPGRADE_SUPPORT
+    else
+    {
+      struct MHD_Response *response = pos->request.response;
+
+      /* Data forwarding was finished (for TLS connections) AND
+       * application was closed upgraded connection.
+       * Insert connection into cleanup list. */
+      if ( (NULL != response) &&
+           (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode) &&
+           (NULL != response->termination_cb) )
+        response->termination_cb (response->termination_cb_cls,
+                                  MHD_REQUEST_TERMINATED_COMPLETED_OK,
+                                  &pos->request.client_context);
+      DLL_insert (daemon->cleanup_head,
+                  daemon->cleanup_tail,
+                  pos);
+
+    }
+#endif /* UPGRADE_SUPPORT */
+    pos->resuming = false;
+  }
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+  if ( (used_thr_p_c) &&
+       (ret) )
+  {   /* Wake up suspended connections. */
+    if (! MHD_itc_activate_ (daemon->itc,
+                             "w"))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_ITC_USE_FAILED,
+                _ (
+                  "Failed to signal resume of connection via inter-thread communication channel.\n"));
+#endif
+    }
+  }
+  return ret;
+}
+
+
+/* end of request_resume.c */
diff --git a/src/lib/request_resume.h b/src/lib/request_resume.h
new file mode 100644
index 0000000..dad4346
--- /dev/null
+++ b/src/lib/request_resume.h
@@ -0,0 +1,43 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/request_resume.h
+ * @brief implementation of MHD_request_resume()
+ * @author Christian Grothoff
+ */
+
+
+#ifndef REQUEST_RESUME_H
+#define REQUEST_RESUME_H
+
+/**
+ * Run through the suspended connections and move any that are no
+ * longer suspended back to the active state.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon daemon context
+ * @return true if a connection was actually resumed
+ */
+bool
+MHD_resume_suspended_connections_ (struct MHD_Daemon *daemon)
+MHD_NONNULL (1);
+
+#endif
diff --git a/src/lib/response.c b/src/lib/response.c
new file mode 100644
index 0000000..aea187a
--- /dev/null
+++ b/src/lib/response.c
@@ -0,0 +1,260 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/response.c
+ * @brief implementation of general response functions
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "internal.h"
+
+
+/**
+ * Add a header or footer line to the response.
+ *
+ * @param response response to add a header to
+ * @param kind header or footer
+ * @param header the header to add
+ * @param content value to add
+ * @return false on error (i.e. invalid header or content format).
+ */
+static bool
+add_response_entry (struct MHD_Response *response,
+                    enum MHD_ValueKind kind,
+                    const char *header,
+                    const char *content)
+{
+  struct MHD_HTTP_Header *hdr;
+
+  if ( (NULL == header) ||
+       (NULL == content) ||
+       (0 == header[0]) ||
+       (0 == content[0]) ||
+       (NULL != strchr (header, '\t')) ||
+       (NULL != strchr (header, '\r')) ||
+       (NULL != strchr (header, '\n')) ||
+       (NULL != strchr (content, '\t')) ||
+       (NULL != strchr (content, '\r')) ||
+       (NULL != strchr (content, '\n')) )
+    return false;
+  if (NULL == (hdr = malloc (sizeof (struct MHD_HTTP_Header))))
+    return false;
+  if (NULL == (hdr->header = strdup (header)))
+  {
+    free (hdr);
+    return false;
+  }
+  if (NULL == (hdr->value = strdup (content)))
+  {
+    free (hdr->header);
+    free (hdr);
+    return false;
+  }
+  hdr->kind = kind;
+  hdr->next = response->first_header;
+  response->first_header = hdr;
+  return true;
+}
+
+
+/**
+ * Explicitly decrease reference counter of a response object.  If the
+ * counter hits zero, destroys a response object and associated
+ * resources.  Usually, this is implicitly done by converting a
+ * response to an action and returning the action to MHD.
+ *
+ * @param response response to decrement RC of
+ * @ingroup response
+ */
+void
+MHD_response_queue_for_destroy (struct MHD_Response *response)
+{
+  struct MHD_HTTP_Header *pos;
+
+  MHD_mutex_lock_chk_ (&response->mutex);
+  if (0 != --(response->reference_count))
+  {
+    MHD_mutex_unlock_chk_ (&response->mutex);
+    return;
+  }
+  MHD_mutex_unlock_chk_ (&response->mutex);
+  MHD_mutex_destroy_chk_ (&response->mutex);
+  if (NULL != response->crfc)
+    response->crfc (response->crc_cls);
+  while (NULL != response->first_header)
+  {
+    pos = response->first_header;
+    response->first_header = pos->next;
+    free (pos->header);
+    free (pos->value);
+    free (pos);
+  }
+  free (response);
+}
+
+
+/**
+ * Add a header line to the response.
+ *
+ * @param response response to add a header to
+ * @param header the header to add
+ * @param content value to add
+ * @return #MHD_NO on error (i.e. invalid header or content format),
+ *         or out of memory
+ * @ingroup response
+ */
+enum MHD_Bool
+MHD_response_add_header (struct MHD_Response *response,
+                         const char *header,
+                         const char *content)
+{
+  return add_response_entry (response,
+                             MHD_HEADER_KIND,
+                             header,
+                             content) ? MHD_YES : MHD_NO;
+}
+
+
+/**
+ * Add a tailer line to the response.
+ *
+ * @param response response to add a footer to
+ * @param footer the footer to add
+ * @param content value to add
+ * @return #MHD_NO on error (i.e. invalid footer or content format),
+ *         or out of memory
+ * @ingroup response
+ */
+enum MHD_Bool
+MHD_response_add_trailer (struct MHD_Response *response,
+                          const char *footer,
+                          const char *content)
+{
+  return add_response_entry (response,
+                             MHD_FOOTER_KIND,
+                             footer,
+                             content) ? MHD_YES : MHD_NO;
+}
+
+
+/**
+ * Delete a header (or footer) line from the response.
+ *
+ * @param response response to remove a header from
+ * @param header the header to delete
+ * @param content value to delete
+ * @return #MHD_NO on error (no such header known)
+ * @ingroup response
+ */
+enum MHD_Bool
+MHD_response_del_header (struct MHD_Response *response,
+                         const char *header,
+                         const char *content)
+{
+  struct MHD_HTTP_Header *pos;
+  struct MHD_HTTP_Header *prev;
+
+  prev = NULL;
+  pos = response->first_header;
+  while (NULL != pos)
+  {
+    if ((0 == strcmp (header,
+                      pos->header)) &&
+        (0 == strcmp (content,
+                      pos->value)))
+    {
+      free (pos->header);
+      free (pos->value);
+      if (NULL == prev)
+        response->first_header = pos->next;
+      else
+        prev->next = pos->next;
+      free (pos);
+      return MHD_YES;
+    }
+    prev = pos;
+    pos = pos->next;
+  }
+  return MHD_NO;
+}
+
+
+/**
+ * Get all of the headers (and footers) added to a response.
+ *
+ * @param response response to query
+ * @param iterator callback to call on each header;
+ *        maybe NULL (then just count headers)
+ * @param iterator_cls extra argument to @a iterator
+ * @return number of entries iterated over
+ * @ingroup response
+ */
+unsigned int
+MHD_response_get_headers (struct MHD_Response *response,
+                          MHD_KeyValueIterator iterator,
+                          void *iterator_cls)
+{
+  unsigned int numHeaders = 0;
+  struct MHD_HTTP_Header *pos;
+
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    numHeaders++;
+    if ( (NULL != iterator) &&
+         (MHD_YES != iterator (iterator_cls,
+                               pos->kind,
+                               pos->header,
+                               pos->value)) )
+      break;
+  }
+  return numHeaders;
+}
+
+
+/**
+ * Get a particular header (or footer) from the response.
+ *
+ * @param response response to query
+ * @param key which header to get
+ * @return NULL if header does not exist
+ * @ingroup response
+ */
+const char *
+MHD_response_get_header (struct MHD_Response *response,
+                         const char *key)
+{
+  struct MHD_HTTP_Header *pos;
+
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if (MHD_str_equal_caseless_ (pos->header,
+                                 key))
+      return pos->value;
+  }
+  return NULL;
+}
+
+
+/* end of response.c */
diff --git a/src/lib/response_for_upgrade.c b/src/lib/response_for_upgrade.c
new file mode 100644
index 0000000..26431e5
--- /dev/null
+++ b/src/lib/response_for_upgrade.c
@@ -0,0 +1,95 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/response_for_upgrade.c
+ * @brief implementation of MHD_response_for_upgrade()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Create a response object that can be used for 101 UPGRADE
+ * responses, for example to implement WebSockets.  After sending the
+ * response, control over the data stream is given to the callback (which
+ * can then, for example, start some bi-directional communication).
+ * If the response is queued for multiple connections, the callback
+ * will be called for each connection.  The callback
+ * will ONLY be called after the response header was successfully passed
+ * to the OS; if there are communication errors before, the usual MHD
+ * connection error handling code will be performed.
+ *
+ * MHD will automatically set the correct HTTP status
+ * code (#MHD_HTTP_SWITCHING_PROTOCOLS).
+ * Setting correct HTTP headers for the upgrade must be done
+ * manually (this way, it is possible to implement most existing
+ * WebSocket versions using this API; in fact, this API might be useful
+ * for any protocol switch, not just WebSockets).  Note that
+ * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this
+ * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake"
+ * cannot be generated; instead, MHD will always produce "HTTP/1.1 101
+ * Switching Protocols" (if the response code 101 is used).
+ *
+ * As usual, the response object can be extended with header
+ * information and then be used any number of times (as long as the
+ * header information is not connection-specific).
+ *
+ * @param upgrade_handler function to call with the "upgraded" socket
+ * @param upgrade_handler_cls closure for @a upgrade_handler
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ */
+struct MHD_Response *
+MHD_response_for_upgrade (MHD_UpgradeHandler upgrade_handler,
+                          void *upgrade_handler_cls)
+{
+#ifdef UPGRADE_SUPPORT
+  struct MHD_Response *response;
+
+  mhd_assert (NULL != upgrade_handler);
+  response = MHD_calloc_ (1,
+                          sizeof (struct MHD_Response));
+  if (NULL == response)
+    return NULL;
+  if (! MHD_mutex_init_ (&response->mutex))
+  {
+    free (response);
+    return NULL;
+  }
+  response->upgrade_handler = upgrade_handler;
+  response->upgrade_handler_cls = upgrade_handler_cls;
+  response->status_code = MHD_HTTP_SWITCHING_PROTOCOLS;
+  response->total_size = MHD_SIZE_UNKNOWN;
+  response->reference_count = 1;
+  if (MHD_NO ==
+      MHD_response_add_header (response,
+                               MHD_HTTP_HEADER_CONNECTION,
+                               "Upgrade"))
+  {
+    MHD_response_queue_for_destroy (response);
+    return NULL;
+  }
+  return response;
+#else
+  return NULL;
+#endif
+}
+
+
+/* end of response_for_upgrade.c */
diff --git a/src/lib/response_from_buffer.c b/src/lib/response_from_buffer.c
new file mode 100644
index 0000000..c964277
--- /dev/null
+++ b/src/lib/response_from_buffer.c
@@ -0,0 +1,89 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/response_from_buffer.c
+ * @brief implementation of MHD_response_from_buffer()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Create a response object.  The response object can be extended with
+ * header information and then be used any number of times.
+ *
+ * @param sc status code to use for the response;
+ *           #MHD_HTTP_NO_CONTENT is only valid if @a size is 0;
+ * @param size size of the data portion of the response
+ * @param buffer size bytes containing the response's data portion
+ * @param mode flags for buffer management
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+struct MHD_Response *
+MHD_response_from_buffer (enum MHD_HTTP_StatusCode sc,
+                          size_t size,
+                          void *buffer,
+                          enum MHD_ResponseMemoryMode mode)
+{
+  struct MHD_Response *response;
+  void *tmp;
+
+  mhd_assert ( (NULL != buffer) ||
+               (0 == size) );
+  if (NULL ==
+      (response = MHD_calloc_ (1,
+                               sizeof (struct MHD_Response))))
+    return NULL;
+  response->fd = -1;
+  if (! MHD_mutex_init_ (&response->mutex))
+  {
+    free (response);
+    return NULL;
+  }
+  if ( (MHD_RESPMEM_MUST_COPY == mode) &&
+       (size > 0) )
+  {
+    if (NULL == (tmp = malloc (size)))
+    {
+      MHD_mutex_destroy_chk_ (&response->mutex);
+      free (response);
+      return NULL;
+    }
+    memcpy (tmp,
+            buffer,
+            size);
+    buffer = tmp;
+  }
+  if (MHD_RESPMEM_PERSISTENT != mode)
+  {
+    response->crfc = &free;
+    response->crc_cls = buffer;
+  }
+  response->status_code = sc;
+  response->reference_count = 1;
+  response->total_size = size;
+  response->data = buffer;
+  response->data_size = size;
+  return response;
+}
+
+
+/* end of response_from_buffer.c */
diff --git a/src/lib/response_from_callback.c b/src/lib/response_from_callback.c
new file mode 100644
index 0000000..e00033c
--- /dev/null
+++ b/src/lib/response_from_callback.c
@@ -0,0 +1,80 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/response_from_callback.c
+ * @brief implementation of MHD_response_from_callback()
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Create a response action.  The response object can be extended with
+ * header information and then be used any number of times.
+ *
+ * @param sc status code to return
+ * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown
+ * @param block_size preferred block size for querying crc (advisory only,
+ *                   MHD may still call @a crc using smaller chunks); this
+ *                   is essentially the buffer size used for IO, clients
+ *                   should pick a value that is appropriate for IO and
+ *                   memory performance requirements
+ * @param crc callback to use to obtain response data
+ * @param crc_cls extra argument to @a crc
+ * @param crfc callback to call to free @a crc_cls resources
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+struct MHD_Response *
+MHD_response_from_callback (enum MHD_HTTP_StatusCode sc,
+                            uint64_t size,
+                            size_t block_size,
+                            MHD_ContentReaderCallback crc,
+                            void *crc_cls,
+                            MHD_ContentReaderFreeCallback crfc)
+{
+  struct MHD_Response *response;
+
+  mhd_assert (NULL != crc);
+  mhd_assert (0 != block_size);
+  if (NULL ==
+      (response = MHD_calloc_ (1,
+                               sizeof (struct MHD_Response)
+                               + block_size)))
+    return NULL;
+  response->fd = -1;
+  response->status_code = sc;
+  response->data = (void *) &response[1];
+  response->data_buffer_size = block_size;
+  if (! MHD_mutex_init_ (&response->mutex))
+  {
+    free (response);
+    return NULL;
+  }
+  response->crc = crc;
+  response->crfc = crfc;
+  response->crc_cls = crc_cls;
+  response->reference_count = 1;
+  response->total_size = size;
+  return response;
+}
+
+
+/* end of response_from_callback.c */
diff --git a/src/lib/response_from_fd.c b/src/lib/response_from_fd.c
new file mode 100644
index 0000000..4b3bfb8
--- /dev/null
+++ b/src/lib/response_from_fd.c
@@ -0,0 +1,211 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2019 Daniel Pittman, Christian Grothoff and
+  Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/response_from_fd.c
+ * @brief implementation of MHD_response_from_fd()
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "internal.h"
+
+
+/**
+ * Size of single file read operation for
+ * file-backed responses.
+ */
+#ifndef MHD_FILE_READ_BLOCK_SIZE
+#ifdef _WIN32
+#define MHD_FILE_READ_BLOCK_SIZE 16384 /* 16k */
+#else /* _WIN32 */
+#define MHD_FILE_READ_BLOCK_SIZE 4096 /* 4k */
+#endif /* _WIN32 */
+#endif /* !MHD_FD_BLOCK_SIZE */
+
+/**
+ * Given a file descriptor, read data from the file
+ * to generate the response.
+ *
+ * @param cls pointer to the response
+ * @param pos offset in the file to access
+ * @param buf where to write the data
+ * @param max number of bytes to write at most
+ * @return number of bytes written
+ */
+static ssize_t
+file_reader (void *cls,
+             uint64_t pos,
+             char *buf,
+             size_t max)
+{
+  struct MHD_Response *response = cls;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+  ssize_t n;
+#else  /* _WIN32 && !__CYGWIN__ */
+  const HANDLE fh = (HANDLE) _get_osfhandle (response->fd);
+#endif /* _WIN32 && !__CYGWIN__ */
+  const int64_t offset64 = (int64_t) (pos + response->fd_off);
+
+  if (offset64 < 0)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */
+
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+  if (max > SSIZE_MAX)
+    max = SSIZE_MAX; /* Clamp to maximum return value. */
+
+#if defined(HAVE_PREAD64)
+  n = pread64 (response->fd,
+               buf,
+               max,
+               offset64);
+#elif defined(HAVE_PREAD)
+  if ( (sizeof(off_t) < sizeof (uint64_t)) &&
+       (offset64 > (uint64_t) INT32_MAX) )
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* Read at required position is not possible. */
+
+  n = pread (response->fd,
+             buf,
+             max,
+             (off_t) offset64);
+#else  /* ! HAVE_PREAD */
+#if defined(HAVE_LSEEK64)
+  if (lseek64 (response->fd,
+               offset64,
+               SEEK_SET) != offset64)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */
+#else  /* ! HAVE_LSEEK64 */
+  if ( (sizeof(off_t) < sizeof (uint64_t)) &&
+       (offset64 > (uint64_t) INT32_MAX) )
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */
+
+  if (lseek (response->fd,
+             (off_t) offset64,
+             SEEK_SET) != (off_t) offset64)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */
+#endif /* ! HAVE_LSEEK64 */
+  n = read (response->fd,
+            buf,
+            max);
+
+#endif /* ! HAVE_PREAD */
+  if (0 == n)
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  if (n < 0)
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  return n;
+#else /* _WIN32 && !__CYGWIN__ */
+  if (INVALID_HANDLE_VALUE == fh)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* Value of 'response->fd' is not valid. */
+  else
+  {
+    OVERLAPPED f_ol = {0, 0, {{0, 0}}, 0};   /* Initialize to zero. */
+    ULARGE_INTEGER pos_uli;
+    DWORD toRead = (max > INT32_MAX) ? INT32_MAX : (DWORD) max;
+    DWORD resRead;
+
+    pos_uli.QuadPart = (uint64_t) offset64;   /* Simple transformation 64bit -> 2x32bit. */
+    f_ol.Offset = pos_uli.LowPart;
+    f_ol.OffsetHigh = pos_uli.HighPart;
+    if (! ReadFile (fh,
+                    (void *) buf,
+                    toRead,
+                    &resRead,
+                    &f_ol))
+      return MHD_CONTENT_READER_END_WITH_ERROR;   /* Read error. */
+    if (0 == resRead)
+      return MHD_CONTENT_READER_END_OF_STREAM;
+    return (ssize_t) resRead;
+  }
+#endif /* _WIN32 && !__CYGWIN__ */
+}
+
+
+/**
+ * Destroy file reader context.  Closes the file
+ * descriptor.
+ *
+ * @param cls pointer to file descriptor
+ */
+static void
+free_callback (void *cls)
+{
+  struct MHD_Response *response = cls;
+
+  (void) close (response->fd);
+  response->fd = -1;
+}
+
+
+/**
+ * Create a response object based on an @a fd from which
+ * data is read.  The response object can be extended with
+ * header information and then be used any number of times.
+ *
+ * @param sc status code to return
+ * @param fd file descriptor referring to a file on disk with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @param offset offset to start reading from in the file;
+ *        reading file beyond 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @param size size of the data portion of the response;
+ *        sizes larger than 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+struct MHD_Response *
+MHD_response_from_fd (enum MHD_HTTP_StatusCode sc,
+                      int fd,
+                      uint64_t offset,
+                      uint64_t size)
+{
+  struct MHD_Response *response;
+
+  mhd_assert (-1 != fd);
+#if ! defined(HAVE___LSEEKI64) && ! defined(HAVE_LSEEK64)
+  if ( (sizeof (uint64_t) > sizeof (off_t)) &&
+       ( (size > (uint64_t) INT32_MAX) ||
+         (offset > (uint64_t) INT32_MAX) ||
+         ((size + offset) >= (uint64_t) INT32_MAX) ) )
+    return NULL;
+#endif
+  if ( ((int64_t) size < 0) ||
+       ((int64_t) offset < 0) ||
+       ((int64_t) (size + offset) < 0) )
+    return NULL;
+
+  response = MHD_response_from_callback (sc,
+                                         size,
+                                         MHD_FILE_READ_BLOCK_SIZE,
+                                         &file_reader,
+                                         NULL,
+                                         &free_callback);
+  if (NULL == response)
+    return NULL;
+  response->fd = fd;
+  response->fd_off = offset;
+  response->crc_cls = response;
+  return response;
+}
+
+
+/* end of response_from_fd.c */
diff --git a/src/lib/response_options.c b/src/lib/response_options.c
new file mode 100644
index 0000000..e349627
--- /dev/null
+++ b/src/lib/response_options.c
@@ -0,0 +1,62 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/response_option.c
+ * @brief implementation of response options
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Only respond in conservative HTTP 1.0-mode.  In
+ * particular, do not (automatically) sent "Connection" headers and
+ * always close the connection after generating the response.
+ *
+ * @param request the request for which we force HTTP 1.0 to be used
+ */
+void
+MHD_response_option_v10_only (struct MHD_Response *response)
+{
+  response->v10_only = true;
+}
+
+
+/**
+ * Set a function to be called once MHD is finished with the
+ * request.
+ *
+ * @param response which response to set the callback for
+ * @param termination_cb function to call
+ * @param termination_cb_cls closure for @e termination_cb
+ */
+void
+MHD_response_option_termination_callback (struct MHD_Response *response,
+                                          MHD_RequestTerminationCallback
+                                          termination_cb,
+                                          void *termination_cb_cls)
+{
+  /* Q: should we assert termination_cb non-NULL? */
+  response->termination_cb = termination_cb;
+  response->termination_cb_cls = termination_cb_cls;
+}
+
+
+/* end of response_option.c */
diff --git a/src/lib/sysfdsetsize.c b/src/lib/sysfdsetsize.c
new file mode 100644
index 0000000..350bfd5
--- /dev/null
+++ b/src/lib/sysfdsetsize.c
@@ -0,0 +1,80 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/sysfdsetsize.c
+ * @brief  Helper for obtaining FD_SETSIZE system default value
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+
+#include "MHD_config.h"
+
+#ifdef FD_SETSIZE
+/* FD_SETSIZE was defined before system headers. */
+/* To get system value of FD_SETSIZE, undefine FD_SETSIZE
+   here. */
+#undef FD_SETSIZE
+#endif /* FD_SETSIZE */
+
+#include <stdlib.h>
+#if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS)
+#include <sockLib.h>
+#endif /* OS_VXWORKS */
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif /* HAVE_SYS_SELECT_H */
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <winsock2.h>
+#endif /* _WIN32 && !__CYGWIN__ */
+
+#ifndef FD_SETSIZE
+#error FD_SETSIZE must be defined in system headers
+#endif /* !FD_SETSIZE */
+
+#include "sysfdsetsize.h"
+
+/**
+ * Get system default value of FD_SETSIZE
+ * @return system default value of FD_SETSIZE
+ */
+int
+get_system_fdsetsize_value (void)
+{
+  return FD_SETSIZE;
+}
diff --git a/src/lib/sysfdsetsize.h b/src/lib/sysfdsetsize.h
new file mode 100644
index 0000000..e3585b2
--- /dev/null
+++ b/src/lib/sysfdsetsize.h
@@ -0,0 +1,36 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/sysfdsetsize.h
+ * @brief  Helper for obtaining FD_SETSIZE system default value
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef SYSFDSETSIZE_H
+#define SYSFDSETSIZE_H 1
+
+/**
+ * Get system default value of FD_SETSIZE
+ * @return system default value of FD_SETSIZE
+ */
+int
+get_system_fdsetsize_value (void);
+
+#endif /* !SYSFDSETSIZE_H */
diff --git a/src/lib/tsearch.c b/src/lib/tsearch.c
new file mode 100644
index 0000000..ab7e32d
--- /dev/null
+++ b/src/lib/tsearch.c
@@ -0,0 +1,144 @@
+/*
+ * Tree search generalized from Knuth (6.2.2) Algorithm T just like
+ * the AT&T man page says.
+ *
+ * The node_t structure is for internal use only, lint doesn't grok it.
+ *
+ * Written by reading the System V Interface Definition, not the code.
+ *
+ * Totally public domain.
+ */
+
+#include "tsearch.h"
+#include <stdlib.h>
+
+
+typedef struct node
+{
+  const void   *key;
+  struct node  *llink;
+  struct node  *rlink;
+} node_t;
+
+
+/*	$NetBSD: tsearch.c,v 1.5 2005/11/29 03:12:00 christos Exp $	*/
+/* find or insert datum into search tree */
+void *
+tsearch (const void *vkey,  /* key to be located */
+         void **vrootp,     /* address of tree root */
+         int (*compar)(const void *, const void *))
+{
+  node_t *q;
+  node_t **rootp = (node_t **) vrootp;
+
+  if (NULL == rootp)
+    return NULL;
+
+  while (*rootp != NULL)
+  {   /* Knuth's T1: */
+    int r;
+
+    if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
+      return *rootp;                               /* we found it! */
+
+    rootp = (r < 0) ?
+            &(*rootp)->llink : /* T3: follow left branch */
+            &(*rootp)->rlink; /* T4: follow right branch */
+  }
+
+  q = malloc (sizeof(node_t)); /* T5: key not found */
+  if (q)
+  {                            /* make new node */
+    *rootp = q;                /* link new node to old */
+    q->key = vkey;             /* initialize new node */
+    q->llink = q->rlink = NULL;
+  }
+  return q;
+}
+
+
+/*	$NetBSD: tfind.c,v 1.5 2005/03/23 08:16:53 kleink Exp $	*/
+/* find a node, or return NULL */
+void *
+tfind (const void *vkey,         /* key to be found */
+       void *const *vrootp,      /* address of the tree root */
+       int (*compar)(const void *, const void *))
+{
+  node_t *const *rootp = (node_t *const *) vrootp;
+
+  if (NULL == rootp)
+    return NULL;
+
+  while (*rootp != NULL)
+  {     /* T1: */
+    int r;
+
+    if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
+      return *rootp;                               /* key found */
+    rootp = (r < 0) ?
+            &(*rootp)->llink : /* T3: follow left branch */
+            &(*rootp)->rlink; /* T4: follow right branch */
+  }
+  return NULL;
+}
+
+
+/*	$NetBSD: tdelete.c,v 1.2 1999/09/16 11:45:37 lukem Exp $	*/
+/*
+ * delete node with given key
+ *
+ * vkey:   key to be deleted
+ * vrootp: address of the root of the tree
+ * compar: function to carry out node comparisons
+ */
+void *
+tdelete (const void *__restrict vkey,
+         void **__restrict vrootp,
+         int (*compar)(const void *, const void *))
+{
+  node_t **rootp = (node_t **) vrootp;
+  node_t *p;
+  node_t *q;
+  node_t *r;
+  int cmp;
+
+  if ((rootp == NULL) || ((p = *rootp) == NULL))
+    return NULL;
+
+  while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0)
+  {
+    p = *rootp;
+    rootp = (cmp < 0) ?
+            &(*rootp)->llink : /* follow llink branch */
+            &(*rootp)->rlink; /* follow rlink branch */
+    if (*rootp == NULL)
+      return NULL;                   /* key not found */
+  }
+  r = (*rootp)->rlink;               /* D1: */
+  if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
+  {
+    q = r;
+  }
+  else if (r != NULL)
+  {       /* Right link is NULL? */
+    if (r->llink == NULL)
+    {     /* D2: Find successor */
+      r->llink = q;
+      q = r;
+    }
+    else
+    {         /* D3: Find NULL link */
+      for (q = r->llink; q->llink != NULL; q = r->llink)
+        r = q;
+      r->llink = q->rlink;
+      q->llink = (*rootp)->llink;
+      q->rlink = (*rootp)->rlink;
+    }
+  }
+  free (*rootp);    /* D4: Free node */
+  *rootp = q;       /* link parent to new node */
+  return p;
+}
+
+
+/* end of tsearch.c */
diff --git a/src/lib/tsearch.h b/src/lib/tsearch.h
new file mode 100644
index 0000000..9c2e25f
--- /dev/null
+++ b/src/lib/tsearch.h
@@ -0,0 +1,38 @@
+/*-
+ * Written by J.T. Conklin <jtc@netbsd.org>
+ * Public domain.
+ *
+ *	$NetBSD: search.h,v 1.12 1999/02/22 10:34:28 christos Exp $
+ * $FreeBSD: release/9.0.0/include/search.h 105250 2002-10-16 14:29:23Z robert $
+ */
+
+#ifndef _TSEARCH_H_
+#define _TSEARCH_H_
+
+#if defined(__cplusplus)
+extern "C" {
+#endif /* __cplusplus */
+
+
+void  *
+tdelete (const void *__restrict,
+         void **__restrict,
+         int (*)(const void *, const void *));
+
+
+void  *
+tfind (const void *,
+       void *const *,
+       int (*)(const void *, const void *));
+
+
+void  *
+tsearch (const void *,
+         void **,
+         int (*)(const void *, const void *));
+
+#if defined(__cplusplus)
+};
+#endif /* __cplusplus */
+
+#endif /* !_TSEARCH_H_ */
diff --git a/src/lib/upgrade_process.c b/src/lib/upgrade_process.c
new file mode 100644
index 0000000..e158b14
--- /dev/null
+++ b/src/lib/upgrade_process.c
@@ -0,0 +1,395 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/upgrade_process.c
+ * @brief function to process upgrade activity (over TLS)
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+#include "upgrade_process.h"
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Performs bi-directional forwarding on upgraded HTTPS connections
+ * based on the readiness state stored in the @a urh handle.
+ * @remark To be called only from thread that process
+ * connection's recv(), send() and response.
+ *
+ * @param urh handle to process
+ */
+void
+MHD_upgrade_response_handle_process_ (struct MHD_UpgradeResponseHandle *urh)
+{
+  /* Help compiler to optimize:
+   * pointers to 'connection' and 'daemon' are not changed
+   * during this processing, so no need to chain dereference
+   * each time. */
+  struct MHD_Connection *const connection = urh->connection;
+  struct MHD_Daemon *const daemon = connection->daemon;
+  /* Prevent data races: use same value of 'was_closed' throughout
+   * this function. If 'was_closed' changed externally in the middle
+   * of processing - it will be processed on next iteration. */
+  bool was_closed;
+  struct MHD_TLS_Plugin *tls = daemon->tls_api;
+
+  if (daemon->shutdown)
+  {
+    /* Daemon shutting down, application will not receive any more data. */
+#ifdef HAVE_MESSAGES
+    if (! urh->was_closed)
+    {
+      MHD_DLOG (daemon,
+                MHD_SC_DAEMON_ALREADY_SHUTDOWN,
+                _ (
+                  "Initiated daemon shutdown while \"upgraded\" connection was not closed.\n"));
+    }
+#endif
+    urh->was_closed = true;
+  }
+  was_closed = urh->was_closed;
+  if (was_closed)
+  {
+    /* Application was closed connections: no more data
+     * can be forwarded to application socket. */
+    if (0 < urh->in_buffer_used)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                MHD_SC_UPGRADE_FORWARD_INCOMPLETE,
+                _ (
+                  "Failed to forward to application "
+                  MHD_UNSIGNED_LONG_LONG_PRINTF \
+                  " bytes of data received from remote side: application shut down socket.\n"),
+                (MHD_UNSIGNED_LONG_LONG) urh->in_buffer_used);
+#endif
+
+    }
+    /* If application signaled MHD about socket closure then
+     * check for any pending data even if socket is not marked
+     * as 'ready' (signal may arrive after poll()/select()).
+     * Socketpair for forwarding is always in non-blocking mode
+     * so no risk that recv() will block the thread. */if (0 != urh->out_buffer_size)
+      urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+    /* Discard any data received form remote. */
+    urh->in_buffer_used = 0;
+    /* Do not try to push data to application. */
+    urh->mhd.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+    /* Reading from remote client is not required anymore. */
+    urh->in_buffer_size = 0;
+    urh->app.celi &= ~MHD_EPOLL_STATE_READ_READY;
+    connection->tls_read_ready = false;
+  }
+
+  /* On some platforms (W32, possibly Darwin) failed send() (send() will always
+   * fail after remote disconnect was detected) may discard data in system
+   * buffers received by system but not yet read by recv().
+   * So, before trying send() on any socket, recv() must be performed at first
+   * otherwise last part of incoming data may be lost. *//* If disconnect or error was detected - try to read from socket
+   * to dry data possibly pending is system buffers. */if (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi))
+    urh->app.celi |= MHD_EPOLL_STATE_READ_READY;
+  if (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi))
+    urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+
+  /*
+   * handle reading from remote TLS client
+   */
+  if ( ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->app.celi)) ||
+         (connection->tls_read_ready) ) &&
+       (urh->in_buffer_used < urh->in_buffer_size) )
+  {
+    ssize_t res;
+    size_t buf_size;
+
+    buf_size = urh->in_buffer_size - urh->in_buffer_used;
+    if (buf_size > SSIZE_MAX)
+      buf_size = SSIZE_MAX;
+
+    connection->tls_read_ready = false;
+    res = tls->recv (tls->cls,
+                     connection->tls_cs,
+                     &urh->in_buffer[urh->in_buffer_used],
+                     buf_size);
+    if (0 >= res)
+    {
+      // FIXME: define GNUTLS-independent error codes!
+      if (GNUTLS_E_INTERRUPTED != res)
+      {
+        urh->app.celi &= ~MHD_EPOLL_STATE_READ_READY;
+        if (GNUTLS_E_AGAIN != res)
+        {
+          /* Unrecoverable error on socket was detected or
+           * socket was disconnected/shut down. */
+          /* Stop trying to read from this TLS socket. */
+          urh->in_buffer_size = 0;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      urh->in_buffer_used += res;
+      if (buf_size > (size_t) res)
+        urh->app.celi &= ~MHD_EPOLL_STATE_READ_READY;
+      else if (0 < tls->check_record_pending (tls->cls,
+                                              connection->tls_cs))
+        connection->tls_read_ready = true;
+    }
+    if (MHD_EPOLL_STATE_ERROR ==
+        ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) & urh->app.celi))
+    {
+      /* Unrecoverable error on socket was detected and all
+       * pending data was read from system buffers. */
+      /* Stop trying to read from this TLS socket. */
+      urh->in_buffer_size = 0;
+    }
+  }
+
+  /*
+   * handle reading from application
+   */
+  if ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->mhd.celi)) &&
+       (urh->out_buffer_used < urh->out_buffer_size) )
+  {
+    ssize_t res;
+    size_t buf_size;
+
+    buf_size = urh->out_buffer_size - urh->out_buffer_used;
+    if (buf_size > MHD_SCKT_SEND_MAX_SIZE_)
+      buf_size = MHD_SCKT_SEND_MAX_SIZE_;
+
+    res = MHD_recv_ (urh->mhd.socket,
+                     &urh->out_buffer[urh->out_buffer_used],
+                     buf_size);
+    if (0 >= res)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if ((0 == res) ||
+          ((! MHD_SCKT_ERR_IS_EINTR_ (err)) &&
+           (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))))
+      {
+        urh->mhd.celi &= ~MHD_EPOLL_STATE_READ_READY;
+        if ((0 == res) ||
+            (was_closed) ||
+            (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ||
+            (! MHD_SCKT_ERR_IS_EAGAIN_ (err)))
+        {
+          /* Socket disconnect/shutdown was detected;
+           * Application signaled about closure of 'upgraded' socket;
+           * or persistent / unrecoverable error. */
+          /* Do not try to pull more data from application. */
+          urh->out_buffer_size = 0;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      urh->out_buffer_used += res;
+      if (buf_size > (size_t) res)
+        urh->mhd.celi &= ~MHD_EPOLL_STATE_READ_READY;
+    }
+    if ( (0 == (MHD_EPOLL_STATE_READ_READY & urh->mhd.celi)) &&
+         ( (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ||
+           (was_closed) ) )
+    {
+      /* Unrecoverable error on socket was detected and all
+       * pending data was read from system buffers. */
+      /* Do not try to pull more data from application. */
+      urh->out_buffer_size = 0;
+    }
+  }
+
+  /*
+   * handle writing to remote HTTPS client
+   */
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) &&
+       (urh->out_buffer_used > 0) )
+  {
+    ssize_t res;
+    size_t data_size;
+
+    data_size = urh->out_buffer_used;
+    if (data_size > SSIZE_MAX)
+      data_size = SSIZE_MAX;
+
+    res = tls->send (tls->cls,
+                     connection->tls_cs,
+                     urh->out_buffer,
+                     data_size);
+    if (0 >= res)
+    {
+      // FIXME: define GNUTLS-independent error codes!
+      if (GNUTLS_E_INTERRUPTED != res)
+      {
+        urh->app.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+        if (GNUTLS_E_INTERRUPTED != res)
+        {
+          /* TLS connection shut down or
+           * persistent / unrecoverable error. */
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    MHD_SC_UPGRADE_FORWARD_INCOMPLETE,
+                    _ (
+                      "Failed to forward to remote client "
+                      MHD_UNSIGNED_LONG_LONG_PRINTF \
+                      " bytes of data received from application: %s\n"),
+                    (MHD_UNSIGNED_LONG_LONG) urh->out_buffer_used,
+                    tls->strerror (tls->cls,
+                                   res));
+#endif
+          /* Discard any data unsent to remote. */
+          urh->out_buffer_used = 0;
+          /* Do not try to pull more data from application. */
+          urh->out_buffer_size = 0;
+          urh->mhd.celi &= ~MHD_EPOLL_STATE_READ_READY;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      const size_t next_out_buffer_used = urh->out_buffer_used - res;
+      if (0 != next_out_buffer_used)
+      {
+        memmove (urh->out_buffer,
+                 &urh->out_buffer[res],
+                 next_out_buffer_used);
+        if (data_size > (size_t) res)
+          urh->app.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+      }
+      urh->out_buffer_used = next_out_buffer_used;
+    }
+    if ( (0 == urh->out_buffer_used) &&
+         (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi)) )
+    {
+      /* Unrecoverable error on socket was detected and all
+       * pending data was sent to remote. */
+      /* Do not try to send to remote anymore. */
+      urh->app.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+      /* Do not try to pull more data from application. */
+      urh->out_buffer_size = 0;
+      urh->mhd.celi &= ~MHD_EPOLL_STATE_READ_READY;
+    }
+  }
+
+  /*
+   * handle writing to application
+   */
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) &&
+       (urh->in_buffer_used > 0) )
+  {
+    ssize_t res;
+    size_t data_size;
+
+    data_size = urh->in_buffer_used;
+    if (data_size > MHD_SCKT_SEND_MAX_SIZE_)
+      data_size = MHD_SCKT_SEND_MAX_SIZE_;
+
+    res = MHD_send_ (urh->mhd.socket,
+                     urh->in_buffer,
+                     data_size);
+    if (0 >= res)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if ( (! MHD_SCKT_ERR_IS_EINTR_ (err)) &&
+           (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) )
+      {
+        urh->mhd.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+        if (! MHD_SCKT_ERR_IS_EAGAIN_ (err))
+        {
+          /* Socketpair connection shut down or
+           * persistent / unrecoverable error. */
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    MHD_SC_UPGRADE_FORWARD_INCOMPLETE,
+                    _ (
+                      "Failed to forward to application "
+                      MHD_UNSIGNED_LONG_LONG_PRINTF \
+                      " bytes of data received from remote side: %s\n"),
+                    (MHD_UNSIGNED_LONG_LONG) urh->in_buffer_used,
+                    MHD_socket_strerr_ (err));
+#endif
+          /* Discard any data received form remote. */
+          urh->in_buffer_used = 0;
+          /* Reading from remote client is not required anymore. */
+          urh->in_buffer_size = 0;
+          urh->app.celi &= ~MHD_EPOLL_STATE_READ_READY;
+          connection->tls_read_ready = false;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      const size_t next_in_buffer_used = urh->in_buffer_used - res;
+      if (0 != next_in_buffer_used)
+      {
+        memmove (urh->in_buffer,
+                 &urh->in_buffer[res],
+                 next_in_buffer_used);
+        if (data_size > (size_t) res)
+          urh->mhd.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+      }
+      urh->in_buffer_used = next_in_buffer_used;
+    }
+    if ( (0 == urh->in_buffer_used) &&
+         (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) )
+    {
+      /* Do not try to push data to application. */
+      urh->mhd.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+      /* Reading from remote client is not required anymore. */
+      urh->in_buffer_size = 0;
+      urh->app.celi &= ~MHD_EPOLL_STATE_READ_READY;
+      connection->tls_read_ready = false;
+    }
+  }
+
+  /* Check whether data is present in TLS buffers
+   * and incoming forward buffer have some space. */
+  if ( (connection->tls_read_ready) &&
+       (urh->in_buffer_used < urh->in_buffer_size) &&
+       (MHD_TM_THREAD_PER_CONNECTION != daemon->threading_mode) )
+    daemon->data_already_pending = true;
+
+  if ( (daemon->shutdown) &&
+       ( (0 != urh->out_buffer_size) ||
+         (0 != urh->out_buffer_used) ) )
+  {
+    /* Daemon shutting down, discard any remaining forward data. */
+#ifdef HAVE_MESSAGES
+    if (0 < urh->out_buffer_used)
+      MHD_DLOG (daemon,
+                MHD_SC_UPGRADE_FORWARD_INCOMPLETE,
+                _ (
+                  "Failed to forward to remote client "
+                  MHD_UNSIGNED_LONG_LONG_PRINTF \
+                  " bytes of data received from application: daemon shut down.\n"),
+                (MHD_UNSIGNED_LONG_LONG) urh->out_buffer_used);
+#endif
+    /* Discard any data unsent to remote. */
+    urh->out_buffer_used = 0;
+    /* Do not try to sent to remote anymore. */
+    urh->app.celi &= ~MHD_EPOLL_STATE_WRITE_READY;
+    /* Do not try to pull more data from application. */
+    urh->out_buffer_size = 0;
+    urh->mhd.celi &= ~MHD_EPOLL_STATE_READ_READY;
+  }
+}
+
+
+#endif /* HTTPS_SUPPORT  && UPGRADE_SUPPORT */
+
+/* end of upgrade_process.c */
diff --git a/src/lib/upgrade_process.h b/src/lib/upgrade_process.h
new file mode 100644
index 0000000..e324201
--- /dev/null
+++ b/src/lib/upgrade_process.h
@@ -0,0 +1,44 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file lib/upgrade_process.h
+ * @brief function to process upgrade activity (over TLS)
+ * @author Christian Grothoff
+ */
+#ifndef UPGRADE_PROCESS_H
+#define UPGRADE_PROCESS_H
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Performs bi-directional forwarding on upgraded HTTPS connections
+ * based on the readiness state stored in the @a urh handle.
+ * @remark To be called only from thread that process
+ * connection's recv(), send() and response.
+ *
+ * @param urh handle to process
+ */
+void
+MHD_upgrade_response_handle_process_ (struct MHD_UpgradeResponseHandle *urh)
+MHD_NONNULL (1);
+
+
+#endif
+
+#endif
diff --git a/src/lib/version.c b/src/lib/version.c
new file mode 100644
index 0000000..c5ec38e
--- /dev/null
+++ b/src/lib/version.c
@@ -0,0 +1,207 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file lib/version.c
+ * @brief versioning and optional feature tests
+ * @author Christian Grothoff
+ */
+#include "internal.h"
+
+
+/**
+ * Obtain the version of this library
+ *
+ * @return static version string, e.g. "0.9.9"
+ * @ingroup specialized
+ */
+const char *
+MHD_get_version (void)
+{
+#ifdef PACKAGE_VERSION
+  return PACKAGE_VERSION;
+#else  /* !PACKAGE_VERSION */
+  static char ver[12] = "\0\0\0\0\0\0\0\0\0\0\0";
+  if (0 == ver[0])
+  {
+    int res = MHD_snprintf_ (ver,
+                             sizeof(ver),
+                             "%x.%x.%x",
+                             (((int) MHD_VERSION >> 24) & 0xFF),
+                             (((int) MHD_VERSION >> 16) & 0xFF),
+                             (((int) MHD_VERSION >> 8) & 0xFF));
+    if ((0 >= res) || (sizeof(ver) <= res))
+      return "0.0.0"; /* Can't return real version*/
+  }
+  return ver;
+#endif /* !PACKAGE_VERSION */
+}
+
+
+/**
+ * Get information about supported MHD features.
+ * Indicate that MHD was compiled with or without support for
+ * particular feature. Some features require additional support
+ * by kernel. Kernel support is not checked by this function.
+ *
+ * @param feature type of requested information
+ * @return #MHD_YES if feature is supported by MHD, #MHD_NO if
+ * feature is not supported or feature is unknown.
+ * @ingroup specialized
+ */
+_MHD_EXTERN enum MHD_Bool
+MHD_is_feature_supported (enum MHD_Feature feature)
+{
+  switch (feature)
+  {
+  case MHD_FEATURE_MESSAGES:
+#ifdef HAVE_MESSAGES
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_TLS:
+#ifdef HTTPS_SUPPORT
+    return MHD_YES;
+#else  /* ! HTTPS_SUPPORT */
+    return MHD_NO;
+#endif  /* ! HTTPS_SUPPORT */
+  case MHD_FEATURE_HTTPS_CERT_CALLBACK:
+#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_MAJOR >= 3
+    return MHD_YES;
+#else  /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */
+    return MHD_NO;
+#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */
+  case MHD_FEATURE_IPv6:
+#ifdef HAVE_INET6
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_IPv6_ONLY:
+#if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_POLL:
+#ifdef HAVE_POLL
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_EPOLL:
+#ifdef EPOLL_SUPPORT
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET:
+#ifdef HAVE_LISTEN_SHUTDOWN
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_SOCKETPAIR:
+#ifdef _MHD_ITC_SOCKETPAIR
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_TCP_FASTOPEN:
+#ifdef TCP_FASTOPEN
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_BASIC_AUTH:
+#ifdef BAUTH_SUPPORT
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH:
+#ifdef DAUTH_SUPPORT
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_POSTPROCESSOR:
+#ifdef HAVE_POSTPROCESSOR
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_HTTPS_KEY_PASSWORD:
+#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030111
+    return MHD_YES;
+#else  /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */
+    return MHD_NO;
+#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */
+  case MHD_FEATURE_LARGE_FILE:
+#if defined(HAVE_PREAD64) || defined(_WIN32)
+    return MHD_YES;
+#elif defined(HAVE_PREAD)
+    return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES;
+#elif defined(HAVE_LSEEK64)
+    return MHD_YES;
+#else
+    return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES;
+#endif
+  case MHD_FEATURE_THREAD_NAMES:
+#if defined(MHD_USE_THREAD_NAME_)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_UPGRADE:
+#if defined(UPGRADE_SUPPORT)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_RESPONSES_SHARED_FD:
+#if defined(HAVE_PREAD64) || defined(HAVE_PREAD) || defined(_WIN32)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_AUTODETECT_BIND_PORT:
+#ifdef MHD_USE_GETSOCKNAME
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_AUTOSUPPRESS_SIGPIPE:
+#if defined(MHD_WINSOCK_SOCKETS) || defined(MHD_socket_nosignal_) || \
+    defined (MSG_NOSIGNAL)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_SENDFILE:
+#ifdef _MHD_HAVE_SENDFILE
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+
+  }
+  return MHD_NO;
+}
diff --git a/src/microhttpd/.gitignore b/src/microhttpd/.gitignore
new file mode 100644
index 0000000..27d65b7
--- /dev/null
+++ b/src/microhttpd/.gitignore
@@ -0,0 +1,88 @@
+/microhttpd_dll_res.rc
+/test_postprocessor_large
+/test_postprocessor
+/test_daemon
+/test_postprocessor_amp
+/md5.gcda
+/digestauth.gcda
+/md5.gcno
+/digestauth.gcno
+/base64.gcno
+/response.gcno
+/response.gcda
+/reason_phrase.gcno
+/reason_phrase.gcda
+/postprocessor_test.gcno
+/postprocessor_test.gcda
+/postprocessor_large_test.gcno
+/postprocessor_large_test.gcda
+/postprocessor.gcno
+/postprocessor.gcda
+/memorypool.gcno
+/memorypool.gcda
+/internal.gcno
+/internal.gcda
+/daemontest
+/daemon_test.gcno
+/daemon_test.gcda
+/daemon.gcno
+/daemon.gcda
+/connection_https.gcno
+/connection_https.gcda
+/connection.gcno
+/connection.gcda
+/daemon.loT
+/daemon_test
+/libmicrohttpd_la-internal.loT
+/libmicrohttpd_la-connection.loT
+/libmicrohttpd_la-postprocessor.loT
+/libmicrohttpd_la-daemon.loT
+/postprocessor_large_test
+/postprocessor_test
+/gmon.out
+*.exe
+test_upgrade_tls
+test_http_reasons
+/test_daemon.trs
+/test_shutdown_poll_ignore
+/test_shutdown_select_ignore
+/test_str_compare
+/test_str_to_value
+/test_str_from_value
+/test_upgrade
+/test_upgrade_ssl
+/test_options
+/test_start_stop
+/test_str_token
+/test_str_token_remove
+/test_str_tokens_remove
+/test_response_entries
+test_shutdown_poll
+test_shutdown_select
+test_md5
+test_sha256
+/test_sha1
+test_upgrade_large
+test_upgrade_large_tls
+test_postprocessor_md
+/test_client_put_shutdown
+/test_client_put_close
+/test_client_put_hard_close
+/test_client_put_steps_shutdown
+/test_client_put_steps_close
+/test_client_put_steps_hard_close
+/test_client_put_chunked_shutdown
+/test_client_put_chunked_close
+/test_client_put_chunked_hard_close
+/test_client_put_chunked_steps_shutdown
+/test_client_put_chunked_steps_close
+/test_client_put_chunked_steps_hard_close
+/test_set_panic
+/test_auth_parse
+/test_str_quote
+/test_str_base64
+/test_str_pct
+/test_str_bin_hex
+/test_dauth_userdigest
+/test_dauth_userhash
+test_*[a-z0-9_][a-z0-9_][a-z0-9_]
diff --git a/src/microhttpd/Makefile.am b/src/microhttpd/Makefile.am
index dbf3bac..f114b41 100644
--- a/src/microhttpd/Makefile.am
+++ b/src/microhttpd/Makefile.am
@@ -1,13 +1,14 @@
 # This Makefile.am is in the public domain
+
 AM_CPPFLAGS = \
   -I$(top_srcdir)/src/include \
-  -I$(top_srcdir)/src/microhttpd
+  $(CPPFLAGS_ac)
 
-AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS)
+AM_CFLAGS = $(CFLAGS_ac) $(HIDDEN_VISIBILITY_CFLAGS)
 
-if HAVE_W32
-MHD_W32_LIB = $(top_builddir)/src/platform/libplatform_interface.la
-endif
+AM_LDFLAGS = $(LDFLAGS_ac)
+
+AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac)
 
 lib_LTLIBRARIES = \
   libmicrohttpd.la
@@ -15,32 +16,50 @@
 noinst_DATA =
 MOSTLYCLEANFILES =
 
+AM_V_LIB = $(am__v_LIB_@AM_V@)
+am__v_LIB_ = $(am__v_LIB_@AM_DEFAULT_V@)
+am__v_LIB_0 = @echo "  LIB     " $@;
+am__v_LIB_1 = 
+
 if W32_SHARED_LIB_EXP
+AM_V_DLLTOOL = $(am__v_DLLTOOL_@AM_V@)
+am__v_DLLTOOL_ = $(am__v_DLLTOOL_@AM_DEFAULT_V@)
+am__v_DLLTOOL_0 = @echo "  DLLTOOL " $@;
+am__v_DLLTOOL_1 = 
+
 W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd.def -XCClinker -static-libgcc
-noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp
+noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def
 MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp
 
 $(lt_cv_objdir)/libmicrohttpd.def: libmicrohttpd.la
+	$(AM_V_at)test -f $@ && touch $@ || \
+	  ( rm -f libmicrohttpd.la ; $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la && touch $@ )
+
+if USE_EXPORT_FILE
+noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.exp
 
 $(lt_cv_objdir)/libmicrohttpd.exp: $(lt_cv_objdir)/libmicrohttpd.lib
+	$(AM_V_at)test -f $@ && touch $@ || \
+	  ( rm -f $(lt_cv_objdir)/libmicrohttpd.lib ; $(MAKE) $(AM_MAKEFLAGS) $(lt_cv_objdir)/libmicrohttpd.lib  && touch $@ )
+endif
 
-$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS)
 if USE_MS_LIB_TOOL
-	@echo Creating $@ and libmicrohttpd.exp by $(MS_LIB_TOOL)... && \
-	dll_name=`$(EGREP) -o dlname=\'.+\' libmicrohttpd.la` && \
-	dll_name=$${dll_name#*\'} && dll_name=$${dll_name%\'} && test -n "$$dll_name" && \
-	echo Creating $$dll_name by $(MS_LIB_TOOL).. && cd "$(lt_cv_objdir)" && \
-	$(MS_LIB_TOOL) -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) && cd ..
+$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS)
+	$(AM_V_LIB) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \
+	$(MS_LIB_TOOL) -nologo -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -ignore:4221
 else
-	@echo Creating $@ and libmicrohttpd.exp by $(DLLTOOL)... && \
-	dll_name=`$(EGREP) -o dlname=\'.+\' libmicrohttpd.la` && \
-	dll_name=$${dll_name#*\'} && dll_name=$${dll_name%\'} && test -n "$$dll_name" && \
-	echo Creating $$dll_name by $(DLLTOOL).. && cd "$(lt_cv_objdir)" && \
-	$(DLLTOOL) -d ./libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp && cd .. &&\
-	echo Created libmicrohttpd.exp and libmicrohttpd.lib.
+if USE_EXPORT_FILE
+$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS)
+	$(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \
+	$(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp
+else
+$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la
+	$(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \
+	$(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib
+endif
 endif
 else
-  W32_MHD_LIB_LDFLAGS =
+W32_MHD_LIB_LDFLAGS =
 endif
 
 if W32_STATIC_LIB
@@ -49,33 +68,56 @@
 
 $(lt_cv_objdir)/libmicrohttpd-static.lib: libmicrohttpd.la $(libmicrohttpd_la_OBJECTS)
 if USE_MS_LIB_TOOL
-	$(MS_LIB_TOOL) -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o)
+	$(AM_V_LIB) $(MS_LIB_TOOL) -nologo -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o)
 else
-	cp $(lt_cv_objdir)/libmicrohttpd.a $@
+	$(AM_V_at)cp $(lt_cv_objdir)/libmicrohttpd.a $@
 endif
 endif
 
 
 libmicrohttpd_la_SOURCES = \
   connection.c connection.h \
-  reason_phrase.c reason_phrase.h \
+  reason_phrase.c \
   daemon.c  \
   internal.c internal.h \
   memorypool.c memorypool.h \
+  mhd_mono_clock.c mhd_mono_clock.h \
+  mhd_limits.h \
+  sysfdsetsize.c sysfdsetsize.h \
+  mhd_str.c mhd_str.h mhd_str_types.h\
+  mhd_send.h mhd_send.c \
+  mhd_assert.h \
+  mhd_sockets.c mhd_sockets.h \
+  mhd_itc.c mhd_itc.h mhd_itc_types.h \
+  mhd_compat.c mhd_compat.h \
+  mhd_panic.c mhd_panic.h \
   response.c response.h
+
+if USE_POSIX_THREADS
+libmicrohttpd_la_SOURCES += \
+  mhd_threads.c mhd_threads.h \
+  mhd_locks.h
+endif
+if USE_W32_THREADS
+libmicrohttpd_la_SOURCES += \
+  mhd_threads.c mhd_threads.h \
+  mhd_locks.h
+endif
+
+
 libmicrohttpd_la_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) \
+  $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) \
   -DBUILDING_MHD_LIB=1
 libmicrohttpd_la_CFLAGS = \
-  $(AM_CFLAGS) $(MHD_LIB_CFLAGS)
+  $(AM_CFLAGS) $(MHD_LIB_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
 libmicrohttpd_la_LDFLAGS = \
-  $(MHD_LIB_LDFLAGS) \
+  $(AM_LDFLAGS) $(MHD_LIB_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) \
   $(W32_MHD_LIB_LDFLAGS) \
+  -export-dynamic -no-undefined \
   -version-info @LIB_VERSION_CURRENT@:@LIB_VERSION_REVISION@:@LIB_VERSION_AGE@
 libmicrohttpd_la_LIBADD = \
-  $(MHD_W32_LIB) $(MHD_LIBDEPS)
-libmicrohttpd_la_DEPENDENCIES = \
-  $(MHD_W32_LIB)
+  $(MHD_LIBDEPS) $(MHD_TLS_LIBDEPS)
+
 
 if HAVE_W32
 MHD_DLL_RES_SRC = microhttpd_dll_res.rc
@@ -84,9 +126,14 @@
 EXTRA_libmicrohttpd_la_DEPENDENCIES = $(MHD_DLL_RES_LO)
 libmicrohttpd_la_LIBADD += $(MHD_DLL_RES_LO)
 
+AM_V_RC = $(am__v_RC_$(V))
+am__v_RC_ = $(am__v_RC_$(AM_DEFAULT_VERBOSITY))
+am__v_RC_0 = @echo "  RC      " $@;
+am__v_RC_1 = 
+
 # General rule is not required, but keep it just in case
 .rc.lo:
-	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $< -o $@
+	$(AM_V_RC) $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $< -o $@
 
 # To add dll resource only to .dll file and exclude it form static
 # lib, a little trick was used. Allow libtool to create file.lo,
@@ -97,35 +144,64 @@
 # Note: windres does not understand '-isystem' flag, so all
 # possible '-isystem' flags are replaced by simple '-I' flags.
 $(MHD_DLL_RES_LO): $(MHD_DLL_RES_SRC)
-	RC_CPP_FLAGS=" $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) " && \
-	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_CPP_FLAGS// -isystem / -I } $< -o $@ && \
-	echo > $@-empty.c && $(CC) $(AM_CFLAGS) $(CFLAGS) -c $@-empty.c -o $(@:.lo=.o) && rm -f $@-empty.c
+	$(AM_V_RC) RC_CPP_FLAGS=" $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) " && \
+	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_CPP_FLAGS// -isystem / -I} $< -o $@ && \
+	echo > $@-empty.c && $(CC) $(DEFS) $(AM_CFLAGS) $(CFLAGS) -c $@-empty.c -o $(@:.lo=.o) && rm -f $@-empty.c
 endif
 
 if USE_COVERAGE
   AM_CFLAGS += --coverage
 endif
 
-if !HAVE_TSEARCH
+if !MHD_USE_SYS_TSEARCH
 libmicrohttpd_la_SOURCES += \
   tsearch.c tsearch.h
 endif
 
 if HAVE_POSTPROCESSOR
 libmicrohttpd_la_SOURCES += \
-  postprocessor.c
+  postprocessor.c postprocessor.h
 endif
 
+if HAVE_ANYAUTH
+libmicrohttpd_la_SOURCES += \
+  gen_auth.c gen_auth.h
+endif
 if ENABLE_DAUTH
 libmicrohttpd_la_SOURCES += \
-  digestauth.c \
+  digestauth.c digestauth.h \
+  mhd_bithelpers.h mhd_byteorder.h mhd_align.h
+if ENABLE_MD5
+libmicrohttpd_la_SOURCES += \
+  mhd_md5_wrap.h
+if ! ENABLE_MD5_EXT
+libmicrohttpd_la_SOURCES += \
   md5.c md5.h
+else
+libmicrohttpd_la_SOURCES += \
+  md5_ext.c md5_ext.h
+endif
+endif
+if ENABLE_SHA256
+libmicrohttpd_la_SOURCES += \
+  mhd_sha256_wrap.h
+if ! ENABLE_SHA256_EXT
+libmicrohttpd_la_SOURCES += \
+  sha256.c sha256.h
+else
+libmicrohttpd_la_SOURCES += \
+  sha256_ext.c sha256_ext.h
+endif
+endif
+if ENABLE_SHA512_256
+libmicrohttpd_la_SOURCES += \
+  sha512_256.c sha512_256.h
+endif
 endif
 
 if ENABLE_BAUTH
 libmicrohttpd_la_SOURCES += \
-  basicauth.c \
-  base64.c base64.h
+  basicauth.c basicauth.h
 endif
 
 if ENABLE_HTTPS
@@ -133,10 +209,66 @@
   connection_https.c connection_https.h
 endif
 
-
-
 check_PROGRAMS = \
-  test_daemon
+  test_str_compare \
+  test_str_to_value \
+  test_str_from_value \
+  test_str_token \
+  test_str_token_remove \
+  test_str_tokens_remove \
+  test_str_pct \
+  test_str_bin_hex \
+  test_http_reasons \
+  test_sha1 \
+  test_start_stop \
+  test_daemon \
+  test_response_entries \
+  test_postprocessor_md \
+  test_client_put_shutdown \
+  test_client_put_close \
+  test_client_put_hard_close \
+  test_client_put_steps_shutdown \
+  test_client_put_steps_close \
+  test_client_put_steps_hard_close \
+  test_client_put_chunked_shutdown \
+  test_client_put_chunked_close \
+  test_client_put_chunked_hard_close \
+  test_client_put_chunked_steps_shutdown \
+  test_client_put_chunked_steps_close \
+  test_client_put_chunked_steps_hard_close \
+  test_options \
+  test_set_panic
+
+if ENABLE_MD5
+check_PROGRAMS += \
+  test_md5
+endif
+if ENABLE_SHA256
+check_PROGRAMS += \
+  test_sha256
+endif
+if ENABLE_SHA512_256
+check_PROGRAMS += \
+  test_sha512_256
+endif
+
+if HAVE_POSIX_THREADS
+if ENABLE_UPGRADE
+if USE_POSIX_THREADS
+  check_PROGRAMS += test_upgrade test_upgrade_large
+endif
+if USE_W32_THREADS
+  check_PROGRAMS += test_upgrade test_upgrade_large
+endif
+if ENABLE_HTTPS
+if USE_THREADS
+if USE_UPGRADE_TLS_TESTS
+check_PROGRAMS += test_upgrade_tls test_upgrade_large_tls
+endif
+endif
+endif
+endif
+endif
 
 if HAVE_POSTPROCESSOR
 check_PROGRAMS += \
@@ -145,32 +277,377 @@
   test_postprocessor_amp
 endif
 
+# Do not test trigger of select by shutdown of listen socket
+# on Cygwin as this ability is deliberately ignored on Cygwin
+# to improve compatibility with core OS.
+if !CYGWIN_TARGET
+if HAVE_POSIX_THREADS
+if HAVE_LISTEN_SHUTDOWN
+check_PROGRAMS += \
+  test_shutdown_select \
+  test_shutdown_poll
+else
+check_PROGRAMS += \
+  test_shutdown_select_ignore \
+  test_shutdown_poll_ignore
+endif
+endif
+endif
+
+if HAVE_ANYAUTH
+check_PROGRAMS += \
+  test_auth_parse
+endif
+if ENABLE_DAUTH
+check_PROGRAMS += \
+  test_str_quote \
+  test_dauth_userdigest \
+  test_dauth_userhash
+endif
+if ENABLE_BAUTH
+check_PROGRAMS += \
+  test_str_base64
+endif
+
+
+if HEAVY_TESTS
+if TESTS_STRESS_OS
+check_PROGRAMS += \
+  test_client_put_hard_close_stress_os \
+  test_client_put_steps_hard_close_stress_os \
+  test_client_put_chunked_steps_hard_close_stress_os
+endif
+endif
+
+
 TESTS = $(check_PROGRAMS)
 
+update-po-POTFILES.in: $(top_srcdir)/po/POTFILES.in
+
+$(top_srcdir)/po/POTFILES.in: $(srcdir)/Makefile.am
+	@echo "Creating $@"
+	@echo  src/include/microhttpd.h > "$@" && \
+	for src in $(am__libmicrohttpd_la_SOURCES_DIST) ; do \
+	  echo "$(subdir)/$$src" >> "$@" ; \
+	done
+
+test_start_stop_SOURCES = \
+  test_start_stop.c
+test_start_stop_LDADD = \
+  libmicrohttpd.la
+
 test_daemon_SOURCES = \
   test_daemon.c
 test_daemon_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
+  $(builddir)/libmicrohttpd.la
+
+test_response_entries_SOURCES = \
+  test_response_entries.c
+test_response_entries_LDADD = \
+  libmicrohttpd.la
+
+test_upgrade_SOURCES = \
+  test_upgrade.c test_helpers.h mhd_sockets.h
+test_upgrade_CPPFLAGS = \
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_upgrade_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+test_upgrade_LDFLAGS = \
+  $(MHD_TLS_LIB_LDFLAGS)
+test_upgrade_LDADD = \
+  $(builddir)/libmicrohttpd.la \
+  $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) \
+  $(PTHREAD_LIBS)
+
+test_upgrade_large_SOURCES = \
+  test_upgrade_large.c test_helpers.h mhd_sockets.h mhd_sockets.c mhd_itc.h mhd_itc_types.h mhd_itc.c
+test_upgrade_large_CPPFLAGS = \
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_upgrade_large_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+test_upgrade_large_LDFLAGS = \
+  $(MHD_TLS_LIB_LDFLAGS)
+test_upgrade_large_LDADD = \
+  $(builddir)/libmicrohttpd.la \
+  $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) \
+  $(PTHREAD_LIBS)
+
+test_upgrade_tls_SOURCES = \
+  test_upgrade.c test_helpers.h mhd_sockets.h
+test_upgrade_tls_CPPFLAGS = \
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_upgrade_tls_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+test_upgrade_tls_LDFLAGS = \
+  $(MHD_TLS_LIB_LDFLAGS)
+test_upgrade_tls_LDADD = \
+  $(builddir)/libmicrohttpd.la \
+  $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) \
+  $(PTHREAD_LIBS)
+
+test_upgrade_large_tls_SOURCES = \
+  test_upgrade_large.c test_helpers.h mhd_sockets.h mhd_sockets.c mhd_itc.h mhd_itc_types.h mhd_itc.c
+test_upgrade_large_tls_CPPFLAGS = \
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_upgrade_large_tls_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+test_upgrade_large_tls_LDFLAGS = \
+  $(MHD_TLS_LIB_LDFLAGS)
+test_upgrade_large_tls_LDADD = \
+  $(builddir)/libmicrohttpd.la \
+  $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) \
+  $(PTHREAD_LIBS)
 
 test_postprocessor_SOURCES = \
   test_postprocessor.c
 test_postprocessor_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_postprocessor_CFLAGS = \
+  $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
 test_postprocessor_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(MHD_W32_LIB)
+  $(builddir)/libmicrohttpd.la
 
 test_postprocessor_amp_SOURCES = \
   test_postprocessor_amp.c
 test_postprocessor_amp_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_postprocessor_amp_CFLAGS = \
+  $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
 test_postprocessor_amp_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
+  $(builddir)/libmicrohttpd.la
 
 test_postprocessor_large_SOURCES = \
   test_postprocessor_large.c
 test_postprocessor_large_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
+  $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_postprocessor_large_CFLAGS = \
+  $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
 test_postprocessor_large_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(MHD_W32_LIB)
+  $(builddir)/libmicrohttpd.la
+
+test_postprocessor_md_SOURCES = \
+  test_postprocessor_md.c postprocessor.h postprocessor.c \
+  internal.h internal.c mhd_str.h mhd_str.c \
+  mhd_panic.h mhd_panic.c
+
+test_shutdown_select_SOURCES = \
+  test_shutdown_select.c
+test_shutdown_select_CFLAGS = $(AM_CFLAGS)
+test_shutdown_select_LDADD = $(LDADD)
+if USE_POSIX_THREADS
+test_shutdown_select_CFLAGS += \
+  $(PTHREAD_CFLAGS)
+test_shutdown_select_LDADD += \
+  $(PTHREAD_LIBS)
+endif
+
+test_shutdown_poll_SOURCES = \
+  test_shutdown_select.c mhd_threads.h
+test_shutdown_poll_CFLAGS = $(AM_CFLAGS)
+test_shutdown_poll_LDADD = $(LDADD)
+if USE_POSIX_THREADS
+test_shutdown_poll_CFLAGS += \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
+test_shutdown_poll_LDADD += \
+  $(PTHREAD_LIBS)
+endif
+
+test_shutdown_select_ignore_SOURCES = \
+  test_shutdown_select.c
+test_shutdown_select_ignore_CFLAGS = $(AM_CFLAGS)
+test_shutdown_select_ignore_LDADD = $(LDADD)
+if USE_POSIX_THREADS
+test_shutdown_select_ignore_CFLAGS += \
+  $(PTHREAD_CFLAGS)
+test_shutdown_select_ignore_LDADD += \
+  $(PTHREAD_LIBS)
+endif
+
+test_shutdown_poll_ignore_SOURCES = \
+  test_shutdown_select.c mhd_threads.h
+test_shutdown_poll_ignore_CFLAGS = $(AM_CFLAGS)
+test_shutdown_poll_ignore_LDADD = $(LDADD)
+if USE_POSIX_THREADS
+test_shutdown_poll_ignore_CFLAGS += \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
+test_shutdown_poll_ignore_LDADD += \
+  $(PTHREAD_LIBS)
+endif
+
+test_str_compare_SOURCES = \
+  test_str.c test_helpers.h mhd_str.c mhd_str.h
+
+test_str_to_value_SOURCES = \
+  test_str.c test_helpers.h mhd_str.c mhd_str.h
+
+test_str_from_value_SOURCES = \
+  test_str.c test_helpers.h mhd_str.c mhd_str.h
+
+test_str_token_SOURCES = \
+  test_str_token.c mhd_str.c mhd_str.h
+
+test_str_token_remove_SOURCES = \
+  test_str_token_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h
+
+test_str_tokens_remove_SOURCES = \
+  test_str_tokens_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h
+
+test_http_reasons_SOURCES = \
+  test_http_reasons.c \
+  reason_phrase.c mhd_str.c mhd_str.h
+
+test_md5_SOURCES = \
+  test_md5.c test_helpers.h mhd_md5_wrap.h ../include/mhd_options.h
+if ! ENABLE_MD5_EXT
+test_md5_SOURCES += \
+  md5.c md5.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h
+test_md5_CPPFLAGS = $(AM_CPPFLAGS)
+test_md5_CFLAGS = $(AM_CFLAGS)
+test_md5_LDFLAGS = $(AM_LDFLAGS)
+test_md5_LDADD = $(LDADD)
+else
+test_md5_SOURCES += \
+  md5_ext.c md5_ext.h
+test_md5_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_md5_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+test_md5_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS)
+test_md5_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD)
+endif
+
+test_sha256_SOURCES = \
+  test_sha256.c test_helpers.h mhd_sha256_wrap.h ../include/mhd_options.h
+if ! ENABLE_SHA256_EXT
+test_sha256_SOURCES += \
+  sha256.c sha256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h
+test_sha256_CPPFLAGS = $(AM_CPPFLAGS)
+test_sha256_CFLAGS = $(AM_CFLAGS)
+test_sha256_LDFLAGS = $(AM_LDFLAGS)
+test_sha256_LDADD = $(LDADD)
+else
+test_sha256_SOURCES += \
+  sha256_ext.c sha256_ext.h
+test_sha256_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+test_sha256_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS)
+test_sha256_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS)
+test_sha256_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD)
+endif
+
+test_sha512_256_SOURCES = \
+  test_sha512_256.c test_helpers.h \
+  sha512_256.c sha512_256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h
+
+test_sha1_SOURCES = \
+  test_sha1.c test_helpers.h \
+  sha1.c sha1.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h
+
+test_auth_parse_SOURCES = \
+  test_auth_parse.c gen_auth.c gen_auth.h  mhd_str.h mhd_str.c mhd_assert.h
+
+test_str_quote_SOURCES = \
+  test_str_quote.c mhd_str.h mhd_str.c mhd_assert.h
+
+test_str_base64_SOURCES = \
+  test_str_base64.c mhd_str.h mhd_str.c mhd_assert.h
+
+test_str_pct_SOURCES = \
+  test_str_pct.c mhd_str.h mhd_str.c mhd_assert.h
+
+test_str_bin_hex_SOURCES = \
+  test_str_bin_hex.c mhd_str.h mhd_str.c mhd_assert.h
+
+test_options_SOURCES = \
+  test_options.c
+test_options_LDADD = \
+  $(builddir)/libmicrohttpd.la
+
+test_client_put_shutdown_SOURCES = \
+  test_client_put_stop.c
+test_client_put_shutdown_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_hard_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_hard_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_hard_close_stress_os_SOURCES = \
+  $(test_client_put_hard_close_SOURCES)
+test_client_put_hard_close_stress_os_LDADD = \
+  $(test_client_put_hard_close_LDADD)
+
+test_client_put_steps_shutdown_SOURCES = \
+  test_client_put_stop.c
+test_client_put_steps_shutdown_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_steps_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_steps_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_steps_hard_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_steps_hard_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_steps_hard_close_stress_os_SOURCES = \
+  $(test_client_put_steps_hard_close_SOURCES)
+test_client_put_steps_hard_close_stress_os_LDADD = \
+  $(test_client_put_steps_hard_close_LDADD)
+
+test_client_put_chunked_shutdown_SOURCES = \
+  test_client_put_stop.c
+test_client_put_chunked_shutdown_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_chunked_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_chunked_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_chunked_hard_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_chunked_hard_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_chunked_steps_shutdown_SOURCES = \
+  test_client_put_stop.c
+test_client_put_chunked_steps_shutdown_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_chunked_steps_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_chunked_steps_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_chunked_steps_hard_close_SOURCES = \
+  test_client_put_stop.c
+test_client_put_chunked_steps_hard_close_LDADD = \
+  libmicrohttpd.la
+
+test_client_put_chunked_steps_hard_close_stress_os_SOURCES = \
+  $(test_client_put_chunked_steps_hard_close_SOURCES)
+test_client_put_chunked_steps_hard_close_stress_os_LDADD = \
+  $(test_client_put_chunked_steps_hard_close_LDADD)
+
+test_set_panic_SOURCES = \
+  test_set_panic.c
+test_set_panic_LDADD = \
+  libmicrohttpd.la
+
+test_dauth_userdigest_SOURCES = \
+  test_dauth_userdigest.c
+test_dauth_userdigest_LDADD = \
+  libmicrohttpd.la
+
+test_dauth_userhash_SOURCES = \
+  test_dauth_userhash.c
+test_dauth_userhash_LDADD = \
+  libmicrohttpd.la
+
+.PHONY: update-po-POTFILES.in
diff --git a/src/microhttpd/Makefile.in b/src/microhttpd/Makefile.in
deleted file mode 100644
index f6aa7ab..0000000
--- a/src/microhttpd/Makefile.in
+++ /dev/null
@@ -1,1427 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@W32_SHARED_LIB_EXP_TRUE@am__append_1 = $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp
-@W32_SHARED_LIB_EXP_TRUE@am__append_2 = $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp
-@W32_STATIC_LIB_TRUE@am__append_3 = $(lt_cv_objdir)/libmicrohttpd-static.lib
-@W32_STATIC_LIB_TRUE@am__append_4 = $(lt_cv_objdir)/libmicrohttpd-static.lib
-@HAVE_W32_TRUE@am__append_5 = $(MHD_DLL_RES_LO)
-@USE_COVERAGE_TRUE@am__append_6 = --coverage
-@HAVE_TSEARCH_FALSE@am__append_7 = \
-@HAVE_TSEARCH_FALSE@  tsearch.c tsearch.h
-
-@HAVE_POSTPROCESSOR_TRUE@am__append_8 = \
-@HAVE_POSTPROCESSOR_TRUE@  postprocessor.c
-
-@ENABLE_DAUTH_TRUE@am__append_9 = \
-@ENABLE_DAUTH_TRUE@  digestauth.c \
-@ENABLE_DAUTH_TRUE@  md5.c md5.h
-
-@ENABLE_BAUTH_TRUE@am__append_10 = \
-@ENABLE_BAUTH_TRUE@  basicauth.c \
-@ENABLE_BAUTH_TRUE@  base64.c base64.h
-
-@ENABLE_HTTPS_TRUE@am__append_11 = \
-@ENABLE_HTTPS_TRUE@  connection_https.c connection_https.h
-
-check_PROGRAMS = test_daemon$(EXEEXT) $(am__EXEEXT_1)
-@HAVE_POSTPROCESSOR_TRUE@am__append_12 = \
-@HAVE_POSTPROCESSOR_TRUE@  test_postprocessor \
-@HAVE_POSTPROCESSOR_TRUE@  test_postprocessor_large \
-@HAVE_POSTPROCESSOR_TRUE@  test_postprocessor_amp
-
-subdir = src/microhttpd
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(srcdir)/microhttpd_dll_res.rc.in $(top_srcdir)/depcomp \
-	$(top_srcdir)/test-driver
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES = microhttpd_dll_res.rc
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(libdir)"
-LTLIBRARIES = $(lib_LTLIBRARIES)
-am__DEPENDENCIES_1 =
-am__libmicrohttpd_la_SOURCES_DIST = connection.c connection.h \
-	reason_phrase.c reason_phrase.h daemon.c internal.c internal.h \
-	memorypool.c memorypool.h response.c response.h tsearch.c \
-	tsearch.h postprocessor.c digestauth.c md5.c md5.h basicauth.c \
-	base64.c base64.h connection_https.c connection_https.h
-@HAVE_TSEARCH_FALSE@am__objects_1 = libmicrohttpd_la-tsearch.lo
-@HAVE_POSTPROCESSOR_TRUE@am__objects_2 =  \
-@HAVE_POSTPROCESSOR_TRUE@	libmicrohttpd_la-postprocessor.lo
-@ENABLE_DAUTH_TRUE@am__objects_3 = libmicrohttpd_la-digestauth.lo \
-@ENABLE_DAUTH_TRUE@	libmicrohttpd_la-md5.lo
-@ENABLE_BAUTH_TRUE@am__objects_4 = libmicrohttpd_la-basicauth.lo \
-@ENABLE_BAUTH_TRUE@	libmicrohttpd_la-base64.lo
-@ENABLE_HTTPS_TRUE@am__objects_5 =  \
-@ENABLE_HTTPS_TRUE@	libmicrohttpd_la-connection_https.lo
-am_libmicrohttpd_la_OBJECTS = libmicrohttpd_la-connection.lo \
-	libmicrohttpd_la-reason_phrase.lo libmicrohttpd_la-daemon.lo \
-	libmicrohttpd_la-internal.lo libmicrohttpd_la-memorypool.lo \
-	libmicrohttpd_la-response.lo $(am__objects_1) $(am__objects_2) \
-	$(am__objects_3) $(am__objects_4) $(am__objects_5)
-libmicrohttpd_la_OBJECTS = $(am_libmicrohttpd_la_OBJECTS)
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-libmicrohttpd_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(libmicrohttpd_la_CFLAGS) $(CFLAGS) \
-	$(libmicrohttpd_la_LDFLAGS) $(LDFLAGS) -o $@
-@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_1 = test_postprocessor$(EXEEXT) \
-@HAVE_POSTPROCESSOR_TRUE@	test_postprocessor_large$(EXEEXT) \
-@HAVE_POSTPROCESSOR_TRUE@	test_postprocessor_amp$(EXEEXT)
-am_test_daemon_OBJECTS = test_daemon.$(OBJEXT)
-test_daemon_OBJECTS = $(am_test_daemon_OBJECTS)
-test_daemon_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_postprocessor_OBJECTS =  \
-	test_postprocessor-test_postprocessor.$(OBJEXT)
-test_postprocessor_OBJECTS = $(am_test_postprocessor_OBJECTS)
-test_postprocessor_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la $(MHD_W32_LIB)
-am_test_postprocessor_amp_OBJECTS =  \
-	test_postprocessor_amp-test_postprocessor_amp.$(OBJEXT)
-test_postprocessor_amp_OBJECTS = $(am_test_postprocessor_amp_OBJECTS)
-test_postprocessor_amp_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_postprocessor_large_OBJECTS =  \
-	test_postprocessor_large-test_postprocessor_large.$(OBJEXT)
-test_postprocessor_large_OBJECTS =  \
-	$(am_test_postprocessor_large_OBJECTS)
-test_postprocessor_large_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la $(MHD_W32_LIB)
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(libmicrohttpd_la_SOURCES) $(test_daemon_SOURCES) \
-	$(test_postprocessor_SOURCES) \
-	$(test_postprocessor_amp_SOURCES) \
-	$(test_postprocessor_large_SOURCES)
-DIST_SOURCES = $(am__libmicrohttpd_la_SOURCES_DIST) \
-	$(test_daemon_SOURCES) $(test_postprocessor_SOURCES) \
-	$(test_postprocessor_amp_SOURCES) \
-	$(test_postprocessor_large_SOURCES)
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-DATA = $(noinst_DATA)
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-am__tty_colors_dummy = \
-  mgn= red= grn= lgn= blu= brg= std=; \
-  am__color_tests=no
-am__tty_colors = { \
-  $(am__tty_colors_dummy); \
-  if test "X$(AM_COLOR_TESTS)" = Xno; then \
-    am__color_tests=no; \
-  elif test "X$(AM_COLOR_TESTS)" = Xalways; then \
-    am__color_tests=yes; \
-  elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \
-    am__color_tests=yes; \
-  fi; \
-  if test $$am__color_tests = yes; then \
-    red=''; \
-    grn=''; \
-    lgn=''; \
-    blu=''; \
-    mgn=''; \
-    brg=''; \
-    std=''; \
-  fi; \
-}
-am__recheck_rx = ^[ 	]*:recheck:[ 	]*
-am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
-am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
-# A command that, given a newline-separated list of test names on the
-# standard input, print the name of the tests that are to be re-run
-# upon "make recheck".
-am__list_recheck_tests = $(AWK) '{ \
-  recheck = 1; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-        { \
-          if ((getline line2 < ($$0 ".log")) < 0) \
-	    recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \
-        { \
-          recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \
-        { \
-          break; \
-        } \
-    }; \
-  if (recheck) \
-    print $$0; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# A command that, given a newline-separated list of test names on the
-# standard input, create the global log from their .trs and .log files.
-am__create_global_log = $(AWK) ' \
-function fatal(msg) \
-{ \
-  print "fatal: making $@: " msg | "cat >&2"; \
-  exit 1; \
-} \
-function rst_section(header) \
-{ \
-  print header; \
-  len = length(header); \
-  for (i = 1; i <= len; i = i + 1) \
-    printf "="; \
-  printf "\n\n"; \
-} \
-{ \
-  copy_in_global_log = 1; \
-  global_test_result = "RUN"; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-         fatal("failed to read from " $$0 ".trs"); \
-      if (line ~ /$(am__global_test_result_rx)/) \
-        { \
-          sub("$(am__global_test_result_rx)", "", line); \
-          sub("[ 	]*$$", "", line); \
-          global_test_result = line; \
-        } \
-      else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \
-        copy_in_global_log = 0; \
-    }; \
-  if (copy_in_global_log) \
-    { \
-      rst_section(global_test_result ": " $$0); \
-      while ((rc = (getline line < ($$0 ".log"))) != 0) \
-      { \
-        if (rc < 0) \
-          fatal("failed to read from " $$0 ".log"); \
-        print line; \
-      }; \
-      printf "\n"; \
-    }; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# Restructured Text title.
-am__rst_title = { sed 's/.*/   &   /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; }
-# Solaris 10 'make', and several other traditional 'make' implementations,
-# pass "-e" to $(SHELL), and POSIX 2008 even requires this.  Work around it
-# by disabling -e (using the XSI extension "set +e") if it's set.
-am__sh_e_setup = case $$- in *e*) set +e;; esac
-# Default flags passed to test drivers.
-am__common_driver_flags = \
-  --color-tests "$$am__color_tests" \
-  --enable-hard-errors "$$am__enable_hard_errors" \
-  --expect-failure "$$am__expect_failure"
-# To be inserted before the command running the test.  Creates the
-# directory for the log if needed.  Stores in $dir the directory
-# containing $f, in $tst the test, in $log the log.  Executes the
-# developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and
-# passes TESTS_ENVIRONMENT.  Set up options for the wrapper that
-# will run the test scripts (or their associated LOG_COMPILER, if
-# thy have one).
-am__check_pre = \
-$(am__sh_e_setup);					\
-$(am__vpath_adj_setup) $(am__vpath_adj)			\
-$(am__tty_colors);					\
-srcdir=$(srcdir); export srcdir;			\
-case "$@" in						\
-  */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;;	\
-    *) am__odir=.;; 					\
-esac;							\
-test "x$$am__odir" = x"." || test -d "$$am__odir" 	\
-  || $(MKDIR_P) "$$am__odir" || exit $$?;		\
-if test -f "./$$f"; then dir=./;			\
-elif test -f "$$f"; then dir=;				\
-else dir="$(srcdir)/"; fi;				\
-tst=$$dir$$f; log='$@'; 				\
-if test -n '$(DISABLE_HARD_ERRORS)'; then		\
-  am__enable_hard_errors=no; 				\
-else							\
-  am__enable_hard_errors=yes; 				\
-fi; 							\
-case " $(XFAIL_TESTS) " in				\
-  *[\ \	]$$f[\ \	]* | *[\ \	]$$dir$$f[\ \	]*) \
-    am__expect_failure=yes;;				\
-  *)							\
-    am__expect_failure=no;;				\
-esac; 							\
-$(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT)
-# A shell command to get the names of the tests scripts with any registered
-# extension removed (i.e., equivalently, the names of the test logs, with
-# the '.log' extension removed).  The result is saved in the shell variable
-# '$bases'.  This honors runtime overriding of TESTS and TEST_LOGS.  Sadly,
-# we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)",
-# since that might cause problem with VPATH rewrites for suffix-less tests.
-# See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'.
-am__set_TESTS_bases = \
-  bases='$(TEST_LOGS)'; \
-  bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \
-  bases=`echo $$bases`
-RECHECK_LOGS = $(TEST_LOGS)
-AM_RECURSIVE_TARGETS = check recheck
-TEST_SUITE_LOG = test-suite.log
-TEST_EXTENSIONS = @EXEEXT@ .test
-LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)
-am__set_b = \
-  case '$@' in \
-    */*) \
-      case '$*' in \
-        */*) b='$*';; \
-          *) b=`echo '$@' | sed 's/\.log$$//'`; \
-       esac;; \
-    *) \
-      b='$*';; \
-  esac
-am__test_logs1 = $(TESTS:=.log)
-am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log)
-TEST_LOGS = $(am__test_logs2:.test.log=.log)
-TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
-	$(TEST_LOG_FLAGS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include \
-  -I$(top_srcdir)/src/microhttpd
-
-AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS) $(am__append_6)
-@HAVE_W32_TRUE@MHD_W32_LIB = $(top_builddir)/src/platform/libplatform_interface.la
-lib_LTLIBRARIES = \
-  libmicrohttpd.la
-
-noinst_DATA = $(am__append_1) $(am__append_3)
-MOSTLYCLEANFILES = $(am__append_2) $(am__append_4)
-@W32_SHARED_LIB_EXP_FALSE@W32_MHD_LIB_LDFLAGS = 
-@W32_SHARED_LIB_EXP_TRUE@W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd.def -XCClinker -static-libgcc
-libmicrohttpd_la_SOURCES = connection.c connection.h reason_phrase.c \
-	reason_phrase.h daemon.c internal.c internal.h memorypool.c \
-	memorypool.h response.c response.h $(am__append_7) \
-	$(am__append_8) $(am__append_9) $(am__append_10) \
-	$(am__append_11)
-libmicrohttpd_la_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) \
-  -DBUILDING_MHD_LIB=1
-
-libmicrohttpd_la_CFLAGS = \
-  $(AM_CFLAGS) $(MHD_LIB_CFLAGS)
-
-libmicrohttpd_la_LDFLAGS = \
-  $(MHD_LIB_LDFLAGS) \
-  $(W32_MHD_LIB_LDFLAGS) \
-  -version-info @LIB_VERSION_CURRENT@:@LIB_VERSION_REVISION@:@LIB_VERSION_AGE@
-
-libmicrohttpd_la_LIBADD = $(MHD_W32_LIB) $(MHD_LIBDEPS) \
-	$(am__append_5)
-libmicrohttpd_la_DEPENDENCIES = \
-  $(MHD_W32_LIB)
-
-@HAVE_W32_TRUE@MHD_DLL_RES_SRC = microhttpd_dll_res.rc
-@HAVE_W32_TRUE@MHD_DLL_RES_LO = libmicrohttpd_la-$(MHD_DLL_RES_SRC:.rc=.lo)
-@HAVE_W32_TRUE@EXTRA_libmicrohttpd_la_DEPENDENCIES = $(MHD_DLL_RES_LO)
-TESTS = $(check_PROGRAMS)
-test_daemon_SOURCES = \
-  test_daemon.c
-
-test_daemon_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-test_postprocessor_SOURCES = \
-  test_postprocessor.c
-
-test_postprocessor_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
-
-test_postprocessor_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(MHD_W32_LIB)
-
-test_postprocessor_amp_SOURCES = \
-  test_postprocessor_amp.c
-
-test_postprocessor_amp_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
-
-test_postprocessor_amp_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-test_postprocessor_large_SOURCES = \
-  test_postprocessor_large.c
-
-test_postprocessor_large_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS)
-
-test_postprocessor_large_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(MHD_W32_LIB)
-
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .log .o .obj .rc .test .test$(EXEEXT) .trs
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/microhttpd/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/microhttpd/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-microhttpd_dll_res.rc: $(top_builddir)/config.status $(srcdir)/microhttpd_dll_res.rc.in
-	cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@
-
-install-libLTLIBRARIES: $(lib_LTLIBRARIES)
-	@$(NORMAL_INSTALL)
-	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
-	list2=; for p in $$list; do \
-	  if test -f $$p; then \
-	    list2="$$list2 $$p"; \
-	  else :; fi; \
-	done; \
-	test -z "$$list2" || { \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \
-	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
-	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
-	}
-
-uninstall-libLTLIBRARIES:
-	@$(NORMAL_UNINSTALL)
-	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
-	for p in $$list; do \
-	  $(am__strip_dir) \
-	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
-	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
-	done
-
-clean-libLTLIBRARIES:
-	-test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
-	@list='$(lib_LTLIBRARIES)'; \
-	locs=`for p in $$list; do echo $$p; done | \
-	      sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \
-	      sort -u`; \
-	test -z "$$locs" || { \
-	  echo rm -f $${locs}; \
-	  rm -f $${locs}; \
-	}
-
-libmicrohttpd.la: $(libmicrohttpd_la_OBJECTS) $(libmicrohttpd_la_DEPENDENCIES) $(EXTRA_libmicrohttpd_la_DEPENDENCIES) 
-	$(AM_V_CCLD)$(libmicrohttpd_la_LINK) -rpath $(libdir) $(libmicrohttpd_la_OBJECTS) $(libmicrohttpd_la_LIBADD) $(LIBS)
-
-clean-checkPROGRAMS:
-	@list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-test_daemon$(EXEEXT): $(test_daemon_OBJECTS) $(test_daemon_DEPENDENCIES) $(EXTRA_test_daemon_DEPENDENCIES) 
-	@rm -f test_daemon$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_daemon_OBJECTS) $(test_daemon_LDADD) $(LIBS)
-
-test_postprocessor$(EXEEXT): $(test_postprocessor_OBJECTS) $(test_postprocessor_DEPENDENCIES) $(EXTRA_test_postprocessor_DEPENDENCIES) 
-	@rm -f test_postprocessor$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_postprocessor_OBJECTS) $(test_postprocessor_LDADD) $(LIBS)
-
-test_postprocessor_amp$(EXEEXT): $(test_postprocessor_amp_OBJECTS) $(test_postprocessor_amp_DEPENDENCIES) $(EXTRA_test_postprocessor_amp_DEPENDENCIES) 
-	@rm -f test_postprocessor_amp$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_postprocessor_amp_OBJECTS) $(test_postprocessor_amp_LDADD) $(LIBS)
-
-test_postprocessor_large$(EXEEXT): $(test_postprocessor_large_OBJECTS) $(test_postprocessor_large_DEPENDENCIES) $(EXTRA_test_postprocessor_large_DEPENDENCIES) 
-	@rm -f test_postprocessor_large$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_postprocessor_large_OBJECTS) $(test_postprocessor_large_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-base64.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-connection.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-daemon.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-internal.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-md5.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-response.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_daemon.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor-test_postprocessor.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-libmicrohttpd_la-connection.lo: connection.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-connection.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-connection.Tpo -c -o libmicrohttpd_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-connection.Tpo $(DEPDIR)/libmicrohttpd_la-connection.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='connection.c' object='libmicrohttpd_la-connection.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c
-
-libmicrohttpd_la-reason_phrase.lo: reason_phrase.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-reason_phrase.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-reason_phrase.Tpo -c -o libmicrohttpd_la-reason_phrase.lo `test -f 'reason_phrase.c' || echo '$(srcdir)/'`reason_phrase.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-reason_phrase.Tpo $(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='reason_phrase.c' object='libmicrohttpd_la-reason_phrase.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-reason_phrase.lo `test -f 'reason_phrase.c' || echo '$(srcdir)/'`reason_phrase.c
-
-libmicrohttpd_la-daemon.lo: daemon.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-daemon.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-daemon.Tpo -c -o libmicrohttpd_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-daemon.Tpo $(DEPDIR)/libmicrohttpd_la-daemon.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='daemon.c' object='libmicrohttpd_la-daemon.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c
-
-libmicrohttpd_la-internal.lo: internal.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-internal.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-internal.Tpo -c -o libmicrohttpd_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-internal.Tpo $(DEPDIR)/libmicrohttpd_la-internal.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='internal.c' object='libmicrohttpd_la-internal.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c
-
-libmicrohttpd_la-memorypool.lo: memorypool.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-memorypool.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-memorypool.Tpo -c -o libmicrohttpd_la-memorypool.lo `test -f 'memorypool.c' || echo '$(srcdir)/'`memorypool.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-memorypool.Tpo $(DEPDIR)/libmicrohttpd_la-memorypool.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='memorypool.c' object='libmicrohttpd_la-memorypool.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-memorypool.lo `test -f 'memorypool.c' || echo '$(srcdir)/'`memorypool.c
-
-libmicrohttpd_la-response.lo: response.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-response.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-response.Tpo -c -o libmicrohttpd_la-response.lo `test -f 'response.c' || echo '$(srcdir)/'`response.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-response.Tpo $(DEPDIR)/libmicrohttpd_la-response.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='response.c' object='libmicrohttpd_la-response.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-response.lo `test -f 'response.c' || echo '$(srcdir)/'`response.c
-
-libmicrohttpd_la-tsearch.lo: tsearch.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-tsearch.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-tsearch.Tpo -c -o libmicrohttpd_la-tsearch.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-tsearch.Tpo $(DEPDIR)/libmicrohttpd_la-tsearch.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tsearch.c' object='libmicrohttpd_la-tsearch.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-tsearch.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c
-
-libmicrohttpd_la-postprocessor.lo: postprocessor.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-postprocessor.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-postprocessor.Tpo -c -o libmicrohttpd_la-postprocessor.lo `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-postprocessor.Tpo $(DEPDIR)/libmicrohttpd_la-postprocessor.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='postprocessor.c' object='libmicrohttpd_la-postprocessor.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-postprocessor.lo `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c
-
-libmicrohttpd_la-digestauth.lo: digestauth.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-digestauth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-digestauth.Tpo -c -o libmicrohttpd_la-digestauth.lo `test -f 'digestauth.c' || echo '$(srcdir)/'`digestauth.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-digestauth.Tpo $(DEPDIR)/libmicrohttpd_la-digestauth.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='digestauth.c' object='libmicrohttpd_la-digestauth.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-digestauth.lo `test -f 'digestauth.c' || echo '$(srcdir)/'`digestauth.c
-
-libmicrohttpd_la-md5.lo: md5.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-md5.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-md5.Tpo -c -o libmicrohttpd_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-md5.Tpo $(DEPDIR)/libmicrohttpd_la-md5.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='md5.c' object='libmicrohttpd_la-md5.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c
-
-libmicrohttpd_la-basicauth.lo: basicauth.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-basicauth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-basicauth.Tpo -c -o libmicrohttpd_la-basicauth.lo `test -f 'basicauth.c' || echo '$(srcdir)/'`basicauth.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-basicauth.Tpo $(DEPDIR)/libmicrohttpd_la-basicauth.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='basicauth.c' object='libmicrohttpd_la-basicauth.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-basicauth.lo `test -f 'basicauth.c' || echo '$(srcdir)/'`basicauth.c
-
-libmicrohttpd_la-base64.lo: base64.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-base64.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-base64.Tpo -c -o libmicrohttpd_la-base64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-base64.Tpo $(DEPDIR)/libmicrohttpd_la-base64.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='base64.c' object='libmicrohttpd_la-base64.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-base64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c
-
-libmicrohttpd_la-connection_https.lo: connection_https.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-connection_https.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-connection_https.Tpo -c -o libmicrohttpd_la-connection_https.lo `test -f 'connection_https.c' || echo '$(srcdir)/'`connection_https.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-connection_https.Tpo $(DEPDIR)/libmicrohttpd_la-connection_https.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='connection_https.c' object='libmicrohttpd_la-connection_https.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-connection_https.lo `test -f 'connection_https.c' || echo '$(srcdir)/'`connection_https.c
-
-test_postprocessor-test_postprocessor.o: test_postprocessor.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor-test_postprocessor.o -MD -MP -MF $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo -c -o test_postprocessor-test_postprocessor.o `test -f 'test_postprocessor.c' || echo '$(srcdir)/'`test_postprocessor.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo $(DEPDIR)/test_postprocessor-test_postprocessor.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_postprocessor.c' object='test_postprocessor-test_postprocessor.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor-test_postprocessor.o `test -f 'test_postprocessor.c' || echo '$(srcdir)/'`test_postprocessor.c
-
-test_postprocessor-test_postprocessor.obj: test_postprocessor.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor-test_postprocessor.obj -MD -MP -MF $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo -c -o test_postprocessor-test_postprocessor.obj `if test -f 'test_postprocessor.c'; then $(CYGPATH_W) 'test_postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo $(DEPDIR)/test_postprocessor-test_postprocessor.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_postprocessor.c' object='test_postprocessor-test_postprocessor.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor-test_postprocessor.obj `if test -f 'test_postprocessor.c'; then $(CYGPATH_W) 'test_postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor.c'; fi`
-
-test_postprocessor_amp-test_postprocessor_amp.o: test_postprocessor_amp.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_amp-test_postprocessor_amp.o -MD -MP -MF $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo -c -o test_postprocessor_amp-test_postprocessor_amp.o `test -f 'test_postprocessor_amp.c' || echo '$(srcdir)/'`test_postprocessor_amp.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_postprocessor_amp.c' object='test_postprocessor_amp-test_postprocessor_amp.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_amp-test_postprocessor_amp.o `test -f 'test_postprocessor_amp.c' || echo '$(srcdir)/'`test_postprocessor_amp.c
-
-test_postprocessor_amp-test_postprocessor_amp.obj: test_postprocessor_amp.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_amp-test_postprocessor_amp.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo -c -o test_postprocessor_amp-test_postprocessor_amp.obj `if test -f 'test_postprocessor_amp.c'; then $(CYGPATH_W) 'test_postprocessor_amp.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_amp.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_postprocessor_amp.c' object='test_postprocessor_amp-test_postprocessor_amp.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_amp-test_postprocessor_amp.obj `if test -f 'test_postprocessor_amp.c'; then $(CYGPATH_W) 'test_postprocessor_amp.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_amp.c'; fi`
-
-test_postprocessor_large-test_postprocessor_large.o: test_postprocessor_large.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_large-test_postprocessor_large.o -MD -MP -MF $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo -c -o test_postprocessor_large-test_postprocessor_large.o `test -f 'test_postprocessor_large.c' || echo '$(srcdir)/'`test_postprocessor_large.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_postprocessor_large.c' object='test_postprocessor_large-test_postprocessor_large.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_large-test_postprocessor_large.o `test -f 'test_postprocessor_large.c' || echo '$(srcdir)/'`test_postprocessor_large.c
-
-test_postprocessor_large-test_postprocessor_large.obj: test_postprocessor_large.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_large-test_postprocessor_large.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo -c -o test_postprocessor_large-test_postprocessor_large.obj `if test -f 'test_postprocessor_large.c'; then $(CYGPATH_W) 'test_postprocessor_large.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_large.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_postprocessor_large.c' object='test_postprocessor_large-test_postprocessor_large.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_large-test_postprocessor_large.obj `if test -f 'test_postprocessor_large.c'; then $(CYGPATH_W) 'test_postprocessor_large.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_large.c'; fi`
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-am
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-am
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-am
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-# Recover from deleted '.trs' file; this should ensure that
-# "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create
-# both 'foo.log' and 'foo.trs'.  Break the recipe in two subshells
-# to avoid problems with "make -n".
-.log.trs:
-	rm -f $< $@
-	$(MAKE) $(AM_MAKEFLAGS) $<
-
-# Leading 'am--fnord' is there to ensure the list of targets does not
-# expand to empty, as could happen e.g. with make check TESTS=''.
-am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck)
-am--force-recheck:
-	@:
-
-$(TEST_SUITE_LOG): $(TEST_LOGS)
-	@$(am__set_TESTS_bases); \
-	am__f_ok () { test -f "$$1" && test -r "$$1"; }; \
-	redo_bases=`for i in $$bases; do \
-	              am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \
-	            done`; \
-	if test -n "$$redo_bases"; then \
-	  redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \
-	  redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \
-	  if $(am__make_dryrun); then :; else \
-	    rm -f $$redo_logs && rm -f $$redo_results || exit 1; \
-	  fi; \
-	fi; \
-	if test -n "$$am__remaking_logs"; then \
-	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
-	       "recursion detected" >&2; \
-	else \
-	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
-	fi; \
-	if $(am__make_dryrun); then :; else \
-	  st=0;  \
-	  errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \
-	  for i in $$redo_bases; do \
-	    test -f $$i.trs && test -r $$i.trs \
-	      || { echo "$$errmsg $$i.trs" >&2; st=1; }; \
-	    test -f $$i.log && test -r $$i.log \
-	      || { echo "$$errmsg $$i.log" >&2; st=1; }; \
-	  done; \
-	  test $$st -eq 0 || exit 1; \
-	fi
-	@$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \
-	ws='[ 	]'; \
-	results=`for b in $$bases; do echo $$b.trs; done`; \
-	test -n "$$results" || results=/dev/null; \
-	all=`  grep "^$$ws*:test-result:"           $$results | wc -l`; \
-	pass=` grep "^$$ws*:test-result:$$ws*PASS"  $$results | wc -l`; \
-	fail=` grep "^$$ws*:test-result:$$ws*FAIL"  $$results | wc -l`; \
-	skip=` grep "^$$ws*:test-result:$$ws*SKIP"  $$results | wc -l`; \
-	xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \
-	xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \
-	error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \
-	if test `expr $$fail + $$xpass + $$error` -eq 0; then \
-	  success=true; \
-	else \
-	  success=false; \
-	fi; \
-	br='==================='; br=$$br$$br$$br$$br; \
-	result_count () \
-	{ \
-	    if test x"$$1" = x"--maybe-color"; then \
-	      maybe_colorize=yes; \
-	    elif test x"$$1" = x"--no-color"; then \
-	      maybe_colorize=no; \
-	    else \
-	      echo "$@: invalid 'result_count' usage" >&2; exit 4; \
-	    fi; \
-	    shift; \
-	    desc=$$1 count=$$2; \
-	    if test $$maybe_colorize = yes && test $$count -gt 0; then \
-	      color_start=$$3 color_end=$$std; \
-	    else \
-	      color_start= color_end=; \
-	    fi; \
-	    echo "$${color_start}# $$desc $$count$${color_end}"; \
-	}; \
-	create_testsuite_report () \
-	{ \
-	  result_count $$1 "TOTAL:" $$all   "$$brg"; \
-	  result_count $$1 "PASS: " $$pass  "$$grn"; \
-	  result_count $$1 "SKIP: " $$skip  "$$blu"; \
-	  result_count $$1 "XFAIL:" $$xfail "$$lgn"; \
-	  result_count $$1 "FAIL: " $$fail  "$$red"; \
-	  result_count $$1 "XPASS:" $$xpass "$$red"; \
-	  result_count $$1 "ERROR:" $$error "$$mgn"; \
-	}; \
-	{								\
-	  echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" |	\
-	    $(am__rst_title);						\
-	  create_testsuite_report --no-color;				\
-	  echo;								\
-	  echo ".. contents:: :depth: 2";				\
-	  echo;								\
-	  for b in $$bases; do echo $$b; done				\
-	    | $(am__create_global_log);					\
-	} >$(TEST_SUITE_LOG).tmp || exit 1;				\
-	mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG);			\
-	if $$success; then						\
-	  col="$$grn";							\
-	 else								\
-	  col="$$red";							\
-	  test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG);		\
-	fi;								\
-	echo "$${col}$$br$${std}"; 					\
-	echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}";	\
-	echo "$${col}$$br$${std}"; 					\
-	create_testsuite_report --maybe-color;				\
-	echo "$$col$$br$$std";						\
-	if $$success; then :; else					\
-	  echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}";		\
-	  if test -n "$(PACKAGE_BUGREPORT)"; then			\
-	    echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}";	\
-	  fi;								\
-	  echo "$$col$$br$$std";					\
-	fi;								\
-	$$success || exit 1
-
-check-TESTS:
-	@list='$(RECHECK_LOGS)';           test -z "$$list" || rm -f $$list
-	@list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	trs_list=`for i in $$bases; do echo $$i.trs; done`; \
-	log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \
-	exit $$?;
-recheck: all $(check_PROGRAMS)
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	bases=`for i in $$bases; do echo $$i; done \
-	         | $(am__list_recheck_tests)` || exit 1; \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	log_list=`echo $$log_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \
-	        am__force_recheck=am--force-recheck \
-	        TEST_LOGS="$$log_list"; \
-	exit $$?
-test_daemon.log: test_daemon$(EXEEXT)
-	@p='test_daemon$(EXEEXT)'; \
-	b='test_daemon'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_postprocessor.log: test_postprocessor$(EXEEXT)
-	@p='test_postprocessor$(EXEEXT)'; \
-	b='test_postprocessor'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_postprocessor_large.log: test_postprocessor_large$(EXEEXT)
-	@p='test_postprocessor_large$(EXEEXT)'; \
-	b='test_postprocessor_large'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_postprocessor_amp.log: test_postprocessor_amp$(EXEEXT)
-	@p='test_postprocessor_amp$(EXEEXT)'; \
-	b='test_postprocessor_amp'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-.test.log:
-	@p='$<'; \
-	$(am__set_b); \
-	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-@am__EXEEXT_TRUE@.test$(EXEEXT).log:
-@am__EXEEXT_TRUE@	@p='$<'; \
-@am__EXEEXT_TRUE@	$(am__set_b); \
-@am__EXEEXT_TRUE@	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-@am__EXEEXT_TRUE@	--log-file $$b.log --trs-file $$b.trs \
-@am__EXEEXT_TRUE@	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-@am__EXEEXT_TRUE@	"$$tst" $(AM_TESTS_FD_REDIRECT)
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
-	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
-check: check-am
-all-am: Makefile $(LTLIBRARIES) $(DATA)
-installdirs:
-	for dir in "$(DESTDIR)$(libdir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-	-test -z "$(MOSTLYCLEANFILES)" || rm -f $(MOSTLYCLEANFILES)
-	-test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS)
-	-test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs)
-	-test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \
-	clean-libtool mostlyclean-am
-
-distclean: distclean-am
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am: install-libLTLIBRARIES
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-libLTLIBRARIES
-
-.MAKE: check-am install-am install-strip
-
-.PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \
-	clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \
-	clean-libtool cscopelist-am ctags ctags-am distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am \
-	install-libLTLIBRARIES install-man install-pdf install-pdf-am \
-	install-ps install-ps-am install-strip installcheck \
-	installcheck-am installdirs maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-compile \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	recheck tags tags-am uninstall uninstall-am \
-	uninstall-libLTLIBRARIES
-
-
-@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.def: libmicrohttpd.la
-
-@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.exp: $(lt_cv_objdir)/libmicrohttpd.lib
-
-@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS)
-@USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@	@echo Creating $@ and libmicrohttpd.exp by $(MS_LIB_TOOL)... && \
-@USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@	dll_name=`$(EGREP) -o dlname=\'.+\' libmicrohttpd.la` && \
-@USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@	dll_name=$${dll_name#*\'} && dll_name=$${dll_name%\'} && test -n "$$dll_name" && \
-@USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@	echo Creating $$dll_name by $(MS_LIB_TOOL).. && cd "$(lt_cv_objdir)" && \
-@USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@	$(MS_LIB_TOOL) -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) && cd ..
-@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@	@echo Creating $@ and libmicrohttpd.exp by $(DLLTOOL)... && \
-@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@	dll_name=`$(EGREP) -o dlname=\'.+\' libmicrohttpd.la` && \
-@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@	dll_name=$${dll_name#*\'} && dll_name=$${dll_name%\'} && test -n "$$dll_name" && \
-@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@	echo Creating $$dll_name by $(DLLTOOL).. && cd "$(lt_cv_objdir)" && \
-@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@	$(DLLTOOL) -d ./libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp && cd .. &&\
-@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@	echo Created libmicrohttpd.exp and libmicrohttpd.lib.
-
-@W32_STATIC_LIB_TRUE@$(lt_cv_objdir)/libmicrohttpd-static.lib: libmicrohttpd.la $(libmicrohttpd_la_OBJECTS)
-@USE_MS_LIB_TOOL_TRUE@@W32_STATIC_LIB_TRUE@	$(MS_LIB_TOOL) -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o)
-@USE_MS_LIB_TOOL_FALSE@@W32_STATIC_LIB_TRUE@	cp $(lt_cv_objdir)/libmicrohttpd.a $@
-
-# General rule is not required, but keep it just in case
-@HAVE_W32_TRUE@.rc.lo:
-@HAVE_W32_TRUE@	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $< -o $@
-
-# To add dll resource only to .dll file and exclude it form static
-# lib, a little trick was used. Allow libtool to create file.lo,
-# file.o and .libs/file.lo, .libs/file.o files, then overwrite file.o
-# by empty object generated from empty c-file. Later libtool will
-# use .libs/file.o for shared lib and empty file.o for static lib.
-# This implementation is based on trick found in liblzma.
-# Note: windres does not understand '-isystem' flag, so all
-# possible '-isystem' flags are replaced by simple '-I' flags.
-@HAVE_W32_TRUE@$(MHD_DLL_RES_LO): $(MHD_DLL_RES_SRC)
-@HAVE_W32_TRUE@	RC_CPP_FLAGS=" $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) " && \
-@HAVE_W32_TRUE@	$(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_CPP_FLAGS// -isystem / -I } $< -o $@ && \
-@HAVE_W32_TRUE@	echo > $@-empty.c && $(CC) $(AM_CFLAGS) $(CFLAGS) -c $@-empty.c -o $(@:.lo=.o) && rm -f $@-empty.c
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/microhttpd/base64.c b/src/microhttpd/base64.c
deleted file mode 100644
index 4fb4755..0000000
--- a/src/microhttpd/base64.c
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * This code implements the BASE64 algorithm.
- * This code is in the public domain; do with it what you wish.
- *
- * @file base64.c
- * @brief This code implements the BASE64 algorithm
- * @author Matthieu Speder
- */
-#include "base64.h"
-
-static const char base64_chars[] =
-  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
-static const char base64_digits[] =
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
-    0, 0, 0, -1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
-    14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26,
-    27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
-    45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
-
-
-char *
-BASE64Decode(const char* src)
-{
-  size_t in_len = strlen (src);
-  char* dest;
-  char* result;
-
-  if (in_len % 4)
-    {
-      /* Wrong base64 string length */
-      return NULL;
-    }
-  result = dest = malloc(in_len / 4 * 3 + 1);
-  if (result == NULL)
-    return NULL; /* out of memory */
-  while (*src) {
-    char a = base64_digits[(unsigned char)*(src++)];
-    char b = base64_digits[(unsigned char)*(src++)];
-    char c = base64_digits[(unsigned char)*(src++)];
-    char d = base64_digits[(unsigned char)*(src++)];
-    *(dest++) = (a << 2) | ((b & 0x30) >> 4);
-    if (c == (char)-1)
-      break;
-    *(dest++) = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2);
-    if (d == (char)-1)
-      break;
-    *(dest++) = ((c & 0x03) << 6) | d;
-  }
-  *dest = 0;
-  return result;
-}
-
-
-/* end of base64.c */
diff --git a/src/microhttpd/basicauth.c b/src/microhttpd/basicauth.c
index cbe0fc7..78818a9 100644
--- a/src/microhttpd/basicauth.c
+++ b/src/microhttpd/basicauth.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,128 +22,301 @@
  * @brief Implements HTTP basic authentication methods
  * @author Amr Ali
  * @author Matthieu Speder
+ * @author Karlson2k (Evgeny Grin)
  */
+#include "basicauth.h"
+#include "gen_auth.h"
 #include "platform.h"
-#include <limits.h>
+#include "mhd_limits.h"
 #include "internal.h"
-#include "base64.h"
+#include "mhd_compat.h"
+#include "mhd_str.h"
+
 
 /**
- * Beginning string for any valid Basic authentication header.
+ * Get the username and password from the Basic Authorisation header
+ * sent by the client
+ *
+ * @param connection the MHD connection structure
+ * @return NULL if no valid Basic Authentication header is present in
+ *         current request, or
+ *         pointer to structure with username and password, which must be
+ *         freed by #MHD_free().
+ * @note Available since #MHD_VERSION 0x00097517
+ * @ingroup authentication
  */
-#define _BASIC_BASE		"Basic "
+_MHD_EXTERN struct MHD_BasicAuthInfo *
+MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection)
+{
+  const struct MHD_RqBAuth *params;
+  size_t decoded_max_len;
+  struct MHD_BasicAuthInfo *ret;
+
+  params = MHD_get_rq_bauth_params_ (connection);
+
+  if (NULL == params)
+    return NULL;
+
+  if ((NULL == params->token68.str) || (0 == params->token68.len))
+    return NULL;
+
+  decoded_max_len = MHD_base64_max_dec_size_ (params->token68.len);
+  ret = (struct MHD_BasicAuthInfo *) malloc (sizeof(struct MHD_BasicAuthInfo)
+                                             + decoded_max_len + 1);
+  if (NULL != ret)
+  {
+    size_t decoded_len;
+    char *decoded;
+
+    decoded = (char *) (ret + 1);
+    decoded_len = MHD_base64_to_bin_n (params->token68.str, params->token68.len,
+                                       decoded, decoded_max_len);
+    mhd_assert (decoded_max_len >= decoded_len);
+    if (0 != decoded_len)
+    {
+      size_t username_len;
+      char *colon;
+
+      colon = memchr (decoded, ':', decoded_len);
+      if (NULL != colon)
+      {
+        size_t password_pos;
+        size_t password_len;
+
+        username_len = (size_t) (colon - decoded);
+        password_pos = username_len + 1;
+        password_len = decoded_len - password_pos;
+        ret->password = decoded + password_pos;
+        ret->password[password_len] = 0;  /* Zero-terminate the string */
+        ret->password_len = password_len;
+      }
+      else
+      {
+        username_len = decoded_len;
+        ret->password = NULL;
+        ret->password_len = 0;
+      }
+      ret->username = decoded;
+      ret->username[username_len] = 0;  /* Zero-terminate the string */
+      ret->username_len = username_len;
+
+      return ret; /* Success exit point */
+    }
+#ifdef HAVE_MESSAGES
+    else
+      MHD_DLOG (connection->daemon,
+                _ ("Error decoding Basic Authorization authentication.\n"));
+#endif /* HAVE_MESSAGES */
+
+    free (ret);
+  }
+#ifdef HAVE_MESSAGES
+  else
+  {
+    MHD_DLOG (connection->daemon,
+              _ ("Failed to allocate memory to process " \
+                 "Basic Authorization authentication.\n"));
+  }
+#endif /* HAVE_MESSAGES */
+
+  return NULL; /* Failure exit point */
+}
 
 
 /**
  * Get the username and password from the basic authorization header sent by the client
  *
  * @param connection The MHD connection structure
- * @param password a pointer for the password
+ * @param[out] password a pointer for the password, free using #MHD_free().
  * @return NULL if no username could be found, a pointer
- * 			to the username if found
+ *      to the username if found, free using #MHD_free().
+ * @deprecated use #MHD_basic_auth_get_username_password3()
  * @ingroup authentication
  */
-char *
+_MHD_EXTERN char *
 MHD_basic_auth_get_username_password (struct MHD_Connection *connection,
-				      char** password) 
+                                      char **password)
 {
-  const char *header;
-  char *decode;
-  const char *separator;
-  char *user;
-  
-  if ( (NULL == (header = MHD_lookup_connection_value (connection, 
-						       MHD_HEADER_KIND,
-						       MHD_HTTP_HEADER_AUTHORIZATION))) ||
-       (0 != strncmp (header, _BASIC_BASE, strlen(_BASIC_BASE))) )
+  struct MHD_BasicAuthInfo *info;
+
+  info = MHD_basic_auth_get_username_password3 (connection);
+  if (NULL == info)
     return NULL;
-  header += strlen (_BASIC_BASE);
-  if (NULL == (decode = BASE64Decode (header)))
+
+  /* For backward compatibility this function must return NULL if
+   * no password is provided */
+  if (NULL != info->password)
+  {
+    char *username;
+
+    username = malloc (info->username_len + 1);
+    if (NULL != username)
     {
-#if HAVE_MESSAGES
+      memcpy (username, info->username, info->username_len + 1);
+      mhd_assert (0 == username[info->username_len]);
+      if (NULL != password)
+      {
+        *password = malloc (info->password_len + 1);
+        if (NULL != *password)
+        {
+          memcpy (*password, info->password, info->password_len + 1);
+          mhd_assert (0 == (*password)[info->password_len]);
+
+          free (info);
+          return username; /* Success exit point */
+        }
+#ifdef HAVE_MESSAGES
+        else
+          MHD_DLOG (connection->daemon,
+                    _ ("Failed to allocate memory.\n"));
+#endif /* HAVE_MESSAGES */
+      }
+      else
+      {
+        free (info);
+        return username; /* Success exit point */
+      }
+
+      free (username);
+    }
+#ifdef HAVE_MESSAGES
+    else
       MHD_DLOG (connection->daemon,
-		"Error decoding basic authentication\n");
-#endif
-      return NULL;
-    }
-  /* Find user:password pattern */
-  if (NULL == (separator = strchr (decode, ':')))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG(connection->daemon,
-	       "Basic authentication doesn't contain ':' separator\n");
-#endif
-      free (decode);
-      return NULL;
-    }
-  if (NULL == (user = strdup (decode)))
-    {
-      free (decode);
-      return NULL;
-    }
-  user[separator - decode] = '\0'; /* cut off at ':' */
-  if (NULL != password) 
-    {
-      *password = strdup (separator + 1);  
-      if (NULL == *password)
-	{
-#if HAVE_MESSAGES
-	  MHD_DLOG(connection->daemon,
-		   "Failed to allocate memory for password\n");
-#endif
-	  free (decode);
-	  free (user);
-	  return NULL;
-	}
-    }
-  free (decode);
-  return user;
+                _ ("Failed to allocate memory.\n"));
+#endif /* HAVE_MESSAGES */
+
+  }
+  free (info);
+  if (NULL != password)
+    *password = NULL;
+  return NULL;  /* Failure exit point */
 }
 
 
 /**
  * Queues a response to request basic authentication from the client.
+ *
+ * The given response object is expected to include the payload for
+ * the response; the "WWW-Authenticate" header will be added and the
+ * response queued with the 'UNAUTHORIZED' status code.
+ *
+ * See RFC 7617#section-2 for details.
+ *
+ * The @a response is modified by this function. The modified response object
+ * can be used to respond subsequent requests by #MHD_queue_response()
+ * function with status code #MHD_HTTP_UNAUTHORIZED and must not be used again
+ * with MHD_queue_basic_auth_fail_response3() function. The response could
+ * be destroyed right after call of this function.
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param prefer_utf8 if not set to #MHD_NO, parameter'charset="UTF-8"' will
+ *                    be added, indicating for client that UTF-8 encoding
+ *                    is preferred
+ * @param response the response object to modify and queue; the NULL
+ *                 is tolerated
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00097516
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_queue_basic_auth_fail_response3 (struct MHD_Connection *connection,
+                                     const char *realm,
+                                     int prefer_utf8,
+                                     struct MHD_Response *response)
+{
+  static const char prefix[] = "Basic realm=\"";
+  static const char suff_charset[] = "\", charset=\"UTF-8\"";
+  static const size_t prefix_len = MHD_STATICSTR_LEN_ (prefix);
+  static const size_t suff_simple_len = MHD_STATICSTR_LEN_ ("\"");
+  static const size_t suff_charset_len =
+    MHD_STATICSTR_LEN_ (suff_charset);
+  enum MHD_Result ret;
+  char *h_str;
+  size_t h_maxlen;
+  size_t suffix_len;
+  size_t realm_len;
+  size_t realm_quoted_len;
+  size_t pos;
+
+  if (NULL == response)
+    return MHD_NO;
+
+  suffix_len = (0 == prefer_utf8) ? suff_simple_len : suff_charset_len;
+  realm_len = strlen (realm);
+  h_maxlen = prefix_len + realm_len * 2 + suffix_len;
+
+  h_str = (char *) malloc (h_maxlen + 1);
+  if (NULL == h_str)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              "Failed to allocate memory for Basic Authentication header.\n");
+#endif /* HAVE_MESSAGES */
+    return MHD_NO;
+  }
+  memcpy (h_str, prefix, prefix_len);
+  pos = prefix_len;
+  realm_quoted_len = MHD_str_quote (realm, realm_len, h_str + pos,
+                                    h_maxlen - prefix_len - suffix_len);
+  pos += realm_quoted_len;
+  mhd_assert (pos + suffix_len <= h_maxlen);
+  if (0 == prefer_utf8)
+  {
+    h_str[pos++] = '\"';
+    h_str[pos++] = 0; /* Zero terminate the result */
+    mhd_assert (pos <= h_maxlen + 1);
+  }
+  else
+  {
+    /* Copy with the final zero-termination */
+    mhd_assert (pos + suff_charset_len <= h_maxlen);
+    memcpy (h_str + pos, suff_charset, suff_charset_len + 1);
+    mhd_assert (0 == h_str[pos + suff_charset_len]);
+  }
+
+  ret = MHD_add_response_header (response,
+                                 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
+                                 h_str);
+  free (h_str);
+  if (MHD_NO != ret)
+  {
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_UNAUTHORIZED,
+                              response);
+  }
+  else
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Failed to add Basic Authentication header.\n"));
+#endif /* HAVE_MESSAGES */
+  }
+  return ret;
+}
+
+
+/**
+ * Queues a response to request basic authentication from the client
  * The given response object is expected to include the payload for
  * the response; the "WWW-Authenticate" header will be added and the
  * response queued with the 'UNAUTHORIZED' status code.
  *
  * @param connection The MHD connection structure
  * @param realm the realm presented to the client
- * @param response response object to modify and queue
+ * @param response response object to modify and queue; the NULL is tolerated
  * @return #MHD_YES on success, #MHD_NO otherwise
+ * @deprecated use MHD_queue_basic_auth_fail_response3()
  * @ingroup authentication
  */
-int 
+_MHD_EXTERN enum MHD_Result
 MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection,
-				    const char *realm, 
-				    struct MHD_Response *response) 
+                                    const char *realm,
+                                    struct MHD_Response *response)
 {
-  int ret;
-  size_t hlen = strlen(realm) + strlen("Basic realm=\"\"") + 1;
-  char *header;
-  
-  header = (char*)malloc(hlen);
-  if (NULL == header)
-  {
-#if HAVE_MESSAGES
-    MHD_DLOG(connection->daemon,
-		   "Failed to allocate memory for auth header\n");
-#endif /* HAVE_MESSAGES */
-    return MHD_NO;
-  }
-  MHD_snprintf_ (header, 
-	    hlen, 
-	    "Basic realm=\"%s\"", 
-	    realm);
-  ret = MHD_add_response_header (response,
-				 MHD_HTTP_HEADER_WWW_AUTHENTICATE,
-				 header);
-  free(header);
-  if (MHD_YES == ret)
-    ret = MHD_queue_response (connection, 
-			      MHD_HTTP_UNAUTHORIZED, 
-			      response);
-  return ret;
+  return MHD_queue_basic_auth_fail_response3 (connection, realm, MHD_NO,
+                                              response);
 }
 
+
 /* end of basicauth.c */
diff --git a/src/microhttpd/basicauth.h b/src/microhttpd/basicauth.h
new file mode 100644
index 0000000..e0bbeec
--- /dev/null
+++ b/src/microhttpd/basicauth.h
@@ -0,0 +1,45 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file basicauth.c
+ * @brief Implements HTTP basic authentication methods
+ * @author Amr Ali
+ * @author Matthieu Speder
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_BASICAUTH_H
+#define MHD_BASICAUTH_H 1
+
+#include "mhd_str.h"
+
+/**
+ * Beginning string for any valid Basic authentication header.
+ */
+#define _MHD_AUTH_BASIC_BASE   "Basic"
+
+struct MHD_RqBAuth
+{
+  struct _MHD_str_w_len token68;
+};
+
+#endif /* ! MHD_BASICAUTH_H */
+
+/* end of basicauth.h */
diff --git a/src/microhttpd/connection.c b/src/microhttpd/connection.c
index ff57ac4..859ca82 100644
--- a/src/microhttpd/connection.c
+++ b/src/microhttpd/connection.c
@@ -1,6 +1,7 @@
 /*
-    This file is part of libmicrohttpd
-     Copyright (C) 2007-2015 Daniel Pittman and Christian Grothoff
+     This file is part of libmicrohttpd
+     Copyright (C) 2007-2020 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2015-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -17,33 +18,43 @@
      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 
 */
-
 /**
  * @file connection.c
  * @brief  Methods for managing connections
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
-
 #include "internal.h"
-#include <limits.h>
+#include "mhd_limits.h"
 #include "connection.h"
 #include "memorypool.h"
 #include "response.h"
-#include "reason_phrase.h"
-
-#if HAVE_NETINET_TCP_H
-/* for TCP_CORK */
-#include <netinet/tcp.h>
+#include "mhd_mono_clock.h"
+#include "mhd_str.h"
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#include "mhd_locks.h"
 #endif
-
-#if defined(_WIN32) && defined(MHD_W32_MUTEX_)
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN 1
-#endif /* !WIN32_LEAN_AND_MEAN */
-#include <windows.h>
-#endif /* _WIN32 && MHD_W32_MUTEX_ */
-
+#include "mhd_sockets.h"
+#include "mhd_compat.h"
+#include "mhd_itc.h"
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#include <sys/sendfile.h>
+#endif /* MHD_LINUX_SOLARIS_SENDFILE */
+#if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE)
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+#endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */
+#ifdef HTTPS_SUPPORT
+#include "connection_https.h"
+#endif /* HTTPS_SUPPORT */
+#ifdef HAVE_SYS_PARAM_H
+/* For FreeBSD version identification */
+#include <sys/param.h>
+#endif /* HAVE_SYS_PARAM_H */
+#include "mhd_send.h"
+#include "mhd_assert.h"
 
 /**
  * Message to transmit when http 1.1 request is received
@@ -57,8 +68,9 @@
  * Intentionally empty here to keep our memory footprint
  * minimal.
  */
-#if HAVE_MESSAGES
-#define REQUEST_TOO_BIG "<html><head><title>Request too big</title></head><body>Your HTTP header was too big for the memory constraints of this webserver.</body></html>"
+#ifdef HAVE_MESSAGES
+#define REQUEST_TOO_BIG \
+  "<html><head><title>Request too big</title></head><body>Your HTTP header was too big for the memory constraints of this webserver.</body></html>"
 #else
 #define REQUEST_TOO_BIG ""
 #endif
@@ -70,85 +82,507 @@
  * Intentionally empty here to keep our memory footprint
  * minimal.
  */
-#if HAVE_MESSAGES
-#define REQUEST_LACKS_HOST "<html><head><title>&quot;Host:&quot; header required</title></head><body>In HTTP 1.1, requests must include a &quot;Host:&quot; header, and your HTTP 1.1 request lacked such a header.</body></html>"
+#ifdef HAVE_MESSAGES
+#define REQUEST_LACKS_HOST \
+  "<html><head><title>&quot;Host:&quot; header required</title></head><body>In HTTP 1.1, requests must include a &quot;Host:&quot; header, and your HTTP 1.1 request lacked such a header.</body></html>"
 #else
 #define REQUEST_LACKS_HOST ""
 #endif
 
 /**
+ * Response text used when the request has unsupported "Transfer-Enconding:".
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_UNSUPPORTED_TR_ENCODING \
+  "<html>" \
+  "<head><title>Unsupported Transfer-Encoding</title></head>" \
+  "<body>The Transfer-Encoding used in request is not supported.</body>" \
+  "</html>"
+#else
+#define REQUEST_UNSUPPORTED_TR_ENCODING ""
+#endif
+
+/**
+ * Response text used when the request has unsupported both headers:
+ * "Transfer-Enconding:" and "Content-Length:"
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_LENGTH_WITH_TR_ENCODING \
+  "<html>" \
+  "<head><title>Malformed request</title></head>" \
+  "<body>Wrong combination of the request headers: both Transfer-Encoding " \
+  "and Content-Length headers are used at the same time.</body>" \
+  "</html>"
+#else
+#define REQUEST_LENGTH_WITH_TR_ENCODING ""
+#endif
+
+/**
  * Response text used when the request (http header) is
  * malformed.
  *
  * Intentionally empty here to keep our memory footprint
  * minimal.
  */
-#if HAVE_MESSAGES
-#define REQUEST_MALFORMED "<html><head><title>Request malformed</title></head><body>Your HTTP request was syntactically incorrect.</body></html>"
+#ifdef HAVE_MESSAGES
+#define REQUEST_MALFORMED \
+  "<html><head><title>Request malformed</title></head><body>Your HTTP request was syntactically incorrect.</body></html>"
 #else
 #define REQUEST_MALFORMED ""
 #endif
 
 /**
+ * Response text used when the request HTTP chunked encoding is
+ * malformed.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_CHUNKED_MALFORMED \
+  "<html><head><title>Request malformed</title></head><body>Your HTTP chunked encoding was syntactically incorrect.</body></html>"
+#else
+#define REQUEST_CHUNKED_MALFORMED ""
+#endif
+
+/**
+ * Response text used when the request HTTP chunk is too large.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_CHUNK_TOO_LARGE \
+  "<html><head><title>Request content too large</title></head><body>The chunk size used in your HTTP chunked encoded request is too large.</body></html>"
+#else
+#define REQUEST_CHUNK_TOO_LARGE ""
+#endif
+
+/**
+ * Response text used when the request HTTP content is too large.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_CONTENTLENGTH_TOOLARGE \
+  "<html><head><title>Request content too large</title></head>" \
+  "<body>Your HTTP request has too large value for <b>Content-Length</b> header.</body></html>"
+#else
+#define REQUEST_CONTENTLENGTH_TOOLARGE ""
+#endif
+
+/**
+ * Response text used when the request HTTP chunked encoding is
+ * malformed.
+ */
+#ifdef HAVE_MESSAGES
+#define REQUEST_CONTENTLENGTH_MALFORMED \
+  "<html><head><title>Request malformed</title></head>" \
+  "<body>Your HTTP request has wrong value for <b>Content-Length</b> header.</body></html>"
+#else
+#define REQUEST_CONTENTLENGTH_MALFORMED ""
+#endif
+
+/**
  * Response text used when there is an internal server error.
  *
  * Intentionally empty here to keep our memory footprint
  * minimal.
  */
-#if HAVE_MESSAGES
-#define INTERNAL_ERROR "<html><head><title>Internal server error</title></head><body>Some programmer needs to study the manual more carefully.</body></html>"
+#ifdef HAVE_MESSAGES
+#define INTERNAL_ERROR \
+  "<html><head><title>Internal server error</title></head><body>Please ask the developer of this Web server to carefully read the GNU libmicrohttpd documentation about connection management and blocking.</body></html>"
 #else
 #define INTERNAL_ERROR ""
 #endif
 
 /**
- * Add extra debug messages with reasons for closing connections
- * (non-error reasons).
+ * Response text used when the request HTTP version is too old.
  */
-#define DEBUG_CLOSE MHD_NO
+#ifdef HAVE_MESSAGES
+#define REQ_HTTP_VER_IS_TOO_OLD \
+  "<html><head><title>Requested HTTP version is not supported</title></head><body>Requested HTTP version is too old and not supported.</body></html>"
+#else
+#define REQ_HTTP_VER_IS_TOO_OLD ""
+#endif
 
 /**
- * Should all data send be printed to stderr?
+ * Response text used when the request HTTP version is not supported.
  */
-#define DEBUG_SEND_DATA MHD_NO
+#ifdef HAVE_MESSAGES
+#define REQ_HTTP_VER_IS_NOT_SUPPORTED \
+  "<html><head><title>Requested HTTP version is not supported</title></head><body>Requested HTTP version is not supported.</body></html>"
+#else
+#define REQ_HTTP_VER_IS_NOT_SUPPORTED ""
+#endif
+
+
+/**
+ * sendfile() chuck size
+ */
+#define MHD_SENFILE_CHUNK_         (0x20000)
+
+/**
+ * sendfile() chuck size for thread-per-connection
+ */
+#define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000)
+
+#ifdef HAVE_MESSAGES
+/**
+ * Return text description for MHD_ERR_*_ codes
+ * @param mhd_err_code the error code
+ * @return pointer to static string with error description
+ */
+static const char *
+str_conn_error_ (ssize_t mhd_err_code)
+{
+  switch (mhd_err_code)
+  {
+  case MHD_ERR_AGAIN_:
+    return _ ("The operation would block, retry later");
+  case MHD_ERR_CONNRESET_:
+    return _ ("The connection was forcibly closed by remote peer");
+  case MHD_ERR_NOTCONN_:
+    return _ ("The socket is not connected");
+  case MHD_ERR_NOMEM_:
+    return _ ("Not enough system resources to serve the request");
+  case MHD_ERR_BADF_:
+    return _ ("Bad FD value");
+  case MHD_ERR_INVAL_:
+    return _ ("Argument value is invalid");
+  case MHD_ERR_OPNOTSUPP_:
+    return _ ("Argument value is not supported");
+  case MHD_ERR_PIPE_:
+    return _ ("The socket is no longer available for sending");
+  case MHD_ERR_TLS_:
+    return _ ("TLS encryption or decryption error");
+  default:
+    break;   /* Mute compiler warning */
+  }
+  if (0 <= mhd_err_code)
+    return _ ("Not an error code");
+
+  mhd_assert (0); /* Should never be reachable */
+  return _ ("Wrong error code value");
+}
+
+
+#endif /* HAVE_MESSAGES */
+
+/**
+ * Allocate memory from connection's memory pool.
+ * If memory pool doesn't have enough free memory but read or write buffer
+ * have some unused memory, the size of the buffer will be reduced as needed.
+ * @param connection the connection to use
+ * @param size the size of allocated memory area
+ * @return pointer to allocated memory region in the pool or
+ *         NULL if no memory is available
+ */
+void *
+MHD_connection_alloc_memory_ (struct MHD_Connection *connection,
+                              size_t size)
+{
+  struct MHD_Connection *const c = connection; /* a short alias */
+  struct MemoryPool *const pool = c->pool;     /* a short alias */
+  size_t need_to_free; /**< The required amount of free memory */
+  void *res;
+
+  res = MHD_pool_try_alloc (pool, size, &need_to_free);
+  if (NULL == res)
+  {
+    if (NULL != c->write_buffer)
+    {
+      /* The connection is in the sending phase */
+      mhd_assert (MHD_CONNECTION_START_REPLY <= c->state);
+      if (c->write_buffer_size - c->write_buffer_append_offset >= need_to_free)
+      {
+        char *buf;
+        const size_t new_buf_size = c->write_buffer_size - need_to_free;
+        buf = MHD_pool_reallocate (pool,
+                                   c->write_buffer,
+                                   c->write_buffer_size,
+                                   new_buf_size);
+        mhd_assert (c->write_buffer == buf);
+        mhd_assert (c->write_buffer_append_offset <= new_buf_size);
+        mhd_assert (c->write_buffer_send_offset <= new_buf_size);
+        c->write_buffer_size = new_buf_size;
+        c->write_buffer = buf;
+      }
+      else
+        return NULL;
+    }
+    else if (NULL != c->read_buffer)
+    {
+      /* The connection is in the receiving phase */
+      if (c->read_buffer_size - c->read_buffer_offset >= need_to_free)
+      {
+        char *buf;
+        const size_t new_buf_size = c->read_buffer_size - need_to_free;
+        buf = MHD_pool_reallocate (pool,
+                                   c->read_buffer,
+                                   c->read_buffer_size,
+                                   new_buf_size);
+        mhd_assert (c->read_buffer == buf);
+        mhd_assert (c->read_buffer_offset <= new_buf_size);
+        c->read_buffer_size = new_buf_size;
+        c->read_buffer = buf;
+      }
+      else
+        return NULL;
+    }
+    else
+      return NULL;
+    res = MHD_pool_allocate (pool, size, true);
+    mhd_assert (NULL != res); /* It has been checked that pool has enough space */
+  }
+  return res;
+}
+
+
+/**
+ * Callback for receiving data from the socket.
+ *
+ * @param connection the MHD connection structure
+ * @param other where to write received data to
+ * @param i maximum size of other (in bytes)
+ * @return positive value for number of bytes actually received or
+ *         negative value for error number MHD_ERR_xxx_
+ */
+static ssize_t
+recv_param_adapter (struct MHD_Connection *connection,
+                    void *other,
+                    size_t i)
+{
+  ssize_t ret;
+
+  if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
+       (MHD_CONNECTION_CLOSED == connection->state) )
+  {
+    return MHD_ERR_NOTCONN_;
+  }
+  if (i > MHD_SCKT_SEND_MAX_SIZE_)
+    i = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */
+
+  ret = MHD_recv_ (connection->socket_fd,
+                   other,
+                   i);
+  if (0 > ret)
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* Got EAGAIN --- no longer read-ready */
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+    if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+      return MHD_ERR_CONNRESET_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_))
+      return MHD_ERR_OPNOTSUPP_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_))
+      return MHD_ERR_NOTCONN_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_))
+      return MHD_ERR_INVAL_;
+    if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))
+      return MHD_ERR_NOMEM_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_))
+      return MHD_ERR_BADF_;
+    /* Treat any other error as a hard error. */
+    return MHD_ERR_NOTCONN_;
+  }
+#ifdef EPOLL_SUPPORT
+  else if (i > (size_t) ret)
+    connection->epoll_state &=
+      ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+#endif /* EPOLL_SUPPORT */
+  return ret;
+}
 
 
 /**
  * Get all of the headers from the request.
  *
  * @param connection connection to get values from
- * @param kind types of values to iterate over
+ * @param kind types of values to iterate over, can be a bitmask
  * @param iterator callback to call on each header;
  *        maybe NULL (then just count headers)
  * @param iterator_cls extra argument to @a iterator
  * @return number of entries iterated over
+ *         -1 if connection is NULL.
  * @ingroup request
  */
-int
+_MHD_EXTERN int
 MHD_get_connection_values (struct MHD_Connection *connection,
                            enum MHD_ValueKind kind,
-                           MHD_KeyValueIterator iterator, void *iterator_cls)
+                           MHD_KeyValueIterator iterator,
+                           void *iterator_cls)
 {
   int ret;
-  struct MHD_HTTP_Header *pos;
+  struct MHD_HTTP_Req_Header *pos;
 
   if (NULL == connection)
     return -1;
   ret = 0;
-  for (pos = connection->headers_received; NULL != pos; pos = pos->next)
+  for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
     if (0 != (pos->kind & kind))
+    {
+      ret++;
+      if ( (NULL != iterator) &&
+           (MHD_NO == iterator (iterator_cls,
+                                pos->kind,
+                                pos->header,
+                                pos->value)) )
+        return ret;
+    }
+  return ret;
+}
+
+
+/**
+ * Get all of the headers from the request.
+ *
+ * @param connection connection to get values from
+ * @param kind types of values to iterate over, can be a bitmask
+ * @param iterator callback to call on each header;
+ *        maybe NULL (then just count headers)
+ * @param iterator_cls extra argument to @a iterator
+ * @return number of entries iterated over,
+ *         -1 if connection is NULL.
+ * @ingroup request
+ */
+_MHD_EXTERN int
+MHD_get_connection_values_n (struct MHD_Connection *connection,
+                             enum MHD_ValueKind kind,
+                             MHD_KeyValueIteratorN iterator,
+                             void *iterator_cls)
+{
+  int ret;
+  struct MHD_HTTP_Req_Header *pos;
+
+  if (NULL == connection)
+    return -1;
+  ret = 0;
+
+  if (NULL == iterator)
+    for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+    {
+      if (0 != (kind & pos->kind))
+        ret++;
+    }
+  else
+    for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+      if (0 != (kind & pos->kind))
       {
-	ret++;
-	if ((NULL != iterator) &&
-	    (MHD_YES != iterator (iterator_cls,
-				  kind, pos->header, pos->value)))
-	  return ret;
+        ret++;
+        if (MHD_NO == iterator (iterator_cls,
+                                pos->kind,
+                                pos->header,
+                                pos->header_size,
+                                pos->value,
+                                pos->value_size))
+          return ret;
       }
   return ret;
 }
 
 
 /**
+ * This function can be used to add an arbitrary entry to connection.
+ * Internal version of #MHD_set_connection_value_n() without checking
+ * of arguments values.
+ *
+ * @param connection the connection for which a
+ *                   value should be set
+ * @param kind kind of the value
+ * @param key key for the value, must be zero-terminated
+ * @param key_size number of bytes in @a key (excluding 0-terminator)
+ * @param value the value itself, must be zero-terminated
+ * @param value_size number of bytes in @a value (excluding 0-terminator)
+ * @return #MHD_NO if the operation could not be
+ *         performed due to insufficient memory;
+ *         #MHD_YES on success
+ * @ingroup request
+ */
+static enum MHD_Result
+MHD_set_connection_value_n_nocheck_ (struct MHD_Connection *connection,
+                                     enum MHD_ValueKind kind,
+                                     const char *key,
+                                     size_t key_size,
+                                     const char *value,
+                                     size_t value_size)
+{
+  struct MHD_HTTP_Req_Header *pos;
+
+  pos = MHD_connection_alloc_memory_ (connection,
+                                      sizeof (struct MHD_HTTP_Res_Header));
+  if (NULL == pos)
+    return MHD_NO;
+  pos->header = key;
+  pos->header_size = key_size;
+  pos->value = value;
+  pos->value_size = value_size;
+  pos->kind = kind;
+  pos->next = NULL;
+  /* append 'pos' to the linked list of headers */
+  if (NULL == connection->rq.headers_received_tail)
+  {
+    connection->rq.headers_received = pos;
+    connection->rq.headers_received_tail = pos;
+  }
+  else
+  {
+    connection->rq.headers_received_tail->next = pos;
+    connection->rq.headers_received_tail = pos;
+  }
+  return MHD_YES;
+}
+
+
+/**
+ * This function can be used to add an arbitrary entry to connection.
+ * This function could add entry with binary zero, which is allowed
+ * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is
+ * recommended to use #MHD_set_connection_value.
+ *
+ * This function MUST only be called from within the
+ * #MHD_AccessHandlerCallback (otherwise, access maybe improperly
+ * synchronized).  Furthermore, the client must guarantee that the key
+ * and value arguments are 0-terminated strings that are NOT freed
+ * until the connection is closed.  (The easiest way to do this is by
+ * passing only arguments to permanently allocated strings.).
+ *
+ * @param connection the connection for which a
+ *  value should be set
+ * @param kind kind of the value
+ * @param key key for the value, must be zero-terminated
+ * @param key_size number of bytes in @a key (excluding 0-terminator)
+ * @param value the value itself, must be zero-terminated
+ * @param value_size number of bytes in @a value (excluding 0-terminator)
+ * @return #MHD_NO if the operation could not be
+ *         performed due to insufficient memory;
+ *         #MHD_YES on success
+ * @ingroup request
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_set_connection_value_n (struct MHD_Connection *connection,
+                            enum MHD_ValueKind kind,
+                            const char *key,
+                            size_t key_size,
+                            const char *value,
+                            size_t value_size)
+{
+  if ( (MHD_GET_ARGUMENT_KIND != kind) &&
+       ( ((key ? strlen (key) : 0) != key_size) ||
+         ((value ? strlen (value) : 0) != value_size) ) )
+    return MHD_NO; /* binary zero is allowed only in GET arguments */
+
+  return MHD_set_connection_value_n_nocheck_ (connection,
+                                              kind,
+                                              key,
+                                              key_size,
+                                              value,
+                                              value_size);
+}
+
+
+/**
  * This function can be used to add an entry to the HTTP headers of a
  * connection (so that the #MHD_get_connection_values function will
  * return them -- and the `struct MHD_PostProcessor` will also see
@@ -173,33 +607,22 @@
  *         #MHD_YES on success
  * @ingroup request
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_set_connection_value (struct MHD_Connection *connection,
                           enum MHD_ValueKind kind,
-                          const char *key, const char *value)
+                          const char *key,
+                          const char *value)
 {
-  struct MHD_HTTP_Header *pos;
-
-  pos = MHD_pool_allocate (connection->pool,
-                           sizeof (struct MHD_HTTP_Header), MHD_YES);
-  if (NULL == pos)
-    return MHD_NO;
-  pos->header = (char *) key;
-  pos->value = (char *) value;
-  pos->kind = kind;
-  pos->next = NULL;
-  /* append 'pos' to the linked list of headers */
-  if (NULL == connection->headers_received_tail)
-    {
-      connection->headers_received = pos;
-      connection->headers_received_tail = pos;
-    }
-  else
-    {
-      connection->headers_received_tail->next = pos;
-      connection->headers_received_tail = pos;
-    }
-  return MHD_YES;
+  return MHD_set_connection_value_n_nocheck_ (connection,
+                                              kind,
+                                              key,
+                                              NULL != key
+                                              ? strlen (key)
+                                              : 0,
+                                              value,
+                                              NULL != value
+                                              ? strlen (value)
+                                              : 0);
 }
 
 
@@ -213,81 +636,341 @@
  * @return NULL if no such item was found
  * @ingroup request
  */
-const char *
+_MHD_EXTERN const char *
 MHD_lookup_connection_value (struct MHD_Connection *connection,
-                             enum MHD_ValueKind kind, const char *key)
+                             enum MHD_ValueKind kind,
+                             const char *key)
 {
-  struct MHD_HTTP_Header *pos;
+  const char *value;
+
+  value = NULL;
+  (void) MHD_lookup_connection_value_n (connection,
+                                        kind,
+                                        key,
+                                        (NULL == key) ? 0 : strlen (key),
+                                        &value,
+                                        NULL);
+  return value;
+}
+
+
+/**
+ * Get a particular header value.  If multiple
+ * values match the kind, return any one of them.
+ * @note Since MHD_VERSION 0x00096304
+ *
+ * @param connection connection to get values from
+ * @param kind what kind of value are we looking for
+ * @param key the header to look for, NULL to lookup 'trailing' value without a key
+ * @param key_size the length of @a key in bytes
+ * @param[out] value_ptr the pointer to variable, which will be set to found value,
+ *                       will not be updated if key not found,
+ *                       could be NULL to just check for presence of @a key
+ * @param[out] value_size_ptr the pointer variable, which will set to found value,
+ *                            will not be updated if key not found,
+ *                            could be NULL
+ * @return #MHD_YES if key is found,
+ *         #MHD_NO otherwise.
+ * @ingroup request
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_lookup_connection_value_n (struct MHD_Connection *connection,
+                               enum MHD_ValueKind kind,
+                               const char *key,
+                               size_t key_size,
+                               const char **value_ptr,
+                               size_t *value_size_ptr)
+{
+  struct MHD_HTTP_Req_Header *pos;
 
   if (NULL == connection)
-    return NULL;
-  for (pos = connection->headers_received; NULL != pos; pos = pos->next)
-    if ((0 != (pos->kind & kind)) &&
-	( (key == pos->header) ||
-	  ( (NULL != pos->header) &&
-	    (NULL != key) &&
-        (MHD_str_equal_caseless_(key, pos->header)))))
-      return pos->value;
-  return NULL;
+    return MHD_NO;
+
+  if (NULL == key)
+  {
+    for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+    {
+      if ( (0 != (kind & pos->kind)) &&
+           (NULL == pos->header) )
+        break;
+    }
+  }
+  else
+  {
+    for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+    {
+      if ( (0 != (kind & pos->kind)) &&
+           (key_size == pos->header_size) &&
+           ( (key == pos->header) ||
+             (MHD_str_equal_caseless_bin_n_ (key,
+                                             pos->header,
+                                             key_size) ) ) )
+        break;
+    }
+  }
+
+  if (NULL == pos)
+    return MHD_NO;
+
+  if (NULL != value_ptr)
+    *value_ptr = pos->value;
+
+  if (NULL != value_size_ptr)
+    *value_size_ptr = pos->value_size;
+
+  return MHD_YES;
 }
 
 
 /**
+ * Check whether request header contains particular token.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param connection the connection to get values from
+ * @param header     the header name
+ * @param header_len the length of header, not including optional
+ *                   terminating null-character
+ * @param token      the token to find
+ * @param token_len  the length of token, not including optional
+ *                   terminating null-character.
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+static bool
+MHD_lookup_header_token_ci (const struct MHD_Connection *connection,
+                            const char *header,
+                            size_t header_len,
+                            const char *token,
+                            size_t token_len)
+{
+  struct MHD_HTTP_Req_Header *pos;
+
+  if ((NULL == connection) || (NULL == header) || (0 == header[0]) ||
+      (NULL == token) || (0 == token[0]))
+    return false;
+
+  for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+  {
+    if ((0 != (pos->kind & MHD_HEADER_KIND)) &&
+        (header_len == pos->header_size) &&
+        ( (header == pos->header) ||
+          (MHD_str_equal_caseless_bin_n_ (header,
+                                          pos->header,
+                                          header_len)) ) &&
+        (MHD_str_has_token_caseless_ (pos->value, token, token_len)))
+      return true;
+  }
+  return false;
+}
+
+
+/**
+ * Check whether request header contains particular static @a tkn.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param c   the connection to get values from
+ * @param h   the static string of header name
+ * @param tkn the static string of token to find
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+#define MHD_lookup_header_s_token_ci(c,h,tkn) \
+  MHD_lookup_header_token_ci ((c),(h),MHD_STATICSTR_LEN_ (h), \
+                              (tkn),MHD_STATICSTR_LEN_ (tkn))
+
+
+/**
  * Do we (still) need to send a 100 continue
  * message for this connection?
  *
  * @param connection connection to test
- * @return 0 if we don't need 100 CONTINUE, 1 if we do
+ * @return false if we don't need 100 CONTINUE, true if we do
  */
-static int
+static bool
 need_100_continue (struct MHD_Connection *connection)
 {
   const char *expect;
 
-  return ( (NULL == connection->response) &&
-	   (NULL != connection->version) &&
-       (MHD_str_equal_caseless_(connection->version,
-			     MHD_HTTP_VERSION_1_1)) &&
-	   (NULL != (expect = MHD_lookup_connection_value (connection,
-							   MHD_HEADER_KIND,
-							   MHD_HTTP_HEADER_EXPECT))) &&
-	   (MHD_str_equal_caseless_(expect, "100-continue")) &&
-	   (connection->continue_message_write_offset <
-	    strlen (HTTP_100_CONTINUE)) );
+  if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver))
+    return false;
+
+  if (0 == connection->rq.remaining_upload_size)
+    return false;
+
+  if (MHD_NO ==
+      MHD_lookup_connection_value_n (connection,
+                                     MHD_HEADER_KIND,
+                                     MHD_HTTP_HEADER_EXPECT,
+                                     MHD_STATICSTR_LEN_ ( \
+                                       MHD_HTTP_HEADER_EXPECT),
+                                     &expect,
+                                     NULL))
+    return false;
+
+  if (MHD_str_equal_caseless_ (expect,
+                               "100-continue"))
+    return true;
+
+  return false;
+}
+
+
+/**
+ * Mark connection as "closed".
+ * @remark To be called from any thread.
+ *
+ * @param connection connection to close
+ */
+void
+MHD_connection_mark_closed_ (struct MHD_Connection *connection)
+{
+  const struct MHD_Daemon *daemon = connection->daemon;
+
+  if (0 == (daemon->options & MHD_USE_TURBO))
+  {
+#ifdef HTTPS_SUPPORT
+    /* For TLS connection use shutdown of TLS layer
+     * and do not shutdown TCP socket. This give more
+     * chances to send TLS closure data to remote side.
+     * Closure of TLS layer will be interpreted by
+     * remote side as end of transmission. */
+    if (0 != (daemon->options & MHD_USE_TLS))
+    {
+      if (! MHD_tls_connection_shutdown (connection))
+        shutdown (connection->socket_fd,
+                  SHUT_WR);
+    }
+    else   /* Combined with next 'shutdown()'. */
+#endif /* HTTPS_SUPPORT */
+    shutdown (connection->socket_fd,
+              SHUT_WR);
+  }
+  connection->state = MHD_CONNECTION_CLOSED;
+  connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
 }
 
 
 /**
  * Close the given connection and give the
  * specified termination code to the user.
+ * @remark To be called only from thread that
+ * process connection's recv(), send() and response.
  *
  * @param connection connection to close
  * @param termination_code termination reason to give
  */
 void
-MHD_connection_close (struct MHD_Connection *connection,
-                      enum MHD_RequestTerminationCode termination_code)
+MHD_connection_close_ (struct MHD_Connection *connection,
+                       enum MHD_RequestTerminationCode termination_code)
 {
-  struct MHD_Daemon *daemon;
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_Response *resp = connection->rp.response;
 
-  daemon = connection->daemon;
-  if (0 == (connection->daemon->options & MHD_USE_EPOLL_TURBO))
-    shutdown (connection->socket_fd,
-	      (MHD_YES == connection->read_closed) ? SHUT_WR : SHUT_RDWR);
-  connection->state = MHD_CONNECTION_CLOSED;
-  connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
+  mhd_assert (! connection->suspended);
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (connection->pid) );
+#endif /* MHD_USE_THREADS */
   if ( (NULL != daemon->notify_completed) &&
-       (MHD_YES == connection->client_aware) )
+       (connection->rq.client_aware) )
     daemon->notify_completed (daemon->notify_completed_cls,
-			      connection,
-			      &connection->client_context,
-			      termination_code);
-  connection->client_aware = MHD_NO;
+                              connection,
+                              &connection->rq.client_context,
+                              termination_code);
+  connection->rq.client_aware = false;
+  if (NULL != resp)
+  {
+    connection->rp.response = NULL;
+    MHD_destroy_response (resp);
+  }
+  if (NULL != connection->pool)
+  {
+    MHD_pool_destroy (connection->pool);
+    connection->pool = NULL;
+  }
+
+  MHD_connection_mark_closed_ (connection);
 }
 
 
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
 /**
- * A serious error occured, close the
+ * Stop TLS forwarding on upgraded connection and
+ * reflect remote disconnect state to socketpair.
+ * @remark In thread-per-connection mode this function
+ * can be called from any thread, in other modes this
+ * function must be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param connection the upgraded connection
+ */
+void
+MHD_connection_finish_forward_ (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_UpgradeResponseHandle *urh = connection->urh;
+
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+#endif /* MHD_USE_THREADS */
+
+  if (0 == (daemon->options & MHD_USE_TLS))
+    return; /* Nothing to do with non-TLS connection. */
+
+  if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+    DLL_remove (daemon->urh_head,
+                daemon->urh_tail,
+                urh);
+#ifdef EPOLL_SUPPORT
+  if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+       (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                        EPOLL_CTL_DEL,
+                        connection->socket_fd,
+                        NULL)) )
+  {
+    MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+  }
+  if (urh->in_eready_list)
+  {
+    EDLL_remove (daemon->eready_urh_head,
+                 daemon->eready_urh_tail,
+                 urh);
+    urh->in_eready_list = false;
+  }
+#endif /* EPOLL_SUPPORT */
+  if (MHD_INVALID_SOCKET != urh->mhd.socket)
+  {
+#ifdef EPOLL_SUPPORT
+    if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+         (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                          EPOLL_CTL_DEL,
+                          urh->mhd.socket,
+                          NULL)) )
+    {
+      MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+    }
+#endif /* EPOLL_SUPPORT */
+    /* Reflect remote disconnect to application by breaking
+     * socketpair connection. */
+    shutdown (urh->mhd.socket, SHUT_RDWR);
+  }
+  /* Socketpair sockets will remain open as they will be
+   * used with MHD_UPGRADE_ACTION_CLOSE. They will be
+   * closed by cleanup_upgraded_connection() during
+   * connection's final cleanup.
+   */
+}
+
+
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT*/
+
+
+/**
+ * A serious error occurred, close the
  * connection (and notify the application).
  *
  * @param connection connection to close with error
@@ -295,21 +978,28 @@
  */
 static void
 connection_close_error (struct MHD_Connection *connection,
-			const char *emsg)
+                        const char *emsg)
 {
-#if HAVE_MESSAGES
+  connection->stop_with_error = true;
+  connection->discard_request = true;
+#ifdef HAVE_MESSAGES
   if (NULL != emsg)
-    MHD_DLOG (connection->daemon, emsg);
-#endif
-  MHD_connection_close (connection, MHD_REQUEST_TERMINATED_WITH_ERROR);
+    MHD_DLOG (connection->daemon,
+              "%s\n",
+              emsg);
+#else  /* ! HAVE_MESSAGES */
+  (void) emsg; /* Mute compiler warning. */
+#endif /* ! HAVE_MESSAGES */
+  MHD_connection_close_ (connection,
+                         MHD_REQUEST_TERMINATED_WITH_ERROR);
 }
 
 
 /**
  * Macro to only include error message in call to
- * "connection_close_error" if we have HAVE_MESSAGES.
+ * #connection_close_error() if we have HAVE_MESSAGES.
  */
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
 #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, emsg)
 #else
 #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, NULL)
@@ -317,6 +1007,41 @@
 
 
 /**
+ * A serious error occurred, check whether error response is already
+ * queued and close the connection if response wasn't queued.
+ *
+ * @param connection connection to close with error
+ * @param emsg error message (can be NULL)
+ */
+static void
+connection_close_error_check (struct MHD_Connection *connection,
+                              const char *emsg)
+{
+  if ( (NULL != connection->rp.response) &&
+       (400 <= connection->rp.responseCode) &&
+       (NULL == connection->rp.response->crc) && /* Static response only! */
+       (connection->stop_with_error) &&
+       (MHD_CONNECTION_HEADERS_SENDING == connection->state) )
+    return; /* An error response was already queued */
+
+  connection_close_error (connection, emsg);
+}
+
+
+/**
+ * Macro to only include error message in call to
+ * #connection_close_error_check() if we have HAVE_MESSAGES.
+ */
+#ifdef HAVE_MESSAGES
+#define CONNECTION_CLOSE_ERROR_CHECK(c, emsg) \
+  connection_close_error_check (c, emsg)
+#else
+#define CONNECTION_CLOSE_ERROR_CHECK(c, emsg) \
+  connection_close_error_check (c, NULL)
+#endif
+
+
+/**
  * Prepare the response buffer of this connection for
  * sending.  Assumes that the response mutex is
  * already held.  If the transmission is complete,
@@ -328,60 +1053,92 @@
  *  lock on the response will have been released already
  *  in this case).
  */
-static int
+static enum MHD_Result
 try_ready_normal_body (struct MHD_Connection *connection)
 {
   ssize_t ret;
   struct MHD_Response *response;
 
-  response = connection->response;
+  response = connection->rp.response;
+  mhd_assert (connection->rp.props.send_reply_body);
+
+  if ( (0 == response->total_size) ||
+                     /* TODO: replace the next check with assert */
+       (connection->rp.rsp_write_position == response->total_size) )
+    return MHD_YES;  /* 0-byte response is always ready */
+  if (NULL != response->data_iov)
+  {
+    size_t copy_size;
+
+    if (NULL != connection->rp.resp_iov.iov)
+      return MHD_YES;
+    copy_size = response->data_iovcnt * sizeof(MHD_iovec_);
+    connection->rp.resp_iov.iov = MHD_connection_alloc_memory_ (connection,
+                                                                copy_size);
+    if (NULL == connection->rp.resp_iov.iov)
+    {
+      MHD_mutex_unlock_chk_ (&response->mutex);
+      /* not enough memory */
+      CONNECTION_CLOSE_ERROR (connection,
+                              _ ("Closing connection (out of memory)."));
+      return MHD_NO;
+    }
+    memcpy (connection->rp.resp_iov.iov,
+            response->data_iov,
+            copy_size);
+    connection->rp.resp_iov.cnt = response->data_iovcnt;
+    connection->rp.resp_iov.sent = 0;
+    return MHD_YES;
+  }
   if (NULL == response->crc)
     return MHD_YES;
-  if (0 == response->total_size)
-    return MHD_YES; /* 0-byte response is always ready */
   if ( (response->data_start <=
-	connection->response_write_position) &&
+        connection->rp.rsp_write_position) &&
        (response->data_size + response->data_start >
-	connection->response_write_position) )
+        connection->rp.rsp_write_position) )
     return MHD_YES; /* response already ready */
-#if LINUX
-  if ( (MHD_INVALID_SOCKET != response->fd) &&
-       (0 == (connection->daemon->options & MHD_USE_SSL)) )
-    {
-      /* will use sendfile, no need to bother response crc */
-      return MHD_YES;
-    }
-#endif
+#if defined(_MHD_HAVE_SENDFILE)
+  if (MHD_resp_sender_sendfile == connection->rp.resp_sender)
+  {
+    /* will use sendfile, no need to bother response crc */
+    return MHD_YES;
+  }
+#endif /* _MHD_HAVE_SENDFILE */
 
   ret = response->crc (response->crc_cls,
-                       connection->response_write_position,
-                       response->data,
-                       MHD_MIN (response->data_buffer_size,
-                                response->total_size -
-                                connection->response_write_position));
-  if ( (((ssize_t) MHD_CONTENT_READER_END_OF_STREAM) == ret) ||
-       (((ssize_t) MHD_CONTENT_READER_END_WITH_ERROR) == ret) )
-    {
-      /* either error or http 1.0 transfer, close socket! */
-      response->total_size = connection->response_write_position;
-      if (NULL != response->crc)
-        (void) MHD_mutex_unlock_ (&response->mutex);
-      if ( ((ssize_t)MHD_CONTENT_READER_END_OF_STREAM) == ret)
-	MHD_connection_close (connection, MHD_REQUEST_TERMINATED_COMPLETED_OK);
-      else
-	CONNECTION_CLOSE_ERROR (connection,
-				"Closing connection (stream error)\n");
-      return MHD_NO;
-    }
-  response->data_start = connection->response_write_position;
-  response->data_size = ret;
+                       connection->rp.rsp_write_position,
+                       (char *) response->data,
+                       (size_t) MHD_MIN ((uint64_t) response->data_buffer_size,
+                                         response->total_size
+                                         - connection->rp.rsp_write_position));
+  if (0 > ret)
+  {
+    /* either error or http 1.0 transfer, close socket! */
+    /* TODO: do not update total size, check whether response
+     * was really with unknown size */
+    response->total_size = connection->rp.rsp_write_position;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+    if (MHD_CONTENT_READER_END_OF_STREAM == ret)
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_COMPLETED_OK);
+    else
+      CONNECTION_CLOSE_ERROR (connection,
+                              _ ("Closing connection (application reported " \
+                                 "error generating data)."));
+    return MHD_NO;
+  }
+  response->data_start = connection->rp.rsp_write_position;
+  response->data_size = (size_t) ret;
   if (0 == ret)
-    {
-      connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY;
-      if (NULL != response->crc)
-        (void) MHD_mutex_unlock_ (&response->mutex);
-      return MHD_NO;
-    }
+  {
+    connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+    return MHD_NO;
+  }
   return MHD_YES;
 }
 
@@ -390,528 +1147,1233 @@
  * Prepare the response buffer of this connection for sending.
  * Assumes that the response mutex is already held.  If the
  * transmission is complete, this function may close the socket (and
- * return MHD_NO).
+ * return #MHD_NO).
  *
  * @param connection the connection
+ * @param[out] p_finished the pointer to variable that will be set to "true"
+ *                        when application returned indication of the end
+ *                        of the stream
  * @return #MHD_NO if readying the response failed
  */
-static int
-try_ready_chunked_body (struct MHD_Connection *connection)
+static enum MHD_Result
+try_ready_chunked_body (struct MHD_Connection *connection,
+                        bool *p_finished)
 {
   ssize_t ret;
-  char *buf;
   struct MHD_Response *response;
-  size_t size;
-  char cbuf[10];                /* 10: max strlen of "%x\r\n" */
-  size_t cblen;
+  static const size_t max_chunk = 0xFFFFFF;
+  char chunk_hdr[6];            /* 6: max strlen of "FFFFFF" */
+  /* "FFFFFF" + "\r\n" */
+  static const size_t max_chunk_hdr_len = sizeof(chunk_hdr) + 2;
+  /* "FFFFFF" + "\r\n" + "\r\n" (chunk termination) */
+  static const size_t max_chunk_overhead = sizeof(chunk_hdr) + 2 + 2;
+  size_t chunk_hdr_len;
+  uint64_t left_to_send;
+  size_t size_to_fill;
 
-  response = connection->response;
-  if (0 == connection->write_buffer_size)
-    {
-      size = connection->daemon->pool_size;
-      do
-        {
-          size /= 2;
-          if (size < 128)
-            {
-              /* not enough memory */
-              CONNECTION_CLOSE_ERROR (connection,
-				      "Closing connection (out of memory)\n");
-              return MHD_NO;
-            }
-          buf = MHD_pool_allocate (connection->pool, size, MHD_NO);
-        }
-      while (NULL == buf);
-      connection->write_buffer_size = size;
-      connection->write_buffer = buf;
-    }
+  response = connection->rp.response;
+  mhd_assert (NULL != response->crc || NULL != response->data);
 
-  if ( (response->data_start <=
-	connection->response_write_position) &&
-       (response->data_size + response->data_start >
-	connection->response_write_position) )
+  mhd_assert (0 == connection->write_buffer_append_offset);
+
+  /* The buffer must be reasonably large enough */
+  if (128 > connection->write_buffer_size)
+  {
+    size_t size;
+
+    size = connection->write_buffer_size + MHD_pool_get_free (connection->pool);
+    if (128 > size)
     {
-      /* buffer already ready, use what is there for the chunk */
-      ret = response->data_size + response->data_start - connection->response_write_position;
-      if ( (ret > 0) &&
-           (((size_t) ret) > connection->write_buffer_size - sizeof (cbuf) - 2) )
-	ret = connection->write_buffer_size - sizeof (cbuf) - 2;
-      memcpy (&connection->write_buffer[sizeof (cbuf)],
-	      &response->data[connection->response_write_position - response->data_start],
-	      ret);
-    }
-  else
-    {
-      /* buffer not in range, try to fill it */
-      if (0 == response->total_size)
-	ret = 0; /* response must be empty, don't bother calling crc */
-      else
-	ret = response->crc (response->crc_cls,
-			     connection->response_write_position,
-			     &connection->write_buffer[sizeof (cbuf)],
-			     connection->write_buffer_size - sizeof (cbuf) - 2);
-    }
-  if ( ((ssize_t) MHD_CONTENT_READER_END_WITH_ERROR) == ret)
-    {
-      /* error, close socket! */
-      response->total_size = connection->response_write_position;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+      MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+      /* not enough memory */
       CONNECTION_CLOSE_ERROR (connection,
-			      "Closing connection (error generating response)\n");
+                              _ ("Closing connection (out of memory)."));
       return MHD_NO;
     }
-  if ( (((ssize_t) MHD_CONTENT_READER_END_OF_STREAM) == ret) ||
-       (0 == response->total_size) )
-    {
-      /* end of message, signal other side! */
-      strcpy (connection->write_buffer, "0\r\n");
-      connection->write_buffer_append_offset = 3;
-      connection->write_buffer_send_offset = 0;
-      response->total_size = connection->response_write_position;
-      return MHD_YES;
+    /* Limit the buffer size to the largest usable size for chunks */
+    if ( (max_chunk + max_chunk_overhead) < size)
+      size = max_chunk + max_chunk_overhead;
+    connection->write_buffer = MHD_pool_reallocate (connection->pool,
+                                                    connection->write_buffer,
+                                                    connection->
+                                                    write_buffer_size, size);
+    mhd_assert (NULL != connection->write_buffer);
+    connection->write_buffer_size = size;
+  }
+  mhd_assert (max_chunk_overhead < connection->write_buffer_size);
+
+  if (MHD_SIZE_UNKNOWN == response->total_size)
+    left_to_send = MHD_SIZE_UNKNOWN;
+  else
+    left_to_send = response->total_size
+                   - connection->rp.rsp_write_position;
+
+  size_to_fill = connection->write_buffer_size - max_chunk_overhead;
+  /* Limit size for the callback to the max usable size */
+  if (max_chunk < size_to_fill)
+    size_to_fill = max_chunk;
+  if (left_to_send < size_to_fill)
+    size_to_fill = (size_t) left_to_send;
+
+  if (0 == left_to_send)
+    /* nothing to send, don't bother calling crc */
+    ret = MHD_CONTENT_READER_END_OF_STREAM;
+  else if ( (response->data_start <=
+             connection->rp.rsp_write_position) &&
+            (response->data_start + response->data_size >
+             connection->rp.rsp_write_position) )
+  {
+    /* difference between rsp_write_position and data_start is less
+       than data_size which is size_t type, no need to check for overflow */
+    const size_t data_write_offset
+      = (size_t) (connection->rp.rsp_write_position
+                  - response->data_start);
+    /* buffer already ready, use what is there for the chunk */
+    mhd_assert (SSIZE_MAX >= (response->data_size - data_write_offset));
+    mhd_assert (response->data_size >= data_write_offset);
+    ret = (ssize_t) (response->data_size - data_write_offset);
+    if ( ((size_t) ret) > size_to_fill)
+      ret = (ssize_t) size_to_fill;
+    memcpy (&connection->write_buffer[max_chunk_hdr_len],
+            &response->data[data_write_offset],
+            (size_t) ret);
+  }
+  else
+  {
+    if (NULL == response->crc)
+    { /* There is no way to reach this code */
+#if defined(MHD_USE_THREADS)
+      MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+      CONNECTION_CLOSE_ERROR (connection,
+                              _ ("No callback for the chunked data."));
+      return MHD_NO;
     }
+    ret = response->crc (response->crc_cls,
+                         connection->rp.rsp_write_position,
+                         &connection->write_buffer[max_chunk_hdr_len],
+                         size_to_fill);
+  }
+  if (MHD_CONTENT_READER_END_WITH_ERROR == ret)
+  {
+    /* error, close socket! */
+    /* TODO: remove update of the response size */
+    response->total_size = connection->rp.rsp_write_position;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+    CONNECTION_CLOSE_ERROR (connection,
+                            _ ("Closing connection (application error " \
+                               "generating response)."));
+    return MHD_NO;
+  }
+  if (MHD_CONTENT_READER_END_OF_STREAM == ret)
+  {
+    *p_finished = true;
+    /* TODO: remove update of the response size */
+    response->total_size = connection->rp.rsp_write_position;
+    return MHD_YES;
+  }
   if (0 == ret)
-    {
-      connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY;
-      return MHD_NO;
-    }
-  if (ret > 0xFFFFFF)
-    ret = 0xFFFFFF;
-  MHD_snprintf_ (cbuf,
-	    sizeof (cbuf),
-	    "%X\r\n", (unsigned int) ret);
-  cblen = strlen (cbuf);
-  EXTRA_CHECK (cblen <= sizeof (cbuf));
-  memcpy (&connection->write_buffer[sizeof (cbuf) - cblen], cbuf, cblen);
-  memcpy (&connection->write_buffer[sizeof (cbuf) + ret], "\r\n", 2);
-  connection->response_write_position += ret;
-  connection->write_buffer_send_offset = sizeof (cbuf) - cblen;
-  connection->write_buffer_append_offset = sizeof (cbuf) + ret + 2;
+  {
+    connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+    return MHD_NO;
+  }
+  if (size_to_fill < (size_t) ret)
+  {
+#if defined(MHD_USE_THREADS)
+    MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+    CONNECTION_CLOSE_ERROR (connection,
+                            _ ("Closing connection (application returned " \
+                               "more data than requested)."));
+    return MHD_NO;
+  }
+  chunk_hdr_len = MHD_uint32_to_strx ((uint32_t) ret, chunk_hdr,
+                                      sizeof(chunk_hdr));
+  mhd_assert (chunk_hdr_len != 0);
+  mhd_assert (chunk_hdr_len < sizeof(chunk_hdr));
+  *p_finished = false;
+  connection->write_buffer_send_offset =
+    (max_chunk_hdr_len - (chunk_hdr_len + 2));
+  memcpy (connection->write_buffer + connection->write_buffer_send_offset,
+          chunk_hdr,
+          chunk_hdr_len);
+  connection->write_buffer[max_chunk_hdr_len - 2] = '\r';
+  connection->write_buffer[max_chunk_hdr_len - 1] = '\n';
+  connection->write_buffer[max_chunk_hdr_len + (size_t) ret] = '\r';
+  connection->write_buffer[max_chunk_hdr_len + (size_t) ret + 1] = '\n';
+  connection->rp.rsp_write_position += (size_t) ret;
+  connection->write_buffer_append_offset = max_chunk_hdr_len + (size_t) ret + 2;
   return MHD_YES;
 }
 
 
 /**
- * Are we allowed to keep the given connection alive?  We can use the
- * TCP stream for a second request if the connection is HTTP 1.1 and
- * the "Connection" header either does not exist or is not set to
- * "close", or if the connection is HTTP 1.0 and the "Connection"
- * header is explicitly set to "keep-alive".  If no HTTP version is
- * specified (or if it is not 1.0 or 1.1), we definitively close the
- * connection.  If the "Connection" header is not exactly "close" or
- * "keep-alive", we proceed to use the default for the respective HTTP
- * version (which is conservative for HTTP 1.0, but might be a bit
- * optimistic for HTTP 1.1).
+ * Are we allowed to keep the given connection alive?
+ * We can use the TCP stream for a second request if the connection
+ * is HTTP 1.1 and the "Connection" header either does not exist or
+ * is not set to "close", or if the connection is HTTP 1.0 and the
+ * "Connection" header is explicitly set to "keep-alive".
+ * If no HTTP version is specified (or if it is not 1.0 or 1.1), we
+ * definitively close the connection.  If the "Connection" header is
+ * not exactly "close" or "keep-alive", we proceed to use the default
+ * for the respective HTTP version.
+ * If response has HTTP/1.0 flag or has "Connection: close" header
+ * then connection must be closed.
+ * If full request has not been read then connection must be closed
+ * as well.
  *
  * @param connection the connection to check for keepalive
- * @return #MHD_YES if (based on the request), a keepalive is
- *        legal
+ * @return MHD_CONN_USE_KEEPALIVE if (based on the request and the response),
+ *         a keepalive is legal,
+ *         MHD_CONN_MUST_CLOSE if connection must be closed after sending
+ *         complete reply,
+ *         MHD_CONN_MUST_UPGRADE if connection must be upgraded.
  */
-static int
+static enum MHD_ConnKeepAlive
 keepalive_possible (struct MHD_Connection *connection)
 {
-  const char *end;
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MHD_Response *const r = c->rp.response;  /**< a short alias */
 
-  if (NULL == connection->version)
-    return MHD_NO;
-  if ( (NULL != connection->response) &&
-       (0 != (connection->response->flags & MHD_RF_HTTP_VERSION_1_0_ONLY) ) )
-    return MHD_NO;
-  end = MHD_lookup_connection_value (connection,
-                                     MHD_HEADER_KIND,
-                                     MHD_HTTP_HEADER_CONNECTION);
-  if (MHD_str_equal_caseless_(connection->version,
-                       MHD_HTTP_VERSION_1_1))
+  mhd_assert (NULL != r);
+  if (MHD_CONN_MUST_CLOSE == c->keepalive)
+    return MHD_CONN_MUST_CLOSE;
+
+#ifdef UPGRADE_SUPPORT
+  /* TODO: Move below the next check when MHD stops closing connections
+   * when response is queued in first callback */
+  if (NULL != r->upgrade_handler)
   {
-    if (NULL == end)
-      return MHD_YES;
-    if ( (MHD_str_equal_caseless_ (end, "close")) ||
-         (MHD_str_equal_caseless_ (end, "upgrade")) )
-      return MHD_NO;
-   return MHD_YES;
+    /* No "close" token is enforced by 'add_response_header_connection()' */
+    mhd_assert (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE));
+    /* Valid HTTP version is enforced by 'MHD_queue_response()' */
+    mhd_assert (MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver));
+    mhd_assert (! c->stop_with_error);
+    return MHD_CONN_MUST_UPGRADE;
   }
-  if (MHD_str_equal_caseless_(connection->version,
-                       MHD_HTTP_VERSION_1_0))
+#endif /* UPGRADE_SUPPORT */
+
+  mhd_assert ( (! c->stop_with_error) || (c->discard_request));
+  if ((c->read_closed) || (c->discard_request))
+    return MHD_CONN_MUST_CLOSE;
+
+  if (0 != (r->flags & MHD_RF_HTTP_1_0_COMPATIBLE_STRICT))
+    return MHD_CONN_MUST_CLOSE;
+  if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE))
+    return MHD_CONN_MUST_CLOSE;
+
+  if (! MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver))
+    return MHD_CONN_MUST_CLOSE;
+
+  if (MHD_lookup_header_s_token_ci (c,
+                                    MHD_HTTP_HEADER_CONNECTION,
+                                    "close"))
+    return MHD_CONN_MUST_CLOSE;
+
+  if ((MHD_HTTP_VER_1_0 == connection->rq.http_ver) ||
+      (0 != (connection->rp.response->flags & MHD_RF_HTTP_1_0_SERVER)))
   {
-    if (NULL == end)
-      return MHD_NO;
-    if (MHD_str_equal_caseless_(end, "Keep-Alive"))
-      return MHD_YES;
-    return MHD_NO;
+    if (MHD_lookup_header_s_token_ci (connection,
+                                      MHD_HTTP_HEADER_CONNECTION,
+                                      "Keep-Alive"))
+      return MHD_CONN_USE_KEEPALIVE;
+
+    return MHD_CONN_MUST_CLOSE;
   }
-  return MHD_NO;
+
+  if (MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver))
+    return MHD_CONN_USE_KEEPALIVE;
+
+  return MHD_CONN_MUST_CLOSE;
 }
 
 
 /**
- * Produce HTTP "Date:" header.
+ * Produce time stamp.
  *
- * @param date where to write the header, with
- *        at least 128 bytes available space.
+ * Result is NOT null-terminated.
+ * Result is always 29 bytes long.
+ *
+ * @param[out] date where to write the time stamp, with
+ *             at least 29 bytes available space.
  */
-static void
-get_date_string (char *date)
+static bool
+get_date_str (char *date)
 {
-  static const char *const days[] =
-    { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
-  static const char *const mons[] =
-    { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
-    "Nov", "Dec"
+  static const char *const days[] = {
+    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
   };
+  static const char *const mons[] = {
+    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+  };
+  static const size_t buf_len = 29;
   struct tm now;
   time_t t;
-#if defined(_WIN32) && !defined(HAVE_GMTIME_S) && !defined(__CYGWIN__)
-  struct tm* pNow;
+  const char *src;
+#if ! defined(HAVE_C11_GMTIME_S) && ! defined(HAVE_W32_GMTIME_S) && \
+  ! defined(HAVE_GMTIME_R)
+  struct tm *pNow;
 #endif
 
-  date[0] = 0;
-  time (&t);
-#if !defined(_WIN32)
-  if (NULL != gmtime_r (&t, &now))
-    {
-#elif defined(HAVE_GMTIME_S)
-  if (0 == gmtime_s (&now, &t))
-    {
-#elif defined(__CYGWIN__)
-  if (NULL != gmtime_r (&t, &now))
-    {
+  if ((time_t) -1 == time (&t))
+    return false;
+#if defined(HAVE_C11_GMTIME_S)
+  if (NULL == gmtime_s (&t,
+                        &now))
+    return false;
+#elif defined(HAVE_W32_GMTIME_S)
+  if (0 != gmtime_s (&now,
+                     &t))
+    return false;
+#elif defined(HAVE_GMTIME_R)
+  if (NULL == gmtime_r (&t,
+                        &now))
+    return false;
 #else
-  pNow = gmtime(&t);
-  if (NULL != pNow)
-    {
-      now = *pNow;
+  pNow = gmtime (&t);
+  if (NULL == pNow)
+    return false;
+  now = *pNow;
 #endif
-      sprintf (date,
-             "Date: %3s, %02u %3s %04u %02u:%02u:%02u GMT\r\n",
-             days[now.tm_wday % 7],
-             (unsigned int) now.tm_mday,
-             mons[now.tm_mon % 12],
-             (unsigned int) (1900 + now.tm_year),
-             (unsigned int) now.tm_hour,
-             (unsigned int) now.tm_min,
-             (unsigned int) now.tm_sec);
-    }
+
+  /* Day of the week */
+  src = days[now.tm_wday % 7];
+  date[0] = src[0];
+  date[1] = src[1];
+  date[2] = src[2];
+  date[3] = ',';
+  date[4] = ' ';
+  /* Day of the month */
+  if (2 != MHD_uint8_to_str_pad ((uint8_t) now.tm_mday, 2,
+                                 date + 5, buf_len - 5))
+    return false;
+  date[7] = ' ';
+  /* Month */
+  src = mons[now.tm_mon % 12];
+  date[8] = src[0];
+  date[9] = src[1];
+  date[10] = src[2];
+  date[11] = ' ';
+  /* Year */
+  if (4 != MHD_uint16_to_str ((uint16_t) (1900 + now.tm_year), date + 12,
+                              buf_len - 12))
+    return false;
+  date[16] = ' ';
+  /* Time */
+  MHD_uint8_to_str_pad ((uint8_t) now.tm_hour, 2, date + 17, buf_len - 17);
+  date[19] = ':';
+  MHD_uint8_to_str_pad ((uint8_t) now.tm_min, 2, date + 20, buf_len - 20);
+  date[22] = ':';
+  MHD_uint8_to_str_pad ((uint8_t) now.tm_sec, 2, date + 23, buf_len - 23);
+  date[25] = ' ';
+  date[26] = 'G';
+  date[27] = 'M';
+  date[28] = 'T';
+
+  return true;
 }
 
 
 /**
- * Try growing the read buffer.  We initially claim half the
- * available buffer space for the read buffer (the other half
- * being left for management data structures; the write
- * buffer can in the end take virtually everything as the
- * read buffer can be reduced to the minimum necessary at that
- * point.
+ * Produce HTTP DATE header.
+ * Result is always 37 bytes long (plus one terminating null).
+ *
+ * @param[out] header where to write the header, with
+ *             at least 38 bytes available space.
+ */
+static bool
+get_date_header (char *header)
+{
+  if (! get_date_str (header + 6))
+  {
+    header[0] = 0;
+    return false;
+  }
+  header[0] = 'D';
+  header[1] = 'a';
+  header[2] = 't';
+  header[3] = 'e';
+  header[4] = ':';
+  header[5] = ' ';
+  header[35] = '\r';
+  header[36] = '\n';
+  header[37] = 0;
+  return true;
+}
+
+
+/**
+ * Try growing the read buffer.  We initially claim half the available
+ * buffer space for the read buffer (the other half being left for
+ * management data structures; the write buffer can in the end take
+ * virtually everything as the read buffer can be reduced to the
+ * minimum necessary at that point.
  *
  * @param connection the connection
- * @return #MHD_YES on success, #MHD_NO on failure
+ * @param required set to 'true' if grow is required, i.e. connection
+ *                 will fail if no additional space is granted
+ * @return 'true' on success, 'false' on failure
  */
-static int
-try_grow_read_buffer (struct MHD_Connection *connection)
+static bool
+try_grow_read_buffer (struct MHD_Connection *connection,
+                      bool required)
 {
-  void *buf;
   size_t new_size;
+  size_t avail_size;
+  void *rb;
 
+  avail_size = MHD_pool_get_free (connection->pool);
+  if (0 == avail_size)
+    return false;               /* No more space available */
   if (0 == connection->read_buffer_size)
-    new_size = connection->daemon->pool_size / 2;
+    new_size = avail_size / 2;  /* Use half of available buffer for reading */
   else
-    new_size = connection->read_buffer_size + MHD_BUF_INC_SIZE;
-  buf = MHD_pool_reallocate (connection->pool,
-                             connection->read_buffer,
-                             connection->read_buffer_size,
-                             new_size);
-  if (NULL == buf)
-    return MHD_NO;
+  {
+    size_t grow_size;
+
+    grow_size = avail_size / 8;
+    if (MHD_BUF_INC_SIZE > grow_size)
+    {                  /* Shortage of space */
+      if (! required)
+        return false;  /* Grow is not mandatory, leave some space in pool */
+      else
+      {
+        /* Shortage of space, but grow is mandatory */
+        static const size_t small_inc = MHD_BUF_INC_SIZE / 8;
+        if (small_inc < avail_size)
+          grow_size = small_inc;
+        else
+          grow_size = avail_size;
+      }
+    }
+    new_size = connection->read_buffer_size + grow_size;
+  }
   /* we can actually grow the buffer, do it! */
-  connection->read_buffer = buf;
+  rb = MHD_pool_reallocate (connection->pool,
+                            connection->read_buffer,
+                            connection->read_buffer_size,
+                            new_size);
+  if (NULL == rb)
+  {
+    /* This should NOT be possible: we just computed 'new_size' so that
+       it should fit. If it happens, somehow our read buffer is not in
+       the right position in the pool, say because someone called
+       MHD_pool_allocate() without 'from_end' set to 'true'? Anyway,
+       should be investigated! (Ideally provide all data from
+       *pool and connection->read_buffer and new_size for debugging). */
+    mhd_assert (0);
+    return false;
+  }
+  connection->read_buffer = rb;
+  mhd_assert (NULL != connection->read_buffer);
   connection->read_buffer_size = new_size;
-  return MHD_YES;
+  return true;
+}
+
+
+/**
+ * Shrink connection read buffer to the zero size of free space in the buffer
+ * @param connection the connection whose read buffer is being manipulated
+ */
+static void
+connection_shrink_read_buffer (struct MHD_Connection *connection)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  void *new_buf;
+
+  if ((NULL == c->read_buffer) || (0 == c->read_buffer_size))
+  {
+    mhd_assert (0 == c->read_buffer_size);
+    mhd_assert (0 == c->read_buffer_offset);
+    return;
+  }
+
+  mhd_assert (c->read_buffer_offset <= c->read_buffer_size);
+  if (0 == c->read_buffer_offset)
+  {
+    MHD_pool_deallocate (c->pool, c->read_buffer, c->read_buffer_size);
+    c->read_buffer = NULL;
+    c->read_buffer_size = 0;
+  }
+  else
+  {
+    new_buf = MHD_pool_reallocate (c->pool, c->read_buffer, c->read_buffer_size,
+                                   c->read_buffer_offset);
+    mhd_assert (c->read_buffer == new_buf);
+    c->read_buffer = new_buf;
+    c->read_buffer_size = c->read_buffer_offset;
+  }
+}
+
+
+/**
+ * Allocate the maximum available amount of memory from MemoryPool
+ * for write buffer.
+ * @param connection the connection whose write buffer is being manipulated
+ * @return the size of free space in write buffer, may be smaller
+ *         than requested size.
+ */
+static size_t
+connection_maximize_write_buffer (struct MHD_Connection *connection)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MemoryPool *const pool = connection->pool;
+  void *new_buf;
+  size_t new_size;
+  size_t free_size;
+
+  mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size));
+  mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset);
+  mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset);
+
+  free_size = MHD_pool_get_free (pool);
+  if (0 != free_size)
+  {
+    new_size = c->write_buffer_size + free_size;
+    /* This function must not move the buffer position.
+     * MHD_pool_reallocate () may return the new position only if buffer was
+     * allocated 'from_end' or is not the last allocation,
+     * which should not happen. */
+    new_buf = MHD_pool_reallocate (pool,
+                                   c->write_buffer,
+                                   c->write_buffer_size,
+                                   new_size);
+    mhd_assert ((c->write_buffer == new_buf) || (NULL == c->write_buffer));
+    c->write_buffer = new_buf;
+    c->write_buffer_size = new_size;
+    if (c->write_buffer_send_offset == c->write_buffer_append_offset)
+    {
+      /* All data have been sent, reset offsets to zero. */
+      c->write_buffer_send_offset = 0;
+      c->write_buffer_append_offset = 0;
+    }
+  }
+
+  return c->write_buffer_size - c->write_buffer_append_offset;
+}
+
+
+#if 0 /* disable unused function */
+/**
+ * Shrink connection write buffer to the size of unsent data.
+ *
+ * @note: The number of calls of this function should be limited to avoid extra
+ * zeroing of the memory.
+ * @param connection the connection whose write buffer is being manipulated
+ * @param connection the connection to manipulate write buffer
+ */
+static void
+connection_shrink_write_buffer (struct MHD_Connection *connection)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MemoryPool *const pool = connection->pool;
+  void *new_buf;
+
+  mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size));
+  mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset);
+  mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset);
+
+  if ( (NULL == c->write_buffer) || (0 == c->write_buffer_size))
+  {
+    mhd_assert (0 == c->write_buffer_append_offset);
+    mhd_assert (0 == c->write_buffer_send_offset);
+    c->write_buffer = NULL;
+    return;
+  }
+  if (c->write_buffer_append_offset == c->write_buffer_size)
+    return;
+
+  new_buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size,
+                                 c->write_buffer_append_offset);
+  mhd_assert ((c->write_buffer == new_buf) || \
+              (0 == c->write_buffer_append_offset));
+  c->write_buffer_size = c->write_buffer_append_offset;
+  if (0 == c->write_buffer_size)
+    c->write_buffer = NULL;
+  else
+    c->write_buffer = new_buf;
+}
+
+
+#endif /* unused function */
+
+
+/**
+ * Switch connection from recv mode to send mode.
+ *
+ * Current request header or body will not be read anymore,
+ * response must be assigned to connection.
+ * @param connection the connection to prepare for sending.
+ */
+static void
+connection_switch_from_recv_to_send (struct MHD_Connection *connection)
+{
+  /* Read buffer is not needed for this request, shrink it.*/
+  connection_shrink_read_buffer (connection);
+}
+
+
+/**
+ * This enum type describes requirements for reply body and reply bode-specific
+ * headers (namely Content-Length, Transfer-Encoding).
+ */
+enum replyBodyUse
+{
+  /**
+   * No reply body allowed.
+   * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are
+   * not allowed as well.
+   */
+  RP_BODY_NONE = 0,
+
+  /**
+   * Do not send reply body.
+   * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are
+   * allowed, but optional.
+   */
+  RP_BODY_HEADERS_ONLY = 1,
+
+  /**
+   * Send reply body and
+   * reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked'.
+   * Reply body headers are required.
+   */
+  RP_BODY_SEND = 2
+};
+
+
+/**
+ * Check whether reply body must be used.
+ *
+ * If reply body is needed, it could be zero-sized.
+ *
+ * @param connection the connection to check
+ * @param rcode the response code
+ * @return enum value indicating whether response body can be used and
+ *         whether response body length headers are allowed or required.
+ * @sa is_reply_body_header_needed()
+ */
+static enum replyBodyUse
+is_reply_body_needed (struct MHD_Connection *connection,
+                      unsigned int rcode)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+
+  mhd_assert (100 <= rcode);
+  mhd_assert (999 >= rcode);
+
+  if (199 >= rcode)
+    return RP_BODY_NONE;
+
+  if (MHD_HTTP_NO_CONTENT == rcode)
+    return RP_BODY_NONE;
+
+#if 0
+  /* This check is not needed as upgrade handler is used only with code 101 */
+#ifdef UPGRADE_SUPPORT
+  if (NULL != rp.response->upgrade_handler)
+    return RP_BODY_NONE;
+#endif /* UPGRADE_SUPPORT */
+#endif
+
+#if 0
+  /* CONNECT is not supported by MHD */
+  /* Successful responses for connect requests are filtered by
+   * MHD_queue_response() */
+  if ( (MHD_HTTP_MTHD_CONNECT == c->rq.http_mthd) &&
+       (2 == rcode / 100) )
+    return false; /* Actually pass-through CONNECT is not supported by MHD */
+#endif
+
+  /* Reply body headers could be used.
+   * Check whether reply body itself must be used. */
+
+  if (MHD_HTTP_MTHD_HEAD == c->rq.http_mthd)
+    return RP_BODY_HEADERS_ONLY;
+
+  if (MHD_HTTP_NOT_MODIFIED == rcode)
+    return RP_BODY_HEADERS_ONLY;
+
+  /* Reply body must be sent. The body may have zero length, but body size
+   * must be indicated by headers ('Content-Length:' or
+   * 'Transfer-Encoding: chunked'). */
+  return RP_BODY_SEND;
+}
+
+
+/**
+ * Setup connection reply properties.
+ *
+ * Reply properties include presence of reply body, transfer-encoding
+ * type and other.
+ *
+ * @param connection to connection to process
+ */
+static void
+setup_reply_properties (struct MHD_Connection *connection)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MHD_Response *const r = c->rp.response;  /**< a short alias */
+  enum replyBodyUse use_rp_body;
+  bool use_chunked;
+
+  mhd_assert (NULL != r);
+
+  /* ** Adjust reply properties ** */
+
+  c->keepalive = keepalive_possible (c);
+  use_rp_body = is_reply_body_needed (c, c->rp.responseCode);
+  c->rp.props.send_reply_body = (use_rp_body > RP_BODY_HEADERS_ONLY);
+  c->rp.props.use_reply_body_headers = (use_rp_body >= RP_BODY_HEADERS_ONLY);
+
+#ifdef UPGRADE_SUPPORT
+  mhd_assert ((NULL == r->upgrade_handler) || (RP_BODY_NONE == use_rp_body));
+#endif /* UPGRADE_SUPPORT */
+
+  if (c->rp.props.use_reply_body_headers)
+  {
+    if ((MHD_SIZE_UNKNOWN == r->total_size) ||
+        (0 != (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)))
+    { /* Use chunked reply encoding if possible */
+
+      /* Check whether chunked encoding is supported by the client */
+      if (! MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver))
+        use_chunked = false;
+      /* Check whether chunked encoding is allowed for the reply */
+      else if (0 != (r->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT
+                                 | MHD_RF_HTTP_1_0_SERVER)))
+        use_chunked = false;
+      else
+        /* If chunked encoding is supported and allowed, and response size
+         * is unknown, use chunked even for non-Keep-Alive connections.
+         * See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3
+         * Also use chunked if it is enforced by application and supported by
+         * the client. */
+        use_chunked = true;
+    }
+    else
+      use_chunked = false;
+
+    if ( (MHD_SIZE_UNKNOWN == r->total_size) && ! use_chunked)
+    {
+      /* End of the stream is indicated by closure */
+      c->keepalive = MHD_CONN_MUST_CLOSE;
+    }
+  }
+  else
+    use_chunked = false; /* chunked encoding cannot be used without body */
+
+  c->rp.props.chunked = use_chunked;
+#ifdef _DEBUG
+  c->rp.props.set = true;
+#endif /* _DEBUG */
+}
+
+
+/**
+ * Check whether queued response is suitable for @a connection.
+ * @param connection to connection to check
+ */
+static void
+check_connection_reply (struct MHD_Connection *connection)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MHD_Response *const r = c->rp.response;  /**< a short alias */
+  mhd_assert (c->rp.props.set);
+
+#ifdef HAVE_MESSAGES
+  if ((! c->rp.props.use_reply_body_headers) && (0 != r->total_size))
+  {
+    MHD_DLOG (c->daemon,
+              _ ("This reply with response code %u cannot use reply body. "
+                 "Non-empty response body is ignored and not used.\n"),
+              (unsigned) (c->rp.responseCode));
+  }
+  if ( (! c->rp.props.use_reply_body_headers) &&
+       (0 != (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) )
+  {
+    MHD_DLOG (c->daemon,
+              _ ("This reply with response code %u cannot use reply body. "
+                 "Application defined \"Content-Length\" header violates"
+                 "HTTP specification.\n"),
+              (unsigned) (c->rp.responseCode));
+  }
+#else
+  (void) c; /* Mute compiler warning */
+  (void) r; /* Mute compiler warning */
+#endif
+}
+
+
+/**
+ * Append data to the buffer if enough space is available,
+ * update position.
+ * @param[out] buf the buffer to append data to
+ * @param[in,out] ppos the pointer to position in the @a buffer
+ * @param buf_size the size of the @a buffer
+ * @param append the data to append
+ * @param append_size the size of the @a append
+ * @return true if data has been added and position has been updated,
+ *         false if not enough space is available
+ */
+static bool
+buffer_append (char *buf,
+               size_t *ppos,
+               size_t buf_size,
+               const char *append,
+               size_t append_size)
+{
+  mhd_assert (NULL != buf); /* Mute static analyzer */
+  if (buf_size < *ppos + append_size)
+    return false;
+  memcpy (buf + *ppos, append, append_size);
+  *ppos += append_size;
+  return true;
+}
+
+
+/**
+ * Append static string to the buffer if enough space is available,
+ * update position.
+ * @param[out] buf the buffer to append data to
+ * @param[in,out] ppos the pointer to position in the @a buffer
+ * @param buf_size the size of the @a buffer
+ * @param str the static string to append
+ * @return true if data has been added and position has been updated,
+ *         false if not enough space is available
+ */
+#define buffer_append_s(buf,ppos,buf_size,str) \
+  buffer_append (buf,ppos,buf_size,str, MHD_STATICSTR_LEN_ (str))
+
+
+/**
+ * Add user-defined headers from response object to
+ * the text buffer.
+ *
+ * @param buf the buffer to add headers to
+ * @param ppos the pointer to the position in the @a buf
+ * @param buf_size the size of the @a buf
+ * @param response the response
+ * @param filter_transf_enc skip "Transfer-Encoding" header if any
+ * @param filter_content_len skip "Content-Length" header if any
+ * @param add_close add "close" token to the
+ *                  "Connection:" header (if any), ignored if no "Connection:"
+ *                  header was added by user or if "close" token is already
+ *                  present in "Connection:" header
+ * @param add_keep_alive add "Keep-Alive" token to the
+ *                       "Connection:" header (if any)
+ * @return true if succeed,
+ *         false if buffer is too small
+ */
+static bool
+add_user_headers (char *buf,
+                  size_t *ppos,
+                  size_t buf_size,
+                  struct MHD_Response *response,
+                  bool filter_transf_enc,
+                  bool filter_content_len,
+                  bool add_close,
+                  bool add_keep_alive)
+{
+  struct MHD_Response *const r = response; /**< a short alias */
+  struct MHD_HTTP_Res_Header *hdr; /**< Iterates through User-specified headers */
+  size_t el_size; /**< the size of current element to be added to the @a buf */
+
+  mhd_assert (! add_close || ! add_keep_alive);
+
+  if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))
+    filter_transf_enc = false;   /* No such header */
+  if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH))
+    filter_content_len = false;  /* No such header */
+  if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
+  {
+    add_close = false;          /* No such header */
+    add_keep_alive = false;     /* No such header */
+  }
+  else if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE))
+    add_close = false;          /* "close" token was already set */
+
+  for (hdr = r->first_header; NULL != hdr; hdr = hdr->next)
+  {
+    size_t initial_pos = *ppos;
+    if (MHD_HEADER_KIND != hdr->kind)
+      continue;
+    if (filter_transf_enc)
+    { /* Need to filter-out "Transfer-Encoding" */
+      if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) ==
+           hdr->header_size) &&
+          (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                          hdr->header, hdr->header_size)) )
+      {
+        filter_transf_enc = false; /* There is the only one such header */
+        continue; /* Skip "Transfer-Encoding" header */
+      }
+    }
+    if (filter_content_len)
+    { /* Need to filter-out "Content-Length" */
+      if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) ==
+           hdr->header_size) &&
+          (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_CONTENT_LENGTH,
+                                          hdr->header, hdr->header_size)) )
+      {
+        /* Reset filter flag if only one header is allowed */
+        filter_transf_enc =
+          (0 == (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH));
+        continue; /* Skip "Content-Length" header */
+      }
+    }
+
+    /* Add user header */
+    el_size = hdr->header_size + 2 + hdr->value_size + 2;
+    if (buf_size < *ppos + el_size)
+      return false;
+    memcpy (buf + *ppos, hdr->header, hdr->header_size);
+    (*ppos) += hdr->header_size;
+    buf[(*ppos)++] = ':';
+    buf[(*ppos)++] = ' ';
+    if (add_close || add_keep_alive)
+    {
+      /* "Connection:" header must be always the first one */
+      mhd_assert (MHD_str_equal_caseless_n_ (hdr->header, \
+                                             MHD_HTTP_HEADER_CONNECTION, \
+                                             hdr->header_size));
+
+      if (add_close)
+      {
+        el_size += MHD_STATICSTR_LEN_ ("close, ");
+        if (buf_size < initial_pos + el_size)
+          return false;
+        memcpy (buf + *ppos, "close, ",
+                MHD_STATICSTR_LEN_ ("close, "));
+        *ppos += MHD_STATICSTR_LEN_ ("close, ");
+      }
+      else
+      {
+        el_size += MHD_STATICSTR_LEN_ ("Keep-Alive, ");
+        if (buf_size < initial_pos + el_size)
+          return false;
+        memcpy (buf + *ppos, "Keep-Alive, ",
+                MHD_STATICSTR_LEN_ ("Keep-Alive, "));
+        *ppos += MHD_STATICSTR_LEN_ ("Keep-Alive, ");
+      }
+      add_close = false;
+      add_keep_alive = false;
+    }
+    if (0 != hdr->value_size)
+      memcpy (buf + *ppos, hdr->value, hdr->value_size);
+    *ppos += hdr->value_size;
+    buf[(*ppos)++] = '\r';
+    buf[(*ppos)++] = '\n';
+    mhd_assert (initial_pos + el_size == (*ppos));
+  }
+  return true;
 }
 
 
 /**
  * Allocate the connection's write buffer and fill it with all of the
- * headers (or footers, if we have already sent the body) from the
- * HTTPd's response.  If headers are missing in the response supplied
- * by the application, additional headers may be added here.
+ * headers from the response.
+ * Required headers are added here.
  *
  * @param connection the connection
  * @return #MHD_YES on success, #MHD_NO on failure (out of memory)
  */
-static int
+static enum MHD_Result
 build_header_response (struct MHD_Connection *connection)
 {
-  size_t size;
-  size_t off;
-  struct MHD_HTTP_Header *pos;
-  char code[256];
-  char date[128];
-  char content_length_buf[128];
-  size_t content_length_len;
-  char *data;
-  enum MHD_ValueKind kind;
-  const char *reason_phrase;
-  uint32_t rc;
-  const char *client_requested_close;
-  const char *response_has_close;
-  const char *response_has_keepalive;
-  const char *have_encoding;
-  const char *have_content_length;
-  int must_add_close;
-  int must_add_chunked_encoding;
-  int must_add_keep_alive;
-  int must_add_content_length;
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MHD_Response *const r = c->rp.response; /**< a short alias */
+  char *buf;                                     /**< the output buffer */
+  size_t pos;                                    /**< append offset in the @a buf */
+  size_t buf_size;                               /**< the size of the @a buf */
+  size_t el_size;                                /**< the size of current element to be added to the @a buf */
+  unsigned rcode;                                /**< the response code */
+  bool use_conn_close;                           /**< Use "Connection: close" header */
+  bool use_conn_k_alive;                         /**< Use "Connection: Keep-Alive" header */
 
-  EXTRA_CHECK (NULL != connection->version);
-  if (0 == strlen (connection->version))
-    {
-      data = MHD_pool_allocate (connection->pool, 0, MHD_YES);
-      connection->write_buffer = data;
-      connection->write_buffer_append_offset = 0;
-      connection->write_buffer_send_offset = 0;
-      connection->write_buffer_size = 0;
-      return MHD_YES;
-    }
-  if (MHD_CONNECTION_FOOTERS_RECEIVED == connection->state)
-    {
-      rc = connection->responseCode & (~MHD_ICY_FLAG);
-      reason_phrase = MHD_get_reason_phrase_for (rc);
-      sprintf (code,
-               "%s %u %s\r\n",
-	       (0 != (connection->responseCode & MHD_ICY_FLAG))
-	       ? "ICY"
-	       : ( (MHD_str_equal_caseless_ (MHD_HTTP_VERSION_1_0,
-				     connection->version))
-		   ? MHD_HTTP_VERSION_1_0
-		   : MHD_HTTP_VERSION_1_1),
-	       rc,
-	       reason_phrase);
-      off = strlen (code);
-      /* estimate size */
-      size = off + 2;           /* +2 for extra "\r\n" at the end */
-      kind = MHD_HEADER_KIND;
-      if ( (0 == (connection->daemon->options & MHD_SUPPRESS_DATE_NO_CLOCK)) &&
-	   (NULL == MHD_get_response_header (connection->response,
-					     MHD_HTTP_HEADER_DATE)) )
-        get_date_string (date);
-      else
-        date[0] = '\0';
-      size += strlen (date);
-    }
+  mhd_assert (NULL != r);
+
+  /* ** Adjust response properties ** */
+
+  setup_reply_properties (c);
+
+  mhd_assert (c->rp.props.set);
+  mhd_assert ((MHD_CONN_MUST_CLOSE == c->keepalive) || \
+              (MHD_CONN_USE_KEEPALIVE == c->keepalive) || \
+              (MHD_CONN_MUST_UPGRADE == c->keepalive));
+#ifdef UPGRADE_SUPPORT
+  mhd_assert ((NULL == r->upgrade_handler) || \
+              (MHD_CONN_MUST_UPGRADE == c->keepalive));
+#else  /* ! UPGRADE_SUPPORT */
+  mhd_assert (MHD_CONN_MUST_UPGRADE != c->keepalive);
+#endif /* ! UPGRADE_SUPPORT */
+  mhd_assert ((! c->rp.props.chunked) || c->rp.props.use_reply_body_headers);
+  mhd_assert ((! c->rp.props.send_reply_body) || \
+              c->rp.props.use_reply_body_headers);
+#ifdef UPGRADE_SUPPORT
+  mhd_assert (NULL == r->upgrade_handler || \
+              ! c->rp.props.use_reply_body_headers);
+#endif /* UPGRADE_SUPPORT */
+
+  check_connection_reply (c);
+
+  rcode = (unsigned) c->rp.responseCode;
+  if (MHD_CONN_MUST_CLOSE == c->keepalive)
+  {
+    /* The closure of connection must be always indicated by header
+     * to avoid hung connections */
+    use_conn_close = true;
+    use_conn_k_alive = false;
+  }
+  else if (MHD_CONN_USE_KEEPALIVE == c->keepalive)
+  {
+    use_conn_close = false;
+    /* Add "Connection: keep-alive" if request is HTTP/1.0 or
+     * if reply is HTTP/1.0
+     * For HTTP/1.1 add header only if explicitly requested by app
+     * (by response flag), as "Keep-Alive" is default for HTTP/1.1. */
+    if ((0 != (r->flags & MHD_RF_SEND_KEEP_ALIVE_HEADER)) ||
+        (MHD_HTTP_VER_1_0 == c->rq.http_ver) ||
+        (0 != (r->flags & MHD_RF_HTTP_1_0_SERVER)))
+      use_conn_k_alive = true;
+    else
+      use_conn_k_alive = false;
+  }
   else
-    {
-      /* 2 bytes for final CRLF of a Chunked-Body */
-      size = 2;
-      kind = MHD_FOOTER_KIND;
-      off = 0;
+  {
+    use_conn_close = false;
+    use_conn_k_alive = false;
+  }
+
+  /* ** Actually build the response header ** */
+
+  /* Get all space available */
+  connection_maximize_write_buffer (c);
+  buf = c->write_buffer;
+  pos = c->write_buffer_append_offset;
+  buf_size = c->write_buffer_size;
+  if (0 == buf_size)
+    return MHD_NO;
+  mhd_assert (NULL != buf);
+
+  /* * The status line * */
+
+  /* The HTTP version */
+  if (! c->rp.responseIcy)
+  { /* HTTP reply */
+    if (0 == (r->flags & MHD_RF_HTTP_1_0_SERVER))
+    { /* HTTP/1.1 reply */
+      /* Use HTTP/1.1 responses for HTTP/1.0 clients.
+       * See https://datatracker.ietf.org/doc/html/rfc7230#section-2.6 */
+      if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_1))
+        return MHD_NO;
     }
-
-  /* calculate extra headers we need to add, such as 'Connection: close',
-     first see what was explicitly requested by the application */
-  must_add_close = MHD_NO;
-  must_add_chunked_encoding = MHD_NO;
-  must_add_keep_alive = MHD_NO;
-  must_add_content_length = MHD_NO;
-  switch (connection->state)
-    {
-    case MHD_CONNECTION_FOOTERS_RECEIVED:
-      response_has_close = MHD_get_response_header (connection->response,
-                                                    MHD_HTTP_HEADER_CONNECTION);
-      response_has_keepalive = response_has_close;
-      if ( (NULL != response_has_close) &&
-           (!MHD_str_equal_caseless_ (response_has_close, "close")) )
-        response_has_close = NULL;
-      if ( (NULL != response_has_keepalive) &&
-           (!MHD_str_equal_caseless_ (response_has_keepalive, "Keep-Alive")) )
-        response_has_keepalive = NULL;
-      client_requested_close = MHD_lookup_connection_value (connection,
-                                                            MHD_HEADER_KIND,
-                                                            MHD_HTTP_HEADER_CONNECTION);
-      if ( (NULL != client_requested_close) &&
-           (!MHD_str_equal_caseless_ (client_requested_close, "close")) )
-        client_requested_close = NULL;
-
-      /* now analyze chunked encoding situation */
-      connection->have_chunked_upload = MHD_NO;
-
-      if ( (MHD_SIZE_UNKNOWN == connection->response->total_size) &&
-           (NULL == response_has_close) &&
-           (NULL == client_requested_close) )
-        {
-          /* size is unknown, and close was not explicitly requested;
-             need to either to HTTP 1.1 chunked encoding or
-             close the connection */
-          /* 'close' header doesn't exist yet, see if we need to add one;
-             if the client asked for a close, no need to start chunk'ing */
-          if ( (MHD_YES == keepalive_possible (connection)) &&
-               (MHD_str_equal_caseless_ (MHD_HTTP_VERSION_1_1,
-                                         connection->version) ) )
-            {
-              have_encoding = MHD_get_response_header (connection->response,
-                                                       MHD_HTTP_HEADER_TRANSFER_ENCODING);
-              if (NULL == have_encoding)
-                {
-                  must_add_chunked_encoding = MHD_YES;
-                  connection->have_chunked_upload = MHD_YES;
-                }
-              else if (MHD_str_equal_caseless_(have_encoding, "identity"))
-                {
-                  /* application forced identity encoding, can't do 'chunked' */
-                  must_add_close = MHD_YES;
-                }
-              else
-                {
-                  connection->have_chunked_upload = MHD_YES;
-                }
-            }
-          else
-            {
-              /* Keep alive or chunking not possible
-                 => set close header if not present */
-              if (NULL == response_has_close)
-                must_add_close = MHD_YES;
-            }
-        }
-
-      /* check for other reasons to add 'close' header */
-      if ( ( (NULL != client_requested_close) ||
-             (MHD_YES == connection->read_closed) ) &&
-           (NULL == response_has_close) &&
-           (0 == (connection->response->flags & MHD_RF_HTTP_VERSION_1_0_ONLY) ) )
-        must_add_close = MHD_YES;
-
-      /* check if we should add a 'content length' header */
-      have_content_length = MHD_get_response_header (connection->response,
-                                                     MHD_HTTP_HEADER_CONTENT_LENGTH);
-
-      if ( (MHD_SIZE_UNKNOWN != connection->response->total_size) &&
-           (NULL == have_content_length) &&
-           ( (NULL == connection->method) ||
-             (! MHD_str_equal_caseless_ (connection->method,
-                                         MHD_HTTP_METHOD_CONNECT)) ) )
-        {
-          /*
-            Here we add a content-length if one is missing; however,
-            for 'connect' methods, the responses MUST NOT include a
-            content-length header *if* the response code is 2xx (in
-            which case we expect there to be no body).  Still,
-            as we don't know the response code here in some cases, we
-            simply only force adding a content-length header if this
-            is not a 'connect' or if the response is not empty
-            (which is kind of more sane, because if some crazy
-            application did return content with a 2xx status code,
-            then having a content-length might again be a good idea).
-
-            Note that the change from 'SHOULD NOT' to 'MUST NOT' is
-            a recent development of the HTTP 1.1 specification.
-          */
-          content_length_len
-            = sprintf (content_length_buf,
-                       MHD_HTTP_HEADER_CONTENT_LENGTH ": " MHD_UNSIGNED_LONG_LONG_PRINTF "\r\n",
-                       (MHD_UNSIGNED_LONG_LONG) connection->response->total_size);
-          must_add_content_length = MHD_YES;
-        }
-
-      /* check for adding keep alive */
-      if ( (NULL == response_has_keepalive) &&
-           (NULL == response_has_close) &&
-           (MHD_NO == must_add_close) &&
-           (0 == (connection->response->flags & MHD_RF_HTTP_VERSION_1_0_ONLY) ) &&
-           (MHD_YES == keepalive_possible (connection)) )
-        must_add_keep_alive = MHD_YES;
-      break;
-    case MHD_CONNECTION_BODY_SENT:
-      break;
-    default:
-      EXTRA_CHECK (0);
+    else
+    { /* HTTP/1.0 reply */
+      if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_0))
+        return MHD_NO;
     }
-
-  if (must_add_close)
-    size += strlen ("Connection: close\r\n");
-  if (must_add_keep_alive)
-    size += strlen ("Connection: Keep-Alive\r\n");
-  if (must_add_chunked_encoding)
-    size += strlen ("Transfer-Encoding: chunked\r\n");
-  if (must_add_content_length)
-    size += content_length_len;
-  EXTRA_CHECK (! (must_add_close && must_add_keep_alive) );
-  EXTRA_CHECK (! (must_add_chunked_encoding && must_add_content_length) );
-
-  for (pos = connection->response->first_header; NULL != pos; pos = pos->next)
-    if ( (pos->kind == kind) &&
-         (! ( (MHD_YES == must_add_close) &&
-              (pos->value == response_has_keepalive) &&
-              (MHD_str_equal_caseless_(pos->header,
-                                MHD_HTTP_HEADER_CONNECTION) ) ) ) )
-      size += strlen (pos->header) + strlen (pos->value) + 4; /* colon, space, linefeeds */
-  /* produce data */
-  data = MHD_pool_allocate (connection->pool, size + 1, MHD_NO);
-  if (NULL == data)
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-                "Not enough memory for write!\n");
-#endif
+  }
+  else
+  { /* ICY reply */
+    if (! buffer_append_s (buf, &pos, buf_size, "ICY"))
       return MHD_NO;
-    }
-  if (MHD_CONNECTION_FOOTERS_RECEIVED == connection->state)
-    {
-      memcpy (data, code, off);
-    }
-  if (must_add_close)
-    {
-      /* we must add the 'Connection: close' header */
-      memcpy (&data[off],
-              "Connection: close\r\n",
-	      strlen ("Connection: close\r\n"));
-      off += strlen ("Connection: close\r\n");
-    }
-  if (must_add_keep_alive)
-    {
-      /* we must add the 'Connection: Keep-Alive' header */
-      memcpy (&data[off],
-              "Connection: Keep-Alive\r\n",
-	      strlen ("Connection: Keep-Alive\r\n"));
-      off += strlen ("Connection: Keep-Alive\r\n");
-    }
-  if (must_add_chunked_encoding)
-    {
-      /* we must add the 'Transfer-Encoding: chunked' header */
-      memcpy (&data[off],
-              "Transfer-Encoding: chunked\r\n",
-	      strlen ("Transfer-Encoding: chunked\r\n"));
-      off += strlen ("Transfer-Encoding: chunked\r\n");
-    }
-  if (must_add_content_length)
-    {
-      /* we must add the 'Content-Length' header */
-      memcpy (&data[off],
-              content_length_buf,
-	      content_length_len);
-      off += content_length_len;
-    }
-  for (pos = connection->response->first_header; NULL != pos; pos = pos->next)
-    if ( (pos->kind == kind) &&
-         (! ( (pos->value == response_has_keepalive) &&
-              (MHD_YES == must_add_close) &&
-              (MHD_str_equal_caseless_(pos->header,
-                                MHD_HTTP_HEADER_CONNECTION) ) ) ) )
-      off += sprintf (&data[off],
-		      "%s: %s\r\n",
-		      pos->header,
-		      pos->value);
-  if (MHD_CONNECTION_FOOTERS_RECEIVED == connection->state)
-    {
-      strcpy (&data[off], date);
-      off += strlen (date);
-    }
-  memcpy (&data[off], "\r\n", 2);
-  off += 2;
+  }
 
-  if (off != size)
-    mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL);
-  connection->write_buffer = data;
-  connection->write_buffer_append_offset = size;
-  connection->write_buffer_send_offset = 0;
-  connection->write_buffer_size = size + 1;
+  /* The response code */
+  if (buf_size < pos + 5) /* space + code + space */
+    return MHD_NO;
+  buf[pos++] = ' ';
+  pos += MHD_uint16_to_str ((uint16_t) rcode, buf + pos,
+                            buf_size - pos);
+  buf[pos++] = ' ';
+
+  /* The reason phrase */
+  el_size = MHD_get_reason_phrase_len_for (rcode);
+  if (0 == el_size)
+  {
+    if (! buffer_append_s (buf, &pos, buf_size, "Non-Standard Status"))
+      return MHD_NO;
+  }
+  else if (! buffer_append (buf, &pos, buf_size,
+                            MHD_get_reason_phrase_for (rcode),
+                            el_size))
+    return MHD_NO;
+
+  /* The linefeed */
+  if (buf_size < pos + 2)
+    return MHD_NO;
+  buf[pos++] = '\r';
+  buf[pos++] = '\n';
+
+  /* * The headers * */
+
+  /* Main automatic headers */
+
+  /* The "Date:" header */
+  if ( (0 == (r->flags_auto & MHD_RAF_HAS_DATE_HDR)) &&
+       (0 == (c->daemon->options & MHD_USE_SUPPRESS_DATE_NO_CLOCK)) )
+  {
+    /* Additional byte for unused zero-termination */
+    if (buf_size < pos + 38)
+      return MHD_NO;
+    if (get_date_header (buf + pos))
+      pos += 37;
+  }
+  /* The "Connection:" header */
+  mhd_assert (! use_conn_close || ! use_conn_k_alive);
+  mhd_assert (! use_conn_k_alive || ! use_conn_close);
+  if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
+  {
+    if (use_conn_close)
+    {
+      if (! buffer_append_s (buf, &pos, buf_size,
+                             MHD_HTTP_HEADER_CONNECTION ": close\r\n"))
+        return MHD_NO;
+    }
+    else if (use_conn_k_alive)
+    {
+      if (! buffer_append_s (buf, &pos, buf_size,
+                             MHD_HTTP_HEADER_CONNECTION ": Keep-Alive\r\n"))
+        return MHD_NO;
+    }
+  }
+
+  /* User-defined headers */
+
+  if (! add_user_headers (buf, &pos, buf_size, r,
+                          ! c->rp.props.chunked,
+                          (! c->rp.props.use_reply_body_headers) &&
+                          (0 ==
+                           (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)),
+                          use_conn_close,
+                          use_conn_k_alive))
+    return MHD_NO;
+
+  /* Other automatic headers */
+
+  if ( (c->rp.props.use_reply_body_headers) &&
+       (0 == (r->flags & MHD_RF_HEAD_ONLY_RESPONSE)) )
+  {
+    /* Body-specific headers */
+
+    if (c->rp.props.chunked)
+    { /* Chunked encoding is used */
+      if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))
+      { /* No chunked encoding header set by user */
+        if (! buffer_append_s (buf, &pos, buf_size,
+                               MHD_HTTP_HEADER_TRANSFER_ENCODING ": " \
+                               "chunked\r\n"))
+          return MHD_NO;
+      }
+    }
+    else /* Chunked encoding is not used */
+    {
+      if (MHD_SIZE_UNKNOWN != r->total_size)
+      { /* The size is known */
+        if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH))
+        { /* The response does not have "Content-Length" header */
+          if (! buffer_append_s (buf, &pos, buf_size,
+                                 MHD_HTTP_HEADER_CONTENT_LENGTH ": "))
+            return MHD_NO;
+          el_size = MHD_uint64_to_str (r->total_size, buf + pos,
+                                       buf_size - pos);
+          if (0 == el_size)
+            return MHD_NO;
+          pos += el_size;
+
+          if (buf_size < pos + 2)
+            return MHD_NO;
+          buf[pos++] = '\r';
+          buf[pos++] = '\n';
+        }
+      }
+    }
+  }
+
+  /* * Header termination * */
+  if (buf_size < pos + 2)
+    return MHD_NO;
+  buf[pos++] = '\r';
+  buf[pos++] = '\n';
+
+  c->write_buffer_append_offset = pos;
+  return MHD_YES;
+}
+
+
+/**
+ * Allocate the connection's write buffer (if necessary) and fill it
+ * with response footers.
+ * Works only for chunked responses as other responses do not need
+ * and do not support any kind of footers.
+ *
+ * @param connection the connection
+ * @return #MHD_YES on success, #MHD_NO on failure (out of memory)
+ */
+static enum MHD_Result
+build_connection_chunked_response_footer (struct MHD_Connection *connection)
+{
+  char *buf;           /**< the buffer to write footers to */
+  size_t buf_size;     /**< the size of the @a buf */
+  size_t used_size;    /**< the used size of the @a buf */
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MHD_HTTP_Res_Header *pos;
+
+  mhd_assert (connection->rp.props.chunked);
+  /* TODO: allow combining of the final footer with the last chunk,
+   * modify the next assert. */
+  mhd_assert (MHD_CONNECTION_CHUNKED_BODY_SENT == connection->state);
+  mhd_assert (NULL != c->rp.response);
+
+  buf_size = connection_maximize_write_buffer (c);
+  /* '5' is the minimal size of chunked footer ("0\r\n\r\n") */
+  if (buf_size < 5)
+    return MHD_NO;
+  mhd_assert (NULL != c->write_buffer);
+  buf = c->write_buffer + c->write_buffer_append_offset;
+  mhd_assert (NULL != buf);
+  used_size = 0;
+  buf[used_size++] = '0';
+  buf[used_size++] = '\r';
+  buf[used_size++] = '\n';
+
+  for (pos = c->rp.response->first_header; NULL != pos; pos = pos->next)
+  {
+    if (MHD_FOOTER_KIND == pos->kind)
+    {
+      size_t new_used_size; /* resulting size with this header */
+      /* '4' is colon, space, linefeeds */
+      new_used_size = used_size + pos->header_size + pos->value_size + 4;
+      if (new_used_size > buf_size)
+        return MHD_NO;
+      memcpy (buf + used_size, pos->header, pos->header_size);
+      used_size += pos->header_size;
+      buf[used_size++] = ':';
+      buf[used_size++] = ' ';
+      memcpy (buf + used_size, pos->value, pos->value_size);
+      used_size += pos->value_size;
+      buf[used_size++] = '\r';
+      buf[used_size++] = '\n';
+      mhd_assert (used_size == new_used_size);
+    }
+  }
+  if (used_size + 2 > buf_size)
+    return MHD_NO;
+  buf[used_size++] = '\r';
+  buf[used_size++] = '\n';
+
+  c->write_buffer_append_offset += used_size;
+  mhd_assert (c->write_buffer_append_offset <= c->write_buffer_size);
+
   return MHD_YES;
 }
 
@@ -924,205 +2386,341 @@
  * @param connection the connection
  * @param status_code the response code to send (400, 413 or 414)
  * @param message the error message to send
+ * @param message_len the length of the @a message
  */
 static void
-transmit_error_response (struct MHD_Connection *connection,
-                         unsigned int status_code,
-			 const char *message)
+transmit_error_response_len (struct MHD_Connection *connection,
+                             unsigned int status_code,
+                             const char *message,
+                             size_t message_len)
 {
   struct MHD_Response *response;
+  enum MHD_Result iret;
 
-  if (NULL == connection->version)
-    {
-      /* we were unable to process the full header line, so we don't
-	 really know what version the client speaks; assume 1.0 */
-      connection->version = MHD_HTTP_VERSION_1_0;
-    }
-  connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
-  connection->read_closed = MHD_YES;
-#if HAVE_MESSAGES
+  mhd_assert (! connection->stop_with_error); /* Do not send error twice */
+  if (connection->stop_with_error)
+  { /* Should not happen */
+    if (MHD_CONNECTION_CLOSED > connection->state)
+      connection->state = MHD_CONNECTION_CLOSED;
+
+    return;
+  }
+  connection->stop_with_error = true;
+  connection->discard_request = true;
+#ifdef HAVE_MESSAGES
   MHD_DLOG (connection->daemon,
-            "Error %u (`%s') processing request, closing connection.\n",
-            status_code, message);
+            _ ("Error processing request (HTTP response code is %u ('%s')). " \
+               "Closing connection.\n"),
+            status_code,
+            message);
 #endif
-  EXTRA_CHECK (NULL == connection->response);
-  response = MHD_create_response_from_buffer (strlen (message),
-					      (void *) message,
-					      MHD_RESPMEM_PERSISTENT);
-  MHD_queue_response (connection, status_code, response);
-  EXTRA_CHECK (NULL != connection->response);
+  if (MHD_CONNECTION_START_REPLY < connection->state)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Too late to send an error response, " \
+                 "response is being sent already.\n"),
+              status_code,
+              message);
+#endif
+    CONNECTION_CLOSE_ERROR (connection,
+                            _ ("Too late for error response."));
+    return;
+  }
+  /* TODO: remove when special error queue function is implemented */
+  connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED;
+  if (0 != connection->read_buffer_size)
+  {
+    /* Read buffer is not needed anymore, discard it
+     * to free some space for error response. */
+    MHD_pool_deallocate (connection->pool,
+                         connection->read_buffer,
+                         connection->read_buffer_size);
+    connection->read_buffer = NULL;
+    connection->read_buffer_size = 0;
+    connection->read_buffer_offset = 0;
+  }
+  if (NULL != connection->rp.response)
+  {
+    MHD_destroy_response (connection->rp.response);
+    connection->rp.response = NULL;
+  }
+  response = MHD_create_response_from_buffer_static (message_len,
+                                                     message);
+  if (NULL == response)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Failed to create error response.\n"),
+              status_code,
+              message);
+#endif
+    /* can't even send a reply, at least close the connection */
+    connection->state = MHD_CONNECTION_CLOSED;
+    return;
+  }
+  iret = MHD_queue_response (connection,
+                             status_code,
+                             response);
   MHD_destroy_response (response);
+  if (MHD_NO == iret)
+  {
+    /* can't even send a reply, at least close the connection */
+    CONNECTION_CLOSE_ERROR (connection,
+                            _ ("Closing connection " \
+                               "(failed to queue error response)."));
+    return;
+  }
+  mhd_assert (NULL != connection->rp.response);
+  /* Do not reuse this connection. */
+  connection->keepalive = MHD_CONN_MUST_CLOSE;
   if (MHD_NO == build_header_response (connection))
+  {
+    /* No memory. Release everything. */
+    connection->rq.version = NULL;
+    connection->rq.method = NULL;
+    connection->rq.url = NULL;
+    connection->rq.url_len = 0;
+    connection->rq.last = NULL;
+    connection->rq.colon = NULL;
+    connection->rq.headers_received = NULL;
+    connection->rq.headers_received_tail = NULL;
+    connection->write_buffer = NULL;
+    connection->write_buffer_size = 0;
+    connection->write_buffer_send_offset = 0;
+    connection->write_buffer_append_offset = 0;
+    connection->read_buffer
+      = MHD_pool_reset (connection->pool,
+                        NULL,
+                        0,
+                        0);
+    connection->read_buffer_size = 0;
+
+    /* Retry with empty buffer */
+    if (MHD_NO == build_header_response (connection))
     {
-      /* oops - close! */
       CONNECTION_CLOSE_ERROR (connection,
-			      "Closing connection (failed to create response header)\n");
+                              _ ("Closing connection " \
+                                 "(failed to create error response header)."));
+      return;
     }
-  else
-    {
-      connection->state = MHD_CONNECTION_HEADERS_SENDING;
-    }
+  }
+  connection->state = MHD_CONNECTION_HEADERS_SENDING;
 }
 
 
 /**
+ * Transmit static string as error response
+ */
+#define transmit_error_response_static(c, code, msg) \
+  transmit_error_response_len (c, code, msg, MHD_STATICSTR_LEN_ (msg))
+
+/**
  * Update the 'event_loop_info' field of this connection based on the state
  * that the connection is now in.  May also close the connection or
  * perform other updates to the connection if needed to prepare for
  * the next round of the event loop.
  *
- * @param connection connetion to get poll set for
+ * @param connection connection to get poll set for
  */
 static void
 MHD_connection_update_event_loop_info (struct MHD_Connection *connection)
 {
-  while (1)
+  /* Do not update states of suspended connection */
+  if (connection->suspended)
+    return; /* States will be updated after resume. */
+#ifdef HTTPS_SUPPORT
+  if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
+  {   /* HTTPS connection. */
+    switch (connection->tls_state)
     {
-#if DEBUG_STATES
-      MHD_DLOG (connection->daemon,
-                "%s: state: %s\n",
-                __FUNCTION__,
-                MHD_state_to_string (connection->state));
-#endif
-      switch (connection->state)
-        {
-#if HTTPS_SUPPORT
-	case MHD_TLS_CONNECTION_INIT:
-	  if (SSL_want_read (connection->tls_session))
-            connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
-	  else
-            connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
-	  break;
-#endif
-        case MHD_CONNECTION_INIT:
-        case MHD_CONNECTION_URL_RECEIVED:
-        case MHD_CONNECTION_HEADER_PART_RECEIVED:
-          /* while reading headers, we always grow the
-             read buffer if needed, no size-check required */
-          if ( (connection->read_buffer_offset == connection->read_buffer_size) &&
-	       (MHD_NO == try_grow_read_buffer (connection)) )
-            {
-              transmit_error_response (connection,
-                                       (connection->url != NULL)
-                                       ? MHD_HTTP_REQUEST_ENTITY_TOO_LARGE
-                                       : MHD_HTTP_REQUEST_URI_TOO_LONG,
-                                       REQUEST_TOO_BIG);
-              continue;
-            }
-	  if (MHD_NO == connection->read_closed)
-	    connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
-	  else
-	    connection->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
-          break;
-        case MHD_CONNECTION_HEADERS_RECEIVED:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_HEADERS_PROCESSED:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_CONTINUE_SENDING:
-          connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
-          break;
-        case MHD_CONNECTION_CONTINUE_SENT:
-          if (connection->read_buffer_offset == connection->read_buffer_size)
-            {
-              if ((MHD_YES != try_grow_read_buffer (connection)) &&
-                  (0 != (connection->daemon->options &
-                         (MHD_USE_SELECT_INTERNALLY |
-                          MHD_USE_THREAD_PER_CONNECTION))))
-                {
-                  /* failed to grow the read buffer, and the
-                     client which is supposed to handle the
-                     received data in a *blocking* fashion
-                     (in this mode) did not handle the data as
-                     it was supposed to!
-                     => we would either have to do busy-waiting
-                     (on the client, which would likely fail),
-                     or if we do nothing, we would just timeout
-                     on the connection (if a timeout is even
-                     set!).
-                     Solution: we kill the connection with an error */
-                  transmit_error_response (connection,
-                                           MHD_HTTP_INTERNAL_SERVER_ERROR,
-                                           INTERNAL_ERROR);
-                  continue;
-                }
-            }
-          if ( (connection->read_buffer_offset < connection->read_buffer_size) &&
-	       (MHD_NO == connection->read_closed) )
-	    connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
-	  else
-	    connection->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
-          break;
-        case MHD_CONNECTION_BODY_RECEIVED:
-        case MHD_CONNECTION_FOOTER_PART_RECEIVED:
-          /* while reading footers, we always grow the
-             read buffer if needed, no size-check required */
-          if (MHD_YES == connection->read_closed)
-            {
-	      CONNECTION_CLOSE_ERROR (connection,
-				      NULL);
-              continue;
-            }
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
-          /* transition to FOOTERS_RECEIVED
-             happens in read handler */
-          break;
-        case MHD_CONNECTION_FOOTERS_RECEIVED:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
-          break;
-        case MHD_CONNECTION_HEADERS_SENDING:
-          /* headers in buffer, keep writing */
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
-          break;
-        case MHD_CONNECTION_HEADERS_SENT:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_NORMAL_BODY_READY:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
-          break;
-        case MHD_CONNECTION_NORMAL_BODY_UNREADY:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
-          break;
-        case MHD_CONNECTION_CHUNKED_BODY_READY:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
-          break;
-        case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_BLOCK;
-          break;
-        case MHD_CONNECTION_BODY_SENT:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_FOOTERS_SENDING:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
-          break;
-        case MHD_CONNECTION_FOOTERS_SENT:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_CLOSED:
-	  connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
-          return;       /* do nothing, not even reading */
-        default:
-          EXTRA_CHECK (0);
-        }
-      break;
+    case MHD_TLS_CONN_INIT:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      return;
+    case MHD_TLS_CONN_HANDSHAKING:
+    case MHD_TLS_CONN_WR_CLOSING:
+      if (0 == gnutls_record_get_direction (connection->tls_session))
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      else
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      return;
+    case MHD_TLS_CONN_CONNECTED:
+      break; /* Do normal processing */
+    case MHD_TLS_CONN_WR_CLOSED:
+    case MHD_TLS_CONN_TLS_FAILED:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
+      return;
+    case MHD_TLS_CONN_TLS_CLOSING:  /* Not implemented yet */
+    case MHD_TLS_CONN_TLS_CLOSED:   /* Not implemented yet */
+    case MHD_TLS_CONN_INVALID_STATE:
+    case MHD_TLS_CONN_NO_TLS: /* Not possible */
+    default:
+      MHD_PANIC (_ ("Invalid TLS state value.\n"));
     }
+  }
+#endif /* HTTPS_SUPPORT */
+  while (1)
+  {
+#if DEBUG_STATES
+    MHD_DLOG (connection->daemon,
+              _ ("In function %s handling connection at state: %s\n"),
+              MHD_FUNC_,
+              MHD_state_to_string (connection->state));
+#endif
+    switch (connection->state)
+    {
+    case MHD_CONNECTION_INIT:
+    case MHD_CONNECTION_REQ_LINE_RECEIVING:
+    case MHD_CONNECTION_URL_RECEIVED:
+    case MHD_CONNECTION_HEADER_PART_RECEIVED:
+      /* while reading headers, we always grow the
+         read buffer if needed, no size-check required */
+      if ( (connection->read_buffer_offset == connection->read_buffer_size) &&
+           (! try_grow_read_buffer (connection, true)) )
+      {
+        if (connection->rq.url != NULL)
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                                          REQUEST_TOO_BIG);
+        else
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_URI_TOO_LONG,
+                                          REQUEST_TOO_BIG);
+        continue;
+      }
+      if (! connection->discard_request)
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      else
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
+      break;
+    case MHD_CONNECTION_HEADERS_RECEIVED:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_HEADERS_PROCESSED:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_CONTINUE_SENDING:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_CONNECTION_BODY_RECEIVING:
+      if (connection->read_buffer_offset == connection->read_buffer_size)
+      {
+        const bool internal_poll = (0 != (connection->daemon->options
+                                          & MHD_USE_INTERNAL_POLLING_THREAD));
+        if ( (! try_grow_read_buffer (connection, true)) &&
+             internal_poll)
+        {
+          /* failed to grow the read buffer, and the
+             client which is supposed to handle the
+             received data in a *blocking* fashion
+             (in this mode) did not handle the data as
+             it was supposed to!
+             => we would either have to do busy-waiting
+             (on the client, which would likely fail),
+             or if we do nothing, we would just timeout
+             on the connection (if a timeout is even
+             set!).
+             Solution: we kill the connection with an error */
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_INTERNAL_SERVER_ERROR,
+                                          INTERNAL_ERROR);
+          continue;
+        }
+      }
+      if (connection->discard_request)
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
+      else if (connection->read_buffer_offset == connection->read_buffer_size)
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
+      else if (0 == connection->read_buffer_offset)
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      else if (connection->rq.some_payload_processed)
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ;
+      else
+        connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      break;
+    case MHD_CONNECTION_BODY_RECEIVED:
+    case MHD_CONNECTION_FOOTER_PART_RECEIVED:
+      /* while reading footers, we always grow the
+         read buffer if needed, no size-check required */
+      if (connection->read_closed)
+      {
+        CONNECTION_CLOSE_ERROR (connection,
+                                NULL);
+        continue;
+      }
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+      /* transition to FOOTERS_RECEIVED
+         happens in read handler */
+      break;
+    case MHD_CONNECTION_FOOTERS_RECEIVED:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_FULL_REQ_RECEIVED:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
+      break;
+    case MHD_CONNECTION_START_REPLY:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_HEADERS_SENDING:
+      /* headers in buffer, keep writing */
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_CONNECTION_HEADERS_SENT:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_NORMAL_BODY_READY:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_CONNECTION_NORMAL_BODY_UNREADY:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
+      break;
+    case MHD_CONNECTION_CHUNKED_BODY_READY:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS;
+      break;
+    case MHD_CONNECTION_CHUNKED_BODY_SENT:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_FOOTERS_SENDING:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE;
+      break;
+    case MHD_CONNECTION_FULL_REPLY_SENT:
+      mhd_assert (0);
+      break;
+    case MHD_CONNECTION_CLOSED:
+      connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
+      return;           /* do nothing, not even reading */
+#ifdef UPGRADE_SUPPORT
+    case MHD_CONNECTION_UPGRADE:
+      mhd_assert (0);
+      break;
+#endif /* UPGRADE_SUPPORT */
+    default:
+      mhd_assert (0);
+    }
+    break;
+  }
 }
 
 
 /**
- * Parse a single line of the HTTP header.  Advance
- * read_buffer (!) appropriately.  If the current line does not
- * fit, consider growing the buffer.  If the line is
- * far too long, close the connection.  If no line is
- * found (incomplete, buffer too small, line too long),
+ * Parse a single line of the HTTP header.  Advance read_buffer (!)
+ * appropriately.  If the current line does not fit, consider growing
+ * the buffer.  If the line is far too long, close the connection.  If
+ * no line is found (incomplete, buffer too small, line too long),
  * return NULL.  Otherwise return a pointer to the line.
  *
  * @param connection connection we're processing
- * @return NULL if no full line is available
+ * @param[out] line_len pointer to variable that receive
+ *             length of line or NULL
+ * @return NULL if no full line is available; note that the returned
+ *         string will not be 0-termianted
  */
 static char *
-get_next_header_line (struct MHD_Connection *connection)
+get_next_header_line (struct MHD_Connection *connection,
+                      size_t *line_len)
 {
   char *rbuf;
   size_t pos;
@@ -1131,33 +2729,54 @@
     return NULL;
   pos = 0;
   rbuf = connection->read_buffer;
-  while ((pos < connection->read_buffer_offset - 1) &&
-         ('\r' != rbuf[pos]) && ('\n' != rbuf[pos]))
-    pos++;
-  if ( (pos == connection->read_buffer_offset - 1) &&
-       ('\n' != rbuf[pos]) )
-    {
-      /* not found, consider growing... */
-      if ( (connection->read_buffer_offset == connection->read_buffer_size) &&
-	   (MHD_NO ==
-	    try_grow_read_buffer (connection)) )
-	{
-	  transmit_error_response (connection,
-				   (NULL != connection->url)
-				   ? MHD_HTTP_REQUEST_ENTITY_TOO_LARGE
-				   : MHD_HTTP_REQUEST_URI_TOO_LONG,
-				   REQUEST_TOO_BIG);
-	}
-      return NULL;
+  mhd_assert (NULL != rbuf);
+
+  do
+  {
+    const char c = rbuf[pos];
+    bool found;
+    found = false;
+    if ( ('\r' == c) && (pos < connection->read_buffer_offset - 1) &&
+         ('\n' == rbuf[pos + 1]) )
+    { /* Found CRLF */
+      found = true;
+      if (line_len)
+        *line_len = pos;
+      rbuf[pos++] = 0; /* Replace CR with zero */
+      rbuf[pos++] = 0; /* Replace LF with zero */
     }
-  /* found, check if we have proper LFCR */
-  if (('\r' == rbuf[pos]) && ('\n' == rbuf[pos + 1]))
-    rbuf[pos++] = '\0';         /* skip both r and n */
-  rbuf[pos++] = '\0';
-  connection->read_buffer += pos;
-  connection->read_buffer_size -= pos;
-  connection->read_buffer_offset -= pos;
-  return rbuf;
+    else if ('\n' == c) /* TODO: Add MHD option to disallow */
+    { /* Found bare LF */
+      found = true;
+      if (line_len)
+        *line_len = pos;
+      rbuf[pos++] = 0; /* Replace LF with zero */
+    }
+    if (found)
+    {
+      connection->read_buffer += pos;
+      connection->read_buffer_size -= pos;
+      connection->read_buffer_offset -= pos;
+      return rbuf;
+    }
+  } while (++pos < connection->read_buffer_offset);
+
+  /* not found, consider growing... */
+  if ( (connection->read_buffer_offset == connection->read_buffer_size) &&
+       (! try_grow_read_buffer (connection, true)) )
+  {
+    if (NULL != connection->rq.url)
+      transmit_error_response_static (connection,
+                                      MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                                      REQUEST_TOO_BIG);
+    else
+      transmit_error_response_static (connection,
+                                      MHD_HTTP_URI_TOO_LONG,
+                                      REQUEST_TOO_BIG);
+  }
+  if (line_len)
+    *line_len = 0;
+  return NULL;
 }
 
 
@@ -1165,217 +2784,490 @@
  * Add an entry to the HTTP headers of a connection.  If this fails,
  * transmit an error response (request too big).
  *
- * @param connection the connection for which a
- *  value should be set
+ * @param cls the context (connection)
  * @param kind kind of the value
  * @param key key for the value
+ * @param key_size number of bytes in @a key
  * @param value the value itself
+ * @param value_size number of bytes in @a value
  * @return #MHD_NO on failure (out of memory), #MHD_YES for success
  */
-static int
-connection_add_header (struct MHD_Connection *connection,
-                       char *key, char *value, enum MHD_ValueKind kind)
+static enum MHD_Result
+connection_add_header (void *cls,
+                       const char *key,
+                       size_t key_size,
+                       const char *value,
+                       size_t value_size,
+                       enum MHD_ValueKind kind)
 {
-  if (MHD_NO == MHD_set_connection_value (connection,
-					  kind,
-					  key, value))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-                "Not enough memory to allocate header record!\n");
+  struct MHD_Connection *connection = (struct MHD_Connection *) cls;
+  if (MHD_NO ==
+      MHD_set_connection_value_n (connection,
+                                  kind,
+                                  key,
+                                  key_size,
+                                  value,
+                                  value_size))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Not enough memory in pool to allocate header record!\n"));
 #endif
-      transmit_error_response (connection, MHD_HTTP_REQUEST_ENTITY_TOO_LARGE,
-                               REQUEST_TOO_BIG);
-      return MHD_NO;
-    }
+    transmit_error_response_static (connection,
+                                    MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                                    REQUEST_TOO_BIG);
+    return MHD_NO;
+  }
   return MHD_YES;
 }
 
 
+#ifdef COOKIE_SUPPORT
+
 /**
- * Parse and unescape the arguments given by the client as part
- * of the HTTP request URI.
- *
- * @param kind header kind to use for adding to the connection
- * @param connection connection to add headers to
- * @param args argument URI string (after "?" in URI)
- * @return #MHD_NO on failure (out of memory), #MHD_YES for success
+ * Cookie parsing result
  */
-static int
-parse_arguments (enum MHD_ValueKind kind,
-                 struct MHD_Connection *connection,
-		 char *args)
+enum _MHD_ParseCookie
 {
-  char *equals;
-  char *amper;
+  MHD_PARSE_COOKIE_OK = MHD_YES,      /**< Success or no cookies in headers */
+  MHD_PARSE_COOKIE_OK_LAX = 2,        /**< Cookies parsed, but workarounds used */
+  MHD_PARSE_COOKIE_MALFORMED = -1,    /**< Invalid cookie header */
+  MHD_PARSE_COOKIE_NO_MEMORY = MHD_NO /**< Not enough memory in the pool */
+};
 
-  while (NULL != args)
+
+/**
+ * Parse the cookies string (see RFC 6265).
+ *
+ * Try to parse the cookies string even if it is not strictly formed
+ * as specified by RFC 6265.
+ *
+ * @param str the string to parse, without leading whitespaces
+ * @param str_len the size of the @a str, not including mandatory
+ *                zero-termination
+ * @param connection the connection to add parsed cookies
+ * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise
+ */
+static enum _MHD_ParseCookie
+parse_cookies_string (char *str,
+                      const size_t str_len,
+                      struct MHD_Connection *connection)
+{
+  size_t i;
+  bool non_strict;
+  /* Skip extra whitespaces and empty cookies */
+  const bool allow_wsp_empty = (0 >= connection->daemon->client_discipline);
+  /* Allow whitespaces around '=' character */
+  const bool wsp_around_eq = (-3 >= connection->daemon->client_discipline);
+  /* Allow whitespaces in quoted cookie value */
+  const bool wsp_in_quoted = (-2 >= connection->daemon->client_discipline);
+  /* Allow tab as space after semicolon between cookies */
+  const bool tab_as_sp = (0 >= connection->daemon->client_discipline);
+  /* Allow no space after semicolon between cookies */
+  const bool allow_no_space = (0 >= connection->daemon->client_discipline);
+
+  non_strict = false;
+  i = 0;
+  while (i < str_len)
+  {
+    size_t name_start;
+    size_t name_len;
+    size_t value_start;
+    size_t value_len;
+    bool val_quoted;
+    /* Skip any whitespaces and empty cookies */
+    while (' ' == str[i] || '\t' == str[i] || ';' == str[i])
     {
-      equals = strchr (args, '=');
-      amper = strchr (args, '&');
-      if (NULL == amper)
-	{
-	  /* last argument */
-	  if (NULL == equals)
-	    {
-	      /* got 'foo', add key 'foo' with NULL for value */
-              MHD_unescape_plus (args);
-	      connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-						     connection,
-						     args);
-	      return connection_add_header (connection,
-					    args,
-					    NULL,
-					    kind);
-	    }
-	  /* got 'foo=bar' */
-	  equals[0] = '\0';
-	  equals++;
-          MHD_unescape_plus (args);
-	  connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-						 connection,
-						 args);
-          MHD_unescape_plus (equals);
-	  connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-						 connection,
-						 equals);
-	  return connection_add_header (connection, args, equals, kind);
-	}
-      /* amper is non-NULL here */
-      amper[0] = '\0';
-      amper++;
-      if ( (NULL == equals) ||
-	   (equals >= amper) )
-	{
-	  /* got 'foo&bar' or 'foo&bar=val', add key 'foo' with NULL for value */
-          MHD_unescape_plus (args);
-	  connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-						 connection,
-						 args);
-	  if (MHD_NO ==
-	      connection_add_header (connection,
-				     args,
-				     NULL,
-				     kind))
-	    return MHD_NO;
-	  /* continue with 'bar' */
-	  args = amper;
-	  continue;
-
-	}
-      /* equals and amper are non-NULL here, and equals < amper,
-	 so we got regular 'foo=value&bar...'-kind of argument */
-      equals[0] = '\0';
-      equals++;
-      MHD_unescape_plus (args);
-      connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-					     connection,
-					     args);
-      MHD_unescape_plus (equals);
-      connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-					     connection,
-					     equals);
-      if (MHD_NO == connection_add_header (connection, args, equals, kind))
-        return MHD_NO;
-      args = amper;
+      if (! allow_wsp_empty)
+        return MHD_PARSE_COOKIE_MALFORMED;
+      non_strict = true;
+      i++;
+      if (i == str_len)
+        return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK;
     }
-  return MHD_YES;
+    /* 'i' must point to the first char of cookie-name */
+    name_start = i;
+    /* Find the end of the cookie-name */
+    do
+    {
+      const char l = str[i];
+      if (('=' == l) || (' ' == l) || ('\t' == l) || ('"' == l) || (',' == l) ||
+          (';' == l) || (0 == l))
+        break;
+    } while (str_len > ++i);
+    name_len = i - name_start;
+    /* Skip any whitespaces */
+    while (str_len > i && (' ' == str[i] || '\t' == str[i]))
+    {
+      if (! wsp_around_eq)
+        return MHD_PARSE_COOKIE_MALFORMED;
+      non_strict = true;
+      i++;
+    }
+    if ((str_len == i) || ('=' != str[i]) || (0 == name_len))
+      return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie name */
+    /* 'i' must point to the '=' char */
+    mhd_assert ('=' == str[i]);
+    i++;
+    /* Skip any whitespaces */
+    while (str_len > i && (' ' == str[i] || '\t' == str[i]))
+    {
+      if (! wsp_around_eq)
+        return MHD_PARSE_COOKIE_MALFORMED;
+      non_strict = true;
+      i++;
+    }
+    /* 'i' must point to the first char of cookie-value */
+    if (str_len == i)
+    {
+      value_start = 0;
+      value_len = 0;
+#ifdef _DEBUG
+      val_quoted = false; /* This assignment used in assert */
+#endif
+    }
+    else
+    {
+      bool valid_cookie;
+      val_quoted = ('"' == str[i]);
+      if (val_quoted)
+        i++;
+      value_start = i;
+      /* Find the end of the cookie-value */
+      while (str_len > i)
+      {
+        const char l = str[i];
+        if ((';' == l) || ('"' == l) || (',' == l) || (';' == l) ||
+            ('\\' == l) || (0 == l))
+          break;
+        if ((' ' == l) || ('\t' == l))
+        {
+          if (! val_quoted)
+            break;
+          if (! wsp_in_quoted)
+            return MHD_PARSE_COOKIE_MALFORMED;
+          non_strict = true;
+        }
+        i++;
+      }
+      value_len = i - value_start;
+      if (val_quoted)
+      {
+        if ((str_len == i) || ('"' != str[i]))
+          return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie value, no closing quote */
+        i++;
+      }
+      /* Skip any whitespaces */
+      if ((str_len > i) && ((' ' == str[i]) || ('\t' == str[i])))
+      {
+        do
+        {
+          i++;
+        } while (str_len > i && (' ' == str[i] || '\t' == str[i]));
+        /* Whitespace at the end? */
+        if (str_len > i)
+        {
+          if (! allow_wsp_empty)
+            return MHD_PARSE_COOKIE_MALFORMED;
+          non_strict = true;
+        }
+      }
+      if (str_len == i)
+        valid_cookie = true;
+      else if (';' == str[i])
+        valid_cookie = true;
+      else
+        valid_cookie = false;
+
+      if (! valid_cookie)
+        return MHD_PARSE_COOKIE_MALFORMED; /* Garbage at the end of the cookie value */
+    }
+    mhd_assert (0 != name_len);
+    str[name_start + name_len] = 0; /* Zero-terminate the name */
+    if (0 != value_len)
+    {
+      mhd_assert (value_start + value_len <= str_len);
+      str[value_start + value_len] = 0; /* Zero-terminate the value */
+      if (MHD_NO ==
+          MHD_set_connection_value_n_nocheck_ (connection,
+                                               MHD_COOKIE_KIND,
+                                               str + name_start,
+                                               name_len,
+                                               str + value_start,
+                                               value_len))
+        return MHD_PARSE_COOKIE_NO_MEMORY;
+    }
+    else
+    {
+      if (MHD_NO ==
+          MHD_set_connection_value_n_nocheck_ (connection,
+                                               MHD_COOKIE_KIND,
+                                               str + name_start,
+                                               name_len,
+                                               "",
+                                               0))
+        return MHD_PARSE_COOKIE_NO_MEMORY;
+    }
+    if (str_len > i)
+    {
+      mhd_assert (0 == str[i] || ';' == str[i]);
+      mhd_assert (! val_quoted || ';' == str[i]);
+      mhd_assert (';' != str[i] || val_quoted || non_strict || 0 == value_len);
+      i++;
+      if (str_len == i)
+      { /* No next cookie after semicolon */
+        if (! allow_wsp_empty)
+          return MHD_PARSE_COOKIE_MALFORMED;
+        non_strict = true;
+      }
+      else if (' ' != str[i])
+      {/* No space after semicolon */
+        if (('\t' == str[i]) && tab_as_sp)
+          i++;
+        else if (! allow_no_space)
+          return MHD_PARSE_COOKIE_MALFORMED;
+        non_strict = true;
+      }
+      else
+      {
+        i++;
+        if (str_len == i)
+        {
+          if (! allow_wsp_empty)
+            return MHD_PARSE_COOKIE_MALFORMED;
+          non_strict = true;
+        }
+      }
+    }
+  }
+  return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK;
 }
 
 
 /**
- * Parse the cookie header (see RFC 2109).
+ * Parse the cookie header (see RFC 6265).
  *
- * @return #MHD_YES for success, #MHD_NO for failure (malformed, out of memory)
+ * @param connection connection to parse header of
+ * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise
  */
-static int
+static enum _MHD_ParseCookie
 parse_cookie_header (struct MHD_Connection *connection)
 {
   const char *hdr;
+  size_t hdr_len;
   char *cpy;
-  char *pos;
-  char *sce;
-  char *semicolon;
-  char *equals;
-  char *ekill;
-  char old;
-  int quotes;
+  size_t i;
+  enum _MHD_ParseCookie parse_res;
+  struct MHD_HTTP_Req_Header *const saved_tail =
+    connection->rq.headers_received_tail;
+  const bool allow_partially_correct_cookie =
+    (1 >= connection->daemon->client_discipline);
 
-  hdr = MHD_lookup_connection_value (connection,
-				     MHD_HEADER_KIND,
-				     MHD_HTTP_HEADER_COOKIE);
-  if (NULL == hdr)
-    return MHD_YES;
-  cpy = MHD_pool_allocate (connection->pool, strlen (hdr) + 1, MHD_YES);
+  if (MHD_NO ==
+      MHD_lookup_connection_value_n (connection,
+                                     MHD_HEADER_KIND,
+                                     MHD_HTTP_HEADER_COOKIE,
+                                     MHD_STATICSTR_LEN_ (
+                                       MHD_HTTP_HEADER_COOKIE),
+                                     &hdr,
+                                     &hdr_len))
+    return MHD_PARSE_COOKIE_OK;
+  if (0 == hdr_len)
+    return MHD_PARSE_COOKIE_OK;
+
+  cpy = MHD_connection_alloc_memory_ (connection,
+                                      hdr_len + 1);
   if (NULL == cpy)
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-                "Not enough memory to parse cookies!\n");
-#endif
-      transmit_error_response (connection, MHD_HTTP_REQUEST_ENTITY_TOO_LARGE,
-                               REQUEST_TOO_BIG);
-      return MHD_NO;
-    }
-  memcpy (cpy, hdr, strlen (hdr) + 1);
-  pos = cpy;
-  while (NULL != pos)
-    {
-      while (' ' == *pos)
-        pos++;                  /* skip spaces */
+    parse_res = MHD_PARSE_COOKIE_NO_MEMORY;
+  else
+  {
+    memcpy (cpy,
+            hdr,
+            hdr_len);
+    cpy[hdr_len] = '\0';
 
-      sce = pos;
-      while (((*sce) != '\0') &&
-             ((*sce) != ',') && ((*sce) != ';') && ((*sce) != '='))
-        sce++;
-      /* remove tailing whitespace (if any) from key */
-      ekill = sce - 1;
-      while ((*ekill == ' ') && (ekill >= pos))
-        *(ekill--) = '\0';
-      old = *sce;
-      *sce = '\0';
-      if (old != '=')
-        {
-          /* value part omitted, use empty string... */
-          if (MHD_NO ==
-              connection_add_header (connection, pos, "", MHD_COOKIE_KIND))
-            return MHD_NO;
-          if (old == '\0')
-            break;
-          pos = sce + 1;
-          continue;
-        }
-      equals = sce + 1;
-      quotes = 0;
-      semicolon = equals;
-      while ( ('\0' != semicolon[0]) &&
-              ( (0 != quotes) ||
-                ( (';' != semicolon[0]) &&
-                  (',' != semicolon[0]) ) ) )
-        {
-          if ('"' == semicolon[0])
-            quotes = (quotes + 1) & 1;
-          semicolon++;
-        }
-      if ('\0' == semicolon[0])
-        semicolon = NULL;
-      if (NULL != semicolon)
-        {
-          semicolon[0] = '\0';
-          semicolon++;
-        }
-      /* remove quotes */
-      if ( ('"' == equals[0]) &&
-           ('"' == equals[strlen (equals) - 1]) )
-        {
-          equals[strlen (equals) - 1] = '\0';
-          equals++;
-        }
-      if (MHD_NO == connection_add_header (connection,
-                                           pos, equals, MHD_COOKIE_KIND))
-        return MHD_NO;
-      pos = semicolon;
+    i = 0;
+    /* Skip all initial whitespaces */
+    while (i < hdr_len && (' ' == cpy[i] || '\t' == cpy[i]))
+      i++;
+
+    parse_res = parse_cookies_string (cpy + i, hdr_len - i, connection);
+  }
+
+  switch (parse_res)
+  {
+  case MHD_PARSE_COOKIE_OK:
+    break;
+  case MHD_PARSE_COOKIE_OK_LAX:
+#ifdef HAVE_MESSAGES
+    if (saved_tail != connection->rq.headers_received_tail)
+      MHD_DLOG (connection->daemon,
+                _ ("The Cookie header has been parsed, but it is not fully "
+                   "compliant with the standard.\n"));
+#endif /* HAVE_MESSAGES */
+    break;
+  case MHD_PARSE_COOKIE_MALFORMED:
+#ifdef HAVE_MESSAGES
+    if (saved_tail != connection->rq.headers_received_tail)
+    {
+      if (allow_partially_correct_cookie)
+        MHD_DLOG (connection->daemon,
+                  _ ("The Cookie header has been only partially parsed as it "
+                     "contains malformed data.\n"));
+      else
+      {
+        /* Remove extracted values from partially broken cookie */
+        /* Memory remains allocated until the end of the request processing */
+        connection->rq.headers_received_tail = saved_tail;
+        saved_tail->next = NULL;
+        MHD_DLOG (connection->daemon,
+                  _ ("The Cookie header has been ignored as it contains "
+                     "malformed data.\n"));
+      }
     }
+    else
+      MHD_DLOG (connection->daemon,
+                _ ("The Cookie header has malformed data.\n"));
+#endif /* HAVE_MESSAGES */
+    break;
+  case MHD_PARSE_COOKIE_NO_MEMORY:
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Not enough memory in the connection pool to "
+                 "parse client cookies!\n"));
+#endif /* HAVE_MESSAGES */
+    break;
+  default:
+    mhd_assert (0);
+    break;
+  }
+#ifndef HAVE_MESSAGES
+  (void) saved_tail; /* Mute compiler warning */
+#endif /* ! HAVE_MESSAGES */
+
+  return parse_res;
+}
+
+
+#endif /* COOKIE_SUPPORT */
+
+
+/**
+ * The valid length of any HTTP version string
+ */
+#define HTTP_VER_LEN (MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1))
+
+/**
+ * Detect HTTP version, send error response if version is not supported
+ *
+ * @param connection the connection
+ * @param http_string the pointer to HTTP version string
+ * @param len the length of @a http_string in bytes
+ * @return #MHD_YES if HTTP version is correct and supported,
+ *         #MHD_NO if HTTP version is not correct or unsupported.
+ */
+static enum MHD_Result
+parse_http_version (struct MHD_Connection *connection,
+                    const char *http_string,
+                    size_t len)
+{
+  const char *const h = http_string; /**< short alias */
+  mhd_assert (NULL != http_string);
+
+  /* String must start with 'HTTP/d.d', case-sensetive match.
+   * See https://www.rfc-editor.org/rfc/rfc9112#name-http-version */
+  if ((HTTP_VER_LEN != len) ||
+      ('H' != h[0]) || ('T' != h[1]) || ('T' != h[2]) || ('P' != h[3]) ||
+      ('/' != h[4])
+      || ('.' != h[6]) ||
+      (('0' > h[5]) || ('9' < h[5])) ||
+      (('0' > h[7]) || ('9' < h[7])))
+  {
+    connection->rq.http_ver = MHD_HTTP_VER_INVALID;
+    transmit_error_response_static (connection,
+                                    MHD_HTTP_BAD_REQUEST,
+                                    REQUEST_MALFORMED);
+    return MHD_NO;
+  }
+  if (1 == h[5] - '0')
+  {
+    /* HTTP/1.x */
+    if (1 == h[7] - '0')
+      connection->rq.http_ver = MHD_HTTP_VER_1_1;
+    else if (0 == h[7] - '0')
+      connection->rq.http_ver = MHD_HTTP_VER_1_0;
+    else
+      connection->rq.http_ver = MHD_HTTP_VER_1_2__1_9;
+
+    return MHD_YES;
+  }
+
+  if (0 == h[5] - '0')
+  {
+    /* Too old major version */
+    connection->rq.http_ver = MHD_HTTP_VER_TOO_OLD;
+    transmit_error_response_static (connection,
+                                    MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED,
+                                    REQ_HTTP_VER_IS_TOO_OLD);
+    return MHD_NO;
+  }
+
+  connection->rq.http_ver = MHD_HTTP_VER_FUTURE;
+  transmit_error_response_static (connection,
+                                  MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED,
+                                  REQ_HTTP_VER_IS_NOT_SUPPORTED);
+  return MHD_NO;
+}
+
+
+/**
+ * Detect standard HTTP request method
+ *
+ * @param connection the connection
+ * @param method the pointer to HTTP request method string
+ * @param len the length of @a method in bytes
+ * @return #MHD_YES if HTTP method is valid string,
+ *         #MHD_NO if HTTP method string is not valid.
+ */
+static enum MHD_Result
+parse_http_std_method (struct MHD_Connection *connection,
+                       const char *method,
+                       size_t len)
+{
+  const char *const m = method; /**< short alias */
+  mhd_assert (NULL != m);
+
+  if (0 == len)
+    return MHD_NO;
+
+  if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET) == len) &&
+      (0 == memcmp (m, MHD_HTTP_METHOD_GET, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_GET;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_HEAD) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_HEAD, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_HEAD;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_POST) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_POST, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_POST;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_PUT) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_PUT, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_PUT;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_DELETE) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_DELETE, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_DELETE;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_CONNECT) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_CONNECT, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_CONNECT;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_OPTIONS) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_OPTIONS, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_OPTIONS;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_TRACE) == len) &&
+           (0 == memcmp (m, MHD_HTTP_METHOD_TRACE, len)))
+    connection->rq.http_mthd = MHD_HTTP_MTHD_TRACE;
+  else
+    connection->rq.http_mthd = MHD_HTTP_MTHD_OTHER;
+
+  /* Any method string with non-zero length is valid */
   return MHD_YES;
 }
 
@@ -1384,50 +3276,130 @@
  * Parse the first line of the HTTP HEADER.
  *
  * @param connection the connection (updated)
- * @param line the first line
+ * @param line the first line, not 0-terminated
+ * @param line_len length of the first @a line
  * @return #MHD_YES if the line is ok, #MHD_NO if it is malformed
  */
-static int
+static enum MHD_Result
 parse_initial_message_line (struct MHD_Connection *connection,
-                            char *line)
+                            char *line,
+                            size_t line_len)
 {
+  struct MHD_Daemon *daemon = connection->daemon;
+  const char *curi;
   char *uri;
   char *http_version;
   char *args;
 
-  if (NULL == (uri = strchr (line, ' ')))
+  if (NULL == (uri = memchr (line,
+                             ' ',
+                             line_len)))
     return MHD_NO;              /* serious error */
   uri[0] = '\0';
-  connection->method = line;
+  connection->rq.method = line;
+  if (MHD_NO == parse_http_std_method (connection, connection->rq.method,
+                                       (size_t) (uri - line)))
+    return MHD_NO;
   uri++;
-  while (' ' == uri[0])
+  /* Skip any spaces. Not required by standard but allow
+     to be more tolerant. */
+  /* TODO: do not skip them in standard mode */
+  while ( (' ' == uri[0]) &&
+          ( (size_t) (uri - line) < line_len) )
     uri++;
-  http_version = strchr (uri, ' ');
-  if (NULL != http_version)
-    {
-      http_version[0] = '\0';
-      http_version++;
-    }
-  if (NULL != connection->daemon->uri_log_callback)
-    connection->client_context
-      = connection->daemon->uri_log_callback (connection->daemon->uri_log_callback_cls,
-					      uri,
-					      connection);
-  args = strchr (uri, '?');
-  if (NULL != args)
-    {
-      args[0] = '\0';
-      args++;
-      parse_arguments (MHD_GET_ARGUMENT_KIND, connection, args);
-    }
-  connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-					 connection,
-					 uri);
-  connection->url = uri;
-  if (NULL == http_version)
-    connection->version = "";
+  if ((size_t) (uri - line) == line_len)
+  {
+    /* No URI and no http version given */
+    curi = "";
+    uri = NULL;
+    connection->rq.version = "";
+    args = NULL;
+    if (MHD_NO == parse_http_version (connection, connection->rq.version, 0))
+      return MHD_NO;
+  }
   else
-    connection->version = http_version;
+  {
+    size_t uri_len;
+    curi = uri;
+    /* Search from back to accept malformed URI with space */
+    http_version = line + line_len - 1;
+    /* Skip any trailing spaces */
+    /* TODO: do not skip them in standard mode */
+    while ( (' ' == http_version[0]) &&
+            (http_version > uri) )
+      http_version--;
+    /* Find first space in reverse direction */
+    while ( (' ' != http_version[0]) &&
+            (http_version > uri) )
+      http_version--;
+    if (http_version > uri)
+    {
+      /* http_version points to character before HTTP version string */
+      http_version[0] = '\0';
+      connection->rq.version = http_version + 1;
+      if (MHD_NO == parse_http_version (connection, connection->rq.version,
+                                        line_len
+                                        - (size_t)
+                                        (connection->rq.version - line)))
+        return MHD_NO;
+      uri_len = (size_t) (http_version - uri);
+    }
+    else
+    {
+      connection->rq.version = "";
+      if (MHD_NO == parse_http_version (connection, connection->rq.version, 0))
+        return MHD_NO;
+      uri_len = line_len - (size_t) (uri - line);
+    }
+    /* check for spaces in URI if we are "strict" */
+    if ( (-2 < daemon->client_discipline) &&
+         (NULL != memchr (uri,
+                          ' ',
+                          uri_len)) )
+    {
+      /* space exists in URI and we are supposed to be strict, reject */
+      return MHD_NO;
+    }
+
+    args = memchr (uri,
+                   '?',
+                   uri_len);
+  }
+
+  /* log callback before we modify URI *or* args */
+  if (NULL != daemon->uri_log_callback)
+  {
+    connection->rq.client_aware = true;
+    connection->rq.client_context
+      = daemon->uri_log_callback (daemon->uri_log_callback_cls,
+                                  uri,
+                                  connection);
+  }
+
+  if (NULL != args)
+  {
+    args[0] = '\0';
+    args++;
+    /* note that this call clobbers 'args' */
+    MHD_parse_arguments_ (connection,
+                          MHD_GET_ARGUMENT_KIND,
+                          args,
+                          &connection_add_header,
+                          connection);
+  }
+
+  /* unescape URI *after* searching for arguments and log callback */
+  if (NULL != uri)
+  {
+    connection->rq.url_len =
+      daemon->unescape_callback (daemon->unescape_callback_cls,
+                                 connection,
+                                 uri);
+  }
+  else
+    connection->rq.url_len = 0;
+
+  connection->rq.url = curi;
   return MHD_YES;
 }
 
@@ -1442,30 +3414,32 @@
 static void
 call_connection_handler (struct MHD_Connection *connection)
 {
+  struct MHD_Daemon *daemon = connection->daemon;
   size_t processed;
 
-  if (NULL != connection->response)
+  if (NULL != connection->rp.response)
     return;                     /* already queued a response */
   processed = 0;
-  connection->client_aware = MHD_YES;
+  connection->rq.client_aware = true;
   if (MHD_NO ==
-      connection->daemon->default_handler (connection->daemon-> default_handler_cls,
-					   connection,
-                                           connection->url,
-					   connection->method,
-					   connection->version,
-					   NULL, &processed,
-					   &connection->client_context))
-    {
-      /* serious internal error, close connection */
-      CONNECTION_CLOSE_ERROR (connection,
-			      "Internal application error, closing connection.\n");
-      return;
-    }
+      daemon->default_handler (daemon->default_handler_cls,
+                               connection,
+                               connection->rq.url,
+                               connection->rq.method,
+                               connection->rq.version,
+                               NULL,
+                               &processed,
+                               &connection->rq.client_context))
+  {
+    /* serious internal error, close connection */
+    CONNECTION_CLOSE_ERROR (connection,
+                            _ ("Application reported internal error, " \
+                               "closing connection."));
+    return;
+  }
 }
 
 
-
 /**
  * Call the handler of the application for this
  * connection.  Handles chunking of the upload
@@ -1476,262 +3450,284 @@
 static void
 process_request_body (struct MHD_Connection *connection)
 {
-  size_t processed;
+  struct MHD_Daemon *daemon = connection->daemon;
   size_t available;
-  size_t used;
-  size_t i;
-  int instant_retry;
-  int malformed;
+  bool instant_retry;
   char *buffer_head;
-  char *end;
 
-  if (NULL != connection->response)
-    return;                     /* already queued a response */
+  connection->rq.some_payload_processed = false;
+
+  if (NULL != connection->rp.response)
+  {
+    /* TODO: discard all read buffer as early response
+     * means that connection have to be closed. */
+    /* already queued a response, discard remaining upload
+       (but not more, there might be another request after it) */
+    size_t purge;
+
+    purge = (size_t) MHD_MIN (connection->rq.remaining_upload_size,
+                              (uint64_t) connection->read_buffer_offset);
+    connection->rq.remaining_upload_size -= purge;
+    if (connection->read_buffer_offset > purge)
+      memmove (connection->read_buffer,
+               &connection->read_buffer[purge],
+               connection->read_buffer_offset - purge);
+    connection->read_buffer_offset -= purge;
+    return;
+  }
 
   buffer_head = connection->read_buffer;
   available = connection->read_buffer_offset;
   do
+  {
+    size_t to_be_processed;
+    size_t left_unprocessed;
+    size_t processed_size;
+
+    instant_retry = false;
+    if (connection->rq.have_chunked_upload)
     {
-      instant_retry = MHD_NO;
-      if ( (MHD_YES == connection->have_chunked_upload) &&
-           (MHD_SIZE_UNKNOWN == connection->remaining_upload_size) )
+      mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size);
+      if ( (connection->rq.current_chunk_offset ==
+            connection->rq.current_chunk_size) &&
+           (0 != connection->rq.current_chunk_size) )
+      {
+        size_t i;
+        mhd_assert (0 != available);
+        /* skip new line at the *end* of a chunk */
+        i = 0;
+        if ( (2 <= available) &&
+             ('\r' == buffer_head[0]) &&
+             ('\n' == buffer_head[1]) )
+          i += 2;                        /* skip CRLF */
+        else if ('\n' == buffer_head[0]) /* TODO: Add MHD option to disallow */
+          i++;                           /* skip bare LF */
+        else if (2 > available)
+          break;                         /* need more upload data */
+        if (0 == i)
         {
-          if ( (connection->current_chunk_offset == connection->current_chunk_size) &&
-               (0 != connection->current_chunk_offset) &&
-               (available >= 2) )
-            {
-              /* skip new line at the *end* of a chunk */
-              i = 0;
-              if ((buffer_head[i] == '\r') || (buffer_head[i] == '\n'))
-                i++;            /* skip 1st part of line feed */
-              if ((buffer_head[i] == '\r') || (buffer_head[i] == '\n'))
-                i++;            /* skip 2nd part of line feed */
-              if (i == 0)
-                {
-                  /* malformed encoding */
-                  CONNECTION_CLOSE_ERROR (connection,
-					  "Received malformed HTTP request (bad chunked encoding), closing connection.\n");
-                  return;
-                }
-              available -= i;
-              buffer_head += i;
-              connection->current_chunk_offset = 0;
-              connection->current_chunk_size = 0;
-            }
-          if (connection->current_chunk_offset <
-              connection->current_chunk_size)
-            {
-              /* we are in the middle of a chunk, give
-                 as much as possible to the client (without
-                 crossing chunk boundaries) */
-              processed =
-                connection->current_chunk_size -
-                connection->current_chunk_offset;
-              if (processed > available)
-                processed = available;
-              if (available > processed)
-                instant_retry = MHD_YES;
-            }
-          else
-            {
-              /* we need to read chunk boundaries */
-              i = 0;
-              while (i < available)
-                {
-                  if ((buffer_head[i] == '\r') || (buffer_head[i] == '\n'))
-                    break;
-                  i++;
-                  if (i >= 6)
-                    break;
-                }
-              /* take '\n' into account; if '\n'
-                 is the unavailable character, we
-                 will need to wait until we have it
-                 before going further */
-              if ((i + 1 >= available) &&
-                  !((i == 1) && (available == 2) && (buffer_head[0] == '0')))
-                break;          /* need more data... */
-              malformed = (i >= 6);
-              if (!malformed)
-                {
-                  buffer_head[i] = '\0';
-		  connection->current_chunk_size = strtoul (buffer_head, &end, 16);
-                  malformed = ('\0' != *end);
-                }
-              if (malformed)
-                {
-                  /* malformed encoding */
-                  CONNECTION_CLOSE_ERROR (connection,
-					  "Received malformed HTTP request (bad chunked encoding), closing connection.\n");
-                  return;
-                }
-              i++;
-              if ((i < available) &&
-                  ((buffer_head[i] == '\r') || (buffer_head[i] == '\n')))
-                i++;            /* skip 2nd part of line feed */
-
-              buffer_head += i;
-              available -= i;
-              connection->current_chunk_offset = 0;
-
-              if (available > 0)
-                instant_retry = MHD_YES;
-              if (0 == connection->current_chunk_size)
-                {
-                  connection->remaining_upload_size = 0;
-                  break;
-                }
-              continue;
-            }
-        }
-      else
-        {
-          /* no chunked encoding, give all to the client */
-          if ( (0 != connection->remaining_upload_size) &&
-	       (MHD_SIZE_UNKNOWN != connection->remaining_upload_size) &&
-	       (connection->remaining_upload_size < available) )
-	    {
-              processed = connection->remaining_upload_size;
-	    }
-          else
-	    {
-              /**
-               * 1. no chunked encoding, give all to the client
-               * 2. client may send large chunked data, but only a smaller part is available at one time.
-               */
-              processed = available;
-	    }
-        }
-      used = processed;
-      connection->client_aware = MHD_YES;
-      if (MHD_NO ==
-          connection->daemon->default_handler (connection->daemon->default_handler_cls,
-                                               connection,
-                                               connection->url,
-                                               connection->method,
-                                               connection->version,
-                                               buffer_head,
-                                               &processed,
-                                               &connection->client_context))
-        {
-          /* serious internal error, close connection */
-	  CONNECTION_CLOSE_ERROR (connection,
-				  "Internal application error, closing connection.\n");
+          /* malformed encoding */
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_BAD_REQUEST,
+                                          REQUEST_CHUNKED_MALFORMED);
           return;
         }
-      if (processed > used)
-        mhd_panic (mhd_panic_cls, __FILE__, __LINE__
-#if HAVE_MESSAGES
-		   , "API violation"
-#else
-		   , NULL
-#endif
-		   );
-      if (0 != processed)
-        instant_retry = MHD_NO; /* client did not process everything */
-      used -= processed;
-      if (connection->have_chunked_upload == MHD_YES)
-        connection->current_chunk_offset += used;
-      /* dh left "processed" bytes in buffer for next time... */
-      buffer_head += used;
-      available -= used;
-      if (connection->remaining_upload_size != MHD_SIZE_UNKNOWN)
-        connection->remaining_upload_size -= used;
-    }
-  while (MHD_YES == instant_retry);
-  if (available > 0)
-    memmove (connection->read_buffer, buffer_head, available);
-  connection->read_buffer_offset = available;
-}
+        available -= i;
+        buffer_head += i;
+        connection->rq.current_chunk_offset = 0;
+        connection->rq.current_chunk_size = 0;
+        if (0 == available)
+          break;
+      }
+      if (0 != connection->rq.current_chunk_size)
+      {
+        uint64_t cur_chunk_left;
+        mhd_assert (connection->rq.current_chunk_offset < \
+                    connection->rq.current_chunk_size);
+        /* we are in the middle of a chunk, give
+           as much as possible to the client (without
+           crossing chunk boundaries) */
+        cur_chunk_left
+          = connection->rq.current_chunk_size
+            - connection->rq.current_chunk_offset;
+        if (cur_chunk_left > available)
+          to_be_processed = available;
+        else
+        {         /* cur_chunk_left <= (size_t)available */
+          to_be_processed = (size_t) cur_chunk_left;
+          if (available > to_be_processed)
+            instant_retry = true;
+        }
+      }
+      else
+      {
+        size_t i;
+        /** The length of the string with the number of the chunk size */
+        size_t chunk_size_len;
+        bool found_chunk_size_str;
+        bool malformed;
 
-
-/**
- * Try reading data from the socket into the
- * read buffer of the connection.
- *
- * @param connection connection we're processing
- * @return #MHD_YES if something changed,
- *         #MHD_NO if we were interrupted or if
- *                no space was available
- */
-static int
-do_read (struct MHD_Connection *connection)
-{
-  int bytes_read;
-
-  if (connection->read_buffer_size == connection->read_buffer_offset)
-    return MHD_NO;
-  bytes_read = connection->recv_cls (connection,
-                                     &connection->read_buffer
-                                     [connection->read_buffer_offset],
-                                     connection->read_buffer_size -
-                                     connection->read_buffer_offset);
-  if (bytes_read < 0)
-    {
-      const int err = MHD_socket_errno_;
-      if ((EINTR == err) || (EAGAIN == err) || (EWOULDBLOCK == err))
-	  return MHD_NO;
-      if (ECONNRESET == err)
+        /* we need to read chunk boundaries */
+        i = 0;
+        found_chunk_size_str = false;
+        chunk_size_len = 0;
+        mhd_assert (0 != available);
+        do
         {
-           CONNECTION_CLOSE_ERROR (connection, NULL);
-	   return MHD_NO;
-	}
-      CONNECTION_CLOSE_ERROR (connection, NULL);
-      return MHD_YES;
+          if ('\n' == buffer_head[i])
+          {
+            if ((0 < i) && ('\r' == buffer_head[i - 1]))
+            { /* CRLF */
+              if (! found_chunk_size_str)
+                chunk_size_len = i - 1;
+            }
+            else
+            { /* bare LF */
+              /* TODO: Add an option to disallow bare LF */
+              if (! found_chunk_size_str)
+                chunk_size_len = i;
+            }
+            found_chunk_size_str = true;
+            break; /* Found the end of the string */
+          }
+          else if (! found_chunk_size_str && (';' == buffer_head[i]))
+          { /* Found chunk extension */
+            chunk_size_len = i;
+            found_chunk_size_str = true;
+          }
+        } while (available > ++i);
+        mhd_assert ((i == available) || found_chunk_size_str);
+        mhd_assert ((0 == chunk_size_len) || found_chunk_size_str);
+        malformed = ((0 == chunk_size_len) && found_chunk_size_str);
+        if (! malformed)
+        {
+          /* Check whether size is valid hexadecimal number
+           * even if end of the string is not found yet. */
+          size_t num_dig;
+          uint64_t chunk_size;
+          mhd_assert (0 < i);
+          if (! found_chunk_size_str)
+          {
+            mhd_assert (i == available);
+            /* Check already available part of the size string for valid
+             * hexadecimal digits. */
+            chunk_size_len = i;
+            if ('\r' == buffer_head[i - 1])
+            {
+              chunk_size_len--;
+              malformed = (0 == chunk_size_len);
+            }
+          }
+          num_dig = MHD_strx_to_uint64_n_ (buffer_head,
+                                           chunk_size_len,
+                                           &chunk_size);
+          malformed = malformed || (chunk_size_len != num_dig);
+
+          if ((available != i) && ! malformed)
+          {
+            /* Found end of the string and the size of the chunk is valid */
+
+            mhd_assert (found_chunk_size_str);
+            /* Start reading payload data of the chunk */
+            connection->rq.current_chunk_offset = 0;
+            connection->rq.current_chunk_size = chunk_size;
+            i++; /* Consume the last checked char */
+            available -= i;
+            buffer_head += i;
+
+            if (0 == connection->rq.current_chunk_size)
+            { /* The final (termination) chunk */
+              connection->rq.remaining_upload_size = 0;
+              break;
+            }
+            if (available > 0)
+              instant_retry = true;
+            continue;
+          }
+
+          if ((0 == num_dig) && (0 != chunk_size_len))
+          { /* Check whether result is invalid due to uint64_t overflow */
+            /* At least one byte is always available
+             * in the input buffer here. */
+            const char d = buffer_head[0]; /**< first digit */
+            if ((('0' <= d) && ('9' >= d)) ||
+                (('A' <= d) && ('F' >= d)) ||
+                (('a' <= d) && ('f' >= d)))
+            { /* The first char is a valid hexadecimal digit */
+              transmit_error_response_static (connection,
+                                              MHD_HTTP_CONTENT_TOO_LARGE,
+                                              REQUEST_CHUNK_TOO_LARGE);
+              return;
+            }
+          }
+        }
+        if (malformed)
+        {
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_BAD_REQUEST,
+                                          REQUEST_CHUNKED_MALFORMED);
+          return;
+        }
+        mhd_assert (available == i);
+        break; /* The end of the string not found, need more upload data */
+      }
     }
-  if (0 == bytes_read)
+    else
     {
-      /* other side closed connection; RFC 2616, section 8.1.4 suggests
-	 we should then shutdown ourselves as well. */
-      connection->read_closed = MHD_YES;
-      MHD_connection_close (connection,
-			    MHD_REQUEST_TERMINATED_CLIENT_ABORT);
-      return MHD_YES;
+      /* no chunked encoding, give all to the client */
+      mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size);
+      mhd_assert (0 != connection->rq.remaining_upload_size);
+      if (connection->rq.remaining_upload_size < available)
+        to_be_processed = (size_t) connection->rq.remaining_upload_size;
+      else
+        to_be_processed = available;
     }
-  connection->read_buffer_offset += bytes_read;
-  return MHD_YES;
-}
-
-
-/**
- * Try writing data to the socket from the
- * write buffer of the connection.
- *
- * @param connection connection we're processing
- * @return #MHD_YES if something changed,
- *         #MHD_NO if we were interrupted
- */
-static int
-do_write (struct MHD_Connection *connection)
-{
-  ssize_t ret;
-  size_t max;
-
-  max = connection->write_buffer_append_offset - connection->write_buffer_send_offset;
-  ret = connection->send_cls (connection,
-                              &connection->write_buffer
-                              [connection->write_buffer_send_offset],
-                              max);
-
-  if (ret < 0)
+    left_unprocessed = to_be_processed;
+    connection->rq.client_aware = true;
+    if (MHD_NO ==
+        daemon->default_handler (daemon->default_handler_cls,
+                                 connection,
+                                 connection->rq.url,
+                                 connection->rq.method,
+                                 connection->rq.version,
+                                 buffer_head,
+                                 &left_unprocessed,
+                                 &connection->rq.client_context))
     {
-      const int err = MHD_socket_errno_;
-      if ((EINTR == err) || (EAGAIN == err) || (EWOULDBLOCK == err))
-        return MHD_NO;
-      CONNECTION_CLOSE_ERROR (connection, NULL);
-      return MHD_YES;
+      /* serious internal error, close connection */
+      CONNECTION_CLOSE_ERROR (connection,
+                              _ ("Application reported internal error, " \
+                                 "closing connection."));
+      return;
     }
-#if DEBUG_SEND_DATA
-  fprintf (stderr,
-           "Sent response: `%.*s'\n",
-           ret,
-           &connection->write_buffer[connection->write_buffer_send_offset]);
-#endif
-  /* only increment if this wasn't a "sendfile" transmission without
-     buffer involvement! */
-  if (0 != max)
-    connection->write_buffer_send_offset += ret;
-  return MHD_YES;
+    if (left_unprocessed > to_be_processed)
+      MHD_PANIC (_ ("libmicrohttpd API violation.\n"));
+
+    if (left_unprocessed != to_be_processed)
+      /* Something was processed by the application. */
+      connection->rq.some_payload_processed = true;
+    if (0 != left_unprocessed)
+    {
+      instant_retry = false; /* client did not process everything */
+#ifdef HAVE_MESSAGES
+      if ((left_unprocessed == to_be_processed) &&
+          (! connection->suspended))
+      {
+        /* client did not process any upload data, complain if
+           the setup was incorrect, which may prevent us from
+           handling the rest of the request */
+        if (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD))
+          MHD_DLOG (daemon,
+                    _ ("WARNING: Access Handler Callback has not processed " \
+                       "any upload data and connection is not suspended. " \
+                       "This may result in hung connection.\n"));
+      }
+#endif /* HAVE_MESSAGES */
+    }
+    processed_size = to_be_processed - left_unprocessed;
+    if (connection->rq.have_chunked_upload)
+      connection->rq.current_chunk_offset += processed_size;
+    /* dh left "processed" bytes in buffer for next time... */
+    buffer_head += processed_size;
+    available -= processed_size;
+    if (! connection->rq.have_chunked_upload)
+    {
+      mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size);
+      connection->rq.remaining_upload_size -= processed_size;
+    }
+    else
+      mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size);
+  } while (instant_retry);
+  /* TODO: zero out reused memory region */
+  if ( (available > 0) &&
+       (buffer_head != connection->read_buffer) )
+    memmove (connection->read_buffer,
+             buffer_head,
+             available);
+  else
+    mhd_assert ((0 == available) || \
+                (connection->read_buffer_offset == available));
+  connection->read_buffer_offset = available;
 }
 
 
@@ -1743,21 +3739,18 @@
  * @param next_state the next state to transition to
  * @return #MHD_NO if we are not done, #MHD_YES if we are
  */
-static int
+static enum MHD_Result
 check_write_done (struct MHD_Connection *connection,
                   enum MHD_CONNECTION_STATE next_state)
 {
-  if (connection->write_buffer_append_offset !=
-      connection->write_buffer_send_offset)
+  if ( (connection->write_buffer_append_offset !=
+        connection->write_buffer_send_offset)
+       /* || data_in_tls_buffers == true  */
+       )
     return MHD_NO;
   connection->write_buffer_append_offset = 0;
   connection->write_buffer_send_offset = 0;
   connection->state = next_state;
-  MHD_pool_reallocate (connection->pool,
-		       connection->write_buffer,
-                       connection->write_buffer_size, 0);
-  connection->write_buffer = NULL;
-  connection->write_buffer_size = 0;
   return MHD_YES;
 }
 
@@ -1771,32 +3764,49 @@
  * @param line line from the header to process
  * @return #MHD_YES on success, #MHD_NO on error (malformed @a line)
  */
-static int
-process_header_line (struct MHD_Connection *connection, char *line)
+static enum MHD_Result
+process_header_line (struct MHD_Connection *connection,
+                     char *line)
 {
   char *colon;
 
   /* line should be normal header line, find colon */
   colon = strchr (line, ':');
   if (NULL == colon)
-    {
-      /* error in header line, die hard */
-      CONNECTION_CLOSE_ERROR (connection,
-			      "Received malformed line (no colon), closing connection.\n");
+  {
+    /* error in header line, die hard */
+    return MHD_NO;
+  }
+  if (-3 < connection->daemon->client_discipline)
+  {
+    /* check for whitespace before colon, which is not allowed
+ by RFC 7230 section 3.2.4; we count space ' ' and
+ tab '\t', but not '\r\n' as those would have ended the line. */
+    const char *white;
+
+    white = strchr (line, ' ');
+    if ( (NULL != white) &&
+         (white < colon) )
       return MHD_NO;
-    }
+    white = strchr (line, '\t');
+    if ( (NULL != white) &&
+         (white < colon) )
+      return MHD_NO;
+  }
   /* zero-terminate header */
   colon[0] = '\0';
   colon++;                      /* advance to value */
-  while ((colon[0] != '\0') && ((colon[0] == ' ') || (colon[0] == '\t')))
+  while ( ('\0' != colon[0]) &&
+          ( (' ' == colon[0]) ||
+            ('\t' == colon[0]) ) )
     colon++;
   /* we do the actual adding of the connection
      header at the beginning of the while
      loop since we need to be able to inspect
      the *next* header line (in case it starts
      with a space...) */
-  connection->last = line;
-  connection->colon = colon;
+  connection->rq.last = line;
+  connection->rq.colon = colon;
   return MHD_YES;
 }
 
@@ -1811,68 +3821,80 @@
  *        of the given kind
  * @return #MHD_YES if the line was processed successfully
  */
-static int
+static enum MHD_Result
 process_broken_line (struct MHD_Connection *connection,
-                     char *line, enum MHD_ValueKind kind)
+                     char *line,
+                     enum MHD_ValueKind kind)
 {
   char *last;
   char *tmp;
   size_t last_len;
   size_t tmp_len;
 
-  last = connection->last;
-  if ((line[0] == ' ') || (line[0] == '\t'))
+  last = connection->rq.last;
+  if ( (' ' == line[0]) ||
+       ('\t' == line[0]) )
+  {
+    /* value was continued on the next line, see
+       http://www.jmarshall.com/easy/http/ */
+    last_len = strlen (last);
+    /* skip whitespace at start of 2nd line */
+    tmp = line;
+    while ( (' ' == tmp[0]) ||
+            ('\t' == tmp[0]) )
+      tmp++;
+    tmp_len = strlen (tmp);
+    /* FIXME: we might be able to do this better (faster!), as most
+       likely 'last' and 'line' should already be adjacent in
+       memory; however, doing this right gets tricky if we have a
+       value continued over multiple lines (in which case we need to
+       record how often we have done this so we can check for
+       adjacency); also, in the case where these are not adjacent
+       (not sure how it can happen!), we would want to allocate from
+       the end of the pool, so as to not destroy the read-buffer's
+       ability to grow nicely. */
+    last = MHD_pool_reallocate (connection->pool,
+                                last,
+                                last_len + 1,
+                                last_len + tmp_len + 1);
+    if (NULL == last)
     {
-      /* value was continued on the next line, see
-         http://www.jmarshall.com/easy/http/ */
-      last_len = strlen (last);
-      /* skip whitespace at start of 2nd line */
-      tmp = line;
-      while ((tmp[0] == ' ') || (tmp[0] == '\t'))
-        tmp++;
-      tmp_len = strlen (tmp);
-      /* FIXME: we might be able to do this better (faster!), as most
-	 likely 'last' and 'line' should already be adjacent in
-	 memory; however, doing this right gets tricky if we have a
-	 value continued over multiple lines (in which case we need to
-	 record how often we have done this so we can check for
-	 adjaency); also, in the case where these are not adjacent
-	 (not sure how it can happen!), we would want to allocate from
-	 the end of the pool, so as to not destroy the read-buffer's
-	 ability to grow nicely. */
-      last = MHD_pool_reallocate (connection->pool,
-                                  last,
-                                  last_len + 1,
-                                  last_len + tmp_len + 1);
-      if (NULL == last)
-        {
-          transmit_error_response (connection,
-                                   MHD_HTTP_REQUEST_ENTITY_TOO_LARGE,
-                                   REQUEST_TOO_BIG);
-          return MHD_NO;
-        }
-      memcpy (&last[last_len], tmp, tmp_len + 1);
-      connection->last = last;
-      return MHD_YES;           /* possibly more than 2 lines... */
-    }
-  EXTRA_CHECK ((NULL != last) && (NULL != connection->colon));
-  if ((MHD_NO == connection_add_header (connection,
-                                        last, connection->colon, kind)))
-    {
-      transmit_error_response (connection, MHD_HTTP_REQUEST_ENTITY_TOO_LARGE,
-                               REQUEST_TOO_BIG);
+      transmit_error_response_static (connection,
+                                      MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                                      REQUEST_TOO_BIG);
       return MHD_NO;
     }
+    memcpy (&last[last_len],
+            tmp,
+            tmp_len + 1);
+    connection->rq.last = last;
+    return MHD_YES;             /* possibly more than 2 lines... */
+  }
+  mhd_assert ( (NULL != last) &&
+               (NULL != connection->rq.colon) );
+  if (MHD_NO ==
+      connection_add_header (connection,
+                             last,
+                             strlen (last),
+                             connection->rq.colon,
+                             strlen (connection->rq.colon),
+                             kind))
+  {
+    /* Error has been queued by connection_add_header() */
+    return MHD_NO;
+  }
   /* we still have the current line to deal with... */
-  if (0 != strlen (line))
+  if (0 != line[0])
+  {
+    if (MHD_NO == process_header_line (connection,
+                                       line))
     {
-      if (MHD_NO == process_header_line (connection, line))
-        {
-          transmit_error_response (connection,
-                                   MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED);
-          return MHD_NO;
-        }
+      transmit_error_response_static (connection,
+                                      MHD_HTTP_BAD_REQUEST,
+                                      REQUEST_MALFORMED);
+      return MHD_NO;
     }
+  }
   return MHD_YES;
 }
 
@@ -1888,71 +3910,136 @@
 parse_connection_headers (struct MHD_Connection *connection)
 {
   const char *clen;
-  MHD_UNSIGNED_LONG_LONG cval;
-  struct MHD_Response *response;
   const char *enc;
-  char *end;
+  size_t val_len;
 
-  parse_cookie_header (connection);
-  if ( (0 != (MHD_USE_PEDANTIC_CHECKS & connection->daemon->options)) &&
-       (NULL != connection->version) &&
-       (MHD_str_equal_caseless_(MHD_HTTP_VERSION_1_1, connection->version)) &&
-       (NULL ==
-        MHD_lookup_connection_value (connection,
-                                     MHD_HEADER_KIND,
-                                     MHD_HTTP_HEADER_HOST)) )
-    {
-      /* die, http 1.1 request without host and we are pedantic */
-      connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
-      connection->read_closed = MHD_YES;
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-                "Received `%s' request without `%s' header.\n",
-                MHD_HTTP_VERSION_1_1, MHD_HTTP_HEADER_HOST);
+#ifdef COOKIE_SUPPORT
+  if (MHD_PARSE_COOKIE_NO_MEMORY == parse_cookie_header (connection))
+  {
+    transmit_error_response_static (connection,
+                                    MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                                    REQUEST_TOO_BIG);
+    return;
+  }
+#endif /* COOKIE_SUPPORT */
+  if ( (-3 < connection->daemon->client_discipline) &&
+       (MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver)) &&
+       (MHD_NO ==
+        MHD_lookup_connection_value_n (connection,
+                                       MHD_HEADER_KIND,
+                                       MHD_HTTP_HEADER_HOST,
+                                       MHD_STATICSTR_LEN_ (
+                                         MHD_HTTP_HEADER_HOST),
+                                       NULL,
+                                       NULL)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Received HTTP/1.1 request without `Host' header.\n"));
 #endif
-      EXTRA_CHECK (NULL == connection->response);
-      response =
-        MHD_create_response_from_buffer (strlen (REQUEST_LACKS_HOST),
-					 REQUEST_LACKS_HOST,
-					 MHD_RESPMEM_PERSISTENT);
-      MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response);
-      MHD_destroy_response (response);
+    transmit_error_response_static (connection,
+                                    MHD_HTTP_BAD_REQUEST,
+                                    REQUEST_LACKS_HOST);
+    return;
+  }
+
+  connection->rq.remaining_upload_size = 0;
+  if (MHD_NO !=
+      MHD_lookup_connection_value_n (connection,
+                                     MHD_HEADER_KIND,
+                                     MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                     MHD_STATICSTR_LEN_ (
+                                       MHD_HTTP_HEADER_TRANSFER_ENCODING),
+                                     &enc,
+                                     NULL))
+  {
+    if (! MHD_str_equal_caseless_ (enc,
+                                   "chunked"))
+    {
+      transmit_error_response_static (connection,
+                                      MHD_HTTP_BAD_REQUEST,
+                                      REQUEST_UNSUPPORTED_TR_ENCODING);
       return;
     }
-
-  connection->remaining_upload_size = 0;
-  enc = MHD_lookup_connection_value (connection,
-				     MHD_HEADER_KIND,
-				     MHD_HTTP_HEADER_TRANSFER_ENCODING);
-  if (NULL != enc)
+    else if (MHD_NO !=
+             MHD_lookup_connection_value_n (connection,
+                                            MHD_HEADER_KIND,
+                                            MHD_HTTP_HEADER_CONTENT_LENGTH,
+                                            MHD_STATICSTR_LEN_ ( \
+                                              MHD_HTTP_HEADER_CONTENT_LENGTH),
+                                            NULL,
+                                            NULL))
     {
-      connection->remaining_upload_size = MHD_SIZE_UNKNOWN;
-      if (MHD_str_equal_caseless_(enc, "chunked"))
-        connection->have_chunked_upload = MHD_YES;
+      /* TODO: add individual settings */
+      if (1 <= connection->daemon->client_discipline)
+      {
+        transmit_error_response_static (connection,
+                                        MHD_HTTP_BAD_REQUEST,
+                                        REQUEST_LENGTH_WITH_TR_ENCODING);
+        return;
+      }
+      else
+      {
+        /* Must close connection after reply to prevent potential attack */
+        connection->keepalive = MHD_CONN_MUST_CLOSE;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (connection->daemon,
+                  _ ("The 'Content-Length' request header is ignored "
+                     "as chunked Transfer-Encoding is used "
+                     "for this request.\n"));
+#endif /* HAVE_MESSAGES */
+      }
     }
+    connection->rq.have_chunked_upload = true;
+    connection->rq.remaining_upload_size = MHD_SIZE_UNKNOWN;
+  }
   else
+  {
+    if (MHD_NO !=
+        MHD_lookup_connection_value_n (connection,
+                                       MHD_HEADER_KIND,
+                                       MHD_HTTP_HEADER_CONTENT_LENGTH,
+                                       MHD_STATICSTR_LEN_ (
+                                         MHD_HTTP_HEADER_CONTENT_LENGTH),
+                                       &clen,
+                                       &val_len))
     {
-      clen = MHD_lookup_connection_value (connection,
-					  MHD_HEADER_KIND,
-					  MHD_HTTP_HEADER_CONTENT_LENGTH);
-      if (NULL != clen)
+      size_t num_digits;
+
+      num_digits = MHD_str_to_uint64_n_ (clen,
+                                         val_len,
+                                         &connection->rq.remaining_upload_size);
+      if ( (val_len != num_digits) ||
+           (0 == num_digits) )
+      {
+        connection->rq.remaining_upload_size = 0;
+        if ((0 == num_digits) &&
+            (0 != val_len) &&
+            ('0' <= clen[0]) && ('9' >= clen[0]))
         {
-          cval = strtoul (clen, &end, 10);
-          if ( ('\0' != *end) ||
-	     ( (LONG_MAX == cval) && (errno == ERANGE) ) )
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (connection->daemon,
-                        "Failed to parse `%s' header `%s', closing connection.\n",
-                        MHD_HTTP_HEADER_CONTENT_LENGTH,
-                        clen);
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (connection->daemon,
+                    _ ("Too large value of 'Content-Length' header. " \
+                       "Closing connection.\n"));
 #endif
-	      CONNECTION_CLOSE_ERROR (connection, NULL);
-              return;
-            }
-          connection->remaining_upload_size = cval;
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_CONTENT_TOO_LARGE,
+                                          REQUEST_CONTENTLENGTH_TOOLARGE);
         }
+        else
+        {
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (connection->daemon,
+                    _ ("Failed to parse `Content-Length' header. " \
+                       "Closing connection.\n"));
+#endif
+          transmit_error_response_static (connection,
+                                          MHD_HTTP_BAD_REQUEST,
+                                          REQUEST_CONTENTLENGTH_MALFORMED);
+        }
+      }
     }
+  }
 }
 
 
@@ -1963,255 +4050,611 @@
  *
  * @param connection the connection that saw some activity
  */
-static void
-update_last_activity (struct MHD_Connection *connection)
+void
+MHD_update_last_activity_ (struct MHD_Connection *connection)
 {
   struct MHD_Daemon *daemon = connection->daemon;
+#if defined(MHD_USE_THREADS)
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
 
-  connection->last_activity = MHD_monotonic_time();
-  if (connection->connection_timeout != daemon->connection_timeout)
+  if (0 == connection->connection_timeout_ms)
+    return;  /* Skip update of activity for connections
+               without timeout timer. */
+  if (connection->suspended)
+    return;  /* no activity on suspended connections */
+
+  connection->last_activity = MHD_monotonic_msec_counter ();
+  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+    return; /* each connection has personal timeout */
+
+  if (connection->connection_timeout_ms != daemon->connection_timeout_ms)
     return; /* custom timeout, no need to move it in "normal" DLL */
-
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
   /* move connection to head of timeout list (by remove + add operation) */
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
   XDLL_remove (daemon->normal_timeout_head,
-	       daemon->normal_timeout_tail,
-	       connection);
+               daemon->normal_timeout_tail,
+               connection);
   XDLL_insert (daemon->normal_timeout_head,
-	       daemon->normal_timeout_tail,
-	       connection);
-  if  ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-	(MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+               daemon->normal_timeout_tail,
+               connection);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
 }
 
 
 /**
  * This function handles a particular connection when it has been
- * determined that there is data to be read off a socket.
+ * determined that there is data to be read off a socket. All
+ * implementations (multithreaded, external polling, internal polling)
+ * call this function to handle reads.
  *
  * @param connection connection to handle
- * @return always #MHD_YES (we should continue to process the
- *         connection)
+ * @param socket_error set to true if socket error was detected
  */
-int
-MHD_connection_handle_read (struct MHD_Connection *connection)
+void
+MHD_connection_handle_read (struct MHD_Connection *connection,
+                            bool socket_error)
 {
-  update_last_activity (connection);
-  if (MHD_CONNECTION_CLOSED == connection->state)
-    return MHD_YES;
+  ssize_t bytes_read;
+
+  if ( (MHD_CONNECTION_CLOSED == connection->state) ||
+       (connection->suspended) )
+    return;
+#ifdef HTTPS_SUPPORT
+  if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
+  {   /* HTTPS connection. */
+    if (MHD_TLS_CONN_CONNECTED > connection->tls_state)
+    {
+      if (! MHD_run_tls_handshake_ (connection))
+        return;
+    }
+  }
+#endif /* HTTPS_SUPPORT */
+
   /* make sure "read" has a reasonable number of bytes
      in buffer to use per system call (if possible) */
   if (connection->read_buffer_offset + connection->daemon->pool_increment >
       connection->read_buffer_size)
-    try_grow_read_buffer (connection);
-  if (MHD_NO == do_read (connection))
-    return MHD_YES;
-  while (1)
-    {
-#if DEBUG_STATES
-      MHD_DLOG (connection->daemon, "%s: state: %s\n",
-                __FUNCTION__,
-                MHD_state_to_string (connection->state));
-#endif
-      switch (connection->state)
-        {
-        case MHD_CONNECTION_INIT:
-        case MHD_CONNECTION_URL_RECEIVED:
-        case MHD_CONNECTION_HEADER_PART_RECEIVED:
-        case MHD_CONNECTION_HEADERS_RECEIVED:
-        case MHD_CONNECTION_HEADERS_PROCESSED:
-        case MHD_CONNECTION_CONTINUE_SENDING:
-        case MHD_CONNECTION_CONTINUE_SENT:
-        case MHD_CONNECTION_BODY_RECEIVED:
-        case MHD_CONNECTION_FOOTER_PART_RECEIVED:
-          /* nothing to do but default action */
-          if (MHD_YES == connection->read_closed)
-            {
-	      MHD_connection_close (connection,
-				    MHD_REQUEST_TERMINATED_READ_ERROR);
-              continue;
-            }
-          break;
-        case MHD_CONNECTION_CLOSED:
-          return MHD_YES;
-        default:
-          /* shrink read buffer to how much is actually used */
-          MHD_pool_reallocate (connection->pool,
-                               connection->read_buffer,
-                               connection->read_buffer_size + 1,
-                               connection->read_buffer_offset);
-          break;
-        }
-      break;
+    try_grow_read_buffer (connection,
+                          (connection->read_buffer_size ==
+                           connection->read_buffer_offset));
+
+  if (connection->read_buffer_size == connection->read_buffer_offset)
+    return; /* No space for receiving data. */
+  bytes_read = connection->recv_cls (connection,
+                                     &connection->read_buffer
+                                     [connection->read_buffer_offset],
+                                     connection->read_buffer_size
+                                     - connection->read_buffer_offset);
+  if ((bytes_read < 0) || socket_error)
+  {
+    if ((MHD_ERR_AGAIN_ == bytes_read) && ! socket_error)
+      return;     /* No new data to process. */
+    if ((bytes_read > 0) && connection->sk_nonblck)
+    { /* Try to detect the socket error */
+      int dummy;
+      bytes_read = connection->recv_cls (connection, &dummy, sizeof (dummy));
     }
-  return MHD_YES;
+    if (MHD_ERR_CONNRESET_ == bytes_read)
+    {
+      if ( (MHD_CONNECTION_INIT < connection->state) &&
+           (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) )
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (connection->daemon,
+                  _ ("Socket has been disconnected when reading request.\n"));
+#endif
+        connection->discard_request = true;
+      }
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_READ_ERROR);
+      return;
+    }
+
+#ifdef HAVE_MESSAGES
+    if (MHD_CONNECTION_INIT != connection->state)
+      MHD_DLOG (connection->daemon,
+                _ ("Connection socket is closed when reading " \
+                   "request due to the error: %s\n"),
+                (bytes_read < 0) ? str_conn_error_ (bytes_read) :
+                "detected connection closure");
+#endif
+    CONNECTION_CLOSE_ERROR (connection,
+                            NULL);
+    return;
+  }
+
+  if (0 == bytes_read)
+  {   /* Remote side closed connection. */
+    connection->read_closed = true;
+    if ( (MHD_CONNECTION_INIT < connection->state) &&
+         (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("Connection was closed by remote side with incomplete "
+                   "request.\n"));
+#endif
+      connection->discard_request = true;
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_CLIENT_ABORT);
+    }
+    else if (MHD_CONNECTION_INIT == connection->state)
+      /* This termination code cannot be reported to the application
+       * because application has not been informed yet about this request */
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_COMPLETED_OK);
+    else
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_WITH_ERROR);
+    return;
+  }
+  connection->read_buffer_offset += (size_t) bytes_read;
+  MHD_update_last_activity_ (connection);
+#if DEBUG_STATES
+  MHD_DLOG (connection->daemon,
+            _ ("In function %s handling connection at state: %s\n"),
+            MHD_FUNC_,
+            MHD_state_to_string (connection->state));
+#endif
+  /* TODO: check whether the next 'switch()' really needed */
+  switch (connection->state)
+  {
+  case MHD_CONNECTION_INIT:
+  case MHD_CONNECTION_REQ_LINE_RECEIVING:
+  case MHD_CONNECTION_URL_RECEIVED:
+  case MHD_CONNECTION_HEADER_PART_RECEIVED:
+  case MHD_CONNECTION_HEADERS_RECEIVED:
+  case MHD_CONNECTION_HEADERS_PROCESSED:
+  case MHD_CONNECTION_CONTINUE_SENDING:
+  case MHD_CONNECTION_BODY_RECEIVING:
+  case MHD_CONNECTION_BODY_RECEIVED:
+  case MHD_CONNECTION_FOOTER_PART_RECEIVED:
+  case MHD_CONNECTION_FOOTERS_RECEIVED:
+  case MHD_CONNECTION_FULL_REQ_RECEIVED:
+    /* nothing to do but default action */
+    if (connection->read_closed)
+    {
+      /* TODO: check whether this really needed */
+      MHD_connection_close_ (connection,
+                             MHD_REQUEST_TERMINATED_READ_ERROR);
+    }
+    return;
+  case MHD_CONNECTION_CLOSED:
+    return;
+#ifdef UPGRADE_SUPPORT
+  case MHD_CONNECTION_UPGRADE:
+    mhd_assert (0);
+    return;
+#endif /* UPGRADE_SUPPORT */
+  case MHD_CONNECTION_START_REPLY:
+    /* shrink read buffer to how much is actually used */
+    /* TODO: remove shrink as it handled in special function */
+    if ((0 != connection->read_buffer_size) &&
+        (connection->read_buffer_size != connection->read_buffer_offset))
+    {
+      mhd_assert (NULL != connection->read_buffer);
+      connection->read_buffer =
+        MHD_pool_reallocate (connection->pool,
+                             connection->read_buffer,
+                             connection->read_buffer_size,
+                             connection->read_buffer_offset);
+      connection->read_buffer_size = connection->read_buffer_offset;
+    }
+    break;
+  case MHD_CONNECTION_HEADERS_SENDING:
+  case MHD_CONNECTION_HEADERS_SENT:
+  case MHD_CONNECTION_NORMAL_BODY_UNREADY:
+  case MHD_CONNECTION_NORMAL_BODY_READY:
+  case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
+  case MHD_CONNECTION_CHUNKED_BODY_READY:
+  case MHD_CONNECTION_CHUNKED_BODY_SENT:
+  case MHD_CONNECTION_FOOTERS_SENDING:
+  case MHD_CONNECTION_FULL_REPLY_SENT:
+  default:
+    mhd_assert (0); /* Should not be possible */
+  }
+  return;
 }
 
 
 /**
  * This function was created to handle writes to sockets when it has
- * been determined that the socket can be written to.
+ * been determined that the socket can be written to. All
+ * implementations (multithreaded, external select, internal select)
+ * call this function
  *
  * @param connection connection to handle
- * @return always #MHD_YES (we should continue to process the
- *         connection)
  */
-int
+void
 MHD_connection_handle_write (struct MHD_Connection *connection)
 {
   struct MHD_Response *response;
   ssize_t ret;
+  if (connection->suspended)
+    return;
 
-  update_last_activity (connection);
-  while (1)
+#ifdef HTTPS_SUPPORT
+  if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
+  {   /* HTTPS connection. */
+    if (MHD_TLS_CONN_CONNECTED > connection->tls_state)
     {
-#if DEBUG_STATES
-      MHD_DLOG (connection->daemon, "%s: state: %s\n",
-                __FUNCTION__,
-                MHD_state_to_string (connection->state));
-#endif
-      switch (connection->state)
-        {
-        case MHD_CONNECTION_INIT:
-        case MHD_CONNECTION_URL_RECEIVED:
-        case MHD_CONNECTION_HEADER_PART_RECEIVED:
-        case MHD_CONNECTION_HEADERS_RECEIVED:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_HEADERS_PROCESSED:
-          break;
-        case MHD_CONNECTION_CONTINUE_SENDING:
-          ret = connection->send_cls (connection,
-                                      &HTTP_100_CONTINUE
-                                      [connection->continue_message_write_offset],
-                                      strlen (HTTP_100_CONTINUE) -
-                                      connection->continue_message_write_offset);
-          if (ret < 0)
-            {
-              const int err = MHD_socket_errno_;
-              if ((err == EINTR) || (err == EAGAIN) || (EWOULDBLOCK == err))
-                break;
-#if HAVE_MESSAGES
-              MHD_DLOG (connection->daemon,
-                        "Failed to send data: %s\n",
-                        MHD_socket_last_strerr_ ());
-#endif
-	      CONNECTION_CLOSE_ERROR (connection, NULL);
-              return MHD_YES;
-            }
-#if DEBUG_SEND_DATA
-          fprintf (stderr,
-                   "Sent 100 continue response: `%.*s'\n",
-                   (int) ret,
-                   &HTTP_100_CONTINUE[connection->continue_message_write_offset]);
-#endif
-          connection->continue_message_write_offset += ret;
-          break;
-        case MHD_CONNECTION_CONTINUE_SENT:
-        case MHD_CONNECTION_BODY_RECEIVED:
-        case MHD_CONNECTION_FOOTER_PART_RECEIVED:
-        case MHD_CONNECTION_FOOTERS_RECEIVED:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_HEADERS_SENDING:
-          do_write (connection);
-	  if (connection->state != MHD_CONNECTION_HEADERS_SENDING)
- 	     break;
-          check_write_done (connection, MHD_CONNECTION_HEADERS_SENT);
-          break;
-        case MHD_CONNECTION_HEADERS_SENT:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_NORMAL_BODY_READY:
-          response = connection->response;
-          if (NULL != response->crc)
-            (void) MHD_mutex_lock_ (&response->mutex);
-          if (MHD_YES != try_ready_normal_body (connection))
-	    break;
-	  ret = connection->send_cls (connection,
-				      &response->data
-				      [connection->response_write_position
-				       - response->data_start],
-				      response->data_size -
-				      (connection->response_write_position
-				       - response->data_start));
-	  const int err = MHD_socket_errno_;
-#if DEBUG_SEND_DATA
-          if (ret > 0)
-            fprintf (stderr,
-                     "Sent DATA response: `%.*s'\n",
-                     (int) ret,
-                     &response->data[connection->response_write_position -
-                                     response->data_start]);
-#endif
-          if (NULL != response->crc)
-            (void) MHD_mutex_unlock_ (&response->mutex);
-          if (ret < 0)
-            {
-              if ((err == EINTR) || (err == EAGAIN) || (EWOULDBLOCK == err))
-                return MHD_YES;
-#if HAVE_MESSAGES
-              MHD_DLOG (connection->daemon,
-                        "Failed to send data: %s\n",
-                        MHD_socket_last_strerr_ ());
-#endif
-	      CONNECTION_CLOSE_ERROR (connection, NULL);
-              return MHD_YES;
-            }
-          connection->response_write_position += ret;
-          if (connection->response_write_position ==
-              connection->response->total_size)
-            connection->state = MHD_CONNECTION_FOOTERS_SENT; /* have no footers */
-          break;
-        case MHD_CONNECTION_NORMAL_BODY_UNREADY:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_CHUNKED_BODY_READY:
-          do_write (connection);
-	  if (MHD_CONNECTION_CHUNKED_BODY_READY != connection->state)
-	     break;
-          check_write_done (connection,
-                            (connection->response->total_size ==
-                             connection->response_write_position) ?
-                            MHD_CONNECTION_BODY_SENT :
-                            MHD_CONNECTION_CHUNKED_BODY_UNREADY);
-          break;
-        case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
-        case MHD_CONNECTION_BODY_SENT:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_FOOTERS_SENDING:
-          do_write (connection);
-	  if (connection->state != MHD_CONNECTION_FOOTERS_SENDING)
-	    break;
-          check_write_done (connection, MHD_CONNECTION_FOOTERS_SENT);
-          break;
-        case MHD_CONNECTION_FOOTERS_SENT:
-          EXTRA_CHECK (0);
-          break;
-        case MHD_CONNECTION_CLOSED:
-          return MHD_YES;
-        case MHD_TLS_CONNECTION_INIT:
-          EXTRA_CHECK (0);
-          break;
-        default:
-          EXTRA_CHECK (0);
-	  CONNECTION_CLOSE_ERROR (connection,
-                                  "Internal error\n");
-          return MHD_YES;
-        }
-      break;
+      if (! MHD_run_tls_handshake_ (connection))
+        return;
     }
-  return MHD_YES;
+  }
+#endif /* HTTPS_SUPPORT */
+
+#if DEBUG_STATES
+  MHD_DLOG (connection->daemon,
+            _ ("In function %s handling connection at state: %s\n"),
+            MHD_FUNC_,
+            MHD_state_to_string (connection->state));
+#endif
+  switch (connection->state)
+  {
+  case MHD_CONNECTION_INIT:
+  case MHD_CONNECTION_REQ_LINE_RECEIVING:
+  case MHD_CONNECTION_URL_RECEIVED:
+  case MHD_CONNECTION_HEADER_PART_RECEIVED:
+  case MHD_CONNECTION_HEADERS_RECEIVED:
+    mhd_assert (0);
+    return;
+  case MHD_CONNECTION_HEADERS_PROCESSED:
+    return;
+  case MHD_CONNECTION_CONTINUE_SENDING:
+    ret = MHD_send_data_ (connection,
+                          &HTTP_100_CONTINUE
+                          [connection->continue_message_write_offset],
+                          MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE)
+                          - connection->continue_message_write_offset,
+                          true);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("Failed to send data in request for %s.\n"),
+                connection->rq.url);
+#endif
+      CONNECTION_CLOSE_ERROR (connection,
+                              NULL);
+      return;
+    }
+#if _MHD_DEBUG_SEND_DATA
+    fprintf (stderr,
+             _ ("Sent 100 continue response: `%.*s'\n"),
+             (int) ret,
+             &HTTP_100_CONTINUE[connection->continue_message_write_offset]);
+#endif
+    connection->continue_message_write_offset += (size_t) ret;
+    MHD_update_last_activity_ (connection);
+    return;
+  case MHD_CONNECTION_BODY_RECEIVING:
+  case MHD_CONNECTION_BODY_RECEIVED:
+  case MHD_CONNECTION_FOOTER_PART_RECEIVED:
+  case MHD_CONNECTION_FOOTERS_RECEIVED:
+  case MHD_CONNECTION_FULL_REQ_RECEIVED:
+  case MHD_CONNECTION_START_REPLY:
+    mhd_assert (0);
+    return;
+  case MHD_CONNECTION_HEADERS_SENDING:
+    {
+      struct MHD_Response *const resp = connection->rp.response;
+      const size_t wb_ready = connection->write_buffer_append_offset
+                              - connection->write_buffer_send_offset;
+      mhd_assert (connection->write_buffer_append_offset >= \
+                  connection->write_buffer_send_offset);
+      mhd_assert (NULL != resp);
+      mhd_assert ( (0 == resp->data_size) || \
+                   (0 == resp->data_start) || \
+                   (NULL != resp->crc) );
+      mhd_assert ( (0 == connection->rp.rsp_write_position) || \
+                   (resp->total_size ==
+                    connection->rp.rsp_write_position) );
+      mhd_assert ((MHD_CONN_MUST_UPGRADE != connection->keepalive) || \
+                  (! connection->rp.props.send_reply_body));
+
+      if ( (connection->rp.props.send_reply_body) &&
+           (NULL == resp->crc) &&
+           (NULL == resp->data_iov) &&
+           /* TODO: remove the next check as 'send_reply_body' is used */
+           (0 == connection->rp.rsp_write_position) &&
+           (! connection->rp.props.chunked) )
+      {
+        mhd_assert (resp->total_size >= resp->data_size);
+        mhd_assert (0 == resp->data_start);
+        /* Send response headers alongside the response body, if the body
+         * data is available. */
+        ret = MHD_send_hdr_and_body_ (connection,
+                                      &connection->write_buffer
+                                      [connection->write_buffer_send_offset],
+                                      wb_ready,
+                                      false,
+                                      resp->data,
+                                      resp->data_size,
+                                      (resp->total_size == resp->data_size));
+      }
+      else
+      {
+        /* This is response for HEAD request or reply body is not allowed
+         * for any other reason or reply body is dynamically generated. */
+        /* Do not send the body data even if it's available. */
+        ret = MHD_send_hdr_and_body_ (connection,
+                                      &connection->write_buffer
+                                      [connection->write_buffer_send_offset],
+                                      wb_ready,
+                                      false,
+                                      NULL,
+                                      0,
+                                      ((0 == resp->total_size) ||
+                                       (! connection->rp.props.send_reply_body)
+                                      ));
+      }
+
+      if (ret < 0)
+      {
+        if (MHD_ERR_AGAIN_ == ret)
+          return;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (connection->daemon,
+                  _ ("Failed to send the response headers for the " \
+                     "request for `%s'. Error: %s\n"),
+                  connection->rq.url,
+                  str_conn_error_ (ret));
+#endif
+        CONNECTION_CLOSE_ERROR (connection,
+                                NULL);
+        return;
+      }
+      /* 'ret' is not negative, it's safe to cast it to 'size_t'. */
+      if (((size_t) ret) > wb_ready)
+      {
+        /* The complete header and some response data have been sent,
+         * update both offsets. */
+        mhd_assert (0 == connection->rp.rsp_write_position);
+        mhd_assert (! connection->rp.props.chunked);
+        mhd_assert (connection->rp.props.send_reply_body);
+        connection->write_buffer_send_offset += wb_ready;
+        connection->rp.rsp_write_position = ((size_t) ret) - wb_ready;
+      }
+      else
+        connection->write_buffer_send_offset += (size_t) ret;
+      MHD_update_last_activity_ (connection);
+      if (MHD_CONNECTION_HEADERS_SENDING != connection->state)
+        return;
+      check_write_done (connection,
+                        MHD_CONNECTION_HEADERS_SENT);
+      return;
+    }
+  case MHD_CONNECTION_HEADERS_SENT:
+    return;
+  case MHD_CONNECTION_NORMAL_BODY_READY:
+    response = connection->rp.response;
+    if (connection->rp.rsp_write_position <
+        connection->rp.response->total_size)
+    {
+      uint64_t data_write_offset;
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+      if (NULL != response->crc)
+        MHD_mutex_lock_chk_ (&response->mutex);
+#endif
+      if (MHD_NO == try_ready_normal_body (connection))
+      {
+        /* mutex was already unlocked by try_ready_normal_body */
+        return;
+      }
+#if defined(_MHD_HAVE_SENDFILE)
+      if (MHD_resp_sender_sendfile == connection->rp.resp_sender)
+      {
+        mhd_assert (NULL == response->data_iov);
+        ret = MHD_send_sendfile_ (connection);
+      }
+      else /* combined with the next 'if' */
+#endif /* _MHD_HAVE_SENDFILE */
+      if (NULL != response->data_iov)
+      {
+        ret = MHD_send_iovec_ (connection,
+                               &connection->rp.resp_iov,
+                               true);
+      }
+      else
+      {
+        data_write_offset = connection->rp.rsp_write_position
+                            - response->data_start;
+        if (data_write_offset > (uint64_t) SIZE_MAX)
+          MHD_PANIC (_ ("Data offset exceeds limit.\n"));
+        ret = MHD_send_data_ (connection,
+                              &response->data
+                              [(size_t) data_write_offset],
+                              response->data_size
+                              - (size_t) data_write_offset,
+                              true);
+#if _MHD_DEBUG_SEND_DATA
+        if (ret > 0)
+          fprintf (stderr,
+                   _ ("Sent %d-byte DATA response: `%.*s'\n"),
+                   (int) ret,
+                   (int) ret,
+                   &rp.response->data[connection->rp.rsp_write_position
+                                      - rp.response->data_start]);
+#endif
+      }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+      if (NULL != response->crc)
+        MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+      if (ret < 0)
+      {
+        if (MHD_ERR_AGAIN_ == ret)
+          return;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (connection->daemon,
+                  _ ("Failed to send the response body for the " \
+                     "request for `%s'. Error: %s\n"),
+                  connection->rq.url,
+                  str_conn_error_ (ret));
+#endif
+        CONNECTION_CLOSE_ERROR (connection,
+                                NULL);
+        return;
+      }
+      connection->rp.rsp_write_position += (size_t) ret;
+      MHD_update_last_activity_ (connection);
+    }
+    if (connection->rp.rsp_write_position ==
+        connection->rp.response->total_size)
+      connection->state = MHD_CONNECTION_FULL_REPLY_SENT;
+    return;
+  case MHD_CONNECTION_NORMAL_BODY_UNREADY:
+    mhd_assert (0);
+    return;
+  case MHD_CONNECTION_CHUNKED_BODY_READY:
+    ret = MHD_send_data_ (connection,
+                          &connection->write_buffer
+                          [connection->write_buffer_send_offset],
+                          connection->write_buffer_append_offset
+                          - connection->write_buffer_send_offset,
+                          true);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("Failed to send the chunked response body for the " \
+                   "request for `%s'. Error: %s\n"),
+                connection->rq.url,
+                str_conn_error_ (ret));
+#endif
+      CONNECTION_CLOSE_ERROR (connection,
+                              NULL);
+      return;
+    }
+    connection->write_buffer_send_offset += (size_t) ret;
+    MHD_update_last_activity_ (connection);
+    if (MHD_CONNECTION_CHUNKED_BODY_READY != connection->state)
+      return;
+    check_write_done (connection,
+                      (connection->rp.response->total_size ==
+                       connection->rp.rsp_write_position) ?
+                      MHD_CONNECTION_CHUNKED_BODY_SENT :
+                      MHD_CONNECTION_CHUNKED_BODY_UNREADY);
+    return;
+  case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
+  case MHD_CONNECTION_CHUNKED_BODY_SENT:
+    mhd_assert (0);
+    return;
+  case MHD_CONNECTION_FOOTERS_SENDING:
+    ret = MHD_send_data_ (connection,
+                          &connection->write_buffer
+                          [connection->write_buffer_send_offset],
+                          connection->write_buffer_append_offset
+                          - connection->write_buffer_send_offset,
+                          true);
+    if (ret < 0)
+    {
+      if (MHD_ERR_AGAIN_ == ret)
+        return;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("Failed to send the footers for the " \
+                   "request for `%s'. Error: %s\n"),
+                connection->rq.url,
+                str_conn_error_ (ret));
+#endif
+      CONNECTION_CLOSE_ERROR (connection,
+                              NULL);
+      return;
+    }
+    connection->write_buffer_send_offset += (size_t) ret;
+    MHD_update_last_activity_ (connection);
+    if (MHD_CONNECTION_FOOTERS_SENDING != connection->state)
+      return;
+    check_write_done (connection,
+                      MHD_CONNECTION_FULL_REPLY_SENT);
+    return;
+  case MHD_CONNECTION_FULL_REPLY_SENT:
+    mhd_assert (0);
+    return;
+  case MHD_CONNECTION_CLOSED:
+    return;
+#ifdef UPGRADE_SUPPORT
+  case MHD_CONNECTION_UPGRADE:
+    mhd_assert (0);
+    return;
+#endif /* UPGRADE_SUPPORT */
+  default:
+    mhd_assert (0);
+    CONNECTION_CLOSE_ERROR (connection,
+                            _ ("Internal error.\n"));
+    break;
+  }
+  return;
+}
+
+
+/**
+ * Check whether connection has timed out.
+ * @param c the connection to check
+ * @return true if connection has timeout and needs to be closed,
+ *         false otherwise.
+ */
+static bool
+connection_check_timedout (struct MHD_Connection *c)
+{
+  const uint64_t timeout = c->connection_timeout_ms;
+  uint64_t now;
+  uint64_t since_actv;
+
+  if (c->suspended)
+    return false;
+  if (0 == timeout)
+    return false;
+  now = MHD_monotonic_msec_counter ();
+  since_actv = now - c->last_activity;
+  /* Keep the next lines in sync with #connection_get_wait() to avoid
+   * undesired side-effects like busy-waiting. */
+  if (timeout < since_actv)
+  {
+    if (UINT64_MAX / 2 < since_actv)
+    {
+      const uint64_t jump_back = c->last_activity - now;
+      /* Very unlikely that it is more than quarter-million years pause.
+       * More likely that system clock jumps back. */
+      if (5000 >= jump_back)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (c->daemon,
+                  _ ("Detected system clock %u milliseconds jump back.\n"),
+                  (unsigned int) jump_back);
+#endif
+        return false;
+      }
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (c->daemon,
+                _ ("Detected too large system clock %" PRIu64 " milliseconds "
+                   "jump back.\n"),
+                jump_back);
+#endif
+    }
+    return true;
+  }
+  return false;
 }
 
 
 /**
  * Clean up the state of the given connection and move it into the
  * clean up queue for final disposal.
+ * @remark To be called only from thread that process connection's
+ * recv(), send() and response.
  *
  * @param connection handle for the connection to clean up
  */
@@ -2219,484 +4662,648 @@
 cleanup_connection (struct MHD_Connection *connection)
 {
   struct MHD_Daemon *daemon = connection->daemon;
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (connection->pid) );
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
 
-  if (NULL != connection->response)
-    {
-      MHD_destroy_response (connection->response);
-      connection->response = NULL;
-    }
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  if (connection->connection_timeout == daemon->connection_timeout)
-    XDLL_remove (daemon->normal_timeout_head,
-		 daemon->normal_timeout_tail,
-		 connection);
-  else
-    XDLL_remove (daemon->manual_timeout_head,
-		 daemon->manual_timeout_tail,
-		 connection);
-  if (MHD_YES == connection->suspended)
+  if (connection->in_cleanup)
+    return; /* Prevent double cleanup. */
+  connection->in_cleanup = true;
+  if (NULL != connection->rp.response)
+  {
+    MHD_destroy_response (connection->rp.response);
+    connection->rp.response = NULL;
+  }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  if (connection->suspended)
+  {
     DLL_remove (daemon->suspended_connections_head,
                 daemon->suspended_connections_tail,
                 connection);
+    connection->suspended = false;
+  }
   else
+  {
+    if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+    {
+      if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
+        XDLL_remove (daemon->normal_timeout_head,
+                     daemon->normal_timeout_tail,
+                     connection);
+      else
+        XDLL_remove (daemon->manual_timeout_head,
+                     daemon->manual_timeout_tail,
+                     connection);
+    }
     DLL_remove (daemon->connections_head,
                 daemon->connections_tail,
                 connection);
+  }
   DLL_insert (daemon->cleanup_head,
-	      daemon->cleanup_tail,
-	      connection);
-  connection->suspended = MHD_NO;
-  connection->resuming = MHD_NO;
-  connection->in_idle = MHD_NO;
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_(&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+              daemon->cleanup_tail,
+              connection);
+  connection->resuming = false;
+  connection->in_idle = false;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+  {
+    /* if we were at the connection limit before and are in
+       thread-per-connection mode, signal the main thread
+       to resume accepting connections */
+    if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+         (! MHD_itc_activate_ (daemon->itc, "c")) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to signal end of connection via inter-thread " \
+                   "communication channel.\n"));
+#endif
+    }
+  }
+}
+
+
+/**
+ * Reset connection after request-reply cycle.
+ * @param connection the connection to process
+ * @param reuse the flag to choose whether to close connection or
+ *              prepare connection for the next request processing
+ */
+static void
+connection_reset (struct MHD_Connection *connection,
+                  bool reuse)
+{
+  struct MHD_Connection *const c = connection; /**< a short alias */
+  struct MHD_Daemon *const d = connection->daemon;
+
+  if (! reuse)
+  {
+    /* Next function will destroy response, notify client,
+     * destroy memory pool, and set connection state to "CLOSED" */
+    MHD_connection_close_ (c,
+                           c->stop_with_error ?
+                           MHD_REQUEST_TERMINATED_WITH_ERROR :
+                           MHD_REQUEST_TERMINATED_COMPLETED_OK);
+    c->read_buffer = NULL;
+    c->read_buffer_size = 0;
+    c->read_buffer_offset = 0;
+    c->write_buffer = NULL;
+    c->write_buffer_size = 0;
+    c->write_buffer_send_offset = 0;
+    c->write_buffer_append_offset = 0;
+  }
+  else
+  {
+    /* Reset connection to process the next request */
+    size_t new_read_buf_size;
+    mhd_assert (! c->stop_with_error);
+    mhd_assert (! c->discard_request);
+
+    if ( (NULL != d->notify_completed) &&
+         (c->rq.client_aware) )
+      d->notify_completed (d->notify_completed_cls,
+                           c,
+                           &c->rq.client_context,
+                           MHD_REQUEST_TERMINATED_COMPLETED_OK);
+    c->rq.client_aware = false;
+
+    if (NULL != c->rp.response)
+      MHD_destroy_response (c->rp.response);
+    c->rp.response = NULL;
+
+    c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN;
+    c->state = MHD_CONNECTION_INIT;
+    c->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+
+    memset (&c->rq, 0, sizeof(c->rq));
+
+    /* iov (if any) will be deallocated by MHD_pool_reset */
+    memset (&c->rp, 0, sizeof(c->rp));
+
+    c->write_buffer = NULL;
+    c->write_buffer_size = 0;
+    c->write_buffer_send_offset = 0;
+    c->write_buffer_append_offset = 0;
+    c->continue_message_write_offset = 0;
+
+    /* Reset the read buffer to the starting size,
+       preserving the bytes we have already read. */
+    new_read_buf_size = c->daemon->pool_size / 2;
+    if (c->read_buffer_offset > new_read_buf_size)
+      new_read_buf_size = c->read_buffer_offset;
+
+    c->read_buffer
+      = MHD_pool_reset (c->pool,
+                        c->read_buffer,
+                        c->read_buffer_offset,
+                        new_read_buf_size);
+    c->read_buffer_size = new_read_buf_size;
+  }
+  c->rq.client_context = NULL;
 }
 
 
 /**
  * This function was created to handle per-connection processing that
  * has to happen even if the socket cannot be read or written to.
+ * All implementations (multithreaded, external select, internal select)
+ * call this function.
+ * @remark To be called only from thread that process connection's
+ * recv(), send() and response.
  *
  * @param connection connection to handle
  * @return #MHD_YES if we should continue to process the
  *         connection (not dead yet), #MHD_NO if it died
  */
-int
+enum MHD_Result
 MHD_connection_handle_idle (struct MHD_Connection *connection)
 {
   struct MHD_Daemon *daemon = connection->daemon;
-  unsigned int timeout;
-  const char *end;
   char *line;
-  int client_close;
+  size_t line_len;
+  enum MHD_Result ret;
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (connection->pid) );
+#endif /* MHD_USE_THREADS */
+  /* 'daemon' is not used if epoll is not available and asserts are disabled */
+  (void) daemon; /* Mute compiler warning */
 
-  connection->in_idle = MHD_YES;
-  while (1)
-    {
+  connection->in_idle = true;
+  while (! connection->suspended)
+  {
+#ifdef HTTPS_SUPPORT
+    if (MHD_TLS_CONN_NO_TLS != connection->tls_state)
+    {     /* HTTPS connection. */
+      if ((MHD_TLS_CONN_INIT <= connection->tls_state) &&
+          (MHD_TLS_CONN_CONNECTED > connection->tls_state))
+        break;
+    }
+#endif /* HTTPS_SUPPORT */
 #if DEBUG_STATES
-      MHD_DLOG (daemon,
-                "%s: state: %s\n",
-                __FUNCTION__,
-                MHD_state_to_string (connection->state));
+    MHD_DLOG (daemon,
+              _ ("In function %s handling connection at state: %s\n"),
+              MHD_FUNC_,
+              MHD_state_to_string (connection->state));
 #endif
-      switch (connection->state)
+    switch (connection->state)
+    {
+    case MHD_CONNECTION_INIT:
+    case MHD_CONNECTION_REQ_LINE_RECEIVING:
+      line = get_next_header_line (connection,
+                                   &line_len);
+      if (MHD_CONNECTION_REQ_LINE_RECEIVING < connection->state)
+        continue;
+      if (NULL != line)
+      {
+        /* Check for empty string, as we might want
+           to tolerate 'spurious' empty lines */
+        if (0 == line[0])
         {
-        case MHD_CONNECTION_INIT:
-          line = get_next_header_line (connection);
-          if (NULL == line)
-            {
-              if (MHD_CONNECTION_INIT != connection->state)
-                continue;
-              if (MHD_YES == connection->read_closed)
-                {
-		  CONNECTION_CLOSE_ERROR (connection,
-					  NULL);
-                  continue;
-                }
-              break;
-            }
-          if (MHD_NO == parse_initial_message_line (connection, line))
-            CONNECTION_CLOSE_ERROR (connection, NULL);
-          else
-            connection->state = MHD_CONNECTION_URL_RECEIVED;
-          continue;
-        case MHD_CONNECTION_URL_RECEIVED:
-          line = get_next_header_line (connection);
-          if (NULL == line)
-            {
-              if (MHD_CONNECTION_URL_RECEIVED != connection->state)
-                continue;
-              if (MHD_YES == connection->read_closed)
-                {
-		  CONNECTION_CLOSE_ERROR (connection,
-					  NULL);
-                  continue;
-                }
-              break;
-            }
-          if (strlen (line) == 0)
-            {
-              connection->state = MHD_CONNECTION_HEADERS_RECEIVED;
-              continue;
-            }
-          if (MHD_NO == process_header_line (connection, line))
-            {
-              transmit_error_response (connection,
-                                       MHD_HTTP_BAD_REQUEST,
-                                       REQUEST_MALFORMED);
-              break;
-            }
-          connection->state = MHD_CONNECTION_HEADER_PART_RECEIVED;
-          continue;
-        case MHD_CONNECTION_HEADER_PART_RECEIVED:
-          line = get_next_header_line (connection);
-          if (NULL == line)
-            {
-              if (connection->state != MHD_CONNECTION_HEADER_PART_RECEIVED)
-                continue;
-              if (MHD_YES == connection->read_closed)
-                {
-		  CONNECTION_CLOSE_ERROR (connection,
-					  NULL);
-                  continue;
-                }
-              break;
-            }
-          if (MHD_NO ==
-              process_broken_line (connection, line, MHD_HEADER_KIND))
-            continue;
-          if (0 == strlen (line))
-            {
-              connection->state = MHD_CONNECTION_HEADERS_RECEIVED;
-              continue;
-            }
-          continue;
-        case MHD_CONNECTION_HEADERS_RECEIVED:
-          parse_connection_headers (connection);
-          if (MHD_CONNECTION_CLOSED == connection->state)
-            continue;
-          connection->state = MHD_CONNECTION_HEADERS_PROCESSED;
-          continue;
-        case MHD_CONNECTION_HEADERS_PROCESSED:
-          call_connection_handler (connection); /* first call */
-          if (MHD_CONNECTION_CLOSED == connection->state)
-            continue;
-          if (need_100_continue (connection))
-            {
-              connection->state = MHD_CONNECTION_CONTINUE_SENDING;
-              break;
-            }
-          if ( (NULL != connection->response) &&
-	       ( (MHD_str_equal_caseless_ (connection->method,
-				   MHD_HTTP_METHOD_POST)) ||
-		 (MHD_str_equal_caseless_ (connection->method,
-				   MHD_HTTP_METHOD_PUT))) )
-            {
-              /* we refused (no upload allowed!) */
-              connection->remaining_upload_size = 0;
-              /* force close, in case client still tries to upload... */
-              connection->read_closed = MHD_YES;
-            }
-          connection->state = (0 == connection->remaining_upload_size)
-            ? MHD_CONNECTION_FOOTERS_RECEIVED : MHD_CONNECTION_CONTINUE_SENT;
-          continue;
-        case MHD_CONNECTION_CONTINUE_SENDING:
-          if (connection->continue_message_write_offset ==
-              strlen (HTTP_100_CONTINUE))
-            {
-              connection->state = MHD_CONNECTION_CONTINUE_SENT;
-              continue;
-            }
-          break;
-        case MHD_CONNECTION_CONTINUE_SENT:
-          if (0 != connection->read_buffer_offset)
-            {
-              process_request_body (connection);     /* loop call */
-              if (MHD_CONNECTION_CLOSED == connection->state)
-                continue;
-            }
-          if ((0 == connection->remaining_upload_size) ||
-              ((connection->remaining_upload_size == MHD_SIZE_UNKNOWN) &&
-               (0 == connection->read_buffer_offset) &&
-               (MHD_YES == connection->read_closed)))
-            {
-              if ((MHD_YES == connection->have_chunked_upload) &&
-                  (MHD_NO == connection->read_closed))
-                connection->state = MHD_CONNECTION_BODY_RECEIVED;
-              else
-                connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
-              continue;
-            }
-          break;
-        case MHD_CONNECTION_BODY_RECEIVED:
-          line = get_next_header_line (connection);
-          if (NULL == line)
-            {
-              if (connection->state != MHD_CONNECTION_BODY_RECEIVED)
-                continue;
-              if (MHD_YES == connection->read_closed)
-                {
-		  CONNECTION_CLOSE_ERROR (connection,
-					  NULL);
-                  continue;
-                }
-              break;
-            }
-          if (0 == strlen (line))
-            {
-              connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
-              continue;
-            }
-          if (MHD_NO == process_header_line (connection, line))
-            {
-              transmit_error_response (connection,
-                                       MHD_HTTP_BAD_REQUEST,
-                                       REQUEST_MALFORMED);
-              break;
-            }
-          connection->state = MHD_CONNECTION_FOOTER_PART_RECEIVED;
-          continue;
-        case MHD_CONNECTION_FOOTER_PART_RECEIVED:
-          line = get_next_header_line (connection);
-          if (NULL == line)
-            {
-              if (connection->state != MHD_CONNECTION_FOOTER_PART_RECEIVED)
-                continue;
-              if (MHD_YES == connection->read_closed)
-                {
-		  CONNECTION_CLOSE_ERROR (connection,
-					  NULL);
-                  continue;
-                }
-              break;
-            }
-          if (MHD_NO ==
-              process_broken_line (connection, line, MHD_FOOTER_KIND))
-            continue;
-          if (0 == strlen (line))
-            {
-              connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
-              continue;
-            }
-          continue;
-        case MHD_CONNECTION_FOOTERS_RECEIVED:
-          call_connection_handler (connection); /* "final" call */
-          if (connection->state == MHD_CONNECTION_CLOSED)
-            continue;
-          if (NULL == connection->response)
-            break;              /* try again next time */
-          if (MHD_NO == build_header_response (connection))
-            {
-              /* oops - close! */
-	      CONNECTION_CLOSE_ERROR (connection,
-				      "Closing connection (failed to create response header)\n");
-              continue;
-            }
-          connection->state = MHD_CONNECTION_HEADERS_SENDING;
-
-#if HAVE_DECL_TCP_CORK
-          /* starting header send, set TCP cork */
-          {
-            const int val = 1;
-            setsockopt (connection->socket_fd, IPPROTO_TCP, TCP_CORK, &val,
-                        sizeof (val));
-          }
-#endif
-          break;
-        case MHD_CONNECTION_HEADERS_SENDING:
-          /* no default action */
-          break;
-        case MHD_CONNECTION_HEADERS_SENT:
-          if (connection->have_chunked_upload)
-            connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY;
-          else
-            connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY;
-          continue;
-        case MHD_CONNECTION_NORMAL_BODY_READY:
-          /* nothing to do here */
-          break;
-        case MHD_CONNECTION_NORMAL_BODY_UNREADY:
-          if (NULL != connection->response->crc)
-            (void) MHD_mutex_lock_ (&connection->response->mutex);
-          if (0 == connection->response->total_size)
-            {
-              if (NULL != connection->response->crc)
-                (void) MHD_mutex_unlock_ (&connection->response->mutex);
-              connection->state = MHD_CONNECTION_BODY_SENT;
-              continue;
-            }
-          if (MHD_YES == try_ready_normal_body (connection))
-            {
-	      if (NULL != connection->response->crc)
-	        (void) MHD_mutex_unlock_ (&connection->response->mutex);
-              connection->state = MHD_CONNECTION_NORMAL_BODY_READY;
-              break;
-            }
-          /* not ready, no socket action */
-          break;
-        case MHD_CONNECTION_CHUNKED_BODY_READY:
-          /* nothing to do here */
-          break;
-        case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
-          if (NULL != connection->response->crc)
-            (void) MHD_mutex_lock_ (&connection->response->mutex);
-          if (0 == connection->response->total_size)
-            {
-              if (NULL != connection->response->crc)
-                (void) MHD_mutex_unlock_ (&connection->response->mutex);
-              connection->state = MHD_CONNECTION_BODY_SENT;
-              continue;
-            }
-          if (MHD_YES == try_ready_chunked_body (connection))
-            {
-              if (NULL != connection->response->crc)
-                (void) MHD_mutex_unlock_ (&connection->response->mutex);
-              connection->state = MHD_CONNECTION_CHUNKED_BODY_READY;
-              continue;
-            }
-          if (NULL != connection->response->crc)
-            (void) MHD_mutex_unlock_ (&connection->response->mutex);
-          break;
-        case MHD_CONNECTION_BODY_SENT:
-          if (MHD_NO == build_header_response (connection))
-            {
-              /* oops - close! */
-	      CONNECTION_CLOSE_ERROR (connection,
-				      "Closing connection (failed to create response header)\n");
-              continue;
-            }
-          if ( (MHD_NO == connection->have_chunked_upload) ||
-               (connection->write_buffer_send_offset ==
-                connection->write_buffer_append_offset) )
-            connection->state = MHD_CONNECTION_FOOTERS_SENT;
-          else
-            connection->state = MHD_CONNECTION_FOOTERS_SENDING;
-          continue;
-        case MHD_CONNECTION_FOOTERS_SENDING:
-          /* no default action */
-          break;
-        case MHD_CONNECTION_FOOTERS_SENT:
-#if HAVE_DECL_TCP_CORK
-          /* done sending, uncork */
-          {
-            const int val = 0;
-            setsockopt (connection->socket_fd, IPPROTO_TCP, TCP_CORK, &val,
-                        sizeof (val));
-          }
-#endif
-          end =
-            MHD_get_response_header (connection->response,
-				     MHD_HTTP_HEADER_CONNECTION);
-          client_close = ((NULL != end) && (MHD_str_equal_caseless_(end, "close")));
-          MHD_destroy_response (connection->response);
-          connection->response = NULL;
-          if ( (NULL != daemon->notify_completed) &&
-               (MHD_YES == connection->client_aware) )
-          {
-	    daemon->notify_completed (daemon->notify_completed_cls,
-				      connection,
-				      &connection->client_context,
-						  MHD_REQUEST_TERMINATED_COMPLETED_OK);
-            connection->client_aware = MHD_NO;
-          }
-          end =
-            MHD_lookup_connection_value (connection, MHD_HEADER_KIND,
-                                         MHD_HTTP_HEADER_CONNECTION);
-          if ( (MHD_YES == connection->read_closed) ||
-               (client_close) ||
-               ((NULL != end) && (MHD_str_equal_caseless_ (end, "close"))) )
-            {
-              connection->read_closed = MHD_YES;
-              connection->read_buffer_offset = 0;
-            }
-          if (((MHD_YES == connection->read_closed) &&
-               (0 == connection->read_buffer_offset)) ||
-              (MHD_NO == keepalive_possible (connection)))
-            {
-              /* have to close for some reason */
-              MHD_connection_close (connection,
-                                    MHD_REQUEST_TERMINATED_COMPLETED_OK);
-              MHD_pool_destroy (connection->pool);
-              connection->pool = NULL;
-              connection->read_buffer = NULL;
-              connection->read_buffer_size = 0;
-              connection->read_buffer_offset = 0;
-            }
-          else
-            {
-              /* can try to keep-alive */
-              connection->version = NULL;
-              connection->state = MHD_CONNECTION_INIT;
-              connection->read_buffer
-                = MHD_pool_reset (connection->pool,
-                                  connection->read_buffer,
-                                  connection->read_buffer_size);
-            }
-	  connection->client_aware = MHD_NO;
-          connection->client_context = NULL;
-          connection->continue_message_write_offset = 0;
-          connection->responseCode = 0;
-          connection->headers_received = NULL;
-	  connection->headers_received_tail = NULL;
-          connection->response_write_position = 0;
-          connection->have_chunked_upload = MHD_NO;
-          connection->method = NULL;
-          connection->url = NULL;
-          connection->write_buffer = NULL;
-          connection->write_buffer_size = 0;
-          connection->write_buffer_send_offset = 0;
-          connection->write_buffer_append_offset = 0;
-          continue;
-        case MHD_CONNECTION_CLOSED:
-	  cleanup_connection (connection);
-	  return MHD_NO;
-        default:
-          EXTRA_CHECK (0);
-          break;
+          /* TODO: Add MHD option to not tolerate it */
+          connection->state = MHD_CONNECTION_INIT;
+          continue; /* Process the next line */
         }
+        if (MHD_NO == parse_initial_message_line (connection,
+                                                  line,
+                                                  line_len))
+          CONNECTION_CLOSE_ERROR_CHECK (connection,
+                                        NULL);
+        else
+        {
+          mhd_assert (MHD_IS_HTTP_VER_SUPPORTED (connection->rq.http_ver));
+          connection->state = MHD_CONNECTION_URL_RECEIVED;
+        }
+        continue;
+      }
+      /* NULL means we didn't get a full line yet */
+      if (connection->discard_request)
+      {
+        mhd_assert (MHD_CONNECTION_INIT != connection->state);
+        continue;
+      }
+      if (0 < connection->read_buffer_offset)
+        connection->state = MHD_CONNECTION_REQ_LINE_RECEIVING;
       break;
-    }
-  timeout = connection->connection_timeout;
-  if ( (0 != timeout) &&
-       (timeout <= (MHD_monotonic_time() - connection->last_activity)) )
-    {
-      MHD_connection_close (connection, MHD_REQUEST_TERMINATED_TIMEOUT_REACHED);
-      connection->in_idle = MHD_NO;
-      return MHD_YES;
-    }
-  MHD_connection_update_event_loop_info (connection);
-#if EPOLL_SUPPORT
-  switch (connection->event_loop_info)
-    {
-    case MHD_EVENT_LOOP_INFO_READ:
-      if ( (0 != (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) &&
-           (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) &&
-	   (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) )
-	{
-	  EDLL_insert (daemon->eready_head,
-		       daemon->eready_tail,
-		       connection);
-	  connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
-	}
+    case MHD_CONNECTION_URL_RECEIVED:
+      line = get_next_header_line (connection,
+                                   NULL);
+      if (MHD_CONNECTION_URL_RECEIVED != connection->state)
+        continue;
+      if (NULL == line)
+      {
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (0 == line[0])
+      {
+        connection->state = MHD_CONNECTION_HEADERS_RECEIVED;
+        connection->rq.header_size = (size_t) (connection->read_buffer
+                                               - connection->rq.method);
+        continue;
+      }
+      if (MHD_NO == process_header_line (connection,
+                                         line))
+      {
+        transmit_error_response_static (connection,
+                                        MHD_HTTP_BAD_REQUEST,
+                                        REQUEST_MALFORMED);
+        break;
+      }
+      connection->state = MHD_CONNECTION_HEADER_PART_RECEIVED;
+      continue;
+    case MHD_CONNECTION_HEADER_PART_RECEIVED:
+      line = get_next_header_line (connection,
+                                   NULL);
+      if (MHD_CONNECTION_HEADER_PART_RECEIVED != connection->state)
+        continue;
+      if (NULL == line)
+      {
+        if (connection->state != MHD_CONNECTION_HEADER_PART_RECEIVED)
+          continue;
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (MHD_NO ==
+          process_broken_line (connection,
+                               line,
+                               MHD_HEADER_KIND))
+        continue;
+      if (0 == line[0])
+      {
+        connection->state = MHD_CONNECTION_HEADERS_RECEIVED;
+        connection->rq.header_size = (size_t) (connection->read_buffer
+                                               - connection->rq.method);
+        continue;
+      }
+      continue;
+    case MHD_CONNECTION_HEADERS_RECEIVED:
+      parse_connection_headers (connection);
+      if (MHD_CONNECTION_HEADERS_RECEIVED != connection->state)
+        continue;
+      connection->state = MHD_CONNECTION_HEADERS_PROCESSED;
+      if (connection->suspended)
+        break;
+      continue;
+    case MHD_CONNECTION_HEADERS_PROCESSED:
+      call_connection_handler (connection);     /* first call */
+      if (MHD_CONNECTION_HEADERS_PROCESSED != connection->state)
+        continue;
+      if (connection->suspended)
+        continue;
+
+      if ( (NULL == connection->rp.response) &&
+           (need_100_continue (connection)) &&
+           /* If the client is already sending the payload (body)
+              there is no need to send "100 Continue" */
+           (0 == connection->read_buffer_offset) )
+      {
+        connection->state = MHD_CONNECTION_CONTINUE_SENDING;
+        break;
+      }
+      if ( (NULL != connection->rp.response) &&
+           (0 != connection->rq.remaining_upload_size) )
+      {
+        /* we refused (no upload allowed!) */
+        connection->rq.remaining_upload_size = 0;
+        /* force close, in case client still tries to upload... */
+        connection->discard_request = true;
+      }
+      connection->state = (0 == connection->rq.remaining_upload_size)
+                          ? MHD_CONNECTION_FULL_REQ_RECEIVED
+                          : MHD_CONNECTION_BODY_RECEIVING;
+      if (connection->suspended)
+        break;
+      continue;
+    case MHD_CONNECTION_CONTINUE_SENDING:
+      if (connection->continue_message_write_offset ==
+          MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE))
+      {
+        connection->state = MHD_CONNECTION_BODY_RECEIVING;
+        continue;
+      }
       break;
-    case MHD_EVENT_LOOP_INFO_WRITE:
-      if ( (0 != (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) &&
-           (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) &&
-	   (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) )
-	{
-	  EDLL_insert (daemon->eready_head,
-		       daemon->eready_tail,
-		       connection);
-	  connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
-	}
+    case MHD_CONNECTION_BODY_RECEIVING:
+      if (0 != connection->read_buffer_offset)
+      {
+        process_request_body (connection);           /* loop call */
+        if (MHD_CONNECTION_BODY_RECEIVING != connection->state)
+          continue;
+      }
+      if ( (0 == connection->rq.remaining_upload_size) ||
+           ( (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size) &&
+             (0 == connection->read_buffer_offset) &&
+             (connection->discard_request) ) )
+      {
+        if ( (connection->rq.have_chunked_upload) &&
+             (! connection->discard_request) )
+          connection->state = MHD_CONNECTION_BODY_RECEIVED;
+        else
+          connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED;
+        if (connection->suspended)
+          break;
+        continue;
+      }
       break;
-    case MHD_EVENT_LOOP_INFO_BLOCK:
-      /* we should look at this connection again in the next iteration
-	 of the event loop, as we're waiting on the application */
-      if ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) &&
-           (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED))) )
-	{
-	  EDLL_insert (daemon->eready_head,
-		       daemon->eready_tail,
-		       connection);
-	  connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
-	}
+    case MHD_CONNECTION_BODY_RECEIVED:
+      line = get_next_header_line (connection,
+                                   NULL);
+      if (connection->state != MHD_CONNECTION_BODY_RECEIVED)
+        continue;
+      if (NULL == line)
+      {
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  NULL);
+          continue;
+        }
+        if (0 < connection->read_buffer_offset)
+          connection->state = MHD_CONNECTION_FOOTER_PART_RECEIVED;
+        break;
+      }
+      if (0 == line[0])
+      {
+        connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
+        if (connection->suspended)
+          break;
+        continue;
+      }
+      if (MHD_NO == process_header_line (connection,
+                                         line))
+      {
+        transmit_error_response_static (connection,
+                                        MHD_HTTP_BAD_REQUEST,
+                                        REQUEST_MALFORMED);
+        break;
+      }
+      connection->state = MHD_CONNECTION_FOOTER_PART_RECEIVED;
+      continue;
+    case MHD_CONNECTION_FOOTER_PART_RECEIVED:
+      line = get_next_header_line (connection,
+                                   NULL);
+      if (connection->state != MHD_CONNECTION_FOOTER_PART_RECEIVED)
+        continue;
+      if (NULL == line)
+      {
+        if (connection->read_closed)
+        {
+          CONNECTION_CLOSE_ERROR (connection,
+                                  NULL);
+          continue;
+        }
+        break;
+      }
+      if (MHD_NO ==
+          process_broken_line (connection,
+                               line,
+                               MHD_FOOTER_KIND))
+        continue;
+      if (0 == line[0])
+      {
+        connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
+        if (connection->suspended)
+          break;
+        continue;
+      }
+      continue;
+    case MHD_CONNECTION_FOOTERS_RECEIVED:
+      /* The header, the body, and the footers of the request has been received,
+       * switch to the final processing of the request. */
+      connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED;
+      continue;
+    case MHD_CONNECTION_FULL_REQ_RECEIVED:
+      call_connection_handler (connection);     /* "final" call */
+      if (connection->state != MHD_CONNECTION_FULL_REQ_RECEIVED)
+        continue;
+      if (NULL == connection->rp.response)
+        break;                  /* try again next time */
+      /* Response is ready, start reply */
+      connection->state = MHD_CONNECTION_START_REPLY;
+      continue;
+    case MHD_CONNECTION_START_REPLY:
+      mhd_assert (NULL != connection->rp.response);
+      connection_switch_from_recv_to_send (connection);
+      if (MHD_NO == build_header_response (connection))
+      {
+        /* oops - close! */
+        CONNECTION_CLOSE_ERROR (connection,
+                                _ ("Closing connection (failed to create "
+                                   "response header).\n"));
+        continue;
+      }
+      connection->state = MHD_CONNECTION_HEADERS_SENDING;
       break;
-    case MHD_EVENT_LOOP_INFO_CLEANUP:
-      /* This connection is finished, nothing left to do */
+
+    case MHD_CONNECTION_HEADERS_SENDING:
+      /* no default action */
       break;
-    }
-  return MHD_connection_epoll_update_ (connection);
-#else
-  return MHD_YES;
+    case MHD_CONNECTION_HEADERS_SENT:
+#ifdef UPGRADE_SUPPORT
+      if (NULL != connection->rp.response->upgrade_handler)
+      {
+        connection->state = MHD_CONNECTION_UPGRADE;
+        /* This connection is "upgraded".  Pass socket to application. */
+        if (MHD_NO ==
+            MHD_response_execute_upgrade_ (connection->rp.response,
+                                           connection))
+        {
+          /* upgrade failed, fail hard */
+          CONNECTION_CLOSE_ERROR (connection,
+                                  NULL);
+          continue;
+        }
+        /* Response is not required anymore for this connection. */
+        if (1)
+        {
+          struct MHD_Response *const resp = connection->rp.response;
+
+          connection->rp.response = NULL;
+          MHD_destroy_response (resp);
+        }
+        continue;
+      }
+#endif /* UPGRADE_SUPPORT */
+
+      if (connection->rp.props.send_reply_body)
+      {
+        if (connection->rp.props.chunked)
+          connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY;
+        else
+          connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY;
+      }
+      else
+        connection->state = MHD_CONNECTION_FULL_REPLY_SENT;
+      continue;
+    case MHD_CONNECTION_NORMAL_BODY_READY:
+      mhd_assert (connection->rp.props.send_reply_body);
+      mhd_assert (! connection->rp.props.chunked);
+      /* nothing to do here */
+      break;
+    case MHD_CONNECTION_NORMAL_BODY_UNREADY:
+      mhd_assert (connection->rp.props.send_reply_body);
+      mhd_assert (! connection->rp.props.chunked);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+      if (NULL != connection->rp.response->crc)
+        MHD_mutex_lock_chk_ (&connection->rp.response->mutex);
 #endif
+      if (0 == connection->rp.response->total_size)
+      {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+        if (NULL != connection->rp.response->crc)
+          MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
+#endif
+        if (connection->rp.props.chunked)
+          connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT;
+        else
+          connection->state = MHD_CONNECTION_FULL_REPLY_SENT;
+        continue;
+      }
+      if (MHD_NO != try_ready_normal_body (connection))
+      {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+        if (NULL != connection->rp.response->crc)
+          MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
+#endif
+        connection->state = MHD_CONNECTION_NORMAL_BODY_READY;
+        /* Buffering for flushable socket was already enabled*/
+
+        break;
+      }
+      /* mutex was already unlocked by "try_ready_normal_body */
+      /* not ready, no socket action */
+      break;
+    case MHD_CONNECTION_CHUNKED_BODY_READY:
+      mhd_assert (connection->rp.props.send_reply_body);
+      mhd_assert (connection->rp.props.chunked);
+      /* nothing to do here */
+      break;
+    case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
+      mhd_assert (connection->rp.props.send_reply_body);
+      mhd_assert (connection->rp.props.chunked);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+      if (NULL != connection->rp.response->crc)
+        MHD_mutex_lock_chk_ (&connection->rp.response->mutex);
+#endif
+      if ( (0 == connection->rp.response->total_size) ||
+           (connection->rp.rsp_write_position ==
+            connection->rp.response->total_size) )
+      {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+        if (NULL != connection->rp.response->crc)
+          MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
+#endif
+        connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT;
+        continue;
+      }
+      if (1)
+      { /* pseudo-branch for local variables scope */
+        bool finished;
+        if (MHD_NO != try_ready_chunked_body (connection, &finished))
+        {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+          if (NULL != connection->rp.response->crc)
+            MHD_mutex_unlock_chk_ (&connection->rp.response->mutex);
+#endif
+          connection->state = finished ? MHD_CONNECTION_CHUNKED_BODY_SENT :
+                              MHD_CONNECTION_CHUNKED_BODY_READY;
+          continue;
+        }
+        /* mutex was already unlocked by try_ready_chunked_body */
+      }
+      break;
+    case MHD_CONNECTION_CHUNKED_BODY_SENT:
+      mhd_assert (connection->rp.props.send_reply_body);
+      mhd_assert (connection->rp.props.chunked);
+      mhd_assert (connection->write_buffer_send_offset <= \
+                  connection->write_buffer_append_offset);
+
+      if (MHD_NO == build_connection_chunked_response_footer (connection))
+      {
+        /* oops - close! */
+        CONNECTION_CLOSE_ERROR (connection,
+                                _ ("Closing connection (failed to create " \
+                                   "response footer)."));
+        continue;
+      }
+      mhd_assert (connection->write_buffer_send_offset < \
+                  connection->write_buffer_append_offset);
+      connection->state = MHD_CONNECTION_FOOTERS_SENDING;
+      continue;
+    case MHD_CONNECTION_FOOTERS_SENDING:
+      mhd_assert (connection->rp.props.send_reply_body);
+      mhd_assert (connection->rp.props.chunked);
+      /* no default action */
+      break;
+    case MHD_CONNECTION_FULL_REPLY_SENT:
+      if (MHD_HTTP_PROCESSING == connection->rp.responseCode)
+      {
+        /* After this type of response, we allow sending another! */
+        connection->state = MHD_CONNECTION_HEADERS_PROCESSED;
+        MHD_destroy_response (connection->rp.response);
+        connection->rp.response = NULL;
+        /* FIXME: maybe partially reset memory pool? */
+        continue;
+      }
+      /* Reset connection after complete reply */
+      connection_reset (connection,
+                        MHD_CONN_USE_KEEPALIVE == connection->keepalive &&
+                        ! connection->read_closed &&
+                        ! connection->discard_request);
+      continue;
+    case MHD_CONNECTION_CLOSED:
+      cleanup_connection (connection);
+      connection->in_idle = false;
+      return MHD_NO;
+#ifdef UPGRADE_SUPPORT
+    case MHD_CONNECTION_UPGRADE:
+      connection->in_idle = false;
+      return MHD_YES;     /* keep open */
+#endif /* UPGRADE_SUPPORT */
+    default:
+      mhd_assert (0);
+      break;
+    }
+    break;
+  }
+  if (connection_check_timedout (connection))
+  {
+    MHD_connection_close_ (connection,
+                           MHD_REQUEST_TERMINATED_TIMEOUT_REACHED);
+    connection->in_idle = false;
+    return MHD_YES;
+  }
+  MHD_connection_update_event_loop_info (connection);
+  ret = MHD_YES;
+#ifdef EPOLL_SUPPORT
+  if ( (! connection->suspended) &&
+       (0 != (daemon->options & MHD_USE_EPOLL)) )
+  {
+    ret = MHD_connection_epoll_update_ (connection);
+  }
+#endif /* EPOLL_SUPPORT */
+  connection->in_idle = false;
+  return ret;
 }
 
 
-#if EPOLL_SUPPORT
+#ifdef EPOLL_SUPPORT
 /**
  * Perform epoll() processing, possibly moving the connection back into
  * the epoll() set if needed.
@@ -2705,45 +5312,56 @@
  * @return #MHD_YES if we should continue to process the
  *         connection (not dead yet), #MHD_NO if it died
  */
-int
+enum MHD_Result
 MHD_connection_epoll_update_ (struct MHD_Connection *connection)
 {
-  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_Daemon *const daemon = connection->daemon;
 
-  if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-       (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) &&
+  mhd_assert (0 != (daemon->options & MHD_USE_EPOLL));
+
+  if ((0 != (MHD_EVENT_LOOP_INFO_PROCESS & connection->event_loop_info)) &&
+      (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)))
+  {
+    /* Make sure that connection waiting for processing will be processed */
+    EDLL_insert (daemon->eready_head,
+                 daemon->eready_tail,
+                 connection);
+    connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+  }
+
+  if ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) &&
        (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) &&
-       ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ||
-	 ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) &&
-	   ( (MHD_EVENT_LOOP_INFO_READ == connection->event_loop_info) ||
-	     (connection->read_buffer_size > connection->read_buffer_offset) ) &&
-	   (MHD_NO == connection->read_closed) ) ) )
-    {
-      /* add to epoll set */
-      struct epoll_event event;
+       ( ( (MHD_EVENT_LOOP_INFO_WRITE == connection->event_loop_info) &&
+           (0 == (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY))) ||
+         ( (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info)) &&
+           (0 == (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ) )
+  {
+    /* add to epoll set */
+    struct epoll_event event;
 
-      event.events = EPOLLIN | EPOLLOUT | EPOLLET;
-      event.data.ptr = connection;
-      if (0 != epoll_ctl (daemon->epoll_fd,
-			  EPOLL_CTL_ADD,
-			  connection->socket_fd,
-			  &event))
-	{
-#if HAVE_MESSAGES
-	  if (0 != (daemon->options & MHD_USE_DEBUG))
-	    MHD_DLOG (daemon,
-		      "Call to epoll_ctl failed: %s\n",
-		      MHD_socket_last_strerr_ ());
+    event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
+    event.data.ptr = connection;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        connection->socket_fd,
+                        &event))
+    {
+#ifdef HAVE_MESSAGES
+      if (0 != (daemon->options & MHD_USE_ERROR_LOG))
+        MHD_DLOG (daemon,
+                  _ ("Call to epoll_ctl failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
 #endif
-	  connection->state = MHD_CONNECTION_CLOSED;
-	  cleanup_connection (connection);
-	  return MHD_NO;
-	}
-      connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
+      connection->state = MHD_CONNECTION_CLOSED;
+      cleanup_connection (connection);
+      return MHD_NO;
     }
-  connection->in_idle = MHD_NO;
+    connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
+  }
   return MHD_YES;
 }
+
+
 #endif
 
 
@@ -2755,14 +5373,14 @@
 void
 MHD_set_http_callbacks_ (struct MHD_Connection *connection)
 {
-  connection->read_handler = &MHD_connection_handle_read;
-  connection->write_handler = &MHD_connection_handle_write;
-  connection->idle_handler = &MHD_connection_handle_idle;
+  connection->recv_cls = &recv_param_adapter;
 }
 
 
 /**
  * Obtain information about the given connection.
+ * The returned pointer is invalidated with the next call of this function or
+ * when the connection is closed.
  *
  * @param connection what connection to get information about
  * @param info_type what information is desired?
@@ -2771,39 +5389,94 @@
  *         (or if the @a info_type is unknown)
  * @ingroup specialized
  */
-const union MHD_ConnectionInfo *
+_MHD_EXTERN const union MHD_ConnectionInfo *
 MHD_get_connection_info (struct MHD_Connection *connection,
-                         enum MHD_ConnectionInfoType info_type, ...)
+                         enum MHD_ConnectionInfoType info_type,
+                         ...)
 {
   switch (info_type)
-    {
-#if HTTPS_SUPPORT
-    case MHD_CONNECTION_INFO_CIPHER_ALGO:
-      if (connection->tls_session == NULL)
-	return NULL;
-      connection->cipher = SSL_CIPHER_get_name (SSL_get_current_cipher (connection->tls_session));
-      return (const union MHD_ConnectionInfo *) &connection->cipher;
-    case MHD_CONNECTION_INFO_PROTOCOL:
-      if (connection->tls_session == NULL)
-	return NULL;
-      connection->protocol = SSL_CIPHER_get_version (SSL_get_current_cipher (connection->tls_session));
-      return (const union MHD_ConnectionInfo *) &connection->protocol;
-    case MHD_CONNECTION_INFO_TLS_SESSION:
-      if (connection->tls_session == NULL)
-	return NULL;
-      return (const union MHD_ConnectionInfo *) &connection->tls_session;
-#endif
-    case MHD_CONNECTION_INFO_CLIENT_ADDRESS:
-      return (const union MHD_ConnectionInfo *) &connection->addr;
-    case MHD_CONNECTION_INFO_DAEMON:
-      return (const union MHD_ConnectionInfo *) &connection->daemon;
-    case MHD_CONNECTION_INFO_CONNECTION_FD:
-      return (const union MHD_ConnectionInfo *) &connection->socket_fd;
-    case MHD_CONNECTION_INFO_SOCKET_CONTEXT:
-      return (const union MHD_ConnectionInfo *) &connection->socket_context;
-    default:
+  {
+#ifdef HTTPS_SUPPORT
+  case MHD_CONNECTION_INFO_CIPHER_ALGO:
+    if (NULL == connection->tls_session)
       return NULL;
-    };
+    if (1)
+    { /* Workaround to mute compiler warning */
+      gnutls_cipher_algorithm_t res;
+      res = gnutls_cipher_get (connection->tls_session);
+      connection->connection_info_dummy.cipher_algorithm = (int) res;
+    }
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_PROTOCOL:
+    if (NULL == connection->tls_session)
+      return NULL;
+    if (1)
+    { /* Workaround to mute compiler warning */
+      gnutls_protocol_t res;
+      res = gnutls_protocol_get_version (connection->tls_session);
+      connection->connection_info_dummy.protocol = (int) res;
+    }
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_GNUTLS_SESSION:
+    if (NULL == connection->tls_session)
+      return NULL;
+    connection->connection_info_dummy.tls_session = connection->tls_session;
+    return &connection->connection_info_dummy;
+#else  /* ! HTTPS_SUPPORT */
+  case MHD_CONNECTION_INFO_CIPHER_ALGO:
+  case MHD_CONNECTION_INFO_PROTOCOL:
+  case MHD_CONNECTION_INFO_GNUTLS_SESSION:
+#endif /* ! HTTPS_SUPPORT */
+  case MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT:
+    return NULL; /* Not implemented */
+  case MHD_CONNECTION_INFO_CLIENT_ADDRESS:
+    if (0 < connection->addr_len)
+    {
+      mhd_assert (sizeof (connection->addr) == \
+                  sizeof (connection->connection_info_dummy.client_addr));
+      memcpy (&connection->connection_info_dummy.client_addr,
+              &connection->addr,
+              sizeof(connection->addr));
+      return &connection->connection_info_dummy;
+    }
+    return NULL;
+  case MHD_CONNECTION_INFO_DAEMON:
+    connection->connection_info_dummy.daemon = connection->daemon;
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_CONNECTION_FD:
+    connection->connection_info_dummy.connect_fd = connection->socket_fd;
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_SOCKET_CONTEXT:
+    connection->connection_info_dummy.socket_context =
+      connection->socket_context;
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_CONNECTION_SUSPENDED:
+    connection->connection_info_dummy.suspended =
+      connection->suspended ? MHD_YES : MHD_NO;
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_CONNECTION_TIMEOUT:
+#if SIZEOF_UNSIGNED_INT <= (SIZEOF_UINT64_T - 2)
+    if (UINT_MAX < connection->connection_timeout_ms / 1000)
+      connection->connection_info_dummy.connection_timeout = UINT_MAX;
+    else
+#endif /* SIZEOF_UNSIGNED_INT <=(SIZEOF_UINT64_T - 2) */
+    connection->connection_info_dummy.connection_timeout =
+      (unsigned int) (connection->connection_timeout_ms / 1000);
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE:
+    if ( (MHD_CONNECTION_HEADERS_RECEIVED > connection->state) ||
+         (MHD_CONNECTION_CLOSED == connection->state) )
+      return NULL;   /* invalid, too early! */
+    connection->connection_info_dummy.header_size = connection->rq.header_size;
+    return &connection->connection_info_dummy;
+  case MHD_CONNECTION_INFO_HTTP_STATUS:
+    if (NULL == connection->rp.response)
+      return NULL;
+    connection->connection_info_dummy.http_status = connection->rp.responseCode;
+    return &connection->connection_info_dummy;
+  default:
+    return NULL;
+  }
 }
 
 
@@ -2816,53 +5489,71 @@
  * @return #MHD_YES on success, #MHD_NO if setting the option failed
  * @ingroup specialized
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_set_connection_option (struct MHD_Connection *connection,
-			   enum MHD_CONNECTION_OPTION option,
-			   ...)
+                           enum MHD_CONNECTION_OPTION option,
+                           ...)
 {
   va_list ap;
   struct MHD_Daemon *daemon;
+  unsigned int ui_val;
 
   daemon = connection->daemon;
   switch (option)
+  {
+  case MHD_CONNECTION_OPTION_TIMEOUT:
+    if (0 == connection->connection_timeout_ms)
+      connection->last_activity = MHD_monotonic_msec_counter ();
+    va_start (ap, option);
+    ui_val = va_arg (ap, unsigned int);
+    va_end (ap);
+#if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT
+    if ((UINT64_MAX / 4000 - 1) < ui_val)
     {
-    case MHD_CONNECTION_OPTION_TIMEOUT:
-      if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-	   (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-	MHD_PANIC ("Failed to acquire cleanup mutex\n");
-      if (MHD_YES != connection->suspended)
-        {
-          if (connection->connection_timeout == daemon->connection_timeout)
-            XDLL_remove (daemon->normal_timeout_head,
-                         daemon->normal_timeout_tail,
-                         connection);
-          else
-            XDLL_remove (daemon->manual_timeout_head,
-                         daemon->manual_timeout_tail,
-                         connection);
-        }
-      va_start (ap, option);
-      connection->connection_timeout = va_arg (ap, unsigned int);
-      va_end (ap);
-      if (MHD_YES != connection->suspended)
-        {
-          if (connection->connection_timeout == daemon->connection_timeout)
-            XDLL_insert (daemon->normal_timeout_head,
-                         daemon->normal_timeout_tail,
-                         connection);
-          else
-            XDLL_insert (daemon->manual_timeout_head,
-                         daemon->manual_timeout_tail,
-                         connection);
-        }
-      if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-	   (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-	MHD_PANIC ("Failed to release cleanup mutex\n");
-      return MHD_YES;
-    default:
-      return MHD_NO;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("The specified connection timeout (%u) is too " \
+                   "large. Maximum allowed value (%" PRIu64 ") will be used " \
+                   "instead.\n"),
+                ui_val,
+                (UINT64_MAX / 4000 - 1));
+#endif
+      ui_val = UINT64_MAX / 4000 - 1;
     }
+#endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */
+    if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+    {
+#if defined(MHD_USE_THREADS)
+      MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+      if (! connection->suspended)
+      {
+        if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
+          XDLL_remove (daemon->normal_timeout_head,
+                       daemon->normal_timeout_tail,
+                       connection);
+        else
+          XDLL_remove (daemon->manual_timeout_head,
+                       daemon->manual_timeout_tail,
+                       connection);
+        connection->connection_timeout_ms = ui_val * 1000;
+        if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
+          XDLL_insert (daemon->normal_timeout_head,
+                       daemon->normal_timeout_tail,
+                       connection);
+        else
+          XDLL_insert (daemon->manual_timeout_head,
+                       daemon->manual_timeout_tail,
+                       connection);
+      }
+#if defined(MHD_USE_THREADS)
+      MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+    }
+    return MHD_YES;
+  default:
+    return MHD_NO;
+  }
 }
 
 
@@ -2870,48 +5561,267 @@
  * Queue a response to be transmitted to the client (as soon as
  * possible but after #MHD_AccessHandlerCallback returns).
  *
+ * For any active connection this function must be called
+ * only by #MHD_AccessHandlerCallback callback.
+ * For suspended connection this function can be called at any moment. Response
+ * will be sent as soon as connection is resumed.
+ *
+ * If HTTP specifications require use no body in reply, like @a status_code with
+ * value 1xx, the response body is automatically not sent even if it is present
+ * in the response. No "Content-Length" or "Transfer-Encoding" headers are
+ * generated and added.
+ *
+ * When the response is used to respond HEAD request or used with @a status_code
+ * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length"
+ * header is added automatically based the size of the body in the response.
+ * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced
+ * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead
+ * of "Content-Length" header.
+ *
+ * In situations, where reply body is required, like answer for the GET request
+ * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body
+ * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1)
+ * are added automatically.
+ * In practice, the same response object can be used to respond to both HEAD and
+ * GET requests.
+ *
  * @param connection the connection identifying the client
  * @param status_code HTTP status code (i.e. #MHD_HTTP_OK)
- * @param response response to transmit
- * @return #MHD_NO on error (i.e. reply already sent),
+ * @param response response to transmit, the NULL is tolerated
+ * @return #MHD_NO on error (reply already sent, response is NULL),
  *         #MHD_YES on success or if message has been queued
  * @ingroup response
+ * @sa #MHD_AccessHandlerCallback
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_queue_response (struct MHD_Connection *connection,
                     unsigned int status_code,
                     struct MHD_Response *response)
 {
-  if ( (NULL == connection) ||
-       (NULL == response) ||
-       (NULL != connection->response) ||
-       ( (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) &&
-	 (MHD_CONNECTION_FOOTERS_RECEIVED != connection->state) ) )
+  struct MHD_Daemon *daemon;
+  bool reply_icy;
+
+  reply_icy = (0 != (status_code & MHD_ICY_FLAG));
+  status_code &= ~MHD_ICY_FLAG;
+  if ((NULL == connection) || (NULL == response))
     return MHD_NO;
+
+  daemon = connection->daemon;
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if ( (! connection->suspended) &&
+       (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) &&
+       (! MHD_thread_ID_match_current_ (connection->pid)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Attempted to queue response on wrong thread!\n"));
+#endif
+    return MHD_NO;
+  }
+#endif
+
+  if (daemon->shutdown)
+    return MHD_YES; /* If daemon was shut down in parallel,
+                     * response will be aborted now or on later stage. */
+
+  if ( (NULL != connection->rp.response) ||
+       ( (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) &&
+         (MHD_CONNECTION_FULL_REQ_RECEIVED != connection->state) ) )
+    return MHD_NO;
+
+#ifdef UPGRADE_SUPPORT
+  if (NULL != response->upgrade_handler)
+  {
+    struct MHD_HTTP_Res_Header *conn_header;
+    if (0 == (daemon->options & MHD_ALLOW_UPGRADE))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Attempted 'upgrade' connection on daemon without" \
+                   " MHD_ALLOW_UPGRADE option!\n"));
+#endif
+      return MHD_NO;
+    }
+    if (MHD_HTTP_SWITCHING_PROTOCOLS != status_code)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Application used invalid status code for" \
+                   " 'upgrade' response!\n"));
+#endif
+      return MHD_NO;
+    }
+    if (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Application used invalid response" \
+                   " without \"Connection\" header!\n"));
+#endif
+      return MHD_NO;
+    }
+    conn_header = response->first_header;
+    mhd_assert (NULL != conn_header);
+    mhd_assert (MHD_str_equal_caseless_ (conn_header->header,
+                                         MHD_HTTP_HEADER_CONNECTION));
+    if (! MHD_str_has_s_token_caseless_ (conn_header->value,
+                                         "upgrade"))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Application used invalid response" \
+                   " without \"upgrade\" token in" \
+                   " \"Connection\" header!\n"));
+#endif
+      return MHD_NO;
+    }
+    if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Connection \"Upgrade\" can be used only " \
+                   "with HTTP/1.1 connections!\n"));
+#endif
+      return MHD_NO;
+    }
+  }
+#endif /* UPGRADE_SUPPORT */
+  if (MHD_HTTP_SWITCHING_PROTOCOLS == status_code)
+  {
+#ifdef UPGRADE_SUPPORT
+    if (NULL == response->upgrade_handler)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Application used status code 101 \"Switching Protocols\" " \
+                   "with non-'upgrade' response!\n"));
+#endif /* HAVE_MESSAGES */
+      return MHD_NO;
+    }
+#else  /* ! UPGRADE_SUPPORT */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Application used status code 101 \"Switching Protocols\", " \
+                 "but this MHD was built without \"Upgrade\" support!\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_NO;
+#endif /* ! UPGRADE_SUPPORT */
+  }
+  if ( (100 > status_code) ||
+       (999 < status_code) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Refused wrong status code (%u). " \
+                 "HTTP requires three digits status code!\n"),
+              status_code);
+#endif
+    return MHD_NO;
+  }
+  if (200 > status_code)
+  {
+    if (MHD_HTTP_VER_1_0 == connection->rq.http_ver)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Wrong status code (%u) refused. " \
+                   "HTTP/1.0 clients do not support 1xx status codes!\n"),
+                (status_code));
+#endif
+      return MHD_NO;
+    }
+    if (0 != (response->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT
+                                 | MHD_RF_HTTP_1_0_SERVER)))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Wrong status code (%u) refused. " \
+                   "HTTP/1.0 reply mode does not support 1xx status codes!\n"),
+                (status_code));
+#endif
+      return MHD_NO;
+    }
+  }
+  if ( (MHD_HTTP_MTHD_CONNECT == connection->rq.http_mthd) &&
+       (2 == status_code / 100) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Successful (%u) response code cannot be used to answer " \
+                 "\"CONNECT\" request!\n"),
+              (status_code));
+#endif
+    return MHD_NO;
+  }
+
+  if ( (0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) &&
+       (RP_BODY_HEADERS_ONLY < is_reply_body_needed (connection, status_code)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("HEAD-only response cannot be used when the request requires "
+                 "reply body to be sent!\n"));
+#endif
+    return MHD_NO;
+  }
+
+#ifdef HAVE_MESSAGES
+  if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) &&
+       (0 != (MHD_RAF_HAS_CONTENT_LENGTH & response->flags_auto)) )
+  {
+    MHD_DLOG (daemon,
+              _ ("The response has application-defined \"Content-Length\" " \
+                 "header. The reply to the request will be not " \
+                 "HTTP-compliant and may result in hung connection or " \
+                 "other problems!\n"));
+  }
+#endif
+
   MHD_increment_response_rc (response);
-  connection->response = response;
-  connection->responseCode = status_code;
-  if ( (NULL != connection->method) &&
-       (MHD_str_equal_caseless_ (connection->method, MHD_HTTP_METHOD_HEAD)) )
-    {
-      /* if this is a "HEAD" request, pretend that we
-         have already sent the full message body */
-      connection->response_write_position = response->total_size;
-    }
-  if ( (MHD_CONNECTION_HEADERS_PROCESSED == connection->state) &&
-       (NULL != connection->method) &&
-       ( (MHD_str_equal_caseless_ (connection->method,
-			   MHD_HTTP_METHOD_POST)) ||
-	 (MHD_str_equal_caseless_ (connection->method,
-			   MHD_HTTP_METHOD_PUT))) )
-    {
-      /* response was queued "early", refuse to read body / footers or
-         further requests! */
-      connection->read_closed = MHD_YES;
-      connection->state = MHD_CONNECTION_FOOTERS_RECEIVED;
-    }
-  if (MHD_NO == connection->in_idle)
+  connection->rp.response = response;
+  connection->rp.responseCode = status_code;
+  connection->rp.responseIcy = reply_icy;
+#if defined(_MHD_HAVE_SENDFILE)
+  if ( (response->fd == -1) ||
+       (response->is_pipe) ||
+       (0 != (connection->daemon->options & MHD_USE_TLS))
+#if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \
+       defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE)
+       || (! daemon->sigpipe_blocked && ! connection->sk_spipe_suppress)
+#endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED &&
+          MHD_SEND_SPIPE_SUPPRESS_POSSIBLE */
+       )
+    connection->rp.resp_sender = MHD_resp_sender_std;
+  else
+    connection->rp.resp_sender = MHD_resp_sender_sendfile;
+#endif /* _MHD_HAVE_SENDFILE */
+  /* FIXME: if 'is_pipe' is set, TLS is off, and we have *splice*, we could use splice()
+     to avoid two user-space copies... */
+
+  if ( (MHD_HTTP_MTHD_HEAD == connection->rq.http_mthd) ||
+       (MHD_HTTP_OK > status_code) ||
+       (MHD_HTTP_NO_CONTENT == status_code) ||
+       (MHD_HTTP_NOT_MODIFIED == status_code) )
+  {
+    /* if this is a "HEAD" request, or a status code for
+       which a body is not allowed, pretend that we
+       have already sent the full message body. */
+    /* TODO: remove the next assignment, use 'rp_props.send_reply_body' in
+     * checks */
+    connection->rp.rsp_write_position = response->total_size;
+  }
+  if (MHD_CONNECTION_HEADERS_PROCESSED == connection->state)
+  {
+    /* response was queued "early", refuse to read body / footers or
+       further requests! */
+    connection->discard_request = true;
+    connection->state = MHD_CONNECTION_START_REPLY;
+    connection->rq.remaining_upload_size = 0;
+  }
+  if (! connection->in_idle)
     (void) MHD_connection_handle_idle (connection);
+  MHD_update_last_activity_ (connection);
   return MHD_YES;
 }
 
diff --git a/src/microhttpd/connection.h b/src/microhttpd/connection.h
index 07feec2..693e26f 100644
--- a/src/microhttpd/connection.h
+++ b/src/microhttpd/connection.h
@@ -22,6 +22,7 @@
  * @brief  Methods for managing connections
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #ifndef CONNECTION_H
@@ -29,6 +30,52 @@
 
 #include "internal.h"
 
+/**
+ * Error code similar to EGAIN or EINTR
+ */
+#define MHD_ERR_AGAIN_ (-3073)
+
+/**
+ * Connection was hard-closed by remote peer.
+ */
+#define MHD_ERR_CONNRESET_ (-3074)
+
+/**
+ * Connection is not connected anymore due to
+ * network error or any other reason.
+ */
+#define MHD_ERR_NOTCONN_ (-3075)
+
+/**
+ * "Not enough memory" error code
+ */
+#define MHD_ERR_NOMEM_ (-3076)
+
+/**
+ * "Bad FD" error code
+ */
+#define MHD_ERR_BADF_ (-3077)
+
+/**
+ * Error code similar to EINVAL
+ */
+#define MHD_ERR_INVAL_ (-3078)
+
+/**
+ * Argument values are not supported
+ */
+#define MHD_ERR_OPNOTSUPP_ (-3079)
+
+/**
+ * Socket is shut down for writing or no longer connected
+ */
+#define MHD_ERR_PIPE_ (-3080)
+
+/**
+ * General TLS encryption or decryption error
+ */
+#define MHD_ERR_TLS_ (-4097)
+
 
 /**
  * Set callbacks for this connection to those for HTTP.
@@ -42,15 +89,15 @@
 /**
  * This function handles a particular connection when it has been
  * determined that there is data to be read off a socket. All
- * implementations (multithreaded, external select, internal select)
+ * implementations (multithreaded, external polling, internal polling)
  * call this function to handle reads.
  *
  * @param connection connection to handle
- * @return always MHD_YES (we should continue to process the
- *         connection)
+ * @param socket_error set to true if socket error was detected
  */
-int
-MHD_connection_handle_read (struct MHD_Connection *connection);
+void
+MHD_connection_handle_read (struct MHD_Connection *connection,
+                            bool socket_error);
 
 
 /**
@@ -60,51 +107,101 @@
  * call this function
  *
  * @param connection connection to handle
- * @return always MHD_YES (we should continue to process the
- *         connection)
  */
-int
+void
 MHD_connection_handle_write (struct MHD_Connection *connection);
 
 
 /**
  * This function was created to handle per-connection processing that
- * has to happen even if the socket cannot be read or written to.  All
- * implementations (multithreaded, external select, internal select)
+ * has to happen even if the socket cannot be read or written to.
+ * All implementations (multithreaded, external select, internal select)
  * call this function.
+ * @remark To be called only from thread that process connection's
+ * recv(), send() and response.
  *
  * @param connection connection to handle
- * @return MHD_YES if we should continue to process the
- *         connection (not dead yet), MHD_NO if it died
+ * @return #MHD_YES if we should continue to process the
+ *         connection (not dead yet), #MHD_NO if it died
  */
-int
+enum MHD_Result
 MHD_connection_handle_idle (struct MHD_Connection *connection);
 
 
 /**
+ * Mark connection as "closed".
+ * @remark To be called from any thread.
+ *
+ * @param connection connection to close
+ */
+void
+MHD_connection_mark_closed_ (struct MHD_Connection *connection);
+
+
+/**
  * Close the given connection and give the
  * specified termination code to the user.
+ * @remark To be called only from thread that
+ * process connection's recv(), send() and response.
  *
  * @param connection connection to close
  * @param termination_code termination reason to give
  */
 void
-MHD_connection_close (struct MHD_Connection *connection,
-		      enum MHD_RequestTerminationCode termination_code);
+MHD_connection_close_ (struct MHD_Connection *connection,
+                       enum MHD_RequestTerminationCode termination_code);
 
 
-#if EPOLL_SUPPORT
+#ifdef HTTPS_SUPPORT
+/**
+ * Stop TLS forwarding on upgraded connection and
+ * reflect remote disconnect state to socketpair.
+ * @param connection the upgraded connection
+ */
+void
+MHD_connection_finish_forward_ (struct MHD_Connection *connection);
+
+#else  /* ! HTTPS_SUPPORT */
+#define MHD_connection_finish_forward_(conn) (void) conn
+#endif /* ! HTTPS_SUPPORT */
+
+
+#ifdef EPOLL_SUPPORT
 /**
  * Perform epoll processing, possibly moving the connection back into
  * the epoll set if needed.
  *
  * @param connection connection to process
- * @return MHD_YES if we should continue to process the
- *         connection (not dead yet), MHD_NO if it died
+ * @return #MHD_YES if we should continue to process the
+ *         connection (not dead yet), #MHD_NO if it died
  */
-int
+enum MHD_Result
 MHD_connection_epoll_update_ (struct MHD_Connection *connection);
+
 #endif
 
+/**
+ * Update the 'last_activity' field of the connection to the current time
+ * and move the connection to the head of the 'normal_timeout' list if
+ * the timeout for the connection uses the default value.
+ *
+ * @param connection the connection that saw some activity
+ */
+void
+MHD_update_last_activity_ (struct MHD_Connection *connection);
+
+
+/**
+ * Allocate memory from connection's memory pool.
+ * If memory pool doesn't have enough free memory but read or write buffer
+ * have some unused memory, the size of the buffer will be reduced as needed.
+ * @param connection the connection to use
+ * @param size the size of allocated memory area
+ * @return pointer to allocated memory region in the pool or
+ *         NULL if no memory is available
+ */
+void *
+MHD_connection_alloc_memory_ (struct MHD_Connection *connection,
+                              size_t size);
 
 #endif
diff --git a/src/microhttpd/connection_https.c b/src/microhttpd/connection_https.c
index 83c2814..5421d5b 100644
--- a/src/microhttpd/connection_https.c
+++ b/src/microhttpd/connection_https.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008, 2010 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2015-2021 Karlson2k (Evgeny Grin)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -24,145 +25,152 @@
  *         compiled if ENABLE_HTTPS is set.
  * @author Sagie Amir
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "internal.h"
 #include "connection.h"
+#include "connection_https.h"
 #include "memorypool.h"
 #include "response.h"
-#include "reason_phrase.h"
-#include <openssl/ssl.h>
+#include "mhd_mono_clock.h"
+#include <gnutls/gnutls.h>
+#include "mhd_send.h"
+
+
+/**
+ * Callback for receiving data from the socket.
+ *
+ * @param connection the MHD_Connection structure
+ * @param other where to write received data to
+ * @param i maximum size of other (in bytes)
+ * @return positive value for number of bytes actually received or
+ *         negative value for error number MHD_ERR_xxx_
+ */
+static ssize_t
+recv_tls_adapter (struct MHD_Connection *connection,
+                  void *other,
+                  size_t i)
+{
+  ssize_t res;
+
+  if (i > SSIZE_MAX)
+    i = SSIZE_MAX;
+
+  res = gnutls_record_recv (connection->tls_session,
+                            other,
+                            i);
+  if ( (GNUTLS_E_AGAIN == res) ||
+       (GNUTLS_E_INTERRUPTED == res) )
+  {
+#ifdef EPOLL_SUPPORT
+    if (GNUTLS_E_AGAIN == res)
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+#endif
+    /* Any network errors means that buffer is empty. */
+    connection->tls_read_ready = false;
+    return MHD_ERR_AGAIN_;
+  }
+  if (res < 0)
+  {
+    connection->tls_read_ready = false;
+    if ( (GNUTLS_E_DECRYPTION_FAILED == res) ||
+         (GNUTLS_E_INVALID_SESSION == res) ||
+         (GNUTLS_E_DECOMPRESSION_FAILED == res) ||
+         (GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER == res) ||
+         (GNUTLS_E_UNSUPPORTED_VERSION_PACKET == res) ||
+         (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == res) ||
+         (GNUTLS_E_UNEXPECTED_PACKET == res) ||
+         (GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET == res) ||
+         (GNUTLS_E_EXPIRED == res) ||
+         (GNUTLS_E_REHANDSHAKE == res) )
+      return MHD_ERR_TLS_;
+    if ( (GNUTLS_E_PULL_ERROR == res) ||
+         (GNUTLS_E_INTERNAL_ERROR == res) ||
+         (GNUTLS_E_CRYPTODEV_IOCTL_ERROR == res) ||
+         (GNUTLS_E_CRYPTODEV_DEVICE_ERROR == res) )
+      return MHD_ERR_PIPE_;
+#if defined(GNUTLS_E_PREMATURE_TERMINATION)
+    if (GNUTLS_E_PREMATURE_TERMINATION == res)
+      return MHD_ERR_CONNRESET_;
+#elif defined(GNUTLS_E_UNEXPECTED_PACKET_LENGTH)
+    if (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == res)
+      return MHD_ERR_CONNRESET_;
+#endif /* GNUTLS_E_UNEXPECTED_PACKET_LENGTH */
+    if (GNUTLS_E_MEMORY_ERROR == res)
+      return MHD_ERR_NOMEM_;
+    /* Treat any other error as a hard error. */
+    return MHD_ERR_NOTCONN_;
+  }
+
+#ifdef EPOLL_SUPPORT
+  /* Unlike non-TLS connections, do not reset "read-ready" if
+   * received amount smaller than provided amount, as TLS
+   * connections may receive data by fixed-size chunks. */
+#endif /* EPOLL_SUPPORT */
+
+  /* Check whether TLS buffers still have some unread data. */
+  connection->tls_read_ready =
+    ( ((size_t) res == i) &&
+      (0 != gnutls_record_check_pending (connection->tls_session)) );
+  return res;
+}
 
 
 /**
  * Give gnuTLS chance to work on the TLS handshake.
  *
  * @param connection connection to handshake on
- * @return #MHD_YES on error or if the handshake is progressing
- *         #MHD_NO if the handshake has completed successfully
- *         and we should start to read/write data
+ * @return true if the handshake has completed successfully
+ *         and we should start to read/write data,
+ *         false is handshake in progress or in case
+ *         of error
  */
-static int
-run_tls_handshake (struct MHD_Connection *connection)
+bool
+MHD_run_tls_handshake_ (struct MHD_Connection *connection)
 {
   int ret;
-  connection->last_activity = MHD_monotonic_time();
-  if (connection->state == MHD_TLS_CONNECTION_INIT)
+
+  if ((MHD_TLS_CONN_INIT == connection->tls_state) ||
+      (MHD_TLS_CONN_HANDSHAKING == connection->tls_state))
+  {
+#if 0
+    /* According to real-live testing, Nagel's Algorithm is not blocking
+     * partial packets on just connected sockets on modern OSes. As TLS setup
+     * is performed as the fist action upon socket connection, the next
+     * optimisation typically is not required. If any specific OS will
+     * require this optimization, it could be enabled by allowing the next
+     * lines for this specific OS. */
+    if (_MHD_ON != connection->sk_nodelay)
+      MHD_connection_set_nodelay_state_ (connection, true);
+#endif
+    ret = gnutls_handshake (connection->tls_session);
+    if (ret == GNUTLS_E_SUCCESS)
     {
-      ret = SSL_accept (connection->tls_session);
-      if (ret == 1)
-	{
-	  /* set connection state to enable HTTP processing */
-	  connection->state = MHD_CONNECTION_INIT;
-	  return MHD_YES;
-	}
-      int error = SSL_get_error (connection->tls_session, ret);
-      if ( (error == SSL_ERROR_WANT_READ) ||
-	   (error == SSL_ERROR_WANT_WRITE) )
-	{
-	  /* handshake not done */
-	  return MHD_YES;
-	}
-      /* handshake failed */
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-		"Error: received handshake message out of context\n");
-#endif
-      MHD_connection_close (connection,
-			    MHD_REQUEST_TERMINATED_WITH_ERROR);
-      return MHD_YES;
+      /* set connection TLS state to enable HTTP processing */
+      connection->tls_state = MHD_TLS_CONN_CONNECTED;
+      MHD_update_last_activity_ (connection);
+      return true;
     }
-  return MHD_NO;
-}
-
-
-/**
- * This function handles a particular SSL/TLS connection when
- * it has been determined that there is data to be read off a
- * socket. Message processing is done by message type which is
- * determined by peeking into the first message type byte of the
- * stream.
- *
- * Error message handling: all fatal level messages cause the
- * connection to be terminated.
- *
- * Application data is forwarded to the underlying daemon for
- * processing.
- *
- * @param connection the source connection
- * @return always #MHD_YES (we should continue to process the connection)
- */
-static int
-MHD_tls_connection_handle_read (struct MHD_Connection *connection)
-{
-  if (MHD_YES == run_tls_handshake (connection))
-    return MHD_YES;
-  return MHD_connection_handle_read (connection);
-}
-
-
-/**
- * This function was created to handle writes to sockets when it has
- * been determined that the socket can be written to. This function
- * will forward all write requests to the underlying daemon unless
- * the connection has been marked for closing.
- *
- * @return always #MHD_YES (we should continue to process the connection)
- */
-static int
-MHD_tls_connection_handle_write (struct MHD_Connection *connection)
-{
-  if (MHD_YES == run_tls_handshake (connection))
-    return MHD_YES;
-  return MHD_connection_handle_write (connection);
-}
-
-
-/**
- * This function was created to handle per-connection processing that
- * has to happen even if the socket cannot be read or written to.  All
- * implementations (multithreaded, external select, internal select)
- * call this function.
- *
- * @param connection being handled
- * @return #MHD_YES if we should continue to process the
- *         connection (not dead yet), #MHD_NO if it died
- */
-static int
-MHD_tls_connection_handle_idle (struct MHD_Connection *connection)
-{
-  unsigned int timeout;
-
-#if DEBUG_STATES
-  MHD_DLOG (connection->daemon,
-            "%s: state: %s\n",
-            __FUNCTION__,
-            MHD_state_to_string (connection->state));
-#endif
-  timeout = connection->connection_timeout;
-  if ( (timeout != 0) && (timeout <= (MHD_monotonic_time() - connection->last_activity)))
-    MHD_connection_close (connection,
-			  MHD_REQUEST_TERMINATED_TIMEOUT_REACHED);
-  switch (connection->state)
+    if ( (GNUTLS_E_AGAIN == ret) ||
+         (GNUTLS_E_INTERRUPTED == ret) )
     {
-      /* on newly created connections we might reach here before any reply has been received */
-    case MHD_TLS_CONNECTION_INIT:
-      break;
-      /* close connection if necessary */
-    case MHD_CONNECTION_CLOSED:
-      SSL_shutdown (connection->tls_session);
-      return MHD_connection_handle_idle (connection);
-    default:
-      if ( (0 != SSL_pending (connection->tls_session)) &&
-	   (MHD_YES != MHD_tls_connection_handle_read (connection)) )
-	return MHD_YES;
-      return MHD_connection_handle_idle (connection);
+      connection->tls_state = MHD_TLS_CONN_HANDSHAKING;
+      /* handshake not done */
+      return false;
     }
-#if EPOLL_SUPPORT
-  return MHD_connection_epoll_update_ (connection);
-#else
-  return MHD_YES;
+    /* handshake failed */
+    connection->tls_state = MHD_TLS_CONN_TLS_FAILED;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Error: received handshake message out of context.\n"));
 #endif
+    MHD_connection_close_ (connection,
+                           MHD_REQUEST_TERMINATED_WITH_ERROR);
+    return false;
+  }
+  return true;
 }
 
 
@@ -175,9 +183,39 @@
 void
 MHD_set_https_callbacks (struct MHD_Connection *connection)
 {
-  connection->read_handler = &MHD_tls_connection_handle_read;
-  connection->write_handler = &MHD_tls_connection_handle_write;
-  connection->idle_handler = &MHD_tls_connection_handle_idle;
+  connection->recv_cls = &recv_tls_adapter;
 }
 
+
+/**
+ * Initiate shutdown of TLS layer of connection.
+ *
+ * @param connection to use
+ * @return true if succeed, false otherwise.
+ */
+bool
+MHD_tls_connection_shutdown (struct MHD_Connection *connection)
+{
+  if (MHD_TLS_CONN_WR_CLOSED > connection->tls_state)
+  {
+    const int res =
+      gnutls_bye (connection->tls_session, GNUTLS_SHUT_WR);
+    if (GNUTLS_E_SUCCESS == res)
+    {
+      connection->tls_state = MHD_TLS_CONN_WR_CLOSED;
+      return true;
+    }
+    if ((GNUTLS_E_AGAIN == res) ||
+        (GNUTLS_E_INTERRUPTED == res))
+    {
+      connection->tls_state = MHD_TLS_CONN_WR_CLOSING;
+      return true;
+    }
+    else
+      connection->tls_state = MHD_TLS_CONN_TLS_FAILED;
+  }
+  return false;
+}
+
+
 /* end of connection_https.c */
diff --git a/src/microhttpd/connection_https.h b/src/microhttpd/connection_https.h
index 02ffb52..58b7f61 100644
--- a/src/microhttpd/connection_https.h
+++ b/src/microhttpd/connection_https.h
@@ -28,15 +28,53 @@
 
 #include "internal.h"
 
-#if HTTPS_SUPPORT
+#ifdef HTTPS_SUPPORT
 /**
  * Set connection callback function to be used through out
  * the processing of this secure connection.
  *
  * @param connection which callbacks should be modified
  */
-void 
+void
 MHD_set_https_callbacks (struct MHD_Connection *connection);
-#endif
+
+
+/**
+ * Give gnuTLS chance to work on the TLS handshake.
+ *
+ * @param connection connection to handshake on
+ * @return true if the handshake has completed successfully
+ *         and we should start to read/write data,
+ *         false is handshake in progress or in case
+ *         of error
+ */
+bool
+MHD_run_tls_handshake_ (struct MHD_Connection *connection);
+
+
+/**
+ * Initiate shutdown of TLS layer of connection.
+ *
+ * @param connection to use
+ * @return true if succeed, false otherwise.
+ */
+bool
+MHD_tls_connection_shutdown (struct MHD_Connection *connection);
+
+/**
+ * Callback for writing data to the socket.
+ *
+ * @param connection the MHD connection structure
+ * @param other data to write
+ * @param i number of bytes to write
+ * @return positive value for number of bytes actually sent or
+ *         negative value for error number MHD_ERR_xxx_
+ */
+ssize_t
+send_tls_adapter (struct MHD_Connection *connection,
+                  const void *other,
+                  size_t i);
+
+#endif /* HTTPS_SUPPORT */
 
 #endif
diff --git a/src/microhttpd/daemon.c b/src/microhttpd/daemon.c
index 9247fba..df4038f 100644
--- a/src/microhttpd/daemon.c
+++ b/src/microhttpd/daemon.c
@@ -1,6 +1,7 @@
 /*
   This file is part of libmicrohttpd
-  Copyright (C) 2007-2014 Daniel Pittman and Christian Grothoff
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+  Copyright (C) 2015-2021 Evgeny Grin (Karlson2k)
 
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
@@ -23,60 +24,62 @@
  * @brief  A minimal-HTTP server library
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
-#if defined(_WIN32) && !defined(__CYGWIN__)
-/* override small default value */
-#define FD_SETSIZE 1024
-#define MHD_DEFAULT_FD_SETSIZE 64
-#else
-#define MHD_DEFAULT_FD_SETSIZE FD_SETSIZE
-#endif
 #include "platform.h"
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#include "mhd_threads.h"
+#endif
 #include "internal.h"
 #include "response.h"
 #include "connection.h"
 #include "memorypool.h"
-#include <limits.h>
+#include "mhd_limits.h"
 #include "autoinit_funcs.h"
+#include "mhd_mono_clock.h"
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#include "mhd_locks.h"
+#endif
+#include "mhd_sockets.h"
+#include "mhd_itc.h"
+#include "mhd_compat.h"
+#include "mhd_send.h"
+#include "mhd_align.h"
+#include "mhd_str.h"
 
-#if HAVE_SEARCH_H
+#ifdef MHD_USE_SYS_TSEARCH
 #include <search.h>
-#else
+#else  /* ! MHD_USE_SYS_TSEARCH */
 #include "tsearch.h"
-#endif
+#endif /* ! MHD_USE_SYS_TSEARCH */
 
-#if HTTPS_SUPPORT
+#ifdef HTTPS_SUPPORT
 #include "connection_https.h"
-#include <openssl/ssl.h>
-#endif
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+#endif /* HTTPS_SUPPORT */
 
-#if defined(HAVE_POLL_H) && defined(HAVE_POLL)
-#include <poll.h>
-#endif
-
-#ifdef LINUX
-#include <sys/sendfile.h>
-#endif
-
-#ifdef _WIN32
+#if defined(_WIN32) && ! defined(__CYGWIN__)
 #ifndef WIN32_LEAN_AND_MEAN
 #define WIN32_LEAN_AND_MEAN 1
 #endif /* !WIN32_LEAN_AND_MEAN */
 #include <windows.h>
-#include <process.h>
 #endif
 
-#ifndef HAVE_ACCEPT4
-#define HAVE_ACCEPT4 0
-#endif
+#ifdef MHD_USE_POSIX_THREADS
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif /* HAVE_SIGNAL_H */
+#endif /* MHD_USE_POSIX_THREADS */
 
 /**
  * Default connection limit.
  */
-#ifndef WINDOWS
-#define MHD_MAX_CONNECTIONS_DEFAULT FD_SETSIZE - 4
+#ifdef MHD_POSIX_SOCKETS
+#define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 4)
 #else
-#define MHD_MAX_CONNECTIONS_DEFAULT FD_SETSIZE
+#define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 2)
 #endif
 
 /**
@@ -84,93 +87,140 @@
  */
 #define MHD_POOL_SIZE_DEFAULT (32 * 1024)
 
-#ifdef TCP_FASTOPEN
+
+/* Forward declarations. */
+
+
 /**
- * Default TCP fastopen queue size.
+ * Global initialisation function.
  */
-#define MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT 10
-#endif
+void
+MHD_init (void);
 
 /**
- * Print extra messages with reasons for closing
- * sockets? (only adds non-error messages).
+ * Global deinitialisation function.
  */
-#define DEBUG_CLOSE MHD_NO
+void
+MHD_fini (void);
 
 /**
- * Print extra messages when establishing
- * connections? (only adds non-error messages).
- */
-#define DEBUG_CONNECT MHD_NO
-
-#ifndef LINUX
-#ifndef MSG_NOSIGNAL
-#define MSG_NOSIGNAL 0
-#endif
-#endif
-
-#ifndef SOCK_CLOEXEC
-#define SOCK_CLOEXEC 0
-#endif
-
-#ifndef EPOLL_CLOEXEC
-#define EPOLL_CLOEXEC 0
-#endif
-
-
-/**
- * Default implementation of the panic function,
- * prints an error message and aborts.
+ * Close all connections for the daemon.
+ * Must only be called when MHD_Daemon::shutdown was set to true.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
  *
- * @param cls unused
- * @param file name of the file with the problem
- * @param line line number with the problem
- * @param reason error message with details
+ * @param daemon daemon to close down
  */
 static void
-mhd_panic_std (void *cls,
-	       const char *file,
-	       unsigned int line,
-	       const char *reason)
-{
-#if HAVE_MESSAGES
-  fprintf (stderr, "Fatal error in GNU libmicrohttpd %s:%u: %s\n",
-	   file, line, reason);
-#endif
-  abort ();
-}
+close_all_connections (struct MHD_Daemon *daemon);
 
+#ifdef EPOLL_SUPPORT
 
 /**
- * Handler for fatal errors.
+ * Do epoll()-based processing.
+ *
+ * @param daemon daemon to run poll loop for
+ * @param millisec the maximum time in milliseconds to wait for events,
+ *                 set to '0' for non-blocking processing,
+ *                 set to '-1' to wait indefinitely.
+ * @return #MHD_NO on serious errors, #MHD_YES on success
  */
-MHD_PanicCallback mhd_panic;
+static enum MHD_Result
+MHD_epoll (struct MHD_Daemon *daemon,
+           int32_t millisec);
 
-/**
- * Closure argument for "mhd_panic".
- */
-void *mhd_panic_cls;
+#endif /* EPOLL_SUPPORT */
 
-#ifdef _WIN32
+
+#if defined(MHD_WINSOCK_SOCKETS)
 /**
  * Track initialization of winsock
  */
 static int mhd_winsock_inited_ = 0;
+#endif /* MHD_WINSOCK_SOCKETS */
+
+#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
+/**
+ * Do nothing - global initialisation is
+ * performed by library constructor.
+ */
+#define MHD_check_global_init_() (void) 0
+#else  /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
+/**
+ * Track global initialisation
+ */
+volatile int global_init_count = 0;
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+/**
+ * Global initialisation mutex
+ */
+MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
 #endif
 
+
 /**
- * Trace up to and return master daemon. If the supplied daemon
- * is a master, then return the daemon itself.
- *
- * @param daemon handle to a daemon
- * @return master daemon handle
+ * Check whether global initialisation was performed
+ * and call initialiser if necessary.
  */
-static struct MHD_Daemon*
-MHD_get_master (struct MHD_Daemon *daemon)
+void
+MHD_check_global_init_ (void)
 {
-  while (NULL != daemon->master)
-    daemon = daemon->master;
-  return daemon;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+  MHD_mutex_lock_chk_ (&global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+#endif
+  if (0 == global_init_count++)
+    MHD_init ();
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#ifdef MHD_MUTEX_STATIC_DEFN_INIT_
+  MHD_mutex_unlock_chk_ (&global_init_mutex_);
+#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
+#endif
+}
+
+
+#endif /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
+
+#ifdef HAVE_MESSAGES
+/**
+ * Default logger function
+ */
+static void
+MHD_default_logger_ (void *cls,
+                     const char *fm,
+                     va_list ap)
+{
+  vfprintf ((FILE *) cls, fm, ap);
+#ifdef _DEBUG
+  fflush ((FILE *) cls);
+#endif /* _DEBUG */
+}
+
+
+#endif /* HAVE_MESSAGES */
+
+
+/**
+ * Free the memory allocated by MHD.
+ *
+ * If any MHD function explicitly mentions that returned pointer must be
+ * freed by this function, then no other method must be used to free
+ * the memory.
+ *
+ * @param ptr the pointer to free.
+ * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3()
+ * @sa #MHD_basic_auth_get_username_password()
+ * @note Available since #MHD_VERSION 0x00095600
+ * @ingroup specialized
+ */
+_MHD_EXTERN void
+MHD_free (void *ptr)
+{
+  free (ptr);
 }
 
 
@@ -193,7 +243,7 @@
      * IPv4 address.
      */
     struct in_addr ipv4;
-#if HAVE_INET6
+#ifdef HAVE_INET6
     /**
      * IPv6 address.
      */
@@ -216,10 +266,12 @@
 static void
 MHD_ip_count_lock (struct MHD_Daemon *daemon)
 {
-  if (MHD_YES != MHD_mutex_lock_(&daemon->per_ip_connection_mutex))
-    {
-      MHD_PANIC ("Failed to acquire IP connection limit mutex\n");
-    }
+  mhd_assert (NULL == daemon->master);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->per_ip_connection_mutex);
+#else
+  (void) daemon;
+#endif
 }
 
 
@@ -231,10 +283,12 @@
 static void
 MHD_ip_count_unlock (struct MHD_Daemon *daemon)
 {
-  if (MHD_YES != MHD_mutex_unlock_(&daemon->per_ip_connection_mutex))
-    {
-      MHD_PANIC ("Failed to release IP connection limit mutex\n");
-    }
+  mhd_assert (NULL == daemon->master);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->per_ip_connection_mutex);
+#else
+  (void) daemon;
+#endif
 }
 
 
@@ -248,45 +302,59 @@
  * @return -1, 0 or 1 depending on result of compare
  */
 static int
-MHD_ip_addr_compare (const void *a1, const void *a2)
+MHD_ip_addr_compare (const void *a1,
+                     const void *a2)
 {
-  return memcmp (a1, a2, offsetof (struct MHD_IPCount, count));
+  return memcmp (a1,
+                 a2,
+                 offsetof (struct MHD_IPCount,
+                           count));
 }
 
 
 /**
- * Parse address and initialize 'key' using the address.
+ * Parse address and initialize @a key using the address.
  *
  * @param addr address to parse
- * @param addrlen number of bytes in addr
+ * @param addrlen number of bytes in @a addr
  * @param key where to store the parsed address
  * @return #MHD_YES on success and #MHD_NO otherwise (e.g., invalid address type)
  */
-static int
-MHD_ip_addr_to_key (const struct sockaddr *addr,
-		    socklen_t addrlen,
-		    struct MHD_IPCount *key)
+static enum MHD_Result
+MHD_ip_addr_to_key (const struct sockaddr_storage *addr,
+                    socklen_t addrlen,
+                    struct MHD_IPCount *key)
 {
-  memset(key, 0, sizeof(*key));
+  memset (key,
+          0,
+          sizeof(*key));
 
   /* IPv4 addresses */
-  if (sizeof (struct sockaddr_in) == addrlen)
+  if (sizeof (struct sockaddr_in) <= (size_t) addrlen)
+  {
+    if (AF_INET == addr->ss_family)
     {
-      const struct sockaddr_in *addr4 = (const struct sockaddr_in*) addr;
       key->family = AF_INET;
-      memcpy (&key->addr.ipv4, &addr4->sin_addr, sizeof(addr4->sin_addr));
+      memcpy (&key->addr.ipv4,
+              &((const struct sockaddr_in *) addr)->sin_addr,
+              sizeof(((const struct sockaddr_in *) NULL)->sin_addr));
       return MHD_YES;
     }
+  }
 
-#if HAVE_INET6
-  /* IPv6 addresses */
-  if (sizeof (struct sockaddr_in6) == addrlen)
+#ifdef HAVE_INET6
+  if (sizeof (struct sockaddr_in6) <= (size_t) addrlen)
+  {
+    /* IPv6 addresses */
+    if (AF_INET6 == addr->ss_family)
     {
-      const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*) addr;
       key->family = AF_INET6;
-      memcpy (&key->addr.ipv6, &addr6->sin6_addr, sizeof(addr6->sin6_addr));
+      memcpy (&key->addr.ipv6,
+              &((const struct sockaddr_in6 *) addr)->sin6_addr,
+              sizeof(((const struct sockaddr_in6 *) NULL)->sin6_addr));
       return MHD_YES;
     }
+  }
 #endif
 
   /* Some other address */
@@ -295,66 +363,72 @@
 
 
 /**
- * Check if IP address is over its limit.
+ * Check if IP address is over its limit in terms of the number
+ * of allowed concurrent connections.  If the IP is still allowed,
+ * increments the connection counter.
  *
  * @param daemon handle to daemon where connection counts are tracked
  * @param addr address to add (or increment counter)
- * @param addrlen number of bytes in addr
+ * @param addrlen number of bytes in @a addr
  * @return Return #MHD_YES if IP below limit, #MHD_NO if IP has surpassed limit.
  *   Also returns #MHD_NO if fails to allocate memory.
  */
-static int
+static enum MHD_Result
 MHD_ip_limit_add (struct MHD_Daemon *daemon,
-		  const struct sockaddr *addr,
-		  socklen_t addrlen)
+                  const struct sockaddr_storage *addr,
+                  socklen_t addrlen)
 {
-  struct MHD_IPCount *key;
-  void **nodep;
-  void *node;
-  int result;
+  struct MHD_IPCount *newkeyp;
+  struct MHD_IPCount *keyp;
+  struct MHD_IPCount **nodep;
+  enum MHD_Result result;
 
   daemon = MHD_get_master (daemon);
   /* Ignore if no connection limit assigned */
   if (0 == daemon->per_ip_connection_limit)
     return MHD_YES;
 
-  if (NULL == (key = malloc (sizeof(*key))))
+  newkeyp = (struct MHD_IPCount *) malloc (sizeof(struct MHD_IPCount));
+  if (NULL == newkeyp)
     return MHD_NO;
 
   /* Initialize key */
-  if (MHD_NO == MHD_ip_addr_to_key (addr, addrlen, key))
-    {
-      /* Allow unhandled address types through */
-      free (key);
-      return MHD_YES;
-    }
+  if (MHD_NO == MHD_ip_addr_to_key (addr,
+                                    addrlen,
+                                    newkeyp))
+  {
+    free (newkeyp);
+    return MHD_YES; /* Allow unhandled address types through */
+  }
+
   MHD_ip_count_lock (daemon);
 
   /* Search for the IP address */
-  if (NULL == (nodep = tsearch (key,
-				&daemon->per_ip_connection_count,
-				&MHD_ip_addr_compare)))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Failed to add IP connection count node\n");
+  nodep = (struct MHD_IPCount **) tsearch (newkeyp,
+                                           &daemon->per_ip_connection_count,
+                                           &MHD_ip_addr_compare);
+  if (NULL == nodep)
+  {
+    MHD_ip_count_unlock (daemon);
+    free (newkeyp);
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to add IP connection count node.\n"));
 #endif
-      MHD_ip_count_unlock (daemon);
-      free (key);
-      return MHD_NO;
-    }
-  node = *nodep;
-  /* If we got an existing node back, free the one we created */
-  if (node != key)
-    free(key);
-  key = (struct MHD_IPCount *) node;
+    return MHD_NO;
+  }
+  keyp = *nodep;
   /* Test if there is room for another connection; if so,
    * increment count */
-  result = (key->count < daemon->per_ip_connection_limit);
-  if (MHD_YES == result)
-    ++key->count;
-
+  result = (keyp->count < daemon->per_ip_connection_limit) ? MHD_YES : MHD_NO;
+  if (MHD_NO != result)
+    ++keyp->count;
   MHD_ip_count_unlock (daemon);
+
+  /* If we got an existing node back, free the one we created */
+  if (keyp != newkeyp)
+    free (newkeyp);
+
   return result;
 }
 
@@ -369,8 +443,8 @@
  */
 static void
 MHD_ip_limit_del (struct MHD_Daemon *daemon,
-		  const struct sockaddr *addr,
-		  socklen_t addrlen)
+                  const struct sockaddr_storage *addr,
+                  socklen_t addrlen)
 {
   struct MHD_IPCount search_key;
   struct MHD_IPCount *found_key;
@@ -381,203 +455,169 @@
   if (0 == daemon->per_ip_connection_limit)
     return;
   /* Initialize search key */
-  if (MHD_NO == MHD_ip_addr_to_key (addr, addrlen, &search_key))
+  if (MHD_NO == MHD_ip_addr_to_key (addr,
+                                    addrlen,
+                                    &search_key))
     return;
 
   MHD_ip_count_lock (daemon);
 
   /* Search for the IP address */
   if (NULL == (nodep = tfind (&search_key,
-			      &daemon->per_ip_connection_count,
-			      &MHD_ip_addr_compare)))
-    {
-      /* Something's wrong if we couldn't find an IP address
-       * that was previously added */
-      MHD_PANIC ("Failed to find previously-added IP address\n");
-    }
+                              &daemon->per_ip_connection_count,
+                              &MHD_ip_addr_compare)))
+  {
+    /* Something's wrong if we couldn't find an IP address
+     * that was previously added */
+    MHD_PANIC (_ ("Failed to find previously-added IP address.\n"));
+  }
   found_key = (struct MHD_IPCount *) *nodep;
   /* Validate existing count for IP address */
   if (0 == found_key->count)
-    {
-      MHD_PANIC ("Previously-added IP address had 0 count\n");
-    }
+  {
+    MHD_PANIC (_ ("Previously-added IP address had counter of zero.\n"));
+  }
   /* Remove the node entirely if count reduces to 0 */
   if (0 == --found_key->count)
-    {
-      tdelete (found_key,
-	       &daemon->per_ip_connection_count,
-	       &MHD_ip_addr_compare);
-      free (found_key);
-    }
-
-  MHD_ip_count_unlock (daemon);
+  {
+    tdelete (found_key,
+             &daemon->per_ip_connection_count,
+             &MHD_ip_addr_compare);
+    MHD_ip_count_unlock (daemon);
+    free (found_key);
+  }
+  else
+    MHD_ip_count_unlock (daemon);
 }
 
 
-#if HTTPS_SUPPORT
-
-static ssize_t
-recv_param_adapter (struct MHD_Connection *connection,
-                    void *other,
-                    size_t i);
-static ssize_t
-send_param_adapter (struct MHD_Connection *connection,
-                    const void *other,
-                    size_t i);
-
-// Internal functions for implementing OpenSSL BIO.
+#ifdef HTTPS_SUPPORT
+/**
+ * Read and setup our certificate and key.
+ *
+ * @param daemon handle to daemon to initialize
+ * @return 0 on success
+ */
 static int
-MHD_bio_write (BIO* bio, const char* buf, int size)
+MHD_init_daemon_certificate (struct MHD_Daemon *daemon)
 {
-  struct MHD_Connection* connection = (struct MHD_Connection*)bio->ptr;
-  BIO_clear_retry_flags (bio);
-  ssize_t written = send_param_adapter (connection, buf, size);
-  if (written < size)
+  gnutls_datum_t key;
+  gnutls_datum_t cert;
+  int ret;
+
+#if GNUTLS_VERSION_MAJOR >= 3
+  if (NULL != daemon->cert_callback)
+  {
+    gnutls_certificate_set_retrieve_function2 (daemon->x509_cred,
+                                               daemon->cert_callback);
+  }
+#endif
+#if GNUTLS_VERSION_NUMBER >= 0x030603
+  else if (NULL != daemon->cert_callback2)
+  {
+    gnutls_certificate_set_retrieve_function3 (daemon->x509_cred,
+                                               daemon->cert_callback2);
+  }
+#endif
+
+  if (NULL != daemon->https_mem_trust)
+  {
+    size_t paramlen;
+    paramlen = strlen (daemon->https_mem_trust);
+    if (UINT_MAX < paramlen)
     {
-      BIO_set_retry_write (bio);
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Too long trust certificate.\n"));
+#endif
+      return -1;
     }
-  return written;
-}
-
-static int
-MHD_bio_read (BIO* bio, char* buf, int size)
-{
-  struct MHD_Connection* connection = (struct MHD_Connection*)bio->ptr;
-  BIO_clear_retry_flags (bio);
-  ssize_t read = recv_param_adapter (connection, buf, size);
-  if (read < size)
+    cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_trust);
+    cert.size = (unsigned int) paramlen;
+    if (gnutls_certificate_set_x509_trust_mem (daemon->x509_cred,
+                                               &cert,
+                                               GNUTLS_X509_FMT_PEM) < 0)
     {
-      BIO_set_retry_read (bio);
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Bad trust certificate format.\n"));
+#endif
+      return -1;
     }
-  return read;
-}
+  }
 
-static long
-MHD_bio_ctrl (BIO* bio, int cmd, long num, void* ptr)
-{
-  if (cmd == BIO_CTRL_FLUSH)
+  if (daemon->have_dhparams)
+  {
+    gnutls_certificate_set_dh_params (daemon->x509_cred,
+                                      daemon->https_mem_dhparams);
+  }
+  /* certificate & key loaded from memory */
+  if ( (NULL != daemon->https_mem_cert) &&
+       (NULL != daemon->https_mem_key) )
+  {
+    size_t param1len;
+    size_t param2len;
+
+    param1len = strlen (daemon->https_mem_key);
+    param2len = strlen (daemon->https_mem_cert);
+    if ( (UINT_MAX < param1len) ||
+         (UINT_MAX < param2len) )
     {
-      return 1;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Too long key or certificate.\n"));
+#endif
+      return -1;
     }
-  return 0;
-}
+    key.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_key);
+    key.size = (unsigned int) param1len;
+    cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_cert);
+    cert.size = (unsigned int) param2len;
 
-static int
-MHD_bio_new (BIO* bio)
-{
-  bio->shutdown = 0;
-  bio->init = 0;
-  bio->num = -1;  // not used.
-  return 1;
-}
-
-static int
-MHD_bio_free (BIO* bio)
-{
-  if (!bio)
+    if (NULL != daemon->https_key_password)
+    {
+#if GNUTLS_VERSION_NUMBER >= 0x030111
+      ret = gnutls_certificate_set_x509_key_mem2 (daemon->x509_cred,
+                                                  &cert,
+                                                  &key,
+                                                  GNUTLS_X509_FMT_PEM,
+                                                  daemon->https_key_password,
+                                                  0);
+#else
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to setup x509 certificate/key: pre 3.X.X version " \
+                   "of GnuTLS does not support setting key password.\n"));
+#endif
+      return -1;
+#endif
+    }
+    else
+      ret = gnutls_certificate_set_x509_key_mem (daemon->x509_cred,
+                                                 &cert,
+                                                 &key,
+                                                 GNUTLS_X509_FMT_PEM);
+#ifdef HAVE_MESSAGES
+    if (0 != ret)
+      MHD_DLOG (daemon,
+                _ ("GnuTLS failed to setup x509 certificate/key: %s\n"),
+                gnutls_strerror (ret));
+#endif
+    return ret;
+  }
+#if GNUTLS_VERSION_MAJOR >= 3
+  if (NULL != daemon->cert_callback)
     return 0;
-
-  if (bio->init)
-    {
-      bio->ptr = NULL;
-      bio->init = 0;
-    }
-  return 1;
-}
-
-// Describes a BIO built on [send|recv]_param_adapter().
-BIO_METHOD MHD_bio_method =
-{
-    BIO_TYPE_SOURCE_SINK,
-    "mhd",          // name
-    MHD_bio_write,  // write function
-    MHD_bio_read,   // read function
-    NULL,           // puts function, not implemented
-    NULL,           // gets function, not implemented
-    MHD_bio_ctrl,   // control function
-    MHD_bio_new,    // creation
-    MHD_bio_free,   // free
-    NULL,           // callback function, not used
-};
-
-
-/**
- * Callback for receiving data from the socket.
- *
- * @param connection the MHD_Connection structure
- * @param other where to write received data to
- * @param i maximum size of other (in bytes)
- * @return number of bytes actually received
- */
-static ssize_t
-recv_tls_adapter (struct MHD_Connection *connection, void *other, size_t i)
-{
-  int res;
-
-  if (MHD_YES == connection->tls_read_ready)
-    {
-      connection->daemon->num_tls_read_ready--;
-      connection->tls_read_ready = MHD_NO;
-    }
-  res = SSL_read (connection->tls_session, other, i);
-  if ( res < 0 && SSL_want_read (connection->tls_session) )
-    {
-      MHD_set_socket_errno_ (EINTR);
-#if EPOLL_SUPPORT
-      connection->epoll_state &= ~MHD_EPOLL_STATE_READ_READY;
 #endif
-      return -1;
-    }
-  if (res < 0)
-    {
-      /* Likely 'GNUTLS_E_INVALID_SESSION' (client communication
-	 disrupted); set errno to something caller will interpret
-	 correctly as a hard error */
-      MHD_set_socket_errno_ (ECONNRESET);
-      return res;
-    }
-  if (res == i)
-    {
-      connection->tls_read_ready = MHD_YES;
-      connection->daemon->num_tls_read_ready++;
-    }
-  return res;
-}
-
-
-/**
- * Callback for writing data to the socket.
- *
- * @param connection the MHD connection structure
- * @param other data to write
- * @param i number of bytes to write
- * @return actual number of bytes written
- */
-static ssize_t
-send_tls_adapter (struct MHD_Connection *connection,
-                  const void *other, size_t i)
-{
-  int res;
-
-  res = SSL_write (connection->tls_session, other, i);
-  if ( res < 0 && SSL_want_write (connection->tls_session) )
-    {
-      MHD_set_socket_errno_ (EINTR);
-#if EPOLL_SUPPORT
-      connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
+#if GNUTLS_VERSION_NUMBER >= 0x030603
+  else if (NULL != daemon->cert_callback2)
+    return 0;
 #endif
-      return -1;
-    }
-  if (res < 0)
-    {
-      /* some other GNUTLS error, should set 'errno'; as we do not
-         really understand the error (not listed in GnuTLS
-         documentation explicitly), we set 'errno' to something that
-         will cause the connection to fail. */
-      MHD_set_socket_errno_ (ECONNRESET);
-      return -1;
-    }
-  return res;
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (daemon,
+            _ ("You need to specify a certificate and key location.\n"));
+#endif
+  return -1;
 }
 
 
@@ -590,178 +630,34 @@
 static int
 MHD_TLS_init (struct MHD_Daemon *daemon)
 {
-  int ret;
-  daemon->tls_context = SSL_CTX_new (TLSv1_2_server_method());
-  if (NULL == daemon->tls_context)
+  switch (daemon->cred_type)
+  {
+  case GNUTLS_CRD_CERTIFICATE:
+    if (0 !=
+        gnutls_certificate_allocate_credentials (&daemon->x509_cred))
+      return GNUTLS_E_MEMORY_ERROR;
+    return MHD_init_daemon_certificate (daemon);
+  case GNUTLS_CRD_PSK:
+    if (0 !=
+        gnutls_psk_allocate_server_credentials (&daemon->psk_cred))
+      return GNUTLS_E_MEMORY_ERROR;
+    return 0;
+  case GNUTLS_CRD_ANON:
+  case GNUTLS_CRD_SRP:
+  case GNUTLS_CRD_IA:
+  default:
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Error: invalid credentials type %d specified.\n"),
+              daemon->cred_type);
+#endif
     return -1;
-  if (NULL != daemon->https_mem_trust)
-    {
-      ret = 0;
-      BIO* mem_bio = BIO_new_mem_buf ((void*)daemon->https_mem_trust, -1);
-      X509* x509 = PEM_read_bio_X509 (mem_bio, NULL, NULL, NULL);
-      BIO_free(mem_bio);
-      if (x509 != NULL)
-        {
-          ret = SSL_CTX_add_client_CA (daemon->tls_context, x509);
-        }
-      if (ret == 0)
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Bad trust certificate format\n");
-#endif
-          return -1;
-        }
-    }
-
-  if (NULL != daemon->https_mem_dhparams)
-    {
-      ret = 0;
-      BIO* mem_bio = BIO_new_mem_buf ((void*)daemon->https_mem_dhparams, -1);
-      DH* dh = PEM_read_bio_DHparams (mem_bio, NULL, NULL, NULL);
-      BIO_free (mem_bio);
-      if (dh != NULL)
-        {
-          ret = SSL_CTX_set_tmp_dh (daemon->tls_context, dh);
-        }
-      if (ret == 0)
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Bad DH parameters format\n");
-#endif
-          return -1;
-        }
-    }
-
-  /* certificate & key loaded from memory */
-  if ( (NULL != daemon->https_mem_cert) &&
-       (NULL != daemon->https_mem_key) )
-    {
-      ret = 0;
-      BIO* mem_bio = BIO_new_mem_buf ((void*)daemon->https_mem_key, -1);
-      EVP_PKEY* key = PEM_read_bio_PrivateKey (mem_bio, NULL, NULL,
-                                               (void*)daemon->https_key_password);
-      BIO_free (mem_bio);
-      if (key != NULL)
-        {
-          ret = SSL_CTX_use_PrivateKey (daemon->tls_context, key);
-        }
-      if (ret == 0)
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Bad private key format\n");
-#endif
-          return -1;
-        }
-      ret = 0;
-      mem_bio = BIO_new_mem_buf ((void*)daemon->https_mem_cert, -1);
-      X509* x509 = PEM_read_bio_X509 (mem_bio, NULL, NULL, NULL);
-      BIO_free (mem_bio);
-      if (x509 != NULL)
-        {
-          ret = SSL_CTX_use_certificate (daemon->tls_context, x509);
-        }
-      if (ret == 0)
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Bad certificate format\n");
-#endif
-          return -1;
-        }
-      if (1 != SSL_CTX_check_private_key (daemon->tls_context))
-         {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Invalid key / certificate combination\n");
-#endif
-          return -1;
-        }
-    }
-  else
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "You need to specify a certificate and key location\n");
-#endif
-      return -1;
-    }
-  if (NULL != daemon->https_mem_cipher)
-    {
-      ret = SSL_CTX_set_cipher_list (daemon->tls_context,
-                                     daemon->https_mem_cipher);
-      if (ret == 0)
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Bad cipher string format\n");
-#endif
-          return -1;
-        }
-    }
-  else
-    {
-      ret = SSL_CTX_set_cipher_list (daemon->tls_context,
-                                     "HIGH!SHA1!DH@STRENGTH");
-      if (ret == 0)
-         {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Failed to setup default cipher string\n");
-#endif
-          return -1;
-        }
-    }
-  return 0;
+  }
 }
 
-static void
-MHD_TLS_deinit (struct MHD_Daemon *daemon)
-{
-  SSL_CTX_free (daemon->tls_context);
-}
-#endif
 
+#endif /* HTTPS_SUPPORT */
 
-/**
- * Add @a fd to the @a set.  If @a fd is
- * greater than @a max_fd, set @a max_fd to @a fd.
- *
- * @param fd file descriptor to add to the @a set
- * @param set set to modify
- * @param max_fd maximum value to potentially update
- * @param fd_setsize value of FD_SETSIZE
- * @return #MHD_YES on success, #MHD_NO otherwise
- */
-static int
-add_to_fd_set (MHD_socket fd,
-	       fd_set *set,
-	       MHD_socket *max_fd,
-	       unsigned int fd_setsize)
-{
-  if (NULL == set)
-    return MHD_NO;
-#ifdef MHD_WINSOCK_SOCKETS
-  if (set->fd_count >= fd_setsize)
-    {
-      if (FD_ISSET(fd, set))
-        return MHD_YES;
-      else
-        return MHD_NO;
-    }
-#else  // ! MHD_WINSOCK_SOCKETS
-  if (fd >= fd_setsize)
-    return MHD_NO;
-#endif // ! MHD_WINSOCK_SOCKETS
-  FD_SET (fd, set);
-  if ( (NULL != max_fd) && (MHD_INVALID_SOCKET != fd) &&
-       ((fd > *max_fd) || (MHD_INVALID_SOCKET == *max_fd)) )
-    *max_fd = fd;
-
-  return MHD_YES;
-}
 
 #undef MHD_get_fdset
 
@@ -772,6 +668,18 @@
  * before calling this function. FD_SETSIZE is assumed
  * to be platform's default.
  *
+ * This function should be called only when MHD is configured to
+ * use "external" sockets polling with 'select()' or with 'epoll'.
+ * In the latter case, it will only add the single 'epoll' file
+ * descriptor used by MHD to the sets.
+ * It's necessary to use #MHD_get_timeout() to get maximum timeout
+ * value for `select()`. Usage of `select()` with indefinite timeout
+ * (or timeout larger than returned by #MHD_get_timeout()) will
+ * violate MHD API and may results in pending unprocessed data.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
  * @param daemon daemon to get sets from
  * @param read_fd_set read set
  * @param write_fd_set write set
@@ -784,25 +692,401 @@
  *         fit fd_set.
  * @ingroup event
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_get_fdset (struct MHD_Daemon *daemon,
                fd_set *read_fd_set,
                fd_set *write_fd_set,
-	       fd_set *except_fd_set,
-	       MHD_socket *max_fd)
+               fd_set *except_fd_set,
+               MHD_socket *max_fd)
 {
-  return MHD_get_fdset2(daemon, read_fd_set,
-      write_fd_set, except_fd_set,
-      max_fd, MHD_DEFAULT_FD_SETSIZE);
+  return MHD_get_fdset2 (daemon,
+                         read_fd_set,
+                         write_fd_set,
+                         except_fd_set,
+                         max_fd,
+                         _MHD_SYS_DEFAULT_FD_SETSIZE);
 }
 
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Obtain the select() file descriptor sets for the
+ * given @a urh.
+ *
+ * @param urh upgrade handle to wait for
+ * @param[out] rs read set to initialize
+ * @param[out] ws write set to initialize
+ * @param[out] es except set to initialize
+ * @param[out] max_fd maximum FD to update
+ * @param fd_setsize value of FD_SETSIZE
+ * @return true on success, false on error
+ */
+static bool
+urh_to_fdset (struct MHD_UpgradeResponseHandle *urh,
+              fd_set *rs,
+              fd_set *ws,
+              fd_set *es,
+              MHD_socket *max_fd,
+              unsigned int fd_setsize)
+{
+  const MHD_socket conn_sckt = urh->connection->socket_fd;
+  const MHD_socket mhd_sckt = urh->mhd.socket;
+  bool res = true;
+
+  /* Do not add to 'es' only if socket is closed
+   * or not used anymore. */
+  if (MHD_INVALID_SOCKET != conn_sckt)
+  {
+    if ( (urh->in_buffer_used < urh->in_buffer_size) &&
+         (! MHD_add_to_fd_set_ (conn_sckt,
+                                rs,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    if ( (0 != urh->out_buffer_used) &&
+         (! MHD_add_to_fd_set_ (conn_sckt,
+                                ws,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    /* Do not monitor again for errors if error was detected before as
+     * error state is remembered. */
+    if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) &&
+        ((0 != urh->in_buffer_size) ||
+         (0 != urh->out_buffer_size) ||
+         (0 != urh->out_buffer_used)))
+      MHD_add_to_fd_set_ (conn_sckt,
+                          es,
+                          max_fd,
+                          fd_setsize);
+  }
+  if (MHD_INVALID_SOCKET != mhd_sckt)
+  {
+    if ( (urh->out_buffer_used < urh->out_buffer_size) &&
+         (! MHD_add_to_fd_set_ (mhd_sckt,
+                                rs,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    if ( (0 != urh->in_buffer_used) &&
+         (! MHD_add_to_fd_set_ (mhd_sckt,
+                                ws,
+                                max_fd,
+                                fd_setsize)) )
+      res = false;
+    /* Do not monitor again for errors if error was detected before as
+     * error state is remembered. */
+    if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) &&
+        ((0 != urh->out_buffer_size) ||
+         (0 != urh->in_buffer_size) ||
+         (0 != urh->in_buffer_used)))
+      MHD_add_to_fd_set_ (mhd_sckt,
+                          es,
+                          max_fd,
+                          fd_setsize);
+  }
+
+  return res;
+}
+
+
+/**
+ * Update the @a urh based on the ready FDs in
+ * the @a rs, @a ws, and @a es.
+ *
+ * @param urh upgrade handle to update
+ * @param rs read result from select()
+ * @param ws write result from select()
+ * @param es except result from select()
+ */
+static void
+urh_from_fdset (struct MHD_UpgradeResponseHandle *urh,
+                const fd_set *rs,
+                const fd_set *ws,
+                const fd_set *es)
+{
+  const MHD_socket conn_sckt = urh->connection->socket_fd;
+  const MHD_socket mhd_sckt = urh->mhd.socket;
+
+  /* Reset read/write ready, preserve error state. */
+  urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY)
+                    & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY));
+  urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY)
+                    & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY));
+
+  if (MHD_INVALID_SOCKET != conn_sckt)
+  {
+    if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (rs)))
+      urh->app.celi |= MHD_EPOLL_STATE_READ_READY;
+    if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (ws)))
+      urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY;
+    if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (es)))
+      urh->app.celi |= MHD_EPOLL_STATE_ERROR;
+  }
+  if ((MHD_INVALID_SOCKET != mhd_sckt))
+  {
+    if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (rs)))
+      urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+    if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (ws)))
+      urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY;
+    if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (es)))
+      urh->mhd.celi |= MHD_EPOLL_STATE_ERROR;
+  }
+}
+
+
+#ifdef HAVE_POLL
+
+/**
+ * Set required 'event' members in 'pollfd' elements,
+ * assuming that @a p[0].fd is MHD side of socketpair
+ * and @a p[1].fd is TLS connected socket.
+ *
+ * @param urh upgrade handle to watch for
+ * @param p pollfd array to update
+ */
+static void
+urh_update_pollfd (struct MHD_UpgradeResponseHandle *urh,
+                   struct pollfd p[2])
+{
+  p[0].events = 0;
+  p[1].events = 0;
+
+  if (urh->in_buffer_used < urh->in_buffer_size)
+    p[0].events |= POLLIN;
+  if (0 != urh->out_buffer_used)
+    p[0].events |= POLLOUT;
+
+  /* Do not monitor again for errors if error was detected before as
+   * error state is remembered. */
+  if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) &&
+      ((0 != urh->in_buffer_size) ||
+       (0 != urh->out_buffer_size) ||
+       (0 != urh->out_buffer_used)))
+    p[0].events |= MHD_POLL_EVENTS_ERR_DISC;
+
+  if (urh->out_buffer_used < urh->out_buffer_size)
+    p[1].events |= POLLIN;
+  if (0 != urh->in_buffer_used)
+    p[1].events |= POLLOUT;
+
+  /* Do not monitor again for errors if error was detected before as
+   * error state is remembered. */
+  if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) &&
+      ((0 != urh->out_buffer_size) ||
+       (0 != urh->in_buffer_size) ||
+       (0 != urh->in_buffer_used)))
+    p[1].events |= MHD_POLL_EVENTS_ERR_DISC;
+}
+
+
+/**
+ * Set @a p to watch for @a urh.
+ *
+ * @param urh upgrade handle to watch for
+ * @param p pollfd array to set
+ */
+static void
+urh_to_pollfd (struct MHD_UpgradeResponseHandle *urh,
+               struct pollfd p[2])
+{
+  p[0].fd = urh->connection->socket_fd;
+  p[1].fd = urh->mhd.socket;
+  urh_update_pollfd (urh,
+                     p);
+}
+
+
+/**
+ * Update ready state in @a urh based on pollfd.
+ * @param urh upgrade handle to update
+ * @param p 'poll()' processed pollfd.
+ */
+static void
+urh_from_pollfd (struct MHD_UpgradeResponseHandle *urh,
+                 struct pollfd p[2])
+{
+  /* Reset read/write ready, preserve error state. */
+  urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY)
+                    & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY));
+  urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY)
+                    & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY));
+
+  if (0 != (p[0].revents & POLLIN))
+    urh->app.celi |= MHD_EPOLL_STATE_READ_READY;
+  if (0 != (p[0].revents & POLLOUT))
+    urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY;
+  if (0 != (p[0].revents & POLLHUP))
+    urh->app.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY;
+  if (0 != (p[0].revents & MHD_POLL_REVENTS_ERRROR))
+    urh->app.celi |= MHD_EPOLL_STATE_ERROR;
+  if (0 != (p[1].revents & POLLIN))
+    urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+  if (0 != (p[1].revents & POLLOUT))
+    urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY;
+  if (0 != (p[1].revents & POLLHUP))
+    urh->mhd.celi |= MHD_EPOLL_STATE_ERROR;
+  if (0 != (p[1].revents & MHD_POLL_REVENTS_ERRROR))
+    urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY;
+}
+
+
+#endif /* HAVE_POLL */
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+
+/**
+ * Internal version of #MHD_get_fdset2().
+ *
+ * @param daemon daemon to get sets from
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @param max_fd increased to largest FD added (if larger
+ *               than existing value); can be NULL
+ * @param fd_setsize value of FD_SETSIZE
+ * @return #MHD_YES on success, #MHD_NO if any FD didn't
+ *         fit fd_set.
+ * @ingroup event
+ */
+static enum MHD_Result
+internal_get_fdset2 (struct MHD_Daemon *daemon,
+                     fd_set *read_fd_set,
+                     fd_set *write_fd_set,
+                     fd_set *except_fd_set,
+                     MHD_socket *max_fd,
+                     unsigned int fd_setsize)
+
+{
+  struct MHD_Connection *pos;
+  struct MHD_Connection *posn;
+  enum MHD_Result result = MHD_YES;
+  MHD_socket ls;
+
+  if (daemon->shutdown)
+    return MHD_NO;
+
+  ls = daemon->listen_fd;
+  if ( (MHD_INVALID_SOCKET != ls) &&
+       (! daemon->was_quiesced) &&
+       (! MHD_add_to_fd_set_ (ls,
+                              read_fd_set,
+                              max_fd,
+                              fd_setsize)) )
+    result = MHD_NO;
+
+  /* Add all sockets to 'except_fd_set' as well to watch for
+   * out-of-band data. However, ignore errors if INFO_READ
+   * or INFO_WRITE sockets will not fit 'except_fd_set'. */
+  /* Start from oldest connections. Make sense for W32 FDSETs. */
+  for (pos = daemon->connections_tail; NULL != pos; pos = posn)
+  {
+    posn = pos->prev;
+
+    switch (pos->event_loop_info)
+    {
+    case MHD_EVENT_LOOP_INFO_READ:
+    case MHD_EVENT_LOOP_INFO_PROCESS_READ:
+      if (! MHD_add_to_fd_set_ (pos->socket_fd,
+                                read_fd_set,
+                                max_fd,
+                                fd_setsize))
+        result = MHD_NO;
+#ifdef MHD_POSIX_SOCKETS
+      MHD_add_to_fd_set_ (pos->socket_fd,
+                          except_fd_set,
+                          max_fd,
+                          fd_setsize);
+#endif /* MHD_POSIX_SOCKETS */
+      break;
+    case MHD_EVENT_LOOP_INFO_WRITE:
+      if (! MHD_add_to_fd_set_ (pos->socket_fd,
+                                write_fd_set,
+                                max_fd,
+                                fd_setsize))
+        result = MHD_NO;
+#ifdef MHD_POSIX_SOCKETS
+      MHD_add_to_fd_set_ (pos->socket_fd,
+                          except_fd_set,
+                          max_fd,
+                          fd_setsize);
+#endif /* MHD_POSIX_SOCKETS */
+      break;
+    case MHD_EVENT_LOOP_INFO_PROCESS:
+      if ( (NULL == except_fd_set) ||
+           ! MHD_add_to_fd_set_ (pos->socket_fd,
+                                 except_fd_set,
+                                 max_fd,
+                                 fd_setsize))
+        result = MHD_NO;
+      break;
+    case MHD_EVENT_LOOP_INFO_CLEANUP:
+      /* this should never happen */
+      break;
+    }
+  }
+#ifdef MHD_WINSOCK_SOCKETS
+  /* W32 use limited array for fd_set so add INFO_READ/INFO_WRITE sockets
+   * only after INFO_BLOCK sockets to ensure that INFO_BLOCK sockets will
+   * not be pushed out. */
+  for (pos = daemon->connections_tail; NULL != pos; pos = posn)
+  {
+    posn = pos->prev;
+    MHD_add_to_fd_set_ (pos->socket_fd,
+                        except_fd_set,
+                        max_fd,
+                        fd_setsize);
+  }
+#endif /* MHD_WINSOCK_SOCKETS */
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  {
+    struct MHD_UpgradeResponseHandle *urh;
+
+    for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev)
+    {
+      if (MHD_NO ==
+          urh_to_fdset (urh,
+                        read_fd_set,
+                        write_fd_set,
+                        except_fd_set,
+                        max_fd,
+                        fd_setsize))
+        result = MHD_NO;
+    }
+  }
+#endif
+#if _MHD_DEBUG_CONNECT
+#ifdef HAVE_MESSAGES
+  if (NULL != max_fd)
+    MHD_DLOG (daemon,
+              _ ("Maximum socket in select set: %d\n"),
+              *max_fd);
+#endif
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  return result;
+}
+
+
 /**
  * Obtain the `select()` sets for this daemon.
  * Daemon's FDs will be added to fd_sets. To get only
  * daemon FDs in fd_sets, call FD_ZERO for each fd_set
- * before calling this function. Passing custom FD_SETSIZE
- * as @a fd_setsize allow usage of larger/smaller than
- * platform's default fd_sets.
+ * before calling this function.
+ *
+ * Passing custom FD_SETSIZE as @a fd_setsize allow usage of
+ * larger/smaller than platform's default fd_sets.
+ *
+ * This function should be called only when MHD is configured to
+ * use "external" sockets polling with 'select()' or with 'epoll'.
+ * In the latter case, it will only add the single 'epoll' file
+ * descriptor used by MHD to the sets.
+ * It's necessary to use #MHD_get_timeout() to get maximum timeout
+ * value for `select()`. Usage of `select()` with indefinite timeout
+ * (or timeout larger than returned by #MHD_get_timeout()) will
+ * violate MHD API and may results in pending unprocessed data.
+ *
+ * This function must be called only for daemon started
+ * without #MHD_USE_INTERNAL_POLLING_THREAD flag.
  *
  * @param daemon daemon to get sets from
  * @param read_fd_set read set
@@ -817,70 +1101,771 @@
  *         fit fd_set.
  * @ingroup event
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_get_fdset2 (struct MHD_Daemon *daemon,
-               fd_set *read_fd_set,
-               fd_set *write_fd_set,
-               fd_set *except_fd_set,
-               MHD_socket *max_fd,
-               unsigned int fd_setsize)
+                fd_set *read_fd_set,
+                fd_set *write_fd_set,
+                fd_set *except_fd_set,
+                MHD_socket *max_fd,
+                unsigned int fd_setsize)
 {
-  struct MHD_Connection *pos;
+  fd_set es;
 
-  if ( (NULL == daemon)
-       || (NULL == read_fd_set)
-       || (NULL == write_fd_set)
-       || (MHD_YES == daemon->shutdown)
-       || (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
-       || (0 != (daemon->options & MHD_USE_POLL)))
-    return MHD_NO;
-#if EPOLL_SUPPORT
-  if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-    {
-      /* we're in epoll mode, use the epoll FD as a stand-in for
-	 the entire event set */
-
-      return add_to_fd_set (daemon->epoll_fd, read_fd_set, max_fd, fd_setsize);
-    }
-#endif
-  if (MHD_INVALID_SOCKET != daemon->socket_fd &&
-      MHD_YES != add_to_fd_set (daemon->socket_fd, read_fd_set, max_fd, fd_setsize))
+  if ( (NULL == daemon) ||
+       (NULL == read_fd_set) ||
+       (NULL == write_fd_set) ||
+       (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) ||
+       (0 != (daemon->options & MHD_USE_POLL)))
     return MHD_NO;
 
-  for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
-    {
-      switch (pos->event_loop_info)
-	{
-	case MHD_EVENT_LOOP_INFO_READ:
-	  if (MHD_YES != add_to_fd_set (pos->socket_fd, read_fd_set, max_fd, fd_setsize))
-	    return MHD_NO;
-	  break;
-	case MHD_EVENT_LOOP_INFO_WRITE:
-	  if (MHD_YES != add_to_fd_set (pos->socket_fd, write_fd_set, max_fd, fd_setsize))
-	    return MHD_NO;
-	  if (pos->read_buffer_size > pos->read_buffer_offset &&
-	      MHD_YES != add_to_fd_set (pos->socket_fd, read_fd_set, max_fd, fd_setsize))
-            return MHD_NO;
-	  break;
-	case MHD_EVENT_LOOP_INFO_BLOCK:
-	  if (pos->read_buffer_size > pos->read_buffer_offset &&
-	      MHD_YES != add_to_fd_set (pos->socket_fd, read_fd_set, max_fd, fd_setsize))
-            return MHD_NO;
-	  break;
-	case MHD_EVENT_LOOP_INFO_CLEANUP:
-	  /* this should never happen */
-	  break;
-	}
-    }
-#if DEBUG_CONNECT
-#if HAVE_MESSAGES
-  if (NULL != max_fd)
+  if (NULL == except_fd_set)
+  {   /* Workaround to maintain backward compatibility. */
+#ifdef HAVE_MESSAGES
     MHD_DLOG (daemon,
-              "Maximum socket in select set: %d\n",
-              *max_fd);
+              _ ("MHD_get_fdset2() called with except_fd_set "
+                 "set to NULL. Such behavior is unsupported.\n"));
 #endif
+    FD_ZERO (&es);
+    except_fd_set = &es;
+  }
+
+#ifdef EPOLL_SUPPORT
+  if (0 != (daemon->options & MHD_USE_EPOLL))
+  {
+    if (daemon->shutdown)
+      return MHD_NO;
+
+    /* we're in epoll mode, use the epoll FD as a stand-in for
+       the entire event set */
+
+    return MHD_add_to_fd_set_ (daemon->epoll_fd,
+                               read_fd_set,
+                               max_fd,
+                               fd_setsize) ? MHD_YES : MHD_NO;
+  }
 #endif
-  return MHD_YES;
+
+  return internal_get_fdset2 (daemon,
+                              read_fd_set,
+                              write_fd_set,
+                              except_fd_set,
+                              max_fd,
+                              fd_setsize);
+}
+
+
+/**
+ * Call the handlers for a connection in the appropriate order based
+ * on the readiness as detected by the event loop.
+ *
+ * @param con connection to handle
+ * @param read_ready set if the socket is ready for reading
+ * @param write_ready set if the socket is ready for writing
+ * @param force_close set if a hard error was detected on the socket;
+ *        if this information is not available, simply pass #MHD_NO
+ * @return #MHD_YES to continue normally,
+ *         #MHD_NO if a serious error was encountered and the
+ *         connection is to be closed.
+ */
+static enum MHD_Result
+call_handlers (struct MHD_Connection *con,
+               bool read_ready,
+               bool write_ready,
+               bool force_close)
+{
+  enum MHD_Result ret;
+  bool states_info_processed = false;
+  /* Fast track flag */
+  bool on_fasttrack = (con->state == MHD_CONNECTION_INIT);
+  ret = MHD_YES;
+
+#ifdef HTTPS_SUPPORT
+  if (con->tls_read_ready)
+    read_ready = true;
+#endif /* HTTPS_SUPPORT */
+  if ( (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) &&
+       (read_ready || (force_close && con->sk_nonblck)) )
+  {
+    MHD_connection_handle_read (con, force_close);
+    mhd_assert (! force_close || MHD_CONNECTION_CLOSED == con->state);
+    ret = MHD_connection_handle_idle (con);
+    if (force_close)
+      return ret;
+    states_info_processed = true;
+  }
+  if (! force_close)
+  {
+    /* No need to check value of 'ret' here as closed connection
+     * cannot be in MHD_EVENT_LOOP_INFO_WRITE state. */
+    if ( (MHD_EVENT_LOOP_INFO_WRITE == con->event_loop_info) &&
+         write_ready)
+    {
+      MHD_connection_handle_write (con);
+      ret = MHD_connection_handle_idle (con);
+      states_info_processed = true;
+    }
+  }
+  else
+  {
+    MHD_connection_close_ (con,
+                           MHD_REQUEST_TERMINATED_WITH_ERROR);
+    return MHD_connection_handle_idle (con);
+  }
+
+  if (! states_info_processed)
+  {   /* Connection is not read or write ready, but external conditions
+       * may be changed and need to be processed. */
+    ret = MHD_connection_handle_idle (con);
+  }
+  /* Fast track for fast connections. */
+  /* If full request was read by single read_handler() invocation
+     and headers were completely prepared by single MHD_connection_handle_idle()
+     then try not to wait for next sockets polling and send response
+     immediately.
+     As writeability of socket was not checked and it may have
+     some data pending in system buffers, use this optimization
+     only for non-blocking sockets. */
+  /* No need to check 'ret' as connection is always in
+   * MHD_CONNECTION_CLOSED state if 'ret' is equal 'MHD_NO'. */
+  else if (on_fasttrack && con->sk_nonblck)
+  {
+    if (MHD_CONNECTION_HEADERS_SENDING == con->state)
+    {
+      MHD_connection_handle_write (con);
+      /* Always call 'MHD_connection_handle_idle()' after each read/write. */
+      ret = MHD_connection_handle_idle (con);
+    }
+    /* If all headers were sent by single write_handler() and
+     * response body is prepared by single MHD_connection_handle_idle()
+     * call - continue. */
+    if ((MHD_CONNECTION_NORMAL_BODY_READY == con->state) ||
+        (MHD_CONNECTION_CHUNKED_BODY_READY == con->state))
+    {
+      MHD_connection_handle_write (con);
+      ret = MHD_connection_handle_idle (con);
+    }
+  }
+
+  /* All connection's data and states are processed for this turn.
+   * If connection already has more data to be processed - use
+   * zero timeout for next select()/poll(). */
+  /* Thread-per-connection do not need global zero timeout as
+   * connections are processed individually. */
+  /* Note: no need to check for read buffer availability for
+   * TLS read-ready connection in 'read info' state as connection
+   * without space in read buffer will be marked as 'info block'. */
+  if ( (! con->daemon->data_already_pending) &&
+       (0 == (con->daemon->options & MHD_USE_THREAD_PER_CONNECTION)) )
+  {
+    if (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info))
+      con->daemon->data_already_pending = true;
+#ifdef HTTPS_SUPPORT
+    else if ( (con->tls_read_ready) &&
+              (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) )
+      con->daemon->data_already_pending = true;
+#endif /* HTTPS_SUPPORT */
+  }
+  return ret;
+}
+
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * Finally cleanup upgrade-related resources. It should
+ * be called when TLS buffers have been drained and
+ * application signaled MHD by #MHD_UPGRADE_ACTION_CLOSE.
+ *
+ * @param connection handle to the upgraded connection to clean
+ */
+static void
+cleanup_upgraded_connection (struct MHD_Connection *connection)
+{
+  struct MHD_UpgradeResponseHandle *urh = connection->urh;
+
+  if (NULL == urh)
+    return;
+#ifdef HTTPS_SUPPORT
+  /* Signal remote client the end of TLS connection by
+   * gracefully closing TLS session. */
+  if (0 != (connection->daemon->options & MHD_USE_TLS))
+    gnutls_bye (connection->tls_session,
+                GNUTLS_SHUT_WR);
+
+  if (MHD_INVALID_SOCKET != urh->mhd.socket)
+    MHD_socket_close_chk_ (urh->mhd.socket);
+
+  if (MHD_INVALID_SOCKET != urh->app.socket)
+    MHD_socket_close_chk_ (urh->app.socket);
+#endif /* HTTPS_SUPPORT */
+  connection->urh = NULL;
+  free (urh);
+}
+
+
+#endif /* UPGRADE_SUPPORT */
+
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+/**
+ * Performs bi-directional forwarding on upgraded HTTPS connections
+ * based on the readiness state stored in the @a urh handle.
+ * @remark To be called only from thread that processes
+ * connection's recv(), send() and response.
+ *
+ * @param urh handle to process
+ */
+static void
+process_urh (struct MHD_UpgradeResponseHandle *urh)
+{
+  /* Help compiler to optimize:
+   * pointers to 'connection' and 'daemon' are not changed
+   * during this processing, so no need to chain dereference
+   * each time. */
+  struct MHD_Connection *const connection = urh->connection;
+  struct MHD_Daemon *const daemon = connection->daemon;
+  /* Prevent data races: use same value of 'was_closed' throughout
+   * this function. If 'was_closed' changed externally in the middle
+   * of processing - it will be processed on next iteration. */
+  bool was_closed;
+
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (connection->pid) );
+#endif /* MHD_USE_THREADS */
+  if (daemon->shutdown)
+  {
+    /* Daemon shutting down, application will not receive any more data. */
+#ifdef HAVE_MESSAGES
+    if (! urh->was_closed)
+    {
+      MHD_DLOG (daemon,
+                _ ("Initiated daemon shutdown while \"upgraded\" " \
+                   "connection was not closed.\n"));
+    }
+#endif
+    urh->was_closed = true;
+  }
+  was_closed = urh->was_closed;
+  if (was_closed)
+  {
+    /* Application was closed connections: no more data
+     * can be forwarded to application socket. */
+    if (0 < urh->in_buffer_used)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to forward to application %" PRIu64 \
+                   " bytes of data received from remote side: " \
+                   "application shut down socket.\n"),
+                (uint64_t) urh->in_buffer_used);
+#endif
+
+    }
+    /* If application signaled MHD about socket closure then
+     * check for any pending data even if socket is not marked
+     * as 'ready' (signal may arrive after poll()/select()).
+     * Socketpair for forwarding is always in non-blocking mode
+     * so no risk that recv() will block the thread. */
+    if (0 != urh->out_buffer_size)
+      urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+    /* Discard any data received form remote. */
+    urh->in_buffer_used = 0;
+    /* Do not try to push data to application. */
+    urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+    /* Reading from remote client is not required anymore. */
+    urh->in_buffer_size = 0;
+    urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+    connection->tls_read_ready = false;
+  }
+
+  /* On some platforms (W32, possibly Darwin) failed send() (send() will
+   * always fail after remote disconnect was detected) may discard data in
+   * system buffers received by system but not yet read by recv().  So, before
+   * trying send() on any socket, recv() must be performed at first otherwise
+   * last part of incoming data may be lost.  If disconnect or error was
+   * detected - try to read from socket to dry data possibly pending is system
+   * buffers. */
+  if (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi))
+    urh->app.celi |= MHD_EPOLL_STATE_READ_READY;
+  if (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi))
+    urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY;
+
+  /*
+   * handle reading from remote TLS client
+   */
+  if ( ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->app.celi)) ||
+         (connection->tls_read_ready) ) &&
+       (urh->in_buffer_used < urh->in_buffer_size) )
+  {
+    ssize_t res;
+    size_t buf_size;
+
+    buf_size = urh->in_buffer_size - urh->in_buffer_used;
+    if (buf_size > SSIZE_MAX)
+      buf_size = SSIZE_MAX;
+
+    connection->tls_read_ready = false;
+    res = gnutls_record_recv (connection->tls_session,
+                              &urh->in_buffer[urh->in_buffer_used],
+                              buf_size);
+    if (0 >= res)
+    {
+      if (GNUTLS_E_INTERRUPTED != res)
+      {
+        urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+        if (GNUTLS_E_AGAIN != res)
+        {
+          /* Unrecoverable error on socket was detected or
+           * socket was disconnected/shut down. */
+          /* Stop trying to read from this TLS socket. */
+          urh->in_buffer_size = 0;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      urh->in_buffer_used += (size_t) res;
+      if (0 < gnutls_record_check_pending (connection->tls_session))
+      {
+        connection->tls_read_ready = true;
+      }
+    }
+    if (MHD_EPOLL_STATE_ERROR ==
+        ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) & urh->app.celi))
+    {
+      /* Unrecoverable error on socket was detected and all
+       * pending data was read from system buffers. */
+      /* Stop trying to read from this TLS socket. */
+      urh->in_buffer_size = 0;
+    }
+  }
+
+  /*
+   * handle reading from application
+   */
+  if ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->mhd.celi)) &&
+       (urh->out_buffer_used < urh->out_buffer_size) )
+  {
+    ssize_t res;
+    size_t buf_size;
+
+    buf_size = urh->out_buffer_size - urh->out_buffer_used;
+    if (buf_size > MHD_SCKT_SEND_MAX_SIZE_)
+      buf_size = MHD_SCKT_SEND_MAX_SIZE_;
+
+    res = MHD_recv_ (urh->mhd.socket,
+                     &urh->out_buffer[urh->out_buffer_used],
+                     buf_size);
+    if (0 >= res)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if ((0 == res) ||
+          ((! MHD_SCKT_ERR_IS_EINTR_ (err)) &&
+           (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))))
+      {
+        urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+        if ((0 == res) ||
+            (was_closed) ||
+            (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ||
+            (! MHD_SCKT_ERR_IS_EAGAIN_ (err)))
+        {
+          /* Socket disconnect/shutdown was detected;
+           * Application signaled about closure of 'upgraded' socket;
+           * or persistent / unrecoverable error. */
+          /* Do not try to pull more data from application. */
+          urh->out_buffer_size = 0;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      urh->out_buffer_used += (size_t) res;
+      if (buf_size > (size_t) res)
+        urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+    }
+    if ( (0 == (MHD_EPOLL_STATE_READ_READY & urh->mhd.celi)) &&
+         ( (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ||
+           (was_closed) ) )
+    {
+      /* Unrecoverable error on socket was detected and all
+       * pending data was read from system buffers. */
+      /* Do not try to pull more data from application. */
+      urh->out_buffer_size = 0;
+    }
+  }
+
+  /*
+   * handle writing to remote HTTPS client
+   */
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) &&
+       (urh->out_buffer_used > 0) )
+  {
+    ssize_t res;
+    size_t data_size;
+
+    data_size = urh->out_buffer_used;
+    if (data_size > SSIZE_MAX)
+      data_size = SSIZE_MAX;
+
+    res = gnutls_record_send (connection->tls_session,
+                              urh->out_buffer,
+                              data_size);
+    if (0 >= res)
+    {
+      if (GNUTLS_E_INTERRUPTED != res)
+      {
+        urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+        if (GNUTLS_E_AGAIN != res)
+        {
+          /* TLS connection shut down or
+           * persistent / unrecoverable error. */
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Failed to forward to remote client %" PRIu64 \
+                       " bytes of data received from application: %s\n"),
+                    (uint64_t) urh->out_buffer_used,
+                    gnutls_strerror ((int) res));
+#endif
+          /* Discard any data unsent to remote. */
+          urh->out_buffer_used = 0;
+          /* Do not try to pull more data from application. */
+          urh->out_buffer_size = 0;
+          urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      const size_t next_out_buffer_used = urh->out_buffer_used - (size_t) res;
+      if (0 != next_out_buffer_used)
+      {
+        memmove (urh->out_buffer,
+                 &urh->out_buffer[res],
+                 next_out_buffer_used);
+        if (data_size > (size_t) res)
+          urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+      }
+      urh->out_buffer_used = next_out_buffer_used;
+    }
+    if ( (0 == urh->out_buffer_used) &&
+         (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi)) )
+    {
+      /* Unrecoverable error on socket was detected and all
+       * pending data was sent to remote. */
+      /* Do not try to send to remote anymore. */
+      urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+      /* Do not try to pull more data from application. */
+      urh->out_buffer_size = 0;
+      urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+    }
+  }
+
+  /*
+   * handle writing to application
+   */
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) &&
+       (urh->in_buffer_used > 0) )
+  {
+    ssize_t res;
+    size_t data_size;
+
+    data_size = urh->in_buffer_used;
+    if (data_size > MHD_SCKT_SEND_MAX_SIZE_)
+      data_size = MHD_SCKT_SEND_MAX_SIZE_;
+
+    res = MHD_send_ (urh->mhd.socket,
+                     urh->in_buffer,
+                     data_size);
+    if (0 >= res)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if ( (! MHD_SCKT_ERR_IS_EINTR_ (err)) &&
+           (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) )
+      {
+        urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+        if (! MHD_SCKT_ERR_IS_EAGAIN_ (err))
+        {
+          /* Socketpair connection shut down or
+           * persistent / unrecoverable error. */
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Failed to forward to application %" PRIu64 \
+                       " bytes of data received from remote side: %s\n"),
+                    (uint64_t) urh->in_buffer_used,
+                    MHD_socket_strerr_ (err));
+#endif
+          /* Discard any data received form remote. */
+          urh->in_buffer_used = 0;
+          /* Reading from remote client is not required anymore. */
+          urh->in_buffer_size = 0;
+          urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+          connection->tls_read_ready = false;
+        }
+      }
+    }
+    else   /* 0 < res */
+    {
+      const size_t next_in_buffer_used = urh->in_buffer_used - (size_t) res;
+      if (0 != next_in_buffer_used)
+      {
+        memmove (urh->in_buffer,
+                 &urh->in_buffer[res],
+                 next_in_buffer_used);
+        if (data_size > (size_t) res)
+          urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+      }
+      urh->in_buffer_used = next_in_buffer_used;
+    }
+    if ( (0 == urh->in_buffer_used) &&
+         (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) )
+    {
+      /* Do not try to push data to application. */
+      urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+      /* Reading from remote client is not required anymore. */
+      urh->in_buffer_size = 0;
+      urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+      connection->tls_read_ready = false;
+    }
+  }
+
+  /* Check whether data is present in TLS buffers
+   * and incoming forward buffer have some space. */
+  if ( (connection->tls_read_ready) &&
+       (urh->in_buffer_used < urh->in_buffer_size) &&
+       (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) )
+    daemon->data_already_pending = true;
+
+  if ( (daemon->shutdown) &&
+       ( (0 != urh->out_buffer_size) ||
+         (0 != urh->out_buffer_used) ) )
+  {
+    /* Daemon shutting down, discard any remaining forward data. */
+#ifdef HAVE_MESSAGES
+    if (0 < urh->out_buffer_used)
+      MHD_DLOG (daemon,
+                _ ("Failed to forward to remote client %" PRIu64 \
+                   " bytes of data received from application: daemon shut down.\n"),
+                (uint64_t) urh->out_buffer_used);
+#endif
+    /* Discard any data unsent to remote. */
+    urh->out_buffer_used = 0;
+    /* Do not try to sent to remote anymore. */
+    urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+    /* Do not try to pull more data from application. */
+    urh->out_buffer_size = 0;
+    urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY);
+  }
+}
+
+
+#endif /* HTTPS_SUPPORT  && UPGRADE_SUPPORT */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#ifdef UPGRADE_SUPPORT
+/**
+ * Main function of the thread that handles an individual connection
+ * after it was "upgraded" when #MHD_USE_THREAD_PER_CONNECTION is set.
+ * @remark To be called only from thread that process
+ * connection's recv(), send() and response.
+ *
+ * @param con the connection this thread will handle
+ */
+static void
+thread_main_connection_upgrade (struct MHD_Connection *con)
+{
+#ifdef HTTPS_SUPPORT
+  struct MHD_UpgradeResponseHandle *urh = con->urh;
+  struct MHD_Daemon *daemon = con->daemon;
+
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (con->pid) );
+  /* Here, we need to bi-directionally forward
+     until the application tells us that it is done
+     with the socket; */
+  if ( (0 != (daemon->options & MHD_USE_TLS)) &&
+       (0 == (daemon->options & MHD_USE_POLL)))
+  {
+    while ( (0 != urh->in_buffer_size) ||
+            (0 != urh->out_buffer_size) ||
+            (0 != urh->in_buffer_used) ||
+            (0 != urh->out_buffer_used) )
+    {
+      /* use select */
+      fd_set rs;
+      fd_set ws;
+      fd_set es;
+      MHD_socket max_fd;
+      int num_ready;
+      bool result;
+
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      max_fd = MHD_INVALID_SOCKET;
+      result = urh_to_fdset (urh,
+                             &rs,
+                             &ws,
+                             &es,
+                             &max_fd,
+                             FD_SETSIZE);
+      if (! result)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  _ ("Error preparing select.\n"));
+#endif
+        break;
+      }
+      /* FIXME: does this check really needed? */
+      if (MHD_INVALID_SOCKET != max_fd)
+      {
+        struct timeval *tvp;
+        struct timeval tv;
+        if (((con->tls_read_ready) &&
+             (urh->in_buffer_used < urh->in_buffer_size)) ||
+            (daemon->shutdown))
+        {         /* No need to wait if incoming data is already pending in TLS buffers. */
+          tv.tv_sec = 0;
+          tv.tv_usec = 0;
+          tvp = &tv;
+        }
+        else
+          tvp = NULL;
+        num_ready = MHD_SYS_select_ (max_fd + 1,
+                                     &rs,
+                                     &ws,
+                                     &es,
+                                     tvp);
+      }
+      else
+        num_ready = 0;
+      if (num_ready < 0)
+      {
+        const int err = MHD_socket_get_error_ ();
+
+        if (MHD_SCKT_ERR_IS_EINTR_ (err))
+          continue;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  _ ("Error during select (%d): `%s'\n"),
+                  err,
+                  MHD_socket_strerr_ (err));
+#endif
+        break;
+      }
+      urh_from_fdset (urh,
+                      &rs,
+                      &ws,
+                      &es);
+      process_urh (urh);
+    }
+  }
+#ifdef HAVE_POLL
+  else if (0 != (daemon->options & MHD_USE_TLS))
+  {
+    /* use poll() */
+    struct pollfd p[2];
+    memset (p,
+            0,
+            sizeof (p));
+    p[0].fd = urh->connection->socket_fd;
+    p[1].fd = urh->mhd.socket;
+
+    while ( (0 != urh->in_buffer_size) ||
+            (0 != urh->out_buffer_size) ||
+            (0 != urh->in_buffer_used) ||
+            (0 != urh->out_buffer_used) )
+    {
+      int timeout;
+
+      urh_update_pollfd (urh, p);
+
+      if (((con->tls_read_ready) &&
+           (urh->in_buffer_used < urh->in_buffer_size)) ||
+          (daemon->shutdown))
+        timeout = 0;     /* No need to wait if incoming data is already pending in TLS buffers. */
+      else
+        timeout = -1;
+
+      if (MHD_sys_poll_ (p,
+                         2,
+                         timeout) < 0)
+      {
+        const int err = MHD_socket_get_error_ ();
+
+        if (MHD_SCKT_ERR_IS_EINTR_ (err))
+          continue;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  _ ("Error during poll: `%s'\n"),
+                  MHD_socket_strerr_ (err));
+#endif
+        break;
+      }
+      urh_from_pollfd (urh,
+                       p);
+      process_urh (urh);
+    }
+  }
+  /* end POLL */
+#endif
+  /* end HTTPS */
+#endif /* HTTPS_SUPPORT */
+  /* TLS forwarding was finished. Cleanup socketpair. */
+  MHD_connection_finish_forward_ (con);
+  /* Do not set 'urh->clean_ready' yet as 'urh' will be used
+   * in connection thread for a little while. */
+}
+
+
+#endif /* UPGRADE_SUPPORT */
+
+
+/**
+ * Get maximum wait period for the connection (the amount of time left before
+ * connection time out)
+ * @param c the connection to check
+ * @return the maximum number of millisecond before the connection must be
+ *         processed again.
+ */
+static uint64_t
+connection_get_wait (struct MHD_Connection *c)
+{
+  const uint64_t now = MHD_monotonic_msec_counter ();
+  const uint64_t since_actv = now - c->last_activity;
+  const uint64_t timeout = c->connection_timeout_ms;
+  uint64_t mseconds_left;
+
+  mhd_assert (0 != timeout);
+  /* Keep the next lines in sync with #connection_check_timedout() to avoid
+   * undesired side-effects like busy-waiting. */
+  if (timeout < since_actv)
+  {
+    if (UINT64_MAX / 2 < since_actv)
+    {
+      const uint64_t jump_back = c->last_activity - now;
+      /* Very unlikely that it is more than quarter-million years pause.
+       * More likely that system clock jumps back. */
+      if (5000 >= jump_back)
+      { /* Jump back is less than 5 seconds, try to recover. */
+        return 100; /* Set wait time to 0.1 seconds */
+      }
+      /* Too large jump back */
+    }
+    return 0; /* Connection has timed out */
+  }
+  else if (since_actv == timeout)
+  {
+    /* Exact match for timeout and time from last activity.
+     * Maybe this is just a precise match or this happens because the timer
+     * resolution is too low.
+     * Set wait time to 0.1 seconds to avoid busy-waiting with low
+     * timer resolution as connection is not timed-out yet. */
+    return 100;
+  }
+  mseconds_left = timeout - since_actv;
+
+  return mseconds_left;
 }
 
 
@@ -892,22 +1877,18 @@
  * @return always 0
  */
 static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
-MHD_handle_connection (void *data)
+thread_main_handle_connection (void *data)
 {
   struct MHD_Connection *con = data;
+  struct MHD_Daemon *daemon = con->daemon;
   int num_ready;
   fd_set rs;
   fd_set ws;
-  MHD_socket max;
-  struct timeval tv;
-  struct timeval *tvp;
-  unsigned int timeout;
-  time_t now;
-#if WINDOWS
-  MHD_pipe spipe = con->daemon->wpipe[0];
-  char tmp;
+  fd_set es;
+  MHD_socket maxsock;
+#ifdef WINDOWS
 #ifdef HAVE_POLL
-  int extra_slot;
+  unsigned int extra_slot;
 #endif /* HAVE_POLL */
 #define EXTRA_SLOTS 1
 #else  /* !WINDOWS */
@@ -916,404 +1897,1036 @@
 #ifdef HAVE_POLL
   struct pollfd p[1 + EXTRA_SLOTS];
 #endif
-
-  timeout = con->daemon->connection_timeout;
-  while ( (MHD_YES != con->daemon->shutdown) &&
-	  (MHD_CONNECTION_CLOSED != con->state) )
-    {
-      tvp = NULL;
-      if (timeout > 0)
-	{
-	  now = MHD_monotonic_time();
-	  if (now - con->last_activity > timeout)
-	    tv.tv_sec = 0;
-	  else
-	    tv.tv_sec = timeout - (now - con->last_activity);
-	  tv.tv_usec = 0;
-	  tvp = &tv;
-	}
-#if HTTPS_SUPPORT
-      if (MHD_YES == con->tls_read_ready)
-	{
-	  /* do not block (more data may be inside of TLS buffers waiting for us) */
-	  tv.tv_sec = 0;
-	  tv.tv_usec = 0;
-	  tvp = &tv;
-	}
-#endif
-      if (0 == (con->daemon->options & MHD_USE_POLL))
-	{
-	  /* use select */
-	  int err_state = 0;
-	  FD_ZERO (&rs);
-	  FD_ZERO (&ws);
-	  max = 0;
-	  switch (con->event_loop_info)
-	    {
-	    case MHD_EVENT_LOOP_INFO_READ:
-	      if (MHD_YES !=
-                  add_to_fd_set (con->socket_fd, &rs, &max, FD_SETSIZE))
-	        err_state = 1;
-	      break;
-	    case MHD_EVENT_LOOP_INFO_WRITE:
-	      if (MHD_YES !=
-                  add_to_fd_set (con->socket_fd, &ws, &max, FD_SETSIZE))
-                err_state = 1;
-	      if ( (con->read_buffer_size > con->read_buffer_offset) &&
-                   (MHD_YES !=
-                    add_to_fd_set (con->socket_fd, &rs, &max, FD_SETSIZE)) )
-	        err_state = 1;
-	      break;
-	    case MHD_EVENT_LOOP_INFO_BLOCK:
-	      if ( (con->read_buffer_size > con->read_buffer_offset) &&
-                   (MHD_YES !=
-                    add_to_fd_set (con->socket_fd, &rs, &max, FD_SETSIZE)) )
-	        err_state = 1;
-	      tv.tv_sec = 0;
-	      tv.tv_usec = 0;
-	      tvp = &tv;
-	      break;
-	    case MHD_EVENT_LOOP_INFO_CLEANUP:
-	      /* how did we get here!? */
-	      goto exit;
-	    }
-#if WINDOWS
-          if (MHD_INVALID_PIPE_ != spipe)
-            {
-              if (MHD_YES !=
-                  add_to_fd_set (spipe, &rs, &max, FD_SETSIZE))
-                err_state = 1;
-            }
-#endif
-            if (0 != err_state)
-              {
-#if HAVE_MESSAGES
-                MHD_DLOG (con->daemon,
-                          "Can't add FD to fd_set\n");
-#endif
-                goto exit;
-              }
-
-	  num_ready = MHD_SYS_select_ (max + 1, &rs, &ws, NULL, tvp);
-	  if (num_ready < 0)
-	    {
-	      if (EINTR == MHD_socket_errno_)
-		continue;
-#if HAVE_MESSAGES
-	      MHD_DLOG (con->daemon,
-			"Error during select (%d): `%s'\n",
-			MHD_socket_errno_,
-			MHD_socket_last_strerr_ ());
-#endif
-	      break;
-	    }
-#if WINDOWS
-          /* drain signaling pipe */
-          if ( (MHD_INVALID_PIPE_ != spipe) &&
-               (FD_ISSET (spipe, &rs)) )
-            (void) MHD_pipe_read_ (spipe, &tmp, sizeof (tmp));
-#endif
-	  /* call appropriate connection handler if necessary */
-	  if ( (FD_ISSET (con->socket_fd, &rs))
-#if HTTPS_SUPPORT
-	       || (MHD_YES == con->tls_read_ready)
-#endif
-	       )
-	    con->read_handler (con);
-	  if (FD_ISSET (con->socket_fd, &ws))
-	    con->write_handler (con);
-	  if (MHD_NO == con->idle_handler (con))
-	    goto exit;
-	}
+#undef EXTRA_SLOTS
 #ifdef HAVE_POLL
+  const bool use_poll = (0 != (daemon->options & MHD_USE_POLL));
+#else  /* ! HAVE_POLL */
+  const bool use_poll = 0;
+#endif /* ! HAVE_POLL */
+  bool was_suspended = false;
+  MHD_thread_init_ (&(con->pid));
+
+  while ( (! daemon->shutdown) &&
+          (MHD_CONNECTION_CLOSED != con->state) )
+  {
+    bool use_zero_timeout;
+#ifdef UPGRADE_SUPPORT
+    struct MHD_UpgradeResponseHandle *const urh = con->urh;
+#else  /* ! UPGRADE_SUPPORT */
+    static const void *const urh = NULL;
+#endif /* ! UPGRADE_SUPPORT */
+
+    if ( (con->suspended) &&
+         (NULL == urh) )
+    {
+      /* Connection was suspended, wait for resume. */
+      was_suspended = true;
+      if (! use_poll)
+      {
+        FD_ZERO (&rs);
+        if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                                  &rs,
+                                  NULL,
+                                  FD_SETSIZE))
+        {
+  #ifdef HAVE_MESSAGES
+          MHD_DLOG (con->daemon,
+                    _ ("Failed to add FD to fd_set.\n"));
+  #endif
+          goto exit;
+        }
+        if (0 > MHD_SYS_select_ (MHD_itc_r_fd_ (daemon->itc) + 1,
+                                 &rs,
+                                 NULL,
+                                 NULL,
+                                 NULL))
+        {
+          const int err = MHD_socket_get_error_ ();
+
+          if (MHD_SCKT_ERR_IS_EINTR_ (err))
+            continue;
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (con->daemon,
+                    _ ("Error during select (%d): `%s'\n"),
+                    err,
+                    MHD_socket_strerr_ (err));
+#endif
+          break;
+        }
+      }
+#ifdef HAVE_POLL
+      else     /* use_poll */
+      {
+        p[0].events = POLLIN;
+        p[0].fd = MHD_itc_r_fd_ (daemon->itc);
+        p[0].revents = 0;
+        if (0 > MHD_sys_poll_ (p,
+                               1,
+                               -1))
+        {
+          if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_))
+            continue;
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (con->daemon,
+                    _ ("Error during poll: `%s'\n"),
+                    MHD_socket_last_strerr_ ());
+#endif
+          break;
+        }
+      }
+#endif /* HAVE_POLL */
+      MHD_itc_clear_ (daemon->itc);
+      continue; /* Check again for resume. */
+    }           /* End of "suspended" branch. */
+
+    if (was_suspended)
+    {
+      MHD_update_last_activity_ (con);     /* Reset timeout timer. */
+      /* Process response queued during suspend and update states. */
+      MHD_connection_handle_idle (con);
+      was_suspended = false;
+    }
+
+    use_zero_timeout =
+      (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info)
+#ifdef HTTPS_SUPPORT
+       || ( (con->tls_read_ready) &&
+            (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) )
+#endif /* HTTPS_SUPPORT */
+      );
+    if (! use_poll)
+    {
+      /* use select */
+      bool err_state = false;
+      struct timeval tv;
+      struct timeval *tvp;
+      if (use_zero_timeout)
+      {
+        tv.tv_sec = 0;
+        tv.tv_usec = 0;
+        tvp = &tv;
+      }
+      else if (con->connection_timeout_ms > 0)
+      {
+        const uint64_t mseconds_left = connection_get_wait (con);
+#if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC
+        if (mseconds_left / 1000 > TIMEVAL_TV_SEC_MAX)
+          tv.tv_sec = TIMEVAL_TV_SEC_MAX;
+        else
+#endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */
+        tv.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) mseconds_left / 1000;
+
+        tv.tv_usec = ((uint16_t) (mseconds_left % 1000)) * ((int32_t) 1000);
+        tvp = &tv;
+      }
       else
-	{
-	  /* use poll */
-	  memset (&p, 0, sizeof (p));
-	  p[0].fd = con->socket_fd;
-	  switch (con->event_loop_info)
-	    {
-	    case MHD_EVENT_LOOP_INFO_READ:
-	      p[0].events |= POLLIN;
-	      break;
-	    case MHD_EVENT_LOOP_INFO_WRITE:
-	      p[0].events |= POLLOUT;
-	      if (con->read_buffer_size > con->read_buffer_offset)
-		p[0].events |= POLLIN;
-	      break;
-	    case MHD_EVENT_LOOP_INFO_BLOCK:
-	      if (con->read_buffer_size > con->read_buffer_offset)
-		p[0].events |= POLLIN;
-	      tv.tv_sec = 0;
-	      tv.tv_usec = 0;
-	      tvp = &tv;
-	      break;
-	    case MHD_EVENT_LOOP_INFO_CLEANUP:
-	      /* how did we get here!? */
-	      goto exit;
-	    }
-#if WINDOWS
-          extra_slot = 0;
-          if (MHD_INVALID_PIPE_ != spipe)
-            {
-              p[1].events |= POLLIN;
-              p[1].fd = spipe;
-              p[1].revents = 0;
-              extra_slot = 1;
-            }
+        tvp = NULL;
+
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      maxsock = MHD_INVALID_SOCKET;
+      switch (con->event_loop_info)
+      {
+      case MHD_EVENT_LOOP_INFO_READ:
+      case MHD_EVENT_LOOP_INFO_PROCESS_READ:
+        if (! MHD_add_to_fd_set_ (con->socket_fd,
+                                  &rs,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = true;
+        break;
+      case MHD_EVENT_LOOP_INFO_WRITE:
+        if (! MHD_add_to_fd_set_ (con->socket_fd,
+                                  &ws,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = true;
+        break;
+      case MHD_EVENT_LOOP_INFO_PROCESS:
+        if (! MHD_add_to_fd_set_ (con->socket_fd,
+                                  &es,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = true;
+        break;
+      case MHD_EVENT_LOOP_INFO_CLEANUP:
+        /* how did we get here!? */
+        goto exit;
+      }
+#ifdef WINDOWS
+      if (MHD_ITC_IS_VALID_ (daemon->itc) )
+      {
+        if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                                  &rs,
+                                  &maxsock,
+                                  FD_SETSIZE))
+          err_state = 1;
+      }
 #endif
-	  if (MHD_sys_poll_ (p,
-#if WINDOWS
-                    1 + extra_slot,
+      if (err_state)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  _ ("Failed to add FD to fd_set.\n"));
+#endif
+        goto exit;
+      }
+
+      num_ready = MHD_SYS_select_ (maxsock + 1,
+                                   &rs,
+                                   &ws,
+                                   &es,
+                                   tvp);
+      if (num_ready < 0)
+      {
+        const int err = MHD_socket_get_error_ ();
+
+        if (MHD_SCKT_ERR_IS_EINTR_ (err))
+          continue;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  _ ("Error during select (%d): `%s'\n"),
+                  err,
+                  MHD_socket_strerr_ (err));
+#endif
+        break;
+      }
+#ifdef WINDOWS
+      /* Clear ITC before other processing so additional
+       * signals will trigger select() again */
+      if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+           (FD_ISSET (MHD_itc_r_fd_ (daemon->itc),
+                      &rs)) )
+        MHD_itc_clear_ (daemon->itc);
+#endif
+      if (MHD_NO ==
+          call_handlers (con,
+                         FD_ISSET (con->socket_fd,
+                                   &rs),
+                         FD_ISSET (con->socket_fd,
+                                   &ws),
+                         FD_ISSET (con->socket_fd,
+                                   &es)) )
+        goto exit;
+    }
+#ifdef HAVE_POLL
+    else
+    {
+      int timeout_val;
+      /* use poll */
+      if (use_zero_timeout)
+        timeout_val = 0;
+      else if (con->connection_timeout_ms > 0)
+      {
+        const uint64_t mseconds_left = connection_get_wait (con);
+#if SIZEOF_UINT64_T >= SIZEOF_INT
+        if (mseconds_left >= INT_MAX)
+          timeout_val = INT_MAX;
+        else
+#endif /* SIZEOF_UINT64_T >= SIZEOF_INT */
+        timeout_val = (int) mseconds_left;
+      }
+      else
+        timeout_val = -1;
+      memset (&p,
+              0,
+              sizeof (p));
+      p[0].fd = con->socket_fd;
+      switch (con->event_loop_info)
+      {
+      case MHD_EVENT_LOOP_INFO_READ:
+      case MHD_EVENT_LOOP_INFO_PROCESS_READ:
+        p[0].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_WRITE:
+        p[0].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_PROCESS:
+        p[0].events |= MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_CLEANUP:
+        /* how did we get here!? */
+        goto exit;
+      }
+#ifdef WINDOWS
+      extra_slot = 0;
+      if (MHD_ITC_IS_VALID_ (daemon->itc))
+      {
+        p[1].events |= POLLIN;
+        p[1].fd = MHD_itc_r_fd_ (daemon->itc);
+        p[1].revents = 0;
+        extra_slot = 1;
+      }
+#endif
+      if (MHD_sys_poll_ (p,
+#ifdef WINDOWS
+                         1 + extra_slot,
 #else
-                    1,
+                         1,
 #endif
-		    (NULL == tvp) ? -1 : tv.tv_sec * 1000) < 0)
-	    {
-	      if (EINTR == MHD_socket_errno_)
-		continue;
-#if HAVE_MESSAGES
-	      MHD_DLOG (con->daemon,
-                        "Error during poll: `%s'\n",
-			MHD_socket_last_strerr_ ());
+                         timeout_val) < 0)
+      {
+        if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_))
+          continue;
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (con->daemon,
+                  _ ("Error during poll: `%s'\n"),
+                  MHD_socket_last_strerr_ ());
 #endif
-	      break;
-	    }
-#if WINDOWS
-          /* drain signaling pipe */
-          if ( (MHD_INVALID_PIPE_ != spipe) &&
-               (0 != (p[1].revents & (POLLERR | POLLHUP))) )
-            (void) MHD_pipe_read_ (spipe, &tmp, sizeof (tmp));
+        break;
+      }
+#ifdef WINDOWS
+      /* Clear ITC before other processing so additional
+       * signals will trigger poll() again */
+      if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+           (0 != (p[1].revents & (POLLERR | POLLHUP | POLLIN))) )
+        MHD_itc_clear_ (daemon->itc);
 #endif
-	  if ( (0 != (p[0].revents & POLLIN))
-#if HTTPS_SUPPORT
-	       || (MHD_YES == con->tls_read_ready)
-#endif
-	       )
-	    con->read_handler (con);
-	  if (0 != (p[0].revents & POLLOUT))
-	    con->write_handler (con);
-	  if (0 != (p[0].revents & (POLLERR | POLLHUP)))
-	    MHD_connection_close (con, MHD_REQUEST_TERMINATED_WITH_ERROR);
-	  if (MHD_NO == con->idle_handler (con))
-	    goto exit;
-	}
-#endif
+      if (MHD_NO ==
+          call_handlers (con,
+                         (0 != (p[0].revents & POLLIN)),
+                         (0 != (p[0].revents & POLLOUT)),
+                         (0 != (p[0].revents & MHD_POLL_REVENTS_ERR_DISC)) ))
+        goto exit;
     }
-  if (MHD_CONNECTION_IN_CLEANUP != con->state)
+#endif
+#ifdef UPGRADE_SUPPORT
+    if (MHD_CONNECTION_UPGRADE == con->state)
     {
-#if DEBUG_CLOSE
-#if HAVE_MESSAGES
-      MHD_DLOG (con->daemon,
-                "Processing thread terminating, closing connection\n");
-#endif
-#endif
-      if (MHD_CONNECTION_CLOSED != con->state)
-	MHD_connection_close (con,
-			      MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN);
-      con->idle_handler (con);
+      /* Normal HTTP processing is finished,
+       * notify application. */
+      if ( (NULL != daemon->notify_completed) &&
+           (con->rq.client_aware) )
+        daemon->notify_completed (daemon->notify_completed_cls,
+                                  con,
+                                  &con->rq.client_context,
+                                  MHD_REQUEST_TERMINATED_COMPLETED_OK);
+      con->rq.client_aware = false;
+
+      thread_main_connection_upgrade (con);
+      /* MHD_connection_finish_forward_() was called by thread_main_connection_upgrade(). */
+
+      /* "Upgraded" data will not be used in this thread from this point. */
+      con->urh->clean_ready = true;
+      /* If 'urh->was_closed' set to true, connection will be
+       * moved immediately to cleanup list. Otherwise connection
+       * will stay in suspended list until 'urh' will be marked
+       * with 'was_closed' by application. */
+      MHD_resume_connection (con);
+
+      /* skip usual clean up  */
+      return (MHD_THRD_RTRN_TYPE_) 0;
     }
+#endif /* UPGRADE_SUPPORT */
+  }
+#if _MHD_DEBUG_CLOSE
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (con->daemon,
+            _ ("Processing thread terminating. Closing connection.\n"));
+#endif
+#endif
+  if (MHD_CONNECTION_CLOSED != con->state)
+    MHD_connection_close_ (con,
+                           (daemon->shutdown) ?
+                           MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN :
+                           MHD_REQUEST_TERMINATED_WITH_ERROR);
+  MHD_connection_handle_idle (con);
 exit:
-  if (NULL != con->response)
-    {
-      MHD_destroy_response (con->response);
-      con->response = NULL;
-    }
+  if (NULL != con->rp.response)
+  {
+    MHD_destroy_response (con->rp.response);
+    con->rp.response = NULL;
+  }
 
-  if (NULL != con->daemon->notify_connection)
-    con->daemon->notify_connection (con->daemon->notify_connection_cls,
-                                    con,
-                                    &con->socket_context,
-                                    MHD_CONNECTION_NOTIFY_CLOSED);
-
-  return (MHD_THRD_RTRN_TYPE_)0;
+  if (MHD_INVALID_SOCKET != con->socket_fd)
+  {
+    shutdown (con->socket_fd,
+              SHUT_WR);
+    /* 'socket_fd' can be used in other thread to signal shutdown.
+     * To avoid data races, do not close socket here. Daemon will
+     * use more connections only after cleanup anyway. */
+  }
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc, "t")) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to signal thread termination via inter-thread " \
+                 "communication channel.\n"));
+#endif
+  }
+  return (MHD_THRD_RTRN_TYPE_) 0;
 }
 
 
+#endif
+
+
 /**
- * Callback for receiving data from the socket.
+ * Free resources associated with all closed connections.
+ * (destroy responses, free buffers, etc.).  All closed
+ * connections are kept in the "cleanup" doubly-linked list.
  *
- * @param connection the MHD connection structure
- * @param other where to write received data to
- * @param i maximum size of other (in bytes)
- * @return number of bytes actually received
+ * @param daemon daemon to clean up
+ */
+static void
+MHD_cleanup_connections (struct MHD_Daemon *daemon);
+
+#if defined(HTTPS_SUPPORT)
+#if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \
+  defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \
+  ! defined(MHD_socket_nosignal_) && \
+  (GNUTLS_VERSION_NUMBER + 0 < 0x030402) && defined(MSG_NOSIGNAL)
+/**
+ * Older version of GnuTLS do not support suppressing of SIGPIPE signal.
+ * Use push function replacement with suppressing SIGPIPE signal where necessary
+ * and if possible.
+ */
+#define MHD_TLSLIB_NEED_PUSH_FUNC 1
+#endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED &&
+          MHD_SEND_SPIPE_SUPPRESS_POSSIBLE &&
+          ! MHD_socket_nosignal_ && (GNUTLS_VERSION_NUMBER+0 < 0x030402) &&
+          MSG_NOSIGNAL */
+
+#ifdef MHD_TLSLIB_NEED_PUSH_FUNC
+/**
+ * Data push function replacement with suppressing SIGPIPE signal
+ * for TLS library.
  */
 static ssize_t
-recv_param_adapter (struct MHD_Connection *connection,
-		    void *other,
-		    size_t i)
+MHD_tls_push_func_ (gnutls_transport_ptr_t trnsp,
+                    const void *data,
+                    size_t data_size)
 {
-  ssize_t ret;
-
-  if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
-       (MHD_CONNECTION_CLOSED == connection->state) )
-    {
-      MHD_set_socket_errno_ (ENOTCONN);
-      return -1;
-    }
-  ret = recv (connection->socket_fd, other, i, MSG_NOSIGNAL);
-#if EPOLL_SUPPORT
-  if (ret < (ssize_t) i)
-    {
-      /* partial read --- no longer read-ready */
-      connection->epoll_state &= ~MHD_EPOLL_STATE_READ_READY;
-    }
-#endif
-  return ret;
+#if (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX)
+  if (data_size > MHD_SCKT_SEND_MAX_SIZE_)
+    data_size = MHD_SCKT_SEND_MAX_SIZE_;
+#endif /* (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) */
+  return MHD_send_ ((MHD_socket) (intptr_t) (trnsp), data, data_size);
 }
 
 
-/**
- * Callback for writing data to the socket.
- *
- * @param connection the MHD connection structure
- * @param other data to write
- * @param i number of bytes to write
- * @return actual number of bytes written
- */
-static ssize_t
-send_param_adapter (struct MHD_Connection *connection,
-                    const void *other,
-		    size_t i)
-{
-  ssize_t ret;
-#if LINUX
-  MHD_socket fd;
-  off_t offset;
-  off_t left;
-#endif
-
-  if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
-       (MHD_CONNECTION_CLOSED == connection->state) )
-    {
-      MHD_set_socket_errno_ (ENOTCONN);
-      return -1;
-    }
-  if (0 != (connection->daemon->options & MHD_USE_SSL))
-    return send (connection->socket_fd, other, i, MSG_NOSIGNAL);
-#if LINUX
-  if ( (connection->write_buffer_append_offset ==
-	connection->write_buffer_send_offset) &&
-       (NULL != connection->response) &&
-       (MHD_INVALID_SOCKET != (fd = connection->response->fd)) )
-    {
-      /* can use sendfile */
-      offset = (off_t) connection->response_write_position + connection->response->fd_off;
-      left = connection->response->total_size - connection->response_write_position;
-      if (left > SSIZE_MAX)
-	left = SSIZE_MAX; /* cap at return value limit */
-      if (-1 != (ret = sendfile (connection->socket_fd,
-				 fd,
-				 &offset,
-				 (size_t) left)))
-	{
-#if EPOLL_SUPPORT
-	  if (ret < left)
-	    {
-	      /* partial write --- no longer write-ready */
-	      connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
-	    }
-#endif
-	  return ret;
-	}
-      const int err = MHD_socket_errno_;
-      if ( (EINTR == err) || (EAGAIN == err) || (EWOULDBLOCK == err) )
-	return 0;
-      if ( (EINVAL == err) || (EBADF == err) )
-	return -1;
-      /* None of the 'usual' sendfile errors occurred, so we should try
-	 to fall back to 'SEND'; see also this thread for info on
-	 odd libc/Linux behavior with sendfile:
-	 http://lists.gnu.org/archive/html/libmicrohttpd/2011-02/msg00015.html */
-    }
-#endif
-  ret = send (connection->socket_fd, other, i, MSG_NOSIGNAL);
-#if EPOLL_SUPPORT
-  if (ret < (ssize_t) i)
-    {
-      /* partial write --- no longer write-ready */
-      connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
-    }
-#endif
-  /* Handle broken kernel / libc, returning -1 but not setting errno;
-     kill connection as that should be safe; reported on mailinglist here:
-     http://lists.gnu.org/archive/html/libmicrohttpd/2014-10/msg00023.html */
-  if ( (-1 == ret) && (0 == errno) )
-    errno = ECONNRESET;
-  return ret;
-}
+#endif /* MHD_TLSLIB_DONT_SUPPRESS_SIGPIPE */
 
 
 /**
- * Signature of main function for a thread.
+ * Function called by GNUtls to obtain the PSK for a given session.
  *
- * @param cls closure argument for the function
- * @return termination code from the thread
- */
-typedef MHD_THRD_RTRN_TYPE_ (MHD_THRD_CALL_SPEC_ *ThreadStartRoutine)(void *cls);
-
-
-/**
- * Create a thread and set the attributes according to our options.
- *
- * @param thread handle to initialize
- * @param daemon daemon with options
- * @param start_routine main function of thread
- * @param arg argument for start_routine
- * @return 0 on success
+ * @param session the session to lookup PSK for
+ * @param username username to lookup PSK for
+ * @param[out] key where to write PSK
+ * @return 0 on success, -1 on error
  */
 static int
-create_thread (MHD_thread_handle_ *thread,
-	       const struct MHD_Daemon *daemon,
-	       ThreadStartRoutine start_routine,
-	       void *arg)
+psk_gnutls_adapter (gnutls_session_t session,
+                    const char *username,
+                    gnutls_datum_t *key)
 {
-#if defined(MHD_USE_POSIX_THREADS)
-  pthread_attr_t attr;
-  pthread_attr_t *pattr;
-  int ret;
+  struct MHD_Connection *connection;
+  struct MHD_Daemon *daemon;
+#if GNUTLS_VERSION_MAJOR >= 3
+  void *app_psk;
+  size_t app_psk_size;
+#endif /* GNUTLS_VERSION_MAJOR >= 3 */
 
-  if (0 != daemon->thread_stack_size)
-    {
-      if (0 != (ret = pthread_attr_init (&attr)))
-	goto ERR;
-      if (0 != (ret = pthread_attr_setstacksize (&attr, daemon->thread_stack_size)))
-	{
-	  pthread_attr_destroy (&attr);
-	  goto ERR;
-	}
-      pattr = &attr;
-    }
-  else
-    {
-      pattr = NULL;
-    }
-  ret = pthread_create (thread, pattr,
-			start_routine, arg);
-#ifdef HAVE_PTHREAD_SETNAME_NP
-  (void) pthread_setname_np (*thread, "libmicrohttpd");
-#endif /* HAVE_PTHREAD_SETNAME_NP */
-  if (0 != daemon->thread_stack_size)
-    pthread_attr_destroy (&attr);
-  return ret;
- ERR:
-#if HAVE_MESSAGES
-  MHD_DLOG (daemon,
-	    "Failed to set thread stack size\n");
+  connection = gnutls_session_get_ptr (session);
+  if (NULL == connection)
+  {
+#ifdef HAVE_MESSAGES
+    /* Cannot use our logger, we don't even have "daemon" */
+    MHD_PANIC (_ ("Internal server error. This should be impossible.\n"));
 #endif
-  errno = EINVAL;
-  return ret;
-#elif defined(MHD_USE_W32_THREADS)
-  unsigned threadID;
-  *thread = (HANDLE)_beginthreadex(NULL, (unsigned)daemon->thread_stack_size, start_routine,
-                          arg, 0, &threadID);
-  if (NULL == (*thread))
-    return errno;
-
-  W32_SetThreadName(threadID, "libmicrohttpd");
-
+    return -1;
+  }
+  daemon = connection->daemon;
+#if GNUTLS_VERSION_MAJOR >= 3
+  if (NULL == daemon->cred_callback)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("PSK not supported by this server.\n"));
+#endif
+    return -1;
+  }
+  if (0 != daemon->cred_callback (daemon->cred_callback_cls,
+                                  connection,
+                                  username,
+                                  &app_psk,
+                                  &app_psk_size))
+    return -1;
+  if (NULL == (key->data = gnutls_malloc (app_psk_size)))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("PSK authentication failed: gnutls_malloc failed to " \
+                 "allocate memory.\n"));
+#endif
+    free (app_psk);
+    return -1;
+  }
+  if (UINT_MAX < app_psk_size)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("PSK authentication failed: PSK too long.\n"));
+#endif
+    free (app_psk);
+    return -1;
+  }
+  key->size = (unsigned int) app_psk_size;
+  memcpy (key->data,
+          app_psk,
+          app_psk_size);
+  free (app_psk);
   return 0;
+#else
+  (void) username; (void) key; /* Mute compiler warning */
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (daemon,
+            _ ("PSK not supported by this server.\n"));
 #endif
+  return -1;
+#endif
+}
+
+
+#endif /* HTTPS_SUPPORT */
+
+
+/**
+ * Do basic preparation work on the new incoming connection.
+ *
+ * This function do all preparation that is possible outside main daemon
+ * thread.
+ * @remark Could be called from any thread.
+ *
+ * @param daemon daemon that manages the connection
+ * @param client_socket socket to manage (MHD will expect
+ *        to receive an HTTP request from this socket next).
+ * @param addr IP address of the client
+ * @param addrlen number of bytes in @a addr
+ * @param external_add indicate that socket has been added externally
+ * @param non_blck indicate that socket in non-blocking mode
+ * @param sk_spipe_supprs indicate that the @a client_socket has
+ *                         set SIGPIPE suppression
+ * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket
+ * @return pointer to the connection on success, NULL if this daemon could
+ *        not handle the connection (i.e. malloc failed, etc).
+ *        The socket will be closed in case of error; 'errno' is
+ *        set to indicate further details about the error.
+ */
+static struct MHD_Connection *
+new_connection_prepare_ (struct MHD_Daemon *daemon,
+                         MHD_socket client_socket,
+                         const struct sockaddr_storage *addr,
+                         socklen_t addrlen,
+                         bool external_add,
+                         bool non_blck,
+                         bool sk_spipe_supprs,
+                         enum MHD_tristate sk_is_nonip)
+{
+  struct MHD_Connection *connection;
+  int eno = 0;
+
+#ifdef HAVE_MESSAGES
+#if _MHD_DEBUG_CONNECT
+  MHD_DLOG (daemon,
+            _ ("Accepted connection on socket %d.\n"),
+            client_socket);
+#endif
+#endif
+  if ( (daemon->connections == daemon->connection_limit) ||
+       (MHD_NO == MHD_ip_limit_add (daemon,
+                                    addr,
+                                    addrlen)) )
+  {
+    /* above connection limit - reject */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Server reached connection limit. " \
+                 "Closing inbound connection.\n"));
+#endif
+    MHD_socket_close_chk_ (client_socket);
+#if defined(ENFILE) && (ENFILE + 0 != 0)
+    errno = ENFILE;
+#endif
+    return NULL;
+  }
+
+  /* apply connection acceptance policy if present */
+  if ( (NULL != daemon->apc) &&
+       (MHD_NO == daemon->apc (daemon->apc_cls,
+                               (const struct sockaddr *) addr,
+                               addrlen)) )
+  {
+#if _MHD_DEBUG_CLOSE
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Connection rejected by application. Closing connection.\n"));
+#endif
+#endif
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+#if defined(EACCESS) && (EACCESS + 0 != 0)
+    errno = EACCESS;
+#endif
+    return NULL;
+  }
+
+  if (NULL == (connection = MHD_calloc_ (1, sizeof (struct MHD_Connection))))
+  {
+    eno = errno;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Error allocating memory: %s\n"),
+              MHD_strerror_ (errno));
+#endif
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+    errno = eno;
+    return NULL;
+  }
+
+  if (! external_add)
+  {
+    connection->sk_corked = _MHD_OFF;
+    connection->sk_nodelay = _MHD_OFF;
+  }
+  else
+  {
+    connection->sk_corked = _MHD_UNKNOWN;
+    connection->sk_nodelay = _MHD_UNKNOWN;
+  }
+
+  if (0 < addrlen)
+  {
+    if (NULL == (connection->addr = malloc ((size_t) addrlen)))
+    {
+      eno = errno;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Error allocating memory: %s\n"),
+                MHD_strerror_ (errno));
+#endif
+      MHD_socket_close_chk_ (client_socket);
+      MHD_ip_limit_del (daemon,
+                        addr,
+                        addrlen);
+      free (connection);
+      errno = eno;
+      return NULL;
+    }
+    memcpy (connection->addr,
+            addr,
+            (size_t) addrlen);
+  }
+  else
+    connection->addr = NULL;
+  connection->addr_len = addrlen;
+  connection->socket_fd = client_socket;
+  connection->sk_nonblck = non_blck;
+  connection->is_nonip = sk_is_nonip;
+  connection->sk_spipe_suppress = sk_spipe_supprs;
+  connection->daemon = daemon;
+  connection->connection_timeout_ms = daemon->connection_timeout_ms;
+  connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ;
+  if (0 != connection->connection_timeout_ms)
+    connection->last_activity = MHD_monotonic_msec_counter ();
+
+  if (0 == (daemon->options & MHD_USE_TLS))
+  {
+    /* set default connection handlers  */
+    MHD_set_http_callbacks_ (connection);
+  }
+  else
+  {
+#ifdef HTTPS_SUPPORT
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030500)
+    gnutls_init_flags_t
+#else
+    unsigned int
+#endif
+    flags;
+
+    flags = GNUTLS_SERVER;
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030402)
+    flags |= GNUTLS_NO_SIGNAL;
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030402 */
+#if GNUTLS_VERSION_MAJOR >= 3
+    flags |= GNUTLS_NONBLOCK;
+#endif /* GNUTLS_VERSION_MAJOR >= 3*/
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030603)
+    if (0 != (daemon->options & MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT))
+      flags |= GNUTLS_POST_HANDSHAKE_AUTH;
+#endif
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030605)
+    if (0 != (daemon->options & MHD_USE_INSECURE_TLS_EARLY_DATA))
+      flags |= GNUTLS_ENABLE_EARLY_DATA;
+#endif
+    connection->tls_state = MHD_TLS_CONN_INIT;
+    MHD_set_https_callbacks (connection);
+    if ((GNUTLS_E_SUCCESS != gnutls_init (&connection->tls_session, flags)) ||
+        (GNUTLS_E_SUCCESS != gnutls_priority_set (connection->tls_session,
+                                                  daemon->priority_cache)))
+    {
+      if (NULL != connection->tls_session)
+        gnutls_deinit (connection->tls_session);
+      MHD_socket_close_chk_ (client_socket);
+      MHD_ip_limit_del (daemon,
+                        addr,
+                        addrlen);
+      if (NULL != connection->addr)
+        free (connection->addr);
+      free (connection);
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to initialise TLS session.\n"));
+#endif
+#if defined(EPROTO) && (EPROTO + 0 != 0)
+      errno = EPROTO;
+#endif
+      return NULL;
+    }
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030200)
+    if (! daemon->disable_alpn)
+    {
+      static const char prt1[] = "http/1.1"; /* Registered code for HTTP/1.1 */
+      static const char prt2[] = "http/1.0"; /* Registered code for HTTP/1.0 */
+      static const gnutls_datum_t prts[2] =
+      { {_MHD_DROP_CONST (prt1), MHD_STATICSTR_LEN_ (prt1)},
+        {_MHD_DROP_CONST (prt2), MHD_STATICSTR_LEN_ (prt2)} };
+
+      if (GNUTLS_E_SUCCESS !=
+          gnutls_alpn_set_protocols (connection->tls_session,
+                                     prts,
+                                     sizeof(prts) / sizeof(prts[0]),
+                                     0 /* | GNUTLS_ALPN_SERVER_PRECEDENCE */))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Failed to set ALPN protocols.\n"));
+#else  /* ! HAVE_MESSAGES */
+        (void) 0; /* Mute compiler warning */
+#endif /* ! HAVE_MESSAGES */
+      }
+    }
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */
+    gnutls_session_set_ptr (connection->tls_session,
+                            connection);
+    switch (daemon->cred_type)
+    {
+    /* set needed credentials for certificate authentication. */
+    case GNUTLS_CRD_CERTIFICATE:
+      gnutls_credentials_set (connection->tls_session,
+                              GNUTLS_CRD_CERTIFICATE,
+                              daemon->x509_cred);
+      break;
+    case GNUTLS_CRD_PSK:
+      gnutls_credentials_set (connection->tls_session,
+                              GNUTLS_CRD_PSK,
+                              daemon->psk_cred);
+      gnutls_psk_set_server_credentials_function (daemon->psk_cred,
+                                                  &psk_gnutls_adapter);
+      break;
+    case GNUTLS_CRD_ANON:
+    case GNUTLS_CRD_SRP:
+    case GNUTLS_CRD_IA:
+    default:
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to setup TLS credentials: " \
+                   "unknown credential type %d.\n"),
+                daemon->cred_type);
+#endif
+      gnutls_deinit (connection->tls_session);
+      MHD_socket_close_chk_ (client_socket);
+      MHD_ip_limit_del (daemon,
+                        addr,
+                        addrlen);
+      if (NULL != connection->addr)
+        free (connection->addr);
+      free (connection);
+      MHD_PANIC (_ ("Unknown credential type.\n"));
+#if defined(EINVAL) && (EINVAL + 0 != 0)
+      errno = EINVAL;
+#endif
+      return NULL;
+    }
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64)
+    gnutls_transport_set_int (connection->tls_session,
+                              (int) (client_socket));
+#else  /* GnuTLS before 3.1.9 or Win x64 */
+    gnutls_transport_set_ptr (connection->tls_session,
+                              (gnutls_transport_ptr_t) (intptr_t) (client_socket));
+#endif /* GnuTLS before 3.1.9 or Win x64 */
+#ifdef MHD_TLSLIB_NEED_PUSH_FUNC
+    gnutls_transport_set_push_function (connection->tls_session,
+                                        MHD_tls_push_func_);
+#endif /* MHD_TLSLIB_NEED_PUSH_FUNC */
+    if (daemon->https_mem_trust)
+      gnutls_certificate_server_set_request (connection->tls_session,
+                                             GNUTLS_CERT_REQUEST);
+#else  /* ! HTTPS_SUPPORT */
+    MHD_socket_close_chk_ (client_socket);
+    MHD_ip_limit_del (daemon,
+                      addr,
+                      addrlen);
+    free (connection->addr);
+    free (connection);
+    MHD_PANIC (_ ("TLS connection on non-TLS daemon.\n"));
+#if 0
+    /* Unreachable code */
+    eno = EINVAL;
+    return NULL;
+#endif
+#endif /* ! HTTPS_SUPPORT */
+  }
+
+  return connection;
+}
+
+
+#ifdef MHD_USE_THREADS
+/**
+ * Close prepared, but not yet processed connection.
+ * @param daemon     the daemon
+ * @param connection the connection to close
+ */
+static void
+new_connection_close_ (struct MHD_Daemon *daemon,
+                       struct MHD_Connection *connection)
+{
+  mhd_assert (connection->daemon == daemon);
+  mhd_assert (! connection->in_cleanup);
+  mhd_assert (NULL == connection->next);
+  mhd_assert (NULL == connection->nextX);
+#ifdef EPOLL_SUPPORT
+  mhd_assert (NULL == connection->nextE);
+#endif /* EPOLL_SUPPORT */
+
+#ifdef HTTPS_SUPPORT
+  if (NULL != connection->tls_session)
+  {
+    mhd_assert (0 != (daemon->options & MHD_USE_TLS));
+    gnutls_deinit (connection->tls_session);
+  }
+#endif /* HTTPS_SUPPORT */
+  MHD_socket_close_chk_ (connection->socket_fd);
+  MHD_ip_limit_del (daemon,
+                    connection->addr,
+                    connection->addr_len);
+  if (NULL != connection->addr)
+    free (connection->addr);
+  free (connection);
+}
+
+
+#endif /* MHD_USE_THREADS */
+
+
+/**
+ * Finally insert the new connection to the list of connections
+ * served by the daemon and start processing.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon daemon that manages the connection
+ * @param connection the newly created connection
+ * @return #MHD_YES on success, #MHD_NO on error
+ */
+static enum MHD_Result
+new_connection_process_ (struct MHD_Daemon *daemon,
+                         struct MHD_Connection *connection)
+{
+  int eno = 0;
+
+  mhd_assert (connection->daemon == daemon);
+
+#ifdef MHD_USE_THREADS
+  /* Function manipulate connection and timeout DL-lists,
+   * must be called only within daemon thread. */
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
+
+  /* Allocate memory pool in the processing thread so
+   * intensively used memory area is allocated in "good"
+   * (for the thread) memory region. It is important with
+   * NUMA and/or complex cache hierarchy. */
+  connection->pool = MHD_pool_create (daemon->pool_size);
+  if (NULL == connection->pool)
+  { /* 'pool' creation failed */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Error allocating memory: %s\n"),
+              MHD_strerror_ (errno));
+#endif
+#if defined(ENOMEM) && (ENOMEM + 0 != 0)
+    eno = ENOMEM;
+#endif
+    (void) 0; /* Mute possible compiler warning */
+  }
+  else
+  { /* 'pool' creation succeed */
+    MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+    /* Firm check under lock. */
+    if (daemon->connections >= daemon->connection_limit)
+    { /* Connections limit */
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Server reached connection limit. "
+                   "Closing inbound connection.\n"));
+#endif
+#if defined(ENFILE) && (ENFILE + 0 != 0)
+      eno = ENFILE;
+#endif
+      (void) 0; /* Mute possible compiler warning */
+    }
+    else
+    { /* Have space for new connection */
+      daemon->connections++;
+      DLL_insert (daemon->connections_head,
+                  daemon->connections_tail,
+                  connection);
+      if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+      {
+        XDLL_insert (daemon->normal_timeout_head,
+                     daemon->normal_timeout_tail,
+                     connection);
+      }
+      MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+      if (NULL != daemon->notify_connection)
+        daemon->notify_connection (daemon->notify_connection_cls,
+                                   connection,
+                                   &connection->socket_context,
+                                   MHD_CONNECTION_NOTIFY_STARTED);
+#ifdef MHD_USE_THREADS
+      if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+      {
+        mhd_assert (0 == (daemon->options & MHD_USE_EPOLL));
+        if (! MHD_create_named_thread_ (&connection->pid,
+                                        "MHD-connection",
+                                        daemon->thread_stack_size,
+                                        &thread_main_handle_connection,
+                                        connection))
+        {
+          eno = errno;
+#ifdef HAVE_MESSAGES
+#ifdef EAGAIN
+          if (EAGAIN == eno)
+            MHD_DLOG (daemon,
+                      _ ("Failed to create a new thread because it would "
+                         "have exceeded the system limit on the number of "
+                         "threads or no system resources available.\n"));
+          else
+#endif /* EAGAIN */
+          MHD_DLOG (daemon,
+                    _ ("Failed to create a thread: %s\n"),
+                    MHD_strerror_ (eno));
+#endif /* HAVE_MESSAGES */
+        }
+        else               /* New thread has been created successfully */
+          return MHD_YES;  /* *** Function success exit point *** */
+      }
+      else
+#else  /* ! MHD_USE_THREADS */
+      if (1)
+#endif /* ! MHD_USE_THREADS */
+      { /* No 'thread-per-connection' */
+#ifdef MHD_USE_THREADS
+        connection->pid = daemon->pid;
+#endif /* MHD_USE_THREADS */
+#ifdef EPOLL_SUPPORT
+        if (0 != (daemon->options & MHD_USE_EPOLL))
+        {
+          if (0 == (daemon->options & MHD_USE_TURBO))
+          {
+            struct epoll_event event;
+
+            event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET | EPOLLRDHUP;
+            event.data.ptr = connection;
+            if (0 != epoll_ctl (daemon->epoll_fd,
+                                EPOLL_CTL_ADD,
+                                connection->socket_fd,
+                                &event))
+            {
+              eno = errno;
+#ifdef HAVE_MESSAGES
+              MHD_DLOG (daemon,
+                        _ ("Call to epoll_ctl failed: %s\n"),
+                        MHD_socket_last_strerr_ ());
+#endif
+            }
+            else
+            { /* 'socket_fd' has been added to 'epool' */
+              connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
+
+              return MHD_YES;  /* *** Function success exit point *** */
+            }
+          }
+          else
+          {
+            connection->epoll_state |= MHD_EPOLL_STATE_READ_READY
+                                       | MHD_EPOLL_STATE_WRITE_READY
+                                       | MHD_EPOLL_STATE_IN_EREADY_EDLL;
+            EDLL_insert (daemon->eready_head,
+                         daemon->eready_tail,
+                         connection);
+
+            return MHD_YES;  /* *** Function success exit point *** */
+          }
+        }
+        else /* No 'epoll' */
+#endif /* EPOLL_SUPPORT */
+        return MHD_YES;    /* *** Function success exit point *** */
+      }
+
+      /* ** Below is a cleanup path ** */
+      if (NULL != daemon->notify_connection)
+        daemon->notify_connection (daemon->notify_connection_cls,
+                                   connection,
+                                   &connection->socket_context,
+                                   MHD_CONNECTION_NOTIFY_CLOSED);
+      MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+      if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+      {
+        XDLL_remove (daemon->normal_timeout_head,
+                     daemon->normal_timeout_tail,
+                     connection);
+      }
+      DLL_remove (daemon->connections_head,
+                  daemon->connections_tail,
+                  connection);
+      daemon->connections--;
+      MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+    }
+    MHD_pool_destroy (connection->pool);
+  }
+  /* Free resources allocated before the call of this functions */
+#ifdef HTTPS_SUPPORT
+  if (NULL != connection->tls_session)
+    gnutls_deinit (connection->tls_session);
+#endif /* HTTPS_SUPPORT */
+  MHD_ip_limit_del (daemon,
+                    connection->addr,
+                    connection->addr_len);
+  if (NULL != connection->addr)
+    free (connection->addr);
+  MHD_socket_close_chk_ (connection->socket_fd);
+  free (connection);
+  if (0 != eno)
+    errno = eno;
+#ifdef EINVAL
+  else
+    errno = EINVAL;
+#endif /* EINVAL */
+  return MHD_NO;  /* *** Function failure exit point *** */
 }
 
 
@@ -1329,8 +2942,6 @@
  * this call and must no longer be used directly by the application
  * afterwards.
  *
- * Per-IP connection limits are ignored when using this API.
- *
  * @param daemon daemon that manages the connection
  * @param client_socket socket to manage (MHD will expect
  *        to receive an HTTP request from this socket next).
@@ -1338,364 +2949,232 @@
  * @param addrlen number of bytes in @a addr
  * @param external_add perform additional operations needed due
  *        to the application calling us directly
+ * @param non_blck indicate that socket in non-blocking mode
+ * @param sk_spipe_supprs indicate that the @a client_socket has
+ *                         set SIGPIPE suppression
+ * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket
  * @return #MHD_YES on success, #MHD_NO if this daemon could
  *        not handle the connection (i.e. malloc failed, etc).
  *        The socket will be closed in any case; 'errno' is
  *        set to indicate further details about the error.
  */
-static int
+static enum MHD_Result
 internal_add_connection (struct MHD_Daemon *daemon,
-			 MHD_socket client_socket,
-			 const struct sockaddr *addr,
-			 socklen_t addrlen,
-			 int external_add)
+                         MHD_socket client_socket,
+                         const struct sockaddr_storage *addr,
+                         socklen_t addrlen,
+                         bool external_add,
+                         bool non_blck,
+                         bool sk_spipe_supprs,
+                         enum MHD_tristate sk_is_nonip)
 {
   struct MHD_Connection *connection;
-  int res_thread_create;
-  unsigned int i;
-  int eno;
-  struct MHD_Daemon *worker;
-#if OSX
-  static int on = 1;
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  /* Direct add to master daemon could never happen. */
+  mhd_assert ((NULL == daemon->worker_pool));
 #endif
 
-  if (NULL != daemon->worker_pool)
-    {
-      /* have a pool, try to find a pool with capacity; we use the
-	 socket as the initial offset into the pool for load
-	 balancing */
-      for (i=0;i<daemon->worker_pool_size;i++)
-        {
-          worker = &daemon->worker_pool[(i + client_socket) % daemon->worker_pool_size];
-          if (worker->connections < worker->connection_limit)
-            return internal_add_connection (worker,
-                                            client_socket,
-                                            addr, addrlen,
-                                            external_add);
-        }
-      /* all pools are at their connection limit, must refuse */
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-#if ENFILE
-      errno = ENFILE;
+  if ( (0 == (daemon->options & (MHD_USE_POLL | MHD_USE_EPOLL))) &&
+       (! MHD_SCKT_FD_FITS_FDSET_ (client_socket, NULL)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("New connection socket descriptor (%d) is not less " \
+                 "than FD_SETSIZE (%d).\n"),
+              (int) client_socket,
+              (int) FD_SETSIZE);
 #endif
-      return MHD_NO;
-    }
+    MHD_socket_close_chk_ (client_socket);
+#if defined(ENFILE) && (ENFILE + 0 != 0)
+    errno = ENFILE;
+#endif
+    return MHD_NO;
+  }
 
-#ifndef WINDOWS
-  if ( (client_socket >= FD_SETSIZE) &&
-       (0 == (daemon->options & (MHD_USE_POLL | MHD_USE_EPOLL_LINUX_ONLY))) )
+  if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+       (! non_blck) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Epoll mode supports only non-blocking sockets\n"));
+#endif
+    MHD_socket_close_chk_ (client_socket);
+#if defined(EINVAL) && (EINVAL + 0 != 0)
+    errno = EINVAL;
+#endif
+    return MHD_NO;
+  }
+
+  connection = new_connection_prepare_ (daemon,
+                                        client_socket,
+                                        addr, addrlen,
+                                        external_add,
+                                        non_blck,
+                                        sk_spipe_supprs,
+                                        sk_is_nonip);
+  if (NULL == connection)
+    return MHD_NO;
+
+  if ((external_add) &&
+      (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)))
+  {
+    /* Connection is added externally and MHD is handling its own threads. */
+    MHD_mutex_lock_chk_ (&daemon->new_connections_mutex);
+    DLL_insert (daemon->new_connections_head,
+                daemon->new_connections_tail,
+                connection);
+    daemon->have_new = true;
+    MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex);
+
+    /* The rest of connection processing must be handled in
+     * the daemon thread. */
+    if ((MHD_ITC_IS_VALID_ (daemon->itc)) &&
+        (! MHD_itc_activate_ (daemon->itc, "n")))
     {
-#if HAVE_MESSAGES
+ #ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-		"Socket descriptor larger than FD_SETSIZE: %d > %d\n",
-		client_socket,
-		FD_SETSIZE);
-#endif
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-#if EINVAL
-      errno = EINVAL;
-#endif
-      return MHD_NO;
+                _ ("Failed to signal new connection via inter-thread " \
+                   "communication channel.\n"));
+ #endif
     }
-#endif
+    return MHD_YES;
+  }
+
+  return new_connection_process_ (daemon, connection);
+}
 
 
-#if HAVE_MESSAGES
-#if DEBUG_CONNECT
-  MHD_DLOG (daemon,
-            "Accepted connection on socket %d\n",
-            client_socket);
-#endif
-#endif
-  if ( (daemon->connections == daemon->connection_limit) ||
-       (MHD_NO == MHD_ip_limit_add (daemon, addr, addrlen)) )
+static void
+new_connections_list_process_ (struct MHD_Daemon *daemon)
+{
+  struct MHD_Connection *local_head;
+  struct MHD_Connection *local_tail;
+  mhd_assert (daemon->have_new);
+  mhd_assert (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD));
+
+  /* Detach DL-list of new connections from the daemon for
+   * following local processing. */
+  MHD_mutex_lock_chk_ (&daemon->new_connections_mutex);
+  mhd_assert (NULL != daemon->new_connections_head);
+  local_head = daemon->new_connections_head;
+  local_tail = daemon->new_connections_tail;
+  daemon->new_connections_head = NULL;
+  daemon->new_connections_tail = NULL;
+  daemon->have_new = false;
+  MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex);
+  (void) local_head; /* Mute compiler warning */
+
+  /* Process new connections in FIFO order. */
+  do
+  {
+    struct MHD_Connection *c;   /**< Currently processed connection */
+
+    c = local_tail;
+    DLL_remove (local_head,
+                local_tail,
+                c);
+    mhd_assert (daemon == c->daemon);
+    if (MHD_NO == new_connection_process_ (daemon, c))
     {
-      /* above connection limit - reject */
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-                "Server reached connection limit (closing inbound connection)\n");
+                _ ("Failed to start serving new connection.\n"));
 #endif
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-#if ENFILE
-      errno = ENFILE;
-#endif
-      return MHD_NO;
+      (void) 0;
     }
+  } while (NULL != local_tail);
 
-  /* apply connection acceptance policy if present */
-  if ( (NULL != daemon->apc) &&
-       (MHD_NO == daemon->apc (daemon->apc_cls,
-			       addr, addrlen)) )
-    {
-#if DEBUG_CLOSE
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "Connection rejected, closing connection\n");
-#endif
-#endif
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-      MHD_ip_limit_del (daemon, addr, addrlen);
-#if EACCESS
-      errno = EACCESS;
-#endif
-      return MHD_NO;
-    }
-
-#if OSX
-#ifdef SOL_SOCKET
-#ifdef SO_NOSIGPIPE
-  setsockopt (client_socket,
-	      SOL_SOCKET, SO_NOSIGPIPE,
-	      &on, sizeof (on));
-#endif
-#endif
-#endif
-
-  if (NULL == (connection = malloc (sizeof (struct MHD_Connection))))
-    {
-      eno = errno;
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Error allocating memory: %s\n",
-		MHD_strerror_ (errno));
-#endif
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-      MHD_ip_limit_del (daemon, addr, addrlen);
-      errno = eno;
-      return MHD_NO;
-    }
-  memset (connection,
-          0,
-          sizeof (struct MHD_Connection));
-  connection->pool = MHD_pool_create (daemon->pool_size);
-  if (NULL == connection->pool)
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Error allocating memory: %s\n",
-		MHD_strerror_ (errno));
-#endif
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-      MHD_ip_limit_del (daemon, addr, addrlen);
-      free (connection);
-#if ENOMEM
-      errno = ENOMEM;
-#endif
-      return MHD_NO;
-    }
-
-  connection->connection_timeout = daemon->connection_timeout;
-  if (NULL == (connection->addr = malloc (addrlen)))
-    {
-      eno = errno;
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Error allocating memory: %s\n",
-		MHD_strerror_ (errno));
-#endif
-      if (0 != MHD_socket_close_ (client_socket))
-	MHD_PANIC ("close failed\n");
-      MHD_ip_limit_del (daemon, addr, addrlen);
-      MHD_pool_destroy (connection->pool);
-      free (connection);
-      errno = eno;
-      return MHD_NO;
-    }
-  memcpy (connection->addr, addr, addrlen);
-  connection->addr_len = addrlen;
-  connection->socket_fd = client_socket;
-  connection->daemon = daemon;
-  connection->last_activity = MHD_monotonic_time();
-
-  /* set default connection handlers  */
-  MHD_set_http_callbacks_ (connection);
-  connection->recv_cls = &recv_param_adapter;
-  connection->send_cls = &send_param_adapter;
-
-  if (0 == (connection->daemon->options & MHD_USE_EPOLL_TURBO))
-    {
-      /* non-blocking sockets are required on most systems and for GNUtls;
-	 however, they somehow cause serious problems on CYGWIN (#1824);
-	 in turbo mode, we assume that non-blocking was already set
-	 by 'accept4' or whoever calls 'MHD_add_connection' */
-#ifdef CYGWIN
-      if (0 != (daemon->options & MHD_USE_SSL))
-#endif
-	{
-	  /* make socket non-blocking */
-#if !defined(WINDOWS) || defined(CYGWIN)
-	  int flags = fcntl (connection->socket_fd, F_GETFL);
-	  if ( (-1 == flags) ||
-	       (0 != fcntl (connection->socket_fd, F_SETFL, flags | O_NONBLOCK)) )
-	    {
-#if HAVE_MESSAGES
-	      MHD_DLOG (daemon,
-			"Failed to make socket non-blocking: %s\n",
-			MHD_socket_last_strerr_ ());
-#endif
-	    }
-#else
-	  unsigned long flags = 1;
-	  if (0 != ioctlsocket (connection->socket_fd, FIONBIO, &flags))
-	    {
-#if HAVE_MESSAGES
-	      MHD_DLOG (daemon,
-			"Failed to make socket non-blocking: %s\n",
-			MHD_socket_last_strerr_ ());
-#endif
-	    }
-#endif
-	}
-    }
-
-#if HTTPS_SUPPORT
-  if (0 != (daemon->options & MHD_USE_SSL))
-    {
-      connection->recv_cls = &recv_tls_adapter;
-      connection->send_cls = &send_tls_adapter;
-      connection->state = MHD_TLS_CONNECTION_INIT;
-      MHD_set_https_callbacks (connection);
-      connection->tls_session = SSL_new (daemon->tls_context);
-      BIO* bio = BIO_new (&MHD_bio_method);
-      if (bio)
-        {
-          bio->ptr = connection;
-          bio->init = 1;
-        }
-      SSL_set_bio (connection->tls_session, bio, bio);
-      SSL_set_app_data (connection->tls_session, connection);
-    }
-#endif
-
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  XDLL_insert (daemon->normal_timeout_head,
-	       daemon->normal_timeout_tail,
-	       connection);
-  DLL_insert (daemon->connections_head,
-	      daemon->connections_tail,
-	      connection);
-  if  ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-	(MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
-
-  if (NULL != daemon->notify_connection)
-    daemon->notify_connection (daemon->notify_connection_cls,
-                               connection,
-                               &connection->socket_context,
-                               MHD_CONNECTION_NOTIFY_STARTED);
-
-  /* attempt to create handler thread */
-  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
-    {
-      res_thread_create = create_thread (&connection->pid,
-                                         daemon,
-					 &MHD_handle_connection,
-                                         connection);
-      if (0 != res_thread_create)
-        {
-	  eno = errno;
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Failed to create a thread: %s\n",
-                    MHD_strerror_ (res_thread_create));
-#endif
-	  goto cleanup;
-        }
-    }
-  else
-    if ( (MHD_YES == external_add) &&
-	 (MHD_INVALID_PIPE_ != daemon->wpipe[1]) &&
-	 (1 != MHD_pipe_write_ (daemon->wpipe[1], "n", 1)) )
-      {
-#if HAVE_MESSAGES
-	MHD_DLOG (daemon,
-		  "failed to signal new connection via pipe");
-#endif
-      }
-#if EPOLL_SUPPORT
-  if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-    {
-      if (0 == (daemon->options & MHD_USE_EPOLL_TURBO))
-	{
-	  struct epoll_event event;
-
-	  event.events = EPOLLIN | EPOLLOUT | EPOLLET;
-	  event.data.ptr = connection;
-	  if (0 != epoll_ctl (daemon->epoll_fd,
-			      EPOLL_CTL_ADD,
-			      client_socket,
-			      &event))
-	    {
-	      eno = errno;
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "Call to epoll_ctl failed: %s\n",
-                        MHD_socket_last_strerr_ ());
-#endif
-	      goto cleanup;
-	    }
-	  connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
-	}
-      else
-	{
-	  connection->epoll_state |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY
-	    | MHD_EPOLL_STATE_IN_EREADY_EDLL;
-	  EDLL_insert (daemon->eready_head,
-		       daemon->eready_tail,
-		       connection);
-	}
-    }
-#endif
-  daemon->connections++;
-  return MHD_YES;
- cleanup:
-  if (NULL != daemon->notify_connection)
-    daemon->notify_connection (daemon->notify_connection_cls,
-                               connection,
-                               &connection->socket_context,
-                               MHD_CONNECTION_NOTIFY_CLOSED);
-  if (0 != MHD_socket_close_ (client_socket))
-    MHD_PANIC ("close failed\n");
-  MHD_ip_limit_del (daemon, addr, addrlen);
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  DLL_remove (daemon->connections_head,
-	      daemon->connections_tail,
-	      connection);
-  XDLL_remove (daemon->normal_timeout_head,
-	       daemon->normal_timeout_tail,
-	       connection);
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
-  MHD_pool_destroy (connection->pool);
-  free (connection->addr);
-  free (connection);
-#if EINVAL
-  errno = eno;
-#endif
-  return MHD_NO;
 }
 
 
 /**
- * Suspend handling of network data for a given connection.  This can
- * be used to dequeue a connection from MHD's event loop (external
- * select, internal select or thread pool; not applicable to
- * thread-per-connection!) for a while.
+ * Internal version of ::MHD_suspend_connection().
  *
- * If you use this API in conjunction with a internal select or a
- * thread pool, you must set the option #MHD_USE_PIPE_FOR_SHUTDOWN to
- * ensure that a resumed connection is immediately processed by MHD.
+ * @remark In thread-per-connection mode: can be called from any thread,
+ * in any other mode: to be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param connection the connection to suspend
+ */
+void
+internal_suspend_connection_ (struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  mhd_assert (NULL == daemon->worker_pool);
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  if (connection->resuming)
+  {
+    /* suspending again while we didn't even complete resuming yet */
+    connection->resuming = false;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+    return;
+  }
+  if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+  {
+    if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
+      XDLL_remove (daemon->normal_timeout_head,
+                   daemon->normal_timeout_tail,
+                   connection);
+    else
+      XDLL_remove (daemon->manual_timeout_head,
+                   daemon->manual_timeout_tail,
+                   connection);
+  }
+  DLL_remove (daemon->connections_head,
+              daemon->connections_tail,
+              connection);
+  mhd_assert (! connection->suspended);
+  DLL_insert (daemon->suspended_connections_head,
+              daemon->suspended_connections_tail,
+              connection);
+  connection->suspended = true;
+#ifdef EPOLL_SUPPORT
+  if (0 != (daemon->options & MHD_USE_EPOLL))
+  {
+    if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+    {
+      EDLL_remove (daemon->eready_head,
+                   daemon->eready_tail,
+                   connection);
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL);
+    }
+    if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET))
+    {
+      if (0 != epoll_ctl (daemon->epoll_fd,
+                          EPOLL_CTL_DEL,
+                          connection->socket_fd,
+                          NULL))
+        MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EPOLL_SET);
+    }
+    connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED;
+  }
+#endif
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+}
+
+
+/**
+ * Suspend handling of network data for a given connection.
+ * This can be used to dequeue a connection from MHD's event loop
+ * (not applicable to thread-per-connection!) for a while.
+ *
+ * If you use this API in conjunction with an "internal" socket polling,
+ * you must set the option #MHD_USE_ITC to ensure that a resumed
+ * connection is immediately processed by MHD.
  *
  * Suspended connections continue to count against the total number of
  * connections allowed (per daemon, as well as per IP, if such limits
@@ -1704,228 +3183,277 @@
  * connection is suspended, MHD will not detect disconnects by the
  * client.
  *
- * The only safe time to suspend a connection is from the
- * #MHD_AccessHandlerCallback.
+ * The only safe way to call this function is to call it from the
+ * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback.
  *
  * Finally, it is an API violation to call #MHD_stop_daemon while
  * having suspended connections (this will at least create memory and
  * socket leaks or lead to undefined behavior).  You must explicitly
  * resume all connections before stopping the daemon.
  *
+ * @remark In thread-per-connection mode: can be called from any thread,
+ * in any other mode: to be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
  * @param connection the connection to suspend
+ *
+ * @sa #MHD_AccessHandlerCallback
  */
-void
+_MHD_EXTERN void
 MHD_suspend_connection (struct MHD_Connection *connection)
 {
-  struct MHD_Daemon *daemon;
+  struct MHD_Daemon *const daemon = connection->daemon;
 
-  daemon = connection->daemon;
-  if (MHD_USE_SUSPEND_RESUME != (daemon->options & MHD_USE_SUSPEND_RESUME))
-    MHD_PANIC ("Cannot suspend connections without enabling MHD_USE_SUSPEND_RESUME!\n");
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  DLL_remove (daemon->connections_head,
-              daemon->connections_tail,
-              connection);
-  DLL_insert (daemon->suspended_connections_head,
-              daemon->suspended_connections_tail,
-              connection);
-  if (connection->connection_timeout == daemon->connection_timeout)
-    XDLL_remove (daemon->normal_timeout_head,
-                 daemon->normal_timeout_tail,
-                 connection);
-  else
-    XDLL_remove (daemon->manual_timeout_head,
-                 daemon->manual_timeout_tail,
-                 connection);
-#if EPOLL_SUPPORT
-  if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-    {
-      if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
-        {
-          EDLL_remove (daemon->eready_head,
-                       daemon->eready_tail,
-                       connection);
-          connection->epoll_state &= ~MHD_EPOLL_STATE_IN_EREADY_EDLL;
-        }
-      if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET))
-        {
-          if (0 != epoll_ctl (daemon->epoll_fd,
-                              EPOLL_CTL_DEL,
-                              connection->socket_fd,
-                              NULL))
-            MHD_PANIC ("Failed to remove FD from epoll set\n");
-          connection->epoll_state &= ~MHD_EPOLL_STATE_IN_EPOLL_SET;
-        }
-      connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED;
-    }
-#endif
-  connection->suspended = MHD_YES;
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+#endif /* MHD_USE_THREADS */
+
+  if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
+    MHD_PANIC (_ ("Cannot suspend connections without " \
+                  "enabling MHD_ALLOW_SUSPEND_RESUME!\n"));
+#ifdef UPGRADE_SUPPORT
+  if (NULL != connection->urh)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Error: connection scheduled for \"upgrade\" cannot " \
+                 "be suspended.\n"));
+#endif /* HAVE_MESSAGES */
+    return;
+  }
+#endif /* UPGRADE_SUPPORT */
+  internal_suspend_connection_ (connection);
 }
 
 
 /**
  * Resume handling of network data for suspended connection.  It is
- * safe to resume a suspended connection at any time.  Calling this function
- * on a connection that was not previously suspended will result
- * in undefined behavior.
+ * safe to resume a suspended connection at any time.  Calling this
+ * function on a connection that was not previously suspended will
+ * result in undefined behavior.
+ *
+ * If you are using this function in "external" sockets polling mode, you must
+ * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before
+ * again calling #MHD_get_fdset()), as otherwise the change may not be
+ * reflected in the set returned by #MHD_get_fdset() and you may end up
+ * with a connection that is stuck until the next network activity.
  *
  * @param connection the connection to resume
  */
-void
+_MHD_EXTERN void
 MHD_resume_connection (struct MHD_Connection *connection)
 {
-  struct MHD_Daemon *daemon;
+  struct MHD_Daemon *daemon = connection->daemon;
+#if defined(MHD_USE_THREADS)
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
 
-  daemon = connection->daemon;
-  if (MHD_USE_SUSPEND_RESUME != (daemon->options & MHD_USE_SUSPEND_RESUME))
-    MHD_PANIC ("Cannot resume connections without enabling MHD_USE_SUSPEND_RESUME!\n");
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  connection->resuming = MHD_YES;
-  daemon->resuming = MHD_YES;
-  if ( (MHD_INVALID_PIPE_ != daemon->wpipe[1]) &&
-       (1 != MHD_pipe_write_ (daemon->wpipe[1], "r", 1)) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "failed to signal resume via pipe");
+  if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
+    MHD_PANIC (_ ("Cannot resume connections without enabling " \
+                  "MHD_ALLOW_SUSPEND_RESUME!\n"));
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
 #endif
-    }
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+  connection->resuming = true;
+  daemon->resuming = true;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc, "r")) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to signal resume via inter-thread " \
+                 "communication channel.\n"));
+#endif
+  }
 }
 
 
+#ifdef UPGRADE_SUPPORT
+/**
+ * Mark upgraded connection as closed by application.
+ *
+ * The @a connection pointer must not be used after call of this function
+ * as it may be freed in other thread immediately.
+ * @param connection the upgraded connection to mark as closed by application
+ */
+void
+MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection)
+{
+  /* Cache 'daemon' here to avoid data races */
+  struct MHD_Daemon *const daemon = connection->daemon;
+#if defined(MHD_USE_THREADS)
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
+  mhd_assert (NULL != connection->urh);
+  mhd_assert (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME));
+
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+  connection->urh->was_closed = true;
+  connection->resuming = true;
+  daemon->resuming = true;
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc, "r")) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to signal resume via " \
+                 "inter-thread communication channel.\n"));
+#endif
+  }
+}
+
+
+#endif /* UPGRADE_SUPPORT */
+
 /**
  * Run through the suspended connections and move any that are no
  * longer suspended back to the active state.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
  *
  * @param daemon daemon context
  * @return #MHD_YES if a connection was actually resumed
  */
-static int
+static enum MHD_Result
 resume_suspended_connections (struct MHD_Daemon *daemon)
 {
   struct MHD_Connection *pos;
-  struct MHD_Connection *next = NULL;
-  int ret;
+  struct MHD_Connection *prev = NULL;
+  enum MHD_Result ret;
+  const bool used_thr_p_c = (0 != (daemon->options
+                                   & MHD_USE_THREAD_PER_CONNECTION));
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  mhd_assert (NULL == daemon->worker_pool);
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+#endif
 
   ret = MHD_NO;
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  if (MHD_YES == daemon->resuming)
-    next = daemon->suspended_connections_head;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
 
-  while (NULL != (pos = next))
+  if (daemon->resuming)
+  {
+    prev = daemon->suspended_connections_tail;
+    /* During shutdown check for resuming is forced. */
+    mhd_assert ((NULL != prev) || (daemon->shutdown) || \
+                (0 != (daemon->options & MHD_ALLOW_UPGRADE)));
+  }
+
+  daemon->resuming = false;
+
+  while (NULL != (pos = prev))
+  {
+#ifdef UPGRADE_SUPPORT
+    struct MHD_UpgradeResponseHandle *const urh = pos->urh;
+#else  /* ! UPGRADE_SUPPORT */
+    static const void *const urh = NULL;
+#endif /* ! UPGRADE_SUPPORT */
+    prev = pos->prev;
+    if ( (! pos->resuming)
+#ifdef UPGRADE_SUPPORT
+         || ( (NULL != urh) &&
+              ( (! urh->was_closed) ||
+                (! urh->clean_ready) ) )
+#endif /* UPGRADE_SUPPORT */
+         )
+      continue;
+    ret = MHD_YES;
+    mhd_assert (pos->suspended);
+    DLL_remove (daemon->suspended_connections_head,
+                daemon->suspended_connections_tail,
+                pos);
+    pos->suspended = false;
+    if (NULL == urh)
     {
-      next = pos->next;
-      if (MHD_NO == pos->resuming)
-        continue;
-      ret = MHD_YES;
-      DLL_remove (daemon->suspended_connections_head,
-                  daemon->suspended_connections_tail,
-                  pos);
       DLL_insert (daemon->connections_head,
                   daemon->connections_tail,
                   pos);
-      if (pos->connection_timeout == daemon->connection_timeout)
-        XDLL_insert (daemon->normal_timeout_head,
-                     daemon->normal_timeout_tail,
-                     pos);
-      else
-        XDLL_insert (daemon->manual_timeout_head,
-                     daemon->manual_timeout_tail,
-                     pos);
-#if EPOLL_SUPPORT
-      if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-        {
-          if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
-            MHD_PANIC ("Resumed connection was already in EREADY set\n");
-          /* we always mark resumed connections as ready, as we
-             might have missed the edge poll event during suspension */
-          EDLL_insert (daemon->eready_head,
-                       daemon->eready_tail,
+      if (! used_thr_p_c)
+      {
+        /* Reset timeout timer on resume. */
+        if (0 != pos->connection_timeout_ms)
+          pos->last_activity = MHD_monotonic_msec_counter ();
+
+        if (pos->connection_timeout_ms == daemon->connection_timeout_ms)
+          XDLL_insert (daemon->normal_timeout_head,
+                       daemon->normal_timeout_tail,
                        pos);
-          pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
-          pos->epoll_state &= ~MHD_EPOLL_STATE_SUSPENDED;
-        }
+        else
+          XDLL_insert (daemon->manual_timeout_head,
+                       daemon->manual_timeout_tail,
+                       pos);
+      }
+#ifdef EPOLL_SUPPORT
+      if (0 != (daemon->options & MHD_USE_EPOLL))
+      {
+        if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+          MHD_PANIC ("Resumed connection was already in EREADY set.\n");
+        /* we always mark resumed connections as ready, as we
+           might have missed the edge poll event during suspension */
+        EDLL_insert (daemon->eready_head,
+                     daemon->eready_tail,
+                     pos);
+        pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL   \
+                            | MHD_EPOLL_STATE_READ_READY
+                            | MHD_EPOLL_STATE_WRITE_READY;
+        pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_SUSPENDED);
+      }
 #endif
-      pos->suspended = MHD_NO;
-      pos->resuming = MHD_NO;
     }
-  daemon->resuming = MHD_NO;
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+#ifdef UPGRADE_SUPPORT
+    else
+    {
+      /* Data forwarding was finished (for TLS connections) AND
+       * application was closed upgraded connection.
+       * Insert connection into cleanup list. */
+
+      if ( (NULL != daemon->notify_completed) &&
+           (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
+           (pos->rq.client_aware) )
+      {
+        daemon->notify_completed (daemon->notify_completed_cls,
+                                  pos,
+                                  &pos->rq.client_context,
+                                  MHD_REQUEST_TERMINATED_COMPLETED_OK);
+        pos->rq.client_aware = false;
+      }
+      DLL_insert (daemon->cleanup_head,
+                  daemon->cleanup_tail,
+                  pos);
+      daemon->data_already_pending = true;
+    }
+#endif /* UPGRADE_SUPPORT */
+    pos->resuming = false;
+  }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  if ( (used_thr_p_c) &&
+       (MHD_NO != ret) )
+  {   /* Wake up suspended connections. */
+    if (! MHD_itc_activate_ (daemon->itc,
+                             "w"))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to signal resume of connection via " \
+                   "inter-thread communication channel.\n"));
+#endif
+    }
+  }
   return ret;
 }
 
 
 /**
- * Change socket options to be non-blocking, non-inheritable.
- *
- * @param daemon daemon context
- * @param sock socket to manipulate
- */
-static void
-make_nonblocking_noninheritable (struct MHD_Daemon *daemon,
-				 MHD_socket sock)
-{
-#ifdef WINDOWS
-  DWORD dwFlags;
-  unsigned long flags = 1;
-
-  if (0 != ioctlsocket (sock, FIONBIO, &flags))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Failed to make socket non-blocking: %s\n",
-		MHD_socket_last_strerr_ ());
-#endif
-    }
-  if (!GetHandleInformation ((HANDLE) sock, &dwFlags) ||
-      ((dwFlags != (dwFlags & ~HANDLE_FLAG_INHERIT)) &&
-       !SetHandleInformation ((HANDLE) sock, HANDLE_FLAG_INHERIT, 0)))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Failed to make socket non-inheritable: %u\n",
-		(unsigned int) GetLastError ());
-#endif
-    }
-#else
-  int flags;
-  int nonblock;
-
-  nonblock = O_NONBLOCK;
-#ifdef CYGWIN
-  if (0 == (daemon->options & MHD_USE_SSL))
-    nonblock = 0;
-#endif
-  flags = fcntl (sock, F_GETFD);
-  if ( ( (-1 == flags) ||
-	 ( (flags != (flags | FD_CLOEXEC)) &&
-	   (0 != fcntl (sock, F_SETFD, flags | nonblock | FD_CLOEXEC)) ) ) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Failed to make socket non-inheritable: %s\n",
-		MHD_socket_last_strerr_ ());
-#endif
-    }
-#endif
-}
-
-
-/**
  * Add another client connection to the set of connections managed by
  * MHD.  This API is usually not needed (since MHD will accept inbound
  * connections on the server socket).  Use this API in special cases,
@@ -1934,15 +3462,13 @@
  *
  * If you use this API in conjunction with a internal select or a
  * thread pool, you must set the option
- * #MHD_USE_PIPE_FOR_SHUTDOWN to ensure that the freshly added
+ * #MHD_USE_ITC to ensure that the freshly added
  * connection is immediately processed by MHD.
  *
  * The given client socket will be managed (and closed!) by MHD after
  * this call and must no longer be used directly by the application
  * afterwards.
  *
- * Per-IP connection limits are ignored when using this API.
- *
  * @param daemon daemon that manages the connection
  * @param client_socket socket to manage (MHD will expect
  *        to receive an HTTP request from this socket next).
@@ -1954,18 +3480,160 @@
  *        set to indicate further details about the error.
  * @ingroup specialized
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_add_connection (struct MHD_Daemon *daemon,
-		    MHD_socket client_socket,
-		    const struct sockaddr *addr,
-		    socklen_t addrlen)
+                    MHD_socket client_socket,
+                    const struct sockaddr *addr,
+                    socklen_t addrlen)
 {
-  make_nonblocking_noninheritable (daemon,
-				   client_socket);
+  bool sk_nonbl;
+  bool sk_spipe_supprs;
+  struct sockaddr_storage addrstorage;
+
+  /* NOT thread safe with internal thread. TODO: fix thread safety. */
+  if ((0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) &&
+      (daemon->connection_limit <= daemon->connections))
+    MHD_cleanup_connections (daemon);
+
+#ifdef HAVE_MESSAGES
+  if ((0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) &&
+      (0 == (daemon->options & MHD_USE_ITC)))
+  {
+    MHD_DLOG (daemon,
+              _ ("MHD_add_connection() has been called for daemon started"
+                 " without MHD_USE_ITC flag.\nDaemon will not process newly"
+                 " added connection until any activity occurs in already"
+                 " added sockets.\n"));
+  }
+#endif /* HAVE_MESSAGES */
+  if (0 != addrlen)
+  {
+    if (AF_INET == addr->sa_family)
+    {
+      if (sizeof(struct sockaddr_in) > (size_t) addrlen)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("MHD_add_connection() has been called with "
+                     "incorrect 'addrlen' value.\n"));
+#endif /* HAVE_MESSAGES */
+        return MHD_NO;
+      }
+    }
+#ifdef HAVE_INET6
+    if (AF_INET6 == addr->sa_family)
+    {
+      if (sizeof(struct sockaddr_in6) > (size_t) addrlen)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("MHD_add_connection() has been called with "
+                     "incorrect 'addrlen' value.\n"));
+#endif /* HAVE_MESSAGES */
+        return MHD_NO;
+      }
+    }
+#endif /* HAVE_INET6 */
+  }
+
+  if (! MHD_socket_nonblocking_ (client_socket))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to set nonblocking mode on new client socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
+    sk_nonbl = false;
+  }
+  else
+    sk_nonbl = true;
+
+#ifndef MHD_WINSOCK_SOCKETS
+  sk_spipe_supprs = false;
+#else  /* MHD_WINSOCK_SOCKETS */
+  sk_spipe_supprs = true; /* Nothing to suppress on W32 */
+#endif /* MHD_WINSOCK_SOCKETS */
+#if defined(MHD_socket_nosignal_)
+  if (! sk_spipe_supprs && ! MHD_socket_nosignal_ (client_socket))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to suppress SIGPIPE on new client socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#else  /* ! HAVE_MESSAGES */
+    (void) 0; /* Mute compiler warning */
+#endif /* ! HAVE_MESSAGES */
+#ifndef MSG_NOSIGNAL
+    /* Application expects that SIGPIPE will be suppressed,
+     * but suppression failed and SIGPIPE cannot be suppressed with send(). */
+    if (! daemon->sigpipe_blocked)
+    {
+      int err = MHD_socket_get_error_ ();
+      MHD_socket_close_ (client_socket);
+      MHD_socket_fset_error_ (err);
+      return MHD_NO;
+    }
+#endif /* MSG_NOSIGNAL */
+  }
+  else
+    sk_spipe_supprs = true;
+#endif /* MHD_socket_nosignal_ */
+
+  if ( (0 != (daemon->options & MHD_USE_TURBO)) &&
+       (! MHD_socket_noninheritable_ (client_socket)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to set noninheritable mode on new client socket.\n"));
+#endif
+  }
+
+  /* Copy to sockaddr_storage structure to avoid alignment problems */
+  if (0 < addrlen)
+    memcpy (&addrstorage, addr, (size_t) addrlen);
+#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
+  addrstorage.ss_len = addrlen; /* Force set the right length */
+#endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if (NULL != daemon->worker_pool)
+  {
+    unsigned int i;
+    /* have a pool, try to find a pool with capacity; we use the
+       socket as the initial offset into the pool for load
+       balancing */
+    for (i = 0; i < daemon->worker_pool_size; ++i)
+    {
+      struct MHD_Daemon *const worker =
+        &daemon->worker_pool[(i + (unsigned int) client_socket)
+                             % daemon->worker_pool_size];
+      if (worker->connections < worker->connection_limit)
+        return internal_add_connection (worker,
+                                        client_socket,
+                                        &addrstorage,
+                                        addrlen,
+                                        true,
+                                        sk_nonbl,
+                                        sk_spipe_supprs,
+                                        _MHD_UNKNOWN);
+    }
+    /* all pools are at their connection limit, must refuse */
+    MHD_socket_close_chk_ (client_socket);
+#if defined(ENFILE) && (ENFILE + 0 != 0)
+    errno = ENFILE;
+#endif
+    return MHD_NO;
+  }
+#endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */
+
   return internal_add_connection (daemon,
-				  client_socket,
-				  addr, addrlen,
-				  MHD_YES);
+                                  client_socket,
+                                  &addrstorage,
+                                  addrlen,
+                                  true,
+                                  sk_nonbl,
+                                  sk_spipe_supprs,
+                                  _MHD_UNKNOWN);
 }
 
 
@@ -1973,6 +3641,8 @@
  * Accept an incoming connection and create the MHD_Connection object for
  * it.  This function also enforces policy by way of checking with the
  * accept policy callback.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
  *
  * @param daemon handle with the listen socket
  * @return #MHD_YES on success (connections denied by policy or due
@@ -1981,72 +3651,223 @@
  *         a return code of #MHD_NO only refers to the actual
  *         accept() system call.
  */
-static int
+static enum MHD_Result
 MHD_accept_connection (struct MHD_Daemon *daemon)
 {
-#if HAVE_INET6
-  struct sockaddr_in6 addrstorage;
-#else
-  struct sockaddr_in addrstorage;
-#endif
-  struct sockaddr *addr = (struct sockaddr *) &addrstorage;
+  struct sockaddr_storage addrstorage;
   socklen_t addrlen;
   MHD_socket s;
   MHD_socket fd;
-  int nonblock;
+  bool sk_nonbl;
+  bool sk_spipe_supprs;
+  bool sk_cloexec;
+  enum MHD_tristate sk_non_ip;
 
-  addrlen = sizeof (addrstorage);
-  memset (addr, 0, sizeof (addrstorage));
-  if (MHD_INVALID_SOCKET == (fd = daemon->socket_fd))
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
+
+  if ( (MHD_INVALID_SOCKET == (fd = daemon->listen_fd)) ||
+       (daemon->was_quiesced) )
     return MHD_NO;
-#ifdef HAVE_SOCK_NONBLOCK
-  nonblock = SOCK_NONBLOCK;
-#else
-  nonblock = 0;
+
+  addrlen = (socklen_t) sizeof (addrstorage);
+  memset (&addrstorage,
+          0,
+          (size_t) addrlen);
+#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
+  addrstorage.ss_len = addrlen;
+#endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */
+
+  /* Initialise with default values to avoid compiler warnings */
+  sk_nonbl = false;
+  sk_spipe_supprs = false;
+  sk_cloexec = false;
+
+#ifdef USE_ACCEPT4
+  if (MHD_INVALID_SOCKET !=
+      (s = accept4 (fd,
+                    (struct sockaddr *) &addrstorage,
+                    &addrlen,
+                    SOCK_CLOEXEC_OR_ZERO | SOCK_NONBLOCK_OR_ZERO
+                    | SOCK_NOSIGPIPE_OR_ZERO)))
+  {
+    sk_nonbl = (SOCK_NONBLOCK_OR_ZERO != 0);
+#ifndef MHD_WINSOCK_SOCKETS
+    sk_spipe_supprs = (SOCK_NOSIGPIPE_OR_ZERO != 0);
+#else  /* MHD_WINSOCK_SOCKETS */
+    sk_spipe_supprs = true; /* Nothing to suppress on W32 */
+#endif /* MHD_WINSOCK_SOCKETS */
+    sk_cloexec = (SOCK_CLOEXEC_OR_ZERO != 0);
+  }
+#else  /* ! USE_ACCEPT4 */
+  if (MHD_INVALID_SOCKET !=
+      (s = accept (fd,
+                   (struct sockaddr *) &addrstorage,
+                   &addrlen)))
+  {
+#ifdef MHD_ACCEPT_INHERIT_NONBLOCK
+    sk_nonbl = daemon->listen_nonblk;
+#else  /* ! MHD_ACCEPT_INHERIT_NONBLOCK */
+    sk_nonbl = false;
+#endif /* ! MHD_ACCEPT_INHERIT_NONBLOCK */
+#ifndef MHD_WINSOCK_SOCKETS
+    sk_spipe_supprs = false;
+#else  /* MHD_WINSOCK_SOCKETS */
+    sk_spipe_supprs = true; /* Nothing to suppress on W32 */
+#endif /* MHD_WINSOCK_SOCKETS */
+    sk_cloexec = false;
+  }
+#endif /* ! USE_ACCEPT4 */
+
+  if (MHD_INVALID_SOCKET == s)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    /* This could be a common occurrence with multiple worker threads */
+    if (MHD_SCKT_ERR_IS_ (err,
+                          MHD_SCKT_EINVAL_))
+      return MHD_NO;   /* can happen during shutdown */
+    if (MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_ (err))
+      return MHD_NO;   /* do not print error if client just disconnected early */
+#ifdef HAVE_MESSAGES
+    if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) )
+      MHD_DLOG (daemon,
+                _ ("Error accepting connection: %s\n"),
+                MHD_socket_strerr_ (err));
 #endif
-#ifdef CYGWIN
-  if (0 == (daemon->options & MHD_USE_SSL))
-    nonblock = 0;
-#endif
-#if HAVE_ACCEPT4
-  s = accept4 (fd, addr, &addrlen, SOCK_CLOEXEC | nonblock);
-#else
-  s = accept (fd, addr, &addrlen);
-#endif
-  if ((MHD_INVALID_SOCKET == s) || (addrlen <= 0))
+    if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err) )
     {
-#if HAVE_MESSAGES
-      const int err = MHD_socket_errno_;
-      /* This could be a common occurance with multiple worker threads */
-      if ( (EINVAL == err) &&
-           (MHD_INVALID_SOCKET == daemon->socket_fd) )
-        return MHD_NO; /* can happen during shutdown */
-      if ((EAGAIN != err) && (EWOULDBLOCK != err))
+      /* system/process out of resources */
+      if (0 == daemon->connections)
+      {
+#ifdef HAVE_MESSAGES
+        /* Not setting 'at_limit' flag, as there is no way it
+           would ever be cleared.  Instead trying to produce
+           bit fat ugly warning. */
         MHD_DLOG (daemon,
-		  "Error accepting connection: %s\n",
-		  MHD_socket_last_strerr_ ());
+                  _ ("Hit process or system resource limit at FIRST " \
+                     "connection. This is really bad as there is no sane " \
+                     "way to proceed. Will try busy waiting for system " \
+                     "resources to become magically available.\n"));
 #endif
-      if (MHD_INVALID_SOCKET != s)
-        {
-          if (0 != MHD_socket_close_ (s))
-	    MHD_PANIC ("close failed\n");
-          /* just in case */
-        }
+      }
+      else
+      {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+        MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+        daemon->at_limit = true;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+        MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Hit process or system resource limit at %u " \
+                     "connections, temporarily suspending accept(). " \
+                     "Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"),
+                  (unsigned int) daemon->connections);
+#endif
+      }
+    }
+    return MHD_NO;
+  }
+
+  sk_non_ip = daemon->listen_is_unix;
+  if (0 >= addrlen)
+  {
+    /* Should not happen as 'sockaddr_storage' must be large enough to
+     * store any address supported by the system. */
+#ifdef HAVE_MESSAGES
+    if (_MHD_NO != daemon->listen_is_unix)
+      MHD_DLOG (daemon,
+                _ ("Accepted socket has zero-length address. "
+                   "Processing the new socket as a socket with " \
+                   "unknown type.\n"));
+#endif
+    addrlen = 0;
+    sk_non_ip = _MHD_YES; /* IP-type addresses have non-zero length */
+  }
+  if (((socklen_t) sizeof (addrstorage)) < addrlen)
+  {
+    /* Should not happen as 'sockaddr_storage' must be large enough to
+     * store any address supported by the system. */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Accepted socket address is larger than expected by " \
+                 "system headers. Processing the new socket as a socket with " \
+                 "unknown type.\n"));
+#endif
+    addrlen = 0;
+    sk_non_ip = _MHD_YES; /* IP-type addresses must fit */
+  }
+
+  if (! sk_nonbl && ! MHD_socket_nonblocking_ (s))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to set nonblocking mode on incoming connection " \
+                 "socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#else  /* ! HAVE_MESSAGES */
+    (void) 0; /* Mute compiler warning */
+#endif /* ! HAVE_MESSAGES */
+  }
+  else
+    sk_nonbl = true;
+
+  if (! sk_cloexec && ! MHD_socket_noninheritable_ (s))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to set noninheritable mode on incoming connection " \
+                 "socket.\n"));
+#else  /* ! HAVE_MESSAGES */
+    (void) 0; /* Mute compiler warning */
+#endif /* ! HAVE_MESSAGES */
+  }
+
+#if defined(MHD_socket_nosignal_)
+  if (! sk_spipe_supprs && ! MHD_socket_nosignal_ (s))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to suppress SIGPIPE on incoming connection " \
+                 "socket: %s\n"),
+              MHD_socket_last_strerr_ ());
+#else  /* ! HAVE_MESSAGES */
+    (void) 0; /* Mute compiler warning */
+#endif /* ! HAVE_MESSAGES */
+#ifndef MSG_NOSIGNAL
+    /* Application expects that SIGPIPE will be suppressed,
+     * but suppression failed and SIGPIPE cannot be suppressed with send(). */
+    if (! daemon->sigpipe_blocked)
+    {
+      MHD_socket_close_ (s);
       return MHD_NO;
     }
-#if !defined(HAVE_ACCEPT4) || HAVE_ACCEPT4+0 == 0 || !defined(HAVE_SOCK_NONBLOCK) || SOCK_CLOEXEC+0 == 0
-  make_nonblocking_noninheritable (daemon, s);
-#endif
-#if HAVE_MESSAGES
-#if DEBUG_CONNECT
+#endif /* MSG_NOSIGNAL */
+  }
+  else
+    sk_spipe_supprs = true;
+#endif /* MHD_socket_nosignal_ */
+#ifdef HAVE_MESSAGES
+#if _MHD_DEBUG_CONNECT
   MHD_DLOG (daemon,
-            "Accepted connection on socket %d\n",
+            _ ("Accepted connection on socket %d\n"),
             s);
 #endif
 #endif
-  (void) internal_add_connection (daemon, s,
-				  addr, addrlen,
-				  MHD_NO);
+  (void) internal_add_connection (daemon,
+                                  s,
+                                  &addrstorage,
+                                  addrlen,
+                                  false,
+                                  sk_nonbl,
+                                  sk_spipe_supprs,
+                                  sk_non_ip);
   return MHD_YES;
 }
 
@@ -2055,6 +3876,8 @@
  * Free resources associated with all closed connections.
  * (destroy responses, free buffers, etc.).  All closed
  * connections are kept in the "cleanup" doubly-linked list.
+ * @remark To be called only from thread that
+ * process daemon's select()/poll()/etc.
  *
  * @param daemon daemon to clean up
  */
@@ -2062,181 +3885,427 @@
 MHD_cleanup_connections (struct MHD_Daemon *daemon)
 {
   struct MHD_Connection *pos;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+  mhd_assert (NULL == daemon->worker_pool);
 
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  while (NULL != (pos = daemon->cleanup_head))
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  while (NULL != (pos = daemon->cleanup_tail))
+  {
+    DLL_remove (daemon->cleanup_head,
+                daemon->cleanup_tail,
+                pos);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+    if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
+         (! pos->thread_joined) &&
+         (! MHD_join_thread_ (pos->pid.handle)) )
+      MHD_PANIC (_ ("Failed to join a thread.\n"));
+#endif
+#ifdef UPGRADE_SUPPORT
+    cleanup_upgraded_connection (pos);
+#endif /* UPGRADE_SUPPORT */
+    MHD_pool_destroy (pos->pool);
+#ifdef HTTPS_SUPPORT
+    if (NULL != pos->tls_session)
+      gnutls_deinit (pos->tls_session);
+#endif /* HTTPS_SUPPORT */
+
+    /* clean up the connection */
+    if (NULL != daemon->notify_connection)
+      daemon->notify_connection (daemon->notify_connection_cls,
+                                 pos,
+                                 &pos->socket_context,
+                                 MHD_CONNECTION_NOTIFY_CLOSED);
+    MHD_ip_limit_del (daemon,
+                      pos->addr,
+                      pos->addr_len);
+#ifdef EPOLL_SUPPORT
+    if (0 != (daemon->options & MHD_USE_EPOLL))
     {
-      DLL_remove (daemon->cleanup_head,
-		  daemon->cleanup_tail,
-		  pos);
-      if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-	   (MHD_NO == pos->thread_joined) )
-	{
-	  if (0 != MHD_join_thread_ (pos->pid))
-	    {
-	      MHD_PANIC ("Failed to join a thread\n");
-	    }
-	}
-      MHD_pool_destroy (pos->pool);
-#if HTTPS_SUPPORT
-      if (NULL != pos->tls_session)
- 	SSL_free (pos->tls_session);
-#endif
-      if (NULL != daemon->notify_connection)
-        daemon->notify_connection (daemon->notify_connection_cls,
-                                   pos,
-                                   &pos->socket_context,
-                                   MHD_CONNECTION_NOTIFY_CLOSED);
-      MHD_ip_limit_del (daemon, pos->addr, pos->addr_len);
-#if EPOLL_SUPPORT
       if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
-	{
-	  EDLL_remove (daemon->eready_head,
-		       daemon->eready_tail,
-		       pos);
-	  pos->epoll_state &= ~MHD_EPOLL_STATE_IN_EREADY_EDLL;
-	}
-      if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-	   (MHD_INVALID_SOCKET != daemon->epoll_fd) &&
-	   (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) )
-	{
-	  /* epoll documentation suggests that closing a FD
-	     automatically removes it from the epoll set; however,
-	     this is not true as if we fail to do manually remove it,
-	     we are still seeing an event for this fd in epoll,
-	     causing grief (use-after-free...) --- at least on my
-	     system. */
-	  if (0 != epoll_ctl (daemon->epoll_fd,
-			      EPOLL_CTL_DEL,
-			      pos->socket_fd,
-			      NULL))
-	    MHD_PANIC ("Failed to remove FD from epoll set\n");
-	  pos->epoll_state &= ~MHD_EPOLL_STATE_IN_EPOLL_SET;
-	}
-#endif
-      if (NULL != pos->response)
-	{
-	  MHD_destroy_response (pos->response);
-	  pos->response = NULL;
-	}
-      if (MHD_INVALID_SOCKET != pos->socket_fd)
-	{
-#ifdef WINDOWS
-	  shutdown (pos->socket_fd, SHUT_WR);
-#endif
-	  if (0 != MHD_socket_close_ (pos->socket_fd))
-	    MHD_PANIC ("close failed\n");
-	}
-      if (NULL != pos->addr)
-	free (pos->addr);
-      free (pos);
-      daemon->connections--;
+      {
+        EDLL_remove (daemon->eready_head,
+                     daemon->eready_tail,
+                     pos);
+        pos->epoll_state &=
+          ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL);
+      }
+      if ( (-1 != daemon->epoll_fd) &&
+           (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) )
+      {
+        /* epoll documentation suggests that closing a FD
+           automatically removes it from the epoll set; however,
+           this is not true as if we fail to do manually remove it,
+           we are still seeing an event for this fd in epoll,
+           causing grief (use-after-free...) --- at least on my
+           system. */
+        if (0 != epoll_ctl (daemon->epoll_fd,
+                            EPOLL_CTL_DEL,
+                            pos->socket_fd,
+                            NULL))
+          MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+        pos->epoll_state &=
+          ~((enum MHD_EpollState)
+            MHD_EPOLL_STATE_IN_EPOLL_SET);
+      }
     }
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+#endif
+    if (NULL != pos->rp.response)
+    {
+      MHD_destroy_response (pos->rp.response);
+      pos->rp.response = NULL;
+    }
+    if (MHD_INVALID_SOCKET != pos->socket_fd)
+      MHD_socket_close_chk_ (pos->socket_fd);
+    if (NULL != pos->addr)
+      free (pos->addr);
+    free (pos);
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+    daemon->connections--;
+    daemon->at_limit = false;
+  }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
 }
 
 
 /**
- * Obtain timeout value for `select()` for this daemon (only needed if
- * connection timeout is used).  The returned value is how long
- * `select()` or `poll()` should at most block, not the timeout value set
- * for connections.  This function MUST NOT be called if MHD is
- * running with #MHD_USE_THREAD_PER_CONNECTION.
+ * Obtain timeout value for polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function. Smaller timeout values can be used for
+ * polling function if it is required for any reason, but using larger
+ * timeout value or no timeout (indefinite timeout) when this function
+ * return #MHD_YES will break MHD processing logic and result in "hung"
+ * connections with data pending in network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout64(),
+ * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external"
+ * polling is used.
+ * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select())
+ * must be called right after return from polling function, regardless of
+ * the states of MHD FDs.
+ *
+ * In practice, if #MHD_YES is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than @a timeout
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
  *
  * @param daemon daemon to query for timeout
- * @param timeout set to the timeout (in milliseconds)
+ * @param[out] timeout set to the timeout (in milliseconds)
  * @return #MHD_YES on success, #MHD_NO if timeouts are
- *        not used (or no connections exist that would
- *        necessiate the use of a timeout right now).
+ *         not used and no data processing is pending.
  * @ingroup event
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_get_timeout (struct MHD_Daemon *daemon,
-		 MHD_UNSIGNED_LONG_LONG *timeout)
+                 MHD_UNSIGNED_LONG_LONG *timeout)
 {
-  time_t earliest_deadline;
-  time_t now;
-  struct MHD_Connection *pos;
-  int have_timeout;
-
-  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "Illegal call to MHD_get_timeout\n");
-#endif
-      return MHD_NO;
-    }
-
-#if HTTPS_SUPPORT
-  if (0 != daemon->num_tls_read_ready)
-    {
-      /* if there is any TLS connection with data ready for
-	 reading, we must not block in the event loop */
-      *timeout = 0;
-      return MHD_YES;
-    }
-#endif
-
-  have_timeout = MHD_NO;
-  earliest_deadline = 0; /* avoid compiler warnings */
-  for (pos = daemon->manual_timeout_head; NULL != pos; pos = pos->nextX)
-    {
-      if (0 != pos->connection_timeout)
-	{
-	  if ( (! have_timeout) ||
-	       (earliest_deadline > pos->last_activity + pos->connection_timeout) )
-	    earliest_deadline = pos->last_activity + pos->connection_timeout;
-#if HTTPS_SUPPORT
-	  if (  (0 != (daemon->options & MHD_USE_SSL)) &&
-		(0 != SSL_pending (pos->tls_session)) )
-	    earliest_deadline = 0;
-#endif
-	  have_timeout = MHD_YES;
-	}
-    }
-  /* normal timeouts are sorted, so we only need to look at the 'head' */
-  pos = daemon->normal_timeout_head;
-  if ( (NULL != pos) &&
-       (0 != pos->connection_timeout) )
-    {
-      if ( (! have_timeout) ||
-	   (earliest_deadline > pos->last_activity + pos->connection_timeout) )
-	earliest_deadline = pos->last_activity + pos->connection_timeout;
-#if HTTPS_SUPPORT
-      if (  (0 != (daemon->options & MHD_USE_SSL)) &&
-	    (0 != SSL_pending (pos->tls_session)) )
-	earliest_deadline = 0;
-#endif
-      have_timeout = MHD_YES;
-    }
-
-  if (MHD_NO == have_timeout)
+  uint64_t t64;
+  if (MHD_NO == MHD_get_timeout64 (daemon, &t64))
     return MHD_NO;
-  now = MHD_monotonic_time();
-  if (earliest_deadline < now)
-    *timeout = 0;
+
+#if SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG
+  if (ULLONG_MAX <= t64)
+    *timeout = ULLONG_MAX;
   else
-    *timeout = 1000 * (1 + earliest_deadline - now);
+#endif /* SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG */
+  *timeout = (MHD_UNSIGNED_LONG_LONG) t64;
   return MHD_YES;
 }
 
 
 /**
- * Run webserver operations. This method should be called by clients
- * in combination with #MHD_get_fdset if the client-controlled select
- * method is used.
+ * Obtain timeout value for external polling function for this daemon.
  *
- * You can use this function instead of #MHD_run if you called
- * `select()` on the result from #MHD_get_fdset.  File descriptors in
- * the sets that are not controlled by MHD will be ignored.  Calling
- * this function instead of #MHD_run is more efficient as MHD will
- * not have to call `select()` again to determine which operations are
- * ready.
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function. Smaller timeout values can be used for
+ * polling function if it is required for any reason, but using larger
+ * timeout value or no timeout (indefinite timeout) when this function
+ * return #MHD_YES will break MHD processing logic and result in "hung"
+ * connections with data pending in network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout(),
+ * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external"
+ * polling is used.
+ * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select())
+ * must be called right after return from polling function, regardless of
+ * the states of MHD FDs.
+ *
+ * In practice, if #MHD_YES is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than @a timeout
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon daemon to query for timeout
+ * @param[out] timeout64 the pointer to the variable to be set to the
+ *                  timeout (in milliseconds)
+ * @return #MHD_YES if timeout value has been set,
+ *         #MHD_NO if timeouts are not used and no data processing is pending.
+ * @note Available since #MHD_VERSION 0x00097508
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_get_timeout64 (struct MHD_Daemon *daemon,
+                   uint64_t *timeout64)
+{
+  uint64_t earliest_deadline;
+  struct MHD_Connection *pos;
+  struct MHD_Connection *earliest_tmot_conn; /**< the connection with earliest timeout */
+
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+#endif /* MHD_USE_THREADS */
+
+  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Illegal call to MHD_get_timeout.\n"));
+#endif
+    return MHD_NO;
+  }
+  if (daemon->data_already_pending)
+  {
+    /* Some data already waiting to be processed. */
+    *timeout64 = 0;
+    return MHD_YES;
+  }
+#ifdef EPOLL_SUPPORT
+  if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+       ((NULL != daemon->eready_head)
+#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
+        || (NULL != daemon->eready_urh_head)
+#endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */
+       ) )
+  {
+    /* Some connection(s) already have some data pending. */
+    *timeout64 = 0;
+    return MHD_YES;
+  }
+#endif /* EPOLL_SUPPORT */
+
+  earliest_tmot_conn = NULL;
+  earliest_deadline = 0; /* mute compiler warning */
+  /* normal timeouts are sorted, so we only need to look at the 'tail' (oldest) */
+  pos = daemon->normal_timeout_tail;
+  if ( (NULL != pos) &&
+       (0 != pos->connection_timeout_ms) )
+  {
+    earliest_tmot_conn = pos;
+    earliest_deadline = pos->last_activity + pos->connection_timeout_ms;
+  }
+
+  for (pos = daemon->manual_timeout_tail; NULL != pos; pos = pos->prevX)
+  {
+    if (0 != pos->connection_timeout_ms)
+    {
+      if ( (NULL == earliest_tmot_conn) ||
+           (earliest_deadline - pos->last_activity >
+            pos->connection_timeout_ms) )
+      {
+        earliest_tmot_conn = pos;
+        earliest_deadline = pos->last_activity + pos->connection_timeout_ms;
+      }
+    }
+  }
+
+  if (NULL != earliest_tmot_conn)
+  {
+    *timeout64 = connection_get_wait (earliest_tmot_conn);
+    return MHD_YES;
+  }
+  return MHD_NO;
+}
+
+
+#if defined(HAVE_POLL) || defined(EPOLL_SUPPORT)
+/**
+ * Obtain timeout value for external polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function (if returned value is non-negative).
+ * Smaller timeout values can be used for polling function if it is required
+ * for any reason, but using larger timeout value or no timeout (indefinite
+ * timeout) when this function returns non-negative value will break MHD
+ * processing logic and result in "hung" connections with data pending in
+ * network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout(),
+ * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external"
+ * polling is used.
+ * If this function returns non-negative value then #MHD_run() (or
+ * #MHD_run_from_select()) must be called right after return from polling
+ * function, regardless of the states of MHD FDs.
+ *
+ * In practice, if zero or positive value is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than returned amount of
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon the daemon to query for timeout
+ * @return -1 if connections' timeouts are not set and no data processing
+ *         is pending, so external polling function may wait for sockets
+ *         activity for indefinite amount of time,
+ *         otherwise returned value is the the maximum amount of millisecond
+ *         that external polling function must wait for the activity of FDs.
+ * @note Available since #MHD_VERSION 0x00097509
+ * @ingroup event
+ */
+_MHD_EXTERN int64_t
+MHD_get_timeout64s (struct MHD_Daemon *daemon)
+{
+  uint64_t utimeout;
+  if (MHD_NO == MHD_get_timeout64 (daemon, &utimeout))
+    return -1;
+  if (INT64_MAX < utimeout)
+    return INT64_MAX;
+
+  return (int64_t) utimeout;
+}
+
+
+/**
+ * Obtain timeout value for external polling function for this daemon.
+ *
+ * This function set value to the amount of milliseconds for which polling
+ * function (`select()`, `poll()` or epoll) should at most block, not the
+ * timeout value set for connections.
+ *
+ * Any "external" sockets polling function must be called with the timeout
+ * value provided by this function (if returned value is non-negative).
+ * Smaller timeout values can be used for polling function if it is required
+ * for any reason, but using larger timeout value or no timeout (indefinite
+ * timeout) when this function returns non-negative value will break MHD
+ * processing logic and result in "hung" connections with data pending in
+ * network buffers and other problems.
+ *
+ * It is important to always use this function (or #MHD_get_timeout(),
+ * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external"
+ * polling is used.
+ * If this function returns non-negative value then #MHD_run() (or
+ * #MHD_run_from_select()) must be called right after return from polling
+ * function, regardless of the states of MHD FDs.
+ *
+ * In practice, if zero or positive value is returned then #MHD_run() (or
+ * #MHD_run_from_select()) must be called not later than returned amount of
+ * millisecond even if no activity is detected on sockets by sockets
+ * polling function.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon the daemon to query for timeout
+ * @return -1 if connections' timeouts are not set and no data processing
+ *         is pending, so external polling function may wait for sockets
+ *         activity for indefinite amount of time,
+ *         otherwise returned value is the the maximum amount of millisecond
+ *         (capped at INT_MAX) that external polling function must wait
+ *         for the activity of FDs.
+ * @note Available since #MHD_VERSION 0x00097510
+ * @ingroup event
+ */
+_MHD_EXTERN int
+MHD_get_timeout_i (struct MHD_Daemon *daemon)
+{
+#if SIZEOF_INT >= SIZEOF_INT64_T
+  return MHD_get_timeout64s (daemon);
+#else  /* SIZEOF_INT < SIZEOF_INT64_T */
+  const int64_t to64 = MHD_get_timeout64s (daemon);
+  if (INT_MAX >= to64)
+    return (int) to64;
+  return INT_MAX;
+#endif /* SIZEOF_INT < SIZEOF_INT64_T */
+}
+
+
+/**
+ * Obtain timeout value for polling function for this daemon.
+ * @remark To be called only from the thread that processes
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon the daemon to query for timeout
+ * @param max_timeout the maximum return value (in milliseconds),
+ *                    ignored if set to '-1'
+ * @return timeout value in milliseconds or -1 if no timeout is expected.
+ */
+static int64_t
+get_timeout_millisec_ (struct MHD_Daemon *daemon,
+                       int32_t max_timeout)
+{
+  uint64_t d_timeout;
+  mhd_assert (0 <= max_timeout || -1 == max_timeout);
+  if (0 == max_timeout)
+    return 0;
+
+  if (MHD_NO == MHD_get_timeout64 (daemon, &d_timeout))
+    return max_timeout;
+
+  if ((0 < max_timeout) && ((uint64_t) max_timeout < d_timeout))
+    return max_timeout;
+
+  if (INT64_MAX <= d_timeout)
+    return INT64_MAX;
+
+  return (int64_t) d_timeout;
+}
+
+
+/**
+ * Obtain timeout value for polling function for this daemon.
+ * @remark To be called only from the thread that processes
+ * daemon's select()/poll()/etc.
+ *
+ * @param daemon the daemon to query for timeout
+ * @param max_timeout the maximum return value (in milliseconds),
+ *                    ignored if set to '-1'
+ * @return timeout value in milliseconds, capped to INT_MAX, or
+ *         -1 if no timeout is expected.
+ */
+static int
+get_timeout_millisec_int (struct MHD_Daemon *daemon,
+                          int32_t max_timeout)
+{
+  int64_t res;
+
+  res = get_timeout_millisec_ (daemon, max_timeout);
+#if SIZEOF_INT < SIZEOF_INT64_T
+  if (INT_MAX <= res)
+    return INT_MAX;
+#endif /* SIZEOF_INT < SIZEOF_INT64_T */
+  return (int) res;
+}
+
+
+#endif /* HAVE_POLL || EPOLL_SUPPORT */
+
+/**
+ * Internal version of #MHD_run_from_select().
  *
  * @param daemon daemon to run select loop for
  * @param read_fd_set read set
@@ -2245,181 +4314,358 @@
  * @return #MHD_NO on serious errors, #MHD_YES on success
  * @ingroup event
  */
-int
-MHD_run_from_select (struct MHD_Daemon *daemon,
-		     const fd_set *read_fd_set,
-		     const fd_set *write_fd_set,
-		     const fd_set *except_fd_set)
+static enum MHD_Result
+internal_run_from_select (struct MHD_Daemon *daemon,
+                          const fd_set *read_fd_set,
+                          const fd_set *write_fd_set,
+                          const fd_set *except_fd_set)
 {
   MHD_socket ds;
-  char tmp;
   struct MHD_Connection *pos;
-  struct MHD_Connection *next;
+  struct MHD_Connection *prev;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  struct MHD_UpgradeResponseHandle *urh;
+  struct MHD_UpgradeResponseHandle *urhn;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  /* Reset. New value will be set when connections are processed. */
+  /* Note: no-op for thread-per-connection as it is always false in that mode. */
+  daemon->data_already_pending = false;
 
-#if EPOLL_SUPPORT
-  if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-    {
-      /* we're in epoll mode, the epoll FD stands for
-	 the entire event set! */
-      if (daemon->epoll_fd >= FD_SETSIZE)
-	return MHD_NO; /* poll fd too big, fail hard */
-      if (FD_ISSET (daemon->epoll_fd, read_fd_set))
-	return MHD_run (daemon);
-      return MHD_YES;
-    }
-#endif
+  /* Clear ITC to avoid spinning select */
+  /* Do it before any other processing so new signals
+     will trigger select again and will be processed */
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (FD_ISSET (MHD_itc_r_fd_ (daemon->itc),
+                  (fd_set *) _MHD_DROP_CONST (read_fd_set))) )
+    MHD_itc_clear_ (daemon->itc);
+
+  /* Process externally added connection if any */
+  if (daemon->have_new)
+    new_connections_list_process_ (daemon);
 
   /* select connection thread handling type */
-  if ( (MHD_INVALID_SOCKET != (ds = daemon->socket_fd)) &&
-       (FD_ISSET (ds, (fd_set*)read_fd_set)) )
+  if ( (MHD_INVALID_SOCKET != (ds = daemon->listen_fd)) &&
+       (! daemon->was_quiesced) &&
+       (FD_ISSET (ds,
+                  (fd_set *) _MHD_DROP_CONST (read_fd_set))) )
     (void) MHD_accept_connection (daemon);
-  /* drain signaling pipe to avoid spinning select */
-  if ( (MHD_INVALID_PIPE_ != daemon->wpipe[0]) &&
-       (FD_ISSET (daemon->wpipe[0], (fd_set*)read_fd_set)) )
-    (void) MHD_pipe_read_ (daemon->wpipe[0], &tmp, sizeof (tmp));
 
   if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+  {
+    /* do not have a thread per connection, process all connections now */
+    prev = daemon->connections_tail;
+    while (NULL != (pos = prev))
     {
-      /* do not have a thread per connection, process all connections now */
-      next = daemon->connections_head;
-      while (NULL != (pos = next))
-        {
-	  next = pos->next;
-          ds = pos->socket_fd;
-          if (MHD_INVALID_SOCKET == ds)
-	    continue;
-	  switch (pos->event_loop_info)
-	    {
-	    case MHD_EVENT_LOOP_INFO_READ:
-	      if ( (FD_ISSET (ds, (fd_set*)read_fd_set))
-#if HTTPS_SUPPORT
-		   || (MHD_YES == pos->tls_read_ready)
-#endif
-		   )
-		pos->read_handler (pos);
-	      break;
-	    case MHD_EVENT_LOOP_INFO_WRITE:
-	      if ( (FD_ISSET (ds, (fd_set*)read_fd_set)) &&
-		   (pos->read_buffer_size > pos->read_buffer_offset) )
-		pos->read_handler (pos);
-	      if (FD_ISSET (ds, (fd_set*)write_fd_set))
-		pos->write_handler (pos);
-	      break;
-	    case MHD_EVENT_LOOP_INFO_BLOCK:
-	      if ( (FD_ISSET (ds, (fd_set*)read_fd_set)) &&
-		   (pos->read_buffer_size > pos->read_buffer_offset) )
-		pos->read_handler (pos);
-	      break;
-	    case MHD_EVENT_LOOP_INFO_CLEANUP:
-	      /* should never happen */
-	      break;
-	    }
-	  pos->idle_handler (pos);
-        }
+      prev = pos->prev;
+      ds = pos->socket_fd;
+      if (MHD_INVALID_SOCKET == ds)
+        continue;
+      call_handlers (pos,
+                     FD_ISSET (ds,
+                               (fd_set *) _MHD_DROP_CONST (read_fd_set)),
+                     FD_ISSET (ds,
+                               (fd_set *) _MHD_DROP_CONST (write_fd_set)),
+                     FD_ISSET (ds,
+                               (fd_set *) _MHD_DROP_CONST (except_fd_set)));
     }
+  }
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  /* handle upgraded HTTPS connections */
+  for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
+  {
+    urhn = urh->prev;
+    /* update urh state based on select() output */
+    urh_from_fdset (urh,
+                    read_fd_set,
+                    write_fd_set,
+                    except_fd_set);
+    /* call generic forwarding function for passing data */
+    process_urh (urh);
+    /* Finished forwarding? */
+    if ( (0 == urh->in_buffer_size) &&
+         (0 == urh->out_buffer_size) &&
+         (0 == urh->in_buffer_used) &&
+         (0 == urh->out_buffer_used) )
+    {
+      MHD_connection_finish_forward_ (urh->connection);
+      urh->clean_ready = true;
+      /* Resuming will move connection to cleanup list. */
+      MHD_resume_connection (urh->connection);
+    }
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
   MHD_cleanup_connections (daemon);
   return MHD_YES;
 }
 
 
 /**
+ * Run webserver operations. This method should be called by clients
+ * in combination with #MHD_get_fdset and #MHD_get_timeout() if the
+ * client-controlled select method is used.
+ *
+ * You can use this function instead of #MHD_run if you called
+ * `select()` on the result from #MHD_get_fdset.  File descriptors in
+ * the sets that are not controlled by MHD will be ignored.  Calling
+ * this function instead of #MHD_run is more efficient as MHD will
+ * not have to call `select()` again to determine which operations are
+ * ready.
+ *
+ * If #MHD_get_timeout() returned #MHD_YES, than this function must be
+ * called right after `select()` returns regardless of detected activity
+ * on the daemon's FDs.
+ *
+ * This function cannot be used with daemon started with
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag.
+ *
+ * @param daemon daemon to run select loop for
+ * @param read_fd_set read set
+ * @param write_fd_set write set
+ * @param except_fd_set except set
+ * @return #MHD_NO on serious errors, #MHD_YES on success
+ * @ingroup event
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_run_from_select (struct MHD_Daemon *daemon,
+                     const fd_set *read_fd_set,
+                     const fd_set *write_fd_set,
+                     const fd_set *except_fd_set)
+{
+  fd_set es;
+  if (0 != (daemon->options
+            & (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_POLL)) )
+    return MHD_NO;
+  if ((NULL == read_fd_set) || (NULL == write_fd_set))
+    return MHD_NO;
+  if (NULL == except_fd_set)
+  {   /* Workaround to maintain backward compatibility. */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("MHD_run_from_select() called with except_fd_set "
+                 "set to NULL. Such behavior is deprecated.\n"));
+#endif
+    FD_ZERO (&es);
+    except_fd_set = &es;
+  }
+  if (0 != (daemon->options & MHD_USE_EPOLL))
+  {
+#ifdef EPOLL_SUPPORT
+    enum MHD_Result ret = MHD_epoll (daemon,
+                                     0);
+
+    MHD_cleanup_connections (daemon);
+    return ret;
+#else  /* ! EPOLL_SUPPORT */
+    return MHD_NO;
+#endif /* ! EPOLL_SUPPORT */
+  }
+
+  /* Resuming external connections when using an extern mainloop  */
+  if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
+    resume_suspended_connections (daemon);
+
+  return internal_run_from_select (daemon,
+                                   read_fd_set,
+                                   write_fd_set,
+                                   except_fd_set);
+}
+
+
+/**
  * Main internal select() call.  Will compute select sets, call select()
- * and then #MHD_run_from_select with the result.
+ * and then #internal_run_from_select with the result.
  *
  * @param daemon daemon to run select() loop for
- * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @param millisec the maximum time in milliseconds to wait for events,
+ *                 set to '0' for non-blocking processing,
+ *                 set to '-1' to wait indefinitely.
  * @return #MHD_NO on serious errors, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 MHD_select (struct MHD_Daemon *daemon,
-	    int may_block)
+            int32_t millisec)
 {
   int num_ready;
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
   struct timeval timeout;
   struct timeval *tv;
-  MHD_UNSIGNED_LONG_LONG ltimeout;
+  int err_state;
+  MHD_socket ls;
 
   timeout.tv_sec = 0;
   timeout.tv_usec = 0;
-  if (MHD_YES == daemon->shutdown)
+  if (daemon->shutdown)
     return MHD_NO;
   FD_ZERO (&rs);
   FD_ZERO (&ws);
   FD_ZERO (&es);
-  max = MHD_INVALID_SOCKET;
+  maxsock = MHD_INVALID_SOCKET;
+  err_state = MHD_NO;
+  if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) &&
+       (MHD_NO != resume_suspended_connections (daemon)) &&
+       (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) )
+    millisec = 0;
+
   if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+  {
+    /* single-threaded, go over everything */
+    if (MHD_NO ==
+        internal_get_fdset2 (daemon,
+                             &rs,
+                             &ws,
+                             &es,
+                             &maxsock,
+                             FD_SETSIZE))
     {
-      if ( (MHD_USE_SUSPEND_RESUME == (daemon->options & MHD_USE_SUSPEND_RESUME)) &&
-           (MHD_YES == resume_suspended_connections (daemon)) )
-        may_block = MHD_NO;
-
-      /* single-threaded, go over everything */
-      if (MHD_NO == MHD_get_fdset2 (daemon, &rs, &ws, &es, &max, FD_SETSIZE))
-        return MHD_NO;
-
-      /* If we're at the connection limit, no need to
-         accept new connections; however, make sure
-         we do not miss the shutdown, so only do this
-         optimization if we have a shutdown signaling
-         pipe. */
-      if ( (MHD_INVALID_SOCKET != daemon->socket_fd) &&
-           (daemon->connections == daemon->connection_limit) &&
-           (0 != (daemon->options & MHD_USE_PIPE_FOR_SHUTDOWN)) )
-        FD_CLR (daemon->socket_fd, &rs);
-    }
-  else
-    {
-      /* accept only, have one thread per connection */
-      if ( (MHD_INVALID_SOCKET != daemon->socket_fd) &&
-           (MHD_YES != add_to_fd_set (daemon->socket_fd,
-                                      &rs,
-                                      &max,
-                                      FD_SETSIZE)) )
-        return MHD_NO;
-    }
-  if ( (MHD_INVALID_PIPE_ != daemon->wpipe[0]) &&
-       (MHD_YES != add_to_fd_set (daemon->wpipe[0],
-                                  &rs,
-                                  &max,
-                                  FD_SETSIZE)) )
-    return MHD_NO;
-
-  tv = NULL;
-  if (MHD_NO == may_block)
-    {
-      timeout.tv_usec = 0;
-      timeout.tv_sec = 0;
-      tv = &timeout;
-    }
-  else if ( (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-	    (MHD_YES == MHD_get_timeout (daemon, &ltimeout)) )
-    {
-      /* ltimeout is in ms */
-      timeout.tv_usec = (ltimeout % 1000) * 1000;
-      timeout.tv_sec = ltimeout / 1000;
-      tv = &timeout;
-    }
-  if (MHD_INVALID_SOCKET == max)
-    return MHD_YES;
-  num_ready = MHD_SYS_select_ (max + 1, &rs, &ws, &es, tv);
-  if (MHD_YES == daemon->shutdown)
-    return MHD_NO;
-  if (num_ready < 0)
-    {
-      if (EINTR == MHD_socket_errno_)
-        return MHD_YES;
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-                "select failed: %s\n",
-                MHD_socket_last_strerr_ ());
+                _ ("Could not obtain daemon fdsets.\n"));
+#endif
+      err_state = MHD_YES;
+    }
+  }
+  else
+  {
+    /* accept only, have one thread per connection */
+    if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+         (! daemon->was_quiesced) &&
+         (! MHD_add_to_fd_set_ (ls,
+                                &rs,
+                                &maxsock,
+                                FD_SETSIZE)) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Could not add listen socket to fdset.\n"));
 #endif
       return MHD_NO;
     }
-  return MHD_run_from_select (daemon, &rs, &ws, &es);
+  }
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                              &rs,
+                              &maxsock,
+                              FD_SETSIZE)) )
+  {
+    bool retry_succeed;
+
+    retry_succeed = false;
+#if defined(MHD_WINSOCK_SOCKETS)
+    /* fdset limit reached, new connections
+       cannot be handled. Remove listen socket FD
+       from fdset and retry to add ITC FD. */
+    if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+         (! daemon->was_quiesced) )
+    {
+      FD_CLR (ls,
+              &rs);
+      if (MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
+                              &rs,
+                              &maxsock,
+                              FD_SETSIZE))
+        retry_succeed = true;
+    }
+#endif /* MHD_WINSOCK_SOCKETS */
+
+    if (! retry_succeed)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon, _ ("Could not add control inter-thread " \
+                           "communication channel FD to fdset.\n"));
+#endif
+      err_state = MHD_YES;
+    }
+  }
+  /* Stop listening if we are at the configured connection limit */
+  /* If we're at the connection limit, no point in really
+     accepting new connections; however, make sure we do not miss
+     the shutdown OR the termination of an existing connection; so
+     only do this optimization if we have a signaling ITC in
+     place. */
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+       (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       ( (daemon->connections == daemon->connection_limit) ||
+         (daemon->at_limit) ) )
+  {
+    FD_CLR (ls,
+            &rs);
+  }
+
+  if (MHD_NO != err_state)
+    millisec = 0;
+  if (0 == millisec)
+  {
+    timeout.tv_usec = 0;
+    timeout.tv_sec = 0;
+    tv = &timeout;
+  }
+  else
+  {
+    uint64_t mhd_tmo;
+    uint64_t select_tmo;
+
+    if ( (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
+         (MHD_NO != MHD_get_timeout64 (daemon, &mhd_tmo)) )
+    {
+      if ( (0 < millisec) &&
+           (mhd_tmo > (uint64_t) millisec) )
+        select_tmo = (uint64_t) millisec;
+      else
+        select_tmo = mhd_tmo;
+      tv = &timeout; /* have timeout value */
+    }
+    else if (0 < millisec)
+    {
+      select_tmo = (uint64_t) millisec;
+      tv = &timeout; /* have timeout value */
+    }
+    else
+    {
+      select_tmo = 0; /* Not actually used, silent compiler warning */
+      tv = NULL;
+    }
+
+    if (NULL != tv)
+    { /* have timeout value */
+#if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC
+      if (select_tmo / 1000 > TIMEVAL_TV_SEC_MAX)
+        timeout.tv_sec = TIMEVAL_TV_SEC_MAX;
+      else
+#endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */
+      timeout.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) (select_tmo / 1000);
+
+      timeout.tv_usec = ((uint16_t) (select_tmo % 1000)) * ((int32_t) 1000);
+    }
+  }
+  num_ready = MHD_SYS_select_ (maxsock + 1,
+                               &rs,
+                               &ws,
+                               &es,
+                               tv);
+  if (daemon->shutdown)
+    return MHD_NO;
+  if (num_ready < 0)
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return (MHD_NO == err_state) ? MHD_YES : MHD_NO;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("select failed: %s\n"),
+              MHD_socket_strerr_ (err));
+#endif
+    return MHD_NO;
+  }
+  if (MHD_NO != internal_run_from_select (daemon,
+                                          &rs,
+                                          &ws,
+                                          &es))
+    return (MHD_NO == err_state) ? MHD_YES : MHD_NO;
+  return MHD_NO;
 }
 
 
@@ -2429,179 +4675,214 @@
  * socket using poll().
  *
  * @param daemon daemon to run poll loop for
- * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @param millisec the maximum time in milliseconds to wait for events,
+ *                 set to '0' for non-blocking processing,
+ *                 set to '-1' to wait indefinitely.
  * @return #MHD_NO on serious errors, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 MHD_poll_all (struct MHD_Daemon *daemon,
-	      int may_block)
+              int32_t millisec)
 {
   unsigned int num_connections;
   struct MHD_Connection *pos;
-  struct MHD_Connection *next;
+  struct MHD_Connection *prev;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  struct MHD_UpgradeResponseHandle *urh;
+  struct MHD_UpgradeResponseHandle *urhn;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
 
-  if ( (MHD_USE_SUSPEND_RESUME == (daemon->options & MHD_USE_SUSPEND_RESUME)) &&
-       (MHD_YES == resume_suspended_connections (daemon)) )
-    may_block = MHD_NO;
+  if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) &&
+       (MHD_NO != resume_suspended_connections (daemon)) )
+    millisec = 0;
 
   /* count number of connections and thus determine poll set size */
   num_connections = 0;
   for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
     num_connections++;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  for (urh = daemon->urh_head; NULL != urh; urh = urh->next)
+    num_connections += 2;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
   {
-    MHD_UNSIGNED_LONG_LONG ltimeout;
     unsigned int i;
     int timeout;
     unsigned int poll_server;
     int poll_listen;
-    int poll_pipe;
-    char tmp;
+    int poll_itc_idx;
     struct pollfd *p;
+    MHD_socket ls;
 
-    p = malloc(sizeof (struct pollfd) * (2 + num_connections));
+    p = MHD_calloc_ ((2 + (size_t) num_connections),
+                     sizeof (struct pollfd));
     if (NULL == p)
-      {
-#if HAVE_MESSAGES
-        MHD_DLOG(daemon,
-                 "Error allocating memory: %s\n",
-                 MHD_strerror_(errno));
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Error allocating memory: %s\n"),
+                MHD_strerror_ (errno));
 #endif
-        return MHD_NO;
-      }
-    memset (p, 0, sizeof (struct pollfd) * (2 + num_connections));
+      return MHD_NO;
+    }
     poll_server = 0;
     poll_listen = -1;
-    if ( (MHD_INVALID_SOCKET != daemon->socket_fd) &&
-	 (daemon->connections < daemon->connection_limit) )
-      {
-	/* only listen if we are not at the connection limit */
-	p[poll_server].fd = daemon->socket_fd;
-	p[poll_server].events = POLLIN;
-	p[poll_server].revents = 0;
-	poll_listen = (int) poll_server;
-	poll_server++;
-      }
-    poll_pipe = -1;
-    if (MHD_INVALID_PIPE_ != daemon->wpipe[0])
-      {
-	p[poll_server].fd = daemon->wpipe[0];
-	p[poll_server].events = POLLIN;
-	p[poll_server].revents = 0;
-        poll_pipe = (int) poll_server;
-	poll_server++;
-      }
-    if (may_block == MHD_NO)
-      timeout = 0;
-    else if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) ||
-	      (MHD_YES != MHD_get_timeout (daemon, &ltimeout)) )
-      timeout = -1;
-    else
-      timeout = (ltimeout > INT_MAX) ? INT_MAX : (int) ltimeout;
+    if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+         (! daemon->was_quiesced) &&
+         (daemon->connections < daemon->connection_limit) &&
+         (! daemon->at_limit) )
+    {
+      /* only listen if we are not at the connection limit */
+      p[poll_server].fd = ls;
+      p[poll_server].events = POLLIN;
+      p[poll_server].revents = 0;
+      poll_listen = (int) poll_server;
+      poll_server++;
+    }
+    poll_itc_idx = -1;
+    if (MHD_ITC_IS_VALID_ (daemon->itc))
+    {
+      p[poll_server].fd = MHD_itc_r_fd_ (daemon->itc);
+      p[poll_server].events = POLLIN;
+      p[poll_server].revents = 0;
+      poll_itc_idx = (int) poll_server;
+      poll_server++;
+    }
+
+    timeout = get_timeout_millisec_int (daemon, millisec);
 
     i = 0;
-    for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
+    for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev)
+    {
+      p[poll_server + i].fd = pos->socket_fd;
+      switch (pos->event_loop_info)
       {
-	p[poll_server+i].fd = pos->socket_fd;
-	switch (pos->event_loop_info)
-	  {
-	  case MHD_EVENT_LOOP_INFO_READ:
-	    p[poll_server+i].events |= POLLIN;
-	    break;
-	  case MHD_EVENT_LOOP_INFO_WRITE:
-	    p[poll_server+i].events |= POLLOUT;
-	    if (pos->read_buffer_size > pos->read_buffer_offset)
-	      p[poll_server+i].events |= POLLIN;
-	    break;
-	  case MHD_EVENT_LOOP_INFO_BLOCK:
-	    if (pos->read_buffer_size > pos->read_buffer_offset)
-	      p[poll_server+i].events |= POLLIN;
-	    break;
-	  case MHD_EVENT_LOOP_INFO_CLEANUP:
-	    timeout = 0; /* clean up "pos" immediately */
-	    break;
-	  }
-	i++;
+      case MHD_EVENT_LOOP_INFO_READ:
+      case MHD_EVENT_LOOP_INFO_PROCESS_READ:
+        p[poll_server + i].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_WRITE:
+        p[poll_server + i].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_PROCESS:
+        p[poll_server + i].events |=  MHD_POLL_EVENTS_ERR_DISC;
+        break;
+      case MHD_EVENT_LOOP_INFO_CLEANUP:
+        timeout = 0; /* clean up "pos" immediately */
+        break;
       }
+      i++;
+    }
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev)
+    {
+      urh_to_pollfd (urh, &(p[poll_server + i]));
+      i += 2;
+    }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
     if (0 == poll_server + num_connections)
+    {
+      free (p);
+      return MHD_YES;
+    }
+    if (MHD_sys_poll_ (p,
+                       poll_server + num_connections,
+                       timeout) < 0)
+    {
+      const int err = MHD_socket_get_error_ ();
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
       {
-        free(p);
+        free (p);
         return MHD_YES;
       }
-    if (MHD_sys_poll_(p, poll_server + num_connections, timeout) < 0)
-      {
-	if (EINTR == MHD_socket_errno_)
-      {
-        free(p);
-        return MHD_YES;
-      }
-#if HAVE_MESSAGES
-	MHD_DLOG (daemon,
-		  "poll failed: %s\n",
-		  MHD_socket_last_strerr_ ());
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("poll failed: %s\n"),
+                MHD_socket_strerr_ (err));
 #endif
-        free(p);
-	return MHD_NO;
-      }
+      free (p);
+      return MHD_NO;
+    }
+
+    /* handle ITC FD */
+    /* do it before any other processing so
+       new signals will be processed in next loop */
+    if ( (-1 != poll_itc_idx) &&
+         (0 != (p[poll_itc_idx].revents & POLLIN)) )
+      MHD_itc_clear_ (daemon->itc);
+
     /* handle shutdown */
-    if (MHD_YES == daemon->shutdown)
-      {
-        free(p);
-        return MHD_NO;
-      }
-    i = 0;
-    next = daemon->connections_head;
-    while (NULL != (pos = next))
-      {
-	next = pos->next;
-	switch (pos->event_loop_info)
-	  {
-	  case MHD_EVENT_LOOP_INFO_READ:
-	    /* first, sanity checks */
-	    if (i >= num_connections)
-	      break; /* connection list changed somehow, retry later ... */
-	    if (p[poll_server+i].fd != pos->socket_fd)
-	      break; /* fd mismatch, something else happened, retry later ... */
-	    /* normal handling */
-	    if (0 != (p[poll_server+i].revents & POLLIN))
-	      pos->read_handler (pos);
-	    pos->idle_handler (pos);
-	    i++;
-	    break;
-	  case MHD_EVENT_LOOP_INFO_WRITE:
-	    /* first, sanity checks */
-	    if (i >= num_connections)
-	      break; /* connection list changed somehow, retry later ... */
-	    if (p[poll_server+i].fd != pos->socket_fd)
-	      break; /* fd mismatch, something else happened, retry later ... */
-	    /* normal handling */
-	    if (0 != (p[poll_server+i].revents & POLLIN))
-	      pos->read_handler (pos);
-	    if (0 != (p[poll_server+i].revents & POLLOUT))
-	      pos->write_handler (pos);
-	    pos->idle_handler (pos);
-	    i++;
-	    break;
-	  case MHD_EVENT_LOOP_INFO_BLOCK:
-	    if (0 != (p[poll_server+i].revents & POLLIN))
-	      pos->read_handler (pos);
-	    pos->idle_handler (pos);
-	    break;
-	  case MHD_EVENT_LOOP_INFO_CLEANUP:
-	    pos->idle_handler (pos);
-	    break;
-	  }
-      }
+    if (daemon->shutdown)
+    {
+      free (p);
+      return MHD_NO;
+    }
+
+    /* Process externally added connection if any */
+    if (daemon->have_new)
+      new_connections_list_process_ (daemon);
+
     /* handle 'listen' FD */
     if ( (-1 != poll_listen) &&
-	 (0 != (p[poll_listen].revents & POLLIN)) )
+         (0 != (p[poll_listen].revents & POLLIN)) )
       (void) MHD_accept_connection (daemon);
 
-    /* handle pipe FD */
-    if ( (-1 != poll_pipe) &&
-         (0 != (p[poll_pipe].revents & POLLIN)) )
-      (void) MHD_pipe_read_ (daemon->wpipe[0], &tmp, sizeof (tmp));
+    /* Reset. New value will be set when connections are processed. */
+    daemon->data_already_pending = false;
 
-    free(p);
+    i = 0;
+    prev = daemon->connections_tail;
+    while (NULL != (pos = prev))
+    {
+      prev = pos->prev;
+      /* first, sanity checks */
+      if (i >= num_connections)
+        break;     /* connection list changed somehow, retry later ... */
+      if (p[poll_server + i].fd != pos->socket_fd)
+        continue;  /* fd mismatch, something else happened, retry later ... */
+      call_handlers (pos,
+                     0 != (p[poll_server + i].revents & POLLIN),
+                     0 != (p[poll_server + i].revents & POLLOUT),
+                     0 != (p[poll_server + i].revents
+                           & MHD_POLL_REVENTS_ERR_DISC));
+      i++;
+    }
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
+    {
+      if (i >= num_connections)
+        break;   /* connection list changed somehow, retry later ... */
+
+      /* Get next connection here as connection can be removed
+       * from 'daemon->urh_head' list. */
+      urhn = urh->prev;
+      /* Check for fd mismatch. FIXME: required for safety? */
+      if ((p[poll_server + i].fd != urh->connection->socket_fd) ||
+          (p[poll_server + i + 1].fd != urh->mhd.socket))
+        break;
+      urh_from_pollfd (urh,
+                       &p[poll_server + i]);
+      i += 2;
+      process_urh (urh);
+      /* Finished forwarding? */
+      if ( (0 == urh->in_buffer_size) &&
+           (0 == urh->out_buffer_size) &&
+           (0 == urh->in_buffer_used) &&
+           (0 == urh->out_buffer_used) )
+      {
+        /* MHD_connection_finish_forward_() will remove connection from
+         * 'daemon->urh_head' list. */
+        MHD_connection_finish_forward_ (urh->connection);
+        urh->clean_ready = true;
+        /* If 'urh->was_closed' already was set to true, connection will be
+         * moved immediately to cleanup list. Otherwise connection
+         * will stay in suspended list until 'urh' will be marked
+         * with 'was_closed' by application. */
+        MHD_resume_connection (urh->connection);
+      }
+    }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+    free (p);
   }
   return MHD_YES;
 }
@@ -2614,60 +4895,88 @@
  * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
  * @return #MHD_NO on serious errors, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 MHD_poll_listen_socket (struct MHD_Daemon *daemon,
-			int may_block)
+                        int may_block)
 {
   struct pollfd p[2];
   int timeout;
   unsigned int poll_count;
   int poll_listen;
+  int poll_itc_idx;
+  MHD_socket ls;
 
-  memset (&p, 0, sizeof (p));
+  memset (&p,
+          0,
+          sizeof (p));
   poll_count = 0;
   poll_listen = -1;
-  if (MHD_INVALID_SOCKET != daemon->socket_fd)
-    {
-      p[poll_count].fd = daemon->socket_fd;
-      p[poll_count].events = POLLIN;
-      p[poll_count].revents = 0;
-      poll_listen = poll_count;
-      poll_count++;
-    }
-  if (MHD_INVALID_PIPE_ != daemon->wpipe[0])
-    {
-      p[poll_count].fd = daemon->wpipe[0];
-      p[poll_count].events = POLLIN;
-      p[poll_count].revents = 0;
-      poll_count++;
-    }
+  poll_itc_idx = -1;
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+       (! daemon->was_quiesced) )
+
+  {
+    p[poll_count].fd = ls;
+    p[poll_count].events = POLLIN;
+    p[poll_count].revents = 0;
+    poll_listen = (int) poll_count;
+    poll_count++;
+  }
+  if (MHD_ITC_IS_VALID_ (daemon->itc))
+  {
+    p[poll_count].fd = MHD_itc_r_fd_ (daemon->itc);
+    p[poll_count].events = POLLIN;
+    p[poll_count].revents = 0;
+    poll_itc_idx = (int) poll_count;
+    poll_count++;
+  }
+
+  if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
+    (void) resume_suspended_connections (daemon);
+
   if (MHD_NO == may_block)
     timeout = 0;
   else
     timeout = -1;
   if (0 == poll_count)
     return MHD_YES;
-  if (MHD_sys_poll_(p, poll_count, timeout) < 0)
-    {
-      if (EINTR == MHD_socket_errno_)
-	return MHD_YES;
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "poll failed: %s\n",
-                MHD_socket_last_strerr_ ());
+  if (MHD_sys_poll_ (p,
+                     poll_count,
+                     timeout) < 0)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_YES;
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("poll failed: %s\n"),
+              MHD_socket_strerr_ (err));
 #endif
-      return MHD_NO;
-    }
-  /* handle shutdown */
-  if (MHD_YES == daemon->shutdown)
     return MHD_NO;
-  if ( (-1 != poll_listen) &&
+  }
+  if ( (0 <= poll_itc_idx) &&
+       (0 != (p[poll_itc_idx].revents & POLLIN)) )
+    MHD_itc_clear_ (daemon->itc);
+
+  /* handle shutdown */
+  if (daemon->shutdown)
+    return MHD_NO;
+
+  /* Process externally added connection if any */
+  if (daemon->have_new)
+    new_connections_list_process_ (daemon);
+
+  if ( (0 <= poll_listen) &&
        (0 != (p[poll_listen].revents & POLLIN)) )
     (void) MHD_accept_connection (daemon);
   return MHD_YES;
 }
+
+
 #endif
 
+#ifdef HAVE_POLL
 
 /**
  * Do poll()-based processing.
@@ -2676,24 +4985,22 @@
  * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
  * @return #MHD_NO on serious errors, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 MHD_poll (struct MHD_Daemon *daemon,
-	  int may_block)
+          int may_block)
 {
-#ifdef HAVE_POLL
-  if (MHD_YES == daemon->shutdown)
-    return MHD_NO;
   if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
-    return MHD_poll_all (daemon, may_block);
-  else
-    return MHD_poll_listen_socket (daemon, may_block);
-#else
-  return MHD_NO;
-#endif
+    return MHD_poll_all (daemon,
+                         may_block ? -1 : 0);
+  return MHD_poll_listen_socket (daemon,
+                                 may_block);
 }
 
 
-#if EPOLL_SUPPORT
+#endif /* HAVE_POLL */
+
+
+#ifdef EPOLL_SUPPORT
 
 /**
  * How many events to we process at most per epoll() call?  Trade-off
@@ -2706,220 +5013,495 @@
 #define MAX_EVENTS 128
 
 
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+
 /**
- * Do epoll()-based processing (this function is allowed to
- * block if @a may_block is set to #MHD_YES).
+ * Checks whether @a urh has some data to process.
+ *
+ * @param urh upgrade handler to analyse
+ * @return 'true' if @a urh has some data to process,
+ *         'false' otherwise
+ */
+static bool
+is_urh_ready (struct MHD_UpgradeResponseHandle *const urh)
+{
+  const struct MHD_Connection *const connection = urh->connection;
+
+  if ( (0 == urh->in_buffer_size) &&
+       (0 == urh->out_buffer_size) &&
+       (0 == urh->in_buffer_used) &&
+       (0 == urh->out_buffer_used) )
+    return false;
+  if (connection->daemon->shutdown)
+    return true;
+  if ( ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->app.celi)) ||
+         (connection->tls_read_ready) ) &&
+       (urh->in_buffer_used < urh->in_buffer_size) )
+    return true;
+  if ( (0 != (MHD_EPOLL_STATE_READ_READY & urh->mhd.celi)) &&
+       (urh->out_buffer_used < urh->out_buffer_size) )
+    return true;
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) &&
+       (urh->out_buffer_used > 0) )
+    return true;
+  if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) &&
+       (urh->in_buffer_used > 0) )
+    return true;
+  return false;
+}
+
+
+/**
+ * Do epoll()-based processing for TLS connections that have been
+ * upgraded.  This requires a separate epoll() invocation as we
+ * cannot use the `struct MHD_Connection` data structures for
+ * the `union epoll_data` in this case.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
+ */
+static enum MHD_Result
+run_epoll_for_upgrade (struct MHD_Daemon *daemon)
+{
+  struct epoll_event events[MAX_EVENTS];
+  int num_events;
+  struct MHD_UpgradeResponseHandle *pos;
+  struct MHD_UpgradeResponseHandle *prev;
+
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+#endif /* MHD_USE_THREADS */
+
+  num_events = MAX_EVENTS;
+  while (0 != num_events)
+  {
+    unsigned int i;
+    /* update event masks */
+    num_events = epoll_wait (daemon->epoll_upgrade_fd,
+                             events,
+                             MAX_EVENTS,
+                             0);
+    if (-1 == num_events)
+    {
+      const int err = MHD_socket_get_error_ ();
+
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        return MHD_YES;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Call to epoll_wait failed: %s\n"),
+                MHD_socket_strerr_ (err));
+#endif
+      return MHD_NO;
+    }
+    for (i = 0; i < (unsigned int) num_events; i++)
+    {
+      struct UpgradeEpollHandle *const ueh = events[i].data.ptr;
+      struct MHD_UpgradeResponseHandle *const urh = ueh->urh;
+      bool new_err_state = false;
+
+      if (urh->clean_ready)
+        continue;
+
+      /* Update ueh state based on what is ready according to epoll() */
+      if (0 != (events[i].events & EPOLLIN))
+      {
+        ueh->celi |= MHD_EPOLL_STATE_READ_READY;
+      }
+      if (0 != (events[i].events & EPOLLOUT))
+      {
+        ueh->celi |= MHD_EPOLL_STATE_WRITE_READY;
+      }
+      if (0 != (events[i].events & EPOLLHUP))
+      {
+        ueh->celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY;
+      }
+
+      if ( (0 == (ueh->celi & MHD_EPOLL_STATE_ERROR)) &&
+           (0 != (events[i].events & (EPOLLERR | EPOLLPRI))) )
+      {
+        /* Process new error state only one time and avoid continuously
+         * marking this connection as 'ready'. */
+        ueh->celi |= MHD_EPOLL_STATE_ERROR;
+        new_err_state = true;
+      }
+      if (! urh->in_eready_list)
+      {
+        if (new_err_state ||
+            is_urh_ready (urh))
+        {
+          EDLL_insert (daemon->eready_urh_head,
+                       daemon->eready_urh_tail,
+                       urh);
+          urh->in_eready_list = true;
+        }
+      }
+    }
+  }
+  prev = daemon->eready_urh_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevE;
+    process_urh (pos);
+    if (! is_urh_ready (pos))
+    {
+      EDLL_remove (daemon->eready_urh_head,
+                   daemon->eready_urh_tail,
+                   pos);
+      pos->in_eready_list = false;
+    }
+    /* Finished forwarding? */
+    if ( (0 == pos->in_buffer_size) &&
+         (0 == pos->out_buffer_size) &&
+         (0 == pos->in_buffer_used) &&
+         (0 == pos->out_buffer_used) )
+    {
+      MHD_connection_finish_forward_ (pos->connection);
+      pos->clean_ready = true;
+      /* If 'pos->was_closed' already was set to true, connection
+       * will be moved immediately to cleanup list. Otherwise
+       * connection will stay in suspended list until 'pos' will
+       * be marked with 'was_closed' by application. */
+      MHD_resume_connection (pos->connection);
+    }
+  }
+
+  return MHD_YES;
+}
+
+
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+
+/**
+ * Pointer-marker to distinguish ITC slot in epoll sets.
+ */
+static const char *const epoll_itc_marker = "itc_marker";
+
+
+/**
+ * Do epoll()-based processing.
  *
  * @param daemon daemon to run poll loop for
- * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking
+ * @param millisec the maximum time in milliseconds to wait for events,
+ *                 set to '0' for non-blocking processing,
+ *                 set to '-1' to wait indefinitely.
  * @return #MHD_NO on serious errors, #MHD_YES on success
  */
-static int
+static enum MHD_Result
 MHD_epoll (struct MHD_Daemon *daemon,
-	   int may_block)
+           int32_t millisec)
 {
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  static const char *const upgrade_marker = "upgrade_ptr";
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
   struct MHD_Connection *pos;
-  struct MHD_Connection *next;
+  struct MHD_Connection *prev;
   struct epoll_event events[MAX_EVENTS];
   struct epoll_event event;
   int timeout_ms;
-  MHD_UNSIGNED_LONG_LONG timeout_ll;
   int num_events;
   unsigned int i;
-  unsigned int series_length;
-  char tmp;
+  MHD_socket ls;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  bool run_upgraded = false;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  bool need_to_accept;
 
   if (-1 == daemon->epoll_fd)
     return MHD_NO; /* we're down! */
-  if (MHD_YES == daemon->shutdown)
+  if (daemon->shutdown)
     return MHD_NO;
-  if ( (MHD_INVALID_SOCKET != daemon->socket_fd) &&
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+       (! daemon->was_quiesced) &&
        (daemon->connections < daemon->connection_limit) &&
-       (MHD_NO == daemon->listen_socket_in_epoll) )
+       (! daemon->listen_socket_in_epoll) &&
+       (! daemon->at_limit) )
+  {
+    event.events = EPOLLIN | EPOLLRDHUP;
+    event.data.ptr = daemon;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        ls,
+                        &event))
     {
-      event.events = EPOLLIN;
-      event.data.ptr = daemon;
-      if (0 != epoll_ctl (daemon->epoll_fd,
-			  EPOLL_CTL_ADD,
-			  daemon->socket_fd,
-			  &event))
-	{
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Call to epoll_ctl failed: %s\n",
-                    MHD_socket_last_strerr_ ());
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Call to epoll_ctl failed: %s\n"),
+                MHD_socket_last_strerr_ ());
 #endif
-	  return MHD_NO;
-	}
-      daemon->listen_socket_in_epoll = MHD_YES;
+      return MHD_NO;
     }
-  if ( (MHD_YES == daemon->listen_socket_in_epoll) &&
-       (daemon->connections == daemon->connection_limit) )
-    {
-      /* we're at the connection limit, disable listen socket
-	 for event loop for now */
-      if (0 != epoll_ctl (daemon->epoll_fd,
-			  EPOLL_CTL_DEL,
-			  daemon->socket_fd,
-			  NULL))
-	MHD_PANIC ("Failed to remove listen FD from epoll set\n");
-      daemon->listen_socket_in_epoll = MHD_NO;
-    }
-  if (MHD_YES == may_block)
-    {
-      if (MHD_YES == MHD_get_timeout (daemon,
-				      &timeout_ll))
-	{
-	  if (timeout_ll >= (MHD_UNSIGNED_LONG_LONG) INT_MAX)
-	    timeout_ms = INT_MAX;
-	  else
-	    timeout_ms = (int) timeout_ll;
-	}
-      else
-	timeout_ms = -1;
-    }
-  else
-    timeout_ms = 0;
+    daemon->listen_socket_in_epoll = true;
+  }
+  if ( (daemon->was_quiesced) &&
+       (daemon->listen_socket_in_epoll) )
+  {
+    if ( (0 != epoll_ctl (daemon->epoll_fd,
+                          EPOLL_CTL_DEL,
+                          ls,
+                          NULL)) &&
+         (ENOENT != errno) )   /* ENOENT can happen due to race with
+                                  #MHD_quiesce_daemon() */
+      MHD_PANIC ("Failed to remove listen FD from epoll set.\n");
+    daemon->listen_socket_in_epoll = false;
+  }
 
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if ( ( (! daemon->upgrade_fd_in_epoll) &&
+         (-1 != daemon->epoll_upgrade_fd) ) )
+  {
+    event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP;
+    event.data.ptr = _MHD_DROP_CONST (upgrade_marker);
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        daemon->epoll_upgrade_fd,
+                        &event))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Call to epoll_ctl failed: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      return MHD_NO;
+    }
+    daemon->upgrade_fd_in_epoll = true;
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  if ( (daemon->listen_socket_in_epoll) &&
+       ( (daemon->connections == daemon->connection_limit) ||
+         (daemon->at_limit) ||
+         (daemon->was_quiesced) ) )
+  {
+    /* we're at the connection limit, disable listen socket
+ for event loop for now */
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_DEL,
+                        ls,
+                        NULL))
+      MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n"));
+    daemon->listen_socket_in_epoll = false;
+  }
+
+  if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) &&
+       (MHD_NO != resume_suspended_connections (daemon)) )
+    millisec = 0;
+
+  timeout_ms = get_timeout_millisec_int (daemon, millisec);
+
+  /* Reset. New value will be set when connections are processed. */
+  /* Note: Used mostly for uniformity here as same situation is
+   * signaled in epoll mode by non-empty eready DLL. */
+  daemon->data_already_pending = false;
+
+  need_to_accept = false;
   /* drain 'epoll' event queue; need to iterate as we get at most
      MAX_EVENTS in one system call here; in practice this should
      pretty much mean only one round, but better an extra loop here
      than unfair behavior... */
   num_events = MAX_EVENTS;
   while (MAX_EVENTS == num_events)
+  {
+    /* update event masks */
+    num_events = epoll_wait (daemon->epoll_fd,
+                             events,
+                             MAX_EVENTS,
+                             timeout_ms);
+    if (-1 == num_events)
     {
-      /* update event masks */
-      num_events = epoll_wait (daemon->epoll_fd,
-			       events, MAX_EVENTS, timeout_ms);
-      if (-1 == num_events)
-	{
-	  if (EINTR == MHD_socket_errno_)
-	    return MHD_YES;
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Call to epoll_wait failed: %s\n",
-                    MHD_socket_last_strerr_ ());
+      const int err = MHD_socket_get_error_ ();
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        return MHD_YES;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Call to epoll_wait failed: %s\n"),
+                MHD_socket_strerr_ (err));
 #endif
-	  return MHD_NO;
-	}
-      for (i=0;i<(unsigned int) num_events;i++)
-	{
-	  if (NULL == events[i].data.ptr)
-	    continue; /* shutdown signal! */
-          if ( (MHD_INVALID_PIPE_ != daemon->wpipe[0]) &&
-               (daemon->wpipe[0] == events[i].data.fd) )
-            {
-              (void) MHD_pipe_read_ (daemon->wpipe[0], &tmp, sizeof (tmp));
-              continue;
-            }
-	  if (daemon != events[i].data.ptr)
-	    {
-	      /* this is an event relating to a 'normal' connection,
-		 remember the event and if appropriate mark the
-		 connection as 'eready'. */
-	      pos = events[i].data.ptr;
-	      if (0 != (events[i].events & EPOLLIN))
-		{
-		  pos->epoll_state |= MHD_EPOLL_STATE_READ_READY;
-		  if ( ( (MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info) ||
-			 (pos->read_buffer_size > pos->read_buffer_offset) ) &&
-		       (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
-		    {
-		      EDLL_insert (daemon->eready_head,
-				   daemon->eready_tail,
-				   pos);
-		      pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
-		    }
-		}
-	      if (0 != (events[i].events & EPOLLOUT))
-		{
-		  pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY;
-		  if ( (MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) &&
-		       (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
-		    {
-		      EDLL_insert (daemon->eready_head,
-				   daemon->eready_tail,
-				   pos);
-		      pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
-		    }
-		}
-	    }
-	  else /* must be listen socket */
-	    {
-	      /* run 'accept' until it fails or we are not allowed to take
-		 on more connections */
-	      series_length = 0;
-	      while ( (MHD_YES == MHD_accept_connection (daemon)) &&
-		      (daemon->connections < daemon->connection_limit) &&
-		      (series_length < 128) )
-                series_length++;
-	    }
-	}
+      return MHD_NO;
     }
-
-  /* we handle resumes here because we may have ready connections
-     that will not be placed into the epoll list immediately. */
-  if ( (MHD_USE_SUSPEND_RESUME == (daemon->options & MHD_USE_SUSPEND_RESUME)) &&
-       (MHD_YES == resume_suspended_connections (daemon)) )
-    may_block = MHD_NO;
-
-  /* process events for connections */
-  while (NULL != (pos = daemon->eready_tail))
+    for (i = 0; i < (unsigned int) num_events; i++)
     {
-      EDLL_remove (daemon->eready_head,
-		   daemon->eready_tail,
-		   pos);
-      pos->epoll_state &= ~MHD_EPOLL_STATE_IN_EREADY_EDLL;
-      if (MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info)
-	pos->read_handler (pos);
-      if (MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info)
-	pos->write_handler (pos);
-      pos->idle_handler (pos);
+      /* First, check for the values of `ptr` that would indicate
+         that this event is not about a normal connection. */
+      if (NULL == events[i].data.ptr)
+        continue;     /* shutdown signal! */
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+      if (upgrade_marker == events[i].data.ptr)
+      {
+        /* activity on an upgraded connection, we process
+           those in a separate epoll() */
+        run_upgraded = true;
+        continue;
+      }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+      if (epoll_itc_marker == events[i].data.ptr)
+      {
+        /* It's OK to clear ITC here as all external
+           conditions will be processed later. */
+        MHD_itc_clear_ (daemon->itc);
+        continue;
+      }
+      if (daemon == events[i].data.ptr)
+      {
+        /* Check for error conditions on listen socket. */
+        /* FIXME: Initiate MHD_quiesce_daemon() to prevent busy waiting? */
+        if (0 == (events[i].events & (EPOLLERR | EPOLLHUP)))
+          need_to_accept = true;
+        continue;
+      }
+      /* this is an event relating to a 'normal' connection,
+         remember the event and if appropriate mark the
+         connection as 'eready'. */
+      pos = events[i].data.ptr;
+      /* normal processing: update read/write data */
+      if (0 != (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP)))
+      {
+        pos->epoll_state |= MHD_EPOLL_STATE_ERROR;
+        if (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
+        {
+          EDLL_insert (daemon->eready_head,
+                       daemon->eready_tail,
+                       pos);
+          pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+        }
+      }
+      else
+      {
+        if (0 != (events[i].events & EPOLLIN))
+        {
+          pos->epoll_state |= MHD_EPOLL_STATE_READ_READY;
+          if ( ( (0 != (MHD_EVENT_LOOP_INFO_READ & pos->event_loop_info)) ||
+                 (pos->read_buffer_size > pos->read_buffer_offset) ) &&
+               (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
+          {
+            EDLL_insert (daemon->eready_head,
+                         daemon->eready_tail,
+                         pos);
+            pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+          }
+        }
+        if (0 != (events[i].events & EPOLLOUT))
+        {
+          pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY;
+          if ( (MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) &&
+               (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
+          {
+            EDLL_insert (daemon->eready_head,
+                         daemon->eready_tail,
+                         pos);
+            pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
+          }
+        }
+      }
     }
+  }
 
-  /* Finally, handle timed-out connections; we need to do this here
-     as the epoll mechanism won't call the 'idle_handler' on everything,
+  /* Process externally added connection if any */
+  if (daemon->have_new)
+    new_connections_list_process_ (daemon);
+
+  if (need_to_accept)
+  {
+    unsigned int series_length = 0;
+
+    /* Run 'accept' until it fails or daemon at limit of connections.
+     * Do not accept more then 10 connections at once. The rest will
+     * be accepted on next turn (level trigger is used for listen
+     * socket). */
+    while ( (MHD_NO != MHD_accept_connection (daemon)) &&
+            (series_length < 10) &&
+            (daemon->connections < daemon->connection_limit) &&
+            (! daemon->at_limit) )
+      series_length++;
+  }
+
+  /* Handle timed-out connections; we need to do this here
+     as the epoll mechanism won't call the 'MHD_connection_handle_idle()' on everything,
      as the other event loops do.  As timeouts do not get an explicit
      event, we need to find those connections that might have timed out
      here.
 
      Connections with custom timeouts must all be looked at, as we
      do not bother to sort that (presumably very short) list. */
-  next = daemon->manual_timeout_head;
-  while (NULL != (pos = next))
-    {
-      next = pos->nextX;
-      pos->idle_handler (pos);
-    }
+  prev = daemon->manual_timeout_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevX;
+    MHD_connection_handle_idle (pos);
+  }
   /* Connections with the default timeout are sorted by prepending
      them to the head of the list whenever we touch the connection;
-     thus it sufficies to iterate from the tail until the first
+     thus it suffices to iterate from the tail until the first
      connection is NOT timed out */
-  next = daemon->normal_timeout_tail;
-  while (NULL != (pos = next))
+  prev = daemon->normal_timeout_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevX;
+    MHD_connection_handle_idle (pos);
+    if (MHD_CONNECTION_CLOSED != pos->state)
+      break; /* sorted by timeout, no need to visit the rest! */
+  }
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if (run_upgraded || (NULL != daemon->eready_urh_head))
+    run_epoll_for_upgrade (daemon);
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+  /* process events for connections */
+  prev = daemon->eready_tail;
+  while (NULL != (pos = prev))
+  {
+    prev = pos->prevE;
+    call_handlers (pos,
+                   0 != (pos->epoll_state & MHD_EPOLL_STATE_READ_READY),
+                   0 != (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY),
+                   0 != (pos->epoll_state & MHD_EPOLL_STATE_ERROR));
+    if (MHD_EPOLL_STATE_IN_EREADY_EDLL ==
+        (pos->epoll_state & (MHD_EPOLL_STATE_SUSPENDED
+                             | MHD_EPOLL_STATE_IN_EREADY_EDLL)))
     {
-      next = pos->prevX;
-      pos->idle_handler (pos);
-      if (MHD_CONNECTION_CLOSED != pos->state)
-	break; /* sorted by timeout, no need to visit the rest! */
+      if ( ((MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info) &&
+            (0 == (pos->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ||
+           ((MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) &&
+            (0 == (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ) ||
+           (MHD_EVENT_LOOP_INFO_CLEANUP == pos->event_loop_info) )
+      {
+        EDLL_remove (daemon->eready_head,
+                     daemon->eready_tail,
+                     pos);
+        pos->epoll_state &=
+          ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL);
+      }
     }
+  }
+
   return MHD_YES;
 }
+
+
 #endif
 
 
 /**
- * Run webserver operations (without blocking unless in client
- * callbacks).  This method should be called by clients in combination
- * with #MHD_get_fdset if the client-controlled select method is used.
+ * Run webserver operations (without blocking unless in client callbacks).
+ *
+ * This method should be called by clients in combination with
+ * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD
+ * if epoll is used) and #MHD_get_timeout() if the client-controlled
+ * connection polling method is used (i.e. daemon was started without
+ * #MHD_USE_INTERNAL_POLLING_THREAD flag).
  *
  * This function is a convenience method, which is useful if the
  * fd_sets from #MHD_get_fdset were not directly passed to `select()`;
  * with this function, MHD will internally do the appropriate `select()`
- * call itself again.  While it is always safe to call #MHD_run (in
- * external select mode), you should call #MHD_run_from_select if
- * performance is important (as it saves an expensive call to
- * `select()`).
+ * call itself again.  While it is acceptable to call #MHD_run (if
+ * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should
+ * call #MHD_run_from_select() if performance is important (as it saves an
+ * expensive call to `select()`).
+ *
+ * If #MHD_get_timeout() returned #MHD_YES, than this function must be called
+ * right after polling function returns regardless of detected activity on
+ * the daemon's FDs.
  *
  * @param daemon daemon to run
  * @return #MHD_YES on success, #MHD_NO if this
@@ -2927,65 +5509,212 @@
  *         options for this call.
  * @ingroup event
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_run (struct MHD_Daemon *daemon)
 {
-  if ( (MHD_YES == daemon->shutdown) ||
-       (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) ||
-       (0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) )
+  if ( (daemon->shutdown) ||
+       (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) )
     return MHD_NO;
-  if (0 != (daemon->options & MHD_USE_POLL))
-  {
-    MHD_poll (daemon, MHD_NO);
-    MHD_cleanup_connections (daemon);
-  }
-#if EPOLL_SUPPORT
-  else if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-  {
-    MHD_epoll (daemon, MHD_NO);
-    MHD_cleanup_connections (daemon);
-  }
-#endif
-  else
-  {
-    MHD_select (daemon, MHD_NO);
-    /* MHD_select does MHD_cleanup_connections already */
-  }
+
+  (void) MHD_run_wait (daemon, 0);
   return MHD_YES;
 }
 
 
 /**
- * Thread that runs the select loop until the daemon
- * is explicitly shut down.
+ * Run websever operation with possible blocking.
  *
- * @param cls 'struct MHD_Deamon' to run select loop in a thread for
- * @return always 0 (on shutdown)
+ * This function does the following: waits for any network event not more than
+ * specified number of milliseconds, processes all incoming and outgoing data,
+ * processes new connections, processes any timed-out connection, and does
+ * other things required to run webserver.
+ * Once all connections are processed, function returns.
+ *
+ * This function is useful for quick and simple (lazy) webserver implementation
+ * if application needs to run a single thread only and does not have any other
+ * network activity.
+ *
+ * This function calls MHD_get_timeout() internally and use returned value as
+ * maximum wait time if it less than value of @a millisec parameter.
+ *
+ * It is expected that the "external" socket polling function is not used in
+ * conjunction with this function unless the @a millisec is set to zero.
+ *
+ * @param daemon the daemon to run
+ * @param millisec the maximum time in milliseconds to wait for network and
+ *                 other events. Note: there is no guarantee that function
+ *                 blocks for the specified amount of time. The real processing
+ *                 time can be shorter (if some data or connection timeout
+ *                 comes earlier) or longer (if data processing requires more
+ *                 time, especially in user callbacks).
+ *                 If set to '0' then function does not block and processes
+ *                 only already available data (if any).
+ *                 If set to '-1' then function waits for events
+ *                 indefinitely (blocks until next network activity or
+ *                 connection timeout).
+ * @return #MHD_YES on success, #MHD_NO if this
+ *         daemon was not started with the right
+ *         options for this call or some serious
+ *         unrecoverable error occurs.
+ * @note Available since #MHD_VERSION 0x00097206
+ * @ingroup event
  */
-static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
-MHD_select_thread (void *cls)
+_MHD_EXTERN enum MHD_Result
+MHD_run_wait (struct MHD_Daemon *daemon,
+              int32_t millisec)
 {
-  struct MHD_Daemon *daemon = cls;
+  enum MHD_Result res;
+  if ( (daemon->shutdown) ||
+       (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) )
+    return MHD_NO;
 
-  while (MHD_YES != daemon->shutdown)
-    {
-      if (0 != (daemon->options & MHD_USE_POLL))
-	MHD_poll (daemon, MHD_YES);
-#if EPOLL_SUPPORT
-      else if (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY))
-	MHD_epoll (daemon, MHD_YES);
+  if (0 > millisec)
+    millisec = -1;
+#ifdef HAVE_POLL
+  if (0 != (daemon->options & MHD_USE_POLL))
+  {
+    res = MHD_poll_all (daemon, millisec);
+    MHD_cleanup_connections (daemon);
+  }
+  else
+#endif /* HAVE_POLL */
+#ifdef EPOLL_SUPPORT
+  if (0 != (daemon->options & MHD_USE_EPOLL))
+  {
+    res = MHD_epoll (daemon, millisec);
+    MHD_cleanup_connections (daemon);
+  }
+  else
 #endif
-      else
-	MHD_select (daemon, MHD_YES);
-      MHD_cleanup_connections (daemon);
-    }
-  return (MHD_THRD_RTRN_TYPE_)0;
+  if (1)
+  {
+    res = MHD_select (daemon, millisec);
+    /* MHD_select does MHD_cleanup_connections already */
+  }
+  return res;
 }
 
 
 /**
+ * Close the given connection, remove it from all of its
+ * DLLs and move it into the cleanup queue.
+ * @remark To be called only from thread that
+ * process daemon's select()/poll()/etc.
+ *
+ * @param pos connection to move to cleanup
+ */
+static void
+close_connection (struct MHD_Connection *pos)
+{
+  struct MHD_Daemon *daemon = pos->daemon;
+
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
+
+  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+  {
+    MHD_connection_mark_closed_ (pos);
+    return;   /* must let thread to do the rest */
+  }
+  MHD_connection_close_ (pos,
+                         MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+  mhd_assert (! pos->suspended);
+  mhd_assert (! pos->resuming);
+  if (pos->connection_timeout_ms == daemon->connection_timeout_ms)
+    XDLL_remove (daemon->normal_timeout_head,
+                 daemon->normal_timeout_tail,
+                 pos);
+  else
+    XDLL_remove (daemon->manual_timeout_head,
+                 daemon->manual_timeout_tail,
+                 pos);
+  DLL_remove (daemon->connections_head,
+              daemon->connections_tail,
+              pos);
+  DLL_insert (daemon->cleanup_head,
+              daemon->cleanup_tail,
+              pos);
+  daemon->data_already_pending = true;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+}
+
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+/**
+ * Thread that runs the polling loop until the daemon
+ * is explicitly shut down.
+ *
+ * @param cls `struct MHD_Deamon` to run select loop in a thread for
+ * @return always 0 (on shutdown)
+ */
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+MHD_polling_thread (void *cls)
+{
+  struct MHD_Daemon *daemon = cls;
+#ifdef HAVE_PTHREAD_SIGMASK
+  sigset_t s_mask;
+  int err;
+#endif /* HAVE_PTHREAD_SIGMASK */
+
+  MHD_thread_init_ (&(daemon->pid));
+#ifdef HAVE_PTHREAD_SIGMASK
+  if ((0 == sigemptyset (&s_mask)) &&
+      (0 == sigaddset (&s_mask, SIGPIPE)))
+  {
+    err = pthread_sigmask (SIG_BLOCK, &s_mask, NULL);
+  }
+  else
+    err = errno;
+  if (0 == err)
+    daemon->sigpipe_blocked = true;
+#ifdef HAVE_MESSAGES
+  else
+    MHD_DLOG (daemon,
+              _ ("Failed to block SIGPIPE on daemon thread: %s\n"),
+              MHD_strerror_ (errno));
+#endif /* HAVE_MESSAGES */
+#endif /* HAVE_PTHREAD_SIGMASK */
+  while (! daemon->shutdown)
+  {
+#ifdef HAVE_POLL
+    if (0 != (daemon->options & MHD_USE_POLL))
+      MHD_poll (daemon, MHD_YES);
+    else
+#endif /* HAVE_POLL */
+#ifdef EPOLL_SUPPORT
+    if (0 != (daemon->options & MHD_USE_EPOLL))
+      MHD_epoll (daemon, -1);
+    else
+#endif
+    MHD_select (daemon, -1);
+    MHD_cleanup_connections (daemon);
+  }
+
+  /* Resume any pending for resume connections, join
+   * all connection's threads (if any) and finally cleanup
+   * everything. */
+  if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options))
+    resume_suspended_connections (daemon);
+  close_all_connections (daemon);
+
+  return (MHD_THRD_RTRN_TYPE_) 0;
+}
+
+
+#endif
+
+
+/**
  * Process escape sequences ('%HH') Updates val in place; the
- * result should be UTF-8 encoded and cannot be larger than the input.
+ * result cannot be larger than the input.
  * The result must also still be 0-terminated.
  *
  * @param cls closure (use NULL)
@@ -2999,7 +5728,23 @@
                   struct MHD_Connection *connection,
                   char *val)
 {
-  return MHD_http_unescape (val);
+  bool broken;
+  size_t res;
+  (void) cls; /* Mute compiler warning. */
+
+  /* TODO: add individual parameter */
+  if (0 <= connection->daemon->client_discipline)
+    return MHD_str_pct_decode_in_place_strict_ (val);
+
+  res = MHD_str_pct_decode_in_place_lenient_ (val, &broken);
+#ifdef HAVE_MESSAGES
+  if (broken)
+  {
+    MHD_DLOG (connection->daemon,
+              _ ("The URL encoding is broken.\n"));
+  }
+#endif /* HAVE_MESSAGES */
+  return res;
 }
 
 
@@ -3008,7 +5753,11 @@
  * #MHD_start_daemon_va.
  *
  * @param flags combination of `enum MHD_FLAG` values
- * @param port port to bind to
+ * @param port port to bind to (in host byte order),
+ *        use '0' to bind to random free port,
+ *        ignored if #MHD_OPTION_SOCK_ADDR or
+ *        #MHD_OPTION_LISTEN_SOCKET is provided
+ *        or #MHD_USE_NO_LISTEN_SOCKET is specified
  * @param apc callback to call to check which clients
  *        will be allowed to connect; you can pass NULL
  *        in which case connections from any IP will be
@@ -3019,18 +5768,27 @@
  * @return NULL on error, handle to daemon on success
  * @ingroup event
  */
-struct MHD_Daemon *
+_MHD_EXTERN struct MHD_Daemon *
 MHD_start_daemon (unsigned int flags,
                   uint16_t port,
                   MHD_AcceptPolicyCallback apc,
                   void *apc_cls,
-                  MHD_AccessHandlerCallback dh, void *dh_cls, ...)
+                  MHD_AccessHandlerCallback dh,
+                  void *dh_cls,
+                  ...)
 {
   struct MHD_Daemon *daemon;
   va_list ap;
 
-  va_start (ap, dh_cls);
-  daemon = MHD_start_daemon_va (flags, port, apc, apc_cls, dh, dh_cls, ap);
+  va_start (ap,
+            dh_cls);
+  daemon = MHD_start_daemon_va (flags,
+                                port,
+                                apc,
+                                apc_cls,
+                                dh,
+                                dh_cls,
+                                ap);
   va_end (ap);
   return daemon;
 }
@@ -3041,12 +5799,12 @@
  * clients to continue processing, but stops accepting new
  * connections.  Note that the caller is responsible for closing the
  * returned socket; however, if MHD is run using threads (anything but
- * external select mode), it must not be closed until AFTER
- * #MHD_stop_daemon has been called (as it is theoretically possible
- * that an existing thread is still using it).
+ * external select mode), socket will be removed from existing threads
+ * with some delay and it must not be closed while it's in use. To make
+ * sure that the socket is not used anymore, call #MHD_stop_daemon.
  *
  * Note that some thread modes require the caller to have passed
- * #MHD_USE_PIPE_FOR_SHUTDOWN when using this API.  If this daemon is
+ * #MHD_USE_ITC when using this API.  If this daemon is
  * in one of those modes and this option was not given to
  * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET.
  *
@@ -3055,57 +5813,75 @@
  *         the daemon was already not listening anymore
  * @ingroup specialized
  */
-MHD_socket
+_MHD_EXTERN MHD_socket
 MHD_quiesce_daemon (struct MHD_Daemon *daemon)
 {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   unsigned int i;
+#endif
   MHD_socket ret;
 
-  ret = daemon->socket_fd;
+  ret = daemon->listen_fd;
   if (MHD_INVALID_SOCKET == ret)
     return MHD_INVALID_SOCKET;
-  if ( (MHD_INVALID_PIPE_ == daemon->wpipe[1]) &&
-       (0 != (daemon->options & (MHD_USE_SELECT_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION))) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Using MHD_quiesce_daemon in this mode requires MHD_USE_PIPE_FOR_SHUTDOWN\n");
+  if ( (0 == (daemon->options & (MHD_USE_ITC))) &&
+       (0 != (daemon->options & (MHD_USE_INTERNAL_POLLING_THREAD))) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Using MHD_quiesce_daemon in this mode " \
+                 "requires MHD_USE_ITC.\n"));
 #endif
-      return MHD_INVALID_SOCKET;
-    }
+    return MHD_INVALID_SOCKET;
+  }
 
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   if (NULL != daemon->worker_pool)
     for (i = 0; i < daemon->worker_pool_size; i++)
-      {
-	daemon->worker_pool[i].socket_fd = MHD_INVALID_SOCKET;
-#if EPOLL_SUPPORT
-	if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-	     (-1 != daemon->worker_pool[i].epoll_fd) &&
-	     (MHD_YES == daemon->worker_pool[i].listen_socket_in_epoll) )
-	  {
-	    if (0 != epoll_ctl (daemon->worker_pool[i].epoll_fd,
-				EPOLL_CTL_DEL,
-				ret,
-				NULL))
-	      MHD_PANIC ("Failed to remove listen FD from epoll set\n");
-	    daemon->worker_pool[i].listen_socket_in_epoll = MHD_NO;
-	  }
-#endif
-      }
-  daemon->socket_fd = MHD_INVALID_SOCKET;
-#if EPOLL_SUPPORT
-  if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-       (-1 != daemon->epoll_fd) &&
-       (MHD_YES == daemon->listen_socket_in_epoll) )
     {
-      if (0 != epoll_ctl (daemon->epoll_fd,
-			  EPOLL_CTL_DEL,
-			  ret,
-			  NULL))
-	MHD_PANIC ("Failed to remove listen FD from epoll set\n");
-      daemon->listen_socket_in_epoll = MHD_NO;
+      daemon->worker_pool[i].was_quiesced = true;
+#ifdef EPOLL_SUPPORT
+      if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+           (-1 != daemon->worker_pool[i].epoll_fd) &&
+           (daemon->worker_pool[i].listen_socket_in_epoll) )
+      {
+        if (0 != epoll_ctl (daemon->worker_pool[i].epoll_fd,
+                            EPOLL_CTL_DEL,
+                            ret,
+                            NULL))
+          MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n"));
+        daemon->worker_pool[i].listen_socket_in_epoll = false;
+      }
+      else
+#endif
+      if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc))
+      {
+        if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "q"))
+          MHD_PANIC (_ ("Failed to signal quiesce via inter-thread " \
+                        "communication channel.\n"));
+      }
     }
 #endif
+  daemon->was_quiesced = true;
+#ifdef EPOLL_SUPPORT
+  if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+       (-1 != daemon->epoll_fd) &&
+       (daemon->listen_socket_in_epoll) )
+  {
+    if ( (0 != epoll_ctl (daemon->epoll_fd,
+                          EPOLL_CTL_DEL,
+                          ret,
+                          NULL)) &&
+         (ENOENT != errno) )   /* ENOENT can happen due to race with
+                                  #MHD_epoll() */
+      MHD_PANIC ("Failed to remove listen FD from epoll set.\n");
+    daemon->listen_socket_in_epoll = false;
+  }
+#endif
+  if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+       (! MHD_itc_activate_ (daemon->itc, "q")) )
+    MHD_PANIC (_ ("failed to signal quiesce via inter-thread " \
+                  "communication channel.\n"));
   return ret;
 }
 
@@ -3117,9 +5893,10 @@
  * @param format format string
  * @param va arguments to the format string (fprintf-style)
  */
-typedef void (*VfprintfFunctionPointerType)(void *cls,
-					    const char *format,
-					    va_list va);
+typedef void
+(*VfprintfFunctionPointerType)(void *cls,
+                               const char *format,
+                               va_list va);
 
 
 /**
@@ -3130,10 +5907,10 @@
  * @param ap the options
  * @return #MHD_YES on success, #MHD_NO on error
  */
-static int
+static enum MHD_Result
 parse_options_va (struct MHD_Daemon *daemon,
-		  const struct sockaddr **servaddr,
-		  va_list ap);
+                  const struct sockaddr **servaddr,
+                  va_list ap);
 
 
 /**
@@ -3144,21 +5921,286 @@
  * @param ... the options
  * @return #MHD_YES on success, #MHD_NO on error
  */
-static int
+static enum MHD_Result
 parse_options (struct MHD_Daemon *daemon,
-	       const struct sockaddr **servaddr,
-	       ...)
+               const struct sockaddr **servaddr,
+               ...)
 {
   va_list ap;
-  int ret;
+  enum MHD_Result ret;
 
   va_start (ap, servaddr);
-  ret = parse_options_va (daemon, servaddr, ap);
+  ret = parse_options_va (daemon,
+                          servaddr,
+                          ap);
   va_end (ap);
   return ret;
 }
 
 
+#ifdef HTTPS_SUPPORT
+/**
+ * Type of GnuTLS priorities base string
+ */
+enum MHD_TlsPrioritiesBaseType
+{
+  MHD_TLS_PRIO_BASE_LIBMHD = 0, /**< @c "@LIBMICROHTTPD" */
+  MHD_TLS_PRIO_BASE_SYSTEM = 1, /**< @c "@SYSTEM" */
+#if GNUTLS_VERSION_NUMBER >= 0x030300
+  MHD_TLS_PRIO_BASE_DEFAULT,    /**< Default priorities string */
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
+  MHD_TLS_PRIO_BASE_NORMAL      /**< @c "NORMAL */
+};
+
+static const struct _MHD_cstr_w_len MHD_TlsBasePriotities[] = {
+  _MHD_S_STR_W_LEN ("@LIBMICROHTTPD"),
+  _MHD_S_STR_W_LEN ("@SYSTEM"),
+#if GNUTLS_VERSION_NUMBER >= 0x030300
+  {NULL, 0},
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
+  _MHD_S_STR_W_LEN ("NORMAL")
+};
+
+/**
+ * Initialise TLS priorities with default settings
+ * @param daemon the daemon to initialise TLS priorities
+ * @return true on success, false on error
+ */
+static bool
+daemon_tls_priorities_init_default (struct MHD_Daemon *daemon)
+{
+  unsigned int p;
+  int res;
+
+  mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS));
+  mhd_assert (NULL == daemon->priority_cache);
+  mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \
+              sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]));
+
+  for (p = 0;
+       p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]);
+       ++p)
+  {
+    res = gnutls_priority_init (&daemon->priority_cache,
+                                MHD_TlsBasePriotities[p].str, NULL);
+    if (GNUTLS_E_SUCCESS == res)
+    {
+#ifdef _DEBUG
+#ifdef HAVE_MESSAGES
+      switch ((enum MHD_TlsPrioritiesBaseType) p)
+      {
+      case MHD_TLS_PRIO_BASE_LIBMHD:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "@LIBMICROHTTPD application-specific system-wide " \
+                     "configuration.\n") );
+        break;
+      case MHD_TLS_PRIO_BASE_SYSTEM:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "@SYSTEM system-wide configuration.\n") );
+        break;
+#if GNUTLS_VERSION_NUMBER >= 0x030300
+      case MHD_TLS_PRIO_BASE_DEFAULT:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "GnuTLS default configuration.\n") );
+        break;
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
+      case MHD_TLS_PRIO_BASE_NORMAL:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "NORMAL configuration.\n") );
+        break;
+      default:
+        mhd_assert (0);
+      }
+#endif /* HAVE_MESSAGES */
+#endif /* _DEBUG */
+      return true;
+    }
+  }
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (daemon,
+            _ ("Failed to set GnuTLS priorities. Last error: %s\n"),
+            gnutls_strerror (res));
+#endif /* HAVE_MESSAGES */
+  return false;
+}
+
+
+/**
+ * The inner helper function for #daemon_tls_priorities_init_app().
+ * @param daemon the daemon to use
+ * @param prio   the appication-specified appendix for default priorities
+ * @param prio_len the length of @a prio
+ * @param buf    the temporal buffer for string manipulations
+ * @param buf_size the size of the @a buf
+ * @return true on success, false on error
+ */
+static bool
+daemon_tls_priorities_init_append_inner_ (struct MHD_Daemon *daemon,
+                                          const char *prio,
+                                          size_t prio_len,
+                                          char *buf,
+                                          const size_t buf_size)
+{
+  unsigned int p;
+  int res;
+  const char *err_pos;
+
+  (void) buf_size; /* Mute compiler warning for non-Debug builds */
+  mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS));
+  mhd_assert (NULL == daemon->priority_cache);
+  mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \
+              sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]));
+
+  for (p = 0;
+       p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]);
+       ++p)
+  {
+
+#if GNUTLS_VERSION_NUMBER >= 0x030300
+#if GNUTLS_VERSION_NUMBER >= 0x030603
+    if (NULL == MHD_TlsBasePriotities[p].str)
+      res = gnutls_priority_init2 (&daemon->priority_cache, prio, &err_pos,
+                                   GNUTLS_PRIORITY_INIT_DEF_APPEND);
+    else
+#else  \
+    /* 0x030300 <= GNUTLS_VERSION_NUMBER && GNUTLS_VERSION_NUMBER < 0x030603 */
+    if (NULL == MHD_TlsBasePriotities[p].str)
+      continue; /* Skip the value, no way to append priorities to the default string */
+    else
+#endif /* GNUTLS_VERSION_NUMBER < 0x030603 */
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
+    if (1)
+    {
+      size_t buf_pos;
+
+      mhd_assert (NULL != MHD_TlsBasePriotities[p].str);
+      buf_pos = 0;
+      memcpy (buf + buf_pos, MHD_TlsBasePriotities[p].str,
+              MHD_TlsBasePriotities[p].len);
+      buf_pos += MHD_TlsBasePriotities[p].len;
+      buf[buf_pos++] = ':';
+      memcpy (buf + buf_pos, prio, prio_len + 1);
+#ifdef _DEBUG
+      buf_pos += prio_len + 1;
+      mhd_assert (buf_size >= buf_pos);
+#endif /* _DEBUG */
+      res = gnutls_priority_init (&daemon->priority_cache, buf, &err_pos);
+    }
+    if (GNUTLS_E_SUCCESS == res)
+    {
+#ifdef _DEBUG
+#ifdef HAVE_MESSAGES
+      switch ((enum MHD_TlsPrioritiesBaseType) p)
+      {
+      case MHD_TLS_PRIO_BASE_LIBMHD:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "priorities specified by application appended to " \
+                     "@LIBMICROHTTPD application-specific system-wide " \
+                     "configuration.\n") );
+        break;
+      case MHD_TLS_PRIO_BASE_SYSTEM:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "priorities specified by application appended to " \
+                     "@SYSTEM system-wide configuration.\n") );
+        break;
+#if GNUTLS_VERSION_NUMBER >= 0x030300
+      case MHD_TLS_PRIO_BASE_DEFAULT:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "priorities specified by application appended to " \
+                     "GnuTLS default configuration.\n") );
+        break;
+#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
+      case MHD_TLS_PRIO_BASE_NORMAL:
+        MHD_DLOG (daemon,
+                  _ ("GnuTLS priorities have been initialised with " \
+                     "priorities specified by application appended to " \
+                     "NORMAL configuration.\n") );
+        break;
+      default:
+        mhd_assert (0);
+      }
+#endif /* HAVE_MESSAGES */
+#endif /* _DEBUG */
+      return true;
+    }
+  }
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (daemon,
+            _ ("Failed to set GnuTLS priorities. Last error: %s. " \
+               "The problematic part starts at: %s\n"),
+            gnutls_strerror (res), err_pos);
+#endif /* HAVE_MESSAGES */
+  return false;
+}
+
+
+#define LOCAL_BUFF_SIZE 128
+
+/**
+ * Initialise TLS priorities with default settings with application-specified
+ * appended string.
+ * @param daemon the daemon to initialise TLS priorities
+ * @param prio the application specified priorities to be appended to
+ *             the GnuTLS standard priorities string
+ * @return true on success, false on error
+ */
+static bool
+daemon_tls_priorities_init_append (struct MHD_Daemon *daemon, const char *prio)
+{
+  static const size_t longest_base_prio = MHD_STATICSTR_LEN_ ("@LIBMICROHTTPD");
+  bool ret;
+  size_t prio_len;
+  size_t buf_size_needed;
+
+  if (NULL == prio)
+    return daemon_tls_priorities_init_default (daemon);
+
+  if (':' == prio[0])
+    ++prio;
+
+  prio_len = strlen (prio);
+
+  buf_size_needed = longest_base_prio + 1 + prio_len + 1;
+
+  if (LOCAL_BUFF_SIZE >= buf_size_needed)
+  {
+    char local_buffer[LOCAL_BUFF_SIZE];
+    ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len,
+                                                    local_buffer,
+                                                    LOCAL_BUFF_SIZE);
+  }
+  else
+  {
+    char *allocated_buffer;
+    allocated_buffer = (char *) malloc (buf_size_needed);
+    if (NULL == allocated_buffer)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Error allocating memory: %s\n"),
+                MHD_strerror_ (errno));
+#endif
+      return false;
+    }
+    ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len,
+                                                    allocated_buffer,
+                                                    buf_size_needed);
+    free (allocated_buffer);
+  }
+  return ret;
+}
+
+
+#endif /* HTTPS_SUPPORT */
+
+
 /**
  * Parse a list of options given as varargs.
  *
@@ -3167,438 +6209,806 @@
  * @param ap the options
  * @return #MHD_YES on success, #MHD_NO on error
  */
-static int
+static enum MHD_Result
 parse_options_va (struct MHD_Daemon *daemon,
-		  const struct sockaddr **servaddr,
-		  va_list ap)
+                  const struct sockaddr **servaddr,
+                  va_list ap)
 {
   enum MHD_OPTION opt;
   struct MHD_OptionItem *oa;
   unsigned int i;
-#if HTTPS_SUPPORT
-  int ret;
+  unsigned int uv;
+#ifdef HTTPS_SUPPORT
   const char *pstr;
+#if GNUTLS_VERSION_MAJOR >= 3
+  gnutls_certificate_retrieve_function2 *pgcrf;
 #endif
+#if GNUTLS_VERSION_NUMBER >= 0x030603
+  gnutls_certificate_retrieve_function3 *pgcrf2;
+#endif
+#endif /* HTTPS_SUPPORT */
 
   while (MHD_OPTION_END != (opt = (enum MHD_OPTION) va_arg (ap, int)))
+  {
+    /* Increase counter at start, so resulting value is number of
+     * processed options, including any failed ones. */
+    daemon->num_opts++;
+    switch (opt)
     {
-      switch (opt)
+    case MHD_OPTION_CONNECTION_MEMORY_LIMIT:
+      daemon->pool_size = va_arg (ap,
+                                  size_t);
+      break;
+    case MHD_OPTION_CONNECTION_MEMORY_INCREMENT:
+      daemon->pool_increment = va_arg (ap,
+                                       size_t);
+      break;
+    case MHD_OPTION_CONNECTION_LIMIT:
+      daemon->connection_limit = va_arg (ap,
+                                         unsigned int);
+      break;
+    case MHD_OPTION_CONNECTION_TIMEOUT:
+      uv = va_arg (ap,
+                   unsigned int);
+#if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT
+      if ((UINT64_MAX / 4000 - 1) < uv)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("The specified connection timeout (%u) is too large. " \
+                     "Maximum allowed value (%" PRIu64 ") will be used " \
+                     "instead.\n"),
+                  uv,
+                  (UINT64_MAX / 4000 - 1));
+#endif
+        uv = UINT64_MAX / 4000 - 1;
+      }
+#endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */
+      daemon->connection_timeout_ms = uv * 1000;
+      break;
+    case MHD_OPTION_NOTIFY_COMPLETED:
+      daemon->notify_completed = va_arg (ap,
+                                         MHD_RequestCompletedCallback);
+      daemon->notify_completed_cls = va_arg (ap,
+                                             void *);
+      break;
+    case MHD_OPTION_NOTIFY_CONNECTION:
+      daemon->notify_connection = va_arg (ap,
+                                          MHD_NotifyConnectionCallback);
+      daemon->notify_connection_cls = va_arg (ap,
+                                              void *);
+      break;
+    case MHD_OPTION_PER_IP_CONNECTION_LIMIT:
+      daemon->per_ip_connection_limit = va_arg (ap,
+                                                unsigned int);
+      break;
+    case MHD_OPTION_SOCK_ADDR:
+      *servaddr = va_arg (ap,
+                          const struct sockaddr *);
+      break;
+    case MHD_OPTION_URI_LOG_CALLBACK:
+      daemon->uri_log_callback = va_arg (ap,
+                                         LogCallback);
+      daemon->uri_log_callback_cls = va_arg (ap,
+                                             void *);
+      break;
+    case MHD_OPTION_SERVER_INSANITY:
+      daemon->insanity_level = (enum MHD_DisableSanityCheck)
+                               va_arg (ap,
+                                       unsigned int);
+      break;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    case MHD_OPTION_THREAD_POOL_SIZE:
+      daemon->worker_pool_size = va_arg (ap,
+                                         unsigned int);
+      if (0 == daemon->worker_pool_size)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Warning: Zero size, specified for thread pool size," \
+                     " is ignored. Thread pool is not used.\n"));
+#endif
+      }
+      else if (1 == daemon->worker_pool_size)
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Warning: \"1\", specified for thread pool size, " \
+                     "is ignored. Thread pool is not used.\n"));
+#endif
+        daemon->worker_pool_size = 0;
+      }
+#if SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2)
+      /* Next comparison could be always false on some platforms and whole branch will
+       * be optimized out on these platforms. On others it will be compiled into real
+       * check. */
+      else if (daemon->worker_pool_size >=
+               (SIZE_MAX / sizeof (struct MHD_Daemon)))            /* Compiler may warn on some platforms, ignore warning. */
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Specified thread pool size (%u) too big.\n"),
+                  daemon->worker_pool_size);
+#endif
+        return MHD_NO;
+      }
+#endif /* SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) */
+      else
+      {
+        if (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD))
         {
-        case MHD_OPTION_CONNECTION_MEMORY_LIMIT:
-          daemon->pool_size = va_arg (ap, size_t);
-          break;
-        case MHD_OPTION_CONNECTION_MEMORY_INCREMENT:
-          daemon->pool_increment= va_arg (ap, size_t);
-          break;
-        case MHD_OPTION_CONNECTION_LIMIT:
-          daemon->connection_limit = va_arg (ap, unsigned int);
-          break;
-        case MHD_OPTION_CONNECTION_TIMEOUT:
-          daemon->connection_timeout = va_arg (ap, unsigned int);
-          break;
-        case MHD_OPTION_NOTIFY_COMPLETED:
-          daemon->notify_completed =
-            va_arg (ap, MHD_RequestCompletedCallback);
-          daemon->notify_completed_cls = va_arg (ap, void *);
-          break;
-        case MHD_OPTION_NOTIFY_CONNECTION:
-          daemon->notify_connection =
-            va_arg (ap, MHD_NotifyConnectionCallback);
-          daemon->notify_connection_cls = va_arg (ap, void *);
-          break;
-        case MHD_OPTION_PER_IP_CONNECTION_LIMIT:
-          daemon->per_ip_connection_limit = va_arg (ap, unsigned int);
-          break;
-        case MHD_OPTION_SOCK_ADDR:
-          *servaddr = va_arg (ap, const struct sockaddr *);
-          break;
-        case MHD_OPTION_URI_LOG_CALLBACK:
-          daemon->uri_log_callback =
-            va_arg (ap, LogCallback);
-          daemon->uri_log_callback_cls = va_arg (ap, void *);
-          break;
-        case MHD_OPTION_THREAD_POOL_SIZE:
-          daemon->worker_pool_size = va_arg (ap, unsigned int);
-	  if (daemon->worker_pool_size >= (SIZE_MAX / sizeof (struct MHD_Daemon)))
-	    {
-#if HAVE_MESSAGES
-	      MHD_DLOG (daemon,
-			"Specified thread pool size (%u) too big\n",
-			daemon->worker_pool_size);
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("MHD_OPTION_THREAD_POOL_SIZE option is specified but "
+                       "MHD_USE_INTERNAL_POLLING_THREAD flag is not specified.\n"));
 #endif
-	      return MHD_NO;
-	    }
-          break;
-#if HTTPS_SUPPORT
-        case MHD_OPTION_HTTPS_MEM_KEY:
-	  if (0 != (daemon->options & MHD_USE_SSL))
-	    {
-	      daemon->https_mem_key = va_arg (ap, const char *);
-	    }
-	  else
-	    {
-#if HAVE_MESSAGES
-	    MHD_DLOG (daemon,
-		      "MHD HTTPS option %d passed to MHD but MHD_USE_SSL not set\n",
-		      opt);
-#endif
-	    }
-          break;
-        case MHD_OPTION_HTTPS_KEY_PASSWORD:
-	  if (0 != (daemon->options & MHD_USE_SSL))
-	    {
-	      daemon->https_key_password = va_arg (ap, const char *);
-	    }
-	  else
-	    {
-#if HAVE_MESSAGES
-	    MHD_DLOG (daemon,
-		      "MHD HTTPS option %d passed to MHD but MHD_USE_SSL not set\n",
-		      opt);
-#endif
-	    }
-          break;
-        case MHD_OPTION_HTTPS_MEM_CERT:
-	  if (0 != (daemon->options & MHD_USE_SSL))
-	    {
-	      daemon->https_mem_cert = va_arg (ap, const char *);
-	    }
-	  else
-	    {
-#if HAVE_MESSAGES
-	    MHD_DLOG (daemon,
-		      "MHD HTTPS option %d passed to MHD but MHD_USE_SSL not set\n",
-		      opt);
-#endif
-	    }
-          break;
-        case MHD_OPTION_HTTPS_MEM_TRUST:
-	  if (0 != (daemon->options & MHD_USE_SSL))
-	    {
-	      daemon->https_mem_trust = va_arg (ap, const char *);
-	    }
-	  else
-	    {
-#if HAVE_MESSAGES
-	    MHD_DLOG (daemon,
-		      "MHD HTTPS option %d passed to MHD but MHD_USE_SSL not set\n",
-		      opt);
-#endif
-	    }
-          break;
-	case MHD_OPTION_HTTPS_CRED_TYPE:
-	  break;
-        case MHD_OPTION_HTTPS_MEM_DHPARAMS:
-	  if (0 != (daemon->options & MHD_USE_SSL))
-	    {
-	      daemon->https_mem_dhparams = va_arg (ap, const char *);
-	    }
-	  else
-	    {
-#if HAVE_MESSAGES
-	    MHD_DLOG (daemon,
-		      "MHD HTTPS option %d passed to MHD but MHD_USE_SSL not set\n",
-		      opt);
-#endif
-	    }
-          break;
-        case MHD_OPTION_HTTPS_PRIORITIES:
-	  if (0 != (daemon->options & MHD_USE_SSL))
-	    {
-	      daemon->https_mem_cipher = va_arg (ap, const char *);
-	    }
-	  else
-	    {
-#if HAVE_MESSAGES
-	      MHD_DLOG (daemon,
-			"MHD HTTPS option %d passed to MHD but MHD_USE_SSL not set\n",
-			opt);
-#endif
-	    }
-          break;
-        case MHD_OPTION_HTTPS_CERT_CALLBACK:
-          break;
-#endif
-#ifdef DAUTH_SUPPORT
-	case MHD_OPTION_DIGEST_AUTH_RANDOM:
-	  daemon->digest_auth_rand_size = va_arg (ap, size_t);
-	  daemon->digest_auth_random = va_arg (ap, const char *);
-	  break;
-	case MHD_OPTION_NONCE_NC_SIZE:
-	  daemon->nonce_nc_size = va_arg (ap, unsigned int);
-	  break;
-#endif
-	case MHD_OPTION_LISTEN_SOCKET:
-	  daemon->socket_fd = va_arg (ap, MHD_socket);
-	  break;
-        case MHD_OPTION_EXTERNAL_LOGGER:
-#if HAVE_MESSAGES
-          daemon->custom_error_log =
-            va_arg (ap, VfprintfFunctionPointerType);
-          daemon->custom_error_log_cls = va_arg (ap, void *);
-#else
-          va_arg (ap, VfprintfFunctionPointerType);
-          va_arg (ap, void *);
-#endif
-          break;
-        case MHD_OPTION_THREAD_STACK_SIZE:
-          daemon->thread_stack_size = va_arg (ap, size_t);
-          break;
-#ifdef TCP_FASTOPEN
-        case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE:
-          daemon->fastopen_queue_size = va_arg (ap, unsigned int);
-          break;
-#endif
-	case MHD_OPTION_LISTENING_ADDRESS_REUSE:
-	  daemon->listening_address_reuse = va_arg (ap, unsigned int) ? 1 : -1;
-	  break;
-	case MHD_OPTION_ARRAY:
-	  oa = va_arg (ap, struct MHD_OptionItem*);
-	  i = 0;
-	  while (MHD_OPTION_END != (opt = oa[i].option))
-	    {
-	      switch (opt)
-		{
-		  /* all options taking 'size_t' */
-		case MHD_OPTION_CONNECTION_MEMORY_LIMIT:
-		case MHD_OPTION_CONNECTION_MEMORY_INCREMENT:
-		case MHD_OPTION_THREAD_STACK_SIZE:
-		  if (MHD_YES != parse_options (daemon,
-						servaddr,
-						opt,
-						(size_t) oa[i].value,
-						MHD_OPTION_END))
-		    return MHD_NO;
-		  break;
-		  /* all options taking 'unsigned int' */
-		case MHD_OPTION_NONCE_NC_SIZE:
-		case MHD_OPTION_CONNECTION_LIMIT:
-		case MHD_OPTION_CONNECTION_TIMEOUT:
-		case MHD_OPTION_PER_IP_CONNECTION_LIMIT:
-		case MHD_OPTION_THREAD_POOL_SIZE:
-                case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE:
-		case MHD_OPTION_LISTENING_ADDRESS_REUSE:
-		  if (MHD_YES != parse_options (daemon,
-						servaddr,
-						opt,
-						(unsigned int) oa[i].value,
-						MHD_OPTION_END))
-		    return MHD_NO;
-		  break;
-		  /* all options taking 'enum' */
-		case MHD_OPTION_HTTPS_CRED_TYPE:
-		  if (MHD_YES != parse_options (daemon,
-						servaddr,
-						opt,
-						(int) oa[i].value,
-						MHD_OPTION_END))
-		    return MHD_NO;
-		  break;
-                  /* all options taking 'MHD_socket' */
-                case MHD_OPTION_LISTEN_SOCKET:
-                  if (MHD_YES != parse_options (daemon,
-                                                servaddr,
-                                                opt,
-                                                (MHD_socket) oa[i].value,
-                                                MHD_OPTION_END))
-                    return MHD_NO;
-                  break;
-		  /* all options taking one pointer */
-		case MHD_OPTION_SOCK_ADDR:
-		case MHD_OPTION_HTTPS_MEM_KEY:
-		case MHD_OPTION_HTTPS_KEY_PASSWORD:
-		case MHD_OPTION_HTTPS_MEM_CERT:
-		case MHD_OPTION_HTTPS_MEM_TRUST:
-	        case MHD_OPTION_HTTPS_MEM_DHPARAMS:
-		case MHD_OPTION_HTTPS_PRIORITIES:
-		case MHD_OPTION_ARRAY:
-                case MHD_OPTION_HTTPS_CERT_CALLBACK:
-		  if (MHD_YES != parse_options (daemon,
-						servaddr,
-						opt,
-						oa[i].ptr_value,
-						MHD_OPTION_END))
-		    return MHD_NO;
-		  break;
-		  /* all options taking two pointers */
-		case MHD_OPTION_NOTIFY_COMPLETED:
-		case MHD_OPTION_NOTIFY_CONNECTION:
-		case MHD_OPTION_URI_LOG_CALLBACK:
-		case MHD_OPTION_EXTERNAL_LOGGER:
-		case MHD_OPTION_UNESCAPE_CALLBACK:
-		  if (MHD_YES != parse_options (daemon,
-						servaddr,
-						opt,
-						(void *) oa[i].value,
-						oa[i].ptr_value,
-						MHD_OPTION_END))
-		    return MHD_NO;
-		  break;
-		  /* options taking size_t-number followed by pointer */
-		case MHD_OPTION_DIGEST_AUTH_RANDOM:
-		  if (MHD_YES != parse_options (daemon,
-						servaddr,
-						opt,
-						(size_t) oa[i].value,
-						oa[i].ptr_value,
-						MHD_OPTION_END))
-		    return MHD_NO;
-		  break;
-		default:
-		  return MHD_NO;
-		}
-	      i++;
-	    }
-	  break;
-        case MHD_OPTION_UNESCAPE_CALLBACK:
-          daemon->unescape_callback =
-            va_arg (ap, UnescapeCallback);
-          daemon->unescape_callback_cls = va_arg (ap, void *);
-          break;
-        default:
-#if HAVE_MESSAGES
-          if (((opt >= MHD_OPTION_HTTPS_MEM_KEY) &&
-              (opt <= MHD_OPTION_HTTPS_PRIORITIES)) || (opt == MHD_OPTION_HTTPS_MEM_TRUST))
-            {
-              MHD_DLOG (daemon,
-			"MHD HTTPS option %d passed to MHD compiled without HTTPS support\n",
-			opt);
-            }
-          else
-            {
-              MHD_DLOG (daemon,
-			"Invalid option %d! (Did you terminate the list with MHD_OPTION_END?)\n",
-			opt);
-            }
-#endif
-	  return MHD_NO;
+          return MHD_NO;
         }
+        if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+        {
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Both MHD_OPTION_THREAD_POOL_SIZE option and "
+                       "MHD_USE_THREAD_PER_CONNECTION flag are specified.\n"));
+#endif
+          return MHD_NO;
+        }
+      }
+      break;
+#endif
+#ifdef HTTPS_SUPPORT
+    case MHD_OPTION_HTTPS_MEM_KEY:
+      pstr = va_arg (ap,
+                     const char *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+        daemon->https_mem_key = pstr;
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif
+      break;
+    case MHD_OPTION_HTTPS_KEY_PASSWORD:
+      pstr = va_arg (ap,
+                     const char *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+        daemon->https_key_password = pstr;
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif
+      break;
+    case MHD_OPTION_HTTPS_MEM_CERT:
+      pstr = va_arg (ap,
+                     const char *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+        daemon->https_mem_cert = pstr;
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif
+      break;
+    case MHD_OPTION_HTTPS_MEM_TRUST:
+      pstr = va_arg (ap,
+                     const char *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+        daemon->https_mem_trust = pstr;
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif
+      break;
+    case MHD_OPTION_HTTPS_CRED_TYPE:
+      daemon->cred_type = (gnutls_credentials_type_t) va_arg (ap,
+                                                              int);
+      break;
+    case MHD_OPTION_HTTPS_MEM_DHPARAMS:
+      pstr = va_arg (ap,
+                     const char *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+      {
+        gnutls_datum_t dhpar;
+        size_t pstr_len;
+
+        if (gnutls_dh_params_init (&daemon->https_mem_dhparams) < 0)
+        {
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Error initializing DH parameters.\n"));
+#endif
+          return MHD_NO;
+        }
+        dhpar.data = (unsigned char *) _MHD_DROP_CONST (pstr);
+        pstr_len = strlen (pstr);
+        if (UINT_MAX < pstr_len)
+        {
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Diffie-Hellman parameters string too long.\n"));
+#endif
+          return MHD_NO;
+        }
+        dhpar.size = (unsigned int) pstr_len;
+        if (gnutls_dh_params_import_pkcs3 (daemon->https_mem_dhparams,
+                                           &dhpar,
+                                           GNUTLS_X509_FMT_PEM) < 0)
+        {
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Bad Diffie-Hellman parameters format.\n"));
+#endif
+          gnutls_dh_params_deinit (daemon->https_mem_dhparams);
+          return MHD_NO;
+        }
+        daemon->have_dhparams = true;
+      }
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif
+      break;
+    case MHD_OPTION_HTTPS_PRIORITIES:
+    case MHD_OPTION_HTTPS_PRIORITIES_APPEND:
+      pstr = va_arg (ap,
+                     const char *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+      {
+        if (NULL != daemon->priority_cache)
+          gnutls_priority_deinit (daemon->priority_cache);
+
+        if (MHD_OPTION_HTTPS_PRIORITIES == opt)
+        {
+          int init_res;
+          const char *err_pos;
+          init_res = gnutls_priority_init (&daemon->priority_cache,
+                                           pstr,
+                                           &err_pos);
+          if (GNUTLS_E_SUCCESS != init_res)
+          {
+#ifdef HAVE_MESSAGES
+            MHD_DLOG (daemon,
+                      _ ("Setting priorities to '%s' failed: %s " \
+                         "The problematic part starts at: %s\n"),
+                      pstr,
+                      gnutls_strerror (init_res),
+                      err_pos);
+#endif
+            daemon->priority_cache = NULL;
+            return MHD_NO;
+          }
+        }
+        else
+        {
+          /* The cache has been deinited */
+          daemon->priority_cache = NULL;
+          if (! daemon_tls_priorities_init_append (daemon, pstr))
+            return MHD_NO;
+        }
+      }
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif
+      break;
+    case MHD_OPTION_HTTPS_CERT_CALLBACK:
+#if GNUTLS_VERSION_MAJOR < 3
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("MHD_OPTION_HTTPS_CERT_CALLBACK requires building " \
+                   "MHD with GnuTLS >= 3.0.\n"));
+#endif
+      return MHD_NO;
+#else
+      pgcrf = va_arg (ap,
+                      gnutls_certificate_retrieve_function2 *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+        daemon->cert_callback = pgcrf;
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif /*  HAVE_MESSAGES */
+      break;
+#endif
+    case MHD_OPTION_HTTPS_CERT_CALLBACK2:
+#if GNUTLS_VERSION_NUMBER < 0x030603
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("MHD_OPTION_HTTPS_CERT_CALLBACK2 requires building " \
+                   "MHD with GnuTLS >= 3.6.3.\n"));
+#endif
+      return MHD_NO;
+#else
+      pgcrf2 = va_arg (ap,
+                       gnutls_certificate_retrieve_function3 *);
+      if (0 != (daemon->options & MHD_USE_TLS))
+        daemon->cert_callback2 = pgcrf2;
+#ifdef HAVE_MESSAGES
+      else
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD but " \
+                     "MHD_USE_TLS not set.\n"),
+                  opt);
+#endif /* HAVE_MESSAGES */
+      break;
+#endif
+#endif /* HTTPS_SUPPORT */
+#ifdef DAUTH_SUPPORT
+    case MHD_OPTION_DIGEST_AUTH_RANDOM:
+    case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY:
+      daemon->digest_auth_rand_size = va_arg (ap,
+                                              size_t);
+      daemon->digest_auth_random = va_arg (ap,
+                                           const char *);
+      if (MHD_OPTION_DIGEST_AUTH_RANDOM_COPY == opt)
+        /* Set to some non-NULL value just to indicate that copy is required. */
+        daemon->digest_auth_random_copy = daemon;
+      else
+        daemon->digest_auth_random_copy = NULL;
+      break;
+    case MHD_OPTION_NONCE_NC_SIZE:
+      daemon->nonce_nc_size = va_arg (ap,
+                                      unsigned int);
+      break;
+    case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE:
+      daemon->dauth_bind_type = va_arg (ap,
+                                        unsigned int);
+      if (0 != (daemon->dauth_bind_type & MHD_DAUTH_BIND_NONCE_URI_PARAMS))
+        daemon->dauth_bind_type |= MHD_DAUTH_BIND_NONCE_URI;
+      break;
+#endif
+    case MHD_OPTION_LISTEN_SOCKET:
+      if (0 != (daemon->options & MHD_USE_NO_LISTEN_SOCKET))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("MHD_OPTION_LISTEN_SOCKET specified for daemon "
+                     "with MHD_USE_NO_LISTEN_SOCKET flag set.\n"));
+#endif
+        return MHD_NO;
+      }
+      else
+      {
+        daemon->listen_fd = va_arg (ap,
+                                    MHD_socket);
+#if defined(SO_DOMAIN) && defined(AF_UNIX)
+        {
+          int af;
+          socklen_t len = sizeof (af);
+
+          if (0 == getsockopt (daemon->listen_fd,
+                               SOL_SOCKET,
+                               SO_DOMAIN,
+                               &af,
+                               &len))
+          {
+            daemon->listen_is_unix = (AF_UNIX == af) ? _MHD_YES : _MHD_NO;
+          }
+          else
+            daemon->listen_is_unix = _MHD_UNKNOWN;
+        }
+#else  /* ! SO_DOMAIN || ! AF_UNIX */
+        daemon->listen_is_unix = _MHD_UNKNOWN;
+#endif /* ! SO_DOMAIN || ! AF_UNIX */
+      }
+      break;
+    case MHD_OPTION_EXTERNAL_LOGGER:
+#ifdef HAVE_MESSAGES
+      daemon->custom_error_log = va_arg (ap,
+                                         VfprintfFunctionPointerType);
+      daemon->custom_error_log_cls = va_arg (ap,
+                                             void *);
+      if (1 != daemon->num_opts)
+        MHD_DLOG (daemon,
+                  _ ("MHD_OPTION_EXTERNAL_LOGGER is not the first option "
+                     "specified for the daemon. Some messages may be "
+                     "printed by the standard MHD logger.\n"));
+
+#else
+      va_arg (ap,
+              VfprintfFunctionPointerType);
+      va_arg (ap,
+              void *);
+#endif
+      break;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    case MHD_OPTION_THREAD_STACK_SIZE:
+      daemon->thread_stack_size = va_arg (ap,
+                                          size_t);
+      break;
+#endif
+    case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE:
+#ifdef TCP_FASTOPEN
+      daemon->fastopen_queue_size = va_arg (ap,
+                                            unsigned int);
+      break;
+#else  /* ! TCP_FASTOPEN */
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("TCP fastopen is not supported on this platform.\n"));
+#endif /* HAVE_MESSAGES */
+      return MHD_NO;
+#endif /* ! TCP_FASTOPEN */
+    case MHD_OPTION_LISTENING_ADDRESS_REUSE:
+      daemon->listening_address_reuse = va_arg (ap,
+                                                unsigned int) ? 1 : -1;
+      break;
+    case MHD_OPTION_LISTEN_BACKLOG_SIZE:
+      daemon->listen_backlog_size = va_arg (ap,
+                                            unsigned int);
+      break;
+    case MHD_OPTION_STRICT_FOR_CLIENT:
+      daemon->client_discipline = va_arg (ap, int); /* Temporal assignment */
+      /* Map to correct value */
+      if (-1 >= daemon->client_discipline)
+        daemon->client_discipline = -3;
+      else if (1 <= daemon->client_discipline)
+        daemon->client_discipline = 1;
+#ifdef HAVE_MESSAGES
+      if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) &&
+           (1 != daemon->client_discipline) )
+      {
+        MHD_DLOG (daemon,
+                  _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because "
+                     "another behaviour is specified by "
+                     "MHD_OPTION_STRICT_CLIENT.\n"));
+      }
+#endif /* HAVE_MESSAGES */
+      break;
+    case MHD_OPTION_CLIENT_DISCIPLINE_LVL:
+      daemon->client_discipline = va_arg (ap, int);
+#ifdef HAVE_MESSAGES
+      if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) &&
+           (1 != daemon->client_discipline) )
+      {
+        MHD_DLOG (daemon,
+                  _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because "
+                     "another behaviour is specified by "
+                     "MHD_OPTION_CLIENT_DISCIPLINE_LVL.\n"));
+      }
+#endif /* HAVE_MESSAGES */
+      break;
+    case MHD_OPTION_ARRAY:
+      daemon->num_opts--; /* Do not count MHD_OPTION_ARRAY */
+      oa = va_arg (ap, struct MHD_OptionItem *);
+      i = 0;
+      while (MHD_OPTION_END != (opt = oa[i].option))
+      {
+        switch (opt)
+        {
+        /* all options taking 'size_t' */
+        case MHD_OPTION_CONNECTION_MEMORY_LIMIT:
+        case MHD_OPTION_CONNECTION_MEMORY_INCREMENT:
+        case MHD_OPTION_THREAD_STACK_SIZE:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (size_t) oa[i].value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        /* all options taking 'unsigned int' */
+        case MHD_OPTION_NONCE_NC_SIZE:
+        case MHD_OPTION_CONNECTION_LIMIT:
+        case MHD_OPTION_CONNECTION_TIMEOUT:
+        case MHD_OPTION_PER_IP_CONNECTION_LIMIT:
+        case MHD_OPTION_THREAD_POOL_SIZE:
+        case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE:
+        case MHD_OPTION_LISTENING_ADDRESS_REUSE:
+        case MHD_OPTION_LISTEN_BACKLOG_SIZE:
+        case MHD_OPTION_SERVER_INSANITY:
+        case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (unsigned int) oa[i].value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        /* all options taking 'enum' */
+        case MHD_OPTION_HTTPS_CRED_TYPE:
+#ifdef HTTPS_SUPPORT
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (gnutls_credentials_type_t) oa[i].value,
+                                       MHD_OPTION_END))
+#endif /* HTTPS_SUPPORT */
+          return MHD_NO;
+          break;
+        /* all options taking 'MHD_socket' */
+        case MHD_OPTION_LISTEN_SOCKET:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (MHD_socket) oa[i].value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        /* all options taking 'int' */
+        case MHD_OPTION_STRICT_FOR_CLIENT:
+        case MHD_OPTION_CLIENT_DISCIPLINE_LVL:
+        case MHD_OPTION_SIGPIPE_HANDLED_BY_APP:
+        case MHD_OPTION_TLS_NO_ALPN:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (int) oa[i].value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        /* all options taking one pointer */
+        case MHD_OPTION_SOCK_ADDR:
+        case MHD_OPTION_HTTPS_MEM_KEY:
+        case MHD_OPTION_HTTPS_KEY_PASSWORD:
+        case MHD_OPTION_HTTPS_MEM_CERT:
+        case MHD_OPTION_HTTPS_MEM_TRUST:
+        case MHD_OPTION_HTTPS_MEM_DHPARAMS:
+        case MHD_OPTION_HTTPS_PRIORITIES:
+        case MHD_OPTION_HTTPS_PRIORITIES_APPEND:
+        case MHD_OPTION_ARRAY:
+        case MHD_OPTION_HTTPS_CERT_CALLBACK:
+        case MHD_OPTION_HTTPS_CERT_CALLBACK2:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       oa[i].ptr_value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        /* all options taking two pointers */
+        case MHD_OPTION_NOTIFY_COMPLETED:
+        case MHD_OPTION_NOTIFY_CONNECTION:
+        case MHD_OPTION_URI_LOG_CALLBACK:
+        case MHD_OPTION_EXTERNAL_LOGGER:
+        case MHD_OPTION_UNESCAPE_CALLBACK:
+        case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (void *) oa[i].value,
+                                       oa[i].ptr_value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        /* options taking size_t-number followed by pointer */
+        case MHD_OPTION_DIGEST_AUTH_RANDOM:
+        case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY:
+          if (MHD_NO == parse_options (daemon,
+                                       servaddr,
+                                       opt,
+                                       (size_t) oa[i].value,
+                                       oa[i].ptr_value,
+                                       MHD_OPTION_END))
+            return MHD_NO;
+          break;
+        case MHD_OPTION_END: /* Not possible */
+        default:
+          return MHD_NO;
+        }
+        i++;
+      }
+      break;
+    case MHD_OPTION_UNESCAPE_CALLBACK:
+      daemon->unescape_callback = va_arg (ap,
+                                          UnescapeCallback);
+      daemon->unescape_callback_cls = va_arg (ap,
+                                              void *);
+      break;
+#ifdef HTTPS_SUPPORT
+    case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER:
+#if GNUTLS_VERSION_MAJOR >= 3
+      daemon->cred_callback = va_arg (ap,
+                                      MHD_PskServerCredentialsCallback);
+      daemon->cred_callback_cls = va_arg (ap,
+                                          void *);
+      break;
+#else
+      MHD_DLOG (daemon,
+                _ ("MHD HTTPS option %d passed to MHD compiled " \
+                   "without GNUtls >= 3.\n"),
+                opt);
+      return MHD_NO;
+#endif
+#endif /* HTTPS_SUPPORT */
+    case MHD_OPTION_SIGPIPE_HANDLED_BY_APP:
+      if (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD))
+        daemon->sigpipe_blocked = ( (va_arg (ap,
+                                             int)) != 0);
+      else
+      {
+        (void) va_arg (ap,
+                       int);
+      }
+      break;
+    case MHD_OPTION_TLS_NO_ALPN:
+#ifdef HTTPS_SUPPORT
+      daemon->disable_alpn = (va_arg (ap,
+                                      int) != 0);
+#else  /* ! HTTPS_SUPPORT */
+      (void) va_arg (ap, int);
+#endif /* ! HTTPS_SUPPORT */
+#ifdef HAVE_MESSAGES
+      if (0 == (daemon->options & MHD_USE_TLS))
+        MHD_DLOG (daemon,
+                  _ ("MHD HTTPS option %d passed to MHD " \
+                     "but MHD_USE_TLS not set.\n"),
+                  (int) opt);
+#endif /* HAVE_MESSAGES */
+      break;
+#ifndef HTTPS_SUPPORT
+    case MHD_OPTION_HTTPS_MEM_KEY:
+    case MHD_OPTION_HTTPS_MEM_CERT:
+    case MHD_OPTION_HTTPS_CRED_TYPE:
+    case MHD_OPTION_HTTPS_PRIORITIES:
+    case MHD_OPTION_HTTPS_PRIORITIES_APPEND:
+    case MHD_OPTION_HTTPS_MEM_TRUST:
+    case MHD_OPTION_HTTPS_CERT_CALLBACK:
+    case MHD_OPTION_HTTPS_MEM_DHPARAMS:
+    case MHD_OPTION_HTTPS_KEY_PASSWORD:
+    case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER:
+    case MHD_OPTION_HTTPS_CERT_CALLBACK2:
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("MHD HTTPS option %d passed to MHD "
+                   "compiled without HTTPS support.\n"),
+                opt);
+#endif
+      return MHD_NO;
+#endif /* HTTPS_SUPPORT */
+    case MHD_OPTION_END: /* Not possible */
+    default:
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Invalid option %d! (Did you terminate "
+                   "the list with MHD_OPTION_END?).\n"),
+                opt);
+#endif
+      return MHD_NO;
     }
+  }
   return MHD_YES;
 }
 
 
-/**
- * Create a listen socket, if possible with SOCK_CLOEXEC flag set.
- *
- * @param daemon daemon for which we create the socket
- * @param domain socket domain (i.e. PF_INET)
- * @param type socket type (usually SOCK_STREAM)
- * @param protocol desired protocol, 0 for default
- */
-static MHD_socket
-create_socket (struct MHD_Daemon *daemon,
-	       int domain, int type, int protocol)
+#ifdef EPOLL_SUPPORT
+static int
+setup_epoll_fd (struct MHD_Daemon *daemon)
 {
-  int ctype = type | SOCK_CLOEXEC;
-  MHD_socket fd;
+  int fd;
 
-  /* use SOCK_STREAM rather than ai_socktype: some getaddrinfo
-   * implementations do not set ai_socktype, e.g. RHL6.2. */
-  fd = socket (domain, ctype, protocol);
-  if ( (MHD_INVALID_SOCKET == fd) && (EINVAL == MHD_socket_errno_) && (0 != SOCK_CLOEXEC) )
-  {
-    ctype = type;
-    fd = socket(domain, type, protocol);
-  }
+#ifndef HAVE_MESSAGES
+  (void) daemon; /* Mute compiler warning. */
+#endif /* ! HAVE_MESSAGES */
+
+#ifdef USE_EPOLL_CREATE1
+  fd = epoll_create1 (EPOLL_CLOEXEC);
+#else  /* ! USE_EPOLL_CREATE1 */
+  fd = epoll_create (MAX_EVENTS);
+#endif /* ! USE_EPOLL_CREATE1 */
   if (MHD_INVALID_SOCKET == fd)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Call to epoll_create1 failed: %s\n"),
+              MHD_socket_last_strerr_ ());
+#endif
     return MHD_INVALID_SOCKET;
-  if (type == ctype)
-    make_nonblocking_noninheritable (daemon, fd);
+  }
+#if ! defined(USE_EPOLL_CREATE1)
+  if (! MHD_socket_noninheritable_ (fd))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to set noninheritable mode on epoll FD.\n"));
+#endif
+  }
+#endif /* ! USE_EPOLL_CREATE1 */
   return fd;
 }
 
 
-#if EPOLL_SUPPORT
 /**
  * Setup epoll() FD for the daemon and initialize it to listen
  * on the listen FD.
+ * @remark To be called only from MHD_start_daemon_va()
  *
  * @param daemon daemon to initialize for epoll()
  * @return #MHD_YES on success, #MHD_NO on failure
  */
-static int
+static enum MHD_Result
 setup_epoll_to_listen (struct MHD_Daemon *daemon)
 {
   struct epoll_event event;
+  MHD_socket ls;
 
-#ifdef HAVE_EPOLL_CREATE1
-  daemon->epoll_fd = epoll_create1 (EPOLL_CLOEXEC);
-#else  /* !HAVE_EPOLL_CREATE1 */
-  daemon->epoll_fd = epoll_create (MAX_EVENTS);
-#endif /* !HAVE_EPOLL_CREATE1 */
+  mhd_assert (0 != (daemon->options & MHD_USE_EPOLL));
+  mhd_assert (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION));
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) || \
+               MHD_ITC_IS_VALID_ (daemon->itc) );
+  daemon->epoll_fd = setup_epoll_fd (daemon);
   if (-1 == daemon->epoll_fd)
+    return MHD_NO;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if (0 != (MHD_ALLOW_UPGRADE & daemon->options))
+  {
+    daemon->epoll_upgrade_fd = setup_epoll_fd (daemon);
+    if (MHD_INVALID_SOCKET == daemon->epoll_upgrade_fd)
+      return MHD_NO;
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+  if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
+       (! daemon->was_quiesced) )
+  {
+    event.events = EPOLLIN | EPOLLRDHUP;
+    event.data.ptr = daemon;
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        ls,
+                        &event))
     {
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-                "Call to epoll_create1 failed: %s\n",
+                _ ("Call to epoll_ctl failed: %s\n"),
                 MHD_socket_last_strerr_ ());
 #endif
       return MHD_NO;
     }
-#ifndef HAVE_EPOLL_CREATE1
-  else
+    daemon->listen_socket_in_epoll = true;
+  }
+
+  if (MHD_ITC_IS_VALID_ (daemon->itc))
+  {
+    event.events = EPOLLIN | EPOLLRDHUP;
+    event.data.ptr = _MHD_DROP_CONST (epoll_itc_marker);
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_ADD,
+                        MHD_itc_r_fd_ (daemon->itc),
+                        &event))
     {
-      int fdflags = fcntl (daemon->epoll_fd, F_GETFD);
-      if (0 > fdflags || 0 > fcntl (daemon->epoll_fd, F_SETFD, fdflags | FD_CLOEXEC))
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Failed to change flags on epoll fd: %s\n",
-                    MHD_socket_last_strerr_ ());
-#endif /* HAVE_MESSAGES */
-        }
-    }
-#endif /* !HAVE_EPOLL_CREATE1 */
-  if (0 == EPOLL_CLOEXEC)
-    make_nonblocking_noninheritable (daemon,
-				     daemon->epoll_fd);
-  if (MHD_INVALID_SOCKET == daemon->socket_fd)
-    return MHD_YES; /* non-listening daemon */
-  event.events = EPOLLIN;
-  event.data.ptr = daemon;
-  if (0 != epoll_ctl (daemon->epoll_fd,
-		      EPOLL_CTL_ADD,
-		      daemon->socket_fd,
-		      &event))
-    {
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-                "Call to epoll_ctl failed: %s\n",
+                _ ("Call to epoll_ctl failed: %s\n"),
                 MHD_socket_last_strerr_ ());
 #endif
       return MHD_NO;
     }
-  if ( (MHD_INVALID_PIPE_ != daemon->wpipe[0]) &&
-       (MHD_USE_SUSPEND_RESUME == (daemon->options & MHD_USE_SUSPEND_RESUME)) )
-    {
-      event.events = EPOLLIN | EPOLLET;
-      event.data.ptr = NULL;
-      event.data.fd = daemon->wpipe[0];
-      if (0 != epoll_ctl (daemon->epoll_fd,
-                          EPOLL_CTL_ADD,
-                          daemon->wpipe[0],
-                          &event))
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Call to epoll_ctl failed: %s\n",
-                    MHD_socket_last_strerr_ ());
-#endif
-          return MHD_NO;
-        }
-    }
-  daemon->listen_socket_in_epoll = MHD_YES;
+  }
   return MHD_YES;
 }
-#endif
 
 
+#endif
+
 /**
  * Start a webserver on the given port.
  *
  * @param flags combination of `enum MHD_FLAG` values
- * @param port port to bind to (in host byte order)
+ * @param port port to bind to (in host byte order),
+ *        use '0' to bind to random free port,
+ *        ignored if #MHD_OPTION_SOCK_ADDR or
+ *        #MHD_OPTION_LISTEN_SOCKET is provided
+ *        or #MHD_USE_NO_LISTEN_SOCKET is specified
  * @param apc callback to call to check which clients
  *        will be allowed to connect; you can pass NULL
  *        in which case connections from any IP will be
@@ -3611,60 +7021,114 @@
  * @return NULL on error, handle to daemon on success
  * @ingroup event
  */
-struct MHD_Daemon *
+_MHD_EXTERN struct MHD_Daemon *
 MHD_start_daemon_va (unsigned int flags,
                      uint16_t port,
                      MHD_AcceptPolicyCallback apc,
                      void *apc_cls,
-                     MHD_AccessHandlerCallback dh, void *dh_cls,
-		     va_list ap)
+                     MHD_AccessHandlerCallback dh,
+                     void *dh_cls,
+                     va_list ap)
 {
-  const int on = 1;
+  const MHD_SCKT_OPT_BOOL_ on = 1;
   struct MHD_Daemon *daemon;
-  MHD_socket socket_fd;
+  MHD_socket listen_fd;
   struct sockaddr_in servaddr4;
-#if HAVE_INET6
+#ifdef HAVE_INET6
   struct sockaddr_in6 servaddr6;
 #endif
   const struct sockaddr *servaddr = NULL;
   socklen_t addrlen;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   unsigned int i;
-  int res_thread_create;
-  int use_pipe;
+#endif
+  enum MHD_FLAG eflags; /* same type as in MHD_Daemon */
+  enum MHD_FLAG *pflags;
 
+  MHD_check_global_init_ ();
+  eflags = (enum MHD_FLAG) flags;
+  pflags = &eflags;
 #ifndef HAVE_INET6
-  if (0 != (flags & MHD_USE_IPv6))
+  if (0 != (*pflags & MHD_USE_IPv6))
     return NULL;
 #endif
 #ifndef HAVE_POLL
-  if (0 != (flags & MHD_USE_POLL))
+  if (0 != (*pflags & MHD_USE_POLL))
     return NULL;
 #endif
-#if ! HTTPS_SUPPORT
-  if (0 != (flags & MHD_USE_SSL))
+#ifndef EPOLL_SUPPORT
+  if (0 != (*pflags & MHD_USE_EPOLL))
     return NULL;
-#endif
+#endif /* ! EPOLL_SUPPORT */
+#ifndef HTTPS_SUPPORT
+  if (0 != (*pflags & MHD_USE_TLS))
+    return NULL;
+#endif /* ! HTTPS_SUPPORT */
 #ifndef TCP_FASTOPEN
-  if (0 != (flags & MHD_USE_TCP_FASTOPEN))
+  if (0 != (*pflags & MHD_USE_TCP_FASTOPEN))
     return NULL;
 #endif
+  if (0 != (*pflags & MHD_ALLOW_UPGRADE))
+  {
+#ifdef UPGRADE_SUPPORT
+    *pflags |= MHD_ALLOW_SUSPEND_RESUME;
+#else  /* ! UPGRADE_SUPPORT */
+    return NULL;
+#endif /* ! UPGRADE_SUPPORT */
+  }
   if (NULL == dh)
     return NULL;
-  if (NULL == (daemon = malloc (sizeof (struct MHD_Daemon))))
+
+  /* Check for invalid combinations of flags. */
+  if ((0 != (*pflags & MHD_USE_POLL)) && (0 != (*pflags & MHD_USE_EPOLL)))
     return NULL;
-  memset (daemon, 0, sizeof (struct MHD_Daemon));
-#if EPOLL_SUPPORT
+  if ((0 != (*pflags & MHD_USE_EPOLL)) &&
+      (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)))
+    return NULL;
+  if ((0 != (*pflags & MHD_USE_POLL)) &&
+      (0 == (*pflags & (MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_THREAD_PER_CONNECTION))))
+    return NULL;
+  if ((0 != (*pflags & MHD_USE_AUTO)) &&
+      (0 != (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL))))
+    return NULL;
+
+  if (0 != (*pflags & MHD_USE_AUTO))
+  {
+#if defined(EPOLL_SUPPORT) && defined(HAVE_POLL)
+    if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))
+      *pflags |= MHD_USE_POLL;
+    else
+      *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */
+#elif defined(HAVE_POLL)
+    if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD))
+      *pflags |= MHD_USE_POLL; /* Including thread-per-connection */
+#elif defined(EPOLL_SUPPORT)
+#warning 'epoll' enabled, while 'poll' not detected. Check configure.
+#else
+    /* No choice: use select() for any mode - do not modify flags */
+#endif
+  }
+
+  if (NULL == (daemon = MHD_calloc_ (1, sizeof (struct MHD_Daemon))))
+    return NULL;
+#ifdef EPOLL_SUPPORT
   daemon->epoll_fd = -1;
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  daemon->epoll_upgrade_fd = -1;
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
 #endif
   /* try to open listen socket */
-  daemon->socket_fd = MHD_INVALID_SOCKET;
+#ifdef HTTPS_SUPPORT
+  daemon->priority_cache = NULL;
+#endif /* HTTPS_SUPPORT */
+  daemon->listen_fd = MHD_INVALID_SOCKET;
+  daemon->listen_is_unix = _MHD_NO;
   daemon->listening_address_reuse = 0;
-  daemon->options = flags;
-#if WINDOWS
-  /* Winsock is broken with respect to 'shutdown';
-     this disables us calling 'shutdown' on W32. */
-  daemon->options |= MHD_USE_EPOLL_TURBO;
-#endif
+  daemon->options = *pflags;
+  pflags = &daemon->options;
+  daemon->client_discipline = (0 != (*pflags & MHD_USE_PEDANTIC_CHECKS)) ?
+                              1 : 0;
   daemon->port = port;
   daemon->apc = apc;
   daemon->apc_cls = apc_cls;
@@ -3675,484 +7139,726 @@
   daemon->pool_size = MHD_POOL_SIZE_DEFAULT;
   daemon->pool_increment = MHD_BUF_INC_SIZE;
   daemon->unescape_callback = &unescape_wrapper;
-  daemon->connection_timeout = 0;       /* no timeout */
-  daemon->wpipe[0] = MHD_INVALID_PIPE_;
-  daemon->wpipe[1] = MHD_INVALID_PIPE_;
-#if HAVE_MESSAGES
-  daemon->custom_error_log = (MHD_LogCallback) &vfprintf;
+  daemon->connection_timeout_ms = 0;       /* no timeout */
+  MHD_itc_set_invalid_ (daemon->itc);
+#ifdef SOMAXCONN
+  daemon->listen_backlog_size = SOMAXCONN;
+#else  /* !SOMAXCONN */
+  daemon->listen_backlog_size = 511; /* should be safe value */
+#endif /* !SOMAXCONN */
+#ifdef HAVE_MESSAGES
+  daemon->custom_error_log = &MHD_default_logger_;
   daemon->custom_error_log_cls = stderr;
 #endif
+#ifndef MHD_WINSOCK_SOCKETS
+  daemon->sigpipe_blocked = false;
+#else  /* MHD_WINSOCK_SOCKETS */
+  /* There is no SIGPIPE on W32, nothing to block. */
+  daemon->sigpipe_blocked = true;
+#endif /* _WIN32 && ! __CYGWIN__ */
+
+  if ( (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) &&
+       (0 == (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) )
+  {
+    /* Log warning message later, when log parameters are processes */
+    *pflags |= MHD_USE_INTERNAL_POLLING_THREAD;
+  }
+  if (0 == (*pflags & MHD_USE_INTERNAL_POLLING_THREAD))
+    *pflags = (*pflags & ~((enum MHD_FLAG) MHD_USE_ITC)); /* useless if we are using 'external' select */
+  else
+  {
 #ifdef HAVE_LISTEN_SHUTDOWN
-  use_pipe = (0 != (daemon->options & (MHD_USE_NO_LISTEN_SOCKET | MHD_USE_PIPE_FOR_SHUTDOWN)));
-#else
-  use_pipe = 1; /* yes, must use pipe to signal shutdown */
+    if (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET))
 #endif
-  if (0 == (flags & (MHD_USE_SELECT_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION)))
-    use_pipe = 0; /* useless if we are using 'external' select */
-  if ( (use_pipe) && (0 != MHD_pipe_ (daemon->wpipe)) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Failed to create control pipe: %s\n",
-		MHD_strerror_ (errno));
-#endif
-      free (daemon);
-      return NULL;
-    }
-#ifndef WINDOWS
-  if ( (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL_LINUX_ONLY))) &&
-       (1 == use_pipe) &&
-       (daemon->wpipe[0] >= FD_SETSIZE) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"file descriptor for control pipe exceeds maximum value\n");
-#endif
-      if (0 != MHD_pipe_close_ (daemon->wpipe[0]))
-	MHD_PANIC ("close failed\n");
-      if (0 != MHD_pipe_close_ (daemon->wpipe[1]))
-	MHD_PANIC ("close failed\n");
-      free (daemon);
-      return NULL;
-    }
-#endif
+    *pflags |= MHD_USE_ITC;       /* yes, must use ITC to signal thread */
+  }
 #ifdef DAUTH_SUPPORT
   daemon->digest_auth_rand_size = 0;
   daemon->digest_auth_random = NULL;
   daemon->nonce_nc_size = 4; /* tiny */
 #endif
+#ifdef HTTPS_SUPPORT
+  if (0 != (*pflags & MHD_USE_TLS))
+  {
+    daemon->cred_type = GNUTLS_CRD_CERTIFICATE;
+  }
+#endif /* HTTPS_SUPPORT */
 
 
-  if (MHD_YES != parse_options_va (daemon, &servaddr, ap))
+  if (MHD_NO == parse_options_va (daemon,
+                                  &servaddr,
+                                  ap))
+  {
+#ifdef HTTPS_SUPPORT
+    if ( (0 != (*pflags & MHD_USE_TLS)) &&
+         (NULL != daemon->priority_cache) )
+      gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
+    free (daemon);
+    return NULL;
+  }
+#ifdef HTTPS_SUPPORT
+  if ((0 != (*pflags & MHD_USE_TLS))
+      && (NULL == daemon->priority_cache)
+      && ! daemon_tls_priorities_init_default (daemon))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to initialise GnuTLS priorities.\n"));
+#endif /* HAVE_MESSAGES */
+    free (daemon);
+    return NULL;
+  }
+#endif /* HTTPS_SUPPORT */
+
+#ifdef HAVE_MESSAGES
+  if ( (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) &&
+       (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD)) )
+  {
+    MHD_DLOG (daemon,
+              _ ("Warning: MHD_USE_THREAD_PER_CONNECTION must be used " \
+                 "only with MHD_USE_INTERNAL_POLLING_THREAD. " \
+                 "Flag MHD_USE_INTERNAL_POLLING_THREAD was added. " \
+                 "Consider setting MHD_USE_INTERNAL_POLLING_THREAD " \
+                 "explicitly.\n"));
+  }
+#endif
+
+  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+       && ((NULL != daemon->notify_completed)
+           || (NULL != daemon->notify_connection)) )
+    *pflags |= MHD_USE_ITC; /* requires ITC */
+
+#ifndef NDEBUG
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (daemon,
+            _ ("Using debug build of libmicrohttpd.\n") );
+#endif /* HAVE_MESSAGES */
+#endif /* ! NDEBUG */
+
+  if ( (0 != (*pflags & MHD_USE_ITC))
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+       && (0 == daemon->worker_pool_size)
+#endif
+       )
+  {
+    if (! MHD_itc_init_ (daemon->itc))
     {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to create inter-thread communication channel: %s\n"),
+                MHD_itc_last_strerror_ ());
+#endif
+#ifdef HTTPS_SUPPORT
+      if (NULL != daemon->priority_cache)
+        gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
       free (daemon);
       return NULL;
     }
+    if ( (0 == (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL))) &&
+         (! MHD_SCKT_FD_FITS_FDSET_ (MHD_itc_r_fd_ (daemon->itc),
+                                     NULL)) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("file descriptor for inter-thread communication " \
+                   "channel exceeds maximum value.\n"));
+#endif
+      MHD_itc_destroy_chk_ (daemon->itc);
+#ifdef HTTPS_SUPPORT
+      if (NULL != daemon->priority_cache)
+        gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
+      free (daemon);
+      return NULL;
+    }
+  }
+
 #ifdef DAUTH_SUPPORT
-  if (daemon->nonce_nc_size > 0)
+  if (NULL != daemon->digest_auth_random_copy)
+  {
+    mhd_assert (daemon == daemon->digest_auth_random_copy);
+    daemon->digest_auth_random_copy = malloc (daemon->digest_auth_rand_size);
+    if (NULL == daemon->digest_auth_random_copy)
     {
-      if ( ( (size_t) (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc))) /
-	   sizeof(struct MHD_NonceNc) != daemon->nonce_nc_size)
-	{
-#if HAVE_MESSAGES
-	  MHD_DLOG (daemon,
-		    "Specified value for NC_SIZE too large\n");
-#endif
-	  free (daemon);
-	  return NULL;
-	}
-      daemon->nnc = malloc (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc));
-      if (NULL == daemon->nnc)
-	{
-#if HAVE_MESSAGES
-	  MHD_DLOG (daemon,
-		    "Failed to allocate memory for nonce-nc map: %s\n",
-		    MHD_strerror_ (errno));
-#endif
-	  free (daemon);
-	  return NULL;
-	}
-    }
-
-  if (MHD_YES != MHD_mutex_create_ (&daemon->nnc_lock))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"MHD failed to initialize nonce-nc mutex\n");
-#endif
-      free (daemon->nnc);
+#ifdef HTTPS_SUPPORT
+      if (0 != (*pflags & MHD_USE_TLS))
+        gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
       free (daemon);
       return NULL;
     }
+    memcpy (daemon->digest_auth_random_copy,
+            daemon->digest_auth_random,
+            daemon->digest_auth_rand_size);
+    daemon->digest_auth_random = daemon->digest_auth_random_copy;
+  }
+  if (daemon->nonce_nc_size > 0)
+  {
+    if ( ( (size_t) (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc)))
+         / sizeof(struct MHD_NonceNc) != daemon->nonce_nc_size)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Specified value for NC_SIZE too large.\n"));
+#endif
+#ifdef HTTPS_SUPPORT
+      if (0 != (*pflags & MHD_USE_TLS))
+        gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
+      free (daemon->digest_auth_random_copy);
+      free (daemon);
+      return NULL;
+    }
+    daemon->nnc = MHD_calloc_ (daemon->nonce_nc_size,
+                               sizeof (struct MHD_NonceNc));
+    if (NULL == daemon->nnc)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to allocate memory for nonce-nc map: %s\n"),
+                MHD_strerror_ (errno));
+#endif
+#ifdef HTTPS_SUPPORT
+      if (0 != (*pflags & MHD_USE_TLS))
+        gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
+      free (daemon->digest_auth_random_copy);
+      free (daemon);
+      return NULL;
+    }
+  }
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if (! MHD_mutex_init_ (&daemon->nnc_lock))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("MHD failed to initialize nonce-nc mutex.\n"));
+#endif
+#ifdef HTTPS_SUPPORT
+    if (0 != (*pflags & MHD_USE_TLS))
+      gnutls_priority_deinit (daemon->priority_cache);
+#endif /* HTTPS_SUPPORT */
+    free (daemon->digest_auth_random_copy);
+    free (daemon->nnc);
+    free (daemon);
+    return NULL;
+  }
+#endif
 #endif
 
-  /* Thread pooling currently works only with internal select thread model */
-  if ( (0 == (flags & MHD_USE_SELECT_INTERNALLY)) &&
+  /* Thread polling currently works only with internal select thread mode */
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if ( (0 == (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) &&
        (daemon->worker_pool_size > 0) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("MHD thread polling only works with " \
+                 "MHD_USE_INTERNAL_POLLING_THREAD.\n"));
+#endif
+    goto free_and_fail;
+  }
+#endif
+  if ( (MHD_INVALID_SOCKET == daemon->listen_fd) &&
+       (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) )
+  {
+    /* try to open listen socket */
+    int domain;
+
+#ifdef HAVE_INET6
+    domain = (*pflags & MHD_USE_IPv6) ? PF_INET6 : PF_INET;
+#else  /* ! HAVE_INET6 */
+    if (*pflags & MHD_USE_IPv6)
+      goto free_and_fail;
+    domain = PF_INET;
+#endif /* ! HAVE_INET6 */
+
+    listen_fd = MHD_socket_create_listen_ (domain);
+    if (MHD_INVALID_SOCKET == listen_fd)
     {
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-		"MHD thread pooling only works with MHD_USE_SELECT_INTERNALLY\n");
+                _ ("Failed to create socket for listening: %s\n"),
+                MHD_socket_last_strerr_ ());
 #endif
       goto free_and_fail;
     }
 
-  if ( (MHD_USE_SUSPEND_RESUME == (flags & MHD_USE_SUSPEND_RESUME)) &&
-       (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) )
+    /* Apply the socket options according to listening_address_reuse. */
+    if (0 == daemon->listening_address_reuse)
     {
-#if HAVE_MESSAGES
+#ifndef MHD_WINSOCK_SOCKETS
+      /* No user requirement, use "traditional" default SO_REUSEADDR
+       * on non-W32 platforms, and do not fail if it doesn't work.
+       * Don't use it on W32, because on W32 it will allow multiple
+       * bind to the same address:port, like SO_REUSEPORT on others. */
+      if (0 > setsockopt (listen_fd,
+                          SOL_SOCKET,
+                          SO_REUSEADDR,
+                          (const void *) &on, sizeof (on)))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("setsockopt failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+      }
+#endif /* ! MHD_WINSOCK_SOCKETS */
+    }
+    else if (daemon->listening_address_reuse > 0)
+    {
+      /* User requested to allow reusing listening address:port. */
+#ifndef MHD_WINSOCK_SOCKETS
+      /* Use SO_REUSEADDR on non-W32 platforms, and do not fail if
+       * it doesn't work. */
+      if (0 > setsockopt (listen_fd,
+                          SOL_SOCKET,
+                          SO_REUSEADDR,
+                          (const void *) &on, sizeof (on)))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("setsockopt failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+      }
+#endif /* ! MHD_WINSOCK_SOCKETS */
+      /* Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms.
+       * Fail if SO_REUSEPORT is not defined or setsockopt fails.
+       */
+      /* SO_REUSEADDR on W32 has the same semantics
+         as SO_REUSEPORT on BSD/Linux */
+#if defined(MHD_WINSOCK_SOCKETS) || defined(SO_REUSEPORT)
+      if (0 > setsockopt (listen_fd,
+                          SOL_SOCKET,
+#ifndef MHD_WINSOCK_SOCKETS
+                          SO_REUSEPORT,
+#else  /* MHD_WINSOCK_SOCKETS */
+                          SO_REUSEADDR,
+#endif /* MHD_WINSOCK_SOCKETS */
+                          (const void *) &on,
+                          sizeof (on)))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("setsockopt failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+        goto free_and_fail;
+      }
+#else  /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */
+      /* we're supposed to allow address:port re-use, but
+         on this platform we cannot; fail hard */
+#ifdef HAVE_MESSAGES
       MHD_DLOG (daemon,
-                "Combining MHD_USE_THREAD_PER_CONNECTION and MHD_USE_SUSPEND_RESUME is not supported.\n");
+                _ ("Cannot allow listening address reuse: " \
+                   "SO_REUSEPORT not defined.\n"));
 #endif
       goto free_and_fail;
+#endif /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */
     }
-
-#ifdef __SYMBIAN32__
-  if (0 != (flags & (MHD_USE_SELECT_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION)))
+    else   /* if (daemon->listening_address_reuse < 0) */
     {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Threaded operations are not supported on Symbian.\n");
-#endif
-      goto free_and_fail;
-    }
-#endif
-  if ( (MHD_INVALID_SOCKET == daemon->socket_fd) &&
-       (0 == (daemon->options & MHD_USE_NO_LISTEN_SOCKET)) )
-    {
-      /* try to open listen socket */
-      if (0 != (flags & MHD_USE_IPv6))
-	socket_fd = create_socket (daemon,
-				   PF_INET6, SOCK_STREAM, 0);
-      else
-	socket_fd = create_socket (daemon,
-				   PF_INET, SOCK_STREAM, 0);
-      if (MHD_INVALID_SOCKET == socket_fd)
-	{
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Call to socket failed: %s\n",
-                    MHD_socket_last_strerr_ ());
-#endif
-	  goto free_and_fail;
-	}
-
-      /* Apply the socket options according to listening_address_reuse. */
-      if (0 == daemon->listening_address_reuse)
-        {
-          /* No user requirement, use "traditional" default SO_REUSEADDR,
-           and do not fail if it doesn't work */
-          if (0 > setsockopt (socket_fd,
-                              SOL_SOCKET,
-                              SO_REUSEADDR,
-                              (void*)&on, sizeof (on)))
-          {
-#if HAVE_MESSAGES
-            MHD_DLOG (daemon,
-                      "setsockopt failed: %s\n",
-                      MHD_socket_last_strerr_ ());
-#endif
-          }
-        }
-      else if (daemon->listening_address_reuse > 0)
-        {
-          /* User requested to allow reusing listening address:port.
-           * Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms.
-           * Fail if SO_REUSEPORT does not exist or setsockopt fails.
-           */
-#ifdef _WIN32
-          /* SO_REUSEADDR on W32 has the same semantics
-             as SO_REUSEPORT on BSD/Linux */
-          if (0 > setsockopt (socket_fd,
-                              SOL_SOCKET,
-                              SO_REUSEADDR,
-                              (void*)&on, sizeof (on)))
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "setsockopt failed: %s\n",
-                        MHD_socket_last_strerr_ ());
-#endif
-              goto free_and_fail;
-            }
-#else
-#ifndef SO_REUSEPORT
-#ifdef LINUX
-/* Supported since Linux 3.9, but often not present (or commented out)
-   in the headers at this time; but 15 is reserved for this and
-   thus should be safe to use. */
-#define SO_REUSEPORT 15
-#endif
-#endif
-#ifdef SO_REUSEPORT
-          if (0 > setsockopt (socket_fd,
-                              SOL_SOCKET,
-                              SO_REUSEPORT,
-                              (void*)&on, sizeof (on)))
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "setsockopt failed: %s\n",
-                        MHD_socket_last_strerr_ ());
-#endif
-              goto free_and_fail;
-            }
-#else
-          /* we're supposed to allow address:port re-use, but
-             on this platform we cannot; fail hard */
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Cannot allow listening address reuse: SO_REUSEPORT not defined\n");
-#endif
-          goto free_and_fail;
-#endif
-#endif
-        }
-      else /* if (daemon->listening_address_reuse < 0) */
-        {
-          /* User requested to disallow reusing listening address:port.
-           * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE
-           * is used. Fail if it does not exist or setsockopt fails.
-           */
-#ifdef _WIN32
+      /* User requested to disallow reusing listening address:port.
+       * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE
+       * is used and Solaris with SO_EXCLBIND.
+       * Fail if MHD was compiled for W32 without SO_EXCLUSIVEADDRUSE
+       * or setsockopt fails.
+       */
+#if (defined(MHD_WINSOCK_SOCKETS) && defined(SO_EXCLUSIVEADDRUSE)) || \
+      (defined(__sun) && defined(SO_EXCLBIND))
+      if (0 > setsockopt (listen_fd,
+                          SOL_SOCKET,
 #ifdef SO_EXCLUSIVEADDRUSE
-          if (0 > setsockopt (socket_fd,
-                              SOL_SOCKET,
-                              SO_EXCLUSIVEADDRUSE,
-                              (void*)&on, sizeof (on)))
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "setsockopt failed: %s\n",
-                        MHD_socket_last_strerr_ ());
+                          SO_EXCLUSIVEADDRUSE,
+#else  /* SO_EXCLBIND */
+                          SO_EXCLBIND,
+#endif /* SO_EXCLBIND */
+                          (const void *) &on,
+                          sizeof (on)))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("setsockopt failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
 #endif
-              goto free_and_fail;
-            }
-#else /* SO_EXCLUSIVEADDRUSE not defined on W32? */
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Cannot disallow listening address reuse: SO_EXCLUSIVEADDRUSE not defined\n");
+        goto free_and_fail;
+      }
+#elif defined(MHD_WINSOCK_SOCKETS) /* SO_EXCLUSIVEADDRUSE not defined on W32? */
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Cannot disallow listening address reuse: " \
+                   "SO_EXCLUSIVEADDRUSE not defined.\n"));
 #endif
-          goto free_and_fail;
-#endif
-#endif /* _WIN32 */
-        }
+      goto free_and_fail;
+#endif /* MHD_WINSOCK_SOCKETS */
+    }
 
-      /* check for user supplied sockaddr */
-#if HAVE_INET6
-      if (0 != (flags & MHD_USE_IPv6))
-	addrlen = sizeof (struct sockaddr_in6);
+    /* check for user supplied sockaddr */
+#ifdef HAVE_INET6
+    if (0 != (*pflags & MHD_USE_IPv6))
+      addrlen = sizeof (struct sockaddr_in6);
+    else
+#endif
+    addrlen = sizeof (struct sockaddr_in);
+    if (NULL == servaddr)
+    {
+#ifdef HAVE_INET6
+      if (0 != (*pflags & MHD_USE_IPv6))
+      {
+#ifdef IN6ADDR_ANY_INIT
+        static const struct in6_addr static_in6any = IN6ADDR_ANY_INIT;
+#endif
+        memset (&servaddr6,
+                0,
+                sizeof (struct sockaddr_in6));
+        servaddr6.sin6_family = AF_INET6;
+        servaddr6.sin6_port = htons (port);
+#ifdef IN6ADDR_ANY_INIT
+        servaddr6.sin6_addr = static_in6any;
+#endif
+#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+        servaddr6.sin6_len = sizeof (struct sockaddr_in6);
+#endif
+        servaddr = (struct sockaddr *) &servaddr6;
+      }
       else
 #endif
-	addrlen = sizeof (struct sockaddr_in);
-      if (NULL == servaddr)
-	{
-#if HAVE_INET6
-	  if (0 != (flags & MHD_USE_IPv6))
-	    {
-	      memset (&servaddr6, 0, sizeof (struct sockaddr_in6));
-	      servaddr6.sin6_family = AF_INET6;
-	      servaddr6.sin6_port = htons (port);
-#if HAVE_SOCKADDR_IN_SIN_LEN
-	      servaddr6.sin6_len = sizeof (struct sockaddr_in6);
+      {
+        memset (&servaddr4,
+                0,
+                sizeof (struct sockaddr_in));
+        servaddr4.sin_family = AF_INET;
+        servaddr4.sin_port = htons (port);
+        if (0 != INADDR_ANY)
+          servaddr4.sin_addr.s_addr = htonl (INADDR_ANY);
+#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+        servaddr4.sin_len = sizeof (struct sockaddr_in);
 #endif
-	      servaddr = (struct sockaddr *) &servaddr6;
-	    }
-	  else
-#endif
-	    {
-	      memset (&servaddr4, 0, sizeof (struct sockaddr_in));
-	      servaddr4.sin_family = AF_INET;
-	      servaddr4.sin_port = htons (port);
-#if HAVE_SOCKADDR_IN_SIN_LEN
-	      servaddr4.sin_len = sizeof (struct sockaddr_in);
-#endif
-	      servaddr = (struct sockaddr *) &servaddr4;
-	    }
-	}
-      daemon->socket_fd = socket_fd;
-
-      if (0 != (flags & MHD_USE_IPv6))
-	{
+        servaddr = (struct sockaddr *) &servaddr4;
+      }
+    }
+    daemon->listen_fd = listen_fd;
+    if (0 != (*pflags & MHD_USE_IPv6))
+    {
 #ifdef IPPROTO_IPV6
 #ifdef IPV6_V6ONLY
-	  /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options"
-	     (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx);
-	     and may also be missing on older POSIX systems; good luck if you have any of those,
-	     your IPv6 socket may then also bind against IPv4 anyway... */
-#ifndef WINDOWS
-	  const int
-#else
-	  const char
-#endif
-            on = (MHD_USE_DUAL_STACK != (flags & MHD_USE_DUAL_STACK));
-	  if (0 > setsockopt (socket_fd,
-                              IPPROTO_IPV6, IPV6_V6ONLY,
-                              &on, sizeof (on)))
+      /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options"
+         (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx);
+         and may also be missing on older POSIX systems; good luck if you have any of those,
+         your IPv6 socket may then also bind against IPv4 anyway... */
+      const MHD_SCKT_OPT_BOOL_ v6_only =
+        (MHD_USE_DUAL_STACK != (*pflags & MHD_USE_DUAL_STACK));
+      if (0 > setsockopt (listen_fd,
+                          IPPROTO_IPV6, IPV6_V6ONLY,
+                          (const void *) &v6_only,
+                          sizeof (v6_only)))
       {
-#if HAVE_MESSAGES
-            MHD_DLOG (daemon,
-                      "setsockopt failed: %s\n",
-                      MHD_socket_last_strerr_ ());
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("setsockopt failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
 #endif
       }
 #endif
 #endif
-	}
-      if (-1 == bind (socket_fd, servaddr, addrlen))
-	{
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Failed to bind to port %u: %s\n",
-                    (unsigned int) port,
-                    MHD_socket_last_strerr_ ());
+    }
+    if (-1 == bind (listen_fd, servaddr, addrlen))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to bind to port %u: %s\n"),
+                (unsigned int) port,
+                MHD_socket_last_strerr_ ());
 #endif
-	  if (0 != MHD_socket_close_ (socket_fd))
-	    MHD_PANIC ("close failed\n");
-	  goto free_and_fail;
-	}
+      MHD_socket_close_chk_ (listen_fd);
+      goto free_and_fail;
+    }
 #ifdef TCP_FASTOPEN
-      if (0 != (flags & MHD_USE_TCP_FASTOPEN))
+    if (0 != (*pflags & MHD_USE_TCP_FASTOPEN))
+    {
+      if (0 == daemon->fastopen_queue_size)
+        daemon->fastopen_queue_size = MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT;
+      if (0 != setsockopt (listen_fd,
+                           IPPROTO_TCP,
+                           TCP_FASTOPEN,
+                           (const void *) &daemon->fastopen_queue_size,
+                           sizeof (daemon->fastopen_queue_size)))
       {
-        if (0 == daemon->fastopen_queue_size)
-          daemon->fastopen_queue_size = MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT;
-        if (0 != setsockopt (socket_fd,
-                             IPPROTO_TCP, TCP_FASTOPEN,
-                             &daemon->fastopen_queue_size,
-                             sizeof (daemon->fastopen_queue_size)))
-        {
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "setsockopt failed: %s\n",
-                    MHD_socket_last_strerr_ ());
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("setsockopt failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
 #endif
-        }
       }
-#endif
-#if EPOLL_SUPPORT
-      if (0 != (flags & MHD_USE_EPOLL_LINUX_ONLY))
-	{
-	  int sk_flags = fcntl (socket_fd, F_GETFL);
-	  if (0 != fcntl (socket_fd, F_SETFL, sk_flags | O_NONBLOCK))
-	    {
-#if HAVE_MESSAGES
-	      MHD_DLOG (daemon,
-			"Failed to make listen socket non-blocking: %s\n",
-			MHD_socket_last_strerr_ ());
-#endif
-	      if (0 != MHD_socket_close_ (socket_fd))
-		MHD_PANIC ("close failed\n");
-	      goto free_and_fail;
-	    }
-	}
-#endif
-      if (listen (socket_fd, 32) < 0)
-	{
-#if HAVE_MESSAGES
-          MHD_DLOG (daemon,
-                    "Failed to listen for connections: %s\n",
-                    MHD_socket_last_strerr_ ());
-#endif
-	  if (0 != MHD_socket_close_ (socket_fd))
-	    MHD_PANIC ("close failed\n");
-	  goto free_and_fail;
-	}
     }
+#endif
+    if (listen (listen_fd,
+                (int) daemon->listen_backlog_size) < 0)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to listen for connections: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      MHD_socket_close_chk_ (listen_fd);
+      goto free_and_fail;
+    }
+  }
   else
-    {
-      socket_fd = daemon->socket_fd;
-    }
-#ifndef WINDOWS
-  if ( (socket_fd >= FD_SETSIZE) &&
-       (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL_LINUX_ONLY)) ) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "Socket descriptor larger than FD_SETSIZE: %d > %d\n",
-                socket_fd,
-                FD_SETSIZE);
+  {
+    listen_fd = daemon->listen_fd;
+  }
+
+#ifdef MHD_USE_GETSOCKNAME
+  if ( (0 == daemon->port) &&
+       (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) )
+  {   /* Get port number. */
+    struct sockaddr_storage bindaddr;
+
+    memset (&bindaddr,
+            0,
+            sizeof (struct sockaddr_storage));
+    addrlen = sizeof (struct sockaddr_storage);
+#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
+    bindaddr.ss_len = addrlen;
 #endif
-      if (0 != MHD_socket_close_ (socket_fd))
-	MHD_PANIC ("close failed\n");
+    if (0 != getsockname (listen_fd,
+                          (struct sockaddr *) &bindaddr,
+                          &addrlen))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to get listen port number: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif /* HAVE_MESSAGES */
+    }
+#ifdef MHD_POSIX_SOCKETS
+    else if (sizeof (bindaddr) < addrlen)
+    {
+      /* should be impossible with `struct sockaddr_storage` */
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to get listen port number " \
+                   "(`struct sockaddr_storage` too small!?).\n"));
+#endif /* HAVE_MESSAGES */
+    }
+#ifndef __linux__
+    else if (0 == addrlen)
+    {
+      /* Many non-Linux-based platforms return zero addrlen
+       * for AF_UNIX sockets */
+      daemon->port = 0;     /* special value for UNIX domain sockets */
+    }
+#endif /* __linux__ */
+#endif /* MHD_POSIX_SOCKETS */
+    else
+    {
+      switch (bindaddr.ss_family)
+      {
+      case AF_INET:
+        {
+          struct sockaddr_in *s4 = (struct sockaddr_in *) &bindaddr;
+
+          daemon->port = ntohs (s4->sin_port);
+          break;
+        }
+#ifdef HAVE_INET6
+      case AF_INET6:
+        {
+          struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &bindaddr;
+
+          daemon->port = ntohs (s6->sin6_port);
+          mhd_assert (0 != (*pflags & MHD_USE_IPv6));
+          break;
+        }
+#endif /* HAVE_INET6 */
+#ifdef AF_UNIX
+      case AF_UNIX:
+        daemon->port = 0;     /* special value for UNIX domain sockets */
+        break;
+#endif
+      default:
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Unknown address family!\n"));
+#endif
+        daemon->port = 0;     /* ugh */
+        break;
+      }
+    }
+  }
+#endif /* MHD_USE_GETSOCKNAME */
+
+  if (MHD_INVALID_SOCKET != listen_fd)
+  {
+    if (! MHD_socket_nonblocking_ (listen_fd))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to set nonblocking mode on listening socket: %s\n"),
+                MHD_socket_last_strerr_ ());
+#endif
+      if (0 != (*pflags & MHD_USE_EPOLL)
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+          || (daemon->worker_pool_size > 0)
+#endif
+          )
+      {
+        /* Accept must be non-blocking. Multiple children may wake up
+         * to handle a new connection, but only one will win the race.
+         * The others must immediately return. */
+        MHD_socket_close_chk_ (listen_fd);
+        goto free_and_fail;
+      }
+      daemon->listen_nonblk = false;
+    }
+    else
+      daemon->listen_nonblk = true;
+    if ( (! MHD_SCKT_FD_FITS_FDSET_ (listen_fd,
+                                     NULL)) &&
+         (0 == (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL)) ) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Listen socket descriptor (%d) is not " \
+                   "less than FD_SETSIZE (%d).\n"),
+                (int) listen_fd,
+                (int) FD_SETSIZE);
+#endif
+      MHD_socket_close_chk_ (listen_fd);
       goto free_and_fail;
     }
+  }
+  else
+    daemon->listen_nonblk = false; /* Actually listen socket does not exist */
+
+#ifdef EPOLL_SUPPORT
+  if ( (0 != (*pflags & MHD_USE_EPOLL))
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+       && (0 == daemon->worker_pool_size)
+#endif
+       )
+  {
+    if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Combining MHD_USE_THREAD_PER_CONNECTION and " \
+                   "MHD_USE_EPOLL is not supported.\n"));
+#endif
+      goto free_and_fail;
+    }
+    if (MHD_NO == setup_epoll_to_listen (daemon))
+      goto free_and_fail;
+  }
+#endif /* EPOLL_SUPPORT */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if (! MHD_mutex_init_ (&daemon->per_ip_connection_mutex))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("MHD failed to initialize IP connection limit mutex.\n"));
+#endif
+    if (MHD_INVALID_SOCKET != listen_fd)
+      MHD_socket_close_chk_ (listen_fd);
+    goto free_and_fail;
+  }
 #endif
 
-#if EPOLL_SUPPORT
-  if ( (0 != (flags & MHD_USE_EPOLL_LINUX_ONLY)) &&
-       (0 == daemon->worker_pool_size) &&
-       (0 == (daemon->options & MHD_USE_NO_LISTEN_SOCKET)) )
-    {
-      if (0 != (flags & MHD_USE_THREAD_PER_CONNECTION))
-	{
-#if HAVE_MESSAGES
-	  MHD_DLOG (daemon,
-		    "Combining MHD_USE_THREAD_PER_CONNECTION and MHD_USE_EPOLL_LINUX_ONLY is not supported.\n");
-#endif
-	  goto free_and_fail;
-	}
-      if (MHD_YES != setup_epoll_to_listen (daemon))
-	goto free_and_fail;
-    }
-#else
-  if (0 != (flags & MHD_USE_EPOLL_LINUX_ONLY))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"epoll is not supported on this platform by this build.\n");
-#endif
-      goto free_and_fail;
-    }
-#endif
-
-  if (MHD_YES != MHD_mutex_create_ (&daemon->per_ip_connection_mutex))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-               "MHD failed to initialize IP connection limit mutex\n");
-#endif
-      if ( (MHD_INVALID_SOCKET != socket_fd) &&
-	   (0 != MHD_socket_close_ (socket_fd)) )
-	MHD_PANIC ("close failed\n");
-      goto free_and_fail;
-    }
-  if (MHD_YES != MHD_mutex_create_ (&daemon->cleanup_connection_mutex))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-               "MHD failed to initialize IP connection limit mutex\n");
-#endif
-      (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
-      if ( (MHD_INVALID_SOCKET != socket_fd) &&
-	   (0 != MHD_socket_close_ (socket_fd)) )
-	MHD_PANIC ("close failed\n");
-      goto free_and_fail;
-    }
-
-#if HTTPS_SUPPORT
+#ifdef HTTPS_SUPPORT
   /* initialize HTTPS daemon certificate aspects & send / recv functions */
-  if ((0 != (flags & MHD_USE_SSL)) && (0 != MHD_TLS_init (daemon)))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-		"Failed to initialize TLS support\n");
+  if ( (0 != (*pflags & MHD_USE_TLS)) &&
+       (0 != MHD_TLS_init (daemon)) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Failed to initialize TLS support.\n"));
 #endif
-      if ( (MHD_INVALID_SOCKET != socket_fd) &&
-	   (0 != MHD_socket_close_ (socket_fd)) )
-	MHD_PANIC ("close failed\n");
-      (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
-      (void) MHD_mutex_destroy_ (&daemon->per_ip_connection_mutex);
-      goto free_and_fail;
+    if (MHD_INVALID_SOCKET != listen_fd)
+      MHD_socket_close_chk_ (listen_fd);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+#endif
+    goto free_and_fail;
+  }
+#endif /* HTTPS_SUPPORT */
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  /* Start threads if requested by parameters */
+  if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD))
+  {
+    /* Internal thread (or threads) is used.
+     * Make sure that MHD will be able to communicate with threads. */
+    /* If using a thread pool ITC will be initialised later
+     * for each individual worker thread. */
+#ifdef HAVE_LISTEN_SHUTDOWN
+    mhd_assert ((1 < daemon->worker_pool_size) || \
+                (MHD_ITC_IS_VALID_ (daemon->itc)) || \
+                (MHD_INVALID_SOCKET != daemon->listen_fd));
+#else  /* ! HAVE_LISTEN_SHUTDOWN */
+    mhd_assert ((1 < daemon->worker_pool_size) || \
+                (MHD_ITC_IS_VALID_ (daemon->itc)));
+#endif /* ! HAVE_LISTEN_SHUTDOWN */
+    if (0 == daemon->worker_pool_size)
+    {
+      if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Failed to initialise internal lists mutex.\n"));
+#endif
+        MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+        if (MHD_INVALID_SOCKET != listen_fd)
+          MHD_socket_close_chk_ (listen_fd);
+        goto free_and_fail;
+      }
+      if (! MHD_mutex_init_ (&daemon->new_connections_mutex))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Failed to initialise mutex.\n"));
+#endif
+        MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+        MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
+        if (MHD_INVALID_SOCKET != listen_fd)
+          MHD_socket_close_chk_ (listen_fd);
+        goto free_and_fail;
+      }
+      if (! MHD_create_named_thread_ (&daemon->pid,
+                                      (*pflags
+                                       & MHD_USE_THREAD_PER_CONNECTION) ?
+                                      "MHD-listen" : "MHD-single",
+                                      daemon->thread_stack_size,
+                                      &MHD_polling_thread,
+                                      daemon) )
+      {
+#ifdef HAVE_MESSAGES
+#ifdef EAGAIN
+        if (EAGAIN == errno)
+          MHD_DLOG (daemon,
+                    _ ("Failed to create a new thread because it would have " \
+                       "exceeded the system limit on the number of threads or " \
+                       "no system resources available.\n"));
+        else
+#endif /* EAGAIN */
+        MHD_DLOG (daemon,
+                  _ ("Failed to create listen thread: %s\n"),
+                  MHD_strerror_ (errno));
+#endif /* HAVE_MESSAGES */
+        MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex);
+        MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+        MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
+        if (MHD_INVALID_SOCKET != listen_fd)
+          MHD_socket_close_chk_ (listen_fd);
+        goto free_and_fail;
+      }
     }
-#endif
-  if ( ( (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) ||
-	 ( (0 != (flags & MHD_USE_SELECT_INTERNALLY)) &&
-	   (0 == daemon->worker_pool_size)) ) &&
-       (0 == (daemon->options & MHD_USE_NO_LISTEN_SOCKET)) &&
-       (0 != (res_thread_create =
-	      create_thread (&daemon->pid, daemon, &MHD_select_thread, daemon))))
+    else   /* 0 < daemon->worker_pool_size */
     {
-#if HAVE_MESSAGES
-      MHD_DLOG (daemon,
-                "Failed to create listen thread: %s\n",
-		MHD_strerror_ (res_thread_create));
-#endif
-      (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
-      (void) MHD_mutex_destroy_ (&daemon->per_ip_connection_mutex);
-      if ( (MHD_INVALID_SOCKET != socket_fd) &&
-	   (0 != MHD_socket_close_ (socket_fd)) )
-	MHD_PANIC ("close failed\n");
-      goto free_and_fail;
-    }
-  if ( (daemon->worker_pool_size > 0) &&
-       (0 == (daemon->options & MHD_USE_NO_LISTEN_SOCKET)) )
-    {
-#if !defined(WINDOWS) || defined(CYGWIN)
-      int sk_flags;
-#else
-      unsigned long sk_flags;
-#endif
-
       /* Coarse-grained count of connections per thread (note error
        * due to integer division). Also keep track of how many
        * connections are leftover after an equal split. */
@@ -4161,22 +7867,8 @@
       unsigned int leftover_conns = daemon->connection_limit
                                     % daemon->worker_pool_size;
 
-      i = 0; /* we need this in case fcntl or malloc fails */
-
-      /* Accept must be non-blocking. Multiple children may wake up
-       * to handle a new connection, but only one will win the race.
-       * The others must immediately return. */
-#if !defined(WINDOWS) || defined(CYGWIN)
-      sk_flags = fcntl (socket_fd, F_GETFL);
-      if (sk_flags < 0)
-        goto thread_failed;
-      if (0 != fcntl (socket_fd, F_SETFL, sk_flags | O_NONBLOCK))
-        goto thread_failed;
-#else
-      sk_flags = 1;
-      if (SOCKET_ERROR == ioctlsocket (socket_fd, FIONBIO, &sk_flags))
-        goto thread_failed;
-#endif /* WINDOWS && !CYGWIN */
+      mhd_assert (2 <= daemon->worker_pool_size);
+      i = 0;     /* we need this in case fcntl or malloc fails */
 
       /* Allocate memory for pooled objects */
       daemon->worker_pool = malloc (sizeof (struct MHD_Daemon)
@@ -4186,83 +7878,164 @@
 
       /* Start the workers in the pool */
       for (i = 0; i < daemon->worker_pool_size; ++i)
+      {
+        /* Create copy of the Daemon object for each worker */
+        struct MHD_Daemon *d = &daemon->worker_pool[i];
+
+        memcpy (d, daemon, sizeof (struct MHD_Daemon));
+        /* Adjust polling params for worker daemons; note that memcpy()
+           has already copied MHD_USE_INTERNAL_POLLING_THREAD thread mode into
+           the worker threads. */
+        d->master = daemon;
+        d->worker_pool_size = 0;
+        d->worker_pool = NULL;
+        if (! MHD_mutex_init_ (&d->cleanup_connection_mutex))
         {
-          /* Create copy of the Daemon object for each worker */
-          struct MHD_Daemon *d = &daemon->worker_pool[i];
-
-          memcpy (d, daemon, sizeof (struct MHD_Daemon));
-          /* Adjust pooling params for worker daemons; note that memcpy()
-             has already copied MHD_USE_SELECT_INTERNALLY thread model into
-             the worker threads. */
-          d->master = daemon;
-          d->worker_pool_size = 0;
-          d->worker_pool = NULL;
-
-          if ( (MHD_USE_SUSPEND_RESUME == (flags & MHD_USE_SUSPEND_RESUME)) &&
-               (0 != MHD_pipe_ (d->wpipe)) )
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "Failed to create worker control pipe: %s\n",
-                        MHD_pipe_last_strerror_() );
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Failed to initialise internal lists mutex.\n"));
 #endif
-              goto thread_failed;
-            }
-#ifndef WINDOWS
-          if ( (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL_LINUX_ONLY))) &&
-               (MHD_USE_SUSPEND_RESUME == (flags & MHD_USE_SUSPEND_RESUME)) &&
-               (d->wpipe[0] >= FD_SETSIZE) )
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "file descriptor for worker control pipe exceeds maximum value\n");
-#endif
-              if (0 != MHD_pipe_close_ (d->wpipe[0]))
-                MHD_PANIC ("close failed\n");
-              if (0 != MHD_pipe_close_ (d->wpipe[1]))
-                MHD_PANIC ("close failed\n");
-              goto thread_failed;
-            }
-#endif
-
-          /* Divide available connections evenly amongst the threads.
-           * Thread indexes in [0, leftover_conns) each get one of the
-           * leftover connections. */
-          d->connection_limit = conns_per_thread;
-          if (i < leftover_conns)
-            ++d->connection_limit;
-#if EPOLL_SUPPORT
-	  if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-	       (MHD_YES != setup_epoll_to_listen (d)) )
-	    goto thread_failed;
-#endif
-          /* Must init cleanup connection mutex for each worker */
-          if (MHD_YES != MHD_mutex_create_ (&d->cleanup_connection_mutex))
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                       "MHD failed to initialize cleanup connection mutex for thread worker %d\n", i);
-#endif
-              goto thread_failed;
-            }
-
-          /* Spawn the worker thread */
-          if (0 != (res_thread_create =
-		    create_thread (&d->pid, daemon, &MHD_select_thread, d)))
-            {
-#if HAVE_MESSAGES
-              MHD_DLOG (daemon,
-                        "Failed to create pool thread: %s\n",
-			MHD_strerror_ (res_thread_create));
-#endif
-              /* Free memory for this worker; cleanup below handles
-               * all previously-created workers. */
-              (void) MHD_mutex_destroy_ (&d->cleanup_connection_mutex);
-              goto thread_failed;
-            }
+          goto thread_failed;
         }
+        if (! MHD_mutex_init_ (&d->new_connections_mutex))
+        {
+#ifdef HAVE_MESSAGES
+          MHD_DLOG (daemon,
+                    _ ("Failed to initialise mutex.\n"));
+#endif
+          MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+          goto thread_failed;
+        }
+        if (0 != (*pflags & MHD_USE_ITC))
+        {
+          if (! MHD_itc_init_ (d->itc))
+          {
+#ifdef HAVE_MESSAGES
+            MHD_DLOG (daemon,
+                      _ ("Failed to create worker inter-thread " \
+                         "communication channel: %s\n"),
+                      MHD_itc_last_strerror_ () );
+#endif
+            MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
+            MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+            goto thread_failed;
+          }
+          if ( (0 == (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL))) &&
+               (! MHD_SCKT_FD_FITS_FDSET_ (MHD_itc_r_fd_ (d->itc),
+                                           NULL)) )
+          {
+#ifdef HAVE_MESSAGES
+            MHD_DLOG (daemon,
+                      _ ("File descriptor for worker inter-thread " \
+                         "communication channel exceeds maximum value.\n"));
+#endif
+            MHD_itc_destroy_chk_ (d->itc);
+            MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
+            MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+            goto thread_failed;
+          }
+        }
+        else
+          MHD_itc_set_invalid_ (d->itc);
+
+#ifdef HAVE_LISTEN_SHUTDOWN
+        mhd_assert ((MHD_ITC_IS_VALID_ (d->itc)) || \
+                    (MHD_INVALID_SOCKET != d->listen_fd));
+#else  /* ! HAVE_LISTEN_SHUTDOWN */
+        mhd_assert (MHD_ITC_IS_VALID_ (d->itc));
+#endif /* ! HAVE_LISTEN_SHUTDOWN */
+
+        /* Divide available connections evenly amongst the threads.
+         * Thread indexes in [0, leftover_conns) each get one of the
+         * leftover connections. */
+        d->connection_limit = conns_per_thread;
+        if (i < leftover_conns)
+          ++d->connection_limit;
+#ifdef EPOLL_SUPPORT
+        if ( (0 != (*pflags & MHD_USE_EPOLL)) &&
+             (MHD_NO == setup_epoll_to_listen (d)) )
+        {
+          if (MHD_ITC_IS_VALID_ (d->itc))
+            MHD_itc_destroy_chk_ (d->itc);
+          MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
+          MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+          goto thread_failed;
+        }
+#endif
+        /* Some members must be used only in master daemon */
+#if defined(MHD_USE_THREADS)
+        memset (&d->per_ip_connection_mutex, 0x7F,
+                sizeof(d->per_ip_connection_mutex));
+#endif /* MHD_USE_THREADS */
+#ifdef DAUTH_SUPPORT
+        d->nnc = NULL;
+        d->nonce_nc_size = 0;
+        d->digest_auth_random_copy = NULL;
+#if defined(MHD_USE_THREADS)
+        memset (&d->nnc_lock, 0x7F, sizeof(d->nnc_lock));
+#endif /* MHD_USE_THREADS */
+#endif /* DAUTH_SUPPORT */
+
+        /* Spawn the worker thread */
+        if (! MHD_create_named_thread_ (&d->pid,
+                                        "MHD-worker",
+                                        daemon->thread_stack_size,
+                                        &MHD_polling_thread,
+                                        d))
+        {
+#ifdef HAVE_MESSAGES
+#ifdef EAGAIN
+          if (EAGAIN == errno)
+            MHD_DLOG (daemon,
+                      _ ("Failed to create a new pool thread because it would " \
+                         "have exceeded the system limit on the number of " \
+                         "threads or no system resources available.\n"));
+          else
+#endif /* EAGAIN */
+          MHD_DLOG (daemon,
+                    _ ("Failed to create pool thread: %s\n"),
+                    MHD_strerror_ (errno));
+#endif
+          /* Free memory for this worker; cleanup below handles
+           * all previously-created workers. */
+          MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+          if (MHD_ITC_IS_VALID_ (d->itc))
+            MHD_itc_destroy_chk_ (d->itc);
+          MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
+          MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
+          goto thread_failed;
+        }
+      }
     }
-#if HTTPS_SUPPORT
+  }
+  else
+  { /* Daemon without internal threads */
+    if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to initialise internal lists mutex.\n"));
+#endif
+      MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+      if (MHD_INVALID_SOCKET != listen_fd)
+        MHD_socket_close_chk_ (listen_fd);
+      goto free_and_fail;
+    }
+    if (! MHD_mutex_init_ (&daemon->new_connections_mutex))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to initialise mutex.\n"));
+#endif
+      MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
+      MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+      if (MHD_INVALID_SOCKET != listen_fd)
+        MHD_socket_close_chk_ (listen_fd);
+      goto free_and_fail;
+    }
+  }
+#endif
+#ifdef HTTPS_SUPPORT
   /* API promises to never use the password after initialization,
      so we additionally NULL it here to not deref a dangling pointer. */
   daemon->https_key_password = NULL;
@@ -4270,22 +8043,21 @@
 
   return daemon;
 
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
 thread_failed:
   /* If no worker threads created, then shut down normally. Calling
      MHD_stop_daemon (as we do below) doesn't work here since it
      assumes a 0-sized thread pool means we had been in the default
-     MHD_USE_SELECT_INTERNALLY mode. */
+     MHD_USE_INTERNAL_POLLING_THREAD mode. */
   if (0 == i)
-    {
-      if ( (MHD_INVALID_SOCKET != socket_fd) &&
-	   (0 != MHD_socket_close_ (socket_fd)) )
-	MHD_PANIC ("close failed\n");
-      (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
-      (void) MHD_mutex_destroy_ (&daemon->per_ip_connection_mutex);
-      if (NULL != daemon->worker_pool)
-        free (daemon->worker_pool);
-      goto free_and_fail;
-    }
+  {
+    if (MHD_INVALID_SOCKET != listen_fd)
+      MHD_socket_close_chk_ (listen_fd);
+    MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+    if (NULL != daemon->worker_pool)
+      free (daemon->worker_pool);
+    goto free_and_fail;
+  }
 
   /* Shutdown worker threads we've already created. Pretend
      as though we had fully initialized our daemon, but
@@ -4294,60 +8066,59 @@
   daemon->worker_pool_size = i;
   MHD_stop_daemon (daemon);
   return NULL;
+#endif
 
- free_and_fail:
+free_and_fail:
   /* clean up basic memory state in 'daemon' and return NULL to
      indicate failure */
-#if EPOLL_SUPPORT
+#ifdef EPOLL_SUPPORT
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if (daemon->upgrade_fd_in_epoll)
+  {
+    if (0 != epoll_ctl (daemon->epoll_fd,
+                        EPOLL_CTL_DEL,
+                        daemon->epoll_upgrade_fd,
+                        NULL))
+      MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
+    daemon->upgrade_fd_in_epoll = false;
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
   if (-1 != daemon->epoll_fd)
     close (daemon->epoll_fd);
-#endif
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  if (-1 != daemon->epoll_upgrade_fd)
+    close (daemon->epoll_upgrade_fd);
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
 #ifdef DAUTH_SUPPORT
+  free (daemon->digest_auth_random_copy);
   free (daemon->nnc);
-  (void) MHD_mutex_destroy_ (&daemon->nnc_lock);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_destroy_chk_ (&daemon->nnc_lock);
 #endif
+#endif
+#ifdef HTTPS_SUPPORT
+  if (0 != (*pflags & MHD_USE_TLS))
+  {
+    gnutls_priority_deinit (daemon->priority_cache);
+    if (daemon->x509_cred)
+      gnutls_certificate_free_credentials (daemon->x509_cred);
+    if (daemon->psk_cred)
+      gnutls_psk_free_server_credentials (daemon->psk_cred);
+  }
+#endif /* HTTPS_SUPPORT */
+  if (MHD_ITC_IS_VALID_ (daemon->itc))
+    MHD_itc_destroy_chk_ (daemon->itc);
   free (daemon);
   return NULL;
 }
 
 
 /**
- * Close the given connection, remove it from all of its
- * DLLs and move it into the cleanup queue.
- *
- * @param pos connection to move to cleanup
- */
-static void
-close_connection (struct MHD_Connection *pos)
-{
-  struct MHD_Daemon *daemon = pos->daemon;
-
-  MHD_connection_close (pos,
-			MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN);
-  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
-    return; /* must let thread to the rest */
-  if (pos->connection_timeout == pos->daemon->connection_timeout)
-    XDLL_remove (daemon->normal_timeout_head,
-		 daemon->normal_timeout_tail,
-		 pos);
-  else
-    XDLL_remove (daemon->manual_timeout_head,
-		 daemon->manual_timeout_tail,
-		 pos);
-  DLL_remove (daemon->connections_head,
-	      daemon->connections_tail,
-	      pos);
-  pos->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP;
-  DLL_insert (daemon->cleanup_head,
-	      daemon->cleanup_tail,
-	      pos);
-}
-
-
-/**
- * Close all connections for the daemon; must only be called after
- * all of the threads have been joined and there is no more concurrent
- * activity on the connection lists.
+ * Close all connections for the daemon.
+ * Must only be called when MHD_Daemon::shutdown was set to true.
+ * @remark To be called only from thread that process
+ * daemon's select()/poll()/etc.
  *
  * @param daemon daemon to close down
  */
@@ -4355,219 +8126,386 @@
 close_all_connections (struct MHD_Daemon *daemon)
 {
   struct MHD_Connection *pos;
+  const bool used_thr_p_c = (0 != (daemon->options
+                                   & MHD_USE_THREAD_PER_CONNECTION));
+#ifdef UPGRADE_SUPPORT
+  const bool upg_allowed = (0 != (daemon->options & MHD_ALLOW_UPGRADE));
+#endif /* UPGRADE_SUPPORT */
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  struct MHD_UpgradeResponseHandle *urh;
+  struct MHD_UpgradeResponseHandle *urhn;
+  const bool used_tls = (0 != (daemon->options & MHD_USE_TLS));
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
 
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) || \
+               MHD_thread_ID_match_current_ (daemon->pid) );
+  mhd_assert (NULL == daemon->worker_pool);
+#endif /* MHD_USE_THREADS */
+  mhd_assert (daemon->shutdown);
+
+#ifdef MHD_USE_THREADS
+/* Remove externally added new connections that are
+   * not processed by the daemon thread. */
+  while (NULL != (pos = daemon->new_connections_tail))
+  {
+    mhd_assert (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD));
+    DLL_remove (daemon->new_connections_head,
+                daemon->new_connections_tail,
+                pos);
+    new_connection_close_ (daemon, pos);
+  }
+#endif /* MHD_USE_THREADS */
+
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+  /* give upgraded HTTPS connections a chance to finish */
+  /* 'daemon->urh_head' is not used in thread-per-connection mode. */
+  for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
+  {
+    mhd_assert (! used_thr_p_c);
+    urhn = urh->prev;
+    /* call generic forwarding function for passing data
+       with chance to detect that application is done. */
+    process_urh (urh);
+    MHD_connection_finish_forward_ (urh->connection);
+    urh->clean_ready = true;
+    /* Resuming will move connection to cleanup list. */
+    MHD_resume_connection (urh->connection);
+  }
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+
+  /* Give suspended connections a chance to resume to avoid
+     running into the check for there not being any suspended
+     connections left in case of a tight race with a recently
+     resumed connection. */
+  if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options))
+  {
+    daemon->resuming = true;   /* Force check for pending resume. */
+    resume_suspended_connections (daemon);
+  }
   /* first, make sure all threads are aware of shutdown; need to
      traverse DLLs in peace... */
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_lock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to acquire cleanup mutex\n");
-  for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
-    {
-      shutdown (pos->socket_fd,
-                (pos->read_closed == MHD_YES) ? SHUT_WR : SHUT_RDWR);
-#if WINDOWS
-      if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-           (MHD_INVALID_PIPE_ != daemon->wpipe[1]) &&
-           (1 != MHD_pipe_write_ (daemon->wpipe[1], "e", 1)) )
-        MHD_PANIC ("failed to signal shutdown via pipe");
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
 #endif
-    }
-  if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
-       (MHD_YES != MHD_mutex_unlock_ (&daemon->cleanup_connection_mutex)) )
-    MHD_PANIC ("Failed to release cleanup mutex\n");
+#ifdef UPGRADE_SUPPORT
+  if (upg_allowed)
+  {
+    struct MHD_Connection *susp;
 
-  /* now, collect threads from thread pool */
-  if (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION))
+    susp = daemon->suspended_connections_tail;
+    while (NULL != susp)
     {
-      for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
-	{
-	  if (0 != MHD_join_thread_ (pos->pid))
-	    MHD_PANIC ("Failed to join a thread\n");
-	  pos->thread_joined = MHD_YES;
-	}
+      if (NULL == susp->urh)     /* "Upgraded" connection? */
+        MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \
+                      "suspended connections.\n"));
+#ifdef HTTPS_SUPPORT
+      else if (used_tls &&
+               used_thr_p_c &&
+               (! susp->urh->clean_ready) )
+        shutdown (susp->urh->app.socket,
+                  SHUT_RDWR);     /* Wake thread by shutdown of app socket. */
+#endif /* HTTPS_SUPPORT */
+      else
+      {
+#ifdef HAVE_MESSAGES
+        if (! susp->urh->was_closed)
+          MHD_DLOG (daemon,
+                    _ ("Initiated daemon shutdown while \"upgraded\" " \
+                       "connection was not closed.\n"));
+#endif
+        susp->urh->was_closed = true;
+        /* If thread-per-connection is used, connection's thread
+         * may still processing "upgrade" (exiting). */
+        if (! used_thr_p_c)
+          MHD_connection_finish_forward_ (susp);
+        /* Do not use MHD_resume_connection() as mutex is
+         * already locked. */
+        susp->resuming = true;
+        daemon->resuming = true;
+      }
+      susp = susp->prev;
     }
+  }
+  else /* This 'else' is combined with next 'if' */
+#endif /* UPGRADE_SUPPORT */
+  if (NULL != daemon->suspended_connections_head)
+    MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \
+                  "suspended connections.\n"));
+#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
+#ifdef MHD_USE_THREADS
+  if (upg_allowed && used_tls && used_thr_p_c)
+  {
+    /* "Upgraded" threads may be running in parallel. Connection will not be
+     * moved to the "cleanup list" until connection's thread finishes.
+     * We must ensure that all "upgraded" connections are finished otherwise
+     * connection may stay in "suspended" list and will not be cleaned. */
+    for (pos = daemon->suspended_connections_tail; NULL != pos; pos = pos->prev)
+    {
+      /* Any connection found here is "upgraded" connection, normal suspended
+       * connections are already removed from this list. */
+      mhd_assert (NULL != pos->urh);
+      if (! pos->thread_joined)
+      {
+        /* While "cleanup" list is not manipulated by "upgraded"
+         * connection, "cleanup" mutex is required for call of
+         * MHD_resume_connection() during finishing of "upgraded"
+         * thread. */
+        MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+        if (! MHD_join_thread_ (pos->pid.handle))
+          MHD_PANIC (_ ("Failed to join a thread.\n"));
+        pos->thread_joined = true;
+        MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+      }
+    }
+  }
+#endif /* MHD_USE_THREADS */
+#endif
+  for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev)
+  {
+    shutdown (pos->socket_fd,
+              SHUT_RDWR);
+#ifdef MHD_WINSOCK_SOCKETS
+    if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
+         (MHD_ITC_IS_VALID_ (daemon->itc)) &&
+         (! MHD_itc_activate_ (daemon->itc, "e")) )
+      MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \
+                    "communication channel.\n"));
+#endif
+  }
 
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  /* now, collect per-connection threads */
+  if (used_thr_p_c)
+  {
+    pos = daemon->connections_tail;
+    while (NULL != pos)
+    {
+      if (! pos->thread_joined)
+      {
+        MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+        if (! MHD_join_thread_ (pos->pid.handle))
+          MHD_PANIC (_ ("Failed to join a thread.\n"));
+        MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
+        pos->thread_joined = true;
+        /* The thread may have concurrently modified the DLL,
+           need to restart from the beginning */
+        pos = daemon->connections_tail;
+        continue;
+      }
+      pos = pos->prev;
+    }
+  }
+  MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
+#endif
+
+#ifdef UPGRADE_SUPPORT
+  /* Finished threads with "upgraded" connections need to be moved
+   * to cleanup list by resume_suspended_connections(). */
+  /* "Upgraded" connections that were not closed explicitly by
+   * application should be moved to cleanup list too. */
+  if (upg_allowed)
+  {
+    daemon->resuming = true;   /* Force check for pending resume. */
+    resume_suspended_connections (daemon);
+  }
+#endif /* UPGRADE_SUPPORT */
+
+  mhd_assert (NULL == daemon->suspended_connections_head);
   /* now that we're alone, move everyone to cleanup */
-  while (NULL != (pos = daemon->connections_head))
+  while (NULL != (pos = daemon->connections_tail))
+  {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    if ( (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) &&
+         (! pos->thread_joined) )
+      MHD_PANIC (_ ("Failed to join a thread.\n"));
+#endif
     close_connection (pos);
+  }
   MHD_cleanup_connections (daemon);
 }
 
 
-#if EPOLL_SUPPORT
-/**
- * Shutdown epoll()-event loop by adding 'wpipe' to its event set.
- *
- * @param daemon daemon of which the epoll() instance must be signalled
- */
-static void
-epoll_shutdown (struct MHD_Daemon *daemon)
-{
-  struct epoll_event event;
-
-  if (MHD_INVALID_PIPE_ == daemon->wpipe[1])
-    {
-      /* wpipe was required in this mode, how could this happen? */
-      MHD_PANIC ("Internal error\n");
-    }
-  event.events = EPOLLOUT;
-  event.data.ptr = NULL;
-  if (0 != epoll_ctl (daemon->epoll_fd,
-		      EPOLL_CTL_ADD,
-		      daemon->wpipe[1],
-		      &event))
-    MHD_PANIC ("Failed to add wpipe to epoll set to signal termination\n");
-}
-#endif
-
-
 /**
  * Shutdown an HTTP daemon.
  *
  * @param daemon daemon to stop
  * @ingroup event
  */
-void
+_MHD_EXTERN void
 MHD_stop_daemon (struct MHD_Daemon *daemon)
 {
   MHD_socket fd;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   unsigned int i;
+#endif
 
   if (NULL == daemon)
     return;
-  daemon->shutdown = MHD_YES;
-  fd = daemon->socket_fd;
-  daemon->socket_fd = MHD_INVALID_SOCKET;
-  /* Prepare workers for shutdown */
+  if ( (daemon->shutdown) && (NULL == daemon->master) )
+    MHD_PANIC (_ ("MHD_stop_daemon() was called twice."));
+  /* Slave daemons must be stopped by master daemon. */
+  mhd_assert ( (NULL == daemon->master) || (daemon->shutdown) );
+
+  daemon->shutdown = true;
+  if (daemon->was_quiesced)
+    fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */
+  else
+    fd = daemon->listen_fd;
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   if (NULL != daemon->worker_pool)
+  {   /* Master daemon with worker pool. */
+    mhd_assert (1 < daemon->worker_pool_size);
+    mhd_assert (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD));
+
+    /* Let workers shutdown in parallel. */
+    for (i = 0; i < daemon->worker_pool_size; ++i)
     {
-      /* MHD_USE_NO_LISTEN_SOCKET disables thread pools, hence we need to check */
-      for (i = 0; i < daemon->worker_pool_size; ++i)
-	{
-	  daemon->worker_pool[i].shutdown = MHD_YES;
-	  daemon->worker_pool[i].socket_fd = MHD_INVALID_SOCKET;
-#if EPOLL_SUPPORT
-	  if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-	       (-1 != daemon->worker_pool[i].epoll_fd) &&
-	       (MHD_INVALID_SOCKET == fd) )
-	    epoll_shutdown (&daemon->worker_pool[i]);
-#endif
-	}
-    }
-  if (MHD_INVALID_PIPE_ != daemon->wpipe[1])
-    {
-      if (1 != MHD_pipe_write_ (daemon->wpipe[1], "e", 1))
-	MHD_PANIC ("failed to signal shutdown via pipe");
+      daemon->worker_pool[i].shutdown = true;
+      if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc))
+      {
+        if (! MHD_itc_activate_ (daemon->worker_pool[i].itc,
+                                 "e"))
+          MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \
+                        "communication channel.\n"));
+      }
+      else
+        mhd_assert (MHD_INVALID_SOCKET != fd);
     }
 #ifdef HAVE_LISTEN_SHUTDOWN
+    if (MHD_INVALID_SOCKET != fd)
+    {
+      (void) shutdown (fd,
+                       SHUT_RDWR);
+    }
+#endif /* HAVE_LISTEN_SHUTDOWN */
+    for (i = 0; i < daemon->worker_pool_size; ++i)
+    {
+      MHD_stop_daemon (&daemon->worker_pool[i]);
+    }
+    free (daemon->worker_pool);
+    mhd_assert (MHD_ITC_IS_INVALID_ (daemon->itc));
+#ifdef EPOLL_SUPPORT
+    mhd_assert (-1 == daemon->epoll_fd);
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    mhd_assert (-1 == daemon->epoll_upgrade_fd);
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
+  }
   else
-    {
-      /* fd might be MHD_INVALID_SOCKET here due to 'MHD_quiesce_daemon' */
-      if (MHD_INVALID_SOCKET != fd)
-	(void) shutdown (fd, SHUT_RDWR);
-    }
 #endif
-#if EPOLL_SUPPORT
-  if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-       (-1 != daemon->epoll_fd) &&
-       (MHD_INVALID_SOCKET == fd) )
-    epoll_shutdown (daemon);
-#endif
+  {   /* Worker daemon or single daemon. */
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    if (0 != (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD))
+    {     /* Worker daemon or single daemon with internal thread(s). */
+      mhd_assert (0 == daemon->worker_pool_size);
+      /* Separate thread(s) is used for polling sockets. */
+      if (MHD_ITC_IS_VALID_ (daemon->itc))
+      {
+        if (! MHD_itc_activate_ (daemon->itc,
+                                 "e"))
+          MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \
+                        "communication channel.\n"));
+      }
+      else
+      {
+#ifdef HAVE_LISTEN_SHUTDOWN
+        if (MHD_INVALID_SOCKET != fd)
+        {
+          if (NULL == daemon->master)
+            (void) shutdown (fd,
+                             SHUT_RDWR);
+        }
+        else
+#endif /* HAVE_LISTEN_SHUTDOWN */
+        mhd_assert (false); /* Should never happen */
+      }
 
-#if DEBUG_CLOSE
-#if HAVE_MESSAGES
-  MHD_DLOG (daemon,
-            "MHD listen socket shutdown\n");
-#endif
-#endif
-
-
-  /* Signal workers to stop and clean them up */
-  if (NULL != daemon->worker_pool)
-    {
-      /* MHD_USE_NO_LISTEN_SOCKET disables thread pools, hence we need to check */
-      for (i = 0; i < daemon->worker_pool_size; ++i)
-	{
-	  if (MHD_INVALID_PIPE_ != daemon->worker_pool[i].wpipe[1])
-	    {
-	      if (1 != MHD_pipe_write_ (daemon->worker_pool[i].wpipe[1], "e", 1))
-		MHD_PANIC ("failed to signal shutdown via pipe");
-	    }
-	  if (0 != MHD_join_thread_ (daemon->worker_pool[i].pid))
-	      MHD_PANIC ("Failed to join a thread\n");
-	  close_all_connections (&daemon->worker_pool[i]);
-	  (void) MHD_mutex_destroy_ (&daemon->worker_pool[i].cleanup_connection_mutex);
-#if EPOLL_SUPPORT
-	  if ( (-1 != daemon->worker_pool[i].epoll_fd) &&
-	       (0 != MHD_socket_close_ (daemon->worker_pool[i].epoll_fd)) )
-	    MHD_PANIC ("close failed\n");
-#endif
-          if ( (MHD_USE_SUSPEND_RESUME == (daemon->options & MHD_USE_SUSPEND_RESUME)) )
-            {
-              if (MHD_INVALID_PIPE_ != daemon->worker_pool[i].wpipe[1])
-                {
-	           if (0 != MHD_pipe_close_ (daemon->worker_pool[i].wpipe[0]))
-	             MHD_PANIC ("close failed\n");
-	           if (0 != MHD_pipe_close_ (daemon->worker_pool[i].wpipe[1]))
-	             MHD_PANIC ("close failed\n");
-                }
-	    }
-	}
-      free (daemon->worker_pool);
+      if (! MHD_join_thread_ (daemon->pid.handle))
+      {
+        MHD_PANIC (_ ("Failed to join a thread.\n"));
+      }
+      /* close_all_connections() was called in daemon thread. */
     }
-  else
+    else
+#endif
     {
-      /* clean up master threads */
-      if ((0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)) ||
-	  ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY))
-	   && (0 == daemon->worker_pool_size)))
-	{
-	  if (0 != MHD_join_thread_ (daemon->pid))
-	    {
-	      MHD_PANIC ("Failed to join a thread\n");
-	    }
-	}
+      /* No internal threads are used for polling sockets. */
+      close_all_connections (daemon);
     }
-  close_all_connections (daemon);
-  if ( (MHD_INVALID_SOCKET != fd) &&
-       (0 != MHD_socket_close_ (fd)) )
-    MHD_PANIC ("close failed\n");
+    mhd_assert (NULL == daemon->connections_head);
+    mhd_assert (NULL == daemon->cleanup_head);
+    mhd_assert (NULL == daemon->suspended_connections_head);
+    mhd_assert (NULL == daemon->new_connections_head);
+#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
+    mhd_assert (NULL == daemon->urh_head);
+#endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */
 
-  /* TLS clean up */
-#if HTTPS_SUPPORT
-  if (0 != (daemon->options & MHD_USE_SSL))
+    if (MHD_ITC_IS_VALID_ (daemon->itc))
+      MHD_itc_destroy_chk_ (daemon->itc);
+
+#ifdef EPOLL_SUPPORT
+    if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+         (-1 != daemon->epoll_fd) )
+      MHD_socket_close_chk_ (daemon->epoll_fd);
+#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
+    if ( (0 != (daemon->options & MHD_USE_EPOLL)) &&
+         (-1 != daemon->epoll_upgrade_fd) )
+      MHD_socket_close_chk_ (daemon->epoll_upgrade_fd);
+#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
+    MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex);
+#endif
+  }
+
+  if (NULL == daemon->master)
+  {   /* Cleanup that should be done only one time in master/single daemon.
+       * Do not perform this cleanup in worker daemons. */
+
+    if (MHD_INVALID_SOCKET != fd)
+      MHD_socket_close_chk_ (fd);
+
+    /* TLS clean up */
+#ifdef HTTPS_SUPPORT
+    if (daemon->have_dhparams)
     {
-      MHD_TLS_deinit (daemon);
+      gnutls_dh_params_deinit (daemon->https_mem_dhparams);
+      daemon->have_dhparams = false;
     }
-#endif
-#if EPOLL_SUPPORT
-  if ( (0 != (daemon->options & MHD_USE_EPOLL_LINUX_ONLY)) &&
-       (-1 != daemon->epoll_fd) &&
-       (0 != MHD_socket_close_ (daemon->epoll_fd)) )
-    MHD_PANIC ("close failed\n");
-#endif
+    if (0 != (daemon->options & MHD_USE_TLS))
+    {
+      gnutls_priority_deinit (daemon->priority_cache);
+      if (daemon->x509_cred)
+        gnutls_certificate_free_credentials (daemon->x509_cred);
+      if (daemon->psk_cred)
+        gnutls_psk_free_server_credentials (daemon->psk_cred);
+    }
+#endif /* HTTPS_SUPPORT */
 
 #ifdef DAUTH_SUPPORT
-  free (daemon->nnc);
-  (void) MHD_mutex_destroy_ (&daemon->nnc_lock);
+    free (daemon->digest_auth_random_copy);
+    free (daemon->nnc);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_destroy_chk_ (&daemon->nnc_lock);
 #endif
-  (void) MHD_mutex_destroy_ (&daemon->per_ip_connection_mutex);
-  (void) MHD_mutex_destroy_ (&daemon->cleanup_connection_mutex);
-
-  if (MHD_INVALID_PIPE_ != daemon->wpipe[1])
-    {
-      if (0 != MHD_pipe_close_ (daemon->wpipe[0]))
-	MHD_PANIC ("close failed\n");
-      if (0 != MHD_pipe_close_ (daemon->wpipe[1]))
-	MHD_PANIC ("close failed\n");
-    }
-  free (daemon);
+#endif
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
+#endif
+    free (daemon);
+  }
 }
 
 
 /**
- * Obtain information about the given daemon
- * (not fully implemented!).
+ * Obtain information about the given daemon.
+ * The returned pointer is invalidated with the next call of this function or
+ * when the daemon is stopped.
  *
  * @param daemon what daemon to get information about
  * @param info_type what information is desired?
@@ -4576,65 +8514,61 @@
  *         (or if the @a info_type is unknown)
  * @ingroup specialized
  */
-const union MHD_DaemonInfo *
+_MHD_EXTERN const union MHD_DaemonInfo *
 MHD_get_daemon_info (struct MHD_Daemon *daemon,
-		     enum MHD_DaemonInfoType info_type,
-		     ...)
+                     enum MHD_DaemonInfoType info_type,
+                     ...)
 {
+  if (NULL == daemon)
+    return NULL;
   switch (info_type)
+  {
+  case MHD_DAEMON_INFO_KEY_SIZE:
+    return NULL;   /* no longer supported */
+  case MHD_DAEMON_INFO_MAC_KEY_SIZE:
+    return NULL;   /* no longer supported */
+  case MHD_DAEMON_INFO_LISTEN_FD:
+    daemon->daemon_info_dummy_listen_fd.listen_fd = daemon->listen_fd;
+    return &daemon->daemon_info_dummy_listen_fd;
+  case MHD_DAEMON_INFO_EPOLL_FD:
+#ifdef EPOLL_SUPPORT
+    daemon->daemon_info_dummy_epoll_fd.epoll_fd = daemon->epoll_fd;
+    return &daemon->daemon_info_dummy_epoll_fd;
+#else  /* ! EPOLL_SUPPORT */
+    return NULL;
+#endif /* ! EPOLL_SUPPORT */
+  case MHD_DAEMON_INFO_CURRENT_CONNECTIONS:
+    if (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD))
     {
-    case MHD_DAEMON_INFO_KEY_SIZE:
-      return NULL; /* no longer supported */
-    case MHD_DAEMON_INFO_MAC_KEY_SIZE:
-      return NULL; /* no longer supported */
-    case MHD_DAEMON_INFO_LISTEN_FD:
-      return (const union MHD_DaemonInfo *) &daemon->socket_fd;
-#if EPOLL_SUPPORT
-    case MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY:
-      return (const union MHD_DaemonInfo *) &daemon->epoll_fd;
-#endif
-    case MHD_DAEMON_INFO_CURRENT_CONNECTIONS:
+      /* Assume that MHD_run() in not called in other thread
+       * at the same time. */
       MHD_cleanup_connections (daemon);
-      if (daemon->worker_pool)
-        {
-          /* Collect the connection information stored in the workers. */
-          unsigned int i;
-
-          daemon->connections = 0;
-          for (i=0;i<daemon->worker_pool_size;i++)
-            {
-              MHD_cleanup_connections (&daemon->worker_pool[i]);
-              daemon->connections += daemon->worker_pool[i].connections;
-            }
-        }
-      return (const union MHD_DaemonInfo *) &daemon->connections;
-    default:
-      return NULL;
-    };
-}
-
-
-/**
- * Sets the global error handler to a different implementation.  @a cb
- * will only be called in the case of typically fatal, serious
- * internal consistency issues.  These issues should only arise in the
- * case of serious memory corruption or similar problems with the
- * architecture.  While @a cb is allowed to return and MHD will then
- * try to continue, this is never safe.
- *
- * The default implementation that is used if no panic function is set
- * simply prints an error message and calls `abort()`.  Alternative
- * implementations might call `exit()` or other similar functions.
- *
- * @param cb new error handler
- * @param cls passed to @a cb
- * @ingroup logging
- */
-void
-MHD_set_panic_func (MHD_PanicCallback cb, void *cls)
-{
-  mhd_panic = cb;
-  mhd_panic_cls = cls;
+    }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    else if (daemon->worker_pool)
+    {
+      unsigned int i;
+      /* Collect the connection information stored in the workers. */
+      daemon->connections = 0;
+      for (i = 0; i < daemon->worker_pool_size; i++)
+      {
+        /* FIXME: next line is thread-safe only if read is atomic. */
+        daemon->connections += daemon->worker_pool[i].connections;
+      }
+    }
+#endif
+    daemon->daemon_info_dummy_num_connections.num_connections
+      = daemon->connections;
+    return &daemon->daemon_info_dummy_num_connections;
+  case MHD_DAEMON_INFO_FLAGS:
+    daemon->daemon_info_dummy_flags.flags = daemon->options;
+    return &daemon->daemon_info_dummy_flags;
+  case MHD_DAEMON_INFO_BIND_PORT:
+    daemon->daemon_info_dummy_port.port = daemon->port;
+    return &daemon->daemon_info_dummy_port;
+  default:
+    return NULL;
+  }
 }
 
 
@@ -4644,7 +8578,7 @@
  * @return static version string, e.g. "0.9.9"
  * @ingroup specialized
  */
-const char *
+_MHD_EXTERN const char *
 MHD_get_version (void)
 {
 #ifdef PACKAGE_VERSION
@@ -4653,12 +8587,14 @@
   static char ver[12] = "\0\0\0\0\0\0\0\0\0\0\0";
   if (0 == ver[0])
   {
-    int res = MHD_snprintf_(ver, sizeof(ver), "%x.%x.%x",
-                            (((int)MHD_VERSION >> 24) & 0xFF),
-                            (((int)MHD_VERSION >> 16) & 0xFF),
-                            (((int)MHD_VERSION >> 8) & 0xFF));
-    if (0 >= res || sizeof(ver) <= res)
-      return "0.0.0"; /* Can't return real version*/
+    int res = MHD_snprintf_ (ver,
+                             sizeof(ver),
+                             "%x.%x.%x",
+                             (int) (((uint32_t) MHD_VERSION >> 24) & 0xFF),
+                             (int) (((uint32_t) MHD_VERSION >> 16) & 0xFF),
+                             (int) (((uint32_t) MHD_VERSION >> 8) & 0xFF));
+    if ((0 >= res) || (sizeof(ver) <= res))
+      return "0.0.0"; /* Can't return real version */
   }
   return ver;
 #endif /* !PACKAGE_VERSION */
@@ -4666,6 +8602,21 @@
 
 
 /**
+ * Obtain the version of this library as a binary value.
+ *
+ * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of
+ *         compiled MHD binary)
+ * @note Available since #MHD_VERSION 0x00097544
+ * @ingroup specialized
+ */
+_MHD_EXTERN uint32_t
+MHD_get_version_bin (void)
+{
+  return (uint32_t) MHD_VERSION;
+}
+
+
+/**
  * Get information about supported MHD features.
  * Indicate that MHD was compiled with or without support for
  * particular feature. Some features require additional support
@@ -4676,126 +8627,353 @@
  * feature is not supported or feature is unknown.
  * @ingroup specialized
  */
-_MHD_EXTERN int
-MHD_is_feature_supported(enum MHD_FEATURE feature)
+_MHD_EXTERN enum MHD_Result
+MHD_is_feature_supported (enum MHD_FEATURE feature)
 {
-  switch(feature)
-    {
-    case MHD_FEATURE_MESSGES:
-#if HAVE_MESSAGES
-      return MHD_YES;
+  switch (feature)
+  {
+  case MHD_FEATURE_MESSAGES:
+#ifdef HAVE_MESSAGES
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_SSL:
-#if HTTPS_SUPPORT
-      return MHD_YES;
-#else
-      return MHD_NO;
-#endif
-    case MHD_FEATURE_HTTPS_CERT_CALLBACK:
-      return MHD_NO;
-    case MHD_FEATURE_IPv6:
+  case MHD_FEATURE_TLS:
+#ifdef HTTPS_SUPPORT
+    return MHD_YES;
+#else  /* ! HTTPS_SUPPORT */
+    return MHD_NO;
+#endif  /* ! HTTPS_SUPPORT */
+  case MHD_FEATURE_HTTPS_CERT_CALLBACK:
+#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_MAJOR >= 3
+    return MHD_YES;
+#else  /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */
+    return MHD_NO;
+#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */
+  case MHD_FEATURE_HTTPS_CERT_CALLBACK2:
+#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030603
+    return MHD_YES;
+#else  /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */
+    return MHD_NO;
+#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */
+  case MHD_FEATURE_IPv6:
 #ifdef HAVE_INET6
-      return MHD_YES;
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_IPv6_ONLY:
+  case MHD_FEATURE_IPv6_ONLY:
 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
-      return MHD_YES;
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_POLL:
+  case MHD_FEATURE_POLL:
 #ifdef HAVE_POLL
-      return MHD_YES;
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_EPOLL:
-#if EPOLL_SUPPORT
-      return MHD_YES;
+  case MHD_FEATURE_EPOLL:
+#ifdef EPOLL_SUPPORT
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET:
+  case MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET:
 #ifdef HAVE_LISTEN_SHUTDOWN
-      return MHD_YES;
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_SOCKETPAIR:
-#ifdef MHD_DONT_USE_PIPES
-      return MHD_YES;
+  case MHD_FEATURE_SOCKETPAIR:
+#ifdef _MHD_ITC_SOCKETPAIR
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_TCP_FASTOPEN:
+  case MHD_FEATURE_TCP_FASTOPEN:
 #ifdef TCP_FASTOPEN
-      return MHD_YES;
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_BASIC_AUTH:
-#if BAUTH_SUPPORT
-      return MHD_YES;
+  case MHD_FEATURE_BASIC_AUTH:
+#ifdef BAUTH_SUPPORT
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_DIGEST_AUTH:
-#if DAUTH_SUPPORT
-      return MHD_YES;
+  case MHD_FEATURE_DIGEST_AUTH:
+#ifdef DAUTH_SUPPORT
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_POSTPROCESSOR:
-#if HAVE_POSTPROCESSOR
-      return MHD_YES;
+  case MHD_FEATURE_POSTPROCESSOR:
+#ifdef HAVE_POSTPROCESSOR
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return MHD_NO;
 #endif
-    case MHD_FEATURE_HTTPS_KEY_PASSWORD:
-#if HTTPS_SUPPORT
-      return MHD_YES;
+  case MHD_FEATURE_HTTPS_KEY_PASSWORD:
+#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030111
+    return MHD_YES;
+#else  /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */
+    return MHD_NO;
+#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */
+  case MHD_FEATURE_LARGE_FILE:
+#if defined(HAVE_PREAD64) || defined(_WIN32)
+    return MHD_YES;
+#elif defined(HAVE_PREAD)
+    return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES;
+#elif defined(HAVE_LSEEK64)
+    return MHD_YES;
 #else
-      return MHD_NO;
+    return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES;
 #endif
-    }
+  case MHD_FEATURE_THREAD_NAMES:
+#if defined(MHD_USE_THREAD_NAME_)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_UPGRADE:
+#if defined(UPGRADE_SUPPORT)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_RESPONSES_SHARED_FD:
+#if defined(HAVE_PREAD64) || defined(HAVE_PREAD) || defined(_WIN32)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_AUTODETECT_BIND_PORT:
+#ifdef MHD_USE_GETSOCKNAME
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_AUTOSUPPRESS_SIGPIPE:
+#if defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || \
+    ! defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_SENDFILE:
+#ifdef _MHD_HAVE_SENDFILE
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_THREADS:
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_HTTPS_COOKIE_PARSING:
+#if defined(COOKIE_SUPPORT)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_RFC2069:
+#ifdef DAUTH_SUPPORT
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_MD5:
+#if defined(DAUTH_SUPPORT) && defined(MHD_MD5_SUPPORT)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_SHA256:
+#if defined(DAUTH_SUPPORT) && defined(MHD_SHA256_SUPPORT)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_SHA512_256:
+#if defined(DAUTH_SUPPORT) && defined(MHD_SHA512_256_SUPPORT)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_AUTH_INT:
+#ifdef DAUTH_SUPPORT
+    return MHD_NO;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION:
+#ifdef DAUTH_SUPPORT
+    return MHD_NO;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DIGEST_AUTH_USERHASH:
+#ifdef DAUTH_SUPPORT
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_EXTERN_HASH:
+#if defined(MHD_MD5_TLSLIB) || defined(MHD_SHA256_TLSLIB)
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+  case MHD_FEATURE_DEBUG_BUILD:
+#ifdef _DEBUG
+    return MHD_YES;
+#else
+    return MHD_NO;
+#endif
+
+  default:
+    break;
+  }
   return MHD_NO;
 }
 
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#if defined(HTTPS_SUPPORT) && GCRYPT_VERSION_NUMBER < 0x010600
+#if defined(MHD_USE_POSIX_THREADS)
+GCRY_THREAD_OPTION_PTHREAD_IMPL;
+#elif defined(MHD_W32_MUTEX_)
+
+static int
+gcry_w32_mutex_init (void **ppmtx)
+{
+  *ppmtx = malloc (sizeof (MHD_mutex_));
+
+  if (NULL == *ppmtx)
+    return ENOMEM;
+  if (! MHD_mutex_init_ ((MHD_mutex_ *) *ppmtx))
+  {
+    free (*ppmtx);
+    *ppmtx = NULL;
+    return EPERM;
+  }
+
+  return 0;
+}
+
+
+static int
+gcry_w32_mutex_destroy (void **ppmtx)
+{
+  int res = (MHD_mutex_destroy_ ((MHD_mutex_ *) *ppmtx)) ? 0 : EINVAL;
+  free (*ppmtx);
+  return res;
+}
+
+
+static int
+gcry_w32_mutex_lock (void **ppmtx)
+{
+  return MHD_mutex_lock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL;
+}
+
+
+static int
+gcry_w32_mutex_unlock (void **ppmtx)
+{
+  return MHD_mutex_unlock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL;
+}
+
+
+static struct gcry_thread_cbs gcry_threads_w32 = {
+  (GCRY_THREAD_OPTION_USER | (GCRY_THREAD_OPTION_VERSION << 8)),
+  NULL, gcry_w32_mutex_init, gcry_w32_mutex_destroy,
+  gcry_w32_mutex_lock, gcry_w32_mutex_unlock,
+  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+};
+
+#endif /* defined(MHD_W32_MUTEX_) */
+#endif /* HTTPS_SUPPORT && GCRYPT_VERSION_NUMBER < 0x010600 */
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+
 /**
  * Initialize do setup work.
  */
-void MHD_init(void)
+void
+MHD_init (void)
 {
-  mhd_panic = &mhd_panic_std;
-  mhd_panic_cls = NULL;
-
-#ifdef _WIN32
+#if defined(MHD_WINSOCK_SOCKETS)
   WSADATA wsd;
-  if (0 != WSAStartup(MAKEWORD(2, 2), &wsd))
-    MHD_PANIC ("Failed to initialize winsock\n");
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  MHD_set_panic_func (NULL, NULL);
+
+#if defined(MHD_WINSOCK_SOCKETS)
+  if (0 != WSAStartup (MAKEWORD (2, 2), &wsd))
+    MHD_PANIC (_ ("Failed to initialize winsock.\n"));
   mhd_winsock_inited_ = 1;
-  if (2 != LOBYTE(wsd.wVersion) && 2 != HIBYTE(wsd.wVersion))
-    MHD_PANIC ("Winsock version 2.2 is not available\n");
+  if ((2 != LOBYTE (wsd.wVersion)) && (2 != HIBYTE (wsd.wVersion)))
+    MHD_PANIC (_ ("Winsock version 2.2 is not available.\n"));
+#endif /* MHD_WINSOCK_SOCKETS */
+#ifdef HTTPS_SUPPORT
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#if GCRYPT_VERSION_NUMBER < 0x010600
+#if GNUTLS_VERSION_NUMBER <= 0x020b00
+#if defined(MHD_USE_POSIX_THREADS)
+  if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS,
+                         &gcry_threads_pthread))
+    MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n"));
+#elif defined(MHD_W32_MUTEX_)
+  if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS,
+                         &gcry_threads_w32))
+    MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n"));
+#endif /* defined(MHD_W32_MUTEX_) */
+#endif /* GNUTLS_VERSION_NUMBER <= 0x020b00 */
+  gcry_check_version (NULL);
+#else
+  if (NULL == gcry_check_version ("1.6.0"))
+    MHD_PANIC (_ ("libgcrypt is too old. MHD was compiled for " \
+                  "libgcrypt 1.6.0 or newer.\n"));
 #endif
-#if HTTPS_SUPPORT
-  SSL_library_init();
-#endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  gnutls_global_init ();
+#endif /* HTTPS_SUPPORT */
+  MHD_monotonic_sec_counter_init ();
+  MHD_send_init_static_vars_ ();
+  MHD_init_mem_pools_ ();
+  /* Check whether sizes were correctly detected by configure */
+#ifdef _DEBUG
+  if (1)
+  {
+    struct timeval tv;
+    mhd_assert (sizeof(tv.tv_sec) == SIZEOF_STRUCT_TIMEVAL_TV_SEC);
+  }
+#endif /* _DEBUG */
+  mhd_assert (sizeof(uint64_t) == SIZEOF_UINT64_T);
 }
 
 
-void MHD_fini(void)
+void
+MHD_fini (void)
 {
-#ifdef _WIN32
+#ifdef HTTPS_SUPPORT
+  gnutls_global_deinit ();
+#endif /* HTTPS_SUPPORT */
+#if defined(MHD_WINSOCK_SOCKETS)
   if (mhd_winsock_inited_)
-    WSACleanup();
-#endif
+    WSACleanup ();
+#endif /* MHD_WINSOCK_SOCKETS */
+  MHD_monotonic_sec_counter_finish ();
 }
 
-_SET_INIT_AND_DEINIT_FUNCS(MHD_init, MHD_fini);
+
+#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
+_SET_INIT_AND_DEINIT_FUNCS (MHD_init, MHD_fini);
+#endif /* _AUTOINIT_FUNCS_ARE_SUPPORTED */
 
 /* end of daemon.c */
diff --git a/src/microhttpd/digestauth.c b/src/microhttpd/digestauth.c
index 9c3fe8c..5505118 100644
--- a/src/microhttpd/digestauth.c
+++ b/src/microhttpd/digestauth.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2010, 2011, 2012, 2015, 2018 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,25 +22,134 @@
  * @brief Implements HTTP digest authentication
  * @author Amr Ali
  * @author Matthieu Speder
+ * @author Christian Grothoff (RFC 7616 support)
+ * @author Karlson2k (Evgeny Grin) (fixes, new API, improvements, large rewrite,
+ *                                  many RFC 7616 features implementation,
+ *                                  old RFC 2069 support)
  */
+#include "digestauth.h"
+#include "gen_auth.h"
 #include "platform.h"
-#include <limits.h>
+#include "mhd_limits.h"
 #include "internal.h"
-#include "md5.h"
+#include "response.h"
+#ifdef MHD_MD5_SUPPORT
+#  include "mhd_md5_wrap.h"
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+#  include "mhd_sha256_wrap.h"
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+#  include "sha512_256.h"
+#endif /* MHD_SHA512_256_SUPPORT */
+#include "mhd_locks.h"
+#include "mhd_mono_clock.h"
+#include "mhd_str.h"
+#include "mhd_compat.h"
+#include "mhd_bithelpers.h"
+#include "mhd_assert.h"
 
-#if defined(_WIN32) && defined(MHD_W32_MUTEX_)
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN 1
-#endif /* !WIN32_LEAN_AND_MEAN */
-#include <windows.h>
-#endif /* _WIN32 && MHD_W32_MUTEX_ */
-
-#define HASH_MD5_HEX_LEN (2 * MD5_DIGEST_SIZE)
 
 /**
- * Beginning string for any valid Digest authentication header.
+ * Allow re-use of the nonce-nc map array slot after #REUSE_TIMEOUT seconds,
+ * if this slot is needed for the new nonce, while the old nonce was not used
+ * even one time by the client.
+ * Typically clients immediately use generated nonce for new request.
  */
-#define _BASE		"Digest "
+#define REUSE_TIMEOUT 30
+
+/**
+ * The maximum value of artificial timestamp difference to avoid clashes.
+ * The value must be suitable for bitwise AND operation.
+ */
+#define DAUTH_JUMPBACK_MAX (0x7F)
+
+
+/**
+ * 48 bit value in bytes
+ */
+#define TIMESTAMP_BIN_SIZE (48 / 8)
+
+
+/**
+ * Trim value to the TIMESTAMP_BIN_SIZE size
+ */
+#define TRIM_TO_TIMESTAMP(value) \
+  ((value) & ((UINT64_C (1) << (TIMESTAMP_BIN_SIZE * 8)) - 1))
+
+
+/**
+ * The printed timestamp size in chars
+ */
+#define TIMESTAMP_CHARS_LEN (TIMESTAMP_BIN_SIZE * 2)
+
+
+/**
+ * Standard server nonce length, not including terminating null,
+ *
+ * @param digest_size digest size
+ */
+#define NONCE_STD_LEN(digest_size) \
+  ((digest_size) * 2 + TIMESTAMP_CHARS_LEN)
+
+
+#ifdef MHD_SHA512_256_SUPPORT
+/**
+ * Maximum size of any digest hash supported by MHD.
+ * (SHA-512/256 > MD5).
+ */
+#define MAX_DIGEST SHA512_256_DIGEST_SIZE
+
+/**
+ * The common size of SHA-256 digest and SHA-512/256 digest
+ */
+#define SHA256_SHA512_256_DIGEST_SIZE SHA512_256_DIGEST_SIZE
+#elif defined(MHD_SHA256_SUPPORT)
+/**
+ * Maximum size of any digest hash supported by MHD.
+ * (SHA-256 > MD5).
+ */
+#define MAX_DIGEST SHA256_DIGEST_SIZE
+
+/**
+ * The common size of SHA-256 digest and SHA-512/256 digest
+ */
+#define SHA256_SHA512_256_DIGEST_SIZE SHA256_DIGEST_SIZE
+#elif defined(MHD_MD5_SUPPORT)
+/**
+ * Maximum size of any digest hash supported by MHD.
+ */
+#define MAX_DIGEST MD5_DIGEST_SIZE
+#else  /* ! MHD_MD5_SUPPORT */
+#error At least one hashing algorithm must be enabled
+#endif /* ! MHD_MD5_SUPPORT */
+
+
+/**
+ * Macro to avoid using VLAs if the compiler does not support them.
+ */
+#ifndef HAVE_C_VARARRAYS
+/**
+ * Return #MAX_DIGEST.
+ *
+ * @param n length of the digest to be used for a VLA
+ */
+#define VLA_ARRAY_LEN_DIGEST(n) (MAX_DIGEST)
+
+#else
+/**
+ * Return @a n.
+ *
+ * @param n length of the digest to be used for a VLA
+ */
+#define VLA_ARRAY_LEN_DIGEST(n) (n)
+#endif
+
+/**
+ * Check that @a n is below #MAX_DIGEST
+ */
+#define VLA_CHECK_LEN_DIGEST(n) \
+  do { if ((n) > MAX_DIGEST) MHD_PANIC (_ ("VLA too big.\n")); } while (0)
 
 /**
  * Maximum length of a username for digest authentication.
@@ -54,413 +164,2032 @@
 /**
  * Maximum length of the response in digest authentication.
  */
-#define MAX_AUTH_RESPONSE_LENGTH 128
+#define MAX_AUTH_RESPONSE_LENGTH (MAX_DIGEST * 2)
+
+/**
+ * The required prefix of parameter with the extended notation
+ */
+#define MHD_DAUTH_EXT_PARAM_PREFIX "UTF-8'"
+
+/**
+ * The minimal size of the prefix for parameter with the extended notation
+ */
+#define MHD_DAUTH_EXT_PARAM_MIN_LEN \
+  MHD_STATICSTR_LEN_ (MHD_DAUTH_EXT_PARAM_PREFIX "'")
+
+/**
+ * The result of nonce-nc map array check.
+ */
+enum MHD_CheckNonceNC_
+{
+  /**
+   * The nonce and NC are OK (valid and NC was not used before).
+   */
+  MHD_CHECK_NONCENC_OK = MHD_DAUTH_OK,
+
+  /**
+   * The 'nonce' was overwritten with newer 'nonce' in the same slot or
+   * NC was already used.
+   * The validity of the 'nonce' was not be checked.
+   */
+  MHD_CHECK_NONCENC_STALE = MHD_DAUTH_NONCE_STALE,
+
+  /**
+   * The 'nonce' is wrong, it was not generated before.
+   */
+  MHD_CHECK_NONCENC_WRONG = MHD_DAUTH_NONCE_WRONG,
+};
 
 
 /**
- * convert bin to hex
- *
- * @param bin binary data
- * @param len number of bytes in bin
- * @param hex pointer to len*2+1 bytes
+ * Get base hash calculation algorithm from #MHD_DigestAuthAlgo3 value.
+ * @param algo3 the MHD_DigestAuthAlgo3 value
+ * @return the base hash calculation algorithm
  */
-static void
-cvthex (const unsigned char *bin,
-	size_t len,
-	char *hex)
+_MHD_static_inline enum MHD_DigestBaseAlgo
+get_base_digest_algo (enum MHD_DigestAuthAlgo3 algo3)
 {
-  size_t i;
-  unsigned int j;
+  unsigned int base_algo;
 
-  for (i = 0; i < len; ++i)
-    {
-      j = (bin[i] >> 4) & 0x0f;
-      hex[i * 2] = j <= 9 ? (j + '0') : (j + 'a' - 10);
-      j = bin[i] & 0x0f;
-      hex[i * 2 + 1] = j <= 9 ? (j + '0') : (j + 'a' - 10);
-    }
-  hex[len * 2] = '\0';
+  base_algo =
+    ((unsigned int) algo3)
+    & ~((unsigned int)
+        (MHD_DIGEST_AUTH_ALGO3_NON_SESSION
+         | MHD_DIGEST_AUTH_ALGO3_NON_SESSION));
+  return (enum MHD_DigestBaseAlgo) base_algo;
 }
 
 
 /**
- * calculate H(A1) as per RFC2617 spec and store the
- * result in 'sessionkey'.
+ * Get digest size for specified algorithm.
  *
- * @param alg The hash algorithm used, can be "md5" or "md5-sess"
- * @param username A `char *' pointer to the username value
- * @param realm A `char *' pointer to the realm value
- * @param password A `char *' pointer to the password value
- * @param nonce A `char *' pointer to the nonce value
- * @param cnonce A `char *' pointer to the cnonce value
- * @param sessionkey pointer to buffer of HASH_MD5_HEX_LEN+1 bytes
+ * Internal inline version.
+ * @param algo3 the algorithm to check
+ * @return the size of the digest or zero if the input value is not
+ *         supported/valid
  */
-static void
-digest_calc_ha1 (const char *alg,
-		 const char *username,
-		 const char *realm,
-		 const char *password,
-		 const char *nonce,
-		 const char *cnonce,
-		 char *sessionkey)
+_MHD_static_inline size_t
+digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3)
 {
-  struct MD5Context md5;
-  unsigned char ha1[MD5_DIGEST_SIZE];
+#ifdef MHD_MD5_SUPPORT
+  mhd_assert (MHD_MD5_DIGEST_SIZE == MD5_DIGEST_SIZE);
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  mhd_assert (MHD_SHA256_DIGEST_SIZE == SHA256_DIGEST_SIZE);
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  mhd_assert (MHD_SHA512_256_DIGEST_SIZE == SHA512_256_DIGEST_SIZE);
+#ifdef MHD_SHA256_SUPPORT
+  mhd_assert (SHA256_DIGEST_SIZE == SHA512_256_DIGEST_SIZE);
+#endif /* MHD_SHA256_SUPPORT */
+#endif /* MHD_SHA512_256_SUPPORT */
+  /* Only one algorithm must be specified */
+  mhd_assert (1 == \
+              (((0 != (algo3 & MHD_DIGEST_BASE_ALGO_MD5)) ? 1 : 0)   \
+               + ((0 != (algo3 & MHD_DIGEST_BASE_ALGO_SHA256)) ? 1 : 0)   \
+               + ((0 != (algo3 & MHD_DIGEST_BASE_ALGO_SHA512_256)) ? 1 : 0)));
+#ifdef MHD_MD5_SUPPORT
+  if (0 != (((unsigned int) algo3)
+            & ((unsigned int) MHD_DIGEST_BASE_ALGO_MD5)))
+    return MHD_MD5_DIGEST_SIZE;
+  else
+#endif /* MHD_MD5_SUPPORT */
+#if defined(MHD_SHA256_SUPPORT) && defined(MHD_SHA512_256_SUPPORT)
+  if (0 != (((unsigned int) algo3)
+            & ( ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA256)
+                | ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA512_256))))
+    return MHD_SHA256_DIGEST_SIZE; /* The same as SHA512_256_DIGEST_SIZE */
+  else
+#elif defined(MHD_SHA256_SUPPORT)
+  if (0 != (((unsigned int) algo3)
+            & ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA256)))
+    return MHD_SHA256_DIGEST_SIZE;
+  else
+#elif defined(MHD_SHA512_256_SUPPORT)
+  if (0 != (((unsigned int) algo3)
+            & ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA512_256)))
+    return MHD_SHA512_256_DIGEST_SIZE;
+  else
+#endif /* MHD_SHA512_256_SUPPORT */
+    (void) 0; /* Unsupported algorithm */
 
-  MD5Init (&md5);
-  MD5Update (&md5, username, strlen (username));
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, realm, strlen (realm));
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, password, strlen (password));
-  MD5Final (ha1, &md5);
-  if (MHD_str_equal_caseless_(alg, "md5-sess"))
-    {
-      MD5Init (&md5);
-      MD5Update (&md5, ha1, sizeof (ha1));
-      MD5Update (&md5, ":", 1);
-      MD5Update (&md5, nonce, strlen (nonce));
-      MD5Update (&md5, ":", 1);
-      MD5Update (&md5, cnonce, strlen (cnonce));
-      MD5Final (ha1, &md5);
-    }
-  cvthex (ha1, sizeof (ha1), sessionkey);
+  return 0; /* Wrong input or unsupported algorithm */
 }
 
 
 /**
- * Calculate request-digest/response-digest as per RFC2617 spec
+ * Get digest size for specified algorithm.
  *
- * @param ha1 H(A1)
- * @param nonce nonce from server
- * @param noncecount 8 hex digits
- * @param cnonce client nonce
- * @param qop qop-value: "", "auth" or "auth-int"
- * @param method method from request
- * @param uri requested URL
- * @param hentity H(entity body) if qop="auth-int"
- * @param response request-digest or response-digest
+ * The size of the digest specifies the size of the userhash, userdigest
+ * and other parameters which size depends on used hash algorithm.
+ * @param algo3 the algorithm to check
+ * @return the size of the digest (either #MHD_MD5_DIGEST_SIZE or
+ *         #MHD_SHA256_DIGEST_SIZE/MHD_SHA512_256_DIGEST_SIZE)
+ *         or zero if the input value is not supported or not valid
+ * @sa #MHD_digest_auth_calc_userdigest()
+ * @sa #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_calc_userhash_hex()
+ * @note Available since #MHD_VERSION 0x00097526
+ * @ingroup authentication
  */
-static void
-digest_calc_response (const char *ha1,
-		      const char *nonce,
-		      const char *noncecount,
-		      const char *cnonce,
-		      const char *qop,
-		      const char *method,
-		      const char *uri,
-		      const char *hentity,
-		      char *response)
+_MHD_EXTERN size_t
+MHD_digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3)
 {
-  struct MD5Context md5;
-  unsigned char ha2[MD5_DIGEST_SIZE];
-  unsigned char resphash[MD5_DIGEST_SIZE];
-  char ha2hex[HASH_MD5_HEX_LEN + 1];
-
-  MD5Init (&md5);
-  MD5Update (&md5, method, strlen(method));
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, uri, strlen(uri));
-#if 0
-  if (0 == strcasecmp(qop, "auth-int"))
-    {
-      /* This is dead code since the rest of this module does
-	 not support auth-int. */
-      MD5Update (&md5, ":", 1);
-      if (NULL != hentity)
-	MD5Update (&md5, hentity, strlen(hentity));
-    }
-#endif
-  MD5Final (ha2, &md5);
-  cvthex (ha2, MD5_DIGEST_SIZE, ha2hex);
-  MD5Init (&md5);
-  /* calculate response */
-  MD5Update (&md5, ha1, HASH_MD5_HEX_LEN);
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, nonce, strlen(nonce));
-  MD5Update (&md5, ":", 1);
-  if ('\0' != *qop)
-    {
-      MD5Update (&md5, noncecount, strlen(noncecount));
-      MD5Update (&md5, ":", 1);
-      MD5Update (&md5, cnonce, strlen(cnonce));
-      MD5Update (&md5, ":", 1);
-      MD5Update (&md5, qop, strlen(qop));
-      MD5Update (&md5, ":", 1);
-    }
-  MD5Update (&md5, ha2hex, HASH_MD5_HEX_LEN);
-  MD5Final (resphash, &md5);
-  cvthex (resphash, sizeof (resphash), response);
+  return digest_get_hash_size (algo3);
 }
 
 
 /**
- * Lookup subvalue off of the HTTP Authorization header.
- *
- * A description of the input format for 'data' is at
- * http://en.wikipedia.org/wiki/Digest_access_authentication
- *
- *
- * @param dest where to store the result (possibly truncated if
- *             the buffer is not big enough).
- * @param size size of dest
- * @param data pointer to the Authorization header
- * @param key key to look up in data
- * @return size of the located value, 0 if otherwise
+ * Digest context data
  */
-static size_t
-lookup_sub_value (char *dest,
-		  size_t size,
-		  const char *data,
-		  const char *key)
+union DigestCtx
 {
-  size_t keylen;
-  size_t len;
-  const char *ptr;
-  const char *eq;
-  const char *q1;
-  const char *q2;
-  const char *qn;
+#ifdef MHD_MD5_SUPPORT
+  struct Md5CtxWr md5_ctx;
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  struct Sha256CtxWr sha256_ctx;
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  struct Sha512_256Ctx sha512_256_ctx;
+#endif /* MHD_SHA512_256_SUPPORT */
+};
 
-  if (0 == size)
-    return 0;
-  keylen = strlen (key);
-  ptr = data;
-  while ('\0' != *ptr)
-    {
-      if (NULL == (eq = strchr (ptr, '=')))
-	return 0;
-      q1 = eq + 1;
-      while (' ' == *q1)
-	q1++;
-      if ('\"' != *q1)
-	{
-	  q2 = strchr (q1, ',');
-	  qn = q2;
-	}
-      else
-	{
-	  q1++;
-	  q2 = strchr (q1, '\"');
-	  if (NULL == q2)
-	    return 0; /* end quote not found */
-	  qn = q2 + 1;
-	}
-      if ((MHD_str_equal_caseless_n_(ptr,
-			      key,
-			      keylen)) &&
-	   (eq == &ptr[keylen]) )
-	{
-	  if (NULL == q2)
-	    {
-	      len = strlen (q1) + 1;
-	      if (size > len)
-		size = len;
-	      size--;
-	      strncpy (dest,
-		       q1,
-		       size);
-	      dest[size] = '\0';
-	      return size;
-	    }
-	  else
-	    {
-	      if (size > (size_t) ((q2 - q1) + 1))
-		size = (q2 - q1) + 1;
-	      size--;
-	      memcpy (dest,
-		      q1,
-		      size);
-	      dest[size] = '\0';
-	      return size;
-	    }
-	}
-      if (NULL == qn)
-	return 0;
-      ptr = strchr (qn, ',');
-      if (NULL == ptr)
-	return 0;
-      ptr++;
-      while (' ' == *ptr)
-	ptr++;
-    }
+/**
+ * The digest calculation structure.
+ */
+struct DigestAlgorithm
+{
+  /**
+   * A context for the digest algorithm, already initialized to be
+   * useful for @e init, @e update and @e digest.
+   */
+  union DigestCtx ctx;
+
+  /**
+   * The hash calculation algorithm.
+   */
+  enum MHD_DigestBaseAlgo algo;
+
+  /**
+   * Buffer for hex-print of the final digest.
+   */
+#if _DEBUG
+  bool uninitialised; /**< The structure has been not set-up */
+  bool algo_selected; /**< The algorithm has been selected */
+  bool ready_for_hashing; /**< The structure is ready to hash data */
+  bool hashing; /**< Some data has been hashed, but the digest has not finalised yet */
+#endif /* _DEBUG */
+};
+
+
+/**
+ * Return the size of the digest.
+ * @param da the digest calculation structure to identify
+ * @return the size of the digest.
+ */
+_MHD_static_inline unsigned int
+digest_get_size (struct DigestAlgorithm *da)
+{
+  mhd_assert (! da->uninitialised);
+  mhd_assert (da->algo_selected);
+#ifdef MHD_MD5_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo)
+    return MD5_DIGEST_SIZE;
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo)
+    return SHA256_DIGEST_SIZE;
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo)
+    return SHA512_256_DIGEST_SIZE;
+#endif /* MHD_SHA512_256_SUPPORT */
+  mhd_assert (0); /* May not happen */
   return 0;
 }
 
 
+#if defined(MHD_MD5_HAS_DEINIT) || defined(MHD_SHA256_HAS_DEINIT)
 /**
- * Check nonce-nc map array with either new nonce counter
- * or a whole new nonce.
+ * Indicates presence of digest_deinit() function
+ */
+#define MHD_DIGEST_HAS_DEINIT 1
+#endif /* MHD_MD5_HAS_DEINIT || MHD_SHA256_HAS_DEINIT */
+
+#ifdef MHD_DIGEST_HAS_DEINIT
+/**
+ * Zero-initialise digest calculation structure.
+ *
+ * This initialisation is enough to safely call #digest_deinit() only.
+ * To make any real digest calculation, #digest_setup_and_init() must be called.
+ * @param da the digest calculation
+ */
+_MHD_static_inline void
+digest_setup_zero (struct DigestAlgorithm *da)
+{
+#ifdef _DEBUG
+  da->uninitialised = false;
+  da->algo_selected = false;
+  da->ready_for_hashing = false;
+  da->hashing = false;
+#endif /* _DEBUG */
+  da->algo = MHD_DIGEST_BASE_ALGO_INVALID;
+}
+
+
+/**
+ * De-initialise digest calculation structure.
+ *
+ * This function must be called if #digest_setup_and_init() was called for
+ * @a da.
+ * This function must not be called if @a da was not initialised by
+ * #digest_setup_and_init() or by #digest_setup_zero().
+ * @param da the digest calculation
+ */
+_MHD_static_inline void
+digest_deinit (struct DigestAlgorithm *da)
+{
+  mhd_assert (! da->uninitialised);
+#ifdef MHD_MD5_HAS_DEINIT
+  if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo)
+    MHD_MD5_deinit (&da->ctx.md5_ctx);
+  else
+#endif /* MHD_MD5_HAS_DEINIT */
+#ifdef MHD_SHA256_HAS_DEINIT
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo)
+    MHD_SHA256_deinit (&da->ctx.sha256_ctx);
+  else
+#endif /* MHD_SHA256_HAS_DEINIT */
+  (void) 0;
+  digest_setup_zero (da);
+}
+
+
+#else  /* ! MHD_DIGEST_HAS_DEINIT */
+#define digest_setup_zero(da) (void)0
+#define digest_deinit(da) (void)0
+#endif /* ! MHD_DIGEST_HAS_DEINIT */
+
+
+/**
+ * Set-up the digest calculation structure and initialise with initial values.
+ *
+ * If @a da was successfully initialised, #digest_deinit() must be called
+ * after finishing using of the @a da.
+ *
+ * This function must not be called more than once for any @a da.
+ *
+ * @param da the structure to set-up
+ * @param algo the algorithm to use for digest calculation
+ * @return boolean 'true' if successfully set-up,
+ *         false otherwise.
+ */
+_MHD_static_inline bool
+digest_init_one_time (struct DigestAlgorithm *da,
+                      enum MHD_DigestBaseAlgo algo)
+{
+#ifdef _DEBUG
+  da->uninitialised = false;
+  da->algo_selected = false;
+  da->ready_for_hashing = false;
+  da->hashing = false;
+#endif /* _DEBUG */
+#ifdef MHD_MD5_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_MD5 == algo)
+  {
+    da->algo = MHD_DIGEST_BASE_ALGO_MD5;
+#ifdef _DEBUG
+    da->algo_selected = true;
+#endif
+    MHD_MD5_init_one_time (&da->ctx.md5_ctx);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif
+    return true;
+  }
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == algo)
+  {
+    da->algo = MHD_DIGEST_BASE_ALGO_SHA256;
+#ifdef _DEBUG
+    da->algo_selected = true;
+#endif
+    MHD_SHA256_init_one_time (&da->ctx.sha256_ctx);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif
+    return true;
+  }
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA512_256 == algo)
+  {
+    da->algo = MHD_DIGEST_BASE_ALGO_SHA512_256;
+#ifdef _DEBUG
+    da->algo_selected = true;
+#endif
+    MHD_SHA512_256_init (&da->ctx.sha512_256_ctx);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif
+    return true;
+  }
+#endif /* MHD_SHA512_256_SUPPORT */
+
+  da->algo = MHD_DIGEST_BASE_ALGO_INVALID;
+  return false; /* Unsupported or bad algorithm */
+}
+
+
+/**
+ * Feed digest calculation with more data.
+ * @param da the digest calculation
+ * @param data the data to process
+ * @param length the size of the @a data in bytes
+ */
+_MHD_static_inline void
+digest_update (struct DigestAlgorithm *da,
+               const void *data,
+               size_t length)
+{
+  mhd_assert (! da->uninitialised);
+  mhd_assert (da->algo_selected);
+  mhd_assert (da->ready_for_hashing);
+#ifdef MHD_MD5_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo)
+    MHD_MD5_update (&da->ctx.md5_ctx, (const uint8_t *) data, length);
+  else
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo)
+    MHD_SHA256_update (&da->ctx.sha256_ctx, (const uint8_t *) data, length);
+  else
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo)
+    MHD_SHA512_256_update (&da->ctx.sha512_256_ctx,
+                           (const uint8_t *) data, length);
+  else
+#endif /* MHD_SHA512_256_SUPPORT */
+  mhd_assert (0);   /* May not happen */
+#ifdef _DEBUG
+  da->hashing = true;
+#endif
+}
+
+
+/**
+ * Feed digest calculation with more data from string.
+ * @param da the digest calculation
+ * @param str the zero-terminated string to process
+ */
+_MHD_static_inline void
+digest_update_str (struct DigestAlgorithm *da,
+                   const char *str)
+{
+  const size_t str_len = strlen (str);
+  digest_update (da, (const uint8_t *) str, str_len);
+}
+
+
+/**
+ * Feed digest calculation with single colon ':' character.
+ * @param da the digest calculation
+ * @param str the zero-terminated string to process
+ */
+_MHD_static_inline void
+digest_update_with_colon (struct DigestAlgorithm *da)
+{
+  static const uint8_t colon = (uint8_t) ':';
+  digest_update (da, &colon, 1);
+}
+
+
+/**
+ * Finally calculate hash (the digest).
+ * @param da the digest calculation
+ * @param[out] digest the pointer to the buffer to put calculated digest,
+ *                    must be at least digest_get_size(da) bytes large
+ */
+_MHD_static_inline void
+digest_calc_hash (struct DigestAlgorithm *da, uint8_t *digest)
+{
+  mhd_assert (! da->uninitialised);
+  mhd_assert (da->algo_selected);
+  mhd_assert (da->ready_for_hashing);
+#ifdef MHD_MD5_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo)
+  {
+#ifdef MHD_MD5_HAS_FINISH
+    MHD_MD5_finish (&da->ctx.md5_ctx, digest);
+#ifdef _DEBUG
+    da->ready_for_hashing = false;
+#endif /* _DEBUG */
+#else  /* ! MHD_MD5_HAS_FINISH */
+    MHD_MD5_finish_reset (&da->ctx.md5_ctx, digest);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif /* _DEBUG */
+#endif /* ! MHD_MD5_HAS_FINISH */
+  }
+  else
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo)
+  {
+#ifdef MHD_SHA256_HAS_FINISH
+    MHD_SHA256_finish (&da->ctx.sha256_ctx, digest);
+#ifdef _DEBUG
+    da->ready_for_hashing = false;
+#endif /* _DEBUG */
+#else  /* ! MHD_SHA256_HAS_FINISH */
+    MHD_SHA256_finish_reset (&da->ctx.sha256_ctx, digest);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif /* _DEBUG */
+#endif /* ! MHD_SHA256_HAS_FINISH */
+  }
+  else
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo)
+  {
+    MHD_SHA512_256_finish (&da->ctx.sha512_256_ctx, digest);
+#ifdef _DEBUG
+    da->ready_for_hashing = false;
+#endif /* _DEBUG */
+  }
+  else
+#endif /* MHD_SHA512_256_SUPPORT */
+  mhd_assert (0);   /* Should not happen */
+#ifdef _DEBUG
+  da->hashing = false;
+#endif /* _DEBUG */
+}
+
+
+/**
+ * Reset the digest calculation structure.
+ *
+ * @param da the structure to reset
+ */
+_MHD_static_inline void
+digest_reset (struct DigestAlgorithm *da)
+{
+  mhd_assert (! da->uninitialised);
+  mhd_assert (da->algo_selected);
+  mhd_assert (! da->hashing);
+#ifdef MHD_MD5_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo)
+  {
+#ifdef MHD_MD5_HAS_FINISH
+    mhd_assert (! da->ready_for_hashing);
+#else  /* ! MHD_MD5_HAS_FINISH */
+    mhd_assert (da->ready_for_hashing);
+#endif /* ! MHD_MD5_HAS_FINISH */
+    MHD_MD5_reset (&da->ctx.md5_ctx);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif /* _DEBUG */
+  }
+  else
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo)
+  {
+#ifdef MHD_SHA256_HAS_FINISH
+    mhd_assert (! da->ready_for_hashing);
+#else  /* ! MHD_SHA256_HAS_FINISH */
+    mhd_assert (da->ready_for_hashing);
+#endif /* ! MHD_SHA256_HAS_FINISH */
+    MHD_SHA256_reset (&da->ctx.sha256_ctx);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif /* _DEBUG */
+  }
+  else
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo)
+  {
+    mhd_assert (! da->ready_for_hashing);
+    MHD_SHA512_256_init (&da->ctx.sha512_256_ctx);
+#ifdef _DEBUG
+    da->ready_for_hashing = true;
+#endif
+  }
+  else
+#endif /* MHD_SHA512_256_SUPPORT */
+  {
+#ifdef _DEBUG
+    da->ready_for_hashing = false;
+#endif
+    mhd_assert (0); /* May not happen, bad algorithm */
+  }
+}
+
+
+#if defined(MHD_MD5_HAS_EXT_ERROR) || defined(MHD_SHA256_HAS_EXT_ERROR)
+/**
+ * Indicates that digest algorithm has external error status
+ */
+#define MHD_DIGEST_HAS_EXT_ERROR 1
+#endif /* MHD_MD5_HAS_EXT_ERROR || MHD_SHA256_HAS_EXT_ERROR */
+
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+/**
+ * Get external error code.
+ *
+ * When external digest calculation used, an error may occur during
+ * initialisation or hashing data. This function checks whether external
+ * error has been reported for digest calculation.
+ * @param da the digest calculation
+ * @return true if external error occurs
+ */
+_MHD_static_inline bool
+digest_ext_error (struct DigestAlgorithm *da)
+{
+  mhd_assert (! da->uninitialised);
+  mhd_assert (da->algo_selected);
+#ifdef MHD_MD5_HAS_EXT_ERROR
+  if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo)
+    return 0 != da->ctx.md5_ctx.ext_error;
+#endif /* MHD_MD5_HAS_EXT_ERROR */
+#ifdef MHD_SHA256_HAS_EXT_ERROR
+  if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo)
+    return 0 != da->ctx.sha256_ctx.ext_error;
+#endif /* MHD_MD5_HAS_EXT_ERROR */
+  return false;
+}
+
+
+#else  /* ! MHD_DIGEST_HAS_EXT_ERROR */
+#define digest_ext_error(da) (false)
+#endif /* ! MHD_DIGEST_HAS_EXT_ERROR */
+
+
+/**
+ * Extract timestamp from the given nonce.
+ * @param nonce the nonce to check
+ * @param noncelen the length of the nonce, zero for autodetect
+ * @param[out] ptimestamp the pointer to store extracted timestamp
+ * @return true if timestamp was extracted,
+ *         false if nonce does not have valid timestamp.
+ */
+static bool
+get_nonce_timestamp (const char *const nonce,
+                     size_t noncelen,
+                     uint64_t *const ptimestamp)
+{
+  if (0 == noncelen)
+    noncelen = strlen (nonce);
+
+  if (true
+#ifdef MHD_MD5_SUPPORT
+      && (NONCE_STD_LEN (MD5_DIGEST_SIZE) != noncelen)
+#endif /* MHD_MD5_SUPPORT */
+#if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT)
+      && (NONCE_STD_LEN (SHA256_SHA512_256_DIGEST_SIZE) != noncelen)
+#endif /* MHD_SHA256_SUPPORT */
+      )
+    return false;
+
+  if (TIMESTAMP_CHARS_LEN !=
+      MHD_strx_to_uint64_n_ (nonce + noncelen - TIMESTAMP_CHARS_LEN,
+                             TIMESTAMP_CHARS_LEN,
+                             ptimestamp))
+    return false;
+  return true;
+}
+
+
+/**
+ * Super-fast xor-based "hash" function
+ *
+ * @param data the data to calculate hash for
+ * @param data_size the size of the data in bytes
+ * @return the "hash"
+ */
+static uint32_t
+fast_simple_hash (const uint8_t *data,
+                  size_t data_size)
+{
+  uint32_t hash;
+
+  if (0 != data_size)
+  {
+    size_t i;
+    hash = data[0];
+    for (i = 1; i < data_size; i++)
+      hash = _MHD_ROTL32 (hash, 7) ^ data[i];
+  }
+  else
+    hash = 0;
+
+  return hash;
+}
+
+
+/**
+ * Get index of the nonce in the nonce-nc map array.
+ *
+ * @param arr_size the size of nonce_nc array
+ * @param nonce the pointer that referenced a zero-terminated array of nonce
+ * @param noncelen the length of @a nonce, in characters
+ * @return #MHD_YES if successful, #MHD_NO if invalid (or we have no NC array)
+ */
+static size_t
+get_nonce_nc_idx (size_t arr_size,
+                  const char *nonce,
+                  size_t noncelen)
+{
+  mhd_assert (0 != arr_size);
+  mhd_assert (0 != noncelen);
+  return fast_simple_hash ((const uint8_t *) nonce, noncelen) % arr_size;
+}
+
+
+/**
+ * Check nonce-nc map array with the new nonce counter.
  *
  * @param connection The MHD connection structure
- * @param nonce A pointer that referenced a zero-terminated array of nonce
- * @param nc The nonce counter, zero to add the nonce to the array
- * @return MHD_YES if successful, MHD_NO if invalid (or we have no NC array)
+ * @param nonce the pointer that referenced hex nonce, does not need to be
+ *              zero-terminated
+ * @param noncelen the length of @a nonce, in characters
+ * @param nc The nonce counter
+ * @return #MHD_DAUTH_NONCENC_OK if successful,
+ *         #MHD_DAUTH_NONCENC_STALE if nonce is stale (or no nonce-nc array
+ *         is available),
+ *         #MHD_DAUTH_NONCENC_WRONG if nonce was not recodered in nonce-nc map
+ *         array, while it should.
  */
-static int
+static enum MHD_CheckNonceNC_
 check_nonce_nc (struct MHD_Connection *connection,
-		const char *nonce,
-		unsigned long int nc)
+                const char *nonce,
+                size_t noncelen,
+                uint64_t nonce_time,
+                uint64_t nc)
 {
-  uint32_t off;
+  struct MHD_Daemon *daemon = MHD_get_master (connection->daemon);
+  struct MHD_NonceNc *nn;
   uint32_t mod;
-  const char *np;
+  enum MHD_CheckNonceNC_ ret;
 
-  mod = connection->daemon->nonce_nc_size;
+  mhd_assert (0 != noncelen);
+  mhd_assert (0 != nc);
+  if (MAX_DIGEST_NONCE_LENGTH < noncelen)
+    return MHD_CHECK_NONCENC_WRONG; /* This should be impossible, but static analysis
+                      tools have a hard time with it *and* this also
+                      protects against unsafe modifications that may
+                      happen in the future... */
+  mod = daemon->nonce_nc_size;
   if (0 == mod)
-    return MHD_NO; /* no array! */
-  /* super-fast xor-based "hash" function for HT lookup in nonce array */
-  off = 0;
-  np = nonce;
-  while ('\0' != *np)
-    {
-      off = (off << 8) | (*np ^ (off >> 24));
-      np++;
-    }
-  off = off % mod;
-  /*
-   * Look for the nonce, if it does exist and its corresponding
-   * nonce counter is less than the current nonce counter by 1,
-   * then only increase the nonce counter by one.
-   */
+    return MHD_CHECK_NONCENC_STALE;  /* no array! */
+  if (nc >= UINT32_MAX - 64)
+    return MHD_CHECK_NONCENC_STALE;  /* Overflow, unrealistically high value */
 
-  (void) MHD_mutex_lock_ (&connection->daemon->nnc_lock);
-  if (0 == nc)
-    {
-      strcpy(connection->daemon->nnc[off].nonce,
-	     nonce);
-      connection->daemon->nnc[off].nc = 0;
-      (void) MHD_mutex_unlock_ (&connection->daemon->nnc_lock);
-      return MHD_YES;
+  nn = &daemon->nnc[get_nonce_nc_idx (mod, nonce, noncelen)];
+
+  MHD_mutex_lock_chk_ (&daemon->nnc_lock);
+
+  mhd_assert (0 == nn->nonce[noncelen]); /* The old value must be valid */
+
+  if ( (0 != memcmp (nn->nonce, nonce, noncelen)) ||
+       (0 != nn->nonce[noncelen]) )
+  { /* The nonce in the slot does not match nonce from the client */
+    if (0 == nn->nonce[0])
+    { /* The slot was never used, while the client's nonce value should be
+       * recorded when it was generated by MHD */
+      ret = MHD_CHECK_NONCENC_WRONG;
     }
-  if ( (nc <= connection->daemon->nnc[off].nc) ||
-       (0 != strcmp(connection->daemon->nnc[off].nonce, nonce)) )
-    {
-      (void) MHD_mutex_unlock_ (&connection->daemon->nnc_lock);
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-		"Stale nonce received.  If this happens a lot, you should probably increase the size of the nonce array.\n");
-#endif
-      return MHD_NO;
+    else if (0 != nn->nonce[noncelen])
+    { /* The value is the slot is wrong */
+      ret =  MHD_CHECK_NONCENC_STALE;
     }
-  connection->daemon->nnc[off].nc = nc;
-  (void) MHD_mutex_unlock_ (&connection->daemon->nnc_lock);
-  return MHD_YES;
+    else
+    {
+      uint64_t slot_ts; /**< The timestamp in the slot */
+      if (! get_nonce_timestamp (nn->nonce, noncelen, &slot_ts))
+      {
+        mhd_assert (0); /* The value is the slot is wrong */
+        ret = MHD_CHECK_NONCENC_STALE;
+      }
+      else
+      {
+        /* Unsigned value, will be large if nonce_time is less than slot_ts */
+        const uint64_t ts_diff = TRIM_TO_TIMESTAMP (nonce_time - slot_ts);
+        if ((REUSE_TIMEOUT * 1000) >= ts_diff)
+        {
+          /* The nonce from the client may not have been placed in the slot
+           * because another nonce in that slot has not yet expired. */
+          ret = MHD_CHECK_NONCENC_STALE;
+        }
+        else if (TRIM_TO_TIMESTAMP (UINT64_MAX) / 2 >= ts_diff)
+        {
+          /* Too large value means that nonce_time is less than slot_ts.
+           * The nonce from the client may have been overwritten by the newer
+           * nonce. */
+          ret = MHD_CHECK_NONCENC_STALE;
+        }
+        else
+        {
+          /* The nonce from the client should be generated after the nonce
+           * in the slot has been expired, the nonce must be recorded, but
+           * it's not. */
+          ret = MHD_CHECK_NONCENC_WRONG;
+        }
+      }
+    }
+  }
+  else if (nc > nn->nc)
+  {
+    /* 'nc' is larger, shift bitmask and bump limit */
+    const uint32_t jump_size = (uint32_t) nc - nn->nc;
+    if (64 > jump_size)
+    {
+      /* small jump, less than mask width */
+      nn->nmask <<= jump_size;
+      /* Set bit for the old 'nc' value */
+      nn->nmask |= (UINT64_C (1) << (jump_size - 1));
+    }
+    else if (64 == jump_size)
+      nn->nmask = (UINT64_C (1) << 63);
+    else
+      nn->nmask = 0;                /* big jump, unset all bits in the mask */
+    nn->nc = (uint32_t) nc;
+    ret = MHD_CHECK_NONCENC_OK;
+  }
+  else if (nc < nn->nc)
+  {
+    /* Note that we use 64 here, as we do not store the
+       bit for 'nn->nc' itself in 'nn->nmask' */
+    if ( (nc + 64 >= nn->nc) &&
+         (0 == ((UINT64_C (1) << (nn->nc - nc - 1)) & nn->nmask)) )
+    {
+      /* Out-of-order nonce, but within 64-bit bitmask, set bit */
+      nn->nmask |= (UINT64_C (1) << (nn->nc - nc - 1));
+      ret = MHD_CHECK_NONCENC_OK;
+    }
+    else
+      /* 'nc' was already used or too old (more then 64 values ago) */
+      ret = MHD_CHECK_NONCENC_STALE;
+  }
+  else /* if (nc == nn->nc) */
+    /* 'nc' was already used */
+    ret = MHD_CHECK_NONCENC_STALE;
+
+  MHD_mutex_unlock_chk_ (&daemon->nnc_lock);
+
+  return ret;
+}
+
+
+/**
+ * Get username type used by the client.
+ * This function does not check whether userhash can be decoded or
+ * extended notation (if used) is valid.
+ * @param params the Digest Authorization parameters
+ * @return the type of username
+ */
+_MHD_static_inline enum MHD_DigestAuthUsernameType
+get_rq_uname_type (const struct MHD_RqDAuth *params)
+{
+  if (NULL != params->username.value.str)
+  {
+    if (NULL == params->username_ext.value.str)
+      return params->userhash ?
+             MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH :
+             MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD;
+    else  /* Both 'username' and 'username*' are used */
+      return MHD_DIGEST_AUTH_UNAME_TYPE_INVALID;
+  }
+  else if (NULL != params->username_ext.value.str)
+  {
+    if (! params->username_ext.quoted && ! params->userhash &&
+        (MHD_DAUTH_EXT_PARAM_MIN_LEN <= params->username_ext.value.len) )
+      return MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED;
+    else
+      return MHD_DIGEST_AUTH_UNAME_TYPE_INVALID;
+  }
+
+  return MHD_DIGEST_AUTH_UNAME_TYPE_MISSING;
+}
+
+
+/**
+ * Get total size required for 'username' and 'userhash_bin'
+ * @param params the Digest Authorization parameters
+ * @param uname_type the type of username
+ * @return the total size required for 'username' and
+ *         'userhash_bin' is userhash is used
+ */
+_MHD_static_inline size_t
+get_rq_unames_size (const struct MHD_RqDAuth *params,
+                    enum MHD_DigestAuthUsernameType uname_type)
+{
+  size_t s;
+
+  mhd_assert (get_rq_uname_type (params) == uname_type);
+  s = 0;
+  if ((MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD == uname_type) ||
+      (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) )
+  {
+    s += params->username.value.len + 1; /* Add one byte for zero-termination */
+    if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type)
+      s += (params->username.value.len + 1) / 2;
+  }
+  else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED == uname_type)
+    s += params->username_ext.value.len
+         - MHD_DAUTH_EXT_PARAM_MIN_LEN + 1; /* Add one byte for zero-termination */
+  return s;
+}
+
+
+/**
+ * Get unquoted version of Digest Authorization parameter.
+ * This function automatically zero-teminate the result.
+ * @param param the parameter to extract
+ * @param[out] buf the output buffer, must be enough size to hold the result,
+ *                 the recommended size is 'param->value.len + 1'
+ * @return the size of the result, not including the terminating zero
+ */
+static size_t
+get_rq_param_unquoted_copy_z (const struct MHD_RqDAuthParam *param, char *buf)
+{
+  size_t len;
+  mhd_assert (NULL != param->value.str);
+  if (! param->quoted)
+  {
+    memcpy (buf, param->value.str, param->value.len);
+    buf [param->value.len] = 0;
+    return param->value.len;
+  }
+
+  len = MHD_str_unquote (param->value.str, param->value.len, buf);
+  mhd_assert (0 != len);
+  mhd_assert (len < param->value.len);
+  buf[len] = 0;
+  return len;
+}
+
+
+/**
+ * Get decoded version of username from extended notation.
+ * This function automatically zero-teminate the result.
+ * @param uname_ext the string of client's 'username*' parameter value
+ * @param uname_ext_len the length of @a uname_ext in chars
+ * @param[out] buf the output buffer to put decoded username value
+ * @param buf_size the size of @a buf
+ * @return the number of characters copied to the output buffer or
+ *         -1 if wrong extended notation is used.
+ */
+static ssize_t
+get_rq_extended_uname_copy_z (const char *uname_ext, size_t uname_ext_len,
+                              char *buf, size_t buf_size)
+{
+  size_t r;
+  size_t w;
+  if ((size_t) SSIZE_MAX < uname_ext_len)
+    return -1; /* Too long input string */
+
+  if (MHD_DAUTH_EXT_PARAM_MIN_LEN > uname_ext_len)
+    return -1; /* Required prefix is missing */
+
+  if (! MHD_str_equal_caseless_bin_n_ (uname_ext, MHD_DAUTH_EXT_PARAM_PREFIX,
+                                       MHD_STATICSTR_LEN_ ( \
+                                         MHD_DAUTH_EXT_PARAM_PREFIX)))
+    return -1; /* Only UTF-8 is supported, as it is implied by RFC 7616 */
+
+  r = MHD_STATICSTR_LEN_ (MHD_DAUTH_EXT_PARAM_PREFIX);
+  /* Skip language tag */
+  while (r < uname_ext_len && '\'' != uname_ext[r])
+  {
+    const char chr = uname_ext[r];
+    if ((' ' == chr) || ('\t' == chr) || ('\"' == chr) || (',' == chr) ||
+        (';' == chr) )
+      return -1; /* Wrong char in language tag */
+    r++;
+  }
+  if (r >= uname_ext_len)
+    return -1; /* The end of the language tag was not found */
+  r++; /* Advance to the next char */
+
+  w = MHD_str_pct_decode_strict_n_ (uname_ext + r, uname_ext_len - r,
+                                    buf, buf_size);
+  if ((0 == w) && (0 != uname_ext_len - r))
+    return -1; /* Broken percent encoding */
+  buf[w] = 0; /* Zero terminate the result */
+  mhd_assert (SSIZE_MAX > w);
+  return (ssize_t) w;
+}
+
+
+/**
+ * Get copy of username used by the client.
+ * @param params the Digest Authorization parameters
+ * @param uname_type the type of username
+ * @param[out] uname_info the pointer to the structure to be filled
+ * @param buf the buffer to be used for usernames
+ * @param buf_size the size of the @a buf
+ * @return the size of the @a buf used by pointers in @a unames structure
+ */
+static size_t
+get_rq_uname (const struct MHD_RqDAuth *params,
+              enum MHD_DigestAuthUsernameType uname_type,
+              struct MHD_DigestAuthUsernameInfo *uname_info,
+              uint8_t *buf,
+              size_t buf_size)
+{
+  size_t buf_used;
+
+  buf_used = 0;
+  mhd_assert (get_rq_uname_type (params) == uname_type);
+  mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID != uname_type);
+  mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_type);
+
+  uname_info->username = NULL;
+  uname_info->username_len = 0;
+  uname_info->userhash_hex = NULL;
+  uname_info->userhash_hex_len = 0;
+  uname_info->userhash_bin = NULL;
+
+  if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD == uname_type)
+  {
+    uname_info->username = (char *) (buf + buf_used);
+    uname_info->username_len =
+      get_rq_param_unquoted_copy_z (&params->username,
+                                    uname_info->username);
+    buf_used += uname_info->username_len + 1;
+    uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD;
+  }
+  else if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type)
+  {
+    size_t res;
+
+    uname_info->userhash_hex = (char *) (buf + buf_used);
+    uname_info->userhash_hex_len =
+      get_rq_param_unquoted_copy_z (&params->username,
+                                    uname_info->userhash_hex);
+    buf_used += uname_info->userhash_hex_len + 1;
+    uname_info->userhash_bin = (uint8_t *) (buf + buf_used);
+    res = MHD_hex_to_bin (uname_info->userhash_hex,
+                          uname_info->userhash_hex_len,
+                          uname_info->userhash_bin);
+    if (res != uname_info->userhash_hex_len / 2)
+    {
+      uname_info->userhash_bin = NULL;
+      uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID;
+    }
+    else
+    {
+      /* Avoid pointers outside allocated region when the size is zero */
+      if (0 == res)
+        uname_info->userhash_bin = (uint8_t *) uname_info->username;
+      uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH;
+      buf_used += res;
+    }
+  }
+  else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED == uname_type)
+  {
+    ssize_t res;
+    res = get_rq_extended_uname_copy_z (params->username_ext.value.str,
+                                        params->username_ext.value.len,
+                                        (char *) (buf + buf_used),
+                                        buf_size - buf_used);
+    if (0 > res)
+      uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID;
+    else
+    {
+      uname_info->username = (char *) (buf + buf_used);
+      uname_info->username_len = (size_t) res;
+      uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED;
+      buf_used += uname_info->username_len + 1;
+    }
+  }
+  else
+  {
+    mhd_assert (0);
+    uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID;
+  }
+  mhd_assert (buf_size >= buf_used);
+  return buf_used;
+}
+
+
+/**
+ * Result of request's Digest Authorization 'nc' value extraction
+ */
+enum MHD_GetRqNCResult
+{
+  MHD_GET_RQ_NC_NONE = -1,    /**< No 'nc' value */
+  MHD_GET_RQ_NC_VALID = 0,    /**< Readable 'nc' value */
+  MHD_GET_RQ_NC_TOO_LONG = 1, /**< The 'nc' value is too long */
+  MHD_GET_RQ_NC_TOO_LARGE = 2,/**< The 'nc' value is too big to fit uint32_t */
+  MHD_GET_RQ_NC_BROKEN = 3    /**< The 'nc' value is not a number */
+};
+
+
+/**
+ * Get 'nc' value from request's Authorization header
+ * @param params the request digest authentication
+ * @param[out] nc the pointer to put nc value to
+ * @return enum value indicating the result
+ */
+static enum MHD_GetRqNCResult
+get_rq_nc (const struct MHD_RqDAuth *params,
+           uint32_t *nc)
+{
+  const struct MHD_RqDAuthParam *const nc_param =
+    &params->nc;
+  char unq[16];
+  const char *val;
+  size_t val_len;
+  size_t res;
+  uint64_t nc_val;
+
+  if (NULL == nc_param->value.str)
+    return MHD_GET_RQ_NC_NONE;
+
+  if (0 == nc_param->value.len)
+    return MHD_GET_RQ_NC_BROKEN;
+
+  if (! nc_param->quoted)
+  {
+    val = nc_param->value.str;
+    val_len = nc_param->value.len;
+  }
+  else
+  {
+    /* Actually no backslashes must be used in 'nc' */
+    if (sizeof(unq) < params->nc.value.len)
+      return MHD_GET_RQ_NC_TOO_LONG;
+    val_len = MHD_str_unquote (nc_param->value.str, nc_param->value.len, unq);
+    if (0 == val_len)
+      return MHD_GET_RQ_NC_BROKEN;
+    val = unq;
+  }
+
+  res = MHD_strx_to_uint64_n_ (val, val_len, &nc_val);
+  if (0 == res)
+  {
+    const char f = val[0];
+    if ( (('9' >= f) && ('0' <= f)) ||
+         (('F' >= f) && ('A' <= f)) ||
+         (('a' <= f) && ('f' >= f)) )
+      return MHD_GET_RQ_NC_TOO_LARGE;
+    else
+      return MHD_GET_RQ_NC_BROKEN;
+  }
+  if (val_len != res)
+    return MHD_GET_RQ_NC_BROKEN;
+  if (UINT32_MAX < nc_val)
+    return MHD_GET_RQ_NC_TOO_LARGE;
+  *nc = (uint32_t) nc_val;
+  return MHD_GET_RQ_NC_VALID;
+}
+
+
+/**
+ * Get information about Digest Authorization client's header.
+ *
+ * @param connection The MHD connection structure
+ * @return NULL no valid Digest Authorization header is used in the request;
+ *         a pointer structure with information if the valid request header
+ *         found, free using #MHD_free().
+ * @note Available since #MHD_VERSION 0x00097519
+ * @ingroup authentication
+ */
+_MHD_EXTERN struct MHD_DigestAuthInfo *
+MHD_digest_auth_get_request_info3 (struct MHD_Connection *connection)
+{
+  const struct MHD_RqDAuth *params;
+  struct MHD_DigestAuthInfo *info;
+  enum MHD_DigestAuthUsernameType uname_type;
+  size_t unif_buf_size;
+  uint8_t *unif_buf_ptr;
+  size_t unif_buf_used;
+  enum MHD_GetRqNCResult nc_res;
+
+  params = MHD_get_rq_dauth_params_ (connection);
+  if (NULL == params)
+    return NULL;
+
+  unif_buf_size = 0;
+
+  uname_type = get_rq_uname_type (params);
+
+  unif_buf_size += get_rq_unames_size (params, uname_type);
+
+  if (NULL != params->opaque.value.str)
+    unif_buf_size += params->opaque.value.len + 1;  /* Add one for zero-termination */
+  if (NULL != params->realm.value.str)
+    unif_buf_size += params->realm.value.len + 1;   /* Add one for zero-termination */
+  info = (struct MHD_DigestAuthInfo *)
+         MHD_calloc_ (1, (sizeof(struct MHD_DigestAuthInfo)) + unif_buf_size);
+  unif_buf_ptr = (uint8_t *) (info + 1);
+  unif_buf_used = 0;
+
+  info->algo3 = params->algo3;
+
+  if ( (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_type) &&
+       (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID != uname_type) )
+    unif_buf_used +=
+      get_rq_uname (params, uname_type,
+                    (struct MHD_DigestAuthUsernameInfo *) info,
+                    unif_buf_ptr + unif_buf_used,
+                    unif_buf_size - unif_buf_used);
+  else
+    info->uname_type = uname_type;
+
+  if (NULL != params->opaque.value.str)
+  {
+    info->opaque = (char *) (unif_buf_ptr + unif_buf_used);
+    info->opaque_len = get_rq_param_unquoted_copy_z (&params->opaque,
+                                                     info->opaque);
+    unif_buf_used += info->opaque_len + 1;
+  }
+  if (NULL != params->realm.value.str)
+  {
+    info->realm = (char *) (unif_buf_ptr + unif_buf_used);
+    info->realm_len = get_rq_param_unquoted_copy_z (&params->realm,
+                                                    info->realm);
+    unif_buf_used += info->realm_len + 1;
+  }
+
+  mhd_assert (unif_buf_size >= unif_buf_used);
+
+  info->qop = params->qop;
+
+  if (NULL != params->cnonce.value.str)
+    info->cnonce_len = params->cnonce.value.len;
+  else
+    info->cnonce_len = 0;
+
+  nc_res = get_rq_nc (params, &info->nc);
+  if (MHD_GET_RQ_NC_VALID != nc_res)
+    info->nc = MHD_DIGEST_AUTH_INVALID_NC_VALUE;
+
+  return info;
+}
+
+
+/**
+ * Get the username from Digest Authorization client's header.
+ *
+ * @param connection The MHD connection structure
+ * @return NULL if no valid Digest Authorization header is used in the request,
+ *         or no username parameter is present in the header, or username is
+ *         provided incorrectly by client (see description for
+ *         #MHD_DIGEST_AUTH_UNAME_TYPE_INVALID);
+ *         a pointer structure with information if the valid request header
+ *         found, free using #MHD_free().
+ * @sa MHD_digest_auth_get_request_info3() provides more complete information
+ * @note Available since #MHD_VERSION 0x00097519
+ * @ingroup authentication
+ */
+_MHD_EXTERN struct MHD_DigestAuthUsernameInfo *
+MHD_digest_auth_get_username3 (struct MHD_Connection *connection)
+{
+  const struct MHD_RqDAuth *params;
+  struct MHD_DigestAuthUsernameInfo *uname_info;
+  enum MHD_DigestAuthUsernameType uname_type;
+  size_t unif_buf_size;
+  uint8_t *unif_buf_ptr;
+  size_t unif_buf_used;
+
+  params = MHD_get_rq_dauth_params_ (connection);
+  if (NULL == params)
+    return NULL;
+
+  uname_type = get_rq_uname_type (params);
+  if ( (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING == uname_type) ||
+       (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID == uname_type) )
+    return NULL;
+
+  unif_buf_size = get_rq_unames_size (params, uname_type);
+
+  uname_info = (struct MHD_DigestAuthUsernameInfo *)
+               MHD_calloc_ (1, (sizeof(struct MHD_DigestAuthUsernameInfo))
+                            + unif_buf_size);
+  unif_buf_ptr = (uint8_t *) (uname_info + 1);
+  unif_buf_used = get_rq_uname (params, uname_type, uname_info, unif_buf_ptr,
+                                unif_buf_size);
+  mhd_assert (unif_buf_size >= unif_buf_used);
+  (void) unif_buf_used; /* Mute compiler warning on non-debug builds */
+  mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_info->uname_type);
+
+  if (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID == uname_info->uname_type)
+  {
+    free (uname_info);
+    return NULL;
+  }
+  mhd_assert (uname_type == uname_info->uname_type);
+  uname_info->algo3 = params->algo3;
+
+  return uname_info;
 }
 
 
 /**
  * Get the username from the authorization header sent by the client
  *
+ * This function supports username in standard and extended notations.
+ * "userhash" is not supported by this function.
+ *
  * @param connection The MHD connection structure
- * @return NULL if no username could be found, a pointer
- * 			to the username if found
+ * @return NULL if no username could be found, username provided as
+ *         "userhash", extended notation broken or memory allocation error
+ *         occurs;
+ *         a pointer to the username if found, free using #MHD_free().
+ * @warning Returned value must be freed by #MHD_free().
+ * @sa #MHD_digest_auth_get_username3()
  * @ingroup authentication
  */
-char *
-MHD_digest_auth_get_username(struct MHD_Connection *connection)
+_MHD_EXTERN char *
+MHD_digest_auth_get_username (struct MHD_Connection *connection)
 {
-  size_t len;
-  char user[MAX_USERNAME_LENGTH];
-  const char *header;
+  const struct MHD_RqDAuth *params;
+  char *username;
+  size_t buf_size;
+  enum MHD_DigestAuthUsernameType uname_type;
 
-  if (NULL == (header = MHD_lookup_connection_value (connection,
-						     MHD_HEADER_KIND,
-						     MHD_HTTP_HEADER_AUTHORIZATION)))
+  params = MHD_get_rq_dauth_params_ (connection);
+  if (NULL == params)
     return NULL;
-  if (0 != strncmp (header, _BASE, strlen (_BASE)))
+
+  uname_type = get_rq_uname_type (params);
+
+  if ( (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != uname_type) &&
+       (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != uname_type) )
     return NULL;
-  header += strlen (_BASE);
-  if (0 == (len = lookup_sub_value (user,
-				    sizeof (user),
-				    header,
-				    "username")))
+
+  buf_size = get_rq_unames_size (params, uname_type);
+
+  mhd_assert (0 != buf_size);
+
+  username = (char *) MHD_calloc_ (1, buf_size);
+  if (NULL == username)
     return NULL;
-  return strdup (user);
+
+  if (1)
+  {
+    struct MHD_DigestAuthUsernameInfo uname_strct;
+    size_t used;
+
+    memset (&uname_strct, 0, sizeof(uname_strct));
+
+    used = get_rq_uname (params, uname_type, &uname_strct,
+                         (uint8_t *) username, buf_size);
+    if (uname_type != uname_strct.uname_type)
+    { /* Broken encoding for extended notation */
+      free (username);
+      return NULL;
+    }
+    (void) used; /* Mute compiler warning for non-debug builds */
+    mhd_assert (buf_size >= used);
+  }
+
+  return username;
 }
 
 
 /**
  * Calculate the server nonce so that it mitigates replay attacks
  * The current format of the nonce is ...
- * H(timestamp ":" method ":" random ":" uri ":" realm) + Hex(timestamp)
+ * H(timestamp:random data:various parameters) + Hex(timestamp)
  *
  * @param nonce_time The amount of time in seconds for a nonce to be invalid
- * @param method HTTP method
- * @param rnd A pointer to a character array for the random seed
+ * @param mthd_e HTTP method as enum value
+ * @param method HTTP method as a string
+ * @param rnd the pointer to a character array for the random seed
  * @param rnd_size The size of the random seed array @a rnd
- * @param uri HTTP URI (in MHD, without the arguments ("?k=v")
+ * @param saddr the pointer to the socket address structure
+ * @param saddr_size the size of the socket address structure @a saddr
+ * @param uri the HTTP URI (in MHD, without the arguments ("?k=v")
+ * @param uri_len the length of the @a uri
+ * @param first_header the pointer to the first request's header
  * @param realm A string of characters that describes the realm of auth.
- * @param nonce A pointer to a character array for the nonce to put in
+ * @param realm_len the length of the @a realm.
+ * @param bind_options the nonce bind options (#MHD_DAuthBindNonce values).
+ * @param da digest algorithm to use
+ * @param[out] nonce the pointer to a character array for the nonce to put in,
+ *                   must provide NONCE_STD_LEN(digest_get_size(da)) bytes,
+ *                   result is NOT zero-terminated
  */
 static void
-calculate_nonce (uint32_t nonce_time,
-		 const char *method,
-		 const char *rnd,
-		 size_t rnd_size,
-		 const char *uri,
-		 const char *realm,
-		 char *nonce)
+calculate_nonce (uint64_t nonce_time,
+                 enum MHD_HTTP_Method mthd_e,
+                 const char *method,
+                 const char *rnd,
+                 size_t rnd_size,
+                 const struct sockaddr_storage *saddr,
+                 size_t saddr_size,
+                 const char *uri,
+                 size_t uri_len,
+                 const struct MHD_HTTP_Req_Header *first_header,
+                 const char *realm,
+                 size_t realm_len,
+                 unsigned int bind_options,
+                 struct DigestAlgorithm *da,
+                 char *nonce)
 {
-  struct MD5Context md5;
-  unsigned char timestamp[4];
-  unsigned char tmpnonce[MD5_DIGEST_SIZE];
-  char timestamphex[sizeof(timestamp) * 2 + 1];
-
-  MD5Init (&md5);
-  timestamp[0] = (nonce_time & 0xff000000) >> 0x18;
-  timestamp[1] = (nonce_time & 0x00ff0000) >> 0x10;
-  timestamp[2] = (nonce_time & 0x0000ff00) >> 0x08;
-  timestamp[3] = (nonce_time & 0x000000ff);
-  MD5Update (&md5, timestamp, 4);
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, method, strlen (method));
-  MD5Update (&md5, ":", 1);
+  mhd_assert (! da->hashing);
+  if (1)
+  {
+    /* Add the timestamp to the hash calculation */
+    uint8_t timestamp[TIMESTAMP_BIN_SIZE];
+    /* If the nonce_time is milliseconds, then the same 48 bit value will repeat
+     * every 8 919 years, which is more than enough to mitigate a replay attack */
+#if TIMESTAMP_BIN_SIZE != 6
+#error The code needs to be updated here
+#endif
+    timestamp[0] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 0)));
+    timestamp[1] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 1)));
+    timestamp[2] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 2)));
+    timestamp[3] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 3)));
+    timestamp[4] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 4)));
+    timestamp[5] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 5)));
+    MHD_bin_to_hex (timestamp,
+                    sizeof (timestamp),
+                    nonce + digest_get_size (da) * 2);
+    digest_update (da,
+                   timestamp,
+                   sizeof (timestamp));
+  }
   if (rnd_size > 0)
-    MD5Update (&md5, rnd, rnd_size);
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, uri, strlen (uri));
-  MD5Update (&md5, ":", 1);
-  MD5Update (&md5, realm, strlen (realm));
-  MD5Final (tmpnonce, &md5);
-  cvthex (tmpnonce, sizeof (tmpnonce), nonce);
-  cvthex (timestamp, 4, timestamphex);
-  strncat (nonce, timestamphex, 8);
+  {
+    /* Add the unique random value to the hash calculation */
+    digest_update_with_colon (da);
+    digest_update (da,
+                   rnd,
+                   rnd_size);
+  }
+  if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) &&
+       (0 != saddr_size) )
+  {
+    /* Add full client address including source port to make unique nonces
+     * for requests received exactly at the same time */
+    digest_update_with_colon (da);
+    digest_update (da,
+                   saddr,
+                   saddr_size);
+  }
+  if ( (0 != (bind_options & MHD_DAUTH_BIND_NONCE_CLIENT_IP)) &&
+       (0 != saddr_size) )
+  {
+    /* Add the client's IP address to the hash calculation */
+    digest_update_with_colon (da);
+    if (AF_INET == saddr->ss_family)
+      digest_update (da,
+                     &((const struct sockaddr_in *) saddr)->sin_addr,
+                     sizeof(((const struct sockaddr_in *) saddr)->sin_addr));
+#ifdef HAVE_INET6
+    else if (AF_INET6 == saddr->ss_family)
+      digest_update (da,
+                     &((const struct sockaddr_in6 *) saddr)->sin6_addr,
+                     sizeof(((const struct sockaddr_in6 *) saddr)->sin6_addr));
+#endif /* HAVE_INET6 */
+  }
+  if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) ||
+       (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI)))
+  {
+    /* Add the request method to the hash calculation */
+    digest_update_with_colon (da);
+    if (MHD_HTTP_MTHD_OTHER != mthd_e)
+    {
+      uint8_t mthd_for_hash;
+      if (MHD_HTTP_MTHD_HEAD != mthd_e)
+        mthd_for_hash = (uint8_t) mthd_e;
+      else /* Treat HEAD method in the same way as GET method */
+        mthd_for_hash = (uint8_t) MHD_HTTP_MTHD_GET;
+      digest_update (da,
+                     &mthd_for_hash,
+                     sizeof(mthd_for_hash));
+    }
+    else
+      digest_update_str (da, method);
+  }
+
+  if (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI))
+  {
+    /* Add the request URI to the hash calculation */
+    digest_update_with_colon (da);
+
+    digest_update (da,
+                   uri,
+                   uri_len);
+  }
+  if (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI_PARAMS))
+  {
+    /* Add the request URI parameters to the hash calculation */
+    const struct MHD_HTTP_Req_Header *h;
+
+    digest_update_with_colon (da);
+    for (h = first_header; NULL != h; h = h->next)
+    {
+      if (MHD_GET_ARGUMENT_KIND != h->kind)
+        continue;
+      digest_update (da, "\0", 2);
+      if (0 != h->header_size)
+        digest_update (da, h->header, h->header_size);
+      digest_update (da, "", 1);
+      if (0 != h->value_size)
+        digest_update (da, h->value, h->value_size);
+    }
+  }
+  if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) ||
+       (0 != (bind_options & MHD_DAUTH_BIND_NONCE_REALM)))
+  {
+    /* Add the realm to the hash calculation */
+    digest_update_with_colon (da);
+    digest_update (da,
+                   realm,
+                   realm_len);
+  }
+  if (1)
+  {
+    uint8_t hash[MAX_DIGEST];
+    digest_calc_hash (da, hash);
+    MHD_bin_to_hex (hash,
+                    digest_get_size (da),
+                    nonce);
+  }
 }
 
 
 /**
+ * Check whether it is possible to use slot in nonce-nc map array.
+ *
+ * Should be called with mutex held to avoid external modification of
+ * the slot data.
+ *
+ * @param nn the pointer to the nonce-nc slot
+ * @param now the current time
+ * @param new_nonce the new nonce supposed to be stored in this slot,
+ *                  zero-terminated
+ * @param new_nonce_len the length of the @a new_nonce in chars, not including
+ *                      the terminating zero.
+ * @return true if the slot can be used to store the new nonce,
+ *         false otherwise.
+ */
+static bool
+is_slot_available (const struct MHD_NonceNc *const nn,
+                   const uint64_t now,
+                   const char *const new_nonce,
+                   size_t new_nonce_len)
+{
+  uint64_t timestamp;
+  bool timestamp_valid;
+  mhd_assert (new_nonce_len <= NONCE_STD_LEN (MAX_DIGEST));
+  mhd_assert (NONCE_STD_LEN (MAX_DIGEST) <= MAX_DIGEST_NONCE_LENGTH);
+  if (0 == nn->nonce[0])
+    return true; /* The slot is empty */
+
+  if (0 == memcmp (nn->nonce, new_nonce, new_nonce_len))
+  {
+    /* The slot has the same nonce already. This nonce cannot be registered
+     * again as it would just clear 'nc' usage history. */
+    return false;
+  }
+
+  if (0 != nn->nc)
+    return true; /* Client already used the nonce in this slot at least
+                    one time, re-use the slot */
+
+  /* The nonce must be zero-terminated */
+  mhd_assert (0 == nn->nonce[sizeof(nn->nonce) - 1]);
+  if (0 != nn->nonce[sizeof(nn->nonce) - 1])
+    return true; /* Wrong nonce format in the slot */
+
+  timestamp_valid = get_nonce_timestamp (nn->nonce, 0, &timestamp);
+  mhd_assert (timestamp_valid);
+  if (! timestamp_valid)
+    return true; /* Invalid timestamp in nonce-nc, should not be possible */
+
+  if ((REUSE_TIMEOUT * 1000) < TRIM_TO_TIMESTAMP (now - timestamp))
+    return true;
+
+  return false;
+}
+
+
+/**
+ * Calculate the server nonce so that it mitigates replay attacks and add
+ * the new nonce to the nonce-nc map array.
+ *
+ * @param connection the MHD connection structure
+ * @param timestamp the current timestamp
+ * @param realm the string of characters that describes the realm of auth
+ * @param realm_len the length of the @a realm
+ * @param da the digest algorithm to use
+ * @param[out] nonce the pointer to a character array for the nonce to put in,
+ *                   must provide NONCE_STD_LEN(digest_get_size(da)) bytes,
+ *                   result is NOT zero-terminated
+ * @return true if the new nonce has been added to the nonce-nc map array,
+ *         false otherwise.
+ */
+static bool
+calculate_add_nonce (struct MHD_Connection *const connection,
+                     uint64_t timestamp,
+                     const char *realm,
+                     size_t realm_len,
+                     struct DigestAlgorithm *da,
+                     char *nonce)
+{
+  struct MHD_Daemon *const daemon = MHD_get_master (connection->daemon);
+  struct MHD_NonceNc *nn;
+  const size_t nonce_size = NONCE_STD_LEN (digest_get_size (da));
+  bool ret;
+
+  mhd_assert (! da->hashing);
+  mhd_assert (MAX_DIGEST_NONCE_LENGTH >= nonce_size);
+  mhd_assert (0 != nonce_size);
+
+  calculate_nonce (timestamp,
+                   connection->rq.http_mthd,
+                   connection->rq.method,
+                   daemon->digest_auth_random,
+                   daemon->digest_auth_rand_size,
+                   connection->addr,
+                   (size_t) connection->addr_len,
+                   connection->rq.url,
+                   connection->rq.url_len,
+                   connection->rq.headers_received,
+                   realm,
+                   realm_len,
+                   daemon->dauth_bind_type,
+                   da,
+                   nonce);
+
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+  if (digest_ext_error (da))
+    return false;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+
+  if (0 == daemon->nonce_nc_size)
+    return false;
+
+  /* Sanity check for values */
+  mhd_assert (MAX_DIGEST_NONCE_LENGTH == NONCE_STD_LEN (MAX_DIGEST));
+
+  nn = daemon->nnc + get_nonce_nc_idx (daemon->nonce_nc_size,
+                                       nonce,
+                                       nonce_size);
+
+  MHD_mutex_lock_chk_ (&daemon->nnc_lock);
+  if (is_slot_available (nn, timestamp, nonce, nonce_size))
+  {
+    memcpy (nn->nonce,
+            nonce,
+            nonce_size);
+    nn->nonce[nonce_size] = 0;  /* With terminating zero */
+    nn->nc = 0;
+    nn->nmask = 0;
+    ret = true;
+  }
+  else
+    ret = false;
+  MHD_mutex_unlock_chk_ (&daemon->nnc_lock);
+
+  return ret;
+}
+
+
+/**
+ * Calculate the server nonce so that it mitigates replay attacks and add
+ * the new nonce to the nonce-nc map array.
+ *
+ * @param connection the MHD connection structure
+ * @param realm A string of characters that describes the realm of auth.
+ * @param da digest algorithm to use
+ * @param[out] nonce the pointer to a character array for the nonce to put in,
+ *                   must provide NONCE_STD_LEN(digest_get_size(da)) bytes,
+ *                   result is NOT zero-terminated
+ */
+static bool
+calculate_add_nonce_with_retry (struct MHD_Connection *const connection,
+                                const char *realm,
+                                struct DigestAlgorithm *da,
+                                char *nonce)
+{
+  const uint64_t timestamp1 = MHD_monotonic_msec_counter ();
+  const size_t realm_len = strlen (realm);
+  mhd_assert (! da->hashing);
+
+#ifdef HAVE_MESSAGES
+  if (0 == MHD_get_master (connection->daemon)->digest_auth_rand_size)
+    MHD_DLOG (connection->daemon,
+              _ ("Random value was not initialised by " \
+                 "MHD_OPTION_DIGEST_AUTH_RANDOM or " \
+                 "MHD_OPTION_DIGEST_AUTH_RANDOM_COPY, generated nonces " \
+                 "are predictable.\n"));
+#endif
+
+  if (! calculate_add_nonce (connection, timestamp1, realm, realm_len, da,
+                             nonce))
+  {
+    /* Either:
+     * 1. The same nonce was already generated. If it will be used then one
+     * of the clients will fail (as no initial 'nc' value could be given to
+     * the client, the second client which will use 'nc=00000001' will fail).
+     * 2. Another nonce uses the same slot, and this nonce never has been
+     * used by the client and this nonce is still fresh enough.
+     */
+    const size_t digest_size = digest_get_size (da);
+    char nonce2[NONCE_STD_LEN (MAX_DIGEST) + 1];
+    uint64_t timestamp2;
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+    if (digest_ext_error (da))
+      return false; /* No need to re-try */
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+    if (0 == MHD_get_master (connection->daemon)->nonce_nc_size)
+      return false; /* No need to re-try */
+
+    timestamp2 = MHD_monotonic_msec_counter ();
+    if (timestamp1 == timestamp2)
+    {
+      /* The timestamps are equal, need to generate some arbitrary
+       * difference for nonce. */
+      /* As the number is needed only to differentiate clients, weak
+       * pseudo-random generators could be used. Seeding is not needed. */
+      uint64_t base1;
+      uint32_t base2;
+      uint16_t base3;
+      uint8_t base4;
+#ifdef HAVE_RANDOM
+      base1 = ((uint64_t) random ()) ^ UINT64_C (0x54a5acff5be47e63);
+      base4 = 0xb8;
+#elif defined(HAVE_RAND)
+      base1 = ((uint64_t) rand ()) ^ UINT64_C (0xc4bcf553b12f3965);
+      base4 = 0x92;
+#else
+      /* Monotonic msec counter alone does not really help here as it is already
+         known that this value is not unique. */
+      base1 = ((uint64_t) (uintptr_t) nonce2) ^ UINT64_C (0xf2e1b21bc6c92655);
+      base2 = ((uint32_t) (base1 >> 32)) ^ ((uint32_t) base1);
+      base2 = _MHD_ROTR32 (base2, 4);
+      base3 = ((uint16_t) (base2 >> 16)) ^ ((uint16_t) base2);
+      base4 = ((uint8_t) (base3 >> 8)) ^ ((uint8_t) base3);
+      base1 = ((uint64_t) MHD_monotonic_msec_counter ())
+              ^ UINT64_C (0xccab93f72cf5b15);
+#endif
+      base2 = ((uint32_t) (base1 >> 32)) ^ ((uint32_t) base1);
+      base2 = _MHD_ROTL32 (base2, (((base4 >> 4) ^ base4) % 32));
+      base3 = ((uint16_t) (base2 >> 16)) ^ ((uint16_t) base2);
+      base4 = ((uint8_t) (base3 >> 8)) ^ ((uint8_t) base3);
+      /* Use up to 127 ms difference */
+      timestamp2 -= (base4 & DAUTH_JUMPBACK_MAX);
+      if (timestamp1 == timestamp2)
+        timestamp2 -= 2; /* Fallback value */
+    }
+    digest_reset (da);
+    if (! calculate_add_nonce (connection, timestamp2, realm, realm_len, da,
+                               nonce2))
+    {
+      /* No free slot has been found. Re-tries are expensive, just use
+       * the generated nonce. As it is not stored in nonce-nc map array,
+       * the next request of the client will be recognized as valid, but 'stale'
+       * so client should re-try automatically. */
+      return false;
+    }
+    memcpy (nonce, nonce2, NONCE_STD_LEN (digest_size));
+  }
+  return true;
+}
+
+
+/**
+ * Calculate userdigest, return it as binary data.
+ *
+ * It is equal to H(A1) for non-session algorithms.
+ *
+ * MHD internal version.
+ *
+ * @param da the digest algorithm
+ * @param username the username to use
+ * @param username_len the length of the @a username
+ * @param realm the realm to use
+ * @param realm_len the length of the @a realm
+ * @param password the password, must be zero-terminated
+ * @param[out] ha1_bin the output buffer, must have at least
+ *                     #digest_get_size(da) bytes available
+ */
+_MHD_static_inline void
+calc_userdigest (struct DigestAlgorithm *da,
+                 const char *username, const size_t username_len,
+                 const char *realm, const size_t realm_len,
+                 const char *password,
+                 uint8_t *ha1_bin)
+{
+  mhd_assert (! da->hashing);
+  digest_update (da, username, username_len);
+  digest_update_with_colon (da);
+  digest_update (da, realm, realm_len);
+  digest_update_with_colon (da);
+  digest_update_str (da, password);
+  digest_calc_hash (da, ha1_bin);
+}
+
+
+/**
+ * Calculate userdigest, return it as binary data.
+ *
+ * The "userdigest" is the hash of the "username:realm:password" string.
+ *
+ * The "userdigest" can be used to avoid storing the password in clear text
+ * in database/files
+ *
+ * This function is designed to improve security of stored credentials,
+ * the "userdigest" does not improve security of the authentication process.
+ *
+ * The results can be used to store username & userdigest pairs instead of
+ * username & password pairs. To further improve security, application may
+ * store username & userhash & userdigest triplets.
+ *
+ * @param algo3 the digest algorithm
+ * @param username the username
+ * @param realm the realm
+ * @param password the password, must be zero-terminated
+ * @param[out] userdigest_bin the output buffer for userdigest;
+ *                            if this function succeeds, then this buffer has
+ *                            #MHD_digest_get_hash_size(algo3) bytes of
+ *                            userdigest upon return
+ * @param userdigest_bin the size of the @a userdigest_bin buffer, must be
+ *                       at least #MHD_digest_get_hash_size(algo3) bytes long
+ * @return MHD_YES on success,
+ *         MHD_NO if @a userdigest_bin is too small or if @a algo3 algorithm is
+ *         not supported (or external error has occurred,
+ *         see #MHD_FEATURE_EXTERN_HASH).
+ * @sa #MHD_digest_auth_check_digest3()
+ * @note Available since #MHD_VERSION 0x00097535
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_digest_auth_calc_userdigest (enum MHD_DigestAuthAlgo3 algo3,
+                                 const char *username,
+                                 const char *realm,
+                                 const char *password,
+                                 void *userdigest_bin,
+                                 size_t bin_buf_size)
+{
+  struct DigestAlgorithm da;
+  enum MHD_Result ret;
+  if (! digest_init_one_time (&da, get_base_digest_algo (algo3)))
+    return MHD_NO;
+
+  if (digest_get_size (&da) > bin_buf_size)
+    ret = MHD_NO;
+  else
+  {
+    calc_userdigest (&da,
+                     username,
+                     strlen (username),
+                     realm,
+                     strlen (realm),
+                     password,
+                     userdigest_bin);
+    ret = MHD_YES;
+
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+    if (digest_ext_error (&da))
+      ret = MHD_NO;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+  }
+  digest_deinit (&da);
+
+  return ret;
+}
+
+
+/**
+ * Calculate userhash, return it as binary data.
+ *
+ * MHD internal version.
+ *
+ * @param da the digest algorithm
+ * @param username the username to use
+ * @param username_len the length of the @a username
+ * @param realm the realm to use
+ * @param realm_len the length of the @a realm
+ * @param[out] digest_bin the output buffer, must have at least
+ *                        #MHD_digest_get_hash_size(algo3) bytes available
+ */
+_MHD_static_inline void
+calc_userhash (struct DigestAlgorithm *da,
+               const char *username, const size_t username_len,
+               const char *realm, const size_t realm_len,
+               uint8_t *digest_bin)
+{
+  mhd_assert (NULL != username);
+  mhd_assert (! da->hashing);
+  digest_update (da, username, username_len);
+  digest_update_with_colon (da);
+  digest_update (da, realm, realm_len);
+  digest_calc_hash (da, digest_bin);
+}
+
+
+/**
+ * Calculate "userhash", return it as binary data.
+ *
+ * The "userhash" is the hash of the string "username:realm".
+ *
+ * The "Userhash" could be used to avoid sending username in cleartext in Digest
+ * Authorization client's header.
+ *
+ * Userhash is not designed to hide the username in local database or files,
+ * as username in cleartext is required for #MHD_digest_auth_check3() function
+ * to check the response, but it can be used to hide username in HTTP headers.
+ *
+ * This function could be used when the new username is added to the username
+ * database to save the "userhash" alongside with the username (preferably) or
+ * when loading list of the usernames to generate the userhash for every loaded
+ * username (this will cause delays at the start with the long lists).
+ *
+ * Once "userhash" is generated it could be used to identify users for clients
+ * with "userhash" support.
+ * Avoid repetitive usage of this function for the same username/realm
+ * combination as it will cause excessive CPU load; save and re-use the result
+ * instead.
+ *
+ * @param algo3 the algorithm for userhash calculations
+ * @param username the username
+ * @param realm the realm
+ * @param[out] userhash_bin the output buffer for userhash as binary data;
+ *                          if this function succeeds, then this buffer has
+ *                          #MHD_digest_get_hash_size(algo3) bytes of userhash
+ *                          upon return
+ * @param bin_buf_size the size of the @a userhash_bin buffer, must be
+ *                     at least #MHD_digest_get_hash_size(algo3) bytes long
+ * @return MHD_YES on success,
+ *         MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is
+ *         not supported (or external error has occurred,
+ *         see #MHD_FEATURE_EXTERN_HASH)
+ * @note Available since #MHD_VERSION 0x00097535
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_digest_auth_calc_userhash (enum MHD_DigestAuthAlgo3 algo3,
+                               const char *username,
+                               const char *realm,
+                               void *userhash_bin,
+                               size_t bin_buf_size)
+{
+  struct DigestAlgorithm da;
+  enum MHD_Result ret;
+
+  if (! digest_init_one_time (&da, get_base_digest_algo (algo3)))
+    return MHD_NO;
+  if (digest_get_size (&da) > bin_buf_size)
+    ret = MHD_NO;
+  else
+  {
+    calc_userhash (&da,
+                   username,
+                   strlen (username),
+                   realm,
+                   strlen (realm),
+                   userhash_bin);
+    ret = MHD_YES;
+
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+    if (digest_ext_error (&da))
+      ret = MHD_NO;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+  }
+  digest_deinit (&da);
+
+  return ret;
+}
+
+
+/**
+ * Calculate "userhash", return it as hexadecimal data.
+ *
+ * The "userhash" is the hash of the string "username:realm".
+ *
+ * The "Userhash" could be used to avoid sending username in cleartext in Digest
+ * Authorization client's header.
+ *
+ * Userhash is not designed to hide the username in local database or files,
+ * as username in cleartext is required for #MHD_digest_auth_check3() function
+ * to check the response, but it can be used to hide username in HTTP headers.
+ *
+ * This function could be used when the new username is added to the username
+ * database to save the "userhash" alongside with the username (preferably) or
+ * when loading list of the usernames to generate the userhash for every loaded
+ * username (this will cause delays at the start with the long lists).
+ *
+ * Once "userhash" is generated it could be used to identify users for clients
+ * with "userhash" support.
+ * Avoid repetitive usage of this function for the same username/realm
+ * combination as it will cause excessive CPU load; save and re-use the result
+ * instead.
+ *
+ * @param algo3 the algorithm for userhash calculations
+ * @param username the username
+ * @param realm the realm
+ * @param[out] userhash_hex the output buffer for userhash as hex data;
+ *                          if this function succeeds, then this buffer has
+ *                          #MHD_digest_get_hash_size(algo3)*2 chars long
+ *                          userhash string
+ * @param bin_buf_size the size of the @a userhash_bin buffer, must be
+ *                     at least #MHD_digest_get_hash_size(algo3)*2+1 chars long
+ * @return MHD_YES on success,
+ *         MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is
+ *         not supported (or external error has occurred,
+ *         see #MHD_FEATURE_EXTERN_HASH).
+ * @note Available since #MHD_VERSION 0x00097535
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_digest_auth_calc_userhash_hex (enum MHD_DigestAuthAlgo3 algo3,
+                                   const char *username,
+                                   const char *realm,
+                                   char *userhash_hex,
+                                   size_t hex_buf_size)
+{
+  uint8_t userhash_bin[MAX_DIGEST];
+  size_t digest_size;
+
+  digest_size = digest_get_hash_size (algo3);
+  if (digest_size * 2 + 1 > hex_buf_size)
+    return MHD_NO;
+  if (MHD_NO == MHD_digest_auth_calc_userhash (algo3, username, realm,
+                                               userhash_bin, MAX_DIGEST))
+    return MHD_NO;
+
+  MHD_bin_to_hex_z (userhash_bin, digest_size, userhash_hex);
+  return MHD_YES;
+}
+
+
+struct test_header_param
+{
+  struct MHD_Connection *connection;
+  size_t num_headers;
+};
+
+/**
  * Test if the given key-value pair is in the headers for the
  * given connection.
  *
- * @param connection the connection
+ * @param cls the test context
  * @param key the key
+ * @param key_size number of bytes in @a key
  * @param value the value, can be NULL
+ * @param value_size number of bytes in @a value
+ * @param kind type of the header
  * @return #MHD_YES if the key-value pair is in the headers,
  *         #MHD_NO if not
  */
-static int
-test_header (struct MHD_Connection *connection,
-	     const char *key,
-	     const char *value)
+static enum MHD_Result
+test_header (void *cls,
+             const char *key,
+             size_t key_size,
+             const char *value,
+             size_t value_size,
+             enum MHD_ValueKind kind)
 {
-  struct MHD_HTTP_Header *pos;
+  struct test_header_param *const param = (struct test_header_param *) cls;
+  struct MHD_Connection *connection = param->connection;
+  struct MHD_HTTP_Req_Header *pos;
+  size_t i;
 
-  for (pos = connection->headers_received; NULL != pos; pos = pos->next)
+  param->num_headers++;
+  i = 0;
+  for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+  {
+    if (kind != pos->kind)
+      continue;
+    if (++i == param->num_headers)
     {
-      if (MHD_GET_ARGUMENT_KIND != pos->kind)
-	continue;
-      if (0 != strcmp (key, pos->header))
-	continue;
-      if ( (NULL == value) &&
-	   (NULL == pos->value) )
-	return MHD_YES;
-      if ( (NULL == value) ||
-	   (NULL == pos->value) ||
-	   (0 != strcmp (value, pos->value)) )
-	continue;
+      if (key_size != pos->header_size)
+        return MHD_NO;
+      if (value_size != pos->value_size)
+        return MHD_NO;
+      if (0 != key_size)
+      {
+        mhd_assert (NULL != key);
+        mhd_assert (NULL != pos->header);
+        if (0 != memcmp (key,
+                         pos->header,
+                         key_size))
+          return MHD_NO;
+      }
+      if (0 != value_size)
+      {
+        mhd_assert (NULL != value);
+        mhd_assert (NULL != pos->value);
+        if (0 != memcmp (value,
+                         pos->value,
+                         value_size))
+          return MHD_NO;
+      }
       return MHD_YES;
     }
+  }
   return MHD_NO;
 }
 
@@ -471,314 +2200,1766 @@
  * got as part of the HTTP request URI.
  *
  * @param connection connections with headers to compare against
- * @param args argument URI string (after "?" in URI)
- * @return MHD_YES if the arguments match,
- *         MHD_NO if not
+ * @param args the copy of argument URI string (after "?" in URI), will be
+ *             modified by this function
+ * @return boolean true if the arguments match,
+ *         boolean false if not
  */
-static int
+static bool
 check_argument_match (struct MHD_Connection *connection,
-		      const char *args)
+                      char *args)
 {
-  struct MHD_HTTP_Header *pos;
-  char *argb;
-  char *argp;
-  char *equals;
-  char *amper;
-  unsigned int num_headers;
+  struct MHD_HTTP_Req_Header *pos;
+  enum MHD_Result ret;
+  struct test_header_param param;
 
-  argb = strdup(args);
-  if (NULL == argb)
+  param.connection = connection;
+  param.num_headers = 0;
+  ret = MHD_parse_arguments_ (connection,
+                              MHD_GET_ARGUMENT_KIND,
+                              args,
+                              &test_header,
+                              &param);
+  if (MHD_NO == ret)
   {
-#if HAVE_MESSAGES
-    MHD_DLOG(connection->daemon,
-             "Failed to allocate memory for copy of URI arguments\n");
-#endif /* HAVE_MESSAGES */
-    return MHD_NO;
+    return false;
   }
-  num_headers = 0;
-  argp = argb;
-  while ( (NULL != argp) &&
-	  ('\0' != argp[0]) )
-    {
-      equals = strchr (argp, '=');
-      if (NULL == equals)
-	{
-	  /* add with 'value' NULL */
-	  connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-						 connection,
-						 argp);
-	  if (MHD_YES != test_header (connection, argp, NULL))
-	    return MHD_NO;
-	  num_headers++;
-	  break;
-	}
-      equals[0] = '\0';
-      equals++;
-      amper = strchr (equals, '&');
-      if (NULL != amper)
-	{
-	  amper[0] = '\0';
-	  amper++;
-	}
-      connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-					     connection,
-					     argp);
-      connection->daemon->unescape_callback (connection->daemon->unescape_callback_cls,
-					     connection,
-					     equals);
-      if (! test_header (connection, argp, equals))
-	return MHD_NO;
-      num_headers++;
-      argp = amper;
-    }
-
   /* also check that the number of headers matches */
-  for (pos = connection->headers_received; NULL != pos; pos = pos->next)
-    {
-      if (MHD_GET_ARGUMENT_KIND != pos->kind)
-	continue;
-      num_headers--;
-    }
-  if (0 != num_headers)
-    return MHD_NO;
-  return MHD_YES;
+  for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next)
+  {
+    if (MHD_GET_ARGUMENT_KIND != pos->kind)
+      continue;
+    param.num_headers--;
+  }
+  if (0 != param.num_headers)
+  {
+    /* argument count mismatch */
+    return false;
+  }
+  return true;
+}
+
+
+/**
+ * Check that the URI provided by the client as part
+ * of the authentication header match the real HTTP request URI.
+ *
+ * @param connection connections with headers to compare against
+ * @param uri the copy of URI in the authentication header, should point to
+ *            modifiable buffer at least @a uri_len + 1 characters long,
+ *            will be modified by this function, not valid upon return
+ * @param uri_len the length of the @a uri string in characters
+ * @return boolean true if the URIs match,
+ *         boolean false if not
+ */
+static bool
+check_uri_match (struct MHD_Connection *connection, char *uri, size_t uri_len)
+{
+  char *qmark;
+  char *args;
+  struct MHD_Daemon *const daemon = connection->daemon;
+
+  uri[uri_len] = 0;
+  qmark = memchr (uri,
+                  '?',
+                  uri_len);
+  if (NULL != qmark)
+    *qmark = '\0';
+
+  /* Need to unescape URI before comparing with connection->url */
+  uri_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                       connection,
+                                       uri);
+  if ((uri_len != connection->rq.url_len) ||
+      (0 != memcmp (uri, connection->rq.url, uri_len)))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Authentication failed, URI does not match.\n"));
+#endif
+    return false;
+  }
+
+  args = (NULL != qmark) ? (qmark + 1) : uri + uri_len;
+
+  if (! check_argument_match (connection,
+                              args) )
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Authentication failed, arguments do not match.\n"));
+#endif
+    return false;
+  }
+  return true;
+}
+
+
+/**
+ * The size of the unquoting buffer in stack
+ */
+#define _MHD_STATIC_UNQ_BUFFER_SIZE 128
+
+
+/**
+ * Get the pointer to buffer with required size
+ * @param tmp1 the first buffer with fixed size
+ * @param ptmp2 the pointer to pointer to malloc'ed buffer
+ * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2
+ * @param required_size the required size in buffer
+ * @return the pointer to the buffer or NULL if failed to allocate buffer with
+ *         requested size
+ */
+static char *
+get_buffer_for_size (char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE],
+                     char **ptmp2,
+                     size_t *ptmp2_size,
+                     size_t required_size)
+{
+  mhd_assert ((0 == *ptmp2_size) || (NULL != *ptmp2));
+  mhd_assert ((NULL != *ptmp2) || (0 == *ptmp2_size));
+  mhd_assert ((0 == *ptmp2_size) || \
+              (_MHD_STATIC_UNQ_BUFFER_SIZE < *ptmp2_size));
+
+  if (required_size <= _MHD_STATIC_UNQ_BUFFER_SIZE)
+    return tmp1;
+
+  if (required_size <= *ptmp2_size)
+    return *ptmp2;
+
+  if (required_size > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE)
+    return NULL;
+  if (NULL != *ptmp2)
+    free (*ptmp2);
+  *ptmp2 = (char *) malloc (required_size);
+  if (NULL == *ptmp2)
+    *ptmp2_size = 0;
+  else
+    *ptmp2_size = required_size;
+  return *ptmp2;
+}
+
+
+/**
+  * The result of parameter unquoting
+  */
+enum _MHD_GetUnqResult
+{
+  _MHD_UNQ_OK = 0,         /**< Got unquoted string */
+  _MHD_UNQ_TOO_LARGE = -7, /**< The string is too large to unquote */
+  _MHD_UNQ_OUT_OF_MEM = 3  /**< Out of memory error */
+};
+
+/**
+ * Get Digest authorisation parameter as unquoted string.
+ * @param param the parameter to process
+ * @param tmp1 the small buffer in stack
+ * @param ptmp2 the pointer to pointer to malloc'ed buffer
+ * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2
+ * @param[out] unquoted the pointer to store the result, NOT zero terminated
+ * @return enum code indicating result of the process
+ */
+static enum _MHD_GetUnqResult
+get_unquoted_param (const struct MHD_RqDAuthParam *param,
+                    char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE],
+                    char **ptmp2,
+                    size_t *ptmp2_size,
+                    struct _MHD_str_w_len *unquoted)
+{
+  char *str;
+  size_t len;
+  mhd_assert (NULL != param->value.str);
+  mhd_assert (0 != param->value.len);
+
+  if (! param->quoted)
+  {
+    unquoted->str = param->value.str;
+    unquoted->len = param->value.len;
+    return _MHD_UNQ_OK;
+  }
+  /* The value is present and is quoted, needs to be copied and unquoted */
+  str = get_buffer_for_size (tmp1, ptmp2, ptmp2_size, param->value.len);
+  if (NULL == str)
+    return (param->value.len > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) ?
+           _MHD_UNQ_TOO_LARGE : _MHD_UNQ_OUT_OF_MEM;
+
+  len = MHD_str_unquote (param->value.str, param->value.len, str);
+  unquoted->str = str;
+  unquoted->len = len;
+  mhd_assert (0 != unquoted->len);
+  mhd_assert (unquoted->len < param->value.len);
+  return _MHD_UNQ_OK;
+}
+
+
+/**
+ * Get copy of Digest authorisation parameter as unquoted string.
+ * @param param the parameter to process
+ * @param tmp1 the small buffer in stack
+ * @param ptmp2 the pointer to pointer to malloc'ed buffer
+ * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2
+ * @param[out] unquoted the pointer to store the result, NOT zero terminated,
+ *                      but with enough space to zero-terminate
+ * @return enum code indicating result of the process
+ */
+static enum _MHD_GetUnqResult
+get_unquoted_param_copy (const struct MHD_RqDAuthParam *param,
+                         char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE],
+                         char **ptmp2,
+                         size_t *ptmp2_size,
+                         struct _MHD_mstr_w_len *unquoted)
+{
+  mhd_assert (NULL != param->value.str);
+  mhd_assert (0 != param->value.len);
+
+  /* The value is present and is quoted, needs to be copied and unquoted */
+  /* Allocate buffer with one more additional byte for zero-termination */
+  unquoted->str =
+    get_buffer_for_size (tmp1, ptmp2, ptmp2_size, param->value.len + 1);
+
+  if (NULL == unquoted->str)
+    return (param->value.len + 1 > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) ?
+           _MHD_UNQ_TOO_LARGE : _MHD_UNQ_OUT_OF_MEM;
+
+  if (! param->quoted)
+  {
+    memcpy (unquoted->str, param->value.str, param->value.len);
+    unquoted->len = param->value.len;
+    return _MHD_UNQ_OK;
+  }
+
+  unquoted->len =
+    MHD_str_unquote (param->value.str, param->value.len, unquoted->str);
+  mhd_assert (0 != unquoted->len);
+  mhd_assert (unquoted->len < param->value.len);
+  return _MHD_UNQ_OK;
+}
+
+
+/**
+ * Check whether Digest Auth request parameter is equal to given string
+ * @param param the parameter to check
+ * @param str the string to compare with, does not need to be zero-terminated
+ * @param str_len the length of the @a str
+ * @return true is parameter is equal to the given string,
+ *         false otherwise
+ */
+_MHD_static_inline bool
+is_param_equal (const struct MHD_RqDAuthParam *param,
+                const char *const str,
+                const size_t str_len)
+{
+  mhd_assert (NULL != param->value.str);
+  mhd_assert (0 != param->value.len);
+  if (param->quoted)
+    return MHD_str_equal_quoted_bin_n (param->value.str, param->value.len,
+                                       str, str_len);
+  return (str_len == param->value.len) &&
+         (0 == memcmp (str, param->value.str, str_len));
+
+}
+
+
+/**
+ * Check whether Digest Auth request parameter is caseless equal to given string
+ * @param param the parameter to check
+ * @param str the string to compare with, does not need to be zero-terminated
+ * @param str_len the length of the @a str
+ * @return true is parameter is caseless equal to the given string,
+ *         false otherwise
+ */
+_MHD_static_inline bool
+is_param_equal_caseless (const struct MHD_RqDAuthParam *param,
+                         const char *const str,
+                         const size_t str_len)
+{
+  mhd_assert (NULL != param->value.str);
+  mhd_assert (0 != param->value.len);
+  if (param->quoted)
+    return MHD_str_equal_quoted_bin_n (param->value.str, param->value.len,
+                                       str, str_len);
+  return (str_len == param->value.len) &&
+         (0 == memcmp (str, param->value.str, str_len));
+
 }
 
 
 /**
  * Authenticates the authorization header sent by the client
  *
- * @param connection The MHD connection structure
- * @param realm The realm presented to the client
- * @param username The username needs to be authenticated
- * @param password The password used in the authentication
- * @param nonce_timeout The amount of time for a nonce to be
- * 			invalid in seconds
- * @return #MHD_YES if authenticated, #MHD_NO if not,
- * 			#MHD_INVALID_NONCE if nonce is invalid
+ * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in
+ * @a mqop and the client uses this mode, then server generated nonces are
+ * used as one-time nonces because nonce-count is not supported in this old RFC.
+ * Communication in this mode is very inefficient, especially if the client
+ * requests several resources one-by-one as for every request new nonce must be
+ * generated and client repeat all requests twice (first time to get a new
+ * nonce and second time to perform an authorised request).
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param username the username needs to be authenticated
+ * @param password the password used in the authentication
+ * @param userdigest the optional precalculated binary hash of the string
+ *                   "username:realm:password"
+ * @param nonce_timeout the period of seconds since nonce generation, when
+ *                      the nonce is recognised as valid and not stale.
+ * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc
+ *               exceeds the specified value then MHD_DAUTH_NONCE_STALE is
+ *               returned;
+ *               zero for no limit
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithms allowed to use, fail if algorithm specified
+ *               by the client is not allowed by this parameter
+ * @param[out] pbuf the pointer to pointer to internally malloc'ed buffer,
+ *                  to be free if not NULL upon return
+ * @return #MHD_DAUTH_OK if authenticated,
+ *         error code otherwise.
  * @ingroup authentication
  */
-int
-MHD_digest_auth_check (struct MHD_Connection *connection,
-		       const char *realm,
-		       const char *username,
-		       const char *password,
-		       unsigned int nonce_timeout)
+static enum MHD_DigestAuthResult
+digest_auth_check_all_inner (struct MHD_Connection *connection,
+                             const char *realm,
+                             const char *username,
+                             const char *password,
+                             const uint8_t *userdigest,
+                             unsigned int nonce_timeout,
+                             uint32_t max_nc,
+                             enum MHD_DigestAuthMultiQOP mqop,
+                             enum MHD_DigestAuthMultiAlgo3 malgo3,
+                             char **pbuf,
+                             struct DigestAlgorithm *da)
 {
-  size_t len;
-  const char *header;
-  char *end;
-  char nonce[MAX_NONCE_LENGTH];
-  char cnonce[MAX_NONCE_LENGTH];
-  char qop[15]; /* auth,auth-int */
-  char nc[20];
-  char response[MAX_AUTH_RESPONSE_LENGTH];
+  struct MHD_Daemon *daemon = MHD_get_master (connection->daemon);
+  enum MHD_DigestAuthAlgo3 c_algo; /**< Client's algorithm */
+  enum MHD_DigestAuthQOP c_qop; /**< Client's QOP */
+  unsigned int digest_size;
+  uint8_t hash1_bin[MAX_DIGEST];
+  uint8_t hash2_bin[MAX_DIGEST];
+#if 0
   const char *hentity = NULL; /* "auth-int" is not supported */
-  char ha1[HASH_MD5_HEX_LEN + 1];
-  char respexp[HASH_MD5_HEX_LEN + 1];
-  char noncehashexp[HASH_MD5_HEX_LEN + 9];
-  uint32_t nonce_time;
-  uint32_t t;
-  size_t left; /* number of characters left in 'header' for 'uri' */
-  unsigned long int nci;
+#endif
+  uint64_t nonce_time;
+  uint64_t nci;
+  const struct MHD_RqDAuth *params;
+  /**
+   * Temporal buffer in stack for unquoting and other needs
+   */
+  char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE];
+  char **const ptmp2 = pbuf;     /**< Temporal malloc'ed buffer for unquoting */
+  size_t tmp2_size; /**< The size of @a tmp2 buffer */
+  struct _MHD_str_w_len unquoted;
+  struct _MHD_mstr_w_len unq_copy;
+  enum _MHD_GetUnqResult unq_res;
+  size_t username_len;
+  size_t realm_len;
 
-  header = MHD_lookup_connection_value (connection,
-					MHD_HEADER_KIND,
-					MHD_HTTP_HEADER_AUTHORIZATION);
-  if (NULL == header)
-    return MHD_NO;
-  if (0 != strncmp(header, _BASE, strlen(_BASE)))
-    return MHD_NO;
-  header += strlen (_BASE);
-  left = strlen (header);
+  tmp2_size = 0;
 
+  params = MHD_get_rq_dauth_params_ (connection);
+  if (NULL == params)
+    return MHD_DAUTH_WRONG_HEADER;
+
+  /* ** Initial parameters checks and setup ** */
+  /* Get client's algorithm */
+  c_algo = params->algo3;
+  /* Check whether client's algorithm is allowed by function parameter */
+  if (((unsigned int) c_algo) !=
+      (((unsigned int) c_algo) & ((unsigned int) malgo3)))
+    return MHD_DAUTH_WRONG_ALGO;
+  /* Check whether client's algorithm is supported */
+  if (0 != (((unsigned int) c_algo) & MHD_DIGEST_AUTH_ALGO3_SESSION))
   {
-    char un[MAX_USERNAME_LENGTH];
-
-    len = lookup_sub_value (un,
-			    sizeof (un),
-			    header, "username");
-    if ( (0 == len) ||
-	 (0 != strcmp(username, un)) )
-      return MHD_NO;
-    left -= strlen ("username") + len;
-  }
-
-  {
-    char r[MAX_REALM_LENGTH];
-
-    len = lookup_sub_value(r,
-			   sizeof (r),
-			   header, "realm");
-    if ( (0 == len) ||
-	 (0 != strcmp(realm, r)) )
-      return MHD_NO;
-    left -= strlen ("realm") + len;
-  }
-
-  if (0 == (len = lookup_sub_value (nonce,
-				    sizeof (nonce),
-				    header, "nonce")))
-    return MHD_NO;
-  left -= strlen ("nonce") + len;
-  if (left > 32 * 1024)
-  {
-    /* we do not permit URIs longer than 32k, as we want to
-       make sure to not blow our stack (or per-connection
-       heap memory limit).  Besides, 32k is already insanely
-       large, but of course in theory the
-       #MHD_OPTION_CONNECTION_MEMORY_LIMIT might be very large
-       and would thus permit sending a >32k authorization
-       header value. */
-    return MHD_NO;
-  }
-  {
-    char *uri;
-    
-    uri = malloc(left + 1);
-    if (NULL == uri)
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG(connection->daemon,
-               "Failed to allocate memory for auth header processing\n");
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The 'session' algorithms are not supported.\n"));
 #endif /* HAVE_MESSAGES */
-      return MHD_NO;
-    }
-    if (0 == lookup_sub_value (uri,
-                               left + 1,
-                               header, "uri"))
-    {
-      free(uri);
-      return MHD_NO;
-    }
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#ifndef MHD_MD5_SUPPORT
+  if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_MD5))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The MD5 algorithm is not supported by this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#endif /* ! MHD_MD5_SUPPORT */
+#ifndef MHD_SHA256_SUPPORT
+  if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_SHA256))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The SHA-256 algorithm is not supported by "
+                 "this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#endif /* ! MHD_SHA256_SUPPORT */
+#ifndef MHD_SHA512_256_SUPPORT
+  if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_SHA512_256))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The SHA-512/256 algorithm is not supported by "
+                 "this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#endif /* ! MHD_SHA512_256_SUPPORT */
+  if (! digest_init_one_time (da, get_base_digest_algo (c_algo)))
+    MHD_PANIC (_ ("Wrong 'malgo3' value, API violation"));
+  /* Check 'mqop' value */
+  c_qop = params->qop;
+  /* Check whether client's QOP is allowed by function parameter */
+  if (((unsigned int) c_qop) !=
+      (((unsigned int) c_qop) & ((unsigned int) mqop)))
+    return MHD_DAUTH_WRONG_QOP;
+  if (0 != (((unsigned int) c_qop) & MHD_DIGEST_AUTH_QOP_AUTH_INT))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The 'auth-int' QOP is not supported.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_QOP;
+  }
+#ifdef HAVE_MESSAGES
+  if ((MHD_DIGEST_AUTH_QOP_NONE == c_qop) &&
+      (0 == (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_MD5)))
+    MHD_DLOG (connection->daemon,
+              _ ("RFC2069 with SHA-256 or SHA-512/256 algorithm is " \
+                 "non-standard extension.\n"));
+#endif /* HAVE_MESSAGES */
 
-    /* 8 = 4 hexadecimal numbers for the timestamp */
-    nonce_time = strtoul (nonce + len - 8, (char **)NULL, 16);
-    t = (uint32_t) MHD_monotonic_time();
+  digest_size = digest_get_size (da);
+
+  /* ** A quick check for presence of all required parameters ** */
+
+  if ((NULL == params->username.value.str) &&
+      (NULL == params->username_ext.value.str))
+    return MHD_DAUTH_WRONG_USERNAME;
+  else if ((NULL != params->username.value.str) &&
+           (NULL != params->username_ext.value.str))
+    return MHD_DAUTH_WRONG_USERNAME; /* Parameters cannot be used together */
+  else if ((NULL != params->username_ext.value.str) &&
+           (MHD_DAUTH_EXT_PARAM_MIN_LEN > params->username_ext.value.len))
+    return MHD_DAUTH_WRONG_USERNAME;  /* Broken extended notation */
+  else if (params->userhash && (NULL == params->username.value.str))
+    return MHD_DAUTH_WRONG_USERNAME;  /* Userhash cannot be used with extended notation */
+  else if (params->userhash && (digest_size * 2 > params->username.value.len))
+    return MHD_DAUTH_WRONG_USERNAME;  /* Too few chars for correct userhash */
+  else if (params->userhash && (digest_size * 4 < params->username.value.len))
+    return MHD_DAUTH_WRONG_USERNAME;  /* Too many chars for correct userhash */
+
+  if (NULL == params->realm.value.str)
+    return MHD_DAUTH_WRONG_REALM;
+  else if (((NULL == userdigest) || params->userhash) &&
+           (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->realm.value.len))
+    return MHD_DAUTH_TOO_LARGE; /* Realm is too large and should be used in hash calculations */
+
+  if (MHD_DIGEST_AUTH_QOP_NONE != c_qop)
+  {
+    if (NULL == params->nc.value.str)
+      return MHD_DAUTH_WRONG_HEADER;
+    else if (0 == params->nc.value.len)
+      return MHD_DAUTH_WRONG_HEADER;
+    else if (4 * 8 < params->nc.value.len) /* Four times more than needed */
+      return MHD_DAUTH_WRONG_HEADER;
+
+    if (NULL == params->cnonce.value.str)
+      return MHD_DAUTH_WRONG_HEADER;
+    else if (0 == params->cnonce.value.len)
+      return MHD_DAUTH_WRONG_HEADER;
+    else if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->cnonce.value.len)
+      return MHD_DAUTH_TOO_LARGE;
+  }
+
+  /* The QOP parameter was checked already */
+
+  if (NULL == params->uri.value.str)
+    return MHD_DAUTH_WRONG_URI;
+  else if (0 == params->uri.value.len)
+    return MHD_DAUTH_WRONG_URI;
+  else if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->uri.value.len)
+    return MHD_DAUTH_TOO_LARGE;
+
+  if (NULL == params->nonce.value.str)
+    return MHD_DAUTH_NONCE_WRONG;
+  else if (0 == params->nonce.value.len)
+    return MHD_DAUTH_NONCE_WRONG;
+  else if (NONCE_STD_LEN (digest_size) * 2 < params->nonce.value.len)
+    return MHD_DAUTH_NONCE_WRONG;
+
+  if (NULL == params->response.value.str)
+    return MHD_DAUTH_RESPONSE_WRONG;
+  else if (0 == params->response.value.len)
+    return MHD_DAUTH_RESPONSE_WRONG;
+  else if (digest_size * 4 < params->response.value.len)
+    return MHD_DAUTH_RESPONSE_WRONG;
+
+  /* ** Check simple parameters match ** */
+
+  /* Check 'algorithm' */
+  /* The 'algorithm' was checked at the start of the function */
+  /* 'algorithm' valid */
+
+  /* Check 'qop' */
+  /* The 'qop' was checked at the start of the function */
+  /* 'qop' valid */
+
+  /* Check 'realm' */
+  realm_len = strlen (realm);
+  if (! is_param_equal (&params->realm, realm, realm_len))
+    return MHD_DAUTH_WRONG_REALM;
+  /* 'realm' valid */
+
+  /* Check 'username' */
+  username_len = strlen (username);
+  if (! params->userhash)
+  {
+    if (NULL != params->username.value.str)
+    { /* Username in standard notation */
+      if (! is_param_equal (&params->username, username, username_len))
+        return MHD_DAUTH_WRONG_USERNAME;
+    }
+    else
+    { /* Username in extended notation */
+      char *r_uname;
+      size_t buf_size = params->username_ext.value.len;
+      ssize_t res;
+
+      mhd_assert (NULL != params->username_ext.value.str);
+      mhd_assert (MHD_DAUTH_EXT_PARAM_MIN_LEN <= buf_size); /* It was checked already */
+      buf_size += 1; /* For zero-termination */
+      buf_size -= MHD_DAUTH_EXT_PARAM_MIN_LEN;
+      r_uname = get_buffer_for_size (tmp1, ptmp2, &tmp2_size, buf_size);
+      if (NULL == r_uname)
+        return (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < buf_size) ?
+               MHD_DAUTH_TOO_LARGE : MHD_DAUTH_ERROR;
+      res = get_rq_extended_uname_copy_z (params->username_ext.value.str,
+                                          params->username_ext.value.len,
+                                          r_uname, buf_size);
+      if (0 > res)
+        return MHD_DAUTH_WRONG_HEADER; /* Broken extended notation */
+      if ((username_len != (size_t) res) ||
+          (0 != memcmp (username, r_uname, username_len)))
+        return MHD_DAUTH_WRONG_USERNAME;
+    }
+  }
+  else
+  { /* Userhash */
+    mhd_assert (NULL != params->username.value.str);
+    calc_userhash (da, username, username_len, realm, realm_len, hash1_bin);
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+    if (digest_ext_error (da))
+      return MHD_DAUTH_ERROR;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+    mhd_assert (sizeof (tmp1) >= (2 * digest_size));
+    MHD_bin_to_hex (hash1_bin, digest_size, tmp1);
+    if (! is_param_equal_caseless (&params->username, tmp1, 2 * digest_size))
+      return MHD_DAUTH_WRONG_USERNAME;
+    /* To simplify the logic, the digest is reset here instead of resetting
+       before the next hash calculation. */
+    digest_reset (da);
+  }
+  /* 'username' valid */
+
+  /* ** Do basic nonce and nonce-counter checks (size, timestamp) ** */
+
+  /* Get 'nc' digital value */
+  if (MHD_DIGEST_AUTH_QOP_NONE != c_qop)
+  {
+
+    unq_res = get_unquoted_param (&params->nc, tmp1, ptmp2, &tmp2_size,
+                                  &unquoted);
+    if (_MHD_UNQ_OK != unq_res)
+      return MHD_DAUTH_ERROR;
+
+    if (unquoted.len != MHD_strx_to_uint64_n_ (unquoted.str,
+                                               unquoted.len,
+                                               &nci))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Authentication failed, invalid nc format.\n"));
+#endif
+      return MHD_DAUTH_WRONG_HEADER;   /* invalid nonce format */
+    }
+    if (0 == nci)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Authentication failed, invalid 'nc' value.\n"));
+#endif
+      return MHD_DAUTH_WRONG_HEADER;   /* invalid nc value */
+    }
+    if ((0 != max_nc) && (max_nc < nci))
+      return MHD_DAUTH_NONCE_STALE;    /* Too large 'nc' value */
+  }
+  else
+    nci = 1; /* Force 'nc' value */
+  /* Got 'nc' digital value */
+
+  /* Get 'nonce' with basic checks */
+  unq_res = get_unquoted_param (&params->nonce, tmp1, ptmp2, &tmp2_size,
+                                &unquoted);
+  if (_MHD_UNQ_OK != unq_res)
+    return MHD_DAUTH_ERROR;
+
+  if ((NONCE_STD_LEN (digest_size) != unquoted.len) ||
+      (! get_nonce_timestamp (unquoted.str, unquoted.len, &nonce_time)))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (daemon,
+              _ ("Authentication failed, invalid nonce format.\n"));
+#endif
+    return MHD_DAUTH_NONCE_WRONG;
+  }
+
+  if (1)
+  {
+    uint64_t t;
+
+    t = MHD_monotonic_msec_counter ();
     /*
      * First level vetting for the nonce validity: if the timestamp
      * attached to the nonce exceeds `nonce_timeout', then the nonce is
      * invalid.
      */
-    if ( (t > nonce_time + nonce_timeout) ||
-	 (nonce_time + nonce_timeout < nonce_time) )
-    { 
-      free(uri);
-      return MHD_INVALID_NONCE;
-    }
-    if (0 != strncmp (uri,
-		      connection->url,
-		      strlen (connection->url)))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-		"Authentication failed, URI does not match.\n");
-#endif
-      free(uri);
-      return MHD_NO;
-    }
-    {
-      const char *args = strchr (uri, '?');
-
-      if (NULL == args)
-	args = "";
-      else
-	args++;
-      if (MHD_YES !=
-	  check_argument_match (connection,
-				args) )
-      {
-#if HAVE_MESSAGES
-	MHD_DLOG (connection->daemon,
-		  "Authentication failed, arguments do not match.\n");
-#endif
-       free(uri);
-       return MHD_NO;
-      }
-    }
-    calculate_nonce (nonce_time,
-		     connection->method,
-		     connection->daemon->digest_auth_random,
-		     connection->daemon->digest_auth_rand_size,
-		     connection->url,
-		     realm,
-		     noncehashexp);
-    /*
-     * Second level vetting for the nonce validity
-     * if the timestamp attached to the nonce is valid
-     * and possibly fabricated (in case of an attack)
-     * the attacker must also know the random seed to be
-     * able to generate a "sane" nonce, which if he does
-     * not, the nonce fabrication process going to be
-     * very hard to achieve.
-     */
-
-    if (0 != strcmp (nonce, noncehashexp))
-    {
-      free(uri);
-      return MHD_INVALID_NONCE;
-    }
-    if ( (0 == lookup_sub_value (cnonce,
-				 sizeof (cnonce),
-				 header, "cnonce")) ||
-	 (0 == lookup_sub_value (qop, sizeof (qop), header, "qop")) ||
-	 ( (0 != strcmp (qop, "auth")) &&
-	   (0 != strcmp (qop, "")) ) ||
-	 (0 == lookup_sub_value (nc, sizeof (nc), header, "nc"))  ||
-	 (0 == lookup_sub_value (response, sizeof (response), header, "response")) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-		"Authentication failed, invalid format.\n");
-#endif
-      free(uri);
-      return MHD_NO;
-    }
-    nci = strtoul (nc, &end, 16);
-    if ( ('\0' != *end) ||
-	 ( (LONG_MAX == nci) &&
-	   (ERANGE == errno) ) )
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-		"Authentication failed, invalid format.\n");
-#endif
-      free(uri);
-      return MHD_NO; /* invalid nonce format */
-    }
+    if (TRIM_TO_TIMESTAMP (t - nonce_time) > (nonce_timeout * 1000))
+      return MHD_DAUTH_NONCE_STALE; /* too old */
+  }
+  if (1)
+  {
+    enum MHD_CheckNonceNC_ nonce_nc_check;
     /*
      * Checking if that combination of nonce and nc is sound
-     * and not a replay attack attempt. Also adds the nonce
-     * to the nonce-nc map if it does not exist there.
+     * and not a replay attack attempt. Refuse if nonce was not
+     * generated previously.
      */
-
-    if (MHD_YES != check_nonce_nc (connection, nonce, nci))
+    nonce_nc_check = check_nonce_nc (connection,
+                                     unquoted.str,
+                                     NONCE_STD_LEN (digest_size),
+                                     nonce_time,
+                                     nci);
+    if (MHD_CHECK_NONCENC_STALE == nonce_nc_check)
     {
-      free(uri);
+#ifdef HAVE_MESSAGES
+      if (MHD_DIGEST_AUTH_QOP_NONE != c_qop)
+        MHD_DLOG (daemon,
+                  _ ("Stale nonce received. If this happens a lot, you should "
+                     "probably increase the size of the nonce array.\n"));
+      else
+        MHD_DLOG (daemon,
+                  _ ("Stale nonce received. This is expected when client " \
+                     "uses RFC2069-compatible mode and makes more than one " \
+                     "request.\n"));
+#endif
+      return MHD_DAUTH_NONCE_STALE;
+    }
+    else if (MHD_CHECK_NONCENC_WRONG == nonce_nc_check)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Received nonce that was not "
+                   "generated by MHD. This may indicate an attack attempt.\n"));
+#endif
+      return MHD_DAUTH_NONCE_WRONG;
+    }
+    mhd_assert (MHD_CHECK_NONCENC_OK == nonce_nc_check);
+  }
+  /* The nonce was generated by MHD, is not stale and nonce-nc combination was
+     not used before */
+
+  /* ** Build H(A2) and check URI match in the header and in the request ** */
+
+  /* Get 'uri' */
+  mhd_assert (! da->hashing);
+  digest_update_str (da, connection->rq.method);
+  digest_update_with_colon (da);
+#if 0
+  /* TODO: add support for "auth-int" */
+  digest_update_str (da, hentity);
+  digest_update_with_colon (da);
+#endif
+  unq_res = get_unquoted_param_copy (&params->uri, tmp1, ptmp2, &tmp2_size,
+                                     &unq_copy);
+  if (_MHD_UNQ_OK != unq_res)
+    return MHD_DAUTH_ERROR;
+
+  digest_update (da, unq_copy.str, unq_copy.len);
+  /* The next check will modify copied URI string */
+  if (! check_uri_match (connection, unq_copy.str, unq_copy.len))
+    return MHD_DAUTH_WRONG_URI;
+  digest_calc_hash (da, hash2_bin);
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+  /* Skip digest calculation external error check, the next one checks both */
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+  /* Got H(A2) */
+
+  /* ** Build H(A1) ** */
+  if (NULL == userdigest)
+  {
+    mhd_assert (! da->hashing);
+    digest_reset (da);
+    calc_userdigest (da,
+                     username, username_len,
+                     realm, realm_len,
+                     password,
+                     hash1_bin);
+  }
+  /* TODO: support '-sess' versions */
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+  if (digest_ext_error (da))
+    return MHD_DAUTH_ERROR;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+  /* Got H(A1) */
+
+  /* **  Check 'response' ** */
+
+  mhd_assert (! da->hashing);
+  digest_reset (da);
+  /* Update digest with H(A1) */
+  mhd_assert (sizeof (tmp1) >= (digest_size * 2));
+  if (NULL == userdigest)
+    MHD_bin_to_hex (hash1_bin, digest_size, tmp1);
+  else
+    MHD_bin_to_hex (userdigest, digest_size, tmp1);
+  digest_update (da, (const uint8_t *) tmp1, digest_size * 2);
+
+  /* H(A1) is not needed anymore, reuse the buffer.
+   * Use hash1_bin for the client's 'response' decoded to binary form. */
+  unq_res = get_unquoted_param (&params->response, tmp1, ptmp2, &tmp2_size,
+                                &unquoted);
+  if (_MHD_UNQ_OK != unq_res)
+    return MHD_DAUTH_ERROR;
+  if (digest_size != MHD_hex_to_bin (unquoted.str, unquoted.len, hash1_bin))
+    return MHD_DAUTH_RESPONSE_WRONG;
+
+  /* Update digest with ':' */
+  digest_update_with_colon (da);
+  /* Update digest with 'nonce' text value */
+  unq_res = get_unquoted_param (&params->nonce, tmp1, ptmp2, &tmp2_size,
+                                &unquoted);
+  if (_MHD_UNQ_OK != unq_res)
+    return MHD_DAUTH_ERROR;
+  digest_update (da, (const uint8_t *) unquoted.str, unquoted.len);
+  /* Update digest with ':' */
+  digest_update_with_colon (da);
+  if (MHD_DIGEST_AUTH_QOP_NONE != c_qop)
+  {
+    /* Update digest with 'nc' text value */
+    unq_res = get_unquoted_param (&params->nc, tmp1, ptmp2, &tmp2_size,
+                                  &unquoted);
+    if (_MHD_UNQ_OK != unq_res)
+      return MHD_DAUTH_ERROR;
+    digest_update (da, (const uint8_t *) unquoted.str, unquoted.len);
+    /* Update digest with ':' */
+    digest_update_with_colon (da);
+    /* Update digest with 'cnonce' value */
+    unq_res = get_unquoted_param (&params->cnonce, tmp1, ptmp2, &tmp2_size,
+                                  &unquoted);
+    if (_MHD_UNQ_OK != unq_res)
+      return MHD_DAUTH_ERROR;
+    digest_update (da, (const uint8_t *) unquoted.str, unquoted.len);
+    /* Update digest with ':' */
+    digest_update_with_colon (da);
+    /* Update digest with 'qop' value */
+    unq_res = get_unquoted_param (&params->qop_raw, tmp1, ptmp2, &tmp2_size,
+                                  &unquoted);
+    if (_MHD_UNQ_OK != unq_res)
+      return MHD_DAUTH_ERROR;
+    digest_update (da, (const uint8_t *) unquoted.str, unquoted.len);
+    /* Update digest with ':' */
+    digest_update_with_colon (da);
+  }
+  /* Update digest with H(A2) */
+  MHD_bin_to_hex (hash2_bin, digest_size, tmp1);
+  digest_update (da, (const uint8_t *) tmp1, digest_size * 2);
+
+  /* H(A2) is not needed anymore, reuse the buffer.
+   * Use hash2_bin for the calculated response in binary form */
+  digest_calc_hash (da, hash2_bin);
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+  if (digest_ext_error (da))
+    return MHD_DAUTH_ERROR;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+
+  if (0 != memcmp (hash1_bin, hash2_bin, digest_size))
+    return MHD_DAUTH_RESPONSE_WRONG;
+
+  if (MHD_DAUTH_BIND_NONCE_NONE != daemon->dauth_bind_type)
+  {
+    mhd_assert (sizeof(tmp1) >= (NONCE_STD_LEN (digest_size) + 1));
+    /* It was already checked that 'nonce' (including timestamp) was generated
+       by MHD. */
+    mhd_assert (! da->hashing);
+    digest_reset (da);
+    calculate_nonce (nonce_time,
+                     connection->rq.http_mthd,
+                     connection->rq.method,
+                     daemon->digest_auth_random,
+                     daemon->digest_auth_rand_size,
+                     connection->addr,
+                     (size_t) connection->addr_len,
+                     connection->rq.url,
+                     connection->rq.url_len,
+                     connection->rq.headers_received,
+                     realm,
+                     realm_len,
+                     daemon->dauth_bind_type,
+                     da,
+                     tmp1);
+
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+    if (digest_ext_error (da))
+      return MHD_DAUTH_ERROR;
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+
+    if (! is_param_equal (&params->nonce, tmp1,
+                          NONCE_STD_LEN (digest_size)))
+      return MHD_DAUTH_NONCE_OTHER_COND;
+    /* The 'nonce' was generated in the same conditions */
+  }
+
+  return MHD_DAUTH_OK;
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client
+ *
+ * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in
+ * @a mqop and the client uses this mode, then server generated nonces are
+ * used as one-time nonces because nonce-count is not supported in this old RFC.
+ * Communication in this mode is very inefficient, especially if the client
+ * requests several resources one-by-one as for every request new nonce must be
+ * generated and client repeat all requests twice (first time to get a new
+ * nonce and second time to perform an authorised request).
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param username the username needs to be authenticated
+ * @param password the password used in the authentication
+ * @param userdigest the optional precalculated binary hash of the string
+ *                   "username:realm:password"
+ * @param nonce_timeout the period of seconds since nonce generation, when
+ *                      the nonce is recognised as valid and not stale.
+ * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc
+ *               exceeds the specified value then MHD_DAUTH_NONCE_STALE is
+ *               returned;
+ *               zero for no limit
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithms allowed to use, fail if algorithm specified
+ *               by the client is not allowed by this parameter
+ * @return #MHD_DAUTH_OK if authenticated,
+ *         error code otherwise.
+ * @ingroup authentication
+ */
+static enum MHD_DigestAuthResult
+digest_auth_check_all (struct MHD_Connection *connection,
+                       const char *realm,
+                       const char *username,
+                       const char *password,
+                       const uint8_t *userdigest,
+                       unsigned int nonce_timeout,
+                       uint32_t max_nc,
+                       enum MHD_DigestAuthMultiQOP mqop,
+                       enum MHD_DigestAuthMultiAlgo3 malgo3)
+{
+  enum MHD_DigestAuthResult res;
+  char *buf;
+  struct DigestAlgorithm da;
+
+  buf = NULL;
+  digest_setup_zero (&da);
+  res = digest_auth_check_all_inner (connection, realm, username, password,
+                                     userdigest,
+                                     nonce_timeout,
+                                     max_nc, mqop, malgo3,
+                                     &buf, &da);
+  digest_deinit (&da);
+  if (NULL != buf)
+    free (buf);
+
+  return res;
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ * Uses #MHD_DIGEST_ALG_MD5 (for now, for backwards-compatibility).
+ * Note that this MAY change to #MHD_DIGEST_ALG_AUTO in the future.
+ * If you want to be sure you get MD5, use #MHD_digest_auth_check2()
+ * and specify MD5 explicitly.
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param password The password used in the authentication
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @deprecated use MHD_digest_auth_check3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check (struct MHD_Connection *connection,
+                       const char *realm,
+                       const char *username,
+                       const char *password,
+                       unsigned int nonce_timeout)
+{
+  return MHD_digest_auth_check2 (connection,
+                                 realm,
+                                 username,
+                                 password,
+                                 nonce_timeout,
+                                 MHD_DIGEST_ALG_MD5);
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ *
+ * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in
+ * @a mqop and the client uses this mode, then server generated nonces are
+ * used as one-time nonces because nonce-count is not supported in this old RFC.
+ * Communication in this mode is very inefficient, especially if the client
+ * requests several resources one-by-one as for every request new nonce must be
+ * generated and client repeat all requests twice (first time to get a new
+ * nonce and second time to perform an authorised request).
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm to be used for authorization of the client
+ * @param username the username needs to be authenticated, must be in clear text
+ *                 even if userhash is used by the client
+ * @param password the password used in the authentication
+ * @param nonce_timeout the nonce validity duration in seconds
+ * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc
+ *               exceeds the specified value then MHD_DAUTH_NONCE_STALE is
+ *               returned;
+ *               zero for no limit
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithms allowed to use, fail if algorithm used
+ *               by the client is not allowed by this parameter
+ * @return #MHD_DAUTH_OK if authenticated,
+ *         the error code otherwise
+ * @note Available since #MHD_VERSION 0x00097528
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_DigestAuthResult
+MHD_digest_auth_check3 (struct MHD_Connection *connection,
+                        const char *realm,
+                        const char *username,
+                        const char *password,
+                        unsigned int nonce_timeout,
+                        uint32_t max_nc,
+                        enum MHD_DigestAuthMultiQOP mqop,
+                        enum MHD_DigestAuthMultiAlgo3 malgo3)
+{
+  mhd_assert (NULL != password);
+
+  return digest_auth_check_all (connection,
+                                realm,
+                                username,
+                                password,
+                                NULL,
+                                nonce_timeout,
+                                max_nc,
+                                mqop,
+                                malgo3);
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client by using
+ * hash of "username:realm:password".
+ *
+ * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in
+ * @a mqop and the client uses this mode, then server generated nonces are
+ * used as one-time nonces because nonce-count is not supported in this old RFC.
+ * Communication in this mode is very inefficient, especially if the client
+ * requests several resources one-by-one as for every request new nonce must be
+ * generated and client repeat all requests twice (first time to get a new
+ * nonce and second time to perform an authorised request).
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm to be used for authorization of the client
+ * @param username the username needs to be authenticated, must be in clear text
+ *                 even if userhash is used by the client
+ * @param userdigest the precalculated binary hash of the string
+ *                   "username:realm:password",
+ *                   see #MHD_digest_auth_calc_userdigest()
+ * @param userdigest_size the size of the @a userdigest in bytes, must match the
+ *                        hashing algorithm (see #MHD_MD5_DIGEST_SIZE,
+ *                        #MHD_SHA256_DIGEST_SIZE, #MHD_SHA512_256_DIGEST_SIZE,
+ *                        #MHD_digest_get_hash_size())
+ * @param nonce_timeout the period of seconds since nonce generation, when
+ *                      the nonce is recognised as valid and not stale.
+ * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc
+ *               exceeds the specified value then MHD_DAUTH_NONCE_STALE is
+ *               returned;
+ *               zero for no limit
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithms allowed to use, fail if algorithm used
+ *               by the client is not allowed by this parameter;
+ *               more than one base algorithms (MD5, SHA-256, SHA-512/256)
+ *               cannot be used at the same time for this function
+ *               as @a userdigest must match specified algorithm
+ * @return #MHD_DAUTH_OK if authenticated,
+ *         the error code otherwise
+ * @sa #MHD_digest_auth_calc_userdigest()
+ * @note Available since #MHD_VERSION 0x00097528
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_DigestAuthResult
+MHD_digest_auth_check_digest3 (struct MHD_Connection *connection,
+                               const char *realm,
+                               const char *username,
+                               const void *userdigest,
+                               size_t userdigest_size,
+                               unsigned int nonce_timeout,
+                               uint32_t max_nc,
+                               enum MHD_DigestAuthMultiQOP mqop,
+                               enum MHD_DigestAuthMultiAlgo3 malgo3)
+{
+  if (1 != (((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_MD5)) ? 1 : 0)
+            + ((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_SHA256)) ? 1 : 0)
+            + ((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_SHA512_256)) ? 1 : 0)))
+    MHD_PANIC (_ ("Wrong 'malgo3' value, only one base hashing algorithm " \
+                  "(MD5, SHA-256 or SHA-512/256) must be specified, " \
+                  "API violation"));
+
+#ifndef MHD_MD5_SUPPORT
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_MD5))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The MD5 algorithm is not supported by this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#endif /* ! MHD_MD5_SUPPORT */
+#ifndef MHD_SHA256_SUPPORT
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA256))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The SHA-256 algorithm is not supported by "
+                 "this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#endif /* ! MHD_SHA256_SUPPORT */
+#ifndef MHD_SHA512_256_SUPPORT
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA512_256))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The SHA-512/256 algorithm is not supported by "
+                 "this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_DAUTH_WRONG_ALGO;
+  }
+#endif /* ! MHD_SHA512_256_SUPPORT */
+
+  if (digest_get_hash_size ((enum MHD_DigestAuthAlgo3) malgo3) !=
+      userdigest_size)
+    MHD_PANIC (_ ("Wrong 'userdigest_size' value, does not match 'malgo3', "
+                  "API violation"));
+
+  return digest_auth_check_all (connection,
+                                realm,
+                                username,
+                                NULL,
+                                (const uint8_t *) userdigest,
+                                nonce_timeout,
+                                max_nc,
+                                mqop,
+                                malgo3);
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param password The password used in the authentication
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @param algo digest algorithms allowed for verification
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @note Available since #MHD_VERSION 0x00096200
+ * @deprecated use MHD_digest_auth_check3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check2 (struct MHD_Connection *connection,
+                        const char *realm,
+                        const char *username,
+                        const char *password,
+                        unsigned int nonce_timeout,
+                        enum MHD_DigestAuthAlgorithm algo)
+{
+  enum MHD_DigestAuthResult res;
+  enum MHD_DigestAuthMultiAlgo3 malgo3;
+
+  if (MHD_DIGEST_ALG_AUTO == algo)
+    malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION;
+  else if (MHD_DIGEST_ALG_MD5 == algo)
+    malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5;
+  else if (MHD_DIGEST_ALG_SHA256 == algo)
+    malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256;
+  else
+    MHD_PANIC (_ ("Wrong 'algo' value, API violation"));
+
+  res = MHD_digest_auth_check3 (connection,
+                                realm,
+                                username,
+                                password,
+                                nonce_timeout,
+                                0, MHD_DIGEST_AUTH_MULT_QOP_AUTH,
+                                malgo3);
+  if (MHD_DAUTH_OK == res)
+    return MHD_YES;
+  else if ((MHD_DAUTH_NONCE_STALE == res) || (MHD_DAUTH_NONCE_WRONG == res) ||
+           (MHD_DAUTH_NONCE_OTHER_COND == res) )
+    return MHD_INVALID_NONCE;
+  return MHD_NO;
+
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client.
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param digest An `unsigned char *' pointer to the binary MD5 sum
+ *      for the precalculated hash value "username:realm:password"
+ *      of @a digest_size bytes
+ * @param digest_size number of bytes in @a digest (size must match @a algo!)
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @param algo digest algorithms allowed for verification
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @note Available since #MHD_VERSION 0x00096200
+ * @deprecated use MHD_digest_auth_check_digest3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check_digest2 (struct MHD_Connection *connection,
+                               const char *realm,
+                               const char *username,
+                               const uint8_t *digest,
+                               size_t digest_size,
+                               unsigned int nonce_timeout,
+                               enum MHD_DigestAuthAlgorithm algo)
+{
+  enum MHD_DigestAuthResult res;
+  enum MHD_DigestAuthMultiAlgo3 malgo3;
+
+  if (MHD_DIGEST_ALG_AUTO == algo)
+    malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION;
+  else if (MHD_DIGEST_ALG_MD5 == algo)
+    malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5;
+  else if (MHD_DIGEST_ALG_SHA256 == algo)
+    malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256;
+  else
+    MHD_PANIC (_ ("Wrong 'algo' value, API violation"));
+
+  res = MHD_digest_auth_check_digest3 (connection,
+                                       realm,
+                                       username,
+                                       digest,
+                                       digest_size,
+                                       nonce_timeout,
+                                       0, MHD_DIGEST_AUTH_MULT_QOP_AUTH,
+                                       malgo3);
+  if (MHD_DAUTH_OK == res)
+    return MHD_YES;
+  else if ((MHD_DAUTH_NONCE_STALE == res) || (MHD_DAUTH_NONCE_WRONG == res) ||
+           (MHD_DAUTH_NONCE_OTHER_COND == res) )
+    return MHD_INVALID_NONCE;
+  return MHD_NO;
+}
+
+
+/**
+ * Authenticates the authorization header sent by the client
+ * Uses #MHD_DIGEST_ALG_MD5 (required, as @a digest is of fixed
+ * size).
+ *
+ * @param connection The MHD connection structure
+ * @param realm The realm presented to the client
+ * @param username The username needs to be authenticated
+ * @param digest An `unsigned char *' pointer to the binary hash
+ *    for the precalculated hash value "username:realm:password";
+ *    length must be #MHD_MD5_DIGEST_SIZE bytes
+ * @param nonce_timeout The amount of time for a nonce to be
+ *      invalid in seconds
+ * @return #MHD_YES if authenticated, #MHD_NO if not,
+ *         #MHD_INVALID_NONCE if nonce is invalid or stale
+ * @note Available since #MHD_VERSION 0x00096000
+ * @deprecated use #MHD_digest_auth_check_digest3()
+ * @ingroup authentication
+ */
+_MHD_EXTERN int
+MHD_digest_auth_check_digest (struct MHD_Connection *connection,
+                              const char *realm,
+                              const char *username,
+                              const uint8_t digest[MHD_MD5_DIGEST_SIZE],
+                              unsigned int nonce_timeout)
+{
+  return MHD_digest_auth_check_digest2 (connection,
+                                        realm,
+                                        username,
+                                        digest,
+                                        MHD_MD5_DIGEST_SIZE,
+                                        nonce_timeout,
+                                        MHD_DIGEST_ALG_MD5);
+}
+
+
+/**
+ * Internal version of #MHD_queue_auth_required_response3() to simplify
+ * cleanups.
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param opaque the string for opaque value, can be NULL, but NULL is
+ *               not recommended for better compatibility with clients;
+ *               the recommended format is hex or Base64 encoded string
+ * @param domain the optional space-separated list of URIs for which the
+ *               same authorisation could be used, URIs can be in form
+ *               "path-absolute" (the path for the same host with initial slash)
+ *               or in form "absolute-URI" (the full path with protocol), in
+ *               any case client may assume that URI is in the same "protection
+ *               space" if it starts with any of values specified here;
+ *               could be NULL (clients typically assume that the same
+ *               credentials could be used for any URI on the same host)
+ * @param response the reply to send; should contain the "access denied"
+ *                 body; note that this function sets the "WWW Authenticate"
+ *                 header and that the caller should not do this;
+ *                 the NULL is tolerated
+ * @param signal_stale set to #MHD_YES if the nonce is stale to add 'stale=true'
+ *                     to the authentication header, this instructs the client
+ *                     to retry immediately with the new nonce and the same
+ *                     credentials, without asking user for the new password
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithm to use, MHD selects; if several algorithms
+ *               are allowed then MD5 is preferred (currently, may be changed
+ *               in next versions)
+ * @param userhash_support if set to non-zero value (#MHD_YES) then support of
+ *                         userhash is indicated, the client may provide
+ *                         hash("username:realm") instead of username in
+ *                         clear text;
+ *                         note that clients are allowed to provide the username
+ *                         in cleartext even if this parameter set to non-zero;
+ *                         when userhash is used, application must be ready to
+ *                         identify users by provided userhash value instead of
+ *                         username; see #MHD_digest_auth_calc_userhash() and
+ *                         #MHD_digest_auth_calc_userhash_hex()
+ * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is
+ *                    added, indicating for the client that UTF-8 encoding
+ *                    is preferred
+ * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is
+ *                    added, indicating for the client that UTF-8 encoding
+ *                    is preferred
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00097526
+ * @ingroup authentication
+ */
+static enum MHD_Result
+queue_auth_required_response3_inner (struct MHD_Connection *connection,
+                                     const char *realm,
+                                     const char *opaque,
+                                     const char *domain,
+                                     struct MHD_Response *response,
+                                     int signal_stale,
+                                     enum MHD_DigestAuthMultiQOP mqop,
+                                     enum MHD_DigestAuthMultiAlgo3 malgo3,
+                                     int userhash_support,
+                                     int prefer_utf8,
+                                     char **buf_ptr,
+                                     struct DigestAlgorithm *da)
+{
+  static const char prefix_realm[] = "realm=\"";
+  static const char prefix_qop[] = "qop=\"";
+  static const char prefix_algo[] = "algorithm=";
+  static const char prefix_nonce[] = "nonce=\"";
+  static const char prefix_opaque[] = "opaque=\"";
+  static const char prefix_domain[] = "domain=\"";
+  static const char str_charset[] = "charset=UTF-8";
+  static const char str_userhash[] = "userhash=true";
+  static const char str_stale[] = "stale=true";
+  enum MHD_DigestAuthAlgo3 s_algo; /**< Selected algorithm */
+  size_t realm_len;
+  size_t opaque_len;
+  size_t domain_len;
+  size_t buf_size;
+  char *buf;
+  size_t p; /* The position in the buffer */
+  char *hdr_name;
+
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_AUTH_ALGO3_SESSION))
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The 'session' algorithms are not supported.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_NO;
+  }
+#ifdef MHD_MD5_SUPPORT
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_MD5))
+    s_algo = MHD_DIGEST_AUTH_ALGO3_MD5;
+  else
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA256))
+    s_algo = MHD_DIGEST_AUTH_ALGO3_SHA256;
+  else
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+  if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA512_256))
+    s_algo = MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+  else
+#endif /* MHD_SHA512_256_SUPPORT */
+  {
+    if (0 == (((unsigned int) malgo3)
+              & (MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_BASE_ALGO_SHA512_256
+                 | MHD_DIGEST_BASE_ALGO_SHA512_256)))
+      MHD_PANIC (_ ("Wrong 'malgo3' value, API violation"));
+    else
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("No requested algorithm is supported by this MHD build.\n"));
+#endif /* HAVE_MESSAGES */
+    }
+    return MHD_NO;
+  }
+
+  if (((unsigned int) mqop) !=
+      (((unsigned int) mqop) & MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT))
+    MHD_PANIC (_ ("Wrong 'mqop' value, API violation"));
+
+  if (! digest_init_one_time (da, get_base_digest_algo (s_algo)))
+    MHD_PANIC (_ ("Wrong 'algo' value, API violation"));
+
+  if (MHD_DIGEST_AUTH_MULT_QOP_NONE == mqop)
+  {
+#ifdef HAVE_MESSAGES
+    if ((0 != userhash_support) || (0 != prefer_utf8))
+      MHD_DLOG (connection->daemon,
+                _ ("The 'userhash' and 'charset' ('prefer_utf8') parameters " \
+                   "are not compatible with RFC2069 and ignored.\n"));
+    if (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5))
+      MHD_DLOG (connection->daemon,
+                _ ("RFC2069 with SHA-256 or SHA-512/256 algorithm is " \
+                   "non-standard extension.\n"));
+#endif
+    userhash_support = 0;
+    prefer_utf8 = 0;
+  }
+
+  if (0 == MHD_get_master (connection->daemon)->nonce_nc_size)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The nonce array size is zero.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_NO;
+  }
+
+  /* Calculate required size */
+  buf_size = 0;
+  /* 'Digest ' */
+  buf_size += MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE) + 1; /* 1 for ' ' */
+  buf_size += MHD_STATICSTR_LEN_ (prefix_realm) + 3; /* 3 for '", ' */
+  /* 'realm="xxxx", ' */
+  realm_len = strlen (realm);
+  if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < realm_len)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The 'realm' is too large.\n"));
+#endif /* HAVE_MESSAGES */
+    return MHD_NO;
+  }
+  if ((NULL != memchr (realm, '\r', realm_len)) ||
+      (NULL != memchr (realm, '\n', realm_len)))
+    return MHD_NO;
+
+  buf_size += realm_len * 2; /* Quoting may double the size */
+  /* 'qop="xxxx", ' */
+  if (MHD_DIGEST_AUTH_MULT_QOP_NONE != mqop)
+  {
+    buf_size += MHD_STATICSTR_LEN_ (prefix_qop) + 3; /* 3 for '", ' */
+    buf_size += MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_);
+  }
+  /* 'algorithm="xxxx", ' */
+  if (((MHD_DIGEST_AUTH_MULT_QOP_NONE) != mqop) ||
+      (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5)))
+  {
+    buf_size += MHD_STATICSTR_LEN_ (prefix_algo) + 2; /* 2 for ', ' */
+#ifdef MHD_MD5_SUPPORT
+    if (MHD_DIGEST_AUTH_ALGO3_MD5 == s_algo)
+      buf_size += MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN);
+    else
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+    if (MHD_DIGEST_AUTH_ALGO3_SHA256 == s_algo)
+      buf_size += MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN);
+    else
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+    if (MHD_DIGEST_AUTH_ALGO3_SHA512_256 == s_algo)
+      buf_size += MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN);
+    else
+#endif /* MHD_SHA512_256_SUPPORT */
+    mhd_assert (0);
+  }
+  /* 'nonce="xxxx", ' */
+  buf_size += MHD_STATICSTR_LEN_ (prefix_nonce) + 3; /* 3 for '", ' */
+  buf_size += NONCE_STD_LEN (digest_get_size (da)); /* Escaping not needed */
+  /* 'opaque="xxxx", ' */
+  if (NULL != opaque)
+  {
+    buf_size += MHD_STATICSTR_LEN_ (prefix_opaque) + 3; /* 3 for '", ' */
+    opaque_len = strlen (opaque);
+    if ((NULL != memchr (opaque, '\r', opaque_len)) ||
+        (NULL != memchr (opaque, '\n', opaque_len)))
+      return MHD_NO;
+
+    buf_size += opaque_len * 2; /* Quoting may double the size */
+  }
+  else
+    opaque_len = 0;
+  /* 'domain="xxxx", ' */
+  if (NULL != domain)
+  {
+    buf_size += MHD_STATICSTR_LEN_ (prefix_domain) + 3; /* 3 for '", ' */
+    domain_len = strlen (domain);
+    if ((NULL != memchr (domain, '\r', domain_len)) ||
+        (NULL != memchr (domain, '\n', domain_len)))
+      return MHD_NO;
+
+    buf_size += domain_len * 2; /* Quoting may double the size */
+  }
+  else
+    domain_len = 0;
+  /* 'charset=UTF-8' */
+  if (MHD_NO != prefer_utf8)
+    buf_size += MHD_STATICSTR_LEN_ (str_charset) + 2; /* 2 for ', ' */
+  /* 'userhash=true' */
+  if (MHD_NO != userhash_support)
+    buf_size += MHD_STATICSTR_LEN_ (str_userhash) + 2; /* 2 for ', ' */
+  /* 'stale=true' */
+  if (MHD_NO != signal_stale)
+    buf_size += MHD_STATICSTR_LEN_ (str_stale) + 2; /* 2 for ', ' */
+
+  /* The calculated length is for string ended with ", ". One character will
+   * be used for zero-termination, the last one will not be used. */
+
+  /* Allocate the buffer */
+  buf = malloc (buf_size);
+  if (NULL == buf)
+    return MHD_NO;
+  *buf_ptr = buf;
+
+  /* Build the challenge string */
+  p = 0;
+  /* 'Digest: ' */
+  memcpy (buf + p, _MHD_AUTH_DIGEST_BASE,
+          MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE));
+  p += MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE);
+  buf[p++] = ' ';
+  /* 'realm="xxxx", ' */
+  memcpy (buf + p, prefix_realm,
+          MHD_STATICSTR_LEN_ (prefix_realm));
+  p += MHD_STATICSTR_LEN_ (prefix_realm);
+  mhd_assert ((buf_size - p) >= (realm_len * 2));
+  if (1)
+  {
+    size_t quoted_size;
+    quoted_size = MHD_str_quote (realm, realm_len, buf + p, buf_size - p);
+    if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < quoted_size)
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("The 'realm' is too large after 'quoting'.\n"));
+#endif /* HAVE_MESSAGES */
       return MHD_NO;
     }
-
-    digest_calc_ha1("md5",
-		    username,
-		    realm,
-		    password,
-		    nonce,
-		    cnonce,
-		    ha1);
-    digest_calc_response (ha1,
-			  nonce,
-			  nc,
-			  cnonce,
-			  qop,
-			  connection->method,
-			  uri,
-			  hentity,
-			  respexp);
-    free(uri);
-    return (0 == strcmp(response, respexp))
-      ? MHD_YES
-      : MHD_NO;
+    p += quoted_size;
   }
+  buf[p++] = '\"';
+  buf[p++] = ',';
+  buf[p++] = ' ';
+  /* 'qop="xxxx", ' */
+  if (MHD_DIGEST_AUTH_MULT_QOP_NONE != mqop)
+  {
+    memcpy (buf + p, prefix_qop,
+            MHD_STATICSTR_LEN_ (prefix_qop));
+    p += MHD_STATICSTR_LEN_ (prefix_qop);
+    memcpy (buf + p, MHD_TOKEN_AUTH_,
+            MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_));
+    p += MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_);
+    buf[p++] = '\"';
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  /* 'algorithm="xxxx", ' */
+  if (((MHD_DIGEST_AUTH_MULT_QOP_NONE) != mqop) ||
+      (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5)))
+  {
+    memcpy (buf + p, prefix_algo,
+            MHD_STATICSTR_LEN_ (prefix_algo));
+    p += MHD_STATICSTR_LEN_ (prefix_algo);
+#ifdef MHD_MD5_SUPPORT
+    if (MHD_DIGEST_AUTH_ALGO3_MD5 == s_algo)
+    {
+      memcpy (buf + p, _MHD_MD5_TOKEN,
+              MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN));
+      p += MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN);
+    }
+    else
+#endif /* MHD_MD5_SUPPORT */
+#ifdef MHD_SHA256_SUPPORT
+    if (MHD_DIGEST_AUTH_ALGO3_SHA256 == s_algo)
+    {
+      memcpy (buf + p, _MHD_SHA256_TOKEN,
+              MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN));
+      p += MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN);
+    }
+    else
+#endif /* MHD_SHA256_SUPPORT */
+#ifdef MHD_SHA512_256_SUPPORT
+    if (MHD_DIGEST_AUTH_ALGO3_SHA512_256 == s_algo)
+    {
+      memcpy (buf + p, _MHD_SHA512_256_TOKEN,
+              MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN));
+      p += MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN);
+    }
+    else
+#endif /* MHD_SHA512_256_SUPPORT */
+    mhd_assert (0);
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  /* 'nonce="xxxx", ' */
+  memcpy (buf + p, prefix_nonce,
+          MHD_STATICSTR_LEN_ (prefix_nonce));
+  p += MHD_STATICSTR_LEN_ (prefix_nonce);
+  mhd_assert ((buf_size - p) >= (NONCE_STD_LEN (digest_get_size (da))));
+  if (! calculate_add_nonce_with_retry (connection, realm, da, buf + p))
+  {
+#ifdef MHD_DIGEST_HAS_EXT_ERROR
+    if (digest_ext_error (da))
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (connection->daemon,
+                _ ("TLS library reported hash calculation error, nonce could "
+                   "not be generated.\n"));
+#endif /* HAVE_MESSAGES */
+      return MHD_NO;
+    }
+#endif /* MHD_DIGEST_HAS_EXT_ERROR */
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Could not register nonce. Client's requests with this "
+                 "nonce will be always 'stale'. Probably clients' requests "
+                 "are too intensive.\n"));
+#endif /* HAVE_MESSAGES */
+    (void) 0; /* Mute compiler warning for builds without messages */
+  }
+  p += NONCE_STD_LEN (digest_get_size (da));
+  buf[p++] = '\"';
+  buf[p++] = ',';
+  buf[p++] = ' ';
+  /* 'opaque="xxxx", ' */
+  if (NULL != opaque)
+  {
+    memcpy (buf + p, prefix_opaque,
+            MHD_STATICSTR_LEN_ (prefix_opaque));
+    p += MHD_STATICSTR_LEN_ (prefix_opaque);
+    mhd_assert ((buf_size - p) >= (opaque_len * 2));
+    p += MHD_str_quote (opaque, opaque_len, buf + p, buf_size - p);
+    buf[p++] = '\"';
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  /* 'domain="xxxx", ' */
+  if (NULL != domain)
+  {
+    memcpy (buf + p, prefix_domain,
+            MHD_STATICSTR_LEN_ (prefix_domain));
+    p += MHD_STATICSTR_LEN_ (prefix_domain);
+    mhd_assert ((buf_size - p) >= (domain_len * 2));
+    p += MHD_str_quote (domain, domain_len, buf + p, buf_size - p);
+    buf[p++] = '\"';
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  /* 'charset=UTF-8' */
+  if (MHD_NO != prefer_utf8)
+  {
+    memcpy (buf + p, str_charset,
+            MHD_STATICSTR_LEN_ (str_charset));
+    p += MHD_STATICSTR_LEN_ (str_charset);
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  /* 'userhash=true' */
+  if (MHD_NO != userhash_support)
+  {
+    memcpy (buf + p, str_userhash,
+            MHD_STATICSTR_LEN_ (str_userhash));
+    p += MHD_STATICSTR_LEN_ (str_userhash);
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  /* 'stale=true' */
+  if (MHD_NO != signal_stale)
+  {
+    memcpy (buf + p, str_stale,
+            MHD_STATICSTR_LEN_ (str_stale));
+    p += MHD_STATICSTR_LEN_ (str_stale);
+    buf[p++] = ',';
+    buf[p++] = ' ';
+  }
+  mhd_assert (buf_size >= p);
+  /* The built string ends with ", ". Replace comma with zero-termination. */
+  --p;
+  buf[--p] = 0;
+
+  hdr_name = malloc (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_WWW_AUTHENTICATE) + 1);
+  if (NULL != hdr_name)
+  {
+    memcpy (hdr_name, MHD_HTTP_HEADER_WWW_AUTHENTICATE,
+            MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_WWW_AUTHENTICATE) + 1);
+    if (MHD_add_response_entry_no_alloc_ (response, MHD_HEADER_KIND,
+                                          hdr_name,
+                                          MHD_STATICSTR_LEN_ ( \
+                                            MHD_HTTP_HEADER_WWW_AUTHENTICATE),
+                                          buf, p))
+    {
+      *buf_ptr = NULL; /* The buffer will be free()ed when the response is destroyed */
+      return MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response);
+    }
+#ifdef HAVE_MESSAGES
+    else
+    {
+      MHD_DLOG (connection->daemon,
+                _ ("Failed to add Digest auth header.\n"));
+    }
+#endif /* HAVE_MESSAGES */
+    free (hdr_name);
+  }
+  return MHD_NO;
+}
+
+
+/**
+ * Queues a response to request authentication from the client
+ *
+ * This function modifies provided @a response. The @a response must not be
+ * reused and should be destroyed (by #MHD_destroy_response()) after call of
+ * this function.
+ *
+ * If @a mqop allows both RFC 2069 (MHD_DIGEST_AUTH_QOP_NONE) and QOP with
+ * value, then response is formed like if MHD_DIGEST_AUTH_QOP_NONE bit was
+ * not set, because such response should be backward-compatible with RFC 2069.
+ *
+ * If @a mqop allows only MHD_DIGEST_AUTH_MULT_QOP_NONE, then the response is
+ * formed in strict accordance with RFC 2069 (no 'qop', no 'userhash', no
+ * 'charset'). For better compatibility with clients, it is recommended (but
+ * not required) to set @a domain to NULL in this mode.
+ *
+ * @param connection the MHD connection structure
+ * @param realm the realm presented to the client
+ * @param opaque the string for opaque value, can be NULL, but NULL is
+ *               not recommended for better compatibility with clients;
+ *               the recommended format is hex or Base64 encoded string
+ * @param domain the optional space-separated list of URIs for which the
+ *               same authorisation could be used, URIs can be in form
+ *               "path-absolute" (the path for the same host with initial slash)
+ *               or in form "absolute-URI" (the full path with protocol), in
+ *               any case client may assume that URI is in the same "protection
+ *               space" if it starts with any of values specified here;
+ *               could be NULL (clients typically assume that the same
+ *               credentials could be used for any URI on the same host)
+ * @param response the reply to send; should contain the "access denied"
+ *                 body; note that this function sets the "WWW Authenticate"
+ *                 header and that the caller should not do this;
+ *                 the NULL is tolerated
+ * @param signal_stale set to #MHD_YES if the nonce is stale to add 'stale=true'
+ *                     to the authentication header, this instructs the client
+ *                     to retry immediately with the new nonce and the same
+ *                     credentials, without asking user for the new password
+ * @param mqop the QOP to use
+ * @param malgo3 digest algorithm to use, MHD selects; if several algorithms
+ *               are allowed then MD5 is preferred (currently, may be changed
+ *               in next versions)
+ * @param userhash_support if set to non-zero value (#MHD_YES) then support of
+ *                         userhash is indicated, the client may provide
+ *                         hash("username:realm") instead of username in
+ *                         clear text;
+ *                         note that clients are allowed to provide the username
+ *                         in cleartext even if this parameter set to non-zero;
+ *                         when userhash is used, application must be ready to
+ *                         identify users by provided userhash value instead of
+ *                         username; see #MHD_digest_auth_calc_userhash() and
+ *                         #MHD_digest_auth_calc_userhash_hex()
+ * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is
+ *                    added, indicating for the client that UTF-8 encoding
+ *                    is preferred
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00097526
+ * @ingroup authentication
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_queue_auth_required_response3 (struct MHD_Connection *connection,
+                                   const char *realm,
+                                   const char *opaque,
+                                   const char *domain,
+                                   struct MHD_Response *response,
+                                   int signal_stale,
+                                   enum MHD_DigestAuthMultiQOP mqop,
+                                   enum MHD_DigestAuthMultiAlgo3 malgo3,
+                                   int userhash_support,
+                                   int prefer_utf8)
+{
+  struct DigestAlgorithm da;
+  char *buf_ptr;
+  enum MHD_Result ret;
+
+  buf_ptr = NULL;
+  digest_setup_zero (&da);
+  ret = queue_auth_required_response3_inner (connection,
+                                             realm,
+                                             opaque,
+                                             domain,
+                                             response,
+                                             signal_stale,
+                                             mqop,
+                                             malgo3,
+                                             userhash_support,
+                                             prefer_utf8,
+                                             &buf_ptr,
+                                             &da);
+  digest_deinit (&da);
+  if (NULL != buf_ptr)
+    free (buf_ptr);
+  return ret;
 }
 
 
@@ -790,81 +3971,71 @@
  * @param opaque string to user for opaque value
  * @param response reply to send; should contain the "access denied"
  *        body; note that this function will set the "WWW Authenticate"
- *        header and that the caller should not do this
- * @param signal_stale #MHD_YES if the nonce is invalid to add
- * 			'stale=true' to the authentication header
+ *        header and that the caller should not do this; the NULL is tolerated
+ * @param signal_stale #MHD_YES if the nonce is stale to add
+ *        'stale=true' to the authentication header
+ * @param algo digest algorithm to use
  * @return #MHD_YES on success, #MHD_NO otherwise
+ * @note Available since #MHD_VERSION 0x00096200
  * @ingroup authentication
  */
-int
-MHD_queue_auth_fail_response (struct MHD_Connection *connection,
-			      const char *realm,
-			      const char *opaque,
-			      struct MHD_Response *response,
-			      int signal_stale)
+_MHD_EXTERN enum MHD_Result
+MHD_queue_auth_fail_response2 (struct MHD_Connection *connection,
+                               const char *realm,
+                               const char *opaque,
+                               struct MHD_Response *response,
+                               int signal_stale,
+                               enum MHD_DigestAuthAlgorithm algo)
 {
-  int ret;
-  size_t hlen;
-  char nonce[HASH_MD5_HEX_LEN + 9];
+  enum MHD_DigestAuthMultiAlgo3 algo3;
 
-  /* Generating the server nonce */
-  calculate_nonce ((uint32_t) MHD_monotonic_time(),
-		   connection->method,
-		   connection->daemon->digest_auth_random,
-		   connection->daemon->digest_auth_rand_size,
-		   connection->url,
-		   realm,
-		   nonce);
-  if (MHD_YES != check_nonce_nc (connection, nonce, 0))
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG (connection->daemon,
-		"Could not register nonce (is the nonce array size zero?).\n");
-#endif
-      return MHD_NO;
-    }
-  /* Building the authentication header */
-  hlen = MHD_snprintf_(NULL,
-		   0,
-		   "Digest realm=\"%s\",qop=\"auth\",nonce=\"%s\",opaque=\"%s\"%s",
-		   realm,
-		   nonce,
-		   opaque,
-		   signal_stale
-		   ? ",stale=\"true\""
-		   : "");
-  {
-    char *header;
-    
-    header = malloc(hlen + 1);
-    if (NULL == header)
-    {
-#if HAVE_MESSAGES
-      MHD_DLOG(connection->daemon,
-               "Failed to allocate memory for auth response header\n");
-#endif /* HAVE_MESSAGES */
-      return MHD_NO;
-    }
+  if (MHD_DIGEST_ALG_MD5 == algo)
+    algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5;
+  else if (MHD_DIGEST_ALG_SHA256 == algo)
+    algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256;
+  else if (MHD_DIGEST_ALG_AUTO == algo)
+    algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION;
+  else
+    MHD_PANIC (_ ("Wrong algo value.\n")); /* API violation! */
 
-    MHD_snprintf_(header,
-	      hlen + 1,
-	      "Digest realm=\"%s\",qop=\"auth\",nonce=\"%s\",opaque=\"%s\"%s",
-	      realm,
-	      nonce,
-	      opaque,
-	      signal_stale
-	      ? ",stale=\"true\""
-	      : "");
-    ret = MHD_add_response_header(response,
-				  MHD_HTTP_HEADER_WWW_AUTHENTICATE,
-				  header);
-    free(header);
-  }
-  if (MHD_YES == ret)
-    ret = MHD_queue_response(connection,
-			     MHD_HTTP_UNAUTHORIZED,
-			     response);
-  return ret;
+  return MHD_queue_auth_required_response3 (connection, realm, opaque,
+                                            NULL, response, signal_stale,
+                                            MHD_DIGEST_AUTH_MULT_QOP_AUTH,
+                                            algo3,
+                                            0, 0);
+}
+
+
+/**
+ * Queues a response to request authentication from the client.
+ * For now uses MD5 (for backwards-compatibility). Still, if you
+ * need to be sure, use #MHD_queue_auth_fail_response2().
+ *
+ * @param connection The MHD connection structure
+ * @param realm the realm presented to the client
+ * @param opaque string to user for opaque value
+ * @param response reply to send; should contain the "access denied"
+ *        body; note that this function will set the "WWW Authenticate"
+ *        header and that the caller should not do this; the NULL is tolerated
+ * @param signal_stale #MHD_YES if the nonce is stale to add
+ *        'stale=true' to the authentication header
+ * @return #MHD_YES on success, #MHD_NO otherwise
+ * @ingroup authentication
+ * @deprecated use MHD_queue_auth_fail_response2()
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_queue_auth_fail_response (struct MHD_Connection *connection,
+                              const char *realm,
+                              const char *opaque,
+                              struct MHD_Response *response,
+                              int signal_stale)
+{
+  return MHD_queue_auth_fail_response2 (connection,
+                                        realm,
+                                        opaque,
+                                        response,
+                                        signal_stale,
+                                        MHD_DIGEST_ALG_MD5);
 }
 
 
diff --git a/src/microhttpd/digestauth.h b/src/microhttpd/digestauth.h
new file mode 100644
index 0000000..4ba2670
--- /dev/null
+++ b/src/microhttpd/digestauth.h
@@ -0,0 +1,84 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010, 2011, 2012, 2015, 2018 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+/**
+ * @file digestauth.c
+ * @brief Implements HTTP digest authentication
+ * @author Amr Ali
+ * @author Matthieu Speder
+ * @author Christian Grothoff (RFC 7616 support)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_DIGESTAUTH_H
+#define MHD_DIGESTAUTH_H 1
+
+#include "mhd_options.h"
+#include "mhd_str.h"
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+
+/**
+ * The maximum supported size for Digest Auth parameters, like "real",
+ * "username" etc. This limitation is used only for quoted parameters.
+ * Parameters without quoted backslash character will be processed as long
+ * as they fit connection pool (buffer) size.
+ */
+#define _MHD_AUTH_DIGEST_MAX_PARAM_SIZE (65535)
+
+/**
+ * Beginning string for any valid Digest Authentication header.
+ */
+#define _MHD_AUTH_DIGEST_BASE   "Digest"
+
+/**
+ * The token for MD5 algorithm.
+ */
+#define _MHD_MD5_TOKEN "MD5"
+
+/**
+ * The token for SHA-256 algorithm.
+ */
+#define _MHD_SHA256_TOKEN "SHA-256"
+
+/**
+ * The token for SHA-512/256 algorithm.
+ */
+#define _MHD_SHA512_256_TOKEN "SHA-512-256"
+
+/**
+ * The suffix token for "session" algorithms.
+ */
+#define _MHD_SESS_TOKEN "-sess"
+
+/**
+ * The "auth" token for QOP
+ */
+#define MHD_TOKEN_AUTH_ "auth"
+
+/**
+ * The "auth-int" token for QOP
+ */
+#define MHD_TOKEN_AUTH_INT_ "auth-int"
+
+#endif /* ! MHD_DIGESTAUTH_H */
+
+/* end of digestauth.h */
diff --git a/src/microhttpd/gen_auth.c b/src/microhttpd/gen_auth.c
new file mode 100644
index 0000000..c10e4be
--- /dev/null
+++ b/src/microhttpd/gen_auth.c
@@ -0,0 +1,667 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/gen_auth.c
+ * @brief  HTTP authorisation general functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "gen_auth.h"
+#include "internal.h"
+#include "connection.h"
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+#ifdef BAUTH_SUPPORT
+#include "basicauth.h"
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+#include "digestauth.h"
+#endif /* DAUTH_SUPPORT */
+
+#if ! defined(BAUTH_SUPPORT) && ! defined(DAUTH_SUPPORT)
+#error This file requires Basic or Digest authentication support
+#endif
+
+/**
+ * Type of authorisation
+ */
+enum MHD_AuthType
+{
+  MHD_AUTHTYPE_NONE = 0,/**< No authorisation, unused */
+  MHD_AUTHTYPE_BASIC,   /**< Basic Authorisation, RFC 7617  */
+  MHD_AUTHTYPE_DIGEST,  /**< Digest Authorisation, RFC 7616 */
+  MHD_AUTHTYPE_UNKNOWN, /**< Unknown/Unsupported authorisation type, unused */
+  MHD_AUTHTYPE_INVALID  /**< Wrong/broken authorisation header, unused */
+};
+
+/**
+ * Find required "Authorization" request header
+ * @param c the connection with request
+ * @param type the type of the authorisation: basic or digest
+ * @param[out] auth_value will be set to the remaining of header value after
+ *                        authorisation token (after "Basic " or "Digest ")
+ * @return true if requested header is found,
+ *         false otherwise
+ */
+static bool
+find_auth_rq_header_ (const struct MHD_Connection *c, enum MHD_AuthType type,
+                      struct _MHD_str_w_len *auth_value)
+{
+  const struct MHD_HTTP_Req_Header *h;
+  const char *token;
+  size_t token_len;
+
+  mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= c->state);
+  if (MHD_CONNECTION_HEADERS_PROCESSED > c->state)
+    return false;
+
+#ifdef DAUTH_SUPPORT
+  if (MHD_AUTHTYPE_DIGEST == type)
+  {
+    token = _MHD_AUTH_DIGEST_BASE;
+    token_len = MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE);
+  }
+  else /* combined with the next line */
+#endif /* DAUTH_SUPPORT */
+#ifdef BAUTH_SUPPORT
+  if (MHD_AUTHTYPE_BASIC == type)
+  {
+    token = _MHD_AUTH_BASIC_BASE;
+    token_len = MHD_STATICSTR_LEN_ (_MHD_AUTH_BASIC_BASE);
+  }
+  else /* combined with the next line */
+#endif /* BAUTH_SUPPORT */
+  {
+    mhd_assert (0);
+    return false;
+  }
+
+  for (h = c->rq.headers_received; NULL != h; h = h->next)
+  {
+    if (MHD_HEADER_KIND != h->kind)
+      continue;
+    if (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION) != h->header_size)
+      continue;
+    if (token_len > h->value_size)
+      continue;
+    if (! MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_AUTHORIZATION,
+                                         h->header,
+                                         MHD_STATICSTR_LEN_ ( \
+                                           MHD_HTTP_HEADER_AUTHORIZATION)))
+      continue;
+    if (! MHD_str_equal_caseless_bin_n_ (h->value, token, token_len))
+      continue;
+    /* Match only if token string is full header value or token is
+     * followed by space or tab
+     * Note: RFC 9110 (and RFC 7234) allows only space character, but
+     * tab is supported here as well for additional flexibility and uniformity
+     * as tabs are supported as separators between parameters.
+     */
+    if ((token_len == h->value_size) ||
+        (' ' == h->value[token_len]) || ('\t'  == h->value[token_len]))
+    {
+      if (token_len != h->value_size)
+      { /* Skip whitespace */
+        auth_value->str = h->value + token_len + 1;
+        auth_value->len = h->value_size - (token_len + 1);
+      }
+      else
+      { /* No whitespace to skip */
+        auth_value->str = h->value + token_len;
+        auth_value->len = h->value_size - token_len;
+      }
+      return true; /* Found a match */
+    }
+  }
+  return false; /* No matching header has been found */
+}
+
+
+#ifdef BAUTH_SUPPORT
+
+
+/**
+ * Parse request Authorization header parameters for Basic Authentication
+ * @param str the header string, everything after "Basic " substring
+ * @param str_len the length of @a str in characters
+ * @param[out] pbauth the pointer to the structure with Basic Authentication
+ *               parameters
+ * @return true if parameters has been successfully parsed,
+ *         false if format of the @a str is invalid
+ */
+static bool
+parse_bauth_params (const char *str,
+                    size_t str_len,
+                    struct MHD_RqBAuth *pbauth)
+{
+  size_t i;
+
+  i = 0;
+
+  /* Skip all whitespaces at start */
+  while (i < str_len && (' ' == str[i] || '\t' == str[i]))
+    i++;
+
+  if (str_len > i)
+  {
+    size_t token68_start;
+    size_t token68_len;
+
+    /* 'i' points to the first non-whitespace char after scheme token */
+    token68_start = i;
+    /* Find end of the token. Token cannot contain whitespace. */
+    while (i < str_len && ' ' != str[i] && '\t' != str[i])
+    {
+      if (0 == str[i])
+        return false;  /* Binary zero is not allowed */
+      if ((',' == str[i]) || (';' == str[i]))
+        return false;  /* Only single token68 is allowed */
+      i++;
+    }
+    token68_len = i - token68_start;
+    mhd_assert (0 != token68_len);
+
+    /* Skip all whitespaces */
+    while (i < str_len && (' ' == str[i] || '\t' == str[i]))
+      i++;
+    /* Check whether any garbage is present at the end of the string */
+    if (str_len != i)
+      return false;
+    else
+    {
+      /* No more data in the string, only single token68. */
+      pbauth->token68.str = str + token68_start;
+      pbauth->token68.len = token68_len;
+    }
+  }
+  return true;
+}
+
+
+/**
+ * Return request's Basic Authorisation parameters.
+ *
+ * Function return result of parsing of the request's "Authorization" header or
+ * returns cached parsing result if the header was already parsed for
+ * the current request.
+ * @param connection the connection to process
+ * @return the pointer to structure with Authentication parameters,
+ *         NULL if no memory in memory pool, if called too early (before
+ *         header has been received) or if no valid Basic Authorisation header
+ *         found.
+ */
+const struct MHD_RqBAuth *
+MHD_get_rq_bauth_params_ (struct MHD_Connection *connection)
+{
+  struct _MHD_str_w_len h_auth_value;
+  struct MHD_RqBAuth *bauth;
+
+  mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= connection->state);
+
+  if (connection->rq.bauth_tried)
+    return connection->rq.bauth;
+
+  if (MHD_CONNECTION_HEADERS_PROCESSED > connection->state)
+    return NULL;
+
+  if (! find_auth_rq_header_ (connection, MHD_AUTHTYPE_BASIC, &h_auth_value))
+  {
+    connection->rq.bauth_tried = true;
+    connection->rq.bauth = NULL;
+    return NULL;
+  }
+
+  bauth =
+    (struct MHD_RqBAuth *)
+    MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_RqBAuth));
+
+  if (NULL == bauth)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Not enough memory in the connection's pool to allocate " \
+                 "for Basic Authorization header parsing.\n"));
+#endif /* HAVE_MESSAGES */
+    return NULL;
+  }
+
+  memset (bauth, 0, sizeof(struct MHD_RqBAuth));
+  if (parse_bauth_params (h_auth_value.str, h_auth_value.len, bauth))
+    connection->rq.bauth = bauth;
+  else
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The Basic Authorization client's header has "
+                 "incorrect format.\n"));
+#endif /* HAVE_MESSAGES */
+    connection->rq.bauth = NULL;
+    /* Memory in the pool remains allocated until next request */
+  }
+  connection->rq.bauth_tried = true;
+  return connection->rq.bauth;
+}
+
+
+#endif /* BAUTH_SUPPORT */
+
+#ifdef DAUTH_SUPPORT
+
+/**
+ * Helper structure to map token name to position where to put token's value
+ */
+struct dauth_token_param
+{
+  const struct _MHD_cstr_w_len *const tk_name;
+  struct MHD_RqDAuthParam *const param;
+};
+
+
+/**
+ * Get client's Digest Authorization algorithm type.
+ * If no algorithm is specified by client, MD5 is assumed.
+ * @param params the Digest Authorization 'algorithm' parameter
+ * @return the algorithm type
+ */
+static enum MHD_DigestAuthAlgo3
+get_rq_dauth_algo (const struct MHD_RqDAuthParam *const algo_param)
+{
+  if (NULL == algo_param->value.str)
+    return MHD_DIGEST_AUTH_ALGO3_MD5; /* Assume MD5 by default */
+
+  if (algo_param->quoted)
+  {
+    if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \
+                                               algo_param->value.len, \
+                                               _MHD_MD5_TOKEN))
+      return MHD_DIGEST_AUTH_ALGO3_MD5;
+    if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \
+                                               algo_param->value.len, \
+                                               _MHD_SHA256_TOKEN))
+      return MHD_DIGEST_AUTH_ALGO3_SHA256;
+    if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \
+                                               algo_param->value.len, \
+                                               _MHD_MD5_TOKEN _MHD_SESS_TOKEN))
+      return MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+    if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \
+                                               algo_param->value.len, \
+                                               _MHD_SHA512_256_TOKEN \
+                                               _MHD_SESS_TOKEN))
+
+      /* Algorithms below are not supported by MHD for authentication */
+
+      return MHD_DIGEST_AUTH_ALGO3_MD5_SESSION;
+    if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \
+                                               algo_param->value.len, \
+                                               _MHD_SHA256_TOKEN \
+                                               _MHD_SESS_TOKEN))
+      return MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION;
+    if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \
+                                               algo_param->value.len, \
+                                               _MHD_SHA512_256_TOKEN))
+      return MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION;
+
+    /* No known algorithm has been detected */
+    return MHD_DIGEST_AUTH_ALGO3_INVALID;
+  }
+  /* The algorithm value is not quoted */
+  if (MHD_str_equal_caseless_s_bin_n_ (_MHD_MD5_TOKEN, \
+                                       algo_param->value.str, \
+                                       algo_param->value.len))
+    return MHD_DIGEST_AUTH_ALGO3_MD5;
+  if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA256_TOKEN, \
+                                       algo_param->value.str, \
+                                       algo_param->value.len))
+    return MHD_DIGEST_AUTH_ALGO3_SHA256;
+  if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA512_256_TOKEN, \
+                                       algo_param->value.str, \
+                                       algo_param->value.len))
+    return MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+
+  /* Algorithms below are not supported by MHD for authentication */
+
+  if (MHD_str_equal_caseless_s_bin_n_ (_MHD_MD5_TOKEN _MHD_SESS_TOKEN, \
+                                       algo_param->value.str, \
+                                       algo_param->value.len))
+    return MHD_DIGEST_AUTH_ALGO3_MD5_SESSION;
+  if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA256_TOKEN _MHD_SESS_TOKEN, \
+                                       algo_param->value.str, \
+                                       algo_param->value.len))
+    return MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION;
+  if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA512_256_TOKEN _MHD_SESS_TOKEN, \
+                                       algo_param->value.str, \
+                                       algo_param->value.len))
+    return MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION;
+
+  /* No known algorithm has been detected */
+  return MHD_DIGEST_AUTH_ALGO3_INVALID;
+}
+
+
+/**
+ * Get QOP ('quality of protection') type.
+ * @param qop_param the Digest Authorization 'QOP' parameter
+ * @return detected QOP ('quality of protection') type.
+ */
+static enum MHD_DigestAuthQOP
+get_rq_dauth_qop (const struct MHD_RqDAuthParam *const qop_param)
+{
+  if (NULL == qop_param->value.str)
+    return MHD_DIGEST_AUTH_QOP_NONE;
+  if (qop_param->quoted)
+  {
+    if (MHD_str_equal_caseless_quoted_s_bin_n (qop_param->value.str, \
+                                               qop_param->value.len, \
+                                               MHD_TOKEN_AUTH_))
+      return MHD_DIGEST_AUTH_QOP_AUTH;
+    if (MHD_str_equal_caseless_quoted_s_bin_n (qop_param->value.str, \
+                                               qop_param->value.len, \
+                                               MHD_TOKEN_AUTH_INT_))
+      return MHD_DIGEST_AUTH_QOP_AUTH_INT;
+  }
+  else
+  {
+    if (MHD_str_equal_caseless_s_bin_n_ (MHD_TOKEN_AUTH_, \
+                                         qop_param->value.str, \
+                                         qop_param->value.len))
+      return MHD_DIGEST_AUTH_QOP_AUTH;
+    if (MHD_str_equal_caseless_s_bin_n_ (MHD_TOKEN_AUTH_INT_, \
+                                         qop_param->value.str, \
+                                         qop_param->value.len))
+      return MHD_DIGEST_AUTH_QOP_AUTH_INT;
+  }
+  /* No know QOP has been detected */
+  return MHD_DIGEST_AUTH_QOP_INVALID;
+}
+
+
+/**
+ * Parse request Authorization header parameters for Digest Authentication
+ * @param str the header string, everything after "Digest " substring
+ * @param str_len the length of @a str in characters
+ * @param[out] pdauth the pointer to the structure with Digest Authentication
+ *               parameters
+ * @return true if parameters has been successfully parsed,
+ *         false if format of the @a str is invalid
+ */
+static bool
+parse_dauth_params (const char *str,
+                    const size_t str_len,
+                    struct MHD_RqDAuth *pdauth)
+{
+  static const struct _MHD_cstr_w_len nonce_tk = _MHD_S_STR_W_LEN ("nonce");
+  static const struct _MHD_cstr_w_len opaque_tk = _MHD_S_STR_W_LEN ("opaque");
+  static const struct _MHD_cstr_w_len algorithm_tk =
+    _MHD_S_STR_W_LEN ("algorithm");
+  static const struct _MHD_cstr_w_len response_tk =
+    _MHD_S_STR_W_LEN ("response");
+  static const struct _MHD_cstr_w_len username_tk =
+    _MHD_S_STR_W_LEN ("username");
+  static const struct _MHD_cstr_w_len username_ext_tk =
+    _MHD_S_STR_W_LEN ("username*");
+  static const struct _MHD_cstr_w_len realm_tk = _MHD_S_STR_W_LEN ("realm");
+  static const struct _MHD_cstr_w_len uri_tk = _MHD_S_STR_W_LEN ("uri");
+  static const struct _MHD_cstr_w_len qop_tk = _MHD_S_STR_W_LEN ("qop");
+  static const struct _MHD_cstr_w_len cnonce_tk = _MHD_S_STR_W_LEN ("cnonce");
+  static const struct _MHD_cstr_w_len nc_tk = _MHD_S_STR_W_LEN ("nc");
+  static const struct _MHD_cstr_w_len userhash_tk =
+    _MHD_S_STR_W_LEN ("userhash");
+  struct MHD_RqDAuthParam userhash;
+  struct MHD_RqDAuthParam algorithm;
+  struct dauth_token_param map[] = {
+    {&nonce_tk, &(pdauth->nonce)},
+    {&opaque_tk, &(pdauth->opaque)},
+    {&algorithm_tk, &algorithm},
+    {&response_tk, &(pdauth->response)},
+    {&username_tk, &(pdauth->username)},
+    {&username_ext_tk, &(pdauth->username_ext)},
+    {&realm_tk, &(pdauth->realm)},
+    {&uri_tk, &(pdauth->uri)},
+    {&qop_tk, &(pdauth->qop_raw)},
+    {&cnonce_tk, &(pdauth->cnonce)},
+    {&nc_tk, &(pdauth->nc)},
+    {&userhash_tk, &userhash}
+  };
+  size_t i;
+  size_t p;
+
+  memset (&userhash, 0, sizeof(userhash));
+  memset (&algorithm, 0, sizeof(algorithm));
+  i = 0;
+
+  /* Skip all whitespaces at start */
+  while (i < str_len && (' ' == str[i] || '\t' == str[i]))
+    i++;
+
+  while (str_len > i)
+  {
+    size_t left;
+    mhd_assert (' ' != str[i]);
+    mhd_assert ('\t' != str[i]);
+
+    left = str_len - i;
+    if ('=' == str[i])
+      return false; /* The equal sign is not allowed as the first character */
+    for (p = 0; p < sizeof(map) / sizeof(map[0]); p++)
+    {
+      struct dauth_token_param *const aparam = map + p;
+      if ( (aparam->tk_name->len <= left) &&
+           MHD_str_equal_caseless_bin_n_ (str + i, aparam->tk_name->str,
+                                          aparam->tk_name->len) &&
+           ((aparam->tk_name->len == left) ||
+            ('=' == str[i + aparam->tk_name->len]) ||
+            (' ' == str[i + aparam->tk_name->len]) ||
+            ('\t' == str[i + aparam->tk_name->len]) ||
+            (',' == str[i + aparam->tk_name->len]) ||
+            (';' == str[i + aparam->tk_name->len])) )
+      {
+        size_t value_start;
+        size_t value_len;
+        bool quoted; /* Only mark as "quoted" if backslash-escape used */
+
+        if (aparam->tk_name->len == left)
+          return false; /* No equal sign after parameter name, broken data */
+
+        quoted = false;
+        i += aparam->tk_name->len;
+        /* Skip all whitespaces before '=' */
+        while (str_len > i && (' ' == str[i] || '\t' == str[i]))
+          i++;
+        if ((i == str_len) || ('=' != str[i]))
+          return false; /* No equal sign, broken data */
+        i++;
+        /* Skip all whitespaces after '=' */
+        while (str_len > i && (' ' == str[i] || '\t' == str[i]))
+          i++;
+        if ((str_len > i) && ('"' == str[i]))
+        { /* Value is in quotation marks */
+          i++; /* Advance after the opening quote */
+          value_start = i;
+          while (str_len > i && '"' != str[i])
+          {
+            if ('\\' == str[i])
+            {
+              i++;
+              quoted = true; /* Have escaped chars */
+            }
+            if (0 == str[i])
+              return false; /* Binary zero in parameter value */
+            i++;
+          }
+          if (str_len <= i)
+            return false; /* No closing quote */
+          mhd_assert ('"' == str[i]);
+          value_len = i - value_start;
+          i++; /* Advance after the closing quote */
+        }
+        else
+        {
+          value_start = i;
+          while (str_len > i && ',' != str[i] &&
+                 ' ' != str[i] && '\t' != str[i] && ';' != str[i])
+          {
+            if (0 == str[i])
+              return false;  /* Binary zero in parameter value */
+            i++;
+          }
+          if (';' == str[i])
+            return false;  /* Semicolon in parameter value */
+          value_len = i - value_start;
+        }
+        /* Skip all whitespaces after parameter value */
+        while (str_len > i && (' ' == str[i] || '\t' == str[i]))
+          i++;
+        if ((str_len > i) && (',' != str[i]))
+          return false; /* Garbage after parameter value */
+
+        /* Have valid parameter name and value */
+        mhd_assert (! quoted || 0 != value_len);
+        aparam->param->value.str = str + value_start;
+        aparam->param->value.len = value_len;
+        aparam->param->quoted = quoted;
+
+        break; /* Found matching parameter name */
+      }
+    }
+    if (p == sizeof(map) / sizeof(map[0]))
+    {
+      /* No matching parameter name */
+      while (str_len > i && ',' != str[i])
+      {
+        if ((0 == str[i]) || (';' == str[i]))
+          return false; /* Not allowed characters */
+        if ('"' == str[i])
+        { /* Skip quoted part */
+          i++; /* Advance after the opening quote */
+          while (str_len > i && '"' != str[i])
+          {
+            if (0 == str[i])
+              return false;  /* Binary zero is not allowed */
+            if ('\\' == str[i])
+              i++;           /* Skip escaped char */
+            i++;
+          }
+          if (str_len <= i)
+            return false; /* No closing quote */
+          mhd_assert ('"' == str[i]);
+        }
+        i++;
+      }
+    }
+    mhd_assert (str_len == i || ',' == str[i]);
+    if (str_len > i)
+      i++; /* Advance after ',' */
+    /* Skip all whitespaces before next parameter name */
+    while (i < str_len && (' ' == str[i] || '\t' == str[i]))
+      i++;
+  }
+
+  /* Postprocess values */
+
+  if (NULL != userhash.value.str)
+  {
+    if (userhash.quoted)
+      pdauth->userhash =
+        MHD_str_equal_caseless_quoted_s_bin_n (userhash.value.str, \
+                                               userhash.value.len, \
+                                               "true");
+    else
+      pdauth->userhash =
+        MHD_str_equal_caseless_s_bin_n_ ("true", userhash.value.str, \
+                                         userhash.value.len);
+
+  }
+  else
+    pdauth->userhash = false;
+
+  pdauth->algo3 = get_rq_dauth_algo (&algorithm);
+  pdauth->qop = get_rq_dauth_qop (&pdauth->qop_raw);
+
+  return true;
+}
+
+
+/**
+ * Return request's Digest Authorisation parameters.
+ *
+ * Function return result of parsing of the request's "Authorization" header or
+ * returns cached parsing result if the header was already parsed for
+ * the current request.
+ * @param connection the connection to process
+ * @return the pointer to structure with Authentication parameters,
+ *         NULL if no memory in memory pool, if called too early (before
+ *         header has been received) or if no valid Basic Authorisation header
+ *         found.
+ */
+const struct MHD_RqDAuth *
+MHD_get_rq_dauth_params_ (struct MHD_Connection *connection)
+{
+  struct _MHD_str_w_len h_auth_value;
+  struct MHD_RqDAuth *dauth;
+
+  mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= connection->state);
+
+  if (connection->rq.dauth_tried)
+    return connection->rq.dauth;
+
+  if (MHD_CONNECTION_HEADERS_PROCESSED > connection->state)
+    return NULL;
+
+  if (! find_auth_rq_header_ (connection, MHD_AUTHTYPE_DIGEST, &h_auth_value))
+  {
+    connection->rq.dauth_tried = true;
+    connection->rq.dauth = NULL;
+    return NULL;
+  }
+
+  dauth =
+    (struct MHD_RqDAuth *)
+    MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_RqDAuth));
+
+  if (NULL == dauth)
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("Not enough memory in the connection's pool to allocate " \
+                 "for Digest Authorization header parsing.\n"));
+#endif /* HAVE_MESSAGES */
+    return NULL;
+  }
+
+  memset (dauth, 0, sizeof(struct MHD_RqDAuth));
+  if (parse_dauth_params (h_auth_value.str, h_auth_value.len, dauth))
+    connection->rq.dauth = dauth;
+  else
+  {
+#ifdef HAVE_MESSAGES
+    MHD_DLOG (connection->daemon,
+              _ ("The Digest Authorization client's header has "
+                 "incorrect format.\n"));
+#endif /* HAVE_MESSAGES */
+    connection->rq.dauth = NULL;
+    /* Memory in the pool remains allocated until next request */
+  }
+  connection->rq.dauth_tried = true;
+  return connection->rq.dauth;
+}
+
+
+#endif /* DAUTH_SUPPORT */
diff --git a/src/microhttpd/gen_auth.h b/src/microhttpd/gen_auth.h
new file mode 100644
index 0000000..9cd8414
--- /dev/null
+++ b/src/microhttpd/gen_auth.h
@@ -0,0 +1,76 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/gen_auth.h
+ * @brief  Declarations for HTTP authorisation general functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_GET_AUTH_H
+#define MHD_GET_AUTH_H 1
+
+#include "mhd_options.h"
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+struct MHD_Connection; /* Forward declaration to avoid include of the large headers */
+
+#ifdef BAUTH_SUPPORT
+
+/* Forward declaration to avoid additional headers inclusion */
+struct MHD_RqBAuth;
+/**
+ * Return request's Basic Authorisation parameters.
+ *
+ * Function return result of parsing of the request's "Authorization" header or
+ * returns cached parsing result if the header was already parsed for
+ * the current request.
+ * @param connection the connection to process
+ * @return the pointer to structure with Authentication parameters,
+ *         NULL if no memory in memory pool, if called too early (before
+ *         header has been received) or if no valid Basic Authorisation header
+ *         found.
+ */
+const struct MHD_RqBAuth *
+MHD_get_rq_bauth_params_ (struct MHD_Connection *connection);
+
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+/* Forward declaration to avoid additional headers inclusion */
+struct MHD_RqDAuth;
+
+/**
+ * Return request's Digest Authorisation parameters.
+ *
+ * Function return result of parsing of the request's "Authorization" header or
+ * returns cached parsing result if the header was already parsed for
+ * the current request.
+ * @param connection the connection to process
+ * @return the pointer to structure with Authentication parameters,
+ *         NULL if no memory in memory pool, if called too early (before
+ *         header has been received) or if no valid Basic Authorisation header
+ *         found.
+ */
+const struct MHD_RqDAuth *
+MHD_get_rq_dauth_params_ (struct MHD_Connection *connection);
+#endif /* DAUTH_SUPPORT */
+
+#endif /* MHD_GET_AUTH_H */
diff --git a/src/microhttpd/internal.c b/src/microhttpd/internal.c
index 6a9188f..6f80b98 100644
--- a/src/microhttpd/internal.c
+++ b/src/microhttpd/internal.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2015-2021 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -22,11 +23,13 @@
  * @brief  internal shared structures
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "internal.h"
+#include "mhd_str.h"
 
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
 #if DEBUG_STATES
 /**
  * State to string dictionary.
@@ -35,77 +38,90 @@
 MHD_state_to_string (enum MHD_CONNECTION_STATE state)
 {
   switch (state)
-    {
-    case MHD_CONNECTION_INIT:
-      return "connection init";
-    case MHD_CONNECTION_URL_RECEIVED:
-      return "connection url received";
-    case MHD_CONNECTION_HEADER_PART_RECEIVED:
-      return "header partially received";
-    case MHD_CONNECTION_HEADERS_RECEIVED:
-      return "headers received";
-    case MHD_CONNECTION_HEADERS_PROCESSED:
-      return "headers processed";
-    case MHD_CONNECTION_CONTINUE_SENDING:
-      return "continue sending";
-    case MHD_CONNECTION_CONTINUE_SENT:
-      return "continue sent";
-    case MHD_CONNECTION_BODY_RECEIVED:
-      return "body received";
-    case MHD_CONNECTION_FOOTER_PART_RECEIVED:
-      return "footer partially received";
-    case MHD_CONNECTION_FOOTERS_RECEIVED:
-      return "footers received";
-    case MHD_CONNECTION_HEADERS_SENDING:
-      return "headers sending";
-    case MHD_CONNECTION_HEADERS_SENT:
-      return "headers sent";
-    case MHD_CONNECTION_NORMAL_BODY_READY:
-      return "normal body ready";
-    case MHD_CONNECTION_NORMAL_BODY_UNREADY:
-      return "normal body unready";
-    case MHD_CONNECTION_CHUNKED_BODY_READY:
-      return "chunked body ready";
-    case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
-      return "chunked body unready";
-    case MHD_CONNECTION_BODY_SENT:
-      return "body sent";
-    case MHD_CONNECTION_FOOTERS_SENDING:
-      return "footers sending";
-    case MHD_CONNECTION_FOOTERS_SENT:
-      return "footers sent";
-    case MHD_CONNECTION_CLOSED:
-      return "closed";
-    case MHD_TLS_CONNECTION_INIT:
-      return "secure connection init";
-    default:
-      return "unrecognized connection state";
-    }
+  {
+  case MHD_CONNECTION_INIT:
+    return "connection init";
+  case MHD_CONNECTION_REQ_LINE_RECEIVING:
+    return "receiving request line";
+  case MHD_CONNECTION_URL_RECEIVED:
+    return "connection url received";
+  case MHD_CONNECTION_HEADER_PART_RECEIVED:
+    return "header partially received";
+  case MHD_CONNECTION_HEADERS_RECEIVED:
+    return "headers received";
+  case MHD_CONNECTION_HEADERS_PROCESSED:
+    return "headers processed";
+  case MHD_CONNECTION_CONTINUE_SENDING:
+    return "continue sending";
+  case MHD_CONNECTION_BODY_RECEIVING:
+    return "body receiving";
+  case MHD_CONNECTION_BODY_RECEIVED:
+    return "body received";
+  case MHD_CONNECTION_FOOTER_PART_RECEIVED:
+    return "footer partially received";
+  case MHD_CONNECTION_FOOTERS_RECEIVED:
+    return "footers received";
+  case MHD_CONNECTION_FULL_REQ_RECEIVED:
+    return "full request received";
+  case MHD_CONNECTION_START_REPLY:
+    return "start sending reply";
+  case MHD_CONNECTION_HEADERS_SENDING:
+    return "headers sending";
+  case MHD_CONNECTION_HEADERS_SENT:
+    return "headers sent";
+  case MHD_CONNECTION_NORMAL_BODY_UNREADY:
+    return "normal body unready";
+  case MHD_CONNECTION_NORMAL_BODY_READY:
+    return "normal body ready";
+  case MHD_CONNECTION_CHUNKED_BODY_UNREADY:
+    return "chunked body unready";
+  case MHD_CONNECTION_CHUNKED_BODY_READY:
+    return "chunked body ready";
+  case MHD_CONNECTION_CHUNKED_BODY_SENT:
+    return "chunked body sent";
+  case MHD_CONNECTION_FOOTERS_SENDING:
+    return "footers sending";
+  case MHD_CONNECTION_FULL_REPLY_SENT:
+    return "reply sent completely";
+  case MHD_CONNECTION_CLOSED:
+    return "closed";
+  default:
+    return "unrecognized connection state";
+  }
 }
+
+
 #endif
 #endif
 
-#if HAVE_MESSAGES
+
+#ifdef HAVE_MESSAGES
 /**
  * fprintf-like helper function for logging debug
  * messages.
  */
 void
-MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...)
+MHD_DLOG (const struct MHD_Daemon *daemon,
+          const char *format,
+          ...)
 {
   va_list va;
 
-  if (0 == (daemon->options & MHD_USE_DEBUG))
+  if (0 == (daemon->options & MHD_USE_ERROR_LOG))
     return;
   va_start (va, format);
-  daemon->custom_error_log (daemon->custom_error_log_cls, format, va);
+  daemon->custom_error_log (daemon->custom_error_log_cls,
+                            format,
+                            va);
   va_end (va);
 }
+
+
 #endif
 
 
 /**
- * Convert all occurences of '+' to ' '.
+ * Convert all occurrences of '+' to ' '.
  *
  * @param arg string that is modified (in place), must be 0-terminated
  */
@@ -114,82 +130,143 @@
 {
   char *p;
 
-  for (p=strchr (arg, '+'); NULL != p; p = strchr (p + 1, '+'))
+  for (p = strchr (arg, '+'); NULL != p; p = strchr (p + 1, '+'))
     *p = ' ';
 }
 
 
 /**
  * Process escape sequences ('%HH') Updates val in place; the
- * result should be UTF-8 encoded and cannot be larger than the input.
- * The result must also still be 0-terminated.
+ * result cannot be larger than the input.
+ * The result is still be 0-terminated.
  *
  * @param val value to unescape (modified in the process)
- * @return length of the resulting val (strlen(val) maybe
+ * @return length of the resulting val (`strlen(val)` may be
  *  shorter afterwards due to elimination of escape sequences)
  */
-size_t
+_MHD_EXTERN size_t
 MHD_http_unescape (char *val)
 {
-  char *rpos = val;
-  char *wpos = val;
-  char *end;
-  unsigned int num;
-  char buf3[3];
-
-  while ('\0' != *rpos)
-    {
-      switch (*rpos)
-	{
-	case '%':
-          if ( ('\0' == rpos[1]) ||
-               ('\0' == rpos[2]) )
-          {
-            *wpos = '\0';
-            return wpos - val;
-          }
-	  buf3[0] = rpos[1];
-	  buf3[1] = rpos[2];
-	  buf3[2] = '\0';
-	  num = strtoul (buf3, &end, 16);
-	  if ('\0' == *end)
-	    {
-	      *wpos = (char)((unsigned char) num);
-	      wpos++;
-	      rpos += 3;
-	      break;
-	    }
-	  /* intentional fall through! */
-	default:
-	  *wpos = *rpos;
-	  wpos++;
-	  rpos++;
-	}
-    }
-  *wpos = '\0'; /* add 0-terminator */
-  return wpos - val; /* = strlen(val) */
+  return MHD_str_pct_decode_in_place_lenient_ (val, NULL);
 }
 
 
 /**
- * Equivalent to time(NULL) but tries to use some sort of monotonic
- * clock that isn't affected by someone setting the system real time
- * clock.
+ * Parse and unescape the arguments given by the client
+ * as part of the HTTP request URI.
  *
- * @return 'current' time
+ * @param kind header kind to pass to @a cb
+ * @param connection connection to add headers to
+ * @param[in,out] args argument URI string (after "?" in URI),
+ *        clobbered in the process!
+ * @param cb function to call on each key-value pair found
+ * @param cls the iterator context
+ * @return #MHD_NO on failure (@a cb returned #MHD_NO),
+ *         #MHD_YES for success (parsing succeeded, @a cb always
+ *                               returned #MHD_YES)
  */
-time_t
-MHD_monotonic_time (void)
+enum MHD_Result
+MHD_parse_arguments_ (struct MHD_Connection *connection,
+                      enum MHD_ValueKind kind,
+                      char *args,
+                      MHD_ArgumentIterator_ cb,
+                      void *cls)
 {
-#ifdef HAVE_CLOCK_GETTIME
-#ifdef CLOCK_MONOTONIC
-  struct timespec ts;
+  struct MHD_Daemon *daemon = connection->daemon;
+  char *equals;
+  char *amper;
 
-  if (0 == clock_gettime (CLOCK_MONOTONIC, &ts))
-    return ts.tv_sec;
-#endif
-#endif
-  return time (NULL);
+  while ( (NULL != args) &&
+          ('\0' != args[0]) )
+  {
+    size_t key_len;
+    size_t value_len;
+    equals = strchr (args, '=');
+    amper = strchr (args, '&');
+    if (NULL == amper)
+    {
+      /* last argument */
+      if (NULL == equals)
+      {
+        /* last argument, without '=' */
+        MHD_unescape_plus (args);
+        key_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                             connection,
+                                             args);
+        if (MHD_NO == cb (cls,
+                          args,
+                          key_len,
+                          NULL,
+                          0,
+                          kind))
+          return MHD_NO;
+        break;
+      }
+      /* got 'foo=bar' */
+      equals[0] = '\0';
+      equals++;
+      MHD_unescape_plus (args);
+      key_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                           connection,
+                                           args);
+      MHD_unescape_plus (equals);
+      value_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                             connection,
+                                             equals);
+      if (MHD_NO == cb (cls,
+                        args,
+                        key_len,
+                        equals,
+                        value_len,
+                        kind))
+        return MHD_NO;
+      break;
+    }
+    /* amper is non-NULL here */
+    amper[0] = '\0';
+    amper++;
+    if ( (NULL == equals) ||
+         (equals >= amper) )
+    {
+      /* got 'foo&bar' or 'foo&bar=val', add key 'foo' with NULL for value */
+      MHD_unescape_plus (args);
+      key_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                           connection,
+                                           args);
+      if (MHD_NO == cb (cls,
+                        args,
+                        key_len,
+                        NULL,
+                        0,
+                        kind))
+        return MHD_NO;
+      /* continue with 'bar' */
+      args = amper;
+      continue;
+    }
+    /* equals and amper are non-NULL here, and equals < amper,
+ so we got regular 'foo=value&bar...'-kind of argument */
+    equals[0] = '\0';
+    equals++;
+    MHD_unescape_plus (args);
+    key_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                         connection,
+                                         args);
+    MHD_unescape_plus (equals);
+    value_len = daemon->unescape_callback (daemon->unescape_callback_cls,
+                                           connection,
+                                           equals);
+    if (MHD_NO == cb (cls,
+                      args,
+                      key_len,
+                      equals,
+                      value_len,
+                      kind))
+      return MHD_NO;
+    args = amper;
+  }
+  return MHD_YES;
 }
 
+
 /* end of internal.c */
diff --git a/src/microhttpd/internal.h b/src/microhttpd/internal.h
index fa751be..9f5ed44 100644
--- a/src/microhttpd/internal.h
+++ b/src/microhttpd/internal.h
@@ -1,6 +1,7 @@
 /*
   This file is part of libmicrohttpd
-  Copyright (C) 2007-2015 Daniel Pittman and Christian Grothoff
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+  Copyright (C) 2014-2021 Evgeny Grin (Karlson2k)
 
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
@@ -19,41 +20,118 @@
 
 /**
  * @file microhttpd/internal.h
- * @brief  internal shared structures
+ * @brief  MHD internal shared structures
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #ifndef INTERNAL_H
 #define INTERNAL_H
 
+#include "mhd_options.h"
 #include "platform.h"
 #include "microhttpd.h"
-#include "platform_interface.h"
-#if HTTPS_SUPPORT
-#include <openssl/ssl.h>
+#include "mhd_assert.h"
+
+#ifdef HTTPS_SUPPORT
+#include <gnutls/gnutls.h>
+#if GNUTLS_VERSION_MAJOR >= 3
+#include <gnutls/abstract.h>
 #endif
-#if EPOLL_SUPPORT
-#include <sys/epoll.h>
+#endif /* HTTPS_SUPPORT */
+
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
 #endif
-#if HAVE_NETINET_TCP_H
-/* for TCP_FASTOPEN */
-#include <netinet/tcp.h>
+
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif /* HAVE_INTTYPES_H */
+
+#ifndef PRIu64
+#define PRIu64  "llu"
+#endif /* ! PRIu64 */
+
+/* Must be included before other internal headers! */
+#include "mhd_panic.h"
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+#include "mhd_threads.h"
 #endif
+#include "mhd_locks.h"
+#include "mhd_sockets.h"
+#include "mhd_itc_types.h"
+#include "mhd_str_types.h"
+#if defined(BAUTH_SUPPORT) || defined(DAUTH_SUPPORT)
+#include "gen_auth.h"
+#endif /* BAUTH_SUPPORT || DAUTH_SUPPORT*/
 
 
 /**
- * Should we perform additional sanity checks at runtime (on our internal
- * invariants)?  This may lead to aborts, but can be useful for debugging.
+ * Macro to drop 'const' qualifier from pointer without compiler warning.
+ * To be used *only* to deal with broken external APIs, which require non-const
+ * pointer to unmodifiable data.
+ * Must not be used to transform pointers for MHD needs.
  */
-#define EXTRA_CHECKS MHD_NO
+#define _MHD_DROP_CONST(ptr)    ((void *) ((uintptr_t) ((const void *) (ptr))))
 
-#define MHD_MAX(a,b) ((a)<(b)) ? (b) : (a)
-#define MHD_MIN(a,b) ((a)<(b)) ? (a) : (b)
+/**
+ * @def _MHD_MACRO_NO
+ * "Negative answer"/"false" for use in macros, meaningful for precompiler
+ */
+#define _MHD_MACRO_NO   0
+
+/**
+ * @def _MHD_MACRO_YES
+ * "Positive answer"/"true" for use in macros, meaningful for precompiler
+ */
+#define _MHD_MACRO_YES  1
+
+/**
+ * Close FD and abort execution if error is detected.
+ * @param fd the FD to close
+ */
+#define MHD_fd_close_chk_(fd) do {                      \
+    if ( (0 != close ((fd)) && (EBADF == errno)) ) {    \
+      MHD_PANIC (_ ("Failed to close FD.\n"));          \
+    }                                                   \
+} while (0)
+
+/*
+#define EXTRA_CHECKS _MHD_MACRO_NO
+ * Not used. Behaviour is controlled by _DEBUG/NDEBUG macros.
+ */
+
+#ifndef _MHD_DEBUG_CONNECT
+/**
+ * Print extra messages when establishing
+ * connections? (only adds non-error messages).
+ */
+#define _MHD_DEBUG_CONNECT _MHD_MACRO_NO
+#endif /* ! _MHD_DEBUG_CONNECT */
+
+#ifndef _MHD_DEBUG_SEND_DATA
+/**
+ * Should all data send be printed to stderr?
+ */
+#define _MHD_DEBUG_SEND_DATA _MHD_MACRO_NO
+#endif /* ! _MHD_DEBUG_SEND_DATA */
+
+#ifndef _MHD_DEBUG_CLOSE
+/**
+ * Add extra debug messages with reasons for closing connections
+ * (non-error reasons).
+ */
+#define _MHD_DEBUG_CLOSE _MHD_MACRO_NO
+#endif /* ! _MHD_DEBUG_CLOSE */
+
+#define MHD_MAX(a,b) (((a)<(b)) ? (b) : (a))
+#define MHD_MIN(a,b) (((a)<(b)) ? (a) : (b))
 
 
 /**
- * Minimum size by which MHD tries to increment read/write buffers.
+ * Minimum reasonable size by which MHD tries to increment read/write buffers.
  * We usually begin with half the available pool space for the
  * IO-buffer, but if absolutely needed we additively grow by the
  * number of bytes given here (up to -- theoretically -- the full pool
@@ -61,118 +139,133 @@
  */
 #define MHD_BUF_INC_SIZE 1024
 
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
 
 /**
- * Handler for fatal errors.
+ * Tri-state on/off/unknown
  */
-extern MHD_PanicCallback mhd_panic;
-
-/**
- * Closure argument for "mhd_panic".
- */
-extern void *mhd_panic_cls;
-
-/* If we have Clang or gcc >= 4.5, use __buildin_unreachable() */
-#if defined(__clang__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
-#define BUILTIN_NOT_REACHED __builtin_unreachable()
-#else
-#define BUILTIN_NOT_REACHED
-#endif
-
-
-#if HAVE_MESSAGES
-/**
- * Trigger 'panic' action based on fatal errors.
- *
- * @param msg error message (const char *)
- */
-#define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, msg); BUILTIN_NOT_REACHED; } while (0)
-#else
-/**
- * Trigger 'panic' action based on fatal errors.
- *
- * @param msg error message (const char *)
- */
-#define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL); BUILTIN_NOT_REACHED; } while (0)
-#endif
+enum MHD_tristate
+{
+  _MHD_UNKNOWN = -1,    /**< State is not yet checked nor set */
+  _MHD_OFF     = false, /**< State is "off" / "disabled" */
+  _MHD_NO      = false, /**< State is "off" / "disabled" */
+  _MHD_ON      = true,  /**< State is "on"  / "enabled" */
+  _MHD_YES     = true   /**< State is "on"  / "enabled" */
+} _MHD_FIXED_ENUM;
 
 
 /**
  * State of the socket with respect to epoll (bitmask).
  */
 enum MHD_EpollState
-  {
+{
 
-    /**
-     * The socket is not involved with a defined state in epoll right
-     * now.
-     */
-    MHD_EPOLL_STATE_UNREADY = 0,
+  /**
+   * The socket is not involved with a defined state in epoll() right
+   * now.
+   */
+  MHD_EPOLL_STATE_UNREADY = 0,
 
-    /**
-     * epoll told us that data was ready for reading, and we did
-     * not consume all of it yet.
-     */
-    MHD_EPOLL_STATE_READ_READY = 1,
+  /**
+   * epoll() told us that data was ready for reading, and we did
+   * not consume all of it yet.
+   */
+  MHD_EPOLL_STATE_READ_READY = 1,
 
-    /**
-     * epoll told us that space was available for writing, and we did
-     * not consume all of it yet.
-     */
-    MHD_EPOLL_STATE_WRITE_READY = 2,
+  /**
+   * epoll() told us that space was available for writing, and we did
+   * not consume all of it yet.
+   */
+  MHD_EPOLL_STATE_WRITE_READY = 2,
 
-    /**
-     * Is this connection currently in the 'eready' EDLL?
-     */
-    MHD_EPOLL_STATE_IN_EREADY_EDLL = 4,
+  /**
+   * Is this connection currently in the 'eready' EDLL?
+   */
+  MHD_EPOLL_STATE_IN_EREADY_EDLL = 4,
 
-    /**
-     * Is this connection currently in the 'epoll' set?
-     */
-    MHD_EPOLL_STATE_IN_EPOLL_SET = 8,
+  /**
+   * Is this connection currently in the epoll() set?
+   */
+  MHD_EPOLL_STATE_IN_EPOLL_SET = 8,
 
-    /**
-     * Is this connection currently suspended?
-     */
-    MHD_EPOLL_STATE_SUSPENDED = 16
-  };
+  /**
+   * Is this connection currently suspended?
+   */
+  MHD_EPOLL_STATE_SUSPENDED = 16,
+
+  /**
+   * Is this connection in some error state?
+   */
+  MHD_EPOLL_STATE_ERROR = 128
+} _MHD_FIXED_FLAGS_ENUM;
 
 
 /**
  * What is this connection waiting for?
  */
 enum MHD_ConnectionEventLoopInfo
-  {
-    /**
-     * We are waiting to be able to read.
-     */
-    MHD_EVENT_LOOP_INFO_READ = 0,
+{
+  /**
+   * We are waiting to be able to read.
+   */
+  MHD_EVENT_LOOP_INFO_READ = 1 << 0,
 
-    /**
-     * We are waiting to be able to write.
-     */
-    MHD_EVENT_LOOP_INFO_WRITE = 1,
+  /**
+   * We are waiting to be able to write.
+   */
+  MHD_EVENT_LOOP_INFO_WRITE = 1 << 1,
 
-    /**
-     * We are waiting for the application to provide data.
-     */
-    MHD_EVENT_LOOP_INFO_BLOCK = 2,
+  /**
+   * We are waiting for the application to provide data.
+   */
+  MHD_EVENT_LOOP_INFO_PROCESS = 1 << 2,
 
-    /**
-     * We are finished and are awaiting cleanup.
-     */
-    MHD_EVENT_LOOP_INFO_CLEANUP = 3
-  };
+  /**
+   * Some data is ready to be processed, but more data could
+   * be read.
+   */
+  MHD_EVENT_LOOP_INFO_PROCESS_READ =
+    MHD_EVENT_LOOP_INFO_READ | MHD_EVENT_LOOP_INFO_PROCESS,
+
+  /**
+   * We are finished and are awaiting cleanup.
+   */
+  MHD_EVENT_LOOP_INFO_CLEANUP = 1 << 3
+} _MHD_FIXED_ENUM;
 
 
 /**
- * Maximum length of a nonce in digest authentication.  32(MD5 Hex) +
- * 8(Timestamp Hex) + 1(NULL); hence 41 should suffice, but Opera
+ * Additional test value for enum MHD_FLAG to check only for MHD_ALLOW_SUSPEND_RESUME and
+ * NOT for MHD_USE_ITC.
+ */
+#define MHD_TEST_ALLOW_SUSPEND_RESUME 8192
+
+/**
+ * Maximum length of a nonce in digest authentication.  64(SHA-256 Hex) +
+ * 12(Timestamp Hex) + 1(NULL); hence 77 should suffice, but Opera
  * (already) takes more (see Mantis #1633), so we've increased the
  * value to support something longer...
  */
-#define MAX_NONCE_LENGTH 129
+#define MAX_CLIENT_NONCE_LENGTH 129
 
+/**
+ * The maximum size of MHD-generated nonce when printed with hexadecimal chars.
+ *
+ * This is equal to "(32 bytes for SHA-256 (or SHA-512/256) nonce plus 6 bytes
+ * for timestamp) multiplied by two hex chars per byte".
+ * Please keep it in sync with digestauth.c
+ */
+#if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT)
+#define MAX_DIGEST_NONCE_LENGTH ((32 + 6) * 2)
+#else  /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */
+#define MAX_DIGEST_NONCE_LENGTH ((16 + 6) * 2)
+#endif /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */
 
 /**
  * A structure representing the internal holder of the
@@ -183,52 +276,77 @@
 
   /**
    * Nonce counter, a value that increases for each subsequent
-   * request for the same nonce.
+   * request for the same nonce. Matches the largest last received
+   * 'nc' value.
+   * This 'nc' value was already used by the client.
    */
-  unsigned long int nc;
+  uint32_t nc;
 
   /**
-   * Nonce value:
+   * Bitmask over the previous 64 nonce counter values (down to to nc-64).
+   * Used to allow out-of-order 'nc'.
+   * If bit in the bitmask is set to one, then this 'nc' value was already used
+   * by the client.
    */
-  char nonce[MAX_NONCE_LENGTH];
+  uint64_t nmask;
+
+  /**
+   * Nonce value
+   */
+  char nonce[MAX_DIGEST_NONCE_LENGTH + 1];
 
 };
 
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
 /**
- * fprintf-like helper function for logging debug
+ * fprintf()-like helper function for logging debug
  * messages.
  */
 void
 MHD_DLOG (const struct MHD_Daemon *daemon,
-	  const char *format, ...);
+          const char *format,
+          ...);
+
 #endif
 
 
 /**
- * Header or cookie in HTTP request or response.
+ * Header or footer for HTTP response.
  */
-struct MHD_HTTP_Header
+struct MHD_HTTP_Res_Header
 {
   /**
-   * Headers are kept in a linked list.
+   * Headers are kept in a double-linked list.
    */
-  struct MHD_HTTP_Header *next;
+  struct MHD_HTTP_Res_Header *next;
 
   /**
-   * The name of the header (key), without
-   * the colon.
+   * Headers are kept in a double-linked list.
+   */
+  struct MHD_HTTP_Res_Header *prev;
+
+  /**
+   * The name of the header (key), without the colon.
    */
   char *header;
 
   /**
+   * The length of the @a header, not including the final zero termination.
+   */
+  size_t header_size;
+
+  /**
    * The value of the header.
    */
   char *value;
 
   /**
-   * Type of the header (where in the HTTP
-   * protocol is this header from).
+   * The length of the @a value, not including the final zero termination.
+   */
+  size_t value_size;
+
+  /**
+   * Type of the value.
    */
   enum MHD_ValueKind kind;
 
@@ -236,23 +354,137 @@
 
 
 /**
+ * Header, footer, or cookie for HTTP request.
+ */
+struct MHD_HTTP_Req_Header
+{
+  /**
+   * Headers are kept in a double-linked list.
+   */
+  struct MHD_HTTP_Req_Header *next;
+
+  /**
+   * Headers are kept in a double-linked list.
+   */
+  struct MHD_HTTP_Req_Header *prev;
+
+  /**
+   * The name of the header (key), without the colon.
+   */
+  const char *header;
+
+  /**
+   * The length of the @a header, not including the final zero termination.
+   */
+  size_t header_size;
+
+  /**
+   * The value of the header.
+   */
+  const char *value;
+
+  /**
+   * The length of the @a value, not including the final zero termination.
+   */
+  size_t value_size;
+
+  /**
+   * Type of the value.
+   */
+  enum MHD_ValueKind kind;
+
+};
+
+
+/**
+ * Automatically assigned flags
+ */
+enum MHD_ResponseAutoFlags
+{
+  MHD_RAF_NO_FLAGS = 0,                   /**< No auto flags */
+  MHD_RAF_HAS_CONNECTION_HDR = 1 << 0,    /**< Has "Connection" header */
+  MHD_RAF_HAS_CONNECTION_CLOSE = 1 << 1,  /**< Has "Connection: close" */
+  MHD_RAF_HAS_TRANS_ENC_CHUNKED = 1 << 2, /**< Has "Transfer-Encoding: chunked" */
+  MHD_RAF_HAS_CONTENT_LENGTH = 1 << 3,    /**< Has "Content-Length" header */
+  MHD_RAF_HAS_DATE_HDR = 1 << 4           /**< Has "Date" header */
+} _MHD_FIXED_FLAGS_ENUM;
+
+
+#if defined(MHD_WINSOCK_SOCKETS)
+/**
+ * Internally used I/O vector type for use with winsock.
+ * Binary matches system "WSABUF".
+ */
+typedef struct _MHD_W32_iovec
+{
+  unsigned long iov_len;
+  char *iov_base;
+} MHD_iovec_;
+#define MHD_IOV_ELMN_MAX_SIZE    ULONG_MAX
+typedef unsigned long MHD_iov_size_;
+#elif defined(HAVE_SENDMSG) || defined(HAVE_WRITEV)
+/**
+ * Internally used I/O vector type for use when writev or sendmsg
+ * is available. Matches system "struct iovec".
+ */
+typedef struct iovec MHD_iovec_;
+#define MHD_IOV_ELMN_MAX_SIZE    SIZE_MAX
+typedef size_t MHD_iov_size_;
+#else
+/**
+ * Internally used I/O vector type for use when writev or sendmsg
+ * is not available.
+ */
+typedef struct MHD_IoVec MHD_iovec_;
+#define MHD_IOV_ELMN_MAX_SIZE    SIZE_MAX
+typedef size_t MHD_iov_size_;
+#endif
+
+
+struct MHD_iovec_track_
+{
+  /**
+   * The copy of array of iovec elements.
+   * The copy of elements are updated during sending.
+   * The number of elements is not changed during lifetime.
+   */
+  MHD_iovec_ *iov;
+
+  /**
+   * The number of elements in @a iov.
+   * This value is not changed during lifetime.
+   */
+  size_t cnt;
+
+  /**
+   * The number of sent elements.
+   * At the same time, it is the index of the next (or current) element
+   * to send.
+   */
+  size_t sent;
+};
+
+/**
  * Representation of a response.
  */
 struct MHD_Response
 {
 
   /**
-   * Headers to send for the response.  Initially
-   * the linked list is created in inverse order;
-   * the order should be inverted before sending!
+   * Head of double-linked list of headers to send for the response.
    */
-  struct MHD_HTTP_Header *first_header;
+  struct MHD_HTTP_Res_Header *first_header;
+
+  /**
+   * Tail of double-linked list of headers to send for the response.
+   */
+  struct MHD_HTTP_Res_Header *last_header;
 
   /**
    * Buffer pointing to data that we are supposed
    * to send as a response.
    */
-  char *data;
+  const char *data;
 
   /**
    * Closure to give to the content reader @e crc
@@ -272,13 +504,30 @@
    */
   MHD_ContentReaderFreeCallback crfc;
 
+#ifdef UPGRADE_SUPPORT
+  /**
+   * Application function to call once we are done sending the headers
+   * of the response; NULL unless this is a response created with
+   * #MHD_create_response_for_upgrade().
+   */
+  MHD_UpgradeHandler upgrade_handler;
+
+  /**
+   * Closure for @e uh.
+   */
+  void *upgrade_handler_cls;
+#endif /* UPGRADE_SUPPORT */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   /**
    * Mutex to synchronize access to @e data, @e size and
    * @e reference_count.
    */
   MHD_mutex_ mutex;
+#endif
 
   /**
+   * The size of the response body.
    * Set to #MHD_SIZE_UNKNOWN if size is not known.
    */
   uint64_t total_size;
@@ -292,7 +541,7 @@
   /**
    * Offset to start reading from when using @e fd.
    */
-  off_t fd_off;
+  uint64_t fd_off;
 
   /**
    * Number of bytes ready in @e data (buffer may be larger
@@ -301,13 +550,13 @@
   size_t data_size;
 
   /**
-   * Size of the data buffer @e data.
+   * Size of the writable data buffer @e data.
    */
   size_t data_buffer_size;
 
   /**
-   * Reference count for this response.  Free
-   * once the counter hits zero.
+   * Reference count for this response.  Free once the counter hits
+   * zero.
    */
   unsigned int reference_count;
 
@@ -321,22 +570,42 @@
    */
   enum MHD_ResponseFlags flags;
 
+  /**
+   * Automatic flags set for the MHD response.
+   */
+  enum MHD_ResponseAutoFlags flags_auto;
+
+  /**
+   * If the @e fd is a pipe (no sendfile()).
+   */
+  bool is_pipe;
+
+  /**
+   * I/O vector used with MHD_create_response_from_iovec.
+   */
+  MHD_iovec_ *data_iov;
+
+  /**
+   * Number of elements in data_iov.
+   */
+  unsigned int data_iovcnt;
 };
 
 
 /**
  * States in a state machine for a connection.
  *
- * Transitions are any-state to CLOSED, any state to state+1,
- * FOOTERS_SENT to INIT.  CLOSED is the terminal state and
- * INIT the initial state.
+ * The main transitions are any-state to #MHD_CONNECTION_CLOSED, any
+ * state to state+1, #MHD_CONNECTION_FOOTERS_SENT to
+ * #MHD_CONNECTION_INIT.  #MHD_CONNECTION_CLOSED is the terminal state
+ * and #MHD_CONNECTION_INIT the initial state.
  *
- * Note that transitions for *reading* happen only after
- * the input has been processed; transitions for
- * *writing* happen after the respective data has been
- * put into the write buffer (the write does not have
- * to be completed yet).  A transition to CLOSED or INIT
- * requires the write to be complete.
+ * Note that transitions for *reading* happen only after the input has
+ * been processed; transitions for *writing* happen after the
+ * respective data has been put into the write buffer (the write does
+ * not have to be completed yet).  A transition to
+ * #MHD_CONNECTION_CLOSED or #MHD_CONNECTION_INIT requires the write
+ * to be complete.
  */
 enum MHD_CONNECTION_STATE
 {
@@ -347,132 +616,163 @@
   MHD_CONNECTION_INIT = 0,
 
   /**
-   * 1: We got the URL (and request type and version).  Wait for a header line.
+   * Part of the request line was received.
+   * Wait for complete line.
    */
-  MHD_CONNECTION_URL_RECEIVED = MHD_CONNECTION_INIT + 1,
+  MHD_CONNECTION_REQ_LINE_RECEIVING = MHD_CONNECTION_INIT + 1,
 
   /**
-   * 2: We got part of a multi-line request header.  Wait for the rest.
+   * We got the URL (and request type and version).  Wait for a header line.
+   */
+  MHD_CONNECTION_URL_RECEIVED = MHD_CONNECTION_REQ_LINE_RECEIVING + 1,
+
+  /**
+   * We got part of a multi-line request header.  Wait for the rest.
    */
   MHD_CONNECTION_HEADER_PART_RECEIVED = MHD_CONNECTION_URL_RECEIVED + 1,
 
   /**
-   * 3: We got the request headers.  Process them.
+   * We got the request headers.  Process them.
    */
   MHD_CONNECTION_HEADERS_RECEIVED = MHD_CONNECTION_HEADER_PART_RECEIVED + 1,
 
   /**
-   * 4: We have processed the request headers.  Send 100 continue.
+   * We have processed the request headers.  Send 100 continue.
    */
   MHD_CONNECTION_HEADERS_PROCESSED = MHD_CONNECTION_HEADERS_RECEIVED + 1,
 
   /**
-   * 5: We have processed the headers and need to send 100 CONTINUE.
+   * We have processed the headers and need to send 100 CONTINUE.
    */
   MHD_CONNECTION_CONTINUE_SENDING = MHD_CONNECTION_HEADERS_PROCESSED + 1,
 
   /**
-   * 6: We have sent 100 CONTINUE (or do not need to).  Read the message body.
+   * We have sent 100 CONTINUE (or do not need to).  Read the message body.
    */
-  MHD_CONNECTION_CONTINUE_SENT = MHD_CONNECTION_CONTINUE_SENDING + 1,
+  MHD_CONNECTION_BODY_RECEIVING = MHD_CONNECTION_CONTINUE_SENDING + 1,
 
   /**
-   * 7: We got the request body.  Wait for a line of the footer.
+   * We got the request body.  Wait for a line of the footer.
    */
-  MHD_CONNECTION_BODY_RECEIVED = MHD_CONNECTION_CONTINUE_SENT + 1,
+  MHD_CONNECTION_BODY_RECEIVED = MHD_CONNECTION_BODY_RECEIVING + 1,
 
   /**
-   * 8: We got part of a line of the footer.  Wait for the
+   * We got part of a line of the footer.  Wait for the
    * rest.
    */
   MHD_CONNECTION_FOOTER_PART_RECEIVED = MHD_CONNECTION_BODY_RECEIVED + 1,
 
   /**
-   * 9: We received the entire footer.  Wait for a response to be queued
-   * and prepare the response headers.
+   * We received the entire footer.
    */
   MHD_CONNECTION_FOOTERS_RECEIVED = MHD_CONNECTION_FOOTER_PART_RECEIVED + 1,
 
   /**
-   * 10: We have prepared the response headers in the writ buffer.
-   * Send the response headers.
+   * We received the entire request.
+   * Wait for a response to be queued.
    */
-  MHD_CONNECTION_HEADERS_SENDING = MHD_CONNECTION_FOOTERS_RECEIVED + 1,
+  MHD_CONNECTION_FULL_REQ_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVED + 1,
 
   /**
-   * 11: We have sent the response headers.  Get ready to send the body.
+   * Finished reading of the request and the response is ready.
+   * Switch internal logic from receiving to sending, prepare connection
+   * sending the reply and build the reply header.
+   */
+  MHD_CONNECTION_START_REPLY = MHD_CONNECTION_FULL_REQ_RECEIVED + 1,
+
+  /**
+   * We have prepared the response headers in the write buffer.
+   * Send the response headers.
+   */
+  MHD_CONNECTION_HEADERS_SENDING = MHD_CONNECTION_START_REPLY + 1,
+
+  /**
+   * We have sent the response headers.  Get ready to send the body.
    */
   MHD_CONNECTION_HEADERS_SENT = MHD_CONNECTION_HEADERS_SENDING + 1,
 
   /**
-   * 12: We are ready to send a part of a non-chunked body.  Send it.
-   */
-  MHD_CONNECTION_NORMAL_BODY_READY = MHD_CONNECTION_HEADERS_SENT + 1,
-
-  /**
-   * 13: We are waiting for the client to provide more
+   * We are waiting for the client to provide more
    * data of a non-chunked body.
    */
-  MHD_CONNECTION_NORMAL_BODY_UNREADY = MHD_CONNECTION_NORMAL_BODY_READY + 1,
+  MHD_CONNECTION_NORMAL_BODY_UNREADY = MHD_CONNECTION_HEADERS_SENT + 1,
 
   /**
-   * 14: We are ready to send a chunk.
+   * We are ready to send a part of a non-chunked body.  Send it.
    */
-  MHD_CONNECTION_CHUNKED_BODY_READY = MHD_CONNECTION_NORMAL_BODY_UNREADY + 1,
+  MHD_CONNECTION_NORMAL_BODY_READY = MHD_CONNECTION_NORMAL_BODY_UNREADY + 1,
 
   /**
-   * 15: We are waiting for the client to provide a chunk of the body.
+   * We are waiting for the client to provide a chunk of the body.
    */
-  MHD_CONNECTION_CHUNKED_BODY_UNREADY = MHD_CONNECTION_CHUNKED_BODY_READY + 1,
+  MHD_CONNECTION_CHUNKED_BODY_UNREADY = MHD_CONNECTION_NORMAL_BODY_READY + 1,
 
   /**
-   * 16: We have sent the response body. Prepare the footers.
+   * We are ready to send a chunk.
    */
-  MHD_CONNECTION_BODY_SENT = MHD_CONNECTION_CHUNKED_BODY_UNREADY + 1,
+  MHD_CONNECTION_CHUNKED_BODY_READY = MHD_CONNECTION_CHUNKED_BODY_UNREADY + 1,
 
   /**
-   * 17: We have prepared the response footer.  Send it.
+   * We have sent the chunked response body. Prepare the footers.
    */
-  MHD_CONNECTION_FOOTERS_SENDING = MHD_CONNECTION_BODY_SENT + 1,
+  MHD_CONNECTION_CHUNKED_BODY_SENT = MHD_CONNECTION_CHUNKED_BODY_READY + 1,
 
   /**
-   * 18: We have sent the response footer.  Shutdown or restart.
+   * We have prepared the response footer.  Send it.
    */
-  MHD_CONNECTION_FOOTERS_SENT = MHD_CONNECTION_FOOTERS_SENDING + 1,
+  MHD_CONNECTION_FOOTERS_SENDING = MHD_CONNECTION_CHUNKED_BODY_SENT + 1,
 
   /**
-   * 19: This connection is to be closed.
+   * We have sent the entire reply.
+   * Shutdown connection or restart processing to get a new request.
    */
-  MHD_CONNECTION_CLOSED = MHD_CONNECTION_FOOTERS_SENT + 1,
+  MHD_CONNECTION_FULL_REPLY_SENT = MHD_CONNECTION_FOOTERS_SENDING + 1,
 
   /**
-   * 20: This connection is finished (only to be freed)
+   * This connection is to be closed.
    */
-  MHD_CONNECTION_IN_CLEANUP = MHD_CONNECTION_CLOSED + 1,
+  MHD_CONNECTION_CLOSED = MHD_CONNECTION_FULL_REPLY_SENT + 1
 
-  /*
-   *  SSL/TLS connection states
-   */
-
+#ifdef UPGRADE_SUPPORT
+  ,
   /**
-   * The initial connection state for all secure connectoins
-   * Handshake messages will be processed in this state & while
-   * in the 'MHD_TLS_HELLO_REQUEST' state
+   * Connection was "upgraded" and socket is now under the
+   * control of the application.
    */
-  MHD_TLS_CONNECTION_INIT = MHD_CONNECTION_IN_CLEANUP + 1
+  MHD_CONNECTION_UPGRADE = MHD_CONNECTION_CLOSED + 1
+#endif /* UPGRADE_SUPPORT */
 
-};
+} _MHD_FIXED_ENUM;
+
+
+/**
+ * States of TLS transport layer.
+ */
+enum MHD_TLS_CONN_STATE
+{
+  MHD_TLS_CONN_NO_TLS = 0,  /**< Not a TLS connection (plain socket).   */
+  MHD_TLS_CONN_INIT,        /**< TLS connection is not established yet. */
+  MHD_TLS_CONN_HANDSHAKING, /**< TLS is in handshake process.           */
+  MHD_TLS_CONN_CONNECTED,   /**< TLS is established.                    */
+  MHD_TLS_CONN_WR_CLOSING,  /**< Closing WR side of TLS layer.          */
+  MHD_TLS_CONN_WR_CLOSED,   /**< WR side of TLS layer is closed.        */
+  MHD_TLS_CONN_TLS_CLOSING, /**< TLS session is terminating.            */
+  MHD_TLS_CONN_TLS_CLOSED,  /**< TLS session is terminated.             */
+  MHD_TLS_CONN_TLS_FAILED,  /**< TLS session failed.                    */
+  MHD_TLS_CONN_INVALID_STATE/**< Sentinel. Not a valid value.           */
+} _MHD_FIXED_ENUM;
 
 /**
  * Should all state transitions be printed to stderr?
  */
-#define DEBUG_STATES MHD_NO
+#define DEBUG_STATES _MHD_MACRO_NO
 
 
-#if HAVE_MESSAGES
+#ifdef HAVE_MESSAGES
 #if DEBUG_STATES
 const char *
 MHD_state_to_string (enum MHD_CONNECTION_STATE state);
+
 #endif
 #endif
 
@@ -482,7 +782,7 @@
  * @param conn the connection struct
  * @param write_to where to write received data
  * @param max_bytes maximum number of bytes to receive
- * @return number of bytes written to write_to
+ * @return number of bytes written to @a write_to
  */
 typedef ssize_t
 (*ReceiveCallback) (struct MHD_Connection *conn,
@@ -500,17 +800,377 @@
  */
 typedef ssize_t
 (*TransmitCallback) (struct MHD_Connection *conn,
-                     const void *write_to,
+                     const void *read_from,
                      size_t max_bytes);
 
 
 /**
+ * Ability to use same connection for next request
+ */
+enum MHD_ConnKeepAlive
+{
+  /**
+   * Connection must be closed after sending response.
+   */
+  MHD_CONN_MUST_CLOSE = -1,
+
+  /**
+   * KeelAlive state is not yet determined
+   */
+  MHD_CONN_KEEPALIVE_UNKOWN = 0,
+
+  /**
+   * Connection can be used for serving next request
+   */
+  MHD_CONN_USE_KEEPALIVE = 1,
+
+  /**
+   * Connection will be upgraded
+   */
+  MHD_CONN_MUST_UPGRADE = 2
+} _MHD_FIXED_ENUM;
+
+enum MHD_HTTP_Version
+{
+  /**
+   * Not a HTTP protocol or HTTP version is invalid.
+   */
+  MHD_HTTP_VER_INVALID = -1,
+
+  /**
+   * HTTP version is not yet received from the client.
+   */
+  MHD_HTTP_VER_UNKNOWN = 0,
+
+  /**
+   * HTTP version before 1.0, unsupported.
+   */
+  MHD_HTTP_VER_TOO_OLD = 1,
+
+  /**
+   * HTTP version 1.0
+   */
+  MHD_HTTP_VER_1_0 = 2,
+
+  /**
+   * HTTP version 1.1
+   */
+  MHD_HTTP_VER_1_1 = 3,
+
+  /**
+   * HTTP version 1.2-1.9, must be used as 1.1
+   */
+  MHD_HTTP_VER_1_2__1_9 = 4,
+
+  /**
+   * HTTP future version. Unsupported.
+   */
+  MHD_HTTP_VER_FUTURE = 100
+} _MHD_FIXED_ENUM;
+
+/**
+ * Returns boolean 'true' if HTTP version is supported by MHD
+ */
+#define MHD_IS_HTTP_VER_SUPPORTED(ver) (MHD_HTTP_VER_1_0 <= (ver) && \
+                                        MHD_HTTP_VER_1_2__1_9 >= (ver))
+
+/**
+ * Protocol should be used as HTTP/1.1 protocol.
+ *
+ * See the last paragraph of
+ * https://datatracker.ietf.org/doc/html/rfc7230#section-2.6
+ */
+#define MHD_IS_HTTP_VER_1_1_COMPAT(ver) (MHD_HTTP_VER_1_1 == (ver) || \
+                                         MHD_HTTP_VER_1_2__1_9 == (ver))
+
+/**
+ * The HTTP method.
+ *
+ * Only primary methods (specified in RFC7231) are defined here.
+ */
+enum MHD_HTTP_Method
+{
+  /**
+   * No request string has been received yet
+   */
+  MHD_HTTP_MTHD_NO_METHOD = 0,
+  /**
+   * HTTP method GET
+   */
+  MHD_HTTP_MTHD_GET = 1,
+  /**
+   * HTTP method HEAD
+   */
+  MHD_HTTP_MTHD_HEAD = 2,
+  /**
+   * HTTP method POST
+   */
+  MHD_HTTP_MTHD_POST = 3,
+  /**
+   * HTTP method PUT
+   */
+  MHD_HTTP_MTHD_PUT = 4,
+  /**
+   * HTTP method DELETE
+   */
+  MHD_HTTP_MTHD_DELETE = 5,
+  /**
+   * HTTP method CONNECT
+   */
+  MHD_HTTP_MTHD_CONNECT = 6,
+  /**
+   * HTTP method OPTIONS
+   */
+  MHD_HTTP_MTHD_OPTIONS = 7,
+  /**
+   * HTTP method TRACE
+   */
+  MHD_HTTP_MTHD_TRACE = 8,
+  /**
+   * Other HTTP method. Check the string value.
+   */
+  MHD_HTTP_MTHD_OTHER = 1000
+} _MHD_FIXED_ENUM;
+
+
+/**
+ * Request-specific values.
+ *
+ * Meaningful for the current request only.
+ */
+struct MHD_Request
+{
+  /**
+   * HTTP version string (i.e. http/1.1).  Allocated
+   * in pool.
+   */
+  const char *version;
+
+  /**
+   * HTTP protocol version as enum.
+   */
+  enum MHD_HTTP_Version http_ver;
+
+  /**
+   * Request method.  Should be GET/POST/etc.  Allocated in pool.
+   */
+  const char *method;
+
+  /**
+   * The request method as enum.
+   */
+  enum MHD_HTTP_Method http_mthd;
+
+  /**
+   * Requested URL (everything after "GET" only).  Allocated
+   * in pool.
+   */
+  const char *url;
+
+  /**
+   * The length of the @a url in characters, not including the terminating zero.
+   */
+  size_t url_len;
+
+  /**
+   * Linked list of parsed headers.
+   */
+  struct MHD_HTTP_Req_Header *headers_received;
+
+  /**
+   * Tail of linked list of parsed headers.
+   */
+  struct MHD_HTTP_Req_Header *headers_received_tail;
+
+  /**
+   * Number of bytes we had in the HTTP header, set once we
+   * pass #MHD_CONNECTION_HEADERS_RECEIVED.
+   */
+  size_t header_size;
+
+  /**
+   * How many more bytes of the body do we expect
+   * to read? #MHD_SIZE_UNKNOWN for unknown.
+   */
+  uint64_t remaining_upload_size;
+
+  /**
+   * Are we receiving with chunked encoding?
+   * This will be set to #MHD_YES after we parse the headers and
+   * are processing the body with chunks.
+   * After we are done with the body and we are processing the footers;
+   * once the footers are also done, this will be set to #MHD_NO again
+   * (before the final call to the handler).
+   * It is used only for requests, chunked encoding for response is
+   * indicated by @a rp_props.
+   */
+  bool have_chunked_upload;
+
+  /**
+   * If we are receiving with chunked encoding, where are we right
+   * now?
+   * Set to 0 if we are waiting to receive the chunk size;
+   * otherwise, this is the size of the current chunk.
+   * A value of zero is also used when we're at the end of the chunks.
+   */
+  uint64_t current_chunk_size;
+
+  /**
+   * If we are receiving with chunked encoding, where are we currently
+   * with respect to the current chunk (at what offset / position)?
+   */
+  uint64_t current_chunk_offset;
+
+  /**
+   * Indicate that some of the upload payload data have been processed
+   * by the last call of the connection handler.
+   * If any data have been processed, but some data left in the buffer
+   * for further processing, then MHD will use zero timeout before the
+   * next data processing round.
+   * If no data have been processed, than MHD will wait for more data
+   * to come (as it makes no sense to call the connection handler with
+   * the same conditions).
+   */
+  bool some_payload_processed;
+
+  /**
+   * We allow the main application to associate some pointer with the
+   * HTTP request, which is passed to each #MHD_AccessHandlerCallback
+   * and some other API calls.  Here is where we store it.  (MHD does
+   * not know or care what it is).
+   */
+  void *client_context;
+
+  /**
+   * Did we ever call the "default_handler" on this request?
+   * This flag determines if we have called the #MHD_OPTION_NOTIFY_COMPLETED
+   * handler when the request finishes.
+   */
+  bool client_aware;
+
+#ifdef BAUTH_SUPPORT
+  /**
+   * Basic Authorization parameters.
+   * The result of Basic Authorization header parsing.
+   * Allocated in the connection's pool.
+   */
+  const struct MHD_RqBAuth *bauth;
+
+  /**
+   * Set to true if current request headers are checked for Basic Authorization
+   */
+  bool bauth_tried;
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  /**
+   * Digest Authorization parameters.
+   * The result of Digest Authorization header parsing.
+   * Allocated in the connection's pool.
+   */
+  const struct MHD_RqDAuth *dauth;
+
+  /**
+   * Set to true if current request headers are checked for Digest Authorization
+   */
+  bool dauth_tried;
+#endif /* DAUTH_SUPPORT */
+
+  /**
+   * Last incomplete header line during parsing of headers.
+   * Allocated in pool.  Only valid if state is
+   * either #MHD_CONNECTION_HEADER_PART_RECEIVED or
+   * #MHD_CONNECTION_FOOTER_PART_RECEIVED.
+   */
+  char *last;
+
+  /**
+   * Position after the colon on the last incomplete header
+   * line during parsing of headers.
+   * Allocated in pool.  Only valid if state is
+   * either #MHD_CONNECTION_HEADER_PART_RECEIVED or
+   * #MHD_CONNECTION_FOOTER_PART_RECEIVED.
+   */
+  char *colon;
+};
+
+
+/**
+ * Reply-specific properties.
+ */
+struct MHD_Reply_Properties
+{
+#ifdef _DEBUG
+  bool set; /**< Indicates that other members are set and valid */
+#endif /* _DEBUG */
+  bool use_reply_body_headers; /**< Use reply body-specific headers */
+  bool send_reply_body; /**< Send reply body (can be zero-sized) */
+  bool chunked; /**< Use chunked encoding for reply */
+};
+
+#if defined(_MHD_HAVE_SENDFILE)
+enum MHD_resp_sender_
+{
+  MHD_resp_sender_std = 0,
+  MHD_resp_sender_sendfile
+};
+#endif /* _MHD_HAVE_SENDFILE */
+
+/**
+ * Reply-specific values.
+ *
+ * Meaningful for the current reply only.
+ */
+struct MHD_Reply
+{
+  /**
+   * Response to transmit (initially NULL).
+   */
+  struct MHD_Response *response;
+
+  /**
+   * HTTP response code.  Only valid if response object
+   * is already set.
+   */
+  unsigned int responseCode;
+
+  /**
+   * The "ICY" response.
+   * Reply begins with the SHOUTcast "ICY" line instead of "HTTP".
+   */
+  bool responseIcy;
+
+  /**
+   * Current write position in the actual response
+   * (excluding headers, content only; should be 0
+   * while sending headers).
+   */
+  uint64_t rsp_write_position;
+
+  /**
+   * The copy of iov response.
+   * Valid if iovec response is used.
+   * Updated during send.
+   * Members are allocated in the pool.
+   */
+  struct MHD_iovec_track_ resp_iov;
+
+#if defined(_MHD_HAVE_SENDFILE)
+  enum MHD_resp_sender_ resp_sender;
+#endif /* _MHD_HAVE_SENDFILE */
+
+  /**
+   * Reply-specific properties
+   */
+  struct MHD_Reply_Properties props;
+};
+
+/**
  * State kept for each HTTP request.
  */
 struct MHD_Connection
 {
 
-#if EPOLL_SUPPORT
+#ifdef EPOLL_SUPPORT
   /**
    * Next pointer for the EDLL listing connections that are epoll-ready.
    */
@@ -552,42 +1212,27 @@
   struct MHD_Daemon *daemon;
 
   /**
-   * Linked list of parsed headers.
+   * Request-specific data
    */
-  struct MHD_HTTP_Header *headers_received;
+  struct MHD_Request rq;
 
   /**
-   * Tail of linked list of parsed headers.
+   * Reply-specific data
    */
-  struct MHD_HTTP_Header *headers_received_tail;
+  struct MHD_Reply rp;
 
   /**
-   * Response to transmit (initially NULL).
-   */
-  struct MHD_Response *response;
-
-  /**
-   * The memory pool is created whenever we first read
-   * from the TCP stream and destroyed at the end of
-   * each request (and re-created for the next request).
-   * In the meantime, this pointer is NULL.  The
-   * pool is used for all connection-related data
-   * except for the response (which maybe shared between
-   * connections) and the IP address (which persists
-   * across individual requests).
+   * The memory pool is created whenever we first read from the TCP
+   * stream and destroyed at the end of each request (and re-created
+   * for the next request).  In the meantime, this pointer is NULL.
+   * The pool is used for all connection-related data except for the
+   * response (which maybe shared between connections) and the IP
+   * address (which persists across individual requests).
    */
   struct MemoryPool *pool;
 
   /**
    * We allow the main application to associate some pointer with the
-   * HTTP request, which is passed to each #MHD_AccessHandlerCallback
-   * and some other API calls.  Here is where we store it.  (MHD does
-   * not know or care what it is).
-   */
-  void *client_context;
-
-  /**
-   * We allow the main application to associate some pointer with the
    * TCP connection (which may span multiple HTTP requests).  Here is
    * where we store it.  (MHD does not know or care what it is).
    * The location is given to the #MHD_NotifyConnectionCallback and
@@ -596,27 +1241,15 @@
   void *socket_context;
 
   /**
-   * Request method.  Should be GET/POST/etc.  Allocated
-   * in pool.
+   * Close connection after sending response?
+   * Functions may change value from "Unknown" or "KeepAlive" to "Must close",
+   * but no functions reset value "Must Close" to any other value.
    */
-  char *method;
+  enum MHD_ConnKeepAlive keepalive;
 
   /**
-   * Requested URL (everything after "GET" only).  Allocated
-   * in pool.
-   */
-  char *url;
-
-  /**
-   * HTTP version string (i.e. http/1.1).  Allocated
-   * in pool.
-   */
-  char *version;
-
-  /**
-   * Buffer for reading requests.   Allocated
-   * in pool.  Actually one byte larger than
-   * @e read_buffer_size (if non-NULL) to allow for
+   * Buffer for reading requests.  Allocated in pool.  Actually one
+   * byte larger than @e read_buffer_size (if non-NULL) to allow for
    * 0-termination.
    */
   char *read_buffer;
@@ -628,55 +1261,39 @@
   char *write_buffer;
 
   /**
-   * Last incomplete header line during parsing of headers.
-   * Allocated in pool.  Only valid if state is
-   * either #MHD_CONNECTION_HEADER_PART_RECEIVED or
-   * #MHD_CONNECTION_FOOTER_PART_RECEIVED.
-   */
-  char *last;
-
-  /**
-   * Position after the colon on the last incomplete header
-   * line during parsing of headers.
-   * Allocated in pool.  Only valid if state is
-   * either #MHD_CONNECTION_HEADER_PART_RECEIVED or
-   * #MHD_CONNECTION_FOOTER_PART_RECEIVED.
-   */
-  char *colon;
-
-  /**
    * Foreign address (of length @e addr_len).  MALLOCED (not
    * in pool!).
    */
-  struct sockaddr *addr;
+  struct sockaddr_storage *addr;
 
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   /**
    * Thread handle for this connection (if we are using
    * one thread per connection).
    */
-  MHD_thread_handle_ pid;
+  MHD_thread_handle_ID_ pid;
+#endif
 
   /**
-   * Size of read_buffer (in bytes).  This value indicates
-   * how many bytes we're willing to read into the buffer;
-   * the real buffer is one byte longer to allow for
-   * adding zero-termination (when needed).
+   * Size of @e read_buffer (in bytes).
+   * This value indicates how many bytes we're willing to read
+   * into the buffer.
    */
   size_t read_buffer_size;
 
   /**
-   * Position where we currently append data in
-   * read_buffer (last valid position).
+   * Position where we currently append data in @e read_buffer (the
+   * next char after the last valid position).
    */
   size_t read_buffer_offset;
 
   /**
-   * Size of write_buffer (in bytes).
+   * Size of @e write_buffer (in bytes).
    */
   size_t write_buffer_size;
 
   /**
-   * Offset where we are with sending from write_buffer.
+   * Offset where we are with sending from @e write_buffer.
    */
   size_t write_buffer_send_offset;
 
@@ -687,19 +1304,6 @@
   size_t write_buffer_append_offset;
 
   /**
-   * How many more bytes of the body do we expect
-   * to read? #MHD_SIZE_UNKNOWN for unknown.
-   */
-  uint64_t remaining_upload_size;
-
-  /**
-   * Current write position in the actual response
-   * (excluding headers, content only; should be 0
-   * while sending headers).
-   */
-  uint64_t response_write_position;
-
-  /**
    * Position in the 100 CONTINUE message that
    * we need to send when receiving http 1.1 requests.
    */
@@ -714,20 +1318,14 @@
    * Last time this connection had any activity
    * (reading or writing).
    */
-  time_t last_activity;
+  uint64_t last_activity;
 
   /**
-   * After how many seconds of inactivity should
-   * this connection time out?  Zero for no timeout.
+   * After how many milliseconds of inactivity should
+   * this connection time out?
+   * Zero for no timeout.
    */
-  unsigned int connection_timeout;
-
-  /**
-   * Did we ever call the "default_handler" on this connection?
-   * (this flag will determine if we call the 'notify_completed'
-   * handler when the connection closes down).
-   */
-  int client_aware;
+  uint64_t connection_timeout_ms;
 
   /**
    * Socket for this connection.  Set to #MHD_INVALID_SOCKET if
@@ -737,24 +1335,76 @@
   MHD_socket socket_fd;
 
   /**
+   * true if @e socket_fd is not TCP/IP (a UNIX domain socket, a pipe),
+   * false (TCP/IP) otherwise.
+   */
+  enum MHD_tristate is_nonip;
+
+  /**
+   * true if #socket_fd is non-blocking, false otherwise.
+   */
+  bool sk_nonblck;
+
+  /**
+   * true if connection socket has set SIGPIPE suppression
+   */
+  bool sk_spipe_suppress;
+
+  /**
+   * Tracks TCP_CORK / TCP_NOPUSH of the connection socket.
+   */
+  enum MHD_tristate sk_corked;
+
+  /**
+   * Tracks TCP_NODELAY state of the connection socket.
+   */
+  enum MHD_tristate sk_nodelay;
+
+  /**
    * Has this socket been closed for reading (i.e.  other side closed
    * the connection)?  If so, we must completely close the connection
    * once we are done sending our response (and stop trying to read
    * from this socket).
    */
-  int read_closed;
+  bool read_closed;
 
   /**
-   * Set to #MHD_YES if the thread has been joined.
+   * Some error happens during processing the connection therefore this
+   * connection must be closed.
+   * The error may come from the client side (like wrong request format),
+   * from the application side (like data callback returned error), or from
+   * the OS side (like out-of-memory).
    */
-  int thread_joined;
+  bool stop_with_error;
 
   /**
-   * Are we currently inside the "idle" handler (to avoid recursively invoking it).
+   * Response queued early, before the request is fully processed,
+   * the client upload is rejected.
+   * The connection cannot be reused for additional requests as the current
+   * request is incompletely read and it is unclear where is the initial
+   * byte of the next request.
    */
-  int in_idle;
+  bool discard_request;
 
-#if EPOLL_SUPPORT
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  /**
+   * Set to `true` if the thread has been joined.
+   */
+  bool thread_joined;
+#endif
+
+  /**
+   * Are we currently inside the "idle" handler (to avoid recursively
+   * invoking it).
+   */
+  bool in_idle;
+
+  /**
+   * Connection is in the cleanup DL-linked list.
+   */
+  bool in_cleanup;
+
+#ifdef EPOLL_SUPPORT
   /**
    * What is the state of this socket in relation to epoll?
    */
@@ -772,102 +1422,252 @@
   enum MHD_ConnectionEventLoopInfo event_loop_info;
 
   /**
-   * HTTP response code.  Only valid if response object
-   * is already set.
-   */
-  unsigned int responseCode;
-
-  /**
-   * Set to MHD_YES if the response's content reader
-   * callback failed to provide data the last time
-   * we tried to read from it.  In that case, the
-   * write socket should be marked as unready until
-   * the CRC call succeeds.
-   */
-  int response_unready;
-
-  /**
-   * Are we receiving with chunked encoding?  This will be set to
-   * MHD_YES after we parse the headers and are processing the body
-   * with chunks.  After we are done with the body and we are
-   * processing the footers; once the footers are also done, this will
-   * be set to MHD_NO again (before the final call to the handler).
-   */
-  int have_chunked_upload;
-
-  /**
-   * If we are receiving with chunked encoding, where are we right
-   * now?  Set to 0 if we are waiting to receive the chunk size;
-   * otherwise, this is the size of the current chunk.  A value of
-   * zero is also used when we're at the end of the chunks.
-   */
-  size_t current_chunk_size;
-
-  /**
-   * If we are receiving with chunked encoding, where are we currently
-   * with respect to the current chunk (at what offset / position)?
-   */
-  size_t current_chunk_offset;
-
-  /**
-   * Handler used for processing read connection operations
-   */
-  int (*read_handler) (struct MHD_Connection *connection);
-
-  /**
-   * Handler used for processing write connection operations
-   */
-  int (*write_handler) (struct MHD_Connection *connection);
-
-  /**
-   * Handler used for processing idle connection operations
-   */
-  int (*idle_handler) (struct MHD_Connection *connection);
-
-  /**
    * Function used for reading HTTP request stream.
    */
   ReceiveCallback recv_cls;
 
+#ifdef UPGRADE_SUPPORT
   /**
-   * Function used for writing HTTP response stream.
+   * If this connection was upgraded, this points to
+   * the upgrade response details such that the
+   * #thread_main_connection_upgrade()-logic can perform the
+   * bi-directional forwarding.
    */
-  TransmitCallback send_cls;
+  struct MHD_UpgradeResponseHandle *urh;
+#endif /* UPGRADE_SUPPORT */
 
-#if HTTPS_SUPPORT
+#ifdef HTTPS_SUPPORT
+
   /**
    * State required for HTTPS/SSL/TLS support.
    */
-  SSL* tls_session;
+  gnutls_session_t tls_session;
 
   /**
-   * Memory location to return for protocol session info.
+   * State of connection's TLS layer
    */
-  const char* protocol;
-
-  /**
-   * Memory location to return for protocol session info.
-   */
-  const char* cipher;
+  enum MHD_TLS_CONN_STATE tls_state;
 
   /**
    * Could it be that we are ready to read due to TLS buffers
    * even though the socket is not?
    */
-  int tls_read_ready;
-#endif
+  bool tls_read_ready;
+#endif /* HTTPS_SUPPORT */
 
   /**
    * Is the connection suspended?
    */
-  int suspended;
+  bool suspended;
 
   /**
    * Is the connection wanting to resume?
    */
-  int resuming;
+  volatile bool resuming;
+
+  /**
+   * Special member to be returned by #MHD_get_connection_info()
+   */
+  union MHD_ConnectionInfo connection_info_dummy;
 };
 
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * Buffer we use for upgrade response handling in the unlikely
+ * case where the memory pool was so small it had no buffer
+ * capacity left.  Note that we don't expect to _ever_ use this
+ * buffer, so it's mostly wasted memory (except that it allows
+ * us to handle a tricky error condition nicely). So no need to
+ * make this one big.  Applications that want to perform well
+ * should just pick an adequate size for the memory pools.
+ */
+#define RESERVE_EBUF_SIZE 8
+
+/**
+ * Context we pass to epoll() for each of the two sockets
+ * of a `struct MHD_UpgradeResponseHandle`.  We need to do
+ * this so we can distinguish the two sockets when epoll()
+ * gives us event notifications.
+ */
+struct UpgradeEpollHandle
+{
+  /**
+   * Reference to the overall response handle this struct is
+   * included within.
+   */
+  struct MHD_UpgradeResponseHandle *urh;
+
+  /**
+   * The socket this event is kind-of about.  Note that this is NOT
+   * necessarily the socket we are polling on, as for when we read
+   * from TLS, we epoll() on the connection's socket
+   * (`urh->connection->socket_fd`), while this then the application's
+   * socket (where the application will read from).  Nevertheless, for
+   * the application to read, we need to first read from TLS, hence
+   * the two are related.
+   *
+   * Similarly, for writing to TLS, this epoll() will be on the
+   * connection's `socket_fd`, and this will merely be the FD which
+   * the application would write to.  Hence this struct must always be
+   * interpreted based on which field in `struct
+   * MHD_UpgradeResponseHandle` it is (`app` or `mhd`).
+   */
+  MHD_socket socket;
+
+  /**
+   * IO-state of the @e socket (or the connection's `socket_fd`).
+   */
+  enum MHD_EpollState celi;
+
+};
+
+
+/**
+ * Handle given to the application to manage special
+ * actions relating to MHD responses that "upgrade"
+ * the HTTP protocol (i.e. to WebSockets).
+ */
+struct MHD_UpgradeResponseHandle
+{
+  /**
+   * The connection for which this is an upgrade handle.  Note that
+   * because a response may be shared over many connections, this may
+   * not be the only upgrade handle for the response of this connection.
+   */
+  struct MHD_Connection *connection;
+
+#ifdef HTTPS_SUPPORT
+  /**
+   * Kept in a DLL per daemon.
+   */
+  struct MHD_UpgradeResponseHandle *next;
+
+  /**
+   * Kept in a DLL per daemon.
+   */
+  struct MHD_UpgradeResponseHandle *prev;
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * Next pointer for the EDLL listing urhs that are epoll-ready.
+   */
+  struct MHD_UpgradeResponseHandle *nextE;
+
+  /**
+   * Previous pointer for the EDLL listing urhs that are epoll-ready.
+   */
+  struct MHD_UpgradeResponseHandle *prevE;
+
+  /**
+   * Specifies whether urh already in EDLL list of ready connections.
+   */
+  bool in_eready_list;
+#endif
+
+  /**
+   * The buffer for receiving data from TLS to
+   * be passed to the application.  Contains @e in_buffer_size
+   * bytes (unless @e in_buffer_size is zero). Do not free!
+   */
+  char *in_buffer;
+
+  /**
+   * The buffer for receiving data from the application to
+   * be passed to TLS.  Contains @e out_buffer_size
+   * bytes (unless @e out_buffer_size is zero). Do not free!
+   */
+  char *out_buffer;
+
+  /**
+   * Size of the @e in_buffer.
+   * Set to 0 if the TLS connection went down for reading or socketpair
+   * went down for writing.
+   */
+  size_t in_buffer_size;
+
+  /**
+   * Size of the @e out_buffer.
+   * Set to 0 if the TLS connection went down for writing or socketpair
+   * went down for reading.
+   */
+  size_t out_buffer_size;
+
+  /**
+   * Number of bytes actually in use in the @e in_buffer.  Can be larger
+   * than @e in_buffer_size if and only if @a in_buffer_size is zero and
+   * we still have bytes that can be forwarded.
+   * Reset to zero if all data was forwarded to socketpair or
+   * if socketpair went down for writing.
+   */
+  size_t in_buffer_used;
+
+  /**
+   * Number of bytes actually in use in the @e out_buffer. Can be larger
+   * than @e out_buffer_size if and only if @a out_buffer_size is zero and
+   * we still have bytes that can be forwarded.
+   * Reset to zero if all data was forwarded to TLS connection or
+   * if TLS connection went down for writing.
+   */
+  size_t out_buffer_used;
+
+  /**
+   * The socket we gave to the application (r/w).
+   */
+  struct UpgradeEpollHandle app;
+
+  /**
+   * If @a app_sock was a socketpair, our end of it, otherwise
+   * #MHD_INVALID_SOCKET; (r/w).
+   */
+  struct UpgradeEpollHandle mhd;
+
+  /**
+   * Emergency IO buffer we use in case the memory pool has literally
+   * nothing left.
+   */
+  char e_buf[RESERVE_EBUF_SIZE];
+
+#endif /* HTTPS_SUPPORT */
+
+  /**
+   * Set to true after the application finished with the socket
+   * by #MHD_UPGRADE_ACTION_CLOSE.
+   *
+   * When BOTH @e was_closed (changed by command from application)
+   * AND @e clean_ready (changed internally by MHD) are set to
+   * #MHD_YES, function #MHD_resume_connection() will move this
+   * connection to cleanup list.
+   * @remark This flag could be changed from any thread.
+   */
+  volatile bool was_closed;
+
+  /**
+   * Set to true if connection is ready for cleanup.
+   *
+   * In TLS mode functions #MHD_connection_finish_forward_() must
+   * be called before setting this flag to true.
+   *
+   * In thread-per-connection mode, true in this flag means
+   * that connection's thread exited or about to exit and will
+   * not use MHD_Connection::urh data anymore.
+   *
+   * In any mode true in this flag also means that
+   * MHD_Connection::urh data will not be used for socketpair
+   * forwarding and forwarding itself is finished.
+   *
+   * When BOTH @e was_closed (changed by command from application)
+   * AND @e clean_ready (changed internally by MHD) are set to
+   * true, function #MHD_resume_connection() will move this
+   * connection to cleanup list.
+   * @remark This flag could be changed from thread that process
+   * connection's recv(), send() and response.
+   */
+  volatile bool clean_ready;
+};
+#endif /* UPGRADE_SUPPORT */
+
+
 /**
  * Signature of function called to log URI accesses.
  *
@@ -877,8 +1677,8 @@
  * @return new closure
  */
 typedef void *
-(*LogCallback)(void * cls,
-               const char * uri,
+(*LogCallback)(void *cls,
+               const char *uri,
                struct MHD_Connection *con);
 
 /**
@@ -917,6 +1717,24 @@
   void *default_handler_cls;
 
   /**
+   * Daemon's flags (bitfield).
+   *
+   * @remark Keep this member after pointer value to keep it
+   * properly aligned as it will be used as member of union MHD_DaemonInfo.
+   */
+  enum MHD_FLAG options;
+
+  /**
+   * Head of doubly-linked list of new, externally added connections.
+   */
+  struct MHD_Connection *new_connections_head;
+
+  /**
+   * Tail of doubly-linked list of new, externally added connections.
+   */
+  struct MHD_Connection *new_connections_tail;
+
+  /**
    * Head of doubly-linked list of our current, active connections.
    */
   struct MHD_Connection *connections_head;
@@ -946,7 +1764,12 @@
    */
   struct MHD_Connection *cleanup_tail;
 
-#if EPOLL_SUPPORT
+  /**
+   * _MHD_YES if the @e listen_fd socket is a UNIX domain socket.
+   */
+  enum MHD_tristate listen_is_unix;
+
+#ifdef EPOLL_SUPPORT
   /**
    * Head of EDLL of connections ready for processing (in epoll mode).
    */
@@ -956,7 +1779,47 @@
    * Tail of EDLL of connections ready for processing (in epoll mode)
    */
   struct MHD_Connection *eready_tail;
-#endif
+
+  /**
+   * File descriptor associated with our epoll loop.
+   *
+   * @remark Keep this member after pointer value to keep it
+   * properly aligned as it will be used as member of union MHD_DaemonInfo.
+   */
+  int epoll_fd;
+
+  /**
+   * true if the @e listen_fd socket is in the 'epoll' set,
+   * false if not.
+   */
+  bool listen_socket_in_epoll;
+
+#ifdef UPGRADE_SUPPORT
+#ifdef HTTPS_SUPPORT
+  /**
+   * File descriptor associated with the #run_epoll_for_upgrade() loop.
+   * Only available if #MHD_USE_HTTPS_EPOLL_UPGRADE is set.
+   */
+  int epoll_upgrade_fd;
+
+  /**
+   * true if @e epoll_upgrade_fd is in the 'epoll' set,
+   * false if not.
+   */
+  bool upgrade_fd_in_epoll;
+#endif /* HTTPS_SUPPORT */
+
+  /**
+   * Head of EDLL of upgraded connections ready for processing (in epoll mode).
+   */
+  struct MHD_UpgradeResponseHandle *eready_urh_head;
+
+  /**
+   * Tail of EDLL of upgraded connections ready for processing (in epoll mode)
+   */
+  struct MHD_UpgradeResponseHandle *eready_urh_tail;
+#endif /* UPGRADE_SUPPORT */
+#endif /* EPOLL_SUPPORT */
 
   /**
    * Head of the XDLL of ALL connections with a default ('normal')
@@ -967,14 +1830,17 @@
    * moved back to the tail of the list.
    *
    * All connections by default start in this list; if a custom
-   * timeout that does not match 'connection_timeout' is set, they
-   * are moved to the 'manual_timeout_head'-XDLL.
+   * timeout that does not match @e connection_timeout_ms is set, they
+   * are moved to the @e manual_timeout_head-XDLL.
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode as each thread
+   * needs only one connection-specific timeout.
    */
   struct MHD_Connection *normal_timeout_head;
 
   /**
    * Tail of the XDLL of ALL connections with a default timeout,
    * sorted by timeout (earliest timeout at the tail).
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
    */
   struct MHD_Connection *normal_timeout_tail;
 
@@ -982,12 +1848,14 @@
    * Head of the XDLL of ALL connections with a non-default/custom
    * timeout, unsorted.  MHD will do a O(n) scan over this list to
    * determine the current timeout.
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
    */
   struct MHD_Connection *manual_timeout_head;
 
   /**
    * Tail of the XDLL of ALL connections with a non-default/custom
    * timeout, unsorted.
+   * Not used in MHD_USE_THREAD_PER_CONNECTION mode.
    */
   struct MHD_Connection *manual_timeout_tail;
 
@@ -1009,7 +1877,7 @@
   MHD_RequestCompletedCallback notify_completed;
 
   /**
-   * Closure argument to notify_completed.
+   * Closure argument to @e notify_completed.
    */
   void *notify_completed_cls;
 
@@ -1020,7 +1888,7 @@
   MHD_NotifyConnectionCallback notify_connection;
 
   /**
-   * Closure argument to notify_connection.
+   * Closure argument to @e notify_connection.
    */
   void *notify_connection_cls;
 
@@ -1048,15 +1916,23 @@
    */
   void *unescape_callback_cls;
 
-#if HAVE_MESSAGES
+  /**
+   * Listen port.
+   *
+   * @remark Keep this member after pointer value to keep it
+   * properly aligned as it will be used as member of union MHD_DaemonInfo.
+   */
+  uint16_t port;
+
+#ifdef HAVE_MESSAGES
   /**
    * Function for logging error messages (if we
    * support error reporting).
    */
-  void (*custom_error_log) (void *cls, const char *fmt, va_list va);
+  MHD_LogCallback custom_error_log;
 
   /**
-   * Closure argument to custom_error_log.
+   * Closure argument to @e custom_error_log.
    */
   void *custom_error_log_cls;
 #endif
@@ -1067,9 +1943,24 @@
   struct MHD_Daemon *master;
 
   /**
+   * Listen socket.
+   *
+   * @remark Keep this member after pointer value to keep it
+   * properly aligned as it will be used as member of union MHD_DaemonInfo.
+   */
+  MHD_socket listen_fd;
+
+  /**
+   * Listen socket is non-blocking.
+   */
+  bool listen_nonblk;
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  /**
    * Worker daemons (one per thread)
    */
   struct MHD_Daemon *worker_pool;
+#endif
 
   /**
    * Table storing number of connections per IP
@@ -1077,6 +1968,14 @@
   void *per_ip_connection_count;
 
   /**
+   * Number of active parallel connections.
+   *
+   * @remark Keep this member after pointer value to keep it
+   * properly aligned as it will be used as member of union MHD_DaemonInfo.
+   */
+  unsigned int connections;
+
+  /**
    * Size of the per-connection memory pools.
    */
   size_t pool_size;
@@ -1086,6 +1985,7 @@
    */
   size_t pool_increment;
 
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   /**
    * Size of threads created by MHD.
    */
@@ -1099,7 +1999,7 @@
   /**
    * The select thread handle (if we have internal select)
    */
-  MHD_thread_handle_ pid;
+  MHD_thread_handle_ID_ pid;
 
   /**
    * Mutex for per-IP connection counts.
@@ -1107,60 +2007,83 @@
   MHD_mutex_ per_ip_connection_mutex;
 
   /**
-   * Mutex for (modifying) access to the "cleanup" connection DLL.
+   * Mutex for (modifying) access to the "cleanup", "normal_timeout" and
+   * "manual_timeout" DLLs.
    */
   MHD_mutex_ cleanup_connection_mutex;
 
   /**
-   * Listen socket.
+   * Mutex for any access to the "new connections" DL-list.
    */
-  MHD_socket socket_fd;
+  MHD_mutex_ new_connections_mutex;
+#endif
+
+  /**
+   * Our #MHD_OPTION_SERVER_INSANITY level, bits indicating
+   * which sanity checks are off.
+   */
+  enum MHD_DisableSanityCheck insanity_level;
 
   /**
    * Whether to allow/disallow/ignore reuse of listening address.
    * The semantics is the following:
-   * 0: ignore (user did not ask for neither allow/disallow, use SO_REUSEADDR)
+   * 0: ignore (user did not ask for neither allow/disallow, use SO_REUSEADDR
+   *    except W32)
    * >0: allow (use SO_REUSEPORT on most platforms, SO_REUSEADDR on Windows)
-   * <0: disallow (mostly no action, SO_EXCLUSIVEADDRUSE on Windows)
+   * <0: disallow (mostly no action, SO_EXCLUSIVEADDRUSE on Windows or SO_EXCLBIND
+   *     on Solaris)
    */
   int listening_address_reuse;
 
-#if EPOLL_SUPPORT
-  /**
-   * File descriptor associated with our epoll loop.
-   */
-  int epoll_fd;
 
   /**
-   * MHD_YES if the listen socket is in the 'epoll' set,
-   * MHD_NO if not.
+   * Inter-thread communication channel (also used to unblock
+   * select() in non-threaded code).
    */
-  int listen_socket_in_epoll;
-#endif
-
-  /**
-   * Pipe we use to signal shutdown, unless
-   * 'HAVE_LISTEN_SHUTDOWN' is defined AND we have a listen
-   * socket (which we can then 'shutdown' to stop listening).
-   * MHD can be build with usage of socketpair instead of
-   * pipe (forced on W32).
-   */
-  MHD_pipe wpipe[2];
+  struct MHD_itc_ itc;
 
   /**
    * Are we shutting down?
    */
-  int shutdown;
+  volatile bool shutdown;
+
+  /**
+   * Has this daemon been quiesced via #MHD_quiesce_daemon()?
+   * If so, we should no longer use the @e listen_fd (including
+   * removing it from the @e epoll_fd when possible).
+   */
+  volatile bool was_quiesced;
+
+  /**
+   * Did we hit some system or process-wide resource limit while
+   * trying to accept() the last time? If so, we don't accept new
+   * connections until we close an existing one.  This effectively
+   * temporarily lowers the "connection_limit" to the current
+   * number of connections.
+   */
+  bool at_limit;
 
   /*
    * Do we need to process resuming connections?
    */
-  int resuming;
+  volatile bool resuming;
 
   /**
-   * Number of active parallel connections.
+   * Indicate that new connections in @e new_connections_head list
+   * need to be processed.
    */
-  unsigned int connections;
+  volatile bool have_new;
+
+  /**
+   * 'True' if some data is already waiting to be processed.
+   * If set to 'true' - zero timeout for select()/poll*()
+   * is used.
+   * Should be reset each time before processing connections
+   * and raised by any connection which require additional
+   * immediately processing (application does not provide
+   * data for response, data waiting in TLS buffers etc.)
+   */
+  bool data_already_pending;
 
   /**
    * Limit on the number of parallel connections.
@@ -1168,10 +2091,11 @@
   unsigned int connection_limit;
 
   /**
-   * After how many seconds of inactivity should
-   * connections time out?  Zero for no timeout.
+   * After how many milliseconds of inactivity should
+   * this connection time out?
+   * Zero for no timeout.
    */
-  unsigned int connection_timeout;
+  uint64_t connection_timeout_ms;
 
   /**
    * Maximum number of connections per IP, or 0 for
@@ -1180,24 +2104,92 @@
   unsigned int per_ip_connection_limit;
 
   /**
-   * Daemon's flags (bitfield).
+   * The strictness level for parsing of incoming data.
+   * @see #MHD_OPTION_CLIENT_DISCIPLINE_LVL
    */
-  enum MHD_FLAG options;
+  int client_discipline;
 
   /**
-   * Listen port.
+   * True if SIGPIPE is blocked
    */
-  uint16_t port;
+  bool sigpipe_blocked;
 
-#if HTTPS_SUPPORT
-  SSL_CTX* tls_context;
+#ifdef HTTPS_SUPPORT
+#ifdef UPGRADE_SUPPORT
   /**
-   * Pointer to our SSL/TLS key (in PEM) in memory.
+   * Head of DLL of upgrade response handles we are processing.
+   * Used for upgraded TLS connections when thread-per-connection
+   * is not used.
+   */
+  struct MHD_UpgradeResponseHandle *urh_head;
+
+  /**
+   * Tail of DLL of upgrade response handles we are processing.
+   * Used for upgraded TLS connections when thread-per-connection
+   * is not used.
+   */
+  struct MHD_UpgradeResponseHandle *urh_tail;
+#endif /* UPGRADE_SUPPORT */
+
+  /**
+   * Desired cipher algorithms.
+   */
+  gnutls_priority_t priority_cache;
+
+  /**
+   * What kind of credentials are we offering
+   * for SSL/TLS?
+   */
+  gnutls_credentials_type_t cred_type;
+
+  /**
+   * Server x509 credentials
+   */
+  gnutls_certificate_credentials_t x509_cred;
+
+  /**
+   * Diffie-Hellman parameters
+   */
+  gnutls_dh_params_t dh_params;
+
+  /**
+   * Server PSK credentials
+   */
+  gnutls_psk_server_credentials_t psk_cred;
+
+#if GNUTLS_VERSION_MAJOR >= 3
+  /**
+   * Function that can be used to obtain the certificate.  Needed
+   * for SNI support.  See #MHD_OPTION_HTTPS_CERT_CALLBACK.
+   */
+  gnutls_certificate_retrieve_function2 *cert_callback;
+
+  /**
+   * Function that can be used to obtain the shared key.
+   */
+  MHD_PskServerCredentialsCallback cred_callback;
+
+  /**
+   * Closure for @e cred_callback.
+   */
+  void *cred_callback_cls;
+#endif
+
+#if GNUTLS_VERSION_NUMBER >= 0x030603
+  /**
+   * Function that can be used to obtain the certificate.  Needed
+   * for OCSP stapling support.  See #MHD_OPTION_HTTPS_CERT_CALLBACK2.
+   */
+  gnutls_certificate_retrieve_function3 *cert_callback2;
+#endif
+
+  /**
+   * Pointer to our SSL/TLS key (in ASCII) in memory.
    */
   const char *https_mem_key;
 
   /**
-   * Pointer to our SSL/TLS certificate (in PEM) in memory.
+   * Pointer to our SSL/TLS certificate (in ASCII) in memory.
    */
   const char *https_mem_cert;
 
@@ -1207,29 +2199,26 @@
   const char *https_key_password;
 
   /**
-   * Pointer to our SSL/TLS certificate authority (in PEM) in memory.
+   * Pointer to our SSL/TLS certificate authority (in ASCII) in memory.
    */
   const char *https_mem_trust;
 
   /**
-   * Our Diffie-Hellman parameters (in PEM) in memory.
+   * Our Diffie-Hellman parameters in memory.
    */
-  const char *https_mem_dhparams;
+  gnutls_dh_params_t https_mem_dhparams;
 
   /**
-   * Pointer to SSL/TLS cipher string in memory.
+   * true if we have initialized @e https_mem_dhparams.
    */
-  const char *https_mem_cipher;
+  bool have_dhparams;
 
   /**
-   * For how many connections do we have 'tls_read_ready' set to MHD_YES?
-   * Used to avoid O(n) traversal over all connections when determining
-   * event-loop timeout (as it needs to be zero if there is any connection
-   * which might have ready data within TLS).
+   * true if ALPN is disabled.
    */
-  unsigned int num_tls_read_ready;
+  bool disable_alpn;
 
-#endif
+  #endif /* HTTPS_SUPPORT */
 
 #ifdef DAUTH_SUPPORT
 
@@ -1239,14 +2228,21 @@
   const char *digest_auth_random;
 
   /**
+   * The malloc'ed copy of the @a digest_auth_random.
+   */
+  void *digest_auth_random_copy;
+
+  /**
    * An array that contains the map nonce-nc.
    */
   struct MHD_NonceNc *nnc;
 
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
   /**
-   * A rw-lock for synchronizing access to `nnc'.
+   * A rw-lock for synchronizing access to @e nnc.
    */
   MHD_mutex_ nnc_lock;
+#endif
 
   /**
    * Size of `digest_auth_random.
@@ -1258,6 +2254,10 @@
    */
   unsigned int nonce_nc_size;
 
+  /**
+   * Nonce bind type.
+   */
+  unsigned int dauth_bind_type;
 #endif
 
 #ifdef TCP_FASTOPEN
@@ -1266,15 +2266,95 @@
    */
   unsigned int fastopen_queue_size;
 #endif
+
+  /**
+   * The size of queue for listen socket.
+   */
+  unsigned int listen_backlog_size;
+
+  /**
+   * The number of user options used.
+   *
+   * Contains number of only meaningful options, i.e. #MHD_OPTION_END
+   * and #MHD_OPTION_ARRAY are not counted, while options inside
+   * #MHD_OPTION_ARRAY are counted.
+   */
+  size_t num_opts;
+
+  /* TODO: replace with a single member */
+  /**
+   * The value to be returned by #MHD_get_daemon_info()
+   */
+  union MHD_DaemonInfo daemon_info_dummy_listen_fd;
+
+#ifdef EPOLL_SUPPORT
+  /**
+   * The value to be returned by #MHD_get_daemon_info()
+   */
+  union MHD_DaemonInfo daemon_info_dummy_epoll_fd;
+#endif /* EPOLL_SUPPORT */
+
+  /**
+   * The value to be returned by #MHD_get_daemon_info()
+   */
+  union MHD_DaemonInfo daemon_info_dummy_num_connections;
+
+  /**
+   * The value to be returned by #MHD_get_daemon_info()
+   */
+  union MHD_DaemonInfo daemon_info_dummy_flags;
+
+  /**
+   * The value to be returned by #MHD_get_daemon_info()
+   */
+  union MHD_DaemonInfo daemon_info_dummy_port;
 };
 
 
-#if EXTRA_CHECKS
-#define EXTRA_CHECK(a) do { if (!(a)) abort(); } while (0)
-#else
-#define EXTRA_CHECK(a)
-#endif
+#ifdef DAUTH_SUPPORT
 
+/**
+ * Parameter of request's Digest Authorization header
+ */
+struct MHD_RqDAuthParam
+{
+  /**
+   * The string with length, NOT zero-terminated
+   */
+  struct _MHD_str_w_len value;
+  /**
+   * True if string must be "unquoted" before processing.
+   * This member is false if the string is used in DQUOTE marks, but no
+   * backslash-escape is used in the string.
+   */
+  bool quoted;
+};
+
+/**
+ * Request client's Digest Authorization header parameters
+ */
+struct MHD_RqDAuth
+{
+  struct MHD_RqDAuthParam nonce;
+  struct MHD_RqDAuthParam opaque;
+  struct MHD_RqDAuthParam response;
+  struct MHD_RqDAuthParam username;
+  struct MHD_RqDAuthParam username_ext;
+  struct MHD_RqDAuthParam realm;
+  struct MHD_RqDAuthParam uri;
+  /* The raw QOP value, used in the 'response' calculation */
+  struct MHD_RqDAuthParam qop_raw;
+  struct MHD_RqDAuthParam cnonce;
+  struct MHD_RqDAuthParam nc;
+
+  /* Decoded values are below */
+  bool userhash; /* True if 'userhash' parameter has value 'true'. */
+  enum MHD_DigestAuthAlgo3 algo3;
+  enum MHD_DigestAuthQOP qop;
+};
+
+
+#endif /* DAUTH_SUPPORT */
 
 /**
  * Insert an element at the head of a DLL. Assumes that head, tail and
@@ -1285,15 +2365,16 @@
  * @param element element to insert
  */
 #define DLL_insert(head,tail,element) do { \
-  EXTRA_CHECK (NULL == (element)->next); \
-  EXTRA_CHECK (NULL == (element)->prev); \
-  (element)->next = (head); \
-  (element)->prev = NULL; \
-  if ((tail) == NULL) \
-    (tail) = element; \
-  else \
-    (head)->prev = element; \
-  (head) = (element); } while (0)
+    mhd_assert (NULL == (element)->next); \
+    mhd_assert (NULL == (element)->prev); \
+    (element)->next = (head);       \
+    (element)->prev = NULL;         \
+    if ((tail) == NULL) {           \
+      (tail) = element;             \
+    } else {                        \
+      (head)->prev = element;       \
+    }                               \
+    (head) = (element); } while (0)
 
 
 /**
@@ -1306,19 +2387,20 @@
  * @param element element to remove
  */
 #define DLL_remove(head,tail,element) do { \
-  EXTRA_CHECK ( (NULL != (element)->next) || ((element) == (tail)));  \
-  EXTRA_CHECK ( (NULL != (element)->prev) || ((element) == (head)));  \
-  if ((element)->prev == NULL) \
-    (head) = (element)->next;  \
-  else \
-    (element)->prev->next = (element)->next; \
-  if ((element)->next == NULL) \
-    (tail) = (element)->prev;  \
-  else \
-    (element)->next->prev = (element)->prev; \
-  (element)->next = NULL; \
-  (element)->prev = NULL; } while (0)
-
+    mhd_assert ( (NULL != (element)->next) || ((element) == (tail)));  \
+    mhd_assert ( (NULL != (element)->prev) || ((element) == (head)));  \
+    if ((element)->prev == NULL) {                                     \
+      (head) = (element)->next;                \
+    } else {                                   \
+      (element)->prev->next = (element)->next; \
+    }                                          \
+    if ((element)->next == NULL) {             \
+      (tail) = (element)->prev;                \
+    } else {                                   \
+      (element)->next->prev = (element)->prev; \
+    }                                          \
+    (element)->next = NULL;                    \
+    (element)->prev = NULL; } while (0)
 
 
 /**
@@ -1330,15 +2412,16 @@
  * @param element element to insert
  */
 #define XDLL_insert(head,tail,element) do { \
-  EXTRA_CHECK (NULL == (element)->nextX); \
-  EXTRA_CHECK (NULL == (element)->prevX); \
-  (element)->nextX = (head); \
-  (element)->prevX = NULL; \
-  if (NULL == (tail)) \
-    (tail) = element; \
-  else \
-    (head)->prevX = element; \
-  (head) = (element); } while (0)
+    mhd_assert (NULL == (element)->nextX); \
+    mhd_assert (NULL == (element)->prevX); \
+    (element)->nextX = (head);     \
+    (element)->prevX = NULL;       \
+    if (NULL == (tail)) {          \
+      (tail) = element;            \
+    } else {                       \
+      (head)->prevX = element;     \
+    }                              \
+    (head) = (element); } while (0)
 
 
 /**
@@ -1351,18 +2434,20 @@
  * @param element element to remove
  */
 #define XDLL_remove(head,tail,element) do { \
-  EXTRA_CHECK ( (NULL != (element)->nextX) || ((element) == (tail)));  \
-  EXTRA_CHECK ( (NULL != (element)->prevX) || ((element) == (head)));  \
-  if (NULL == (element)->prevX) \
-    (head) = (element)->nextX;  \
-  else \
-    (element)->prevX->nextX = (element)->nextX; \
-  if (NULL == (element)->nextX) \
-    (tail) = (element)->prevX;  \
-  else \
-    (element)->nextX->prevX = (element)->prevX; \
-  (element)->nextX = NULL; \
-  (element)->prevX = NULL; } while (0)
+    mhd_assert ( (NULL != (element)->nextX) || ((element) == (tail)));  \
+    mhd_assert ( (NULL != (element)->prevX) || ((element) == (head)));  \
+    if (NULL == (element)->prevX) {                                     \
+      (head) = (element)->nextX;                  \
+    } else {                                      \
+      (element)->prevX->nextX = (element)->nextX; \
+    }                                             \
+    if (NULL == (element)->nextX) {               \
+      (tail) = (element)->prevX;                  \
+    } else {                                      \
+      (element)->nextX->prevX = (element)->prevX; \
+    }                                             \
+    (element)->nextX = NULL;                      \
+    (element)->prevX = NULL; } while (0)
 
 
 /**
@@ -1374,13 +2459,14 @@
  * @param element element to insert
  */
 #define EDLL_insert(head,tail,element) do { \
-  (element)->nextE = (head); \
-  (element)->prevE = NULL; \
-  if ((tail) == NULL) \
-    (tail) = element; \
-  else \
-    (head)->prevE = element; \
-  (head) = (element); } while (0)
+    (element)->nextE = (head); \
+    (element)->prevE = NULL;   \
+    if ((tail) == NULL) {      \
+      (tail) = element;        \
+    } else {                   \
+      (head)->prevE = element; \
+    }                          \
+    (head) = (element); } while (0)
 
 
 /**
@@ -1392,32 +2478,23 @@
  * @param tail pointer to the tail of the EDLL
  * @param element element to remove
  */
-#define EDLL_remove(head,tail,element) do { \
-  if ((element)->prevE == NULL) \
-    (head) = (element)->nextE;  \
-  else \
-    (element)->prevE->nextE = (element)->nextE; \
-  if ((element)->nextE == NULL) \
-    (tail) = (element)->prevE;  \
-  else \
-    (element)->nextE->prevE = (element)->prevE; \
-  (element)->nextE = NULL; \
-  (element)->prevE = NULL; } while (0)
+#define EDLL_remove(head,tail,element) do {       \
+    if ((element)->prevE == NULL) {               \
+      (head) = (element)->nextE;                  \
+    } else {                                      \
+      (element)->prevE->nextE = (element)->nextE; \
+    }                                             \
+    if ((element)->nextE == NULL) {               \
+      (tail) = (element)->prevE;                  \
+    } else {                                      \
+      (element)->nextE->prevE = (element)->prevE; \
+    }                                             \
+    (element)->nextE = NULL;                      \
+    (element)->prevE = NULL; } while (0)
 
 
 /**
- * Equivalent to `time(NULL)` but tries to use some sort of monotonic
- * clock that isn't affected by someone setting the system real time
- * clock.
- *
- * @return 'current' time
- */
-time_t
-MHD_monotonic_time(void);
-
-
-/**
- * Convert all occurences of '+' to ' '.
+ * Convert all occurrences of '+' to ' '.
  *
  * @param arg string that is modified (in place), must be 0-terminated
  */
@@ -1425,4 +2502,135 @@
 MHD_unescape_plus (char *arg);
 
 
+/**
+ * Callback invoked when iterating over @a key / @a value
+ * argument pairs during parsing.
+ *
+ * @param cls context of the iteration
+ * @param key 0-terminated key string, never NULL
+ * @param key_size number of bytes in key
+ * @param value 0-terminated binary data, may include binary zeros, may be NULL
+ * @param value_size number of bytes in value
+ * @param kind origin of the key-value pair
+ * @return #MHD_YES on success (continue to iterate)
+ *         #MHD_NO to signal failure (and abort iteration)
+ */
+typedef enum MHD_Result
+(*MHD_ArgumentIterator_)(void *cls,
+                         const char *key,
+                         size_t key_size,
+                         const char *value,
+                         size_t value_size,
+                         enum MHD_ValueKind kind);
+
+
+/**
+ * Parse and unescape the arguments given by the client
+ * as part of the HTTP request URI.
+ *
+ * @param kind header kind to pass to @a cb
+ * @param connection connection to add headers to
+ * @param[in,out] args argument URI string (after "?" in URI),
+ *        clobbered in the process!
+ * @param cb function to call on each key-value pair found
+ * @param cls the iterator context
+ * @return #MHD_NO on failure (@a cb returned #MHD_NO),
+ *         #MHD_YES for success (parsing succeeded, @a cb always
+ *                               returned #MHD_YES)
+ */
+enum MHD_Result
+MHD_parse_arguments_ (struct MHD_Connection *connection,
+                      enum MHD_ValueKind kind,
+                      char *args,
+                      MHD_ArgumentIterator_ cb,
+                      void *cls);
+
+
+/**
+ * Check whether response header contains particular token.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ *
+ * @param response  the response to query
+ * @param key       header name
+ * @param key_len   the length of @a key, not including optional
+ *                  terminating null-character.
+ * @param token     the token to find
+ * @param token_len the length of @a token, not including optional
+ *                  terminating null-character.
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+bool
+MHD_check_response_header_token_ci (const struct MHD_Response *response,
+                                    const char *key,
+                                    size_t key_len,
+                                    const char *token,
+                                    size_t token_len);
+
+/**
+ * Check whether response header contains particular static @a tkn.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ * @param r   the response to query
+ * @param k   header name
+ * @param tkn the static string of token to find
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+#define MHD_check_response_header_s_token_ci(r,k,tkn) \
+  MHD_check_response_header_token_ci ((r),(k),MHD_STATICSTR_LEN_ (k), \
+                                      (tkn),MHD_STATICSTR_LEN_ (tkn))
+
+
+/**
+ * Internal version of #MHD_suspend_connection().
+ *
+ * @remark In thread-per-connection mode: can be called from any thread,
+ * in any other mode: to be called only from thread that process
+ * daemon's select()/poll()/etc.
+ *
+ * @param connection the connection to suspend
+ */
+void
+internal_suspend_connection_ (struct MHD_Connection *connection);
+
+
+/**
+ * Trace up to and return master daemon. If the supplied daemon
+ * is a master, then return the daemon itself.
+ *
+ * @param daemon handle to a daemon
+ * @return master daemon handle
+ */
+_MHD_static_inline struct MHD_Daemon *
+MHD_get_master (struct MHD_Daemon *const daemon)
+{
+  struct MHD_Daemon *ret;
+
+  if (NULL != daemon->master)
+    ret = daemon->master;
+  else
+    ret = daemon;
+  mhd_assert (NULL == ret->master);
+
+  return ret;
+}
+
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * Mark upgraded connection as closed by application.
+ *
+ * The @a connection pointer must not be used after call of this function
+ * as it may be freed in other thread immediately.
+ * @param connection the upgraded connection to mark as closed by application
+ */
+void
+MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection);
+#endif /* UPGRADE_SUPPORT */
+
+
 #endif
diff --git a/src/microhttpd/md5.c b/src/microhttpd/md5.c
index e35d5f2..609ed50 100644
--- a/src/microhttpd/md5.c
+++ b/src/microhttpd/md5.c
@@ -1,267 +1,546 @@
 /*
- * This code implements the MD5 message-digest algorithm.
- * The algorithm is due to Ron Rivest.	This code was
- * written by Colin Plumb in 1993, no copyright is claimed.
- * This code is in the public domain; do with it what you wish.
- *
- * Equivalent code is available from RSA Data Security, Inc.
- * This code has been tested against that, and is equivalent,
- * except that you don't need to include two pages of legalese
- * with every copy.
- *
- * To compute the message digest of a chunk of bytes, declare an
- * MD5Context structure, pass it to MD5Init, call MD5Update as
- * needed on buffers full of bytes, and then call MD5Final, which
- * will fill a supplied 16-byte array with the digest.
- */
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
 
-/* Brutally hacked by John Walker back from ANSI C to K&R (no
-   prototypes) to maintain the tradition that Netfone will compile
-   with Sun's original "cc". */
+     GNU libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/md5.c
+ * @brief  Calculation of MD5 digest as defined in RFC 1321
+ * @author Karlson2k (Evgeny Grin)
+ */
 
 #include "md5.h"
 
+#include <string.h>
+#ifdef HAVE_MEMORY_H
+#include <memory.h>
+#endif /* HAVE_MEMORY_H */
+#include "mhd_bithelpers.h"
+#include "mhd_assert.h"
 
-#ifndef HIGHFIRST
-#define byteReverse(buf, len)	/* Nothing */
-#else
-/*
- * Note: this code is harmless on little-endian machines.
+/**
+ * Initialise structure for MD5 calculation.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_MD5_init (struct Md5Ctx *ctx)
+{
+  /* Initial hash values, see RFC 1321, Clause 3.3 (step 3). */
+  /* Note: values specified in RFC by bytes and should be loaded in
+           little-endian mode, therefore hash values here are initialised with
+           original bytes used in little-endian order. */
+  ctx->H[0] = UINT32_C (0x67452301);
+  ctx->H[1] = UINT32_C (0xefcdab89);
+  ctx->H[2] = UINT32_C (0x98badcfe);
+  ctx->H[3] = UINT32_C (0x10325476);
+
+  /* Initialise the number of bytes. */
+  ctx->count = 0;
+}
+
+
+/**
+ * Base of MD5 transformation.
+ * Gets full 64 bytes block of data and updates hash values;
+ * @param H     hash values
+ * @param M     the data buffer with #MD5_BLOCK_SIZE bytes block
  */
 static void
-byteReverse(unsigned char *buf,
-	    unsigned longs)
+md5_transform (uint32_t H[MD5_HASH_SIZE_WORDS],
+               const void *M)
 {
-    uint32_t t;
-    do {
-	t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
-	    ((unsigned) buf[1] << 8 | buf[0]);
-	*(uint32_t *) buf = t;
-	buf += 4;
-    } while (--longs);
-}
-#endif
+  /* Working variables,
+     See RFC 1321, Clause 3.4 (step 4). */
+  uint32_t A = H[0];
+  uint32_t B = H[1];
+  uint32_t C = H[2];
+  uint32_t D = H[3];
 
+  /* The data buffer. See RFC 1321, Clause 3.4 (step 4). */
+  uint32_t X[16];
 
-/* The four core functions - F1 is optimized somewhat */
+#ifndef _MHD_GET_32BIT_LE_UNALIGNED
+  if (0 != (((uintptr_t) M) % _MHD_UINT32_ALIGN))
+  { /* The input data is unaligned. */
+    /* Copy the unaligned input data to the aligned buffer. */
+    memcpy (X, M, sizeof(X));
+    /* The X[] buffer itself will be used as the source of the data,
+     * but the data will be reloaded in correct bytes order on
+     * the next steps. */
+    M = (const void *) X;
+  }
+#endif /* _MHD_GET_32BIT_LE_UNALIGNED */
 
-/* #define F1(x, y, z) (x & y | ~x & z) */
-#define F1(x, y, z) (z ^ (x & (y ^ z)))
-#define F2(x, y, z) F1(z, x, y)
-#define F3(x, y, z) (x ^ y ^ z)
-#define F4(x, y, z) (y ^ (x | ~z))
+  /* Four auxiliary functions, see RFC 1321, Clause 3.4 (step 4). */
+  /* Some optimisations used. */
+/* #define F_FUNC(x,y,z) (((x)&(y)) | ((~(x))&(z))) */ /* Original version */
+#define F_FUNC(x,y,z) ((((y) ^ (z)) & (x)) ^ (z))
+/* #define G_FUNC_1(x,y,z) (((x)&(z)) | ((y)&(~(z)))) */ /* Original version */
+/* #define G_FUNC_2(x,y,z) UINT32_C(0) */ /* Original version */
+#ifndef MHD_FAVOR_SMALL_CODE
+#  define G_FUNC_1(x,y,z) ((~(z)) & (y))
+#  define G_FUNC_2(x,y,z) ((z) & (x))
+#else  /* MHD_FAVOR_SMALL_CODE */
+#  define G_FUNC_1(x,y,z) ((((x) ^ (y)) & (z)) ^ (y))
+#  define G_FUNC_2(x,y,z) UINT32_C(0)
+#endif /* MHD_FAVOR_SMALL_CODE */
+#define H_FUNC(x,y,z) ((x) ^ (y) ^ (z)) /* Original version */
+/* #define I_FUNC(x,y,z) ((y) ^ ((x) | (~(z)))) */ /* Original version */
+#define I_FUNC(x,y,z) (((~(z)) | (x)) ^ (y))
 
-/* This is the central step in the MD5 algorithm. */
-#define MD5STEP(f, w, x, y, z, data, s) \
-	( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
+  /* One step of round 1 of MD5 computation, see RFC 1321, Clause 3.4 (step 4).
+     The original function was modified to use X[k] and T[i] as
+     direct inputs. */
+#define MD5STEP_R1(va,vb,vc,vd,vX,vs,vT) do {          \
+    (va) += (vX) + (vT);                               \
+    (va) += F_FUNC((vb),(vc),(vd));                    \
+    (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0)
 
-/*
- * The core of the MD5 algorithm, this alters an existing MD5 hash to
- * reflect the addition of 16 longwords of new data.  MD5Update blocks
- * the data and converts bytes into longwords for this routine.
- */
-static void
-MD5Transform(uint32_t buf[4],
-	     uint32_t in[16])
-{
-  uint32_t a, b, c, d;
+  /* Get value of X(k) from input data buffer.
+     See RFC 1321 Clause 3.4 (step 4). */
+#define GET_X_FROM_DATA(buf,t) \
+  _MHD_GET_32BIT_LE (((const uint32_t*) (buf)) + (t))
 
-    a = buf[0];
-    b = buf[1];
-    c = buf[2];
-    d = buf[3];
+  /* One step of round 2 of MD5 computation, see RFC 1321, Clause 3.4 (step 4).
+     The original function was modified to use X[k] and T[i] as
+     direct inputs. */
+#define MD5STEP_R2(va,vb,vc,vd,vX,vs,vT) do {         \
+    (va) += (vX) + (vT);                              \
+    (va) += G_FUNC_1((vb),(vc),(vd));                 \
+    (va) += G_FUNC_2((vb),(vc),(vd));                 \
+    (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0)
 
-    MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
-    MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
-    MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
-    MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
-    MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
-    MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
-    MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
-    MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
-    MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
-    MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
-    MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
-    MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
-    MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
-    MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
-    MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
-    MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+  /* One step of round 3 of MD5 computation, see RFC 1321, Clause 3.4 (step 4).
+     The original function was modified to use X[k] and T[i] as
+     direct inputs. */
+#define MD5STEP_R3(va,vb,vc,vd,vX,vs,vT) do {         \
+    (va) += (vX) + (vT);                              \
+    (va) += H_FUNC((vb),(vc),(vd));                   \
+    (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0)
 
-    MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
-    MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
-    MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
-    MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
-    MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
-    MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
-    MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
-    MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
-    MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
-    MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
-    MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
-    MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
-    MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
-    MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
-    MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
-    MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+  /* One step of round 4 of MD5 computation, see RFC 1321, Clause 3.4 (step 4).
+     The original function was modified to use X[k] and T[i] as
+     direct inputs. */
+#define MD5STEP_R4(va,vb,vc,vd,vX,vs,vT) do {         \
+    (va) += (vX) + (vT);                              \
+    (va) += I_FUNC((vb),(vc),(vd));                   \
+    (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0)
 
-    MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
-    MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
-    MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
-    MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
-    MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
-    MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
-    MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
-    MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
-    MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
-    MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
-    MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
-    MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
-    MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
-    MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
-    MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
-    MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+#if ! defined(MHD_FAVOR_SMALL_CODE)
 
-    MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
-    MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
-    MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
-    MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
-    MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
-    MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
-    MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
-    MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
-    MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
-    MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
-    MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
-    MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
-    MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
-    MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
-    MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
-    MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+  /* Round 1. */
 
-    buf[0] += a;
-    buf[1] += b;
-    buf[2] += c;
-    buf[3] += d;
-}
+#if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+  if ((const void *) X == M)
+  {
+    /* The input data is already in the data buffer X[] in correct bytes
+       order. */
+    MD5STEP_R1 (A, B, C, D, X[0],  7,  UINT32_C (0xd76aa478));
+    MD5STEP_R1 (D, A, B, C, X[1],  12, UINT32_C (0xe8c7b756));
+    MD5STEP_R1 (C, D, A, B, X[2],  17, UINT32_C (0x242070db));
+    MD5STEP_R1 (B, C, D, A, X[3],  22, UINT32_C (0xc1bdceee));
 
+    MD5STEP_R1 (A, B, C, D, X[4],  7,  UINT32_C (0xf57c0faf));
+    MD5STEP_R1 (D, A, B, C, X[5],  12, UINT32_C (0x4787c62a));
+    MD5STEP_R1 (C, D, A, B, X[6],  17, UINT32_C (0xa8304613));
+    MD5STEP_R1 (B, C, D, A, X[7],  22, UINT32_C (0xfd469501));
 
-/*
- * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
- * initialization constants.
- */
-void
-MD5Init(struct MD5Context *ctx)
-{
-    ctx->buf[0] = 0x67452301;
-    ctx->buf[1] = 0xefcdab89;
-    ctx->buf[2] = 0x98badcfe;
-    ctx->buf[3] = 0x10325476;
+    MD5STEP_R1 (A, B, C, D, X[8],  7,  UINT32_C (0x698098d8));
+    MD5STEP_R1 (D, A, B, C, X[9],  12, UINT32_C (0x8b44f7af));
+    MD5STEP_R1 (C, D, A, B, X[10], 17, UINT32_C (0xffff5bb1));
+    MD5STEP_R1 (B, C, D, A, X[11], 22, UINT32_C (0x895cd7be));
 
-    ctx->bits[0] = 0;
-    ctx->bits[1] = 0;
-}
+    MD5STEP_R1 (A, B, C, D, X[12], 7,  UINT32_C (0x6b901122));
+    MD5STEP_R1 (D, A, B, C, X[13], 12, UINT32_C (0xfd987193));
+    MD5STEP_R1 (C, D, A, B, X[14], 17, UINT32_C (0xa679438e));
+    MD5STEP_R1 (B, C, D, A, X[15], 22, UINT32_C (0x49b40821));
+  }
+  else /* Combined with the next 'if' */
+#endif /* _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN */
+  if (1)
+  {
+    /* The input data is loaded in correct (little-endian) format before
+       calculations on each step. */
+    MD5STEP_R1 (A, B, C, D, X[0]  = GET_X_FROM_DATA (M, 0),  7, \
+                UINT32_C (0xd76aa478));
+    MD5STEP_R1 (D, A, B, C, X[1]  = GET_X_FROM_DATA (M, 1),  12, \
+                UINT32_C (0xe8c7b756));
+    MD5STEP_R1 (C, D, A, B, X[2]  = GET_X_FROM_DATA (M, 2),  17, \
+                UINT32_C (0x242070db));
+    MD5STEP_R1 (B, C, D, A, X[3]  = GET_X_FROM_DATA (M, 3),  22, \
+                UINT32_C (0xc1bdceee));
 
-/*
- * Update context to reflect the concatenation of another buffer full
- * of bytes.
- */
-void
-MD5Update(struct MD5Context *ctx,
-	  const void *data,
-	  unsigned len)
-{
-    const unsigned char *buf = data;
-    uint32_t t;
+    MD5STEP_R1 (A, B, C, D, X[4]  = GET_X_FROM_DATA (M, 4),  7, \
+                UINT32_C (0xf57c0faf));
+    MD5STEP_R1 (D, A, B, C, X[5]  = GET_X_FROM_DATA (M, 5),  12, \
+                UINT32_C (0x4787c62a));
+    MD5STEP_R1 (C, D, A, B, X[6]  = GET_X_FROM_DATA (M, 6),  17, \
+                UINT32_C (0xa8304613));
+    MD5STEP_R1 (B, C, D, A, X[7]  = GET_X_FROM_DATA (M, 7),  22, \
+                UINT32_C (0xfd469501));
 
-    /* Update bitcount */
+    MD5STEP_R1 (A, B, C, D, X[8]  = GET_X_FROM_DATA (M, 8),  7, \
+                UINT32_C (0x698098d8));
+    MD5STEP_R1 (D, A, B, C, X[9]  = GET_X_FROM_DATA (M, 9),  12, \
+                UINT32_C (0x8b44f7af));
+    MD5STEP_R1 (C, D, A, B, X[10] = GET_X_FROM_DATA (M, 10), 17, \
+                UINT32_C (0xffff5bb1));
+    MD5STEP_R1 (B, C, D, A, X[11] = GET_X_FROM_DATA (M, 11), 22, \
+                UINT32_C (0x895cd7be));
 
-    t = ctx->bits[0];
-    if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
-	ctx->bits[1]++; 	/* Carry from low to high */
-    ctx->bits[1] += len >> 29;
+    MD5STEP_R1 (A, B, C, D, X[12] = GET_X_FROM_DATA (M, 12), 7, \
+                UINT32_C (0x6b901122));
+    MD5STEP_R1 (D, A, B, C, X[13] = GET_X_FROM_DATA (M, 13), 12, \
+                UINT32_C (0xfd987193));
+    MD5STEP_R1 (C, D, A, B, X[14] = GET_X_FROM_DATA (M, 14), 17, \
+                UINT32_C (0xa679438e));
+    MD5STEP_R1 (B, C, D, A, X[15] = GET_X_FROM_DATA (M, 15), 22, \
+                UINT32_C (0x49b40821));
+  }
 
-    t = (t >> 3) & 0x3f;	/* Bytes already in shsInfo->data */
+  /* Round 2. */
 
-    /* Handle any leading odd-sized chunks */
+  MD5STEP_R2 (A, B, C, D, X[1], 5, UINT32_C (0xf61e2562));
+  MD5STEP_R2 (D, A, B, C, X[6], 9, UINT32_C (0xc040b340));
+  MD5STEP_R2 (C, D, A, B, X[11], 14, UINT32_C (0x265e5a51));
+  MD5STEP_R2 (B, C, D, A, X[0], 20, UINT32_C (0xe9b6c7aa));
 
-    if (t) {
-	unsigned char *p = (unsigned char *) ctx->in + t;
+  MD5STEP_R2 (A, B, C, D, X[5], 5, UINT32_C (0xd62f105d));
+  MD5STEP_R2 (D, A, B, C, X[10], 9, UINT32_C (0x02441453));
+  MD5STEP_R2 (C, D, A, B, X[15], 14, UINT32_C (0xd8a1e681));
+  MD5STEP_R2 (B, C, D, A, X[4], 20, UINT32_C (0xe7d3fbc8));
 
-	t = 64 - t;
-	if (len < t) {
-	    memcpy(p, buf, len);
-	    return;
-	}
-	memcpy(p, buf, t);
-	byteReverse(ctx->in, 16);
-	MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-	buf += t;
-	len -= t;
-    }
-    /* Process data in 64-byte chunks */
+  MD5STEP_R2 (A, B, C, D, X[9], 5, UINT32_C (0x21e1cde6));
+  MD5STEP_R2 (D, A, B, C, X[14], 9, UINT32_C (0xc33707d6));
+  MD5STEP_R2 (C, D, A, B, X[3], 14, UINT32_C (0xf4d50d87));
+  MD5STEP_R2 (B, C, D, A, X[8], 20, UINT32_C (0x455a14ed));
 
-    while (len >= 64) {
-	memcpy(ctx->in, buf, 64);
-	byteReverse(ctx->in, 16);
-	MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-	buf += 64;
-	len -= 64;
-    }
+  MD5STEP_R2 (A, B, C, D, X[13], 5, UINT32_C (0xa9e3e905));
+  MD5STEP_R2 (D, A, B, C, X[2], 9, UINT32_C (0xfcefa3f8));
+  MD5STEP_R2 (C, D, A, B, X[7], 14, UINT32_C (0x676f02d9));
+  MD5STEP_R2 (B, C, D, A, X[12], 20, UINT32_C (0x8d2a4c8a));
 
-    /* Handle any remaining bytes of data. */
+  /* Round 3. */
 
-    memcpy(ctx->in, buf, len);
-}
+  MD5STEP_R3 (A, B, C, D, X[5], 4, UINT32_C (0xfffa3942));
+  MD5STEP_R3 (D, A, B, C, X[8], 11, UINT32_C (0x8771f681));
+  MD5STEP_R3 (C, D, A, B, X[11], 16, UINT32_C (0x6d9d6122));
+  MD5STEP_R3 (B, C, D, A, X[14], 23, UINT32_C (0xfde5380c));
 
-/*
- * Final wrapup - pad to 64-byte boundary with the bit pattern
- * 1 0* (64-bit count of bits processed, MSB-first)
- */
-void
-MD5Final (unsigned char digest[16],
-          struct MD5Context *ctx)
-{
-  unsigned count;
-  unsigned char *p;
+  MD5STEP_R3 (A, B, C, D, X[1], 4, UINT32_C (0xa4beea44));
+  MD5STEP_R3 (D, A, B, C, X[4], 11, UINT32_C (0x4bdecfa9));
+  MD5STEP_R3 (C, D, A, B, X[7], 16, UINT32_C (0xf6bb4b60));
+  MD5STEP_R3 (B, C, D, A, X[10], 23, UINT32_C (0xbebfbc70));
 
-  /* Compute number of bytes mod 64 */
-  count = (ctx->bits[0] >> 3) & 0x3F;
+  MD5STEP_R3 (A, B, C, D, X[13], 4, UINT32_C (0x289b7ec6));
+  MD5STEP_R3 (D, A, B, C, X[0], 11, UINT32_C (0xeaa127fa));
+  MD5STEP_R3 (C, D, A, B, X[3], 16, UINT32_C (0xd4ef3085));
+  MD5STEP_R3 (B, C, D, A, X[6], 23, UINT32_C (0x04881d05));
 
-  /* Set the first char of padding to 0x80.  This is safe since there is
-     always at least one byte free */
-  p = ctx->in + count;
-  *p++ = 0x80;
+  MD5STEP_R3 (A, B, C, D, X[9], 4, UINT32_C (0xd9d4d039));
+  MD5STEP_R3 (D, A, B, C, X[12], 11, UINT32_C (0xe6db99e5));
+  MD5STEP_R3 (C, D, A, B, X[15], 16, UINT32_C (0x1fa27cf8));
+  MD5STEP_R3 (B, C, D, A, X[2], 23, UINT32_C (0xc4ac5665));
 
-  /* Bytes of padding needed to make 64 bytes */
-  count = 64 - 1 - count;
+  /* Round 4. */
 
-  /* Pad out to 56 mod 64 */
-  if (count < 8)
+  MD5STEP_R4 (A, B, C, D, X[0], 6, UINT32_C (0xf4292244));
+  MD5STEP_R4 (D, A, B, C, X[7], 10, UINT32_C (0x432aff97));
+  MD5STEP_R4 (C, D, A, B, X[14], 15, UINT32_C (0xab9423a7));
+  MD5STEP_R4 (B, C, D, A, X[5], 21, UINT32_C (0xfc93a039));
+
+  MD5STEP_R4 (A, B, C, D, X[12], 6, UINT32_C (0x655b59c3));
+  MD5STEP_R4 (D, A, B, C, X[3], 10, UINT32_C (0x8f0ccc92));
+  MD5STEP_R4 (C, D, A, B, X[10], 15, UINT32_C (0xffeff47d));
+  MD5STEP_R4 (B, C, D, A, X[1], 21, UINT32_C (0x85845dd1));
+
+  MD5STEP_R4 (A, B, C, D, X[8], 6, UINT32_C (0x6fa87e4f));
+  MD5STEP_R4 (D, A, B, C, X[15], 10, UINT32_C (0xfe2ce6e0));
+  MD5STEP_R4 (C, D, A, B, X[6], 15, UINT32_C (0xa3014314));
+  MD5STEP_R4 (B, C, D, A, X[13], 21, UINT32_C (0x4e0811a1));
+
+  MD5STEP_R4 (A, B, C, D, X[4], 6, UINT32_C (0xf7537e82));
+  MD5STEP_R4 (D, A, B, C, X[11], 10, UINT32_C (0xbd3af235));
+  MD5STEP_R4 (C, D, A, B, X[2], 15, UINT32_C (0x2ad7d2bb));
+  MD5STEP_R4 (B, C, D, A, X[9], 21, UINT32_C (0xeb86d391));
+#else  /* MHD_FAVOR_SMALL_CODE */
+  if (1)
+  {
+    static const uint32_t T[64] =
+    { UINT32_C (0xd76aa478), UINT32_C (0xe8c7b756), UINT32_C (0x242070db),
+      UINT32_C (0xc1bdceee), UINT32_C (0xf57c0faf), UINT32_C (0x4787c62a),
+      UINT32_C (0xa8304613), UINT32_C (0xfd469501), UINT32_C (0x698098d8),
+      UINT32_C (0x8b44f7af), UINT32_C (0xffff5bb1), UINT32_C (0x895cd7be),
+      UINT32_C (0x6b901122), UINT32_C (0xfd987193), UINT32_C (0xa679438e),
+      UINT32_C (0x49b40821), UINT32_C (0xf61e2562), UINT32_C (0xc040b340),
+      UINT32_C (0x265e5a51), UINT32_C (0xe9b6c7aa), UINT32_C (0xd62f105d),
+      UINT32_C (0x02441453), UINT32_C (0xd8a1e681), UINT32_C (0xe7d3fbc8),
+      UINT32_C (0x21e1cde6), UINT32_C (0xc33707d6), UINT32_C (0xf4d50d87),
+      UINT32_C (0x455a14ed), UINT32_C (0xa9e3e905), UINT32_C (0xfcefa3f8),
+      UINT32_C (0x676f02d9), UINT32_C (0x8d2a4c8a), UINT32_C (0xfffa3942),
+      UINT32_C (0x8771f681), UINT32_C (0x6d9d6122), UINT32_C (0xfde5380c),
+      UINT32_C (0xa4beea44), UINT32_C (0x4bdecfa9), UINT32_C (0xf6bb4b60),
+      UINT32_C (0xbebfbc70), UINT32_C (0x289b7ec6), UINT32_C (0xeaa127fa),
+      UINT32_C (0xd4ef3085), UINT32_C (0x04881d05), UINT32_C (0xd9d4d039),
+      UINT32_C (0xe6db99e5), UINT32_C (0x1fa27cf8), UINT32_C (0xc4ac5665),
+      UINT32_C (0xf4292244), UINT32_C (0x432aff97), UINT32_C (0xab9423a7),
+      UINT32_C (0xfc93a039), UINT32_C (0x655b59c3), UINT32_C (0x8f0ccc92),
+      UINT32_C (0xffeff47d), UINT32_C (0x85845dd1), UINT32_C (0x6fa87e4f),
+      UINT32_C (0xfe2ce6e0), UINT32_C (0xa3014314), UINT32_C (0x4e0811a1),
+      UINT32_C (0xf7537e82), UINT32_C (0xbd3af235), UINT32_C (0x2ad7d2bb),
+      UINT32_C (0xeb86d391) };
+    unsigned int i; /**< Zero-based index */
+
+    /* Round 1. */
+
+    i = 0;
+    do
     {
-      /* Two lots of padding:  Pad the first block to 64 bytes */
-      memset(p, 0, count);
-      byteReverse(ctx->in, 16);
-      MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+      /* The input data is loaded in correct (little-endian) format before
+         calculations on each step. */
+      MD5STEP_R1 (A, B, C, D, X[i]  = GET_X_FROM_DATA (M, i),  7,  T[i]);
+      ++i;
+      MD5STEP_R1 (D, A, B, C, X[i]  = GET_X_FROM_DATA (M, i),  12, T[i]);
+      ++i;
+      MD5STEP_R1 (C, D, A, B, X[i]  = GET_X_FROM_DATA (M, i),  17, T[i]);
+      ++i;
+      MD5STEP_R1 (B, C, D, A, X[i]  = GET_X_FROM_DATA (M, i),  22, T[i]);
+      ++i;
+    } while (i < 16);
 
-      /* Now fill the next block with 56 bytes */
-      memset(ctx->in, 0, 56);
-    }
-  else
+    /* Round 2. */
+
+    do
     {
-      /* Pad block to 56 bytes */
-      memset(p, 0, count - 8);
-    }
-  byteReverse(ctx->in, 14);
+      const unsigned int idx_add = i;
+      MD5STEP_R2 (A, B, C, D, X[(1U  + idx_add) & 15U], 5,  T[i]);
+      ++i;
+      MD5STEP_R2 (D, A, B, C, X[(6U  + idx_add) & 15U], 9,  T[i]);
+      ++i;
+      MD5STEP_R2 (C, D, A, B, X[(11U + idx_add) & 15U], 14, T[i]);
+      ++i;
+      MD5STEP_R2 (B, C, D, A, X[(0U  + idx_add) & 15U], 20, T[i]);
+      ++i;
+    } while (i < 32);
 
-  /* Append length in bits and transform */
-  ((uint32_t *) ctx->in)[14] = ctx->bits[0];
-  ((uint32_t *) ctx->in)[15] = ctx->bits[1];
+    /* Round 3. */
 
-  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-  byteReverse((unsigned char *) ctx->buf, 4);
-  memcpy(digest, ctx->buf, 16);
-  memset(ctx, 0, sizeof(struct MD5Context));        /* In case it's sensitive */
+    do
+    {
+      const unsigned int idx_add = i;
+      MD5STEP_R3 (A, B, C, D, X[(5U  + 64U - idx_add) & 15U], 4,  T[i]);
+      ++i;
+      MD5STEP_R3 (D, A, B, C, X[(8U  + 64U - idx_add) & 15U], 11, T[i]);
+      ++i;
+      MD5STEP_R3 (C, D, A, B, X[(11U + 64U - idx_add) & 15U], 16, T[i]);
+      ++i;
+      MD5STEP_R3 (B, C, D, A, X[(14U + 64U - idx_add) & 15U], 23, T[i]);
+      ++i;
+    } while (i < 48);
+
+    /* Round 4. */
+
+    do
+    {
+      const unsigned int idx_add = i;
+      MD5STEP_R4 (A, B, C, D, X[(0U  + 64U - idx_add) & 15U], 6,  T[i]);
+      ++i;
+      MD5STEP_R4 (D, A, B, C, X[(7U  + 64U - idx_add) & 15U], 10, T[i]);
+      ++i;
+      MD5STEP_R4 (C, D, A, B, X[(14U + 64U - idx_add) & 15U], 15, T[i]);
+      ++i;
+      MD5STEP_R4 (B, C, D, A, X[(5U  + 64U - idx_add) & 15U], 21, T[i]);
+      ++i;
+    } while (i < 64);
+  }
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+  /* Finally increment and store working variables.
+     See RFC 1321, end of Clause 3.4 (step 4). */
+
+  H[0] += A;
+  H[1] += B;
+  H[2] += C;
+  H[3] += D;
 }
 
-/* end of md5.c */
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_MD5_update (struct Md5Ctx *ctx,
+                const uint8_t *data,
+                size_t length)
+{
+  unsigned int bytes_have; /**< Number of bytes in the context buffer */
+
+  mhd_assert ((data != NULL) || (length == 0));
+
+#ifndef MHD_FAVOR_SMALL_CODE
+  if (0 == length)
+    return; /* Shortcut, do nothing */
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+  /* Note: (count & (MD5_BLOCK_SIZE-1))
+           equals (count % MD5_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned int) (ctx->count & (MD5_BLOCK_SIZE - 1));
+  ctx->count += length;
+
+  if (0 != bytes_have)
+  {
+    unsigned int bytes_left = MD5_BLOCK_SIZE - bytes_have;
+    if (length >= bytes_left)
+    {     /* Combine new data with data in the buffer and
+             process the full block. */
+      memcpy (((uint8_t *) ctx->buffer) + bytes_have,
+              data,
+              bytes_left);
+      data += bytes_left;
+      length -= bytes_left;
+      md5_transform (ctx->H, ctx->buffer);
+      bytes_have = 0;
+    }
+  }
+
+  while (MD5_BLOCK_SIZE <= length)
+  {   /* Process any full blocks of new data directly,
+         without copying to the buffer. */
+    md5_transform (ctx->H, data);
+    data += MD5_BLOCK_SIZE;
+    length -= MD5_BLOCK_SIZE;
+  }
+
+  if (0 != length)
+  {   /* Copy incomplete block of new data (if any)
+         to the buffer. */
+    memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length);
+  }
+}
+
+
+/**
+ * Size of "length" insertion in bits.
+ * See RFC 1321, end of Clause 3.2 (step 2).
+ */
+#define MD5_SIZE_OF_LEN_ADD_BITS 64
+
+/**
+ * Size of "length" insertion in bytes.
+ */
+#define MD5_SIZE_OF_LEN_ADD (MD5_SIZE_OF_LEN_ADD_BITS / 8)
+
+/**
+ * Finalise MD5 calculation, return digest.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes
+ */
+void
+MHD_MD5_finish (struct Md5Ctx *ctx,
+                uint8_t digest[MD5_DIGEST_SIZE])
+{
+  uint64_t num_bits;   /**< Number of processed bits */
+  unsigned int bytes_have; /**< Number of bytes in the context buffer */
+
+  /* Memorise the number of processed bits.
+     The padding and other data added here during the postprocessing must
+     not change the amount of hashed data. */
+  num_bits = ctx->count << 3;
+
+  /* Note: (count & (MD5_BLOCK_SIZE-1))
+           equals (count % MD5_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned int) (ctx->count & (MD5_BLOCK_SIZE - 1));
+
+  /* Input data must be padded with a single bit "1", then with zeros and
+     the finally the length of data in bits must be added as the final bytes
+     of the last block.
+     See RFC 1321, Clauses 3.1 and 3.2 (steps 1 and 2). */
+  /* Data is always processed in form of bytes (not by individual bits),
+     therefore position of the first padding bit in byte is always
+     predefined (0x80). */
+  /* Buffer always have space for one byte at least (as full buffers are
+     processed immediately). */
+  ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80;
+
+  if (MD5_BLOCK_SIZE - bytes_have < MD5_SIZE_OF_LEN_ADD)
+  {   /* No space in the current block to put the total length of message.
+         Pad the current block with zeros and process it. */
+    if (bytes_have < MD5_BLOCK_SIZE)
+      memset (((uint8_t *) ctx->buffer) + bytes_have, 0,
+              MD5_BLOCK_SIZE - bytes_have);
+    /* Process the full block. */
+    md5_transform (ctx->H, ctx->buffer);
+    /* Start the new block. */
+    bytes_have = 0;
+  }
+
+  /* Pad the rest of the buffer with zeros. */
+  memset (((uint8_t *) ctx->buffer) + bytes_have, 0,
+          MD5_BLOCK_SIZE - MD5_SIZE_OF_LEN_ADD - bytes_have);
+  /* Put the number of bits in processed data as little-endian value.
+     See RFC 1321, clauses 2 and 3.2 (step 2). */
+  _MHD_PUT_64BIT_LE_SAFE (ctx->buffer + MD5_BLOCK_SIZE_WORDS - 2,
+                          num_bits);
+  /* Process the full final block. */
+  md5_transform (ctx->H, ctx->buffer);
+
+  /* Put in LE mode the hash as the final digest.
+     See RFC 1321, clauses 2 and 3.5 (step 5). */
+#ifndef _MHD_PUT_32BIT_LE_UNALIGNED
+  if (1
+#ifndef MHD_FAVOR_SMALL_CODE
+      && (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN)
+#endif /* MHD_FAVOR_SMALL_CODE */
+      )
+  {
+    /* If storing of the final result requires aligned address and
+       the destination address is not aligned or compact code is used,
+       store the final digest in aligned temporary buffer first, then
+       copy it to the destination. */
+    uint32_t alig_dgst[MD5_DIGEST_SIZE_WORDS];
+    _MHD_PUT_32BIT_LE (alig_dgst + 0, ctx->H[0]);
+    _MHD_PUT_32BIT_LE (alig_dgst + 1, ctx->H[1]);
+    _MHD_PUT_32BIT_LE (alig_dgst + 2, ctx->H[2]);
+    _MHD_PUT_32BIT_LE (alig_dgst + 3, ctx->H[3]);
+    /* Copy result to the unaligned destination address. */
+    memcpy (digest, alig_dgst, MD5_DIGEST_SIZE);
+  }
+#ifndef MHD_FAVOR_SMALL_CODE
+  else /* Combined with the next 'if' */
+#endif /* MHD_FAVOR_SMALL_CODE */
+#endif /* ! _MHD_PUT_32BIT_LE_UNALIGNED */
+#if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_32BIT_LE_UNALIGNED)
+  if (1)
+  {
+    /* Use cast to (void*) here to mute compiler alignment warnings.
+     * Compilers are not smart enough to see that alignment has been checked. */
+    _MHD_PUT_32BIT_LE ((void *) (digest + 0 * MD5_BYTES_IN_WORD), ctx->H[0]);
+    _MHD_PUT_32BIT_LE ((void *) (digest + 1 * MD5_BYTES_IN_WORD), ctx->H[1]);
+    _MHD_PUT_32BIT_LE ((void *) (digest + 2 * MD5_BYTES_IN_WORD), ctx->H[2]);
+    _MHD_PUT_32BIT_LE ((void *) (digest + 3 * MD5_BYTES_IN_WORD), ctx->H[3]);
+  }
+#endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_32BIT_LE_UNALIGNED */
+
+  /* Erase potentially sensitive data. */
+  memset (ctx, 0, sizeof(struct Md5Ctx));
+}
diff --git a/src/microhttpd/md5.h b/src/microhttpd/md5.h
index 5e77774..71cb29f 100644
--- a/src/microhttpd/md5.h
+++ b/src/microhttpd/md5.h
@@ -1,52 +1,131 @@
 /*
- * This code implements the MD5 message-digest algorithm.
- * The algorithm is due to Ron Rivest.	This code was
- * written by Colin Plumb in 1993, no copyright is claimed.
- * This code is in the public domain; do with it what you wish.
- *
- * Equivalent code is available from RSA Data Security, Inc.
- * This code has been tested against that, and is equivalent,
- * except that you don't need to include two pages of legalese
- * with every copy.
- *
- * To compute the message digest of a chunk of bytes, declare an
- * MD5Context structure, pass it to MD5Init, call MD5Update as
- * needed on buffers full of bytes, and then call MD5Final, which
- * will fill a supplied 16-byte array with the digest.
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/md5.h
+ * @brief  Calculation of MD5 digest
+ * @author Karlson2k (Evgeny Grin)
  */
 
-/* Brutally hacked by John Walker back from ANSI C to K&R (no
-   prototypes) to maintain the tradition that Netfone will compile
-   with Sun's original "cc". */
+#ifndef MHD_MD5_H
+#define MHD_MD5_H 1
 
-#ifndef MD5_H
-#define MD5_H
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
 
-#include "platform.h"
-#ifdef WORDS_BIGENDIAN
-#define HIGHFIRST
-#endif
+/**
+ * Number of bits in single MD5 word.
+ */
+#define MD5_WORD_SIZE_BITS 32
 
-#define MD5_DIGEST_SIZE 16
+/**
+ * Number of bytes in single MD5 word.
+ */
+#define MD5_BYTES_IN_WORD (MD5_WORD_SIZE_BITS / 8)
 
-struct MD5Context
+/**
+ * Hash is kept internally as four 32-bit words.
+ * This is intermediate hash size, used during computing the final digest.
+ */
+#define MD5_HASH_SIZE_WORDS 4
+
+/**
+ * Size of MD5 resulting digest in bytes.
+ * This is the final digest size, not intermediate hash.
+ */
+#define MD5_DIGEST_SIZE_WORDS MD5_HASH_SIZE_WORDS
+
+/**
+ * Size of MD5 resulting digest in bytes
+ * This is the final digest size, not intermediate hash.
+ */
+#define MD5_DIGEST_SIZE (MD5_DIGEST_SIZE_WORDS * MD5_BYTES_IN_WORD)
+
+/**
+ * Size of MD5 digest string in chars including termination NUL.
+ */
+#define MD5_DIGEST_STRING_SIZE ((MD5_DIGEST_SIZE) * 2 + 1)
+
+/**
+ * Size of MD5 single processing block in bits.
+ */
+#define MD5_BLOCK_SIZE_BITS 512
+
+/**
+ * Size of MD5 single processing block in bytes.
+ */
+#define MD5_BLOCK_SIZE (MD5_BLOCK_SIZE_BITS / 8)
+
+/**
+ * Size of MD5 single processing block in words.
+ */
+#define MD5_BLOCK_SIZE_WORDS (MD5_BLOCK_SIZE_BITS / MD5_WORD_SIZE_BITS)
+
+
+/**
+ * MD5 calculation context
+ */
+struct Md5Ctx
 {
-  uint32_t buf[4];
-  uint32_t bits[2];
-  unsigned char in[64];
+  uint32_t H[MD5_HASH_SIZE_WORDS];         /**< Intermediate hash value / digest at end of calculation */
+  uint32_t buffer[MD5_BLOCK_SIZE_WORDS];   /**< MD5 input data buffer */
+  uint64_t count;                          /**< number of bytes, mod 2^64 */
 };
 
-
+/**
+ * Initialise structure for MD5 calculation.
+ *
+ * @param ctx the calculation context
+ */
 void
-MD5Init(struct MD5Context *ctx);
+MHD_MD5_init (struct Md5Ctx *ctx);
 
+
+/**
+ * MD5 process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
 void
-MD5Update(struct MD5Context *ctx,
-	  const void *buf,
-	  unsigned len);
+MHD_MD5_update (struct Md5Ctx *ctx,
+                const uint8_t *data,
+                size_t length);
 
+
+/**
+ * Finalise MD5 calculation, return digest.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes
+ */
 void
-MD5Final(unsigned char digest[MD5_DIGEST_SIZE],
-         struct MD5Context *ctx);
+MHD_MD5_finish (struct Md5Ctx *ctx,
+                uint8_t digest[MD5_DIGEST_SIZE]);
 
-#endif /* !MD5_H */
+/**
+ * Indicates that function MHD_MD5_finish() (without context reset) is available
+ */
+#define MHD_MD5_HAS_FINISH 1
+
+#endif /* MHD_MD5_H */
diff --git a/src/microhttpd/md5_ext.c b/src/microhttpd/md5_ext.c
new file mode 100644
index 0000000..02cc53c
--- /dev/null
+++ b/src/microhttpd/md5_ext.c
@@ -0,0 +1,100 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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 GNU libmicrohttpd.
+     If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file microhttpd/md5_ext.c
+ * @brief  Wrapper for MD5 calculation performed by TLS library
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "md5_ext.h"
+#include "mhd_assert.h"
+
+
+/**
+ * Initialise structure for MD5 calculation, allocate resources.
+ *
+ * This function must not be called more than one time for @a ctx.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_MD5_init_one_time (struct Md5CtxExt *ctx)
+{
+  ctx->handle = NULL;
+  ctx->ext_error = gnutls_hash_init (&ctx->handle,
+                                     GNUTLS_DIG_MD5);
+  if ((0 != ctx->ext_error) && (NULL != ctx->handle))
+  {
+    /* GnuTLS may return initialisation error and set the handle at the
+       same time. Such handle cannot be used for calculations.
+       Note: GnuTLS may also return an error and NOT set the handle. */
+    gnutls_free (ctx->handle);
+    ctx->handle = NULL;
+  }
+
+  /* If handle is NULL, the error must be set */
+  mhd_assert ((NULL != ctx->handle) || (0 != ctx->ext_error));
+  /* If error is set, the handle must be NULL */
+  mhd_assert ((0 == ctx->ext_error) || (NULL == ctx->handle));
+}
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_MD5_update (struct Md5CtxExt *ctx,
+                const uint8_t *data,
+                size_t length)
+{
+  if (0 == ctx->ext_error)
+    ctx->ext_error = gnutls_hash (ctx->handle, data, length);
+}
+
+
+/**
+ * Finalise MD5 calculation, return digest, reset hash calculation.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes
+ */
+void
+MHD_MD5_finish_reset (struct Md5CtxExt *ctx,
+                      uint8_t digest[MD5_DIGEST_SIZE])
+{
+  if (0 == ctx->ext_error)
+    gnutls_hash_output (ctx->handle, digest);
+}
+
+
+/**
+ * Free allocated resources.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_MD5_deinit (struct Md5CtxExt *ctx)
+{
+  if (NULL != ctx->handle)
+    gnutls_hash_deinit (ctx->handle, NULL);
+}
diff --git a/src/microhttpd/md5_ext.h b/src/microhttpd/md5_ext.h
new file mode 100644
index 0000000..435991c
--- /dev/null
+++ b/src/microhttpd/md5_ext.h
@@ -0,0 +1,112 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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 GNU libmicrohttpd.
+     If not, see <http://www.gnu.org/licenses/>.
+*/
+/**
+ * @file microhttpd/md5_ext.h
+ * @brief  Wrapper declarations for MD5 calculation performed by TLS library
+ * @author Karlson2k (Evgeny Grin)
+ */
+#ifndef MHD_MD5_EXT_H
+#define MHD_MD5_EXT_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
+#include <gnutls/crypto.h>
+
+/**
+ * Size of MD5 resulting digest in bytes
+ * This is the final digest size, not intermediate hash.
+ */
+#define MD5_DIGEST_SIZE (16)
+
+
+/**
+ * Indicates that struct Md5CtxExt has 'ext_error'
+ */
+#define MHD_MD5_HAS_EXT_ERROR 1
+
+/**
+ * MD5 calculation context
+ */
+struct Md5CtxExt
+{
+  gnutls_hash_hd_t handle; /**< Hash calculation handle */
+  int ext_error; /**< Non-zero if external error occurs during init or hashing */
+};
+
+/**
+ * Indicates that MHD_MD5_init_one_time() function is present.
+ */
+#define MHD_MD5_HAS_INIT_ONE_TIME 1
+
+/**
+ * Initialise structure for MD5 calculation, allocate resources.
+ *
+ * This function must not be called more than one time for @a ctx.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_MD5_init_one_time (struct Md5CtxExt *ctx);
+
+
+/**
+ * MD5 process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_MD5_update (struct Md5CtxExt *ctx,
+                const uint8_t *data,
+                size_t length);
+
+
+/**
+ * Indicates that MHD_MD5_finish_reset() function is available
+ */
+#define MHD_MD5_HAS_FINISH_RESET 1
+
+/**
+ * Finalise MD5 calculation, return digest, reset hash calculation.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes
+ */
+void
+MHD_MD5_finish_reset (struct Md5CtxExt *ctx,
+                      uint8_t digest[MD5_DIGEST_SIZE]);
+
+/**
+ * Indicates that MHD_MD5_deinit() function is present
+ */
+#define MHD_MD5_HAS_DEINIT 1
+
+/**
+ * Free allocated resources.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_MD5_deinit (struct Md5CtxExt *ctx);
+
+#endif /* MHD_MD5_EXT_H */
diff --git a/src/microhttpd/memorypool.c b/src/microhttpd/memorypool.c
index 2f39931..8d80f88 100644
--- a/src/microhttpd/memorypool.c
+++ b/src/microhttpd/memorypool.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007, 2009, 2010 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2007--2021 Daniel Pittman, Christian Grothoff, and
+     Karlson2k (Evgeny Grin)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,15 +22,66 @@
  * @file memorypool.c
  * @brief memory pool
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "memorypool.h"
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#include <string.h>
+#include <stdint.h>
+#include "mhd_assert.h"
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+#ifdef _WIN32
+#include <windows.h>
+#endif
+#ifdef HAVE_SYSCONF
+#include <unistd.h>
+#if defined(_SC_PAGE_SIZE)
+#define MHD_SC_PAGESIZE _SC_PAGE_SIZE
+#elif defined(_SC_PAGESIZE)
+#define MHD_SC_PAGESIZE _SC_PAGESIZE
+#endif /* _SC_PAGESIZE */
+#endif /* HAVE_SYSCONF */
+#include "mhd_limits.h" /* for SIZE_MAX, PAGESIZE / PAGE_SIZE */
+
+#if defined(MHD_USE_PAGESIZE_MACRO) || defined(MHD_USE_PAGE_SIZE_MACRO)
+#ifndef HAVE_SYSCONF /* Avoid duplicate include */
+#include <unistd.h>
+#endif /* HAVE_SYSCONF */
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif /* HAVE_SYS_PARAM_H */
+#endif /* MHD_USE_PAGESIZE_MACRO || MHD_USE_PAGE_SIZE_MACRO */
+
+/**
+ * Fallback value of page size
+ */
+#define _MHD_FALLBACK_PAGE_SIZE (4096)
+
+#if defined(MHD_USE_PAGESIZE_MACRO)
+#define MHD_DEF_PAGE_SIZE_ PAGESIZE
+#elif defined(MHD_USE_PAGE_SIZE_MACRO)
+#define MHD_DEF_PAGE_SIZE_ PAGE_SIZE
+#else  /* ! PAGESIZE */
+#define MHD_DEF_PAGE_SIZE_ _MHD_FALLBACK_PAGE_SIZE
+#endif /* ! PAGESIZE */
+
+
+#ifdef MHD_ASAN_POISON_ACTIVE
+#include <sanitizer/asan_interface.h>
+#endif /* MHD_ASAN_POISON_ACTIVE */
 
 /* define MAP_ANONYMOUS for Mac OS X */
-#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
+#if defined(MAP_ANON) && ! defined(MAP_ANONYMOUS)
 #define MAP_ANONYMOUS MAP_ANON
 #endif
-#ifndef MAP_FAILED
-#define MAP_FAILED ((void*)-1)
+#if defined(_WIN32)
+#define MAP_FAILED NULL
+#elif ! defined(MAP_FAILED)
+#define MAP_FAILED ((void*) -1)
 #endif
 
 /**
@@ -40,7 +92,138 @@
 /**
  * Round up 'n' to a multiple of ALIGN_SIZE.
  */
-#define ROUND_TO_ALIGN(n) ((n+(ALIGN_SIZE-1)) & (~(ALIGN_SIZE-1)))
+#define ROUND_TO_ALIGN(n) (((n) + (ALIGN_SIZE - 1)) \
+                           / (ALIGN_SIZE) *(ALIGN_SIZE))
+
+
+#ifndef MHD_ASAN_POISON_ACTIVE
+#define _MHD_NOSANITIZE_PTRS /**/
+#define _MHD_RED_ZONE_SIZE (0)
+#define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) ROUND_TO_ALIGN(n)
+#define _MHD_POISON_MEMORY(pointer, size) (void)0
+#define _MHD_UNPOISON_MEMORY(pointer, size) (void)0
+/**
+ * Boolean 'true' if the first pointer is less or equal the second pointer
+ */
+#define mp_ptr_le_(p1,p2) \
+  (((const uint8_t*)(p1)) <= ((const uint8_t*)(p2)))
+/**
+ * The difference in bytes between positions of the first and
+ * the second pointers
+ */
+#define mp_ptr_diff_(p1,p2) \
+  ((size_t)(((const uint8_t*)(p1)) - ((const uint8_t*)(p2))))
+#else  /* MHD_ASAN_POISON_ACTIVE */
+#define _MHD_RED_ZONE_SIZE (ALIGN_SIZE)
+#define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) (ROUND_TO_ALIGN(n) + _MHD_RED_ZONE_SIZE)
+#define _MHD_POISON_MEMORY(pointer, size) \
+  ASAN_POISON_MEMORY_REGION ((pointer), (size))
+#define _MHD_UNPOISON_MEMORY(pointer, size) \
+  ASAN_UNPOISON_MEMORY_REGION ((pointer), (size))
+#if defined(FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS)
+/**
+ * Boolean 'true' if the first pointer is less or equal the second pointer
+ */
+#define mp_ptr_le_(p1,p2) \
+  (((uintptr_t)((const void*)(p1))) <= ((uintptr_t)((const void*)(p2))))
+/**
+ * The difference in bytes between positions of the first and
+ * the second pointers
+ */
+#define mp_ptr_diff_(p1,p2) \
+  ((size_t)(((uintptr_t)((const uint8_t*)(p1))) - \
+            ((uintptr_t)((const uint8_t*)(p2)))))
+#elif defined(FUNC_ATTR_PTRCOMPARE_WORKS) && \
+  defined(FUNC_ATTR_PTRSUBTRACT_WORKS)
+#ifdef _DEBUG
+/**
+ * Boolean 'true' if the first pointer is less or equal the second pointer
+ */
+__attribute__((no_sanitize ("pointer-compare"))) static bool
+mp_ptr_le_ (const void *p1, const void *p2)
+{
+  return (((const uint8_t *) p1) <= ((const uint8_t *) p2));
+}
+
+
+#endif /* _DEBUG */
+
+
+/**
+ * The difference in bytes between positions of the first and
+ * the second pointers
+ */
+__attribute__((no_sanitize ("pointer-subtract"))) static size_t
+mp_ptr_diff_ (const void *p1, const void *p2)
+{
+  return (size_t) (((const uint8_t *) p1) - ((const uint8_t *) p2));
+}
+
+
+#elif defined(FUNC_ATTR_NOSANITIZE_WORKS)
+#ifdef _DEBUG
+/**
+ * Boolean 'true' if the first pointer is less or equal the second pointer
+ */
+__attribute__((no_sanitize ("address"))) static bool
+mp_ptr_le_ (const void *p1, const void *p2)
+{
+  return (((const uint8_t *) p1) <= ((const uint8_t *) p2));
+}
+
+
+#endif /* _DEBUG */
+
+/**
+ * The difference in bytes between positions of the first and
+ * the second pointers
+ */
+__attribute__((no_sanitize ("address"))) static size_t
+mp_ptr_diff_ (const void *p1, const void *p2)
+{
+  return (size_t) (((const uint8_t *) p1) - ((const uint8_t *) p2));
+}
+
+
+#else  /* ! FUNC_ATTR_NOSANITIZE_WORKS */
+#error User-poisoning cannot be used
+#endif /* ! FUNC_ATTR_NOSANITIZE_WORKS */
+#endif /* MHD_ASAN_POISON_ACTIVE */
+
+/**
+ * Size of memory page
+ */
+static size_t MHD_sys_page_size_ =
+#if defined(MHD_USE_PAGESIZE_MACRO_STATIC)
+  PAGESIZE;
+#elif defined(MHD_USE_PAGE_SIZE_MACRO_STATIC)
+  PAGE_SIZE;
+#else  /* ! MHD_USE_PAGE_SIZE_MACRO_STATIC */
+  _MHD_FALLBACK_PAGE_SIZE;   /* Default fallback value */
+#endif /* ! MHD_USE_PAGE_SIZE_MACRO_STATIC */
+
+/**
+ * Initialise values for memory pools
+ */
+void
+MHD_init_mem_pools_ (void)
+{
+#ifdef MHD_SC_PAGESIZE
+  long result;
+  result = sysconf (MHD_SC_PAGESIZE);
+  if (-1 != result)
+    MHD_sys_page_size_ = (size_t) result;
+  else
+    MHD_sys_page_size_ = MHD_DEF_PAGE_SIZE_;
+#elif defined(_WIN32)
+  SYSTEM_INFO si;
+  GetSystemInfo (&si);
+  MHD_sys_page_size_ = (size_t) si.dwPageSize;
+#else
+  MHD_sys_page_size_ = MHD_DEF_PAGE_SIZE_;
+#endif /* _WIN32 */
+  mhd_assert (0 == (MHD_sys_page_size_ % ALIGN_SIZE));
+}
 
 
 /**
@@ -53,7 +236,7 @@
   /**
    * Pointer to the pool's memory
    */
-  char *memory;
+  uint8_t *memory;
 
   /**
    * Size of the pool.
@@ -66,14 +249,14 @@
   size_t pos;
 
   /**
-   * Offset of the last unallocated byte.
+   * Offset of the byte after the last unallocated byte.
    */
   size_t end;
 
   /**
-   * #MHD_NO if pool was malloc'ed, #MHD_YES if mmapped (VirtualAlloc'ed for W32).
+   * 'false' if pool was malloc'ed, 'true' if mmapped (VirtualAlloc'ed for W32).
    */
-  int is_mmap;
+  bool is_mmap;
 };
 
 
@@ -87,41 +270,64 @@
 MHD_pool_create (size_t max)
 {
   struct MemoryPool *pool;
+  size_t alloc_size;
 
+  mhd_assert (max > 0);
+  alloc_size = 0;
   pool = malloc (sizeof (struct MemoryPool));
   if (NULL == pool)
     return NULL;
 #if defined(MAP_ANONYMOUS) || defined(_WIN32)
-  if (max <= 32 * 1024)
+  if ( (max <= 32 * 1024) ||
+       (max < MHD_sys_page_size_ * 4 / 3) )
+  {
     pool->memory = MAP_FAILED;
+  }
   else
-#if defined(MAP_ANONYMOUS) && !defined(_WIN32)
-    pool->memory = mmap (NULL, max, PROT_READ | PROT_WRITE,
-			 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+  {
+    /* Round up allocation to page granularity. */
+    alloc_size = max + MHD_sys_page_size_ - 1;
+    alloc_size -= alloc_size % MHD_sys_page_size_;
+#if defined(MAP_ANONYMOUS) && ! defined(_WIN32)
+    pool->memory = mmap (NULL,
+                         alloc_size,
+                         PROT_READ | PROT_WRITE,
+                         MAP_PRIVATE | MAP_ANONYMOUS,
+                         -1,
+                         0);
 #elif defined(_WIN32)
-    pool->memory = VirtualAlloc(NULL, max, MEM_COMMIT | MEM_RESERVE,
-        PAGE_READWRITE);
-#endif
-#else
+    pool->memory = VirtualAlloc (NULL,
+                                 alloc_size,
+                                 MEM_COMMIT | MEM_RESERVE,
+                                 PAGE_READWRITE);
+#endif /* _WIN32 */
+  }
+#else  /* ! _WIN32 && ! MAP_ANONYMOUS */
   pool->memory = MAP_FAILED;
-#endif
-  if ((pool->memory == MAP_FAILED) || (pool->memory == NULL))
+#endif /* ! _WIN32 && ! MAP_ANONYMOUS */
+  if (MAP_FAILED == pool->memory)
+  {
+    alloc_size = ROUND_TO_ALIGN (max);
+    pool->memory = malloc (alloc_size);
+    if (NULL == pool->memory)
     {
-      pool->memory = malloc (max);
-      if (pool->memory == NULL)
-        {
-          free (pool);
-          return NULL;
-        }
-      pool->is_mmap = MHD_NO;
+      free (pool);
+      return NULL;
     }
+    pool->is_mmap = false;
+  }
+#if defined(MAP_ANONYMOUS) || defined(_WIN32)
   else
-    {
-      pool->is_mmap = MHD_YES;
-    }
+  {
+    pool->is_mmap = true;
+  }
+#endif /* _WIN32 || MAP_ANONYMOUS */
+  mhd_assert (0 == (((uintptr_t) pool->memory) % ALIGN_SIZE));
   pool->pos = 0;
-  pool->end = max;
-  pool->size = max;
+  pool->end = alloc_size;
+  pool->size = alloc_size;
+  mhd_assert (0 < alloc_size);
+  _MHD_POISON_MEMORY (pool->memory, pool->size);
   return pool;
 }
 
@@ -134,28 +340,56 @@
 void
 MHD_pool_destroy (struct MemoryPool *pool)
 {
-  if (pool == NULL)
+  if (NULL == pool)
     return;
-  if (pool->is_mmap == MHD_NO)
+
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos));
+  _MHD_UNPOISON_MEMORY (pool->memory, pool->size);
+  if (! pool->is_mmap)
     free (pool->memory);
   else
-#if defined(MAP_ANONYMOUS) && !defined(_WIN32)
-    munmap (pool->memory, pool->size);
+#if defined(MAP_ANONYMOUS) && ! defined(_WIN32)
+    munmap (pool->memory,
+            pool->size);
 #elif defined(_WIN32)
-    VirtualFree(pool->memory, 0, MEM_RELEASE);
+    VirtualFree (pool->memory,
+                 0,
+                 MEM_RELEASE);
 #else
-    abort();
+    abort ();
 #endif
   free (pool);
 }
 
 
 /**
+ * Check how much memory is left in the @a pool
+ *
+ * @param pool pool to check
+ * @return number of bytes still available in @a pool
+ */
+size_t
+MHD_pool_get_free (struct MemoryPool *pool)
+{
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos));
+#ifdef MHD_ASAN_POISON_ACTIVE
+  if ((pool->end - pool->pos) <= _MHD_RED_ZONE_SIZE)
+    return 0;
+#endif /* MHD_ASAN_POISON_ACTIVE */
+  return (pool->end - pool->pos) - _MHD_RED_ZONE_SIZE;
+}
+
+
+/**
  * Allocate size bytes from the pool.
  *
  * @param pool memory pool to use for the operation
  * @param size number of bytes to allocate
- * @param from_end allocate from end of pool (set to #MHD_YES);
+ * @param from_end allocate from end of pool (set to 'true');
  *        use this for small, persistent allocations that
  *        will never be reallocated
  * @return NULL if the pool cannot support size more
@@ -163,26 +397,84 @@
  */
 void *
 MHD_pool_allocate (struct MemoryPool *pool,
-		   size_t size, int from_end)
+                   size_t size,
+                   bool from_end)
 {
   void *ret;
   size_t asize;
 
-  asize = ROUND_TO_ALIGN (size);
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos));
+  asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size);
   if ( (0 == asize) && (0 != size) )
     return NULL; /* size too close to SIZE_MAX */
-  if ((pool->pos + asize > pool->end) || (pool->pos + asize < pool->pos))
+  if (asize > pool->end - pool->pos)
     return NULL;
-  if (from_end == MHD_YES)
-    {
-      ret = &pool->memory[pool->end - asize];
-      pool->end -= asize;
-    }
+  if (from_end)
+  {
+    ret = &pool->memory[pool->end - asize];
+    pool->end -= asize;
+  }
   else
-    {
-      ret = &pool->memory[pool->pos];
-      pool->pos += asize;
-    }
+  {
+    ret = &pool->memory[pool->pos];
+    pool->pos += asize;
+  }
+  _MHD_UNPOISON_MEMORY (ret, size);
+  return ret;
+}
+
+
+/**
+ * Try to allocate @a size bytes memory area from the @a pool.
+ *
+ * If allocation fails, @a required_bytes is updated with size required to be
+ * freed in the @a pool from rellocatable area to allocate requested number
+ * of bytes.
+ * Allocated memory area is always not rellocatable ("from end").
+ *
+ * @param pool memory pool to use for the operation
+ * @param size the size of memory in bytes to allocate
+ * @param[out] required_bytes the pointer to variable to be updated with
+ *                            the size of the required additional free
+ *                            memory area, not updated if function succeed.
+ *                            Cannot be NULL.
+ * @return the pointer to allocated memory area if succeed,
+ *         NULL if the pool doesn't have enough space, required_bytes is updated
+ *         with amount of space needed to be freed in rellocatable area or
+ *         set to SIZE_MAX if requested size is too large for the pool.
+ */
+void *
+MHD_pool_try_alloc (struct MemoryPool *pool,
+                    size_t size,
+                    size_t *required_bytes)
+{
+  void *ret;
+  size_t asize;
+
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos));
+  asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size);
+  if ( (0 == asize) && (0 != size) )
+  { /* size is too close to SIZE_MAX, very unlikely */
+    *required_bytes = SIZE_MAX;
+    return NULL;
+  }
+  if (asize > pool->end - pool->pos)
+  {
+    mhd_assert ((pool->end - pool->pos) == \
+                ROUND_TO_ALIGN (pool->end - pool->pos));
+    if (asize <= pool->end)
+      *required_bytes = asize - (pool->end - pool->pos);
+    else
+      *required_bytes = SIZE_MAX;
+    return NULL;
+  }
+  ret = &pool->memory[pool->end - asize];
+  pool->end -= asize;
+  _MHD_UNPOISON_MEMORY (ret, size);
   return ret;
 }
 
@@ -191,10 +483,10 @@
  * Reallocate a block of memory obtained from the pool.
  * This is particularly efficient when growing or
  * shrinking the block that was last (re)allocated.
- * If the given block is not the most recenlty
+ * If the given block is not the most recently
  * (re)allocated block, the memory of the previous
- * allocation may be leaked until the pool is
- * destroyed (and copying the data maybe required).
+ * allocation may be not released until the pool is
+ * destroyed or reset.
  *
  * @param pool memory pool to use for the operation
  * @param old the existing block
@@ -207,77 +499,267 @@
 void *
 MHD_pool_reallocate (struct MemoryPool *pool,
                      void *old,
-		     size_t old_size,
-		     size_t new_size)
+                     size_t old_size,
+                     size_t new_size)
 {
-  void *ret;
   size_t asize;
+  uint8_t *new_blc;
 
-  asize = ROUND_TO_ALIGN (new_size);
-  if ( (0 == asize) && (0 != new_size) )
-    return NULL; /* new_size too close to SIZE_MAX */
-  if ((pool->end < old_size) || (pool->end < asize))
-    return NULL;                /* unsatisfiable or bogus request */
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (old != NULL || old_size == 0);
+  mhd_assert (pool->size >= old_size);
+  mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos));
+#if defined(MHD_ASAN_POISON_ACTIVE) && defined(HAVE___ASAN_REGION_IS_POISONED)
+  mhd_assert (NULL == __asan_region_is_poisoned (old, old_size));
+#endif /* MHD_ASAN_POISON_ACTIVE && HAVE___ASAN_REGION_IS_POISONED */
 
-  if ((pool->pos >= old_size) && (&pool->memory[pool->pos - old_size] == old))
+  if (NULL != old)
+  {   /* Have previously allocated data */
+    const size_t old_offset = mp_ptr_diff_ (old, pool->memory);
+    const bool shrinking = (old_size > new_size);
+
+    mhd_assert (mp_ptr_le_ (pool->memory, old));
+    /* (pool->memory + pool->size >= (uint8_t*) old + old_size) */
+    mhd_assert ((pool->size - _MHD_RED_ZONE_SIZE) >= (old_offset + old_size));
+    /* Blocks "from the end" must not be reallocated */
+    /* (old_size == 0 || pool->memory + pool->pos > (uint8_t*) old) */
+    mhd_assert ((old_size == 0) || \
+                (pool->pos > old_offset));
+    mhd_assert ((old_size == 0) || \
+                ((pool->end - _MHD_RED_ZONE_SIZE) >= (old_offset + old_size)));
+    /* Try resizing in-place */
+    if (shrinking)
+    {     /* Shrinking in-place, zero-out freed part */
+      memset ((uint8_t *) old + new_size, 0, old_size - new_size);
+      _MHD_POISON_MEMORY ((uint8_t *) old + new_size, old_size - new_size);
+    }
+    if (pool->pos ==
+        ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + old_size))
+    {     /* "old" block is the last allocated block */
+      const size_t new_apos =
+        ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + new_size);
+      if (! shrinking)
+      {                               /* Grow in-place, check for enough space. */
+        if ( (new_apos > pool->end) ||
+             (new_apos < pool->pos) ) /* Value wrap */
+          return NULL;                /* No space */
+      }
+      /* Resized in-place */
+      pool->pos = new_apos;
+      _MHD_UNPOISON_MEMORY (old, new_size);
+      return old;
+    }
+    if (shrinking)
+      return old;   /* Resized in-place, freed part remains allocated */
+  }
+  /* Need to allocate new block */
+  asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (new_size);
+  if ( ( (0 == asize) &&
+         (0 != new_size) ) || /* Value wrap, too large new_size. */
+       (asize > pool->end - pool->pos) ) /* Not enough space */
+    return NULL;
+
+  new_blc = pool->memory + pool->pos;
+  pool->pos += asize;
+
+  _MHD_UNPOISON_MEMORY (new_blc, new_size);
+  if (0 != old_size)
+  {
+    /* Move data to new block, old block remains allocated */
+    memcpy (new_blc, old, old_size);
+    /* Zero-out old block */
+    memset (old, 0, old_size);
+    _MHD_POISON_MEMORY (old, old_size);
+  }
+  return new_blc;
+}
+
+
+/**
+ * Deallocate a block of memory obtained from the pool.
+ *
+ * If the given block is not the most recently
+ * (re)allocated block, the memory of the this block
+ * allocation may be not released until the pool is
+ * destroyed or reset.
+ *
+ * @param pool memory pool to use for the operation
+ * @param block the allocated block, the NULL is tolerated
+ * @param block_size the size of the allocated block
+ */
+void
+MHD_pool_deallocate (struct MemoryPool *pool,
+                     void *block,
+                     size_t block_size)
+{
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (block != NULL || block_size == 0);
+  mhd_assert (pool->size >= block_size);
+  mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos));
+
+  if (NULL != block)
+  {   /* Have previously allocated data */
+    const size_t block_offset = mp_ptr_diff_ (block, pool->memory);
+    mhd_assert (mp_ptr_le_ (pool->memory, block));
+    mhd_assert (block_offset <= pool->size);
+    mhd_assert ((block_offset != pool->pos) || (block_size == 0));
+    /* Zero-out deallocated region */
+    if (0 != block_size)
     {
-      /* was the previous allocation - optimize! */
-      if (pool->pos + asize - old_size <= pool->end)
+      memset (block, 0, block_size);
+      _MHD_POISON_MEMORY (block, block_size);
+    }
+#if ! defined(MHD_FAVOR_SMALL_CODE) && ! defined(MHD_ASAN_POISON_ACTIVE)
+    else
+      return; /* Zero size, no need to do anything */
+#endif /* ! MHD_FAVOR_SMALL_CODE && ! MHD_ASAN_POISON_ACTIVE */
+    if (block_offset <= pool->pos)
+    {
+      /* "Normal" block, not allocated "from the end". */
+      const size_t alg_end =
+        ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size);
+      mhd_assert (alg_end <= pool->pos);
+      if (alg_end == pool->pos)
+      {
+        /* The last allocated block, return deallocated block to the pool */
+        size_t alg_start = ROUND_TO_ALIGN (block_offset);
+        mhd_assert (alg_start >= block_offset);
+#if defined(MHD_ASAN_POISON_ACTIVE)
+        if (alg_start != block_offset)
         {
-          /* fits */
-          pool->pos += asize - old_size;
-          if (asize < old_size)      /* shrinking - zero again! */
-            memset (&pool->memory[pool->pos], 0, old_size - asize);
-          return old;
+          _MHD_POISON_MEMORY (pool->memory + block_offset, \
+                              alg_start - block_offset);
         }
-      /* does not fit */
-      return NULL;
+        else if (0 != alg_start)
+        {
+          bool need_red_zone_before;
+          mhd_assert (_MHD_RED_ZONE_SIZE <= alg_start);
+#if defined(HAVE___ASAN_REGION_IS_POISONED)
+          need_red_zone_before =
+            (NULL == __asan_region_is_poisoned (pool->memory
+                                                + alg_start
+                                                - _MHD_RED_ZONE_SIZE,
+                                                _MHD_RED_ZONE_SIZE));
+#elif defined(HAVE___ASAN_ADDRESS_IS_POISONED)
+          need_red_zone_before =
+            (0 == __asan_address_is_poisoned (pool->memory + alg_start - 1));
+#else  /* ! HAVE___ASAN_ADDRESS_IS_POISONED */
+          need_red_zone_before = true; /* Unknown, assume new red zone needed */
+#endif /* ! HAVE___ASAN_ADDRESS_IS_POISONED */
+          if (need_red_zone_before)
+          {
+            _MHD_POISON_MEMORY (pool->memory + alg_start, _MHD_RED_ZONE_SIZE);
+            alg_start += _MHD_RED_ZONE_SIZE;
+          }
+        }
+#endif /* MHD_ASAN_POISON_ACTIVE */
+        mhd_assert (alg_start <= pool->pos);
+        mhd_assert (alg_start == ROUND_TO_ALIGN (alg_start));
+        pool->pos = alg_start;
+      }
     }
-  if (asize <= old_size)
-    return old;                 /* cannot shrink, no need to move */
-  if ((pool->pos + asize >= pool->pos) &&
-      (pool->pos + asize <= pool->end))
+    else
     {
-      /* fits */
-      ret = &pool->memory[pool->pos];
-      memcpy (ret, old, old_size);
-      pool->pos += asize;
-      return ret;
+      /* Allocated "from the end" block. */
+      /* The size and the pointers of such block should not be manipulated by
+         MHD code (block split is disallowed). */
+      mhd_assert (block_offset >= pool->end);
+      mhd_assert (ROUND_TO_ALIGN (block_offset) == block_offset);
+      if (block_offset == pool->end)
+      {
+        /* The last allocated block, return deallocated block to the pool */
+        const size_t alg_end =
+          ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size);
+        pool->end = alg_end;
+      }
     }
-  /* does not fit */
-  return NULL;
+  }
 }
 
 
 /**
  * Clear all entries from the memory pool except
- * for @a keep of the given @a size.
+ * for @a keep of the given @a copy_bytes.  The pointer
+ * returned should be a buffer of @a new_size where
+ * the first @a copy_bytes are from @a keep.
  *
  * @param pool memory pool to use for the operation
  * @param keep pointer to the entry to keep (maybe NULL)
- * @param size how many bytes need to be kept at this address
+ * @param copy_bytes how many bytes need to be kept at this address
+ * @param new_size how many bytes should the allocation we return have?
+ *                 (should be larger or equal to @a copy_bytes)
  * @return addr new address of @a keep (if it had to change)
  */
 void *
 MHD_pool_reset (struct MemoryPool *pool,
-		void *keep,
-		size_t size)
+                void *keep,
+                size_t copy_bytes,
+                size_t new_size)
 {
-  if (NULL != keep)
+  mhd_assert (pool->end >= pool->pos);
+  mhd_assert (pool->size >= pool->end - pool->pos);
+  mhd_assert (copy_bytes <= new_size);
+  mhd_assert (copy_bytes <= pool->size);
+  mhd_assert (keep != NULL || copy_bytes == 0);
+  mhd_assert (keep == NULL || mp_ptr_le_ (pool->memory, keep));
+  /* (keep == NULL || pool->memory + pool->size >= (uint8_t*) keep + copy_bytes) */
+  mhd_assert ((keep == NULL) || \
+              (pool->size >= mp_ptr_diff_ (keep, pool->memory) + copy_bytes));
+#if defined(MHD_ASAN_POISON_ACTIVE) && defined(HAVE___ASAN_REGION_IS_POISONED)
+  mhd_assert (NULL == __asan_region_is_poisoned (keep, copy_bytes));
+#endif /* MHD_ASAN_POISON_ACTIVE && HAVE___ASAN_REGION_IS_POISONED */
+  _MHD_UNPOISON_MEMORY (pool->memory, new_size);
+  if ( (NULL != keep) &&
+       (keep != pool->memory) )
+  {
+    if (0 != copy_bytes)
+      memmove (pool->memory,
+               keep,
+               copy_bytes);
+  }
+  /* technically not needed, but safer to zero out */
+  if (pool->size > copy_bytes)
+  {
+    size_t to_zero;   /** Size of area to zero-out */
+
+    to_zero = pool->size - copy_bytes;
+    _MHD_UNPOISON_MEMORY (pool->memory + copy_bytes, to_zero);
+#ifdef _WIN32
+    if (pool->is_mmap)
     {
-      if (keep != pool->memory)
-        {
-          memmove (pool->memory, keep, size);
-          keep = pool->memory;
-        }
+      size_t to_recommit;     /** Size of decommitted and re-committed area. */
+      uint8_t *recommit_addr;
+      /* Round down to page size */
+      to_recommit = to_zero - to_zero % MHD_sys_page_size_;
+      recommit_addr = pool->memory + pool->size - to_recommit;
+
+      /* De-committing and re-committing again clear memory and make
+       * pages free / available for other needs until accessed. */
+      if (VirtualFree (recommit_addr,
+                       to_recommit,
+                       MEM_DECOMMIT))
+      {
+        to_zero -= to_recommit;
+
+        if (recommit_addr != VirtualAlloc (recommit_addr,
+                                           to_recommit,
+                                           MEM_COMMIT,
+                                           PAGE_READWRITE))
+          abort ();      /* Serious error, must never happen */
+      }
     }
+#endif /* _WIN32 */
+    memset (&pool->memory[copy_bytes],
+            0,
+            to_zero);
+  }
+  pool->pos = ROUND_TO_ALIGN_PLUS_RED_ZONE (new_size);
   pool->end = pool->size;
-  memset (&pool->memory[size],
-	  0,
-	  pool->size - size);
-  if (NULL != keep)
-    pool->pos = ROUND_TO_ALIGN(size);
-  return keep;
+  _MHD_POISON_MEMORY (((uint8_t *) pool->memory) + new_size, \
+                      pool->size - new_size);
+  return pool->memory;
 }
 
 
diff --git a/src/microhttpd/memorypool.h b/src/microhttpd/memorypool.h
index 4db952a..49bbcbe 100644
--- a/src/microhttpd/memorypool.h
+++ b/src/microhttpd/memorypool.h
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007, 2009 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2007--2019 Daniel Pittman, Christian Grothoff and
+     Karlson2k (Evgeny Grin)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -23,12 +24,19 @@
  *        for each connection and bounding memory use for each
  *        request
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #ifndef MEMORYPOOL_H
 #define MEMORYPOOL_H
 
-#include "internal.h"
+#include "mhd_options.h"
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif /* HAVE_STDDEF_H */
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
 
 /**
  * Opaque handle for a memory pool.
@@ -37,6 +45,12 @@
  */
 struct MemoryPool;
 
+/**
+ * Initialize values for memory pools
+ */
+void
+MHD_init_mem_pools_ (void);
+
 
 /**
  * Create a memory pool.
@@ -62,7 +76,7 @@
  *
  * @param pool memory pool to use for the operation
  * @param size number of bytes to allocate
- * @param from_end allocate from end of pool (set to MHD_YES);
+ * @param from_end allocate from end of pool (set to 'true');
  *        use this for small, persistent allocations that
  *        will never be reallocated
  * @return NULL if the pool cannot support size more
@@ -70,45 +84,104 @@
  */
 void *
 MHD_pool_allocate (struct MemoryPool *pool,
-		   size_t size, int from_end);
+                   size_t size,
+                   bool from_end);
+
+
+/**
+ * Try to allocate @a size bytes memory area from the @a pool.
+ *
+ * If allocation fails, @a required_bytes is updated with size required to be
+ * freed in the @a pool from rellocatable area to allocate requested number
+ * of bytes.
+ * Allocated memory area is always not rellocatable ("from end").
+ *
+ * @param pool memory pool to use for the operation
+ * @param size the size of memory in bytes to allocate
+ * @param[out] required_bytes the pointer to variable to be updated with
+ *                            the size of the required additional free
+ *                            memory area, not updated if function succeed.
+ *                            Cannot be NULL.
+ * @return the pointer to allocated memory area if succeed,
+ *         NULL if the pool doesn't have enough space, required_bytes is updated
+ *         with amount of space needed to be freed in rellocatable area or
+ *         set to SIZE_MAX if requested size is too large for the pool.
+ */
+void *
+MHD_pool_try_alloc (struct MemoryPool *pool,
+                    size_t size,
+                    size_t *required_bytes);
 
 
 /**
  * Reallocate a block of memory obtained from the pool.
  * This is particularly efficient when growing or
  * shrinking the block that was last (re)allocated.
- * If the given block is not the most recenlty
+ * If the given block is not the most recently
  * (re)allocated block, the memory of the previous
- * allocation may be leaked until the pool is
- * destroyed (and copying the data maybe required).
+ * allocation may be not released until the pool is
+ * destroyed or reset.
  *
  * @param pool memory pool to use for the operation
  * @param old the existing block
  * @param old_size the size of the existing block
  * @param new_size the new size of the block
  * @return new address of the block, or
- *         NULL if the pool cannot support new_size
- *         bytes (old continues to be valid for old_size)
+ *         NULL if the pool cannot support @a new_size
+ *         bytes (old continues to be valid for @a old_size)
  */
 void *
 MHD_pool_reallocate (struct MemoryPool *pool,
-		     void *old,
-		     size_t old_size,
-		     size_t new_size);
+                     void *old,
+                     size_t old_size,
+                     size_t new_size);
+
+
+/**
+ * Check how much memory is left in the @a pool
+ *
+ * @param pool pool to check
+ * @return number of bytes still available in @a pool
+ */
+size_t
+MHD_pool_get_free (struct MemoryPool *pool);
+
+
+/**
+ * Deallocate a block of memory obtained from the pool.
+ *
+ * If the given block is not the most recently
+ * (re)allocated block, the memory of the this block
+ * allocation may be not released until the pool is
+ * destroyed or reset.
+ *
+ * @param pool memory pool to use for the operation
+ * @param block the allocated block, the NULL is tolerated
+ * @param block_size the size of the allocated block
+ */
+void
+MHD_pool_deallocate (struct MemoryPool *pool,
+                     void *block,
+                     size_t block_size);
 
 
 /**
  * Clear all entries from the memory pool except
- * for "keep" of the given "size".
+ * for @a keep of the given @a copy_bytes.  The pointer
+ * returned should be a buffer of @a new_size where
+ * the first @a copy_bytes are from @a keep.
  *
  * @param pool memory pool to use for the operation
  * @param keep pointer to the entry to keep (maybe NULL)
- * @param size how many bytes need to be kept at this address
- * @return addr new address of "keep" (if it had to change)
+ * @param copy_bytes how many bytes need to be kept at this address
+ * @param new_size how many bytes should the allocation we return have?
+ *                 (should be larger or equal to @a copy_bytes)
+ * @return addr new address of @a keep (if it had to change)
  */
 void *
 MHD_pool_reset (struct MemoryPool *pool,
-		void *keep,
-		size_t size);
+                void *keep,
+                size_t copy_bytes,
+                size_t new_size);
 
 #endif
diff --git a/src/microhttpd/mhd_align.h b/src/microhttpd/mhd_align.h
new file mode 100644
index 0000000..46fcb0b
--- /dev/null
+++ b/src/microhttpd/mhd_align.h
@@ -0,0 +1,97 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2021 Karlson2k (Evgeny Grin)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/mhd_align.h
+ * @brief  types alignment macros
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_ALIGN_H
+#define MHD_ALIGN_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+
+#ifdef HAVE_C_ALIGNOF
+#ifdef HAVE_STDALIGN_H
+#include <stdalign.h>
+#endif /* HAVE_STDALIGN_H */
+#define _MHD_ALIGNOF(type) alignof(type)
+#endif /* HAVE_C_ALIGNOF */
+
+#ifndef _MHD_ALIGNOF
+#if defined(_MSC_VER) && ! defined(__clang__) && _MSC_VER >= 1700
+#define _MHD_ALIGNOF(type) __alignof(type)
+#endif /* _MSC_VER >= 1700 */
+#endif /* !_MHD_ALIGNOF */
+
+#ifdef _MHD_ALIGNOF
+#if (defined(__GNUC__) && __GNUC__ < 4 && __GNUC_MINOR__ < 9 && \
+  ! defined(__clang__)) || \
+  (defined(__clang__) && __clang_major__ < 8) || \
+  (defined(__clang__) && __clang_major__ < 11 && \
+  defined(__apple_build_version__))
+/* GCC before 4.9 and clang before 8.0 have incorrect implementation of 'alignof()'
+   which returns preferred alignment instead of minimal required alignment */
+#define _MHD_ALIGNOF_UNRELIABLE 1
+#endif
+
+#if defined(_MSC_VER) && ! defined(__clang__) && _MSC_VER < 1900
+/* MSVC has the same problem as old GCC versions:
+   '__alignof()' may return "preferred" alignment instead of "required". */
+#define _MHD_ALIGNOF_UNRELIABLE 1
+#endif /* _MSC_VER < 1900 */
+#endif /* _MHD_ALIGNOF */
+
+
+#ifdef offsetof
+#define _MHD_OFFSETOF(strct, membr) offsetof(strct, membr)
+#else  /* ! offsetof */
+#define _MHD_OFFSETOF(strct, membr) (size_t)(((char*)&(((strct*)0)->membr)) - \
+                                     ((char*)((strct*)0)))
+#endif /* ! offsetof */
+
+/* Provide a limited set of alignment macros */
+/* The set could be extended as needed */
+#if defined(_MHD_ALIGNOF) && ! defined(_MHD_ALIGNOF_UNRELIABLE)
+#define _MHD_UINT32_ALIGN _MHD_ALIGNOF(uint32_t)
+#define _MHD_UINT64_ALIGN _MHD_ALIGNOF(uint64_t)
+#else  /* ! _MHD_ALIGNOF */
+struct _mhd_dummy_uint32_offset_test
+{
+  char dummy;
+  uint32_t ui32;
+};
+#define _MHD_UINT32_ALIGN \
+  _MHD_OFFSETOF(struct _mhd_dummy_uint32_offset_test, ui32)
+
+struct _mhd_dummy_uint64_offset_test
+{
+  char dummy;
+  uint64_t ui64;
+};
+#define _MHD_UINT64_ALIGN \
+  _MHD_OFFSETOF(struct _mhd_dummy_uint64_offset_test, ui64)
+#endif /* ! _MHD_ALIGNOF */
+
+#endif /* ! MHD_ALIGN_H */
diff --git a/src/microhttpd/mhd_assert.h b/src/microhttpd/mhd_assert.h
new file mode 100644
index 0000000..b24ce93
--- /dev/null
+++ b/src/microhttpd/mhd_assert.h
@@ -0,0 +1,63 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017-2021 Karlson2k (Evgeny Grin)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/mhd_assert.h
+ * @brief  macros for mhd_assert()
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+/* Unlike POSIX version of 'assert.h', MHD version of 'assert' header
+ * does not allow multiple redefinition of 'mhd_assert' macro within single
+ * source file. */
+#ifndef MHD_ASSERT_H
+#define MHD_ASSERT_H 1
+
+#include "mhd_options.h"
+
+#if ! defined(_DEBUG) && ! defined(NDEBUG)
+#ifndef DEBUG /* Used by some toolchains */
+#define NDEBUG 1 /* Use NDEBUG by default */
+#else  /* DEBUG */
+#define _DEBUG 1
+#endif /* DEBUG */
+#endif /* !_DEBUG && !NDEBUG */
+#if defined(_DEBUG) && defined(NDEBUG)
+#error Both _DEBUG and NDEBUG are defined
+#endif /* _DEBUG && NDEBUG */
+#ifdef NDEBUG
+#  define mhd_assert(ignore) ((void) 0)
+#else  /* _DEBUG */
+#  ifdef HAVE_ASSERT
+#    include <assert.h>
+#    define mhd_assert(CHK) assert (CHK)
+#  else  /* ! HAVE_ASSERT */
+#    include <stdio.h>
+#    include <stdlib.h>
+#    define mhd_assert(CHK) \
+  do { \
+    if (! (CHK)) { \
+      fprintf (stderr, "%s:%u Assertion failed: %s\nProgram aborted.\n", \
+               __FILE__, (unsigned) __LINE__, #CHK); \
+      fflush (stderr); abort (); } \
+  } while (0)
+#  endif /* ! HAVE_ASSERT */
+#endif /* _DEBUG */
+
+#endif /* ! MHD_ASSERT_H */
diff --git a/src/microhttpd/mhd_bithelpers.h b/src/microhttpd/mhd_bithelpers.h
new file mode 100644
index 0000000..94f4e1a
--- /dev/null
+++ b/src/microhttpd/mhd_bithelpers.h
@@ -0,0 +1,398 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2019-2021 Karlson2k (Evgeny Grin)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/mhd_bithelpers.h
+ * @brief  macros for bits manipulations
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_BITHELPERS_H
+#define MHD_BITHELPERS_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \
+  defined(__OPTIMIZE__)))
+/* Declarations for VC & Clang/C2 built-ins */
+#include <intrin.h>
+#endif /* _MSC_FULL_VER  */
+#include "mhd_byteorder.h"
+#if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN || _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#include "mhd_align.h"
+#endif /* _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN ||
+          _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */
+
+#ifndef __has_builtin
+/* Avoid precompiler errors with non-clang */
+#  define __has_builtin(x) 0
+#  define _MHD_has_builtin_dummy 1
+#endif
+
+
+#ifdef MHD_HAVE___BUILTIN_BSWAP32
+#define _MHD_BYTES_SWAP32(value32)  \
+  ((uint32_t) __builtin_bswap32 ((uint32_t) value32))
+#elif defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \
+  defined(__OPTIMIZE__)))
+/* Clang/C2 may not inline this function if optimizations are turned off. */
+#ifndef __clang__
+#pragma intrinsic(_byteswap_ulong)
+#endif /* ! __clang__ */
+#define _MHD_BYTES_SWAP32(value32)  \
+  ((uint32_t) _byteswap_ulong ((uint32_t) value32))
+#elif __has_builtin (__builtin_bswap32)
+#define _MHD_BYTES_SWAP32(value32)  \
+  ((uint32_t) __builtin_bswap32 ((uint32_t) value32))
+#else  /* ! __has_builtin(__builtin_bswap32) */
+#define _MHD_BYTES_SWAP32(value32)                                  \
+  ( (((uint32_t) (value32)) << 24)                                  \
+    | ((((uint32_t) (value32)) & ((uint32_t) 0x0000FF00)) << 8)     \
+    | ((((uint32_t) (value32)) & ((uint32_t) 0x00FF0000)) >> 8)     \
+    | (((uint32_t) (value32))                           >> 24) )
+#endif /* ! __has_builtin(__builtin_bswap32) */
+
+#ifdef MHD_HAVE___BUILTIN_BSWAP64
+#define _MHD_BYTES_SWAP64(value64) \
+  ((uint64_t) __builtin_bswap64 ((uint64_t) value64))
+#elif defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \
+  defined(__OPTIMIZE__)))
+/* Clang/C2 may not inline this function if optimizations are turned off. */
+#ifndef __clang__
+#pragma intrinsic(_byteswap_uint64)
+#endif /* ! __clang__ */
+#define _MHD_BYTES_SWAP64(value64)  \
+  ((uint64_t) _byteswap_uint64 ((uint64_t) value64))
+#elif __has_builtin (__builtin_bswap64)
+#define _MHD_BYTES_SWAP64(value64) \
+  ((uint64_t) __builtin_bswap64 ((uint64_t) value64))
+#else  /* ! __has_builtin(__builtin_bswap64) */
+#define _MHD_BYTES_SWAP64(value64)                                          \
+  ( (((uint64_t) (value64)) << 56)                                          \
+    | ((((uint64_t) (value64)) & ((uint64_t) 0x000000000000FF00)) << 40)    \
+    | ((((uint64_t) (value64)) & ((uint64_t) 0x0000000000FF0000)) << 24)    \
+    | ((((uint64_t) (value64)) & ((uint64_t) 0x00000000FF000000)) << 8)     \
+    | ((((uint64_t) (value64)) & ((uint64_t) 0x000000FF00000000)) >> 8)     \
+    | ((((uint64_t) (value64)) & ((uint64_t) 0x0000FF0000000000)) >> 24)    \
+    | ((((uint64_t) (value64)) & ((uint64_t) 0x00FF000000000000)) >> 40)    \
+    | (((uint64_t) (value64))                                   >> 56) )
+#endif /* ! __has_builtin(__builtin_bswap64) */
+
+
+/* _MHD_PUT_64BIT_LE (addr, value64)
+ * put native-endian 64-bit value64 to addr
+ * in little-endian mode.
+ */
+/* Slow version that works with unaligned addr and with any bytes order */
+#define _MHD_PUT_64BIT_LE_SLOW(addr, value64) do {                       \
+    ((uint8_t*) (addr))[0] = (uint8_t) ((uint64_t) (value64));           \
+    ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 8);    \
+    ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 16);   \
+    ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 24);   \
+    ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 32);   \
+    ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 40);   \
+    ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 48);   \
+    ((uint8_t*) (addr))[7] = (uint8_t) (((uint64_t) (value64)) >> 56);   \
+} while (0)
+#if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_PUT_64BIT_LE(addr, value64)             \
+  ((*(uint64_t*) (addr)) = (uint64_t) (value64))
+#elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_PUT_64BIT_LE(addr, value64)             \
+  ((*(uint64_t*) (addr)) = _MHD_BYTES_SWAP64 (value64))
+#else  /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_PUT_64BIT_LE(addr, value64) do {                            \
+    ((uint8_t*) (addr))[0] = (uint8_t) ((uint64_t) (value64));           \
+    ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 8);    \
+    ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 16);   \
+    ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 24);   \
+    ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 32);   \
+    ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 40);   \
+    ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 48);   \
+    ((uint8_t*) (addr))[7] = (uint8_t) (((uint64_t) (value64)) >> 56);   \
+} while (0)
+/* Indicate that _MHD_PUT_64BIT_LE does not need aligned pointer */
+#define _MHD_PUT_64BIT_LE_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */
+
+/* Put result safely to unaligned address */
+_MHD_static_inline void
+_MHD_PUT_64BIT_LE_SAFE (void *dst, uint64_t value)
+{
+#ifndef _MHD_PUT_64BIT_LE_UNALIGNED
+  if (0 != ((uintptr_t) dst) % (_MHD_UINT64_ALIGN))
+    _MHD_PUT_64BIT_LE_SLOW (dst, value);
+  else
+#endif /* ! _MHD_PUT_64BIT_LE_UNALIGNED */
+  _MHD_PUT_64BIT_LE (dst, value);
+}
+
+
+/* _MHD_PUT_32BIT_LE (addr, value32)
+ * put native-endian 32-bit value32 to addr
+ * in little-endian mode.
+ */
+#if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_PUT_32BIT_LE(addr,value32)             \
+  ((*(uint32_t*) (addr)) = (uint32_t) (value32))
+#elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_PUT_32BIT_LE(addr, value32)            \
+  ((*(uint32_t*) (addr)) = _MHD_BYTES_SWAP32 (value32))
+#else  /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_PUT_32BIT_LE(addr, value32) do {                            \
+    ((uint8_t*) (addr))[0] = (uint8_t) ((uint32_t) (value32));           \
+    ((uint8_t*) (addr))[1] = (uint8_t) (((uint32_t) (value32)) >> 8);    \
+    ((uint8_t*) (addr))[2] = (uint8_t) (((uint32_t) (value32)) >> 16);   \
+    ((uint8_t*) (addr))[3] = (uint8_t) (((uint32_t) (value32)) >> 24);   \
+} while (0)
+/* Indicate that _MHD_PUT_32BIT_LE does not need aligned pointer */
+#define _MHD_PUT_32BIT_LE_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */
+
+/* _MHD_GET_32BIT_LE (addr)
+ * get little-endian 32-bit value storied at addr
+ * and return it in native-endian mode.
+ */
+#if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_GET_32BIT_LE(addr)             \
+  (*(const uint32_t*) (addr))
+#elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_GET_32BIT_LE(addr)             \
+  _MHD_BYTES_SWAP32 (*(const uint32_t*) (addr))
+#else  /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_GET_32BIT_LE(addr)                           \
+  ( ( (uint32_t) (((const uint8_t*) addr)[0]))            \
+    | (((uint32_t) (((const uint8_t*) addr)[1])) << 8)    \
+    | (((uint32_t) (((const uint8_t*) addr)[2])) << 16)   \
+    | (((uint32_t) (((const uint8_t*) addr)[3])) << 24) )
+/* Indicate that _MHD_GET_32BIT_LE does not need aligned pointer */
+#define _MHD_GET_32BIT_LE_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */
+
+
+/* _MHD_PUT_64BIT_BE (addr, value64)
+ * put native-endian 64-bit value64 to addr
+ * in big-endian mode.
+ */
+/* Slow version that works with unaligned addr and with any bytes order */
+#define _MHD_PUT_64BIT_BE_SLOW(addr, value64) do {                       \
+    ((uint8_t*) (addr))[7] = (uint8_t) ((uint64_t) (value64));           \
+    ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 8);    \
+    ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 16);   \
+    ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 24);   \
+    ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 32);   \
+    ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 40);   \
+    ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 48);   \
+    ((uint8_t*) (addr))[0] = (uint8_t) (((uint64_t) (value64)) >> 56);   \
+} while (0)
+#if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_PUT_64BIT_BE(addr, value64)             \
+  ((*(uint64_t*) (addr)) = (uint64_t) (value64))
+#elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_PUT_64BIT_BE(addr, value64)             \
+  ((*(uint64_t*) (addr)) = _MHD_BYTES_SWAP64 (value64))
+#else  /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_PUT_64BIT_BE(addr, value64) _MHD_PUT_64BIT_BE_SLOW(addr, value64)
+/* Indicate that _MHD_PUT_64BIT_BE does not need aligned pointer */
+#define _MHD_PUT_64BIT_BE_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+
+/* Put result safely to unaligned address */
+_MHD_static_inline void
+_MHD_PUT_64BIT_BE_SAFE (void *dst, uint64_t value)
+{
+#ifndef _MHD_PUT_64BIT_BE_UNALIGNED
+  if (0 != ((uintptr_t) dst) % (_MHD_UINT64_ALIGN))
+    _MHD_PUT_64BIT_BE_SLOW (dst, value);
+  else
+#endif /* ! _MHD_PUT_64BIT_BE_UNALIGNED */
+  _MHD_PUT_64BIT_BE (dst, value);
+}
+
+
+/* _MHD_GET_64BIT_BE (addr)
+ * load 64-bit value located at addr in big endian mode.
+ */
+#if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_GET_64BIT_BE(addr)             \
+  (*(const uint64_t*) (addr))
+#elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_GET_64BIT_BE(addr)             \
+  _MHD_BYTES_SWAP64 (*(const uint64_t*) (addr))
+#else  /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_GET_64BIT_BE(addr)                           \
+  (   (((uint64_t) (((const uint8_t*) addr)[0])) << 56)   \
+    | (((uint64_t) (((const uint8_t*) addr)[1])) << 48)   \
+    | (((uint64_t) (((const uint8_t*) addr)[2])) << 40)   \
+    | (((uint64_t) (((const uint8_t*) addr)[3])) << 32)   \
+    | (((uint64_t) (((const uint8_t*) addr)[4])) << 24)   \
+    | (((uint64_t) (((const uint8_t*) addr)[5])) << 16)   \
+    | (((uint64_t) (((const uint8_t*) addr)[6])) << 8)    \
+    | ((uint64_t)  (((const uint8_t*) addr)[7])) )
+/* Indicate that _MHD_GET_64BIT_BE does not need aligned pointer */
+#define _MHD_GET_64BIT_BE_ALLOW_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+
+
+/* _MHD_PUT_32BIT_BE (addr, value32)
+ * put native-endian 32-bit value32 to addr
+ * in big-endian mode.
+ */
+#if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_PUT_32BIT_BE(addr, value32)             \
+  ((*(uint32_t*) (addr)) = (uint32_t) (value32))
+#elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_PUT_32BIT_BE(addr, value32)             \
+  ((*(uint32_t*) (addr)) = _MHD_BYTES_SWAP32 (value32))
+#else  /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_PUT_32BIT_BE(addr, value32) do {                            \
+    ((uint8_t*) (addr))[3] = (uint8_t) ((uint32_t) (value32));           \
+    ((uint8_t*) (addr))[2] = (uint8_t) (((uint32_t) (value32)) >> 8);    \
+    ((uint8_t*) (addr))[1] = (uint8_t) (((uint32_t) (value32)) >> 16);   \
+    ((uint8_t*) (addr))[0] = (uint8_t) (((uint32_t) (value32)) >> 24);   \
+} while (0)
+/* Indicate that _MHD_PUT_32BIT_BE does not need aligned pointer */
+#define _MHD_PUT_32BIT_BE_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+
+/* _MHD_GET_32BIT_BE (addr)
+ * get big-endian 32-bit value storied at addr
+ * and return it in native-endian mode.
+ */
+#if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#define _MHD_GET_32BIT_BE(addr)             \
+  (*(const uint32_t*) (addr))
+#elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN
+#define _MHD_GET_32BIT_BE(addr)             \
+  _MHD_BYTES_SWAP32 (*(const uint32_t*) (addr))
+#else  /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+/* Endianness was not detected or non-standard like PDP-endian */
+#define _MHD_GET_32BIT_BE(addr)                           \
+  ( (((uint32_t) (((const uint8_t*) addr)[0])) << 24)     \
+    | (((uint32_t) (((const uint8_t*) addr)[1])) << 16)   \
+    | (((uint32_t) (((const uint8_t*) addr)[2])) << 8)    \
+    | ((uint32_t) (((const uint8_t*) addr)[3])) )
+/* Indicate that _MHD_GET_32BIT_BE does not need aligned pointer */
+#define _MHD_GET_32BIT_BE_UNALIGNED 1
+#endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */
+
+
+/**
+ * Rotate right 32-bit value by number of bits.
+ * bits parameter must be more than zero and must be less than 32.
+ */
+#if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \
+  defined(__OPTIMIZE__)))
+/* Clang/C2 do not inline this function if optimizations are turned off. */
+#ifndef __clang__
+#pragma intrinsic(_rotr)
+#endif /* ! __clang__ */
+#define _MHD_ROTR32(value32, bits) \
+  ((uint32_t) _rotr ((uint32_t) (value32),(bits)))
+#elif __has_builtin (__builtin_rotateright32)
+#define _MHD_ROTR32(value32, bits) \
+  ((uint32_t) __builtin_rotateright32 ((value32), (bits)))
+#else  /* ! __builtin_rotateright32 */
+_MHD_static_inline uint32_t
+_MHD_ROTR32 (uint32_t value32, int bits)
+{
+  bits %= 32;
+  if (0 == bits)
+    return value32;
+  /* Defined in form which modern compiler could optimize. */
+  return (value32 >> bits) | (value32 << (32 - bits));
+}
+
+
+#endif /* ! __builtin_rotateright32 */
+
+
+/**
+ * Rotate left 32-bit value by number of bits.
+ * bits parameter must be more than zero and must be less than 32.
+ */
+#if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \
+  defined(__OPTIMIZE__)))
+/* Clang/C2 do not inline this function if optimizations are turned off. */
+#ifndef __clang__
+#pragma intrinsic(_rotl)
+#endif /* ! __clang__ */
+#define _MHD_ROTL32(value32, bits) \
+  ((uint32_t) _rotl ((uint32_t) (value32),(bits)))
+#elif __has_builtin (__builtin_rotateleft32)
+#define _MHD_ROTL32(value32, bits) \
+  ((uint32_t) __builtin_rotateleft32 ((value32), (bits)))
+#else  /* ! __builtin_rotateleft32 */
+_MHD_static_inline uint32_t
+_MHD_ROTL32 (uint32_t value32, int bits)
+{
+  bits %= 32;
+  if (0 == bits)
+    return value32;
+  /* Defined in form which modern compiler could optimize. */
+  return (value32 << bits) | (value32 >> (32 - bits));
+}
+
+
+#endif /* ! __builtin_rotateleft32 */
+
+
+/**
+ * Rotate right 64-bit value by number of bits.
+ * bits parameter must be more than zero and must be less than 64.
+ */
+#if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \
+  defined(__OPTIMIZE__)))
+/* Clang/C2 do not inline this function if optimisations are turned off. */
+#ifndef __clang__
+#pragma intrinsic(_rotr64)
+#endif /* ! __clang__ */
+#define _MHD_ROTR64(value64, bits) \
+  ((uint64_t) _rotr64 ((uint64_t) (value64),(bits)))
+#elif __has_builtin (__builtin_rotateright64)
+#define _MHD_ROTR64(value64, bits) \
+  ((uint64_t) __builtin_rotateright64 ((value64), (bits)))
+#else  /* ! __builtin_rotateright64 */
+_MHD_static_inline uint64_t
+_MHD_ROTR64 (uint64_t value64, int bits)
+{
+  bits %= 64;
+  if (0 == bits)
+    return value64;
+  /* Defined in form which modern compiler could optimise. */
+  return (value64 >> bits) | (value64 << (64 - bits));
+}
+
+
+#endif /* ! __builtin_rotateright64 */
+
+
+#ifdef _MHD_has_builtin_dummy
+/* Remove macro function replacement to avoid misdetection in files which
+ * include this header */
+#  undef __has_builtin
+#endif
+
+#endif /* ! MHD_BITHELPERS_H */
diff --git a/src/microhttpd/mhd_byteorder.h b/src/microhttpd/mhd_byteorder.h
new file mode 100644
index 0000000..4ef095d
--- /dev/null
+++ b/src/microhttpd/mhd_byteorder.h
@@ -0,0 +1,169 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/mhd_byteorder.h
+ * @brief  macro definitions for host byte order
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_BYTEORDER_H
+#define MHD_BYTEORDER_H
+
+#include "mhd_options.h"
+
+#include <stdint.h>
+
+#ifdef HAVE_ENDIAN_H
+#include <endian.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef HAVE_MACHINE_ENDIAN_H
+#include <machine/endian.h>
+#endif
+
+#ifdef HAVE_SYS_ENDIAN_H
+#include <sys/endian.h>
+#endif
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#ifdef HAVE_SYS_BYTEORDER_H
+#include <sys/byteorder.h>
+#endif
+
+#ifdef HAVE_SYS_MACHINE_H
+#include <sys/machine.h>
+#endif
+
+#ifdef HAVE_MACHINE_PARAM_H
+#include <machine/param.h>
+#endif
+
+#ifdef HAVE_SYS_ISA_DEFS_H
+#include <sys/isa_defs.h>
+#endif
+
+#define _MHD_BIG_ENDIAN 1234
+#define _MHD_LITTLE_ENDIAN 4321
+#define _MHD_PDP_ENDIAN 2143
+
+#if defined(__BYTE_ORDER__)
+#if defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == \
+  __ORDER_LITTLE_ENDIAN__
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__ORDER_PDP_ENDIAN__) && __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ */
+#elif defined(__BYTE_ORDER)
+#if defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__PDP_ENDIAN) && __BYTE_ORDER == __PDP_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* __BYTE_ORDER == __PDP_ENDIAN */
+#elif defined(BYTE_ORDER)
+#if defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(LITTLE_ENDIAN) && BYTE_ORDER == LITTLE_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(PDP_ENDIAN) && BYTE_ORDER == PDP_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* __BYTE_ORDER == _PDP_ENDIAN */
+#elif defined(_BYTE_ORDER)
+#if defined(_BIG_ENDIAN) && _BYTE_ORDER == _BIG_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(_LITTLE_ENDIAN) && _BYTE_ORDER == _LITTLE_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(_PDP_ENDIAN) && _BYTE_ORDER == _PDP_ENDIAN
+#define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN
+#endif /* _BYTE_ORDER == _PDP_ENDIAN */
+#endif /* _BYTE_ORDER */
+
+#ifndef _MHD_BYTE_ORDER
+/* Byte order specification didn't detected in system headers */
+/* Try some guessing */
+
+#if   (defined(__BIG_ENDIAN__) && ! defined(__LITTLE_ENDIAN__)) || \
+  (defined(_BIG_ENDIAN) && ! defined(_LITTLE_ENDIAN))
+/* Seems that we are on big endian platform */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif (defined(__LITTLE_ENDIAN__) && ! defined(__BIG_ENDIAN__)) || \
+  (defined(_LITTLE_ENDIAN) && ! defined(_BIG_ENDIAN))
+/* Seems that we are on little endian platform */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || \
+  defined(__x86_64) || \
+  defined(_M_X64) || defined(_M_AMD64) || defined(i386) || defined(__i386) || \
+  defined(__i386__) || defined(__i486__) || defined(__i586__) || \
+  defined(__i686__) || \
+  defined(_M_IX86) || defined(_X86_) || defined(__THW_INTEL__)
+/* x86 family is little endian */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
+  defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__)
+/* Looks like we are on ARM/MIPS in big endian mode */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \
+  defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)
+/* Looks like we are on ARM/MIPS in little endian mode */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(__m68k__) || defined(M68000) || defined(__hppa__) || \
+  defined(__hppa) || \
+  defined(__HPPA__) || defined(__370__) || defined(__THW_370__) || \
+  defined(__s390__) || defined(__s390x__) || defined(__SYSC_ZARCH__)
+/* Looks like we are on big endian platform */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#elif defined(__ia64__) || defined(_IA64) || defined(__IA64__) || \
+  defined(__ia64) || \
+  defined(_M_IA64) || defined(__itanium__) || defined(__bfin__) || \
+  defined(__BFIN__) || defined(bfin) || defined(BFIN)
+/* Looks like we are on little endian platform */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(_WIN32)
+/* W32 is always little endian on all platforms */
+#define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN
+#elif defined(WORDS_BIGENDIAN)
+/* Use byte order detected by configure */
+#define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN
+#endif /* _WIN32 */
+
+#endif /* !_MHD_BYTE_ORDER */
+
+#ifdef _MHD_BYTE_ORDER
+/* Some safety checks */
+#if defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN
+#error \
+  Configure detected big endian byte order but headers specify different byte order
+#elif ! defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+#error \
+  Configure did not detect big endian byte order but headers specify big endian byte order
+#endif /* !WORDS_BIGENDIAN && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */
+#endif /* _MHD_BYTE_ORDER */
+
+#endif /* !MHD_BYTEORDER_H */
diff --git a/src/microhttpd/mhd_compat.c b/src/microhttpd/mhd_compat.c
new file mode 100644
index 0000000..fd8132a
--- /dev/null
+++ b/src/microhttpd/mhd_compat.c
@@ -0,0 +1,118 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_compat.c
+ * @brief  Implementation of platform missing functions.
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_compat.h"
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#include <stdint.h>
+#include <time.h>
+#ifndef HAVE_SNPRINTF
+#include <stdio.h>
+#include <stdarg.h>
+#endif  /* HAVE_SNPRINTF */
+#endif /* _WIN32  && !__CYGWIN__ */
+
+#ifndef HAVE_CALLOC
+#include <string.h> /* for memset() */
+#endif /* ! HAVE_CALLOC */
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+
+#ifndef HAVE_SNPRINTF
+/* Emulate snprintf function on W32 */
+int
+W32_snprintf (char *__restrict s,
+              size_t n,
+              const char *__restrict format,
+              ...)
+{
+  int ret;
+  va_list args;
+
+  if ( (0 != n) &&
+       (NULL != s) )
+  {
+    va_start (args,
+              format);
+    ret = _vsnprintf (s,
+                      n,
+                      format,
+                      args);
+    va_end (args);
+    if ((int) n == ret)
+      s[n - 1] = 0;
+    if (ret >= 0)
+      return ret;
+  }
+  va_start (args,
+            format);
+  ret = _vscprintf (format,
+                    args);
+  va_end (args);
+  if ( (0 <= ret) &&
+       (0 != n) &&
+       (NULL == s) )
+    return -1;
+
+  return ret;
+}
+
+
+#endif  /* HAVE_SNPRINTF */
+#endif /* _WIN32  && !__CYGWIN__ */
+
+#ifndef HAVE_CALLOC
+
+#ifdef __has_builtin
+#  if __has_builtin (__builtin_mul_overflow)
+#    define MHD_HAVE_NUL_OVERFLOW 1
+#  endif
+#elif __GNUC__ + 0 >= 5
+#  define MHD_HAVE_NUL_OVERFLOW 1
+#endif /* __GNUC__ >= 5 */
+
+
+void *
+MHD_calloc_ (size_t nelem, size_t elsize)
+{
+  size_t alloc_size;
+  void *ptr;
+#ifdef MHD_HAVE_NUL_OVERFLOW
+  if (__builtin_mul_overflow (nelem, elsize, &alloc_size) || (0 == alloc_size))
+    return NULL;
+#else  /* ! MHD_HAVE_NUL_OVERFLOW */
+  alloc_size = nelem * elsize;
+  if ((0 == alloc_size) || (elsize != alloc_size / nelem))
+    return NULL;
+#endif /* ! MHD_HAVE_NUL_OVERFLOW */
+  ptr = malloc (alloc_size);
+  if (NULL == ptr)
+    return NULL;
+  memset (ptr, 0, alloc_size);
+  return ptr;
+}
+
+
+#endif /* ! HAVE_CALLOC */
diff --git a/src/microhttpd/mhd_compat.h b/src/microhttpd/mhd_compat.h
new file mode 100644
index 0000000..37b9744
--- /dev/null
+++ b/src/microhttpd/mhd_compat.h
@@ -0,0 +1,93 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_compat.h
+ * @brief  Header for platform missing functions.
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Provides compatibility for platforms with some missing
+ * functionality.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ */
+
+#ifndef MHD_COMPAT_H
+#define MHD_COMPAT_H 1
+
+#include "mhd_options.h"
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#ifdef HAVE_STRING_H /* for strerror() */
+#include <string.h>
+#endif /* HAVE_STRING_H */
+
+/* MHD_strerror_ is strerror */
+#define MHD_strerror_(errnum) strerror ((errnum))
+
+/* Platform-independent snprintf name */
+#if defined(HAVE_SNPRINTF)
+#define MHD_snprintf_ snprintf
+#else  /* ! HAVE_SNPRINTF */
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+/* Emulate snprintf function on W32 */
+int W32_snprintf (char *__restrict s, size_t n, const char *__restrict format,
+                  ...);
+
+#define MHD_snprintf_ W32_snprintf
+#else  /* ! _WIN32 || __CYGWIN__ */
+#error \
+  Your platform does not support snprintf() and MHD does not know how to emulate it on your platform.
+#endif /* ! _WIN32 || __CYGWIN__ */
+#endif /* ! HAVE_SNPRINTF */
+
+#ifdef HAVE_RANDOM
+/**
+ * Generate pseudo random number at least 30-bit wide.
+ * @return pseudo random number at least 30-bit wide.
+ */
+#define MHD_random_() random ()
+#else  /* HAVE_RANDOM */
+#ifdef HAVE_RAND
+/**
+ * Generate pseudo random number at least 30-bit wide.
+ * @return pseudo random number at least 30-bit wide.
+ */
+#define MHD_random_() ( (((long) rand ()) << 15) + (long) rand () )
+#endif /* HAVE_RAND */
+#endif /* HAVE_RANDOM */
+
+#ifdef HAVE_CALLOC
+/**
+ * MHD_calloc_ is platform-independent calloc()
+ */
+#define MHD_calloc_(n,s) calloc ((n),(s))
+#else  /* ! HAVE_CALLOC */
+/**
+ * MHD_calloc_ is platform-independent calloc()
+ */
+void *MHD_calloc_ (size_t nelem, size_t elsize);
+
+#endif /* ! HAVE_CALLOC */
+
+#endif /* MHD_COMPAT_H */
diff --git a/src/microhttpd/mhd_itc.c b/src/microhttpd/mhd_itc.c
new file mode 100644
index 0000000..ef5e49b
--- /dev/null
+++ b/src/microhttpd/mhd_itc.c
@@ -0,0 +1,72 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_itc.c
+ * @brief  Implementation of inter-thread communication functions
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+
+#include "mhd_itc.h"
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#include <fcntl.h>
+#include "internal.h"
+
+
+#if defined(_MHD_ITC_PIPE)
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+
+#ifndef HAVE_PIPE2_FUNC
+/**
+ * Change itc FD options to be non-blocking.
+ *
+ * @param itc the inter-thread communication primitive to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_itc_nonblocking_ (struct MHD_itc_ itc)
+{
+  unsigned int i;
+
+  for (i = 0; i<2; i++)
+  {
+    int flags;
+
+    flags = fcntl (itc.fd[i],
+                   F_GETFL);
+    if (-1 == flags)
+      return 0;
+
+    if ( ((flags | O_NONBLOCK) != flags) &&
+         (0 != fcntl (itc.fd[i],
+                      F_SETFL,
+                      flags | O_NONBLOCK)) )
+      return 0;
+  }
+  return ! 0;
+}
+
+
+#endif /* ! HAVE_PIPE2_FUNC */
+#endif /* !_WIN32 || __CYGWIN__ */
+#endif /* _MHD_ITC_EVENTFD ||  _MHD_ITC_PIPE */
diff --git a/src/microhttpd/mhd_itc.h b/src/microhttpd/mhd_itc.h
new file mode 100644
index 0000000..ad0d14e
--- /dev/null
+++ b/src/microhttpd/mhd_itc.h
@@ -0,0 +1,371 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_itc.h
+ * @brief  Header for platform-independent inter-thread communication
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ *
+ * Provides basic abstraction for inter-thread communication.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ */
+#ifndef MHD_ITC_H
+#define MHD_ITC_H 1
+#include "mhd_itc_types.h"
+
+#include <fcntl.h>
+
+#ifndef MHD_PANIC
+#  include <stdio.h>
+#  ifdef HAVE_STDLIB_H
+#    include <stdlib.h>
+#  endif /* HAVE_STDLIB_H */
+/* Simple implementation of MHD_PANIC, to be used outside lib */
+#  define MHD_PANIC(msg) do { fprintf (stderr,           \
+                                       "Abnormal termination at %d line in file %s: %s\n", \
+                                       (int) __LINE__, __FILE__, msg); abort (); \
+} while (0)
+#endif /* ! MHD_PANIC */
+
+#if defined(_MHD_ITC_EVENTFD)
+
+/* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */
+#include <sys/eventfd.h>
+#include <stdint.h>      /* for uint64_t */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>      /* for read(), write(), errno */
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_STRING_H
+#include <string.h> /* for strerror() */
+#endif
+
+
+/**
+ * Initialise ITC by generating eventFD
+ * @param itc the itc to initialise
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_init_(itc) (-1 != ((itc).fd = eventfd (0, EFD_CLOEXEC \
+                                                       | EFD_NONBLOCK)))
+
+/**
+ * Get description string of last errno for itc operations.
+ */
+#define MHD_itc_last_strerror_() strerror (errno)
+
+/**
+ * Internal static const helper for MHD_itc_activate_()
+ */
+static const uint64_t _MHD_itc_wr_data = 1;
+
+/**
+ * Activate signal on @a itc
+ * @param itc the itc to use
+ * @param str ignored
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_activate_(itc, str) \
+  ((write ((itc).fd, (const void*) &_MHD_itc_wr_data, 8) > 0) || (EAGAIN == \
+                                                                  errno))
+
+/**
+ * Return read FD of @a itc which can be used for poll(), select() etc.
+ * @param itc the itc to get FD
+ * @return FD of read side
+ */
+#define MHD_itc_r_fd_(itc) ((itc).fd)
+
+/**
+ * Return write FD of @a itc
+ * @param itc the itc to get FD
+ * @return FD of write side
+ */
+#define MHD_itc_w_fd_(itc) ((itc).fd)
+
+/**
+ * Clear signaled state on @a itc
+ * @param itc the itc to clear
+ */
+#define MHD_itc_clear_(itc)                       \
+  do { uint64_t __b;                              \
+       (void) read ((itc).fd, &__b, sizeof(__b)); \
+     } while (0)
+
+/**
+ * Destroy previously initialised ITC.  Note that close()
+ * on some platforms returns odd errors, so we ONLY fail
+ * if the errno is EBADF.
+ * @param itc the itc to destroy
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_destroy_(itc) ((0 == close ((itc).fd)) || (EBADF != errno))
+
+/**
+ * Check whether ITC has valid value.
+ *
+ * Macro check whether @a itc value is valid (allowed),
+ * macro does not check whether @a itc was really initialised.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has valid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_VALID_(itc)  (-1 != ((itc).fd))
+
+/**
+ * Set @a itc to invalid value.
+ * @param itc the itc to set
+ */
+#define MHD_itc_set_invalid_(itc) ((itc).fd = -1)
+
+
+#elif defined(_MHD_ITC_PIPE)
+
+/* **************** Standard UNIX ITC implementation by pipe ********** */
+
+#if defined(HAVE_PIPE2_FUNC) && defined(HAVE_FCNTL_H)
+#  include <fcntl.h>     /* for O_CLOEXEC, O_NONBLOCK */
+#endif /* HAVE_PIPE2_FUNC && HAVE_FCNTL_H */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>      /* for read(), write(), errno */
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_STRING_H
+#include <string.h> /* for strerror() */
+#endif
+
+
+/**
+ * Initialise ITC by generating pipe
+ * @param itc the itc to initialise
+ * @return non-zero if succeeded, zero otherwise
+ */
+#ifdef HAVE_PIPE2_FUNC
+#  define MHD_itc_init_(itc) (! pipe2 ((itc).fd, O_CLOEXEC | O_NONBLOCK))
+#else  /* ! HAVE_PIPE2_FUNC */
+#  define MHD_itc_init_(itc)              \
+  ( (! pipe ((itc).fd)) ?                \
+    (MHD_itc_nonblocking_ ((itc)) ?   \
+     (! 0) :                         \
+     (MHD_itc_destroy_ ((itc)), 0) ) \
+    : (0) )
+#endif /* ! HAVE_PIPE2_FUNC */
+
+/**
+ * Get description string of last errno for itc operations.
+ */
+#define MHD_itc_last_strerror_() strerror (errno)
+
+/**
+ * Activate signal on @a itc
+ * @param itc the itc to use
+ * @param str one-symbol string, useful only for strace debug
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_activate_(itc, str) \
+  ((write ((itc).fd[1], (const void*) (str), 1) > 0) || (EAGAIN == errno))
+
+
+/**
+ * Return read FD of @a itc which can be used for poll(), select() etc.
+ * @param itc the itc to get FD
+ * @return FD of read side
+ */
+#define MHD_itc_r_fd_(itc) ((itc).fd[0])
+
+/**
+ * Return write FD of @a itc
+ * @param itc the itc to get FD
+ * @return FD of write side
+ */
+#define MHD_itc_w_fd_(itc) ((itc).fd[1])
+
+/**
+ * Clear signaled state on @a itc
+ * @param itc the itc to clear
+ */
+#define MHD_itc_clear_(itc) do                      \
+  { long __b;                                       \
+    while (0 < read ((itc).fd[0], &__b, sizeof(__b))) \
+    {} } while (0)
+
+/**
+ * Destroy previously initialised ITC
+ * @param itc the itc to destroy
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_destroy_(itc)      \
+  ( (0 == close ((itc).fd[0])) ?   \
+    (0 == close ((itc).fd[1])) : \
+    ((close ((itc).fd[1])), 0) )
+
+/**
+ * Check whether ITC has valid value.
+ *
+ * Macro check whether @a itc value is valid (allowed),
+ * macro does not check whether @a itc was really initialised.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has valid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_VALID_(itc)  (-1 != (itc).fd[0])
+
+/**
+ * Set @a itc to invalid value.
+ * @param itc the itc to set
+ */
+#define MHD_itc_set_invalid_(itc) ((itc).fd[0] = (itc).fd[1] = -1)
+
+#ifndef HAVE_PIPE2_FUNC
+/**
+ * Change itc FD options to be non-blocking.
+ *
+ * @param fd the FD to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_itc_nonblocking_ (struct MHD_itc_ itc);
+
+#endif /* ! HAVE_PIPE2_FUNC */
+
+
+#elif defined(_MHD_ITC_SOCKETPAIR)
+
+/* **************** ITC implementation by socket pair ********** */
+
+#include "mhd_sockets.h"
+
+
+/**
+ * Initialise ITC by generating socketpair
+ * @param itc the itc to initialise
+ * @return non-zero if succeeded, zero otherwise
+ */
+#ifdef MHD_socket_pair_nblk_
+#  define MHD_itc_init_(itc) MHD_socket_pair_nblk_ ((itc).sk)
+#else  /* ! MHD_socket_pair_nblk_ */
+#  define MHD_itc_init_(itc)            \
+  (MHD_socket_pair_ ((itc).sk) ?      \
+   (MHD_itc_nonblocking_ ((itc)) ?   \
+    (! 0) :                         \
+    (MHD_itc_destroy_ ((itc)), 0) ) \
+   : (0))
+#endif /* ! MHD_socket_pair_nblk_ */
+
+/**
+ * Get description string of last error for itc operations.
+ */
+#define MHD_itc_last_strerror_() MHD_socket_last_strerr_ ()
+
+/**
+ * Activate signal on @a itc
+ * @param itc the itc to use
+ * @param str one-symbol string, useful only for strace debug
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_activate_(itc, str)          \
+  ((MHD_send_ ((itc).sk[1], (str), 1) > 0) || \
+   (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ())))
+
+/**
+ * Return read FD of @a itc which can be used for poll(), select() etc.
+ * @param itc the itc to get FD
+ * @return FD of read side
+ */
+#define MHD_itc_r_fd_(itc) ((itc).sk[0])
+
+/**
+ * Return write FD of @a itc
+ * @param itc the itc to get FD
+ * @return FD of write side
+ */
+#define MHD_itc_w_fd_(itc) ((itc).sk[1])
+
+/**
+ * Clear signaled state on @a itc
+ * @param itc the itc to clear
+ */
+#define MHD_itc_clear_(itc) do      \
+  { long __b;                       \
+    while (0 < recv ((itc).sk[0],     \
+                     (char*) &__b,     \
+                     sizeof(__b), 0)) \
+    {} } while (0)
+
+/**
+ * Destroy previously initialised ITC
+ * @param itc the itc to destroy
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_itc_destroy_(itc)          \
+  (MHD_socket_close_ ((itc).sk[0]) ?   \
+   MHD_socket_close_ ((itc).sk[1]) : \
+   ((void) MHD_socket_close_ ((itc).sk[1]), 0) )
+
+
+/**
+ * Check whether ITC has valid value.
+ *
+ * Macro check whether @a itc value is valid (allowed),
+ * macro does not check whether @a itc was really initialised.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has valid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_VALID_(itc)  (MHD_INVALID_SOCKET != (itc).sk[0])
+
+/**
+ * Set @a itc to invalid value.
+ * @param itc the itc to set
+ */
+#define MHD_itc_set_invalid_(itc) ((itc).sk[0] = (itc).sk[1] = \
+                                     MHD_INVALID_SOCKET)
+
+#ifndef MHD_socket_pair_nblk_
+#  define MHD_itc_nonblocking_(pip) (MHD_socket_nonblocking_ ((pip).sk[0]) && \
+                                     MHD_socket_nonblocking_ ((pip).sk[1]))
+#endif /* ! MHD_socket_pair_nblk_ */
+
+#endif /* _MHD_ITC_SOCKETPAIR */
+
+/**
+ * Destroy previously initialised ITC and abort execution
+ * if error is detected.
+ * @param itc the itc to destroy
+ */
+#define MHD_itc_destroy_chk_(itc) do {          \
+    if (! MHD_itc_destroy_ (itc))                 \
+      MHD_PANIC (_ ("Failed to destroy ITC.\n")); \
+} while (0)
+
+/**
+ * Check whether ITC has invalid value.
+ *
+ * Macro check whether @a itc value is invalid,
+ * macro does not check whether @a itc was destroyed.
+ * @param itc the itc to check
+ * @return boolean true if @a itc has invalid value,
+ *         boolean false otherwise.
+ */
+#define MHD_ITC_IS_INVALID_(itc)  (! MHD_ITC_IS_VALID_ (itc))
+
+#endif /* MHD_ITC_H */
diff --git a/src/microhttpd/mhd_itc_types.h b/src/microhttpd/mhd_itc_types.h
new file mode 100644
index 0000000..04d3023
--- /dev/null
+++ b/src/microhttpd/mhd_itc_types.h
@@ -0,0 +1,94 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin), Christian Grothoff
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_itc_types.h
+ * @brief  Types for platform-independent inter-thread communication
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ *
+ * Provides basic types for inter-thread communication.
+ * Designed to be included by other headers.
+ */
+#ifndef MHD_ITC_TYPES_H
+#define MHD_ITC_TYPES_H 1
+#include "mhd_options.h"
+
+/* Force socketpair on native W32 */
+#if defined(_WIN32) && ! defined(__CYGWIN__) && ! defined(_MHD_ITC_SOCKETPAIR)
+#error _MHD_ITC_SOCKETPAIR is not defined on naitive W32 platform
+#endif /* _WIN32 && !__CYGWIN__ && !_MHD_ITC_SOCKETPAIR */
+
+#if defined(_MHD_ITC_EVENTFD)
+/* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */
+
+/**
+ * Data type for a MHD ITC.
+ */
+struct MHD_itc_
+{
+  int fd;
+};
+
+/**
+ * Static initialiser for struct MHD_itc_
+ */
+#define MHD_ITC_STATIC_INIT_INVALID { -1 }
+
+
+#elif defined(_MHD_ITC_PIPE)
+/* **************** Standard UNIX ITC implementation by pipe ********** */
+
+/**
+ * Data type for a MHD ITC.
+ */
+struct MHD_itc_
+{
+  int fd[2];
+};
+
+/**
+ * Static initialiser for struct MHD_itc_
+ */
+#define MHD_ITC_STATIC_INIT_INVALID { { -1, -1 } }
+
+
+#elif defined(_MHD_ITC_SOCKETPAIR)
+/* **************** ITC implementation by socket pair ********** */
+
+#include "mhd_sockets.h"
+
+/**
+ * Data type for a MHD ITC.
+ */
+struct MHD_itc_
+{
+  MHD_socket sk[2];
+};
+
+/**
+ * Static initialiser for struct MHD_itc_
+ */
+#define MHD_ITC_STATIC_INIT_INVALID \
+  { { MHD_INVALID_SOCKET, MHD_INVALID_SOCKET } }
+
+#endif /* _MHD_ITC_SOCKETPAIR */
+
+#endif /* ! MHD_ITC_TYPES_H */
diff --git a/src/microhttpd/mhd_limits.h b/src/microhttpd/mhd_limits.h
new file mode 100644
index 0000000..b61da5f
--- /dev/null
+++ b/src/microhttpd/mhd_limits.h
@@ -0,0 +1,156 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_limits.h
+ * @brief  limits values definitions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_LIMITS_H
+#define MHD_LIMITS_H
+
+#include "platform.h"
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#define MHD_UNSIGNED_TYPE_MAX_(type) ((type) - 1)
+/* Assume 8 bits per byte, no padding bits. */
+#define MHD_SIGNED_TYPE_MAX_(type) \
+  ( (type) ((( ((type) 1) << (sizeof(type) * 8 - 2)) - 1) * 2 + 1) )
+#define MHD_TYPE_IS_SIGNED_(type) (((type) 0)>((type) - 1))
+
+#ifndef INT_MAX
+#ifdef __INT_MAX__
+#define INT_MAX __INT_MAX__
+#else  /* ! __UINT_MAX__ */
+#define INT_MAX MHD_SIGNED_TYPE_MAX_ (int)
+#endif /* ! __UINT_MAX__ */
+#endif /* !UINT_MAX */
+
+#ifndef UINT_MAX
+#ifdef __UINT_MAX__
+#define UINT_MAX __UINT_MAX__
+#else  /* ! __UINT_MAX__ */
+#define UINT_MAX MHD_UNSIGNED_TYPE_MAX_ (unsigned int)
+#endif /* ! __UINT_MAX__ */
+#endif /* !UINT_MAX */
+
+#ifndef LONG_MAX
+#ifdef __LONG_MAX__
+#define LONG_MAX __LONG_MAX__
+#else  /* ! __LONG_MAX__ */
+#define LONG_MAX MHD_SIGNED_TYPE_MAX (long)
+#endif /* ! __LONG_MAX__ */
+#endif /* !LONG_MAX */
+
+#ifndef ULLONG_MAX
+#ifdef ULONGLONG_MAX
+#define ULLONG_MAX ULONGLONG_MAX
+#else  /* ! ULONGLONG_MAX */
+#define ULLONG_MAX MHD_UNSIGNED_TYPE_MAX_ (MHD_UNSIGNED_LONG_LONG)
+#endif /* ! ULONGLONG_MAX */
+#endif /* !ULLONG_MAX */
+
+#ifndef INT32_MAX
+#ifdef __INT32_MAX__
+#define INT32_MAX __INT32_MAX__
+#else  /* ! __INT32_MAX__ */
+#define INT32_MAX ((int32_t) 0x7FFFFFFF)
+#endif /* ! __INT32_MAX__ */
+#endif /* !INT32_MAX */
+
+#ifndef UINT32_MAX
+#ifdef __UINT32_MAX__
+#define UINT32_MAX __UINT32_MAX__
+#else  /* ! __UINT32_MAX__ */
+#define UINT32_MAX ((int32_t) 0xFFFFFFFF)
+#endif /* ! __UINT32_MAX__ */
+#endif /* !UINT32_MAX */
+
+#ifndef UINT64_MAX
+#ifdef __UINT64_MAX__
+#define UINT64_MAX __UINT64_MAX__
+#else  /* ! __UINT64_MAX__ */
+#define UINT64_MAX ((uint64_t) 0xFFFFFFFFFFFFFFFF)
+#endif /* ! __UINT64_MAX__ */
+#endif /* !UINT64_MAX */
+
+#ifndef INT64_MAX
+#ifdef __INT64_MAX__
+#define INT64_MAX __INT64_MAX__
+#else  /* ! __INT64_MAX__ */
+#define INT64_MAX ((int64_t) 0x7FFFFFFFFFFFFFFF)
+#endif /* ! __UINT64_MAX__ */
+#endif /* !INT64_MAX */
+
+#ifndef SIZE_MAX
+#ifdef __SIZE_MAX__
+#define SIZE_MAX __SIZE_MAX__
+#elif defined(UINTPTR_MAX)
+#define SIZE_MAX UINTPTR_MAX
+#else  /* ! __SIZE_MAX__ */
+#define SIZE_MAX MHD_UNSIGNED_TYPE_MAX_ (size_t)
+#endif /* ! __SIZE_MAX__ */
+#endif /* !SIZE_MAX */
+
+#ifndef SSIZE_MAX
+#ifdef __SSIZE_MAX__
+#define SSIZE_MAX __SSIZE_MAX__
+#elif defined(INTPTR_MAX)
+#define SSIZE_MAX INTPTR_MAX
+#else
+#define SSIZE_MAX MHD_SIGNED_TYPE_MAX_ (ssize_t)
+#endif
+#endif /* ! SSIZE_MAX */
+
+#ifndef OFF_T_MAX
+#ifdef OFF_MAX
+#define OFF_T_MAX OFF_MAX
+#elif defined(OFFT_MAX)
+#define OFF_T_MAX OFFT_MAX
+#elif defined(__APPLE__) && defined(__MACH__)
+#define OFF_T_MAX INT64_MAX
+#else
+#define OFF_T_MAX MHD_SIGNED_TYPE_MAX_ (off_t)
+#endif
+#endif /* !OFF_T_MAX */
+
+#if defined(_LARGEFILE64_SOURCE) && ! defined(OFF64_T_MAX)
+#define OFF64_T_MAX MHD_SIGNED_TYPE_MAX_ (uint64_t)
+#endif /* _LARGEFILE64_SOURCE && !OFF64_T_MAX */
+
+#ifndef TIME_T_MAX
+#define TIME_T_MAX ((time_t)              \
+                    (MHD_TYPE_IS_SIGNED_ (time_t) ?    \
+                     MHD_SIGNED_TYPE_MAX_ (time_t) : \
+                     MHD_UNSIGNED_TYPE_MAX_ (time_t)))
+#endif /* !TIME_T_MAX */
+
+#ifndef TIMEVAL_TV_SEC_MAX
+#ifndef _WIN32
+#define TIMEVAL_TV_SEC_MAX TIME_T_MAX
+#else  /* _WIN32 */
+#define TIMEVAL_TV_SEC_MAX LONG_MAX
+#endif /* _WIN32 */
+#endif /* !TIMEVAL_TV_SEC_MAX */
+
+#endif /* MHD_LIMITS_H */
diff --git a/src/microhttpd/mhd_locks.h b/src/microhttpd/mhd_locks.h
new file mode 100644
index 0000000..ad9fa20
--- /dev/null
+++ b/src/microhttpd/mhd_locks.h
@@ -0,0 +1,202 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_locks.h
+ * @brief  Header for platform-independent locks abstraction
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ *
+ * Provides basic abstraction for locks/mutex.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ *
+ * @warning Unlike pthread functions, most of functions return
+ *          nonzero on success.
+ */
+
+#ifndef MHD_LOCKS_H
+#define MHD_LOCKS_H 1
+
+#include "mhd_options.h"
+
+#ifdef MHD_USE_THREADS
+
+#if defined(MHD_USE_W32_THREADS)
+#  define MHD_W32_MUTEX_ 1
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
+#  endif /* !WIN32_LEAN_AND_MEAN */
+#  include <windows.h>
+#elif defined(HAVE_PTHREAD_H) && defined(MHD_USE_POSIX_THREADS)
+#  define MHD_PTHREAD_MUTEX_ 1
+#  undef HAVE_CONFIG_H
+#  include <pthread.h>
+#  define HAVE_CONFIG_H 1
+#else
+#  error No base mutex API is available.
+#endif
+
+#ifndef MHD_PANIC
+#  include <stdio.h>
+#  ifdef HAVE_STDLIB_H
+#    include <stdlib.h>
+#  endif /* HAVE_STDLIB_H */
+/* Simple implementation of MHD_PANIC, to be used outside lib */
+#  define MHD_PANIC(msg) \
+  do { fprintf (stderr,           \
+       "Abnormal termination at %d line in file %s: %s\n", \
+       (int) __LINE__, __FILE__, msg); abort (); \
+  } while (0)
+#endif /* ! MHD_PANIC */
+
+#if defined(MHD_PTHREAD_MUTEX_)
+typedef pthread_mutex_t MHD_mutex_;
+#elif defined(MHD_W32_MUTEX_)
+typedef CRITICAL_SECTION MHD_mutex_;
+#endif
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Initialise new mutex.
+ * @param pmutex pointer to the mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_init_(pmutex) (! (pthread_mutex_init ((pmutex), NULL)))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Initialise new mutex.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_init_(pmutex) \
+  (InitializeCriticalSectionAndSpinCount ((pmutex),16))
+#endif
+
+#if defined(MHD_PTHREAD_MUTEX_)
+#  if defined(PTHREAD_MUTEX_INITIALIZER)
+/**
+ *  Define static mutex and statically initialise it.
+ */
+#    define MHD_MUTEX_STATIC_DEFN_INIT_(m) \
+  static MHD_mutex_ m = PTHREAD_MUTEX_INITIALIZER
+#  endif /* PTHREAD_MUTEX_INITIALIZER */
+#endif
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Destroy previously initialised mutex.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_destroy_(pmutex) (! (pthread_mutex_destroy ((pmutex))))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Destroy previously initialised mutex.
+ * @param pmutex pointer to mutex
+ * @return Always nonzero
+ */
+#define MHD_mutex_destroy_(pmutex) (DeleteCriticalSection ((pmutex)), ! 0)
+#endif
+
+/**
+ * Destroy previously initialised mutex and abort execution
+ * if error is detected.
+ * @param pmutex pointer to mutex
+ */
+#define MHD_mutex_destroy_chk_(pmutex) do {       \
+    if (! MHD_mutex_destroy_ (pmutex))              \
+      MHD_PANIC (_ ("Failed to destroy mutex.\n")); \
+  } while (0)
+
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Acquire lock on previously initialised mutex.
+ * If mutex was already locked by other thread, function
+ * blocks until mutex becomes available.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_lock_(pmutex) (! (pthread_mutex_lock ((pmutex))))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Acquire lock on previously initialised mutex.
+ * If mutex was already locked by other thread, function
+ * blocks until mutex becomes available.
+ * @param pmutex pointer to mutex
+ * @return Always nonzero
+ */
+#define MHD_mutex_lock_(pmutex) (EnterCriticalSection ((pmutex)), ! 0)
+#endif
+
+/**
+ * Acquire lock on previously initialised mutex.
+ * If mutex was already locked by other thread, function
+ * blocks until mutex becomes available.
+ * If error is detected, execution will be aborted.
+ * @param pmutex pointer to mutex
+ */
+#define MHD_mutex_lock_chk_(pmutex) do {       \
+    if (! MHD_mutex_lock_ (pmutex))              \
+      MHD_PANIC (_ ("Failed to lock mutex.\n")); \
+} while (0)
+
+#if defined(MHD_PTHREAD_MUTEX_)
+/**
+ * Unlock previously initialised and locked mutex.
+ * @param pmutex pointer to mutex
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_mutex_unlock_(pmutex) (! (pthread_mutex_unlock ((pmutex))))
+#elif defined(MHD_W32_MUTEX_)
+/**
+ * Unlock previously initialised and locked mutex.
+ * @param pmutex pointer to mutex
+ * @return Always nonzero
+ */
+#define MHD_mutex_unlock_(pmutex) (LeaveCriticalSection ((pmutex)), ! 0)
+#endif
+
+/**
+ * Unlock previously initialised and locked mutex.
+ * If error is detected, execution will be aborted.
+ * @param pmutex pointer to mutex
+ */
+#define MHD_mutex_unlock_chk_(pmutex) do {       \
+    if (! MHD_mutex_unlock_ (pmutex))              \
+      MHD_PANIC (_ ("Failed to unlock mutex.\n")); \
+} while (0)
+
+#else  /* ! MHD_USE_THREADS */
+
+#define MHD_mutex_init_(ignore) (! 0)
+#define MHD_mutex_destroy_(ignore) (! 0)
+#define MHD_mutex_destroy_chk_(ignore) (void)0
+#define MHD_mutex_lock_(ignore) (! 0)
+#define MHD_mutex_lock_chk_(ignore) (void)0
+#define MHD_mutex_unlock_(ignore) (! 0)
+#define MHD_mutex_unlock_chk_(ignore) (void)0
+
+#endif /* ! MHD_USE_THREADS */
+
+#endif /* ! MHD_LOCKS_H */
diff --git a/src/microhttpd/mhd_md5_wrap.h b/src/microhttpd/mhd_md5_wrap.h
new file mode 100644
index 0000000..98a5d95
--- /dev/null
+++ b/src/microhttpd/mhd_md5_wrap.h
@@ -0,0 +1,98 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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 GNU libmicrohttpd.
+     If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file microhttpd/mhd_md5_wrap.h
+ * @brief  Simple wrapper for selection of built-in/external MD5 implementation
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_MD5_WRAP_H
+#define MHD_MD5_WRAP_H 1
+
+#include "mhd_options.h"
+#ifndef MHD_MD5_SUPPORT
+#error This file must be used only when MD5 is enabled
+#endif
+#ifndef MHD_MD5_TLSLIB
+#include "md5.h"
+#else  /* MHD_MD5_TLSLIB */
+#include "md5_ext.h"
+#endif /* MHD_MD5_TLSLIB */
+
+#ifndef MD5_DIGEST_SIZE
+/**
+ * Size of MD5 resulting digest in bytes
+ * This is the final digest size, not intermediate hash.
+ */
+#define MD5_DIGEST_SIZE (16)
+#endif /* ! MD5_DIGEST_SIZE */
+
+#ifndef MD5_DIGEST_STRING_SIZE
+/**
+ * Size of MD5 digest string in chars including termination NUL.
+ */
+#define MD5_DIGEST_STRING_SIZE ((MD5_DIGEST_SIZE) * 2 + 1)
+#endif /* ! MD5_DIGEST_STRING_SIZE */
+
+#ifndef MHD_MD5_TLSLIB
+/**
+ * Universal ctx type mapped for chosen implementation
+ */
+#define Md5CtxWr Md5Ctx
+#else  /* MHD_MD5_TLSLIB */
+/**
+ * Universal ctx type mapped for chosen implementation
+ */
+#define Md5CtxWr Md5CtxExt
+#endif /* MHD_MD5_TLSLIB */
+
+#ifndef MHD_MD5_HAS_INIT_ONE_TIME
+/**
+ * Setup and prepare ctx for hash calculation
+ */
+#define MHD_MD5_init_one_time(ctx) MHD_MD5_init(ctx)
+#endif /* ! MHD_MD5_HAS_INIT_ONE_TIME */
+
+#ifndef MHD_MD5_HAS_FINISH_RESET
+/**
+ * Re-use the same ctx for the new hashing after digest calculated
+ */
+#define MHD_MD5_reset(ctx) MHD_MD5_init(ctx)
+/**
+ * Finalise MD5 calculation, return digest, reset hash calculation.
+ */
+#define MHD_MD5_finish_reset(ctx,digest) MHD_MD5_finish(ctx,digest), \
+                                         MHD_MD5_reset(ctx)
+
+#else  /* MHD_MD5_HAS_FINISH_RESET */
+#define MHD_MD5_reset(ctx) (void)0
+#endif /* MHD_MD5_HAS_FINISH_RESET */
+
+#ifndef MHD_MD5_HAS_DEINIT
+#define MHD_MD5_deinit(ignore) (void)0
+#endif /* HAVE_MD5_DEINIT */
+
+/* Sanity checks */
+
+#if ! defined(MHD_MD5_HAS_FINISH_RESET) && ! defined(MHD_MD5_HAS_FINISH)
+#error Required at least one of MHD_MD5_finish_reset(), MHD_MD5_finish_reset()
+#endif /* ! MHD_MD5_HAS_FINISH_RESET && ! MHD_MD5_HAS_FINISH */
+
+#endif /* MHD_MD5_WRAP_H */
diff --git a/src/microhttpd/mhd_mono_clock.c b/src/microhttpd/mhd_mono_clock.c
new file mode 100644
index 0000000..e6f8267
--- /dev/null
+++ b/src/microhttpd/mhd_mono_clock.c
@@ -0,0 +1,503 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_mono_clock.h
+ * @brief  internal monotonic clock functions implementations
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_mono_clock.h"
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+/* Prefer native clock source over wrappers */
+#ifdef HAVE_CLOCK_GETTIME
+#undef HAVE_CLOCK_GETTIME
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_GETTIMEOFDAY
+#undef HAVE_GETTIMEOFDAY
+#endif /* HAVE_GETTIMEOFDAY */
+#endif /* _WIN32 && ! __CYGWIN__ */
+
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+
+#ifdef HAVE_CLOCK_GET_TIME
+#include <mach/mach.h>
+/* for host_get_clock_service(), mach_host_self(), mach_task_self() */
+#include <mach/clock.h>
+/* for clock_get_time() */
+
+#define _MHD_INVALID_CLOCK_SERV ((clock_serv_t) -2)
+
+static clock_serv_t mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+#endif /* HAVE_CLOCK_GET_TIME */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+/* Do not include unneeded parts of W32 headers. */
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#include <stdint.h>
+#endif /* _WIN32 */
+
+#ifndef NULL
+#define NULL ((void*)0)
+#endif /* ! NULL */
+
+#ifdef HAVE_CLOCK_GETTIME
+#ifdef CLOCK_REALTIME
+#define _MHD_UNWANTED_CLOCK CLOCK_REALTIME
+#else  /* !CLOCK_REALTIME */
+#define _MHD_UNWANTED_CLOCK ((clockid_t) -2)
+#endif /* !CLOCK_REALTIME */
+
+static clockid_t mono_clock_id = _MHD_UNWANTED_CLOCK;
+#endif /* HAVE_CLOCK_GETTIME */
+
+/* sync clocks; reduce chance of value wrap */
+#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GET_TIME) || \
+  defined(HAVE_GETHRTIME)
+static time_t mono_clock_start;
+#endif /* HAVE_CLOCK_GETTIME || HAVE_CLOCK_GET_TIME || HAVE_GETHRTIME */
+#if defined(HAVE_TIMESPEC_GET) || defined(HAVE_GETTIMEOFDAY)
+/* The start value shared for timespec_get() and gettimeofday () */
+static time_t gettime_start;
+#endif /* HAVE_TIMESPEC_GET || HAVE_GETTIMEOFDAY */
+static time_t sys_clock_start;
+#ifdef HAVE_GETHRTIME
+static hrtime_t hrtime_start;
+#endif /* HAVE_GETHRTIME */
+#ifdef _WIN32
+#if _WIN32_WINNT >= 0x0600
+static uint64_t tick_start;
+#else  /* _WIN32_WINNT < 0x0600 */
+static uint64_t perf_freq;
+static uint64_t perf_start;
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+
+
+/**
+ * Type of monotonic clock source
+ */
+enum _MHD_mono_clock_source
+{
+  /**
+   * No monotonic clock
+   */
+  _MHD_CLOCK_NO_SOURCE = 0,
+
+  /**
+   * clock_gettime() with specific clock
+   */
+  _MHD_CLOCK_GETTIME,
+
+  /**
+   * clock_get_time() with specific clock service
+   */
+  _MHD_CLOCK_GET_TIME,
+
+  /**
+   * gethrtime() / 1000000000
+   */
+  _MHD_CLOCK_GETHRTIME,
+
+  /**
+   * GetTickCount64() / 1000
+   */
+  _MHD_CLOCK_GETTICKCOUNT64,
+
+  /**
+   * QueryPerformanceCounter() / QueryPerformanceFrequency()
+   */
+  _MHD_CLOCK_PERFCOUNTER
+};
+
+
+/**
+ * Initialise monotonic seconds and milliseconds counters.
+ */
+void
+MHD_monotonic_sec_counter_init (void)
+{
+#ifdef HAVE_CLOCK_GET_TIME
+  mach_timespec_t cur_time;
+#endif /* HAVE_CLOCK_GET_TIME */
+  enum _MHD_mono_clock_source mono_clock_source = _MHD_CLOCK_NO_SOURCE;
+#ifdef HAVE_CLOCK_GETTIME
+  struct timespec ts;
+
+  mono_clock_id = _MHD_UNWANTED_CLOCK;
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+#endif /* HAVE_CLOCK_GET_TIME */
+
+  /* just a little syntactic trick to get the
+     various following ifdef's to work out nicely */
+  if (0)
+  {
+    (void) 0; /* Mute possible compiler warning */
+  }
+  else
+#ifdef HAVE_CLOCK_GETTIME
+#ifdef CLOCK_MONOTONIC_COARSE
+  /* Linux-specific fast value-getting clock */
+  /* Can be affected by frequency adjustment and don't count time in suspend, */
+  /* but preferred since it's fast */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_COARSE,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_COARSE;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_COARSE */
+#ifdef CLOCK_MONOTONIC_FAST
+  /* FreeBSD/DragonFly fast value-getting clock */
+  /* Can be affected by frequency adjustment, but preferred since it's fast */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_FAST,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_FAST;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_COARSE */
+#ifdef CLOCK_MONOTONIC_RAW_APPROX
+  /* Darwin-specific clock */
+  /* Not affected by frequency adjustment, returns clock value cached at
+   * context switch. Can be "milliseconds old", but it's fast. */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_RAW_APPROX,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_RAW_APPROX;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_RAW */
+#ifdef CLOCK_MONOTONIC_RAW
+  /* Linux and Darwin clock */
+  /* Not affected by frequency adjustment,
+   * on Linux don't count time in suspend */
+  if (0 == clock_gettime (CLOCK_MONOTONIC_RAW,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC_RAW;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC_RAW */
+#ifdef CLOCK_BOOTTIME
+  /* Count time in suspend on Linux so it's real monotonic, */
+  /* but can be slower value-getting than other clocks */
+  if (0 == clock_gettime (CLOCK_BOOTTIME,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_BOOTTIME;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_BOOTTIME */
+#ifdef CLOCK_MONOTONIC
+  /* Monotonic clock */
+  /* Widely supported, may be affected by frequency adjustment */
+  /* On Linux it's not truly monotonic as it doesn't count time in suspend */
+  if (0 == clock_gettime (CLOCK_MONOTONIC,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_MONOTONIC;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_MONOTONIC */
+#ifdef CLOCK_UPTIME
+  /* non-Linux clock */
+  /* Doesn't count time in suspend */
+  if (0 == clock_gettime (CLOCK_UPTIME,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_UPTIME;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_BOOTTIME */
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  /* Darwin-specific monotonic clock */
+  /* Should be monotonic as clock_set_time function always unconditionally */
+  /* failed on latest kernels */
+  if ( (KERN_SUCCESS == host_get_clock_service (mach_host_self (),
+                                                SYSTEM_CLOCK,
+                                                &mono_clock_service)) &&
+       (KERN_SUCCESS == clock_get_time (mono_clock_service,
+                                        &cur_time)) )
+  {
+    mono_clock_start = cur_time.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GET_TIME;
+  }
+  else
+#endif /* HAVE_CLOCK_GET_TIME */
+#ifdef _WIN32
+#if _WIN32_WINNT >= 0x0600
+  /* W32 Vista or later specific monotonic clock */
+  /* Available since Vista, ~15ms accuracy */
+  if (1)
+  {
+    tick_start = GetTickCount64 ();
+    mono_clock_source = _MHD_CLOCK_GETTICKCOUNT64;
+  }
+  else
+#else  /* _WIN32_WINNT < 0x0600 */
+  /* W32 specific monotonic clock */
+  /* Available on Windows 2000 and later */
+  if (1)
+  {
+    LARGE_INTEGER freq;
+    LARGE_INTEGER perf_counter;
+
+    QueryPerformanceFrequency (&freq);       /* never fail on XP and later */
+    QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */
+    perf_freq = (uint64_t) freq.QuadPart;
+    perf_start = (uint64_t) perf_counter.QuadPart;
+    mono_clock_source = _MHD_CLOCK_PERFCOUNTER;
+  }
+  else
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+#ifdef HAVE_CLOCK_GETTIME
+#ifdef CLOCK_HIGHRES
+  /* Solaris-specific monotonic high-resolution clock */
+  /* Not preferred due to be potentially resource-hungry */
+  if (0 == clock_gettime (CLOCK_HIGHRES,
+                          &ts))
+  {
+    mono_clock_id = CLOCK_HIGHRES;
+    mono_clock_start = ts.tv_sec;
+    mono_clock_source = _MHD_CLOCK_GETTIME;
+  }
+  else
+#endif /* CLOCK_HIGHRES */
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_GETHRTIME
+  /* HP-UX and Solaris monotonic clock */
+  /* Not preferred due to be potentially resource-hungry */
+  if (1)
+  {
+    hrtime_start = gethrtime ();
+    mono_clock_source = _MHD_CLOCK_GETHRTIME;
+  }
+  else
+#endif /* HAVE_GETHRTIME */
+  {
+    /* no suitable clock source was found */
+    mono_clock_source = _MHD_CLOCK_NO_SOURCE;
+  }
+
+#ifdef HAVE_CLOCK_GET_TIME
+  if ( (_MHD_CLOCK_GET_TIME != mono_clock_source) &&
+       (_MHD_INVALID_CLOCK_SERV != mono_clock_service) )
+  {
+    /* clock service was initialised but clock_get_time failed */
+    mach_port_deallocate (mach_task_self (),
+                          mono_clock_service);
+    mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+  }
+#else
+  (void) mono_clock_source; /* avoid compiler warning */
+#endif /* HAVE_CLOCK_GET_TIME */
+
+#ifdef HAVE_TIMESPEC_GET
+  if (1)
+  {
+    struct timespec tsg;
+    if (TIME_UTC == timespec_get (&tsg, TIME_UTC))
+      gettime_start = tsg.tv_sec;
+    else
+      gettime_start = 0;
+  }
+#elif defined(HAVE_GETTIMEOFDAY)
+  if (1)
+  {
+    struct timeval tv;
+    if (0 == gettimeofday (&tv, NULL))
+      gettime_start = tv.tv_sec;
+    else
+      gettime_start = 0;
+  }
+#endif /* HAVE_GETTIMEOFDAY */
+  sys_clock_start = time (NULL);
+}
+
+
+/**
+ * Deinitialise monotonic seconds  and milliseconds counters by freeing
+ * any allocated resources
+ */
+void
+MHD_monotonic_sec_counter_finish (void)
+{
+#ifdef HAVE_CLOCK_GET_TIME
+  if (_MHD_INVALID_CLOCK_SERV != mono_clock_service)
+  {
+    mach_port_deallocate (mach_task_self (),
+                          mono_clock_service);
+    mono_clock_service = _MHD_INVALID_CLOCK_SERV;
+  }
+#endif /* HAVE_CLOCK_GET_TIME */
+}
+
+
+/**
+ * Monotonic seconds counter.
+ * Tries to be not affected by manually setting the system real time
+ * clock or adjustments by NTP synchronization.
+ *
+ * @return number of seconds from some fixed moment
+ */
+time_t
+MHD_monotonic_sec_counter (void)
+{
+#ifdef HAVE_CLOCK_GETTIME
+  struct timespec ts;
+
+  if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) &&
+       (0 == clock_gettime (mono_clock_id,
+                            &ts)) )
+    return ts.tv_sec - mono_clock_start;
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  if (_MHD_INVALID_CLOCK_SERV != mono_clock_service)
+  {
+    mach_timespec_t cur_time;
+
+    if (KERN_SUCCESS == clock_get_time (mono_clock_service,
+                                        &cur_time))
+      return cur_time.tv_sec - mono_clock_start;
+  }
+#endif /* HAVE_CLOCK_GET_TIME */
+#if defined(_WIN32)
+#if _WIN32_WINNT >= 0x0600
+  if (1)
+    return (time_t) (((uint64_t) (GetTickCount64 () - tick_start)) / 1000);
+#else  /* _WIN32_WINNT < 0x0600 */
+  if (0 != perf_freq)
+  {
+    LARGE_INTEGER perf_counter;
+
+    QueryPerformanceCounter (&perf_counter);   /* never fail on XP and later */
+    return (time_t) (((uint64_t) perf_counter.QuadPart - perf_start)
+                     / perf_freq);
+  }
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+#ifdef HAVE_GETHRTIME
+  if (1)
+    return (time_t) (((uint64_t) (gethrtime () - hrtime_start)) / 1000000000);
+#endif /* HAVE_GETHRTIME */
+
+  return time (NULL) - sys_clock_start;
+}
+
+
+/**
+ * Monotonic milliseconds counter, useful for timeout calculation.
+ * Tries to be not affected by manually setting the system real time
+ * clock or adjustments by NTP synchronization.
+ *
+ * @return number of microseconds from some fixed moment
+ */
+uint64_t
+MHD_monotonic_msec_counter (void)
+{
+#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_TIMESPEC_GET)
+  struct timespec ts;
+#endif /* HAVE_CLOCK_GETTIME || HAVE_TIMESPEC_GET */
+
+#ifdef HAVE_CLOCK_GETTIME
+  if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) &&
+       (0 == clock_gettime (mono_clock_id,
+                            &ts)) )
+    return (uint64_t) (((uint64_t) (ts.tv_sec - mono_clock_start)) * 1000
+                       + (uint64_t) (ts.tv_nsec / 1000000));
+#endif /* HAVE_CLOCK_GETTIME */
+#ifdef HAVE_CLOCK_GET_TIME
+  if (_MHD_INVALID_CLOCK_SERV != mono_clock_service)
+  {
+    mach_timespec_t cur_time;
+
+    if (KERN_SUCCESS == clock_get_time (mono_clock_service,
+                                        &cur_time))
+      return (uint64_t) (((uint64_t) (cur_time.tv_sec - mono_clock_start))
+                         * 1000 + (uint64_t) (cur_time.tv_nsec / 1000000));
+  }
+#endif /* HAVE_CLOCK_GET_TIME */
+#if defined(_WIN32)
+#if _WIN32_WINNT >= 0x0600
+  if (1)
+    return (uint64_t) (GetTickCount64 () - tick_start);
+#else  /* _WIN32_WINNT < 0x0600 */
+  if (0 != perf_freq)
+  {
+    LARGE_INTEGER perf_counter;
+    uint64_t num_ticks;
+
+    QueryPerformanceCounter (&perf_counter);   /* never fail on XP and later */
+    num_ticks = (uint64_t) (perf_counter.QuadPart - perf_start);
+    return ((num_ticks / perf_freq) * 1000)
+           + ((num_ticks % perf_freq) / (perf_freq / 1000));
+  }
+#endif /* _WIN32_WINNT < 0x0600 */
+#endif /* _WIN32 */
+#ifdef HAVE_GETHRTIME
+  if (1)
+    return ((uint64_t) (gethrtime () - hrtime_start)) / 1000000;
+#endif /* HAVE_GETHRTIME */
+
+  /* Fallbacks, affected by system time change */
+#ifdef HAVE_TIMESPEC_GET
+  if (TIME_UTC == timespec_get (&ts, TIME_UTC))
+    return (uint64_t) (((uint64_t) (ts.tv_sec - gettime_start)) * 1000
+                       + (uint64_t) (ts.tv_nsec / 1000000));
+#elif defined(HAVE_GETTIMEOFDAY)
+  if (1)
+  {
+    struct timeval tv;
+    if (0 == gettimeofday (&tv, NULL))
+      return (uint64_t) (((uint64_t) (tv.tv_sec - gettime_start)) * 1000
+                         + (uint64_t) (tv.tv_usec / 1000));
+  }
+#endif /* HAVE_GETTIMEOFDAY */
+
+  /* The last resort fallback with very low resolution */
+  return (uint64_t) (time (NULL) - sys_clock_start) * 1000;
+}
diff --git a/src/microhttpd/mhd_mono_clock.h b/src/microhttpd/mhd_mono_clock.h
new file mode 100644
index 0000000..f7a3d4a
--- /dev/null
+++ b/src/microhttpd/mhd_mono_clock.h
@@ -0,0 +1,73 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_mono_clock.h
+ * @brief  internal monotonic clock functions declarations
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_MONO_CLOCK_H
+#define MHD_MONO_CLOCK_H 1
+#include "mhd_options.h"
+
+#if defined(HAVE_TIME_H)
+#include <time.h>
+#elif defined(HAVE_SYS_TYPES_H)
+#include <sys/types.h>
+#endif
+#include <stdint.h>
+
+/**
+ * Initialise monotonic seconds and milliseconds counters.
+ */
+void
+MHD_monotonic_sec_counter_init (void);
+
+
+/**
+ * Deinitialise monotonic seconds  and milliseconds counters by freeing
+ * any allocated resources
+ */
+void
+MHD_monotonic_sec_counter_finish (void);
+
+
+/**
+ * Monotonic seconds counter.
+ * Tries to be not affected by manually setting the system real time
+ * clock or adjustments by NTP synchronization.
+ *
+ * @return number of seconds from some fixed moment
+ */
+time_t
+MHD_monotonic_sec_counter (void);
+
+
+/**
+ * Monotonic milliseconds counter, useful for timeout calculation.
+ * Tries to be not affected by manually setting the system real time
+ * clock or adjustments by NTP synchronization.
+ *
+ * @return number of microseconds from some fixed moment
+ */
+uint64_t
+MHD_monotonic_msec_counter (void);
+
+#endif /* MHD_MONO_CLOCK_H */
diff --git a/src/microhttpd/mhd_panic.c b/src/microhttpd/mhd_panic.c
new file mode 100644
index 0000000..dfe1f6b
--- /dev/null
+++ b/src/microhttpd/mhd_panic.c
@@ -0,0 +1,103 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+  Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_panic.h
+ * @brief  MHD_panic() function and helpers
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_panic.h"
+#include "platform.h"
+#include "microhttpd.h"
+
+/**
+ * Handler for fatal errors.
+ */
+MHD_PanicCallback mhd_panic = (MHD_PanicCallback) NULL;
+
+/**
+ * Closure argument for #mhd_panic.
+ */
+void *mhd_panic_cls = NULL;
+
+
+/**
+ * Default implementation of the panic function,
+ * prints an error message and aborts.
+ *
+ * @param cls unused
+ * @param file name of the file with the problem
+ * @param line line number with the problem
+ * @param reason error message with details
+ */
+_MHD_NORETURN static void
+mhd_panic_std (void *cls,
+               const char *file,
+               unsigned int line,
+               const char *reason)
+{
+  (void) cls; /* Mute compiler warning. */
+#ifdef HAVE_MESSAGES
+  fprintf (stderr,
+           _ ("Fatal error in GNU libmicrohttpd %s:%u: %s\n"),
+           file,
+           line,
+           reason);
+#else  /* ! HAVE_MESSAGES */
+  (void) file;   /* Mute compiler warning. */
+  (void) line;   /* Mute compiler warning. */
+  (void) reason; /* Mute compiler warning. */
+#endif
+  abort ();
+}
+
+
+/**
+ * Sets the global error handler to a different implementation.
+ *
+ * @a cb will only be called in the case of typically fatal, serious internal
+ * consistency issues or serious system failures like failed lock of mutex.
+ *
+ * These issues should only arise in the case of serious memory corruption or
+ * similar problems with the architecture, there is no safe way to continue
+ * even for closing of the application.
+ *
+ * The default implementation that is used if no panic function is set simply
+ * prints an error message and calls `abort()`.
+ * Alternative implementations might call `exit()` or other similar functions.
+ *
+ * @param cb new error handler or NULL to use default handler
+ * @param cls passed to @a cb
+ * @ingroup logging
+ */
+_MHD_EXTERN void
+MHD_set_panic_func (MHD_PanicCallback cb,
+                    void *cls)
+{
+  if ((MHD_PanicCallback) NULL != cb)
+    mhd_panic = cb;
+  else
+    mhd_panic = &mhd_panic_std;
+
+  mhd_panic_cls = cls;
+}
diff --git a/src/microhttpd/mhd_panic.h b/src/microhttpd/mhd_panic.h
new file mode 100644
index 0000000..19fe9cd
--- /dev/null
+++ b/src/microhttpd/mhd_panic.h
@@ -0,0 +1,82 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff
+  Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_panic.h
+ * @brief  Declaration and macros for MHD_panic()
+ * @author Daniel Pittman
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_PANIC_H
+#define MHD_PANIC_H 1
+
+#include "mhd_options.h"
+
+#ifdef MHD_PANIC
+/* Override any possible defined MHD_PANIC macro with proper one */
+#undef MHD_PANIC
+#endif /* MHD_PANIC */
+
+/* If we have Clang or gcc >= 4.5, use __builtin_unreachable() */
+#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 4) || \
+  (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 5)
+#define BUILTIN_NOT_REACHED __builtin_unreachable ()
+#elif defined(_MSC_FULL_VER)
+#define BUILTIN_NOT_REACHED __assume (0)
+#else
+#define BUILTIN_NOT_REACHED
+#endif
+
+/* The MHD_PanicCallback type, but without main header. */
+/**
+ * Handler for fatal errors.
+ */
+extern void
+(*mhd_panic) (void *cls,
+              const char *file,
+              unsigned int line,
+              const char *reason);
+
+/**
+ * Closure argument for "mhd_panic".
+ */
+extern void *mhd_panic_cls;
+
+#ifdef HAVE_MESSAGES
+/**
+ * Trigger 'panic' action based on fatal errors.
+ *
+ * @param msg error message (const char *)
+ */
+#define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, msg); \
+                            BUILTIN_NOT_REACHED; } while (0)
+#else
+/**
+ * Trigger 'panic' action based on fatal errors.
+ *
+ * @param msg error message (const char *)
+ */
+#define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL); \
+                            BUILTIN_NOT_REACHED; } while (0)
+#endif
+
+#endif /* MHD_PANIC_H */
diff --git a/src/microhttpd/mhd_send.c b/src/microhttpd/mhd_send.c
new file mode 100644
index 0000000..fc1aaa0
--- /dev/null
+++ b/src/microhttpd/mhd_send.c
@@ -0,0 +1,1657 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017,2020 Karlson2k (Evgeny Grin), Full re-write of buffering and
+                     pushing, many bugs fixes, optimisations, sendfile() porting
+  Copyright (C) 2019 ng0 <ng0@n0.is>, Initial version of send() wrappers
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+ */
+
+/**
+ * @file microhttpd/mhd_send.c
+ * @brief Implementation of send() wrappers and helper functions.
+ * @author Karlson2k (Evgeny Grin)
+ * @author ng0 (N. Gillmann)
+ * @author Christian Grothoff
+ */
+
+/* Worth considering for future improvements and additions:
+ * NetBSD has no sendfile or sendfile64. The way to work
+ * with this seems to be to mmap the file and write(2) as
+ * large a chunk as possible to the socket. Alternatively,
+ * use madvise(..., MADV_SEQUENTIAL). */
+
+#include "mhd_send.h"
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#include <sys/sendfile.h>
+#endif /* MHD_LINUX_SOLARIS_SENDFILE */
+#if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE)
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/uio.h>
+#endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */
+#ifdef HAVE_SYS_PARAM_H
+/* For FreeBSD version identification */
+#include <sys/param.h>
+#endif /* HAVE_SYS_PARAM_H */
+#ifdef HAVE_SYSCONF
+#include <unistd.h>
+#endif /* HAVE_SYSCONF */
+#include "mhd_assert.h"
+
+#include "mhd_limits.h"
+
+#ifdef MHD_VECT_SEND
+#if (! defined(HAVE_SENDMSG) || ! defined(MSG_NOSIGNAL)) && \
+  defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \
+  defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED)
+#define _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED 1
+#endif /* (!HAVE_SENDMSG || !MSG_NOSIGNAL) &&
+          MHD_SEND_SPIPE_SUPPRESS_POSSIBLE && MHD_SEND_SPIPE_SUPPRESS_NEEDED */
+#endif /* MHD_VECT_SEND */
+
+/**
+ * sendfile() chuck size
+ */
+#define MHD_SENFILE_CHUNK_         (0x20000)
+
+/**
+ * sendfile() chuck size for thread-per-connection
+ */
+#define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000)
+
+#ifdef HAVE_FREEBSD_SENDFILE
+#ifdef SF_FLAGS
+/**
+ * FreeBSD sendfile() flags
+ */
+static int freebsd_sendfile_flags_;
+
+/**
+ * FreeBSD sendfile() flags for thread-per-connection
+ */
+static int freebsd_sendfile_flags_thd_p_c_;
+
+
+/**
+ * Initialises variables for FreeBSD's sendfile()
+ */
+static void
+freebsd_sendfile_init_ (void)
+{
+  long sys_page_size = sysconf (_SC_PAGESIZE);
+  if (0 >= sys_page_size)
+  {   /* Failed to get page size. */
+    freebsd_sendfile_flags_ = SF_NODISKIO;
+    freebsd_sendfile_flags_thd_p_c_ = SF_NODISKIO;
+  }
+  else
+  {
+    freebsd_sendfile_flags_ =
+      SF_FLAGS ((uint16_t) ((MHD_SENFILE_CHUNK_ + sys_page_size - 1)
+                            / sys_page_size), SF_NODISKIO);
+    freebsd_sendfile_flags_thd_p_c_ =
+      SF_FLAGS ((uint16_t) ((MHD_SENFILE_CHUNK_THR_P_C_ + sys_page_size - 1)
+                            / sys_page_size), SF_NODISKIO);
+  }
+}
+
+
+#endif /* SF_FLAGS */
+#endif /* HAVE_FREEBSD_SENDFILE */
+
+
+#if defined(HAVE_SYSCONF) && defined(_SC_IOV_MAX)
+/**
+ * Current IOV_MAX system value
+ */
+static unsigned long mhd_iov_max_ = 0;
+
+static void
+iov_max_init_ (void)
+{
+  long res = sysconf (_SC_IOV_MAX);
+  if (res >= 0)
+    mhd_iov_max_ = (unsigned long) res;
+  else
+  {
+#if defined(IOV_MAX)
+    mhd_iov_max_ = IOV_MAX;
+#else  /* ! IOV_MAX */
+    mhd_iov_max_ = 8; /* Should be the safe limit */
+#endif /* ! IOV_MAX */
+  }
+}
+
+
+/**
+ * IOV_MAX (run-time) value
+ */
+#define _MHD_IOV_MAX    mhd_iov_max_
+#elif defined(IOV_MAX)
+
+/**
+ * IOV_MAX (static) value
+ */
+#define _MHD_IOV_MAX    IOV_MAX
+#endif /* HAVE_SYSCONF && _SC_IOV_MAX */
+
+
+/**
+ * Initialises static variables
+ */
+void
+MHD_send_init_static_vars_ (void)
+{
+#ifdef HAVE_FREEBSD_SENDFILE
+  /* FreeBSD 11 and later allow to specify read-ahead size
+   * and handles SF_NODISKIO differently.
+   * SF_FLAGS defined only on FreeBSD 11 and later. */
+#ifdef SF_FLAGS
+  freebsd_sendfile_init_ ();
+#endif /* SF_FLAGS */
+#endif /* HAVE_FREEBSD_SENDFILE */
+#if defined(HAVE_SYSCONF) && defined(_SC_IOV_MAX)
+  iov_max_init_ ();
+#endif /* HAVE_SYSCONF && _SC_IOV_MAX */
+}
+
+
+bool
+MHD_connection_set_nodelay_state_ (struct MHD_Connection *connection,
+                                   bool nodelay_state)
+{
+#ifdef TCP_NODELAY
+  const MHD_SCKT_OPT_BOOL_ off_val = 0;
+  const MHD_SCKT_OPT_BOOL_ on_val = 1;
+  int err_code;
+
+  if (_MHD_YES == connection->is_nonip)
+    return false;
+
+  if (0 == setsockopt (connection->socket_fd,
+                       IPPROTO_TCP,
+                       TCP_NODELAY,
+                       (const void *) (nodelay_state ? &on_val : &off_val),
+                       sizeof (off_val)))
+  {
+    connection->sk_nodelay = nodelay_state;
+    return true;
+  }
+
+  err_code = MHD_socket_get_error_ ();
+  if (MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_EINVAL_) ||
+      MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOPROTOOPT_) ||
+      MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOTSOCK_))
+  {
+    if (_MHD_UNKNOWN == connection->is_nonip)
+      connection->is_nonip = _MHD_YES;
+#ifdef HAVE_MESSAGES
+    else
+    {
+      MHD_DLOG (connection->daemon,
+                _ ("Setting %s option to %s state failed "
+                   "for TCP/IP socket %d: %s\n"),
+                "TCP_NODELAY",
+                nodelay_state ? _ ("ON") : _ ("OFF"),
+                (int) connection->socket_fd,
+                MHD_socket_strerr_ (err_code));
+    }
+#endif /* HAVE_MESSAGES */
+  }
+#ifdef HAVE_MESSAGES
+  else
+  {
+    MHD_DLOG (connection->daemon,
+              _ ("Setting %s option to %s state failed: %s\n"),
+              "TCP_NODELAY",
+              nodelay_state ? _ ("ON") : _ ("OFF"),
+              MHD_socket_strerr_ (err_code));
+  }
+#endif /* HAVE_MESSAGES */
+
+#else  /* ! TCP_NODELAY */
+  (void) connection; (void) nodelay_state; /* Mute compiler warnings */
+#endif /* ! TCP_NODELAY */
+  return false;
+}
+
+
+/**
+ * Set required cork state for connection socket
+ *
+ * The function automatically updates sk_corked state.
+ *
+ * @param connection the connection to manipulate
+ * @param cork_state the requested new state of socket
+ * @return true if succeed, false if failed or not supported
+ *         by the current platform / kernel.
+ */
+bool
+MHD_connection_set_cork_state_ (struct MHD_Connection *connection,
+                                bool cork_state)
+{
+#if defined(MHD_TCP_CORK_NOPUSH)
+  const MHD_SCKT_OPT_BOOL_ off_val = 0;
+  const MHD_SCKT_OPT_BOOL_ on_val = 1;
+  int err_code;
+
+  if (_MHD_YES == connection->is_nonip)
+    return false;
+  if (0 == setsockopt (connection->socket_fd,
+                       IPPROTO_TCP,
+                       MHD_TCP_CORK_NOPUSH,
+                       (const void *) (cork_state ? &on_val : &off_val),
+                       sizeof (off_val)))
+  {
+    connection->sk_corked = cork_state;
+    return true;
+  }
+
+  err_code = MHD_socket_get_error_ ();
+  if (MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_EINVAL_) ||
+      MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOPROTOOPT_) ||
+      MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOTSOCK_))
+  {
+    if (_MHD_UNKNOWN == connection->is_nonip)
+      connection->is_nonip = _MHD_YES;
+#ifdef HAVE_MESSAGES
+    else
+    {
+      MHD_DLOG (connection->daemon,
+                _ ("Setting %s option to %s state failed "
+                   "for TCP/IP socket %d: %s\n"),
+#ifdef TCP_CORK
+                "TCP_CORK",
+#else  /* ! TCP_CORK */
+                "TCP_NOPUSH",
+#endif /* ! TCP_CORK */
+                cork_state ? _ ("ON") : _ ("OFF"),
+                (int) connection->socket_fd,
+                MHD_socket_strerr_ (err_code));
+    }
+#endif /* HAVE_MESSAGES */
+  }
+#ifdef HAVE_MESSAGES
+  else
+  {
+    MHD_DLOG (connection->daemon,
+              _ ("Setting %s option to %s state failed: %s\n"),
+#ifdef TCP_CORK
+              "TCP_CORK",
+#else  /* ! TCP_CORK */
+              "TCP_NOPUSH",
+#endif /* ! TCP_CORK */
+              cork_state ? _ ("ON") : _ ("OFF"),
+              MHD_socket_strerr_ (err_code));
+  }
+#endif /* HAVE_MESSAGES */
+
+#else  /* ! MHD_TCP_CORK_NOPUSH */
+  (void) connection; (void) cork_state; /* Mute compiler warnings. */
+#endif /* ! MHD_TCP_CORK_NOPUSH */
+  return false;
+}
+
+
+/**
+ * Handle pre-send setsockopt calls.
+ *
+ * @param connection the MHD_Connection structure
+ * @param plain_send set to true if plain send() or sendmsg() will be called,
+ *                   set to false if TLS socket send(), sendfile() or
+ *                   writev() will be called.
+ * @param push_data whether to push data to the network from buffers after
+ *                  the next call of send function.
+ */
+static void
+pre_send_setopt (struct MHD_Connection *connection,
+                 bool plain_send,
+                 bool push_data)
+{
+  /* Try to buffer data if not sending the final piece.
+   * Final piece is indicated by push_data == true. */
+  const bool buffer_data = (! push_data);
+
+  if (_MHD_YES == connection->is_nonip)
+    return;
+  /* The goal is to minimise the total number of additional sys-calls
+   * before and after send().
+   * The following tricky (over-)complicated algorithm typically use zero,
+   * one or two additional sys-calls (depending on OS) for each response. */
+
+  if (buffer_data)
+  {
+    /* Need to buffer data if possible. */
+#ifdef MHD_USE_MSG_MORE
+    if (plain_send)
+      return; /* Data is buffered by send() with MSG_MORE flag.
+               * No need to check or change anything. */
+#else  /* ! MHD_USE_MSG_MORE */
+    (void) plain_send; /* Mute compiler warning. */
+#endif /* ! MHD_USE_MSG_MORE */
+
+#ifdef MHD_TCP_CORK_NOPUSH
+    if (_MHD_ON == connection->sk_corked)
+      return; /* The connection was already corked. */
+
+    if (MHD_connection_set_cork_state_ (connection, true))
+      return; /* The connection has been corked. */
+
+    /* Failed to cork the connection.
+     * Really unlikely to happen on TCP connections. */
+#endif /* MHD_TCP_CORK_NOPUSH */
+    if (_MHD_OFF == connection->sk_nodelay)
+      return; /* TCP_NODELAY was not set for the socket.
+               * Nagle's algorithm will buffer some data. */
+
+    /* Try to reset TCP_NODELAY state for the socket.
+     * Ignore possible error as no other options exist to
+     * buffer data. */
+    MHD_connection_set_nodelay_state_ (connection, false);
+    /* TCP_NODELAY has been (hopefully) reset for the socket.
+     * Nagle's algorithm will buffer some data. */
+    return;
+  }
+
+  /* Need to push data after send() */
+  /* If additional sys-call is required prefer to make it after the send()
+   * as the next send() may consume only part of the prepared data and
+   * more send() calls will be used. */
+#ifdef MHD_TCP_CORK_NOPUSH
+#ifdef _MHD_CORK_RESET_PUSH_DATA
+#ifdef _MHD_CORK_RESET_PUSH_DATA_ALWAYS
+  /* Data can be pushed immediately by uncorking socket regardless of
+   * cork state before. */
+  /* This is typical for Linux, no other kernel with
+   * such behavior are known so far. */
+
+  /* No need to check the current state of TCP_CORK / TCP_NOPUSH
+   * as reset of cork will push the data anyway. */
+  return; /* Data may be pushed by resetting of
+           * TCP_CORK / TCP_NOPUSH after send() */
+#else  /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */
+  /* Reset of TCP_CORK / TCP_NOPUSH will push the data
+   * only if socket is corked. */
+
+#ifdef _MHD_NODELAY_SET_PUSH_DATA_ALWAYS
+  /* Data can be pushed immediately by setting TCP_NODELAY regardless
+   * of TCP_NODDELAY or corking state before. */
+
+  /* Dead code currently, no known kernels with such behavior. */
+  return; /* Data may be pushed by setting of TCP_NODELAY after send().
+             No need to make extra sys-calls before send().*/
+#else  /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */
+
+#ifdef _MHD_NODELAY_SET_PUSH_DATA
+  /* Setting of TCP_NODELAY will push the data only if
+   * both TCP_NODELAY and TCP_CORK / TCP_NOPUSH were not set. */
+
+  /* Data can be pushed immediately by uncorking socket if
+   * socket was corked before or by setting TCP_NODELAY if
+   * socket was not corked and TCP_NODELAY was not set before. */
+
+  /* Dead code currently as Linux is the only kernel that push
+   * data by setting of TCP_NODELAY and Linux push data always. */
+#else  /* ! _MHD_NODELAY_SET_PUSH_DATA */
+  /* Data can be pushed immediately by uncorking socket or
+   * can be pushed by send() on uncorked socket if
+   * TCP_NODELAY was set *before*. */
+
+  /* This is typical FreeBSD behavior. */
+#endif /* ! _MHD_NODELAY_SET_PUSH_DATA */
+
+  if (_MHD_ON == connection->sk_corked)
+    return; /* Socket is corked. Data can be pushed by resetting of
+             * TCP_CORK / TCP_NOPUSH after send() */
+  else if (_MHD_OFF == connection->sk_corked)
+  {
+    /* The socket is not corked. */
+    if (_MHD_ON == connection->sk_nodelay)
+      return; /* TCP_NODELAY was already set,
+               * data will be pushed automatically by the next send() */
+#ifdef _MHD_NODELAY_SET_PUSH_DATA
+    else if (_MHD_UNKNOWN == connection->sk_nodelay)
+    {
+      /* Setting TCP_NODELAY may push data.
+       * Cork socket here and uncork after send(). */
+      if (MHD_connection_set_cork_state_ (connection, true))
+        return; /* The connection has been corked.
+                 * Data can be pushed by resetting of
+                 * TCP_CORK / TCP_NOPUSH after send() */
+      else
+      {
+        /* The socket cannot be corked.
+         * Really unlikely to happen on TCP connections */
+        /* Have to set TCP_NODELAY.
+         * If TCP_NODELAY real system state was OFF then
+         * already buffered data may be pushed here, but this is unlikely
+         * to happen as it is only a backup solution when corking has failed.
+         * Ignore possible error here as no other options exist to
+         * push data. */
+        MHD_connection_set_nodelay_state_ (connection, true);
+        /* TCP_NODELAY has been (hopefully) set for the socket.
+         * The data will be pushed by the next send(). */
+        return;
+      }
+    }
+#endif /* _MHD_NODELAY_SET_PUSH_DATA */
+    else
+    {
+#ifdef _MHD_NODELAY_SET_PUSH_DATA
+      /* TCP_NODELAY was switched off and
+       * the socket is not corked. */
+#else  /* ! _MHD_NODELAY_SET_PUSH_DATA */
+      /* Socket is not corked and TCP_NODELAY was not set or unknown. */
+#endif /* ! _MHD_NODELAY_SET_PUSH_DATA */
+
+      /* At least one additional sys-call is required. */
+      /* Setting TCP_NODELAY is optimal here as data will be pushed
+       * automatically by the next send() and no additional
+       * sys-call are needed after the send(). */
+      if (MHD_connection_set_nodelay_state_ (connection, true))
+        return;
+      else
+      {
+        /* Failed to set TCP_NODELAY for the socket.
+         * Really unlikely to happen on TCP connections. */
+        /* Cork the socket here and make additional sys-call
+         * to uncork the socket after send(). */
+        /* Ignore possible error here as no other options exist to
+         * push data. */
+        MHD_connection_set_cork_state_ (connection, true);
+        /* The connection has been (hopefully) corked.
+         * Data can be pushed by resetting of TCP_CORK / TCP_NOPUSH
+         * after send() */
+        return;
+      }
+    }
+  }
+  /* Corked state is unknown. Need to make sys-call here otherwise
+   * data may not be pushed. */
+  if (MHD_connection_set_cork_state_ (connection, true))
+    return; /* The connection has been corked.
+             * Data can be pushed by resetting of
+             * TCP_CORK / TCP_NOPUSH after send() */
+  /* The socket cannot be corked.
+   * Really unlikely to happen on TCP connections */
+  if (_MHD_ON == connection->sk_nodelay)
+    return; /* TCP_NODELAY was already set,
+             * data will be pushed by the next send() */
+  /* Have to set TCP_NODELAY. */
+#ifdef _MHD_NODELAY_SET_PUSH_DATA
+  /* If TCP_NODELAY state was unknown (external connection) then
+   * already buffered data may be pushed here, but this is unlikely
+   * to happen as it is only a backup solution when corking has failed. */
+#endif /* _MHD_NODELAY_SET_PUSH_DATA */
+  /* Ignore possible error here as no other options exist to
+   * push data. */
+  MHD_connection_set_nodelay_state_ (connection, true);
+  /* TCP_NODELAY has been (hopefully) set for the socket.
+   * The data will be pushed by the next send(). */
+  return;
+#endif /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */
+#endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */
+#else  /* ! _MHD_CORK_RESET_PUSH_DATA */
+  /* Neither uncorking the socket or setting TCP_NODELAY
+   * push the data immediately. */
+  /* The only way to push the data is to use send() on uncorked
+   * socket with TCP_NODELAY switched on . */
+
+  /* This is a typical *BSD (except FreeBSD) and Darwin behavior. */
+
+  /* Uncork socket if socket wasn't uncorked. */
+  if (_MHD_OFF != connection->sk_corked)
+    MHD_connection_set_cork_state_ (connection, false);
+
+  /* Set TCP_NODELAY if it wasn't set. */
+  if (_MHD_ON != connection->sk_nodelay)
+    MHD_connection_set_nodelay_state_ (connection, true);
+
+  return;
+#endif /* ! _MHD_CORK_RESET_PUSH_DATA */
+#else  /* ! MHD_TCP_CORK_NOPUSH */
+  /* Buffering of data is controlled only by
+   * Nagel's algorithm. */
+  /* Set TCP_NODELAY if it wasn't set. */
+  if (_MHD_ON != connection->sk_nodelay)
+    MHD_connection_set_nodelay_state_ (connection, true);
+#endif /* ! MHD_TCP_CORK_NOPUSH */
+}
+
+
+#ifndef _MHD_CORK_RESET_PUSH_DATA_ALWAYS
+/**
+ * Send zero-sized data
+ *
+ * This function use send of zero-sized data to kick data from the socket
+ * buffers to the network. The socket must not be corked and must have
+ * TCP_NODELAY switched on.
+ * Used only as last resort option, when other options are failed due to
+ * some errors.
+ * Should not be called on typical data processing.
+ * @return true if succeed, false if failed
+ */
+static bool
+zero_send_ (struct MHD_Connection *connection)
+{
+  int dummy;
+
+  if (_MHD_YES == connection->is_nonip)
+    return false;
+  mhd_assert (_MHD_OFF == connection->sk_corked);
+  mhd_assert (_MHD_ON == connection->sk_nodelay);
+  dummy = 0; /* Mute compiler and analyzer warnings */
+  if (0 == MHD_send_ (connection->socket_fd, &dummy, 0))
+    return true;
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (connection->daemon,
+            _ ("Zero-send failed: %s\n"),
+            MHD_socket_last_strerr_ () );
+#endif /* HAVE_MESSAGES */
+  return false;
+}
+
+
+#endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */
+
+/**
+ * Handle post-send setsockopt calls.
+ *
+ * @param connection the MHD_Connection structure
+ * @param plain_send_next set to true if plain send() or sendmsg() will be
+ *                        called next,
+ *                        set to false if TLS socket send(), sendfile() or
+ *                        writev() will be called next.
+ * @param push_data whether to push data to the network from buffers
+ */
+static void
+post_send_setopt (struct MHD_Connection *connection,
+                  bool plain_send_next,
+                  bool push_data)
+{
+  /* Try to buffer data if not sending the final piece.
+   * Final piece is indicated by push_data == true. */
+  const bool buffer_data = (! push_data);
+
+  if (_MHD_YES == connection->is_nonip)
+    return;
+  if (buffer_data)
+    return; /* Nothing to do after send(). */
+
+#ifndef MHD_USE_MSG_MORE
+  (void) plain_send_next; /* Mute compiler warning */
+#endif /* ! MHD_USE_MSG_MORE */
+
+  /* Need to push data. */
+#ifdef MHD_TCP_CORK_NOPUSH
+#ifdef _MHD_CORK_RESET_PUSH_DATA_ALWAYS
+#ifdef _MHD_NODELAY_SET_PUSH_DATA_ALWAYS
+#ifdef MHD_USE_MSG_MORE
+  if (_MHD_OFF == connection->sk_corked)
+  {
+    if (_MHD_ON == connection->sk_nodelay)
+      return; /* Data was already pushed by send(). */
+  }
+  /* This is Linux kernel. There are options:
+   * * Push the data by setting of TCP_NODELAY (without change
+   *   of the cork on the socket),
+   * * Push the data by resetting of TCP_CORK.
+   * The optimal choice depends on the next final send functions
+   * used on the same socket. If TCP_NODELAY wasn't set then push
+   * data by setting TCP_NODELAY (TCP_NODELAY will not be removed
+   * and is needed to push the data by send() without MSG_MORE).
+   * If send()/sendmsg() will be used next than push data by
+   * resetting of TCP_CORK so next send without MSG_MORE will push
+   * data to the network (without additional sys-call to push data).
+   * If next final send function will not support MSG_MORE (like
+   * sendfile() or TLS-connection) than push data by setting
+   * TCP_NODELAY so socket will remain corked (no additional
+   * sys-call before next send()). */
+  if ((_MHD_ON != connection->sk_nodelay) ||
+      (! plain_send_next))
+  {
+    if (MHD_connection_set_nodelay_state_ (connection, true))
+      return; /* Data has been pushed by TCP_NODELAY. */
+    /* Failed to set TCP_NODELAY for the socket.
+     * Really unlikely to happen on TCP connections. */
+    if (MHD_connection_set_cork_state_ (connection, false))
+      return; /* Data has been pushed by uncorking the socket. */
+    /* Failed to uncork the socket.
+     * Really unlikely to happen on TCP connections. */
+
+    /* The socket cannot be uncorked, no way to push data */
+  }
+  else
+  {
+    if (MHD_connection_set_cork_state_ (connection, false))
+      return; /* Data has been pushed by uncorking the socket. */
+    /* Failed to uncork the socket.
+     * Really unlikely to happen on TCP connections. */
+    if (MHD_connection_set_nodelay_state_ (connection, true))
+      return; /* Data has been pushed by TCP_NODELAY. */
+    /* Failed to set TCP_NODELAY for the socket.
+     * Really unlikely to happen on TCP connections. */
+
+    /* The socket cannot be uncorked, no way to push data */
+  }
+#else  /* ! MHD_USE_MSG_MORE */
+  /* Use setting of TCP_NODELAY here to avoid sys-call
+   * for corking the socket during sending of the next response. */
+  if (MHD_connection_set_nodelay_state_ (connection, true))
+    return; /* Data was pushed by TCP_NODELAY. */
+  /* Failed to set TCP_NODELAY for the socket.
+   * Really unlikely to happen on TCP connections. */
+  if (MHD_connection_set_cork_state_ (connection, false))
+    return; /* Data was pushed by uncorking the socket. */
+  /* Failed to uncork the socket.
+   * Really unlikely to happen on TCP connections. */
+
+  /* The socket remains corked, no way to push data */
+#endif /* ! MHD_USE_MSG_MORE */
+#else  /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */
+  if (MHD_connection_set_cork_state_ (connection, false))
+    return; /* Data was pushed by uncorking the socket. */
+  /* Failed to uncork the socket.
+   * Really unlikely to happen on TCP connections. */
+  return; /* Socket remains corked, no way to push data */
+#endif /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */
+#else  /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */
+  /* This is a typical *BSD or Darwin kernel. */
+
+  if (_MHD_OFF == connection->sk_corked)
+  {
+    if (_MHD_ON == connection->sk_nodelay)
+      return; /* Data was already pushed by send(). */
+
+    /* Unlikely to reach this code.
+     * TCP_NODELAY should be turned on before send(). */
+    if (MHD_connection_set_nodelay_state_ (connection, true))
+    {
+      /* TCP_NODELAY has been set on uncorked socket.
+       * Use zero-send to push the data. */
+      if (zero_send_ (connection))
+        return; /* The data has been pushed by zero-send. */
+    }
+
+    /* Failed to push the data by all means. */
+    /* There is nothing left to try. */
+  }
+  else
+  {
+#ifdef _MHD_CORK_RESET_PUSH_DATA
+    enum MHD_tristate old_cork_state = connection->sk_corked;
+#endif /* _MHD_CORK_RESET_PUSH_DATA */
+    /* The socket is corked or cork state is unknown. */
+
+    if (MHD_connection_set_cork_state_ (connection, false))
+    {
+#ifdef _MHD_CORK_RESET_PUSH_DATA
+      /* FreeBSD kernel */
+      if (_MHD_OFF == old_cork_state)
+        return; /* Data has been pushed by uncorking the socket. */
+#endif /* _MHD_CORK_RESET_PUSH_DATA */
+
+      /* Unlikely to reach this code.
+       * The data should be pushed by uncorking (FreeBSD) or
+       * the socket should be uncorked before send(). */
+      if ((_MHD_ON == connection->sk_nodelay) ||
+          (MHD_connection_set_nodelay_state_ (connection, true)))
+      {
+        /* TCP_NODELAY is turned ON on uncorked socket.
+         * Use zero-send to push the data. */
+        if (zero_send_ (connection))
+          return; /* The data has been pushed by zero-send. */
+      }
+    }
+    /* The socket remains corked. Data cannot be pushed. */
+  }
+#endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */
+#else  /* ! MHD_TCP_CORK_NOPUSH */
+  /* Corking is not supported. Buffering is controlled
+   * by TCP_NODELAY only. */
+  mhd_assert (_MHD_ON != connection->sk_corked);
+  if (_MHD_ON == connection->sk_nodelay)
+    return; /* Data was already pushed by send(). */
+
+  /* Unlikely to reach this code.
+   * TCP_NODELAY should be turned on before send(). */
+  if (MHD_connection_set_nodelay_state_ (connection, true))
+  {
+    /* TCP_NODELAY has been set.
+     * Use zero-send to push the data. */
+    if (zero_send_ (connection))
+      return; /* The data has been pushed by zero-send. */
+  }
+
+  /* Failed to push the data. */
+#endif /* ! MHD_TCP_CORK_NOPUSH */
+#ifdef HAVE_MESSAGES
+  MHD_DLOG (connection->daemon,
+            _ ("Failed to push the data from buffers to the network. "
+               "Client may experience some delay "
+               "(usually in range 200ms - 5 sec).\n"));
+#endif /* HAVE_MESSAGES */
+  return;
+}
+
+
+ssize_t
+MHD_send_data_ (struct MHD_Connection *connection,
+                const char *buffer,
+                size_t buffer_size,
+                bool push_data)
+{
+  MHD_socket s = connection->socket_fd;
+  ssize_t ret;
+#ifdef HTTPS_SUPPORT
+  const bool tls_conn = (connection->daemon->options & MHD_USE_TLS);
+#else  /* ! HTTPS_SUPPORT */
+  const bool tls_conn = false;
+#endif /* ! HTTPS_SUPPORT */
+
+  if ( (MHD_INVALID_SOCKET == s) ||
+       (MHD_CONNECTION_CLOSED == connection->state) )
+  {
+    return MHD_ERR_NOTCONN_;
+  }
+
+  if (buffer_size > SSIZE_MAX)
+  {
+    buffer_size = SSIZE_MAX; /* Max return value */
+    push_data = false; /* Incomplete send */
+  }
+
+  if (tls_conn)
+  {
+#ifdef HTTPS_SUPPORT
+    pre_send_setopt (connection, (! tls_conn), push_data);
+    ret = gnutls_record_send (connection->tls_session,
+                              buffer,
+                              buffer_size);
+    if (GNUTLS_E_AGAIN == ret)
+    {
+#ifdef EPOLL_SUPPORT
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif
+      return MHD_ERR_AGAIN_;
+    }
+    if (GNUTLS_E_INTERRUPTED == ret)
+      return MHD_ERR_AGAIN_;
+    if ( (GNUTLS_E_ENCRYPTION_FAILED == ret) ||
+         (GNUTLS_E_INVALID_SESSION == ret) ||
+         (GNUTLS_E_COMPRESSION_FAILED == ret) ||
+         (GNUTLS_E_EXPIRED == ret) ||
+         (GNUTLS_E_HASH_FAILED == ret) )
+      return MHD_ERR_TLS_;
+    if ( (GNUTLS_E_PUSH_ERROR == ret) ||
+         (GNUTLS_E_INTERNAL_ERROR == ret) ||
+         (GNUTLS_E_CRYPTODEV_IOCTL_ERROR == ret) ||
+         (GNUTLS_E_CRYPTODEV_DEVICE_ERROR == ret) )
+      return MHD_ERR_PIPE_;
+#if defined(GNUTLS_E_PREMATURE_TERMINATION)
+    if (GNUTLS_E_PREMATURE_TERMINATION == ret)
+      return MHD_ERR_CONNRESET_;
+#elif defined(GNUTLS_E_UNEXPECTED_PACKET_LENGTH)
+    if (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == ret)
+      return MHD_ERR_CONNRESET_;
+#endif /* GNUTLS_E_UNEXPECTED_PACKET_LENGTH */
+    if (GNUTLS_E_MEMORY_ERROR == ret)
+      return MHD_ERR_NOMEM_;
+    if (ret < 0)
+    {
+      /* Treat any other error as hard error. */
+      return MHD_ERR_NOTCONN_;
+    }
+#ifdef EPOLL_SUPPORT
+    /* Unlike non-TLS connections, do not reset "write-ready" if
+     * sent amount smaller than provided amount, as TLS
+     * connections may break data into smaller parts for sending. */
+#endif /* EPOLL_SUPPORT */
+#else  /* ! HTTPS_SUPPORT  */
+    ret = MHD_ERR_NOTCONN_;
+#endif /* ! HTTPS_SUPPORT  */
+  }
+  else
+  {
+    /* plaintext transmission */
+    if (buffer_size > MHD_SCKT_SEND_MAX_SIZE_)
+    {
+      buffer_size = MHD_SCKT_SEND_MAX_SIZE_; /* send() return value limit */
+      push_data = false; /* Incomplete send */
+    }
+
+    pre_send_setopt (connection, (! tls_conn), push_data);
+#ifdef MHD_USE_MSG_MORE
+    ret = MHD_send4_ (s,
+                      buffer,
+                      buffer_size,
+                      push_data ? 0 : MSG_MORE);
+#else
+    ret = MHD_send4_ (s,
+                      buffer,
+                      buffer_size,
+                      0);
+#endif
+
+    if (0 > ret)
+    {
+      const int err = MHD_socket_get_error_ ();
+
+      if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+      {
+#ifdef EPOLL_SUPPORT
+        /* EAGAIN, no longer write-ready */
+        connection->epoll_state &=
+          ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+        return MHD_ERR_AGAIN_;
+      }
+      if (MHD_SCKT_ERR_IS_EINTR_ (err))
+        return MHD_ERR_AGAIN_;
+      if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+        return MHD_ERR_CONNRESET_;
+      if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_))
+        return MHD_ERR_PIPE_;
+      if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_))
+        return MHD_ERR_OPNOTSUPP_;
+      if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_))
+        return MHD_ERR_NOTCONN_;
+      if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_))
+        return MHD_ERR_INVAL_;
+      if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))
+        return MHD_ERR_NOMEM_;
+      if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_))
+        return MHD_ERR_BADF_;
+      /* Treat any other error as a hard error. */
+      return MHD_ERR_NOTCONN_;
+    }
+#ifdef EPOLL_SUPPORT
+    else if (buffer_size > (size_t) ret)
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+  }
+
+  /* If there is a need to push the data from network buffers
+   * call post_send_setopt(). */
+  /* If TLS connection is used then next final send() will be
+   * without MSG_MORE support. If non-TLS connection is used
+   * it's unknown whether sendfile() will be used or not so
+   * assume that next call will be the same, like this call. */
+  if ( (push_data) &&
+       (buffer_size == (size_t) ret) )
+    post_send_setopt (connection, (! tls_conn), push_data);
+
+  return ret;
+}
+
+
+ssize_t
+MHD_send_hdr_and_body_ (struct MHD_Connection *connection,
+                        const char *header,
+                        size_t header_size,
+                        bool never_push_hdr,
+                        const char *body,
+                        size_t body_size,
+                        bool complete_response)
+{
+  ssize_t ret;
+  bool push_hdr;
+  bool push_body;
+  MHD_socket s = connection->socket_fd;
+#ifndef _WIN32
+#define _MHD_SEND_VEC_MAX   MHD_SCKT_SEND_MAX_SIZE_
+#else  /* ! _WIN32 */
+#define _MHD_SEND_VEC_MAX   UINT32_MAX
+#endif /* ! _WIN32 */
+#ifdef MHD_VECT_SEND
+#if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV)
+  struct iovec vector[2];
+#ifdef HAVE_SENDMSG
+  struct msghdr msg;
+#endif /* HAVE_SENDMSG */
+#endif /* HAVE_SENDMSG || HAVE_WRITEV */
+#ifdef _WIN32
+  WSABUF vector[2];
+  DWORD vec_sent;
+#endif /* _WIN32 */
+  bool no_vec; /* Is vector-send() disallowed? */
+
+  no_vec = false;
+#ifdef HTTPS_SUPPORT
+  no_vec = no_vec || (connection->daemon->options & MHD_USE_TLS);
+#endif /* HTTPS_SUPPORT */
+#if (! defined(HAVE_SENDMSG) || ! defined(MSG_NOSIGNAL) ) && \
+  defined(MHD_SEND_SPIPE_SEND_SUPPRESS_POSSIBLE) && \
+  defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED)
+  no_vec = no_vec || (! connection->daemon->sigpipe_blocked &&
+                      ! connection->sk_spipe_suppress);
+#endif /* (!HAVE_SENDMSG || ! MSG_NOSIGNAL) &&
+          MHD_SEND_SPIPE_SEND_SUPPRESS_POSSIBLE &&
+          MHD_SEND_SPIPE_SUPPRESS_NEEDED */
+#endif /* MHD_VECT_SEND */
+
+  mhd_assert ( (NULL != body) || (0 == body_size) );
+
+  if ( (MHD_INVALID_SOCKET == s) ||
+       (MHD_CONNECTION_CLOSED == connection->state) )
+  {
+    return MHD_ERR_NOTCONN_;
+  }
+
+  push_body = complete_response;
+
+  if (! never_push_hdr)
+  {
+    if (! complete_response)
+      push_hdr = true; /* Push the header as the client may react
+                        * on header alone while the body data is
+                        * being prepared. */
+    else
+    {
+      if (1400 > (header_size + body_size))
+        push_hdr = false;  /* Do not push the header as complete
+                           * reply is already ready and the whole
+                           * reply most probably will fit into
+                           * the single IP packet. */
+      else
+        push_hdr = true;   /* Push header alone so client may react
+                           * on it while reply body is being delivered. */
+    }
+  }
+  else
+    push_hdr = false;
+
+  if (complete_response && (0 == body_size))
+    push_hdr = true; /* The header alone is equal to the whole response. */
+
+  if (
+#ifdef MHD_VECT_SEND
+    (no_vec) ||
+    (0 == body_size) ||
+    ((size_t) SSIZE_MAX <= header_size) ||
+    ((size_t) _MHD_SEND_VEC_MAX < header_size)
+#ifdef _WIN32
+    || ((size_t) UINT_MAX < header_size)
+#endif /* _WIN32 */
+#else  /* ! MHD_VECT_SEND */
+    true
+#endif /* ! MHD_VECT_SEND */
+    )
+  {
+    ret = MHD_send_data_ (connection,
+                          header,
+                          header_size,
+                          push_hdr);
+
+    if ( (header_size == (size_t) ret) &&
+         ((size_t) SSIZE_MAX > header_size) &&
+         (0 != body_size) &&
+         (connection->sk_nonblck) )
+    {
+      ssize_t ret2;
+      /* The header has been sent completely.
+       * Try to send the reply body without waiting for
+       * the next round. */
+      /* Make sure that sum of ret + ret2 will not exceed SSIZE_MAX as
+       * function needs to return positive value if succeed. */
+      if ( (((size_t) SSIZE_MAX) - ((size_t) ret)) <  body_size)
+      {
+        body_size = (((size_t) SSIZE_MAX) - ((size_t) ret));
+        complete_response = false;
+        push_body = complete_response;
+      }
+
+      ret2 = MHD_send_data_ (connection,
+                             body,
+                             body_size,
+                             push_body);
+      if (0 < ret2)
+        return ret + ret2; /* Total data sent */
+      if (MHD_ERR_AGAIN_ == ret2)
+        return ret;
+
+      return ret2; /* Error code */
+    }
+    return ret;
+  }
+#ifdef MHD_VECT_SEND
+
+  if ( ((size_t) SSIZE_MAX <= body_size) ||
+       ((size_t) SSIZE_MAX < (header_size + body_size)) )
+  {
+    /* Return value limit */
+    body_size = SSIZE_MAX - header_size;
+    complete_response = false;
+    push_body = complete_response;
+  }
+#if (SSIZE_MAX != _MHD_SEND_VEC_MAX) || (_MHD_SEND_VEC_MAX + 0 == 0)
+  if (((size_t) _MHD_SEND_VEC_MAX <= body_size) ||
+      ((size_t) _MHD_SEND_VEC_MAX < (header_size + body_size)))
+  {
+    /* Send total amount limit */
+    body_size = _MHD_SEND_VEC_MAX - header_size;
+    complete_response = false;
+    push_body = complete_response;
+  }
+#endif /* SSIZE_MAX != _MHD_SEND_VEC_MAX */
+
+  pre_send_setopt (connection,
+#ifdef HAVE_SENDMSG
+                   true,
+#else  /* ! HAVE_SENDMSG */
+                   false,
+#endif /* ! HAVE_SENDMSG */
+                   push_hdr || push_body);
+#if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV)
+  vector[0].iov_base = _MHD_DROP_CONST (header);
+  vector[0].iov_len = header_size;
+  vector[1].iov_base = _MHD_DROP_CONST (body);
+  vector[1].iov_len = body_size;
+
+#if defined(HAVE_SENDMSG)
+  memset (&msg, 0, sizeof(msg));
+  msg.msg_iov = vector;
+  msg.msg_iovlen = 2;
+
+  ret = sendmsg (s, &msg, MSG_NOSIGNAL_OR_ZERO);
+#elif defined(HAVE_WRITEV)
+  ret = writev (s, vector, 2);
+#endif /* HAVE_WRITEV */
+#endif /* HAVE_SENDMSG || HAVE_WRITEV */
+#ifdef _WIN32
+  if ((size_t) UINT_MAX < body_size)
+  {
+    /* Send item size limit */
+    body_size = UINT_MAX;
+    complete_response = false;
+    push_body = complete_response;
+  }
+  vector[0].buf = (char *) _MHD_DROP_CONST (header);
+  vector[0].len = (unsigned long) header_size;
+  vector[1].buf = (char *) _MHD_DROP_CONST (body);
+  vector[1].len = (unsigned long) body_size;
+
+  ret = WSASend (s, vector, 2, &vec_sent, 0, NULL, NULL);
+  if (0 == ret)
+    ret = (ssize_t) vec_sent;
+  else
+    ret = -1;
+#endif /* _WIN32 */
+
+  if (0 > ret)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* EAGAIN, no longer write-ready */
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+    if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+      return MHD_ERR_CONNRESET_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_))
+      return MHD_ERR_PIPE_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_))
+      return MHD_ERR_OPNOTSUPP_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_))
+      return MHD_ERR_NOTCONN_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_))
+      return MHD_ERR_INVAL_;
+    if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))
+      return MHD_ERR_NOMEM_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_))
+      return MHD_ERR_BADF_;
+    /* Treat any other error as a hard error. */
+    return MHD_ERR_NOTCONN_;
+  }
+#ifdef EPOLL_SUPPORT
+  else if ((header_size + body_size) > (size_t) ret)
+    connection->epoll_state &=
+      ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+
+  /* If there is a need to push the data from network buffers
+   * call post_send_setopt(). */
+  if ( (push_body) &&
+       ((header_size + body_size) == (size_t) ret) )
+  {
+    /* Complete reply has been sent. */
+    /* If TLS connection is used then next final send() will be
+     * without MSG_MORE support. If non-TLS connection is used
+     * it's unknown whether next 'send' will be plain send() / sendmsg() or
+     * sendfile() will be used so assume that next final send() will be
+     * the same, like for this response. */
+    post_send_setopt (connection,
+#ifdef HAVE_SENDMSG
+                      true,
+#else  /* ! HAVE_SENDMSG */
+                      false,
+#endif /* ! HAVE_SENDMSG */
+                      true);
+  }
+  else if ( (push_hdr) &&
+            (header_size <= (size_t) ret))
+  {
+    /* The header has been sent completely and there is a
+     * need to push the header data. */
+    /* Luckily the type of send function will be used next is known. */
+    post_send_setopt (connection,
+#if defined(_MHD_HAVE_SENDFILE)
+                      MHD_resp_sender_std == connection->rp.resp_sender,
+#else  /* ! _MHD_HAVE_SENDFILE */
+                      true,
+#endif /* ! _MHD_HAVE_SENDFILE */
+                      true);
+  }
+
+  return ret;
+#else  /* ! MHD_VECT_SEND */
+  mhd_assert (false);
+  return MHD_ERR_CONNRESET_; /* Unreachable. Mute warnings. */
+#endif /* ! MHD_VECT_SEND */
+}
+
+
+#if defined(_MHD_HAVE_SENDFILE)
+ssize_t
+MHD_send_sendfile_ (struct MHD_Connection *connection)
+{
+  ssize_t ret;
+  const int file_fd = connection->rp.response->fd;
+  uint64_t left;
+  uint64_t offsetu64;
+#ifndef HAVE_SENDFILE64
+  const uint64_t max_off_t = (uint64_t) OFF_T_MAX;
+#else  /* HAVE_SENDFILE64 */
+  const uint64_t max_off_t = (uint64_t) OFF64_T_MAX;
+#endif /* HAVE_SENDFILE64 */
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#ifndef HAVE_SENDFILE64
+  off_t offset;
+#else  /* HAVE_SENDFILE64 */
+  off64_t offset;
+#endif /* HAVE_SENDFILE64 */
+#endif /* MHD_LINUX_SOLARIS_SENDFILE */
+#ifdef HAVE_FREEBSD_SENDFILE
+  off_t sent_bytes;
+  int flags = 0;
+#endif
+#ifdef HAVE_DARWIN_SENDFILE
+  off_t len;
+#endif /* HAVE_DARWIN_SENDFILE */
+  const bool used_thr_p_c = (0 != (connection->daemon->options
+                                   & MHD_USE_THREAD_PER_CONNECTION));
+  const size_t chunk_size = used_thr_p_c ? MHD_SENFILE_CHUNK_THR_P_C_ :
+                            MHD_SENFILE_CHUNK_;
+  size_t send_size = 0;
+  bool push_data;
+  mhd_assert (MHD_resp_sender_sendfile == connection->rp.resp_sender);
+  mhd_assert (0 == (connection->daemon->options & MHD_USE_TLS));
+
+  offsetu64 = connection->rp.rsp_write_position
+              + connection->rp.response->fd_off;
+  if (max_off_t < offsetu64)
+  {   /* Retry to send with standard 'send()'. */
+    connection->rp.resp_sender = MHD_resp_sender_std;
+    return MHD_ERR_AGAIN_;
+  }
+
+  left = connection->rp.response->total_size
+         - connection->rp.rsp_write_position;
+
+  if ( (uint64_t) SSIZE_MAX < left)
+    left = SSIZE_MAX;
+
+  /* Do not allow system to stick sending on single fast connection:
+   * use 128KiB chunks (2MiB for thread-per-connection). */
+  if (chunk_size < left)
+  {
+    send_size = chunk_size;
+    push_data = false; /* No need to push data, there is more to send. */
+  }
+  else
+  {
+    send_size = (size_t) left;
+    push_data = true; /* Final piece of data, need to push to the network. */
+  }
+  pre_send_setopt (connection, false, push_data);
+
+#ifdef MHD_LINUX_SOLARIS_SENDFILE
+#ifndef HAVE_SENDFILE64
+  offset = (off_t) offsetu64;
+  ret = sendfile (connection->socket_fd,
+                  file_fd,
+                  &offset,
+                  send_size);
+#else  /* HAVE_SENDFILE64 */
+  offset = (off64_t) offsetu64;
+  ret = sendfile64 (connection->socket_fd,
+                    file_fd,
+                    &offset,
+                    send_size);
+#endif /* HAVE_SENDFILE64 */
+  if (0 > ret)
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* EAGAIN --- no longer write-ready */
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+#ifdef HAVE_LINUX_SENDFILE
+    if (MHD_SCKT_ERR_IS_ (err,
+                          MHD_SCKT_EBADF_))
+      return MHD_ERR_BADF_;
+    /* sendfile() failed with EINVAL if mmap()-like operations are not
+       supported for FD or other 'unusual' errors occurred, so we should try
+       to fall back to 'SEND'; see also this thread for info on
+       odd libc/Linux behavior with sendfile:
+       http://lists.gnu.org/archive/html/libmicrohttpd/2011-02/msg00015.html */
+    connection->rp.resp_sender = MHD_resp_sender_std;
+    return MHD_ERR_AGAIN_;
+#else  /* HAVE_SOLARIS_SENDFILE */
+    if ( (EAFNOSUPPORT == err) ||
+         (EINVAL == err) ||
+         (EOPNOTSUPP == err) )
+    {     /* Retry with standard file reader. */
+      connection->rp.resp_sender = MHD_resp_sender_std;
+      return MHD_ERR_AGAIN_;
+    }
+    if ( (ENOTCONN == err) ||
+         (EPIPE == err) )
+    {
+      return MHD_ERR_CONNRESET_;
+    }
+    return MHD_ERR_BADF_;   /* Fail hard */
+#endif /* HAVE_SOLARIS_SENDFILE */
+  }
+#ifdef EPOLL_SUPPORT
+  else if (send_size > (size_t) ret)
+    connection->epoll_state &=
+      ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+#elif defined(HAVE_FREEBSD_SENDFILE)
+#ifdef SF_FLAGS
+  flags = used_thr_p_c ?
+          freebsd_sendfile_flags_thd_p_c_ : freebsd_sendfile_flags_;
+#endif /* SF_FLAGS */
+  if (0 != sendfile (file_fd,
+                     connection->socket_fd,
+                     (off_t) offsetu64,
+                     send_size,
+                     NULL,
+                     &sent_bytes,
+                     flags))
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err) ||
+        MHD_SCKT_ERR_IS_EINTR_ (err) ||
+        (EBUSY == err) )
+    {
+      mhd_assert (SSIZE_MAX >= sent_bytes);
+      if (0 != sent_bytes)
+        return (ssize_t) sent_bytes;
+
+      return MHD_ERR_AGAIN_;
+    }
+    /* Some unrecoverable error. Possibly file FD is not suitable
+     * for sendfile(). Retry with standard send(). */
+    connection->rp.resp_sender = MHD_resp_sender_std;
+    return MHD_ERR_AGAIN_;
+  }
+  mhd_assert (0 < sent_bytes);
+  mhd_assert (SSIZE_MAX >= sent_bytes);
+  ret = (ssize_t) sent_bytes;
+#elif defined(HAVE_DARWIN_SENDFILE)
+  len = (off_t) send_size; /* chunk always fit */
+  if (0 != sendfile (file_fd,
+                     connection->socket_fd,
+                     (off_t) offsetu64,
+                     &len,
+                     NULL,
+                     0))
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err) ||
+        MHD_SCKT_ERR_IS_EINTR_ (err))
+    {
+      mhd_assert (0 <= len);
+      mhd_assert (SSIZE_MAX >= len);
+      mhd_assert (send_size >= (size_t) len);
+      if (0 != len)
+        return (ssize_t) len;
+
+      return MHD_ERR_AGAIN_;
+    }
+    if ((ENOTCONN == err) ||
+        (EPIPE == err) )
+      return MHD_ERR_CONNRESET_;
+    if ((ENOTSUP == err) ||
+        (EOPNOTSUPP == err) )
+    {     /* This file FD is not suitable for sendfile().
+           * Retry with standard send(). */
+      connection->rp.resp_sender = MHD_resp_sender_std;
+      return MHD_ERR_AGAIN_;
+    }
+    return MHD_ERR_BADF_;   /* Return hard error. */
+  }
+  mhd_assert (0 <= len);
+  mhd_assert (SSIZE_MAX >= len);
+  mhd_assert (send_size >= (size_t) len);
+  ret = (ssize_t) len;
+#endif /* HAVE_FREEBSD_SENDFILE */
+
+  /* If there is a need to push the data from network buffers
+   * call post_send_setopt(). */
+  /* It's unknown whether sendfile() will be used in the next
+   * response so assume that next response will be the same. */
+  if ( (push_data) &&
+       (send_size == (size_t) ret) )
+    post_send_setopt (connection, false, push_data);
+
+  return ret;
+}
+
+
+#endif /* _MHD_HAVE_SENDFILE */
+
+#if defined(MHD_VECT_SEND)
+
+
+/**
+ * Function sends iov data by system sendmsg or writev function.
+ *
+ * Connection must be in non-TLS (non-HTTPS) mode.
+ *
+ * @param connection the MHD connection structure
+ * @param r_iov the pointer to iov data structure with tracking
+ * @param push_data set to true to force push the data to the network from
+ *                  system buffers (usually set for the last piece of data),
+ *                  set to false to prefer holding incomplete network packets
+ *                  (more data will be send for the same reply).
+ * @return actual number of bytes sent
+ */
+static ssize_t
+send_iov_nontls (struct MHD_Connection *connection,
+                 struct MHD_iovec_track_ *const r_iov,
+                 bool push_data)
+{
+  ssize_t res;
+  size_t items_to_send;
+#ifdef HAVE_SENDMSG
+  struct msghdr msg;
+#elif defined(MHD_WINSOCK_SOCKETS)
+  DWORD bytes_sent;
+  DWORD cnt_w;
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  mhd_assert (0 == (connection->daemon->options & MHD_USE_TLS));
+
+  if ( (MHD_INVALID_SOCKET == connection->socket_fd) ||
+       (MHD_CONNECTION_CLOSED == connection->state) )
+  {
+    return MHD_ERR_NOTCONN_;
+  }
+
+  items_to_send = r_iov->cnt - r_iov->sent;
+#ifdef _MHD_IOV_MAX
+  if (_MHD_IOV_MAX < items_to_send)
+  {
+    mhd_assert (0 < _MHD_IOV_MAX);
+    if (0 == _MHD_IOV_MAX)
+      return MHD_ERR_NOTCONN_; /* Should never happen */
+    items_to_send = _MHD_IOV_MAX;
+    push_data = false; /* Incomplete response */
+  }
+#endif /* _MHD_IOV_MAX */
+#ifdef HAVE_SENDMSG
+  memset (&msg, 0, sizeof(struct msghdr));
+  msg.msg_iov = r_iov->iov + r_iov->sent;
+  msg.msg_iovlen = items_to_send;
+
+  pre_send_setopt (connection, true, push_data);
+#ifdef MHD_USE_MSG_MORE
+  res = sendmsg (connection->socket_fd, &msg,
+                 MSG_NOSIGNAL_OR_ZERO | (push_data ? 0 : MSG_MORE));
+#else  /* ! MHD_USE_MSG_MORE */
+  res = sendmsg (connection->socket_fd, &msg, MSG_NOSIGNAL_OR_ZERO);
+#endif /* ! MHD_USE_MSG_MORE */
+#elif defined(HAVE_WRITEV)
+  pre_send_setopt (connection, true, push_data);
+  res = writev (connection->socket_fd, r_iov->iov + r_iov->sent,
+                items_to_send);
+#elif defined(MHD_WINSOCK_SOCKETS)
+#ifdef _WIN64
+  if (items_to_send > UINT32_MAX)
+  {
+    cnt_w = UINT32_MAX;
+    push_data = false; /* Incomplete response */
+  }
+  else
+    cnt_w = (DWORD) items_to_send;
+#else  /* ! _WIN64 */
+  cnt_w = (DWORD) items_to_send;
+#endif /* ! _WIN64 */
+  pre_send_setopt (connection, true, push_data);
+  if (0 == WSASend (connection->socket_fd,
+                    (LPWSABUF) (r_iov->iov + r_iov->sent),
+                    cnt_w,
+                    &bytes_sent, 0, NULL, NULL))
+    res = (ssize_t) bytes_sent;
+  else
+    res = -1;
+#else /* !HAVE_SENDMSG && !HAVE_WRITEV && !MHD_WINSOCK_SOCKETS */
+#error No vector-send function available
+#endif
+
+  if (0 > res)
+  {
+    const int err = MHD_socket_get_error_ ();
+
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+    {
+#ifdef EPOLL_SUPPORT
+      /* EAGAIN --- no longer write-ready */
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+      return MHD_ERR_AGAIN_;
+    }
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return MHD_ERR_AGAIN_;
+    if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+      return MHD_ERR_CONNRESET_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_))
+      return MHD_ERR_PIPE_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_))
+      return MHD_ERR_OPNOTSUPP_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_))
+      return MHD_ERR_NOTCONN_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_))
+      return MHD_ERR_INVAL_;
+    if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err))
+      return MHD_ERR_NOMEM_;
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_))
+      return MHD_ERR_BADF_;
+    /* Treat any other error as a hard error. */
+    return MHD_ERR_NOTCONN_;
+  }
+
+  /* Some data has been sent */
+  if (1)
+  {
+    size_t track_sent = (size_t) res;
+    /* Adjust the internal tracking information for the iovec to
+     * take this last send into account. */
+    while ((0 != track_sent) && (r_iov->iov[r_iov->sent].iov_len <= track_sent))
+    {
+      track_sent -= r_iov->iov[r_iov->sent].iov_len;
+      r_iov->sent++; /* The iov element has been completely sent */
+      mhd_assert ((r_iov->cnt > r_iov->sent) || (0 == track_sent));
+    }
+
+    if (r_iov->cnt == r_iov->sent)
+      post_send_setopt (connection, true, push_data);
+    else
+    {
+#ifdef EPOLL_SUPPORT
+      connection->epoll_state &=
+        ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY);
+#endif /* EPOLL_SUPPORT */
+      if (0 != track_sent)
+      {
+        mhd_assert (r_iov->cnt > r_iov->sent);
+        /* The last iov element has been partially sent */
+        r_iov->iov[r_iov->sent].iov_base =
+          (void *) ((uint8_t *) r_iov->iov[r_iov->sent].iov_base + track_sent);
+        r_iov->iov[r_iov->sent].iov_len -= (MHD_iov_size_) track_sent;
+      }
+    }
+  }
+
+  return res;
+}
+
+
+#endif /* MHD_VECT_SEND */
+
+#if ! defined(MHD_VECT_SEND) || defined(HTTPS_SUPPORT) || \
+  defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED)
+
+
+/**
+ * Function sends iov data by sending buffers one-by-one by standard
+ * data send function.
+ *
+ * Connection could be in HTTPS or non-HTTPS mode.
+ *
+ * @param connection the MHD connection structure
+ * @param r_iov the pointer to iov data structure with tracking
+ * @param push_data set to true to force push the data to the network from
+ *                  system buffers (usually set for the last piece of data),
+ *                  set to false to prefer holding incomplete network packets
+ *                  (more data will be send for the same reply).
+ * @return actual number of bytes sent
+ */
+static ssize_t
+send_iov_emu (struct MHD_Connection *connection,
+              struct MHD_iovec_track_ *const r_iov,
+              bool push_data)
+{
+  const bool non_blk = connection->sk_nonblck;
+  size_t total_sent;
+  ssize_t res;
+
+  mhd_assert (NULL != r_iov->iov);
+  total_sent = 0;
+  do
+  {
+    if ((size_t) SSIZE_MAX - total_sent < r_iov->iov[r_iov->sent].iov_len)
+      return (ssize_t) total_sent; /* return value would overflow */
+
+    res = MHD_send_data_ (connection,
+                          r_iov->iov[r_iov->sent].iov_base,
+                          r_iov->iov[r_iov->sent].iov_len,
+                          push_data && (r_iov->cnt == r_iov->sent + 1));
+    if (0 > res)
+    {
+      /* Result is an error */
+      if (0 == total_sent)
+        return res; /* Nothing was sent, return result as is */
+
+      if (MHD_ERR_AGAIN_ == res)
+        return (ssize_t) total_sent; /* Return the amount of the sent data */
+
+      return res; /* Any kind of a hard error */
+    }
+
+    total_sent += (size_t) res;
+
+    if (r_iov->iov[r_iov->sent].iov_len != (size_t) res)
+    {
+      const size_t sent = (size_t) res;
+      /* Incomplete buffer has been sent.
+       * Adjust buffer of the last element. */
+      r_iov->iov[r_iov->sent].iov_base =
+        (void *) ((uint8_t *) r_iov->iov[r_iov->sent].iov_base + sent);
+      r_iov->iov[r_iov->sent].iov_len -= (MHD_iov_size_) sent;
+
+      return (ssize_t) total_sent;
+    }
+    /* The iov element has been completely sent */
+    r_iov->sent++;
+  } while ((r_iov->cnt > r_iov->sent) && (non_blk));
+
+  return (ssize_t) total_sent;
+}
+
+
+#endif /* !MHD_VECT_SEND || HTTPS_SUPPORT
+          || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */
+
+
+ssize_t
+MHD_send_iovec_ (struct MHD_Connection *connection,
+                 struct MHD_iovec_track_ *const r_iov,
+                 bool push_data)
+{
+#ifdef MHD_VECT_SEND
+#if defined(HTTPS_SUPPORT) || \
+  defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED)
+  bool use_iov_send = true;
+#endif /* HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */
+#endif /* MHD_VECT_SEND */
+
+  mhd_assert (NULL != connection->rp.resp_iov.iov);
+  mhd_assert (NULL != connection->rp.response->data_iov);
+  mhd_assert (connection->rp.resp_iov.cnt > connection->rp.resp_iov.sent);
+#ifdef MHD_VECT_SEND
+#if defined(HTTPS_SUPPORT) || \
+  defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED)
+#ifdef HTTPS_SUPPORT
+  use_iov_send = use_iov_send &&
+                 (0 == (connection->daemon->options & MHD_USE_TLS));
+#endif /* HTTPS_SUPPORT */
+#ifdef _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED
+  use_iov_send = use_iov_send && (connection->daemon->sigpipe_blocked ||
+                                  connection->sk_spipe_suppress);
+#endif /* _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */
+  if (use_iov_send)
+#endif /* HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */
+  return send_iov_nontls (connection, r_iov, push_data);
+#endif /* MHD_VECT_SEND */
+
+#if ! defined(MHD_VECT_SEND) || defined(HTTPS_SUPPORT) || \
+  defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED)
+  return send_iov_emu (connection, r_iov, push_data);
+#endif /* !MHD_VECT_SEND || HTTPS_SUPPORT
+          || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */
+}
diff --git a/src/microhttpd/mhd_send.h b/src/microhttpd/mhd_send.h
new file mode 100644
index 0000000..1b2ad6a
--- /dev/null
+++ b/src/microhttpd/mhd_send.h
@@ -0,0 +1,163 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017, 2020 Karlson2k (Evgeny Grin)
+  Copyright (C) 2019 ng0
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file mhd_send.h
+ * @brief Declarations of send() wrappers.
+ * @author ng0
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SEND_H
+#define MHD_SEND_H
+
+#include "platform.h"
+#include "internal.h"
+#if defined(HAVE_STDBOOL_H)
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+#include <errno.h>
+#include "mhd_sockets.h"
+#include "connection.h"
+#ifdef HTTPS_SUPPORT
+#include "connection_https.h"
+#endif
+
+#if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) || \
+  defined(MHD_WINSOCK_SOCKETS)
+#define MHD_VECT_SEND 1
+#endif /* HAVE_SENDMSG || HAVE_WRITEV || MHD_WINSOCK_SOCKETS */
+
+/**
+ * Initialises static variables
+ */
+void
+MHD_send_init_static_vars_ (void);
+
+
+/**
+ * Send buffer to the client, push data from network buffer if requested
+ * and full buffer is sent.
+ *
+ * @param connection the MHD_Connection structure
+ * @param buffer content of the buffer to send
+ * @param buffer_size the size of the @a buffer (in bytes)
+ * @param push_data set to true to force push the data to the network from
+ *                  system buffers (usually set for the last piece of data),
+ *                  set to false to prefer holding incomplete network packets
+ *                  (more data will be send for the same reply).
+ * @return sum of the number of bytes sent from both buffers or
+ *         error code (negative)
+ */
+ssize_t
+MHD_send_data_ (struct MHD_Connection *connection,
+                const char *buffer,
+                size_t buffer_size,
+                bool push_data);
+
+
+/**
+ * Send reply header with optional reply body.
+ *
+ * @param connection the MHD_Connection structure
+ * @param header content of header to send
+ * @param header_size the size of the @a header (in bytes)
+ * @param never_push_hdr set to true to disable internal algorithm
+ *                       that can push automatically header data
+ *                       alone to the network
+ * @param body content of the body to send (optional, may be NULL)
+ * @param body_size the size of the @a body (in bytes)
+ * @param complete_response set to true if complete response
+ *                          is provided by @a header and @a body,
+ *                          set to false if additional body data
+ *                          will be sent later
+ * @return sum of the number of bytes sent from both buffers or
+ *         error code (negative)
+ */
+ssize_t
+MHD_send_hdr_and_body_ (struct MHD_Connection *connection,
+                        const char *header,
+                        size_t header_size,
+                        bool never_push_hdr,
+                        const char *body,
+                        size_t body_size,
+                        bool complete_response);
+
+#if defined(_MHD_HAVE_SENDFILE)
+/**
+ * Function for sending responses backed by file FD.
+ *
+ * @param connection the MHD connection structure
+ * @return actual number of bytes sent
+ */
+ssize_t
+MHD_send_sendfile_ (struct MHD_Connection *connection);
+
+#endif
+
+
+/**
+ * Set required TCP_NODELAY state for connection socket
+ *
+ * The function automatically updates sk_nodelay state.
+ * @param connection the connection to manipulate
+ * @param nodelay_state the requested new state of socket
+ * @return true if succeed, false if failed or not supported
+ *         by the current platform / kernel.
+ */
+bool
+MHD_connection_set_nodelay_state_ (struct MHD_Connection *connection,
+                                   bool nodelay_state);
+
+
+/**
+ * Set required cork state for connection socket
+ *
+ * The function automatically updates sk_corked state.
+ *
+ * @param connection the connection to manipulate
+ * @param cork_state the requested new state of socket
+ * @return true if succeed, false if failed or not supported
+ *         by the current platform / kernel.
+ */
+bool
+MHD_connection_set_cork_state_ (struct MHD_Connection *connection,
+                                bool cork_state);
+
+
+/**
+ * Function for sending responses backed by a an array of memory buffers.
+ *
+ * @param connection the MHD connection structure
+ * @param r_iov the pointer to iov response structure with tracking
+ * @param push_data set to true to force push the data to the network from
+ *                  system buffers (usually set for the last piece of data),
+ *                  set to false to prefer holding incomplete network packets
+ *                  (more data will be send for the same reply).
+ * @return actual number of bytes sent
+ */
+ssize_t
+MHD_send_iovec_ (struct MHD_Connection *connection,
+                 struct MHD_iovec_track_ *const r_iov,
+                 bool push_data);
+
+
+#endif /* MHD_SEND_H */
diff --git a/src/microhttpd/mhd_sha256_wrap.h b/src/microhttpd/mhd_sha256_wrap.h
new file mode 100644
index 0000000..5879c2c
--- /dev/null
+++ b/src/microhttpd/mhd_sha256_wrap.h
@@ -0,0 +1,100 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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 GNU libmicrohttpd.
+     If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file microhttpd/mhd_sha256_wrap.h
+ * @brief  Simple wrapper for selection of built-in/external SHA-256
+ *         implementation
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SHA256_WRAP_H
+#define MHD_SHA256_WRAP_H 1
+
+#include "mhd_options.h"
+#include "mhd_options.h"
+#ifndef MHD_SHA256_SUPPORT
+#error This file must be used only when SHA-256 is enabled
+#endif
+#ifndef MHD_SHA256_TLSLIB
+#include "sha256.h"
+#else  /* MHD_SHA256_TLSLIB */
+#include "sha256_ext.h"
+#endif /* MHD_SHA256_TLSLIB */
+
+#ifndef SHA256_DIGEST_SIZE
+/**
+ * Size of SHA-256 resulting digest in bytes
+ * This is the final digest size, not intermediate hash.
+ */
+#define SHA256_DIGEST_SIZE (32)
+#endif /* ! SHA256_DIGEST_SIZE */
+
+#ifndef SHA256_DIGEST_STRING_SIZE
+/**
+ * Size of MD5 digest string in chars including termination NUL.
+ */
+#define SHA256_DIGEST_STRING_SIZE ((SHA256_DIGEST_SIZE) * 2 + 1)
+#endif /* ! SHA256_DIGEST_STRING_SIZE */
+
+#ifndef MHD_SHA256_TLSLIB
+/**
+ * Universal ctx type mapped for chosen implementation
+ */
+#define Sha256CtxWr Sha256Ctx
+#else  /* MHD_SHA256_TLSLIB */
+/**
+ * Universal ctx type mapped for chosen implementation
+ */
+#define Sha256CtxWr Sha256CtxExt
+#endif /* MHD_SHA256_TLSLIB */
+
+#ifndef MHD_SHA256_HAS_INIT_ONE_TIME
+/**
+ * Setup and prepare ctx for hash calculation
+ */
+#define MHD_SHA256_init_one_time(ctx) MHD_SHA256_init(ctx)
+#endif /* ! MHD_SHA256_HAS_INIT_ONE_TIME */
+
+#ifndef MHD_SHA256_HAS_FINISH_RESET
+/**
+ * Re-use the same ctx for the new hashing after digest calculated
+ */
+#define MHD_SHA256_reset(ctx) MHD_SHA256_init(ctx)
+/**
+ * Finalise MD5 calculation, return digest, reset hash calculation.
+ */
+#define MHD_SHA256_finish_reset(ctx,digest) MHD_SHA256_finish(ctx,digest), \
+                                            MHD_SHA256_reset(ctx)
+
+#else  /* MHD_SHA256_HAS_FINISH_RESET */
+#define MHD_SHA256_reset(ctx) (void)0
+#endif /* MHD_SHA256_HAS_FINISH_RESET */
+
+#ifndef MHD_SHA256_HAS_DEINIT
+#define MHD_SHA256_deinit(ignore) (void)0
+#endif /* HAVE_SHA256_DEINIT */
+
+/* Sanity checks */
+
+#if ! defined(MHD_SHA256_HAS_FINISH_RESET) && ! defined(MHD_SHA256_HAS_FINISH)
+#error Required MHD_SHA256_finish_reset() or MHD_SHA256_finish_reset()
+#endif /* ! MHD_SHA256_HAS_FINISH_RESET && ! MHD_SHA256_HAS_FINISH */
+
+#endif /* MHD_SHA256_WRAP_H */
diff --git a/src/microhttpd/mhd_sockets.c b/src/microhttpd/mhd_sockets.c
new file mode 100644
index 0000000..2e49652
--- /dev/null
+++ b/src/microhttpd/mhd_sockets.c
@@ -0,0 +1,570 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+/**
+ * @file microhttpd/mhd_sockets.c
+ * @brief  Implementation for sockets functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "mhd_sockets.h"
+
+#ifdef MHD_WINSOCK_SOCKETS
+
+/**
+ * Return pointer to string description of specified WinSock error
+ * @param err the WinSock error code.
+ * @return pointer to string description of specified WinSock error.
+ */
+const char *
+MHD_W32_strerror_winsock_ (int err)
+{
+  switch (err)
+  {
+  case 0:
+    return "No error";
+  case WSA_INVALID_HANDLE:
+    return "Specified event object handle is invalid";
+  case WSA_NOT_ENOUGH_MEMORY:
+    return "Insufficient memory available";
+  case WSA_INVALID_PARAMETER:
+    return "One or more parameters are invalid";
+  case WSA_OPERATION_ABORTED:
+    return "Overlapped operation aborted";
+  case WSA_IO_INCOMPLETE:
+    return "Overlapped I/O event object not in signaled state";
+  case WSA_IO_PENDING:
+    return "Overlapped operations will complete later";
+  case WSAEINTR:
+    return "Interrupted function call";
+  case WSAEBADF:
+    return "File handle is not valid";
+  case WSAEACCES:
+    return "Permission denied";
+  case WSAEFAULT:
+    return "Bad address";
+  case WSAEINVAL:
+    return "Invalid argument";
+  case WSAEMFILE:
+    return "Too many open files";
+  case WSAEWOULDBLOCK:
+    return "Resource temporarily unavailable";
+  case WSAEINPROGRESS:
+    return "Operation now in progress";
+  case WSAEALREADY:
+    return "Operation already in progress";
+  case WSAENOTSOCK:
+    return "Socket operation on nonsocket";
+  case WSAEDESTADDRREQ:
+    return "Destination address required";
+  case WSAEMSGSIZE:
+    return "Message too long";
+  case WSAEPROTOTYPE:
+    return "Protocol wrong type for socket";
+  case WSAENOPROTOOPT:
+    return "Bad protocol option";
+  case WSAEPROTONOSUPPORT:
+    return "Protocol not supported";
+  case WSAESOCKTNOSUPPORT:
+    return "Socket type not supported";
+  case WSAEOPNOTSUPP:
+    return "Operation not supported";
+  case WSAEPFNOSUPPORT:
+    return "Protocol family not supported";
+  case WSAEAFNOSUPPORT:
+    return "Address family not supported by protocol family";
+  case WSAEADDRINUSE:
+    return "Address already in use";
+  case WSAEADDRNOTAVAIL:
+    return "Cannot assign requested address";
+  case WSAENETDOWN:
+    return "Network is down";
+  case WSAENETUNREACH:
+    return "Network is unreachable";
+  case WSAENETRESET:
+    return "Network dropped connection on reset";
+  case WSAECONNABORTED:
+    return "Software caused connection abort";
+  case WSAECONNRESET:
+    return "Connection reset by peer";
+  case WSAENOBUFS:
+    return "No buffer space available";
+  case WSAEISCONN:
+    return "Socket is already connected";
+  case WSAENOTCONN:
+    return "Socket is not connected";
+  case WSAESHUTDOWN:
+    return "Cannot send after socket shutdown";
+  case WSAETOOMANYREFS:
+    return "Too many references";
+  case WSAETIMEDOUT:
+    return "Connection timed out";
+  case WSAECONNREFUSED:
+    return "Connection refused";
+  case WSAELOOP:
+    return "Cannot translate name";
+  case WSAENAMETOOLONG:
+    return "Name too long";
+  case WSAEHOSTDOWN:
+    return "Host is down";
+  case WSAEHOSTUNREACH:
+    return "No route to host";
+  case WSAENOTEMPTY:
+    return "Directory not empty";
+  case WSAEPROCLIM:
+    return "Too many processes";
+  case WSAEUSERS:
+    return "User quota exceeded";
+  case WSAEDQUOT:
+    return "Disk quota exceeded";
+  case WSAESTALE:
+    return "Stale file handle reference";
+  case WSAEREMOTE:
+    return "Item is remote";
+  case WSASYSNOTREADY:
+    return "Network subsystem is unavailable";
+  case WSAVERNOTSUPPORTED:
+    return "Winsock.dll version out of range";
+  case WSANOTINITIALISED:
+    return "Successful WSAStartup not yet performed";
+  case WSAEDISCON:
+    return "Graceful shutdown in progress";
+  case WSAENOMORE:
+    return "No more results";
+  case WSAECANCELLED:
+    return "Call has been canceled";
+  case WSAEINVALIDPROCTABLE:
+    return "Procedure call table is invalid";
+  case WSAEINVALIDPROVIDER:
+    return "Service provider is invalid";
+  case WSAEPROVIDERFAILEDINIT:
+    return "Service provider failed to initialize";
+  case WSASYSCALLFAILURE:
+    return "System call failure";
+  case WSASERVICE_NOT_FOUND:
+    return "Service not found";
+  case WSATYPE_NOT_FOUND:
+    return "Class type not found";
+  case WSA_E_NO_MORE:
+    return "No more results";
+  case WSA_E_CANCELLED:
+    return "Call was canceled";
+  case WSAEREFUSED:
+    return "Database query was refused";
+  case WSAHOST_NOT_FOUND:
+    return "Host not found";
+  case WSATRY_AGAIN:
+    return "Nonauthoritative host not found";
+  case WSANO_RECOVERY:
+    return "This is a nonrecoverable error";
+  case WSANO_DATA:
+    return "Valid name, no data record of requested type";
+  case WSA_QOS_RECEIVERS:
+    return "QoS receivers";
+  case WSA_QOS_SENDERS:
+    return "QoS senders";
+  case WSA_QOS_NO_SENDERS:
+    return "No QoS senders";
+  case WSA_QOS_NO_RECEIVERS:
+    return "QoS no receivers";
+  case WSA_QOS_REQUEST_CONFIRMED:
+    return "QoS request confirmed";
+  case WSA_QOS_ADMISSION_FAILURE:
+    return "QoS admission error";
+  case WSA_QOS_POLICY_FAILURE:
+    return "QoS policy failure";
+  case WSA_QOS_BAD_STYLE:
+    return "QoS bad style";
+  case WSA_QOS_BAD_OBJECT:
+    return "QoS bad object";
+  case WSA_QOS_TRAFFIC_CTRL_ERROR:
+    return "QoS traffic control error";
+  case WSA_QOS_GENERIC_ERROR:
+    return "QoS generic error";
+  case WSA_QOS_ESERVICETYPE:
+    return "QoS service type error";
+  case WSA_QOS_EFLOWSPEC:
+    return "QoS flowspec error";
+  case WSA_QOS_EPROVSPECBUF:
+    return "Invalid QoS provider buffer";
+  case WSA_QOS_EFILTERSTYLE:
+    return "Invalid QoS filter style";
+  case WSA_QOS_EFILTERTYPE:
+    return "Invalid QoS filter type";
+  case WSA_QOS_EFILTERCOUNT:
+    return "Incorrect QoS filter count";
+  case WSA_QOS_EOBJLENGTH:
+    return "Invalid QoS object length";
+  case WSA_QOS_EFLOWCOUNT:
+    return "Incorrect QoS flow count";
+  case WSA_QOS_EUNKOWNPSOBJ:
+    return "Unrecognized QoS object";
+  case WSA_QOS_EPOLICYOBJ:
+    return "Invalid QoS policy object";
+  case WSA_QOS_EFLOWDESC:
+    return "Invalid QoS flow descriptor";
+  case WSA_QOS_EPSFLOWSPEC:
+    return "Invalid QoS provider-specific flowspec";
+  case WSA_QOS_EPSFILTERSPEC:
+    return "Invalid QoS provider-specific filterspec";
+  case WSA_QOS_ESDMODEOBJ:
+    return "Invalid QoS shape discard mode object";
+  case WSA_QOS_ESHAPERATEOBJ:
+    return "Invalid QoS shaping rate object";
+  case WSA_QOS_RESERVED_PETYPE:
+    return "Reserved policy QoS element type";
+  }
+  return "Unknown winsock error";
+}
+
+
+/**
+ * Create pair of mutually connected TCP/IP sockets on loopback address
+ * @param sockets_pair array to receive resulted sockets
+ * @param non_blk if set to non-zero value, sockets created in non-blocking mode
+ *                otherwise sockets will be in blocking mode
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk)
+{
+  int i;
+
+  if (! sockets_pair)
+  {
+    WSASetLastError (WSAEFAULT);
+    return 0;
+  }
+
+#define PAIRMAXTRYIES 800
+  for (i = 0; i < PAIRMAXTRYIES; i++)
+  {
+    struct sockaddr_in listen_addr;
+    SOCKET listen_s;
+    static const int c_addinlen = sizeof(struct sockaddr_in);   /* help compiler to optimize */
+    int addr_len = c_addinlen;
+    unsigned long on_val = 1;
+    unsigned long off_val = 0;
+
+    listen_s = socket (AF_INET,
+                       SOCK_STREAM,
+                       IPPROTO_TCP);
+    if (INVALID_SOCKET == listen_s)
+      break;   /* can't create even single socket */
+
+    listen_addr.sin_family = AF_INET;
+    listen_addr.sin_port = 0;   /* same as htons(0) */
+    listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+    if ( ((0 == bind (listen_s,
+                      (struct sockaddr *) &listen_addr,
+                      c_addinlen)) &&
+          (0 == listen (listen_s,
+                        1) ) &&
+          (0 == getsockname (listen_s,
+                             (struct sockaddr *) &listen_addr,
+                             &addr_len))) )
+    {
+      SOCKET client_s = socket (AF_INET,
+                                SOCK_STREAM,
+                                IPPROTO_TCP);
+      struct sockaddr_in accepted_from_addr;
+      struct sockaddr_in client_addr;
+      SOCKET server_s;
+
+      if (INVALID_SOCKET == client_s)
+      {
+        /* try again */
+        closesocket (listen_s);
+        continue;
+      }
+
+      if ( (0 != ioctlsocket (client_s,
+                              (int) FIONBIO,
+                              &on_val)) ||
+           ( (0 != connect (client_s,
+                            (struct sockaddr *) &listen_addr,
+                            c_addinlen)) &&
+             (WSAGetLastError () != WSAEWOULDBLOCK)) )
+      {
+        /* try again */
+        closesocket (listen_s);
+        closesocket (client_s);
+        continue;
+      }
+
+      addr_len = c_addinlen;
+      server_s = accept (listen_s,
+                         (struct sockaddr *) &accepted_from_addr,
+                         &addr_len);
+      if (INVALID_SOCKET == server_s)
+      {
+        /* try again */
+        closesocket (listen_s);
+        closesocket (client_s);
+        continue;
+      }
+
+      addr_len = c_addinlen;
+      if ( (0 == getsockname (client_s,
+                              (struct sockaddr *) &client_addr,
+                              &addr_len)) &&
+           (accepted_from_addr.sin_port == client_addr.sin_port) &&
+           (accepted_from_addr.sin_addr.s_addr ==
+            client_addr.sin_addr.s_addr) &&
+           (accepted_from_addr.sin_family == client_addr.sin_family) &&
+           ( (0 != non_blk) ?
+             (0 == ioctlsocket (server_s,
+                                (int) FIONBIO,
+                                &on_val)) :
+             (0 == ioctlsocket (client_s,
+                                (int) FIONBIO,
+                                &off_val)) ) &&
+           (0 == setsockopt (server_s,
+                             IPPROTO_TCP,
+                             TCP_NODELAY,
+                             (const void *) (&on_val),
+                             sizeof (on_val))) &&
+           (0 == setsockopt (client_s,
+                             IPPROTO_TCP,
+                             TCP_NODELAY,
+                             (const void *) (&on_val),
+                             sizeof (on_val))) )
+      {
+        closesocket (listen_s);
+        sockets_pair[0] = server_s;
+        sockets_pair[1] = client_s;
+        return ! 0;
+      }
+      closesocket (server_s);
+      closesocket (client_s);
+    }
+    closesocket (listen_s);
+  }
+
+  sockets_pair[0] = INVALID_SOCKET;
+  sockets_pair[1] = INVALID_SOCKET;
+  WSASetLastError (WSAECONNREFUSED);
+
+  return 0;
+}
+
+
+#endif /* MHD_WINSOCK_SOCKETS */
+
+
+/**
+ * Add @a fd to the @a set.  If @a fd is
+ * greater than @a max_fd, set @a max_fd to @a fd.
+ *
+ * @param fd file descriptor to add to the @a set
+ * @param set set to modify
+ * @param max_fd maximum value to potentially update
+ * @param fd_setsize value of FD_SETSIZE
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_add_to_fd_set_ (MHD_socket fd,
+                    fd_set *set,
+                    MHD_socket *max_fd,
+                    unsigned int fd_setsize)
+{
+  if ( (NULL == set) ||
+       (MHD_INVALID_SOCKET == fd) )
+    return 0;
+  if (! MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (fd,
+                                         set,
+                                         fd_setsize))
+    return 0;
+  MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_ (fd,
+                                     set,
+                                     fd_setsize);
+  if ( (NULL != max_fd) &&
+       ( (fd > *max_fd) ||
+         (MHD_INVALID_SOCKET == *max_fd) ) )
+    *max_fd = fd;
+  return ! 0;
+}
+
+
+/**
+ * Change socket options to be non-blocking.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_socket_nonblocking_ (MHD_socket sock)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (sock,
+                 F_GETFL);
+  if (-1 == flags)
+    return 0;
+
+  if ( ((flags | O_NONBLOCK) != flags) &&
+       (0 != fcntl (sock,
+                    F_SETFL,
+                    flags | O_NONBLOCK)) )
+    return 0;
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 1;
+
+  if (0 != ioctlsocket (sock,
+                        (int) FIONBIO,
+                        &flags))
+    return 0;
+#endif /* MHD_WINSOCK_SOCKETS */
+  return ! 0;
+}
+
+
+/**
+ * Change socket options to be non-inheritable.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ * @warning Does not set socket error on W32.
+ */
+int
+MHD_socket_noninheritable_ (MHD_socket sock)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (sock,
+                 F_GETFD);
+  if (-1 == flags)
+    return 0;
+
+  if ( ((flags | FD_CLOEXEC) != flags) &&
+       (0 != fcntl (sock,
+                    F_SETFD,
+                    flags | FD_CLOEXEC)) )
+    return 0;
+#elif defined(MHD_WINSOCK_SOCKETS)
+  if (! SetHandleInformation ((HANDLE) sock,
+                              HANDLE_FLAG_INHERIT,
+                              0))
+    return 0;
+#endif /* MHD_WINSOCK_SOCKETS */
+  return ! 0;
+}
+
+
+/**
+ * Disable Nagle's algorithm on @a sock.  This is what we do by default for
+ * all TCP sockets in MHD, unless the platform does not support the MSG_MORE
+ * or MSG_CORK or MSG_NOPUSH options.
+ *
+ * @param sock socket to manipulate
+ * @param on value to use
+ * @return 0 on success
+ */
+int
+MHD_socket_set_nodelay_ (MHD_socket sock,
+                         bool on)
+{
+#ifdef TCP_NODELAY
+  {
+    const MHD_SCKT_OPT_BOOL_ off_val = 0;
+    const MHD_SCKT_OPT_BOOL_ on_val = 1;
+    /* Disable Nagle's algorithm for normal buffering */
+    return setsockopt (sock,
+                       IPPROTO_TCP,
+                       TCP_NODELAY,
+                       (const void *) ((on) ? &on_val : &off_val),
+                       sizeof (on_val));
+  }
+#else
+  (void) sock;
+  return 0;
+#endif /* TCP_NODELAY */
+}
+
+
+/**
+ * Create a listen socket, with noninheritable flag if possible.
+ *
+ * @param pf protocol family to use
+ * @return created socket or MHD_INVALID_SOCKET in case of errors
+ */
+MHD_socket
+MHD_socket_create_listen_ (int pf)
+{
+  MHD_socket fd;
+  int cloexec_set;
+#if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_)
+  int nosigpipe_set;
+#endif /* SOCK_NOSIGPIPE ||  MHD_socket_nosignal_ */
+
+#if defined(MHD_POSIX_SOCKETS) && (defined(SOCK_CLOEXEC) || \
+  defined(SOCK_NOSIGPIPE) )
+
+  cloexec_set = (SOCK_CLOEXEC_OR_ZERO != 0);
+#if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_)
+  nosigpipe_set = (SOCK_NOSIGPIPE_OR_ZERO != 0);
+#endif /* SOCK_NOSIGPIPE ||  MHD_socket_nosignal_ */
+  fd = socket (pf,
+               SOCK_STREAM | SOCK_CLOEXEC | SOCK_NOSIGPIPE_OR_ZERO,
+               0);
+#elif defined(MHD_WINSOCK_SOCKETS) && defined(WSA_FLAG_NO_HANDLE_INHERIT)
+  fd = WSASocketW (pf,
+                   SOCK_STREAM,
+                   0,
+                   NULL,
+                   0,
+                   WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
+  cloexec_set = ! 0;
+#else  /* !SOCK_CLOEXEC */
+  fd = MHD_INVALID_SOCKET;
+#endif /* !SOCK_CLOEXEC */
+  if (MHD_INVALID_SOCKET == fd)
+  {
+    fd = socket (pf,
+                 SOCK_STREAM,
+                 0);
+    cloexec_set = 0;
+#if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_)
+    nosigpipe_set = 0;
+#endif /* SOCK_NOSIGPIPE ||  MHD_socket_nosignal_ */
+  }
+  if (MHD_INVALID_SOCKET == fd)
+    return MHD_INVALID_SOCKET;
+
+#if defined(MHD_socket_nosignal_)
+  if ( (! nosigpipe_set) &&
+       (0 == MHD_socket_nosignal_ (fd)) &&
+       (0 == MSG_NOSIGNAL_OR_ZERO) )
+  {
+    /* SIGPIPE disable is possible on this platform
+     * (so application expect that it will be disabled),
+     * but failed to be disabled here and it is not
+     * possible to disable SIGPIPE by MSG_NOSIGNAL. */
+    const int err = MHD_socket_get_error_ ();
+    (void) MHD_socket_close_ (fd);
+    MHD_socket_fset_error_ (err);
+    return MHD_INVALID_SOCKET;
+  }
+#endif /* defined(MHD_socket_nosignal_) */
+  if (! cloexec_set)
+    (void) MHD_socket_noninheritable_ (fd);
+
+  return fd;
+}
diff --git a/src/microhttpd/mhd_sockets.h b/src/microhttpd/mhd_sockets.h
new file mode 100644
index 0000000..fede77d
--- /dev/null
+++ b/src/microhttpd/mhd_sockets.h
@@ -0,0 +1,958 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2014-2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_sockets.c
+ * @brief  Header for platform-independent sockets abstraction
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Provides basic abstraction for sockets.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ */
+
+#ifndef MHD_SOCKETS_H
+#define MHD_SOCKETS_H 1
+#include "mhd_options.h"
+
+#include <errno.h>
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#include <fcntl.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif /* HAVE_STDDEF_H */
+#if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED)
+#  include <stdint.h>
+#  define _SSIZE_T_DEFINED
+typedef intptr_t ssize_t;
+#endif /* !_SSIZE_T_DEFINED */
+
+#if ! defined(MHD_POSIX_SOCKETS) && ! defined(MHD_WINSOCK_SOCKETS)
+#  if ! defined(_WIN32) || defined(__CYGWIN__)
+#    define MHD_POSIX_SOCKETS 1
+#  else  /* defined(_WIN32) && !defined(__CYGWIN__) */
+#    define MHD_WINSOCK_SOCKETS 1
+#  endif /* defined(_WIN32) && !defined(__CYGWIN__) */
+#endif /* !MHD_POSIX_SOCKETS && !MHD_WINSOCK_SOCKETS */
+
+/*
+ * MHD require headers that define socket type, socket basic functions
+ * (socket(), accept(), listen(), bind(), send(), recv(), select()), socket
+ * parameters like SOCK_CLOEXEC, SOCK_NONBLOCK, additional socket functions
+ * (poll(), epoll(), accept4()), struct timeval and other types, required
+ * for socket function.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  ifdef HAVE_SYS_TYPES_H
+#    include <sys/types.h> /* required on old platforms */
+#  endif
+#  ifdef HAVE_SYS_TIME_H
+#    include <sys/time.h>
+#  endif
+#  ifdef HAVE_TIME_H
+#    include <time.h>
+#  endif
+#  ifdef HAVE_STRING_H
+#    include <string.h> /* for strerror() */
+#  endif
+#  ifdef HAVE_SYS_SOCKET_H
+#    include <sys/socket.h>
+#  endif
+#  if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS)
+#    include <strings.h>  /* required for FD_SET (bzero() function) */
+#    ifdef HAVE_SOCKLIB_H
+#      include <sockLib.h>
+#    endif /* HAVE_SOCKLIB_H */
+#    ifdef HAVE_INETLIB_H
+#      include <inetLib.h>
+#    endif /* HAVE_INETLIB_H */
+#  endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */
+#  ifdef HAVE_NETINET_IN_H
+#    include <netinet/in.h>
+#  endif /* HAVE_NETINET_IN_H */
+#  ifdef HAVE_ARPA_INET_H
+#    include <arpa/inet.h>
+#  endif
+#  ifdef HAVE_NET_IF_H
+#    include <net/if.h>
+#  endif
+#  ifdef HAVE_NETDB_H
+#    include <netdb.h>
+#  endif
+#  ifdef HAVE_SYS_SELECT_H
+#    include <sys/select.h>
+#  endif
+#  ifdef EPOLL_SUPPORT
+#    include <sys/epoll.h>
+#  endif
+#  ifdef HAVE_NETINET_TCP_H
+/* for TCP_FASTOPEN and TCP_CORK */
+#    include <netinet/tcp.h>
+#  endif
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
+#  endif /* !WIN32_LEAN_AND_MEAN */
+#  include <winsock2.h>
+#  include <ws2tcpip.h>
+#endif /* MHD_WINSOCK_SOCKETS */
+
+#if defined(HAVE_POLL_H) && defined(HAVE_POLL)
+#  include <poll.h>
+#endif
+
+
+#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
+#include <sys/param.h> /* For __FreeBSD_version */
+#endif /* __FreeBSD__ */
+
+#include "mhd_limits.h"
+
+#ifdef _MHD_FD_SETSIZE_IS_DEFAULT
+#  define _MHD_SYS_DEFAULT_FD_SETSIZE FD_SETSIZE
+#else  /* ! _MHD_FD_SETSIZE_IS_DEFAULT */
+#  include "sysfdsetsize.h"
+#  define _MHD_SYS_DEFAULT_FD_SETSIZE get_system_fdsetsize_value ()
+#endif /* ! _MHD_FD_SETSIZE_IS_DEFAULT */
+
+#ifndef MHD_PANIC
+#  include <stdio.h>
+#  include <stdlib.h>
+/* Simple implementation of MHD_PANIC, to be used outside lib */
+#  define MHD_PANIC(msg) \
+    do { fprintf (stderr,           \
+                  "Abnormal termination at %d line in file %s: %s\n", \
+                  (int) __LINE__, __FILE__, msg); abort (); \
+} while (0)
+#endif /* ! MHD_PANIC */
+
+#ifndef MHD_SOCKET_DEFINED
+/**
+ * MHD_socket is type for socket FDs
+ */
+#  if defined(MHD_POSIX_SOCKETS)
+typedef int MHD_socket;
+#    define MHD_INVALID_SOCKET (-1)
+#  elif defined(MHD_WINSOCK_SOCKETS)
+typedef SOCKET MHD_socket;
+#    define MHD_INVALID_SOCKET (INVALID_SOCKET)
+#  endif /* MHD_WINSOCK_SOCKETS */
+
+#  define MHD_SOCKET_DEFINED 1
+#endif /* ! MHD_SOCKET_DEFINED */
+
+#ifdef SOCK_CLOEXEC
+#  define SOCK_CLOEXEC_OR_ZERO SOCK_CLOEXEC
+#else  /* ! SOCK_CLOEXEC */
+#  define SOCK_CLOEXEC_OR_ZERO 0
+#endif /* ! SOCK_CLOEXEC */
+
+#ifdef HAVE_SOCK_NONBLOCK
+#  define SOCK_NONBLOCK_OR_ZERO SOCK_NONBLOCK
+#else  /* ! HAVE_SOCK_NONBLOCK */
+#  define SOCK_NONBLOCK_OR_ZERO 0
+#endif /* ! HAVE_SOCK_NONBLOCK */
+
+#ifdef SOCK_NOSIGPIPE
+#  define SOCK_NOSIGPIPE_OR_ZERO SOCK_NOSIGPIPE
+#else  /* ! HAVE_SOCK_NONBLOCK */
+#  define SOCK_NOSIGPIPE_OR_ZERO 0
+#endif /* ! HAVE_SOCK_NONBLOCK */
+
+#ifdef MSG_NOSIGNAL
+#  define MSG_NOSIGNAL_OR_ZERO MSG_NOSIGNAL
+#else  /* ! MSG_NOSIGNAL */
+#  define MSG_NOSIGNAL_OR_ZERO 0
+#endif /* ! MSG_NOSIGNAL */
+
+#if ! defined(SHUT_WR) && defined(SD_SEND)
+#  define SHUT_WR SD_SEND
+#endif
+#if ! defined(SHUT_RD) && defined(SD_RECEIVE)
+#  define SHUT_RD SD_RECEIVE
+#endif
+#if ! defined(SHUT_RDWR) && defined(SD_BOTH)
+#  define SHUT_RDWR SD_BOTH
+#endif
+
+#if defined(HAVE_ACCEPT4) && (defined(HAVE_SOCK_NONBLOCK) || \
+  defined(SOCK_CLOEXEC) || defined(SOCK_NOSIGPIPE))
+#  define USE_ACCEPT4 1
+#endif
+
+#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
+  defined(__OpenBSD__) || defined(__NetBSD__) || \
+  defined(MHD_WINSOCK_SOCKETS) || defined(__MACH__) || defined(__sun) || \
+  defined(SOMEBSD)
+/* Most of OSes inherit nonblocking setting from the listen socket */
+#define MHD_ACCEPT_INHERIT_NONBLOCK 1
+#endif
+
+#if defined(HAVE_EPOLL_CREATE1) && defined(EPOLL_CLOEXEC)
+#  define USE_EPOLL_CREATE1 1
+#endif /* HAVE_EPOLL_CREATE1 && EPOLL_CLOEXEC */
+
+#ifdef TCP_FASTOPEN
+/**
+ * Default TCP fastopen queue size.
+ */
+#define MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT 10
+#endif
+
+
+#if defined(TCP_CORK)
+/**
+ * Value of TCP_CORK or TCP_NOPUSH
+ */
+#define MHD_TCP_CORK_NOPUSH TCP_CORK
+#elif defined(TCP_NOPUSH)
+/**
+ * Value of TCP_CORK or TCP_NOPUSH
+ */
+#define MHD_TCP_CORK_NOPUSH TCP_NOPUSH
+#endif /* TCP_NOPUSH */
+
+
+#ifdef MHD_TCP_CORK_NOPUSH
+#ifdef __linux__
+/**
+ * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network
+ */
+#define _MHD_CORK_RESET_PUSH_DATA 1
+/**
+ * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network
+ * even if TCP_CORK/TCP_NOPUSH was in switched off state.
+ */
+#define _MHD_CORK_RESET_PUSH_DATA_ALWAYS 1
+#endif /* __linux__ */
+#if (defined(__FreeBSD__) && \
+  ((__FreeBSD__ + 0) >= 5 || (__FreeBSD_version + 0) >= 450000)) || \
+  (defined(__FreeBSD_kernel_version) && \
+  (__FreeBSD_kernel_version + 0) >= 450000)
+/* FreeBSD pushes data to the network with reset of TCP_NOPUSH
+ * starting from version 4.5. */
+/**
+ * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network
+ */
+#define _MHD_CORK_RESET_PUSH_DATA 1
+#endif /* __FreeBSD_version >= 450000 */
+#ifdef __OpenBSD__
+/* OpenBSD took implementation from FreeBSD */
+/**
+ * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network
+ */
+#define _MHD_CORK_RESET_PUSH_DATA 1
+#endif /* __OpenBSD__ */
+#endif /* MHD_TCP_CORK_NOPUSH */
+
+#ifdef __linux__
+/**
+ * Indicate that set of TCP_NODELAY push data to the network
+ */
+#define _MHD_NODELAY_SET_PUSH_DATA 1
+/**
+ * Indicate that set of TCP_NODELAY push data to the network even
+ * if TCP_DELAY was already set and regardless of TCP_CORK / TCP_NOPUSH state
+ */
+#define _MHD_NODELAY_SET_PUSH_DATA_ALWAYS 1
+#endif /* __linux__ */
+
+#ifdef MSG_MORE
+#ifdef __linux__
+/* MSG_MORE signal kernel to buffer outbond data and works like
+ * TCP_CORK per call without actually setting TCP_CORK value.
+ * It's known to work on Linux. Add more OSes if they are compatible. */
+/**
+ * Indicate MSG_MORE is usable for buffered send().
+ */
+#define MHD_USE_MSG_MORE 1
+#endif /* __linux__ */
+#endif /* MSG_MORE */
+
+
+/**
+ * MHD_SCKT_OPT_BOOL_ is type for bool parameters for setsockopt()/getsockopt()
+ */
+#ifdef MHD_POSIX_SOCKETS
+typedef int MHD_SCKT_OPT_BOOL_;
+#else /* MHD_WINSOCK_SOCKETS */
+typedef BOOL MHD_SCKT_OPT_BOOL_;
+#endif /* MHD_WINSOCK_SOCKETS */
+
+/**
+ * MHD_SCKT_SEND_SIZE_ is type used to specify size for send and recv
+ * functions
+ */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+typedef size_t MHD_SCKT_SEND_SIZE_;
+#else
+typedef int MHD_SCKT_SEND_SIZE_;
+#endif
+
+/**
+ * MHD_SCKT_SEND_MAX_SIZE_ is maximum send()/recv() size value.
+ */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_SEND_MAX_SIZE_ SSIZE_MAX
+#else
+#  define MHD_SCKT_SEND_MAX_SIZE_ INT_MAX
+#endif
+
+/**
+ * MHD_socket_close_(fd) close any FDs (non-W32) / close only socket
+ * FDs (W32).  Note that on HP-UNIX, this function may leak the FD if
+ * errno is set to EINTR.  Do not use HP-UNIX.
+ *
+ * @param fd descriptor to close
+ * @return boolean true on success (error codes like EINTR and EIO are
+ *         counted as success, only EBADF counts as an error!),
+ *         boolean false otherwise.
+ */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_close_(fd) ((0 == close ((fd))) || (EBADF != errno))
+#else
+#  define MHD_socket_close_(fd) (0 == closesocket ((fd)))
+#endif
+
+/**
+ * MHD_socket_close_chk_(fd) close socket and abort execution
+ * if error is detected.
+ * @param fd socket to close
+ */
+#define MHD_socket_close_chk_(fd) do {        \
+    if (! MHD_socket_close_ (fd))               \
+      MHD_PANIC (_ ("Close socket failed.\n")); \
+} while (0)
+
+
+/**
+ * MHD_send4_ is a wrapper for system's send()
+ * @param s the socket to use
+ * @param b the buffer with data to send
+ * @param l the length of data in @a b
+ * @param f the additional flags
+ * @return ssize_t type value
+ */
+#define MHD_send4_(s,b,l,f) \
+  ((ssize_t) send ((s),(const void*) (b),(MHD_SCKT_SEND_SIZE_) (l), \
+                   ((MSG_NOSIGNAL_OR_ZERO) | (f))))
+
+
+/**
+ * MHD_send_ is a simple wrapper for system's send()
+ * @param s the socket to use
+ * @param b the buffer with data to send
+ * @param l the length of data in @a b
+ * @return ssize_t type value
+ */
+#define MHD_send_(s,b,l) MHD_send4_((s),(b),(l), 0)
+
+
+/**
+ * MHD_recv_ is wrapper for system's recv()
+ * @param s the socket to use
+ * @param b the buffer for data to receive
+ * @param l the length of @a b
+ * @return ssize_t type value
+ */
+#define MHD_recv_(s,b,l) \
+  ((ssize_t) recv ((s),(void*) (b),(MHD_SCKT_SEND_SIZE_) (l), 0))
+
+
+/**
+ * Check whether FD can be added to fd_set with specified FD_SETSIZE.
+ * @param fd   the fd to check
+ * @param pset the pointer to fd_set to check or NULL to check
+ *             whether FD can be used with fd_sets.
+ * @param setsize the value of FD_SETSIZE.
+ * @return boolean true if FD can be added to fd_set,
+ *         boolean false otherwise.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) \
+    ((fd) < ((MHD_socket) setsize))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) \
+   ( ((void*) (pset)==  (void*) 0) || \
+     (((fd_set*) (pset))->fd_count < ((unsigned) setsize)) || \
+     (FD_ISSET ((fd), (pset))) )
+#endif
+
+/**
+ * Check whether FD can be added to fd_set with current FD_SETSIZE.
+ * @param fd   the fd to check
+ * @param pset the pointer to fd_set to check or NULL to check
+ *             whether FD can be used with fd_sets.
+ * @return boolean true if FD can be added to fd_set,
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_FD_FITS_FDSET_(fd,pset) \
+  MHD_SCKT_FD_FITS_FDSET_SETSIZE_ ((fd), (pset), FD_SETSIZE)
+
+/**
+ * Add FD to fd_set with specified FD_SETSIZE.
+ * @param fd   the fd to add
+ * @param pset the valid pointer to fd_set.
+ * @param setsize the value of FD_SETSIZE.
+ * @note  To work on W32 with value of FD_SETSIZE different from currently defined value,
+ *        system definition of FD_SET() is not used.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize) \
+  FD_SET ((fd), (pset))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize)                \
+  do {                                                                      \
+    u_int _i_ = 0;                                                          \
+    fd_set*const _s_ = (fd_set*) (pset);                                    \
+    while ((_i_ < _s_->fd_count) && ((fd) != _s_->fd_array [_i_])) {++_i_;} \
+    if ((_i_ == _s_->fd_count)) {_s_->fd_array [_s_->fd_count ++] = (fd);}  \
+  } while (0)
+#endif
+
+/* MHD_SYS_select_ is wrapper macro for system select() function */
+#if ! defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SYS_select_(n,r,w,e,t) select ((n),(r),(w),(e),(t))
+#else
+#  define MHD_SYS_select_(n,r,w,e,t) \
+  ( ( (((void*) (r) == (void*) 0) || ((fd_set*) (r))->fd_count == 0) &&  \
+      (((void*) (w) == (void*) 0) || ((fd_set*) (w))->fd_count == 0) &&  \
+      (((void*) (e) == (void*) 0) || ((fd_set*) (e))->fd_count == 0) ) ? \
+    ( ((void*) (t) == (void*) 0) ? 0 :                                   \
+      (Sleep ((DWORD)((struct timeval*) (t))->tv_sec * 1000              \
+              + (DWORD)((struct timeval*) (t))->tv_usec / 1000), 0) ) :  \
+    (select ((int) 0,(r),(w),(e),(t))) )
+#endif
+
+#if defined(HAVE_POLL)
+/* MHD_sys_poll_ is wrapper macro for system poll() function */
+#  if ! defined(MHD_WINSOCK_SOCKETS)
+#    define MHD_sys_poll_ poll
+#  else  /* MHD_WINSOCK_SOCKETS */
+#    define MHD_sys_poll_ WSAPoll
+#  endif /* MHD_WINSOCK_SOCKETS */
+
+#  ifdef POLLPRI
+#    define MHD_POLLPRI_OR_ZERO POLLPRI
+#  else  /* ! POLLPRI */
+#    define MHD_POLLPRI_OR_ZERO 0
+#  endif /* ! POLLPRI */
+#  ifdef POLLRDBAND
+#    define MHD_POLLRDBAND_OR_ZERO POLLRDBAND
+#  else  /* ! POLLRDBAND */
+#    define MHD_POLLRDBAND_OR_ZERO 0
+#  endif /* ! POLLRDBAND */
+#  ifdef POLLNVAL
+#    define MHD_POLLNVAL_OR_ZERO POLLNVAL
+#  else  /* ! POLLNVAL */
+#    define MHD_POLLNVAL_OR_ZERO 0
+#  endif /* ! POLLNVAL */
+
+/* MHD_POLL_EVENTS_ERR_DISC is 'events' mask for errors and disconnect.
+ * Note: Out-of-band data is treated as error. */
+#  if defined(_WIN32) && ! defined(__CYGWIN__)
+#    define MHD_POLL_EVENTS_ERR_DISC POLLRDBAND
+#  elif defined(__linux__)
+#    define MHD_POLL_EVENTS_ERR_DISC POLLPRI
+#  else /* ! __linux__ */
+#    define MHD_POLL_EVENTS_ERR_DISC \
+       (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO)
+#  endif /* ! __linux__ */
+/* MHD_POLL_REVENTS_ERR_DISC is 'revents' mask for errors and disconnect.
+ * Note: Out-of-band data is treated as error. */
+#  define MHD_POLL_REVENTS_ERR_DISC \
+  (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \
+   | POLLERR | POLLHUP)
+/* MHD_POLL_REVENTS_ERRROR is 'revents' mask for errors.
+ * Note: Out-of-band data is treated as error. */
+#  define MHD_POLL_REVENTS_ERRROR \
+  (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \
+   | POLLERR)
+#endif /* HAVE_POLL */
+
+#define MHD_SCKT_MISSING_ERR_CODE_ 31450
+
+#if defined(MHD_POSIX_SOCKETS)
+#  if defined(EAGAIN)
+#    define MHD_SCKT_EAGAIN_      EAGAIN
+#  elif defined(EWOULDBLOCK)
+#    define MHD_SCKT_EAGAIN_      EWOULDBLOCK
+#  else  /* !EAGAIN && !EWOULDBLOCK */
+#    define MHD_SCKT_EAGAIN_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* !EAGAIN && !EWOULDBLOCK */
+#  if defined(EWOULDBLOCK)
+#    define MHD_SCKT_EWOULDBLOCK_ EWOULDBLOCK
+#  elif defined(EAGAIN)
+#    define MHD_SCKT_EWOULDBLOCK_ EAGAIN
+#  else  /* !EWOULDBLOCK && !EAGAIN */
+#    define MHD_SCKT_EWOULDBLOCK_ MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* !EWOULDBLOCK && !EAGAIN */
+#  ifdef EINTR
+#    define MHD_SCKT_EINTR_       EINTR
+#  else  /* ! EINTR */
+#    define MHD_SCKT_EINTR_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EINTR */
+#  ifdef ECONNRESET
+#    define MHD_SCKT_ECONNRESET_  ECONNRESET
+#  else  /* ! ECONNRESET */
+#    define MHD_SCKT_ECONNRESET_  MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ECONNRESET */
+#  ifdef ECONNABORTED
+#    define MHD_SCKT_ECONNABORTED_  ECONNABORTED
+#  else  /* ! ECONNABORTED */
+#    define MHD_SCKT_ECONNABORTED_  MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ECONNABORTED */
+#  ifdef ENOTCONN
+#    define MHD_SCKT_ENOTCONN_    ENOTCONN
+#  else  /* ! ENOTCONN */
+#    define MHD_SCKT_ENOTCONN_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOTCONN */
+#  ifdef EMFILE
+#    define MHD_SCKT_EMFILE_      EMFILE
+#  else  /* ! EMFILE */
+#    define MHD_SCKT_EMFILE_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EMFILE */
+#  ifdef ENFILE
+#    define MHD_SCKT_ENFILE_      ENFILE
+#  else  /* ! ENFILE */
+#    define MHD_SCKT_ENFILE_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENFILE */
+#  ifdef ENOMEM
+#    define MHD_SCKT_ENOMEM_      ENOMEM
+#  else  /* ! ENOMEM */
+#    define MHD_SCKT_ENOMEM_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOMEM */
+#  ifdef ENOBUFS
+#    define MHD_SCKT_ENOBUFS_     ENOBUFS
+#  else  /* ! ENOBUFS */
+#    define MHD_SCKT_ENOBUFS_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOBUFS */
+#  ifdef EBADF
+#    define MHD_SCKT_EBADF_       EBADF
+#  else  /* ! EBADF */
+#    define MHD_SCKT_EBADF_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EBADF */
+#  ifdef ENOTSOCK
+#    define MHD_SCKT_ENOTSOCK_    ENOTSOCK
+#  else  /* ! ENOTSOCK */
+#    define MHD_SCKT_ENOTSOCK_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOTSOCK */
+#  ifdef EINVAL
+#    define MHD_SCKT_EINVAL_      EINVAL
+#  else  /* ! EINVAL */
+#    define MHD_SCKT_EINVAL_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EINVAL */
+#  ifdef EPIPE
+#    define MHD_SCKT_EPIPE_       EPIPE
+#  else  /* ! EPIPE */
+#    define MHD_SCKT_EPIPE_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EPIPE */
+#  ifdef EFAULT
+#    define MHD_SCKT_EFAUL_       EFAULT
+#  else  /* ! EFAULT */
+#    define MHD_SCKT_EFAUL_       MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EFAULT */
+#  ifdef ENOSYS
+#    define MHD_SCKT_ENOSYS_      ENOSYS
+#  else  /* ! ENOSYS */
+#    define MHD_SCKT_ENOSYS_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOSYS */
+#  ifdef ENOPROTOOPT
+#    define MHD_SCKT_ENOPROTOOPT_      ENOPROTOOPT
+#  else  /* ! ENOPROTOOPT */
+#    define MHD_SCKT_ENOPROTOOPT_      MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOPROTOOPT */
+#  ifdef ENOTSUP
+#    define MHD_SCKT_ENOTSUP_     ENOTSUP
+#  else  /* ! ENOTSUP */
+#    define MHD_SCKT_ENOTSUP_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENOTSUP */
+#  ifdef EOPNOTSUPP
+#    define MHD_SCKT_EOPNOTSUPP_  EOPNOTSUPP
+#  else  /* ! EOPNOTSUPP */
+#    define MHD_SCKT_EOPNOTSUPP_  MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EOPNOTSUPP */
+#  ifdef EACCES
+#    define MHD_SCKT_EACCESS_     EACCES
+#  else  /* ! EACCES */
+#    define MHD_SCKT_EACCESS_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EACCES */
+#  ifdef ENETDOWN
+#    define MHD_SCKT_ENETDOWN_    ENETDOWN
+#  else  /* ! ENETDOWN */
+#    define MHD_SCKT_ENETDOWN_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! ENETDOWN */
+#  ifdef EALREADY
+#    define MHD_SCKT_EALREADY_    EALREADY
+#  else  /* ! EALREADY */
+#    define MHD_SCKT_EALREADY_    MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EALREADY */
+#  ifdef EINPROGRESS
+#    define MHD_SCKT_EINPROGRESS_ EINPROGRESS
+#  else  /* ! EINPROGRESS */
+#    define MHD_SCKT_EINPROGRESS_ MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EINPROGRESS */
+#  ifdef EISCONN
+#    define MHD_SCKT_EISCONN_     EISCONN
+#  else  /* ! EISCONN */
+#    define MHD_SCKT_EISCONN_     MHD_SCKT_MISSING_ERR_CODE_
+#  endif /* ! EISCONN */
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_EAGAIN_        WSAEWOULDBLOCK
+#  define MHD_SCKT_EWOULDBLOCK_   WSAEWOULDBLOCK
+#  define MHD_SCKT_EINTR_         WSAEINTR
+#  define MHD_SCKT_ECONNRESET_    WSAECONNRESET
+#  define MHD_SCKT_ECONNABORTED_  WSAECONNABORTED
+#  define MHD_SCKT_ENOTCONN_      WSAENOTCONN
+#  define MHD_SCKT_EMFILE_        WSAEMFILE
+#  define MHD_SCKT_ENFILE_        MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_ENOMEM_        MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_ENOBUFS_       WSAENOBUFS
+#  define MHD_SCKT_EBADF_         WSAEBADF
+#  define MHD_SCKT_ENOTSOCK_      WSAENOTSOCK
+#  define MHD_SCKT_EINVAL_        WSAEINVAL
+#  define MHD_SCKT_EPIPE_         WSAESHUTDOWN
+#  define MHD_SCKT_EFAUL_         WSAEFAULT
+#  define MHD_SCKT_ENOSYS_        MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_ENOPROTOOPT_   WSAENOPROTOOPT
+#  define MHD_SCKT_ENOTSUP_       MHD_SCKT_MISSING_ERR_CODE_
+#  define MHD_SCKT_EOPNOTSUPP_    WSAEOPNOTSUPP
+#  define MHD_SCKT_EACCESS_       WSAEACCES
+#  define MHD_SCKT_ENETDOWN_      WSAENETDOWN
+#  define MHD_SCKT_EALREADY_      WSAEALREADY
+#  define MHD_SCKT_EINPROGRESS_   WSAEACCES
+#  define MHD_SCKT_EISCONN_       WSAEISCONN
+#endif
+
+/**
+ * MHD_socket_error_ return system native error code for last socket error.
+ * @return system error code for last socket error.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_socket_get_error_() (errno)
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_get_error_() WSAGetLastError ()
+#endif
+
+#ifdef MHD_WINSOCK_SOCKETS
+/* POSIX-W32 sockets compatibility functions */
+
+/**
+ * Return pointer to string description of specified WinSock error
+ * @param err the WinSock error code.
+ * @return pointer to string description of specified WinSock error.
+ */
+const char *MHD_W32_strerror_winsock_ (int err);
+
+#endif /* MHD_WINSOCK_SOCKETS */
+
+/* MHD_socket_last_strerr_ is description string of specified socket error code */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_socket_strerr_(err) strerror ((err))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_strerr_(err) MHD_W32_strerror_winsock_ ((err))
+#endif
+
+/* MHD_socket_last_strerr_ is description string of last errno (non-W32) /
+ *                            description string of last socket error (W32) */
+#define MHD_socket_last_strerr_() MHD_socket_strerr_ (MHD_socket_get_error_ ())
+
+/**
+ * MHD_socket_fset_error_() set socket system native error code.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_socket_fset_error_(err) (errno = (err))
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_fset_error_(err) (WSASetLastError ((err)))
+#endif
+
+/**
+ * MHD_socket_try_set_error_() set socket system native error code if
+ * specified code is defined on system.
+ * @return non-zero if specified @a err code is defined on system
+ *         and error was set;
+ *         zero if specified @a err code is not defined on system
+ *         and error was not set.
+ */
+#define MHD_socket_try_set_error_(err) \
+  ( (MHD_SCKT_MISSING_ERR_CODE_ != (err)) ? \
+      (MHD_socket_fset_error_ ((err)), ! 0) : 0)
+
+/**
+ * MHD_socket_set_error_() set socket system native error code to
+ * specified code or replacement code if specified code is not
+ * defined on system.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  if defined(ENOSYS)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = ENOSYS) : (errno = (err)) )
+#  elif defined(EOPNOTSUPP)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = EOPNOTSUPP) : (errno = \
+                                                                   (err)) )
+#  elif defined(EFAULT)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = EFAULT) : (errno = (err)) )
+#  elif defined(EINVAL)
+#    define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                         (errno = EINVAL) : (errno = (err)) )
+#  else  /* !EOPNOTSUPP && !EFAULT && !EINVAL */
+#    warning \
+  No suitable replacement for missing socket error code is found. Edit this file and add replacement code which is defined on system.
+#    define MHD_socket_set_error_(err) (errno = (err))
+#  endif /* !EOPNOTSUPP && !EFAULT && !EINVAL*/
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \
+                                       (WSASetLastError ((WSAEOPNOTSUPP))) : \
+                                       (WSASetLastError ((err))) )
+#endif
+
+/**
+ * Check whether given socket error is equal to specified system
+ * native MHD_SCKT_E*_ code.
+ * If platform don't have specific error code, result is
+ * always boolean false.
+ * @return boolean true if @a code is real error code and
+ *         @a err equals to MHD_SCKT_E*_ @a code;
+ *         boolean false otherwise
+ */
+#define MHD_SCKT_ERR_IS_(err,code) \
+  ( (MHD_SCKT_MISSING_ERR_CODE_ != (code)) && ((code) == (err)) )
+
+/**
+ * Check whether last socket error is equal to specified system
+ * native MHD_SCKT_E*_ code.
+ * If platform don't have specific error code, result is
+ * always boolean false.
+ * @return boolean true if @a code is real error code and
+ *         last socket error equals to MHD_SCKT_E*_ @a code;
+ *         boolean false otherwise
+ */
+#define MHD_SCKT_LAST_ERR_IS_(code) \
+  MHD_SCKT_ERR_IS_ (MHD_socket_get_error_ (), (code))
+
+/* Specific error code checks */
+
+/**
+ * Check whether given socket error is equal to system's
+ * socket error codes for EINTR.
+ * @return boolean true if @a err is equal to sockets' EINTR code;
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_ERR_IS_EINTR_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EINTR_)
+
+/**
+ * Check whether given socket error is equal to system's
+ * socket error codes for EAGAIN or EWOULDBLOCK.
+ * @return boolean true if @a err is equal to sockets' EAGAIN or EWOULDBLOCK codes;
+ *         boolean false otherwise.
+ */
+#if MHD_SCKT_EAGAIN_ == MHD_SCKT_EWOULDBLOCK_
+#  define MHD_SCKT_ERR_IS_EAGAIN_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EAGAIN_)
+#else  /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */
+#  define MHD_SCKT_ERR_IS_EAGAIN_(err) \
+  ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EAGAIN_) || \
+    MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EWOULDBLOCK_) )
+#endif /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */
+
+/**
+ * Check whether given socket error is any kind of "low resource" error.
+ * @return boolean true if @a err is any kind of "low resource" error,
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_ERR_IS_LOW_RESOURCES_(err) \
+  ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EMFILE_) || \
+    MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENFILE_) || \
+    MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENOMEM_) || \
+    MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENOBUFS_) )
+
+/**
+ * Check whether is given socket error is type of "incoming connection
+ * was disconnected before 'accept()' is called".
+ * @return boolean true is @a err match described socket error code,
+ *         boolean false otherwise.
+ */
+#if defined(MHD_POSIX_SOCKETS)
+#  define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) \
+  MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNABORTED_)
+#elif defined(MHD_WINSOCK_SOCKETS)
+#  define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) \
+  MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNRESET_)
+#endif
+
+/**
+ * Check whether is given socket error is type of "connection was terminated
+ * by remote side".
+ * @return boolean true is @a err match described socket error code,
+ *         boolean false otherwise.
+ */
+#define MHD_SCKT_ERR_IS_REMOTE_DISCNN_(err) \
+  ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNRESET_) || \
+    MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNABORTED_) )
+
+/* Specific error code set */
+
+/**
+ * Set socket's error code to ENOMEM or equivalent if ENOMEM is not
+ * available on platform.
+ */
+#if MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOMEM_
+#  define MHD_socket_set_error_to_ENOMEM() \
+  MHD_socket_set_error_ (MHD_SCKT_ENOMEM_)
+#elif MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOBUFS_
+#  define MHD_socket_set_error_to_ENOMEM() \
+  MHD_socket_set_error_ (MHD_SCKT_ENOBUFS_)
+#else
+#  warning \
+  No suitable replacement for ENOMEM error codes is found. Edit this file and add replacement code which is defined on system.
+#  define MHD_socket_set_error_to_ENOMEM() MHD_socket_set_error_ ( \
+    MHD_SCKT_ENOMEM_)
+#endif
+
+/* Socket functions */
+
+#if defined(AF_LOCAL)
+#  define MHD_SCKT_LOCAL AF_LOCAL
+#elif defined(AF_UNIX)
+#  define MHD_SCKT_LOCAL AF_UNIX
+#endif /* AF_UNIX */
+
+#if defined(MHD_POSIX_SOCKETS) && defined(MHD_SCKT_LOCAL)
+#  define MHD_socket_pair_(fdarr) \
+    (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM, 0, (fdarr)))
+#  if defined(HAVE_SOCK_NONBLOCK)
+#    define MHD_socket_pair_nblk_(fdarr) \
+      (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM | SOCK_NONBLOCK, 0, (fdarr)))
+#  endif /* HAVE_SOCK_NONBLOCK*/
+#elif defined(MHD_WINSOCK_SOCKETS)
+/**
+ * Create pair of mutually connected TCP/IP sockets on loopback address
+ * @param sockets_pair array to receive resulted sockets
+ * @param non_blk if set to non-zero value, sockets created in non-blocking mode
+ *                otherwise sockets will be in blocking mode
+ * @return non-zero if succeeded, zero otherwise
+ */
+int MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk);
+
+#  define MHD_socket_pair_(fdarr) MHD_W32_socket_pair_ ((fdarr), 0)
+#  define MHD_socket_pair_nblk_(fdarr) MHD_W32_socket_pair_ ((fdarr), 1)
+#endif
+
+/**
+ * Add @a fd to the @a set.  If @a fd is
+ * greater than @a max_fd, set @a max_fd to @a fd.
+ *
+ * @param fd file descriptor to add to the @a set
+ * @param set set to modify
+ * @param max_fd maximum value to potentially update
+ * @param fd_setsize value of FD_SETSIZE
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_add_to_fd_set_ (MHD_socket fd,
+                    fd_set *set,
+                    MHD_socket *max_fd,
+                    unsigned int fd_setsize);
+
+
+/**
+ * Change socket options to be non-blocking.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+int
+MHD_socket_nonblocking_ (MHD_socket sock);
+
+
+/**
+ * Disable Nagle's algorithm on @a sock.  This is what we do by default for
+ * all TCP sockets in MHD, unless the platform does not support the MSG_MORE
+ * or MSG_CORK or MSG_NOPUSH options.
+ *
+ * @param sock socket to manipulate
+ * @param on value to use
+ * @return 0 on success
+ */
+int
+MHD_socket_set_nodelay_ (MHD_socket sock,
+                         bool on);
+
+/**
+ * Change socket options to be non-inheritable.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ * @warning Does not set socket error on W32.
+ */
+int
+MHD_socket_noninheritable_ (MHD_socket sock);
+
+
+#if defined(SOL_SOCKET) && defined(SO_NOSIGPIPE)
+static const int _MHD_socket_int_one = 1;
+/**
+ * Change socket options to no signal on remote disconnect.
+ *
+ * @param sock socket to manipulate
+ * @return non-zero if succeeded, zero otherwise
+ */
+#define MHD_socket_nosignal_(sock) \
+  (! setsockopt ((sock),SOL_SOCKET,SO_NOSIGPIPE,&_MHD_socket_int_one, \
+                 sizeof(_MHD_socket_int_one)))
+#endif /* SOL_SOCKET && SO_NOSIGPIPE */
+
+
+#if defined(MHD_socket_nosignal_) || defined(MSG_NOSIGNAL)
+/**
+ * Indicate that SIGPIPE can be suppressed by MHD for normal send() by flags
+ * or socket options.
+ * If this macro is undefined, MHD cannot suppress SIGPIPE for socket functions
+ * so sendfile() or writev() calls are avoided in application threads.
+ */
+#define MHD_SEND_SPIPE_SUPPRESS_POSSIBLE   1
+#endif /* MHD_WINSOCK_SOCKETS || MHD_socket_nosignal_ || MSG_NOSIGNAL */
+
+#if ! defined(MHD_WINSOCK_SOCKETS)
+/**
+ * Indicate that suppression of SIGPIPE is required.
+ */
+#define MHD_SEND_SPIPE_SUPPRESS_NEEDED     1
+#endif
+
+/**
+ * Create a listen socket, with noninheritable flag if possible.
+ *
+ * @param pf protocol family to use
+ * @return created socket or MHD_INVALID_SOCKET in case of errors
+ */
+MHD_socket
+MHD_socket_create_listen_ (int pf);
+
+
+#endif /* ! MHD_SOCKETS_H */
diff --git a/src/microhttpd/mhd_str.c b/src/microhttpd/mhd_str.c
new file mode 100644
index 0000000..22ae36a
--- /dev/null
+++ b/src/microhttpd/mhd_str.c
@@ -0,0 +1,2007 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015-2022 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_str.c
+ * @brief  Functions implementations for string manipulating
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_str.h"
+
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+#include <string.h>
+
+#include "mhd_assert.h"
+#include "mhd_limits.h"
+#include "mhd_assert.h"
+
+#ifdef MHD_FAVOR_SMALL_CODE
+#ifdef _MHD_static_inline
+#undef _MHD_static_inline
+#endif /* _MHD_static_inline */
+/* Do not force inlining and do not use macro functions, use normal static
+   functions instead.
+   This may give more flexibility for size optimizations. */
+#define _MHD_static_inline static
+#ifndef INLINE_FUNC
+#define INLINE_FUNC 1
+#endif /* !INLINE_FUNC */
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+/*
+ * Block of functions/macros that use US-ASCII charset as required by HTTP
+ * standards. Not affected by current locale settings.
+ */
+
+#ifdef INLINE_FUNC
+
+#if 0 /* Disable unused functions. */
+/**
+ * Check whether character is lower case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is lower case letter, zero otherwise
+ */
+_MHD_static_inline bool
+isasciilower (char c)
+{
+  return (c >= 'a') && (c <= 'z');
+}
+
+
+#endif /* Disable unused functions. */
+
+
+/**
+ * Check whether character is upper case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is upper case letter, zero otherwise
+ */
+_MHD_static_inline bool
+isasciiupper (char c)
+{
+  return (c >= 'A') && (c <= 'Z');
+}
+
+
+#if 0 /* Disable unused functions. */
+/**
+ * Check whether character is letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is letter in US-ASCII, zero otherwise
+ */
+_MHD_static_inline bool
+isasciialpha (char c)
+{
+  return isasciilower (c) || isasciiupper (c);
+}
+
+
+#endif /* Disable unused functions. */
+
+
+/**
+ * Check whether character is decimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is decimal digit, zero otherwise
+ */
+_MHD_static_inline bool
+isasciidigit (char c)
+{
+  return (c >= '0') && (c <= '9');
+}
+
+
+#if 0 /* Disable unused functions. */
+/**
+ * Check whether character is hexadecimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is decimal digit, zero otherwise
+ */
+_MHD_static_inline bool
+isasciixdigit (char c)
+{
+  return isasciidigit (c) ||
+         ( (c >= 'A') && (c <= 'F') ) ||
+         ( (c >= 'a') && (c <= 'f') );
+}
+
+
+/**
+ * Check whether character is decimal digit or letter in US-ASCII
+ *
+ * @param c character to check
+ * @return non-zero if character is decimal digit or letter, zero otherwise
+ */
+_MHD_static_inline bool
+isasciialnum (char c)
+{
+  return isasciialpha (c) || isasciidigit (c);
+}
+
+
+#endif /* Disable unused functions. */
+
+
+#if 0 /* Disable unused functions. */
+/**
+ * Convert US-ASCII character to lower case.
+ * If character is upper case letter in US-ASCII than it's converted to lower
+ * case analog. If character is NOT upper case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to lower case character
+ */
+_MHD_static_inline char
+toasciilower (char c)
+{
+  return isasciiupper (c) ? (c - 'A' + 'a') : c;
+}
+
+
+/**
+ * Convert US-ASCII character to upper case.
+ * If character is lower case letter in US-ASCII than it's converted to upper
+ * case analog. If character is NOT lower case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to upper case character
+ */
+_MHD_static_inline char
+toasciiupper (char c)
+{
+  return isasciilower (c) ? (c - 'a' + 'A') : c;
+}
+
+
+#endif /* Disable unused functions. */
+
+
+#if defined(MHD_FAVOR_SMALL_CODE) /* Used only in MHD_str_to_uvalue_n_() */
+/**
+ * Convert US-ASCII decimal digit to its value.
+ *
+ * @param c character to convert
+ * @return value of decimal digit or -1 if @ c is not decimal digit
+ */
+_MHD_static_inline int
+todigitvalue (char c)
+{
+  if (isasciidigit (c))
+    return (unsigned char) (c - '0');
+
+  return -1;
+}
+
+
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Convert US-ASCII hexadecimal digit to its value.
+ *
+ * @param c character to convert
+ * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit
+ */
+_MHD_static_inline int
+toxdigitvalue (char c)
+{
+  if (isasciidigit (c))
+    return (unsigned char) (c - '0');
+  if ( (c >= 'A') && (c <= 'F') )
+    return (unsigned char) (c - 'A' + 10);
+  if ( (c >= 'a') && (c <= 'f') )
+    return (unsigned char) (c - 'a' + 10);
+
+  return -1;
+}
+
+
+/**
+ * Caseless compare two characters.
+ *
+ * @param c1 the first char to compare
+ * @param c2 the second char to compare
+ * @return boolean 'true' if chars are caseless equal, false otherwise
+ */
+_MHD_static_inline bool
+charsequalcaseless (const char c1, const char c2)
+{
+  return ( (c1 == c2) ||
+           (isasciiupper (c1) ?
+            ((c1 - 'A' + 'a') == c2) :
+            ((c1 == (c2 - 'A' + 'a')) && isasciiupper (c2))) );
+}
+
+
+#else  /* !INLINE_FUNC */
+
+
+/**
+ * Checks whether character is lower case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is lower case letter,
+ *         boolean false otherwise
+ */
+#define isasciilower(c) (((char) (c)) >= 'a' && ((char) (c)) <= 'z')
+
+
+/**
+ * Checks whether character is upper case letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is upper case letter,
+ *         boolean false otherwise
+ */
+#define isasciiupper(c) (((char) (c)) >= 'A' && ((char) (c)) <= 'Z')
+
+
+/**
+ * Checks whether character is letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is letter, boolean false
+ *         otherwise
+ */
+#define isasciialpha(c) (isasciilower (c) || isasciiupper (c))
+
+
+/**
+ * Check whether character is decimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is decimal digit, boolean false
+ *         otherwise
+ */
+#define isasciidigit(c) (((char) (c)) >= '0' && ((char) (c)) <= '9')
+
+
+/**
+ * Check whether character is hexadecimal digit in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is hexadecimal digit,
+ *         boolean false otherwise
+ */
+#define isasciixdigit(c) (isasciidigit ((c)) || \
+                          (((char) (c)) >= 'A' && ((char) (c)) <= 'F') || \
+                          (((char) (c)) >= 'a' && ((char) (c)) <= 'f') )
+
+
+/**
+ * Check whether character is decimal digit or letter in US-ASCII
+ *
+ * @param c character to check
+ * @return boolean true if character is decimal digit or letter,
+ *         boolean false otherwise
+ */
+#define isasciialnum(c) (isasciialpha (c) || isasciidigit (c))
+
+
+/**
+ * Convert US-ASCII character to lower case.
+ * If character is upper case letter in US-ASCII than it's converted to lower
+ * case analog. If character is NOT upper case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to lower case character
+ */
+#define toasciilower(c) ((isasciiupper (c)) ? (((char) (c)) - 'A' + 'a') : \
+                         ((char) (c)))
+
+
+/**
+ * Convert US-ASCII character to upper case.
+ * If character is lower case letter in US-ASCII than it's converted to upper
+ * case analog. If character is NOT lower case letter than it's returned
+ * unmodified.
+ *
+ * @param c character to convert
+ * @return converted to upper case character
+ */
+#define toasciiupper(c) ((isasciilower (c)) ? (((char) (c)) - 'a' + 'A') : \
+                         ((char) (c)))
+
+
+/**
+ * Convert US-ASCII decimal digit to its value.
+ *
+ * @param c character to convert
+ * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit
+ */
+#define todigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \
+                         (int) (-1))
+
+
+/**
+ * Convert US-ASCII hexadecimal digit to its value.
+ * @param c character to convert
+ * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit
+ */
+#define toxdigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \
+                          ( (((char) (c)) >= 'A' && ((char) (c)) <= 'F') ? \
+                            (int) (((unsigned char) (c)) - 'A' + 10) : \
+                            ( (((char) (c)) >= 'a' && ((char) (c)) <= 'f') ? \
+                              (int) (((unsigned char) (c)) - 'a' + 10) : \
+                              (int) (-1) )))
+
+/**
+ * Caseless compare two characters.
+ *
+ * @param c1 the first char to compare
+ * @param c2 the second char to compare
+ * @return boolean 'true' if chars are caseless equal, false otherwise
+ */
+#define charsequalcaseless(c1, c2) \
+  ( ((c1) == (c2)) || \
+           (isasciiupper (c1) ? \
+             (((c1) - 'A' + 'a') == (c2)) : \
+             (((c1) == ((c2) - 'A' + 'a')) && isasciiupper (c2))) )
+
+#endif /* !INLINE_FUNC */
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/**
+ * Check two strings for equality, ignoring case of US-ASCII letters.
+ *
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_ (const char *str1,
+                         const char *str2)
+{
+  while (0 != (*str1))
+  {
+    const char c1 = *str1;
+    const char c2 = *str2;
+    if (charsequalcaseless (c1, c2))
+    {
+      str1++;
+      str2++;
+    }
+    else
+      return 0;
+  }
+  return 0 == (*str2);
+}
+
+
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters and
+ * checking not more than @a maxlen characters.
+ * Compares up to first terminating null character, but not more than
+ * first @a maxlen characters.
+ *
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @param maxlen maximum number of characters to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_n_ (const char *const str1,
+                           const char *const str2,
+                           size_t maxlen)
+{
+  size_t i;
+
+  for (i = 0; i < maxlen; ++i)
+  {
+    const char c1 = str1[i];
+    const char c2 = str2[i];
+    if (0 == c2)
+      return 0 == c1;
+    if (charsequalcaseless (c1, c2))
+      continue;
+    else
+      return 0;
+  }
+  return ! 0;
+}
+
+
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters and
+ * checking not more than @a len bytes.
+ * Compares not more first than @a len bytes, including binary zero characters.
+ * Comparison stops at first unmatched byte.
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @param len number of characters to compare
+ * @return non-zero if @a len bytes are equal, zero otherwise.
+ */
+bool
+MHD_str_equal_caseless_bin_n_ (const char *const str1,
+                               const char *const str2,
+                               size_t len)
+{
+  size_t i;
+
+  for (i = 0; i < len; ++i)
+  {
+    const char c1 = str1[i];
+    const char c2 = str2[i];
+    if (charsequalcaseless (c1, c2))
+      continue;
+    else
+      return 0;
+  }
+  return ! 0;
+}
+
+
+/**
+ * Check whether @a str has case-insensitive @a token.
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Match succeed if substring between start, end (of string) or comma
+ * contains only case-insensitive token and optional spaces and tabs.
+ * @warning token must not contain null-characters except optional
+ *          terminating null-character.
+ * @param str the string to check
+ * @param token the token to find
+ * @param token_len length of token, not including optional terminating
+ *                  null-character.
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+bool
+MHD_str_has_token_caseless_ (const char *str,
+                             const char *const token,
+                             size_t token_len)
+{
+  if (0 == token_len)
+    return false;
+
+  while (0 != *str)
+  {
+    size_t i;
+    /* Skip all whitespaces and empty tokens. */
+    while (' ' == *str || '\t' == *str || ',' == *str)
+      str++;
+
+    /* Check for token match. */
+    i = 0;
+    while (1)
+    {
+      const char sc = *(str++);
+      const char tc = token[i++];
+
+      if (0 == sc)
+        return false;
+      if (! charsequalcaseless (sc, tc))
+        break;
+      if (i >= token_len)
+      {
+        /* Check whether substring match token fully or
+         * has additional unmatched chars at tail. */
+        while (' ' == *str || '\t' == *str)
+          str++;
+        /* End of (sub)string? */
+        if ((0 == *str) || (',' == *str) )
+          return true;
+        /* Unmatched chars at end of substring. */
+        break;
+      }
+    }
+    /* Find next substring. */
+    while (0 != *str && ',' != *str)
+      str++;
+  }
+  return false;
+}
+
+
+/**
+ * Remove case-insensitive @a token from the @a str and put result
+ * to the output @a buf.
+ *
+ * Tokens in @a str could be surrounded by spaces and tabs and delimited by
+ * comma. The token match succeed if substring between start, end (of string)
+ * or comma contains only case-insensitive token and optional spaces and tabs.
+ * The quoted strings and comments are not supported by this function.
+ *
+ * The output string is normalised: empty tokens and repeated whitespaces
+ * are removed, no whitespaces before commas, exactly one space is used after
+ * each comma.
+ *
+ * @param str the string to process
+ * @param str_len the length of the @a str, not including optional
+ *                terminating null-character.
+ * @param token the token to find
+ * @param token_len the length of @a token, not including optional
+ *                  terminating null-character.
+ * @param[out] buf the output buffer, not null-terminated.
+ * @param[in,out] buf_size pointer to the size variable, at input it
+ *                         is the size of allocated buffer, at output
+ *                         it is the size of the resulting string (can
+ *                         be up to 50% larger than input) or negative value
+ *                         if there is not enough space for the result
+ * @return 'true' if token has been removed,
+ *         'false' otherwise.
+ */
+bool
+MHD_str_remove_token_caseless_ (const char *str,
+                                size_t str_len,
+                                const char *const token,
+                                const size_t token_len,
+                                char *buf,
+                                ssize_t *buf_size)
+{
+  const char *s1; /**< the "input" string / character */
+  char *s2;       /**< the "output" string / character */
+  size_t t_pos;   /**< position of matched character in the token */
+  bool token_removed;
+
+  mhd_assert (NULL == memchr (token, 0, token_len));
+  mhd_assert (NULL == memchr (token, ' ', token_len));
+  mhd_assert (NULL == memchr (token, '\t', token_len));
+  mhd_assert (NULL == memchr (token, ',', token_len));
+  mhd_assert (0 <= *buf_size);
+
+  if (SSIZE_MAX <= ((str_len / 2) * 3 + 3))
+  {
+    /* The return value may overflow, refuse */
+    *buf_size = (ssize_t) -1;
+    return false;
+  }
+  s1 = str;
+  s2 = buf;
+  token_removed = false;
+
+  while ((size_t) (s1 - str) < str_len)
+  {
+    const char *cur_token; /**< the first char of current token */
+    size_t copy_size;
+
+    /* Skip any initial whitespaces and empty tokens */
+    while ( ((size_t) (s1 - str) < str_len) &&
+            ((' ' == *s1) || ('\t' == *s1) || (',' == *s1)) )
+      s1++;
+
+    /* 's1' points to the first char of token in the input string or
+     * points just beyond the end of the input string */
+
+    if ((size_t) (s1 - str) >= str_len)
+      break; /* Nothing to copy, end of the input string */
+
+    /* 's1' points to the first char of token in the input string */
+
+    cur_token = s1; /* the first char of input token */
+
+    /* Check the token with case-insensetive match */
+    t_pos = 0;
+    while ( ((size_t) (s1 - str) < str_len) && (token_len > t_pos) &&
+            (charsequalcaseless (*s1, token[t_pos])) )
+    {
+      s1++;
+      t_pos++;
+    }
+    /* s1 may point just beyond the end of the input string */
+    if ( (token_len == t_pos) && (0 != token_len) )
+    {
+      /* 'token' matched, check that current input token does not have
+       * any suffixes */
+      while ( ((size_t) (s1 - str) < str_len) &&
+              ((' ' == *s1) || ('\t' == *s1)) )
+        s1++;
+      /* 's1' points to the first non-whitespace char after the token matched
+       * requested token or points just beyond the end of the input string after
+       * the requested token */
+      if (((size_t) (s1 - str) == str_len) || (',' == *s1))
+      {/* full token match, do not copy current token to the output */
+        token_removed = true;
+        continue;
+      }
+    }
+
+    /* 's1' points to first non-whitespace char, to some char after
+     * first non-whitespace char in the token in the input string, to
+     * the ',', or just beyond the end of the input string */
+    /* The current token in the input string does not match the token
+     * to exclude, it must be copied to the output string */
+    /* the current token size excluding leading whitespaces and current char */
+    copy_size = (size_t) (s1 - cur_token);
+    if (buf == s2)
+    { /* The first token to copy to the output */
+      if ((size_t) *buf_size < copy_size)
+      { /* Not enough space in the output buffer */
+        *buf_size = (ssize_t) -1;
+        return false;
+      }
+    }
+    else
+    { /* Some token was already copied to the output buffer */
+      mhd_assert (s2 > buf);
+      if ((size_t) *buf_size < ((size_t) (s2 - buf)) + copy_size + 2)
+      { /* Not enough space in the output buffer */
+        *buf_size = (ssize_t) -1;
+        return false;
+      }
+      *(s2++) = ',';
+      *(s2++) = ' ';
+    }
+    /* Copy non-matched token to the output */
+    if (0 != copy_size)
+    {
+      memcpy (s2, cur_token, copy_size);
+      s2 += copy_size;
+    }
+
+    while ( ((size_t) (s1 - str) < str_len) && (',' != *s1))
+    {
+      /* 's1' points to first non-whitespace char, to some char after
+       * first non-whitespace char in the token in the input string */
+      /* Copy all non-whitespace chars from the current token in
+       * the input string */
+      while ( ((size_t) (s1 - str) < str_len) &&
+              (',' != *s1) && (' ' != *s1) && ('\t' != *s1) )
+      {
+        mhd_assert (s2 >= buf);
+        if ((size_t) *buf_size <= (size_t) (s2 - buf)) /* '<= s2' equals '< s2 + 1' */
+        { /* Not enough space in the output buffer */
+          *buf_size = (ssize_t) -1;
+          return false;
+        }
+        *(s2++) = *(s1++);
+      }
+      /* 's1' points to some whitespace char in the token in the input
+       * string, to the ',', or just beyond the end of the input string */
+      /* Skip all whitespaces */
+      while ( ((size_t) (s1 - str) < str_len) &&
+              ((' ' == *s1) || ('\t' == *s1)) )
+        s1++;
+
+      /* 's1' points to the first non-whitespace char in the input string
+       * after whitespace chars, to the ',', or just beyond the end of
+       * the input string */
+      if (((size_t) (s1 - str) < str_len) && (',' != *s1))
+      { /* Not the end of the current token */
+        mhd_assert (s2 >= buf);
+        if ((size_t) *buf_size <= (size_t) (s2 - buf)) /* '<= s2' equals '< s2 + 1' */
+        { /* Not enough space in the output buffer */
+          *buf_size = (ssize_t) -1;
+          return false;
+        }
+        *(s2++) = ' ';
+      }
+    }
+  }
+  mhd_assert (((ssize_t) (s2 - buf)) <= *buf_size);
+  *buf_size = (ssize_t) (s2 - buf);
+  return token_removed;
+}
+
+
+/**
+ * Perform in-place case-insensitive removal of @a tokens from the @a str.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * The token match succeed if substring between start, end (of the string), or
+ * comma contains only case-insensitive token and optional spaces and tabs.
+ * The quoted strings and comments are not supported by this function.
+ *
+ * The input string must be normalised: empty tokens and repeated whitespaces
+ * are removed, no whitespaces before commas, exactly one space is used after
+ * each comma. The string is updated in-place.
+ *
+ * Behavior is undefined is the input string in not normalised.
+ *
+ * @param[in,out] str the string to update
+ * @param[in,out] str_len the length of the @a str, not including optional
+ *                        terminating null-character, not null-terminated
+ * @param tokens the token to find
+ * @param tokens_len the length of @a tokens, not including optional
+ *                   terminating null-character.
+ * @return 'true' if any token has been removed,
+ *         'false' otherwise.
+ */
+bool
+MHD_str_remove_tokens_caseless_ (char *str,
+                                 size_t *str_len,
+                                 const char *const tokens,
+                                 const size_t tokens_len)
+{
+  const char *const t = tokens;   /**< a short alias for @a tokens */
+  size_t pt;                      /**< position in @a tokens */
+  bool token_removed;
+
+  mhd_assert (NULL == memchr (tokens, 0, tokens_len));
+
+  token_removed = false;
+  pt = 0;
+
+  while (pt < tokens_len && *str_len != 0)
+  {
+    const char *tkn; /**< the current token */
+    size_t tkn_len;
+
+    /* Skip any initial whitespaces and empty tokens in 'tokens' */
+    while ( (pt < tokens_len) &&
+            ((' ' == t[pt]) || ('\t' == t[pt]) || (',' == t[pt])) )
+      pt++;
+
+    if (pt >= tokens_len)
+      break; /* No more tokens, nothing to remove */
+
+    /* Found non-whitespace char which is not a comma */
+    tkn = t + pt;
+    do
+    {
+      do
+      {
+        pt++;
+      } while (pt < tokens_len &&
+               (' ' != t[pt] && '\t' != t[pt] && ',' != t[pt]));
+      /* Found end of the token string, space, tab, or comma */
+      tkn_len = pt - (size_t) (tkn - t);
+
+      /* Skip all spaces and tabs */
+      while (pt < tokens_len && (' ' == t[pt] || '\t' == t[pt]))
+        pt++;
+      /* Found end of the token string or non-whitespace char */
+    } while(pt < tokens_len && ',' != t[pt]);
+
+    /* 'tkn' is the input token with 'tkn_len' chars */
+    mhd_assert (0 != tkn_len);
+
+    if (*str_len == tkn_len)
+    {
+      if (MHD_str_equal_caseless_bin_n_ (str, tkn, tkn_len))
+      {
+        *str_len = 0;
+        token_removed = true;
+      }
+      continue;
+    }
+    /* 'tkn' cannot match part of 'str' if length of 'tkn' is larger
+     * than length of 'str'.
+     * It's know that 'tkn' is not equal to the 'str' (was checked previously).
+     * As 'str' is normalized when 'tkn' is not equal to the 'str'
+     * it is required that 'str' to be at least 3 chars larger then 'tkn'
+     * (the comma, the space and at least one additional character for the next
+     * token) to remove 'tkn' from the 'str'. */
+    if (*str_len > tkn_len + 2)
+    { /* Remove 'tkn' from the input string */
+      size_t pr;    /**< the 'read' position in the @a str */
+      size_t pw;    /**< the 'write' position in the @a str */
+
+      pr = 0;
+      pw = 0;
+
+      do
+      {
+        mhd_assert (pr >= pw);
+        mhd_assert ((*str_len) >= (pr + tkn_len));
+        if ( ( ((*str_len) == (pr + tkn_len)) || (',' == str[pr + tkn_len]) ) &&
+             MHD_str_equal_caseless_bin_n_ (str + pr, tkn, tkn_len) )
+        {
+          /* current token in the input string matches the 'tkn', skip it */
+          mhd_assert ((*str_len == pr + tkn_len) || \
+                      (' ' == str[pr + tkn_len + 1])); /* 'str' must be normalized */
+          token_removed = true;
+          /* Advance to the next token in the input string or beyond
+           * the end of the input string. */
+          pr += tkn_len + 2;
+        }
+        else
+        {
+          /* current token in the input string does not match the 'tkn',
+           * copy to the output */
+          if (0 != pw)
+          { /* not the first output token, add ", " to separate */
+            if (pr != pw + 2)
+            {
+              str[pw++] = ',';
+              str[pw++] = ' ';
+            }
+            else
+              pw += 2; /* 'str' is not yet modified in this round */
+          }
+          do
+          {
+            if (pr != pw)
+              str[pw] = str[pr];
+            pr++;
+            pw++;
+          } while (pr < *str_len && ',' != str[pr]);
+          /* Advance to the next token in the input string or beyond
+           * the end of the input string. */
+          pr += 2;
+        }
+        /* 'pr' should point to the next token in the input string or beyond
+         * the end of the input string */
+        if ((*str_len) < (pr + tkn_len))
+        { /* The rest of the 'str + pr' is too small to match 'tkn' */
+          if ((*str_len) > pr)
+          { /* Copy the rest of the string */
+            size_t copy_size;
+            copy_size = *str_len - pr;
+            if (0 != pw)
+            { /* not the first output token, add ", " to separate */
+              if (pr != pw + 2)
+              {
+                str[pw++] = ',';
+                str[pw++] = ' ';
+              }
+              else
+                pw += 2; /* 'str' is not yet modified in this round */
+            }
+            if (pr != pw)
+              memmove (str + pw, str + pr, copy_size);
+            pw += copy_size;
+          }
+          *str_len = pw;
+          break;
+        }
+        mhd_assert ((' ' != str[0]) && ('\t' != str[0]));
+        mhd_assert ((0 == pr) || (3 <= pr));
+        mhd_assert ((0 == pr) || (' ' == str[pr - 1]));
+        mhd_assert ((0 == pr) || (',' == str[pr - 2]));
+      } while (1);
+    }
+  }
+
+  return token_removed;
+}
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/* Use individual function for each case */
+
+/**
+ * Convert decimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_ (const char *str,
+                    uint64_t *out_val)
+{
+  const char *const start = str;
+  uint64_t res;
+
+  if (! str || ! out_val || ! isasciidigit (str[0]))
+    return 0;
+
+  res = 0;
+  do
+  {
+    const int digit = (unsigned char) (*str) - '0';
+    if ( (res > (UINT64_MAX / 10)) ||
+         ( (res == (UINT64_MAX / 10)) &&
+           ((uint64_t) digit > (UINT64_MAX % 10)) ) )
+      return 0;
+
+    res *= 10;
+    res += (unsigned int) digit;
+    str++;
+  } while (isasciidigit (*str));
+
+  *out_val = res;
+  return (size_t) (str - start);
+}
+
+
+/**
+ * Convert not more then @a maxlen decimal US-ASCII digits in string to
+ * number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_n_ (const char *str,
+                      size_t maxlen,
+                      uint64_t *out_val)
+{
+  uint64_t res;
+  size_t i;
+
+  if (! str || ! maxlen || ! out_val || ! isasciidigit (str[0]))
+    return 0;
+
+  res = 0;
+  i = 0;
+  do
+  {
+    const int digit = (unsigned char) str[i] - '0';
+
+    if ( (res > (UINT64_MAX / 10)) ||
+         ( (res == (UINT64_MAX / 10)) &&
+           ((uint64_t) digit > (UINT64_MAX % 10)) ) )
+      return 0;
+
+    res *= 10;
+    res += (unsigned int) digit;
+    i++;
+  } while ( (i < maxlen) &&
+            isasciidigit (str[i]) );
+
+  *out_val = res;
+  return i;
+}
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint32_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_ (const char *str,
+                     uint32_t *out_val)
+{
+  const char *const start = str;
+  uint32_t res;
+  int digit;
+
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  digit = toxdigitvalue (*str);
+  while (digit >= 0)
+  {
+    if ( (res < (UINT32_MAX / 16)) ||
+         ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit <= (UINT32_MAX
+                                                               % 16)) ) )
+    {
+      res *= 16;
+      res += (unsigned int) digit;
+    }
+    else
+      return 0;
+    str++;
+    digit = toxdigitvalue (*str);
+  }
+
+  if (str - start > 0)
+    *out_val = res;
+  return (size_t) (str - start);
+}
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint32_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_n_ (const char *str,
+                       size_t maxlen,
+                       uint32_t *out_val)
+{
+  size_t i;
+  uint32_t res;
+  int digit;
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  i = 0;
+  while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0)
+  {
+    if ( (res > (UINT32_MAX / 16)) ||
+         ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit > (UINT32_MAX
+                                                              % 16)) ) )
+      return 0;
+
+    res *= 16;
+    res += (unsigned int) digit;
+    i++;
+  }
+
+  if (i)
+    *out_val = res;
+  return i;
+}
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_ (const char *str,
+                     uint64_t *out_val)
+{
+  const char *const start = str;
+  uint64_t res;
+  int digit;
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  digit = toxdigitvalue (*str);
+  while (digit >= 0)
+  {
+    if ( (res < (UINT64_MAX / 16)) ||
+         ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit <= (UINT64_MAX
+                                                               % 16)) ) )
+    {
+      res *= 16;
+      res += (unsigned int) digit;
+    }
+    else
+      return 0;
+    str++;
+    digit = toxdigitvalue (*str);
+  }
+
+  if (str - start > 0)
+    *out_val = res;
+  return (size_t) (str - start);
+}
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_n_ (const char *str,
+                       size_t maxlen,
+                       uint64_t *out_val)
+{
+  size_t i;
+  uint64_t res;
+  int digit;
+  if (! str || ! out_val)
+    return 0;
+
+  res = 0;
+  i = 0;
+  while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0)
+  {
+    if ( (res > (UINT64_MAX / 16)) ||
+         ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit > (UINT64_MAX
+                                                              % 16)) ) )
+      return 0;
+
+    res *= 16;
+    res += (unsigned int) digit;
+    i++;
+  }
+
+  if (i)
+    *out_val = res;
+  return i;
+}
+
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+
+/**
+ * Generic function for converting not more then @a maxlen
+ * hexadecimal or decimal US-ASCII digits in string to number.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * To be used only within macro.
+ *
+ * @param str the string to convert
+ * @param maxlen the maximum number of characters to process
+ * @param out_val the pointer to variable to store result of conversion
+ * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8
+ * @param max_val the maximum decoded number
+ * @param base the numeric base, 10 or 16
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then @a max_val, @a val_size is not 4/8 or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uvalue_n_ (const char *str,
+                      size_t maxlen,
+                      void *out_val,
+                      size_t val_size,
+                      uint64_t max_val,
+                      unsigned int base)
+{
+  size_t i;
+  uint64_t res;
+  const uint64_t max_v_div_b = max_val / base;
+  const uint64_t max_v_mod_b = max_val % base;
+
+  if (! str || ! out_val ||
+      ((base != 16) && (base != 10)) )
+    return 0;
+
+  res = 0;
+  i = 0;
+  while (maxlen > i)
+  {
+    const int digit = (base == 16) ?
+                      toxdigitvalue (str[i]) : todigitvalue (str[i]);
+
+    if (0 > digit)
+      break;
+    if ( ((max_v_div_b) < res) ||
+         (( (max_v_div_b) == res) && ( (max_v_mod_b) < (uint64_t) digit) ) )
+      return 0;
+
+    res *= base;
+    res += (unsigned int) digit;
+    i++;
+  }
+
+  if (i)
+  {
+    if (8 == val_size)
+      *(uint64_t *) out_val = res;
+    else if (4 == val_size)
+      *(uint32_t *) out_val = (uint32_t) res;
+    else
+      return 0;
+  }
+  return i;
+}
+
+
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+size_t
+MHD_uint32_to_strx (uint32_t val,
+                    char *buf,
+                    size_t buf_size)
+{
+  size_t o_pos = 0; /**< position of the output character */
+  int digit_pos = 8; /** zero-based, digit position in @a 'val' */
+  int digit;
+
+  /* Skip leading zeros */
+  do
+  {
+    digit_pos--;
+    digit = (int) (val >> 28);
+    val <<= 4;
+  } while ((0 == digit) && (0 != digit_pos));
+
+  while (o_pos < buf_size)
+  {
+    buf[o_pos++] = (digit <= 9) ? ('0' + (char) digit) :
+                   ('A' + (char) digit - 10);
+    if (0 == digit_pos)
+      return o_pos;
+    digit_pos--;
+    digit = (int) (val >> 28);
+    val <<= 4;
+  }
+  return 0; /* The buffer is too small */
+}
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+size_t
+MHD_uint16_to_str (uint16_t val,
+                   char *buf,
+                   size_t buf_size)
+{
+  char *chr;  /**< pointer to the current printed digit */
+  /* The biggest printable number is 65535 */
+  uint16_t divisor = UINT16_C (10000);
+  int digit;
+
+  chr = buf;
+  digit = (int) (val / divisor);
+  mhd_assert (digit < 10);
+
+  /* Do not print leading zeros */
+  while ((0 == digit) && (1 < divisor))
+  {
+    divisor /= 10;
+    digit = (int) (val / divisor);
+    mhd_assert (digit < 10);
+  }
+
+  while (0 != buf_size)
+  {
+    *chr = (char) digit + '0';
+    chr++;
+    buf_size--;
+    if (1 == divisor)
+      return (size_t) (chr - buf);
+    val %= divisor;
+    divisor /= 10;
+    digit = (int) (val / divisor);
+    mhd_assert (digit < 10);
+  }
+  return 0; /* The buffer is too small */
+}
+
+
+#endif /* !MHD_FAVOR_SMALL_CODE */
+
+
+size_t
+MHD_uint64_to_str (uint64_t val,
+                   char *buf,
+                   size_t buf_size)
+{
+  char *chr;  /**< pointer to the current printed digit */
+  /* The biggest printable number is 18446744073709551615 */
+  uint64_t divisor = UINT64_C (10000000000000000000);
+  int digit;
+
+  chr = buf;
+  digit = (int) (val / divisor);
+  mhd_assert (digit < 10);
+
+  /* Do not print leading zeros */
+  while ((0 == digit) && (1 < divisor))
+  {
+    divisor /= 10;
+    digit = (int) (val / divisor);
+    mhd_assert (digit < 10);
+  }
+
+  while (0 != buf_size)
+  {
+    *chr = (char) digit + '0';
+    chr++;
+    buf_size--;
+    if (1 == divisor)
+      return (size_t) (chr - buf);
+    val %= divisor;
+    divisor /= 10;
+    digit = (int) (val / divisor);
+    mhd_assert (digit < 10);
+  }
+  return 0; /* The buffer is too small */
+}
+
+
+size_t
+MHD_uint8_to_str_pad (uint8_t val,
+                      uint8_t min_digits,
+                      char *buf,
+                      size_t buf_size)
+{
+  size_t pos; /**< the position of the current printed digit */
+  int digit;
+  mhd_assert (3 >= min_digits);
+  if (0 == buf_size)
+    return 0;
+
+  pos = 0;
+  digit = val / 100;
+  if (0 == digit)
+  {
+    if (3 <= min_digits)
+      buf[pos++] = '0';
+  }
+  else
+  {
+    buf[pos++] = '0' + (char) digit;
+    val %= 100;
+    min_digits = 2;
+  }
+
+  if (buf_size <= pos)
+    return 0;
+  digit = val / 10;
+  if (0 == digit)
+  {
+    if (2 <= min_digits)
+      buf[pos++] = '0';
+  }
+  else
+  {
+    buf[pos++] = '0' + (char) digit;
+    val %= 10;
+  }
+
+  if (buf_size <= pos)
+    return 0;
+  buf[pos++] = '0' + (char) val;
+  return pos;
+}
+
+
+size_t
+MHD_bin_to_hex (const void *bin,
+                size_t size,
+                char *hex)
+{
+  size_t i;
+
+  for (i = 0; i < size; ++i)
+  {
+    uint8_t j;
+    const uint8_t b = ((const uint8_t *) bin)[i];
+    j = b >> 4;
+    hex[i * 2] = (char) ((j < 10) ? (j + '0') : (j - 10 + 'a'));
+    j = b & 0x0f;
+    hex[i * 2 + 1] = (char) ((j < 10) ? (j + '0') : (j - 10 + 'a'));
+  }
+  return i * 2;
+}
+
+
+size_t
+MHD_bin_to_hex_z (const void *bin,
+                  size_t size,
+                  char *hex)
+{
+  size_t res;
+
+  res = MHD_bin_to_hex (bin, size, hex);
+  hex[res] = 0;
+
+  return res;
+}
+
+
+size_t
+MHD_hex_to_bin (const char *hex,
+                size_t len,
+                void *bin)
+{
+  uint8_t *const out = (uint8_t *) bin;
+  size_t r;
+  size_t w;
+
+  if (0 == len)
+    return 0;
+  r = 0;
+  w = 0;
+  if (0 != len % 2)
+  {
+    /* Assume the first byte is encoded with single digit */
+    const int l = toxdigitvalue (hex[r++]);
+    if (0 > l)
+      return 0;
+    out[w++] = (uint8_t) ((unsigned int) l);
+  }
+  while (r < len)
+  {
+    const int h = toxdigitvalue (hex[r++]);
+    const int l = toxdigitvalue (hex[r++]);
+    if ((0 > h) || (0 > l))
+      return 0;
+    out[w++] = ( ((uint8_t) (((uint8_t) ((unsigned int) h)) << 4))
+                 | ((uint8_t) ((unsigned int) l)) );
+  }
+  mhd_assert (len == r);
+  mhd_assert ((len + 1) / 2 == w);
+  return w;
+}
+
+
+size_t
+MHD_str_pct_decode_strict_n_ (const char *pct_encoded,
+                              size_t pct_encoded_len,
+                              char *decoded,
+                              size_t buf_size)
+{
+#ifdef MHD_FAVOR_SMALL_CODE
+  bool broken;
+  size_t res;
+
+  res = MHD_str_pct_decode_lenient_n_ (pct_encoded, pct_encoded_len, decoded,
+                                       buf_size, &broken);
+  if (broken)
+    return 0;
+  return res;
+#else  /* ! MHD_FAVOR_SMALL_CODE */
+  size_t r;
+  size_t w;
+  r = 0;
+  w = 0;
+
+  if (buf_size >= pct_encoded_len)
+  {
+    while (r < pct_encoded_len)
+    {
+      const char chr = pct_encoded[r];
+      if ('%' == chr)
+      {
+        if (2 > pct_encoded_len - r)
+          return 0;
+        else
+        {
+          const int h = toxdigitvalue (pct_encoded[++r]);
+          const int l = toxdigitvalue (pct_encoded[++r]);
+          unsigned char out;
+          if ((0 > h) || (0 > l))
+            return 0;
+          out = (unsigned char) ( (((uint8_t) ((unsigned int) h)) << 4)
+                                  | ((uint8_t) ((unsigned int) l)) );
+          decoded[w] = (char) out;
+        }
+      }
+      else
+        decoded[w] = chr;
+      ++r;
+      ++w;
+    }
+    return w;
+  }
+
+  while (r < pct_encoded_len)
+  {
+    const char chr = pct_encoded[r];
+    if (w >= buf_size)
+      return 0;
+    if ('%' == chr)
+    {
+      if (2 > pct_encoded_len - r)
+        return 0;
+      else
+      {
+        const int h = toxdigitvalue (pct_encoded[++r]);
+        const int l = toxdigitvalue (pct_encoded[++r]);
+        unsigned char out;
+        if ((0 > h) || (0 > l))
+          return 0;
+        out = (unsigned char) ( (((uint8_t) ((unsigned int) h)) << 4)
+                                | ((uint8_t) ((unsigned int) l)) );
+        decoded[w] = (char) out;
+      }
+    }
+    else
+      decoded[w] = chr;
+    ++r;
+    ++w;
+  }
+  return w;
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+}
+
+
+size_t
+MHD_str_pct_decode_lenient_n_ (const char *pct_encoded,
+                               size_t pct_encoded_len,
+                               char *decoded,
+                               size_t buf_size,
+                               bool *broken_encoding)
+{
+  size_t r;
+  size_t w;
+  r = 0;
+  w = 0;
+  if (NULL != broken_encoding)
+    *broken_encoding = false;
+#ifndef MHD_FAVOR_SMALL_CODE
+  if (buf_size >= pct_encoded_len)
+  {
+    while (r < pct_encoded_len)
+    {
+      const char chr = pct_encoded[r];
+      if ('%' == chr)
+      {
+        if (2 > pct_encoded_len - r)
+        {
+          if (NULL != broken_encoding)
+            *broken_encoding = true;
+          decoded[w] = chr; /* Copy "as is" */
+        }
+        else
+        {
+          const int h = toxdigitvalue (pct_encoded[++r]);
+          const int l = toxdigitvalue (pct_encoded[++r]);
+          unsigned char out;
+          if ((0 > h) || (0 > l))
+          {
+            r -= 2;
+            if (NULL != broken_encoding)
+              *broken_encoding = true;
+            decoded[w] = chr; /* Copy "as is" */
+          }
+          else
+          {
+            out = (unsigned char) ( (((uint8_t) ((unsigned int) h)) << 4)
+                                    | ((uint8_t) ((unsigned int) l)) );
+            decoded[w] = (char) out;
+          }
+        }
+      }
+      else
+        decoded[w] = chr;
+      ++r;
+      ++w;
+    }
+    return w;
+  }
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+  while (r < pct_encoded_len)
+  {
+    const char chr = pct_encoded[r];
+    if (w >= buf_size)
+      return 0;
+    if ('%' == chr)
+    {
+      if (2 > pct_encoded_len - r)
+      {
+        if (NULL != broken_encoding)
+          *broken_encoding = true;
+        decoded[w] = chr; /* Copy "as is" */
+      }
+      else
+      {
+        const int h = toxdigitvalue (pct_encoded[++r]);
+        const int l = toxdigitvalue (pct_encoded[++r]);
+        if ((0 > h) || (0 > l))
+        {
+          r -= 2;
+          if (NULL != broken_encoding)
+            *broken_encoding = true;
+          decoded[w] = chr; /* Copy "as is" */
+        }
+        else
+        {
+          unsigned char out;
+          out = (unsigned char) ( (((uint8_t) ((unsigned int) h)) << 4)
+                                  | ((uint8_t) ((unsigned int) l)) );
+          decoded[w] = (char) out;
+        }
+      }
+    }
+    else
+      decoded[w] = chr;
+    ++r;
+    ++w;
+  }
+  return w;
+}
+
+
+size_t
+MHD_str_pct_decode_in_place_strict_ (char *str)
+{
+#ifdef MHD_FAVOR_SMALL_CODE
+  size_t res;
+  bool broken;
+
+  res = MHD_str_pct_decode_in_place_lenient_ (str, &broken);
+  if (broken)
+  {
+    res = 0;
+    str[0] = 0;
+  }
+  return res;
+#else  /* ! MHD_FAVOR_SMALL_CODE */
+  size_t r;
+  size_t w;
+  r = 0;
+  w = 0;
+
+  while (0 != str[r])
+  {
+    const char chr = str[r++];
+    if ('%' == chr)
+    {
+      const char d1 = str[r++];
+      if (0 == d1)
+        return 0;
+      else
+      {
+        const char d2 = str[r++];
+        if (0 == d2)
+          return 0;
+        else
+        {
+          const int h = toxdigitvalue (d1);
+          const int l = toxdigitvalue (d2);
+          unsigned char out;
+          if ((0 > h) || (0 > l))
+            return 0;
+          out = (unsigned char) ( (((uint8_t) ((unsigned int) h)) << 4)
+                                  | ((uint8_t) ((unsigned int) l)) );
+          str[w++] = (char) out;
+        }
+      }
+    }
+    else
+      str[w++] = chr;
+  }
+  str[w] = 0;
+  return w;
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+}
+
+
+size_t
+MHD_str_pct_decode_in_place_lenient_ (char *str,
+                                      bool *broken_encoding)
+{
+#ifdef MHD_FAVOR_SMALL_CODE
+  size_t len;
+  size_t res;
+
+  len = strlen (str);
+  res = MHD_str_pct_decode_lenient_n_ (str, len, str, len, broken_encoding);
+  str[res] = 0;
+
+  return res;
+#else  /* ! MHD_FAVOR_SMALL_CODE */
+  size_t r;
+  size_t w;
+  if (NULL != broken_encoding)
+    *broken_encoding = false;
+  r = 0;
+  w = 0;
+  while (0 != str[r])
+  {
+    const char chr = str[r++];
+    if ('%' == chr)
+    {
+      const char d1 = str[r++];
+      if (0 == d1)
+      {
+        if (NULL != broken_encoding)
+          *broken_encoding = true;
+        str[w++] = chr; /* Copy "as is" */
+        str[w] = 0;
+        return w;
+      }
+      else
+      {
+        const char d2 = str[r++];
+        if (0 == d2)
+        {
+          if (NULL != broken_encoding)
+            *broken_encoding = true;
+          str[w++] = chr; /* Copy "as is" */
+          str[w++] = d1; /* Copy "as is" */
+          str[w] = 0;
+          return w;
+        }
+        else
+        {
+          const int h = toxdigitvalue (d1);
+          const int l = toxdigitvalue (d2);
+          unsigned char out;
+          if ((0 > h) || (0 > l))
+          {
+            if (NULL != broken_encoding)
+              *broken_encoding = true;
+            str[w++] = chr; /* Copy "as is" */
+            str[w++] = d1;
+            str[w++] = d2;
+            continue;
+          }
+          out = (unsigned char) ( (((uint8_t) ((unsigned int) h)) << 4)
+                                  | ((uint8_t) ((unsigned int) l)) );
+          str[w++] = (char) out;
+          continue;
+        }
+      }
+    }
+    str[w++] = chr;
+  }
+  str[w] = 0;
+  return w;
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+}
+
+
+#ifdef DAUTH_SUPPORT
+bool
+MHD_str_equal_quoted_bin_n (const char *quoted,
+                            size_t quoted_len,
+                            const char *unquoted,
+                            size_t unquoted_len)
+{
+  size_t i;
+  size_t j;
+  if (unquoted_len < quoted_len / 2)
+    return false;
+
+  j = 0;
+  for (i = 0; quoted_len > i && unquoted_len > j; ++i, ++j)
+  {
+    if ('\\' == quoted[i])
+    {
+      i++; /* Advance to the next character */
+      if (quoted_len == i)
+        return false; /* No character after escaping backslash */
+    }
+    if (quoted[i] != unquoted[j])
+      return false; /* Different characters */
+  }
+  if ((quoted_len != i) || (unquoted_len != j))
+    return false; /* The strings have different length */
+
+  return true;
+}
+
+
+bool
+MHD_str_equal_caseless_quoted_bin_n (const char *quoted,
+                                     size_t quoted_len,
+                                     const char *unquoted,
+                                     size_t unquoted_len)
+{
+  size_t i;
+  size_t j;
+  if (unquoted_len < quoted_len / 2)
+    return false;
+
+  j = 0;
+  for (i = 0; quoted_len > i && unquoted_len > j; ++i, ++j)
+  {
+    if ('\\' == quoted[i])
+    {
+      i++; /* Advance to the next character */
+      if (quoted_len == i)
+        return false; /* No character after escaping backslash */
+    }
+    if (! charsequalcaseless (quoted[i], unquoted[j]))
+      return false; /* Different characters */
+  }
+  if ((quoted_len != i) || (unquoted_len != j))
+    return false; /* The strings have different length */
+
+  return true;
+}
+
+
+size_t
+MHD_str_unquote (const char *quoted,
+                 size_t quoted_len,
+                 char *result)
+{
+  size_t r;
+  size_t w;
+
+  r = 0;
+  w = 0;
+
+  while (quoted_len > r)
+  {
+    if ('\\' == quoted[r])
+    {
+      ++r;
+      if (quoted_len == r)
+        return 0; /* Last backslash is not followed by char to unescape */
+    }
+    result[w++] = quoted[r++];
+  }
+  return w;
+}
+
+
+#endif /* DAUTH_SUPPORT */
+
+#if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT)
+
+size_t
+MHD_str_quote (const char *unquoted,
+               size_t unquoted_len,
+               char *result,
+               size_t buf_size)
+{
+  size_t r;
+  size_t w;
+
+  r = 0;
+  w = 0;
+
+#ifndef MHD_FAVOR_SMALL_CODE
+  if (unquoted_len * 2 <= buf_size)
+  {
+    /* Fast loop: the output will fit the buffer with any input string content */
+    while (unquoted_len > r)
+    {
+      const char chr = unquoted[r++];
+      if (('\\' == chr) || ('\"' == chr))
+        result[w++] = '\\'; /* Escape current char */
+      result[w++] = chr;
+    }
+  }
+  else
+  {
+    if (unquoted_len > buf_size)
+      return 0; /* Quick fail: the output buffer is too small */
+#else  /* MHD_FAVOR_SMALL_CODE */
+  if (1)
+  {
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+    while (unquoted_len > r)
+    {
+      if (buf_size <= w)
+        return 0; /* The output buffer is too small */
+      else
+      {
+        const char chr = unquoted[r++];
+        if (('\\' == chr) || ('\"' == chr))
+        {
+          result[w++] = '\\'; /* Escape current char */
+          if (buf_size <= w)
+            return 0; /* The output buffer is too small */
+        }
+        result[w++] = chr;
+      }
+    }
+  }
+
+  mhd_assert (w >= r);
+  mhd_assert (w <= r * 2);
+  return w;
+}
+
+
+#endif /* DAUTH_SUPPORT || BAUTH_SUPPORT */
+
+#ifdef BAUTH_SUPPORT
+
+size_t
+MHD_base64_to_bin_n (const char *base64,
+                     size_t base64_len,
+                     void *bin,
+                     size_t bin_size)
+{
+#ifndef MHD_FAVOR_SMALL_CODE
+#define map_type int
+#else  /* MHD_FAVOR_SMALL_CODE */
+#define map_type int8_t
+#endif /* MHD_FAVOR_SMALL_CODE */
+  static const map_type map[] = {
+    /* -1 = invalid char, -2 = padding
+     0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  A,  B,  C,  D,  E,  F */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* 00..0F */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* 10..1F */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,  /* 20..2F */
+    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,  /* 30..3F */
+    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,  /* 40..4F */
+    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,  /* 50..5F */
+    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,  /* 60..6F */
+    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1   /* 70..7F */
+#ifndef MHD_FAVOR_SMALL_CODE
+    ,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* 80..8F */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* 90..9F */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* A0..AF */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* B0..BF */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* C0..CF */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* D0..DF */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* E0..EF */
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  /* F0..FF */
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+  };
+  const uint8_t *const in = (const uint8_t *) base64;
+  uint8_t *const out = (uint8_t *) bin;
+  size_t i;
+  size_t j;
+  if (0 == base64_len)
+    return 0;  /* Nothing to decode */
+  if (0 != base64_len % 4)
+    return 0;  /* Wrong input length */
+  if (base64_len / 4 * 3 - 2 > bin_size)
+    return 0;
+
+  j = 0;
+  for (i = 0; i < (base64_len - 4); i += 4)
+  {
+#ifdef MHD_FAVOR_SMALL_CODE
+    if (0 != (0x80 & (in[i] | in[i + 1] | in[i + 2] | in[i + 3])))
+      return 0;
+#endif /* MHD_FAVOR_SMALL_CODE */
+    if (1)
+    {
+      const map_type v1 = map[in[i + 0]];
+      const map_type v2 = map[in[i + 1]];
+      const map_type v3 = map[in[i + 2]];
+      const map_type v4 = map[in[i + 3]];
+      if ((0 > v1) || (0 > v2) || (0 > v3) || (0 > v4))
+        return 0;
+      out[j + 0] = (uint8_t) ((((uint8_t) v1) << 2) | (((uint8_t) v2) >> 4));
+      out[j + 1] = (uint8_t) ((((uint8_t) v2) << 4) | (((uint8_t) v3) >> 2));
+      out[j + 2] = (uint8_t) ((((uint8_t) v3) << 6) | (((uint8_t) v4)));
+    }
+    j += 3;
+  }
+#ifdef MHD_FAVOR_SMALL_CODE
+  if (0 != (0x80 & (in[i] | in[i + 1] | in[i + 2] | in[i + 3])))
+    return 0;
+#endif /* MHD_FAVOR_SMALL_CODE */
+  if (1)
+  { /* The last four chars block */
+    const map_type v1 = map[in[i + 0]];
+    const map_type v2 = map[in[i + 1]];
+    const map_type v3 = map[in[i + 2]];
+    const map_type v4 = map[in[i + 3]];
+    if ((0 > v1) || (0 > v2))
+      return 0; /* Invalid char or padding at first two positions */
+    mhd_assert (j < bin_size);
+    out[j++] = (uint8_t) ((((uint8_t) v1) << 2) | (((uint8_t) v2) >> 4));
+    if (0 > v3)
+    { /* Third char is either padding or invalid */
+      if ((-2 != v3) || (-2 != v4))
+        return 0;  /* Both two last chars must be padding */
+      if (0 != (uint8_t) (((uint8_t) v2) << 4))
+        return 0;  /* Wrong last char */
+      return j;
+    }
+    if (j >= bin_size)
+      return 0; /* Not enough space */
+    out[j++] = (uint8_t) ((((uint8_t) v2) << 4) | (((uint8_t) v3) >> 2));
+    if (0 > v4)
+    { /* Fourth char is either padding or invalid */
+      if (-2 != v4)
+        return 0;  /* The char must be padding */
+      if (0 != (uint8_t) (((uint8_t) v3) << 6))
+        return 0;  /* Wrong last char */
+      return j;
+    }
+    if (j >= bin_size)
+      return 0; /* Not enough space */
+    out[j++] = (uint8_t) ((((uint8_t) v3) << 6) | (((uint8_t) v4)));
+  }
+  return j;
+#undef map_type
+}
+
+
+#endif /* BAUTH_SUPPORT */
diff --git a/src/microhttpd/mhd_str.h b/src/microhttpd/mhd_str.h
new file mode 100644
index 0000000..f7a4f79
--- /dev/null
+++ b/src/microhttpd/mhd_str.h
@@ -0,0 +1,777 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015-2022 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_str.h
+ * @brief  Header for string manipulating helpers
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_STR_H
+#define MHD_STR_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif /* HAVE_STDDEF_H */
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+#include "mhd_str_types.h"
+
+#if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED)
+#define _SSIZE_T_DEFINED
+typedef intptr_t ssize_t;
+#endif /* !_SSIZE_T_DEFINED */
+
+#ifdef MHD_FAVOR_SMALL_CODE
+#include "mhd_limits.h"
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+/*
+ * Block of functions/macros that use US-ASCII charset as required by HTTP
+ * standards. Not affected by current locale settings.
+ */
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/**
+ * Check two strings for equality, ignoring case of US-ASCII letters.
+ *
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_ (const char *str1,
+                         const char *str2);
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+/* Reuse MHD_str_equal_caseless_n_() to reduce size */
+#define MHD_str_equal_caseless_(s1,s2) MHD_str_equal_caseless_n_ ((s1),(s2), \
+                                                                  SIZE_MAX)
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters and
+ * checking not more than @a maxlen characters.
+ * Compares up to first terminating null character, but not more than
+ * first @a maxlen characters.
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @param maxlen maximum number of characters to compare
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+int
+MHD_str_equal_caseless_n_ (const char *const str1,
+                           const char *const str2,
+                           size_t maxlen);
+
+
+/**
+ * Check two string for equality, ignoring case of US-ASCII letters and
+ * checking not more than @a len bytes.
+ * Compares not more first than @a len bytes, including binary zero characters.
+ * Comparison stops at first unmatched byte.
+ * @param str1 first string to compare
+ * @param str2 second string to compare
+ * @param len number of characters to compare
+ * @return non-zero if @a len bytes are equal, zero otherwise.
+ */
+bool
+MHD_str_equal_caseless_bin_n_ (const char *const str1,
+                               const char *const str2,
+                               size_t len);
+
+
+/**
+ * Check whether string is equal statically allocated another string,
+ * ignoring case of US-ASCII letters and checking not more than @a len bytes.
+ *
+ * If strings have different sizes (lengths) then macro returns boolean false
+ * without checking the content.
+ *
+ * Compares not more first than @a len bytes, including binary zero characters.
+ * Comparison stops at first unmatched byte.
+ * @param a the statically allocated string to compare
+ * @param s the string to compare
+ * @param len number of characters to compare
+ * @return non-zero if @a len bytes are equal, zero otherwise.
+ */
+#define MHD_str_equal_caseless_s_bin_n_(a,s,l) \
+  ((MHD_STATICSTR_LEN_(a) == (l)) \
+   && MHD_str_equal_caseless_bin_n_(a,s,l))
+
+/**
+ * Check whether @a str has case-insensitive @a token.
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Match succeed if substring between start, end (of string) or comma
+ * contains only case-insensitive token and optional spaces and tabs.
+ * @warning token must not contain null-characters except optional
+ *          terminating null-character.
+ * @param str the string to check
+ * @param token the token to find
+ * @param token_len length of token, not including optional terminating
+ *                  null-character.
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+bool
+MHD_str_has_token_caseless_ (const char *str,
+                             const char *const token,
+                             size_t token_len);
+
+/**
+ * Check whether @a str has case-insensitive static @a tkn.
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Match succeed if substring between start, end of string or comma
+ * contains only case-insensitive token and optional spaces and tabs.
+ * @warning tkn must be static string
+ * @param str the string to check
+ * @param tkn the static string of token to find
+ * @return non-zero if two strings are equal, zero otherwise.
+ */
+#define MHD_str_has_s_token_caseless_(str,tkn) \
+  MHD_str_has_token_caseless_ ((str),(tkn),MHD_STATICSTR_LEN_ (tkn))
+
+
+/**
+ * Remove case-insensitive @a token from the @a str and put result
+ * to the output @a buf.
+ *
+ * Tokens in @a str could be surrounded by spaces and tabs and delimited by
+ * comma. The token match succeed if substring between start, end (of string)
+ * or comma contains only case-insensitive token and optional spaces and tabs.
+ * The quoted strings and comments are not supported by this function.
+ *
+ * The output string is normalised: empty tokens and repeated whitespaces
+ * are removed, no whitespaces before commas, exactly one space is used after
+ * each comma.
+ *
+ * @param str the string to process
+ * @param str_len the length of the @a str, not including optional
+ *                terminating null-character.
+ * @param token the token to find
+ * @param token_len the length of @a token, not including optional
+ *                  terminating null-character.
+ * @param[out] buf the output buffer, not null-terminated.
+ * @param[in,out] buf_size pointer to the size variable, at input it
+ *                         is the size of allocated buffer, at output
+ *                         it is the size of the resulting string (can
+ *                         be up to 50% larger than input) or negative value
+ *                         if there is not enough space for the result
+ * @return 'true' if token has been removed,
+ *         'false' otherwise.
+ */
+bool
+MHD_str_remove_token_caseless_ (const char *str,
+                                size_t str_len,
+                                const char *const token,
+                                const size_t token_len,
+                                char *buf,
+                                ssize_t *buf_size);
+
+
+/**
+ * Perform in-place case-insensitive removal of @a tokens from the @a str.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * The token match succeed if substring between start, end (of the string), or
+ * comma contains only case-insensitive token and optional spaces and tabs.
+ * The quoted strings and comments are not supported by this function.
+ *
+ * The input string must be normalised: empty tokens and repeated whitespaces
+ * are removed, no whitespaces before commas, exactly one space is used after
+ * each comma. The string is updated in-place.
+ *
+ * Behavior is undefined is the input string in not normalised.
+ *
+ * @param[in,out] str the string to update
+ * @param[in,out] str_len the length of the @a str, not including optional
+ *                        terminating null-character, not null-terminated
+ * @param tokens the token to find
+ * @param tokens_len the length of @a tokens, not including optional
+ *                   terminating null-character.
+ * @return 'true' if any token has been removed,
+ *         'false' otherwise.
+ */
+bool
+MHD_str_remove_tokens_caseless_ (char *str,
+                                 size_t *str_len,
+                                 const char *const tokens,
+                                 const size_t tokens_len);
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/* Use individual function for each case to improve speed */
+
+/**
+ * Convert decimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_ (const char *str,
+                    uint64_t *out_val);
+
+/**
+ * Convert not more then @a maxlen decimal US-ASCII digits in string to
+ * number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uint64_n_ (const char *str,
+                      size_t maxlen,
+                      uint64_t *out_val);
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint32_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_ (const char *str,
+                     uint32_t *out_val);
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint32_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint32_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint32_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint32_n_ (const char *str,
+                       size_t maxlen,
+                       uint32_t *out_val);
+
+
+/**
+ * Convert hexadecimal US-ASCII digits in string to number in uint64_t.
+ * Conversion stopped at first non-digit character.
+ *
+ * @param str string to convert
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_ (const char *str,
+                     uint64_t *out_val);
+
+
+/**
+ * Convert not more then @a maxlen hexadecimal US-ASCII digits in string
+ * to number in uint64_t.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ *
+ * @param str string to convert
+ * @param maxlen maximum number of characters to process
+ * @param[out] out_val pointer to uint64_t to store result of conversion
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then possible to store in uint64_t or @a out_val is NULL
+ */
+size_t
+MHD_strx_to_uint64_n_ (const char *str,
+                       size_t maxlen,
+                       uint64_t *out_val);
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+/* Use one universal function and macros to reduce size */
+
+/**
+ * Generic function for converting not more then @a maxlen
+ * hexadecimal or decimal US-ASCII digits in string to number.
+ * Conversion stopped at first non-digit character or after @a maxlen
+ * digits.
+ * To be used only within macro.
+ *
+ * @param str the string to convert
+ * @param maxlen the maximum number of characters to process
+ * @param out_val the pointer to variable to store result of conversion
+ * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8
+ * @param max_val the maximum decoded number
+ * @param base the numeric base, 10 or 16
+ * @return non-zero number of characters processed on succeed,
+ *         zero if no digit is found, resulting value is larger
+ *         then @a max_val, @a val_size is not 4/8 or @a out_val is NULL
+ */
+size_t
+MHD_str_to_uvalue_n_ (const char *str,
+                      size_t maxlen,
+                      void *out_val,
+                      size_t val_size,
+                      uint64_t max_val,
+                      unsigned int base);
+
+#define MHD_str_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                       sizeof(uint64_t), \
+                                                       UINT64_MAX,10)
+
+#define MHD_str_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                            sizeof(uint64_t), \
+                                                            UINT64_MAX,10)
+
+#define MHD_strx_to_sizet_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                       sizeof(size_t),SIZE_MAX, \
+                                                       16)
+
+#define MHD_strx_to_sizet_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                            sizeof(size_t), \
+                                                            SIZE_MAX,16)
+
+#define MHD_strx_to_uint32_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                        sizeof(uint32_t), \
+                                                        UINT32_MAX,16)
+
+#define MHD_strx_to_uint32_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                             sizeof(uint32_t), \
+                                                             UINT32_MAX,16)
+
+#define MHD_strx_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \
+                                                        sizeof(uint64_t), \
+                                                        UINT64_MAX,16)
+
+#define MHD_strx_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \
+                                                             sizeof(uint64_t), \
+                                                             UINT64_MAX,16)
+
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Convert uint32_t value to hexdecimal US-ASCII string.
+ * @note: result is NOT zero-terminated.
+ * @param val the value to convert
+ * @param buf the buffer to result to
+ * @param buf_size size of the @a buffer
+ * @return number of characters has been put to the @a buf,
+ *         zero if buffer is too small (buffer may be modified).
+ */
+size_t
+MHD_uint32_to_strx (uint32_t val,
+                    char *buf,
+                    size_t buf_size);
+
+
+#ifndef MHD_FAVOR_SMALL_CODE
+/**
+ * Convert uint16_t value to decimal US-ASCII string.
+ * @note: result is NOT zero-terminated.
+ * @param val the value to convert
+ * @param buf the buffer to result to
+ * @param buf_size size of the @a buffer
+ * @return number of characters has been put to the @a buf,
+ *         zero if buffer is too small (buffer may be modified).
+ */
+size_t
+MHD_uint16_to_str (uint16_t val,
+                   char *buf,
+                   size_t buf_size);
+
+#else  /* MHD_FAVOR_SMALL_CODE */
+#define MHD_uint16_to_str(v,b,s) MHD_uint64_to_str(v,b,s)
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+
+/**
+ * Convert uint64_t value to decimal US-ASCII string.
+ * @note: result is NOT zero-terminated.
+ * @param val the value to convert
+ * @param buf the buffer to result to
+ * @param buf_size size of the @a buffer
+ * @return number of characters has been put to the @a buf,
+ *         zero if buffer is too small (buffer may be modified).
+ */
+size_t
+MHD_uint64_to_str (uint64_t val,
+                   char *buf,
+                   size_t buf_size);
+
+
+/**
+ * Convert uint16_t value to decimal US-ASCII string padded with
+ * zeros on the left side.
+ *
+ * @note: result is NOT zero-terminated.
+ * @param val the value to convert
+ * @param min_digits the minimal number of digits to print,
+ *                   output padded with zeros on the left side,
+ *                   'zero' value is interpreted as 'one',
+ *                   valid values are 3, 2, 1, 0
+ * @param buf the buffer to result to
+ * @param buf_size size of the @a buffer
+ * @return number of characters has been put to the @a buf,
+ *         zero if buffer is too small (buffer may be modified).
+ */
+size_t
+MHD_uint8_to_str_pad (uint8_t val,
+                      uint8_t min_digits,
+                      char *buf,
+                      size_t buf_size);
+
+
+/**
+ * Convert @a size bytes from input binary data to lower case
+ * hexadecimal digits.
+ * Result is NOT zero-terminated
+ * @param bin the pointer to the binary data to convert
+ * @param size the size in bytes of the binary data to convert
+ * @param[out] hex the output buffer, should be at least 2 * @a size
+ * @return The number of characters written to the output buffer.
+ */
+size_t
+MHD_bin_to_hex (const void *bin,
+                size_t size,
+                char *hex);
+
+/**
+ * Convert @a size bytes from input binary data to lower case
+ * hexadecimal digits, zero-terminate the result.
+ * @param bin the pointer to the binary data to convert
+ * @param size the size in bytes of the binary data to convert
+ * @param[out] hex the output buffer, should be at least 2 * @a size + 1
+ * @return The number of characters written to the output buffer,
+ *         not including terminating zero.
+ */
+size_t
+MHD_bin_to_hex_z (const void *bin,
+                  size_t size,
+                  char *hex);
+
+/**
+ * Convert hexadecimal digits to binary data.
+ *
+ * The input decoded byte-by-byte (each byte is two hexadecimal digits).
+ * If length is an odd number, extra leading zero is assumed.
+ *
+ * @param hex the input string with hexadecimal digits
+ * @param len the length of the input string
+ * @param[out] bin the output buffer, must be at least len/2 bytes long (or
+ *                 len/2 + 1 if @a len is not even number)
+ * @return the number of bytes written to the output buffer,
+ *         zero if found any character which is not hexadecimal digits
+ */
+size_t
+MHD_hex_to_bin (const char *hex,
+                size_t len,
+                void *bin);
+
+/**
+ * Decode string with percent-encoded characters as defined by
+ * RFC 3986 #section-2.1.
+ *
+ * This function decode string by converting percent-encoded characters to
+ * their decoded versions and copying all other characters without extra
+ * processing.
+ *
+ * @param pct_encoded the input string to be decoded
+ * @param pct_encoded_len the length of the @a pct_encoded
+ * @param[out] decoded the output buffer, NOT zero-terminated, can point
+ *                     to the same buffer as @a pct_encoded
+ * @param buf_size the size of the output buffer
+ * @return the number of characters written to the output buffer or
+ *         zero if any percent-encoded characters is broken ('%' followed
+ *         by less than two hexadecimal digits) or output buffer is too
+ *         small to hold the result
+ */
+size_t
+MHD_str_pct_decode_strict_n_ (const char *pct_encoded,
+                              size_t pct_encoded_len,
+                              char *decoded,
+                              size_t buf_size);
+
+/**
+ * Decode string with percent-encoded characters as defined by
+ * RFC 3986 #section-2.1.
+ *
+ * This function decode string by converting percent-encoded characters to
+ * their decoded versions and copying all other characters without extra
+ * processing.
+ *
+ * Any invalid percent-encoding sequences ('%' symbol not followed by two
+ * valid hexadecimal digits) are copied to the output string without decoding.
+ *
+ * @param pct_encoded the input string to be decoded
+ * @param pct_encoded_len the length of the @a pct_encoded
+ * @param[out] decoded the output buffer, NOT zero-terminated, can point
+ *                     to the same buffer as @a pct_encoded
+ * @param buf_size the size of the output buffer
+ * @param[out] broken_encoding will be set to true if any '%' symbol is not
+ *                             followed by two valid hexadecimal digits,
+ *                             optional, can be NULL
+ * @return the number of characters written to the output buffer or
+ *         zero if output buffer is too small to hold the result
+ */
+size_t
+MHD_str_pct_decode_lenient_n_ (const char *pct_encoded,
+                               size_t pct_encoded_len,
+                               char *decoded,
+                               size_t buf_size,
+                               bool *broken_encoding);
+
+
+/**
+ * Decode string in-place with percent-encoded characters as defined by
+ * RFC 3986 #section-2.1.
+ *
+ * This function decode string by converting percent-encoded characters to
+ * their decoded versions and copying back all other characters without extra
+ * processing.
+ *
+ * @param[in,out] str the string to be updated in-place, must be zero-terminated
+ *                    on input, the output is zero-terminated; the string is
+ *                    truncated to zero length if broken encoding is found
+ * @return the number of character in decoded string
+ */
+size_t
+MHD_str_pct_decode_in_place_strict_ (char *str);
+
+
+/**
+ * Decode string in-place with percent-encoded characters as defined by
+ * RFC 3986 #section-2.1.
+ *
+ * This function decode string by converting percent-encoded characters to
+ * their decoded versions and copying back all other characters without extra
+ * processing.
+ *
+ * Any invalid percent-encoding sequences ('%' symbol not followed by two
+ * valid hexadecimal digits) are copied to the output string without decoding.
+ *
+ * @param[in,out] str the string to be updated in-place, must be zero-terminated
+ *                    on input, the output is zero-terminated
+ * @param[out] broken_encoding will be set to true if any '%' symbol is not
+ *                             followed by two valid hexadecimal digits,
+ *                             optional, can be NULL
+ * @return the number of character in decoded string
+ */
+size_t
+MHD_str_pct_decode_in_place_lenient_ (char *str,
+                                      bool *broken_encoding);
+
+#ifdef DAUTH_SUPPORT
+/**
+ * Check two strings for equality, "unquoting" the first string from quoted
+ * form as specified by RFC7230#section-3.2.6 and RFC7694#quoted.strings.
+ *
+ * Null-termination for input strings is not required, binary zeros compared
+ * like other characters.
+ *
+ * @param quoted the quoted string to compare, must NOT include leading and
+ *               closing DQUOTE chars, does not need to be zero-terminated
+ * @param quoted_len the length in chars of the @a quoted string
+ * @param unquoted the unquoted string to compare, does not need to be
+ *                 zero-terminated
+ * @param unquoted_len the length in chars of the @a unquoted string
+ * @return zero if quoted form is broken (no character after the last escaping
+ *         backslash), zero if strings are not equal after unquoting of the
+ *         first string,
+ *         non-zero if two strings are equal after unquoting of the
+ *         first string.
+ */
+bool
+MHD_str_equal_quoted_bin_n (const char *quoted,
+                            size_t quoted_len,
+                            const char *unquoted,
+                            size_t unquoted_len);
+
+/**
+ * Check whether the string after "unquoting" equals static string.
+ *
+ * Null-termination for input string is not required, binary zeros compared
+ * like other characters.
+ *
+ * @param q the quoted string to compare, must NOT include leading and
+ *          closing DQUOTE chars, does not need to be zero-terminated
+ * @param l the length in chars of the @a q string
+ * @param u the unquoted static string to compare
+ * @return zero if quoted form is broken (no character after the last escaping
+ *         backslash), zero if strings are not equal after unquoting of the
+ *         first string,
+ *         non-zero if two strings are equal after unquoting of the
+ *         first string.
+ */
+#define MHD_str_equal_quoted_s_bin_n(q,l,u) \
+    MHD_str_equal_quoted_bin_n(q,l,u,MHD_STATICSTR_LEN_(u))
+
+/**
+ * Check two strings for equality, "unquoting" the first string from quoted
+ * form as specified by RFC7230#section-3.2.6 and RFC7694#quoted.strings and
+ * ignoring case of US-ASCII letters.
+ *
+ * Null-termination for input strings is not required, binary zeros compared
+ * like other characters.
+ *
+ * @param quoted the quoted string to compare, must NOT include leading and
+ *               closing DQUOTE chars, does not need to be zero-terminated
+ * @param quoted_len the length in chars of the @a quoted string
+ * @param unquoted the unquoted string to compare, does not need to be
+ *                 zero-terminated
+ * @param unquoted_len the length in chars of the @a unquoted string
+ * @return zero if quoted form is broken (no character after the last escaping
+ *         backslash), zero if strings are not equal after unquoting of the
+ *         first string,
+ *         non-zero if two strings are caseless equal after unquoting of the
+ *         first string.
+ */
+bool
+MHD_str_equal_caseless_quoted_bin_n (const char *quoted,
+                                     size_t quoted_len,
+                                     const char *unquoted,
+                                     size_t unquoted_len);
+
+/**
+ * Check whether the string after "unquoting" equals static string, ignoring
+ * case of US-ASCII letters.
+ *
+ * Null-termination for input string is not required, binary zeros compared
+ * like other characters.
+ *
+ * @param q the quoted string to compare, must NOT include leading and
+ *          closing DQUOTE chars, does not need to be zero-terminated
+ * @param l the length in chars of the @a q string
+ * @param u the unquoted static string to compare
+ * @return zero if quoted form is broken (no character after the last escaping
+ *         backslash), zero if strings are not equal after unquoting of the
+ *         first string,
+ *         non-zero if two strings are caseless equal after unquoting of the
+ *         first string.
+ */
+#define MHD_str_equal_caseless_quoted_s_bin_n(q,l,u) \
+    MHD_str_equal_caseless_quoted_bin_n(q,l,u,MHD_STATICSTR_LEN_(u))
+
+/**
+ * Convert string from quoted to unquoted form as specified by
+ * RFC7230#section-3.2.6 and RFC7694#quoted.strings.
+ *
+ * @param quoted the quoted string, must NOT include leading and closing
+ *               DQUOTE chars, does not need to be zero-terminated
+ * @param quoted_len the length in chars of the @a quoted string
+ * @param[out] result the pointer to the buffer to put the result, must
+ *                    be at least @a size character long. May be modified even
+ *                    if @a quoted is invalid sequence. The result is NOT
+ *                    zero-terminated.
+ * @return The number of characters written to the output buffer,
+ *         zero if last backslash is not followed by any character (or
+ *         @a quoted_len is zero).
+ */
+size_t
+MHD_str_unquote (const char *quoted,
+                 size_t quoted_len,
+                 char *result);
+
+#endif /* DAUTH_SUPPORT */
+
+#if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT)
+
+/**
+ * Convert string from unquoted to quoted form as specified by
+ * RFC7230#section-3.2.6 and RFC7694#quoted.strings.
+ *
+ * @param unquoted the unquoted string, does not need to be zero-terminated
+ * @param unquoted_len the length in chars of the @a unquoted string
+ * @param[out] result the pointer to the buffer to put the result. May be
+ *                    modified even if function failed due to insufficient
+ *                    space. The result is NOT zero-terminated and does not
+ *                    have opening and closing DQUOTE chars.
+ * @param buf_size the size of the allocated memory for @a result
+ * @return The number of copied characters, can be up to two times more than
+ *         @a unquoted_len, zero if @a unquoted_len is zero or if quoted
+ *         string is larger than @a buf_size.
+ */
+size_t
+MHD_str_quote (const char *unquoted,
+               size_t unquoted_len,
+               char *result,
+               size_t buf_size);
+
+#endif /* DAUTH_SUPPORT || BAUTH_SUPPORT */
+
+#ifdef BAUTH_SUPPORT
+
+/**
+ * Returns the maximum possible size of the Base64 decoded data.
+ * The real recoded size could be up to two bytes smaller.
+ * @param enc_size the size of encoded data, in characters
+ * @return the maximum possible size of the decoded data, in bytes, if
+ *         @a enc_size is valid (properly padded),
+ *         undefined value smaller then @a enc_size if @a enc_size is not valid
+ */
+#define MHD_base64_max_dec_size_(enc_size) (((enc_size) / 4) * 3)
+
+/**
+ * Convert Base64 encoded string to binary data.
+ * @param base64 the input string with Base64 encoded data, could be NOT zero
+ *               terminated
+ * @param base64_len the number of characters to decode in @a base64 string,
+ *                   valid number must be a multiple of four
+ * @param[out] bin the pointer to the output buffer, the buffer may be altered
+ *                 even if decoding failed
+ * @param bin_size the size of the @a bin buffer in bytes, if the size is
+ *                 at least @a base64_len / 4 * 3 then result will always
+ *                 fit, regardless of the amount of the padding characters
+ * @return 0 if @a base64_len is zero, or input string has wrong data (not
+ *         valid Base64 sequence), or @a bin_size is too small;
+ *         non-zero number of bytes written to the @a bin, the number must be
+ *         (base64_len / 4 * 3 - 2), (base64_len / 4 * 3 - 1) or
+ *         (base64_len / 4 * 3), depending on the number of padding characters.
+ */
+size_t
+MHD_base64_to_bin_n (const char *base64,
+                     size_t base64_len,
+                     void *bin,
+                     size_t bin_size);
+
+#endif /* BAUTH_SUPPORT */
+
+#endif /* MHD_STR_H */
diff --git a/src/microhttpd/mhd_str_types.h b/src/microhttpd/mhd_str_types.h
new file mode 100644
index 0000000..c846ebe
--- /dev/null
+++ b/src/microhttpd/mhd_str_types.h
@@ -0,0 +1,68 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015-2022 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/mhd_str_types.h
+ * @brief  Header for string manipulating helpers types
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_STR_TYPES_H
+#define MHD_STR_TYPES_H 1
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+/**
+ * Constant string with length
+ */
+struct _MHD_cstr_w_len
+{
+  const char *const str;
+  const size_t len;
+};
+
+/**
+ * String with length
+ */
+struct _MHD_str_w_len
+{
+  const char *str;
+  size_t len;
+};
+
+/**
+ * Modifiable string with length
+ */
+struct _MHD_mstr_w_len
+{
+  char *str;
+  size_t len;
+};
+
+/**
+ * Static string initialiser for struct _MHD_str_w_len
+ */
+#define _MHD_S_STR_W_LEN(str) { str, MHD_STATICSTR_LEN_(str) }
+
+#endif /* MHD_STR_TYPES_H */
diff --git a/src/microhttpd/mhd_threads.c b/src/microhttpd/mhd_threads.c
new file mode 100644
index 0000000..95fc70a
--- /dev/null
+++ b/src/microhttpd/mhd_threads.c
@@ -0,0 +1,378 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_threads.c
+ * @brief  Implementation for thread functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_threads.h"
+#ifdef MHD_USE_W32_THREADS
+#include "mhd_limits.h"
+#include <process.h>
+#endif
+#ifdef MHD_USE_THREAD_NAME_
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#ifdef HAVE_PTHREAD_NP_H
+#include <pthread_np.h>
+#endif /* HAVE_PTHREAD_NP_H */
+#endif /* MHD_USE_THREAD_NAME_ */
+#include <errno.h>
+
+
+#ifndef MHD_USE_THREAD_NAME_
+
+#define MHD_set_thread_name_(t, n) (void)
+#define MHD_set_cur_thread_name_(n) (void)
+
+#else  /* MHD_USE_THREAD_NAME_ */
+
+#if defined(MHD_USE_POSIX_THREADS)
+#if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \
+  defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI)
+#  define MHD_USE_THREAD_ATTR_SETNAME 1
+#endif /* HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD || \
+          HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI */
+
+#if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \
+  defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) \
+  || defined(HAVE_PTHREAD_SETNAME_NP_NETBSD)
+
+/**
+ * Set thread name
+ *
+ * @param thread_id ID of thread
+ * @param thread_name name to set
+ * @return non-zero on success, zero otherwise
+ */
+static int
+MHD_set_thread_name_ (const MHD_thread_ID_ thread_id,
+                      const char *thread_name)
+{
+  if (NULL == thread_name)
+    return 0;
+
+#if defined(HAVE_PTHREAD_SETNAME_NP_GNU)
+  return ! pthread_setname_np (thread_id, thread_name);
+#elif defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD)
+  /* FreeBSD and OpenBSD use different function name and void return type */
+  pthread_set_name_np (thread_id, thread_name);
+  return ! 0;
+#elif defined(HAVE_PTHREAD_SETNAME_NP_NETBSD)
+  /* NetBSD use 3 arguments: second argument is string in printf-like format,
+   *                         third argument is a single argument for printf();
+   * OSF1 use 3 arguments too, but last one always must be zero (NULL).
+   * MHD doesn't use '%' in thread names, so both form are used in same way.
+   */
+  return ! pthread_setname_np (thread_id, thread_name, 0);
+#endif /* HAVE_PTHREAD_SETNAME_NP_NETBSD */
+}
+
+
+#ifndef __QNXNTO__
+/**
+ * Set current thread name
+ * @param n name to set
+ * @return non-zero on success, zero otherwise
+ */
+#define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (pthread_self (),(n))
+#else  /* __QNXNTO__ */
+/* Special case for QNX Neutrino - using zero for thread ID sets name faster. */
+#define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (0,(n))
+#endif /* __QNXNTO__ */
+#elif defined(HAVE_PTHREAD_SETNAME_NP_DARWIN)
+
+/**
+ * Set current thread name
+ * @param n name to set
+ * @return non-zero on success, zero otherwise
+ */
+#define MHD_set_cur_thread_name_(n) (! (pthread_setname_np ((n))))
+#endif /* HAVE_PTHREAD_SETNAME_NP_DARWIN */
+
+#elif defined(MHD_USE_W32_THREADS)
+#ifndef _MSC_FULL_VER
+/* Thread name available only for VC-compiler */
+#else  /* _MSC_FULL_VER */
+/**
+ * Set thread name
+ *
+ * @param thread_id ID of thread, -1 for current thread
+ * @param thread_name name to set
+ * @return non-zero on success, zero otherwise
+ */
+static int
+MHD_set_thread_name_ (const MHD_thread_ID_ thread_id,
+                      const char *thread_name)
+{
+  static const DWORD VC_SETNAME_EXC = 0x406D1388;
+#pragma pack(push,8)
+  struct thread_info_struct
+  {
+    DWORD type;   /* Must be 0x1000. */
+    LPCSTR name;  /* Pointer to name (in user address space). */
+    DWORD ID;     /* Thread ID (-1 = caller thread). */
+    DWORD flags;  /* Reserved for future use, must be zero. */
+  } thread_info;
+#pragma pack(pop)
+
+  if (NULL == thread_name)
+    return 0;
+
+  thread_info.type  = 0x1000;
+  thread_info.name  = thread_name;
+  thread_info.ID    = thread_id;
+  thread_info.flags = 0;
+
+  __try
+  { /* This exception is intercepted by debugger */
+    RaiseException (VC_SETNAME_EXC,
+                    0,
+                    sizeof (thread_info) / sizeof(ULONG_PTR),
+                    (ULONG_PTR *) &thread_info);
+  }
+  __except (EXCEPTION_EXECUTE_HANDLER)
+  {}
+
+  return ! 0;
+}
+
+
+/**
+ * Set current thread name
+ * @param n name to set
+ * @return non-zero on success, zero otherwise
+ */
+#define MHD_set_cur_thread_name_(n) \
+  MHD_set_thread_name_ ((MHD_thread_ID_) -1,(n))
+#endif /* _MSC_FULL_VER */
+#endif /* MHD_USE_W32_THREADS */
+
+#endif /* MHD_USE_THREAD_NAME_ */
+
+
+/**
+ * Create a thread and set the attributes according to our options.
+ *
+ * If thread is created, thread handle must be freed by MHD_join_thread_().
+ *
+ * @param thread        handle to initialize
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise (with errno set)
+ */
+int
+MHD_create_thread_ (MHD_thread_handle_ID_ *thread,
+                    size_t stack_size,
+                    MHD_THREAD_START_ROUTINE_ start_routine,
+                    void *arg)
+{
+#if defined(MHD_USE_POSIX_THREADS)
+  int res;
+
+  if (0 != stack_size)
+  {
+    pthread_attr_t attr;
+    res = pthread_attr_init (&attr);
+    if (0 == res)
+    {
+      res = pthread_attr_setstacksize (&attr,
+                                       stack_size);
+      if (0 == res)
+        res = pthread_create (&(thread->handle),
+                              &attr,
+                              start_routine,
+                              arg);
+      pthread_attr_destroy (&attr);
+    }
+  }
+  else
+    res = pthread_create (&(thread->handle),
+                          NULL,
+                          start_routine,
+                          arg);
+
+  if (0 != res)
+    errno = res;
+
+  return ! res;
+#elif defined(MHD_USE_W32_THREADS)
+#if SIZEOF_SIZE_T != SIZEOF_UNSIGNED_INT
+  if (stack_size > UINT_MAX)
+  {
+    errno = EINVAL;
+    return 0;
+  }
+#endif /* SIZEOF_SIZE_T != SIZEOF_UNSIGNED_INT */
+
+  thread->handle = (MHD_thread_handle_) (uintptr_t)
+                   _beginthreadex (NULL,
+                                   (unsigned int) stack_size,
+                                   start_routine,
+                                   arg,
+                                   0,
+                                   NULL);
+
+  if ((MHD_thread_handle_) - 1 == thread->handle)
+    return 0;
+
+  return ! 0;
+#endif
+}
+
+
+#ifdef MHD_USE_THREAD_NAME_
+
+#ifndef MHD_USE_THREAD_ATTR_SETNAME
+struct MHD_named_helper_param_
+{
+  /**
+   * Real thread start routine
+   */
+  MHD_THREAD_START_ROUTINE_ start_routine;
+
+  /**
+   * Argument for thread start routine
+   */
+  void *arg;
+
+  /**
+   * Name for thread
+   */
+  const char *name;
+};
+
+
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+named_thread_starter (void *data)
+{
+  struct MHD_named_helper_param_ *const param =
+    (struct MHD_named_helper_param_ *) data;
+  void *arg;
+  MHD_THREAD_START_ROUTINE_ thr_func;
+
+  if (NULL == data)
+    return (MHD_THRD_RTRN_TYPE_) 0;
+
+  MHD_set_cur_thread_name_ (param->name);
+
+  arg = param->arg;
+  thr_func = param->start_routine;
+  free (data);
+
+  return thr_func (arg);
+}
+
+
+#endif /* ! MHD_USE_THREAD_ATTR_SETNAME */
+
+
+/**
+ * Create a named thread and set the attributes according to our options.
+ *
+ * @param thread        handle to initialize
+ * @param thread_name   name for new thread
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise (with errno set)
+ */
+int
+MHD_create_named_thread_ (MHD_thread_handle_ID_ *thread,
+                          const char *thread_name,
+                          size_t stack_size,
+                          MHD_THREAD_START_ROUTINE_ start_routine,
+                          void *arg)
+{
+#if defined(MHD_USE_THREAD_ATTR_SETNAME)
+  int res;
+  pthread_attr_t attr;
+
+  res = pthread_attr_init (&attr);
+  if (0 == res)
+  {
+#if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD)
+    /* NetBSD use 3 arguments: second argument is string in printf-like format,
+     *                         third argument is single argument for printf;
+     * OSF1 use 3 arguments too, but last one always must be zero (NULL).
+     * MHD doesn't use '%' in thread names, so both form are used in same way.
+     */
+    res = pthread_attr_setname_np (&attr,
+                                   thread_name,
+                                   0);
+#elif defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI)
+    res = pthread_attr_setname_np (&attr,
+                                   thread_name);
+#else
+#error No pthread_attr_setname_np() function.
+#endif
+    if ((res == 0) && (0 != stack_size) )
+      res = pthread_attr_setstacksize (&attr,
+                                       stack_size);
+    if (0 == res)
+      res = pthread_create (&(thread->handle),
+                            &attr,
+                            start_routine,
+                            arg);
+    pthread_attr_destroy (&attr);
+  }
+  if (0 != res)
+    errno = res;
+
+  return ! res;
+#else  /* ! MHD_USE_THREAD_ATTR_SETNAME */
+  struct MHD_named_helper_param_ *param;
+
+  if (NULL == thread_name)
+  {
+    errno = EINVAL;
+    return 0;
+  }
+
+  param = malloc (sizeof (struct MHD_named_helper_param_));
+  if (NULL == param)
+    return 0;
+
+  param->start_routine = start_routine;
+  param->arg = arg;
+  param->name = thread_name;
+
+  /* Set thread name in thread itself to avoid problems with
+   * threads which terminated before name is set in other thread.
+   */
+  if (! MHD_create_thread_ (thread,
+                            stack_size,
+                            &named_thread_starter,
+                            (void *) param))
+  {
+    free (param);
+    return 0;
+  }
+
+  return ! 0;
+#endif /* ! MHD_USE_THREAD_ATTR_SETNAME */
+}
+
+
+#endif /* MHD_USE_THREAD_NAME_ */
diff --git a/src/microhttpd/mhd_threads.h b/src/microhttpd/mhd_threads.h
new file mode 100644
index 0000000..0a50463
--- /dev/null
+++ b/src/microhttpd/mhd_threads.h
@@ -0,0 +1,248 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd/mhd_threads.h
+ * @brief  Header for platform-independent threads abstraction
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * Provides basic abstraction for threads.
+ * Any functions can be implemented as macro on some platforms
+ * unless explicitly marked otherwise.
+ * Any function argument can be skipped in macro, so avoid
+ * variable modification in function parameters.
+ *
+ * @warning Unlike pthread functions, most of functions return
+ *          nonzero on success.
+ */
+
+#ifndef MHD_THREADS_H
+#define MHD_THREADS_H 1
+
+#include "mhd_options.h"
+#ifdef HAVE_STDDEF_H
+#  include <stddef.h> /* for size_t */
+#elif defined(HAVE_STDLIB_H)
+#  include <stdlib.h> /* for size_t */
+#else /* ! HAVE_STDLIB_H */
+#  include <stdio.h>  /* for size_t */
+#endif /* ! HAVE_STDLIB_H */
+
+#if defined(MHD_USE_POSIX_THREADS)
+#  undef HAVE_CONFIG_H
+#  include <pthread.h>
+#  define HAVE_CONFIG_H 1
+#  ifndef MHD_USE_THREADS
+#    define MHD_USE_THREADS 1
+#  endif
+#elif defined(MHD_USE_W32_THREADS)
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN 1
+#  endif /* !WIN32_LEAN_AND_MEAN */
+#  include <windows.h>
+#  ifndef MHD_USE_THREADS
+#    define MHD_USE_THREADS 1
+#  endif
+#else
+#  error No threading API is available.
+#endif
+
+#ifndef MHD_NO_THREAD_NAMES
+#  if defined(MHD_USE_POSIX_THREADS)
+#    if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \
+  defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) || \
+  defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) || \
+  defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) || \
+  defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \
+  defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI)
+#      define MHD_USE_THREAD_NAME_
+#    endif /* HAVE_PTHREAD_SETNAME_NP */
+#  elif defined(MHD_USE_W32_THREADS)
+#    ifdef _MSC_FULL_VER
+/* Thread names only available with VC compiler */
+#      define MHD_USE_THREAD_NAME_
+#    endif /* _MSC_FULL_VER */
+#  endif
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+typedef pthread_t MHD_thread_handle_;
+#elif defined(MHD_USE_W32_THREADS)
+typedef HANDLE MHD_thread_handle_;
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+#  define MHD_THRD_RTRN_TYPE_ void*
+#  define MHD_THRD_CALL_SPEC_
+#elif defined(MHD_USE_W32_THREADS)
+#  define MHD_THRD_RTRN_TYPE_ unsigned
+#  define MHD_THRD_CALL_SPEC_ __stdcall
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+typedef pthread_t MHD_thread_ID_;
+#elif defined(MHD_USE_W32_THREADS)
+typedef DWORD MHD_thread_ID_;
+#endif
+
+/* Depending on implementation, pthread_create() MAY set thread ID into
+ * provided pointer and after it start thread OR start thread and after
+ * it set thread ID. In the latter case, to avoid data races, additional
+ * pthread_self() call is required in thread routine. If some platform
+ * is known for setting thread ID BEFORE starting thread macro
+ * MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD could be defined
+ * to save some resources. */
+/* * handle - must be valid when other thread knows that particular thread
+     is started.
+   * ID     - must be valid when code is executed inside thread */
+#if defined(MHD_USE_POSIX_THREADS)
+#  ifdef MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD
+union _MHD_thread_handle_ID_
+{
+  MHD_thread_handle_ handle;    /**< To be used in other threads */
+  MHD_thread_ID_ ID;            /**< To be used in thread itself */
+};
+typedef union _MHD_thread_handle_ID_ MHD_thread_handle_ID_;
+#  else  /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+struct _MHD_thread_handle_ID_
+{
+  MHD_thread_handle_ handle;    /**< To be used in other threads */
+  MHD_thread_ID_ ID;            /**< To be used in thread itself */
+};
+typedef struct _MHD_thread_handle_ID_ MHD_thread_handle_ID_;
+#  endif /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+#elif defined(MHD_USE_W32_THREADS)
+struct _MHD_thread_handle_ID_
+{
+  MHD_thread_handle_ handle;    /**< To be used in other threads */
+  MHD_thread_ID_ ID;            /**< To be used in thread itself */
+};
+typedef struct _MHD_thread_handle_ID_ MHD_thread_handle_ID_;
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+/**
+ * Wait until specified thread is ended and free thread handle on success.
+ * @param thread handle to watch
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_join_thread_(thread) (! pthread_join ((thread), NULL))
+#elif defined(MHD_USE_W32_THREADS)
+/**
+ * Wait until specified thread is ended and free thread handle on success.
+ * @param thread handle to watch
+ * @return nonzero on success, zero otherwise
+ */
+#define MHD_join_thread_(thread) \
+  ( (WAIT_OBJECT_0 == WaitForSingleObject ( (thread), INFINITE)) ? \
+    (CloseHandle ( (thread)), ! 0) : 0 )
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+/**
+ * Check whether provided thread ID match current thread.
+ * @param ID thread ID to match
+ * @return nonzero on match, zero otherwise
+ */
+#define MHD_thread_ID_match_current_(pid) \
+          (pthread_equal ((pid).ID, pthread_self ()))
+#elif defined(MHD_USE_W32_THREADS)
+/**
+ * Check whether provided thread ID match current thread.
+ * @param ID thread ID to match
+ * @return nonzero on match, zero otherwise
+ */
+#define MHD_thread_ID_match_current_(pid) (GetCurrentThreadId () == (pid).ID)
+#endif
+
+#if defined(MHD_USE_POSIX_THREADS)
+#  ifdef MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD
+/**
+ * Initialise thread ID.
+ * @param thread_handle_ID_ptr pointer to thread handle-ID
+ */
+#define MHD_thread_init_(thread_handle_ID_ptr) (void) 0
+#  else  /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+/**
+ * Initialise thread ID.
+ * @param thread_handle_ID_ptr pointer to thread handle-ID
+ */
+#define MHD_thread_init_(thread_handle_ID_ptr) ((thread_handle_ID_ptr)->ID = \
+                                                  pthread_self ())
+#  endif /* ! MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD */
+#elif defined(MHD_USE_W32_THREADS)
+/**
+ * Initialise thread ID.
+ * @param thread_handle_ID_ptr pointer to thread handle-ID
+ */
+#define MHD_thread_init_(thread_handle_ID_ptr) ((thread_handle_ID_ptr)->ID = \
+                                                  GetCurrentThreadId ())
+#endif
+
+/**
+ * Signature of main function for a thread.
+ *
+ * @param cls closure argument for the function
+ * @return termination code from the thread
+ */
+typedef MHD_THRD_RTRN_TYPE_
+(MHD_THRD_CALL_SPEC_ *MHD_THREAD_START_ROUTINE_)(void *cls);
+
+
+/**
+ * Create a thread and set the attributes according to our options.
+ *
+ * If thread is created, thread handle must be freed by MHD_join_thread_().
+ *
+ * @param thread        handle to initialize
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise (with errno set)
+ */
+int
+MHD_create_thread_ (MHD_thread_handle_ID_ *thread,
+                    size_t stack_size,
+                    MHD_THREAD_START_ROUTINE_ start_routine,
+                    void *arg);
+
+#ifndef MHD_USE_THREAD_NAME_
+#define MHD_create_named_thread_(t,n,s,r,a) MHD_create_thread_ ((t),(s),(r),(a))
+#else  /* MHD_USE_THREAD_NAME_ */
+/**
+ * Create a named thread and set the attributes according to our options.
+ *
+ * @param thread        handle to initialize
+ * @param thread_name   name for new thread
+ * @param stack_size    size of stack for new thread, 0 for default
+ * @param start_routine main function of thread
+ * @param arg argument  for start_routine
+ * @return non-zero on success; zero otherwise
+ */
+int
+MHD_create_named_thread_ (MHD_thread_handle_ID_ *thread,
+                          const char *thread_name,
+                          size_t stack_size,
+                          MHD_THREAD_START_ROUTINE_ start_routine,
+                          void *arg);
+
+#endif /* MHD_USE_THREAD_NAME_ */
+
+#endif /* ! MHD_THREADS_H */
diff --git a/src/microhttpd/microhttpd_dll_res.rc.in b/src/microhttpd/microhttpd_dll_res.rc.in
index 923f3a9..f89c07a 100644
--- a/src/microhttpd/microhttpd_dll_res.rc.in
+++ b/src/microhttpd/microhttpd_dll_res.rc.in
@@ -7,7 +7,11 @@
   FILEVERSION @PACKAGE_VERSION_MAJOR@,@PACKAGE_VERSION_MINOR@,@PACKAGE_VERSION_SUBMINOR@,0
   PRODUCTVERSION @PACKAGE_VERSION_MAJOR@,@PACKAGE_VERSION_MINOR@,@PACKAGE_VERSION_SUBMINOR@,0
   FILEFLAGSMASK  VS_FFI_FILEFLAGSMASK
+#if defined(_DEBUG)
+  FILEFLAGS      VS_FF_DEBUG
+#else
   FILEFLAGS      0
+#endif
   FILEOS         VOS_NT_WINDOWS32
   FILETYPE       VFT_DLL
   FILESUBTYPE    VFT2_UNKNOWN
@@ -19,11 +23,11 @@
             VALUE "ProductName", "GNU libmicrohttpd\0"
             VALUE "ProductVersion", "@PACKAGE_VERSION@\0"
             VALUE "FileVersion", "@PACKAGE_VERSION@\0"
-            VALUE "FileDescription", "GNU libmicrohttpd dll for Windows (GCC build)\0"
+            VALUE "FileDescription", "GNU libmicrohttpd DLL for Windows (MinGW build, @W32CRT@ run-time lib)\0"
             VALUE "InternalName", "libmicrohttpd\0"
-            VALUE "OriginalFilename", "libmicrohttpd.dll\0"
+            VALUE "OriginalFilename", "libmicrohttpd-@MHD_W32_DLL_SUFF@.dll\0"
             VALUE "CompanyName", "Free Software Foundation\0"
-            VALUE "LegalCopyright",  "Copyright (C) 2007-2015 Christian Grothoff and project contributors\0"
+            VALUE "LegalCopyright",  "Copyright (C) 2007-2021 Christian Grothoff, Evgeny Grin, and project contributors\0"
             VALUE "Comments", "http://www.gnu.org/software/libmicrohttpd/\0"
         END
     END
diff --git a/src/microhttpd/postprocessor.c b/src/microhttpd/postprocessor.c
index d371f3d..c00605c 100644
--- a/src/microhttpd/postprocessor.c
+++ b/src/microhttpd/postprocessor.c
@@ -1,6 +1,6 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007-2013 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2007-2021 Daniel Pittman, Christian Grothoff, and Evgeny Grin
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -21,9 +21,14 @@
  * @file postprocessor.c
  * @brief  Methods for parsing POST data
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
+#include "postprocessor.h"
 #include "internal.h"
+#include "mhd_str.h"
+#include "mhd_compat.h"
+#include "mhd_assert.h"
 
 /**
  * Size of on-stack buffer that we use for un-escaping of the value.
@@ -32,291 +37,71 @@
  */
 #define XBUF_SIZE 512
 
-/**
- * States in the PP parser's state machine.
- */
-enum PP_State
-{
-  /* general states */
-  PP_Error,
-  PP_Done,
-  PP_Init,
-  PP_NextBoundary,
 
-  /* url encoding-states */
-  PP_ProcessValue,
-  PP_ExpectNewLine,
-
-  /* post encoding-states  */
-  PP_ProcessEntryHeaders,
-  PP_PerformCheckMultipart,
-  PP_ProcessValueToBoundary,
-  PP_PerformCleanup,
-
-  /* nested post-encoding states */
-  PP_Nested_Init,
-  PP_Nested_PerformMarking,
-  PP_Nested_ProcessEntryHeaders,
-  PP_Nested_ProcessValueToBoundary,
-  PP_Nested_PerformCleanup
-
-};
-
-
-enum RN_State
-{
-  /**
-   * No RN-preprocessing in this state.
-   */
-  RN_Inactive = 0,
-
-  /**
-   * If the next character is CR, skip it.  Otherwise,
-   * just go inactive.
-   */
-  RN_OptN = 1,
-
-  /**
-   * Expect LFCR (and only LFCR).  As always, we also
-   * expect only LF or only CR.
-   */
-  RN_Full = 2,
-
-  /**
-   * Expect either LFCR or '--'LFCR.  If '--'LFCR, transition into dash-state
-   * for the main state machine
-   */
-  RN_Dash = 3,
-
-  /**
-   * Got a single dash, expect second dash.
-   */
-  RN_Dash2 = 4
-};
-
-
-/**
- * Bits for the globally known fields that
- * should not be deleted when we exit the
- * nested state.
- */
-enum NE_State
-{
-  NE_none = 0,
-  NE_content_name = 1,
-  NE_content_type = 2,
-  NE_content_filename = 4,
-  NE_content_transfer_encoding = 8
-};
-
-
-/**
- * Internal state of the post-processor.  Note that the fields
- * are sorted by type to enable optimal packing by the compiler.
- */
-struct MHD_PostProcessor
-{
-
-  /**
-   * The connection for which we are doing
-   * POST processing.
-   */
-  struct MHD_Connection *connection;
-
-  /**
-   * Function to call with POST data.
-   */
-  MHD_PostDataIterator ikvi;
-
-  /**
-   * Extra argument to ikvi.
-   */
-  void *cls;
-
-  /**
-   * Encoding as given by the headers of the
-   * connection.
-   */
-  const char *encoding;
-
-  /**
-   * Primary boundary (points into encoding string)
-   */
-  const char *boundary;
-
-  /**
-   * Nested boundary (if we have multipart/mixed encoding).
-   */
-  char *nested_boundary;
-
-  /**
-   * Pointer to the name given in disposition.
-   */
-  char *content_name;
-
-  /**
-   * Pointer to the (current) content type.
-   */
-  char *content_type;
-
-  /**
-   * Pointer to the (current) filename.
-   */
-  char *content_filename;
-
-  /**
-   * Pointer to the (current) encoding.
-   */
-  char *content_transfer_encoding;
-
-  /**
-   * Unprocessed value bytes due to escape
-   * sequences (URL-encoding only).
-   */
-  char xbuf[8];
-
-  /**
-   * Size of our buffer for the key.
-   */
-  size_t buffer_size;
-
-  /**
-   * Current position in the key buffer.
-   */
-  size_t buffer_pos;
-
-  /**
-   * Current position in xbuf.
-   */
-  size_t xbuf_pos;
-
-  /**
-   * Current offset in the value being processed.
-   */
-  uint64_t value_offset;
-
-  /**
-   * strlen(boundary) -- if boundary != NULL.
-   */
-  size_t blen;
-
-  /**
-   * strlen(nested_boundary) -- if nested_boundary != NULL.
-   */
-  size_t nlen;
-
-  /**
-   * Do we have to call the 'ikvi' callback when processing the
-   * multipart post body even if the size of the payload is zero?
-   * Set to #MHD_YES whenever we parse a new multiparty entry header,
-   * and to #MHD_NO the first time we call the 'ikvi' callback.
-   * Used to ensure that we do always call 'ikvi' even if the
-   * payload is empty (but not more than once).
-   */
-  int must_ikvi;
-
-  /**
-   * State of the parser.
-   */
-  enum PP_State state;
-
-  /**
-   * Side-state-machine: skip LRCR (or just LF).
-   * Set to 0 if we are not in skip mode.  Set to 2
-   * if a LFCR is expected, set to 1 if a CR should
-   * be skipped if it is the next character.
-   */
-  enum RN_State skip_rn;
-
-  /**
-   * If we are in skip_rn with "dash" mode and
-   * do find 2 dashes, what state do we go into?
-   */
-  enum PP_State dash_state;
-
-  /**
-   * Which headers are global? (used to tell which
-   * headers were only valid for the nested multipart).
-   */
-  enum NE_State have;
-
-};
-
-
-/**
- * Create a `struct MHD_PostProcessor`.
- *
- * A `struct MHD_PostProcessor` can be used to (incrementally) parse
- * the data portion of a POST request.  Note that some buggy browsers
- * fail to set the encoding type.  If you want to support those, you
- * may have to call #MHD_set_connection_value with the proper encoding
- * type before creating a post processor (if no supported encoding
- * type is set, this function will fail).
- *
- * @param connection the connection on which the POST is
- *        happening (used to determine the POST format)
- * @param buffer_size maximum number of bytes to use for
- *        internal buffering (used only for the parsing,
- *        specifically the parsing of the keys).  A
- *        tiny value (256-1024) should be sufficient.
- *        Do NOT use a value smaller than 256.  For good
- *        performance, use 32 or 64k (i.e. 65536).
- * @param iter iterator to be called with the parsed data,
- *        Must NOT be NULL.
- * @param iter_cls first argument to @a iter
- * @return NULL on error (out of memory, unsupported encoding),
- *         otherwise a PP handle
- * @ingroup request
- */
-struct MHD_PostProcessor *
+_MHD_EXTERN struct MHD_PostProcessor *
 MHD_create_post_processor (struct MHD_Connection *connection,
                            size_t buffer_size,
-                           MHD_PostDataIterator iter, void *iter_cls)
+                           MHD_PostDataIterator iter,
+                           void *iter_cls)
 {
   struct MHD_PostProcessor *ret;
   const char *encoding;
   const char *boundary;
   size_t blen;
 
-  if ((buffer_size < 256) || (connection == NULL) || (iter == NULL))
-    mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL);
-  encoding = MHD_lookup_connection_value (connection,
-                                          MHD_HEADER_KIND,
-                                          MHD_HTTP_HEADER_CONTENT_TYPE);
-  if (encoding == NULL)
+  if ( (buffer_size < 256) ||
+       (NULL == connection) ||
+       (NULL == iter))
+    MHD_PANIC (_ ("libmicrohttpd API violation.\n"));
+  encoding = NULL;
+  if (MHD_NO ==
+      MHD_lookup_connection_value_n (connection,
+                                     MHD_HEADER_KIND,
+                                     MHD_HTTP_HEADER_CONTENT_TYPE,
+                                     MHD_STATICSTR_LEN_ (
+                                       MHD_HTTP_HEADER_CONTENT_TYPE),
+                                     &encoding,
+                                     NULL))
     return NULL;
+  mhd_assert (NULL != encoding);
   boundary = NULL;
-  if (!MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED, encoding,
-                        strlen (MHD_HTTP_POST_ENCODING_FORM_URLENCODED)))
+  if (! MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED,
+                                   encoding,
+                                   MHD_STATICSTR_LEN_ (
+                                     MHD_HTTP_POST_ENCODING_FORM_URLENCODED)))
+  {
+    if (! MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA,
+                                     encoding,
+                                     MHD_STATICSTR_LEN_ (
+                                       MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)))
+      return NULL;
+    boundary =
+      &encoding[MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)];
+    /* Q: should this be "strcasestr"? */
+    boundary = strstr (boundary, "boundary=");
+    if (NULL == boundary)
+      return NULL; /* failed to determine boundary */
+    boundary += MHD_STATICSTR_LEN_ ("boundary=");
+    blen = strlen (boundary);
+    if ( (blen < 2) ||
+         (blen * 2 + 2 > buffer_size) )
+      return NULL;              /* (will be) out of memory or invalid boundary */
+    if ( (boundary[0] == '"') &&
+         (boundary[blen - 1] == '"') )
     {
-      if (!MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, encoding,
-                       strlen (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)))
-        return NULL;
-      boundary =
-        &encoding[strlen (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)];
-      /* Q: should this be "strcasestr"? */
-      boundary = strstr (boundary, "boundary=");
-      if (NULL == boundary)
-	return NULL; /* failed to determine boundary */
-      boundary += strlen ("boundary=");
-      blen = strlen (boundary);
-      if ((blen == 0) || (blen * 2 + 2 > buffer_size))
-        return NULL;            /* (will be) out of memory or invalid boundary */
-      if ( (boundary[0] == '"') && (boundary[blen - 1] == '"') )
-	{
-	  /* remove enclosing quotes */
-	  ++boundary;
-	  blen -= 2;
-	}
+      /* remove enclosing quotes */
+      ++boundary;
+      blen -= 2;
     }
+  }
   else
     blen = 0;
   buffer_size += 4; /* round up to get nice block sizes despite boundary search */
 
   /* add +1 to ensure we ALWAYS have a zero-termination at the end */
-  if (NULL == (ret = malloc (sizeof (struct MHD_PostProcessor) + buffer_size + 1)))
+  if (NULL == (ret = MHD_calloc_ (1, sizeof (struct MHD_PostProcessor)
+                                  + buffer_size + 1)))
     return NULL;
-  memset (ret, 0, sizeof (struct MHD_PostProcessor) + buffer_size + 1);
   ret->connection = connection;
   ret->ikvi = iter;
   ret->cls = iter_cls;
@@ -331,6 +116,157 @@
 
 
 /**
+ * Give a (possibly partial) value to the application callback.  We have some
+ * part of the value in the 'pp->xbuf', the rest is between @a value_start and
+ * @a value_end.  If @a last_escape is non-NULL, there may be an incomplete
+ * escape sequence at at @a value_escape between @a value_start and @a
+ * value_end which we should preserve in 'pp->xbuf' for the future.
+ *
+ * Unescapes the value and calls the iterator together with the key.  The key
+ * must already be in the key buffer allocated and 0-terminated at the end of
+ * @a pp at the time of the call.
+ *
+ * @param[in,out] pp post processor to act upon
+ * @param value_start where in memory is the value
+ * @param value_end where does the value end
+ * @param last_escape last '%'-sign in value range,
+ *        if relevant, or NULL
+ */
+static void
+process_value (struct MHD_PostProcessor *pp,
+               const char *value_start,
+               const char *value_end,
+               const char *last_escape)
+{
+  char xbuf[XBUF_SIZE + 1];
+  size_t xoff;
+
+  mhd_assert (pp->xbuf_pos < sizeof (xbuf));
+  /* 'value_start' and 'value_end' must be either both non-NULL or both NULL */
+  mhd_assert ( (NULL == value_start) || (NULL != value_end) );
+  mhd_assert ( (NULL != value_start) || (NULL == value_end) );
+  mhd_assert ( (NULL == last_escape) || (NULL != value_start) );
+  /* move remaining input from previous round into processing buffer */
+  if (0 != pp->xbuf_pos)
+    memcpy (xbuf,
+            pp->xbuf,
+            pp->xbuf_pos);
+  xoff = pp->xbuf_pos;
+  pp->xbuf_pos = 0;
+  if ( (NULL != last_escape) &&
+       (((size_t) (value_end - last_escape)) < sizeof (pp->xbuf)) )
+  {
+    mhd_assert (value_end >= last_escape);
+    pp->xbuf_pos = (size_t) (value_end - last_escape);
+    memcpy (pp->xbuf,
+            last_escape,
+            (size_t) (value_end - last_escape));
+    value_end = last_escape;
+  }
+  while ( (value_start != value_end) ||
+          (pp->must_ikvi) ||
+          (xoff > 0) )
+  {
+    size_t delta = (size_t) (value_end - value_start);
+    bool cut = false;
+    size_t clen = 0;
+
+    mhd_assert (value_end >= value_start);
+
+    if (delta > XBUF_SIZE - xoff)
+      delta = XBUF_SIZE - xoff;
+    /* move (additional) input into processing buffer */
+    if (0 != delta)
+    {
+      memcpy (&xbuf[xoff],
+              value_start,
+              delta);
+      xoff += delta;
+      value_start += delta;
+    }
+    /* find if escape sequence is at the end of the processing buffer;
+       if so, exclude those from processing (reduce delta to point at
+       end of processed region) */
+    if ( (xoff > 0) &&
+         ('%' == xbuf[xoff - 1]) )
+    {
+      cut = (xoff != XBUF_SIZE);
+      xoff--;
+      if (cut)
+      {
+        /* move escape sequence into buffer for next function invocation */
+        pp->xbuf[0] = '%';
+        pp->xbuf_pos = 1;
+      }
+      else
+      {
+        /* just skip escape sequence for next loop iteration */
+        delta = xoff;
+        clen = 1;
+      }
+    }
+    else if ( (xoff > 1) &&
+              ('%' == xbuf[xoff - 2]) )
+    {
+      cut = (xoff != XBUF_SIZE);
+      xoff -= 2;
+      if (cut)
+      {
+        /* move escape sequence into buffer for next function invocation */
+        memcpy (pp->xbuf,
+                &xbuf[xoff],
+                2);
+        pp->xbuf_pos = 2;
+      }
+      else
+      {
+        /* just skip escape sequence for next loop iteration */
+        delta = xoff;
+        clen = 2;
+      }
+    }
+    mhd_assert (xoff < sizeof (xbuf));
+    /* unescape */
+    xbuf[xoff] = '\0';        /* 0-terminate in preparation */
+    if (0 != xoff)
+    {
+      MHD_unescape_plus (xbuf);
+      xoff = MHD_http_unescape (xbuf);
+    }
+    /* finally: call application! */
+    if (pp->must_ikvi || (0 != xoff) )
+    {
+      pp->must_ikvi = false;
+      if (MHD_NO == pp->ikvi (pp->cls,
+                              MHD_POSTDATA_KIND,
+                              (const char *) &pp[1],      /* key */
+                              NULL,
+                              NULL,
+                              NULL,
+                              xbuf,
+                              pp->value_offset,
+                              xoff))
+      {
+        pp->state = PP_Error;
+        return;
+      }
+    }
+    pp->value_offset += xoff;
+    if (cut)
+      break;
+    if (0 != clen)
+    {
+      xbuf[delta] = '%';        /* undo 0-termination */
+      memmove (xbuf,
+               &xbuf[delta],
+               clen);
+    }
+    xoff = clen;
+  }
+}
+
+
+/**
  * Process url-encoded POST data.
  *
  * @param pp post processor context
@@ -338,150 +274,303 @@
  * @param post_data_len number of bytes in @a post_data
  * @return #MHD_YES on success, #MHD_NO if there was an error processing the data
  */
-static int
+static enum MHD_Result
 post_process_urlencoded (struct MHD_PostProcessor *pp,
                          const char *post_data,
-			 size_t post_data_len)
+                         size_t post_data_len)
 {
-  size_t equals;
-  size_t amper;
+  char *kbuf = (char *) &pp[1];
   size_t poff;
-  size_t xoff;
-  size_t delta;
-  int end_of_value_found;
-  char *buf;
-  char xbuf[XBUF_SIZE + 1];
+  const char *start_key = NULL;
+  const char *end_key = NULL;
+  const char *start_value = NULL;
+  const char *end_value = NULL;
+  const char *last_escape = NULL;
 
-  buf = (char *) &pp[1];
+  mhd_assert (PP_Callback != pp->state);
+
   poff = 0;
-  while (poff < post_data_len)
+  while ( ( (poff < post_data_len) ||
+            (pp->state == PP_Callback) ) &&
+          (pp->state != PP_Error) )
+  {
+    switch (pp->state)
     {
-      switch (pp->state)
+    case PP_Error:
+      /* clearly impossible as per while loop invariant */
+      abort ();
+      break; /* Unreachable */
+    case PP_Init:
+      /* initial phase */
+      mhd_assert (NULL == start_key);
+      mhd_assert (NULL == end_key);
+      mhd_assert (NULL == start_value);
+      mhd_assert (NULL == end_value);
+      switch (post_data[poff])
+      {
+      case '=':
+        /* Case: (no key)'=' */
+        /* Empty key with value */
+        pp->state = PP_Error;
+        continue;
+      case '&':
+        /* Case: (no key)'&' */
+        /* Empty key without value */
+        poff++;
+        continue;
+      case '\n':
+      case '\r':
+        /* Case: (no key)'\n' or (no key)'\r' */
+        pp->state = PP_Done;
+        poff++;
+        break;
+      default:
+        /* normal character, key start, advance! */
+        pp->state = PP_ProcessKey;
+        start_key = &post_data[poff];
+        pp->must_ikvi = true;
+        poff++;
+        continue;
+      }
+      break; /* end PP_Init */
+    case PP_ProcessKey:
+      /* key phase */
+      mhd_assert (NULL == start_value);
+      mhd_assert (NULL == end_value);
+      mhd_assert (NULL != start_key || 0 == poff);
+      mhd_assert (0 != poff || NULL == start_key);
+      mhd_assert (NULL == end_key);
+      switch (post_data[poff])
+      {
+      case '=':
+        /* Case: 'key=' */
+        if (0 != poff)
+          end_key = &post_data[poff];
+        poff++;
+        pp->state = PP_ProcessValue;
+        break;
+      case '&':
+        /* Case: 'key&' */
+        if (0 != poff)
+          end_key = &post_data[poff];
+        poff++;
+        pp->state = PP_Callback;
+        break;
+      case '\n':
+      case '\r':
+        /* Case: 'key\n' or 'key\r' */
+        if (0 != poff)
+          end_key = &post_data[poff];
+        /* No advance here, 'PP_Done' will be selected by next 'PP_Init' phase */
+        pp->state = PP_Callback;
+        break;
+      default:
+        /* normal character, advance! */
+        if (0 == poff)
+          start_key = post_data;
+        poff++;
+        break;
+      }
+      mhd_assert (NULL == end_key || NULL != start_key);
+      break; /* end PP_ProcessKey */
+    case PP_ProcessValue:
+      if (NULL == start_value)
+        start_value = &post_data[poff];
+      switch (post_data[poff])
+      {
+      case '=':
+        /* case 'key==' */
+        pp->state = PP_Error;
+        continue;
+      case '&':
+        /* case 'value&' */
+        end_value = &post_data[poff];
+        poff++;
+        if (pp->must_ikvi ||
+            (start_value != end_value) )
         {
-        case PP_Error:
-          return MHD_NO;
-        case PP_Done:
-          /* did not expect to receive more data */
-          pp->state = PP_Error;
-          return MHD_NO;
-        case PP_Init:
-          equals = 0;
-          while ((equals + poff < post_data_len) &&
-                 (post_data[equals + poff] != '='))
-            equals++;
-          if (equals + pp->buffer_pos > pp->buffer_size)
-            {
-              pp->state = PP_Error;     /* out of memory */
-              return MHD_NO;
-            }
-          memcpy (&buf[pp->buffer_pos], &post_data[poff], equals);
-          pp->buffer_pos += equals;
-          if (equals + poff == post_data_len)
-            return MHD_YES;     /* no '=' yet */
-          buf[pp->buffer_pos] = '\0';   /* 0-terminate key */
-          pp->buffer_pos = 0;   /* reset for next key */
-	  MHD_unescape_plus (buf);
-          MHD_http_unescape (buf);
-          poff += equals + 1;
-          pp->state = PP_ProcessValue;
-          pp->value_offset = 0;
-          break;
-        case PP_ProcessValue:
-          /* obtain rest of value from previous iteration */
-          memcpy (xbuf, pp->xbuf, pp->xbuf_pos);
-          xoff = pp->xbuf_pos;
-          pp->xbuf_pos = 0;
-
-          /* find last position in input buffer that is part of the value */
-          amper = 0;
-          while ((amper + poff < post_data_len) &&
-                 (amper < XBUF_SIZE) &&
-                 (post_data[amper + poff] != '&') &&
-                 (post_data[amper + poff] != '\n') &&
-                 (post_data[amper + poff] != '\r'))
-            amper++;
-          end_of_value_found = ((amper + poff < post_data_len) &&
-                                ((post_data[amper + poff] == '&') ||
-                                 (post_data[amper + poff] == '\n') ||
-                                 (post_data[amper + poff] == '\r')));
-          /* compute delta, the maximum number of bytes that we will be able to
-             process right now (either amper-limited of xbuf-size limited) */
-          delta = amper;
-          if (delta > XBUF_SIZE - xoff)
-            delta = XBUF_SIZE - xoff;
-
-          /* move input into processing buffer */
-          memcpy (&xbuf[xoff], &post_data[poff], delta);
-          xoff += delta;
-          poff += delta;
-
-          /* find if escape sequence is at the end of the processing buffer;
-             if so, exclude those from processing (reduce delta to point at
-             end of processed region) */
-          delta = xoff;
-          if ((delta > 0) && (xbuf[delta - 1] == '%'))
-            delta--;
-          else if ((delta > 1) && (xbuf[delta - 2] == '%'))
-            delta -= 2;
-
-          /* if we have an incomplete escape sequence, save it to
-             pp->xbuf for later */
-          if (delta < xoff)
-            {
-              memcpy (pp->xbuf, &xbuf[delta], xoff - delta);
-              pp->xbuf_pos = xoff - delta;
-              xoff = delta;
-            }
-
-          /* If we have nothing to do (delta == 0) and
-             not just because the value is empty (are
-             waiting for more data), go for next iteration */
-          if ((xoff == 0) && (poff == post_data_len))
-            continue;
-
-          /* unescape */
-          xbuf[xoff] = '\0';    /* 0-terminate in preparation */
-	  MHD_unescape_plus (xbuf);
-          xoff = MHD_http_unescape (xbuf);
-          /* finally: call application! */
-	  pp->must_ikvi = MHD_NO;
-          if (MHD_NO == pp->ikvi (pp->cls, MHD_POSTDATA_KIND, (const char *) &pp[1],    /* key */
-                                  NULL, NULL, NULL, xbuf, pp->value_offset,
-                                  xoff))
-            {
-              pp->state = PP_Error;
-              return MHD_NO;
-            }
-          pp->value_offset += xoff;
-
-          /* are we done with the value? */
-          if (end_of_value_found)
-            {
-              /* we found the end of the value! */
-              if ((post_data[poff] == '\n') || (post_data[poff] == '\r'))
-                {
-                  pp->state = PP_ExpectNewLine;
-                }
-              else if (post_data[poff] == '&')
-                {
-                  poff++;       /* skip '&' */
-                  pp->state = PP_Init;
-                }
-            }
-          break;
-        case PP_ExpectNewLine:
-          if ((post_data[poff] == '\n') || (post_data[poff] == '\r'))
-            {
-              poff++;
-              /* we are done, report error if we receive any more... */
-              pp->state = PP_Done;
-              return MHD_YES;
-            }
-          return MHD_NO;
-        default:
-          mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL);          /* should never happen! */
+          pp->state = PP_Callback;
         }
+        else
+        {
+          pp->buffer_pos = 0;
+          pp->value_offset = 0;
+          pp->state = PP_Init;
+          start_value = NULL;
+          end_value = NULL;
+        }
+        continue;
+      case '\n':
+      case '\r':
+        /* Case: 'value\n' or 'value\r' */
+        end_value = &post_data[poff];
+        if (pp->must_ikvi ||
+            (start_value != end_value) )
+          pp->state = PP_Callback; /* No poff advance here to set PP_Done in the next iteration */
+        else
+        {
+          poff++;
+          pp->state = PP_Done;
+        }
+        break;
+      case '%':
+        last_escape = &post_data[poff];
+        poff++;
+        break;
+      case '0':
+      case '1':
+      case '2':
+      case '3':
+      case '4':
+      case '5':
+      case '6':
+      case '7':
+      case '8':
+      case '9':
+        /* character, may be part of escaping */
+        poff++;
+        continue;
+      default:
+        /* normal character, no more escaping! */
+        last_escape = NULL;
+        poff++;
+        continue;
+      }
+      break; /* end PP_ProcessValue */
+    case PP_Done:
+      switch (post_data[poff])
+      {
+      case '\n':
+      case '\r':
+        poff++;
+        continue;
+      }
+      /* unexpected data at the end, fail! */
+      pp->state = PP_Error;
+      break;
+    case PP_Callback:
+      mhd_assert ((NULL != end_key) || (NULL == start_key));
+      if (1)
+      {
+        const size_t key_len = (size_t) (end_key - start_key);
+        mhd_assert (end_key >= start_key);
+        if (0 != key_len)
+        {
+          if ( (pp->buffer_pos + key_len >= pp->buffer_size) ||
+               (pp->buffer_pos + key_len < pp->buffer_pos) )
+          {
+            /* key too long, cannot parse! */
+            pp->state = PP_Error;
+            continue;
+          }
+          /* compute key, if we have not already */
+          memcpy (&kbuf[pp->buffer_pos],
+                  start_key,
+                  key_len);
+          pp->buffer_pos += key_len;
+          start_key = NULL;
+          end_key = NULL;
+          pp->must_unescape_key = true;
+        }
+      }
+#ifdef _DEBUG
+      else
+        mhd_assert (0 != pp->buffer_pos);
+#endif /* _DEBUG */
+      if (pp->must_unescape_key)
+      {
+        kbuf[pp->buffer_pos] = '\0'; /* 0-terminate key */
+        MHD_unescape_plus (kbuf);
+        MHD_http_unescape (kbuf);
+        pp->must_unescape_key = false;
+      }
+      process_value (pp,
+                     start_value,
+                     end_value,
+                     NULL);
+      if (PP_Error == pp->state)
+        continue;
+      pp->value_offset = 0;
+      start_value = NULL;
+      end_value = NULL;
+      pp->buffer_pos = 0;
+      pp->state = PP_Init;
+      break;
+    case PP_NextBoundary:
+    case PP_ProcessEntryHeaders:
+    case PP_PerformCheckMultipart:
+    case PP_ProcessValueToBoundary:
+    case PP_PerformCleanup:
+    case PP_Nested_Init:
+    case PP_Nested_PerformMarking:
+    case PP_Nested_ProcessEntryHeaders:
+    case PP_Nested_ProcessValueToBoundary:
+    case PP_Nested_PerformCleanup:
+    default:
+      MHD_PANIC (_ ("internal error.\n")); /* should never happen! */
     }
+    mhd_assert ((end_key == NULL) || (start_key != NULL));
+    mhd_assert ((end_value == NULL) || (start_value != NULL));
+  }
+
+  mhd_assert (PP_Callback != pp->state);
+
+  if (PP_Error == pp->state)
+  {
+    /* State in error, returning failure */
+    return MHD_NO;
+  }
+
+  /* save remaining data for next iteration */
+  if (NULL != start_key)
+  {
+    size_t key_len;
+    mhd_assert ((PP_ProcessKey == pp->state) || (NULL != end_key));
+    if (NULL == end_key)
+      end_key = &post_data[poff];
+    mhd_assert (end_key >= start_key);
+    key_len = (size_t) (end_key - start_key);
+    mhd_assert (0 != key_len); /* it must be always non-zero here */
+    if (pp->buffer_pos + key_len >= pp->buffer_size)
+    {
+      pp->state = PP_Error;
+      return MHD_NO;
+    }
+    memcpy (&kbuf[pp->buffer_pos],
+            start_key,
+            key_len);
+    pp->buffer_pos += key_len;
+    pp->must_unescape_key = true;
+    start_key = NULL;
+    end_key = NULL;
+  }
+  if ( (NULL != start_value) &&
+       (PP_ProcessValue == pp->state) )
+  {
+    /* compute key, if we have not already */
+    if (pp->must_unescape_key)
+    {
+      kbuf[pp->buffer_pos] = '\0'; /* 0-terminate key */
+      MHD_unescape_plus (kbuf);
+      MHD_http_unescape (kbuf);
+      pp->must_unescape_key = false;
+    }
+    if (NULL == end_value)
+      end_value = &post_data[poff];
+    if ( (NULL != last_escape) &&
+         (2 < (end_value - last_escape)) )
+      last_escape = NULL;
+    process_value (pp,
+                   start_value,
+                   end_value,
+                   last_escape);
+    pp->must_ikvi = false;
+  }
+  if (PP_Error == pp->state)
+  {
+    /* State in error, returning failure */
+    return MHD_NO;
+  }
   return MHD_YES;
 }
 
@@ -491,24 +580,30 @@
  * rest of the line into the suffix ptr.
  *
  * @param prefix prefix to match
+ * @param prefix_len length of @a prefix
  * @param line line to match prefix in
  * @param suffix set to a copy of the rest of the line, starting at the end of the match
  * @return #MHD_YES if there was a match, #MHD_NO if not
  */
 static int
-try_match_header (const char *prefix, char *line, char **suffix)
+try_match_header (const char *prefix,
+                  size_t prefix_len,
+                  char *line,
+                  char **suffix)
 {
   if (NULL != *suffix)
     return MHD_NO;
-  while (*line != 0)
+  while (0 != *line)
+  {
+    if (MHD_str_equal_caseless_n_ (prefix,
+                                   line,
+                                   prefix_len))
     {
-      if (MHD_str_equal_caseless_n_ (prefix, line, strlen (prefix)))
-        {
-          *suffix = strdup (&line[strlen (prefix)]);
-          return MHD_YES;
-        }
-      ++line;
+      *suffix = strdup (&line[prefix_len]);
+      return MHD_YES;
     }
+    ++line;
+  }
   return MHD_NO;
 }
 
@@ -531,39 +626,46 @@
                const char *boundary,
                size_t blen,
                size_t *ioffptr,
-               enum PP_State next_state, enum PP_State next_dash_state)
+               enum PP_State next_state,
+               enum PP_State next_dash_state)
 {
   char *buf = (char *) &pp[1];
   const char *dash;
 
   if (pp->buffer_pos < 2 + blen)
+  {
+    if (pp->buffer_pos == pp->buffer_size)
+      pp->state = PP_Error;     /* out of memory */
+    /* ++(*ioffptr); */
+    return MHD_NO;              /* not enough data */
+  }
+  if ( (0 != memcmp ("--",
+                     buf,
+                     2)) ||
+       (0 != memcmp (&buf[2],
+                     boundary,
+                     blen)))
+  {
+    if (pp->state != PP_Init)
     {
-      if (pp->buffer_pos == pp->buffer_size)
-        pp->state = PP_Error;   /* out of memory */
-      // ++(*ioffptr);
-      return MHD_NO;            /* not enough data */
+      /* garbage not allowed */
+      pp->state = PP_Error;
     }
-  if ((0 != memcmp ("--", buf, 2)) || (0 != memcmp (&buf[2], boundary, blen)))
+    else
     {
-      if (pp->state != PP_Init)
-        {
-          /* garbage not allowed */
-          pp->state = PP_Error;
-        }
+      /* skip over garbage (RFC 2046, 5.1.1) */
+      dash = memchr (buf,
+                     '-',
+                     pp->buffer_pos);
+      if (NULL == dash)
+        (*ioffptr) += pp->buffer_pos;         /* skip entire buffer */
+      else if (dash == buf)
+        (*ioffptr)++;                         /* at least skip one byte */
       else
-        {
-          /* skip over garbage (RFC 2046, 5.1.1) */
-          dash = memchr (buf, '-', pp->buffer_pos);
-          if (NULL == dash)
-            (*ioffptr) += pp->buffer_pos; /* skip entire buffer */
-          else
-            if (dash == buf)
-              (*ioffptr)++; /* at least skip one byte */
-            else
-              (*ioffptr) += dash - buf; /* skip to first possible boundary */
-        }
-      return MHD_NO;            /* expected boundary */
+        (*ioffptr) += (size_t) (dash - buf);  /* skip to first possible boundary */
     }
+    return MHD_NO;                            /* expected boundary */
+  }
   /* remove boundary from buffer */
   (*ioffptr) += 2 + blen;
   /* next: start with headers */
@@ -582,8 +684,8 @@
  */
 static void
 try_get_value (const char *buf,
-	       const char *key,
-	       char **destination)
+               const char *key,
+               char **destination)
 {
   const char *spos;
   const char *bpos;
@@ -596,25 +698,30 @@
   bpos = buf;
   klen = strlen (key);
   while (NULL != (spos = strstr (bpos, key)))
+  {
+    if ( (spos[klen] != '=') ||
+         ( (spos != buf) &&
+           (spos[-1] != ' ') ) )
     {
-      if ((spos[klen] != '=') || ((spos != buf) && (spos[-1] != ' ')))
-        {
-          /* no match */
-          bpos = spos + 1;
-          continue;
-        }
-      if (spos[klen + 1] != '"')
-        return;                 /* not quoted */
-      if (NULL == (endv = strchr (&spos[klen + 2], '\"')))
-        return;                 /* no end-quote */
-      vlen = endv - spos - klen - 1;
-      *destination = malloc (vlen);
-      if (NULL == *destination)
-        return;                 /* out of memory */
-      (*destination)[vlen - 1] = '\0';
-      memcpy (*destination, &spos[klen + 2], vlen - 1);
-      return;                   /* success */
+      /* no match */
+      bpos = spos + 1;
+      continue;
     }
+    if (spos[klen + 1] != '"')
+      return;                   /* not quoted */
+    if (NULL == (endv = strchr (&spos[klen + 2],
+                                '\"')))
+      return;                   /* no end-quote */
+    vlen = (size_t) (endv - spos) - klen - 1;
+    *destination = malloc (vlen);
+    if (NULL == *destination)
+      return;                   /* out of memory */
+    (*destination)[vlen - 1] = '\0';
+    memcpy (*destination,
+            &spos[klen + 2],
+            vlen - 1);
+    return;                     /* success */
+  }
 }
 
 
@@ -635,47 +742,57 @@
  */
 static int
 process_multipart_headers (struct MHD_PostProcessor *pp,
-                           size_t *ioffptr, enum PP_State next_state)
+                           size_t *ioffptr,
+                           enum PP_State next_state)
 {
   char *buf = (char *) &pp[1];
   size_t newline;
 
   newline = 0;
-  while ((newline < pp->buffer_pos) &&
-         (buf[newline] != '\r') && (buf[newline] != '\n'))
+  while ( (newline < pp->buffer_pos) &&
+          (buf[newline] != '\r') &&
+          (buf[newline] != '\n') )
     newline++;
   if (newline == pp->buffer_size)
-    {
-      pp->state = PP_Error;
-      return MHD_NO;            /* out of memory */
-    }
+  {
+    pp->state = PP_Error;
+    return MHD_NO;              /* out of memory */
+  }
   if (newline == pp->buffer_pos)
     return MHD_NO;              /* will need more data */
   if (0 == newline)
-    {
-      /* empty line - end of headers */
-      pp->skip_rn = RN_Full;
-      pp->state = next_state;
-      return MHD_YES;
-    }
+  {
+    /* empty line - end of headers */
+    pp->skip_rn = RN_Full;
+    pp->state = next_state;
+    return MHD_YES;
+  }
   /* got an actual header */
   if (buf[newline] == '\r')
     pp->skip_rn = RN_OptN;
   buf[newline] = '\0';
   if (MHD_str_equal_caseless_n_ ("Content-disposition: ",
-                        buf, strlen ("Content-disposition: ")))
-    {
-      try_get_value (&buf[strlen ("Content-disposition: ")],
-                     "name", &pp->content_name);
-      try_get_value (&buf[strlen ("Content-disposition: ")],
-                     "filename", &pp->content_filename);
-    }
+                                 buf,
+                                 MHD_STATICSTR_LEN_ ("Content-disposition: ")))
+  {
+    try_get_value (&buf[MHD_STATICSTR_LEN_ ("Content-disposition: ")],
+                   "name",
+                   &pp->content_name);
+    try_get_value (&buf[MHD_STATICSTR_LEN_ ("Content-disposition: ")],
+                   "filename",
+                   &pp->content_filename);
+  }
   else
-    {
-      try_match_header ("Content-type: ", buf, &pp->content_type);
-      try_match_header ("Content-Transfer-Encoding: ",
-                        buf, &pp->content_transfer_encoding);
-    }
+  {
+    try_match_header ("Content-type: ",
+                      MHD_STATICSTR_LEN_ ("Content-type: "),
+                      buf,
+                      &pp->content_type);
+    try_match_header ("Content-Transfer-Encoding: ",
+                      MHD_STATICSTR_LEN_ ("Content-Transfer-Encoding: "),
+                      buf,
+                      &pp->content_transfer_encoding);
+  }
   (*ioffptr) += newline + 1;
   return MHD_YES;
 }
@@ -713,71 +830,80 @@
      (\r\n--+boundary) is part of the value */
   newline = 0;
   while (1)
+  {
+    while (newline + 4 < pp->buffer_pos)
     {
-      while (newline + 4 < pp->buffer_pos)
-        {
-          r = memchr (&buf[newline], '\r', pp->buffer_pos - newline - 4);
-          if (NULL == r)
-          {
-            newline = pp->buffer_pos - 4;
-            break;
-          }
-          newline = r - buf;
-          if (0 == memcmp ("\r\n--", &buf[newline], 4))
-            break;
-          newline++;
-        }
-      if (newline + pp->blen + 4 <= pp->buffer_pos)
-        {
-          /* can check boundary */
-          if (0 != memcmp (&buf[newline + 4], boundary, pp->blen))
-            {
-              /* no boundary, "\r\n--" is part of content, skip */
-              newline += 4;
-              continue;
-            }
-          else
-            {
-              /* boundary found, process until newline then
-                 skip boundary and go back to init */
-              pp->skip_rn = RN_Dash;
-              pp->state = next_state;
-              pp->dash_state = next_dash_state;
-              (*ioffptr) += pp->blen + 4;       /* skip boundary as well */
-              buf[newline] = '\0';
-              break;
-            }
-        }
-      else
-        {
-          /* cannot check for boundary, process content that
-             we have and check again later; except, if we have
-             no content, abort (out of memory) */
-          if ((0 == newline) && (pp->buffer_pos == pp->buffer_size))
-            {
-              pp->state = PP_Error;
-              return MHD_NO;
-            }
-          break;
-        }
+      r = memchr (&buf[newline],
+                  '\r',
+                  pp->buffer_pos - newline - 4);
+      if (NULL == r)
+      {
+        newline = pp->buffer_pos - 4;
+        break;
+      }
+      newline = (size_t) (r - buf);
+      if (0 == memcmp ("\r\n--",
+                       &buf[newline],
+                       4))
+        break;
+      newline++;
     }
+    if (newline + blen + 4 <= pp->buffer_pos)
+    {
+      /* can check boundary */
+      if (0 != memcmp (&buf[newline + 4],
+                       boundary,
+                       blen))
+      {
+        /* no boundary, "\r\n--" is part of content, skip */
+        newline += 4;
+        continue;
+      }
+      else
+      {
+        /* boundary found, process until newline then
+           skip boundary and go back to init */
+        pp->skip_rn = RN_Dash;
+        pp->state = next_state;
+        pp->dash_state = next_dash_state;
+        (*ioffptr) += blen + 4;             /* skip boundary as well */
+        buf[newline] = '\0';
+        break;
+      }
+    }
+    else
+    {
+      /* cannot check for boundary, process content that
+         we have and check again later; except, if we have
+         no content, abort (out of memory) */
+      if ( (0 == newline) &&
+           (pp->buffer_pos == pp->buffer_size) )
+      {
+        pp->state = PP_Error;
+        return MHD_NO;
+      }
+      break;
+    }
+  }
   /* newline is either at beginning of boundary or
      at least at the last character that we are sure
      is not part of the boundary */
-  if ( ( (MHD_YES == pp->must_ikvi) ||
-	 (0 != newline) ) &&
+  if ( ( (pp->must_ikvi) ||
+         (0 != newline) ) &&
        (MHD_NO == pp->ikvi (pp->cls,
-			    MHD_POSTDATA_KIND,
-			    pp->content_name,
-			    pp->content_filename,
-			    pp->content_type,
-			    pp->content_transfer_encoding,
-			    buf, pp->value_offset, newline)) )
-    {
-      pp->state = PP_Error;
-      return MHD_NO;
-    }
-  pp->must_ikvi = MHD_NO;
+                            MHD_POSTDATA_KIND,
+                            pp->content_name,
+                            pp->content_filename,
+                            pp->content_type,
+                            pp->content_transfer_encoding,
+                            buf,
+                            pp->value_offset,
+                            newline)) )
+  {
+    pp->state = PP_Error;
+    return MHD_NO;
+  }
+  pp->must_ikvi = false;
   pp->value_offset += newline;
   (*ioffptr) += newline;
   return MHD_YES;
@@ -791,28 +917,30 @@
 static void
 free_unmarked (struct MHD_PostProcessor *pp)
 {
-  if ((NULL != pp->content_name) && (0 == (pp->have & NE_content_name)))
-    {
-      free (pp->content_name);
-      pp->content_name = NULL;
-    }
-  if ((NULL != pp->content_type) && (0 == (pp->have & NE_content_type)))
-    {
-      free (pp->content_type);
-      pp->content_type = NULL;
-    }
-  if ((NULL != pp->content_filename) &&
-      (0 == (pp->have & NE_content_filename)))
-    {
-      free (pp->content_filename);
-      pp->content_filename = NULL;
-    }
-  if ((NULL != pp->content_transfer_encoding) &&
-      (0 == (pp->have & NE_content_transfer_encoding)))
-    {
-      free (pp->content_transfer_encoding);
-      pp->content_transfer_encoding = NULL;
-    }
+  if ( (NULL != pp->content_name) &&
+       (0 == (pp->have & NE_content_name)) )
+  {
+    free (pp->content_name);
+    pp->content_name = NULL;
+  }
+  if ( (NULL != pp->content_type) &&
+       (0 == (pp->have & NE_content_type)) )
+  {
+    free (pp->content_type);
+    pp->content_type = NULL;
+  }
+  if ( (NULL != pp->content_filename) &&
+       (0 == (pp->have & NE_content_filename)) )
+  {
+    free (pp->content_filename);
+    pp->content_filename = NULL;
+  }
+  if ( (NULL != pp->content_transfer_encoding) &&
+       (0 == (pp->have & NE_content_transfer_encoding)) )
+  {
+    free (pp->content_transfer_encoding);
+    pp->content_transfer_encoding = NULL;
+  }
 }
 
 
@@ -824,10 +952,10 @@
  * @param post_data_len number of bytes in @a post_data
  * @return #MHD_NO on error,
  */
-static int
+static enum MHD_Result
 post_process_multipart (struct MHD_PostProcessor *pp,
                         const char *post_data,
-			size_t post_data_len)
+                        size_t post_data_len)
 {
   char *buf;
   size_t max;
@@ -839,328 +967,333 @@
   ioff = 0;
   poff = 0;
   state_changed = 1;
-  while ((poff < post_data_len) ||
-         ((pp->buffer_pos > 0) && (state_changed != 0)))
-    {
-      /* first, move as much input data
-         as possible to our internal buffer */
-      max = pp->buffer_size - pp->buffer_pos;
-      if (max > post_data_len - poff)
-        max = post_data_len - poff;
-      memcpy (&buf[pp->buffer_pos], &post_data[poff], max);
-      poff += max;
-      pp->buffer_pos += max;
-      if ((max == 0) && (state_changed == 0) && (poff < post_data_len))
-        {
-          pp->state = PP_Error;
-          return MHD_NO;        /* out of memory */
-        }
-      state_changed = 0;
-
-      /* first state machine for '\r'-'\n' and '--' handling */
-      switch (pp->skip_rn)
-        {
-        case RN_Inactive:
-          break;
-        case RN_OptN:
-          if (buf[0] == '\n')
-            {
-              ioff++;
-              pp->skip_rn = RN_Inactive;
-              goto AGAIN;
-            }
-          /* fall-through! */
-        case RN_Dash:
-          if (buf[0] == '-')
-            {
-              ioff++;
-              pp->skip_rn = RN_Dash2;
-              goto AGAIN;
-            }
-          pp->skip_rn = RN_Full;
-          /* fall-through! */
-        case RN_Full:
-          if (buf[0] == '\r')
-            {
-              if ((pp->buffer_pos > 1) && (buf[1] == '\n'))
-                {
-                  pp->skip_rn = RN_Inactive;
-                  ioff += 2;
-                }
-              else
-                {
-                  pp->skip_rn = RN_OptN;
-                  ioff++;
-                }
-              goto AGAIN;
-            }
-          if (buf[0] == '\n')
-            {
-              ioff++;
-              pp->skip_rn = RN_Inactive;
-              goto AGAIN;
-            }
-          pp->skip_rn = RN_Inactive;
-          pp->state = PP_Error;
-          return MHD_NO;        /* no '\r\n' */
-        case RN_Dash2:
-          if (buf[0] == '-')
-            {
-              ioff++;
-              pp->skip_rn = RN_Full;
-              pp->state = pp->dash_state;
-              goto AGAIN;
-            }
-          pp->state = PP_Error;
-          break;
-        }
-
-      /* main state engine */
-      switch (pp->state)
-        {
-        case PP_Error:
-          return MHD_NO;
-        case PP_Done:
-          /* did not expect to receive more data */
-          pp->state = PP_Error;
-          return MHD_NO;
-        case PP_Init:
-          /**
-           * Per RFC2046 5.1.1 NOTE TO IMPLEMENTORS, consume anything
-           * prior to the first multipart boundary:
-           *
-           * > There appears to be room for additional information prior
-           * > to the first boundary delimiter line and following the
-           * > final boundary delimiter line.  These areas should
-           * > generally be left blank, and implementations must ignore
-           * > anything that appears before the first boundary delimiter
-           * > line or after the last one.
-           */
-          (void) find_boundary (pp,
-				pp->boundary,
-				pp->blen,
-				&ioff,
-				PP_ProcessEntryHeaders, PP_Done);
-          break;
-        case PP_NextBoundary:
-          if (MHD_NO == find_boundary (pp,
-                                       pp->boundary,
-                                       pp->blen,
-                                       &ioff,
-                                       PP_ProcessEntryHeaders, PP_Done))
-            {
-              if (pp->state == PP_Error)
-                return MHD_NO;
-              goto END;
-            }
-          break;
-        case PP_ProcessEntryHeaders:
-	  pp->must_ikvi = MHD_YES;
-          if (MHD_NO ==
-              process_multipart_headers (pp, &ioff, PP_PerformCheckMultipart))
-            {
-              if (pp->state == PP_Error)
-                return MHD_NO;
-              else
-                goto END;
-            }
-          state_changed = 1;
-          break;
-        case PP_PerformCheckMultipart:
-          if ((pp->content_type != NULL) &&
-              (MHD_str_equal_caseless_n_ (pp->content_type,
-                                 "multipart/mixed",
-                                 strlen ("multipart/mixed"))))
-            {
-              pp->nested_boundary = strstr (pp->content_type, "boundary=");
-              if (pp->nested_boundary == NULL)
-                {
-                  pp->state = PP_Error;
-                  return MHD_NO;
-                }
-              pp->nested_boundary =
-                strdup (&pp->nested_boundary[strlen ("boundary=")]);
-              if (pp->nested_boundary == NULL)
-                {
-                  /* out of memory */
-                  pp->state = PP_Error;
-                  return MHD_NO;
-                }
-              /* free old content type, we will need that field
-                 for the content type of the nested elements */
-              free (pp->content_type);
-              pp->content_type = NULL;
-              pp->nlen = strlen (pp->nested_boundary);
-              pp->state = PP_Nested_Init;
-              state_changed = 1;
-              break;
-            }
-          pp->state = PP_ProcessValueToBoundary;
-          pp->value_offset = 0;
-          state_changed = 1;
-          break;
-        case PP_ProcessValueToBoundary:
-          if (MHD_NO == process_value_to_boundary (pp,
-                                                   &ioff,
-                                                   pp->boundary,
-                                                   pp->blen,
-                                                   PP_PerformCleanup,
-                                                   PP_Done))
-            {
-              if (pp->state == PP_Error)
-                return MHD_NO;
-              break;
-            }
-          break;
-        case PP_PerformCleanup:
-          /* clean up state of one multipart form-data element! */
-          pp->have = NE_none;
-          free_unmarked (pp);
-          if (pp->nested_boundary != NULL)
-            {
-              free (pp->nested_boundary);
-              pp->nested_boundary = NULL;
-            }
-          pp->state = PP_ProcessEntryHeaders;
-          state_changed = 1;
-          break;
-        case PP_Nested_Init:
-          if (pp->nested_boundary == NULL)
-            {
-              pp->state = PP_Error;
-              return MHD_NO;
-            }
-          if (MHD_NO == find_boundary (pp,
-                                       pp->nested_boundary,
-                                       pp->nlen,
-                                       &ioff,
-                                       PP_Nested_PerformMarking,
-                                       PP_NextBoundary /* or PP_Error? */ ))
-            {
-              if (pp->state == PP_Error)
-                return MHD_NO;
-              goto END;
-            }
-          break;
-        case PP_Nested_PerformMarking:
-          /* remember what headers were given
-             globally */
-          pp->have = NE_none;
-          if (pp->content_name != NULL)
-            pp->have |= NE_content_name;
-          if (pp->content_type != NULL)
-            pp->have |= NE_content_type;
-          if (pp->content_filename != NULL)
-            pp->have |= NE_content_filename;
-          if (pp->content_transfer_encoding != NULL)
-            pp->have |= NE_content_transfer_encoding;
-          pp->state = PP_Nested_ProcessEntryHeaders;
-          state_changed = 1;
-          break;
-        case PP_Nested_ProcessEntryHeaders:
-          pp->value_offset = 0;
-          if (MHD_NO ==
-              process_multipart_headers (pp, &ioff,
-                                         PP_Nested_ProcessValueToBoundary))
-            {
-              if (pp->state == PP_Error)
-                return MHD_NO;
-              else
-                goto END;
-            }
-          state_changed = 1;
-          break;
-        case PP_Nested_ProcessValueToBoundary:
-          if (MHD_NO == process_value_to_boundary (pp,
-                                                   &ioff,
-                                                   pp->nested_boundary,
-                                                   pp->nlen,
-                                                   PP_Nested_PerformCleanup,
-                                                   PP_NextBoundary))
-            {
-              if (pp->state == PP_Error)
-                return MHD_NO;
-              break;
-            }
-          break;
-        case PP_Nested_PerformCleanup:
-          free_unmarked (pp);
-          pp->state = PP_Nested_ProcessEntryHeaders;
-          state_changed = 1;
-          break;
-        default:
-          mhd_panic (mhd_panic_cls, __FILE__, __LINE__, NULL);          /* should never happen! */
-        }
-    AGAIN:
-      if (ioff > 0)
-        {
-          memmove (buf, &buf[ioff], pp->buffer_pos - ioff);
-          pp->buffer_pos -= ioff;
-          ioff = 0;
-          state_changed = 1;
-        }
-    }
-END:
-  if (ioff != 0)
-    {
-      memmove (buf, &buf[ioff], pp->buffer_pos - ioff);
-      pp->buffer_pos -= ioff;
-    }
-  if (poff < post_data_len)
+  while ( (poff < post_data_len) ||
+          ( (pp->buffer_pos > 0) &&
+            (0 != state_changed) ) )
+  {
+    /* first, move as much input data
+       as possible to our internal buffer */
+    max = pp->buffer_size - pp->buffer_pos;
+    if (max > post_data_len - poff)
+      max = post_data_len - poff;
+    memcpy (&buf[pp->buffer_pos],
+            &post_data[poff],
+            max);
+    poff += max;
+    pp->buffer_pos += max;
+    if ( (0 == max) &&
+         (0 == state_changed) &&
+         (poff < post_data_len) )
     {
       pp->state = PP_Error;
-      return MHD_NO;            /* serious error */
+      return MHD_NO;            /* out of memory */
     }
+    state_changed = 0;
+
+    /* first state machine for '\r'-'\n' and '--' handling */
+    switch (pp->skip_rn)
+    {
+    case RN_Inactive:
+      break;
+    case RN_OptN:
+      if (buf[0] == '\n')
+      {
+        ioff++;
+        pp->skip_rn = RN_Inactive;
+        goto AGAIN;
+      }
+    /* fall-through! */
+    case RN_Dash:
+      if (buf[0] == '-')
+      {
+        ioff++;
+        pp->skip_rn = RN_Dash2;
+        goto AGAIN;
+      }
+      pp->skip_rn = RN_Full;
+    /* fall-through! */
+    case RN_Full:
+      if (buf[0] == '\r')
+      {
+        if ( (pp->buffer_pos > 1) &&
+             ('\n' == buf[1]) )
+        {
+          pp->skip_rn = RN_Inactive;
+          ioff += 2;
+        }
+        else
+        {
+          pp->skip_rn = RN_OptN;
+          ioff++;
+        }
+        goto AGAIN;
+      }
+      if (buf[0] == '\n')
+      {
+        ioff++;
+        pp->skip_rn = RN_Inactive;
+        goto AGAIN;
+      }
+      pp->skip_rn = RN_Inactive;
+      pp->state = PP_Error;
+      return MHD_NO;            /* no '\r\n' */
+    case RN_Dash2:
+      if (buf[0] == '-')
+      {
+        ioff++;
+        pp->skip_rn = RN_Full;
+        pp->state = pp->dash_state;
+        goto AGAIN;
+      }
+      pp->state = PP_Error;
+      break;
+    }
+
+    /* main state engine */
+    switch (pp->state)
+    {
+    case PP_Error:
+      return MHD_NO;
+    case PP_Done:
+      /* did not expect to receive more data */
+      pp->state = PP_Error;
+      return MHD_NO;
+    case PP_Init:
+      /**
+       * Per RFC2046 5.1.1 NOTE TO IMPLEMENTORS, consume anything
+       * prior to the first multipart boundary:
+       *
+       * > There appears to be room for additional information prior
+       * > to the first boundary delimiter line and following the
+       * > final boundary delimiter line.  These areas should
+       * > generally be left blank, and implementations must ignore
+       * > anything that appears before the first boundary delimiter
+       * > line or after the last one.
+       */
+      (void) find_boundary (pp,
+                            pp->boundary,
+                            pp->blen,
+                            &ioff,
+                            PP_ProcessEntryHeaders,
+                            PP_Done);
+      break;
+    case PP_NextBoundary:
+      if (MHD_NO == find_boundary (pp,
+                                   pp->boundary,
+                                   pp->blen,
+                                   &ioff,
+                                   PP_ProcessEntryHeaders,
+                                   PP_Done))
+      {
+        if (pp->state == PP_Error)
+          return MHD_NO;
+        goto END;
+      }
+      break;
+    case PP_ProcessEntryHeaders:
+      pp->must_ikvi = true;
+      if (MHD_NO ==
+          process_multipart_headers (pp,
+                                     &ioff,
+                                     PP_PerformCheckMultipart))
+      {
+        if (pp->state == PP_Error)
+          return MHD_NO;
+        else
+          goto END;
+      }
+      state_changed = 1;
+      break;
+    case PP_PerformCheckMultipart:
+      if ( (NULL != pp->content_type) &&
+           (MHD_str_equal_caseless_n_ (pp->content_type,
+                                       "multipart/mixed",
+                                       MHD_STATICSTR_LEN_ ("multipart/mixed"))))
+      {
+        pp->nested_boundary = strstr (pp->content_type,
+                                      "boundary=");
+        if (NULL == pp->nested_boundary)
+        {
+          pp->state = PP_Error;
+          return MHD_NO;
+        }
+        pp->nested_boundary =
+          strdup (&pp->nested_boundary[MHD_STATICSTR_LEN_ ("boundary=")]);
+        if (NULL == pp->nested_boundary)
+        {
+          /* out of memory */
+          pp->state = PP_Error;
+          return MHD_NO;
+        }
+        /* free old content type, we will need that field
+           for the content type of the nested elements */
+        free (pp->content_type);
+        pp->content_type = NULL;
+        pp->nlen = strlen (pp->nested_boundary);
+        pp->state = PP_Nested_Init;
+        state_changed = 1;
+        break;
+      }
+      pp->state = PP_ProcessValueToBoundary;
+      pp->value_offset = 0;
+      state_changed = 1;
+      break;
+    case PP_ProcessValueToBoundary:
+      if (MHD_NO == process_value_to_boundary (pp,
+                                               &ioff,
+                                               pp->boundary,
+                                               pp->blen,
+                                               PP_PerformCleanup,
+                                               PP_Done))
+      {
+        if (pp->state == PP_Error)
+          return MHD_NO;
+        break;
+      }
+      break;
+    case PP_PerformCleanup:
+      /* clean up state of one multipart form-data element! */
+      pp->have = NE_none;
+      free_unmarked (pp);
+      if (NULL != pp->nested_boundary)
+      {
+        free (pp->nested_boundary);
+        pp->nested_boundary = NULL;
+      }
+      pp->state = PP_ProcessEntryHeaders;
+      state_changed = 1;
+      break;
+    case PP_Nested_Init:
+      if (NULL == pp->nested_boundary)
+      {
+        pp->state = PP_Error;
+        return MHD_NO;
+      }
+      if (MHD_NO == find_boundary (pp,
+                                   pp->nested_boundary,
+                                   pp->nlen,
+                                   &ioff,
+                                   PP_Nested_PerformMarking,
+                                   PP_NextBoundary /* or PP_Error? */))
+      {
+        if (pp->state == PP_Error)
+          return MHD_NO;
+        goto END;
+      }
+      break;
+    case PP_Nested_PerformMarking:
+      /* remember what headers were given
+         globally */
+      pp->have = NE_none;
+      if (NULL != pp->content_name)
+        pp->have |= NE_content_name;
+      if (NULL != pp->content_type)
+        pp->have |= NE_content_type;
+      if (NULL != pp->content_filename)
+        pp->have |= NE_content_filename;
+      if (NULL != pp->content_transfer_encoding)
+        pp->have |= NE_content_transfer_encoding;
+      pp->state = PP_Nested_ProcessEntryHeaders;
+      state_changed = 1;
+      break;
+    case PP_Nested_ProcessEntryHeaders:
+      pp->value_offset = 0;
+      if (MHD_NO ==
+          process_multipart_headers (pp,
+                                     &ioff,
+                                     PP_Nested_ProcessValueToBoundary))
+      {
+        if (pp->state == PP_Error)
+          return MHD_NO;
+        else
+          goto END;
+      }
+      state_changed = 1;
+      break;
+    case PP_Nested_ProcessValueToBoundary:
+      if (MHD_NO == process_value_to_boundary (pp,
+                                               &ioff,
+                                               pp->nested_boundary,
+                                               pp->nlen,
+                                               PP_Nested_PerformCleanup,
+                                               PP_NextBoundary))
+      {
+        if (pp->state == PP_Error)
+          return MHD_NO;
+        break;
+      }
+      break;
+    case PP_Nested_PerformCleanup:
+      free_unmarked (pp);
+      pp->state = PP_Nested_ProcessEntryHeaders;
+      state_changed = 1;
+      break;
+    case PP_ProcessKey:
+    case PP_ProcessValue:
+    case PP_Callback:
+    default:
+      MHD_PANIC (_ ("internal error.\n")); /* should never happen! */
+    }
+AGAIN:
+    if (ioff > 0)
+    {
+      memmove (buf,
+               &buf[ioff],
+               pp->buffer_pos - ioff);
+      pp->buffer_pos -= ioff;
+      ioff = 0;
+      state_changed = 1;
+    }
+  }
+END:
+  if (0 != ioff)
+  {
+    memmove (buf,
+             &buf[ioff],
+             pp->buffer_pos - ioff);
+    pp->buffer_pos -= ioff;
+  }
+  if (poff < post_data_len)
+  {
+    pp->state = PP_Error;
+    return MHD_NO;              /* serious error */
+  }
   return MHD_YES;
 }
 
 
-/**
- * Parse and process POST data.  Call this function when POST data is
- * available (usually during an #MHD_AccessHandlerCallback) with the
- * "upload_data" and "upload_data_size".  Whenever possible, this will
- * then cause calls to the #MHD_PostDataIterator.
- *
- * @param pp the post processor
- * @param post_data @a post_data_len bytes of POST data
- * @param post_data_len length of @a post_data
- * @return #MHD_YES on success, #MHD_NO on error
- *         (out-of-memory, iterator aborted, parse error)
- * @ingroup request
- */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_post_process (struct MHD_PostProcessor *pp,
-                  const char *post_data, size_t post_data_len)
+                  const char *post_data,
+                  size_t post_data_len)
 {
   if (0 == post_data_len)
     return MHD_YES;
   if (NULL == pp)
     return MHD_NO;
-  if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED, pp->encoding,
-                         strlen(MHD_HTTP_POST_ENCODING_FORM_URLENCODED)))
-    return post_process_urlencoded (pp, post_data, post_data_len);
-  if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, pp->encoding,
-                   strlen (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)))
-    return post_process_multipart (pp, post_data, post_data_len);
+  if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED,
+                                 pp->encoding,
+                                 MHD_STATICSTR_LEN_ (
+                                   MHD_HTTP_POST_ENCODING_FORM_URLENCODED)))
+    return post_process_urlencoded (pp,
+                                    post_data,
+                                    post_data_len);
+  if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA,
+                                 pp->encoding,
+                                 MHD_STATICSTR_LEN_ (
+                                   MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)))
+    return post_process_multipart (pp,
+                                   post_data,
+                                   post_data_len);
   /* this should never be reached */
   return MHD_NO;
 }
 
 
-/**
- * Release PostProcessor resources.
- *
- * @param pp post processor context to destroy
- * @return #MHD_YES if processing completed nicely,
- *         #MHD_NO if there were spurious characters / formatting
- *                problems; it is common to ignore the return
- *                value of this function
- * @ingroup request
- */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_destroy_post_processor (struct MHD_PostProcessor *pp)
 {
-  int ret;
+  enum MHD_Result ret;
 
   if (NULL == pp)
     return MHD_YES;
@@ -1169,23 +1302,26 @@
     /* key without terminated value left at the end of the
        buffer; fake receiving a termination character to
        ensure it is also processed */
-    post_process_urlencoded (pp, "\n", 1);
+    post_process_urlencoded (pp,
+                             "\n",
+                             1);
   }
   /* These internal strings need cleaning up since
      the post-processing may have been interrupted
      at any stage */
-  if ((pp->xbuf_pos > 0) ||
-      ( (pp->state != PP_Done) &&
-	(pp->state != PP_ExpectNewLine)))
+  if ( (pp->xbuf_pos > 0) ||
+       ( (pp->state != PP_Done) &&
+         (pp->state != PP_Init) ) )
     ret = MHD_NO;
   else
     ret = MHD_YES;
   pp->have = NE_none;
   free_unmarked (pp);
-  if (pp->nested_boundary != NULL)
+  if (NULL != pp->nested_boundary)
     free (pp->nested_boundary);
   free (pp);
   return ret;
 }
 
+
 /* end of postprocessor.c */
diff --git a/src/microhttpd/postprocessor.h b/src/microhttpd/postprocessor.h
new file mode 100644
index 0000000..c3b19ef
--- /dev/null
+++ b/src/microhttpd/postprocessor.h
@@ -0,0 +1,246 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007-2022 Daniel Pittman, Christian Grothoff, and Evgeny Grin
+
+     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 2.1 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, write to the Free Software
+     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file postprocessor.h
+ * @brief  Declarations for parsing POST data
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_POSTPROCESSOR_H
+#define MHD_POSTPROCESSOR_H 1
+#include "internal.h"
+
+/**
+ * States in the PP parser's state machine.
+ */
+enum PP_State
+{
+  /* general states */
+  PP_Error,
+  PP_Done,
+  PP_Init,
+  PP_NextBoundary,
+
+  /* url encoding-states */
+  PP_ProcessKey,
+  PP_ProcessValue,
+  PP_Callback,
+
+  /* post encoding-states  */
+  PP_ProcessEntryHeaders,
+  PP_PerformCheckMultipart,
+  PP_ProcessValueToBoundary,
+  PP_PerformCleanup,
+
+  /* nested post-encoding states */
+  PP_Nested_Init,
+  PP_Nested_PerformMarking,
+  PP_Nested_ProcessEntryHeaders,
+  PP_Nested_ProcessValueToBoundary,
+  PP_Nested_PerformCleanup
+
+};
+
+
+enum RN_State
+{
+  /**
+   * No RN-preprocessing in this state.
+   */
+  RN_Inactive = 0,
+
+  /**
+   * If the next character is CR, skip it.  Otherwise,
+   * just go inactive.
+   */
+  RN_OptN = 1,
+
+  /**
+   * Expect CRLF (and only CRLF).  As always, we also
+   * expect only LF or only CR.
+   */
+  RN_Full = 2,
+
+  /**
+   * Expect either CRLF or '--'CRLF.  If '--'CRLF, transition into dash-state
+   * for the main state machine
+   */
+  RN_Dash = 3,
+
+  /**
+   * Got a single dash, expect second dash.
+   */
+  RN_Dash2 = 4
+};
+
+
+/**
+ * Bits for the globally known fields that
+ * should not be deleted when we exit the
+ * nested state.
+ */
+enum NE_State
+{
+  NE_none = 0,
+  NE_content_name = 1,
+  NE_content_type = 2,
+  NE_content_filename = 4,
+  NE_content_transfer_encoding = 8
+};
+
+
+/**
+ * Internal state of the post-processor.  Note that the fields
+ * are sorted by type to enable optimal packing by the compiler.
+ */
+struct MHD_PostProcessor
+{
+
+  /**
+   * The connection for which we are doing
+   * POST processing.
+   */
+  struct MHD_Connection *connection;
+
+  /**
+   * Function to call with POST data.
+   */
+  MHD_PostDataIterator ikvi;
+
+  /**
+   * Extra argument to ikvi.
+   */
+  void *cls;
+
+  /**
+   * Encoding as given by the headers of the connection.
+   */
+  const char *encoding;
+
+  /**
+   * Primary boundary (points into encoding string)
+   */
+  const char *boundary;
+
+  /**
+   * Nested boundary (if we have multipart/mixed encoding).
+   */
+  char *nested_boundary;
+
+  /**
+   * Pointer to the name given in disposition.
+   */
+  char *content_name;
+
+  /**
+   * Pointer to the (current) content type.
+   */
+  char *content_type;
+
+  /**
+   * Pointer to the (current) filename.
+   */
+  char *content_filename;
+
+  /**
+   * Pointer to the (current) encoding.
+   */
+  char *content_transfer_encoding;
+
+  /**
+   * Value data left over from previous iteration.
+   */
+  char xbuf[2];
+
+  /**
+   * Size of our buffer for the key.
+   */
+  size_t buffer_size;
+
+  /**
+   * Current position in the key buffer.
+   */
+  size_t buffer_pos;
+
+  /**
+   * Current position in @e xbuf.
+   */
+  size_t xbuf_pos;
+
+  /**
+   * Current offset in the value being processed.
+   */
+  uint64_t value_offset;
+
+  /**
+   * strlen(boundary) -- if boundary != NULL.
+   */
+  size_t blen;
+
+  /**
+   * strlen(nested_boundary) -- if nested_boundary != NULL.
+   */
+  size_t nlen;
+
+  /**
+   * Do we have to call the 'ikvi' callback when processing the
+   * multipart post body even if the size of the payload is zero?
+   * Set to #MHD_YES whenever we parse a new multiparty entry header,
+   * and to #MHD_NO the first time we call the 'ikvi' callback.
+   * Used to ensure that we do always call 'ikvi' even if the
+   * payload is empty (but not more than once).
+   */
+  bool must_ikvi;
+
+  /**
+   * Set if we still need to run the unescape logic
+   * on the key allocated at the end of this struct.
+   */
+  bool must_unescape_key;
+
+  /**
+   * State of the parser.
+   */
+  enum PP_State state;
+
+  /**
+   * Side-state-machine: skip CRLF (or just LF).
+   * Set to 0 if we are not in skip mode.  Set to 2
+   * if a CRLF is expected, set to 1 if a CR should
+   * be skipped if it is the next character.
+   */
+  enum RN_State skip_rn;
+
+  /**
+   * If we are in skip_rn with "dash" mode and
+   * do find 2 dashes, what state do we go into?
+   */
+  enum PP_State dash_state;
+
+  /**
+   * Which headers are global? (used to tell which
+   * headers were only valid for the nested multipart).
+   */
+  enum NE_State have;
+
+};
+
+#endif /* ! MHD_POSTPROCESSOR_H */
diff --git a/src/microhttpd/reason_phrase.c b/src/microhttpd/reason_phrase.c
index 3afe8af..ec5d6fc 100644
--- a/src/microhttpd/reason_phrase.c
+++ b/src/microhttpd/reason_phrase.c
@@ -1,6 +1,6 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007, 2011 Christian Grothoff
+     Copyright (C) 2007, 2011, 2017, 2019 Christian Grothoff, Karlson2k (Evgeny Grin)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -17,127 +17,152 @@
      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 
 */
-
 /**
  * @file reason_phrase.c
  * @brief  Tables of the string response phrases
  * @author Elliot Glaysher
  * @author Christian Grothoff (minor code clean up)
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "platform.h"
-#include "reason_phrase.h"
+#include "microhttpd.h"
+#include "mhd_str.h"
 
 #ifndef NULL
-#define NULL (void*)0
+#define NULL ((void*) 0)
 #endif
 
-static const char *invalid_hundred[] = { NULL };
-
-static const char *const one_hundred[] = {
-  "Continue",
-  "Switching Protocols",
-  "Processing"
+static const struct _MHD_cstr_w_len invalid_hundred[] = {
+  { NULL, 0 }
 };
 
-static const char *const two_hundred[] = {
-  "OK",
-  "Created",
-  "Accepted",
-  "Non-Authoritative Information",
-  "No Content",
-  "Reset Content",
-  "Partial Content",
-  "Multi Status"
+static const struct _MHD_cstr_w_len one_hundred[] = {
+  /* 100 */ _MHD_S_STR_W_LEN ("Continue"),       /* RFC-ietf-httpbis-semantics, Section 15.2.1 */
+  /* 101 */ _MHD_S_STR_W_LEN ("Switching Protocols"), /* RFC-ietf-httpbis-semantics, Section 15.2.2 */
+  /* 102 */ _MHD_S_STR_W_LEN ("Processing"),     /* RFC2518 */
+  /* 103 */ _MHD_S_STR_W_LEN ("Early Hints")     /* RFC8297 */
 };
 
-static const char *const three_hundred[] = {
-  "Multiple Choices",
-  "Moved Permanently",
-  "Moved Temporarily",
-  "See Other",
-  "Not Modified",
-  "Use Proxy",
-  "Switch Proxy",
-  "Temporary Redirect"
+static const struct _MHD_cstr_w_len two_hundred[] = {
+  /* 200 */ _MHD_S_STR_W_LEN ("OK"),             /* RFC-ietf-httpbis-semantics, Section 15.3.1 */
+  /* 201 */ _MHD_S_STR_W_LEN ("Created"),        /* RFC-ietf-httpbis-semantics, Section 15.3.2 */
+  /* 202 */ _MHD_S_STR_W_LEN ("Accepted"),       /* RFC-ietf-httpbis-semantics, Section 15.3.3 */
+  /* 203 */ _MHD_S_STR_W_LEN ("Non-Authoritative Information"), /* RFC-ietf-httpbis-semantics, Section 15.3.4 */
+  /* 204 */ _MHD_S_STR_W_LEN ("No Content"),     /* RFC-ietf-httpbis-semantics, Section 15.3.5 */
+  /* 205 */ _MHD_S_STR_W_LEN ("Reset Content"),  /* RFC-ietf-httpbis-semantics, Section 15.3.6 */
+  /* 206 */ _MHD_S_STR_W_LEN ("Partial Content"), /* RFC-ietf-httpbis-semantics, Section 15.3.7 */
+  /* 207 */ _MHD_S_STR_W_LEN ("Multi-Status"),   /* RFC4918 */
+  /* 208 */ _MHD_S_STR_W_LEN ("Already Reported"), /* RFC5842 */
+  /* 209 */ {"Unknown", 0},                      /* Not used */
+  /* 210 */ {"Unknown", 0},                      /* Not used */
+  /* 211 */ {"Unknown", 0},                      /* Not used */
+  /* 212 */ {"Unknown", 0},                      /* Not used */
+  /* 213 */ {"Unknown", 0},                      /* Not used */
+  /* 214 */ {"Unknown", 0},                      /* Not used */
+  /* 215 */ {"Unknown", 0},                      /* Not used */
+  /* 216 */ {"Unknown", 0},                      /* Not used */
+  /* 217 */ {"Unknown", 0},                      /* Not used */
+  /* 218 */ {"Unknown", 0},                      /* Not used */
+  /* 219 */ {"Unknown", 0},                      /* Not used */
+  /* 220 */ {"Unknown", 0},                      /* Not used */
+  /* 221 */ {"Unknown", 0},                      /* Not used */
+  /* 222 */ {"Unknown", 0},                      /* Not used */
+  /* 223 */ {"Unknown", 0},                      /* Not used */
+  /* 224 */ {"Unknown", 0},                      /* Not used */
+  /* 225 */ {"Unknown", 0},                      /* Not used */
+  /* 226 */ _MHD_S_STR_W_LEN ("IM Used")         /* RFC3229 */
 };
 
-static const char *const four_hundred[] = {
-  "Bad Request",
-  "Unauthorized",
-  "Payment Required",
-  "Forbidden",
-  "Not Found",
-  "Method Not Allowed",
-  "Not Acceptable",
-  "Proxy Authentication Required",
-  "Request Time-out",
-  "Conflict",
-  "Gone",
-  "Length Required",
-  "Precondition Failed",
-  "Request Entity Too Large",
-  "Request-URI Too Large",
-  "Unsupported Media Type",
-  "Requested Range Not Satisfiable",
-  "Expectation Failed",
-  "Unknown",
-  "Unknown",
-  "Unknown", /* 420 */
-  "Unknown",
-  "Unprocessable Entity",
-  "Locked",
-  "Failed Dependency",
-  "Unordered Collection",
-  "Upgrade Required",
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "Unknown", /* 430 */
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "Unknown", /* 435 */
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "Unknown", /* 440 */
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "No Response",
-  "Unknown", /* 445 */
-  "Unknown",
-  "Unknown",
-  "Unknown",
-  "Retry With",
-  "Blocked by Windows Parental Controls", /* 450 */
-  "Unavailable For Legal Reasons"
+static const struct _MHD_cstr_w_len three_hundred[] = {
+  /* 300 */ _MHD_S_STR_W_LEN ("Multiple Choices"), /* RFC-ietf-httpbis-semantics, Section 15.4.1 */
+  /* 301 */ _MHD_S_STR_W_LEN ("Moved Permanently"), /* RFC-ietf-httpbis-semantics, Section 15.4.2 */
+  /* 302 */ _MHD_S_STR_W_LEN ("Found"),          /* RFC-ietf-httpbis-semantics, Section 15.4.3 */
+  /* 303 */ _MHD_S_STR_W_LEN ("See Other"),      /* RFC-ietf-httpbis-semantics, Section 15.4.4 */
+  /* 304 */ _MHD_S_STR_W_LEN ("Not Modified"),   /* RFC-ietf-httpbis-semantics, Section 15.4.5 */
+  /* 305 */ _MHD_S_STR_W_LEN ("Use Proxy"),      /* RFC-ietf-httpbis-semantics, Section 15.4.6 */
+  /* 306 */ _MHD_S_STR_W_LEN ("Switch Proxy"),   /* Not used! RFC-ietf-httpbis-semantics, Section 15.4.7 */
+  /* 307 */ _MHD_S_STR_W_LEN ("Temporary Redirect"), /* RFC-ietf-httpbis-semantics, Section 15.4.8 */
+  /* 308 */ _MHD_S_STR_W_LEN ("Permanent Redirect") /* RFC-ietf-httpbis-semantics, Section 15.4.9 */
 };
 
-static const char *const five_hundred[] = {
-  "Internal Server Error",
-  "Not Implemented",
-  "Bad Gateway",
-  "Service Unavailable",
-  "Gateway Time-out",
-  "HTTP Version not supported",
-  "Variant Also Negotiates",
-  "Insufficient Storage",
-  "Unknown",
-  "Bandwidth Limit Exceeded",
-  "Not Extended"
+static const struct _MHD_cstr_w_len four_hundred[] = {
+  /* 400 */ _MHD_S_STR_W_LEN ("Bad Request"),    /* RFC-ietf-httpbis-semantics, Section 15.5.1 */
+  /* 401 */ _MHD_S_STR_W_LEN ("Unauthorized"),   /* RFC-ietf-httpbis-semantics, Section 15.5.2 */
+  /* 402 */ _MHD_S_STR_W_LEN ("Payment Required"), /* RFC-ietf-httpbis-semantics, Section 15.5.3 */
+  /* 403 */ _MHD_S_STR_W_LEN ("Forbidden"),      /* RFC-ietf-httpbis-semantics, Section 15.5.4 */
+  /* 404 */ _MHD_S_STR_W_LEN ("Not Found"),      /* RFC-ietf-httpbis-semantics, Section 15.5.5 */
+  /* 405 */ _MHD_S_STR_W_LEN ("Method Not Allowed"), /* RFC-ietf-httpbis-semantics, Section 15.5.6 */
+  /* 406 */ _MHD_S_STR_W_LEN ("Not Acceptable"), /* RFC-ietf-httpbis-semantics, Section 15.5.7 */
+  /* 407 */ _MHD_S_STR_W_LEN ("Proxy Authentication Required"), /* RFC-ietf-httpbis-semantics, Section 15.5.8 */
+  /* 408 */ _MHD_S_STR_W_LEN ("Request Timeout"), /* RFC-ietf-httpbis-semantics, Section 15.5.9 */
+  /* 409 */ _MHD_S_STR_W_LEN ("Conflict"),       /* RFC-ietf-httpbis-semantics, Section 15.5.10 */
+  /* 410 */ _MHD_S_STR_W_LEN ("Gone"),           /* RFC-ietf-httpbis-semantics, Section 15.5.11 */
+  /* 411 */ _MHD_S_STR_W_LEN ("Length Required"), /* RFC-ietf-httpbis-semantics, Section 15.5.12 */
+  /* 412 */ _MHD_S_STR_W_LEN ("Precondition Failed"), /* RFC-ietf-httpbis-semantics, Section 15.5.13 */
+  /* 413 */ _MHD_S_STR_W_LEN ("Content Too Large"), /* RFC-ietf-httpbis-semantics, Section 15.5.14 */
+  /* 414 */ _MHD_S_STR_W_LEN ("URI Too Long"),   /* RFC-ietf-httpbis-semantics, Section 15.5.15 */
+  /* 415 */ _MHD_S_STR_W_LEN ("Unsupported Media Type"), /* RFC-ietf-httpbis-semantics, Section 15.5.16 */
+  /* 416 */ _MHD_S_STR_W_LEN ("Range Not Satisfiable"), /* RFC-ietf-httpbis-semantics, Section 15.5.17 */
+  /* 417 */ _MHD_S_STR_W_LEN ("Expectation Failed"), /* RFC-ietf-httpbis-semantics, Section 15.5.18 */
+  /* 418 */ {"Unknown", 0},                      /* Not used */
+  /* 419 */ {"Unknown", 0},                      /* Not used */
+  /* 420 */ {"Unknown", 0},                      /* Not used */
+  /* 421 */ _MHD_S_STR_W_LEN ("Misdirected Request"), /* RFC-ietf-httpbis-semantics, Section 15.5.20 */
+  /* 422 */ _MHD_S_STR_W_LEN ("Unprocessable Content"), /* RFC-ietf-httpbis-semantics, Section 15.5.21 */
+  /* 423 */ _MHD_S_STR_W_LEN ("Locked"),         /* RFC4918 */
+  /* 424 */ _MHD_S_STR_W_LEN ("Failed Dependency"), /* RFC4918 */
+  /* 425 */ _MHD_S_STR_W_LEN ("Too Early"),      /* RFC8470 */
+  /* 426 */ _MHD_S_STR_W_LEN ("Upgrade Required"), /* RFC-ietf-httpbis-semantics, Section 15.5.22 */
+  /* 427 */ {"Unknown", 0},                      /* Not used */
+  /* 428 */ _MHD_S_STR_W_LEN ("Precondition Required"), /* RFC6585 */
+  /* 429 */ _MHD_S_STR_W_LEN ("Too Many Requests"), /* RFC6585 */
+  /* 430 */ {"Unknown", 0},                      /* Not used */
+  /* 431 */ _MHD_S_STR_W_LEN ("Request Header Fields Too Large"), /* RFC6585 */
+  /* 432 */ {"Unknown", 0},                      /* Not used */
+  /* 433 */ {"Unknown", 0},                      /* Not used */
+  /* 434 */ {"Unknown", 0},                      /* Not used */
+  /* 435 */ {"Unknown", 0},                      /* Not used */
+  /* 436 */ {"Unknown", 0},                      /* Not used */
+  /* 437 */ {"Unknown", 0},                      /* Not used */
+  /* 438 */ {"Unknown", 0},                      /* Not used */
+  /* 439 */ {"Unknown", 0},                      /* Not used */
+  /* 440 */ {"Unknown", 0},                      /* Not used */
+  /* 441 */ {"Unknown", 0},                      /* Not used */
+  /* 442 */ {"Unknown", 0},                      /* Not used */
+  /* 443 */ {"Unknown", 0},                      /* Not used */
+  /* 444 */ {"Unknown", 0},                      /* Not used */
+  /* 445 */ {"Unknown", 0},                      /* Not used */
+  /* 446 */ {"Unknown", 0},                      /* Not used */
+  /* 447 */ {"Unknown", 0},                      /* Not used */
+  /* 448 */ {"Unknown", 0},                      /* Not used */
+  /* 449 */ _MHD_S_STR_W_LEN ("Reply With"),     /* MS IIS extension */
+  /* 450 */ _MHD_S_STR_W_LEN ("Blocked by Windows Parental Controls"), /* MS extension */
+  /* 451 */ _MHD_S_STR_W_LEN ("Unavailable For Legal Reasons") /* RFC7725 */
+};
+
+static const struct _MHD_cstr_w_len five_hundred[] = {
+  /* 500 */ _MHD_S_STR_W_LEN ("Internal Server Error"), /* RFC-ietf-httpbis-semantics, Section 15.6.1 */
+  /* 501 */ _MHD_S_STR_W_LEN ("Not Implemented"), /* RFC-ietf-httpbis-semantics, Section 15.6.2 */
+  /* 502 */ _MHD_S_STR_W_LEN ("Bad Gateway"),    /* RFC-ietf-httpbis-semantics, Section 15.6.3 */
+  /* 503 */ _MHD_S_STR_W_LEN ("Service Unavailable"), /* RFC-ietf-httpbis-semantics, Section 15.6.4 */
+  /* 504 */ _MHD_S_STR_W_LEN ("Gateway Timeout"), /* RFC-ietf-httpbis-semantics, Section 15.6.5 */
+  /* 505 */ _MHD_S_STR_W_LEN ("HTTP Version Not Supported"), /* RFC-ietf-httpbis-semantics, Section 15.6.6 */
+  /* 506 */ _MHD_S_STR_W_LEN ("Variant Also Negotiates"), /* RFC2295 */
+  /* 507 */ _MHD_S_STR_W_LEN ("Insufficient Storage"), /* RFC4918 */
+  /* 508 */ _MHD_S_STR_W_LEN ("Loop Detected"),  /* RFC5842 */
+  /* 509 */ _MHD_S_STR_W_LEN ("Bandwidth Limit Exceeded"), /* Apache extension */
+  /* 510 */ _MHD_S_STR_W_LEN ("Not Extended"),   /* RFC2774 */
+  /* 511 */ _MHD_S_STR_W_LEN ("Network Authentication Required") /* RFC6585 */
 };
 
 
 struct MHD_Reason_Block
 {
-  unsigned int max;
-  const char *const*data;
+  size_t max;
+  const struct _MHD_cstr_w_len *const data;
 };
 
-#define BLOCK(m) { (sizeof(m) / sizeof(char*)), m }
+#define BLOCK(m) { (sizeof(m) / sizeof(m[0])), m }
 
 static const struct MHD_Reason_Block reasons[] = {
   BLOCK (invalid_hundred),
@@ -149,12 +174,23 @@
 };
 
 
-const char *
+_MHD_EXTERN const char *
 MHD_get_reason_phrase_for (unsigned int code)
 {
   if ( (code >= 100) &&
        (code < 600) &&
        (reasons[code / 100].max > (code % 100)) )
-    return reasons[code / 100].data[code % 100];
+    return reasons[code / 100].data[code % 100].str;
   return "Unknown";
 }
+
+
+_MHD_EXTERN size_t
+MHD_get_reason_phrase_len_for (unsigned int code)
+{
+  if ( (code >= 100) &&
+       (code < 600) &&
+       (reasons[code / 100].max > (code % 100)) )
+    return reasons[code / 100].data[code % 100].len;
+  return 0;
+}
diff --git a/src/microhttpd/reason_phrase.h b/src/microhttpd/reason_phrase.h
deleted file mode 100644
index e442232..0000000
--- a/src/microhttpd/reason_phrase.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
-     This file is part of libmicrohttpd
-     Copyright (C) 2007 Lymba
-
-     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 2.1 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, write to the Free Software
-     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-*/
-
-/**
- * @file reason_phrase.c
- * @brief  Tables of the string response phrases
- * @author Elliot Glaysher
- */
-
-#ifndef REASON_PHRASE_H
-#define REASON_PHRASE_H
-
-/**
- * Returns the string reason phrase for a response code.
- *
- * If we don't have a string for a status code, we give the first
- * message in that status code class.
- */
-const char *MHD_get_reason_phrase_for (unsigned int code);
-
-#endif
diff --git a/src/microhttpd/response.c b/src/microhttpd/response.c
index 47a439e..d125ea2 100644
--- a/src/microhttpd/response.c
+++ b/src/microhttpd/response.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007, 2009, 2010 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2007-2021 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2015-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -16,29 +17,274 @@
      License along with this library; if not, write to the Free Software
      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
-
 /**
  * @file response.c
  * @brief  Methods for managing response objects
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
+#define MHD_NO_DEPRECATION 1
+
+#include "mhd_options.h"
+#ifdef HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif /* HAVE_SYS_IOCTL_H */
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#include <windows.h>
+#endif /* _WIN32 && !__CYGWIN__ */
+
 #include "internal.h"
 #include "response.h"
+#include "mhd_limits.h"
+#include "mhd_sockets.h"
+#include "mhd_itc.h"
+#include "mhd_str.h"
+#include "connection.h"
+#include "memorypool.h"
+#include "mhd_send.h"
+#include "mhd_compat.h"
+#include "mhd_assert.h"
 
-#if defined(_WIN32) && defined(MHD_W32_MUTEX_)
+
+#if defined(MHD_W32_MUTEX_)
 #ifndef WIN32_LEAN_AND_MEAN
 #define WIN32_LEAN_AND_MEAN 1
 #endif /* !WIN32_LEAN_AND_MEAN */
 #include <windows.h>
-#endif /* _WIN32 && MHD_W32_MUTEX_ */
+#endif /* MHD_W32_MUTEX_ */
 #if defined(_WIN32)
 #include <io.h> /* for lseek(), read() */
 #endif /* _WIN32 */
 
 
 /**
+ * Size of single file read operation for
+ * file-backed responses.
+ */
+#ifndef MHD_FILE_READ_BLOCK_SIZE
+#ifdef _WIN32
+#define MHD_FILE_READ_BLOCK_SIZE 16384 /* 16k */
+#else /* _WIN32 */
+#define MHD_FILE_READ_BLOCK_SIZE 4096 /* 4k */
+#endif /* _WIN32 */
+#endif /* !MHD_FD_BLOCK_SIZE */
+
+/**
+ * Insert a new header at the first position of the response
+ */
+#define _MHD_insert_header_first(presponse, phdr) do { \
+  mhd_assert (NULL == phdr->next); \
+  mhd_assert (NULL == phdr->prev); \
+  if (NULL == presponse->first_header) \
+  { \
+    mhd_assert (NULL == presponse->last_header); \
+    presponse->first_header = phdr; \
+    presponse->last_header = phdr;  \
+  } \
+  else \
+  { \
+    mhd_assert (NULL != presponse->last_header);        \
+    presponse->first_header->prev = phdr; \
+    phdr->next = presponse->first_header; \
+    presponse->first_header = phdr;       \
+  } \
+} while (0)
+
+/**
+ * Insert a new header at the last position of the response
+ */
+#define _MHD_insert_header_last(presponse, phdr) do { \
+  mhd_assert (NULL == phdr->next); \
+  mhd_assert (NULL == phdr->prev); \
+  if (NULL == presponse->last_header) \
+  { \
+    mhd_assert (NULL == presponse->first_header); \
+    presponse->last_header = phdr;  \
+    presponse->first_header = phdr; \
+  } \
+  else \
+  { \
+    mhd_assert (NULL != presponse->first_header);      \
+    presponse->last_header->next = phdr; \
+    phdr->prev = presponse->last_header; \
+    presponse->last_header = phdr;       \
+  } \
+} while (0)
+
+
+/**
+ * Remove a header from the response
+ */
+#define _MHD_remove_header(presponse, phdr) do { \
+  mhd_assert (NULL != presponse->first_header); \
+  mhd_assert (NULL != presponse->last_header);  \
+  if (NULL == phdr->prev) \
+  { \
+    mhd_assert (phdr == presponse->first_header); \
+    presponse->first_header = phdr->next; \
+  } \
+  else \
+  { \
+    mhd_assert (phdr != presponse->first_header); \
+    mhd_assert (phdr == phdr->prev->next); \
+    phdr->prev->next = phdr->next; \
+  } \
+  if (NULL == phdr->next) \
+  { \
+    mhd_assert (phdr == presponse->last_header); \
+    presponse->last_header = phdr->prev; \
+  } \
+  else \
+  { \
+    mhd_assert (phdr != presponse->last_header); \
+    mhd_assert (phdr == phdr->next->prev); \
+    phdr->next->prev = phdr->prev; \
+  } \
+} while (0)
+
+/**
+ * Add preallocated strings a header or footer line to the response without
+ * checking.
+ *
+ * Header/footer strings are not checked and assumed to be correct.
+ *
+ * The string must not be statically allocated!
+ * The strings must be malloc()'ed and zero terminated. The strings will
+ * be free()'ed when the response is destroyed.
+ *
+ * @param response response to add a header to
+ * @param kind header or footer
+ * @param header the header string to add, must be malloc()'ed and
+ *               zero-terminated
+ * @param header_len the length of the @a header
+ * @param content the value string to add, must be malloc()'ed and
+ *                zero-terminated
+ * @param content_len the length of the @a content
+ */
+bool
+MHD_add_response_entry_no_alloc_ (struct MHD_Response *response,
+                                  enum MHD_ValueKind kind,
+                                  char *header,
+                                  size_t header_len,
+                                  char *content,
+                                  size_t content_len)
+{
+  struct MHD_HTTP_Res_Header *hdr;
+
+  mhd_assert (0 != header_len);
+  mhd_assert (0 != content_len);
+  if (NULL == (hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header))))
+    return false;
+
+  hdr->header = header;
+  hdr->header_size = header_len;
+  hdr->value = content;
+  hdr->value_size = content_len;
+  hdr->kind = kind;
+  _MHD_insert_header_last (response, hdr);
+
+  return true; /* Success exit point */
+}
+
+
+/**
+ * Add a header or footer line to the response without checking.
+ *
+ * It is assumed that parameters are correct.
+ *
+ * @param response response to add a header to
+ * @param kind header or footer
+ * @param header the header to add, does not need to be zero-terminated
+ * @param header_len the length of the @a header
+ * @param content value to add, does not need to be zero-terminated
+ * @param content_len the length of the @a content
+ * @return false on error (like out-of-memory),
+ *         true if succeed
+ */
+bool
+MHD_add_response_entry_no_check_ (struct MHD_Response *response,
+                                  enum MHD_ValueKind kind,
+                                  const char *header,
+                                  size_t header_len,
+                                  const char *content,
+                                  size_t content_len)
+{
+  char *header_malloced;
+  char *value_malloced;
+
+  mhd_assert (0 != header_len);
+  mhd_assert (0 != content_len);
+  header_malloced = malloc (header_len + 1);
+  if (NULL == header_malloced)
+    return false;
+
+  memcpy (header_malloced, header, header_len);
+  header_malloced[header_len] = 0;
+
+  value_malloced = malloc (content_len + 1);
+  if (NULL != value_malloced)
+  {
+    memcpy (value_malloced, content, content_len);
+    value_malloced[content_len] = 0;
+
+    if (MHD_add_response_entry_no_alloc_ (response, kind,
+                                          header_malloced, header_len,
+                                          value_malloced, content_len))
+      return true; /* Success exit point */
+
+    free (value_malloced);
+  }
+  free (header_malloced);
+
+  return false; /* Failure exit point */
+}
+
+
+/**
+ * Add a header or footer line to the response.
+ *
+ * @param header the header to add, does not need to be zero-terminated
+ * @param header_len the length of the @a header
+ * @param content value to add, does not need to be zero-terminated
+ * @param content_len the length of the @a content
+ * @return false on error (out-of-memory, invalid header or content),
+ *         true if succeed
+ */
+static bool
+add_response_entry_n (struct MHD_Response *response,
+                      enum MHD_ValueKind kind,
+                      const char *header,
+                      size_t header_len,
+                      const char *content,
+                      size_t content_len)
+{
+  if (NULL == response)
+    return false;
+  if (0 == header_len)
+    return false;
+  if (0 == content_len)
+    return false;
+  if (NULL != memchr (header, '\t', header_len))
+    return false;
+  if (NULL != memchr (header, ' ', header_len))
+    return false;
+  if (NULL != memchr (header, '\r', header_len))
+    return false;
+  if (NULL != memchr (header, '\n', header_len))
+    return false;
+  if (NULL != memchr (content, '\r', content_len))
+    return false;
+  if (NULL != memchr (content, '\n', content_len))
+    return false;
+
+  return MHD_add_response_entry_no_check_ (response, kind, header, header_len,
+                                           content, content_len);
+}
+
+
+/**
  * Add a header or footer line to the response.
  *
  * @param response response to add a header to
@@ -47,42 +293,276 @@
  * @param content value to add
  * @return #MHD_NO on error (i.e. invalid header or content format).
  */
-static int
+static enum MHD_Result
 add_response_entry (struct MHD_Response *response,
-		    enum MHD_ValueKind kind,
-		    const char *header,
-		    const char *content)
+                    enum MHD_ValueKind kind,
+                    const char *header,
+                    const char *content)
 {
-  struct MHD_HTTP_Header *hdr;
+  size_t header_len;
+  size_t content_len;
 
-  if ( (NULL == response) ||
-       (NULL == header) ||
-       (NULL == content) ||
-       (0 == strlen (header)) ||
-       (0 == strlen (content)) ||
-       (NULL != strchr (header, '\t')) ||
-       (NULL != strchr (header, '\r')) ||
-       (NULL != strchr (header, '\n')) ||
-       (NULL != strchr (content, '\t')) ||
-       (NULL != strchr (content, '\r')) ||
-       (NULL != strchr (content, '\n')) )
+  if (NULL == content)
     return MHD_NO;
-  if (NULL == (hdr = malloc (sizeof (struct MHD_HTTP_Header))))
+
+  header_len = strlen (header);
+  content_len = strlen (content);
+  return add_response_entry_n (response, kind, header,
+                               header_len, content,
+                               content_len) ? MHD_YES : MHD_NO;
+}
+
+
+/**
+ * Add "Connection:" header to the response with special processing.
+ *
+ * "Connection:" header value will be combined with any existing "Connection:"
+ * header, "close" token (if any) will be de-duplicated and moved to the first
+ * position.
+ *
+ * @param response the response to add a header to
+ * @param value the value to add
+ * @return #MHD_NO on error (no memory).
+ */
+static enum MHD_Result
+add_response_header_connection (struct MHD_Response *response,
+                                const char *value)
+{
+  static const char *key = MHD_HTTP_HEADER_CONNECTION;
+  /** the length of the "Connection" key */
+  static const size_t key_len =
+    MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION);
+  size_t value_len; /**< the length of the @a value */
+  size_t old_value_len; /**< the length of the existing "Connection" value */
+  size_t buf_size;  /**< the size of the buffer */
+  size_t norm_len;  /**< the length of the normalised value */
+  char *buf;        /**< the temporal buffer */
+  struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */
+  bool value_has_close; /**< the @a value has "close" token */
+  bool already_has_close; /**< existing "Connection" header has "close" token */
+  size_t pos = 0;   /**< position of addition in the @a buf */
+
+  if ( (NULL != strchr (value, '\r')) ||
+       (NULL != strchr (value, '\n')) )
     return MHD_NO;
-  if (NULL == (hdr->header = strdup (header)))
+
+  if (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR))
+  {
+    hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND,
+                                       key, key_len);
+    already_has_close =
+      (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE));
+    mhd_assert (already_has_close == (0 == memcmp (hdr->value, "close", 5)));
+    mhd_assert (NULL != hdr);
+  }
+  else
+  {
+    hdr = NULL;
+    already_has_close = false;
+    mhd_assert (NULL == MHD_get_response_element_n_ (response,
+                                                     MHD_HEADER_KIND,
+                                                     key, key_len));
+    mhd_assert (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE));
+  }
+  if (NULL != hdr)
+    old_value_len = hdr->value_size + 2; /* additional size for ", " */
+  else
+    old_value_len = 0;
+
+  value_len = strlen (value);
+  if (value_len >= SSIZE_MAX)
+    return MHD_NO;
+  /* Additional space for normalisation and zero-termination */
+  norm_len = value_len + value_len / 2 + 1;
+  if (norm_len >= SSIZE_MAX)
+    return MHD_NO;
+  buf_size = old_value_len + (size_t) norm_len;
+
+  buf = malloc (buf_size);
+  if (NULL == buf)
+    return MHD_NO;
+  if (1)
+  { /* local scope */
+    ssize_t norm_len_s = (ssize_t) norm_len;
+    /* Remove "close" token (if any), it will be moved to the front */
+    value_has_close = MHD_str_remove_token_caseless_ (value, value_len, "close",
+                                                      MHD_STATICSTR_LEN_ ( \
+                                                        "close"),
+                                                      buf + old_value_len,
+                                                      &norm_len_s);
+    mhd_assert (0 <= norm_len_s);
+    if (0 > norm_len_s)
     {
-      free (hdr);
+      /* Must never happen with realistic sizes */
+      free (buf);
       return MHD_NO;
     }
-  if (NULL == (hdr->value = strdup (content)))
-    {
-      free (hdr->header);
-      free (hdr);
+    else
+      norm_len = (size_t) norm_len_s;
+  }
+#ifdef UPGRADE_SUPPORT
+  if ( (NULL != response->upgrade_handler) && value_has_close)
+  { /* The "close" token cannot be used with connection "upgrade" */
+    free (buf);
+    return MHD_NO;
+  }
+#endif /* UPGRADE_SUPPORT */
+  if (0 != norm_len)
+    MHD_str_remove_tokens_caseless_ (buf + old_value_len, &norm_len,
+                                     "keep-alive",
+                                     MHD_STATICSTR_LEN_ ("keep-alive"));
+  if (0 == norm_len)
+  { /* New value is empty after normalisation */
+    if (! value_has_close)
+    { /* The new value had no tokens */
+      free (buf);
       return MHD_NO;
     }
-  hdr->kind = kind;
-  hdr->next = response->first_header;
-  response->first_header = hdr;
+    if (already_has_close)
+    { /* The "close" token is already present, nothing to modify */
+      free (buf);
+      return MHD_YES;
+    }
+  }
+  /* Add "close" token if required */
+  if (value_has_close && ! already_has_close)
+  {
+    /* Need to insert "close" token at the first position */
+    mhd_assert (buf_size >= old_value_len + norm_len   \
+                + MHD_STATICSTR_LEN_ ("close, ") + 1);
+    if (0 != norm_len)
+      memmove (buf + MHD_STATICSTR_LEN_ ("close, ") + old_value_len,
+               buf + old_value_len, norm_len + 1);
+    memcpy (buf, "close", MHD_STATICSTR_LEN_ ("close"));
+    pos += MHD_STATICSTR_LEN_ ("close");
+  }
+  /* Add old value tokens (if any) */
+  if (0 != old_value_len)
+  {
+    if (0 != pos)
+    {
+      buf[pos++] = ',';
+      buf[pos++] = ' ';
+    }
+    memcpy (buf + pos, hdr->value,
+            hdr->value_size);
+    pos += hdr->value_size;
+  }
+  /* Add new value token (if any) */
+  if (0 != norm_len)
+  {
+    if (0 != pos)
+    {
+      buf[pos++] = ',';
+      buf[pos++] = ' ';
+    }
+    /* The new value tokens must be already at the correct position */
+    mhd_assert ((value_has_close && ! already_has_close) ? \
+                (MHD_STATICSTR_LEN_ ("close, ") + old_value_len == pos) : \
+                (old_value_len == pos));
+    pos += norm_len;
+  }
+  mhd_assert (buf_size > pos);
+  buf[pos] = 0; /* Null terminate the result */
+
+  if (NULL == hdr)
+  {
+    struct MHD_HTTP_Res_Header *new_hdr; /**< new "Connection" header */
+    /* Create new response header entry */
+    new_hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header));
+    if (NULL != new_hdr)
+    {
+      new_hdr->header = malloc (key_len + 1);
+      if (NULL != new_hdr->header)
+      {
+        memcpy (new_hdr->header, key, key_len + 1);
+        new_hdr->header_size = key_len;
+        new_hdr->value = buf;
+        new_hdr->value_size = pos;
+        new_hdr->kind = MHD_HEADER_KIND;
+        if (value_has_close)
+          response->flags_auto = (MHD_RAF_HAS_CONNECTION_HDR
+                                  | MHD_RAF_HAS_CONNECTION_CLOSE);
+        else
+          response->flags_auto = MHD_RAF_HAS_CONNECTION_HDR;
+        _MHD_insert_header_first (response, new_hdr);
+        return MHD_YES;
+      }
+      free (new_hdr);
+    }
+    free (buf);
+    return MHD_NO;
+  }
+
+  /* Update existing header entry */
+  free (hdr->value);
+  hdr->value = buf;
+  hdr->value_size = pos;
+  if (value_has_close && ! already_has_close)
+    response->flags_auto |= MHD_RAF_HAS_CONNECTION_CLOSE;
+  return MHD_YES;
+}
+
+
+/**
+ * Remove tokens from "Connection:" header of the response.
+ *
+ * Provided tokens will be removed from "Connection:" header value.
+ *
+ * @param response the response to manipulate "Connection:" header
+ * @param value the tokens to remove
+ * @return #MHD_NO on error (no headers or tokens found).
+ */
+static enum MHD_Result
+del_response_header_connection (struct MHD_Response *response,
+                                const char *value)
+{
+  struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */
+
+  hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND,
+                                     MHD_HTTP_HEADER_CONNECTION,
+                                     MHD_STATICSTR_LEN_ ( \
+                                       MHD_HTTP_HEADER_CONNECTION));
+  if (NULL == hdr)
+    return MHD_NO;
+
+  if (! MHD_str_remove_tokens_caseless_ (hdr->value, &hdr->value_size, value,
+                                         strlen (value)))
+    return MHD_NO;
+  if (0 == hdr->value_size)
+  {
+    _MHD_remove_header (response, hdr);
+    free (hdr->value);
+    free (hdr->header);
+    free (hdr);
+    response->flags_auto &=
+      ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_HDR
+        | (enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE);
+  }
+  else
+  {
+    hdr->value[hdr->value_size] = 0; /* Null-terminate the result */
+    if (0 != (response->flags_auto
+              & ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE)))
+    {
+      if (MHD_STATICSTR_LEN_ ("close") == hdr->value_size)
+      {
+        if (0 != memcmp (hdr->value, "close", MHD_STATICSTR_LEN_ ("close")))
+          response->flags_auto &=
+            ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE);
+      }
+      else if (MHD_STATICSTR_LEN_ ("close, ") < hdr->value_size)
+      {
+        if (0 != memcmp (hdr->value, "close, ",
+                         MHD_STATICSTR_LEN_ ("close, ")))
+          response->flags_auto &=
+            ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE);
+      }
+      else
+        response->flags_auto &=
+          ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE);
+    }
+  }
   return MHD_YES;
 }
 
@@ -90,20 +570,135 @@
 /**
  * Add a header line to the response.
  *
- * @param response response to add a header to
- * @param header the header to add
- * @param content value to add
- * @return #MHD_NO on error (i.e. invalid header or content format).
+ * When reply is generated with queued response, some headers are generated
+ * automatically. Automatically generated headers are only sent to the client,
+ * but not added back to the response object.
+ *
+ * The list of automatic headers:
+ * + "Date" header is added automatically unless already set by
+ *   this function
+ *   @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK
+ * + "Content-Length" is added automatically when required, attempt to set
+ *   it manually by this function is ignored.
+ *   @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH
+ * + "Transfer-Encoding" with value "chunked" is added automatically,
+ *   when chunked transfer encoding is used automatically. Same header with
+ *   the same value can be set manually by this function to enforce chunked
+ *   encoding, however for HTTP/1.0 clients chunked encoding will not be used
+ *   and manually set "Transfer-Encoding" header is automatically removed
+ *   for HTTP/1.0 clients
+ * + "Connection" may be added automatically with value "Keep-Alive" (only
+ *   for HTTP/1.0 clients) or "Close". The header "Connection" with value
+ *   "Close" could be set by this function to enforce closure of
+ *   the connection after sending this response. "Keep-Alive" cannot be
+ *   enforced and will be removed automatically.
+ *   @see #MHD_RF_SEND_KEEP_ALIVE_HEADER
+ *
+ * Some headers are pre-processed by this function:
+ * * "Connection" headers are combined into single header entry, value is
+ *   normilised, "Keep-Alive" tokens are removed.
+ * * "Transfer-Encoding" header: the only one header is allowed, the only
+ *   allowed value is "chunked".
+ * * "Date" header: the only one header is allowed, the second added header
+ *   replaces the first one.
+ * * "Content-Length" application-defined header is not allowed.
+ *   @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH
+ *
+ * Headers are used in order as they were added.
+ *
+ * @param response the response to add a header to
+ * @param header the header name to add, no need to be static, an internal copy
+ *               will be created automatically
+ * @param content the header value to add, no need to be static, an internal
+ *                copy will be created automatically
+ * @return #MHD_YES on success,
+ *         #MHD_NO on error (i.e. invalid header or content format),
+ *         or out of memory
  * @ingroup response
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_add_response_header (struct MHD_Response *response,
-                         const char *header, const char *content)
+                         const char *header,
+                         const char *content)
 {
+  if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_CONNECTION))
+    return add_response_header_connection (response, content);
+
+  if (MHD_str_equal_caseless_ (header,
+                               MHD_HTTP_HEADER_TRANSFER_ENCODING))
+  {
+    if (! MHD_str_equal_caseless_ (content, "chunked"))
+      return MHD_NO;   /* Only "chunked" encoding is allowed */
+    if (0 != (response->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))
+      return MHD_YES;  /* Already has "chunked" encoding header */
+    if ( (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) &&
+         (0 == (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) )
+      return MHD_NO; /* Has "Content-Length" header and no "Insanity" flag */
+    if (MHD_NO != add_response_entry (response,
+                                      MHD_HEADER_KIND,
+                                      header,
+                                      content))
+    {
+      response->flags_auto |= MHD_RAF_HAS_TRANS_ENC_CHUNKED;
+      return MHD_YES;
+    }
+    return MHD_NO;
+  }
+  if (MHD_str_equal_caseless_ (header,
+                               MHD_HTTP_HEADER_DATE))
+  {
+    if (0 != (response->flags_auto & MHD_RAF_HAS_DATE_HDR))
+    {
+      struct MHD_HTTP_Res_Header *hdr;
+      hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_DATE,
+                                         MHD_STATICSTR_LEN_ ( \
+                                           MHD_HTTP_HEADER_DATE));
+      mhd_assert (NULL != hdr);
+      _MHD_remove_header (response, hdr);
+      if (NULL != hdr->value)
+        free (hdr->value);
+      free (hdr->header);
+      free (hdr);
+    }
+    if (MHD_NO != add_response_entry (response,
+                                      MHD_HEADER_KIND,
+                                      header,
+                                      content))
+    {
+      response->flags_auto |= MHD_RAF_HAS_DATE_HDR;
+      return MHD_YES;
+    }
+    return MHD_NO;
+  }
+
+  if (MHD_str_equal_caseless_ (header,
+                               MHD_HTTP_HEADER_CONTENT_LENGTH))
+  {
+    /* Generally MHD sets automatically correct "Content-Length" always when
+     * needed.
+     * Custom "Content-Length" header is allowed only in special cases. */
+    if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) ||
+         ((0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) &&
+          (0 == (response->flags_auto & (MHD_RAF_HAS_TRANS_ENC_CHUNKED
+                                         | MHD_RAF_HAS_CONTENT_LENGTH)))) )
+    {
+      if (MHD_NO != add_response_entry (response,
+                                        MHD_HEADER_KIND,
+                                        header,
+                                        content))
+      {
+        response->flags_auto |= MHD_RAF_HAS_CONTENT_LENGTH;
+        return MHD_YES;
+      }
+    }
+    return MHD_NO;
+  }
+
   return add_response_entry (response,
-			     MHD_HEADER_KIND,
-			     header,
-			     content);
+                             MHD_HEADER_KIND,
+                             header,
+                             content);
 }
 
 
@@ -116,55 +711,100 @@
  * @return #MHD_NO on error (i.e. invalid footer or content format).
  * @ingroup response
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_add_response_footer (struct MHD_Response *response,
-                         const char *footer, const char *content)
+                         const char *footer,
+                         const char *content)
 {
   return add_response_entry (response,
-			     MHD_FOOTER_KIND,
-			     footer,
-			     content);
+                             MHD_FOOTER_KIND,
+                             footer,
+                             content);
 }
 
 
 /**
  * Delete a header (or footer) line from the response.
  *
+ * For "Connection" headers this function remove all tokens from existing
+ * value. Successful result means that at least one token has been removed.
+ * If all tokens are removed from "Connection" header, the empty "Connection"
+ * header removed.
+ *
  * @param response response to remove a header from
  * @param header the header to delete
  * @param content value to delete
  * @return #MHD_NO on error (no such header known)
  * @ingroup response
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_del_response_header (struct MHD_Response *response,
                          const char *header,
-			 const char *content)
+                         const char *content)
 {
-  struct MHD_HTTP_Header *pos;
-  struct MHD_HTTP_Header *prev;
+  struct MHD_HTTP_Res_Header *pos;
+  size_t header_len;
+  size_t content_len;
 
-  if ( (NULL == header) || (NULL == content) )
+  if ( (NULL == header) ||
+       (NULL == content) )
     return MHD_NO;
-  prev = NULL;
+  header_len = strlen (header);
+
+  if ((0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) &&
+      (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION) == header_len) &&
+      MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_CONNECTION,
+                                     header_len))
+    return del_response_header_connection (response, content);
+
+  content_len = strlen (content);
   pos = response->first_header;
-  while (pos != NULL)
+  while (NULL != pos)
+  {
+    if ((header_len == pos->header_size) &&
+        (content_len == pos->value_size) &&
+        (0 == memcmp (header,
+                      pos->header,
+                      header_len)) &&
+        (0 == memcmp (content,
+                      pos->value,
+                      content_len)))
     {
-      if ((0 == strcmp (header, pos->header)) &&
-          (0 == strcmp (content, pos->value)))
-        {
-          free (pos->header);
-          free (pos->value);
-          if (NULL == prev)
-            response->first_header = pos->next;
-          else
-            prev->next = pos->next;
-          free (pos);
-          return MHD_YES;
-        }
-      prev = pos;
-      pos = pos->next;
+      _MHD_remove_header (response, pos);
+      free (pos->header);
+      free (pos->value);
+      free (pos);
+      if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) ==
+            header_len) &&
+           MHD_str_equal_caseless_bin_n_ (header,
+                                          MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                          header_len) )
+        response->flags_auto &=
+          ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_TRANS_ENC_CHUNKED);
+      else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_DATE) ==
+                 header_len) &&
+                MHD_str_equal_caseless_bin_n_ (header,
+                                               MHD_HTTP_HEADER_DATE,
+                                               header_len) )
+        response->flags_auto &=
+          ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_DATE_HDR);
+      else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) ==
+                 header_len) &&
+                MHD_str_equal_caseless_bin_n_ (header,
+                                               MHD_HTTP_HEADER_CONTENT_LENGTH,
+                                               header_len) )
+      {
+        if (NULL == MHD_get_response_element_n_ (response,
+                                                 MHD_HEADER_KIND,
+                                                 MHD_HTTP_HEADER_CONTENT_LENGTH,
+                                                 header_len))
+          response->flags_auto &=
+            ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONTENT_LENGTH);
+      }
+      return MHD_YES;
     }
+    pos = pos->next;
+  }
   return MHD_NO;
 }
 
@@ -179,21 +819,26 @@
  * @return number of entries iterated over
  * @ingroup response
  */
-int
+_MHD_EXTERN int
 MHD_get_response_headers (struct MHD_Response *response,
-                          MHD_KeyValueIterator iterator, void *iterator_cls)
+                          MHD_KeyValueIterator iterator,
+                          void *iterator_cls)
 {
-  struct MHD_HTTP_Header *pos;
   int numHeaders = 0;
+  struct MHD_HTTP_Res_Header *pos;
 
-  for (pos = response->first_header; NULL != pos; pos = pos->next)
-    {
-      numHeaders++;
-      if ((NULL != iterator) &&
-          (MHD_YES != iterator (iterator_cls,
-                                pos->kind, pos->header, pos->value)))
-        break;
-    }
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    numHeaders++;
+    if ((NULL != iterator) &&
+        (MHD_NO == iterator (iterator_cls,
+                             pos->kind,
+                             pos->header,
+                             pos->value)))
+      break;
+  }
   return numHeaders;
 }
 
@@ -206,24 +851,125 @@
  * @return NULL if header does not exist
  * @ingroup response
  */
-const char *
+_MHD_EXTERN const char *
 MHD_get_response_header (struct MHD_Response *response,
-			 const char *key)
+                         const char *key)
 {
-  struct MHD_HTTP_Header *pos;
+  struct MHD_HTTP_Res_Header *pos;
+  size_t key_size;
 
   if (NULL == key)
     return NULL;
-  for (pos = response->first_header; NULL != pos; pos = pos->next)
-    if (0 == strcmp (key, pos->header))
+
+  key_size = strlen (key);
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if ((pos->header_size == key_size) &&
+        (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size)))
       return pos->value;
+  }
   return NULL;
 }
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Get a particular header (or footer) element from the response.
+ *
+ * Function returns the first found element.
+ * @param response response to query
+ * @param kind the kind of element: header or footer
+ * @param key the key which header to get
+ * @param key_len the length of the @a key
+ * @return NULL if header element does not exist
+ * @ingroup response
+ */
+struct MHD_HTTP_Res_Header *
+MHD_get_response_element_n_ (struct MHD_Response *response,
+                             enum MHD_ValueKind kind,
+                             const char *key,
+                             size_t key_len)
+{
+  struct MHD_HTTP_Res_Header *pos;
+
+  mhd_assert (NULL != key);
+  mhd_assert (0 != key[0]);
+  mhd_assert (0 != key_len);
+
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if ((pos->header_size == key_len) &&
+        (kind == pos->kind) &&
+        (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size)))
+      return pos;
+  }
+  return NULL;
+}
+
+
+/**
+ * Check whether response header contains particular token.
+ *
+ * Token could be surrounded by spaces and tabs and delimited by comma.
+ * Case-insensitive match used for header names and tokens.
+ *
+ * @param response  the response to query
+ * @param key       header name
+ * @param key_len   the length of @a key, not including optional
+ *                  terminating null-character.
+ * @param token     the token to find
+ * @param token_len the length of @a token, not including optional
+ *                  terminating null-character.
+ * @return true if token is found in specified header,
+ *         false otherwise
+ */
+bool
+MHD_check_response_header_token_ci (const struct MHD_Response *response,
+                                    const char *key,
+                                    size_t key_len,
+                                    const char *token,
+                                    size_t token_len)
+{
+  struct MHD_HTTP_Res_Header *pos;
+
+  if ( (NULL == key) ||
+       ('\0' == key[0]) ||
+       (NULL == token) ||
+       ('\0' == token[0]) )
+    return false;
+
+  /* Token must not contain binary zero! */
+  mhd_assert (strlen (token) == token_len);
+
+  for (pos = response->first_header;
+       NULL != pos;
+       pos = pos->next)
+  {
+    if ( (pos->kind == MHD_HEADER_KIND) &&
+         (key_len == pos->header_size) &&
+         MHD_str_equal_caseless_bin_n_ (pos->header,
+                                        key,
+                                        key_len) &&
+         MHD_str_has_token_caseless_ (pos->value,
+                                      token,
+                                      token_len) )
+      return true;
+  }
+  return false;
+}
+
+
+/**
+ * Create a response object.
+ * The response object can be extended with header information and then be used
+ * any number of times.
+ *
+ * If response object is used to answer HEAD request then the body of the
+ * response is not used, while all headers (including automatic headers) are
+ * used.
  *
  * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown
  * @param block_size preferred block size for querying crc (advisory only,
@@ -237,7 +983,7 @@
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @ingroup response
  */
-struct MHD_Response *
+_MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_callback (uint64_t size,
                                    size_t block_size,
                                    MHD_ContentReaderCallback crc,
@@ -248,17 +994,19 @@
 
   if ((NULL == crc) || (0 == block_size))
     return NULL;
-  if (NULL == (response = malloc (sizeof (struct MHD_Response) + block_size)))
+  if (NULL == (response = MHD_calloc_ (1, sizeof (struct MHD_Response)
+                                       + block_size)))
     return NULL;
-  memset (response, 0, sizeof (struct MHD_Response));
   response->fd = -1;
   response->data = (void *) &response[1];
   response->data_buffer_size = block_size;
-  if (MHD_YES != MHD_mutex_create_ (&response->mutex))
-    {
-      free (response);
-      return NULL;
-    }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if (! MHD_mutex_init_ (&response->mutex))
+  {
+    free (response);
+    return NULL;
+  }
+#endif
   response->crc = crc;
   response->crfc = crfc;
   response->crc_cls = crc_cls;
@@ -276,22 +1024,44 @@
  * @param ... #MHD_RO_END terminated list of options
  * @return #MHD_YES on success, #MHD_NO on error
  */
-int
+_MHD_EXTERN enum MHD_Result
 MHD_set_response_options (struct MHD_Response *response,
                           enum MHD_ResponseFlags flags,
                           ...)
 {
   va_list ap;
-  int ret;
+  enum MHD_Result ret;
   enum MHD_ResponseOptions ro;
 
+  if (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH))
+  { /* Response has custom "Content-Lengh" header */
+    if ( (0 != (response->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) &&
+         (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)))
+    { /* Request to remove MHD_RF_INSANITY_HEADER_CONTENT_LENGTH flag */
+      return MHD_NO;
+    }
+    if ( (0 != (response->flags & MHD_RF_HEAD_ONLY_RESPONSE)) &&
+         (0 == (flags & MHD_RF_HEAD_ONLY_RESPONSE)))
+    { /* Request to remove MHD_RF_HEAD_ONLY_RESPONSE flag */
+      if (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH))
+        return MHD_NO;
+    }
+  }
+
+  if ( (0 != (flags & MHD_RF_HEAD_ONLY_RESPONSE)) &&
+       (0 != response->total_size) )
+    return MHD_NO;
+
   ret = MHD_YES;
   response->flags = flags;
+
   va_start (ap, flags);
   while (MHD_RO_END != (ro = va_arg (ap, enum MHD_ResponseOptions)))
   {
     switch (ro)
     {
+    case MHD_RO_END: /* Not possible */
+      break;
     default:
       ret = MHD_NO;
       break;
@@ -313,13 +1083,118 @@
  * @return number of bytes written
  */
 static ssize_t
-file_reader (void *cls, uint64_t pos, char *buf, size_t max)
+file_reader (void *cls,
+             uint64_t pos,
+             char *buf,
+             size_t max)
+{
+  struct MHD_Response *response = cls;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+  ssize_t n;
+#else  /* _WIN32 && !__CYGWIN__ */
+  const HANDLE fh = (HANDLE) (uintptr_t) _get_osfhandle (response->fd);
+#endif /* _WIN32 && !__CYGWIN__ */
+  const int64_t offset64 = (int64_t) (pos + response->fd_off);
+
+  if (offset64 < 0)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */
+
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+  if (max > SSIZE_MAX)
+    max = SSIZE_MAX; /* Clamp to maximum return value. */
+
+#if defined(HAVE_PREAD64)
+  n = pread64 (response->fd, buf, max, offset64);
+#elif defined(HAVE_PREAD)
+  if ( (sizeof(off_t) < sizeof (uint64_t)) &&
+       (offset64 > (uint64_t) INT32_MAX) )
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* Read at required position is not possible. */
+
+  n = pread (response->fd, buf, max, (off_t) offset64);
+#else  /* ! HAVE_PREAD */
+#if defined(HAVE_LSEEK64)
+  if (lseek64 (response->fd,
+               offset64,
+               SEEK_SET) != offset64)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */
+#else  /* ! HAVE_LSEEK64 */
+  if ( (sizeof(off_t) < sizeof (uint64_t)) &&
+       (offset64 > (uint64_t) INT32_MAX) )
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */
+
+  if (lseek (response->fd,
+             (off_t) offset64,
+             SEEK_SET) != (off_t) offset64)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */
+#endif /* ! HAVE_LSEEK64 */
+  n = read (response->fd,
+            buf,
+            max);
+
+#endif /* ! HAVE_PREAD */
+  if (0 == n)
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  if (n < 0)
+    return MHD_CONTENT_READER_END_WITH_ERROR;
+  return n;
+#else /* _WIN32 && !__CYGWIN__ */
+  if (INVALID_HANDLE_VALUE == fh)
+    return MHD_CONTENT_READER_END_WITH_ERROR; /* Value of 'response->fd' is not valid. */
+  else
+  {
+    OVERLAPPED f_ol = {0, 0, {{0, 0}}, 0};   /* Initialize to zero. */
+    ULARGE_INTEGER pos_uli;
+    DWORD toRead = (max > INT32_MAX) ? INT32_MAX : (DWORD) max;
+    DWORD resRead;
+
+    pos_uli.QuadPart = (uint64_t) offset64;   /* Simple transformation 64bit -> 2x32bit. */
+    f_ol.Offset = pos_uli.LowPart;
+    f_ol.OffsetHigh = pos_uli.HighPart;
+    if (! ReadFile (fh, (void *) buf, toRead, &resRead, &f_ol))
+      return MHD_CONTENT_READER_END_WITH_ERROR;   /* Read error. */
+    if (0 == resRead)
+      return MHD_CONTENT_READER_END_OF_STREAM;
+    return (ssize_t) resRead;
+  }
+#endif /* _WIN32 && !__CYGWIN__ */
+}
+
+
+/**
+ * Given a pipe descriptor, read data from the pipe
+ * to generate the response.
+ *
+ * @param cls pointer to the response
+ * @param pos offset in the pipe to access (ignored)
+ * @param buf where to write the data
+ * @param max number of bytes to write at most
+ * @return number of bytes written
+ */
+static ssize_t
+pipe_reader (void *cls,
+             uint64_t pos,
+             char *buf,
+             size_t max)
 {
   struct MHD_Response *response = cls;
   ssize_t n;
 
-  (void) lseek (response->fd, pos + response->fd_off, SEEK_SET);
-  n = read (response->fd, buf, max);
+  (void) pos;
+
+#ifndef _WIN32
+  if (SSIZE_MAX < max)
+    max = SSIZE_MAX;
+  n = read (response->fd,
+            buf,
+            (MHD_SCKT_SEND_SIZE_) max);
+#else  /* _WIN32 */
+  if (UINT_MAX < max)
+    max = INT_MAX;
+  n = read (response->fd,
+            buf,
+            (unsigned int) max);
+#endif /* _WIN32 */
+
   if (0 == n)
     return MHD_CONTENT_READER_END_OF_STREAM;
   if (n < 0)
@@ -344,9 +1219,18 @@
 }
 
 
+#undef MHD_create_response_from_fd_at_offset
+
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the content of provided file with
+ * specified offset used as the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
  *
  * @param size size of the data portion of the response
  * @param fd file descriptor referring to a file on disk with the
@@ -360,21 +1244,70 @@
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @ingroup response
  */
-struct MHD_Response *
+_MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_fd_at_offset (size_t size,
-				       int fd,
-				       off_t offset)
+                                       int fd,
+                                       off_t offset)
+{
+  if (0 > offset)
+    return NULL;
+  return MHD_create_response_from_fd_at_offset64 (size,
+                                                  fd,
+                                                  (uint64_t) offset);
+}
+
+
+/**
+ * Create a response object with the content of provided file with
+ * specified offset used as the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response;
+ *        sizes larger than 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @param fd file descriptor referring to a file on disk with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @param offset offset to start reading from in the file;
+ *        reading file beyond 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_fd_at_offset64 (uint64_t size,
+                                         int fd,
+                                         uint64_t offset)
 {
   struct MHD_Response *response;
 
+#if ! defined(HAVE___LSEEKI64) && ! defined(HAVE_LSEEK64)
+  if ( (sizeof(uint64_t) > sizeof(off_t)) &&
+       ( (size > (uint64_t) INT32_MAX) ||
+         (offset > (uint64_t) INT32_MAX) ||
+         ((size + offset) >= (uint64_t) INT32_MAX) ) )
+    return NULL;
+#endif
+  if ( ((int64_t) size < 0) ||
+       ((int64_t) offset < 0) ||
+       ((int64_t) (size + offset) < 0) )
+    return NULL;
+
   response = MHD_create_response_from_callback (size,
-						4 * 1024,
-						&file_reader,
-						NULL,
-						&free_callback);
+                                                MHD_FILE_READ_BLOCK_SIZE,
+                                                &file_reader,
+                                                NULL,
+                                                &free_callback);
   if (NULL == response)
     return NULL;
   response->fd = fd;
+  response->is_pipe = false;
   response->fd_off = offset;
   response->crc_cls = response;
   return response;
@@ -382,80 +1315,145 @@
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the response body created by reading
+ * the provided pipe.
+ *
+ * The response object can be extended with header information and
+ * then be used ONLY ONCE.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param fd file descriptor referring to a read-end of a pipe with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_pipe (int fd)
+{
+  struct MHD_Response *response;
+
+  response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
+                                                MHD_FILE_READ_BLOCK_SIZE,
+                                                &pipe_reader,
+                                                NULL,
+                                                &free_callback);
+  if (NULL == response)
+    return NULL;
+  response->fd = fd;
+  response->is_pipe = true;
+  response->crc_cls = response;
+  return response;
+}
+
+
+/**
+ * Create a response object with the content of provided file used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
  *
  * @param size size of the data portion of the response
  * @param fd file descriptor referring to a file on disk with the data
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @ingroup response
  */
-struct MHD_Response *
+_MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_fd (size_t size,
-			     int fd)
+                             int fd)
 {
-  return MHD_create_response_from_fd_at_offset (size, fd, 0);
+  return MHD_create_response_from_fd_at_offset64 (size,
+                                                  fd,
+                                                  0);
 }
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the content of provided file used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response;
+ *        sizes larger than 2 GiB may be not supported by OS or
+ *        MHD build; see ::MHD_FEATURE_LARGE_FILE
+ * @param fd file descriptor referring to a file on disk with the
+ *        data; will be closed when response is destroyed;
+ *        fd should be in 'blocking' mode
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_fd64 (uint64_t size,
+                               int fd)
+{
+  return MHD_create_response_from_fd_at_offset64 (size,
+                                                  fd,
+                                                  0);
+}
+
+
+/**
+ * Create a response object.
+ * The response object can be extended with header information and then be used
+ * any number of times.
+ *
+ * If response object is used to answer HEAD request then the body of the
+ * response is not used, while all headers (including automatic headers) are
+ * used.
  *
  * @param size size of the @a data portion of the response
  * @param data the data itself
  * @param must_free libmicrohttpd should free data when done
  * @param must_copy libmicrohttpd must make a copy of @a data
- *        right away, the data maybe released anytime after
+ *        right away, the data may be released anytime after
  *        this call returns
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @deprecated use #MHD_create_response_from_buffer instead
  * @ingroup response
  */
-struct MHD_Response *
+_MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_data (size_t size,
-                               void *data, int must_free, int must_copy)
+                               void *data,
+                               int must_free,
+                               int must_copy)
 {
-  struct MHD_Response *response;
-  void *tmp;
+  enum MHD_ResponseMemoryMode mode;
 
-  if ((NULL == data) && (size > 0))
-    return NULL;
-  if (NULL == (response = malloc (sizeof (struct MHD_Response))))
-    return NULL;
-  memset (response, 0, sizeof (struct MHD_Response));
-  response->fd = -1;
-  if (MHD_YES != MHD_mutex_create_ (&response->mutex))
-    {
-      free (response);
-      return NULL;
-    }
-  if ((must_copy) && (size > 0))
-    {
-      if (NULL == (tmp = malloc (size)))
-        {
-          (void) MHD_mutex_destroy_ (&response->mutex);
-          free (response);
-          return NULL;
-        }
-      memcpy (tmp, data, size);
-      must_free = MHD_YES;
-      data = tmp;
-    }
-  response->crc = NULL;
-  response->crfc = must_free ? &free : NULL;
-  response->crc_cls = must_free ? data : NULL;
-  response->reference_count = 1;
-  response->total_size = size;
-  response->data = data;
-  response->data_size = size;
-  return response;
+  if (0 != must_copy)
+    mode = MHD_RESPMEM_MUST_COPY;
+  else if (0 != must_free)
+    mode = MHD_RESPMEM_MUST_FREE;
+  else
+    mode = MHD_RESPMEM_PERSISTENT;
+
+  return MHD_create_response_from_buffer (size, data, mode);
 }
 
 
 /**
- * Create a response object.  The response object can be extended with
- * header information and then be used any number of times.
+ * Create a response object with the content of provided buffer used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
  *
  * @param size size of the data portion of the response
  * @param buffer size bytes containing the response's data portion
@@ -463,62 +1461,875 @@
  * @return NULL on error (i.e. invalid arguments, out of memory)
  * @ingroup response
  */
-struct MHD_Response *
+_MHD_EXTERN struct MHD_Response *
 MHD_create_response_from_buffer (size_t size,
-				 void *buffer,
-				 enum MHD_ResponseMemoryMode mode)
+                                 void *buffer,
+                                 enum MHD_ResponseMemoryMode mode)
 {
-  return MHD_create_response_from_data (size,
-					buffer,
-					mode == MHD_RESPMEM_MUST_FREE,
-					mode == MHD_RESPMEM_MUST_COPY);
+  if (MHD_RESPMEM_MUST_FREE == mode)
+    return MHD_create_response_from_buffer_with_free_callback_cls (size,
+                                                                   buffer,
+                                                                   &free,
+                                                                   buffer);
+  if (MHD_RESPMEM_MUST_COPY == mode)
+    return MHD_create_response_from_buffer_copy (size,
+                                                 buffer);
+
+  return MHD_create_response_from_buffer_with_free_callback_cls (size,
+                                                                 buffer,
+                                                                 NULL,
+                                                                 NULL);
 }
 
 
 /**
+ * Create a response object with the content of provided statically allocated
+ * buffer used as the response body.
+ *
+ * The buffer must be valid for the lifetime of the response. The easiest way
+ * to achieve this is to use a statically allocated buffer.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size the size of the data in @a buffer, can be zero
+ * @param buffer the buffer with the data for the response body, can be NULL
+ *               if @a size is zero
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097506
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_static (size_t size,
+                                        const void *buffer)
+{
+  return MHD_create_response_from_buffer_with_free_callback_cls (size,
+                                                                 buffer,
+                                                                 NULL,
+                                                                 NULL);
+}
+
+
+/**
+ * Create a response object with the content of provided temporal buffer
+ * used as the response body.
+ *
+ * An internal copy of the buffer will be made automatically, so buffer have
+ * to be valid only during the call of this function (as a typical example:
+ * buffer is a local (non-static) array).
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size the size of the data in @a buffer, can be zero
+ * @param buffer the buffer with the data for the response body, can be NULL
+ *               if @a size is zero
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097507
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_copy (size_t size,
+                                      const void *buffer)
+{
+  struct MHD_Response *r;
+  void *mhd_copy;
+
+  if (0 == size)
+    return MHD_create_response_from_buffer_with_free_callback_cls (0,
+                                                                   NULL,
+                                                                   NULL,
+                                                                   NULL);
+  if (NULL == buffer)
+    return NULL;
+
+  mhd_copy = malloc (size);
+  if (NULL == mhd_copy)
+    return NULL;
+  memcpy (mhd_copy, buffer, size);
+
+  r = MHD_create_response_from_buffer_with_free_callback_cls (size,
+                                                              mhd_copy,
+                                                              &free,
+                                                              mhd_copy);
+  if (NULL == r)
+    free (mhd_copy);
+  else
+  {
+    /* TODO: remove the next assignment, the buffer should not be modifiable */
+    r->data_buffer_size = size;
+  }
+
+  return r;
+}
+
+
+/**
+ * Create a response object with the content of provided buffer used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response
+ * @param buffer size bytes containing the response's data portion
+ * @param crfc function to call to free the @a buffer
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_with_free_callback (size_t size,
+                                                    void *buffer,
+                                                    MHD_ContentReaderFreeCallback
+                                                    crfc)
+{
+  return MHD_create_response_from_buffer_with_free_callback_cls (size,
+                                                                 buffer,
+                                                                 crfc,
+                                                                 buffer);
+}
+
+
+/**
+ * Create a response object with the content of provided buffer used as
+ * the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param size size of the data portion of the response
+ * @param buffer size bytes containing the response's data portion
+ * @param crfc function to call to cleanup, if set to NULL then callback
+ *             is not called
+ * @param crfc_cls an argument for @a crfc
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ * @note Available since #MHD_VERSION 0x00097302
+ * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097504
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_buffer_with_free_callback_cls (size_t size,
+                                                        const void *buffer,
+                                                        MHD_ContentReaderFreeCallback
+                                                        crfc,
+                                                        void *crfc_cls)
+{
+  struct MHD_Response *r;
+
+  if ((NULL == buffer) && (size > 0))
+    return NULL;
+#if SIZEOF_SIZE_T >= SIZEOF_UINT64_T
+  if (MHD_SIZE_UNKNOWN == size)
+    return NULL;
+#endif /* SIZEOF_SIZE_T >= SIZEOF_UINT64_T */
+  r = MHD_calloc_ (1, sizeof (struct MHD_Response));
+  if (NULL == r)
+    return NULL;
+#if defined(MHD_USE_THREADS)
+  if (! MHD_mutex_init_ (&r->mutex))
+  {
+    free (r);
+    return NULL;
+  }
+#endif
+  r->fd = -1;
+  r->reference_count = 1;
+  r->total_size = size;
+  r->data = buffer;
+  r->data_size = size;
+  r->crfc = crfc;
+  r->crc_cls = crfc_cls;
+  return r;
+}
+
+
+/**
+ * Create a response object with an array of memory buffers
+ * used as the response body.
+ *
+ * The response object can be extended with header information and then
+ * be used any number of times.
+ *
+ * If response object is used to answer HEAD request then the body
+ * of the response is not used, while all headers (including automatic
+ * headers) are used.
+ *
+ * @param iov the array for response data buffers, an internal copy of this
+ *        will be made
+ * @param iovcnt the number of elements in @a iov
+ * @param free_cb the callback to clean up any data associated with @a iov when
+ *        the response is destroyed.
+ * @param cls the argument passed to @a free_cb
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_from_iovec (const struct MHD_IoVec *iov,
+                                unsigned int iovcnt,
+                                MHD_ContentReaderFreeCallback free_cb,
+                                void *cls)
+{
+  struct MHD_Response *response;
+  unsigned int i;
+  int i_cp = 0;   /**< Index in the copy of iov */
+  uint64_t total_size = 0;
+  const void *last_valid_buffer = NULL;
+
+  if ((NULL == iov) && (0 < iovcnt))
+    return NULL;
+
+  response = MHD_calloc_ (1, sizeof (struct MHD_Response));
+  if (NULL == response)
+    return NULL;
+  if (! MHD_mutex_init_ (&response->mutex))
+  {
+    free (response);
+    return NULL;
+  }
+  /* Calculate final size, number of valid elements, and check 'iov' */
+  for (i = 0; i < iovcnt; ++i)
+  {
+    if (0 == iov[i].iov_len)
+      continue;     /* skip zero-sized elements */
+    if (NULL == iov[i].iov_base)
+    {
+      i_cp = -1;     /* error */
+      break;
+    }
+    if ( (total_size > (total_size + iov[i].iov_len)) ||
+         (INT_MAX == i_cp) ||
+         (SSIZE_MAX < (total_size + iov[i].iov_len)) )
+    {
+      i_cp = -1;     /* overflow */
+      break;
+    }
+    last_valid_buffer = iov[i].iov_base;
+    total_size += iov[i].iov_len;
+#if defined(MHD_POSIX_SOCKETS) || ! defined(_WIN64)
+    i_cp++;
+#else  /* ! MHD_POSIX_SOCKETS && _WIN64 */
+    {
+      int64_t i_add;
+
+      i_add = (int64_t) (iov[i].iov_len / ULONG_MAX);
+      if (0 != iov[i].iov_len % ULONG_MAX)
+        i_add++;
+      if (INT_MAX < (i_add + i_cp))
+      {
+        i_cp = -1;   /* overflow */
+        break;
+      }
+      i_cp += (int) i_add;
+    }
+#endif /* ! MHD_POSIX_SOCKETS && _WIN64 */
+  }
+  if (-1 == i_cp)
+  {
+    /* Some error condition */
+    MHD_mutex_destroy_chk_ (&response->mutex);
+    free (response);
+    return NULL;
+  }
+  response->fd = -1;
+  response->reference_count = 1;
+  response->total_size = total_size;
+  response->crc_cls = cls;
+  response->crfc = free_cb;
+  if (0 == i_cp)
+  {
+    mhd_assert (0 == total_size);
+    return response;
+  }
+  if (1 == i_cp)
+  {
+    mhd_assert (NULL != last_valid_buffer);
+    response->data = last_valid_buffer;
+    response->data_size = (size_t) total_size;
+    return response;
+  }
+  mhd_assert (1 < i_cp);
+  if (1)
+  { /* for local variables local scope only */
+    MHD_iovec_ *iov_copy;
+    int num_copy_elements = i_cp;
+
+    iov_copy = MHD_calloc_ ((size_t) num_copy_elements, \
+                            sizeof(MHD_iovec_));
+    if (NULL == iov_copy)
+    {
+      MHD_mutex_destroy_chk_ (&response->mutex);
+      free (response);
+      return NULL;
+    }
+    i_cp = 0;
+    for (i = 0; i < iovcnt; ++i)
+    {
+      size_t element_size = iov[i].iov_len;
+      const uint8_t *buf = (const uint8_t *) iov[i].iov_base;
+
+      if (0 == element_size)
+        continue;         /* skip zero-sized elements */
+#if defined(MHD_WINSOCK_SOCKETS) && defined(_WIN64)
+      while (MHD_IOV_ELMN_MAX_SIZE < element_size)
+      {
+        iov_copy[i_cp].iov_base = (char *) _MHD_DROP_CONST (buf);
+        iov_copy[i_cp].iov_len = ULONG_MAX;
+        buf += ULONG_MAX;
+        element_size -= ULONG_MAX;
+        i_cp++;
+      }
+#endif /* MHD_WINSOCK_SOCKETS && _WIN64 */
+      iov_copy[i_cp].iov_base = _MHD_DROP_CONST (buf);
+      iov_copy[i_cp].iov_len = (MHD_iov_size_) element_size;
+      i_cp++;
+    }
+    mhd_assert (num_copy_elements == i_cp);
+    mhd_assert (0 <= i_cp);
+    response->data_iov = iov_copy;
+    response->data_iovcnt = (unsigned int) i_cp;
+  }
+  return response;
+}
+
+
+/**
+ * Create a response object with empty (zero size) body.
+ *
+ * The response object can be extended with header information and then be used
+ * any number of times.
+ *
+ * This function is a faster equivalent of #MHD_create_response_from_buffer call
+ * with zero size combined with call of #MHD_set_response_options.
+ *
+ * @param flags the flags for the new response object
+ * @return NULL on error (i.e. invalid arguments, out of memory),
+ *         the pointer to the created response object otherwise
+ * @note Available since #MHD_VERSION 0x00097503
+ * @ingroup response
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_empty (enum MHD_ResponseFlags flags)
+{
+  struct MHD_Response *r;
+  r = (struct MHD_Response *) MHD_calloc_ (1, sizeof (struct MHD_Response));
+  if (NULL != r)
+  {
+    if (MHD_mutex_init_ (&r->mutex))
+    {
+      r->fd = -1;
+      r->reference_count = 1;
+      /* If any flags combination will be not allowed, replace the next
+       * assignment with MHD_set_response_options() call. */
+      r->flags = flags;
+
+      return r; /* Successful result */
+    }
+    free (r);
+  }
+  return NULL; /* Something failed */
+}
+
+
+#ifdef UPGRADE_SUPPORT
+/**
+ * This connection-specific callback is provided by MHD to
+ * applications (unusual) during the #MHD_UpgradeHandler.
+ * It allows applications to perform 'special' actions on
+ * the underlying socket from the upgrade.
+ *
+ * @param urh the handle identifying the connection to perform
+ *            the upgrade @a action on.
+ * @param action which action should be performed
+ * @param ... arguments to the action (depends on the action)
+ * @return #MHD_NO on error, #MHD_YES on success
+ */
+_MHD_EXTERN enum MHD_Result
+MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh,
+                    enum MHD_UpgradeAction action,
+                    ...)
+{
+  struct MHD_Connection *connection;
+  struct MHD_Daemon *daemon;
+
+  if (NULL == urh)
+    return MHD_NO;
+  connection = urh->connection;
+
+  /* Precaution checks on external data. */
+  if (NULL == connection)
+    return MHD_NO;
+  daemon = connection->daemon;
+  if (NULL == daemon)
+    return MHD_NO;
+
+  switch (action)
+  {
+  case MHD_UPGRADE_ACTION_CLOSE:
+    if (urh->was_closed)
+      return MHD_NO; /* Already closed. */
+
+    /* transition to special 'closed' state for start of cleanup */
+#ifdef HTTPS_SUPPORT
+    if (0 != (daemon->options & MHD_USE_TLS) )
+    {
+      /* signal that app is done by shutdown() of 'app' socket */
+      /* Application will not use anyway this socket after this command. */
+      shutdown (urh->app.socket,
+                SHUT_RDWR);
+    }
+#endif /* HTTPS_SUPPORT */
+    mhd_assert (MHD_CONNECTION_UPGRADE == connection->state);
+    /* The next function will mark the connection as closed by application
+     * by setting 'urh->was_closed'.
+     * As soon as connection will be marked with BOTH
+     * 'urh->was_closed' AND 'urh->clean_ready', it will
+     * be moved to cleanup list by MHD_resume_connection(). */
+    MHD_upgraded_connection_mark_app_closed_ (connection);
+    return MHD_YES;
+  case MHD_UPGRADE_ACTION_CORK_ON:
+    /* Unportable API. TODO: replace with portable action. */
+    return MHD_connection_set_cork_state_ (connection,
+                                           true) ? MHD_YES : MHD_NO;
+  case MHD_UPGRADE_ACTION_CORK_OFF:
+    /* Unportable API. TODO: replace with portable action. */
+    return MHD_connection_set_cork_state_ (connection,
+                                           false) ? MHD_YES : MHD_NO;
+  default:
+    /* we don't understand this one */
+    return MHD_NO;
+  }
+}
+
+
+/**
+ * We are done sending the header of a given response to the client.
+ * Now it is time to perform the upgrade and hand over the connection
+ * to the application.
+ * @remark To be called only from thread that process connection's
+ * recv(), send() and response. Must be called right after sending
+ * response headers.
+ *
+ * @param response the response that was created for an upgrade
+ * @param connection the specific connection we are upgrading
+ * @return #MHD_YES on success, #MHD_NO on failure (will cause
+ *        connection to be closed)
+ */
+enum MHD_Result
+MHD_response_execute_upgrade_ (struct MHD_Response *response,
+                               struct MHD_Connection *connection)
+{
+  struct MHD_Daemon *daemon = connection->daemon;
+  struct MHD_UpgradeResponseHandle *urh;
+  size_t rbo;
+
+#ifdef MHD_USE_THREADS
+  mhd_assert ( (0 == (daemon->options & MHD_USE_INTERNAL_POLLING_THREAD)) || \
+               MHD_thread_ID_match_current_ (connection->pid) );
+#endif /* MHD_USE_THREADS */
+
+  /* "Upgrade" responses accepted only if MHD_ALLOW_UPGRADE is enabled */
+  mhd_assert (0 != (daemon->options & MHD_ALLOW_UPGRADE));
+  /* The header was checked when response queued */
+  mhd_assert (NULL != \
+              MHD_get_response_element_n_ (response, MHD_HEADER_KIND,
+                                           MHD_HTTP_HEADER_UPGRADE,
+                                           MHD_STATICSTR_LEN_ ( \
+                                             MHD_HTTP_HEADER_UPGRADE)));
+
+  urh = MHD_calloc_ (1, sizeof (struct MHD_UpgradeResponseHandle));
+  if (NULL == urh)
+    return MHD_NO;
+  urh->connection = connection;
+  rbo = connection->read_buffer_offset;
+  connection->read_buffer_offset = 0;
+  MHD_connection_set_nodelay_state_ (connection, false);
+  MHD_connection_set_cork_state_ (connection, false);
+#ifdef HTTPS_SUPPORT
+  if (0 != (daemon->options & MHD_USE_TLS) )
+  {
+    MHD_socket sv[2];
+#if defined(MHD_socket_nosignal_) || ! defined(MHD_socket_pair_nblk_)
+    int res1;
+    int res2;
+#endif /* MHD_socket_nosignal_ || !MHD_socket_pair_nblk_ */
+
+#ifdef MHD_socket_pair_nblk_
+    if (! MHD_socket_pair_nblk_ (sv))
+    {
+      free (urh);
+      return MHD_NO;
+    }
+#else  /* !MHD_socket_pair_nblk_ */
+    if (! MHD_socket_pair_ (sv))
+    {
+      free (urh);
+      return MHD_NO;
+    }
+    res1 = MHD_socket_nonblocking_ (sv[0]);
+    res2 = MHD_socket_nonblocking_ (sv[1]);
+    if ( (! res1) || (! res2) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to make loopback sockets non-blocking.\n"));
+#endif
+      if (! res2)
+      {
+        /* Socketpair cannot be used. */
+        MHD_socket_close_chk_ (sv[0]);
+        MHD_socket_close_chk_ (sv[1]);
+        free (urh);
+        return MHD_NO;
+      }
+    }
+#endif /* !MHD_socket_pair_nblk_ */
+#ifdef MHD_socket_nosignal_
+    res1 = MHD_socket_nosignal_ (sv[0]);
+    res2 = MHD_socket_nosignal_ (sv[1]);
+    if ( (! res1) || (! res2) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Failed to set SO_NOSIGPIPE on loopback sockets.\n"));
+#endif
+#ifndef MSG_NOSIGNAL
+      if (! res2)
+      {
+        /* Socketpair cannot be used. */
+        MHD_socket_close_chk_ (sv[0]);
+        MHD_socket_close_chk_ (sv[1]);
+        free (urh);
+        return MHD_NO;
+      }
+#endif /* ! MSG_NOSIGNAL */
+    }
+#endif /* MHD_socket_nosignal_ */
+    if ( (! MHD_SCKT_FD_FITS_FDSET_ (sv[1],
+                                     NULL)) &&
+         (0 == (daemon->options & (MHD_USE_POLL | MHD_USE_EPOLL))) )
+    {
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Socketpair descriptor larger than FD_SETSIZE: %d > %d\n"),
+                (int) sv[1],
+                (int) FD_SETSIZE);
+#endif
+      MHD_socket_close_chk_ (sv[0]);
+      MHD_socket_close_chk_ (sv[1]);
+      free (urh);
+      return MHD_NO;
+    }
+    urh->app.socket = sv[0];
+    urh->app.urh = urh;
+    urh->app.celi = MHD_EPOLL_STATE_UNREADY;
+    urh->mhd.socket = sv[1];
+    urh->mhd.urh = urh;
+    urh->mhd.celi = MHD_EPOLL_STATE_UNREADY;
+#ifdef EPOLL_SUPPORT
+    /* Launch IO processing by the event loop */
+    if (0 != (daemon->options & MHD_USE_EPOLL))
+    {
+      /* We're running with epoll(), need to add the sockets
+         to the event set of the daemon's `epoll_upgrade_fd` */
+      struct epoll_event event;
+
+      mhd_assert (-1 != daemon->epoll_upgrade_fd);
+      /* First, add network socket */
+      event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
+      event.data.ptr = &urh->app;
+      if (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                          EPOLL_CTL_ADD,
+                          connection->socket_fd,
+                          &event))
+      {
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Call to epoll_ctl failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+        MHD_socket_close_chk_ (sv[0]);
+        MHD_socket_close_chk_ (sv[1]);
+        free (urh);
+        return MHD_NO;
+      }
+
+      /* Second, add our end of the UNIX socketpair() */
+      event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET;
+      event.data.ptr = &urh->mhd;
+      if (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                          EPOLL_CTL_ADD,
+                          urh->mhd.socket,
+                          &event))
+      {
+        event.events = EPOLLIN | EPOLLOUT | EPOLLPRI;
+        event.data.ptr = &urh->app;
+        if (0 != epoll_ctl (daemon->epoll_upgrade_fd,
+                            EPOLL_CTL_DEL,
+                            connection->socket_fd,
+                            &event))
+          MHD_PANIC (_ ("Error cleaning up while handling epoll error.\n"));
+#ifdef HAVE_MESSAGES
+        MHD_DLOG (daemon,
+                  _ ("Call to epoll_ctl failed: %s\n"),
+                  MHD_socket_last_strerr_ ());
+#endif
+        MHD_socket_close_chk_ (sv[0]);
+        MHD_socket_close_chk_ (sv[1]);
+        free (urh);
+        return MHD_NO;
+      }
+      EDLL_insert (daemon->eready_urh_head,
+                   daemon->eready_urh_tail,
+                   urh);
+      urh->in_eready_list = true;
+    }
+#endif /* EPOLL_SUPPORT */
+    if (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION) )
+    {
+      /* This takes care of further processing for most event loops:
+         simply add to DLL for bi-direcitonal processing */
+      DLL_insert (daemon->urh_head,
+                  daemon->urh_tail,
+                  urh);
+    }
+    /* In thread-per-connection mode, thread will switch to forwarding once
+     * connection.urh is not NULL and connection.state == MHD_CONNECTION_UPGRADE.
+     */
+  }
+  else
+  {
+    urh->app.socket = MHD_INVALID_SOCKET;
+    urh->mhd.socket = MHD_INVALID_SOCKET;
+    /* Non-TLS connection do not hold any additional resources. */
+    urh->clean_ready = true;
+  }
+#else  /* ! HTTPS_SUPPORT */
+  urh->clean_ready = true;
+#endif /* ! HTTPS_SUPPORT */
+  connection->urh = urh;
+  /* As far as MHD's event loops are concerned, this connection is
+     suspended; it will be resumed once application is done by the
+     #MHD_upgrade_action() function */
+  internal_suspend_connection_ (connection);
+
+  /* hand over socket to application */
+  response->upgrade_handler (response->upgrade_handler_cls,
+                             connection,
+                             connection->rq.client_context,
+                             connection->read_buffer,
+                             rbo,
+#ifdef HTTPS_SUPPORT
+                             (0 == (daemon->options & MHD_USE_TLS) ) ?
+                             connection->socket_fd : urh->app.socket,
+#else  /* ! HTTPS_SUPPORT */
+                             connection->socket_fd,
+#endif /* ! HTTPS_SUPPORT */
+                             urh);
+
+#ifdef HTTPS_SUPPORT
+  if (0 != (daemon->options & MHD_USE_TLS))
+  {
+    struct MemoryPool *const pool = connection->pool;
+    size_t avail;
+    char *buf;
+
+    /* All data should be sent already */
+    mhd_assert (connection->write_buffer_send_offset == \
+                connection->write_buffer_append_offset);
+    MHD_pool_deallocate (pool, connection->write_buffer,
+                         connection->write_buffer_size);
+    connection->write_buffer_append_offset = 0;
+    connection->write_buffer_send_offset = 0;
+    connection->write_buffer_size = 0;
+    connection->write_buffer = NULL;
+
+    /* Extra read data should be processed already by the application */
+    MHD_pool_deallocate (pool, connection->read_buffer,
+                         connection->read_buffer_size);
+    connection->read_buffer_offset = 0;
+    connection->read_buffer_size = 0;
+    connection->read_buffer = NULL;
+
+    avail = MHD_pool_get_free (pool);
+    if (avail < RESERVE_EBUF_SIZE)
+    {
+      /* connection's pool is totally at the limit,
+         use our 'emergency' buffer of #RESERVE_EBUF_SIZE bytes. */
+      avail = RESERVE_EBUF_SIZE;
+      buf = urh->e_buf;
+#ifdef HAVE_MESSAGES
+      MHD_DLOG (daemon,
+                _ ("Memory shortage in connection's memory pool. " \
+                   "The \"upgraded\" communication will be inefficient.\n"));
+#endif
+    }
+    else
+    {
+      /* Normal case: grab all remaining memory from the
+         connection's pool for the IO buffers; the connection
+         certainly won't need it anymore as we've upgraded
+         to another protocol. */
+      buf = MHD_pool_allocate (pool,
+                               avail,
+                               false);
+    }
+    /* use half the buffer for inbound, half for outbound */
+    urh->in_buffer_size = avail / 2;
+    urh->out_buffer_size = avail - urh->in_buffer_size;
+    urh->in_buffer = buf;
+    urh->out_buffer = buf + urh->in_buffer_size;
+  }
+#endif /* HTTPS_SUPPORT */
+  return MHD_YES;
+}
+
+
+/**
+ * Create a response object that can be used for 101 UPGRADE
+ * responses, for example to implement WebSockets.  After sending the
+ * response, control over the data stream is given to the callback (which
+ * can then, for example, start some bi-directional communication).
+ * If the response is queued for multiple connections, the callback
+ * will be called for each connection.  The callback
+ * will ONLY be called after the response header was successfully passed
+ * to the OS; if there are communication errors before, the usual MHD
+ * connection error handling code will be performed.
+ *
+ * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS)
+ * and setting correct HTTP headers for the upgrade must be done
+ * manually (this way, it is possible to implement most existing
+ * WebSocket versions using this API; in fact, this API might be useful
+ * for any protocol switch, not just WebSockets).  Note that
+ * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this
+ * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake"
+ * cannot be generated; instead, MHD will always produce "HTTP/1.1 101
+ * Switching Protocols" (if the response code 101 is used).
+ *
+ * As usual, the response object can be extended with header
+ * information and then be used any number of times (as long as the
+ * header information is not connection-specific).
+ *
+ * @param upgrade_handler function to call with the 'upgraded' socket
+ * @param upgrade_handler_cls closure for @a upgrade_handler
+ * @return NULL on error (i.e. invalid arguments, out of memory)
+ */
+_MHD_EXTERN struct MHD_Response *
+MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler,
+                                 void *upgrade_handler_cls)
+{
+  struct MHD_Response *response;
+
+  if (NULL == upgrade_handler)
+    return NULL; /* invalid request */
+  response = MHD_calloc_ (1, sizeof (struct MHD_Response));
+  if (NULL == response)
+    return NULL;
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if (! MHD_mutex_init_ (&response->mutex))
+  {
+    free (response);
+    return NULL;
+  }
+#endif
+  response->upgrade_handler = upgrade_handler;
+  response->upgrade_handler_cls = upgrade_handler_cls;
+  response->total_size = 0;
+  response->reference_count = 1;
+  if (MHD_NO ==
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_CONNECTION,
+                               "Upgrade"))
+  {
+    MHD_destroy_response (response);
+    return NULL;
+  }
+  return response;
+}
+
+
+#endif /* UPGRADE_SUPPORT */
+
+
+/**
  * Destroy a response object and associated resources.  Note that
  * libmicrohttpd may keep some of the resources around if the response
  * is still in the queue for some clients, so the memory may not
- * necessarily be freed immediatley.
+ * necessarily be freed immediately.
  *
  * @param response response to destroy
  * @ingroup response
  */
-void
+_MHD_EXTERN void
 MHD_destroy_response (struct MHD_Response *response)
 {
-  struct MHD_HTTP_Header *pos;
+  struct MHD_HTTP_Res_Header *pos;
 
   if (NULL == response)
     return;
-  (void) MHD_mutex_lock_ (&response->mutex);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&response->mutex);
+#endif
   if (0 != --(response->reference_count))
-    {
-      (void) MHD_mutex_unlock_ (&response->mutex);
-      return;
-    }
-  (void) MHD_mutex_unlock_ (&response->mutex);
-  (void) MHD_mutex_destroy_ (&response->mutex);
-  if (response->crfc != NULL)
+  {
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+    MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
+    return;
+  }
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&response->mutex);
+  MHD_mutex_destroy_chk_ (&response->mutex);
+#endif
+  if (NULL != response->crfc)
     response->crfc (response->crc_cls);
+
+  if (NULL != response->data_iov)
+  {
+    free (response->data_iov);
+  }
+
   while (NULL != response->first_header)
-    {
-      pos = response->first_header;
-      response->first_header = pos->next;
-      free (pos->header);
-      free (pos->value);
-      free (pos);
-    }
+  {
+    pos = response->first_header;
+    response->first_header = pos->next;
+    free (pos->header);
+    free (pos->value);
+    free (pos);
+  }
   free (response);
 }
 
 
+/**
+ * Increments the reference counter for the @a response.
+ *
+ * @param response object to modify
+ */
 void
 MHD_increment_response_rc (struct MHD_Response *response)
 {
-  (void) MHD_mutex_lock_ (&response->mutex);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_lock_chk_ (&response->mutex);
+#endif
   (response->reference_count)++;
-  (void) MHD_mutex_unlock_ (&response->mutex);
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  MHD_mutex_unlock_chk_ (&response->mutex);
+#endif
 }
 
 
diff --git a/src/microhttpd/response.h b/src/microhttpd/response.h
index 5785ec9..ad614c1 100644
--- a/src/microhttpd/response.h
+++ b/src/microhttpd/response.h
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Daniel Pittman and Christian Grothoff
+     Copyright (C) 2015-2022 Karlson2k (Evgeny Grin)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -22,17 +23,103 @@
  * @brief  Methods for managing response objects
  * @author Daniel Pittman
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #ifndef RESPONSE_H
 #define RESPONSE_H
 
 /**
- * Increment response RC.  Should this be part of the
- * public API?
+ * Increments the reference counter for the @a response.
+ *
+ * @param response object to modify
  */
 void
 MHD_increment_response_rc (struct MHD_Response *response);
 
 
+/**
+ * We are done sending the header of a given response
+ * to the client.  Now it is time to perform the upgrade
+ * and hand over the connection to the application.
+ * @remark To be called only from thread that process connection's
+ * recv(), send() and response. Must be called right after sending
+ * response headers.
+ *
+ * @param response the response that was created for an upgrade
+ * @param connection the specific connection we are upgrading
+ * @return #MHD_YES on success, #MHD_NO on failure (will cause
+ *        connection to be closed)
+ */
+enum MHD_Result
+MHD_response_execute_upgrade_ (struct MHD_Response *response,
+                               struct MHD_Connection *connection);
+
+
+/**
+ * Get a particular header (or footer) element from the response.
+ *
+ * Function returns the first found element.
+ * @param response response to query
+ * @param kind the kind of element: header or footer
+ * @param key the key which header to get
+ * @param key_len the length of the @a key
+ * @return NULL if header element does not exist
+ * @ingroup response
+ */
+struct MHD_HTTP_Res_Header *
+MHD_get_response_element_n_ (struct MHD_Response *response,
+                             enum MHD_ValueKind kind,
+                             const char *key,
+                             size_t key_len);
+
+/**
+ * Add a header or footer line to the response without checking.
+ *
+ * It is assumed that parameters are correct.
+ *
+ * @param response response to add a header to
+ * @param kind header or footer
+ * @param header the header to add, does not need to be zero-terminated
+ * @param header_len the length of the @a header
+ * @param content value to add, does not need to be zero-terminated
+ * @param content_len the length of the @a content
+ * @return false on error (like out-of-memory),
+ *         true if succeed
+ */
+bool
+MHD_add_response_entry_no_check_ (struct MHD_Response *response,
+                                  enum MHD_ValueKind kind,
+                                  const char *header,
+                                  size_t header_len,
+                                  const char *content,
+                                  size_t content_len);
+
+/**
+ * Add preallocated strings a header or footer line to the response without
+ * checking.
+ *
+ * Header/footer strings are not checked and assumed to be correct.
+ *
+ * The string must not be statically allocated!
+ * The strings must be malloc()'ed and zero terminated. The strings will
+ * be free()'ed when the response is destroyed.
+ *
+ * @param response response to add a header to
+ * @param kind header or footer
+ * @param header the header string to add, must be malloc()'ed and
+ *               zero-terminated
+ * @param header_len the length of the @a header
+ * @param content the value string to add, must be malloc()'ed and
+ *                zero-terminated
+ * @param content_len the length of the @a content
+ */
+bool
+MHD_add_response_entry_no_alloc_ (struct MHD_Response *response,
+                                  enum MHD_ValueKind kind,
+                                  char *header,
+                                  size_t header_len,
+                                  char *content,
+                                  size_t content_len);
+
 #endif
diff --git a/src/microhttpd/sha1.c b/src/microhttpd/sha1.c
new file mode 100644
index 0000000..be9f73a
--- /dev/null
+++ b/src/microhttpd/sha1.c
@@ -0,0 +1,383 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019-2021 Karlson2k (Evgeny Grin)
+
+     libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha1.c
+ * @brief  Calculation of SHA-1 digest as defined in FIPS PUB 180-4 (2015)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "sha1.h"
+
+#include <string.h>
+#ifdef HAVE_MEMORY_H
+#include <memory.h>
+#endif /* HAVE_MEMORY_H */
+#include "mhd_bithelpers.h"
+#include "mhd_assert.h"
+
+/**
+ * Initialise structure for SHA-1 calculation.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ */
+void
+MHD_SHA1_init (void *ctx_)
+{
+  struct sha1_ctx *const ctx = ctx_;
+  /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.1 */
+  /* Just some "magic" numbers defined by standard */
+  ctx->H[0] = UINT32_C (0x67452301);
+  ctx->H[1] = UINT32_C (0xefcdab89);
+  ctx->H[2] = UINT32_C (0x98badcfe);
+  ctx->H[3] = UINT32_C (0x10325476);
+  ctx->H[4] = UINT32_C (0xc3d2e1f0);
+
+  /* Initialise number of bytes. */
+  ctx->count = 0;
+}
+
+
+/**
+ * Base of SHA-1 transformation.
+ * Gets full 512 bits / 64 bytes block of data and updates hash values;
+ * @param H     hash values
+ * @param data  data, must be exactly 64 bytes long
+ */
+static void
+sha1_transform (uint32_t H[_SHA1_DIGEST_LENGTH],
+                const uint8_t data[SHA1_BLOCK_SIZE])
+{
+  /* Working variables,
+     see FIPS PUB 180-4 paragraph 6.1.3 */
+  uint32_t a = H[0];
+  uint32_t b = H[1];
+  uint32_t c = H[2];
+  uint32_t d = H[3];
+  uint32_t e = H[4];
+
+  /* Data buffer, used as cyclic buffer.
+     See FIPS PUB 180-4 paragraphs 5.2.1, 6.1.3 */
+  uint32_t W[16];
+
+  /* 'Ch' and 'Maj' macro functions are defined with
+     widely-used optimization.
+     See FIPS PUB 180-4 formulae 4.1. */
+#define Ch(x,y,z)     ( (z) ^ ((x) & ((y) ^ (z))) )
+#define Maj(x,y,z)    ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) )
+  /* Unoptimized (original) versions: */
+/* #define Ch(x,y,z)  ( ( (x) & (y) ) ^ ( ~(x) & (z) ) )          */
+/* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */
+#define Par(x,y,z)    ( (x) ^ (y) ^ (z) )
+
+  /* Single step of SHA-1 computation,
+     see FIPS PUB 180-4 paragraph 6.1.3 step 3.
+   * Note: instead of reassigning all working variables on each step,
+           variables are rotated for each step:
+             SHA1STEP32 (a, b, c, d, e, func, K00, W[0]);
+             SHA1STEP32 (e, a, b, c, d, func, K00, W[1]);
+           so current 'vC' will be used as 'vD' on the next step,
+           current 'vE' will be used as 'vA' on the next step.
+   * Note: 'wt' must be used exactly one time in this macro as it change other data as well
+           every time when used. */
+
+#define SHA1STEP32(vA,vB,vC,vD,vE,ft,kt,wt) do {                         \
+    (vE) += _MHD_ROTL32 ((vA), 5) + ft ((vB), (vC), (vD)) + (kt) + (wt); \
+    (vB) = _MHD_ROTL32 ((vB), 30); } while (0)
+
+  /* Get value of W(t) from input data buffer,
+     See FIPS PUB 180-4 paragraph 6.1.3.
+     Input data must be read in big-endian bytes order,
+     see FIPS PUB 180-4 paragraph 3.1.2. */
+  /* Use cast to (void*) to mute compiler alignment warning,
+   * data was already aligned in previous step */
+#define GET_W_FROM_DATA(buf,t) \
+  _MHD_GET_32BIT_BE ((const void *)(((const uint8_t*) (buf)) + \
+                                    (t) * SHA1_BYTES_IN_WORD))
+
+#ifndef _MHD_GET_32BIT_BE_UNALIGNED
+  if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN))
+  {
+    /* Copy the unaligned input data to the aligned buffer */
+    memcpy (W, data, SHA1_BLOCK_SIZE);
+    /* The W[] buffer itself will be used as the source of the data,
+     * but data will be reloaded in correct bytes order during
+     * the next steps */
+    data = (uint8_t *) W;
+  }
+#endif /* _MHD_GET_32BIT_BE_UNALIGNED */
+
+/* SHA-1 values of Kt for t=0..19, see FIPS PUB 180-4 paragraph 4.2.1. */
+#define K00      UINT32_C(0x5a827999)
+/* SHA-1 values of Kt for t=20..39, see FIPS PUB 180-4 paragraph 4.2.1.*/
+#define K20      UINT32_C(0x6ed9eba1)
+/* SHA-1 values of Kt for t=40..59, see FIPS PUB 180-4 paragraph 4.2.1.*/
+#define K40      UINT32_C(0x8f1bbcdc)
+/* SHA-1 values of Kt for t=60..79, see FIPS PUB 180-4 paragraph 4.2.1.*/
+#define K60      UINT32_C(0xca62c1d6)
+
+  /* During first 16 steps, before making any calculations on each step,
+     the W element is read from input data buffer as big-endian value and
+     stored in array of W elements. */
+  /* Note: instead of using K constants as array, all K values are specified
+     individually for each step. */
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[0] = GET_W_FROM_DATA (data, 0));
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[1] = GET_W_FROM_DATA (data, 1));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[2] = GET_W_FROM_DATA (data, 2));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[3] = GET_W_FROM_DATA (data, 3));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[4] = GET_W_FROM_DATA (data, 4));
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[5] = GET_W_FROM_DATA (data, 5));
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[6] = GET_W_FROM_DATA (data, 6));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[7] = GET_W_FROM_DATA (data, 7));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[8] = GET_W_FROM_DATA (data, 8));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[9] = GET_W_FROM_DATA (data, 9));
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[10] = GET_W_FROM_DATA (data, 10));
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[11] = GET_W_FROM_DATA (data, 11));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[12] = GET_W_FROM_DATA (data, 12));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[13] = GET_W_FROM_DATA (data, 13));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[14] = GET_W_FROM_DATA (data, 14));
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[15] = GET_W_FROM_DATA (data, 15));
+
+  /* 'W' generation and assignment for 16 <= t <= 79.
+     See FIPS PUB 180-4 paragraph 6.1.3.
+     As only last 16 'W' are used in calculations, it is possible to
+     use 16 elements array of W as cyclic buffer. */
+#define Wgen(w,t) _MHD_ROTL32((w)[(t + 13) & 0xf] ^ (w)[(t + 8) & 0xf] \
+                              ^ (w)[(t + 2) & 0xf] ^ (w)[t & 0xf], 1)
+
+  /* During last 60 steps, before making any calculations on each step,
+     W element is generated from W elements of cyclic buffer and generated value
+     stored back in cyclic buffer. */
+  /* Note: instead of using K constants as array, all K values are specified
+     individually for each step, see FIPS PUB 180-4 paragraph 4.2.1. */
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[16 & 0xf] = Wgen (W, 16));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[17 & 0xf] = Wgen (W, 17));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[18 & 0xf] = Wgen (W, 18));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[19 & 0xf] = Wgen (W, 19));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[20 & 0xf] = Wgen (W, 20));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[21 & 0xf] = Wgen (W, 21));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[22 & 0xf] = Wgen (W, 22));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[23 & 0xf] = Wgen (W, 23));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[24 & 0xf] = Wgen (W, 24));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[25 & 0xf] = Wgen (W, 25));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[26 & 0xf] = Wgen (W, 26));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[27 & 0xf] = Wgen (W, 27));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[28 & 0xf] = Wgen (W, 28));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[29 & 0xf] = Wgen (W, 29));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[30 & 0xf] = Wgen (W, 30));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[31 & 0xf] = Wgen (W, 31));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[32 & 0xf] = Wgen (W, 32));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[33 & 0xf] = Wgen (W, 33));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[34 & 0xf] = Wgen (W, 34));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[35 & 0xf] = Wgen (W, 35));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[36 & 0xf] = Wgen (W, 36));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[37 & 0xf] = Wgen (W, 37));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[38 & 0xf] = Wgen (W, 38));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[39 & 0xf] = Wgen (W, 39));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[40 & 0xf] = Wgen (W, 40));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[41 & 0xf] = Wgen (W, 41));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[42 & 0xf] = Wgen (W, 42));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[43 & 0xf] = Wgen (W, 43));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[44 & 0xf] = Wgen (W, 44));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[45 & 0xf] = Wgen (W, 45));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[46 & 0xf] = Wgen (W, 46));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[47 & 0xf] = Wgen (W, 47));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[48 & 0xf] = Wgen (W, 48));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[49 & 0xf] = Wgen (W, 49));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[50 & 0xf] = Wgen (W, 50));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[51 & 0xf] = Wgen (W, 51));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[52 & 0xf] = Wgen (W, 52));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[53 & 0xf] = Wgen (W, 53));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[54 & 0xf] = Wgen (W, 54));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[55 & 0xf] = Wgen (W, 55));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[56 & 0xf] = Wgen (W, 56));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[57 & 0xf] = Wgen (W, 57));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[58 & 0xf] = Wgen (W, 58));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[59 & 0xf] = Wgen (W, 59));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[60 & 0xf] = Wgen (W, 60));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[61 & 0xf] = Wgen (W, 61));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[62 & 0xf] = Wgen (W, 62));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[63 & 0xf] = Wgen (W, 63));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[64 & 0xf] = Wgen (W, 64));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[65 & 0xf] = Wgen (W, 65));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[66 & 0xf] = Wgen (W, 66));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[67 & 0xf] = Wgen (W, 67));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[68 & 0xf] = Wgen (W, 68));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[69 & 0xf] = Wgen (W, 69));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[70 & 0xf] = Wgen (W, 70));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[71 & 0xf] = Wgen (W, 71));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[72 & 0xf] = Wgen (W, 72));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[73 & 0xf] = Wgen (W, 73));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[74 & 0xf] = Wgen (W, 74));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[75 & 0xf] = Wgen (W, 75));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[76 & 0xf] = Wgen (W, 76));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[77 & 0xf] = Wgen (W, 77));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[78 & 0xf] = Wgen (W, 78));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[79 & 0xf] = Wgen (W, 79));
+
+  /* Compute intermediate hash.
+     See FIPS PUB 180-4 paragraph 6.1.3 step 4. */
+  H[0] += a;
+  H[1] += b;
+  H[2] += c;
+  H[3] += d;
+  H[4] += e;
+}
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA1_update (void *ctx_,
+                 const uint8_t *data,
+                 size_t length)
+{
+  struct sha1_ctx *const ctx = ctx_;
+  unsigned bytes_have; /**< Number of bytes in buffer */
+
+  mhd_assert ((data != NULL) || (length == 0));
+
+  if (0 == length)
+    return; /* Do nothing */
+
+  /* Note: (count & (SHA1_BLOCK_SIZE-1))
+           equal (count % SHA1_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1));
+  ctx->count += length;
+
+  if (0 != bytes_have)
+  {
+    unsigned bytes_left = SHA1_BLOCK_SIZE - bytes_have;
+    if (length >= bytes_left)
+    {     /* Combine new data with the data in the buffer and
+             process the full block. */
+      memcpy (ctx->buffer + bytes_have,
+              data,
+              bytes_left);
+      data += bytes_left;
+      length -= bytes_left;
+      sha1_transform (ctx->H, ctx->buffer);
+      bytes_have = 0;
+    }
+  }
+
+  while (SHA1_BLOCK_SIZE <= length)
+  {   /* Process any full blocks of new data directly,
+         without copying to the buffer. */
+    sha1_transform (ctx->H, data);
+    data += SHA1_BLOCK_SIZE;
+    length -= SHA1_BLOCK_SIZE;
+  }
+
+  if (0 != length)
+  {   /* Copy incomplete block of new data (if any)
+         to the buffer. */
+    memcpy (ctx->buffer + bytes_have, data, length);
+  }
+}
+
+
+/**
+ * Size of "length" padding addition in bytes.
+ * See FIPS PUB 180-4 paragraph 5.1.1.
+ */
+#define SHA1_SIZE_OF_LEN_ADD (64 / 8)
+
+/**
+ * Finalise SHA-1 calculation, return digest.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA1_finish (void *ctx_,
+                 uint8_t digest[SHA1_DIGEST_SIZE])
+{
+  struct sha1_ctx *const ctx = ctx_;
+  uint64_t num_bits;   /**< Number of processed bits */
+  unsigned bytes_have; /**< Number of bytes in buffer */
+
+  num_bits = ctx->count << 3;
+  /* Note: (count & (SHA1_BLOCK_SIZE-1))
+           equals (count % SHA1_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1));
+
+  /* Input data must be padded with bit "1" and with length of data in bits.
+     See FIPS PUB 180-4 paragraph 5.1.1. */
+  /* Data is always processed in form of bytes (not by individual bits),
+     therefore position of first padding bit in byte is always predefined (0x80). */
+  /* Buffer always have space at least for one byte (as full buffers are
+     processed immediately). */
+  ctx->buffer[bytes_have++] = 0x80;
+
+  if (SHA1_BLOCK_SIZE - bytes_have < SHA1_SIZE_OF_LEN_ADD)
+  {   /* No space in current block to put total length of message.
+         Pad current block with zeros and process it. */
+    if (SHA1_BLOCK_SIZE > bytes_have)
+      memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - bytes_have);
+    /* Process full block. */
+    sha1_transform (ctx->H, ctx->buffer);
+    /* Start new block. */
+    bytes_have = 0;
+  }
+
+  /* Pad the rest of the buffer with zeros. */
+  memset (ctx->buffer + bytes_have, 0,
+          SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD - bytes_have);
+  /* Put the number of bits in the processed message as a big-endian value. */
+  _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD,
+                          num_bits);
+  /* Process the full final block. */
+  sha1_transform (ctx->H, ctx->buffer);
+
+  /* Put final hash/digest in BE mode */
+#ifndef _MHD_PUT_32BIT_BE_UNALIGNED
+  if (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN)
+  {
+    uint32_t alig_dgst[_SHA1_DIGEST_LENGTH];
+    _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]);
+    /* Copy result to unaligned destination address */
+    memcpy (digest, alig_dgst, SHA1_DIGEST_SIZE);
+  }
+  else
+#else  /* _MHD_PUT_32BIT_BE_UNALIGNED */
+  if (1)
+#endif /* _MHD_PUT_32BIT_BE_UNALIGNED */
+  {
+    /* Use cast to (void*) here to mute compiler alignment warnings.
+     * Compilers are not smart enough to see that alignment has been checked. */
+    _MHD_PUT_32BIT_BE ((void *) (digest + 0 * SHA1_BYTES_IN_WORD), ctx->H[0]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 1 * SHA1_BYTES_IN_WORD), ctx->H[1]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 2 * SHA1_BYTES_IN_WORD), ctx->H[2]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 3 * SHA1_BYTES_IN_WORD), ctx->H[3]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 4 * SHA1_BYTES_IN_WORD), ctx->H[4]);
+  }
+
+  /* Erase potentially sensitive data. */
+  memset (ctx, 0, sizeof(struct sha1_ctx));
+}
diff --git a/src/microhttpd/sha1.h b/src/microhttpd/sha1.h
new file mode 100644
index 0000000..9a3847e
--- /dev/null
+++ b/src/microhttpd/sha1.h
@@ -0,0 +1,110 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019-2021 Karlson2k (Evgeny Grin)
+
+     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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha1.h
+ * @brief  Calculation of SHA-1 digest
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SHA1_H
+#define MHD_SHA1_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
+
+/**
+ *  SHA-1 digest is kept internally as 5 32-bit words.
+ */
+#define _SHA1_DIGEST_LENGTH 5
+
+/**
+ * Number of bits in single SHA-1 word
+ */
+#define SHA1_WORD_SIZE_BITS 32
+
+/**
+ * Number of bytes in single SHA-1 word
+ */
+#define SHA1_BYTES_IN_WORD (SHA1_WORD_SIZE_BITS / 8)
+
+/**
+ * Size of SHA-1 digest in bytes
+ */
+#define SHA1_DIGEST_SIZE (_SHA1_DIGEST_LENGTH * SHA1_BYTES_IN_WORD)
+
+/**
+ * Size of SHA-1 digest string in chars including termination NUL
+ */
+#define SHA1_DIGEST_STRING_SIZE ((SHA1_DIGEST_SIZE) * 2 + 1)
+
+/**
+ * Size of single processing block in bits
+ */
+#define SHA1_BLOCK_SIZE_BITS 512
+
+/**
+ * Size of single processing block in bytes
+ */
+#define SHA1_BLOCK_SIZE (SHA1_BLOCK_SIZE_BITS / 8)
+
+
+struct sha1_ctx
+{
+  uint32_t H[_SHA1_DIGEST_LENGTH];    /**< Intermediate hash value / digest at end of calculation */
+  uint8_t buffer[SHA1_BLOCK_SIZE];    /**< SHA256 input data buffer */
+  uint64_t count;                     /**< number of bytes, mod 2^64 */
+};
+
+/**
+ * Initialise structure for SHA-1 calculation.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ */
+void
+MHD_SHA1_init (void *ctx_);
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA1_update (void *ctx_,
+                 const uint8_t *data,
+                 size_t length);
+
+
+/**
+ * Finalise SHA-1 calculation, return digest.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA1_finish (void *ctx_,
+                 uint8_t digest[SHA1_DIGEST_SIZE]);
+
+#endif /* MHD_SHA1_H */
diff --git a/src/microhttpd/sha256.c b/src/microhttpd/sha256.c
new file mode 100644
index 0000000..2f9edf6
--- /dev/null
+++ b/src/microhttpd/sha256.c
@@ -0,0 +1,560 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha256.c
+ * @brief  Calculation of SHA-256 digest as defined in FIPS PUB 180-4 (2015)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "sha256.h"
+
+#include <string.h>
+#ifdef HAVE_MEMORY_H
+#include <memory.h>
+#endif /* HAVE_MEMORY_H */
+#include "mhd_bithelpers.h"
+#include "mhd_assert.h"
+
+/**
+ * Initialise structure for SHA256 calculation.
+ *
+ * @param ctx must be a `struct Sha256Ctx *`
+ */
+void
+MHD_SHA256_init (struct Sha256Ctx *ctx)
+{
+  /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.3 */
+  /* First thirty-two bits of the fractional parts of the square
+   * roots of the first eight prime numbers: 2, 3, 5, 7, 11, 13,
+   * 17, 19." */
+  ctx->H[0] = UINT32_C (0x6a09e667);
+  ctx->H[1] = UINT32_C (0xbb67ae85);
+  ctx->H[2] = UINT32_C (0x3c6ef372);
+  ctx->H[3] = UINT32_C (0xa54ff53a);
+  ctx->H[4] = UINT32_C (0x510e527f);
+  ctx->H[5] = UINT32_C (0x9b05688c);
+  ctx->H[6] = UINT32_C (0x1f83d9ab);
+  ctx->H[7] = UINT32_C (0x5be0cd19);
+
+  /* Initialise number of bytes. */
+  ctx->count = 0;
+}
+
+
+/**
+ * Base of SHA-256 transformation.
+ * Gets full 64 bytes block of data and updates hash values;
+ * @param H     hash values
+ * @param data  data, must be exactly 64 bytes long
+ */
+static void
+sha256_transform (uint32_t H[SHA256_DIGEST_SIZE_WORDS],
+                  const void *data)
+{
+  /* Working variables,
+     see FIPS PUB 180-4 paragraph 6.2. */
+  uint32_t a = H[0];
+  uint32_t b = H[1];
+  uint32_t c = H[2];
+  uint32_t d = H[3];
+  uint32_t e = H[4];
+  uint32_t f = H[5];
+  uint32_t g = H[6];
+  uint32_t h = H[7];
+
+  /* Data buffer, used as cyclic buffer.
+     See FIPS PUB 180-4 paragraphs 5.2.1, 6.2. */
+  uint32_t W[16];
+
+#ifndef _MHD_GET_32BIT_BE_UNALIGNED
+  if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN))
+  {
+    /* Copy the unaligned input data to the aligned buffer */
+    memcpy (W, data, SHA256_BLOCK_SIZE);
+    /* The W[] buffer itself will be used as the source of the data,
+     * but data will be reloaded in correct bytes order during
+     * the next steps */
+    data = (const void *) W;
+  }
+#endif /* _MHD_GET_32BIT_BE_UNALIGNED */
+
+  /* 'Ch' and 'Maj' macro functions are defined with
+     widely-used optimization.
+     See FIPS PUB 180-4 formulae 4.2, 4.3. */
+#define Ch(x,y,z)     ( (z) ^ ((x) & ((y) ^ (z))) )
+#define Maj(x,y,z)    ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) )
+  /* Unoptimized (original) versions: */
+/* #define Ch(x,y,z)  ( ( (x) & (y) ) ^ ( ~(x) & (z) ) )          */
+/* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */
+
+  /* Four 'Sigma' macro functions.
+     See FIPS PUB 180-4 formulae 4.4, 4.5, 4.6, 4.7. */
+#define SIG0(x)  (_MHD_ROTR32 ((x), 2) ^ _MHD_ROTR32 ((x), 13) ^ \
+                  _MHD_ROTR32 ((x), 22) )
+#define SIG1(x)  (_MHD_ROTR32 ((x), 6) ^ _MHD_ROTR32 ((x), 11) ^ \
+                  _MHD_ROTR32 ((x), 25) )
+#define sig0(x)  (_MHD_ROTR32 ((x), 7) ^ _MHD_ROTR32 ((x), 18) ^ \
+                  ((x) >> 3) )
+#define sig1(x)  (_MHD_ROTR32 ((x), 17) ^ _MHD_ROTR32 ((x),19) ^ \
+                  ((x) >> 10) )
+
+  /* One step of SHA-256 computation,
+     see FIPS PUB 180-4 paragraph 6.2.2 step 3.
+   * Note: this macro updates working variables in-place, without rotation.
+   * Note: first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in FIPS PUB 180-4 paragraph 6.2.2 step 3.
+           second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in FIPS PUB 180-4 paragraph 6.2.2 step 3.
+   * Note: 'wt' must be used exactly one time in this macro as it change other data as well
+           every time when used. */
+#define SHA2STEP32(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do {                  \
+    (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt));  \
+    (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0)
+
+  /* Get value of W(t) from input data buffer,
+     See FIPS PUB 180-4 paragraph 6.2.
+     Input data must be read in big-endian bytes order,
+     see FIPS PUB 180-4 paragraph 3.1.2. */
+  /* Use cast to (const void*) to mute compiler alignment warning,
+   * data was already aligned in previous step */
+#define GET_W_FROM_DATA(buf,t) \
+  _MHD_GET_32BIT_BE ((const void*)(((const uint8_t*) (buf)) + \
+                                   (t) * SHA256_BYTES_IN_WORD))
+
+  /* 'W' generation and assignment for 16 <= t <= 63.
+     See FIPS PUB 180-4 paragraph 6.2.2.
+     As only last 16 'W' are used in calculations, it is possible to
+     use 16 elements array of W as cyclic buffer.
+   * Note: ((t-16)&0xf) have same value as (t&0xf) */
+#define Wgen(w,t) ( (w)[(t - 16) & 0xf] + sig1 ((w)[((t) - 2) & 0xf])   \
+                    + (w)[((t) - 7) & 0xf] + sig0 ((w)[((t) - 15) & 0xf]) )
+
+#ifndef MHD_FAVOR_SMALL_CODE
+
+  /* Note: instead of using K constants as array, all K values are specified
+           individually for each step, see FIPS PUB 180-4 paragraph 4.2.2 for
+           K values. */
+  /* Note: instead of reassigning all working variables on each step,
+           variables are rotated for each step:
+             SHA2STEP32(a, b, c, d, e, f, g, h, K[0], data[0]);
+             SHA2STEP32(h, a, b, c, d, e, f, g, K[1], data[1]);
+           so current 'vD' will be used as 'vE' on next step,
+           current 'vH' will be used as 'vA' on next step. */
+#if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+  if ((const void *) W == data)
+  {
+    /* The input data is already in the cyclic data buffer W[] in correct bytes
+       order. */
+    SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x428a2f98), W[0]);
+    SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x71374491), W[1]);
+    SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb5c0fbcf), W[2]);
+    SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xe9b5dba5), W[3]);
+    SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x3956c25b), W[4]);
+    SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x59f111f1), W[5]);
+    SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x923f82a4), W[6]);
+    SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xab1c5ed5), W[7]);
+    SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xd807aa98), W[8]);
+    SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x12835b01), W[9]);
+    SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x243185be), W[10]);
+    SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x550c7dc3), W[11]);
+    SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x72be5d74), W[12]);
+    SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x80deb1fe), W[13]);
+    SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x9bdc06a7), W[14]);
+    SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc19bf174), W[15]);
+  }
+  else /* Combined with the next 'if' */
+#endif /* _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */
+  if (1)
+  {
+    /* During first 16 steps, before making any calculations on each step,
+       the W element is read from input data buffer as big-endian value and
+       stored in array of W elements. */
+    SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x428a2f98), W[0] = \
+                  GET_W_FROM_DATA (data, 0));
+    SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x71374491), W[1] = \
+                  GET_W_FROM_DATA (data, 1));
+    SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb5c0fbcf), W[2] = \
+                  GET_W_FROM_DATA (data, 2));
+    SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xe9b5dba5), W[3] = \
+                  GET_W_FROM_DATA (data, 3));
+    SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x3956c25b), W[4] = \
+                  GET_W_FROM_DATA (data, 4));
+    SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x59f111f1), W[5] = \
+                  GET_W_FROM_DATA (data, 5));
+    SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x923f82a4), W[6] = \
+                  GET_W_FROM_DATA (data, 6));
+    SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xab1c5ed5), W[7] = \
+                  GET_W_FROM_DATA (data, 7));
+    SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xd807aa98), W[8] = \
+                  GET_W_FROM_DATA (data, 8));
+    SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x12835b01), W[9] = \
+                  GET_W_FROM_DATA (data, 9));
+    SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x243185be), W[10] = \
+                  GET_W_FROM_DATA (data, 10));
+    SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x550c7dc3), W[11] = \
+                  GET_W_FROM_DATA (data, 11));
+    SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x72be5d74), W[12] = \
+                  GET_W_FROM_DATA (data, 12));
+    SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x80deb1fe), W[13] = \
+                  GET_W_FROM_DATA (data, 13));
+    SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x9bdc06a7), W[14] = \
+                  GET_W_FROM_DATA (data, 14));
+    SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc19bf174), W[15] = \
+                  GET_W_FROM_DATA (data, 15));
+  }
+
+  /* During last 48 steps, before making any calculations on each step,
+     current W element is generated from other W elements of the cyclic buffer
+     and the generated value is stored back in the cyclic buffer. */
+  /* Note: instead of using K constants as array, all K values are specified
+     individually for each step, see FIPS PUB 180-4 paragraph 4.2.2 for K values. */
+  SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xe49b69c1), W[16 & 0xf] = \
+                Wgen (W,16));
+  SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xefbe4786), W[17 & 0xf] = \
+                Wgen (W,17));
+  SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x0fc19dc6), W[18 & 0xf] = \
+                Wgen (W,18));
+  SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x240ca1cc), W[19 & 0xf] = \
+                Wgen (W,19));
+  SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x2de92c6f), W[20 & 0xf] = \
+                Wgen (W,20));
+  SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x4a7484aa), W[21 & 0xf] = \
+                Wgen (W,21));
+  SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x5cb0a9dc), W[22 & 0xf] = \
+                Wgen (W,22));
+  SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x76f988da), W[23 & 0xf] = \
+                Wgen (W,23));
+  SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x983e5152), W[24 & 0xf] = \
+                Wgen (W,24));
+  SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xa831c66d), W[25 & 0xf] = \
+                Wgen (W,25));
+  SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb00327c8), W[26 & 0xf] = \
+                Wgen (W,26));
+  SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xbf597fc7), W[27 & 0xf] = \
+                Wgen (W,27));
+  SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0xc6e00bf3), W[28 & 0xf] = \
+                Wgen (W,28));
+  SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xd5a79147), W[29 & 0xf] = \
+                Wgen (W,29));
+  SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x06ca6351), W[30 & 0xf] = \
+                Wgen (W,30));
+  SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x14292967), W[31 & 0xf] = \
+                Wgen (W,31));
+  SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x27b70a85), W[32 & 0xf] = \
+                Wgen (W,32));
+  SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x2e1b2138), W[33 & 0xf] = \
+                Wgen (W,33));
+  SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x4d2c6dfc), W[34 & 0xf] = \
+                Wgen (W,34));
+  SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x53380d13), W[35 & 0xf] = \
+                Wgen (W,35));
+  SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x650a7354), W[36 & 0xf] = \
+                Wgen (W,36));
+  SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x766a0abb), W[37 & 0xf] = \
+                Wgen (W,37));
+  SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x81c2c92e), W[38 & 0xf] = \
+                Wgen (W,38));
+  SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x92722c85), W[39 & 0xf] = \
+                Wgen (W,39));
+  SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xa2bfe8a1), W[40 & 0xf] = \
+                Wgen (W,40));
+  SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xa81a664b), W[41 & 0xf] = \
+                Wgen (W,41));
+  SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xc24b8b70), W[42 & 0xf] = \
+                Wgen (W,42));
+  SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xc76c51a3), W[43 & 0xf] = \
+                Wgen (W,43));
+  SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0xd192e819), W[44 & 0xf] = \
+                Wgen (W,44));
+  SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xd6990624), W[45 & 0xf] = \
+                Wgen (W,45));
+  SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0xf40e3585), W[46 & 0xf] = \
+                Wgen (W,46));
+  SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x106aa070), W[47 & 0xf] = \
+                Wgen (W,47));
+  SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x19a4c116), W[48 & 0xf] = \
+                Wgen (W,48));
+  SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x1e376c08), W[49 & 0xf] = \
+                Wgen (W,49));
+  SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x2748774c), W[50 & 0xf] = \
+                Wgen (W,50));
+  SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x34b0bcb5), W[51 & 0xf] = \
+                Wgen (W,51));
+  SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x391c0cb3), W[52 & 0xf] = \
+                Wgen (W,52));
+  SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x4ed8aa4a), W[53 & 0xf] = \
+                Wgen (W,53));
+  SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x5b9cca4f), W[54 & 0xf] = \
+                Wgen (W,54));
+  SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x682e6ff3), W[55 & 0xf] = \
+                Wgen (W,55));
+  SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x748f82ee), W[56 & 0xf] = \
+                Wgen (W,56));
+  SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x78a5636f), W[57 & 0xf] = \
+                Wgen (W,57));
+  SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x84c87814), W[58 & 0xf] = \
+                Wgen (W,58));
+  SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x8cc70208), W[59 & 0xf] = \
+                Wgen (W,59));
+  SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x90befffa), W[60 & 0xf] = \
+                Wgen (W,60));
+  SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xa4506ceb), W[61 & 0xf] = \
+                Wgen (W,61));
+  SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0xbef9a3f7), W[62 & 0xf] = \
+                Wgen (W,62));
+  SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc67178f2), W[63 & 0xf] = \
+                Wgen (W,63));
+#else  /* ! MHD_FAVOR_SMALL_CODE */
+  if (1)
+  {
+    unsigned int t;
+    /* K constants array.
+       See FIPS PUB 180-4 paragraph 4.2.2 for K values. */
+    static const uint32_t K[80] =
+    { UINT32_C (0x428a2f98),  UINT32_C (0x71374491),  UINT32_C (0xb5c0fbcf),
+      UINT32_C (0xe9b5dba5),  UINT32_C (0x3956c25b),  UINT32_C (0x59f111f1),
+      UINT32_C (0x923f82a4),  UINT32_C (0xab1c5ed5),  UINT32_C (0xd807aa98),
+      UINT32_C (0x12835b01),  UINT32_C (0x243185be),  UINT32_C (0x550c7dc3),
+      UINT32_C (0x72be5d74),  UINT32_C (0x80deb1fe),  UINT32_C (0x9bdc06a7),
+      UINT32_C (0xc19bf174),  UINT32_C (0xe49b69c1),  UINT32_C (0xefbe4786),
+      UINT32_C (0x0fc19dc6),  UINT32_C (0x240ca1cc),  UINT32_C (0x2de92c6f),
+      UINT32_C (0x4a7484aa),  UINT32_C (0x5cb0a9dc),  UINT32_C (0x76f988da),
+      UINT32_C (0x983e5152),  UINT32_C (0xa831c66d),  UINT32_C (0xb00327c8),
+      UINT32_C (0xbf597fc7),  UINT32_C (0xc6e00bf3),  UINT32_C (0xd5a79147),
+      UINT32_C (0x06ca6351),  UINT32_C (0x14292967),  UINT32_C (0x27b70a85),
+      UINT32_C (0x2e1b2138),  UINT32_C (0x4d2c6dfc),  UINT32_C (0x53380d13),
+      UINT32_C (0x650a7354),  UINT32_C (0x766a0abb),  UINT32_C (0x81c2c92e),
+      UINT32_C (0x92722c85),  UINT32_C (0xa2bfe8a1),  UINT32_C (0xa81a664b),
+      UINT32_C (0xc24b8b70),  UINT32_C (0xc76c51a3),  UINT32_C (0xd192e819),
+      UINT32_C (0xd6990624),  UINT32_C (0xf40e3585),  UINT32_C (0x106aa070),
+      UINT32_C (0x19a4c116),  UINT32_C (0x1e376c08),  UINT32_C (0x2748774c),
+      UINT32_C (0x34b0bcb5),  UINT32_C (0x391c0cb3),  UINT32_C (0x4ed8aa4a),
+      UINT32_C (0x5b9cca4f),  UINT32_C (0x682e6ff3),  UINT32_C (0x748f82ee),
+      UINT32_C (0x78a5636f),  UINT32_C (0x84c87814),  UINT32_C (0x8cc70208),
+      UINT32_C (0x90befffa),  UINT32_C (0xa4506ceb),  UINT32_C (0xbef9a3f7),
+      UINT32_C (0xc67178f2) };
+    /* One step of SHA-256 computation with working variables rotation,
+       see FIPS PUB 180-4 paragraph 6.2.2 step 3.
+     * Note: this version of macro reassign all working variable on
+             each step. */
+#define SHA2STEP32RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do {              \
+    uint32_t tmp_h_ = (vH);                                           \
+    SHA2STEP32((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt));  \
+    (vH) = (vG);                                                      \
+    (vG) = (vF);                                                      \
+    (vF) = (vE);                                                      \
+    (vE) = (vD);                                                      \
+    (vD) = (vC);                                                      \
+    (vC) = (vB);                                                      \
+    (vB) = (vA);                                                      \
+    (vA) = tmp_h_;  } while (0)
+
+    /* During first 16 steps, before making any calculations on each step,
+       the W element is read from input data buffer as big-endian value and
+       stored in array of W elements. */
+    for (t = 0; t < 16; ++t)
+    {
+      SHA2STEP32RV (a, b, c, d, e, f, g, h, K[t], \
+                    W[t] = GET_W_FROM_DATA (data, t));
+    }
+
+    /* During last 48 steps, before making any calculations on each step,
+       current W element is generated from other W elements of the cyclic buffer
+       and the generated value is stored back in the cyclic buffer. */
+    for (t = 16; t < 64; ++t)
+    {
+      SHA2STEP32RV (a, b, c, d, e, f, g, h, K[t], W[t & 15] = Wgen (W,t));
+    }
+  }
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+
+
+  /* Compute intermediate hash.
+     See FIPS PUB 180-4 paragraph 6.2.2 step 4. */
+  H[0] += a;
+  H[1] += b;
+  H[2] += c;
+  H[3] += d;
+  H[4] += e;
+  H[5] += f;
+  H[6] += g;
+  H[7] += h;
+}
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx_ must be a `struct Sha256Ctx *`
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA256_update (struct Sha256Ctx *ctx,
+                   const uint8_t *data,
+                   size_t length)
+{
+  unsigned bytes_have; /**< Number of bytes in buffer */
+
+  mhd_assert ((data != NULL) || (length == 0));
+
+#ifndef MHD_FAVOR_SMALL_CODE
+  if (0 == length)
+    return; /* Shortcut, do nothing */
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+  /* Note: (count & (SHA256_BLOCK_SIZE-1))
+           equals (count % SHA256_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned) (ctx->count & (SHA256_BLOCK_SIZE - 1));
+  ctx->count += length;
+
+  if (0 != bytes_have)
+  {
+    unsigned bytes_left = SHA256_BLOCK_SIZE - bytes_have;
+    if (length >= bytes_left)
+    {     /* Combine new data with data in the buffer and
+             process full block. */
+      memcpy (((uint8_t *) ctx->buffer) + bytes_have,
+              data,
+              bytes_left);
+      data += bytes_left;
+      length -= bytes_left;
+      sha256_transform (ctx->H, ctx->buffer);
+      bytes_have = 0;
+    }
+  }
+
+  while (SHA256_BLOCK_SIZE <= length)
+  {   /* Process any full blocks of new data directly,
+         without copying to the buffer. */
+    sha256_transform (ctx->H, data);
+    data += SHA256_BLOCK_SIZE;
+    length -= SHA256_BLOCK_SIZE;
+  }
+
+  if (0 != length)
+  {   /* Copy incomplete block of new data (if any)
+         to the buffer. */
+    memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length);
+  }
+}
+
+
+/**
+ * Size of "length" padding addition in bytes.
+ * See FIPS PUB 180-4 paragraph 5.1.1.
+ */
+#define SHA256_SIZE_OF_LEN_ADD (64 / 8)
+
+/**
+ * Finalise SHA256 calculation, return digest.
+ *
+ * @param ctx_ must be a `struct Sha256Ctx *`
+ * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA256_finish (struct Sha256Ctx *ctx,
+                   uint8_t digest[SHA256_DIGEST_SIZE])
+{
+  uint64_t num_bits;   /**< Number of processed bits */
+  unsigned bytes_have; /**< Number of bytes in buffer */
+
+  num_bits = ctx->count << 3;
+  /* Note: (count & (SHA256_BLOCK_SIZE-1))
+           equal (count % SHA256_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned) (ctx->count & (SHA256_BLOCK_SIZE - 1));
+
+  /* Input data must be padded with a single bit "1", then with zeros and
+     the finally the length of data in bits must be added as the final bytes
+     of the last block.
+     See FIPS PUB 180-4 paragraph 5.1.1. */
+
+  /* Data is always processed in form of bytes (not by individual bits),
+     therefore position of first padding bit in byte is always
+     predefined (0x80). */
+  /* Buffer always have space at least for one byte (as full buffers are
+     processed immediately). */
+  ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80;
+
+  if (SHA256_BLOCK_SIZE - bytes_have < SHA256_SIZE_OF_LEN_ADD)
+  {   /* No space in current block to put total length of message.
+         Pad current block with zeros and process it. */
+    if (bytes_have < SHA256_BLOCK_SIZE)
+      memset (((uint8_t *) ctx->buffer) + bytes_have, 0,
+              SHA256_BLOCK_SIZE - bytes_have);
+    /* Process full block. */
+    sha256_transform (ctx->H, ctx->buffer);
+    /* Start new block. */
+    bytes_have = 0;
+  }
+
+  /* Pad the rest of the buffer with zeros. */
+  memset (((uint8_t *) ctx->buffer) + bytes_have, 0,
+          SHA256_BLOCK_SIZE - SHA256_SIZE_OF_LEN_ADD - bytes_have);
+  /* Put the number of bits in processed message as big-endian value. */
+  _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA256_BLOCK_SIZE_WORDS - 2, num_bits);
+  /* Process full final block. */
+  sha256_transform (ctx->H, ctx->buffer);
+
+  /* Put final hash/digest in BE mode */
+#ifndef _MHD_PUT_32BIT_BE_UNALIGNED
+  if (1
+#ifndef MHD_FAVOR_SMALL_CODE
+      && (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN)
+#endif /* MHD_FAVOR_SMALL_CODE */
+      )
+  {
+    /* If storing of the final result requires aligned address and
+       the destination address is not aligned or compact code is used,
+       store the final digest in aligned temporary buffer first, then
+       copy it to the destination. */
+    uint32_t alig_dgst[SHA256_DIGEST_SIZE_WORDS];
+    _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 5, ctx->H[5]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 6, ctx->H[6]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 7, ctx->H[7]);
+    /* Copy result to unaligned destination address */
+    memcpy (digest, alig_dgst, SHA256_DIGEST_SIZE);
+  }
+#ifndef MHD_FAVOR_SMALL_CODE
+  else /* Combined with the next 'if' */
+#endif /* MHD_FAVOR_SMALL_CODE */
+#endif /* ! _MHD_PUT_32BIT_BE_UNALIGNED */
+#if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_32BIT_BE_UNALIGNED)
+  if (1)
+  {
+    /* Use cast to (void*) here to mute compiler alignment warnings.
+     * Compilers are not smart enough to see that alignment has been checked. */
+    _MHD_PUT_32BIT_BE ((void *) (digest + 0 * SHA256_BYTES_IN_WORD), ctx->H[0]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 1 * SHA256_BYTES_IN_WORD), ctx->H[1]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 2 * SHA256_BYTES_IN_WORD), ctx->H[2]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 3 * SHA256_BYTES_IN_WORD), ctx->H[3]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 4 * SHA256_BYTES_IN_WORD), ctx->H[4]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 5 * SHA256_BYTES_IN_WORD), ctx->H[5]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 6 * SHA256_BYTES_IN_WORD), ctx->H[6]);
+    _MHD_PUT_32BIT_BE ((void *) (digest + 7 * SHA256_BYTES_IN_WORD), ctx->H[7]);
+  }
+#endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_32BIT_BE_UNALIGNED */
+
+  /* Erase potentially sensitive data. */
+  memset (ctx, 0, sizeof(struct Sha256Ctx));
+}
diff --git a/src/microhttpd/sha256.h b/src/microhttpd/sha256.h
new file mode 100644
index 0000000..9069a59
--- /dev/null
+++ b/src/microhttpd/sha256.h
@@ -0,0 +1,122 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019-2022 Evgeny Grin (Karlson2k)
+
+     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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha256.h
+ * @brief  Calculation of SHA-256 digest
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SHA256_H
+#define MHD_SHA256_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
+
+
+/**
+ *  Digest is kept internally as 8 32-bit words.
+ */
+#define SHA256_DIGEST_SIZE_WORDS 8
+
+/**
+ * Number of bits in single SHA-256 word
+ */
+#define SHA256_WORD_SIZE_BITS 32
+
+/**
+ * Number of bytes in single SHA-256 word
+ * used to process data
+ */
+#define SHA256_BYTES_IN_WORD (SHA256_WORD_SIZE_BITS / 8)
+
+/**
+ * Size of SHA-256 digest in bytes
+ */
+#define SHA256_DIGEST_SIZE (SHA256_DIGEST_SIZE_WORDS * SHA256_BYTES_IN_WORD)
+
+/**
+ * Size of SHA-256 digest string in chars including termination NUL
+ */
+#define SHA256_DIGEST_STRING_SIZE ((SHA256_DIGEST_SIZE) * 2 + 1)
+
+/**
+ * Size of single processing block in bits
+ */
+#define SHA256_BLOCK_SIZE_BITS 512
+
+/**
+ * Size of single processing block in bytes
+ */
+#define SHA256_BLOCK_SIZE (SHA256_BLOCK_SIZE_BITS / 8)
+
+/**
+ * Size of single processing block in bytes
+ */
+#define SHA256_BLOCK_SIZE_WORDS (SHA256_BLOCK_SIZE_BITS / SHA256_WORD_SIZE_BITS)
+
+
+struct Sha256Ctx
+{
+  uint32_t H[SHA256_DIGEST_SIZE_WORDS];     /**< Intermediate hash value / digest at end of calculation */
+  uint32_t buffer[SHA256_BLOCK_SIZE_WORDS]; /**< SHA256 input data buffer */
+  uint64_t count;                           /**< number of bytes, mod 2^64 */
+};
+
+/**
+ * Initialise structure for SHA256 calculation.
+ *
+ * @param ctx must be a `struct Sha256Ctx *`
+ */
+void
+MHD_SHA256_init (struct Sha256Ctx *ctx);
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx must be a `struct Sha256Ctx *`
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA256_update (struct Sha256Ctx *ctx,
+                   const uint8_t *data,
+                   size_t length);
+
+
+/**
+ * Finalise SHA256 calculation, return digest.
+ *
+ * @param ctx must be a `struct Sha256Ctx *`
+ * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA256_finish (struct Sha256Ctx *ctx,
+                   uint8_t digest[SHA256_DIGEST_SIZE]);
+
+/**
+ * Indicates that function MHD_SHA256_finish() (without context reset) is available
+ */
+#define MHD_SHA256_HAS_FINISH 1
+
+#endif /* MHD_SHA256_H */
diff --git a/src/microhttpd/sha256_ext.c b/src/microhttpd/sha256_ext.c
new file mode 100644
index 0000000..bcbe53a
--- /dev/null
+++ b/src/microhttpd/sha256_ext.c
@@ -0,0 +1,101 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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 GNU libmicrohttpd.
+     If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file microhttpd/sha256_ext.h
+ * @brief  Wrapper for SHA-256 calculation performed by TLS library
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include <gnutls/crypto.h>
+#include "sha256_ext.h"
+#include "mhd_assert.h"
+
+
+/**
+ * Initialise structure for SHA-256 calculation, allocate resources.
+ *
+ * This function must not be called more than one time for @a ctx.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_SHA256_init_one_time (struct Sha256CtxExt *ctx)
+{
+  ctx->handle = NULL;
+  ctx->ext_error = gnutls_hash_init (&ctx->handle, GNUTLS_DIG_SHA256);
+  if ((0 != ctx->ext_error) && (NULL != ctx->handle))
+  {
+    /* GnuTLS may return initialisation error and set the handle at the
+       same time. Such handle cannot be used for calculations.
+       Note: GnuTLS may also return an error and NOT set the handle. */
+    gnutls_free (ctx->handle);
+    ctx->handle = NULL;
+  }
+
+  /* If handle is NULL, the error must be set */
+  mhd_assert ((NULL != ctx->handle) || (0 != ctx->ext_error));
+  /* If error is set, the handle must be NULL */
+  mhd_assert ((0 == ctx->ext_error) || (NULL == ctx->handle));
+}
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA256_update (struct Sha256CtxExt *ctx,
+                   const uint8_t *data,
+                   size_t length)
+{
+  if (0 == ctx->ext_error)
+    ctx->ext_error = gnutls_hash (ctx->handle, data, length);
+}
+
+
+/**
+ * Finalise SHA-256 calculation, return digest, reset hash calculation.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA256_finish_reset (struct Sha256CtxExt *ctx,
+                         uint8_t digest[SHA256_DIGEST_SIZE])
+{
+  if (0 == ctx->ext_error)
+    gnutls_hash_output (ctx->handle, digest);
+}
+
+
+/**
+ * Free allocated resources.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_SHA256_deinit (struct Sha256CtxExt *ctx)
+{
+  if (NULL != ctx->handle)
+    gnutls_hash_deinit (ctx->handle, NULL);
+}
diff --git a/src/microhttpd/sha256_ext.h b/src/microhttpd/sha256_ext.h
new file mode 100644
index 0000000..7d2ee6a
--- /dev/null
+++ b/src/microhttpd/sha256_ext.h
@@ -0,0 +1,115 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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 GNU libmicrohttpd.
+     If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file microhttpd/sha256_ext.h
+ * @brief  Wrapper declarations for SHA-256 calculation performed by TLS library
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SHA256_EXT_H
+#define MHD_SHA256_EXT_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
+
+/**
+ * Size of SHA-256 resulting digest in bytes
+ * This is the final digest size, not intermediate hash.
+ */
+#define SHA256_DIGEST_SIZE (32)
+
+/* Actual declaration is in GnuTLS lib header */
+struct hash_hd_st;
+
+/**
+ * Indicates that struct Sha256CtxExt has 'ext_error'
+ */
+#define MHD_SHA256_HAS_EXT_ERROR 1
+
+/**
+ * SHA-256 calculation context
+ */
+struct Sha256CtxExt
+{
+  struct hash_hd_st *handle; /**< Hash calculation handle */
+  int ext_error; /**< Non-zero if external error occurs during init or hashing */
+};
+
+/**
+ * Indicates that MHD_SHA256_init_one_time() function is present.
+ */
+#define MHD_SHA256_HAS_INIT_ONE_TIME 1
+
+/**
+ * Initialise structure for SHA-256 calculation, allocate resources.
+ *
+ * This function must not be called more than one time for @a ctx.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_SHA256_init_one_time (struct Sha256CtxExt *ctx);
+
+
+/**
+ * SHA-256 process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA256_update (struct Sha256CtxExt *ctx,
+                   const uint8_t *data,
+                   size_t length);
+
+
+/**
+ * Indicates that MHD_SHA256_finish_reset() function is available
+ */
+#define MHD_SHA256_HAS_FINISH_RESET 1
+
+/**
+ * Finalise SHA-256 calculation, return digest, reset hash calculation.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA256_finish_reset (struct Sha256CtxExt *ctx,
+                         uint8_t digest[SHA256_DIGEST_SIZE]);
+
+/**
+ * Indicates that MHD_SHA256_deinit() function is present
+ */
+#define MHD_SHA256_HAS_DEINIT 1
+
+/**
+ * Free allocated resources.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_SHA256_deinit (struct Sha256CtxExt *ctx);
+
+#endif /* MHD_SHA256_EXT_H */
diff --git a/src/microhttpd/sha512_256.c b/src/microhttpd/sha512_256.c
new file mode 100644
index 0000000..b7682b2
--- /dev/null
+++ b/src/microhttpd/sha512_256.c
@@ -0,0 +1,629 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha512_256.c
+ * @brief  Calculation of SHA-512/256 digest as defined in FIPS PUB 180-4 (2015)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "sha512_256.h"
+
+#include <string.h>
+#ifdef HAVE_MEMORY_H
+#include <memory.h>
+#endif /* HAVE_MEMORY_H */
+#include "mhd_bithelpers.h"
+#include "mhd_assert.h"
+
+/**
+ * Initialise structure for SHA-512/256 calculation.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_SHA512_256_init (struct Sha512_256Ctx *ctx)
+{
+  /* Initial hash values, see FIPS PUB 180-4 clause 5.3.6.2 */
+  /* Values generated by "IV Generation Function" as described in
+   * clause 5.3.6 */
+  ctx->H[0] = UINT64_C (0x22312194FC2BF72C);
+  ctx->H[1] = UINT64_C (0x9F555FA3C84C64C2);
+  ctx->H[2] = UINT64_C (0x2393B86B6F53B151);
+  ctx->H[3] = UINT64_C (0x963877195940EABD);
+  ctx->H[4] = UINT64_C (0x96283EE2A88EFFE3);
+  ctx->H[5] = UINT64_C (0xBE5E1E2553863992);
+  ctx->H[6] = UINT64_C (0x2B0199FC2C85B8AA);
+  ctx->H[7] = UINT64_C (0x0EB72DDC81C52CA2);
+
+  /* Initialise number of bytes and high part of number of bits. */
+  ctx->count = 0;
+  ctx->count_bits_hi = 0;
+}
+
+
+/**
+ * Base of SHA-512/256 transformation.
+ * Gets full 128 bytes block of data and updates hash values;
+ * @param H     hash values
+ * @param data  the data buffer with #SHA512_256_BLOCK_SIZE bytes block
+ */
+static void
+sha512_256_transform (uint64_t H[SHA512_256_HASH_SIZE_WORDS],
+                      const void *data)
+{
+  /* Working variables,
+     see FIPS PUB 180-4 clause 6.7, 6.4. */
+  uint64_t a = H[0];
+  uint64_t b = H[1];
+  uint64_t c = H[2];
+  uint64_t d = H[3];
+  uint64_t e = H[4];
+  uint64_t f = H[5];
+  uint64_t g = H[6];
+  uint64_t h = H[7];
+
+  /* Data buffer, used as a cyclic buffer.
+     See FIPS PUB 180-4 clause 5.2.2, 6.7, 6.4. */
+  uint64_t W[16];
+
+#ifndef _MHD_GET_64BIT_BE_ALLOW_UNALIGNED
+  if (0 != (((uintptr_t) data) % _MHD_UINT64_ALIGN))
+  { /* The input data is unaligned */
+    /* Copy the unaligned input data to the aligned buffer */
+    memcpy (W, data, sizeof(W));
+    /* The W[] buffer itself will be used as the source of the data,
+     * but the data will be reloaded in correct bytes order on
+     * the next steps */
+    data = (const void *) W;
+  }
+#endif /* _MHD_GET_64BIT_BE_ALLOW_UNALIGNED */
+
+  /* 'Ch' and 'Maj' macro functions are defined with
+     widely-used optimisation.
+     See FIPS PUB 180-4 formulae 4.8, 4.9. */
+#define Ch(x,y,z)     ( (z) ^ ((x) & ((y) ^ (z))) )
+#define Maj(x,y,z)    ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) )
+  /* Unoptimized (original) versions: */
+/* #define Ch(x,y,z)  ( ( (x) & (y) ) ^ ( ~(x) & (z) ) )          */
+/* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */
+
+  /* Four 'Sigma' macro functions.
+     See FIPS PUB 180-4 formulae 4.10, 4.11, 4.12, 4.13. */
+#define SIG0(x)  \
+  ( _MHD_ROTR64 ((x), 28) ^ _MHD_ROTR64 ((x), 34) ^ _MHD_ROTR64 ((x), 39) )
+#define SIG1(x)  \
+  ( _MHD_ROTR64 ((x), 14) ^ _MHD_ROTR64 ((x), 18) ^ _MHD_ROTR64 ((x), 41) )
+#define sig0(x)  \
+  ( _MHD_ROTR64 ((x), 1) ^ _MHD_ROTR64 ((x), 8) ^ ((x) >> 7) )
+#define sig1(x)  \
+  ( _MHD_ROTR64 ((x), 19) ^ _MHD_ROTR64 ((x), 61) ^ ((x) >> 6) )
+
+  /* One step of SHA-512/256 computation,
+     see FIPS PUB 180-4 clause 6.4.2 step 3.
+   * Note: this macro updates working variables in-place, without rotation.
+   * Note: the first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in
+           FIPS PUB 180-4 clause 6.4.2 step 3.
+           the second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in
+           FIPS PUB 180-4 clause 6.4.2 step 3.
+   * Note: 'wt' must be used exactly one time in this macro as it change other
+           data as well every time when used. */
+#define SHA2STEP64(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do {                  \
+    (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt));  \
+    (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0)
+
+  /* Get value of W(t) from input data buffer for 0 <= t <= 15,
+     See FIPS PUB 180-4 clause 6.2.
+     Input data must be read in big-endian bytes order,
+     see FIPS PUB 180-4 clause 3.1.2. */
+#define GET_W_FROM_DATA(buf,t) \
+  _MHD_GET_64BIT_BE (((const uint64_t*) (buf)) + (t))
+
+  /* 'W' generation and assignment for 16 <= t <= 79.
+     See FIPS PUB 180-4 clause 6.4.2.
+     As only last 16 'W' are used in calculations, it is possible to
+     use 16 elements array of W as a cyclic buffer.
+   * Note: ((t-16) & 15) have same value as (t & 15) */
+#define Wgen(w,t) ( (w)[(t - 16) & 15] + sig1 ((w)[((t) - 2) & 15])   \
+                    + (w)[((t) - 7) & 15] + sig0 ((w)[((t) - 15) & 15]) )
+
+#ifndef MHD_FAVOR_SMALL_CODE
+
+  /* Note: instead of using K constants as array, all K values are specified
+           individually for each step, see FIPS PUB 180-4 clause 4.2.3 for
+           K values. */
+  /* Note: instead of reassigning all working variables on each step,
+           variables are rotated for each step:
+             SHA2STEP64(a, b, c, d, e, f, g, h, K[0], data[0]);
+             SHA2STEP64(h, a, b, c, d, e, f, g, K[1], data[1]);
+           so current 'vD' will be used as 'vE' on next step,
+           current 'vH' will be used as 'vA' on next step. */
+#if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN
+  if ((const void *) W == data)
+  {
+    /* The input data is already in the cyclic data buffer W[] in correct bytes
+       order. */
+    SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x428a2f98d728ae22), W[0]);
+    SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x7137449123ef65cd), W[1]);
+    SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb5c0fbcfec4d3b2f), W[2]);
+    SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xe9b5dba58189dbbc), W[3]);
+    SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x3956c25bf348b538), W[4]);
+    SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x59f111f1b605d019), W[5]);
+    SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x923f82a4af194f9b), W[6]);
+    SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xab1c5ed5da6d8118), W[7]);
+    SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xd807aa98a3030242), W[8]);
+    SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x12835b0145706fbe), W[9]);
+    SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x243185be4ee4b28c), W[10]);
+    SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x550c7dc3d5ffb4e2), W[11]);
+    SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x72be5d74f27b896f), W[12]);
+    SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x80deb1fe3b1696b1), W[13]);
+    SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x9bdc06a725c71235), W[14]);
+    SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc19bf174cf692694), W[15]);
+  }
+  else /* Combined with the next 'if' */
+#endif /* _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */
+  if (1)
+  {
+    /* During first 16 steps, before making any calculations on each step,
+       the W element is read from the input data buffer as big-endian value and
+       stored in the array of W elements. */
+    SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x428a2f98d728ae22), \
+                W[0] = GET_W_FROM_DATA (data, 0));
+    SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x7137449123ef65cd), \
+                W[1] = GET_W_FROM_DATA (data, 1));
+    SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb5c0fbcfec4d3b2f), \
+                W[2] = GET_W_FROM_DATA (data, 2));
+    SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xe9b5dba58189dbbc), \
+                W[3] = GET_W_FROM_DATA (data, 3));
+    SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x3956c25bf348b538), \
+                W[4] = GET_W_FROM_DATA (data, 4));
+    SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x59f111f1b605d019), \
+                W[5] = GET_W_FROM_DATA (data, 5));
+    SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x923f82a4af194f9b), \
+                W[6] = GET_W_FROM_DATA (data, 6));
+    SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xab1c5ed5da6d8118), \
+                W[7] = GET_W_FROM_DATA (data, 7));
+    SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xd807aa98a3030242), \
+                W[8] = GET_W_FROM_DATA (data, 8));
+    SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x12835b0145706fbe), \
+                W[9] = GET_W_FROM_DATA (data, 9));
+    SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x243185be4ee4b28c), \
+                W[10] = GET_W_FROM_DATA (data, 10));
+    SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x550c7dc3d5ffb4e2), \
+                W[11] = GET_W_FROM_DATA (data, 11));
+    SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x72be5d74f27b896f), \
+                W[12] = GET_W_FROM_DATA (data, 12));
+    SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x80deb1fe3b1696b1), \
+                W[13] = GET_W_FROM_DATA (data, 13));
+    SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x9bdc06a725c71235), \
+                W[14] = GET_W_FROM_DATA (data, 14));
+    SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc19bf174cf692694), \
+                W[15] = GET_W_FROM_DATA (data, 15));
+  }
+
+  /* During last 64 steps, before making any calculations on each step,
+     current W element is generated from other W elements of the cyclic buffer
+     and the generated value is stored back in the cyclic buffer. */
+  /* Note: instead of using K constants as array, all K values are specified
+     individually for each step, see FIPS PUB 180-4 clause 4.2.3 for
+     K values. */
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xe49b69c19ef14ad2), \
+              W[16 & 15] = Wgen (W,16));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xefbe4786384f25e3), \
+              W[17 & 15] = Wgen (W,17));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x0fc19dc68b8cd5b5), \
+              W[18 & 15] = Wgen (W,18));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x240ca1cc77ac9c65), \
+              W[19 & 15] = Wgen (W,19));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x2de92c6f592b0275), \
+              W[20 & 15] = Wgen (W,20));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x4a7484aa6ea6e483), \
+              W[21 & 15] = Wgen (W,21));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5cb0a9dcbd41fbd4), \
+              W[22 & 15] = Wgen (W,22));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x76f988da831153b5), \
+              W[23 & 15] = Wgen (W,23));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x983e5152ee66dfab), \
+              W[24 & 15] = Wgen (W,24));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xa831c66d2db43210), \
+              W[25 & 15] = Wgen (W,25));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb00327c898fb213f), \
+              W[26 & 15] = Wgen (W,26));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xbf597fc7beef0ee4), \
+              W[27 & 15] = Wgen (W,27));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0xc6e00bf33da88fc2), \
+              W[28 & 15] = Wgen (W,28));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xd5a79147930aa725), \
+              W[29 & 15] = Wgen (W,29));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x06ca6351e003826f), \
+              W[30 & 15] = Wgen (W,30));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x142929670a0e6e70), \
+              W[31 & 15] = Wgen (W,31));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x27b70a8546d22ffc), \
+              W[32 & 15] = Wgen (W,32));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x2e1b21385c26c926), \
+              W[33 & 15] = Wgen (W,33));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x4d2c6dfc5ac42aed), \
+              W[34 & 15] = Wgen (W,34));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x53380d139d95b3df), \
+              W[35 & 15] = Wgen (W,35));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x650a73548baf63de), \
+              W[36 & 15] = Wgen (W,36));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x766a0abb3c77b2a8), \
+              W[37 & 15] = Wgen (W,37));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x81c2c92e47edaee6), \
+              W[38 & 15] = Wgen (W,38));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x92722c851482353b), \
+              W[39 & 15] = Wgen (W,39));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xa2bfe8a14cf10364), \
+              W[40 & 15] = Wgen (W,40));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xa81a664bbc423001), \
+              W[41 & 15] = Wgen (W,41));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xc24b8b70d0f89791), \
+              W[42 & 15] = Wgen (W,42));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xc76c51a30654be30), \
+              W[43 & 15] = Wgen (W,43));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0xd192e819d6ef5218), \
+              W[44 & 15] = Wgen (W,44));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xd69906245565a910), \
+              W[45 & 15] = Wgen (W,45));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0xf40e35855771202a), \
+              W[46 & 15] = Wgen (W,46));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x106aa07032bbd1b8), \
+              W[47 & 15] = Wgen (W,47));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x19a4c116b8d2d0c8), \
+              W[48 & 15] = Wgen (W,48));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x1e376c085141ab53), \
+              W[49 & 15] = Wgen (W,49));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x2748774cdf8eeb99), \
+              W[50 & 15] = Wgen (W,50));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x34b0bcb5e19b48a8), \
+              W[51 & 15] = Wgen (W,51));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x391c0cb3c5c95a63), \
+              W[52 & 15] = Wgen (W,52));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x4ed8aa4ae3418acb), \
+              W[53 & 15] = Wgen (W,53));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5b9cca4f7763e373), \
+              W[54 & 15] = Wgen (W,54));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x682e6ff3d6b2b8a3), \
+              W[55 & 15] = Wgen (W,55));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x748f82ee5defb2fc), \
+              W[56 & 15] = Wgen (W,56));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x78a5636f43172f60), \
+              W[57 & 15] = Wgen (W,57));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x84c87814a1f0ab72), \
+              W[58 & 15] = Wgen (W,58));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x8cc702081a6439ec), \
+              W[59 & 15] = Wgen (W,59));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x90befffa23631e28), \
+              W[60 & 15] = Wgen (W,60));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xa4506cebde82bde9), \
+              W[61 & 15] = Wgen (W,61));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0xbef9a3f7b2c67915), \
+              W[62 & 15] = Wgen (W,62));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc67178f2e372532b), \
+              W[63 & 15] = Wgen (W,63));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xca273eceea26619c), \
+              W[64 & 15] = Wgen (W,64));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xd186b8c721c0c207), \
+              W[65 & 15] = Wgen (W,65));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xeada7dd6cde0eb1e), \
+              W[66 & 15] = Wgen (W,66));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xf57d4f7fee6ed178), \
+              W[67 & 15] = Wgen (W,67));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x06f067aa72176fba), \
+              W[68 & 15] = Wgen (W,68));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x0a637dc5a2c898a6), \
+              W[69 & 15] = Wgen (W,69));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x113f9804bef90dae), \
+              W[70 & 15] = Wgen (W,70));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x1b710b35131c471b), \
+              W[71 & 15] = Wgen (W,71));
+  SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x28db77f523047d84), \
+              W[72 & 15] = Wgen (W,72));
+  SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x32caab7b40c72493), \
+              W[73 & 15] = Wgen (W,73));
+  SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x3c9ebe0a15c9bebc), \
+              W[74 & 15] = Wgen (W,74));
+  SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x431d67c49c100d4c), \
+              W[75 & 15] = Wgen (W,75));
+  SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x4cc5d4becb3e42b6), \
+              W[76 & 15] = Wgen (W,76));
+  SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x597f299cfc657e2a), \
+              W[77 & 15] = Wgen (W,77));
+  SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5fcb6fab3ad6faec), \
+              W[78 & 15] = Wgen (W,78));
+  SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x6c44198c4a475817), \
+              W[79 & 15] = Wgen (W,79));
+#else  /* MHD_FAVOR_SMALL_CODE */
+  if (1)
+  {
+    unsigned int t;
+    /* K constants array.
+       See FIPS PUB 180-4 clause 4.2.3 for K values. */
+    static const uint64_t K[80] =
+    { UINT64_C (0x428a2f98d728ae22), UINT64_C (0x7137449123ef65cd),
+      UINT64_C (0xb5c0fbcfec4d3b2f), UINT64_C (0xe9b5dba58189dbbc),
+      UINT64_C (0x3956c25bf348b538), UINT64_C (0x59f111f1b605d019),
+      UINT64_C (0x923f82a4af194f9b), UINT64_C (0xab1c5ed5da6d8118),
+      UINT64_C (0xd807aa98a3030242), UINT64_C (0x12835b0145706fbe),
+      UINT64_C (0x243185be4ee4b28c), UINT64_C (0x550c7dc3d5ffb4e2),
+      UINT64_C (0x72be5d74f27b896f), UINT64_C (0x80deb1fe3b1696b1),
+      UINT64_C (0x9bdc06a725c71235), UINT64_C (0xc19bf174cf692694),
+      UINT64_C (0xe49b69c19ef14ad2), UINT64_C (0xefbe4786384f25e3),
+      UINT64_C (0x0fc19dc68b8cd5b5), UINT64_C (0x240ca1cc77ac9c65),
+      UINT64_C (0x2de92c6f592b0275), UINT64_C (0x4a7484aa6ea6e483),
+      UINT64_C (0x5cb0a9dcbd41fbd4), UINT64_C (0x76f988da831153b5),
+      UINT64_C (0x983e5152ee66dfab), UINT64_C (0xa831c66d2db43210),
+      UINT64_C (0xb00327c898fb213f), UINT64_C (0xbf597fc7beef0ee4),
+      UINT64_C (0xc6e00bf33da88fc2), UINT64_C (0xd5a79147930aa725),
+      UINT64_C (0x06ca6351e003826f), UINT64_C (0x142929670a0e6e70),
+      UINT64_C (0x27b70a8546d22ffc), UINT64_C (0x2e1b21385c26c926),
+      UINT64_C (0x4d2c6dfc5ac42aed), UINT64_C (0x53380d139d95b3df),
+      UINT64_C (0x650a73548baf63de), UINT64_C (0x766a0abb3c77b2a8),
+      UINT64_C (0x81c2c92e47edaee6), UINT64_C (0x92722c851482353b),
+      UINT64_C (0xa2bfe8a14cf10364), UINT64_C (0xa81a664bbc423001),
+      UINT64_C (0xc24b8b70d0f89791), UINT64_C (0xc76c51a30654be30),
+      UINT64_C (0xd192e819d6ef5218), UINT64_C (0xd69906245565a910),
+      UINT64_C (0xf40e35855771202a), UINT64_C (0x106aa07032bbd1b8),
+      UINT64_C (0x19a4c116b8d2d0c8), UINT64_C (0x1e376c085141ab53),
+      UINT64_C (0x2748774cdf8eeb99), UINT64_C (0x34b0bcb5e19b48a8),
+      UINT64_C (0x391c0cb3c5c95a63), UINT64_C (0x4ed8aa4ae3418acb),
+      UINT64_C (0x5b9cca4f7763e373), UINT64_C (0x682e6ff3d6b2b8a3),
+      UINT64_C (0x748f82ee5defb2fc), UINT64_C (0x78a5636f43172f60),
+      UINT64_C (0x84c87814a1f0ab72), UINT64_C (0x8cc702081a6439ec),
+      UINT64_C (0x90befffa23631e28), UINT64_C (0xa4506cebde82bde9),
+      UINT64_C (0xbef9a3f7b2c67915), UINT64_C (0xc67178f2e372532b),
+      UINT64_C (0xca273eceea26619c), UINT64_C (0xd186b8c721c0c207),
+      UINT64_C (0xeada7dd6cde0eb1e), UINT64_C (0xf57d4f7fee6ed178),
+      UINT64_C (0x06f067aa72176fba), UINT64_C (0x0a637dc5a2c898a6),
+      UINT64_C (0x113f9804bef90dae), UINT64_C (0x1b710b35131c471b),
+      UINT64_C (0x28db77f523047d84), UINT64_C (0x32caab7b40c72493),
+      UINT64_C (0x3c9ebe0a15c9bebc), UINT64_C (0x431d67c49c100d4c),
+      UINT64_C (0x4cc5d4becb3e42b6), UINT64_C (0x597f299cfc657e2a),
+      UINT64_C (0x5fcb6fab3ad6faec), UINT64_C (0x6c44198c4a475817)};
+
+    /* One step of SHA-512/256 computation with working variables rotation,
+       see FIPS PUB 180-4 clause 6.4.2 step 3.
+     * Note: this version of macro reassign all working variable on
+             each step. */
+#define SHA2STEP64RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do {              \
+  uint64_t tmp_h_ = (vH);                                             \
+  SHA2STEP64((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt));    \
+  (vH) = (vG);                                                        \
+  (vG) = (vF);                                                        \
+  (vF) = (vE);                                                        \
+  (vE) = (vD);                                                        \
+  (vD) = (vC);                                                        \
+  (vC) = (vB);                                                        \
+  (vB) = (vA);                                                        \
+  (vA) = tmp_h_;  } while (0)
+
+    /* During first 16 steps, before making any calculations on each step,
+       the W element is read from the input data buffer as big-endian value and
+       stored in the array of W elements. */
+    for (t = 0; t < 16; ++t)
+    {
+      SHA2STEP64RV (a, b, c, d, e, f, g, h, K[t], \
+                    W[t] = GET_W_FROM_DATA (data, t));
+    }
+    /* During last 64 steps, before making any calculations on each step,
+       current W element is generated from other W elements of the cyclic buffer
+       and the generated value is stored back in the cyclic buffer. */
+    for (t = 16; t < 80; ++t)
+    {
+      SHA2STEP64RV (a, b, c, d, e, f, g, h, K[t], \
+                    W[t & 15] = Wgen (W,t));
+    }
+  }
+#endif /* MHD_FAVOR_SMALL_CODE */
+
+  /* Compute and store the intermediate hash.
+     See FIPS PUB 180-4 clause 6.4.2 step 4. */
+  H[0] += a;
+  H[1] += b;
+  H[2] += c;
+  H[3] += d;
+  H[4] += e;
+  H[5] += f;
+  H[6] += g;
+  H[7] += h;
+}
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA512_256_update (struct Sha512_256Ctx *ctx,
+                       const uint8_t *data,
+                       size_t length)
+{
+  unsigned int bytes_have; /**< Number of bytes in the context buffer */
+  uint64_t count_hi; /**< The high part to be moved to another variable */
+
+  mhd_assert ((data != NULL) || (length == 0));
+
+#ifndef MHD_FAVOR_SMALL_CODE
+  if (0 == length)
+    return; /* Shortcut, do nothing */
+#endif /* ! MHD_FAVOR_SMALL_CODE */
+
+  /* Note: (count & (SHA512_256_BLOCK_SIZE-1))
+           equals (count % SHA512_256_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1));
+  ctx->count += length;
+  count_hi = ctx->count >> 61;
+  if (0 != count_hi)
+  {
+    ctx->count_bits_hi += count_hi;
+    ctx->count &= UINT64_C (0x1FFFFFFFFFFFFFFF);
+  }
+
+  if (0 != bytes_have)
+  {
+    unsigned int bytes_left = SHA512_256_BLOCK_SIZE - bytes_have;
+    if (length >= bytes_left)
+    {     /* Combine new data with data in the buffer and
+             process the full block. */
+      memcpy (((uint8_t *) ctx->buffer) + bytes_have,
+              data,
+              bytes_left);
+      data += bytes_left;
+      length -= bytes_left;
+      sha512_256_transform (ctx->H, ctx->buffer);
+      bytes_have = 0;
+    }
+  }
+
+  while (SHA512_256_BLOCK_SIZE <= length)
+  {   /* Process any full blocks of new data directly,
+         without copying to the buffer. */
+    sha512_256_transform (ctx->H, data);
+    data += SHA512_256_BLOCK_SIZE;
+    length -= SHA512_256_BLOCK_SIZE;
+  }
+
+  if (0 != length)
+  {   /* Copy incomplete block of new data (if any)
+         to the buffer. */
+    memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length);
+  }
+}
+
+
+/**
+ * Size of "length" insertion in bits.
+ * See FIPS PUB 180-4 clause 5.1.2.
+ */
+#define SHA512_256_SIZE_OF_LEN_ADD_BITS 128
+
+/**
+ * Size of "length" insertion in bytes.
+ */
+#define SHA512_256_SIZE_OF_LEN_ADD (SHA512_256_SIZE_OF_LEN_ADD_BITS / 8)
+
+/**
+ * Finalise SHA-512/256 calculation, return digest.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA512_256_finish (struct Sha512_256Ctx *ctx,
+                       uint8_t digest[SHA512_256_DIGEST_SIZE])
+{
+  uint64_t num_bits;   /**< Number of processed bits */
+  unsigned int bytes_have; /**< Number of bytes in the context buffer */
+
+  /* Memorise the number of processed bits.
+     The padding and other data added here during the postprocessing must
+     not change the amount of hashed data. */
+  num_bits = ctx->count << 3;
+
+  /* Note: (count & (SHA512_256_BLOCK_SIZE-1))
+           equals (count % SHA512_256_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1));
+
+  /* Input data must be padded with a single bit "1", then with zeros and
+     the finally the length of data in bits must be added as the final bytes
+     of the last block.
+     See FIPS PUB 180-4 clause 5.1.2. */
+
+  /* Data is always processed in form of bytes (not by individual bits),
+     therefore position of the first padding bit in byte is always
+     predefined (0x80). */
+  /* Buffer always have space for one byte at least (as full buffers are
+     processed immediately). */
+  ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80;
+
+  if (SHA512_256_BLOCK_SIZE - bytes_have < SHA512_256_SIZE_OF_LEN_ADD)
+  {   /* No space in the current block to put the total length of message.
+         Pad the current block with zeros and process it. */
+    if (bytes_have < SHA512_256_BLOCK_SIZE)
+      memset (((uint8_t *) ctx->buffer) + bytes_have, 0,
+              SHA512_256_BLOCK_SIZE - bytes_have);
+    /* Process the full block. */
+    sha512_256_transform (ctx->H, ctx->buffer);
+    /* Start the new block. */
+    bytes_have = 0;
+  }
+
+  /* Pad the rest of the buffer with zeros. */
+  memset (((uint8_t *) ctx->buffer) + bytes_have, 0,
+          SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD - bytes_have);
+  /* Put high part of number of bits in processed message and then lower
+     part of number of bits as big-endian values.
+     See FIPS PUB 180-4 clause 5.1.2. */
+  /* Note: the target location is predefined and buffer is always aligned */
+  _MHD_PUT_64BIT_BE (ctx->buffer + SHA512_256_BLOCK_SIZE_WORDS - 2,
+                     ctx->count_bits_hi);
+  _MHD_PUT_64BIT_BE (ctx->buffer + SHA512_256_BLOCK_SIZE_WORDS - 1,
+                     num_bits);
+  /* Process the full final block. */
+  sha512_256_transform (ctx->H, ctx->buffer);
+
+  /* Put in BE mode the leftmost part of the hash as the final digest.
+     See FIPS PUB 180-4 clause 6.7. */
+#ifndef _MHD_PUT_64BIT_BE_UNALIGNED
+  if (1
+#ifndef MHD_FAVOR_SMALL_CODE
+      && (0 != ((uintptr_t) digest) % _MHD_UINT64_ALIGN)
+#endif /* MHD_FAVOR_SMALL_CODE */
+      )
+  {
+    /* If storing of the final result requires aligned address and
+       the destination address is not aligned or compact code is used,
+       store the final digest in aligned temporary buffer first, then
+       copy it to the destination. */
+    uint64_t alig_dgst[SHA512_256_DIGEST_SIZE_WORDS];
+    _MHD_PUT_64BIT_BE (alig_dgst + 0, ctx->H[0]);
+    _MHD_PUT_64BIT_BE (alig_dgst + 1, ctx->H[1]);
+    _MHD_PUT_64BIT_BE (alig_dgst + 2, ctx->H[2]);
+    _MHD_PUT_64BIT_BE (alig_dgst + 3, ctx->H[3]);
+    /* Copy result to the unaligned destination address */
+    memcpy (digest, alig_dgst, SHA512_256_DIGEST_SIZE);
+  }
+#ifndef MHD_FAVOR_SMALL_CODE
+  else /* Combined with the next 'if' */
+#endif /* MHD_FAVOR_SMALL_CODE */
+#endif /* ! _MHD_PUT_64BIT_BE_UNALIGNED */
+#if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_64BIT_BE_UNALIGNED)
+  if (1)
+  {
+    /* Use cast to (void*) here to mute compiler alignment warnings.
+     * Compilers are not smart enough to see that alignment has been checked. */
+    _MHD_PUT_64BIT_BE ((void *) (digest + 0 * SHA512_256_BYTES_IN_WORD), \
+                       ctx->H[0]);
+    _MHD_PUT_64BIT_BE ((void *) (digest + 1 * SHA512_256_BYTES_IN_WORD), \
+                       ctx->H[1]);
+    _MHD_PUT_64BIT_BE ((void *) (digest + 2 * SHA512_256_BYTES_IN_WORD), \
+                       ctx->H[2]);
+    _MHD_PUT_64BIT_BE ((void *) (digest + 3 * SHA512_256_BYTES_IN_WORD), \
+                       ctx->H[3]);
+  }
+#endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_64BIT_BE_UNALIGNED */
+
+  /* Erase potentially sensitive data. */
+  memset (ctx, 0, sizeof(struct Sha512_256Ctx));
+}
diff --git a/src/microhttpd/sha512_256.h b/src/microhttpd/sha512_256.h
new file mode 100644
index 0000000..31200c2
--- /dev/null
+++ b/src/microhttpd/sha512_256.h
@@ -0,0 +1,137 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha512_256.h
+ * @brief  Calculation of SHA-512/256 digest
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SHA512_256_H
+#define MHD_SHA512_256_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
+
+
+/**
+ * Number of bits in single SHA-512/256 word.
+ */
+#define SHA512_256_WORD_SIZE_BITS 64
+
+/**
+ * Number of bytes in single SHA-512/256 word.
+ */
+#define SHA512_256_BYTES_IN_WORD (SHA512_256_WORD_SIZE_BITS / 8)
+
+/**
+ * Hash is kept internally as 8 64-bit words.
+ * This is intermediate hash size, used during computing the final digest.
+ */
+#define SHA512_256_HASH_SIZE_WORDS 8
+
+/**
+ * Size of SHA-512/256 resulting digest in bytes.
+ * This is the final digest size, not intermediate hash.
+ */
+#define SHA512_256_DIGEST_SIZE_WORDS (SHA512_256_HASH_SIZE_WORDS  / 2)
+
+/**
+ * Size of SHA-512/256 resulting digest in bytes
+ * This is the final digest size, not intermediate hash.
+ */
+#define SHA512_256_DIGEST_SIZE \
+  (SHA512_256_DIGEST_SIZE_WORDS * SHA512_256_BYTES_IN_WORD)
+
+/**
+ * Size of SHA-512/256 digest string in chars including termination NUL.
+ */
+#define SHA512_256_DIGEST_STRING_SIZE ((SHA512_256_DIGEST_SIZE) * 2 + 1)
+
+/**
+ * Size of SHA-512/256 single processing block in bits.
+ */
+#define SHA512_256_BLOCK_SIZE_BITS 1024
+
+/**
+ * Size of SHA-512/256 single processing block in bytes.
+ */
+#define SHA512_256_BLOCK_SIZE (SHA512_256_BLOCK_SIZE_BITS / 8)
+
+/**
+ * Size of SHA-512/256 single processing block in words.
+ */
+#define SHA512_256_BLOCK_SIZE_WORDS \
+ (SHA512_256_BLOCK_SIZE_BITS / SHA512_256_WORD_SIZE_BITS)
+
+
+/**
+ * SHA-512/256 calculation context
+ */
+struct Sha512_256Ctx
+{
+  uint64_t H[SHA512_256_HASH_SIZE_WORDS];       /**< Intermediate hash value  */
+  uint64_t buffer[SHA512_256_BLOCK_SIZE_WORDS]; /**< SHA512_256 input data buffer */
+  /**
+   * The number of bytes, lower part
+   */
+  uint64_t count;
+  /**
+   * The number of bits, high part.
+   * Unlike lower part, this counts the number of bits, not bytes.
+   */
+  uint64_t count_bits_hi;
+};
+
+/**
+ * Initialise structure for SHA-512/256 calculation.
+ *
+ * @param ctx the calculation context
+ */
+void
+MHD_SHA512_256_init (struct Sha512_256Ctx *ctx);
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx the calculation context
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA512_256_update (struct Sha512_256Ctx *ctx,
+                       const uint8_t *data,
+                       size_t length);
+
+
+/**
+ * Finalise SHA-512/256 calculation, return digest.
+ *
+ * @param ctx the calculation context
+ * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA512_256_finish (struct Sha512_256Ctx *ctx,
+                       uint8_t digest[SHA512_256_DIGEST_SIZE]);
+
+#endif /* MHD_SHA512_256_H */
diff --git a/src/microhttpd/sysfdsetsize.c b/src/microhttpd/sysfdsetsize.c
new file mode 100644
index 0000000..f645215
--- /dev/null
+++ b/src/microhttpd/sysfdsetsize.c
@@ -0,0 +1,82 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/sysfdsetsize.c
+ * @brief  Helper for obtaining FD_SETSIZE system default value
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+
+#include "MHD_config.h"
+
+#ifdef FD_SETSIZE
+/* FD_SETSIZE was defined before system headers. */
+/* To get system value of FD_SETSIZE, undefine FD_SETSIZE
+   here. */
+#undef FD_SETSIZE
+#endif /* FD_SETSIZE */
+
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS)
+#include <sockLib.h>
+#endif /* OS_VXWORKS */
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif /* HAVE_SYS_SELECT_H */
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif /* HAVE_SYS_TIME_H */
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <winsock2.h>
+#endif /* _WIN32 && !__CYGWIN__ */
+
+#ifndef FD_SETSIZE
+#error FD_SETSIZE must be defined in system headers
+#endif /* !FD_SETSIZE */
+
+#include "sysfdsetsize.h"
+
+/**
+ * Get system default value of FD_SETSIZE
+ * @return system default value of FD_SETSIZE
+ */
+unsigned int
+get_system_fdsetsize_value (void)
+{
+  return FD_SETSIZE;
+}
diff --git a/src/microhttpd/sysfdsetsize.h b/src/microhttpd/sysfdsetsize.h
new file mode 100644
index 0000000..6b0e37d
--- /dev/null
+++ b/src/microhttpd/sysfdsetsize.h
@@ -0,0 +1,36 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2015 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/sysfdsetsize.h
+ * @brief  Helper for obtaining FD_SETSIZE system default value
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef SYSFDSETSIZE_H
+#define SYSFDSETSIZE_H 1
+
+/**
+ * Get system default value of FD_SETSIZE
+ * @return system default value of FD_SETSIZE
+ */
+unsigned int
+get_system_fdsetsize_value (void);
+
+#endif /* !SYSFDSETSIZE_H */
diff --git a/src/microhttpd/test_auth_parse.c b/src/microhttpd/test_auth_parse.c
new file mode 100644
index 0000000..8c11499
--- /dev/null
+++ b/src/microhttpd/test_auth_parse.c
@@ -0,0 +1,1653 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_auth_parse.c
+ * @brief  Unit tests for request's 'Authorization" headers parsing
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "gen_auth.h"
+#ifdef BAUTH_SUPPORT
+#include "basicauth.h"
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+#include "digestauth.h"
+#endif /* DAUTH_SUPPORT */
+#include "mhd_assert.h"
+#include "internal.h"
+#include "connection.h"
+
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Declarations for local replacements of MHD functions */
+/* None, headers are included */
+
+/* Local replacements implementations */
+
+void *
+MHD_connection_alloc_memory_ (struct MHD_Connection *connection,
+                              size_t size)
+{
+  void *ret;
+  if (NULL == connection)
+    mhdErrorExitDesc ("'connection' parameter is NULL");
+  /* Use 'read_buffer' just as a flag */
+  if (NULL != connection->read_buffer)
+  {
+    /* Use 'write_buffer' just as a flag */
+    if (NULL != connection->write_buffer)
+      mhdErrorExitDesc ("Unexpected third memory allocation, " \
+                        "while previous allocations was not freed");
+  }
+  /* Just use simple "malloc()" here */
+  ret = malloc (size);
+  if (NULL == ret)
+    externalErrorExit ();
+
+  /* Track up to two allocations */
+  if (NULL == connection->read_buffer)
+    connection->read_buffer = (char *) ret;
+  else
+    connection->write_buffer = (char *) ret;
+  return ret;
+}
+
+
+/**
+ * Static variable to avoid additional malloc()/free() pairs
+ */
+static struct MHD_Connection conn;
+
+void
+MHD_DLOG (const struct MHD_Daemon *daemon,
+          const char *format,
+          ...)
+{
+  (void) daemon;
+  if (NULL == conn.rq.last)
+  {
+    fprintf (stderr, "Unexpected call of 'MHD_LOG(), format is '%s'.\n",
+             format);
+    fprintf (stderr, "'Authorization' header value: '%s'.\n",
+             (NULL == conn.rq.headers_received) ?
+             "NULL" : (conn.rq.headers_received->value));
+    mhdErrorExit ();
+  }
+  conn.rq.last = NULL; /* Clear the flag */
+  return;
+}
+
+
+/**
+ * Static variable to avoid additional malloc()/free() pairs
+ */
+static struct MHD_HTTP_Req_Header req_header;
+
+static void
+test_global_init (void)
+{
+  memset (&conn, 0, sizeof(conn));
+  memset (&req_header, 0, sizeof(req_header));
+}
+
+
+/**
+ * Add "Authorization" client test header.
+ *
+ * @param hdr the pointer to the headr value, must be valid until end of
+ *            checking of this header
+ * @param hdr_len the length of the @a hdr
+ * @note The function is NOT thread-safe
+ */
+static void
+add_AuthHeader (const char *hdr, size_t hdr_len)
+{
+  if ((NULL != conn.rq.headers_received) ||
+      (NULL != conn.rq.headers_received_tail))
+    externalErrorExitDesc ("Connection's test headers are not empty already");
+  if (NULL != hdr)
+  {
+    /* Skip initial whitespaces, emulate MHD's headers processing */
+    while (' ' == hdr[0] || '\t' == hdr[0])
+    {
+      hdr++;
+      hdr_len--;
+    }
+    req_header.header = MHD_HTTP_HEADER_AUTHORIZATION; /* Static string */
+    req_header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION);
+    req_header.value = hdr;
+    req_header.value_size = hdr_len;
+    req_header.kind = MHD_HEADER_KIND;
+    req_header.prev = NULL;
+    req_header.next = NULL;
+    conn.rq.headers_received = &req_header;
+    conn.rq.headers_received_tail = &req_header;
+  }
+  else
+  {
+    conn.rq.headers_received = NULL;
+    conn.rq.headers_received_tail = NULL;
+  }
+  conn.state = MHD_CONNECTION_FULL_REQ_RECEIVED; /* Should be a typical value */
+}
+
+
+#ifdef BAUTH_SUPPORT
+/**
+ * Parse previously added Basic Authorization client header and return
+ * result of the parsing.
+ *
+ * Function performs basic checking of the parsing result
+ * @return result of header parsing
+ * @note The function is NOT thread-safe
+ */
+static const struct MHD_RqBAuth *
+get_BAuthRqParams (void)
+{
+  const struct MHD_RqBAuth *res1;
+  const struct MHD_RqBAuth *res2;
+  /* Store pointer in some member unused in this test */
+  res1 = MHD_get_rq_bauth_params_ (&conn);
+  if (! conn.rq.bauth_tried)
+    mhdErrorExitDesc ("'rq.bauth_tried' is not set");
+  res2 = MHD_get_rq_bauth_params_ (&conn);
+  if (res1 != res2)
+    mhdErrorExitDesc ("MHD_get_rq_bauth_params_() returned another pointer " \
+                      "when called for the second time");
+  return res2;
+}
+
+
+#endif /* BAUTH_SUPPORT */
+
+#ifdef DAUTH_SUPPORT
+/**
+ * Parse previously added Digest Authorization client header and return
+ * result of the parsing.
+ *
+ * Function performs basic checking of the parsing result
+ * @return result of header parsing
+ * @note The function is NOT thread-safe
+ */
+static const struct MHD_RqDAuth *
+get_DAuthRqParams (void)
+{
+  const struct MHD_RqDAuth *res1;
+  const struct MHD_RqDAuth *res2;
+  /* Store pointer in some member unused in this test */
+  res1 = MHD_get_rq_dauth_params_ (&conn);
+  if (! conn.rq.dauth_tried)
+    mhdErrorExitDesc ("'rq.dauth_tried' is not set");
+  res2 = MHD_get_rq_dauth_params_ (&conn);
+  if (res1 != res2)
+    mhdErrorExitDesc ("MHD_get_rq_bauth_params_() returned another pointer " \
+                      "when called for the second time");
+  return res2;
+}
+
+
+#endif /* DAUTH_SUPPORT */
+
+
+static void
+clean_AuthHeaders (void)
+{
+  conn.state = MHD_CONNECTION_INIT;
+  free (conn.read_buffer);
+  free (conn.write_buffer);
+
+#ifdef BAUTH_SUPPORT
+  conn.rq.bauth_tried = false;
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  conn.rq.dauth_tried = false;
+#endif /* BAUTH_SUPPORT */
+
+#ifdef BAUTH_SUPPORT
+  if ((NULL != conn.rq.bauth) &&
+      (conn.read_buffer != (const char *) conn.rq.bauth) &&
+      (conn.write_buffer != (const char *) conn.rq.bauth))
+    externalErrorExitDesc ("Memory allocation is not tracked as it should be");
+  conn.rq.bauth = NULL;
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  if ((NULL != conn.rq.dauth) &&
+      (conn.read_buffer != (const char *) conn.rq.dauth) &&
+      (conn.write_buffer != (const char *) conn.rq.dauth))
+    externalErrorExitDesc ("Memory allocation is not tracked as it should be");
+  conn.rq.dauth = NULL;
+#endif /* BAUTH_SUPPORT */
+
+  conn.rq.headers_received = NULL;
+  conn.rq.headers_received_tail = NULL;
+
+  conn.read_buffer = NULL;
+  conn.write_buffer = NULL;
+  conn.rq.last = NULL;
+}
+
+
+enum MHD_TestAuthType
+{
+  MHD_TEST_AUTHTYPE_NONE,
+  MHD_TEST_AUTHTYPE_BASIC,
+  MHD_TEST_AUTHTYPE_DIGEST,
+};
+
+
+/* return zero if succeed, non-zero otherwise */
+static unsigned int
+expect_result_type_n (const char *hdr, size_t hdr_len,
+                      const enum MHD_TestAuthType expected_type,
+                      int expect_log,
+                      unsigned int line_num)
+{
+  static char marker1[] = "Expected log call";
+  unsigned int ret;
+
+  ret = 0;
+  add_AuthHeader (hdr, hdr_len);
+  if (expect_log)
+    conn.rq.last = marker1; /* Use like a flag */
+  else
+    conn.rq.last = NULL;
+#ifdef BAUTH_SUPPORT
+  if (MHD_TEST_AUTHTYPE_BASIC == expected_type)
+  {
+    if (NULL == get_BAuthRqParams ())
+    {
+      fprintf (stderr,
+               "'Authorization' header parsing FAILED:\n"
+               "Basic Authorization was not found, while it should be.\n");
+      ret++;
+    }
+  }
+  else
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  if (MHD_TEST_AUTHTYPE_DIGEST == expected_type)
+  {
+    if (NULL == get_DAuthRqParams ())
+    {
+      fprintf (stderr,
+               "'Authorization' header parsing FAILED:\n"
+               "Digest Authorization was not found, while it should be.\n");
+      ret++;
+    }
+  }
+  else
+#endif /* BAUTH_SUPPORT */
+  {
+#ifdef BAUTH_SUPPORT
+    if (NULL != get_BAuthRqParams ())
+    {
+      fprintf (stderr,
+               "'Authorization' header parsing FAILED:\n"
+               "Found Basic Authorization, while it should not be.\n");
+      ret++;
+    }
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+    if (NULL != get_DAuthRqParams ())
+    {
+      fprintf (stderr,
+               "'Authorization' header parsing FAILED:\n"
+               "Found Digest Authorization, while it should not be.\n");
+      ret++;
+    }
+#endif /* DAUTH_SUPPORT */
+  }
+#if defined(BAUTH_SUPPORT) && defined(DAUTH_SUPPORT)
+  if (conn.rq.last)
+  {
+    fprintf (stderr,
+             "'Authorization' header parsing ERROR:\n"
+             "Log function must be called, but it was not.\n");
+    ret++;
+  }
+#endif /* BAUTH_SUPPORT && DAUTH_SUPPORT */
+
+  if (ret)
+  {
+    if (NULL == hdr)
+      fprintf (stderr,
+               "Input: Absence of 'Authorization' header.\n");
+    else if (0 == hdr_len)
+      fprintf (stderr,
+               "Input: empty 'Authorization' header.\n");
+    else
+      fprintf (stderr,
+               "Input Header: '%.*s'\n", (int) hdr_len, hdr);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret = 1;
+  }
+  clean_AuthHeaders ();
+
+  return ret;
+}
+
+
+#define expect_result_type(h,t,l) \
+    expect_result_type_n(h,MHD_STATICSTR_LEN_(h),t,l,__LINE__)
+
+
+static unsigned int
+check_type (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_result_type_n (NULL, 0, MHD_TEST_AUTHTYPE_NONE, 0, __LINE__);
+
+  r += expect_result_type ("", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("    ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" \t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t \t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" \t ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" \t \t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t \t ", MHD_TEST_AUTHTYPE_NONE, 0);
+
+  r += expect_result_type ("Basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" Basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\tBasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t Basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" \tBasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("    Basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t\tBasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \tBasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \t Basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("Basic ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("Basic \t", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("Basic \t ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("Basic 123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("Basic \t123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("Basic  abc ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" \tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("    bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t\tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \t bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC \t", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC \t ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC 123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC \t123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("bAsIC  abc ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\tbasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" \tbasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("    basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t\tbasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \tbasic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \t basic", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic \t", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic \t ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic 123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic \t123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("basic  abc ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" BASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t BASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type (" \tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("    BASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t\tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("\t\t  \t BASIC", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC \t", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC \t ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC 123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC \t123", MHD_TEST_AUTHTYPE_BASIC, 0);
+  r += expect_result_type ("BASIC  abc ", MHD_TEST_AUTHTYPE_BASIC, 0);
+  /* Only single token is allowed for 'Basic' Authorization */
+  r += expect_result_type ("Basic a b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic a\tb", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic a\tb", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic abc1 b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic c abc1", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic c abc1 ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic c abc1\t", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic c\tabc1\t", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic c abc1 b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic zyx, b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic zyx,b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic zyx ,b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic zyx;b", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Basic zyx; b", MHD_TEST_AUTHTYPE_NONE, 1);
+
+  r += expect_result_type ("Basic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" Basic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" Basic2 ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\tBasic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t Basic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" \tBasic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("    Basic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t\t\tBasic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t\t  \tBasic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t\t  \t Basic2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic2 ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic2 \t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic2 \t ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic2 123", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic2 \t123", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic2  abc ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\tBasicBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\t BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" \tBasicBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("BasicBasic ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("BasicBasic \t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("BasicBasic \t\t", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("BasicDigest", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" BasicDigest", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("BasicDigest ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Basic\0", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\0" "Basic", MHD_TEST_AUTHTYPE_NONE, 0);
+
+  r += expect_result_type ("Digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" Digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t Digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" \tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("    Digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t\tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \t Digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tDigest ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("  Digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t \tDigest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+
+  r += expect_result_type ("digEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" digEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t digEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" \tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("    digEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t\tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \t digEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digEST ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tdigEST ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("  digEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t \tdigEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" \tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("    digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t\tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \t digest", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digest ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("digest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tdigest ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("  digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t \tdigest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type (" \tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("    DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t\tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t\t  \t DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("DIGEST ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("DIGEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("DIGEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\tDIGEST ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("  DIGEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("\t \tDIGEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,\t", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,  ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest   ,  ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,\t, ,\t, ,\t, ,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,\t,\t,\t,\t,\t,\t,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a=b", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a=\"b\"", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc=1", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc=\"1\"", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a=b ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a=\"b\" ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc=1 ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc=\"1\" ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a = b", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a\t=\t\"b\"", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc =1", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc= \"1\"", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a=\tb ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest a = \"b\" ", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc\t\t\t= 1 ", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc   =\t\t\t\"1\" ", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc =1,,,,", MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest nc =1  ,,,,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,,nc= \"1 \"", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,,  nc= \" 1\"", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,, nc= \"1\",,,,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,, nc= \"1\"  ,,,,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,, nc= \"1\"  ,,,,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,, nc= \"1\"  ,,,,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+  r += expect_result_type ("Digest ,,,, nc= \"1\"  ,,,,,", \
+                           MHD_TEST_AUTHTYPE_DIGEST, 0);
+
+  r += expect_result_type ("Digest nc", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest   nc", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc  ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc  ,", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc  , ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest \tnc\t  ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest \tnc\t  ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc,", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc,uri", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1,uri", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1,uri   ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1,uri,", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1, uri,", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1,uri   ,", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1,uri   , ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  /* Binary zero */
+  r += expect_result_type ("Digest nc=1\0", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1\0" " ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1\t\0", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\0" "1", MHD_TEST_AUTHTYPE_NONE, 1);
+  /* Semicolon */
+  r += expect_result_type ("Digest nc=1;", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1; ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=;1", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc;=1", MHD_TEST_AUTHTYPE_NONE, 1);
+  /* The equal sign alone */
+  r += expect_result_type ("Digest =", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest   =", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest   =  ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest ,=", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest , =", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest ,= ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest , = ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1,=", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=1, =", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=bar,=", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=bar, =", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  /* Unclosed quotation */
+  r += expect_result_type ("Digest nc=\"", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"abc", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"   ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"abc   ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"   abc", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"   abc", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"\\", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"\\\"", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"  \\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"\\\"  ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"  \\\"  ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc=\"\\\"\\\"\\\"\\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"abc", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"   ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"abc   ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"   abc", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"   abc", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"\\", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"\\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"  \\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"\\\"  ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"  \\\"  ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest nc= \"\\\"\\\"\\\"\\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"bar", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"   ", MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"bar   ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"   bar", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"   bar", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo= \"   bar", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\",   bar", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"   bar,", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"\\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"  \\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"\\\"  ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"  \\\"  ", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest foo=\"\\\"\\\"\\\"\\\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  /* Full set of parameters with semicolon inside */
+  r += expect_result_type ("Digest username=\"test@example.com\", " \
+                           "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \
+                           "uri=\"/example\", qop=auth, nc=00000001; cnonce=\"0a4f113b\", " \
+                           "response=\"6629fae49393a05397450978507c4ef1\", " \
+                           "opaque=\"sadfljk32sdaf\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest username=\"test@example.com\", " \
+                           "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \
+                           "uri=\"/example\", qop=auth, nc=00000001;cnonce=\"0a4f113b\", " \
+                           "response=\"6629fae49393a05397450978507c4ef1\", " \
+                           "opaque=\"sadfljk32sdaf\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+  r += expect_result_type ("Digest username;=\"test@example.com\", " \
+                           "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \
+                           "uri=\"/example\", qop=auth, nc=00000001, cnonce=\"0a4f113b\", " \
+                           "response=\"6629fae49393a05397450978507c4ef1\", " \
+                           "opaque=\"sadfljk32sdaf\"", \
+                           MHD_TEST_AUTHTYPE_NONE, 1);
+
+  r += expect_result_type ("Digest2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("2Digest", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("a" "Digest", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" Digest2", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" 2Digest", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" a" "Digest", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Digest2 ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("2Digest ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("a" "Digest ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("DigestBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("DigestBasic ", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type (" DigestBasic", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("DigestBasic" "a", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("Digest" "\0", MHD_TEST_AUTHTYPE_NONE, 0);
+  r += expect_result_type ("\0" "Digest", MHD_TEST_AUTHTYPE_NONE, 0);
+  return r;
+}
+
+
+#ifdef BAUTH_SUPPORT
+
+/* return zero if succeed, 1 otherwise */
+static unsigned int
+expect_basic_n (const char *hdr, size_t hdr_len,
+                const char *tkn, size_t tkn_len,
+                unsigned int line_num)
+{
+  const struct MHD_RqBAuth *h;
+  unsigned int ret;
+
+  mhd_assert (NULL != hdr);
+  mhd_assert (0 != hdr_len);
+
+  add_AuthHeader (hdr, hdr_len);
+  h = get_BAuthRqParams ();
+  if (NULL == h)
+    mhdErrorExitDesc ("'MHD_get_rq_bauth_params_()' returned NULL");
+  ret = 1;
+  if (tkn_len != h->token68.len)
+    fprintf (stderr,
+             "'Authorization' header parsing FAILED:\n"
+             "Wrong token length:\tRESULT[%u]: %.*s\tEXPECTED[%u]: %.*s\n",
+             (unsigned) h->token68.len,
+             (int) h->token68.len,
+             h->token68.str ?
+             h->token68.str : "(NULL)",
+             (unsigned) tkn_len, (int) tkn_len, tkn ? tkn : "(NULL)");
+  else if ( ((NULL == tkn) != (NULL == h->token68.str)) ||
+            ((NULL != tkn) &&
+             (0 != memcmp (tkn, h->token68.str, tkn_len))) )
+    fprintf (stderr,
+             "'Authorization' header parsing FAILED:\n"
+             "Wrong token string:\tRESULT[%u]: %.*s\tEXPECTED[%u]: %.*s\n",
+             (unsigned) h->token68.len,
+             (int) h->token68.len,
+             h->token68.str ?
+             h->token68.str : "(NULL)",
+             (unsigned) tkn_len, (int) tkn_len, tkn ? tkn : "(NULL)");
+  else
+    ret = 0;
+  if (0 != ret)
+  {
+    fprintf (stderr,
+             "Input Header: '%.*s'\n", (int) hdr_len, hdr);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  clean_AuthHeaders ();
+
+  return ret;
+}
+
+
+#define expect_basic(h,t) \
+    expect_basic_n(h,MHD_STATICSTR_LEN_(h),t,MHD_STATICSTR_LEN_(t),__LINE__)
+
+static unsigned int
+check_basic (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_basic ("Basic a", "a");
+  r += expect_basic ("Basic    a", "a");
+  r += expect_basic ("Basic \ta", "a");
+  r += expect_basic ("Basic \ta\t", "a");
+  r += expect_basic ("Basic \ta ", "a");
+  r += expect_basic ("Basic  a ", "a");
+  r += expect_basic ("Basic \t a\t ", "a");
+  r += expect_basic ("Basic \t abc\t ", "abc");
+  r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc  ", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("Basic   2143sdfa4325sdfgfdab354354314SDSDFc", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("Basic   2143sdfa4325sdfgfdab354354314SDSDFc  ", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("  Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("  Basic  2143sdfa4325sdfgfdab354354314SDSDFc", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("  Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("  Basic  2143sdfa4325sdfgfdab354354314SDSDFc ", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("  Basic  2143sdfa4325sdfgfdab354354314SDSDFc  ", \
+                     "2143sdfa4325sdfgfdab354354314SDSDFc");
+  r += expect_basic ("Basic -A.1-z~9+/=====", "-A.1-z~9+/=====");
+  r += expect_basic ("  Basic   -A.1-z~9+/===== ", "-A.1-z~9+/=====");
+
+  r += expect_basic_n ("Basic", MHD_STATICSTR_LEN_ ("Basic"), NULL, 0,__LINE__);
+  r += expect_basic_n ("   Basic", MHD_STATICSTR_LEN_ ("   Basic"), NULL, 0,
+                       __LINE__);
+  r += expect_basic_n ("Basic   ", MHD_STATICSTR_LEN_ ("Basic   "), NULL, 0,
+                       __LINE__);
+  r += expect_basic_n ("Basic \t\t", MHD_STATICSTR_LEN_ ("Basic \t\t"), NULL, 0,
+                       __LINE__);
+
+  return r;
+}
+
+
+#endif /* BAUTH_SUPPORT */
+
+
+#ifdef DAUTH_SUPPORT
+
+/* return zero if succeed, 1 otherwise */
+static unsigned int
+cmp_dauth_param (const char *pname, const struct MHD_RqDAuthParam *param,
+                 const char *expected_value)
+{
+  unsigned int ret;
+  size_t expected_len;
+  bool expected_quoted;
+  mhd_assert (NULL != param);
+  mhd_assert (NULL != pname);
+  ret = 0;
+
+  if (NULL == expected_value)
+  {
+    expected_len = 0;
+    expected_quoted = false;
+    if (NULL != param->value.str)
+      ret = 1;
+    else if (param->value.len != expected_len)
+      ret = 1;
+    else if (param->quoted != expected_quoted)
+      ret = 1;
+  }
+  else
+  {
+    expected_len = strlen (expected_value);
+    expected_quoted = (NULL != memchr (expected_value, '\\', expected_len));
+    if (NULL == param->value.str)
+      ret = 1;
+    else if (param->value.len != expected_len)
+      ret = 1;
+    else if (param->quoted != expected_quoted)
+      ret = 1;
+    else if (0 != memcmp (param->value.str, expected_value, expected_len))
+      ret = 1;
+  }
+  if (0 != ret)
+  {
+    fprintf (stderr, "Parameter '%s' parsed incorrectly:\n", pname);
+    fprintf (stderr, "\tRESULT  :\tvalue.str: %.*s",
+             (int) (param->value.str ? param->value.len : 6),
+             param->value.str ? param->value.str : "(NULL)");
+    fprintf (stderr, "\tvalue.len: %u",
+             (unsigned) param->value.len);
+    fprintf (stderr, "\tquoted: %s\n",
+             (unsigned) param->quoted ? "true" : "false");
+    fprintf (stderr, "\tEXPECTED:\tvalue.str: %.*s",
+             (int) (expected_value ? expected_len : 6),
+             expected_value ? expected_value : "(NULL)");
+    fprintf (stderr, "\tvalue.len: %u",
+             (unsigned) expected_len);
+    fprintf (stderr, "\tquoted: %s\n",
+             (unsigned) expected_quoted ? "true" : "false");
+  }
+  return ret;
+}
+
+
+/* return zero if succeed, 1 otherwise */
+static unsigned int
+expect_digest_n (const char *hdr, size_t hdr_len,
+                 const char *nonce,
+                 enum MHD_DigestAuthAlgo3 algo3,
+                 const char *response,
+                 const char *username,
+                 const char *username_ext,
+                 const char *realm,
+                 const char *uri,
+                 const char *qop_raw,
+                 enum MHD_DigestAuthQOP qop,
+                 const char *cnonce,
+                 const char *nc,
+                 int userhash,
+                 unsigned int line_num)
+{
+  const struct MHD_RqDAuth *h;
+  unsigned int ret;
+
+  mhd_assert (NULL != hdr);
+  mhd_assert (0 != hdr_len);
+
+  add_AuthHeader (hdr, hdr_len);
+
+  h = get_DAuthRqParams ();
+  if (NULL == h)
+    mhdErrorExitDesc ("'MHD_get_rq_dauth_params_()' returned NULL");
+  ret = 0;
+
+  ret += cmp_dauth_param ("nonce", &h->nonce, nonce);
+  if (h->algo3 != algo3)
+  {
+    ret += 1;
+    fprintf (stderr, "Parameter 'algorithm' detected incorrectly:\n");
+    fprintf (stderr, "\tRESULT  :\t%u\n",
+             (unsigned) h->algo3);
+    fprintf (stderr, "\tEXPECTED:\t%u\n",
+             (unsigned) algo3);
+  }
+  ret += cmp_dauth_param ("response", &h->response, response);
+  ret += cmp_dauth_param ("username", &h->username, username);
+  ret += cmp_dauth_param ("username_ext", &h->username_ext,
+                          username_ext);
+  ret += cmp_dauth_param ("realm", &h->realm, realm);
+  ret += cmp_dauth_param ("uri", &h->uri, uri);
+  ret += cmp_dauth_param ("qop", &h->qop_raw, qop_raw);
+  if (h->qop != qop)
+  {
+    ret += 1;
+    fprintf (stderr, "Parameter 'qop' detected incorrectly:\n");
+    fprintf (stderr, "\tRESULT  :\t%u\n",
+             (unsigned) h->qop);
+    fprintf (stderr, "\tEXPECTED:\t%u\n",
+             (unsigned) qop);
+  }
+  ret += cmp_dauth_param ("cnonce", &h->cnonce, cnonce);
+  ret += cmp_dauth_param ("nc", &h->nc, nc);
+  if (h->userhash != ! (! userhash))
+  {
+    ret += 1;
+    fprintf (stderr, "Parameter 'userhash' parsed incorrectly:\n");
+    fprintf (stderr, "\tRESULT  :\t%s\n",
+             h->userhash ? "true" : "false");
+    fprintf (stderr, "\tEXPECTED:\t%s\n",
+             userhash ? "true" : "false");
+  }
+  if (0 != ret)
+  {
+    fprintf (stderr,
+             "Input Header: '%.*s'\n", (int) hdr_len, hdr);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  clean_AuthHeaders ();
+
+  return ret;
+}
+
+
+#define expect_digest(h,no,a,rs,un,ux,rm,ur,qr,qe,c,nc,uh) \
+    expect_digest_n(h,MHD_STATICSTR_LEN_(h),\
+                    no,a,rs,un,ux,rm,ur,qr,qe,c,nc,uh,__LINE__)
+
+static unsigned int
+check_digest (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_digest ("Digest", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest nc=1", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, NULL, \
+                      MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest nc=\"1\"", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest nc=\"1\"   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest ,nc=\"1\"   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest nc=\"1\",   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest nc=\"1\" ,   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest nc=1,   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest nc=1 ,   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest ,,,nc=1,   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest ,,,nc=1 ,   ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0);
+  r += expect_digest ("Digest ,,,nc=\"1 \",   ", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0);
+  r += expect_digest ("Digest nc=\"1 \"", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0);
+  r += expect_digest ("Digest nc=\"1 \" ,", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0);
+  r += expect_digest ("Digest nc=\"1 \", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0);
+  r += expect_digest ("Digest nc=\"1;\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1;", 0);
+  r += expect_digest ("Digest nc=\"1\\;\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1\\;", 0);
+
+  r += expect_digest ("Digest userhash=false", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest userhash=\"false\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest userhash=foo", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest userhash=true", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1);
+  r += expect_digest ("Digest userhash=\"true\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1);
+  r += expect_digest ("Digest userhash=\"\\t\\r\\u\\e\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1);
+  r += expect_digest ("Digest userhash=TRUE", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1);
+  r += expect_digest ("Digest userhash=True", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1);
+  r += expect_digest ("Digest userhash = true", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL,  NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1);
+  r += expect_digest ("Digest userhash=True2", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest userhash=\" true\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL,  NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+
+  r += expect_digest ("Digest algorithm=MD5", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=md5", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=Md5", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=mD5", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=\"MD5\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=\"\\M\\D\\5\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=\"\\m\\d\\5\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=SHA-256", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=sha-256", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=Sha-256", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=\"SHA-256\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=\"SHA\\-25\\6\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=\"shA-256\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=MD5-sess", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=MD5-SESS", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=md5-Sess", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=SHA-256-seSS", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=SHA-512-256", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA512_256, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=SHA-512-256-sess", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=MD5-2", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_INVALID, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=MD5-sess2", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_INVALID, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=SHA-256-512", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_INVALID, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+  r += expect_digest ("Digest algorithm=", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_INVALID, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0);
+
+  r += expect_digest ("Digest qop=auth", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=\"auth\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=Auth", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "Auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=AUTH", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "AUTH", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=\"\\A\\ut\\H\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "\\A\\ut\\H", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=\"auth \"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auth ", MHD_DIGEST_AUTH_QOP_INVALID, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=auth-int", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auth-int", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=\"auth-int\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auth-int", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=\"auTh-iNt\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auTh-iNt", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0);
+  r += expect_digest ("Digest qop=\"auTh-iNt2\"", NULL, \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      NULL, NULL, NULL, NULL, NULL, \
+                      "auTh-iNt2", MHD_DIGEST_AUTH_QOP_INVALID, NULL, NULL, 0);
+
+  r += expect_digest ("Digest username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", " \
+                      "nonce=\"32141232413abcde\", " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_MD5, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      NULL, "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, \
+                      "0a4f113b", "00000001", 0);
+  r += expect_digest ("Digest username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest username=test@example.com, " \
+                      "realm=users@example.com, algorithm=\"SHA-256-sess\", " \
+                      "nonce=32141232413abcde, " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=/example, qop=\"auth\", nc=\"00000001\", " \
+                      "cnonce=0a4f113b, " \
+                      "response=6629fae49393a05397450978507c4ef1, " \
+                      "opaque=sadfljk32sdaf", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest username = \"test@example.com\", " \
+                      "realm\t=\t\"users@example.com\", algorithm\t= SHA-256, " \
+                      "nonce\t= \"32141232413abcde\", " \
+                      "username*\t=\tUTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri = \"/example\", qop = auth, nc\t=\t00000001, " \
+                      "cnonce\t\t\t=   \"0a4f113b\", " \
+                      "response  =\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\t\t\"sadfljk32sdaf\"", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest username=\"test@example.com\"," \
+                      "realm=\"users@example.com\",algorithm=SHA-512-256," \
+                      "nonce=\"32141232413abcde\"," \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates," \
+                      "uri=\"/example\",qop=auth,nc=00000001," \
+                      "cnonce=\"0a4f113b\"," \
+                      "response=\"6629fae49393a05397450978507c4ef1\"," \
+                      "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA512_256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest username=\"test@example.com\"," \
+                      "realm=\"users@example.com\",algorithm=SHA-256," \
+                      "nonce=\"32141232413abcde\",asdf=asdffdsaf," \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates," \
+                      "uri=\"/example\",qop=auth,nc=00000001,cnonce=\"0a4f113b\"," \
+                      "response=\"6629fae49393a05397450978507c4ef1\"," \
+                      "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=zyx, username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\"", "32141232413abcde",
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, "
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\",,,,,", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=\"zyx\", username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, "
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=\"zyx, abc\", " \
+                      "username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, "
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=\"zyx, abc=cde\", " \
+                      "username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=\"zyx, abc=cde\", " \
+                      "username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, " \
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\", foo=\"bar1, bar2\"", \
+                      "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=\"zyx, \\\\\"abc=cde\\\\\"\", " \
+                      "username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\", foo=\"bar1, bar2\"", \
+                      "32141232413abcde",
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+  r += expect_digest ("Digest abc=\"zyx, \\\\\"abc=cde\\\\\"\", " \
+                      "username=\"test@example.com\", " \
+                      "realm=\"users@example.com\", algorithm=SHA-256, " \
+                      "nonce=\"32141232413abcde\", " \
+                      "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \
+                      "uri=\"/example\", qop=auth, nc=00000001, "
+                      "cnonce=\"0a4f113b\", " \
+                      "response=\"6629fae49393a05397450978507c4ef1\", " \
+                      "opaque=\"sadfljk32sdaf\", foo=\",nc=02\"",
+                      "32141232413abcde", \
+                      MHD_DIGEST_AUTH_ALGO3_SHA256, \
+                      "6629fae49393a05397450978507c4ef1", "test@example.com", \
+                      "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \
+                      "users@example.com", "/example", \
+                      "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \
+                      "00000001", 0);
+
+  return r;
+}
+
+
+#endif /* DAUTH_SUPPORT */
+
+#define TEST_AUTH_STR "dXNlcjpwYXNz"
+
+static unsigned int
+check_two_auths (void)
+{
+  unsigned int ret;
+  static struct MHD_HTTP_Req_Header h1;
+  static struct MHD_HTTP_Req_Header h2;
+  static struct MHD_HTTP_Req_Header h3;
+#ifdef BAUTH_SUPPORT
+  const struct MHD_RqBAuth *bauth;
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  const struct MHD_RqDAuth *dauth;
+#endif /* DAUTH_SUPPORT */
+
+  if ((NULL != conn.rq.headers_received) ||
+      (NULL != conn.rq.headers_received_tail))
+    externalErrorExitDesc ("Connection's test headers are not empty already");
+
+  /* Init and use both Basic and Digest Auth headers */
+  memset (&h1, 0, sizeof(h1));
+  memset (&h2, 0, sizeof(h2));
+  memset (&h3, 0, sizeof(h3));
+
+  h1.kind = MHD_HEADER_KIND;
+  h1.header = MHD_HTTP_HEADER_HOST; /* Just some random header */
+  h1.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST);
+  h1.value = "localhost";
+  h1.value_size = strlen (h1.value);
+
+  h2.kind = MHD_HEADER_KIND;
+  h2.header = MHD_HTTP_HEADER_AUTHORIZATION;
+  h2.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION);
+  h2.value = "Basic " TEST_AUTH_STR;
+  h2.value_size = strlen (h2.value);
+
+  h3.kind = MHD_HEADER_KIND;
+  h3.header = MHD_HTTP_HEADER_AUTHORIZATION;
+  h3.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION);
+  h3.value = "Digest cnonce=" TEST_AUTH_STR;
+  h3.value_size = strlen (h3.value);
+
+  conn.rq.headers_received = &h1;
+  h1.next = &h2;
+  h2.prev = &h1;
+  h2.next = &h3;
+  h3.prev = &h2;
+  conn.rq.headers_received_tail = &h3;
+
+  conn.state = MHD_CONNECTION_FULL_REQ_RECEIVED; /* Should be a typical value */
+
+  ret = 0;
+#ifdef BAUTH_SUPPORT
+  bauth = get_BAuthRqParams ();
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  dauth = get_DAuthRqParams ();
+#endif /* DAUTH_SUPPORT */
+#ifdef BAUTH_SUPPORT
+  if (NULL == bauth)
+  {
+    fprintf (stderr, "No Basic Authorization header detected. Line: %u\n",
+             (unsigned int) __LINE__);
+    ret++;
+  }
+  else if ((MHD_STATICSTR_LEN_ (TEST_AUTH_STR) != bauth->token68.len) ||
+           (0 != memcmp (bauth->token68.str, TEST_AUTH_STR,
+                         bauth->token68.len)))
+  {
+    fprintf (stderr, "Basic Authorization token does not match. Line: %u\n",
+             (unsigned int) __LINE__);
+    ret++;
+  }
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  if (NULL == dauth)
+  {
+    fprintf (stderr, "No Digest Authorization header detected. Line: %u\n",
+             (unsigned int) __LINE__);
+    ret++;
+  }
+  else if ((MHD_STATICSTR_LEN_ (TEST_AUTH_STR) != dauth->cnonce.value.len) ||
+           (0 != memcmp (dauth->cnonce.value.str, TEST_AUTH_STR,
+                         dauth->cnonce.value.len)))
+  {
+    fprintf (stderr, "Digest Authorization 'cnonce' does not match. Line: %u\n",
+             (unsigned int) __LINE__);
+    ret++;
+  }
+#endif /* DAUTH_SUPPORT */
+
+  /* Cleanup */
+  conn.rq.headers_received = NULL;
+  conn.rq.headers_received_tail = NULL;
+  conn.state = MHD_CONNECTION_INIT;
+
+  return ret;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  test_global_init ();
+
+  errcount += check_type ();
+#ifdef BAUTH_SUPPORT
+  errcount += check_basic ();
+#endif /* BAUTH_SUPPORT */
+#ifdef DAUTH_SUPPORT
+  errcount += check_digest ();
+#endif /* DAUTH_SUPPORT */
+  errcount += check_two_auths ();
+  if (0 == errcount)
+    printf ("All tests were passed without errors.\n");
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_client_put_stop.c b/src/microhttpd/test_client_put_stop.c
new file mode 100644
index 0000000..271bc52
--- /dev/null
+++ b/src/microhttpd/test_client_put_stop.c
@@ -0,0 +1,2219 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_client_put_stop.c
+ * @brief  Testcase for handling of clients aborts
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+#include "MHD_config.h"
+#include "platform.h"
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <stdint.h>
+
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif /* HAVE_STRINGS_H */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif /* HAVE_SIGNAL_H */
+
+#ifdef HAVE_SYSCTL
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif /* HAVE_SYS_SYSCTL_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+#ifdef HAVE_NETINET_IN_SYSTM_H
+#include <netinet/in_systm.h>
+#endif /* HAVE_NETINET_IN_SYSTM_H */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif /* HAVE_NETINET_IN_H */
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+#ifdef HAVE_NETINET_IP_ICMP_H
+#include <netinet/ip_icmp.h>
+#endif /* HAVE_NETINET_IP_ICMP_H */
+#ifdef HAVE_NETINET_ICMP_VAR_H
+#include <netinet/icmp_var.h>
+#endif /* HAVE_NETINET_ICMP_VAR_H */
+#endif /* HAVE_SYSCTL */
+
+#include <stdio.h>
+
+#include "mhd_sockets.h" /* only macros used */
+#include "test_helpers.h"
+#include "mhd_assert.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+#if MHD_CPU_COUNT > 32
+#undef MHD_CPU_COUNT
+/* Limit to reasonable value */
+#define MHD_CPU_COUNT 32
+#endif /* MHD_CPU_COUNT > 32 */
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+/* Time in ms to wait for final packets to be delivered */
+#define FINAL_PACKETS_MS 20
+
+#define EXPECTED_URI_BASE_PATH  "/a"
+
+#define REQ_HOST "localhost"
+
+#define REQ_METHOD "PUT"
+
+#define REQ_BODY "Some content data."
+
+#define REQ_LINE_END "\r\n"
+
+/* Mandatory request headers */
+#define REQ_HEADER_HOST_NAME "Host"
+#define REQ_HEADER_HOST_VALUE REQ_HOST
+#define REQ_HEADER_HOST \
+  REQ_HEADER_HOST_NAME ": " REQ_HEADER_HOST_VALUE REQ_LINE_END
+#define REQ_HEADER_UA_NAME "User-Agent"
+#define REQ_HEADER_UA_VALUE "dummyclient/0.9"
+#define REQ_HEADER_UA REQ_HEADER_UA_NAME ": " REQ_HEADER_UA_VALUE REQ_LINE_END
+
+/* Optional request headers */
+#define REQ_HEADER_CT_NAME "Content-Type"
+#define REQ_HEADER_CT_VALUE "text/plain"
+#define REQ_HEADER_CT REQ_HEADER_CT_NAME ": " REQ_HEADER_CT_VALUE REQ_LINE_END
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Global generic functions */
+
+void
+_MHD_sleep (uint32_t ms);
+
+
+/**
+ * Pause execution for specified number of milliseconds.
+ * @param ms the number of milliseconds to sleep
+ */
+void
+_MHD_sleep (uint32_t ms)
+{
+#if defined(_WIN32)
+  Sleep (ms);
+#elif defined(HAVE_NANOSLEEP)
+  struct timespec slp = {ms / 1000, (ms % 1000) * 1000000};
+  struct timespec rmn;
+  int num_retries = 0;
+  while (0 != nanosleep (&slp, &rmn))
+  {
+    if (EINTR != errno)
+      externalErrorExit ();
+    if (num_retries++ > 8)
+      break;
+    slp = rmn;
+  }
+#elif defined(HAVE_USLEEP)
+  uint64_t us = ms * 1000;
+  do
+  {
+    uint64_t this_sleep;
+    if (999999 < us)
+      this_sleep = 999999;
+    else
+      this_sleep = us;
+    /* Ignore return value as it could be void */
+    usleep (this_sleep);
+    us -= this_sleep;
+  } while (us > 0);
+#else
+  externalErrorExitDesc ("No sleep function available on this system");
+#endif
+}
+
+
+/* Global parameters */
+static int verbose;                 /**< Be verbose */
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+static uint16_t global_port;        /**< MHD daemons listen port number */
+
+static int use_shutdown;            /**< Use shutdown at client side */
+static int use_close;               /**< Use socket close at client side */
+static int use_hard_close;          /**< Use socket close with RST at client side */
+static int use_stress_os;           /**< Stress OS by RST before getting ACKs for sent packets */
+static int by_step;                 /**< Send request byte-by-byte */
+static int upl_chunked;             /**< Use chunked encoding for request body */
+
+static unsigned int rate_limiter;   /**< Maximum number of checks per second */
+
+static void
+test_global_init (void)
+{
+  rate_limiter = 0;
+  if (use_hard_close)
+  {
+#ifdef HAVE_SYSCTLBYNAME
+    if (1)
+    {
+      int blck_hl;
+      size_t blck_hl_size = sizeof (blck_hl);
+      if (0 == sysctlbyname ("net.inet.tcp.blackhole", &blck_hl, &blck_hl_size,
+                             NULL, 0))
+      {
+        if (2 <= blck_hl)
+        {
+          fprintf (stderr, "'sysctl net.inet.tcp.blackhole = %d', test is "
+                   "unreliable with this system setting, skipping.\n", blck_hl);
+          exit (77);
+        }
+      }
+      else
+      {
+        if (ENOENT != errno)
+          externalErrorExitDesc ("Cannot get 'net.inet.tcp.blackhole' value");
+      }
+    }
+#endif
+#if defined(HAVE_SYSCTL) && defined(HAVE_DECL_CTL_NET) && \
+    defined(HAVE_DECL_PF_INET) && defined(HAVE_DECL_IPPROTO_ICMP) && \
+    defined(HAVE_DECL_ICMPCTL_ICMPLIM)
+    /* Macros may have zero values */
+#if HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && \
+    HAVE_DECL_ICMPCTL_ICMPLIM
+    if (1)
+    {
+      int mib[4];
+      int limit;
+      size_t limit_size = sizeof(limit);
+      mib[0] = CTL_NET;
+      mib[1] = PF_INET;
+      mib[2] = IPPROTO_ICMP;
+      mib[3] = ICMPCTL_ICMPLIM;
+      if (0 != sysctl (mib, 4, &limit, &limit_size, NULL, 0))
+      {
+        if (ENOENT == errno)
+          limit = 0; /* No such parameter (new Darwin versions) */
+        else
+          externalErrorExitDesc ("Cannot get RST rate limit value");
+      }
+      else if (sizeof(limit) != limit_size)
+        externalErrorExitDesc ("Cannot get RST rate limit value");
+      if (limit > 0)
+      {
+#ifndef _MHD_HEAVY_TESTS
+        fprintf (stderr, "This system has limits on number of RST packets"
+                 " per second (%d).\nThis test will be used only if configured "
+                 "with '--enable-heavy-test'.\n", limit);
+        exit (77);
+#else  /* _MHD_HEAVY_TESTS */
+        int test_limit; /**< Maximum number of checks per second */
+
+        if (use_stress_os)
+        {
+          fprintf (stderr, "This system has limits on number of RST packet"
+                   " per second (%d).\n'_stress_os' is not possible.\n", limit);
+          exit (77);
+        }
+        test_limit = limit - limit / 10; /* Add some space to not hit the limiter */
+        test_limit /= 4;   /* Assume that all four tests with 'hard_close' run in parallel */
+        test_limit -= 5;   /* Add some more space to not hit the limiter */
+        test_limit /= 3;   /* Use only one third of available limit */
+        if (test_limit <= 0)
+        {
+          fprintf (stderr, "System limit for 'net.inet.icmp.icmplim' is "
+                   "too strict for this test (value: %d).\n", limit);
+          exit (77);
+        }
+        if (verbose)
+        {
+          printf ("Limiting number of checks to %d checks/second.\n",
+                  test_limit);
+          fflush (stdout);
+        }
+        rate_limiter = (unsigned int) test_limit;
+#if ! defined(HAVE_USLEEP) && ! defined(HAVE_NANOSLEEP) && ! defined(_WIN32)
+        fprintf (stderr, "Sleep function is required for this test, "
+                 "but not available on this system.\n");
+        exit (77);
+#endif
+#endif /* _MHD_HEAVY_TESTS */
+      }
+    }
+#endif /* HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && \
+          HAVE_DECL_ICMPCTL_ICMPLIM */
+#endif /* HAVE_SYSCTL && HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET &&
+          HAVE_DECL_IPPROTO_ICMP && HAVE_DECL_ICMPCTL_ICMPLIM */
+  }
+  if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE))
+  {
+#if defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
+    if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
+      externalErrorExitDesc ("Error suppressing SIGPIPE signal");
+#else /* ! HAVE_SIGNAL_H || ! SIGPIPE */
+    fprintf (stderr, "Cannot suppress SIGPIPE signal.\n");
+    /* exit (77); */
+#endif
+  }
+}
+
+
+static void
+test_global_cleanup (void)
+{
+}
+
+
+/**
+ * Change socket to blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+  if ((flags & ~O_NONBLOCK) != flags)
+  {
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      externalErrorExitDesc ("Cannot make socket non-blocking");
+  }
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+/**
+ * Change socket to non-blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_nonblocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+  if ((flags | O_NONBLOCK) != flags)
+  {
+    if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK))
+      externalErrorExitDesc ("Cannot make socket non-blocking");
+  }
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 1;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+/* DumbClient API */
+struct _MHD_dumbClient *
+_MHD_dumbClient_create (uint16_t port, const char *method, const char *url,
+                        const char *add_headers,
+                        const uint8_t *req_body, size_t req_body_size,
+                        int chunked);
+
+void
+_MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt,
+                                 size_t step_size, size_t max_total_send);
+
+void
+_MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt);
+
+int
+_MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt);
+
+
+/**
+ * Process the client data with send()/recv() as needed.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process (struct _MHD_dumbClient *clnt);
+
+
+void
+_MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt,
+                            MHD_socket *maxsckt,
+                            fd_set *rs, fd_set *ws, fd_set *es);
+
+/**
+ * Process the client data with send()/recv() as needed based on
+ * information in fd_sets.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt,
+                                     fd_set *rs, fd_set *ws, fd_set *es);
+
+
+/**
+ * Perform full request.
+ * @param clnt the client to run
+ * @return zero if client finished processing the request,
+ *         non-zero if timeout is reached.
+ */
+int
+_MHD_dumbClient_perform (struct _MHD_dumbClient *clnt);
+
+
+/**
+ * Close the client and free internally allocated resources.
+ * @param clnt the client to close
+ */
+void
+_MHD_dumbClient_close (struct _MHD_dumbClient *clnt);
+
+
+/* DumbClient implementation */
+
+enum _MHD_clientStage
+{
+  DUMB_CLIENT_INIT = 0,
+  DUMB_CLIENT_CONNECTING,
+  DUMB_CLIENT_CONNECTED,
+  DUMB_CLIENT_REQ_SENDING,
+  DUMB_CLIENT_REQ_SENT,
+  DUMB_CLIENT_HEADER_RECVEIVING,
+  DUMB_CLIENT_HEADER_RECVEIVED,
+  DUMB_CLIENT_BODY_RECVEIVING,
+  DUMB_CLIENT_BODY_RECVEIVED,
+  DUMB_CLIENT_FINISHING,
+  DUMB_CLIENT_FINISHED
+};
+
+struct _MHD_dumbClient
+{
+  MHD_socket sckt; /**< the socket to communicate */
+
+  int sckt_nonblock;  /**< non-zero if socket is non-blocking */
+
+  uint16_t port; /**< the port to connect to */
+
+  const char *send_buf; /**< the buffer for the request, malloced */
+
+  void *buf; /**< the buffer location */
+
+  size_t req_size; /**< the size of the request, including header */
+
+  size_t send_off; /**< the number of bytes already sent */
+
+  enum _MHD_clientStage stage;
+
+  /* the test-specific variables */
+  size_t single_send_size; /**< the maximum number of bytes to be sent by
+                                single send() */
+  size_t send_size_limit;  /**< the total number of send bytes limit */
+};
+
+struct _MHD_dumbClient *
+_MHD_dumbClient_create (uint16_t port, const char *method, const char *url,
+                        const char *add_headers,
+                        const uint8_t *req_body, size_t req_body_size,
+                        int chunked)
+{
+  struct _MHD_dumbClient *clnt;
+  size_t method_size;
+  size_t url_size;
+  size_t add_hdrs_size;
+  size_t buf_alloc_size;
+  char *send_buf;
+  mhd_assert (0 != port);
+  mhd_assert (NULL != req_body || 0 == req_body_size);
+  mhd_assert (0 == req_body_size || NULL != req_body);
+
+  clnt = (struct _MHD_dumbClient *) malloc (sizeof(struct _MHD_dumbClient));
+  if (NULL == clnt)
+    externalErrorExit ();
+  memset (clnt, 0, sizeof(struct _MHD_dumbClient));
+  clnt->sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET == clnt->sckt)
+    externalErrorExitDesc ("Cannot create the client socket");
+
+#ifdef MHD_socket_nosignal_
+  if (! MHD_socket_nosignal_ (clnt->sckt))
+    externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket");
+#endif /* MHD_socket_nosignal_ */
+
+  clnt->sckt_nonblock = 0;
+  if (clnt->sckt_nonblock)
+    make_nonblocking (clnt->sckt);
+  else
+    make_blocking (clnt->sckt);
+
+  if (1)
+  { /* Always set TCP NODELAY */
+    const MHD_SCKT_OPT_BOOL_ on_val = 1;
+
+    if (0 != setsockopt (clnt->sckt, IPPROTO_TCP, TCP_NODELAY,
+                         (const void *) &on_val, sizeof (on_val)))
+      externalErrorExitDesc ("Cannot set TCP_NODELAY option");
+  }
+
+  clnt->port = port;
+
+  if (NULL != method)
+    method_size = strlen (method);
+  else
+  {
+    method = MHD_HTTP_METHOD_GET;
+    method_size = MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET);
+  }
+  mhd_assert (0 != method_size);
+  if (NULL != url)
+    url_size = strlen (url);
+  else
+  {
+    url = "/";
+    url_size = 1;
+  }
+  mhd_assert (0 != url_size);
+  add_hdrs_size = (NULL == add_headers) ? 0 : strlen (add_headers);
+  buf_alloc_size = 1024 + method_size + url_size
+                   + add_hdrs_size + req_body_size;
+  send_buf = (char *) malloc (buf_alloc_size);
+  if (NULL == send_buf)
+    externalErrorExit ();
+
+  clnt->req_size = 0;
+  /* Form the request line */
+  memcpy (send_buf + clnt->req_size, method, method_size);
+  clnt->req_size += method_size;
+  send_buf[clnt->req_size++] = ' ';
+  memcpy (send_buf + clnt->req_size, url, url_size);
+  clnt->req_size += url_size;
+  send_buf[clnt->req_size++] = ' ';
+  memcpy (send_buf + clnt->req_size, MHD_HTTP_VERSION_1_1,
+          MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1));
+  clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1);
+  send_buf[clnt->req_size++] = '\r';
+  send_buf[clnt->req_size++] = '\n';
+  /* Form the header */
+  memcpy (send_buf + clnt->req_size, REQ_HEADER_HOST,
+          MHD_STATICSTR_LEN_ (REQ_HEADER_HOST));
+  clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_HOST);
+  memcpy (send_buf + clnt->req_size, REQ_HEADER_UA,
+          MHD_STATICSTR_LEN_ (REQ_HEADER_UA));
+  clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_UA);
+  if ((NULL != req_body) || chunked)
+  {
+    if (! chunked)
+    {
+      int prn_size;
+      memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ",
+              MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "));
+      clnt->req_size +=
+        MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ");
+      prn_size = snprintf (send_buf + clnt->req_size,
+                           (buf_alloc_size - clnt->req_size),
+                           "%u", (unsigned int) req_body_size);
+      if (0 >= prn_size)
+        externalErrorExit ();
+      if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size)
+        externalErrorExit ();
+      clnt->req_size += (unsigned int) prn_size;
+      send_buf[clnt->req_size++] = '\r';
+      send_buf[clnt->req_size++] = '\n';
+    }
+    else
+    {
+      memcpy (send_buf + clnt->req_size,
+              MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked\r\n",
+              MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \
+                                  ": chunked\r\n"));
+      clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \
+                                            ": chunked\r\n");
+    }
+  }
+  if (0 != add_hdrs_size)
+  {
+    memcpy (send_buf + clnt->req_size, add_headers, add_hdrs_size);
+    clnt->req_size += add_hdrs_size;
+  }
+  /* Terminate header */
+  send_buf[clnt->req_size++] = '\r';
+  send_buf[clnt->req_size++] = '\n';
+
+  /* Add body (if any) */
+  if (! chunked)
+  {
+    if (0 != req_body_size)
+    {
+      memcpy (send_buf + clnt->req_size, req_body, req_body_size);
+      clnt->req_size += req_body_size;
+    }
+  }
+  else
+  {
+    if (0 != req_body_size)
+    {
+      int prn_size;
+      prn_size = snprintf (send_buf + clnt->req_size,
+                           (buf_alloc_size - clnt->req_size),
+                           "%x", (unsigned int) req_body_size);
+      if (0 >= prn_size)
+        externalErrorExit ();
+      if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size)
+        externalErrorExit ();
+      clnt->req_size += (unsigned int) prn_size;
+      send_buf[clnt->req_size++] = '\r';
+      send_buf[clnt->req_size++] = '\n';
+      memcpy (send_buf + clnt->req_size, req_body, req_body_size);
+      clnt->req_size += req_body_size;
+      send_buf[clnt->req_size++] = '\r';
+      send_buf[clnt->req_size++] = '\n';
+    }
+    send_buf[clnt->req_size++] = '0';
+    send_buf[clnt->req_size++] = '\r';
+    send_buf[clnt->req_size++] = '\n';
+    send_buf[clnt->req_size++] = '\r';
+    send_buf[clnt->req_size++] = '\n';
+  }
+  mhd_assert (clnt->req_size < buf_alloc_size);
+  clnt->buf = send_buf;
+  clnt->send_buf = send_buf;
+
+  return clnt;
+}
+
+
+void
+_MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt,
+                                 size_t step_size, size_t max_total_send)
+{
+  clnt->single_send_size = step_size;
+  clnt->send_size_limit = max_total_send;
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_connect_init (struct _MHD_dumbClient *clnt)
+{
+  struct sockaddr_in sa;
+  mhd_assert (DUMB_CLIENT_INIT == clnt->stage);
+
+  sa.sin_family = AF_INET;
+  sa.sin_port = htons ((uint16_t) clnt->port);
+  sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+
+  if (0 != connect (clnt->sckt, (struct sockaddr *) &sa, sizeof(sa)))
+  {
+    const int err = MHD_socket_get_error_ ();
+    if ( (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_)) ||
+         (MHD_SCKT_ERR_IS_EAGAIN_ (err)))
+      clnt->stage = DUMB_CLIENT_CONNECTING;
+    else
+      externalErrorExitDesc ("Cannot 'connect()' the client socket");
+  }
+  else
+    clnt->stage = DUMB_CLIENT_CONNECTED;
+}
+
+
+void
+_MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt)
+{
+  mhd_assert (DUMB_CLIENT_INIT == clnt->stage);
+  _MHD_dumbClient_connect_init (clnt);
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_connect_finish (struct _MHD_dumbClient *clnt)
+{
+  int err = 0;
+  socklen_t err_size = sizeof(err);
+  mhd_assert (DUMB_CLIENT_CONNECTING == clnt->stage);
+  if (0 != getsockopt (clnt->sckt, SOL_SOCKET, SO_ERROR,
+                       (void *) &err, &err_size))
+    externalErrorExitDesc ("'getsockopt()' call failed");
+  if (0 != err)
+    externalErrorExitDesc ("Socket connect() failed");
+  clnt->stage = DUMB_CLIENT_CONNECTED;
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_send_req (struct _MHD_dumbClient *clnt)
+{
+  size_t send_size;
+  ssize_t res;
+  mhd_assert (DUMB_CLIENT_CONNECTED <= clnt->stage);
+  mhd_assert (DUMB_CLIENT_REQ_SENT > clnt->stage);
+  mhd_assert (clnt->req_size > clnt->send_off);
+
+  send_size = (((0 != clnt->send_size_limit) &&
+                (clnt->req_size > clnt->send_size_limit)) ?
+               clnt->send_size_limit : clnt->req_size) - clnt->send_off;
+  mhd_assert (0 != send_size);
+  if ((0 != clnt->single_send_size) &&
+      (clnt->single_send_size < send_size))
+    send_size = clnt->single_send_size;
+
+  res = MHD_send_ (clnt->sckt, clnt->send_buf + clnt->send_off, send_size);
+
+  if (res < 0)
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+      return;
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return;
+    if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+      mhdErrorExitDesc ("The connection was aborted by MHD");
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_))
+      mhdErrorExitDesc ("The connection was shut down on MHD side");
+    externalErrorExitDesc ("Unexpected network error");
+  }
+  clnt->send_off += (size_t) res;
+  mhd_assert (clnt->send_off <= clnt->req_size);
+  mhd_assert (clnt->send_off <= clnt->send_size_limit || \
+              0 == clnt->send_size_limit);
+  if (clnt->req_size == clnt->send_off)
+    clnt->stage = DUMB_CLIENT_REQ_SENT;
+  if ((0 != clnt->send_size_limit) &&
+      (clnt->send_size_limit == clnt->send_off))
+    clnt->stage = DUMB_CLIENT_FINISHING;
+}
+
+
+/* internal */
+_MHD_NORETURN /* Declared as 'noreturn' until it is implemented */
+static void
+_MHD_dumbClient_recv_reply (struct _MHD_dumbClient *clnt)
+{
+  (void) clnt;
+  externalErrorExitDesc ("Not implemented for this test");
+}
+
+
+int
+_MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt)
+{
+  return DUMB_CLIENT_REQ_SENT <= clnt->stage;
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_socket_close (struct _MHD_dumbClient *clnt)
+{
+  if (MHD_INVALID_SOCKET != clnt->sckt)
+  {
+    if (use_hard_close)
+    {
+#ifdef SO_LINGER
+      static const struct linger hard_close = {1, 0};
+      mhd_assert (0 == hard_close.l_linger);
+      if (0 != setsockopt (clnt->sckt, SOL_SOCKET, SO_LINGER,
+                           (const void *) &hard_close, sizeof (hard_close)))
+#endif /* SO_LINGER */
+      externalErrorExitDesc ("Failed to set SO_LINGER option");
+    }
+    if (! MHD_socket_close_ (clnt->sckt))
+      externalErrorExitDesc ("Unexpected error while closing " \
+                             "the client socket");
+    clnt->sckt = MHD_INVALID_SOCKET;
+  }
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_finalize (struct _MHD_dumbClient *clnt)
+{
+  if (MHD_INVALID_SOCKET != clnt->sckt)
+  {
+    if (use_shutdown)
+    {
+      if (0 != shutdown (clnt->sckt, SHUT_WR))
+      {
+        const int err = MHD_socket_get_error_ ();
+        if (! MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_) &&
+            ! MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+          mhdErrorExitDesc ("Unexpected error when shutting down " \
+                            "the client socket");
+      }
+    }
+    else if (use_close)
+    {
+      _MHD_dumbClient_socket_close (clnt);
+    }
+    else
+      mhd_assert (0);
+  }
+  clnt->stage = DUMB_CLIENT_FINISHED;
+}
+
+
+/* internal */
+static int
+_MHD_dumbClient_needs_send (const struct _MHD_dumbClient *clnt)
+{
+  return ((DUMB_CLIENT_CONNECTING <= clnt->stage) &&
+          (DUMB_CLIENT_REQ_SENT > clnt->stage)) ||
+         (DUMB_CLIENT_FINISHING == clnt->stage);
+}
+
+
+/* internal */
+static int
+_MHD_dumbClient_needs_recv (const struct _MHD_dumbClient *clnt)
+{
+  return (DUMB_CLIENT_HEADER_RECVEIVING <= clnt->stage) &&
+         (DUMB_CLIENT_BODY_RECVEIVED > clnt->stage);
+}
+
+
+/* internal */
+/**
+ * Check whether the client needs unconditionally process the data.
+ * @param clnt the client to check
+ * @return non-zero if client needs unconditionally process the data,
+ *         zero otherwise.
+ */
+static int
+_MHD_dumbClient_needs_process (const struct _MHD_dumbClient *clnt)
+{
+  switch (clnt->stage)
+  {
+  case DUMB_CLIENT_INIT:
+  case DUMB_CLIENT_REQ_SENT:
+  case DUMB_CLIENT_HEADER_RECVEIVED:
+  case DUMB_CLIENT_BODY_RECVEIVED:
+  case DUMB_CLIENT_FINISHED:
+    return ! 0;
+  case DUMB_CLIENT_CONNECTING:
+  case DUMB_CLIENT_CONNECTED:
+  case DUMB_CLIENT_REQ_SENDING:
+  case DUMB_CLIENT_HEADER_RECVEIVING:
+  case DUMB_CLIENT_BODY_RECVEIVING:
+  case DUMB_CLIENT_FINISHING:
+  default:
+    break;
+  }
+  return 0;
+}
+
+
+/**
+ * Process the client data with send()/recv() as needed.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process (struct _MHD_dumbClient *clnt)
+{
+  do
+  {
+    switch (clnt->stage)
+    {
+    case DUMB_CLIENT_INIT:
+      _MHD_dumbClient_connect_init (clnt);
+      break;
+    case DUMB_CLIENT_CONNECTING:
+      _MHD_dumbClient_connect_finish (clnt);
+      break;
+    case DUMB_CLIENT_CONNECTED:
+    case DUMB_CLIENT_REQ_SENDING:
+      _MHD_dumbClient_send_req (clnt);
+      break;
+    case DUMB_CLIENT_REQ_SENT:
+      mhd_assert (0);
+      clnt->stage = DUMB_CLIENT_HEADER_RECVEIVING;
+      break;
+    case DUMB_CLIENT_HEADER_RECVEIVING:
+      _MHD_dumbClient_recv_reply (clnt);
+      break;
+    case DUMB_CLIENT_HEADER_RECVEIVED:
+      clnt->stage = DUMB_CLIENT_BODY_RECVEIVING;
+      break;
+    case DUMB_CLIENT_BODY_RECVEIVING:
+      _MHD_dumbClient_recv_reply (clnt);
+      break;
+    case DUMB_CLIENT_BODY_RECVEIVED:
+      clnt->stage = DUMB_CLIENT_FINISHING;
+      break;
+    case DUMB_CLIENT_FINISHING:
+      _MHD_dumbClient_finalize (clnt);
+      break;
+    case DUMB_CLIENT_FINISHED:
+      return ! 0;
+    default:
+      mhd_assert (0);
+      mhdErrorExit ();
+    }
+  } while (_MHD_dumbClient_needs_process (clnt));
+  return DUMB_CLIENT_FINISHED == clnt->stage;
+}
+
+
+void
+_MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt,
+                            MHD_socket *maxsckt,
+                            fd_set *rs, fd_set *ws, fd_set *es)
+{
+  mhd_assert (NULL != rs);
+  mhd_assert (NULL != ws);
+  mhd_assert (NULL != es);
+  if (DUMB_CLIENT_FINISHED > clnt->stage)
+  {
+    if (MHD_INVALID_SOCKET != clnt->sckt)
+    {
+      if ( (MHD_INVALID_SOCKET == *maxsckt) ||
+           (clnt->sckt > *maxsckt) )
+        *maxsckt = clnt->sckt;
+      if (_MHD_dumbClient_needs_recv (clnt))
+        FD_SET (clnt->sckt, rs);
+      if (_MHD_dumbClient_needs_send (clnt))
+        FD_SET (clnt->sckt, ws);
+      FD_SET (clnt->sckt, es);
+    }
+  }
+}
+
+
+/**
+ * Process the client data with send()/recv() as needed based on
+ * information in fd_sets.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt,
+                                     fd_set *rs, fd_set *ws, fd_set *es)
+{
+  if (_MHD_dumbClient_needs_process (clnt))
+    return _MHD_dumbClient_process (clnt);
+  else if (MHD_INVALID_SOCKET != clnt->sckt)
+  {
+    if (_MHD_dumbClient_needs_recv (clnt) && FD_ISSET (clnt->sckt, rs))
+      return _MHD_dumbClient_process (clnt);
+    else if (_MHD_dumbClient_needs_send (clnt) && FD_ISSET (clnt->sckt, ws))
+      return _MHD_dumbClient_process (clnt);
+    else if (FD_ISSET (clnt->sckt, es))
+      return _MHD_dumbClient_process (clnt);
+  }
+  return DUMB_CLIENT_FINISHED == clnt->stage;
+}
+
+
+/**
+ * Perform full request.
+ * @param clnt the client to run
+ * @return zero if client finished processing the request,
+ *         non-zero if timeout is reached.
+ */
+int
+_MHD_dumbClient_perform (struct _MHD_dumbClient *clnt)
+{
+  time_t start;
+  time_t now;
+  start = time (NULL);
+  now = start;
+  do
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    struct timeval tv;
+
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+
+    if (! _MHD_dumbClient_needs_process (clnt))
+    {
+      maxMhdSk = MHD_INVALID_SOCKET;
+      _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es);
+      mhd_assert (now >= start);
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+      tv.tv_sec = (time_t) (TIMEOUTS_VAL * 2 - (now - start) + 1);
+#else  /* Native W32 */
+      tv.tv_sec = (long) (TIMEOUTS_VAL * 2 - (now - start) + 1);
+#endif /* Native W32 */
+      tv.tv_usec = 250 * 1000;
+      if (-1 == select ((int) maxMhdSk + 1, &rs, &ws, &es, &tv))
+      {
+#ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+          externalErrorExitDesc ("Unexpected select() error");
+#else  /* ! MHD_POSIX_SOCKETS */
+        mhd_assert ((0 != rs.fd_count) || (0 != ws.fd_count) || \
+                    (0 != es.fd_count));
+        externalErrorExitDesc ("Unexpected select() error");
+        Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
+#endif /* ! MHD_POSIX_SOCKETS */
+        continue;
+      }
+      if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es))
+        return 0;
+    }
+    /* Use double timeout value here as MHD must catch timeout situations
+     * in this test. Timeout in client as a last resort. */
+  } while ((now = time (NULL)) - start <= (TIMEOUTS_VAL * 2));
+  return 1;
+}
+
+
+/**
+ * Close the client and free internally allocated resources.
+ * @param clnt the client to close
+ */
+void
+_MHD_dumbClient_close (struct _MHD_dumbClient *clnt)
+{
+  if (DUMB_CLIENT_FINISHED != clnt->stage)
+    _MHD_dumbClient_finalize (clnt);
+  _MHD_dumbClient_socket_close (clnt);
+  if (NULL != clnt->send_buf)
+  {
+    mhd_assert (clnt->send_buf == clnt->buf);
+    free (clnt->buf);
+    clnt->buf = NULL;
+    clnt->send_buf = NULL;
+  }
+  free (clnt);
+}
+
+
+struct sckt_notif_cb_param
+{
+  volatile unsigned int num_started;
+  volatile unsigned int num_finished;
+};
+
+static void
+socket_cb (void *cls,
+           struct MHD_Connection *c,
+           void **socket_context,
+           enum MHD_ConnectionNotificationCode toe)
+{
+  struct sckt_notif_cb_param *param = (struct sckt_notif_cb_param *) cls;
+  if (NULL == socket_context)
+    mhdErrorExitDesc ("'socket_context' pointer is NULL");
+  if (NULL == c)
+    mhdErrorExitDesc ("'connection' pointer is NULL");
+  if (NULL == param)
+    mhdErrorExitDesc ("'cls' pointer is NULL");
+
+  if (MHD_CONNECTION_NOTIFY_STARTED == toe)
+    param->num_started++;
+  else if (MHD_CONNECTION_NOTIFY_CLOSED == toe)
+    param->num_finished++;
+  else
+    mhdErrorExitDesc ("Unknown 'toe' value");
+}
+
+
+struct term_notif_cb_param
+{
+  volatile int term_reason;
+  volatile unsigned int num_called;
+};
+
+
+static void
+term_cb (void *cls,
+         struct MHD_Connection *c,
+         void **req_cls,
+         enum MHD_RequestTerminationCode term_code)
+{
+  struct term_notif_cb_param *param = (struct term_notif_cb_param *) cls;
+  if (NULL == req_cls)
+    mhdErrorExitDesc ("'req_cls' pointer is NULL");
+  if (NULL == c)
+    mhdErrorExitDesc ("'connection' pointer is NULL");
+  if (NULL == param)
+    mhdErrorExitDesc ("'cls' pointer is NULL");
+  param->term_reason = (int) term_code;
+  param->num_called++;
+}
+
+
+static const char *
+term_reason_str (enum MHD_RequestTerminationCode term_code)
+{
+  switch ((int) term_code)
+  {
+  case MHD_REQUEST_TERMINATED_COMPLETED_OK:
+    return "COMPLETED_OK";
+  case MHD_REQUEST_TERMINATED_WITH_ERROR:
+    return "TERMINATED_WITH_ERROR";
+  case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED:
+    return "TIMEOUT_REACHED";
+  case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN:
+    return "DAEMON_SHUTDOWN";
+  case MHD_REQUEST_TERMINATED_READ_ERROR:
+    return "READ_ERROR";
+  case MHD_REQUEST_TERMINATED_CLIENT_ABORT:
+    return "CLIENT_ABORT";
+  case -1:
+    return "(not called)";
+  default:
+    break;
+  }
+  return "(unknown code)";
+}
+
+
+struct check_uri_cls
+{
+  const char *volatile uri;
+  volatile unsigned int cb_called;
+};
+
+static void *
+check_uri_cb (void *cls,
+              const char *uri,
+              struct MHD_Connection *con)
+{
+  struct check_uri_cls *param = (struct check_uri_cls *) cls;
+
+  if (NULL == con)
+    mhdErrorExitDesc ("The 'con' pointer is NULL");
+
+  param->cb_called++;
+
+  if (0 != strcmp (param->uri,
+                   uri))
+  {
+    fprintf (stderr, "Wrong URI: '%s'\n", uri);
+    mhdErrorExit ();
+  }
+  return NULL;
+}
+
+
+struct mhd_header_checker_param
+{
+  int found_header_host; /**< the number of 'Host' headers */
+  int found_header_ua;   /**< the number of 'User-Agent' headers */
+  int found_header_ct;   /**< the number of 'Content-Type' headers */
+  int found_header_cl;   /**< the number of 'Content-Length' headers */
+  int found_header_te;   /**< the number of 'Transfer-Encoding' headers */
+};
+
+static enum MHD_Result
+headerCheckerInterator (void *cls,
+                        enum MHD_ValueKind kind,
+                        const char *key,
+                        size_t key_size,
+                        const char *value,
+                        size_t value_size)
+{
+  struct mhd_header_checker_param *const param =
+    (struct mhd_header_checker_param *) cls;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (MHD_HEADER_KIND != kind)
+    return MHD_YES; /* Continue iteration */
+
+  if (0 == key_size)
+    mhdErrorExitDesc ("Zero key length");
+
+  if ((strlen (REQ_HEADER_HOST_NAME) == key_size) &&
+      (0 == memcmp (key, REQ_HEADER_HOST_NAME, key_size)))
+  {
+    if ((strlen (REQ_HEADER_HOST_VALUE) == value_size) &&
+        (0 == memcmp (value, REQ_HEADER_HOST_VALUE, value_size)))
+      param->found_header_host++;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, REQ_HEADER_HOST_VALUE);
+  }
+  else if ((strlen (REQ_HEADER_UA_NAME) == key_size) &&
+           (0 == memcmp (key, REQ_HEADER_UA_NAME, key_size)))
+  {
+    if ((strlen (REQ_HEADER_UA_VALUE) == value_size) &&
+        (0 == memcmp (value, REQ_HEADER_UA_VALUE, value_size)))
+      param->found_header_ua++;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, REQ_HEADER_UA_VALUE);
+  }
+  else if ((strlen (REQ_HEADER_CT_NAME) == key_size) &&
+           (0 == memcmp (key, REQ_HEADER_CT_NAME, key_size)))
+  {
+    if ((strlen (REQ_HEADER_CT_VALUE) == value_size) &&
+        (0 == memcmp (value, REQ_HEADER_CT_VALUE, value_size)))
+      param->found_header_ct++;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, REQ_HEADER_CT_VALUE);
+  }
+  else if ((strlen (MHD_HTTP_HEADER_CONTENT_LENGTH) == key_size) &&
+           (0 == memcmp (key, MHD_HTTP_HEADER_CONTENT_LENGTH, key_size)))
+  {
+    /* do not check value of the header here for simplicity */
+    param->found_header_cl++;
+  }
+  else if ((strlen (MHD_HTTP_HEADER_TRANSFER_ENCODING) == key_size) &&
+           (0 == memcmp (key, MHD_HTTP_HEADER_TRANSFER_ENCODING, key_size)))
+  {
+    if ((strlen ("chunked") == value_size) &&
+        (0 == memcmp (value, "chunked", value_size)))
+      param->found_header_te++;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, "chunked");
+  }
+  return MHD_YES;
+}
+
+
+struct ahc_cls_type
+{
+  const char *volatile rp_data;
+  volatile size_t rp_data_size;
+  const char *volatile rq_method;
+  const char *volatile rq_url;
+  const char *volatile req_body;
+  volatile unsigned int cb_called; /* Non-zero indicates that callback was called at least one time */
+  size_t req_body_size; /**< The number of bytes in @a req_body */
+  size_t req_body_uploaded; /* Updated by callback */
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int marker;
+  enum MHD_Result ret;
+  struct mhd_header_checker_param header_check_param;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+  param->cb_called++;
+
+  if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+    mhdErrorExitDesc ("Unexpected HTTP version");
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+  {
+    const char *const upload_body = param->req_body;
+    if (NULL == upload_data)
+      mhdErrorExitDesc ("'upload_data' is NULL while " \
+                        "'*upload_data_size' value is not zero");
+    if (NULL == upload_body)
+      mhdErrorExitDesc ("'*upload_data_size' value is not zero " \
+                        "while no request body is expected");
+    if (param->req_body_uploaded + *upload_data_size > param->req_body_size)
+    {
+      fprintf (stderr, "Too large upload body received. Got %u, expected %u",
+               (unsigned int) (param->req_body_uploaded + *upload_data_size),
+               (unsigned int) param->req_body_size);
+      mhdErrorExit ();
+    }
+    if (0 != memcmp (upload_data, upload_body + param->req_body_uploaded,
+                     *upload_data_size))
+    {
+      fprintf (stderr, "Unexpected request body at offset %u: " \
+               "'%.*s', expected: '%.*s'\n",
+               (unsigned int) param->req_body_uploaded,
+               (int) *upload_data_size, upload_data,
+               (int) *upload_data_size, upload_body + param->req_body_uploaded);
+      mhdErrorExit ();
+    }
+    param->req_body_uploaded += *upload_data_size;
+    *upload_data_size = 0;
+  }
+
+  if (&marker != *req_cls)
+  {
+    /* The first call of the callback for this connection */
+    mhd_assert (NULL == upload_data);
+    param->req_body_uploaded = 0;
+
+    *req_cls = &marker;
+    return MHD_YES;
+  }
+
+  memset (&header_check_param, 0, sizeof(header_check_param));
+  if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND,
+                                       &headerCheckerInterator,
+                                       &header_check_param))
+    mhdErrorExitDesc ("Wrong number of headers in the request");
+  if (1 != header_check_param.found_header_host)
+    mhdErrorExitDesc ("'Host' header has not been detected in request");
+  if (1 != header_check_param.found_header_ua)
+    mhdErrorExitDesc ("'User-Agent' header has not been detected in request");
+  if (1 != header_check_param.found_header_ct)
+    mhdErrorExitDesc ("'Content-Type' header has not been detected in request");
+  if (! upl_chunked && (1 != header_check_param.found_header_cl))
+    mhdErrorExitDesc ("'Content-Length' header has not been detected "
+                      "in request");
+  if (upl_chunked && (1 != header_check_param.found_header_te))
+    mhdErrorExitDesc ("'Transfer-Encoding' header has not been detected "
+                      "in request");
+
+  if (NULL != upload_data)
+    return MHD_YES; /* Full request has not been received so far */
+
+#if 0 /* Code unused in this test */
+  struct MHD_Response *response;
+  response = MHD_create_response_from_buffer (param->rp_data_size,
+                                              (void *) param->rp_data,
+                                              MHD_RESPMEM_MUST_COPY);
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+#else
+  if (NULL == upload_data)
+    mhdErrorExitDesc ("Full request received, " \
+                      "while incomplete request expected");
+  ret = MHD_NO;
+#endif
+
+  return ret;
+}
+
+
+struct simpleQueryParams
+{
+  /* Destination path for HTTP query */
+  const char *queryPath;
+
+  /* Custom query method, NULL for default */
+  const char *method;
+
+  /* Destination port for HTTP query */
+  uint16_t queryPort;
+
+  /* Additional request headers, static */
+  const char *headers;
+
+  /* NULL for request without body */
+  const uint8_t *req_body;
+  size_t req_body_size;
+
+  /* Non-zero to use chunked encoding for request body */
+  int chunked;
+
+  /* Max size of data for single 'send()' call */
+  size_t step_size;
+
+  /* Limit for total amount of sent data */
+  size_t total_send_max;
+
+  /* HTTP query result error flag */
+  volatile int queryError;
+
+  /* Response HTTP code, zero if no response */
+  volatile int responseCode;
+};
+
+
+/* returns non-zero if timed-out */
+static int
+performQueryExternal (struct MHD_Daemon *d, struct _MHD_dumbClient *clnt)
+{
+  time_t start;
+  struct timeval tv;
+  int ret;
+  const union MHD_DaemonInfo *di;
+  MHD_socket lstn_sk;
+  int client_accepted;
+  int full_req_recieved;
+  int full_req_sent;
+  int some_data_recieved;
+
+  di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
+  if (NULL == di)
+    mhdErrorExitDesc ("Cannot get lister socket");
+  lstn_sk = di->listen_fd;
+
+  ret = 1; /* will be replaced with real result */
+  client_accepted = 0;
+
+  _MHD_dumbClient_start_connect (clnt);
+
+  full_req_recieved = 0;
+  some_data_recieved = 0;
+  start = time (NULL);
+  do
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int num_ready;
+    int do_client; /**< Process data in client */
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL == clnt)
+    {
+      /* client has finished, check whether MHD is still
+       * processing any connections */
+      full_req_sent = 1;
+      do_client = 0;
+      if (client_accepted && (0 > MHD_get_timeout64s (d)))
+      {
+        ret = 0;
+        break; /* MHD finished as well */
+      }
+    }
+    else
+    {
+      full_req_sent = _MHD_dumbClient_is_req_sent (clnt);
+      if (! full_req_sent)
+        do_client = 1; /* Request hasn't been sent yet, send the data */
+      else
+      {
+        /* All request data has been sent.
+         * Client will close the socket as the next step. */
+        if (full_req_recieved)
+        {
+          /* All data has been received by the MHD */
+          do_client = 1; /* Close the client socket */
+        }
+        else if (some_data_recieved &&
+                 (! use_hard_close || ((0 == rate_limiter) && use_stress_os)))
+        {
+          /* No RST rate limiter or no "hard close", no need to avoid extra RST
+           * and at least something was received by the MHD */
+          /* In case of 'hard close' this can stress the OS, especially
+           * if 'by_step' is enabled as several ACKs (for delivered packets
+           * containing the request) from the server may arrive to the client
+           * when the client has closed port and may be reflected by several
+           * RSTs from the client side to the server side (when ACK received
+           * without active connection then RST packet should be sent).
+           * When listening socket receives RST packets, it may block
+           * the sender preventing the next connection. */
+          do_client = 1; /* Proceed with the closure of the client socket */
+        }
+        else
+        {
+          /* When rate limiter is enabled, all sent packets must be received
+           * before client closes connection to avoid RST for every ACK.
+           * When rate limiter is not enabled, the MHD must receive at
+           * least something before closing the connection. */
+          do_client = 0; /* Do not close the client socket yet */
+        }
+      }
+
+      if (do_client)
+        _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es);
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    if (do_client)
+    {
+      tv.tv_sec = 1;
+      tv.tv_usec = 250 * 1000;
+    }
+    else
+    { /* Request completely sent but not yet fully received */
+      tv.tv_sec = 0;
+      tv.tv_usec = FINAL_PACKETS_MS * 1000;
+    }
+    num_ready = select ((int) maxMhdSk + 1, &rs, &ws, &es, &tv);
+    if (-1 == num_ready)
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
+#endif
+      continue;
+    }
+    if (0 == num_ready)
+    { /* select() finished by timeout, looks like no more packets are pending */
+      if (do_client)
+        externalErrorExitDesc ("Timeout waiting for sockets");
+      if (full_req_sent && (! full_req_recieved))
+        full_req_recieved = 1;
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+    if (! client_accepted)
+      client_accepted = FD_ISSET (lstn_sk, &rs);
+    else
+    { /* Client connection was already accepted by MHD */
+      if (! some_data_recieved)
+      {
+        if (! do_client)
+        {
+          if (0 != num_ready)
+          { /* Connection was accepted before, "ready" socket means data */
+            some_data_recieved = 1;
+          }
+        }
+        else
+        {
+          if (2 == num_ready)
+            some_data_recieved = 1;
+          else if ((1 == num_ready) &&
+                   ((MHD_INVALID_SOCKET == clnt->sckt) ||
+                    ! FD_ISSET (clnt->sckt, &ws)))
+            some_data_recieved = 1;
+        }
+      }
+    }
+    if (do_client)
+    {
+      if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es))
+        clnt = NULL;
+    }
+    /* Use double timeout value here so MHD would be able to catch timeout
+     * internally */
+  } while (time (NULL) - start <= (TIMEOUTS_VAL * 2));
+
+  return ret;
+}
+
+
+/* Returns zero for successful response and non-zero for failed response */
+static int
+doClientQueryInThread (struct MHD_Daemon *d,
+                       struct simpleQueryParams *p)
+{
+  const union MHD_DaemonInfo *dinfo;
+  struct _MHD_dumbClient *c;
+  int errornum;
+  int use_external_poll;
+
+  dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  use_external_poll = (0 == (dinfo->flags
+                             & MHD_USE_INTERNAL_POLLING_THREAD));
+
+  if (0 == p->queryPort)
+    externalErrorExit ();
+
+  c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath,
+                              p->headers, p->req_body, p->req_body_size,
+                              p->chunked);
+  _MHD_dumbClient_set_send_limits (c, p->step_size, p->total_send_max);
+
+  /* 'internal' polling should not be used in this test */
+  mhd_assert (use_external_poll);
+  if (! use_external_poll)
+    errornum = _MHD_dumbClient_perform (c);
+  else
+    errornum = performQueryExternal (d, c);
+
+  if (errornum)
+    fprintf (stderr, "Request timeout out.\n");
+
+  _MHD_dumbClient_close (c);
+
+  return errornum;
+}
+
+
+static void
+printTestResults (FILE *stream,
+                  struct simpleQueryParams *qParam,
+                  struct ahc_cls_type *ahc_param,
+                  struct check_uri_cls *uri_cb_param,
+                  struct term_notif_cb_param *term_result,
+                  struct sckt_notif_cb_param *sckt_result)
+{
+  if (stderr != stream)
+    fflush (stderr);
+  fprintf (stream, " Request aborted at %u byte%s.",
+           (unsigned int) qParam->total_send_max,
+           1 == qParam->total_send_max ? "" : "s");
+  if ((1 == sckt_result->num_started) && (1 == sckt_result->num_finished))
+    fprintf (stream, " One socket has been accepted and then closed.");
+  else
+    fprintf (stream, " Sockets have been accepted %u time%s"
+             " and closed %u time%s.", sckt_result->num_started,
+             (1 == sckt_result->num_started) ? "" : "s",
+             sckt_result->num_finished,
+             (1 == sckt_result->num_finished) ? "" : "s");
+  if (0 == uri_cb_param->cb_called)
+    fprintf (stream, " URI callback has NOT been called.");
+  else
+    fprintf (stream, " URI callback has been called %u time%s.",
+             uri_cb_param->cb_called,
+             1 == uri_cb_param->cb_called ? "" : "s");
+  if (0 == ahc_param->cb_called)
+    fprintf (stream, " Access handler callback has NOT been called.");
+  else
+    fprintf (stream, " Access handler callback has been called %u time%s.",
+             ahc_param->cb_called,
+             1 == ahc_param->cb_called ? "" : "s");
+  if (0 == term_result->num_called)
+    fprintf (stream, " Final notification callback has NOT been called.");
+  else
+    fprintf (stream, " Final notification callback has been called %u time%s "
+             "with %s code.", term_result->num_called,
+             (1 == term_result->num_called) ? "" : "s",
+             term_reason_str ((enum MHD_RequestTerminationCode)
+                              term_result->term_reason));
+  fprintf (stream, "\n");
+  fflush (stream);
+}
+
+
+/* Perform test queries, shut down MHD daemon, and free parameters */
+static unsigned int
+performTestQueries (struct MHD_Daemon *d, uint16_t d_port,
+                    struct ahc_cls_type *ahc_param,
+                    struct check_uri_cls *uri_cb_param,
+                    struct term_notif_cb_param *term_result,
+                    struct sckt_notif_cb_param *sckt_result)
+{
+  struct simpleQueryParams qParam;
+  time_t start;
+  unsigned int ret = 0;          /* Return value */
+  size_t req_total_size;
+  size_t limit_send_size;
+  size_t inc_size;
+  int expected_reason;
+  int found_right_reason;
+
+  /* Common parameters, to be individually overridden by specific test cases
+   * if needed */
+  qParam.queryPort = d_port;
+  qParam.method = MHD_HTTP_METHOD_PUT;
+  qParam.queryPath = EXPECTED_URI_BASE_PATH;
+  qParam.headers = REQ_HEADER_CT;
+  qParam.req_body = (const uint8_t *) REQ_BODY;
+  qParam.req_body_size = MHD_STATICSTR_LEN_ (REQ_BODY);
+  qParam.chunked = upl_chunked;
+  qParam.step_size = by_step ? 1 : 0;
+
+  uri_cb_param->uri = EXPECTED_URI_BASE_PATH;
+
+  ahc_param->rq_url = EXPECTED_URI_BASE_PATH;
+  ahc_param->rq_method = MHD_HTTP_METHOD_PUT;
+  ahc_param->rp_data = "~";
+  ahc_param->rp_data_size = 1;
+  ahc_param->req_body = (const char *) qParam.req_body;
+  ahc_param->req_body_size = qParam.req_body_size;
+
+  do
+  {
+    struct _MHD_dumbClient *test_c;
+    struct simpleQueryParams *p = &qParam;
+    test_c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath,
+                                     p->headers, p->req_body, p->req_body_size,
+                                     p->chunked);
+    req_total_size = test_c->req_size;
+    _MHD_dumbClient_close (test_c);
+  } while (0);
+
+  expected_reason = use_hard_close ?
+                    MHD_REQUEST_TERMINATED_READ_ERROR :
+                    MHD_REQUEST_TERMINATED_CLIENT_ABORT;
+  found_right_reason = 0;
+  if (0 != rate_limiter)
+  {
+    if (verbose)
+    {
+      printf ("Pausing for rate limiter...");
+      fflush (stdout);
+    }
+    _MHD_sleep (1150); /* Just a bit more than one second */
+    if (verbose)
+    {
+      printf (" OK\n");
+      fflush (stdout);
+    }
+    inc_size = ((req_total_size - 1) + (rate_limiter - 1)) / rate_limiter;
+    if (0 == inc_size)
+      inc_size = 1;
+  }
+  else
+    inc_size = 1;
+
+  start = time (NULL);
+  for (limit_send_size = 1; limit_send_size < req_total_size;
+       limit_send_size += inc_size)
+  {
+    int test_succeed;
+    test_succeed = 0;
+    /* Make sure that maximum size is tested */
+    if (req_total_size - inc_size < limit_send_size)
+      limit_send_size = req_total_size - 1;
+    qParam.total_send_max = limit_send_size;
+    /* To be updated by callbacks */
+    ahc_param->cb_called = 0;
+    uri_cb_param->cb_called = 0;
+    term_result->num_called = 0;
+    term_result->term_reason = -1;
+    sckt_result->num_started = 0;
+    sckt_result->num_finished = 0;
+
+    if (0 != doClientQueryInThread (d, &qParam))
+      fprintf (stderr, "FAILED: connection has NOT been closed by MHD.");
+    else
+    {
+      if ((-1 != term_result->term_reason) &&
+          (MHD_REQUEST_TERMINATED_READ_ERROR != term_result->term_reason) &&
+          (MHD_REQUEST_TERMINATED_CLIENT_ABORT != term_result->term_reason) )
+        fprintf (stderr, "FAILED: Wrong termination code.");
+      else if ((0 == term_result->num_called) &&
+               ((0 != uri_cb_param->cb_called) || (0 != ahc_param->cb_called)))
+        fprintf (stderr, "FAILED: Missing required call of final notification "
+                 "callback.");
+      else if (1 < uri_cb_param->cb_called)
+        fprintf (stderr, "FAILED: Too many URI callbacks.");
+      else if ((0 != ahc_param->cb_called) && (0 == uri_cb_param->cb_called))
+        fprintf (stderr, "FAILED: URI callback has NOT been called "
+                 "while Access Handler callback has been called.");
+      else if (1 < term_result->num_called)
+        fprintf (stderr, "FAILED: Too many final callbacks.");
+      else if (1 != sckt_result->num_started)
+        fprintf (stderr, "FAILED: Wrong number of sockets accepted.");
+      else if (1 != sckt_result->num_finished)
+        fprintf (stderr, "FAILED: Wrong number of sockets closed.");
+      else
+      {
+        test_succeed = 1;
+        if (expected_reason == term_result->term_reason)
+          found_right_reason = 1;
+      }
+    }
+
+    if (! test_succeed)
+    {
+      ret = 1;
+      printTestResults (stderr,
+                        &qParam, ahc_param, uri_cb_param,
+                        term_result, sckt_result);
+    }
+    else if (verbose)
+    {
+      printf ("SUCCEED:");
+      printTestResults (stdout,
+                        &qParam, ahc_param, uri_cb_param,
+                        term_result, sckt_result);
+    }
+
+    if (time (NULL) - start >
+        (time_t) ((TIMEOUTS_VAL * 25)
+                  + (rate_limiter * FINAL_PACKETS_MS) / 1000 + 1))
+    {
+      ret |= 1 << 2;
+      fprintf (stderr, "FAILED: Test total time exceeded.\n");
+      break;
+    }
+  }
+
+  MHD_stop_daemon (d);
+  free (uri_cb_param);
+  free (ahc_param);
+  free (term_result);
+  free (sckt_result);
+
+  if (! found_right_reason)
+  {
+    fprintf (stderr, "FAILED: termination callback was not called with "
+             "expected (%s) reason.\n",
+             term_reason_str ((enum MHD_RequestTerminationCode)
+                              expected_reason));
+    fflush (stderr);
+    ret |= 1 << 1;
+  }
+
+  return ret;
+}
+
+
+enum testMhdThreadsType
+{
+  testMhdThreadExternal              = 0,
+  testMhdThreadInternal              = MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION
+                                       | MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPool
+};
+
+enum testMhdPollType
+{
+  testMhdPollBySelect = 0,
+  testMhdPollByPoll   = MHD_USE_POLL,
+  testMhdPollByEpoll  = MHD_USE_EPOLL,
+  testMhdPollAuto     = MHD_USE_AUTO
+};
+
+/* Get number of threads for thread pool depending
+ * on used poll function and test type. */
+static unsigned int
+testNumThreadsForPool (enum testMhdPollType pollType)
+{
+  unsigned int numThreads = MHD_CPU_COUNT;
+  (void) pollType; /* Don't care about pollType for this test */
+  return numThreads; /* No practical limit for non-cleanup test */
+}
+
+
+static struct MHD_Daemon *
+startTestMhdDaemon (enum testMhdThreadsType thrType,
+                    enum testMhdPollType pollType, uint16_t *pport,
+                    struct ahc_cls_type **ahc_param,
+                    struct check_uri_cls **uri_cb_param,
+                    struct term_notif_cb_param **term_result,
+                    struct sckt_notif_cb_param **sckt_result)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *dinfo;
+
+  if ((NULL == ahc_param) || (NULL == uri_cb_param) || (NULL == term_result))
+    externalErrorExit ();
+
+  *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type));
+  if (NULL == *ahc_param)
+    externalErrorExit ();
+  *uri_cb_param =
+    (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls));
+  if (NULL == *uri_cb_param)
+    externalErrorExit ();
+  *term_result =
+    (struct term_notif_cb_param *) malloc (sizeof(struct term_notif_cb_param));
+  if (NULL == *term_result)
+    externalErrorExit ();
+  *sckt_result =
+    (struct sckt_notif_cb_param *) malloc (sizeof(struct sckt_notif_cb_param));
+  if (NULL == *sckt_result)
+    externalErrorExit ();
+
+  if ( (0 == *pport) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    *pport = 4170;
+    if (use_shutdown)
+      *pport += 0;
+    if (use_close)
+      *pport += 1;
+    if (use_hard_close)
+      *pport += 1;
+    if (by_step)
+      *pport += 1 << 2;
+    if (upl_chunked)
+      *pport += 1 << 3;
+    if (! oneone)
+      *pport += 1 << 4;
+  }
+
+  if (testMhdThreadInternalPool != thrType)
+    d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb,
+                          *uri_cb_param,
+                          MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result,
+                          MHD_OPTION_NOTIFY_CONNECTION, &socket_cb,
+                          *sckt_result,
+                          MHD_OPTION_CONNECTION_TIMEOUT,
+                          (unsigned) TIMEOUTS_VAL,
+                          MHD_OPTION_END);
+  else
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                          | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          testNumThreadsForPool (pollType),
+                          MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb,
+                          *uri_cb_param,
+                          MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result,
+                          MHD_OPTION_NOTIFY_CONNECTION, &socket_cb,
+                          *sckt_result,
+                          MHD_OPTION_CONNECTION_TIMEOUT,
+                          (unsigned) TIMEOUTS_VAL,
+                          MHD_OPTION_END);
+
+  if (NULL == d)
+    mhdErrorExitDesc ("Failed to start MHD daemon");
+
+  if (0 == *pport)
+  {
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port))
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    *pport = dinfo->port;
+    if (0 == global_port)
+      global_port = *pport; /* Reuse the same port for all tests */
+  }
+
+  return d;
+}
+
+
+/* Test runners */
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+  struct sckt_notif_cb_param *sckt_result;
+
+  d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port,
+                          &ahc_param, &uri_cb_param, &term_result,
+                          &sckt_result);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result,
+                             sckt_result);
+}
+
+
+#if 0 /* disabled runners, not suitable for this test */
+static int
+testInternalGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port,
+                          &ahc_param, &uri_cb_param, &term_result);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result);
+}
+
+
+static int
+testMultithreadedGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result);
+}
+
+
+static int
+testMultithreadedPoolGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result);
+}
+
+
+#endif /* disabled runners, not suitable for this test */
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  verbose = 0;
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = ! has_in_name (argv[0], "10");
+  use_shutdown = has_in_name (argv[0], "_shutdown") ? 1 : 0;
+  use_close = has_in_name (argv[0], "_close") ? 1 : 0;
+  use_hard_close = has_in_name (argv[0], "_hard_close") ? 1 : 0;
+  use_stress_os = has_in_name (argv[0], "_stress_os") ? 1 : 0;
+  by_step = has_in_name (argv[0], "_steps") ? 1 : 0;
+  upl_chunked = has_in_name (argv[0], "_chunked") ? 1 : 0;
+#ifndef SO_LINGER
+  if (use_hard_close)
+  {
+    fprintf (stderr, "This test requires SO_LINGER socket option support.\n");
+    return 77;
+  }
+#endif /* ! SO_LINGER */
+  if (1 != use_shutdown + use_close)
+    return 99;
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  if (use_stress_os && ! use_hard_close)
+    return 99;
+
+  test_global_init ();
+
+  /* Could be set to non-zero value to enforce using specific port
+   * in the test */
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet (). Result: %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+#if 0 /* disabled runners, not suitable for this test */
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result = testInternalGet (testMhdPollAuto);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+#ifdef _MHD_HEAVY_TESTS
+    /* Actually tests are not heavy, but took too long to complete while
+     * not really provide any additional results. */
+    test_result = testInternalGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedPoolGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedPoolGet (testMhdPollBySelect). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedGet (testMhdPollBySelect). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result = testInternalGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll). "
+                 "Result: %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result = testInternalGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll). "
+                 "Result: %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+    }
+#else
+    /* Mute compiler warnings */
+    (void) testMultithreadedGet;
+    (void) testMultithreadedPoolGet;
+#endif /* _MHD_HEAVY_TESTS */
+  }
+#endif /* disabled runners, not suitable for this test */
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+
+  test_global_cleanup ();
+
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/microhttpd/test_daemon.c b/src/microhttpd/test_daemon.c
index 13450ba..6990ea3 100644
--- a/src/microhttpd/test_daemon.c
+++ b/src/microhttpd/test_daemon.c
@@ -1,6 +1,6 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2007, 2017 Christian Grothoff
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -35,133 +35,205 @@
 #endif
 
 
-static int
-testStartError ()
+static unsigned int
+testStartError (void)
 {
   struct MHD_Daemon *d;
 
-  d = MHD_start_daemon (MHD_USE_DEBUG, 0, NULL, NULL, NULL, NULL);
-  if (d != NULL)
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, NULL, NULL);
+  if (NULL != d)
+  {
+    MHD_stop_daemon (d);
+    fprintf (stderr,
+             "Succeeded to start without MHD_AccessHandlerCallback?\n");
     return 1;
+  }
   return 0;
 }
 
-static int
-apc_nothing (void *cls, const struct sockaddr *addr, socklen_t addrlen)
+
+static enum MHD_Result
+apc_nothing (void *cls,
+             const struct sockaddr *addr,
+             socklen_t addrlen)
 {
+  (void) cls; (void) addr; (void) addrlen; /* Unused. Silent compiler warning. */
+
   return MHD_NO;
 }
 
-static int
-apc_all (void *cls, const struct sockaddr *addr, socklen_t addrlen)
+
+static enum MHD_Result
+apc_all (void *cls,
+         const struct sockaddr *addr,
+         socklen_t addrlen)
 {
+  (void) cls; (void) addr; (void) addrlen; /* Unused. Silent compiler warning. */
+
   return MHD_YES;
 }
 
-static int
+
+static enum MHD_Result
 ahc_nothing (void *cls,
              struct MHD_Connection *connection,
              const char *url,
              const char *method,
              const char *version,
              const char *upload_data, size_t *upload_data_size,
-             void **unused)
+             void **req_cls)
 {
+  (void) cls; (void) connection; (void) url;         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls;           /* Unused. Silent compiler warning. */
+
   return MHD_NO;
 }
 
-static int
-testStartStop ()
+
+static unsigned int
+testStartStop (void)
 {
   struct MHD_Daemon *d;
 
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080,
-                        &apc_nothing,
-                        NULL, &ahc_nothing, NULL, MHD_OPTION_END);
-  if (d == NULL)
-    return 2;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        0,
+                        &apc_nothing, NULL,
+                        &ahc_nothing, NULL,
+                        MHD_OPTION_END);
+  if (NULL == d)
+  {
+    fprintf (stderr,
+             "Failed to start daemon on port %u\n",
+             (unsigned int) 0);
+    exit (77);
+  }
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
-testExternalRun ()
+
+static unsigned int
+testExternalRun (void)
 {
   struct MHD_Daemon *d;
   fd_set rs;
   MHD_socket maxfd;
   int i;
 
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1081,
-                        &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        0,
+                        &apc_all, NULL,
+                        &ahc_nothing, NULL,
+                        MHD_OPTION_END);
 
-  if (d == NULL)
-    return 4;
+  if (NULL == d)
+  {
+    fprintf (stderr,
+             "Failed to start daemon on port %u\n",
+             (unsigned int) 0);
+    exit (77);
+  }
   i = 0;
   while (i < 15)
+  {
+    maxfd = 0;
+    FD_ZERO (&rs);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &rs, &rs, &maxfd))
     {
-      maxfd = 0;
-      FD_ZERO (&rs);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &rs, &rs, &maxfd))
-	{
-	  MHD_stop_daemon (d);
-	  return 256;
-	}
-      if (MHD_run (d) == MHD_NO)
-        {
-          MHD_stop_daemon (d);
-          return 8;
-        }
-      i++;
+      MHD_stop_daemon (d);
+      fprintf (stderr,
+               "Failed in MHD_get_fdset().\n");
+      return 256;
     }
+    if (MHD_run (d) == MHD_NO)
+    {
+      MHD_stop_daemon (d);
+      fprintf (stderr,
+               "Failed in MHD_run().\n");
+      return 8;
+    }
+    i++;
+  }
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
-testThread ()
+
+static unsigned int
+testThread (void)
 {
   struct MHD_Daemon *d;
-  d = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SELECT_INTERNALLY,
-                        1082,
-                        &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END);
 
-  if (d == NULL)
-    return 16;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_INTERNAL_POLLING_THREAD,
+                        0,
+                        &apc_all, NULL,
+                        &ahc_nothing, NULL,
+                        MHD_OPTION_END);
+
+  if (NULL == d)
+  {
+    fprintf (stderr,
+             "Failed to start daemon on port %u.\n",
+             (unsigned int) 1082);
+    exit (77);
+  }
   if (MHD_run (d) != MHD_NO)
+  {
+    fprintf (stderr,
+             "Failed in MHD_run().\n");
     return 32;
+  }
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
-testMultithread ()
+
+static unsigned int
+testMultithread (void)
 {
   struct MHD_Daemon *d;
-  d = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_THREAD_PER_CONNECTION,
-                        1083,
-                        &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END);
 
-  if (d == NULL)
-    return 64;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_THREAD_PER_CONNECTION,
+                        0,
+                        &apc_all, NULL,
+                        &ahc_nothing, NULL,
+                        MHD_OPTION_END);
+
+  if (NULL == d)
+  {
+    fprintf (stderr,
+             "Failed to start daemon on port %u\n",
+             (unsigned int) 0);
+    exit (77);
+  }
   if (MHD_run (d) != MHD_NO)
+  {
+    fprintf (stderr,
+             "Failed in MHD_run().\n");
     return 128;
+  }
   MHD_stop_daemon (d);
   return 0;
 }
 
+
 int
-main (int argc, char *const *argv)
+main (int argc,
+      char *const *argv)
 {
-  int errorCount = 0;
+  unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+
   errorCount += testStartError ();
   errorCount += testStartStop ();
   errorCount += testExternalRun ();
   errorCount += testThread ();
   errorCount += testMultithread ();
-  if (errorCount != 0)
-    fprintf (stderr, "Error (code: %u)\n", errorCount);
-  return errorCount != 0;       /* 0 == pass */
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  return 0 != errorCount;       /* 0 == pass */
 }
diff --git a/src/microhttpd/test_dauth_userdigest.c b/src/microhttpd/test_dauth_userdigest.c
new file mode 100644
index 0000000..f467be6
--- /dev/null
+++ b/src/microhttpd/test_dauth_userdigest.c
@@ -0,0 +1,647 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Evgeny Grin (Karlson2)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_dauth_userdigest.c
+ * @brief  Tests for Digest Auth calculations of userdigest
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "microhttpd.h"
+#include "test_helpers.h"
+
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
+
+static int verbose = 1; /* verbose level (0-1)*/
+
+/* Declarations and data */
+
+struct data_md5
+{
+  unsigned int line_num;
+  const char *const username;
+  const char *const realm;
+  const char *const password;
+  const uint8_t hash[MHD_MD5_DIGEST_SIZE];
+};
+
+
+static const struct data_md5 md5_tests[] = {
+  {__LINE__,
+   "u", "r", "p",
+   {0x44, 0xad, 0xd2, 0x2b, 0x6f, 0x31, 0x79, 0xb7, 0x51, 0xea, 0xfd, 0x68,
+    0xee, 0x37, 0x0f, 0x7d}},
+  {__LINE__,
+   "testuser", "testrealm", "testpass",
+   {0xeb, 0xff, 0x22, 0x5e, 0x1c, 0xeb, 0x73, 0xe0, 0x26, 0xfc, 0xc6, 0x45,
+    0xaf, 0x3e, 0x84, 0xf6}},
+  {__LINE__,  /* Values from testcurl/test_digestauth2.c */
+   "test_user", "TestRealm", "test pass",
+   {0xd8, 0xb4, 0xa6, 0xd0, 0x01, 0x13, 0x07, 0xb7, 0x67, 0x94, 0xea, 0x66,
+    0x86, 0x03, 0x6b, 0x43}},
+  {__LINE__,
+   "Mufasa", "myhost@testrealm.com", "CircleOfLife",
+   {0x7e, 0xbe, 0xcc, 0x07, 0x18, 0xa5, 0x4a, 0xb4, 0x7e, 0x21, 0x65, 0x69,
+    0x07, 0x66, 0x41, 0x6a}},
+  {__LINE__,
+   "Mufasa", "myhost@example.com", "Circle Of Life",
+   {0x6a, 0x6d, 0x4e, 0x7c, 0xd7, 0x15, 0x18, 0x68, 0xf9, 0xb8, 0xc7, 0xc8,
+    0xd1, 0xcd, 0xd4, 0xe0}},
+  {__LINE__,
+   "Mufasa", "http-auth@example.org", "Circle of Life",
+   {0x3d, 0x78, 0x80, 0x7d, 0xef, 0xe7, 0xde, 0x21, 0x57, 0xe2, 0xb0, 0xb6,
+    0x57, 0x3a, 0x85, 0x5f}},
+  {__LINE__,
+   "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */,
+   "api@example.org", "Secret, or not?",
+   {0x83, 0xa3, 0xf7, 0xf6, 0xb8, 0x3f, 0x71, 0xc5, 0xc2, 0xeb, 0x7c, 0x6d,
+    0xd2, 0xdd, 0x4c, 0x4b}}
+};
+
+struct data_sha256
+{
+  unsigned int line_num;
+  const char *const username;
+  const char *const realm;
+  const char *const password;
+  const uint8_t hash[MHD_SHA256_DIGEST_SIZE];
+};
+
+static const struct data_sha256 sha256_tests[] = {
+  {__LINE__,
+   "u", "r", "p",
+   {0xdc, 0xb0, 0x21, 0x10, 0x2e, 0x49, 0x1e, 0x70, 0x1a, 0x4a, 0x23, 0x6d,
+    0xaa, 0x89, 0x23, 0xaf, 0x21, 0x61, 0x44, 0x7b, 0xce, 0x7b, 0xb7, 0x26,
+    0x0a, 0x35, 0x1e, 0xe8, 0x3e, 0x9f, 0x81, 0x54}},
+  {__LINE__,
+   "testuser", "testrealm", "testpass",
+   {0xa9, 0x2e, 0xf6, 0x3b, 0x3d, 0xec, 0x38, 0x95, 0xb0, 0x8f, 0x3d, 0x4d,
+    0x67, 0x33, 0xf0, 0x70, 0x74, 0xcb, 0xe6, 0xd4, 0xa0, 0x01, 0x27, 0xf5,
+    0x74, 0x1a, 0x77, 0x4f, 0x05, 0xf9, 0xd4, 0x99}},
+  {__LINE__,  /* Values from testcurl/test_digestauth2.c */
+   "test_user", "TestRealm", "test pass",
+   {0xc3, 0x4e, 0x16, 0x5a, 0x17, 0x0f, 0xe5, 0xac, 0x04, 0xf1, 0x6e, 0x46,
+    0x48, 0x2b, 0xa0, 0xc6, 0x56, 0xc1, 0xfb, 0x8f, 0x66, 0xa6, 0xd6, 0x3f,
+    0x91, 0x12, 0xf8, 0x56, 0xa5, 0xec, 0x6d, 0x6d}},
+  {__LINE__,
+   "Mufasa", "myhost@testrealm.com", "CircleOfLife",
+   {0x8e, 0x64, 0x1f, 0xaa, 0x71, 0x7d, 0x20, 0x70, 0x5a, 0xd7, 0x3c, 0x54,
+    0xfb, 0x04, 0x9e, 0x32, 0x6a, 0xe1, 0x1c, 0x80, 0xd6, 0x05, 0x9f, 0xc3,
+    0x7e, 0xbb, 0x2d, 0x7b, 0x60, 0x6c, 0x11, 0xb9}},
+  {__LINE__,
+   "Mufasa", "myhost@example.com", "Circle Of Life",
+   {0x8b, 0xc5, 0xa8, 0xed, 0xe3, 0x02, 0x15, 0x6b, 0x9f, 0x51, 0xce, 0x97,
+    0x81, 0xb5, 0x26, 0xff, 0x99, 0x29, 0x0b, 0xb2, 0xc3, 0xe4, 0x41, 0x71,
+    0x8e, 0xa3, 0xa1, 0x7e, 0x5a, 0xd9, 0xd6, 0x49}},
+  {__LINE__,
+   "Mufasa", "http-auth@example.org", "Circle of Life",
+   {0x79, 0x87, 0xc6, 0x4c, 0x30, 0xe2, 0x5f, 0x1b, 0x74, 0xbe, 0x53, 0xf9,
+    0x66, 0xb4, 0x9b, 0x90, 0xf2, 0x80, 0x8a, 0xa9, 0x2f, 0xaf, 0x9a, 0x00,
+    0x26, 0x23, 0x92, 0xd7, 0xb4, 0x79, 0x42, 0x32}},
+  {__LINE__,
+   "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */,
+   "api@example.org", "Secret, or not?",
+   {0xfd, 0x0b, 0xe3, 0x93, 0x9d, 0xca, 0x4b, 0x5c, 0x2d, 0x46, 0xe8, 0xfa,
+    0x6a, 0x3d, 0x16, 0xdb, 0xea, 0x82, 0x47, 0x4c, 0xb9, 0xa5, 0x88, 0xd4,
+    0xcb, 0x14, 0x9c, 0x54, 0xf3, 0x7c, 0xff, 0x37}}
+};
+
+struct data_sha512_256
+{
+  unsigned int line_num;
+  const char *const username;
+  const char *const realm;
+  const char *const password;
+  const uint8_t hash[MHD_SHA512_256_DIGEST_SIZE];
+};
+
+static const struct data_sha512_256 sha512_256_tests[] = {
+  {__LINE__,
+   "u", "r", "p",
+   {0xd5, 0xe8, 0xe7, 0x3b, 0xa3, 0x47, 0xb9, 0xad, 0xf0, 0xe4, 0x7a, 0x9a,
+    0xce, 0x43, 0xb7, 0x08, 0x2a, 0xbc, 0x8d, 0x27, 0x27, 0x2e, 0x38, 0x7d,
+    0x1d, 0x9c, 0xe2, 0x44, 0x25, 0x68, 0x74, 0x04}},
+  {__LINE__,
+   "testuser", "testrealm", "testpass",
+   {0x41, 0x7d, 0xf9, 0x60, 0x7c, 0xc9, 0x60, 0x28, 0x44, 0x74, 0x75, 0xf7,
+    0x7b, 0x78, 0xe7, 0x60, 0xec, 0x9a, 0xe1, 0x62, 0xd4, 0x95, 0x82, 0x61,
+    0x68, 0xa7, 0x94, 0xe8, 0x3b, 0xdf, 0x8d, 0x59}},
+  {__LINE__,  /* Values from testcurl/test_digestauth2.c */
+   "test_user", "TestRealm", "test pass",
+   {0xe7, 0xa1, 0x9e, 0x27, 0xf6, 0x73, 0x88, 0xb2, 0xde, 0xa4, 0xe2, 0x66,
+    0xc5, 0x16, 0x37, 0x17, 0x4d, 0x29, 0xcc, 0xa3, 0xc1, 0xf5, 0xb2, 0x49,
+    0x20, 0xc1, 0x05, 0xc9, 0x20, 0x13, 0x3c, 0x3d}},
+  {__LINE__,
+   "Mufasa", "myhost@testrealm.com", "CircleOfLife",
+   {0x44, 0xbc, 0xd2, 0xb1, 0x1f, 0x6f, 0x7d, 0xd3, 0xae, 0xa6, 0x66, 0x8a,
+    0x24, 0x84, 0x4b, 0x87, 0x7d, 0xe1, 0x80, 0x24, 0x9a, 0x26, 0x6b, 0xe6,
+    0xdb, 0x7f, 0xe3, 0xc8, 0x7a, 0xf9, 0x75, 0x64}},
+  {__LINE__,
+   "Mufasa", "myhost@example.com", "Circle Of Life",
+   {0xd5, 0xf6, 0x25, 0x7c, 0x64, 0xe4, 0x01, 0xd2, 0x87, 0xd5, 0xaa, 0x19,
+    0xae, 0xf0, 0xa2, 0xa2, 0xce, 0x4e, 0x5d, 0xfc, 0x77, 0x70, 0x0b, 0x72,
+    0x90, 0x43, 0x96, 0xd2, 0x95, 0x6e, 0x83, 0x0a}},
+  {__LINE__,
+   "Mufasa", "http-auth@example.org", "Circle of Life",
+   {0xfb, 0x17, 0x4f, 0x5c, 0x3c, 0x78, 0x02, 0x72, 0x15, 0x17, 0xca, 0xe1,
+    0x3b, 0x98, 0xe2, 0xb8, 0xda, 0xe2, 0xe0, 0x11, 0x8c, 0xb7, 0x05, 0xd9,
+    0x4e, 0xe2, 0x99, 0x46, 0x31, 0x92, 0x04, 0xce}},
+  {__LINE__,
+   "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */,
+   "api@example.org", "Secret, or not?",
+   {0x2d, 0x3d, 0x9f, 0x12, 0xc9, 0xf3, 0xd3, 0x00, 0x11, 0x25, 0x9d, 0xc5,
+    0xfe, 0xce, 0xe0, 0x05, 0xae, 0x24, 0xde, 0x40, 0xe3, 0xe1, 0xf6, 0x18,
+    0x06, 0xd0, 0x3e, 0x65, 0xf1, 0xe6, 0x02, 0x4f}}
+};
+
+
+/*
+ *  Helper functions
+ */
+
+/**
+ * Print bin as lower case hex
+ *
+ * @param bin binary data
+ * @param len number of bytes in bin
+ * @param hex pointer to len*2+1 bytes buffer
+ */
+static void
+bin2hex (const uint8_t *bin,
+         size_t len,
+         char *hex)
+{
+  while (len-- > 0)
+  {
+    unsigned int b1, b2;
+    b1 = (*bin >> 4) & 0xf;
+    *hex++ = (char) ((b1 > 9) ? (b1 + 'a' - 10) : (b1 + '0'));
+    b2 = *bin++ & 0xf;
+    *hex++ = (char) ((b2 > 9) ? (b2 + 'a' - 10) : (b2 + '0'));
+  }
+  *hex = 0;
+}
+
+
+/* Tests */
+
+static unsigned int
+check_md5 (const struct data_md5 *const data)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5;
+  uint8_t hash_bin[MHD_MD5_DIGEST_SIZE];
+  char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1];
+  char expected_hex[MHD_MD5_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userdigest";
+  if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3,
+                                                  data->username,
+                                                  data->realm,
+                                                  data->password,
+                                                  hash_bin, sizeof(hash_bin)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash)))
+  {
+    failed++;
+    bin2hex (hash_bin, sizeof(hash_bin), hash_hex);
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    fprintf (stderr,
+             "FAILED: %s() produced wrong hash. "
+             "Calculated digest %s, expected digest %s.\n",
+             func_name,
+             hash_hex, expected_hex);
+  }
+
+  if (failed)
+  {
+    fprintf (stderr,
+             "The check failed for data located at line: %u.\n",
+             data->line_num);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    printf ("PASSED: check for data at line: %u.\n",
+            data->line_num);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+test_md5 (void)
+{
+  unsigned int num_failed = 0;
+  size_t i;
+
+  for (i = 0; i < sizeof(md5_tests) / sizeof(md5_tests[0]); i++)
+    num_failed += check_md5 (md5_tests + i);
+  return num_failed;
+}
+
+
+static unsigned int
+test_md5_failure (void)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5;
+  uint8_t hash_bin[MHD_MD5_DIGEST_SIZE];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userdigest";
+  if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3,
+                                                 "u", "r", "p",
+                                                 hash_bin, sizeof(hash_bin)
+                                                 - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3,
+                                                 "u", "r", "p",
+                                                 hash_bin, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5))
+  {
+    if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3,
+                                                   "u", "r", "p",
+                                                   hash_bin, sizeof(hash_bin)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  if (! failed && verbose)
+  {
+    printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n",
+            (unsigned) __LINE__);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+check_sha256 (const struct data_sha256 *const data)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256;
+  uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1];
+  char expected_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userdigest";
+  if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3,
+                                                  data->username,
+                                                  data->realm,
+                                                  data->password,
+                                                  hash_bin, sizeof(hash_bin)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash)))
+  {
+    failed++;
+    bin2hex (hash_bin, sizeof(hash_bin), hash_hex);
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    fprintf (stderr,
+             "FAILED: %s() produced wrong hash. "
+             "Calculated digest %s, expected digest %s.\n",
+             func_name,
+             hash_hex, expected_hex);
+  }
+
+  if (failed)
+  {
+    fprintf (stderr,
+             "The check failed for data located at line: %u.\n",
+             data->line_num);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    printf ("PASSED: check for data at line: %u.\n",
+            data->line_num);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+test_sha256 (void)
+{
+  unsigned int num_failed = 0;
+  size_t i;
+
+  for (i = 0; i < sizeof(sha256_tests) / sizeof(sha256_tests[0]); i++)
+    num_failed += check_sha256 (sha256_tests + i);
+  return num_failed;
+}
+
+
+static unsigned int
+test_sha256_failure (void)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256;
+  uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, sizeof(hash_bin) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256))
+  {
+    if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                                 "u", "r",
+                                                 hash_bin, sizeof(hash_bin)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, sizeof(hash_hex) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256))
+  {
+    if (MHD_NO !=
+        MHD_digest_auth_calc_userhash_hex (algo3,
+                                           "u", "r",
+                                           hash_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  if (! failed && verbose)
+  {
+    printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n",
+            (unsigned) __LINE__);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+check_sha512_256 (const struct data_sha512_256 *const data)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 =
+    MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+  uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1];
+  char expected_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userdigest";
+  if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3,
+                                                  data->username,
+                                                  data->realm,
+                                                  data->password,
+                                                  hash_bin, sizeof(hash_bin)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash)))
+  {
+    failed++;
+    bin2hex (hash_bin, sizeof(hash_bin), hash_hex);
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    fprintf (stderr,
+             "FAILED: %s() produced wrong hash. "
+             "Calculated digest %s, expected digest %s.\n",
+             func_name,
+             hash_hex, expected_hex);
+  }
+
+  if (failed)
+  {
+    fprintf (stderr,
+             "The check failed for data located at line: %u.\n",
+             data->line_num);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    printf ("PASSED: check for data at line: %u.\n",
+            data->line_num);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+test_sha512_256 (void)
+{
+  unsigned int num_failed = 0;
+  size_t i;
+
+  for (i = 0; i < sizeof(sha512_256_tests) / sizeof(sha512_256_tests[0]); i++)
+    num_failed += check_sha512_256 (sha512_256_tests + i);
+  return num_failed;
+}
+
+
+static unsigned int
+test_sha512_256_failure (void)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 =
+    MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+  static const enum MHD_FEATURE feature = MHD_FEATURE_DIGEST_AUTH_SHA512_256;
+  uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, sizeof(hash_bin) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (feature))
+  {
+    if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                                 "u", "r",
+                                                 hash_bin, sizeof(hash_bin)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, sizeof(hash_hex) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (feature))
+  {
+    if (MHD_NO !=
+        MHD_digest_auth_calc_userhash_hex (algo3,
+                                           "u", "r",
+                                           hash_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  if (! failed && verbose)
+  {
+    printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n",
+            (unsigned) __LINE__);
+  }
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int num_failed = 0;
+  (void) has_in_name; /* Mute compiler warning. */
+  if (has_param (argc, argv, "-s") || has_param (argc, argv, "--silent"))
+    verbose = 0;
+
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+
+  if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5))
+    num_failed += test_md5 ();
+  num_failed += test_md5_failure ();
+  if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256))
+    num_failed += test_sha256 ();
+  num_failed += test_sha256_failure ();
+  if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA512_256))
+    num_failed += test_sha512_256 ();
+  num_failed += test_sha512_256_failure ();
+
+  return num_failed ? 1 : 0;
+}
diff --git a/src/microhttpd/test_dauth_userhash.c b/src/microhttpd/test_dauth_userhash.c
new file mode 100644
index 0000000..c145beb
--- /dev/null
+++ b/src/microhttpd/test_dauth_userhash.c
@@ -0,0 +1,776 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Evgeny Grin (Karlson2)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_dauth_userhash.c
+ * @brief  Tests for Digest Auth calculations of userhash
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "mhd_options.h"
+#include "microhttpd.h"
+#include "test_helpers.h"
+
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
+
+static int verbose = 1; /* verbose level (0-1)*/
+
+/* Declarations and data */
+
+struct data_md5
+{
+  unsigned int line_num;
+  const char *const username;
+  const char *const realm;
+  const uint8_t hash[MHD_MD5_DIGEST_SIZE];
+};
+
+
+static const struct data_md5 md5_tests[] = {
+  {__LINE__,
+   "u", "r",
+   {0xba, 0x84, 0xbe, 0x20, 0x3f, 0xdf, 0xc7, 0xd3, 0x4e, 0x05, 0x4a, 0x76,
+    0xd2, 0x85, 0xd0, 0xc9}},
+  {__LINE__,
+   "testuser", "testrealm",
+   {0xab, 0xae, 0x15, 0x95, 0x24, 0xe5, 0x17, 0xbf, 0x48, 0xf4, 0x4a, 0xab,
+    0xfe, 0xb9, 0x37, 0x40}},
+  {__LINE__,
+   "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */
+   {0xc5, 0x3c, 0x60, 0x15, 0x03, 0xff, 0x17, 0x6f, 0x18, 0xf6, 0x23, 0x72,
+    0x5f, 0xba, 0x42, 0x81}},
+  {__LINE__,
+   "Mufasa", "myhost@testrealm.com",
+   {0x26, 0x45, 0xae, 0x13, 0xd1, 0xa2, 0xa6, 0x9e, 0xd2, 0x6d, 0xd2, 0x1a,
+    0xa5, 0x52, 0x86, 0xe3}},
+  {__LINE__,
+   "Mufasa", "myhost@example.com",
+   {0x4f, 0xc8, 0x64, 0x02, 0xd7, 0x18, 0x5d, 0x7b, 0x38, 0xd4, 0x38, 0xad,
+    0xd5, 0x5a, 0x35, 0x84}},
+  {__LINE__,
+   "Mufasa", "http-auth@example.org",
+   {0x42, 0x38, 0xf3, 0xa1, 0x61, 0x67, 0x37, 0x3f, 0xeb, 0xb9, 0xbc, 0x4d,
+    0x43, 0xdb, 0x9c, 0xc4}},
+  {__LINE__,
+   "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org",
+   {0x2e, 0x06, 0x3f, 0xa2, 0xc5, 0x4d, 0xea, 0x1c, 0x36, 0x80, 0x8b, 0x7a,
+    0x6e, 0x3b, 0x14, 0xc9}}
+};
+
+struct data_sha256
+{
+  unsigned int line_num;
+  const char *const username;
+  const char *const realm;
+  const uint8_t hash[MHD_SHA256_DIGEST_SIZE];
+};
+
+static const struct data_sha256 sha256_tests[] = {
+  {__LINE__,
+   "u", "r",
+   {0x1d, 0x8a, 0x03, 0xa6, 0xe2, 0x1a, 0x4c, 0xe7, 0x75, 0x06, 0x0e, 0xa5,
+    0x73, 0x60, 0x32, 0x9a, 0xc7, 0x50, 0xde, 0xa5, 0xd8, 0x47, 0x29, 0x7b,
+    0x42, 0xf0, 0xd4, 0x65, 0x39, 0xaf, 0x8a, 0xb2}},
+  {__LINE__,
+   "testuser", "testrealm",
+   {0x75, 0xaf, 0x8a, 0x35, 0x00, 0xf7, 0x71, 0xe5, 0x8a, 0x52, 0x09, 0x3a,
+    0x25, 0xe7, 0x90, 0x5d, 0x6e, 0x42, 0x8a, 0x51, 0x12, 0x85, 0xc1, 0x2e,
+    0xa1, 0x42, 0x0c, 0x73, 0x07, 0x8d, 0xfd, 0x61}},
+  {__LINE__,
+   "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */
+   {0x09, 0x0c, 0x7e, 0x06, 0xb7, 0x7d, 0x66, 0x14, 0xcf, 0x5f, 0xe6, 0xca,
+    0xfa, 0x00, 0x4d, 0x2e, 0x5f, 0x8f, 0xb3, 0x6b, 0xa4, 0x5a, 0x0e, 0x35,
+    0xea, 0xcb, 0x2e, 0xb7, 0x72, 0x8f, 0x34, 0xde}},
+  {__LINE__,
+   "Mufasa", "myhost@testrealm.com",
+   {0x92, 0x9f, 0xac, 0x9e, 0x6c, 0x8b, 0x76, 0xcc, 0xab, 0xa9, 0xe0, 0x6f,
+    0xf6, 0x4d, 0xf2, 0x6f, 0xcb, 0x40, 0x56, 0x4c, 0x19, 0x9c, 0x32, 0xd9,
+    0xea, 0xd9, 0x12, 0x4b, 0x25, 0x34, 0xe1, 0xf9}},
+  {__LINE__,
+   "Mufasa", "myhost@example.com",
+   {0x97, 0x06, 0xf0, 0x07, 0x1c, 0xec, 0x05, 0x3f, 0x88, 0x22, 0xb6, 0x63,
+    0x69, 0xc4, 0xa4, 0x00, 0x39, 0x79, 0xb7, 0xe7, 0x42, 0xb7, 0x4e, 0x42,
+    0x59, 0x63, 0x57, 0xf4, 0xd3, 0x02, 0xae, 0x16}},
+  {__LINE__,
+   "Mufasa", "http-auth@example.org",
+   {0xa9, 0x47, 0xaa, 0xd2, 0x05, 0xe8, 0x0e, 0x42, 0x99, 0x58, 0xa3, 0x87,
+    0x39, 0x49, 0x44, 0xc6, 0xb4, 0x96, 0x30, 0x1e, 0x79, 0xf8, 0x9d, 0x35,
+    0xa4, 0xcc, 0x23, 0xb6, 0xee, 0x12, 0xb5, 0xb6}},
+  {__LINE__,
+   "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org",
+   {0x5a, 0x1a, 0x8a, 0x47, 0xdf, 0x5c, 0x29, 0x85, 0x51, 0xb9, 0xb4, 0x2b,
+    0xa9, 0xb0, 0x58, 0x35, 0x17, 0x4a, 0x5b, 0xd7, 0xd5, 0x11, 0xff, 0x7f,
+    0xe9, 0x19, 0x1d, 0x8e, 0x94, 0x6f, 0xc4, 0xe7}}
+};
+
+struct data_sha512_256
+{
+  unsigned int line_num;
+  const char *const username;
+  const char *const realm;
+  const uint8_t hash[MHD_SHA512_256_DIGEST_SIZE];
+};
+
+
+static const struct data_sha512_256 sha512_256_tests[] = {
+  {__LINE__,
+   "u", "r",
+   {0xc7, 0x38, 0xf2, 0xad, 0x40, 0x1b, 0xc8, 0x7a, 0x71, 0xfe, 0x78, 0x09,
+    0x60, 0x15, 0xc9, 0x7b, 0x9a, 0x26, 0xd5, 0x5f, 0x15, 0xe9, 0xf5, 0x0a,
+    0xc3, 0xa6, 0xde, 0x73, 0xdd, 0xcd, 0x3d, 0x08}},
+  {__LINE__,
+   "testuser", "testrealm",
+   {0x4f, 0x69, 0x1e, 0xe9, 0x50, 0x8a, 0xe4, 0x55, 0x21, 0x32, 0x9e, 0xcf,
+    0xd4, 0x91, 0xf7, 0xe2, 0x77, 0x4b, 0x6f, 0xb8, 0x60, 0x2c, 0x14, 0x86,
+    0xad, 0x94, 0x9d, 0x1c, 0x23, 0xd8, 0xa1, 0xf5}},
+  {__LINE__,
+   "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */
+   {0x62, 0xe1, 0xac, 0x9f, 0x6c, 0xb1, 0xeb, 0x26, 0xaa, 0x75, 0xeb, 0x5d,
+    0x46, 0xef, 0xcd, 0xc8, 0x9c, 0xcb, 0xa7, 0x81, 0xf0, 0xf9, 0xf7, 0x2f,
+    0x6a, 0xfd, 0xb9, 0x42, 0x65, 0xd9, 0xa7, 0x9a}},
+  {__LINE__,
+   "Mufasa", "myhost@testrealm.com",
+   {0xbd, 0x3e, 0xbc, 0x30, 0x10, 0x0b, 0x7c, 0xf1, 0x61, 0x45, 0x6c, 0xfe,
+    0x64, 0x1c, 0x4c, 0xd2, 0x82, 0xe0, 0x62, 0x6e, 0x2c, 0x5e, 0x09, 0xc2,
+    0x4c, 0x90, 0xb1, 0x60, 0x8a, 0xec, 0x28, 0x64}},
+  {__LINE__,
+   "Mufasa", "myhost@example.com",
+   {0xea, 0x4b, 0x59, 0x37, 0xde, 0x2c, 0x4e, 0x9f, 0x16, 0xf9, 0x9c, 0x31,
+    0x01, 0xb6, 0xdd, 0xf8, 0x8c, 0x85, 0xd7, 0xe8, 0xf1, 0x75, 0x90, 0xd0,
+    0x63, 0x2a, 0x75, 0x75, 0xe4, 0x80, 0x13, 0x69}},
+  {__LINE__,
+   "Mufasa", "http-auth@example.org",
+   {0xe2, 0xdf, 0xab, 0xd1, 0xa9, 0x6d, 0xdf, 0x86, 0x77, 0x10, 0xb6, 0x53,
+    0xb6, 0xe6, 0x85, 0x7d, 0x1f, 0x14, 0x70, 0x86, 0xde, 0x7d, 0x7e, 0xf7,
+    0x9d, 0xcd, 0x24, 0x98, 0x59, 0x87, 0x25, 0x70}},
+  {__LINE__,
+   "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org",
+   {0x79, 0x32, 0x63, 0xca, 0xab, 0xb7, 0x07, 0xa5, 0x62, 0x11, 0x94, 0x0d,
+    0x90, 0x41, 0x1e, 0xa4, 0xa5, 0x75, 0xad, 0xec, 0xcb, 0x7e, 0x36, 0x0a,
+    0xeb, 0x62, 0x4e, 0xd0, 0x6e, 0xce, 0x9b, 0x0b}}
+};
+
+
+/*
+ *  Helper functions
+ */
+
+/**
+ * Print bin as lower case hex
+ *
+ * @param bin binary data
+ * @param len number of bytes in bin
+ * @param hex pointer to len*2+1 bytes buffer
+ */
+static void
+bin2hex (const uint8_t *bin,
+         size_t len,
+         char *hex)
+{
+  while (len-- > 0)
+  {
+    unsigned int b1, b2;
+    b1 = (*bin >> 4) & 0xf;
+    *hex++ = (char) ((b1 > 9) ? (b1 + 'a' - 10) : (b1 + '0'));
+    b2 = *bin++ & 0xf;
+    *hex++ = (char) ((b2 > 9) ? (b2 + 'a' - 10) : (b2 + '0'));
+  }
+  *hex = 0;
+}
+
+
+/* Tests */
+
+static unsigned int
+check_md5 (const struct data_md5 *const data)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5;
+  uint8_t hash_bin[MHD_MD5_DIGEST_SIZE];
+  char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1];
+  char expected_hex[MHD_MD5_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_YES != MHD_digest_auth_calc_userhash (algo3,
+                                                data->username, data->realm,
+                                                hash_bin, sizeof(hash_bin)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash)))
+  {
+    failed++;
+    bin2hex (hash_bin, sizeof(hash_bin), hash_hex);
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    fprintf (stderr,
+             "FAILED: %s() produced wrong hash. "
+             "Calculated digest %s, expected digest %s.\n",
+             func_name,
+             hash_hex, expected_hex);
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_YES !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         data->username, data->realm,
+                                         hash_hex, sizeof(hash_hex)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (sizeof(hash_hex) - 1 != strlen (hash_hex))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s produced hash with wrong length. "
+             "Calculated length %u, expected digest %u.\n",
+             func_name,
+             (unsigned) strlen (hash_hex),
+             (unsigned) (sizeof(hash_hex) - 1));
+  }
+  else
+  {
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() produced wrong hash. "
+               "Calculated digest %s, expected digest %s.\n",
+               func_name,
+               hash_hex, expected_hex);
+    }
+  }
+
+  if (failed)
+  {
+    fprintf (stderr,
+             "The check failed for data located at line: %u.\n",
+             data->line_num);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    printf ("PASSED: check for data at line: %u.\n",
+            data->line_num);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+test_md5 (void)
+{
+  unsigned int num_failed = 0;
+  size_t i;
+
+  for (i = 0; i < sizeof(md5_tests) / sizeof(md5_tests[0]); i++)
+    num_failed += check_md5 (md5_tests + i);
+  return num_failed;
+}
+
+
+static unsigned int
+test_md5_failure (void)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5;
+  uint8_t hash_bin[MHD_MD5_DIGEST_SIZE];
+  char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, sizeof(hash_bin) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5))
+  {
+    if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                                 "u", "r",
+                                                 hash_bin, sizeof(hash_bin)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, sizeof(hash_hex) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5))
+  {
+    if (MHD_NO !=
+        MHD_digest_auth_calc_userhash_hex (algo3,
+                                           "u", "r",
+                                           hash_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  if (! failed && verbose)
+  {
+    printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n",
+            (unsigned) __LINE__);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+check_sha256 (const struct data_sha256 *const data)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256;
+  uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1];
+  char expected_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_YES != MHD_digest_auth_calc_userhash (algo3,
+                                                data->username, data->realm,
+                                                hash_bin, sizeof(hash_bin)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash)))
+  {
+    failed++;
+    bin2hex (hash_bin, sizeof(hash_bin), hash_hex);
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    fprintf (stderr,
+             "FAILED: %s() produced wrong hash. "
+             "Calculated digest %s, expected digest %s.\n",
+             func_name,
+             hash_hex, expected_hex);
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_YES !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         data->username, data->realm,
+                                         hash_hex, sizeof(hash_hex)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (sizeof(hash_hex) - 1 != strlen (hash_hex))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s produced hash with wrong length. "
+             "Calculated length %u, expected digest %u.\n",
+             func_name,
+             (unsigned) strlen (hash_hex),
+             (unsigned) (sizeof(hash_hex) - 1));
+  }
+  else
+  {
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() produced wrong hash. "
+               "Calculated digest %s, expected digest %s.\n",
+               func_name,
+               hash_hex, expected_hex);
+    }
+  }
+
+  if (failed)
+  {
+    fprintf (stderr,
+             "The check failed for data located at line: %u.\n",
+             data->line_num);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    printf ("PASSED: check for data at line: %u.\n",
+            data->line_num);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+test_sha256 (void)
+{
+  unsigned int num_failed = 0;
+  size_t i;
+
+  for (i = 0; i < sizeof(sha256_tests) / sizeof(sha256_tests[0]); i++)
+    num_failed += check_sha256 (sha256_tests + i);
+  return num_failed;
+}
+
+
+static unsigned int
+test_sha256_failure (void)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256;
+  uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, sizeof(hash_bin) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256))
+  {
+    if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                                 "u", "r",
+                                                 hash_bin, sizeof(hash_bin)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, sizeof(hash_hex) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256))
+  {
+    if (MHD_NO !=
+        MHD_digest_auth_calc_userhash_hex (algo3,
+                                           "u", "r",
+                                           hash_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  if (! failed && verbose)
+  {
+    printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n",
+            (unsigned) __LINE__);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+check_sha512_256 (const struct data_sha512_256 *const data)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 =
+    MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+  uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1];
+  char expected_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_YES != MHD_digest_auth_calc_userhash (algo3,
+                                                data->username, data->realm,
+                                                hash_bin, sizeof(hash_bin)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash)))
+  {
+    failed++;
+    bin2hex (hash_bin, sizeof(hash_bin), hash_hex);
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    fprintf (stderr,
+             "FAILED: %s() produced wrong hash. "
+             "Calculated digest %s, expected digest %s.\n",
+             func_name,
+             hash_hex, expected_hex);
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_YES !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         data->username, data->realm,
+                                         hash_hex, sizeof(hash_hex)))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_YES.\n",
+             func_name);
+  }
+  else if (sizeof(hash_hex) - 1 != strlen (hash_hex))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s produced hash with wrong length. "
+             "Calculated length %u, expected digest %u.\n",
+             func_name,
+             (unsigned) strlen (hash_hex),
+             (unsigned) (sizeof(hash_hex) - 1));
+  }
+  else
+  {
+    bin2hex (data->hash, sizeof(data->hash), expected_hex);
+    if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() produced wrong hash. "
+               "Calculated digest %s, expected digest %s.\n",
+               func_name,
+               hash_hex, expected_hex);
+    }
+  }
+
+  if (failed)
+  {
+    fprintf (stderr,
+             "The check failed for data located at line: %u.\n",
+             data->line_num);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    printf ("PASSED: check for data at line: %u.\n",
+            data->line_num);
+  }
+  return failed ? 1 : 0;
+}
+
+
+static unsigned int
+test_sha512_256 (void)
+{
+  unsigned int num_failed = 0;
+  size_t i;
+
+  for (i = 0; i < sizeof(sha512_256_tests) / sizeof(sha512_256_tests[0]); i++)
+    num_failed += check_sha512_256 (sha512_256_tests + i);
+  return num_failed;
+}
+
+
+static unsigned int
+test_sha512_256_failure (void)
+{
+  static const enum MHD_DigestAuthAlgo3 algo3 =
+    MHD_DIGEST_AUTH_ALGO3_SHA512_256;
+  static const enum MHD_FEATURE feature = MHD_FEATURE_DIGEST_AUTH_SHA512_256;
+  uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE];
+  char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1];
+  const char *func_name;
+  unsigned int failed = 0;
+
+  func_name = "MHD_digest_auth_calc_userhash";
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, sizeof(hash_bin) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                               "u", "r",
+                                               hash_bin, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (feature))
+  {
+    if (MHD_NO != MHD_digest_auth_calc_userhash (algo3,
+                                                 "u", "r",
+                                                 hash_bin, sizeof(hash_bin)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  func_name = "MHD_digest_auth_calc_userhash_hex";
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, sizeof(hash_hex) - 1))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO !=
+      MHD_digest_auth_calc_userhash_hex (algo3,
+                                         "u", "r",
+                                         hash_hex, 0))
+  {
+    failed++;
+    fprintf (stderr,
+             "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+             func_name, (unsigned) __LINE__);
+  }
+  if (MHD_NO == MHD_is_feature_supported (feature))
+  {
+    if (MHD_NO !=
+        MHD_digest_auth_calc_userhash_hex (algo3,
+                                           "u", "r",
+                                           hash_hex, sizeof(hash_hex)))
+    {
+      failed++;
+      fprintf (stderr,
+               "FAILED: %s() has not returned MHD_NO at line: %u.\n",
+               func_name, (unsigned) __LINE__);
+    }
+  }
+
+  if (! failed && verbose)
+  {
+    printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n",
+            (unsigned) __LINE__);
+  }
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int num_failed = 0;
+  (void) has_in_name; /* Mute compiler warning. */
+  if (has_param (argc, argv, "-s") || has_param (argc, argv, "--silent"))
+    verbose = 0;
+
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+
+  if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5))
+    num_failed += test_md5 ();
+  num_failed += test_md5_failure ();
+  if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256))
+    num_failed += test_sha256 ();
+  num_failed += test_sha256_failure ();
+  if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA512_256))
+    num_failed += test_sha512_256 ();
+  num_failed += test_sha512_256_failure ();
+
+  return num_failed ? 1 : 0;
+}
diff --git a/src/microhttpd/test_helpers.h b/src/microhttpd/test_helpers.h
new file mode 100644
index 0000000..d3804bc
--- /dev/null
+++ b/src/microhttpd/test_helpers.h
@@ -0,0 +1,92 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_helpers.h
+ * @brief Static functions and macros helpers for testsuite.
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include <string.h>
+
+/**
+ * Check whether program name contains specific @a marker string.
+ * Only last component in pathname is checked for marker presence,
+ * all leading directories names (if any) are ignored. Directories
+ * separators are handled correctly on both non-W32 and W32
+ * platforms.
+ * @param prog_name program name, may include path
+ * @param marker    marker to look for.
+ * @return zero if any parameter is NULL or empty string or
+ *         @a prog_name ends with slash or @a marker is not found in
+ *         program name, non-zero if @a maker is found in program
+ *         name.
+ */
+static int
+has_in_name (const char *prog_name, const char *marker)
+{
+  size_t name_pos;
+  size_t pos;
+
+  if (! prog_name || ! marker || ! prog_name[0] || ! marker[0])
+    return 0;
+
+  pos = 0;
+  name_pos = 0;
+  while (prog_name[pos])
+  {
+    if ('/' == prog_name[pos])
+      name_pos = pos + 1;
+#if defined(_WIN32) || defined(__CYGWIN__)
+    else if ('\\' == prog_name[pos])
+      name_pos = pos + 1;
+#endif /* _WIN32 || __CYGWIN__ */
+    pos++;
+  }
+  if (name_pos == pos)
+    return 0;
+  return strstr (prog_name + name_pos, marker) != (char *) 0;
+}
+
+
+/**
+ * Check whether one of strings in array is equal to @a param.
+ * String @a argv[0] is ignored.
+ * @param argc number of strings in @a argv, as passed to main function
+ * @param argv array of strings, as passed to main function
+ * @param param parameter to look for.
+ * @return zero if @a argv is NULL, @a param is NULL or empty string,
+ *         @a argc is less then 2 or @a param is not found in @a argv,
+ *         non-zero if one of strings in @a argv is equal to @a param.
+ */
+static int
+has_param (int argc, char *const argv[], const char *param)
+{
+  int i;
+  if (! argv || ! param || ! param[0])
+    return 0;
+
+  for (i = 1; i < argc; i++)
+  {
+    if (argv[i] && (strcmp (argv[i], param) == 0) )
+      return ! 0;
+  }
+
+  return 0;
+}
diff --git a/src/microhttpd/test_http_reasons.c b/src/microhttpd/test_http_reasons.c
new file mode 100644
index 0000000..19bbcde
--- /dev/null
+++ b/src/microhttpd/test_http_reasons.c
@@ -0,0 +1,174 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017-2021 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_http_reasons.c
+ * @brief  Unit tests for MHD_get_reason_phrase_for() function
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <stdio.h>
+#include <string.h>
+#include "microhttpd.h"
+#include "mhd_str.h"
+
+static const char *const r_unknown = "unknown";
+
+/* Return zero when no error is detected */
+static int
+expect_result (unsigned int code, const char *expected)
+{
+  const char *const reason = MHD_get_reason_phrase_for (code);
+  const size_t len = MHD_get_reason_phrase_len_for (code);
+  size_t exp_len;
+  if (! MHD_str_equal_caseless_ (reason, expected))
+  {
+    fprintf (stderr,
+             "Incorrect reason returned for code %u:\n  Returned: \"%s\"  \tExpected: \"%s\"\n",
+             code, reason, expected);
+    return 1;
+  }
+  if (r_unknown == expected)
+    exp_len = 0;
+  else
+    exp_len = strlen (expected);
+  if (exp_len != len)
+  {
+    fprintf (stderr,
+             "Incorrect reason length returned for code %u:\n  Returned: \"%u\"  \tExpected: \"%u\"\n",
+             code, (unsigned) len, (unsigned) exp_len);
+    return 1;
+  }
+  return 0;
+}
+
+
+static int
+expect_absent (unsigned int code)
+{
+  return expect_result (code, r_unknown);
+}
+
+
+static int
+test_absent_codes (void)
+{
+  int errcount = 0;
+  errcount += expect_absent (0);
+  errcount += expect_absent (1);
+  errcount += expect_absent (50);
+  errcount += expect_absent (99);
+  errcount += expect_absent (600);
+  errcount += expect_absent (601);
+  errcount += expect_absent (900);
+  errcount += expect_absent (10000);
+  return errcount;
+}
+
+
+static int
+test_1xx (void)
+{
+  int errcount = 0;
+  errcount += expect_result (MHD_HTTP_CONTINUE, "continue");
+  errcount += expect_result (MHD_HTTP_PROCESSING, "processing");
+  errcount += expect_absent (110);
+  errcount += expect_absent (190);
+  return errcount;
+}
+
+
+static int
+test_2xx (void)
+{
+  int errcount = 0;
+  errcount += expect_result (MHD_HTTP_OK, "ok");
+  errcount += expect_result (MHD_HTTP_ALREADY_REPORTED, "already reported");
+  errcount += expect_absent (217);
+  errcount += expect_result (MHD_HTTP_IM_USED, "im used");
+  errcount += expect_absent (230);
+  errcount += expect_absent (295);
+  return errcount;
+}
+
+
+static int
+test_3xx (void)
+{
+  int errcount = 0;
+  errcount += expect_result (MHD_HTTP_MULTIPLE_CHOICES, "multiple choices");
+  errcount += expect_result (MHD_HTTP_SEE_OTHER, "see other");
+  errcount += expect_result (MHD_HTTP_PERMANENT_REDIRECT, "permanent redirect");
+  errcount += expect_absent (311);
+  errcount += expect_absent (399);
+  return errcount;
+}
+
+
+static int
+test_4xx (void)
+{
+  int errcount = 0;
+  errcount += expect_result (MHD_HTTP_BAD_REQUEST, "bad request");
+  errcount += expect_result (MHD_HTTP_NOT_FOUND, "not found");
+  errcount += expect_result (MHD_HTTP_URI_TOO_LONG, "uri too long");
+  errcount += expect_result (MHD_HTTP_EXPECTATION_FAILED, "expectation failed");
+  errcount += expect_result (MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,
+                             "request header fields too large");
+  errcount += expect_absent (441);
+  errcount += expect_result (MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS,
+                             "unavailable for legal reasons");
+  errcount += expect_absent (470);
+  errcount += expect_absent (493);
+  return errcount;
+}
+
+
+static int
+test_5xx (void)
+{
+  int errcount = 0;
+  errcount += expect_result (MHD_HTTP_INTERNAL_SERVER_ERROR,
+                             "internal server error");
+  errcount += expect_result (MHD_HTTP_BAD_GATEWAY, "bad gateway");
+  errcount += expect_result (MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED,
+                             "http version not supported");
+  errcount += expect_result (MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED,
+                             "network authentication required");
+  errcount += expect_absent (520);
+  errcount += expect_absent (597);
+  return errcount;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+
+  errcount += test_absent_codes ();
+  errcount += test_1xx ();
+  errcount += test_2xx ();
+  errcount += test_3xx ();
+  errcount += test_4xx ();
+  errcount += test_5xx ();
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_md5.c b/src/microhttpd/test_md5.c
new file mode 100644
index 0000000..e3bb0ce
--- /dev/null
+++ b/src/microhttpd/test_md5.c
@@ -0,0 +1,522 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2019-2023 Evgeny Grin (Karlson2k)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_md5.h
+ * @brief  Unit tests for md5 functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "mhd_md5_wrap.h"
+#include "test_helpers.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#if defined(MHD_MD5_TLSLIB) && defined(MHD_HTTPS_REQUIRE_GCRYPT)
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_MD5_TLSLIB && MHD_HTTPS_REQUIRE_GCRYPT */
+
+static int verbose = 0; /* verbose level (0-1)*/
+
+
+struct str_with_len
+{
+  const char *const str;
+  const size_t len;
+};
+
+#define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1}
+
+struct data_unit1
+{
+  const struct str_with_len str_l;
+  const uint8_t digest[MD5_DIGEST_SIZE];
+};
+
+static const struct data_unit1 data_units1[] = {
+  {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."),
+   {0x1c, 0x68, 0xc2, 0xe5, 0x1f, 0x63, 0xc9, 0x5f, 0x17, 0xab, 0x1f, 0x20,
+    0x8b, 0x86, 0x39, 0x57}},
+  {D_STR_W_LEN ("Simple string."),
+   {0xf1, 0x2b, 0x7c, 0xad, 0xa0, 0x41, 0xfe, 0xde, 0x4e, 0x68, 0x16, 0x63,
+    0xb4, 0x60, 0x5d, 0x78}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"),
+   {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c,
+    0xca, 0x67, 0xe1, 0x3b}},
+  {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"),
+   {0x05, 0x61, 0x3a, 0x6b, 0xde, 0x75, 0x3a, 0x45, 0x91, 0xa8, 0x81, 0xb0,
+    0xa7, 0xe2, 0xe2, 0x0e}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \
+                "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"),
+   {0xaf, 0xab, 0xc7, 0xe9, 0xe7, 0x17, 0xbe, 0xd6, 0xc0, 0x0f, 0x78, 0x8c,
+    0xde, 0xdd, 0x11, 0xd1}},
+  {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/path?with%20some=parameters"),
+   {0x7e, 0xe6, 0xdb, 0xe2, 0x76, 0x49, 0x1a, 0xd8, 0xaf, 0xf3, 0x52, 0x2d,
+    0xd8, 0xfc, 0x89, 0x1e}},
+  {D_STR_W_LEN (""),
+   {0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98,
+    0xec, 0xf8, 0x42, 0x7e}},
+  {D_STR_W_LEN ("a"),
+   {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 0x31, 0xc3, 0x99, 0xe2,
+    0x69, 0x77, 0x26, 0x61}},
+  {D_STR_W_LEN ("abc"),
+   {0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d,
+    0x28, 0xe1, 0x7f, 0x72}},
+  {D_STR_W_LEN ("message digest"),
+   {0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 0x52, 0x5a, 0x2f, 0x31,
+    0xaa, 0xf1, 0x61, 0xd0}},
+  {D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" \
+                "0123456789"),
+   {0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 0xa5, 0x61, 0x1c, 0x2c,
+    0x9f, 0x41, 0x9d, 0x9f}},
+  {D_STR_W_LEN ("12345678901234567890123456789012345678901234567890" \
+                "123456789012345678901234567890"),
+   {0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 0xac, 0x49, 0xda, 0x2e,
+    0x21, 0x07, 0xb6, 0x7a}}
+};
+
+static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]);
+
+struct bin_with_len
+{
+  const uint8_t bin[512];
+  const size_t len;
+};
+
+struct data_unit2
+{
+  const struct bin_with_len bin_l;
+  const uint8_t digest[MD5_DIGEST_SIZE];
+};
+
+static const struct data_unit2 data_units2[] = {
+  { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+       112, 113, 114, 115, 116,
+       117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */
+    {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c,
+     0xca, 0x67, 0xe1, 0x3b}},
+  { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65}, 72 },/* 'A' x 72 times */
+    {0x24, 0xa5, 0xef, 0x36, 0x82, 0x80, 0x3a, 0x06, 0x2f, 0xea, 0xad, 0xad,
+     0x76, 0xda, 0xbd, 0xa8}},
+  { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
+       37, 38, 39, 40, 41, 42,
+       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
+       61, 62, 63, 64, 65, 66, 67,
+       68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */
+    {0x6d, 0x2e, 0x6e, 0xde, 0x5d, 0x64, 0x6a, 0x17, 0xf1, 0x09, 0x2c, 0xac,
+     0x19, 0x10, 0xe3, 0xd6}},
+  { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+       26, 27, 28, 29, 30, 31,
+       32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
+       50, 51, 52, 53, 54, 55, 56,
+       57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */
+    {0x88, 0x13, 0x48, 0x47, 0x73, 0xaa, 0x92, 0xf2, 0xc9, 0xdd, 0x69, 0xb3,
+     0xac, 0xf4, 0xba, 0x6e}},
+  { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
+       56, 57, 58, 59, 60, 61,
+       62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+       80, 81, 82, 83, 84, 85, 86,
+       87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */
+    {0x80, 0xf0, 0x05, 0x7e, 0xa2, 0xf7, 0xc8, 0x43, 0x12, 0xd3, 0xb1, 0x61,
+     0xab, 0x52, 0x3b, 0xaf}},
+  { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26, 27,
+       28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
+       46, 47, 48, 49, 50, 51, 52,
+       53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
+       71, 72},
+      72},/* 1..72 sequence */
+    {0xc3, 0x28, 0xc5, 0xad, 0xc9, 0x26, 0xa9, 0x99, 0x95, 0x4a, 0x5e, 0x25,
+     0x50, 0x34, 0x51, 0x73}},
+  { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26,
+       27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
+       45, 46, 47, 48, 49, 50, 51,
+       52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
+       70, 71, 72, 73, 74, 75, 76,
+       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
+       95, 96, 97, 98, 99, 100,
+       101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
+       115, 116, 117, 118, 119, 120,
+       121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
+       135, 136, 137, 138, 139, 140,
+       141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
+       155, 156, 157, 158, 159, 160,
+       161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
+       175, 176, 177, 178, 179, 180,
+       181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
+       195, 196, 197, 198, 199, 200,
+       201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214,
+       215, 216, 217, 218, 219, 220,
+       221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
+       235, 236, 237, 238, 239, 240,
+       241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
+       255}, 256},                                                                        /* 0..255 sequence */
+    {0xe2, 0xc8, 0x65, 0xdb, 0x41, 0x62, 0xbe, 0xd9, 0x63, 0xbf, 0xaa, 0x9e,
+     0xf6, 0xac, 0x18, 0xf0}},
+  { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,
+       185, 184, 183, 182, 181, 180,
+       179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166,
+       165, 164, 163, 162, 161, 160,
+       159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146,
+       145, 144, 143, 142, 141, 140,
+       139}, 61},  /* 199..139 sequence */
+    {0xbb, 0x3f, 0xdb, 0x4a, 0x96, 0x03, 0x36, 0x37, 0x38, 0x78, 0x5e, 0x44,
+     0xbf, 0x3a, 0x85, 0x51}},
+  { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242,
+       241, 240, 239, 238, 237, 236,
+       235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222,
+       221, 220, 219, 218, 217, 216,
+       215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202,
+       201, 200, 199, 198, 197, 196,
+       195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182,
+       181, 180, 179, 178, 177, 176,
+       175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162,
+       161, 160, 159, 158, 157, 156,
+       155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142,
+       141, 140, 139, 138, 137, 136,
+       135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122,
+       121, 120, 119, 118, 117, 116,
+       115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102,
+       101, 100, 99, 98, 97, 96, 95,
+       94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77,
+       76, 75, 74, 73, 72, 71, 70,
+       69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52,
+       51, 50, 49, 48, 47, 46, 45,
+       44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27,
+       26, 25, 24, 23, 22, 21, 20,
+       19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255},  /* 255..1 sequence */
+    {0x52, 0x21, 0xa5, 0x83, 0x4f, 0x38, 0x7c, 0x73, 0xba, 0x18, 0x22, 0xb1,
+     0xf9, 0x7e, 0xae, 0x8b}},
+  { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233,
+       235, 179, 166, 219, 60, 135,
+       12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187,
+       139, 166, 31, 3, 90, 125, 9,
+       56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28,
+       219, 174, 50, 32, 154, 80, 238,
+       64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242,
+       68, 64, 102, 208, 107, 196,
+       48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202,
+       153, 2, 185, 114, 157, 73,
+       44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103,
+       214, 191, 20, 214, 126, 45,
+       220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30,
+       157, 156, 22, 114, 114, 230,
+       29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51,
+       116, 158, 12, 244, 213,
+       212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144,
+       45, 72, 211, 143, 117, 230,
+       217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212,
+       97, 141, 190, 123, 5, 21, 7,
+       59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21,
+       248, 70, 106, 4, 150, 115,
+       14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255},  /* pseudo-random data */
+    {0x55, 0x61, 0x2c, 0xeb, 0x29, 0xee, 0xa8, 0xb2, 0xf6, 0x10, 0x7b, 0xc1,
+     0x5b, 0x0f, 0x01, 0x95}}
+};
+
+static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]);
+
+
+/*
+ *  Helper functions
+ */
+
+/**
+ * Print bin as hex
+ *
+ * @param bin binary data
+ * @param len number of bytes in bin
+ * @param hex pointer to len*2+1 bytes buffer
+ */
+static void
+bin2hex (const uint8_t *bin,
+         size_t len,
+         char *hex)
+{
+  while (len-- > 0)
+  {
+    unsigned int b1, b2;
+    b1 = (*bin >> 4) & 0xf;
+    *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0'));
+    b2 = *bin++ & 0xf;
+    *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0'));
+  }
+  *hex = 0;
+}
+
+
+static int
+check_result (const char *test_name,
+              unsigned int check_num,
+              const uint8_t calculated[MD5_DIGEST_SIZE],
+              const uint8_t expected[MD5_DIGEST_SIZE])
+{
+  int failed = memcmp (calculated, expected, MD5_DIGEST_SIZE);
+  check_num++; /* Print 1-based numbers */
+  if (failed)
+  {
+    char calc_str[MD5_DIGEST_STRING_SIZE];
+    char expc_str[MD5_DIGEST_STRING_SIZE];
+    bin2hex (calculated, MD5_DIGEST_SIZE, calc_str);
+    bin2hex (expected, MD5_DIGEST_SIZE, expc_str);
+    fprintf (stderr,
+             "FAILED: %s check %u: calculated digest %s, expected digest %s.\n",
+             test_name, check_num, calc_str, expc_str);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    char calc_str[MD5_DIGEST_STRING_SIZE];
+    bin2hex (calculated, MD5_DIGEST_SIZE, calc_str);
+    printf ("PASSED: %s check %u: calculated digest %s "
+            "matches expected digest.\n",
+            test_name, check_num, calc_str);
+    fflush (stdout);
+  }
+  return failed ? 1 : 0;
+}
+
+
+/*
+ *  Tests
+ */
+
+/* Calculated MD5 as one pass for whole data */
+static int
+test1_str (void)
+{
+  unsigned int i;
+  int num_failed = 0;
+  struct Md5CtxWr ctx;
+
+  MHD_MD5_init_one_time (&ctx);
+
+  for (i = 0; i < units1_num; i++)
+  {
+    uint8_t digest[MD5_DIGEST_SIZE];
+
+    MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str,
+                    data_units1[i].str_l.len);
+    MHD_MD5_finish_reset (&ctx, digest);
+#ifdef MHD_MD5_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units1[i].digest);
+  }
+  MHD_MD5_deinit (&ctx);
+  return num_failed;
+}
+
+
+static int
+test1_bin (void)
+{
+  unsigned int i;
+  int num_failed = 0;
+  struct Md5CtxWr ctx;
+
+  MHD_MD5_init_one_time (&ctx);
+
+  for (i = 0; i < units2_num; i++)
+  {
+    uint8_t digest[MD5_DIGEST_SIZE];
+
+    MHD_MD5_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len);
+    MHD_MD5_finish_reset (&ctx, digest);
+#ifdef MHD_MD5_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units2[i].digest);
+  }
+  MHD_MD5_deinit (&ctx);
+  return num_failed;
+}
+
+
+/* Calculated MD5 as two iterations for whole data */
+static int
+test2_str (void)
+{
+  unsigned int i;
+  int num_failed = 0;
+  struct Md5CtxWr ctx;
+
+  MHD_MD5_init_one_time (&ctx);
+
+  for (i = 0; i < units1_num; i++)
+  {
+    uint8_t digest[MD5_DIGEST_SIZE];
+    size_t part_s = data_units1[i].str_l.len / 4;
+
+    MHD_MD5_update (&ctx, (const uint8_t *) "", 0);
+    MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s);
+    MHD_MD5_update (&ctx, (const uint8_t *) "", 0);
+    MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s,
+                    data_units1[i].str_l.len - part_s);
+    MHD_MD5_update (&ctx, (const uint8_t *) "", 0);
+    MHD_MD5_finish_reset (&ctx, digest);
+#ifdef MHD_MD5_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units1[i].digest);
+  }
+  MHD_MD5_deinit (&ctx);
+  return num_failed;
+}
+
+
+static int
+test2_bin (void)
+{
+  unsigned int i;
+  int num_failed = 0;
+  struct Md5CtxWr ctx;
+
+  MHD_MD5_init_one_time (&ctx);
+
+  for (i = 0; i < units2_num; i++)
+  {
+    uint8_t digest[MD5_DIGEST_SIZE];
+    size_t part_s = data_units2[i].bin_l.len * 2 / 3;
+
+    MHD_MD5_update (&ctx, data_units2[i].bin_l.bin, part_s);
+    MHD_MD5_update (&ctx, (const uint8_t *) "", 0);
+    MHD_MD5_update (&ctx, data_units2[i].bin_l.bin + part_s,
+                    data_units2[i].bin_l.len - part_s);
+    MHD_MD5_finish_reset (&ctx, digest);
+#ifdef MHD_MD5_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units2[i].digest);
+  }
+  MHD_MD5_deinit (&ctx);
+  return num_failed;
+}
+
+
+/* Use data set number 7 as it has the longest sequence */
+#define DATA_POS 6
+#define MAX_OFFSET 31
+
+static int
+test_unaligned (void)
+{
+  int num_failed = 0;
+  unsigned int offset;
+  uint8_t *buf;
+  uint8_t *digest_buf;
+  struct Md5CtxWr ctx;
+
+  const struct data_unit2 *const tdata = data_units2 + DATA_POS;
+
+  buf = malloc (tdata->bin_l.len + MAX_OFFSET);
+  digest_buf = malloc (MD5_DIGEST_SIZE + MAX_OFFSET);
+  if ((NULL == buf) || (NULL == digest_buf))
+    exit (99);
+
+  MHD_MD5_init_one_time (&ctx);
+
+  for (offset = MAX_OFFSET; offset >= 1; --offset)
+  {
+    uint8_t *unaligned_digest;
+    uint8_t *unaligned_buf;
+
+    unaligned_buf = buf + offset;
+    memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len);
+    unaligned_digest = digest_buf + MAX_OFFSET - offset;
+    memset (unaligned_digest, 0, MD5_DIGEST_SIZE);
+
+    MHD_MD5_update (&ctx, unaligned_buf, tdata->bin_l.len);
+    MHD_MD5_finish_reset (&ctx, unaligned_digest);
+#ifdef MHD_MD5_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif
+    num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset,
+                                unaligned_digest, tdata->digest);
+  }
+  MHD_MD5_deinit (&ctx);
+  free (digest_buf);
+  free (buf);
+  return num_failed;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int num_failed = 0;
+  (void) has_in_name; /* Mute compiler warning. */
+  if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose"))
+    verbose = 1;
+
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+
+  num_failed += test1_str ();
+  num_failed += test1_bin ();
+
+  num_failed += test2_str ();
+  num_failed += test2_bin ();
+
+  num_failed += test_unaligned ();
+
+  return num_failed ? 1 : 0;
+}
diff --git a/src/testcurl/test_options.c b/src/microhttpd/test_options.c
similarity index 66%
rename from src/testcurl/test_options.c
rename to src/microhttpd/test_options.c
index 4afe3d4..deff9b9 100644
--- a/src/testcurl/test_options.c
+++ b/src/microhttpd/test_options.c
@@ -14,53 +14,57 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
- * @file mhds_get_test.c
+ * @file test_options.c
  * @brief  Testcase for libmicrohttpd HTTPS GET operations
  * @author Sagie Amir
  */
 
 #include "platform.h"
 #include "microhttpd.h"
+#include "mhd_sockets.h"
 
-#define MHD_E_MEM "Error: memory error\n"
-#define MHD_E_SERVER_INIT "Error: failed to start server\n"
-
-const int DEBUG_GNUTLS_LOG_LEVEL = 0;
-const char *test_file_name = "https_test_file";
-const char test_file_data[] = "Hello World\n";
-
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
+  (void) cls;
+  (void) connection;
+  (void) url;
+  (void) method;
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;
+  (void) req_cls;
+
   return 0;
 }
 
-int
-test_wrap (char *test_name, int (*test) (void))
+
+static unsigned int
+test_wrap_loc (const char *test_name, unsigned int (*test)(void))
 {
-  int ret;
+  unsigned int ret;
 
   fprintf (stdout, "running test: %s ", test_name);
   ret = test ();
   if (ret == 0)
-    {
-      fprintf (stdout, "[pass]\n");
-    }
+  {
+    fprintf (stdout, "[pass]\n");
+  }
   else
-    {
-      fprintf (stdout, "[fail]\n");
-    }
+  {
+    fprintf (stdout, "[fail]\n");
+  }
   return ret;
 }
 
@@ -68,43 +72,43 @@
 /**
  * Test daemon initialization with the MHD_OPTION_SOCK_ADDR option
  */
-static int
-test_ip_addr_option ()
+static unsigned int
+test_ip_addr_option (void)
 {
   struct MHD_Daemon *d;
   struct sockaddr_in daemon_ip_addr;
-#if HAVE_INET6
+#if defined(HAVE_INET6) && defined(USE_IPV6_TESTING)
   struct sockaddr_in6 daemon_ip_addr6;
 #endif
 
   memset (&daemon_ip_addr, 0, sizeof (struct sockaddr_in));
   daemon_ip_addr.sin_family = AF_INET;
-  daemon_ip_addr.sin_port = htons (4233);
+  daemon_ip_addr.sin_port = 0;
   daemon_ip_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
 
-#if HAVE_INET6
+#if defined(HAVE_INET6) && defined(USE_IPV6_TESTING)
   memset (&daemon_ip_addr6, 0, sizeof (struct sockaddr_in6));
   daemon_ip_addr6.sin6_family = AF_INET6;
-  daemon_ip_addr6.sin6_port = htons (4233);
+  daemon_ip_addr6.sin6_port = 0;
   daemon_ip_addr6.sin6_addr = in6addr_loopback;
 #endif
 
-  d = MHD_start_daemon (MHD_USE_DEBUG, 4233,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0,
                         NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR,
                         &daemon_ip_addr, MHD_OPTION_END);
 
   if (d == 0)
-    return -1;
+    return 1;
 
   MHD_stop_daemon (d);
 
-#if HAVE_INET6
-  d = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_IPv6, 4233,
+#if defined(HAVE_INET6) && defined(USE_IPV6_TESTING)
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_IPv6, 0,
                         NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR,
                         &daemon_ip_addr6, MHD_OPTION_END);
 
   if (d == 0)
-    return -1;
+    return 1;
 
   MHD_stop_daemon (d);
 #endif
@@ -112,13 +116,15 @@
   return 0;
 }
 
+
 /* setup a temporary transfer test file */
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
-  errorCount += test_wrap ("ip addr option", &test_ip_addr_option);
+  errorCount += test_wrap_loc ("ip addr option", &test_ip_addr_option);
 
   return errorCount != 0;
 }
diff --git a/src/microhttpd/test_postprocessor.c b/src/microhttpd/test_postprocessor.c
index 66bab81..f7a88f1 100644
--- a/src/microhttpd/test_postprocessor.c
+++ b/src/microhttpd/test_postprocessor.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007,2013 Christian Grothoff
+     Copyright (C) 2007, 2013, 2019, 2020 Christian Grothoff
+     Copyright (C) 2021 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,61 +15,112 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
-
 /**
  * @file test_postprocessor.c
  * @brief  Testcase for postprocessor
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
-
 #include "platform.h"
 #include "microhttpd.h"
 #include "internal.h"
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
+#include "mhd_compat.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
 #endif
 
+#ifndef MHD_DEBUG_PP
+#define MHD_DEBUG_PP 0
+#endif /* MHD_DEBUG_PP */
+
+struct expResult
+{
+  const char *key;
+  const char *fname;
+  const char *cnt_type;
+  const char *tr_enc;
+  const char *data;
+};
+
 /**
  * Array of values that the value checker "wants".
  * Each series of checks should be terminated by
  * five NULL-entries.
  */
-const char *want[] = {
+static struct expResult exp_results[] = {
+#define URL_NOVALUE1_DATA "abc&x=5"
+#define URL_NOVALUE1_START 0
+  {"abc", NULL, NULL, NULL, /* NULL */ ""}, /* change after API update */
+  {"x", NULL, NULL, NULL, "5"},
+#define URL_NOVALUE1_END (URL_NOVALUE1_START + 2)
+#define URL_NOVALUE2_DATA "abc=&x=5"
+#define URL_NOVALUE2_START URL_NOVALUE1_END
+  {"abc", NULL, NULL, NULL, ""},
+  {"x", NULL, NULL, NULL, "5"},
+#define URL_NOVALUE2_END (URL_NOVALUE2_START + 2)
+#define URL_NOVALUE3_DATA "xyz="
+#define URL_NOVALUE3_START URL_NOVALUE2_END
+  {"xyz", NULL, NULL, NULL, ""},
+#define URL_NOVALUE3_END (URL_NOVALUE3_START + 1)
+#define URL_NOVALUE4_DATA "xyz"
+#define URL_NOVALUE4_START URL_NOVALUE3_END
+  {"xyz", NULL, NULL, NULL, /* NULL */ ""}, /* change after API update */
+#define URL_NOVALUE4_END (URL_NOVALUE4_START + 1)
 #define URL_DATA "abc=def&x=5"
-#define URL_START 0
-  "abc", NULL, NULL, NULL, "def",
-  "x", NULL, NULL, NULL, "5",
-#define URL_END (URL_START + 10)
-  NULL, NULL, NULL, NULL, NULL,
-#define FORM_DATA "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\nJoe Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\"; filename=\"file1.txt\"\r\nContent-Type: text/plain\r\nContent-Transfer-Encoding: binary\r\n\r\nfiledata\r\n--AaB03x--\r\n"
-#define FORM_START (URL_END + 5)
-  "field1", NULL, NULL, NULL, "Joe Blow",
-  "pics", "file1.txt", "text/plain", "binary", "filedata",
-#define FORM_END (FORM_START + 10)
-  NULL, NULL, NULL, NULL, NULL,
-#define FORM_NESTED_DATA "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\nJane Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\"\r\nContent-type: multipart/mixed, boundary=BbC04y\r\n\r\n--BbC04y\r\nContent-disposition: attachment; filename=\"file1.txt\"\r\nContent-Type: text/plain\r\n\r\nfiledata1\r\n--BbC04y\r\nContent-disposition: attachment; filename=\"file2.gif\"\r\nContent-type: image/gif\r\nContent-Transfer-Encoding: binary\r\n\r\nfiledata2\r\n--BbC04y--\r\n--AaB03x--"
-#define FORM_NESTED_START (FORM_END + 5)
-  "field1", NULL, NULL, NULL, "Jane Blow",
-  "pics", "file1.txt", "text/plain", NULL, "filedata1",
-  "pics", "file2.gif", "image/gif", "binary", "filedata2",
-#define FORM_NESTED_END (FORM_NESTED_START + 15)
-  NULL, NULL, NULL, NULL, NULL,
+#define URL_START URL_NOVALUE4_END
+  {"abc", NULL, NULL, NULL, "def"},
+  {"x", NULL, NULL, NULL, "5"},
+#define URL_END (URL_START + 2)
+#define URL_ENC_DATA "space=%20&key%201=&crlf=%0D%0a&mix%09ed=%2001%0d%0A"
+#define URL_ENC_START URL_END
+  {"space", NULL, NULL, NULL, " "},
+  {"key 1", NULL, NULL, NULL, ""},
+  {"crlf", NULL, NULL, NULL, "\r\n"},
+  {"mix\ted", NULL, NULL, NULL, " 01\r\n"},
+#define URL_ENC_END (URL_ENC_START + 4)
+  {NULL, NULL, NULL, NULL, NULL},
+#define FORM_DATA \
+  "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\n" \
+  "Joe Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\";" \
+  " filename=\"file1.txt\"\r\nContent-Type: text/plain\r\n" \
+  "Content-Transfer-Encoding: binary\r\n\r\nfiledata\r\n--AaB03x--\r\n"
+#define FORM_START (URL_ENC_END + 1)
+  {"field1", NULL, NULL, NULL, "Joe Blow"},
+  {"pics", "file1.txt", "text/plain", "binary", "filedata"},
+#define FORM_END (FORM_START + 2)
+  {NULL, NULL, NULL, NULL, NULL},
+#define FORM_NESTED_DATA \
+  "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\n" \
+  "Jane Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\"\r\n" \
+  "Content-type: multipart/mixed, boundary=BbC04y\r\n\r\n--BbC04y\r\n" \
+  "Content-disposition: attachment; filename=\"file1.txt\"\r\n" \
+  "Content-Type: text/plain\r\n\r\nfiledata1\r\n--BbC04y\r\n" \
+  "Content-disposition: attachment; filename=\"file2.gif\"\r\n" \
+  "Content-type: image/gif\r\nContent-Transfer-Encoding: binary\r\n\r\n" \
+  "filedata2\r\n--BbC04y--\r\n--AaB03x--"
+#define FORM_NESTED_START (FORM_END + 1)
+  {"field1", NULL, NULL, NULL, "Jane Blow"},
+  {"pics", "file1.txt", "text/plain", NULL, "filedata1"},
+  {"pics", "file2.gif", "image/gif", "binary", "filedata2"},
+#define FORM_NESTED_END (FORM_NESTED_START + 3)
+  {NULL, NULL, NULL, NULL, NULL},
 #define URL_EMPTY_VALUE_DATA "key1=value1&key2=&key3="
-#define URL_EMPTY_VALUE_START (FORM_NESTED_END + 5)
-  "key1", NULL, NULL, NULL, "value1",
-  "key2", NULL, NULL, NULL, "",
-  "key3", NULL, NULL, NULL, "",
-#define URL_EMPTY_VALUE_END (URL_EMPTY_VALUE_START + 15)
-  NULL, NULL, NULL, NULL, NULL
+#define URL_EMPTY_VALUE_START (FORM_NESTED_END + 1)
+  {"key1", NULL, NULL, NULL, "value1"},
+  {"key2", NULL, NULL, NULL, ""},
+  {"key3", NULL, NULL, NULL, ""},
+#define URL_EMPTY_VALUE_END (URL_EMPTY_VALUE_START + 3)
+  {NULL, NULL, NULL, NULL, NULL}
 };
 
+
 static int
 mismatch (const char *a, const char *b)
 {
@@ -79,89 +131,252 @@
   return 0 != strcmp (a, b);
 }
 
+
 static int
+mismatch2 (const char *data, const char *expected, size_t offset, size_t size)
+{
+  if (data == expected)
+    return 0;
+  if ((data == NULL) || (expected == NULL))
+    return 1;
+  return 0 != memcmp (data, expected + offset, size);
+}
+
+
+static enum MHD_Result
 value_checker (void *cls,
                enum MHD_ValueKind kind,
                const char *key,
                const char *filename,
                const char *content_type,
                const char *transfer_encoding,
-               const char *data, uint64_t off, size_t size)
+               const char *data,
+               uint64_t off,
+               size_t size)
 {
-  int *want_off = cls;
-  int idx = *want_off;
+  unsigned int *idxp = cls;
+  struct expResult *expect = exp_results + *idxp;
+  (void) kind;  /* Unused. Silent compiler warning. */
 
-#if 0
+#if MHD_DEBUG_PP
   fprintf (stderr,
-           "VC: `%s' `%s' `%s' `%s' `%.*s'\n",
-           key, filename, content_type, transfer_encoding,
-           (int) size,
-           data);
+           "VC: `%s' `%s' `%s' `%s' (+%u)`%.*s' (%d)\n",
+           key ? key : "(NULL)",
+           filename ? filename : "(NULL)",
+           content_type ? content_type : "(NULL)",
+           transfer_encoding ? transfer_encoding : "(NULL)",
+           (unsigned int) off,
+           (int) (data ? size : 6),
+           data ? data : "(NULL)",
+           (int) size);
 #endif
+  if (*idxp == (unsigned int) -1)
+    exit (99);
   if ( (0 != off) && (0 == size) )
+  {
+    if (NULL == expect->data)
+      *idxp += 1;
     return MHD_YES;
-  if ((idx < 0) ||
-      (want[idx] == NULL) ||
-      (0 != strcmp (key, want[idx])) ||
-      (mismatch (filename, want[idx + 1])) ||
-      (mismatch (content_type, want[idx + 2])) ||
-      (mismatch (transfer_encoding, want[idx + 3])) ||
-      (0 != memcmp (data, &want[idx + 4][off], size)))
-    {
-      *want_off = -1;
-      return MHD_NO;
-    }
-  if (off + size == strlen (want[idx + 4]))
-    *want_off = idx + 5;
+  }
+  if ((expect->key == NULL) ||
+      (0 != strcmp (key, expect->key)) ||
+      (mismatch (filename, expect->fname)) ||
+      (mismatch (content_type, expect->cnt_type)) ||
+      (mismatch (transfer_encoding, expect->tr_enc)) ||
+      (mismatch2 (data, expect->data, off, size)))
+  {
+    *idxp = (unsigned int) -1;
+    fprintf (stderr,
+             "Failed with: `%s' `%s' `%s' `%s' `%.*s'\n",
+             key ? key : "(NULL)",
+             filename ? filename : "(NULL)",
+             content_type ? content_type : "(NULL)",
+             transfer_encoding ? transfer_encoding : "(NULL)",
+             (int) (data ? size : 6),
+             data ? data : "(NULL)");
+    fprintf (stderr,
+             "Wanted: `%s' `%s' `%s' `%s' `%s'\n",
+             expect->key ? expect->key : "(NULL)",
+             expect->fname ? expect->fname : "(NULL)",
+             expect->cnt_type ? expect->cnt_type : "(NULL)",
+             expect->tr_enc ? expect->tr_enc : "(NULL)",
+             expect->data ? expect->data : "(NULL)");
+    fprintf (stderr,
+             "Unexpected result: %d/%d/%d/%d/%d/%d\n",
+             (expect->key == NULL),
+             (NULL != expect->key) && (0 != strcmp (key, expect->key)),
+             (mismatch (filename, expect->fname)),
+             (mismatch (content_type, expect->cnt_type)),
+             (mismatch (transfer_encoding, expect->tr_enc)),
+             (mismatch2 (data, expect->data, off, size)));
+    return MHD_NO;
+  }
+  if ( ( (NULL == expect->data) &&
+         (0 == off + size) ) ||
+       ( (NULL != expect->data) &&
+         (off + size == strlen (expect->data)) ) )
+    *idxp += 1;
   return MHD_YES;
-
 }
 
 
-static int
-test_urlencoding ()
+static unsigned int
+test_urlencoding_case (unsigned int want_start,
+                       unsigned int want_end,
+                       const char *url_data)
 {
-  struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
-  struct MHD_PostProcessor *pp;
-  unsigned int want_off = URL_START;
-  int i;
-  int delta;
-  size_t size;
+  size_t step;
+  unsigned int errors = 0;
+  const size_t size = strlen (url_data);
 
-  memset (&connection, 0, sizeof (struct MHD_Connection));
-  memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-  connection.headers_received = &header;
-  header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
-  header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
-  header.kind = MHD_HEADER_KIND;
-  pp = MHD_create_post_processor (&connection,
-                                  1024, &value_checker, &want_off);
-  i = 0;
-  size = strlen (URL_DATA);
-  while (i < size)
+  for (step = 1; size >= step; ++step)
+  {
+    struct MHD_Connection connection;
+    struct MHD_HTTP_Req_Header header;
+    struct MHD_PostProcessor *pp;
+    unsigned int want_off = want_start;
+    size_t i;
+
+    memset (&connection, 0, sizeof (struct MHD_Connection));
+    memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+    connection.rq.headers_received = &header;
+    header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
+    header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE);
+    header.value_size =
+      MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED);
+    header.kind = MHD_HEADER_KIND;
+    pp = MHD_create_post_processor (&connection,
+                                    1024,
+                                    &value_checker,
+                                    &want_off);
+    if (NULL == pp)
     {
-      delta = 1 + MHD_random_ () % (size - i);
-      MHD_post_process (pp, &URL_DATA[i], delta);
-      i += delta;
+      fprintf (stderr, "Failed to create post processor.\n"
+               "Line: %u\n", (unsigned int) __LINE__);
+      exit (50);
     }
-  MHD_destroy_post_processor (pp);
-  if (want_off != URL_END)
-    return 1;
-  return 0;
+    for (i = 0; size > i; i += step)
+    {
+      size_t left = size - i;
+      if (MHD_YES != MHD_post_process (pp,
+                                       &url_data[i],
+                                       (left > step) ? step : left))
+      {
+        fprintf (stderr, "Failed to process the data.\n"
+                 "i: %u. step: %u.\n"
+                 "Line: %u\n", (unsigned) i, (unsigned) step,
+                 (unsigned int) __LINE__);
+        exit (49);
+      }
+    }
+    MHD_destroy_post_processor (pp);
+    if (want_off != want_end)
+    {
+      fprintf (stderr,
+               "Test failed in line %u.\tStep: %u.\tData: \"%s\"\n" \
+               " Got: %u\tExpected: %u\n",
+               (unsigned int) __LINE__,
+               (unsigned int) step,
+               url_data,
+               want_off,
+               want_end);
+      errors++;
+    }
+  }
+  return errors;
 }
 
 
-static int
-test_multipart_garbage ()
+static unsigned int
+test_urlencoding (void)
+{
+  unsigned int errorCount = 0;
+
+  errorCount += test_urlencoding_case (URL_START,
+                                       URL_END,
+                                       URL_DATA);
+  errorCount += test_urlencoding_case (URL_ENC_START,
+                                       URL_ENC_END,
+                                       URL_ENC_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE1_START,
+                                       URL_NOVALUE1_END,
+                                       URL_NOVALUE1_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE2_START,
+                                       URL_NOVALUE2_END,
+                                       URL_NOVALUE2_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE3_START,
+                                       URL_NOVALUE3_END,
+                                       URL_NOVALUE3_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE4_START,
+                                       URL_NOVALUE4_START, /* No advance */
+                                       URL_NOVALUE4_DATA);
+  errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START,
+                                       URL_EMPTY_VALUE_END,
+                                       URL_EMPTY_VALUE_DATA);
+
+  errorCount += test_urlencoding_case (URL_START,
+                                       URL_END,
+                                       URL_DATA "\n");
+  errorCount += test_urlencoding_case (URL_ENC_START,
+                                       URL_ENC_END,
+                                       URL_ENC_DATA "\n");
+  errorCount += test_urlencoding_case (URL_NOVALUE1_START,
+                                       URL_NOVALUE1_END,
+                                       URL_NOVALUE1_DATA "\n");
+  errorCount += test_urlencoding_case (URL_NOVALUE2_START,
+                                       URL_NOVALUE2_END,
+                                       URL_NOVALUE2_DATA "\n");
+  errorCount += test_urlencoding_case (URL_NOVALUE3_START,
+                                       URL_NOVALUE3_END,
+                                       URL_NOVALUE3_DATA "\n");
+  errorCount += test_urlencoding_case (URL_NOVALUE4_START,
+                                       URL_NOVALUE4_END, /* With advance */
+                                       URL_NOVALUE4_DATA "\n");
+  errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START,
+                                       URL_EMPTY_VALUE_END,
+                                       URL_EMPTY_VALUE_DATA "\n");
+
+  errorCount += test_urlencoding_case (URL_START,
+                                       URL_END,
+                                       "&&" URL_DATA);
+  errorCount += test_urlencoding_case (URL_ENC_START,
+                                       URL_ENC_END,
+                                       "&&" URL_ENC_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE1_START,
+                                       URL_NOVALUE1_END,
+                                       "&&" URL_NOVALUE1_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE2_START,
+                                       URL_NOVALUE2_END,
+                                       "&&" URL_NOVALUE2_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE3_START,
+                                       URL_NOVALUE3_END,
+                                       "&&" URL_NOVALUE3_DATA);
+  errorCount += test_urlencoding_case (URL_NOVALUE4_START,
+                                       URL_NOVALUE4_START, /* No advance */
+                                       "&&" URL_NOVALUE4_DATA);
+  errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START,
+                                       URL_EMPTY_VALUE_END,
+                                       "&&" URL_EMPTY_VALUE_DATA);
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Test failed in line %u with %u errors\n",
+             (unsigned int) __LINE__,
+             errorCount);
+  return errorCount;
+}
+
+
+static unsigned int
+test_multipart_garbage (void)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
   unsigned int want_off;
-  size_t size = strlen (FORM_DATA);
+  size_t size = MHD_STATICSTR_LEN_ (FORM_DATA);
   size_t splitpoint;
-  char xdata[size + 3];
+  char xdata[MHD_STATICSTR_LEN_ (FORM_DATA) + 3];
 
   /* fill in evil garbage at the beginning */
   xdata[0] = '-';
@@ -169,35 +384,63 @@
   xdata[2] = '\r';
   memcpy (&xdata[3], FORM_DATA, size);
   size += 3;
-
-  size = strlen (FORM_DATA);
   for (splitpoint = 1; splitpoint < size; splitpoint++)
   {
     want_off = FORM_START;
     memset (&connection, 0, sizeof (struct MHD_Connection));
-    memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-    connection.headers_received = &header;
+    memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+    connection.rq.headers_received = &header;
     header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
     header.value =
       MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x";
+    header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE);
+    header.value_size =
+      MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA \
+                          ", boundary=AaB03x");
     header.kind = MHD_HEADER_KIND;
     pp = MHD_create_post_processor (&connection,
                                     1024, &value_checker, &want_off);
-    MHD_post_process (pp, xdata, splitpoint);
-    MHD_post_process (pp, &xdata[splitpoint], size - splitpoint);
+    if (NULL == pp)
+    {
+      fprintf (stderr, "Failed to create post processor.\n"
+               "Line: %u\n", (unsigned int) __LINE__);
+      exit (50);
+    }
+    if (MHD_YES != MHD_post_process (pp, xdata, splitpoint))
+    {
+      fprintf (stderr,
+               "Test failed in line %u at point %d\n",
+               (unsigned int) __LINE__,
+               (int) splitpoint);
+      exit (49);
+    }
+    if (MHD_YES != MHD_post_process (pp, &xdata[splitpoint], size - splitpoint))
+    {
+      fprintf (stderr,
+               "Test failed in line %u at point %u\n",
+               (unsigned int) __LINE__,
+               (unsigned int) splitpoint);
+      exit (49);
+    }
     MHD_destroy_post_processor (pp);
     if (want_off != FORM_END)
-      return (int) splitpoint;
+    {
+      fprintf (stderr,
+               "Test failed in line %u at point %u\n",
+               (unsigned int) __LINE__,
+               (unsigned int) splitpoint);
+      return (unsigned int) splitpoint;
+    }
   }
   return 0;
 }
 
 
-static int
-test_multipart_splits ()
+static unsigned int
+test_multipart_splits (void)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
   unsigned int want_off;
   size_t size;
@@ -208,142 +451,387 @@
   {
     want_off = FORM_START;
     memset (&connection, 0, sizeof (struct MHD_Connection));
-    memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-    connection.headers_received = &header;
+    memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+    connection.rq.headers_received = &header;
     header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
     header.value =
       MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x";
+    header.header_size = strlen (header.header);
+    header.value_size = strlen (header.value);
     header.kind = MHD_HEADER_KIND;
     pp = MHD_create_post_processor (&connection,
                                     1024, &value_checker, &want_off);
-    MHD_post_process (pp, FORM_DATA, splitpoint);
-    MHD_post_process (pp, &FORM_DATA[splitpoint], size - splitpoint);
+    if (NULL == pp)
+    {
+      fprintf (stderr, "Failed to create post processor.\n"
+               "Line: %u\n", (unsigned int) __LINE__);
+      exit (50);
+    }
+    if (MHD_YES != MHD_post_process (pp, FORM_DATA, splitpoint))
+    {
+      fprintf (stderr,
+               "Test failed in line %u at point %d\n",
+               (unsigned int) __LINE__,
+               (int) splitpoint);
+      exit (49);
+    }
+    if (MHD_YES != MHD_post_process (pp, &FORM_DATA[splitpoint],
+                                     size - splitpoint))
+    {
+      fprintf (stderr,
+               "Test failed in line %u at point %u\n",
+               (unsigned int) __LINE__,
+               (unsigned int) splitpoint);
+      exit (49);
+    }
     MHD_destroy_post_processor (pp);
     if (want_off != FORM_END)
-      return (int) splitpoint;
+    {
+      fprintf (stderr,
+               "Test failed in line %u at point %u\n",
+               (unsigned int) __LINE__,
+               (unsigned int) splitpoint);
+      return (unsigned int) splitpoint;
+    }
   }
   return 0;
 }
 
 
-static int
-test_multipart ()
+static unsigned int
+test_multipart (void)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
   unsigned int want_off = FORM_START;
-  int i;
-  int delta;
+  size_t i;
+  size_t delta;
   size_t size;
 
   memset (&connection, 0, sizeof (struct MHD_Connection));
-  memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-  connection.headers_received = &header;
+  memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+  connection.rq.headers_received = &header;
   header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
   header.value =
     MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x";
   header.kind = MHD_HEADER_KIND;
+  header.header_size = strlen (header.header);
+  header.value_size = strlen (header.value);
   pp = MHD_create_post_processor (&connection,
                                   1024, &value_checker, &want_off);
+  if (NULL == pp)
+  {
+    fprintf (stderr, "Failed to create post processor.\n"
+             "Line: %u\n", (unsigned int) __LINE__);
+    exit (50);
+  }
   i = 0;
   size = strlen (FORM_DATA);
   while (i < size)
+  {
+    delta = 1 + ((size_t) MHD_random_ ()) % (size - i);
+    if (MHD_YES != MHD_post_process (pp,
+                                     &FORM_DATA[i],
+                                     delta))
     {
-      delta = 1 + MHD_random_ () % (size - i);
-      MHD_post_process (pp, &FORM_DATA[i], delta);
-      i += delta;
+      fprintf (stderr, "Failed to process the data.\n"
+               "i: %u. delta: %u.\n"
+               "Line: %u\n", (unsigned) i, (unsigned) delta,
+               (unsigned int) __LINE__);
+      exit (49);
     }
+    i += delta;
+  }
   MHD_destroy_post_processor (pp);
   if (want_off != FORM_END)
+  {
+    fprintf (stderr,
+             "Test failed in line %u\n",
+             (unsigned int) __LINE__);
     return 2;
+  }
   return 0;
 }
 
 
-static int
-test_nested_multipart ()
+static unsigned int
+test_nested_multipart (void)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
   unsigned int want_off = FORM_NESTED_START;
-  int i;
-  int delta;
+  size_t i;
+  size_t delta;
   size_t size;
 
   memset (&connection, 0, sizeof (struct MHD_Connection));
-  memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-  connection.headers_received = &header;
+  memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+  connection.rq.headers_received = &header;
   header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
   header.value =
     MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x";
   header.kind = MHD_HEADER_KIND;
+  header.header_size = strlen (header.header);
+  header.value_size = strlen (header.value);
   pp = MHD_create_post_processor (&connection,
                                   1024, &value_checker, &want_off);
+  if (NULL == pp)
+  {
+    fprintf (stderr, "Failed to create post processor.\n"
+             "Line: %u\n", (unsigned int) __LINE__);
+    exit (50);
+  }
   i = 0;
   size = strlen (FORM_NESTED_DATA);
   while (i < size)
+  {
+    delta = 1 + ((size_t) MHD_random_ ()) % (size - i);
+    if (MHD_YES != MHD_post_process (pp,
+                                     &FORM_NESTED_DATA[i],
+                                     delta))
     {
-      delta = 1 + MHD_random_ () % (size - i);
-      MHD_post_process (pp, &FORM_NESTED_DATA[i], delta);
-      i += delta;
+      fprintf (stderr, "Failed to process the data.\n"
+               "i: %u. delta: %u.\n"
+               "Line: %u\n", (unsigned) i, (unsigned) delta,
+               (unsigned int) __LINE__);
+      exit (49);
     }
+    i += delta;
+  }
   MHD_destroy_post_processor (pp);
   if (want_off != FORM_NESTED_END)
+  {
+    fprintf (stderr,
+             "Test failed in line %u\n",
+             (unsigned int) __LINE__);
     return 4;
+  }
   return 0;
 }
 
 
-static int
-test_empty_value ()
+static enum MHD_Result
+value_checker2 (void *cls,
+                enum MHD_ValueKind kind,
+                const char *key,
+                const char *filename,
+                const char *content_type,
+                const char *transfer_encoding,
+                const char *data,
+                uint64_t off,
+                size_t size)
+{
+  (void) cls; (void) kind; (void) key; /* Mute compiler warnings */
+  (void) filename; (void) content_type; (void) transfer_encoding;
+  (void) data; (void) off; (void) size;
+  return MHD_YES;
+}
+
+
+static unsigned int
+test_overflow (void)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
-  unsigned int want_off = URL_EMPTY_VALUE_START;
-  int i;
-  int delta;
-  size_t size;
+  size_t i;
+  size_t j;
+  size_t delta;
+  char *buf;
 
   memset (&connection, 0, sizeof (struct MHD_Connection));
-  memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-  connection.headers_received = &header;
+  memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+  connection.rq.headers_received = &header;
   header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
   header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+  header.header_size = strlen (header.header);
+  header.value_size = strlen (header.value);
   header.kind = MHD_HEADER_KIND;
-  pp = MHD_create_post_processor (&connection,
-                                  1024, &value_checker, &want_off);
-  i = 0;
-  size = strlen (URL_EMPTY_VALUE_DATA);
-  while (i < size)
+  for (i = 128; i < 1024 * 1024; i += 1024)
+  {
+    pp = MHD_create_post_processor (&connection,
+                                    1024,
+                                    &value_checker2,
+                                    NULL);
+    if (NULL == pp)
     {
-      delta = 1 + MHD_random_ () % (size - i);
-      MHD_post_process (pp, &URL_EMPTY_VALUE_DATA[i], delta);
-      i += delta;
+      fprintf (stderr, "Failed to create post processor.\n"
+               "Line: %u\n", (unsigned int) __LINE__);
+      exit (50);
     }
-  MHD_destroy_post_processor (pp);
-  if (want_off != URL_EMPTY_VALUE_END)
-    return 8;
+    buf = malloc (i);
+    if (NULL == buf)
+      return 1;
+    memset (buf, 'A', i);
+    buf[i / 2] = '=';
+    delta = 1 + (((size_t) MHD_random_ ()) % (i - 1));
+    j = 0;
+    while (j < i)
+    {
+      if (j + delta > i)
+        delta = i - j;
+      if (MHD_NO ==
+          MHD_post_process (pp,
+                            &buf[j],
+                            delta))
+        break;
+      j += delta;
+    }
+    free (buf);
+    MHD_destroy_post_processor (pp);
+  }
   return 0;
 }
 
 
+static unsigned int
+test_empty_key (void)
+{
+  const char form_data[] = "=abcdef";
+  size_t step;
+  const size_t size = MHD_STATICSTR_LEN_ (form_data);
+
+  for (step = 1; size >= step; ++step)
+  {
+    size_t i;
+    struct MHD_Connection connection;
+    struct MHD_HTTP_Req_Header header;
+    struct MHD_PostProcessor *pp;
+    memset (&connection, 0, sizeof (struct MHD_Connection));
+    memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+
+    connection.rq.headers_received = &header;
+    connection.rq.headers_received_tail = &header;
+    header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
+    header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE);
+    header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    header.value_size =
+      MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED);
+    header.kind = MHD_HEADER_KIND;
+    pp = MHD_create_post_processor (&connection,
+                                    1024, &value_checker2, NULL);
+    if (NULL == pp)
+    {
+      fprintf (stderr, "Failed to create post processor.\n"
+               "Line: %u\n", (unsigned int) __LINE__);
+      exit (50);
+    }
+    for (i = 0; size > i; i += step)
+    {
+      if (MHD_NO != MHD_post_process (pp,
+                                      form_data + i,
+                                      (step > size - i) ? (size - i) : step))
+      {
+        fprintf (stderr, "Succeed to process the broken data.\n"
+                 "i: %u. step: %u.\n"
+                 "Line: %u\n", (unsigned) i, (unsigned) step,
+                 (unsigned int) __LINE__);
+        exit (49);
+      }
+    }
+    MHD_destroy_post_processor (pp);
+  }
+  return 0;
+}
+
+
+static unsigned int
+test_double_value (void)
+{
+  const char form_data[] = URL_DATA "=abcdef";
+  size_t step;
+  const size_t size = MHD_STATICSTR_LEN_ (form_data);
+  const size_t safe_size = MHD_STATICSTR_LEN_ (URL_DATA);
+
+  for (step = 1; size >= step; ++step)
+  {
+    size_t i;
+    struct MHD_Connection connection;
+    struct MHD_HTTP_Req_Header header;
+    struct MHD_PostProcessor *pp;
+    unsigned int results_off = URL_START;
+    unsigned int results_final = results_off + 1; /* First value is correct */
+    memset (&connection, 0, sizeof (struct MHD_Connection));
+    memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+
+    connection.rq.headers_received = &header;
+    connection.rq.headers_received_tail = &header;
+    header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
+    header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE);
+    header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    header.value_size =
+      MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED);
+    header.kind = MHD_HEADER_KIND;
+    pp = MHD_create_post_processor (&connection,
+                                    1024, &value_checker, &results_off);
+    if (NULL == pp)
+    {
+      fprintf (stderr, "Failed to create post processor.\n"
+               "Line: %u\n", (unsigned int) __LINE__);
+      exit (50);
+    }
+    for (i = 0; size > i; i += step)
+    {
+      if (MHD_NO != MHD_post_process (pp,
+                                      form_data + i,
+                                      (step > size - i) ? (size - i) : step))
+      {
+        if (safe_size == i + step)
+          results_final = URL_END;
+        if (safe_size < i + step)
+        {
+          fprintf (stderr, "Succeed to process the broken data.\n"
+                   "i: %u. step: %u.\n"
+                   "Line: %u\n", (unsigned) i, (unsigned) step,
+                   (unsigned int) __LINE__);
+          exit (49);
+        }
+      }
+      else
+      {
+        if (safe_size >= i + step)
+        {
+          fprintf (stderr, "Failed to process the data.\n"
+                   "i: %u. step: %u.\n"
+                   "Line: %u\n", (unsigned) i, (unsigned) step,
+                   (unsigned int) __LINE__);
+          exit (49);
+        }
+      }
+    }
+    MHD_destroy_post_processor (pp);
+    if (results_final != results_off)
+    {
+      fprintf (stderr,
+               "Test failed in line %u.\tStep:%u\n Got: %u\tExpected: %u\n",
+               (unsigned int) __LINE__,
+               (unsigned int) step,
+               results_off,
+               results_final);
+      return 1;
+    }
+  }
+  return 0;
+}
 
 
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv;  /* Unused. Silent compiler warning. */
 
   errorCount += test_multipart_splits ();
   errorCount += test_multipart_garbage ();
   errorCount += test_urlencoding ();
   errorCount += test_multipart ();
   errorCount += test_nested_multipart ();
-  errorCount += test_empty_value ();
+  errorCount += test_empty_key ();
+  errorCount += test_double_value ();
+  errorCount += test_overflow ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
-  return errorCount != 0;       /* 0 == pass */
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/microhttpd/test_postprocessor_amp.c b/src/microhttpd/test_postprocessor_amp.c
index 73f72f9..ba24601 100644
--- a/src/microhttpd/test_postprocessor_amp.c
+++ b/src/microhttpd/test_postprocessor_amp.c
@@ -5,16 +5,21 @@
 #include <string.h>
 #include <stdio.h>
 
+static uint64_t num_errors;
 
-int check_post(void *cls, enum MHD_ValueKind kind, const char* key,
-                 const char* filename, const char* content_type,
-                 const char* content_encoding, const char* data,
-                 uint64_t off, size_t size)
+static enum MHD_Result
+check_post (void *cls, enum MHD_ValueKind kind, const char *key,
+            const char *filename, const char *content_type,
+            const char *content_encoding, const char *data,
+            uint64_t off, size_t size)
 {
-  if ((0 != strcmp(key, "a")) && (0 != strcmp(key, "b")))
-    {
-      printf("ERROR: got unexpected '%s'\n", key);
-    }
+  (void) cls; (void) kind; (void) filename; (void) content_type;  /* Unused. Silent compiler warning. */
+  (void) content_encoding; (void) data; (void) off; (void) size;  /* Unused. Silent compiler warning. */
+  if ((0 != strcmp (key, "a")) && (0 != strcmp (key, "b")))
+  {
+    printf ("ERROR: got unexpected '%s'\n", key);
+    num_errors++;
+  }
 
   return MHD_YES;
 }
@@ -24,24 +29,73 @@
 main (int argc, char *const *argv)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
+  const char *post =
+    "a=xx+xx+xxx+xxxxx+xxxx+xxxxxxxx+xxx+xxxxxx+xxx+xxx+xxxxxxx+xxxxx%0A+++"
+    "++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+    "xxxxxxxxxxxxxx%0A+++++++--%3E%0A++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%"
+    "25%22%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%2"
+    "2+xxxxx%3D%22xxxxx%22%3E%0A+++++++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%"
+    "25%22%3E%0A+++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++++++++++++"
+    "++%3Cxx+xxxxx%3D%22xxxx%22%3E%0A+++++++++++++++++++++++++++++++%3Cx+xx"
+    "xxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxxxx%3A%3C%2Fx%3E%0A%0A+++++++++++++"
+    "++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxx%3A%3C%2F"
+    "x%3E%0A%0A+++++++++++++++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3A"
+    "xxxxx%3B+xxxx-xxxxxx%3A+xxxx%3B%22%3Exxxxx+xxxxx%3A%3C%2Fx%3E%0A++++++"
+    "+++++++++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++++++++++%3C%2Fxx%3E%"
+    "0A+++++++++++++++++++%3C%2Fxxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++"
+    "++++++++++++%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3"
+    "E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxx"
+    "xx%22%3Exxxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A++++++++++"
+    "+%3C%2Fxx%3E%0A++++++++++++++++++++++++++%3Cxx%3E%0A++++++++++++++++++"
+    "+%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3E%26xxxxx%3"
+    "B+%3Cxxxx%0A+++++++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxxxx%22%3"
+    "Exxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++++++%3C%2Fxx%3E%0A++++++++++++++"
+    "+%3C%2Fxx%3E%0A++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+x"
+    "xxxx%3D%22xxxx-xxxxx%3A+xxxxx%3Bxxxx-xxxxxx%3A+xxxx%3B+xxxxx%3A+xxxx%2"
+    "2%3E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxx"
+    "xxxxx%22%3Exxxx.xx%3C%2Fxxxx%3E%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A"
+    "+++++++%3C%2Fxxxxx%3E%0A+++++++%3C%21--%0A+++++++xxxxxxxxxxxxxxxxxxxxx"
+    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++x"
+    "xx+xx+xxxxx+xxxxxxx+xxxxxxx%0A+++++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++--%3E%0A+++%3"
+    "C%2Fxxx%3E%0A%0A%0A%0A+++%3Cxxx+xxxxx%3D%22xxxxxxxxx%22+xx%3D%22xxxxxx"
+    "xxx%22%3E%3C%2Fxxx%3E%0A%0A+++%3Cxxx+xx%3D%22xxxx%22+xxxxx%3D%22xxxx%2"
+    "2%3E%0A+++++++%3Cxxxxx+xxxxx%3D%22xxxxxxxxx%22%3E%0A+++++++++++%3Cxx%3"
+    "E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xx"
+    "xxx%3D%22xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxx"
+    "x%22%3E%3C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx"
+    "%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xx%3D%22xxxxxxxxxxxxx"
+    "xxxx%22+xxxxx%3D%22xxxxxxxxxxxxxxxxx%22%3E%3C%2Fxx%3E%0A++++++++++++++"
+    "+%3Cxx+xx%3D%22xxxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxxx%22%3E%0A+++"
+    "++++++++++++++++%3Cxxx+xx%3D%22xxxxxxx%22%3E%3C%2Fxxx%3E%0A+++++++++++"
+    "++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++++++%3Cxx%3E%0A+++++"
+    "++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xxxxx%3D%22"
+    "xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxxx%22%3E%3"
+    "C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++"
+    "++++%3C%2Fxxxxx%3E%0A+++%3C%2Fxxx%3E%0A%3C%2Fxxx%3E%0A%0A%3Cxxx+xx%3D%"
+    "22xxxxxx%22%3E%3C%2Fxxx%3E%0A%0A%3C%2Fxxxx%3E%0A%3C%2Fxxxx%3E+&b=value";
+  (void) argc; (void) argv;  /* Unused. Silent compiler warning. */
 
+  num_errors = 0;
   memset (&connection, 0, sizeof (struct MHD_Connection));
-  memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-  connection.headers_received = &header;
+  memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+  connection.rq.headers_received = &header;
   header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
   header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+  header.header_size = strlen (header.header);
+  header.value_size = strlen (header.value);
   header.kind = MHD_HEADER_KIND;
 
   pp = MHD_create_post_processor (&connection,
                                   4096, &check_post, NULL);
+  if (NULL == pp)
+    return 1;
 
-  const char* post = "a=xx+xx+xxx+xxxxx+xxxx+xxxxxxxx+xxx+xxxxxx+xxx+xxx+xxxxxxx+xxxxx%0A+++++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++--%3E%0A++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%25%22%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%22+xxxxx%3D%22xxxxx%22%3E%0A+++++++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%25%22%3E%0A+++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++++++++++++++%3Cxx+xxxxx%3D%22xxxx%22%3E%0A+++++++++++++++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxxxx%3A%3C%2Fx%3E%0A%0A+++++++++++++++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxx%3A%3C%2Fx%3E%0A%0A+++++++++++++++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3Axxxxx%3B+xxxx-xxxxxx%3A+xxxx%3B%22%3Exxxxx+xxxxx%3A%3C%2Fx%3E%0A+++++++++++++++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++++++%3C%2Fxxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxxxx%22%3Exxxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A++++++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++++++%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxxxx%22%3Exxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3Bxxxx-xxxxxx%3A+xxxx%3B+xxxxx%3A+xxxx%22%3E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxxxx%22%3Exxxx.xx%3C%2Fxxxx%3E%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++%3C%2Fxxxxx%3E%0A+++++++%3C%21--%0A+++++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++xxx+xx+xxxxx+xxxxxxx+xxxxxxx%0A+++++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++--%3E%0A+++%3C%2Fxxx%3E%0A%0A%0A%0A+++%3Cxxx+xxxxx%3D%22xxxxxxxxx%22+xx%3D%22xxxxxxxxx%22%3E%3C%2Fxxx%3E%0A%0A+++%3Cxxx+xx%3D%22xxxx%22+xxxxx%3D%22xxxx%22%3E%0A+++++++%3Cxxxxx+xxxxx%3D%22xxxxxxxxx%22%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxxx%22%3E%3C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xx%3D%22xxxxxxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxxxxxx%22%3E%3C%2Fxx%3E%0A+++++++++++++++%3Cxx+xx%3D%22xxxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxxxx%22%3E%3C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxxx%22%3E%3C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++%3C%2Fxxxxx%3E%0A+++%3C%2Fxxx%3E%0A%3C%2Fxxx%3E%0A%0A%3Cxxx+xx%3D%22xxxxxx%22%3E%3C%2Fxxx%3E%0A%0A%3C%2Fxxxx%3E%0A%3C%2Fxxxx%3E+&b=value";
-
-  MHD_post_process (pp, post, strlen(post));
+  if (MHD_YES != MHD_post_process (pp, post, strlen (post)))
+    num_errors++;
   MHD_destroy_post_processor (pp);
 
-  return 0;
+  return num_errors == 0 ? 0 : 2;
 }
-
diff --git a/src/microhttpd/test_postprocessor_large.c b/src/microhttpd/test_postprocessor_large.c
index 0af4ab9..61f2887 100644
--- a/src/microhttpd/test_postprocessor_large.c
+++ b/src/microhttpd/test_postprocessor_large.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -27,12 +27,13 @@
 #include "platform.h"
 #include "microhttpd.h"
 #include "internal.h"
+#include "mhd_compat.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
 #endif
 
-static int
+static enum MHD_Result
 value_checker (void *cls,
                enum MHD_ValueKind kind,
                const char *key,
@@ -41,10 +42,12 @@
                const char *transfer_encoding,
                const char *data, uint64_t off, size_t size)
 {
-  unsigned int *pos = cls;
+  size_t *pos = (size_t *) cls;
+  (void) kind; (void) key; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; (void) data; (void) off;             /* Unused. Silent compiler warning. */
 #if 0
   fprintf (stderr,
-           "VC: %llu %u `%s' `%s' `%s' `%s' `%.*s'\n",
+           "VC: %" PRIu64 " %u `%s' `%s' `%s' `%s' `%.*s'\n",
            off, size,
            key, filename, content_type, transfer_encoding, size, data);
 #endif
@@ -56,47 +59,60 @@
 }
 
 
-static int
-test_simple_large ()
+static unsigned int
+test_simple_large (void)
 {
   struct MHD_Connection connection;
-  struct MHD_HTTP_Header header;
+  struct MHD_HTTP_Req_Header header;
   struct MHD_PostProcessor *pp;
-  int i;
-  int delta;
+  size_t i;
+  size_t delta;
   size_t size;
   char data[102400];
-  unsigned int pos;
+  size_t pos;
 
   pos = 0;
   memset (data, 'A', sizeof (data));
   memcpy (data, "key=", 4);
   data[sizeof (data) - 1] = '\0';
   memset (&connection, 0, sizeof (struct MHD_Connection));
-  memset (&header, 0, sizeof (struct MHD_HTTP_Header));
-  connection.headers_received = &header;
+  memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header));
+  connection.rq.headers_received = &header;
   header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
   header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+  header.header_size = strlen (header.header);
+  header.value_size = strlen (header.value);
   header.kind = MHD_HEADER_KIND;
   pp = MHD_create_post_processor (&connection, 1024, &value_checker, &pos);
   i = 0;
   size = strlen (data);
   while (i < size)
+  {
+    delta = 1 + ((size_t) MHD_random_ ()) % (size - i);
+    if (MHD_YES !=
+        MHD_post_process (pp,
+                          &data[i],
+                          delta))
     {
-      delta = 1 + MHD_random_ () % (size - i);
-      MHD_post_process (pp, &data[i], delta);
-      i += delta;
+      fprintf (stderr,
+               "MHD_post_process() failed!\n");
+      MHD_destroy_post_processor (pp);
+      return 1;
     }
+    i += delta;
+  }
   MHD_destroy_post_processor (pp);
   if (pos != sizeof (data) - 5) /* minus 0-termination and 'key=' */
     return 1;
   return 0;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv;  /* Unused. Silent compiler warning. */
 
   errorCount += test_simple_large ();
   if (errorCount != 0)
diff --git a/src/microhttpd/test_postprocessor_md.c b/src/microhttpd/test_postprocessor_md.c
new file mode 100644
index 0000000..5593678
--- /dev/null
+++ b/src/microhttpd/test_postprocessor_md.c
@@ -0,0 +1,735 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2020 Christian Grothoff
+     Copyright (C) 2020-2023 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_postprocessor_md.c
+ * @brief  Testcase for postprocessor, keys with no value
+ * @author Markus Doppelbauer
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "mhd_options.h"
+#include <stdio.h>
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#include "microhttpd.h"
+#include "internal.h"
+#include "postprocessor.h"
+#if 0
+#include "mhd_panic.c"
+#include "mhd_str.c"
+#include "internal.c"
+#endif
+
+
+#define DEBUG 0
+
+/* local replacement for MHD functions */
+
+_MHD_EXTERN enum MHD_Result
+MHD_lookup_connection_value_n (struct MHD_Connection *connection,
+                               enum MHD_ValueKind kind,
+                               const char *key,
+                               size_t key_size,
+                               const char **value_ptr,
+                               size_t *value_size_ptr)
+{
+  (void) connection; (void) kind; (void) key; /* Mute compiler warnings */
+  (void) key_size;
+
+  *value_ptr = "";
+  if (NULL != value_size_ptr)
+    *value_size_ptr = 0;
+  return MHD_NO;
+}
+
+
+#define ARRAY_LENGTH(array)     (sizeof(array) / sizeof(array[0]))
+
+
+static unsigned int found;
+
+
+static enum MHD_Result
+post_data_iterator (void *cls,
+                    enum MHD_ValueKind kind,
+                    const char *key,
+                    const char *filename,
+                    const char *content_type,
+                    const char *transfer_encoding,
+                    const char *data,
+                    uint64_t off,
+                    size_t size)
+{
+  (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */
+  (void) content_type; (void) transfer_encoding;
+  (void) off; /* FIXME: shouldn't be checked? */
+#if DEBUG
+  fprintf (stderr,
+           "%s\t%s\n",
+           key,
+           data);
+#endif
+  if (0 == strcmp (key, "xxxx"))
+  {
+    if ( (4 != size) ||
+         (0 != memcmp (data, "xxxx", 4)) )
+      exit (1);
+    found |= 1;
+  }
+  if (0 == strcmp (key, "yyyy"))
+  {
+    if ( (4 != size) ||
+         (0 != memcmp (data, "yyyy", 4)) )
+      exit (1);
+    found |= 2;
+  }
+  if (0 == strcmp (key, "zzzz"))
+  {
+    if (0 != size)
+      exit (1);
+    found |= 4;
+  }
+  if (0 == strcmp (key, "aaaa"))
+  {
+    if (0 != size)
+      exit (1);
+    found |= 8;
+  }
+  return MHD_YES;
+}
+
+
+static enum MHD_Result
+post_data_iterator2 (void *cls,
+                     enum MHD_ValueKind kind,
+                     const char *key,
+                     const char *filename,
+                     const char *content_type,
+                     const char *transfer_encoding,
+                     const char *data,
+                     uint64_t off,
+                     size_t size)
+{
+  static char seen[16];
+  (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */
+  (void) content_type; (void) transfer_encoding;
+
+#if DEBUG
+  printf ("%s\t%s@ %" PRIu64 "\n",
+          key,
+          data,
+          off);
+#endif
+  if (0 == strcmp (key, "text"))
+  {
+    if (off + size > sizeof (seen))
+      exit (6);
+    memcpy (&seen[off],
+            data,
+            size);
+    if ( (10 == off + size) &&
+         (0 == memcmp (seen, "text, text", 10)) )
+      found |= 1;
+  }
+  return MHD_YES;
+}
+
+
+static enum MHD_Result
+post_data_iterator3 (void *cls,
+                     enum MHD_ValueKind kind,
+                     const char *key,
+                     const char *filename,
+                     const char *content_type,
+                     const char *transfer_encoding,
+                     const char *data,
+                     uint64_t off,
+                     size_t size)
+{
+  (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */
+  (void) content_type; (void) transfer_encoding;
+  (void) off; /* FIXME: shouldn't be checked? */
+#if DEBUG
+  fprintf (stderr,
+           "%s\t%s\n",
+           key,
+           data);
+#endif
+  if (0 == strcmp (key, "y"))
+  {
+    if ( (1 != size) ||
+         (0 != memcmp (data, "y", 1)) )
+      exit (1);
+    found |= 1;
+  }
+  return MHD_YES;
+}
+
+
+static enum MHD_Result
+post_data_iterator4 (void *cls,
+                     enum MHD_ValueKind kind,
+                     const char *key,
+                     const char *filename,
+                     const char *content_type,
+                     const char *transfer_encoding,
+                     const char *data,
+                     uint64_t off,
+                     size_t size)
+{
+  (void) cls; (void) kind; (void) key; /* Mute compiler warnings */
+  (void) filename; (void) content_type; (void) transfer_encoding;
+  (void) off; /* FIXME: shouldn't be checked? */
+#if DEBUG
+  fprintf (stderr,
+           "%s\t%s\n",
+           key,
+           data);
+#endif
+  if (NULL != memchr (data, 'M', size))
+  {
+    found |= 1;
+  }
+  return MHD_YES;
+}
+
+
+static enum MHD_Result
+post_data_iterator5 (void *cls,
+                     enum MHD_ValueKind kind,
+                     const char *key,
+                     const char *filename,
+                     const char *content_type,
+                     const char *transfer_encoding,
+                     const char *data,
+                     uint64_t off,
+                     size_t size)
+{
+  (void) cls; (void) kind; (void) key; /* Mute compiler warnings */
+  (void) filename; (void) content_type; (void) transfer_encoding;
+  (void) data; (void) off; (void) size;
+
+  found++;
+  return MHD_YES;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  struct MHD_PostProcessor *postprocessor;
+  (void) argc; (void) argv;
+
+  if (1)
+  {
+    found = 0;
+    postprocessor = malloc (sizeof (struct MHD_PostProcessor)
+                            + 0x1000 + 1);
+    if (NULL == postprocessor)
+      return 77;
+    memset (postprocessor,
+            0,
+            sizeof (struct MHD_PostProcessor) + 0x1000 + 1);
+    postprocessor->ikvi = &post_data_iterator;
+    postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    postprocessor->buffer_size = 0x1000;
+    postprocessor->state = PP_Init;
+    postprocessor->skip_rn = RN_Inactive;
+    if (MHD_YES != MHD_post_process (postprocessor, "xxxx=xxxx", 9))
+      exit (1);
+    if (MHD_YES != MHD_post_process (postprocessor, "&yyyy=yyyy&zzzz=&aaaa=",
+                                     22))
+      exit (1);
+    if (MHD_YES != MHD_post_process (postprocessor, "", 0))
+      exit (1);
+    if (MHD_YES !=
+        MHD_destroy_post_processor (postprocessor))
+      exit (3);
+    if (found != 15)
+      exit (2);
+  }
+  if (1)
+  {
+    found = 0;
+    postprocessor = malloc (sizeof (struct MHD_PostProcessor)
+                            + 0x1000 + 1);
+    if (NULL == postprocessor)
+      return 77;
+    memset (postprocessor,
+            0,
+            sizeof (struct MHD_PostProcessor) + 0x1000 + 1);
+    postprocessor->ikvi = post_data_iterator2;
+    postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    postprocessor->buffer_size = 0x1000;
+    postprocessor->state = PP_Init;
+    postprocessor->skip_rn = RN_Inactive;
+    if (MHD_YES != MHD_post_process (postprocessor, "text=text%2", 11))
+      exit (1);
+    if (MHD_YES != MHD_post_process (postprocessor, "C+text", 6))
+      exit (1);
+    if (MHD_YES != MHD_post_process (postprocessor, "", 0))
+      exit (1);
+    if (MHD_YES != MHD_destroy_post_processor (postprocessor))
+      exit (1);
+    if (found != 1)
+      exit (4);
+  }
+  if (1)
+  {
+    found = 0;
+    postprocessor = malloc (sizeof (struct MHD_PostProcessor)
+                            + 0x1000 + 1);
+    if (NULL == postprocessor)
+      return 77;
+    memset (postprocessor,
+            0,
+            sizeof (struct MHD_PostProcessor) + 0x1000 + 1);
+    postprocessor->ikvi = post_data_iterator3;
+    postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    postprocessor->buffer_size = 0x1000;
+    postprocessor->state = PP_Init;
+    postprocessor->skip_rn = RN_Inactive;
+    {
+      const char *chunk =
+        "x=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxx%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxx%2C%2Cxxxxxx"
+        "%2Cxxxx%2C%2Cxxxxx%2Cxxxxxxxxx%2C%2Cxxx%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxx"
+        "%2Cxxxxx%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx"
+        "%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxx%2C%2Cxxxxx%2C%2Cx%2Cxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C"
+        "xxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxx%2C%2Cxx%2C%2Cx%2Cxx%2C%2Cxxxx%2Cxxx"
+        "%2C%2Cx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C"
+        "%2Cxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "x%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xx%2Cxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxx%2Cxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxx"
+        "xx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxx"
+        "xxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx"
+        "xxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx%2Cx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2"
+        "Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxx%2Cxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cx"
+        "xxxxxxxx%2Cxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxxxxx"
+        "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C"
+        "%2C%2C%2C%2C%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%"
+        "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C"
+        "%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2"
+        "Cxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2"
+        "C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%"
+        "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxx"
+        "xxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2"
+        "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2"
+        "C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cx%2C%"
+        "2Cx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxx%2Cxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cx"
+        "xxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx"
+        "xxx%2Cxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxx%2Cx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cx"
+        "xxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx"
+        "xx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx"
+        "xxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C"
+        "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx"
+        "xxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx"
+        "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2C"
+        "xxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx"
+        "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2"
+        "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxx"
+        "xxx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx"
+        "xxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx"
+        "xxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxx"
+        "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx"
+        "xxxxxxxxx%2Cxxxxx%2Cxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx"
+        "xxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxx%2Cx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxx%2Cx%2Cxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%"
+        "2Cxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxx%"
+        "2Cxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxx"
+        "xx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxx"
+        "xxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%"
+        "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxx"
+        "x%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx"
+        "xxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C"
+        "%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxx"
+        "xxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%"
+        "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx"
+        "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxx%2Cxxx"
+        "xxxx%2Cxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx%"
+        "2C%2C%2Cxxxxxxxxx%2Cxxxxxxxx%2C"
+        "&y=y&z=z";
+
+      if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) ))
+        exit (1);
+    }
+    if (MHD_YES != MHD_post_process (postprocessor, "", 0))
+      exit (1);
+    if (MHD_YES != MHD_destroy_post_processor (postprocessor))
+      exit (1);
+    if (found != 1)
+      exit (5);
+  }
+
+  if (1)
+  {
+    unsigned i;
+    const char *chunks[] = {
+      "t=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxx%2C%2Cx%2Cxxxxxxxx"
+      "xxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxxx%"
+      "2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxx%2C%2Cx%2"
+      "Cxx%2C%2Cxxxx%2Cxxx%2C%2Cx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "x%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2"
+      "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxx"
+      "xxxxxxxx%2C%2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx"
+      "xxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cx%2Cxxxxxxxxxx"
+      "xxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xx%2Cxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxx"
+      "xxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2C"
+      "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C"
+      "%2C%2C%2C%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C"
+      "%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxx"
+      "xxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2"
+      "C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxxxxx"
+      "xxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2"
+      "C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxx",
+      /* one chunk: second line is dropped */
+      "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C"
+      "xxxxxxxxxxxxxxxx%2Cx%2C%2Cx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2Cxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx"
+      "xxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cx%2C%2C"
+      "%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%"
+      "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx"
+      "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "x%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxx%2C%2C%2C%2C"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxx"
+      "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxx"
+      "%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx"
+      "x%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx"
+      "xx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxx%2Cxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%"
+      "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx%2Cxx"
+      "xxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxx"
+      "x%2Cxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%"
+      "2Cx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxx%2Cx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xx%2Cx%2Cxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx%2Cx"
+      "xxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxx"
+      "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%"
+      "2C%2C%2C%2Cxxxxxxxxxxx%2C%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2"
+      "Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx"
+      "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2"
+      "C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxx%2"
+      "C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+      "xxxxxxxxxxxxxxxxxxxxxxxxxZZZZZZZZZZZZZ%2C%2C%2C%2C"
+      "%E2%80%A2MMMMMMMM%2C%2C%2C%2CMMMMMMMMMMMMMMMMMMMM%2CMMMMMMMMMMMMMMMMMM"
+      "MMMMM%2CMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
+      "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
+      "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
+      "MMMMMMMMMMMMMMMMMMMMMMMMMM%2C%2C%2C%2CMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"
+      "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM%2CMMMMMMMMMMMMMMMMMMMM"
+      "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM%2CMMMMMM"
+      "MMMMMMMMMMMMMMMMMMMMMMMMMMMM"
+      "zz",
+      "",
+    };
+    postprocessor = malloc (sizeof(struct MHD_PostProcessor) + 131076 + 1);
+    if (NULL == postprocessor)
+      return 77;
+    memset (postprocessor,
+            0,
+            sizeof (struct MHD_PostProcessor) + 0x1000 + 1);
+    postprocessor->ikvi = post_data_iterator4;
+    postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    postprocessor->buffer_size = 131076;
+    postprocessor->state = PP_Init;
+    postprocessor->skip_rn = RN_Inactive;
+    for (i = 0; i < ARRAY_LENGTH (chunks); ++i)
+    {
+      const char *chunk = chunks[i];
+      if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) ))
+        exit (1);
+    }
+    if (MHD_YES != MHD_destroy_post_processor (postprocessor))
+      exit (1);
+    if (found != 1)
+      return 6;
+  }
+  if (1)
+  {
+    unsigned i;
+    const char *chunks[] = {
+      "XXXXXXXXXXXX=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+      "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&XXXXXX=&XXXXXXXXXXXXXX=X"
+      "XXX+&XXXXXXXXXXXXXXX=XXXXXXXXX&XXXXXXXXXXXXX=XXXX%XX%XXXXXX&XXXXXXXXXX"
+      "X=XXXXXXXXX&XXXXXXXXXXXXX=XXXXXXXXXX&XXXXXXXXXXXXXXX=XX&XXXXXXXXXXXXXX"
+      "X=XXXXXXXXX&XXXXXXXXXXXXX=XXXXXX&XXXXXXXXXXX=XXXXXXXXXXXXXXXXXXXXXXXXX"
+      "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+      "XXXXXXXXXX",
+      "&XXXXXXXX=XXXX",
+      "",
+    };
+    postprocessor = malloc (sizeof(struct MHD_PostProcessor) + 131076 + 1);
+    found = 0;
+    if (NULL == postprocessor)
+      return 77;
+    memset (postprocessor,
+            0,
+            sizeof (struct MHD_PostProcessor) + 0x1000 + 1);
+    postprocessor->ikvi = post_data_iterator5;
+    postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
+    postprocessor->buffer_size = 131076;
+    postprocessor->state = PP_Init;
+    postprocessor->skip_rn = RN_Inactive;
+    for (i = 0; i < ARRAY_LENGTH (chunks); ++i)
+    {
+      const char *chunk = chunks[i];
+      if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) ))
+        exit (1);
+    }
+    if (MHD_YES != MHD_destroy_post_processor (postprocessor))
+      exit (1);
+    if (found != 12)
+      return 7;
+  }
+
+
+  return EXIT_SUCCESS;
+}
diff --git a/src/microhttpd/test_response_entries.c b/src/microhttpd/test_response_entries.c
new file mode 100644
index 0000000..d849f1c
--- /dev/null
+++ b/src/microhttpd/test_response_entries.c
@@ -0,0 +1,886 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021 Karlson2k (Evgeny Grin)
+
+     This test_response_entries.c file is in the public domain
+*/
+
+/**
+ * @file test_response_entries.c
+ * @brief  Test adding and removing response headers
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "mhd_options.h"
+#include "platform.h"
+#include <string.h>
+#include <microhttpd.h>
+
+
+static int
+expect_str (const char *actual, const char *expected)
+{
+  if (expected == actual)
+    return ! 0;
+  if (NULL == actual)
+  {
+    fprintf (stderr, "FAILED: result: NULL\n" \
+             "        expected: \"%s\"\n",
+             expected);
+    return 0;
+  }
+  if (NULL == expected)
+  {
+    fprintf (stderr, "FAILED: result: \"%s\"\n" \
+             "        expected: NULL\n",
+             actual);
+    return 0;
+  }
+  if (0 != strcmp (actual, expected))
+  {
+    fprintf (stderr, "FAILED: result: \"%s\"\n" \
+             "        expected: \"%s\"\n",
+             actual, expected);
+    return 0;
+  }
+  return ! 0;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  struct MHD_Response *r;
+  (void) argc;
+  (void) argv; /* Unused. Silence compiler warning. */
+
+  r = MHD_create_response_empty (MHD_RF_NONE);
+  if (NULL == r)
+  {
+    fprintf (stderr, "Cannot create a response.\n");
+    return 1;
+  }
+
+  /* ** Test basic header functions ** */
+
+  /* Add first header */
+  if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a1"))
+  {
+    fprintf (stderr, "Cannot add header A1.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a1"))
+  {
+    MHD_destroy_response (r);
+    return 2;
+  }
+  /* Add second header with the same name */
+  if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a2"))
+  {
+    fprintf (stderr, "Cannot add header A2.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+  /* Value of the first header must be returned */
+  if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a1"))
+  {
+    MHD_destroy_response (r);
+    return 2;
+  }
+  /* Remove the first header */
+  if (MHD_YES != MHD_del_response_header (r, "Header-Type-A", "value-a1"))
+  {
+    fprintf (stderr, "Cannot remove header A1.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+  /* Value of the ex-second header must be returned */
+  if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2"))
+  {
+    MHD_destroy_response (r);
+    return 2;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a3"))
+  {
+    fprintf (stderr, "Cannot add header A2.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+  /* Value of the ex-second header must be returned */
+  if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2"))
+  {
+    MHD_destroy_response (r);
+    return 2;
+  }
+  /* Remove the last header */
+  if (MHD_YES != MHD_del_response_header (r, "Header-Type-A", "value-a3"))
+  {
+    fprintf (stderr, "Cannot add header A2.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2"))
+  {
+    MHD_destroy_response (r);
+    return 2;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Header-Type-B"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 2;
+  }
+  if (MHD_NO != MHD_del_response_header (r, "Header-Type-C", "value-a3"))
+  {
+    fprintf (stderr, "Removed non-existing header.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+  if (MHD_NO != MHD_del_response_header (r, "Header-Type-A", "value-c"))
+  {
+    fprintf (stderr, "Removed non-existing header value.\n");
+    MHD_destroy_response (r);
+    return 2;
+  }
+
+  /* ** Test "Connection:" header ** */
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "a,b,c,d,e"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with simple values.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "a, b, c, d, e"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "e,b,c,d,a"))
+  {
+    fprintf (stderr,
+             "Cannot remove \"Connection\" header with simple values.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "i,k,l,m,n,o,p,close"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with simple values and \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, i, k, l, m, n, o, p"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "i,k,l,m,n,o,p,close"))
+  {
+    fprintf (stderr,
+             "Cannot remove \"Connection\" header with simple values and \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "1,2,3,4,5,6,7,close"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with simple values and \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, 1, 2, 3, 4, 5, 6, 7"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "8,9,close"))
+  {
+    fprintf (stderr,
+             "Cannot add second \"Connection\" header with simple values and \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, 1, 2, 3, 4, 5, 6, 7, 8, 9"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "1,3,5,7,9"))
+  {
+    fprintf (stderr,
+             "Cannot remove part of \"Connection\" header with simple values.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, 2, 4, 6, 8"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "10,12"))
+  {
+    fprintf (stderr,
+             "Cannot add third \"Connection\" header with simple values.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, 2, 4, 6, 8, 10, 12"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "12  ,10  ,8  ,close"))
+  {
+    fprintf (stderr,
+             "Cannot remove part of \"Connection\" header with simple values and \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "2, 4, 6"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\" only.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, 2, 4, 6"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "4  ,5,6,7  8,"))
+  {
+    fprintf (stderr,
+             "Cannot remove part of \"Connection\" header with simple values and non-existing tokens.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\" only.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "close, 10, 12, 22, nothing"))
+  {
+    fprintf (stderr,
+             "Cannot remove part of \"Connection\" header with \"close\" and non-existing tokens.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "2"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "2"))
+  {
+    fprintf (stderr,
+             "Cannot remove part of \"Connection\" header with simple values and non-existing tokens.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot remove \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close,other-token"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, other-token"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close, new-token"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, other-token, new-token"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "close, new-token"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "other-token"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "other-token"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "close, one-long-token"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, one-long-token"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, one-long-token"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "one-long-token,close"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "close, additional-token"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, additional-token"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "additional-token,close"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "token-1,token-2"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "token-1, token-2"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "token-3"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "token-1, token-2, token-3"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close, token-4"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3, token-4"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection", "close"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "token-1, token-2, token-3, token-4"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "close, token-5"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3, token-4, token-5"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_NO != MHD_del_response_header (r, "Connection",
+                                         "non-existing, token-9"))
+  {
+    fprintf (stderr,
+             "Non-existing tokens successfully removed from \"Connection\" header.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3, token-4, token-5"))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_NO != MHD_add_response_header (r, "Connection",
+                                         ",,,,,,,,,,,,    ,\t\t\t, , , "))
+  {
+    fprintf (stderr,
+             "Empty token was added successfully to \"Connection\" header.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "close, token-1, token-2, token-3, token-4, token-5"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (MHD_NO != MHD_add_response_header (r, "Connection",
+                                         ",,,,,,,,,,,,    ,\t\t\t, , , "))
+  {
+    fprintf (stderr,
+             "Empty token was added successfully to \"Connection\" header.\n");
+    MHD_destroy_response (r);
+    return 3;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 3;
+  }
+
+  if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive"))
+  {
+    fprintf (stderr,
+             "Successfully added \"Connection\" header with \"keep-Alive\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "keep-Alive, Close"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with \"keep-Alive, Close\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive"))
+  {
+    fprintf (stderr,
+             "Successfully added \"Connection\" header with \"keep-Alive\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "keep-Alive, Close"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with \"keep-Alive, Close\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "close"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "close, additional-token"))
+  {
+    fprintf (stderr, "Cannot add \"Connection\" header with "
+             "\"close, additional-token\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, additional-token"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive"))
+  {
+    fprintf (stderr,
+             "Successfully added \"Connection\" header with \"keep-Alive\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, additional-token"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "additional-token,close"))
+  {
+    fprintf (stderr, "Cannot remove tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "Keep-aLive, token-1"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with \"Keep-aLive, token-1\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "Keep-aLive, token-2"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with \"Keep-aLive, token-2\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "token-1, token-2"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection",
+                                          "Keep-aLive, token-3, close"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with \"Keep-aLive, token-3, close\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "close"))
+  {
+    fprintf (stderr, "Cannot remove \"close\" tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "token-1, token-2, token-3"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, close"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Connection\" header with \"Keep-aLive, token-3, close\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"),
+                    "close, token-1, token-2, token-3"))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Connection",
+                                          "close, token-1, Keep-Alive, token-2, token-3"))
+  {
+    fprintf (stderr, "Cannot remove \"close\" tokens from \"Connection\".\n");
+    MHD_destroy_response (r);
+    return 4;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Connection"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 4;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, "Date",
+                                          "Wed, 01 Apr 2015 00:00:00 GMT"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Date\" header with \"Wed, 01 Apr 2015 00:00:00 GMT\".\n");
+    MHD_destroy_response (r);
+    return 5;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Date"),
+                    "Wed, 01 Apr 2015 00:00:00 GMT"))
+  {
+    MHD_destroy_response (r);
+    return 5;
+  }
+  if (MHD_YES != MHD_add_response_header (r, "Date",
+                                          "Thu, 01 Apr 2021 00:00:00 GMT"))
+  {
+    fprintf (stderr,
+             "Cannot add \"Date\" header with \"Thu, 01 Apr 2021 00:00:00 GMT\".\n");
+    MHD_destroy_response (r);
+    return 5;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Date"),
+                    "Thu, 01 Apr 2021 00:00:00 GMT"))
+  {
+    MHD_destroy_response (r);
+    return 5;
+  }
+  if (MHD_YES != MHD_del_response_header (r, "Date",
+                                          "Thu, 01 Apr 2021 00:00:00 GMT"))
+  {
+    fprintf (stderr, "Cannot remove \"Date\" header.\n");
+    MHD_destroy_response (r);
+    return 5;
+  }
+  if (! expect_str (MHD_get_response_header (r, "Date"), NULL))
+  {
+    MHD_destroy_response (r);
+    return 5;
+  }
+
+  if (MHD_YES != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                          "chunked"))
+  {
+    fprintf (stderr,
+             "Cannot add \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \
+             "\" header with \"chunked\".\n");
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (! expect_str (MHD_get_response_header (r,
+                                             MHD_HTTP_HEADER_TRANSFER_ENCODING),
+                    "chunked"))
+  {
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (MHD_YES != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                          "chunked"))
+  {
+    fprintf (stderr,
+             "Cannot add \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \
+             "\" second header with \"chunked\".\n");
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (! expect_str (MHD_get_response_header (r,
+                                             MHD_HTTP_HEADER_TRANSFER_ENCODING),
+                    "chunked"))
+  {
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (MHD_NO != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                         "identity"))
+  {
+    fprintf (stderr,
+             "Successfully added \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \
+             "\" header with \"identity\".\n");
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (! expect_str (MHD_get_response_header (r,
+                                             MHD_HTTP_HEADER_TRANSFER_ENCODING),
+                    "chunked"))
+  {
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (MHD_YES != MHD_del_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                          "chunked"))
+  {
+    fprintf (stderr, "Cannot remove \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \
+             "\" header.\n");
+    MHD_destroy_response (r);
+    return 6;
+  }
+  if (! expect_str (MHD_get_response_header (r,
+                                             MHD_HTTP_HEADER_TRANSFER_ENCODING),
+                    NULL))
+  {
+    MHD_destroy_response (r);
+    return 6;
+  }
+
+  MHD_destroy_response (r);
+  printf ("All tests has been successfully passed.\n");
+  return 0;
+}
diff --git a/src/microhttpd/test_set_panic.c b/src/microhttpd/test_set_panic.c
new file mode 100644
index 0000000..ac803a2
--- /dev/null
+++ b/src/microhttpd/test_set_panic.c
@@ -0,0 +1,1681 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_set_panic.c
+ * @brief  Testcase for MHD_set_panic_func()
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+#include "MHD_config.h"
+#include "platform.h"
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif /* HAVE_STRINGS_H */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif /* HAVE_SIGNAL_H */
+
+#ifdef HAVE_SYSCTL
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif /* HAVE_SYS_SYSCTL_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif /* HAVE_NETINET_IN_H */
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+#ifdef HAVE_NETINET_IP_ICMP_H
+#include <netinet/ip_icmp.h>
+#endif /* HAVE_NETINET_IP_ICMP_H */
+#ifdef HAVE_NETINET_ICMP_VAR_H
+#include <netinet/icmp_var.h>
+#endif /* HAVE_NETINET_ICMP_VAR_H */
+#endif /* HAVE_SYSCTL */
+
+#include <stdio.h>
+
+#include "mhd_sockets.h" /* only macros used */
+#include "test_helpers.h"
+#include "mhd_assert.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+#if MHD_CPU_COUNT > 32
+#undef MHD_CPU_COUNT
+/* Limit to reasonable value */
+#define MHD_CPU_COUNT 32
+#endif /* MHD_CPU_COUNT > 32 */
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+/* Time in ms to wait for final packets to be delivered */
+#define FINAL_PACKETS_MS 20
+
+#define EXPECTED_URI_BASE_PATH  "/a"
+
+#define REQ_HOST "localhost"
+
+#define REQ_METHOD "PUT"
+
+#define REQ_BODY "Some content data."
+
+#define REQ_LINE_END "\r\n"
+
+/* Mandatory request headers */
+#define REQ_HEADER_HOST_NAME "Host"
+#define REQ_HEADER_HOST_VALUE REQ_HOST
+#define REQ_HEADER_HOST \
+  REQ_HEADER_HOST_NAME ": " REQ_HEADER_HOST_VALUE REQ_LINE_END
+#define REQ_HEADER_UA_NAME "User-Agent"
+#define REQ_HEADER_UA_VALUE "dummyclient/0.9"
+#define REQ_HEADER_UA REQ_HEADER_UA_NAME ": " REQ_HEADER_UA_VALUE REQ_LINE_END
+
+/* Optional request headers */
+#define REQ_HEADER_CT_NAME "Content-Type"
+#define REQ_HEADER_CT_VALUE "text/plain"
+#define REQ_HEADER_CT REQ_HEADER_CT_NAME ": " REQ_HEADER_CT_VALUE REQ_LINE_END
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+#ifndef MHD_POSIX_SOCKETS
+
+/**
+ * Pause execution for specified number of milliseconds.
+ * @param ms the number of milliseconds to sleep
+ */
+static void
+_MHD_sleep (uint32_t ms)
+{
+#if defined(_WIN32)
+  Sleep (ms);
+#elif defined(HAVE_NANOSLEEP)
+  struct timespec slp = {ms / 1000, (ms % 1000) * 1000000};
+  struct timespec rmn;
+  int num_retries = 0;
+  while (0 != nanosleep (&slp, &rmn))
+  {
+    if (EINTR != errno)
+      externalErrorExit ();
+    if (num_retries++ > 8)
+      break;
+    slp = rmn;
+  }
+#elif defined(HAVE_USLEEP)
+  uint64_t us = ms * 1000;
+  do
+  {
+    uint64_t this_sleep;
+    if (999999 < us)
+      this_sleep = 999999;
+    else
+      this_sleep = us;
+    /* Ignore return value as it could be void */
+    usleep (this_sleep);
+    us -= this_sleep;
+  } while (us > 0);
+#else
+  externalErrorExitDesc ("No sleep function available on this system");
+#endif
+}
+
+
+#endif /* ! MHD_POSIX_SOCKETS */
+
+/* Global parameters */
+static int verbose;                 /**< Be verbose */
+static uint16_t global_port;        /**< MHD daemons listen port number */
+
+static void
+test_global_init (void)
+{
+  if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE))
+  {
+#if defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
+    if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
+      externalErrorExitDesc ("Error suppressing SIGPIPE signal");
+#else /* ! HAVE_SIGNAL_H || ! SIGPIPE */
+    fprintf (stderr, "Cannot suppress SIGPIPE signal.\n");
+    /* exit (77); */
+#endif
+  }
+}
+
+
+static void
+test_global_cleanup (void)
+{
+}
+
+
+/**
+ * Change socket to blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+  if ((flags & ~O_NONBLOCK) != flags)
+  {
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      externalErrorExitDesc ("Cannot make socket non-blocking");
+  }
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+/**
+ * Change socket to non-blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_nonblocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+  if ((flags | O_NONBLOCK) != flags)
+  {
+    if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK))
+      externalErrorExitDesc ("Cannot make socket non-blocking");
+  }
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 1;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    externalErrorExitDesc ("Cannot make socket non-blocking");
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+enum _MHD_clientStage
+{
+  DUMB_CLIENT_INIT = 0,
+  DUMB_CLIENT_CONNECTING,
+  DUMB_CLIENT_CONNECTED,
+  DUMB_CLIENT_REQ_SENDING,
+  DUMB_CLIENT_REQ_SENT,
+  DUMB_CLIENT_HEADER_RECVEIVING,
+  DUMB_CLIENT_HEADER_RECVEIVED,
+  DUMB_CLIENT_BODY_RECVEIVING,
+  DUMB_CLIENT_BODY_RECVEIVED,
+  DUMB_CLIENT_FINISHING,
+  DUMB_CLIENT_FINISHED
+};
+
+struct _MHD_dumbClient
+{
+  MHD_socket sckt; /**< the socket to communicate */
+
+  int sckt_nonblock;  /**< non-zero if socket is non-blocking */
+
+  uint16_t port; /**< the port to connect to */
+
+  char *send_buf; /**< the buffer for the request, malloced */
+
+  size_t req_size; /**< the size of the request, including header */
+
+  size_t send_off; /**< the number of bytes already sent */
+
+  enum _MHD_clientStage stage;
+
+  /* the test-specific variables */
+  size_t single_send_size; /**< the maximum number of bytes to be sent by
+                                single send() */
+  size_t send_size_limit;  /**< the total number of send bytes limit */
+};
+
+struct _MHD_dumbClient *
+_MHD_dumbClient_create (uint16_t port, const char *method, const char *url,
+                        const char *add_headers,
+                        const uint8_t *req_body, size_t req_body_size,
+                        int chunked);
+
+
+void
+_MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt,
+                                 size_t step_size, size_t max_total_send);
+
+void
+_MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt);
+
+int
+_MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt);
+
+int
+_MHD_dumbClient_process (struct _MHD_dumbClient *clnt);
+
+void
+_MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt,
+                            MHD_socket *maxsckt,
+                            fd_set *rs, fd_set *ws, fd_set *es);
+
+
+/**
+ * Process the client data with send()/recv() as needed based on
+ * information in fd_sets.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt,
+                                     fd_set *rs, fd_set *ws, fd_set *es);
+
+/**
+ * Perform full request.
+ * @param clnt the client to run
+ * @return zero if client finished processing the request,
+ *         non-zero if timeout is reached.
+ */
+int
+_MHD_dumbClient_perform (struct _MHD_dumbClient *clnt);
+
+
+/**
+ * Close the client and free internally allocated resources.
+ * @param clnt the client to close
+ */
+void
+_MHD_dumbClient_close (struct _MHD_dumbClient *clnt);
+
+
+struct _MHD_dumbClient *
+_MHD_dumbClient_create (uint16_t port, const char *method, const char *url,
+                        const char *add_headers,
+                        const uint8_t *req_body, size_t req_body_size,
+                        int chunked)
+{
+  struct _MHD_dumbClient *clnt;
+  size_t method_size;
+  size_t url_size;
+  size_t add_hdrs_size;
+  size_t buf_alloc_size;
+  char *send_buf;
+
+  mhd_assert (0 != port);
+  mhd_assert (NULL != req_body || 0 == req_body_size);
+  mhd_assert (0 == req_body_size || NULL != req_body);
+
+  clnt = (struct _MHD_dumbClient *) malloc (sizeof(struct _MHD_dumbClient));
+  if (NULL == clnt)
+    externalErrorExit ();
+  memset (clnt, 0, sizeof(struct _MHD_dumbClient));
+  clnt->sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET == clnt->sckt)
+    externalErrorExitDesc ("Cannot create the client socket");
+
+#ifdef MHD_socket_nosignal_
+  if (! MHD_socket_nosignal_ (clnt->sckt))
+    externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket");
+#endif /* MHD_socket_nosignal_ */
+
+  clnt->sckt_nonblock = 0;
+  if (clnt->sckt_nonblock)
+    make_nonblocking (clnt->sckt);
+  else
+    make_blocking (clnt->sckt);
+
+  if (1)
+  { /* Always set TCP NODELAY */
+    const MHD_SCKT_OPT_BOOL_ on_val = 1;
+
+    if (0 != setsockopt (clnt->sckt, IPPROTO_TCP, TCP_NODELAY,
+                         (const void *) &on_val, sizeof (on_val)))
+      externalErrorExitDesc ("Cannot set TCP_NODELAY option");
+  }
+
+  clnt->port = port;
+
+  if (NULL != method)
+    method_size = strlen (method);
+  else
+  {
+    method = MHD_HTTP_METHOD_GET;
+    method_size = MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET);
+  }
+  mhd_assert (0 != method_size);
+  if (NULL != url)
+    url_size = strlen (url);
+  else
+  {
+    url = "/";
+    url_size = 1;
+  }
+  mhd_assert (0 != url_size);
+  add_hdrs_size = (NULL == add_headers) ? 0 : strlen (add_headers);
+  buf_alloc_size = 1024 + method_size + url_size
+                   + add_hdrs_size + req_body_size;
+  send_buf = (char *) malloc (buf_alloc_size);
+  if (NULL == send_buf)
+    externalErrorExit ();
+
+  clnt->req_size = 0;
+  /* Form the request line */
+  memcpy (send_buf + clnt->req_size, method, method_size);
+  clnt->req_size += method_size;
+  send_buf[clnt->req_size++] = ' ';
+  memcpy (send_buf + clnt->req_size, url, url_size);
+  clnt->req_size += url_size;
+  send_buf[clnt->req_size++] = ' ';
+  memcpy (send_buf + clnt->req_size, MHD_HTTP_VERSION_1_1,
+          MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1));
+  clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1);
+  send_buf[clnt->req_size++] = '\r';
+  send_buf[clnt->req_size++] = '\n';
+  /* Form the header */
+  memcpy (send_buf + clnt->req_size, REQ_HEADER_HOST,
+          MHD_STATICSTR_LEN_ (REQ_HEADER_HOST));
+  clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_HOST);
+  memcpy (send_buf + clnt->req_size, REQ_HEADER_UA,
+          MHD_STATICSTR_LEN_ (REQ_HEADER_UA));
+  clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_UA);
+  if ((NULL != req_body) || chunked)
+  {
+    if (! chunked)
+    {
+      int prn_size;
+
+      memcpy (send_buf + clnt->req_size,
+              MHD_HTTP_HEADER_CONTENT_LENGTH ": ",
+              MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "));
+      clnt->req_size +=
+        MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ");
+      prn_size = snprintf (send_buf + clnt->req_size,
+                           (buf_alloc_size - clnt->req_size),
+                           "%u", (unsigned int) req_body_size);
+      if (0 >= prn_size)
+        externalErrorExit ();
+      if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size)
+        externalErrorExit ();
+      clnt->req_size += (unsigned int) prn_size;
+      send_buf[clnt->req_size++] = '\r';
+      send_buf[clnt->req_size++] = '\n';
+    }
+    else
+    {
+      memcpy (send_buf + clnt->req_size,
+              MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked\r\n",
+              MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \
+                                  ": chunked\r\n"));
+      clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \
+                                            ": chunked\r\n");
+    }
+  }
+  if (0 != add_hdrs_size)
+  {
+    memcpy (send_buf + clnt->req_size, add_headers, add_hdrs_size);
+    clnt->req_size += add_hdrs_size;
+  }
+  /* Terminate header */
+  send_buf[clnt->req_size++] = '\r';
+  send_buf[clnt->req_size++] = '\n';
+
+  /* Add body (if any) */
+  if (! chunked)
+  {
+    if (0 != req_body_size)
+    {
+      memcpy (send_buf + clnt->req_size, req_body, req_body_size);
+      clnt->req_size += req_body_size;
+    }
+  }
+  else
+  {
+    if (0 != req_body_size)
+    {
+      int prn_size;
+      prn_size = snprintf (send_buf + clnt->req_size,
+                           (buf_alloc_size - clnt->req_size),
+                           "%x", (unsigned int) req_body_size);
+      if (0 >= prn_size)
+        externalErrorExit ();
+      if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size)
+        externalErrorExit ();
+      clnt->req_size += (unsigned int) prn_size;
+      send_buf[clnt->req_size++] = '\r';
+      send_buf[clnt->req_size++] = '\n';
+      memcpy (send_buf + clnt->req_size, req_body, req_body_size);
+      clnt->req_size += req_body_size;
+      send_buf[clnt->req_size++] = '\r';
+      send_buf[clnt->req_size++] = '\n';
+    }
+    send_buf[clnt->req_size++] = '0';
+    send_buf[clnt->req_size++] = '\r';
+    send_buf[clnt->req_size++] = '\n';
+    send_buf[clnt->req_size++] = '\r';
+    send_buf[clnt->req_size++] = '\n';
+  }
+  mhd_assert (clnt->req_size < buf_alloc_size);
+  clnt->send_buf = send_buf;
+
+  return clnt;
+}
+
+
+void
+_MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt,
+                                 size_t step_size, size_t max_total_send)
+{
+  clnt->single_send_size = step_size;
+  clnt->send_size_limit = max_total_send;
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_connect_init (struct _MHD_dumbClient *clnt)
+{
+  struct sockaddr_in sa;
+  mhd_assert (DUMB_CLIENT_INIT == clnt->stage);
+
+  sa.sin_family = AF_INET;
+  sa.sin_port = htons (clnt->port);
+  sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+
+  if (0 != connect (clnt->sckt, (struct sockaddr *) &sa, sizeof(sa)))
+  {
+    const int err = MHD_socket_get_error_ ();
+    if ( (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_)) ||
+         (MHD_SCKT_ERR_IS_EAGAIN_ (err)))
+      clnt->stage = DUMB_CLIENT_CONNECTING;
+    else
+      externalErrorExitDesc ("Cannot 'connect()' the client socket");
+  }
+  else
+    clnt->stage = DUMB_CLIENT_CONNECTED;
+}
+
+
+void
+_MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt)
+{
+  mhd_assert (DUMB_CLIENT_INIT == clnt->stage);
+  _MHD_dumbClient_connect_init (clnt);
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_connect_finish (struct _MHD_dumbClient *clnt)
+{
+  int err = 0;
+  socklen_t err_size = sizeof(err);
+  mhd_assert (DUMB_CLIENT_CONNECTING == clnt->stage);
+  if (0 != getsockopt (clnt->sckt, SOL_SOCKET, SO_ERROR,
+                       (void *) &err, &err_size))
+    externalErrorExitDesc ("'getsockopt()' call failed");
+  if (0 != err)
+    externalErrorExitDesc ("Socket connect() failed");
+  clnt->stage = DUMB_CLIENT_CONNECTED;
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_send_req (struct _MHD_dumbClient *clnt)
+{
+  size_t send_size;
+  ssize_t res;
+  mhd_assert (DUMB_CLIENT_CONNECTED <= clnt->stage);
+  mhd_assert (DUMB_CLIENT_REQ_SENT > clnt->stage);
+  mhd_assert (clnt->req_size > clnt->send_off);
+
+  send_size = (((0 != clnt->send_size_limit) &&
+                (clnt->req_size > clnt->send_size_limit)) ?
+               clnt->send_size_limit : clnt->req_size) - clnt->send_off;
+  mhd_assert (0 != send_size);
+  if ((0 != clnt->single_send_size) &&
+      (clnt->single_send_size < send_size))
+    send_size = clnt->single_send_size;
+
+  res = MHD_send_ (clnt->sckt, clnt->send_buf + clnt->send_off, send_size);
+
+  if (res < 0)
+  {
+    const int err = MHD_socket_get_error_ ();
+    if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
+      return;
+    if (MHD_SCKT_ERR_IS_EINTR_ (err))
+      return;
+    if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+      mhdErrorExitDesc ("The connection was aborted by MHD");
+    if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_))
+      mhdErrorExitDesc ("The connection was shut down on MHD side");
+    externalErrorExitDesc ("Unexpected network error");
+  }
+  clnt->send_off += (size_t) res;
+  mhd_assert (clnt->send_off <= clnt->req_size);
+  mhd_assert (clnt->send_off <= clnt->send_size_limit || \
+              0 == clnt->send_size_limit);
+  if (clnt->req_size == clnt->send_off)
+    clnt->stage = DUMB_CLIENT_REQ_SENT;
+  if ((0 != clnt->send_size_limit) &&
+      (clnt->send_size_limit == clnt->send_off))
+    clnt->stage = DUMB_CLIENT_FINISHING;
+}
+
+
+/* internal */
+_MHD_NORETURN /* not implemented */
+static void
+_MHD_dumbClient_recv_reply (struct _MHD_dumbClient *clnt)
+{
+  (void) clnt;
+  externalErrorExitDesc ("Not implemented for this test");
+}
+
+
+int
+_MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt)
+{
+  return DUMB_CLIENT_REQ_SENT <= clnt->stage;
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_socket_close (struct _MHD_dumbClient *clnt)
+{
+  if (MHD_INVALID_SOCKET != clnt->sckt)
+  {
+    if (! MHD_socket_close_ (clnt->sckt))
+      externalErrorExitDesc ("Unexpected error while closing " \
+                             "the client socket");
+    clnt->sckt = MHD_INVALID_SOCKET;
+  }
+}
+
+
+/* internal */
+static void
+_MHD_dumbClient_finalize (struct _MHD_dumbClient *clnt)
+{
+  if (MHD_INVALID_SOCKET != clnt->sckt)
+  {
+    if (0 != shutdown (clnt->sckt, SHUT_WR))
+    {
+      const int err = MHD_socket_get_error_ ();
+      if (! MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_) &&
+          ! MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err))
+        mhdErrorExitDesc ("Unexpected error when shutting down " \
+                          "the client socket");
+    }
+  }
+  clnt->stage = DUMB_CLIENT_FINISHED;
+}
+
+
+/* internal */
+static int
+_MHD_dumbClient_needs_send (const struct _MHD_dumbClient *clnt)
+{
+  return ((DUMB_CLIENT_CONNECTING <= clnt->stage) &&
+          (DUMB_CLIENT_REQ_SENT > clnt->stage)) ||
+         (DUMB_CLIENT_FINISHING == clnt->stage);
+}
+
+
+/* internal */
+static int
+_MHD_dumbClient_needs_recv (const struct _MHD_dumbClient *clnt)
+{
+  return (DUMB_CLIENT_HEADER_RECVEIVING <= clnt->stage) &&
+         (DUMB_CLIENT_BODY_RECVEIVED > clnt->stage);
+}
+
+
+/* internal */
+/**
+ * Check whether the client needs unconditionally process the data.
+ * @param clnt the client to check
+ * @return non-zero if client needs unconditionally process the data,
+ *         zero otherwise.
+ */
+static int
+_MHD_dumbClient_needs_process (const struct _MHD_dumbClient *clnt)
+{
+  switch (clnt->stage)
+  {
+  case DUMB_CLIENT_INIT:
+  case DUMB_CLIENT_REQ_SENT:
+  case DUMB_CLIENT_HEADER_RECVEIVED:
+  case DUMB_CLIENT_BODY_RECVEIVED:
+  case DUMB_CLIENT_FINISHED:
+    return ! 0;
+  case DUMB_CLIENT_CONNECTING:
+  case DUMB_CLIENT_CONNECTED:
+  case DUMB_CLIENT_REQ_SENDING:
+  case DUMB_CLIENT_HEADER_RECVEIVING:
+  case DUMB_CLIENT_BODY_RECVEIVING:
+  case DUMB_CLIENT_FINISHING:
+  default:
+    return 0;
+  }
+  return 0; /* Should be unreachable */
+}
+
+
+/**
+ * Process the client data with send()/recv() as needed.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process (struct _MHD_dumbClient *clnt)
+{
+  do
+  {
+    switch (clnt->stage)
+    {
+    case DUMB_CLIENT_INIT:
+      _MHD_dumbClient_connect_init (clnt);
+      break;
+    case DUMB_CLIENT_CONNECTING:
+      _MHD_dumbClient_connect_finish (clnt);
+      break;
+    case DUMB_CLIENT_CONNECTED:
+    case DUMB_CLIENT_REQ_SENDING:
+      _MHD_dumbClient_send_req (clnt);
+      break;
+    case DUMB_CLIENT_REQ_SENT:
+      mhd_assert (0);
+      clnt->stage = DUMB_CLIENT_HEADER_RECVEIVING;
+      break;
+    case DUMB_CLIENT_HEADER_RECVEIVING:
+      _MHD_dumbClient_recv_reply (clnt);
+      break;
+    case DUMB_CLIENT_HEADER_RECVEIVED:
+      clnt->stage = DUMB_CLIENT_BODY_RECVEIVING;
+      break;
+    case DUMB_CLIENT_BODY_RECVEIVING:
+      _MHD_dumbClient_recv_reply (clnt);
+      break;
+    case DUMB_CLIENT_BODY_RECVEIVED:
+      clnt->stage = DUMB_CLIENT_FINISHING;
+      break;
+    case DUMB_CLIENT_FINISHING:
+      _MHD_dumbClient_finalize (clnt);
+      break;
+    case DUMB_CLIENT_FINISHED:
+      return ! 0;
+    default:
+      mhd_assert (0);
+      mhdErrorExit ();
+    }
+  } while (_MHD_dumbClient_needs_process (clnt));
+  return DUMB_CLIENT_FINISHED == clnt->stage;
+}
+
+
+void
+_MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt,
+                            MHD_socket *maxsckt,
+                            fd_set *rs, fd_set *ws, fd_set *es)
+{
+  mhd_assert (NULL != rs);
+  mhd_assert (NULL != ws);
+  mhd_assert (NULL != es);
+  if (DUMB_CLIENT_FINISHED > clnt->stage)
+  {
+    if (MHD_INVALID_SOCKET != clnt->sckt)
+    {
+      if ( (MHD_INVALID_SOCKET == *maxsckt) ||
+           (clnt->sckt > *maxsckt) )
+        *maxsckt = clnt->sckt;
+      if (_MHD_dumbClient_needs_recv (clnt))
+        FD_SET (clnt->sckt, rs);
+      if (_MHD_dumbClient_needs_send (clnt))
+        FD_SET (clnt->sckt, ws);
+      FD_SET (clnt->sckt, es);
+    }
+  }
+}
+
+
+/**
+ * Process the client data with send()/recv() as needed based on
+ * information in fd_sets.
+ * @param clnt the client to process
+ * @return non-zero if client finished processing the request,
+ *         zero otherwise.
+ */
+int
+_MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt,
+                                     fd_set *rs, fd_set *ws, fd_set *es)
+{
+  if (_MHD_dumbClient_needs_process (clnt))
+    return _MHD_dumbClient_process (clnt);
+  else if (MHD_INVALID_SOCKET != clnt->sckt)
+  {
+    if (_MHD_dumbClient_needs_recv (clnt) && FD_ISSET (clnt->sckt, rs))
+      return _MHD_dumbClient_process (clnt);
+    else if (_MHD_dumbClient_needs_send (clnt) && FD_ISSET (clnt->sckt, ws))
+      return _MHD_dumbClient_process (clnt);
+    else if (FD_ISSET (clnt->sckt, es))
+      return _MHD_dumbClient_process (clnt);
+  }
+  return DUMB_CLIENT_FINISHED == clnt->stage;
+}
+
+
+/**
+ * Perform full request.
+ * @param clnt the client to run
+ * @return zero if client finished processing the request,
+ *         non-zero if timeout is reached.
+ */
+int
+_MHD_dumbClient_perform (struct _MHD_dumbClient *clnt)
+{
+  time_t start;
+  time_t now;
+  start = time (NULL);
+  now = start;
+  do
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    struct timeval tv;
+
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+
+    if (! _MHD_dumbClient_needs_process (clnt))
+    {
+      maxMhdSk = MHD_INVALID_SOCKET;
+      _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es);
+      mhd_assert (now >= start);
+#ifndef _WIN32
+      tv.tv_sec = (time_t) (TIMEOUTS_VAL * 2 - (now - start) + 1);
+#else
+      tv.tv_sec = (long) (TIMEOUTS_VAL * 2 - (now - start) + 1);
+#endif
+      tv.tv_usec = 250 * 1000;
+      if (-1 == select ((int) (maxMhdSk + 1), &rs, &ws, &es, &tv))
+      {
+#ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+          externalErrorExitDesc ("Unexpected select() error");
+#else  /* ! MHD_POSIX_SOCKETS */
+        mhd_assert ((0 != rs.fd_count) || (0 != ws.fd_count) || \
+                    (0 != es.fd_count));
+        externalErrorExitDesc ("Unexpected select() error");
+        _MHD_sleep ((uint32_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
+#endif /* ! MHD_POSIX_SOCKETS */
+        continue;
+      }
+      if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es))
+        return 0;
+    }
+    /* Use double timeout value here as MHD must catch timeout situations
+     * in this test. Timeout in client as a last resort. */
+  } while ((now = time (NULL)) - start <= (TIMEOUTS_VAL * 2));
+  return 1;
+}
+
+
+/**
+ * Close the client and free internally allocated resources.
+ * @param clnt the client to close
+ */
+void
+_MHD_dumbClient_close (struct _MHD_dumbClient *clnt)
+{
+  if (DUMB_CLIENT_FINISHED != clnt->stage)
+    _MHD_dumbClient_finalize (clnt);
+  _MHD_dumbClient_socket_close (clnt);
+  if (NULL != clnt->send_buf)
+  {
+    free ((void *) clnt->send_buf);
+    clnt->send_buf = NULL;
+  }
+  free (clnt);
+}
+
+
+_MHD_NORETURN static void
+socket_cb (void *cls,
+           struct MHD_Connection *c,
+           void **socket_context,
+           enum MHD_ConnectionNotificationCode toe)
+{
+  (void) cls;            /* Unused */
+  (void) socket_context; /* Unused */
+  (void) toe;            /* Unused */
+
+  MHD_suspend_connection (c); /* Should trigger panic */
+  mhdErrorExitDesc ("Function \"MHD_suspend_connection()\" succeed, while " \
+                    "it must fail as daemon was started without MHD_ALLOW_SUSPEND_RESUME " \
+                    "flag");
+}
+
+
+struct ahc_cls_type
+{
+  const char *volatile rp_data;
+  volatile size_t rp_data_size;
+  const char *volatile rq_method;
+  const char *volatile rq_url;
+  const char *volatile req_body;
+  volatile unsigned int cb_called; /* Non-zero indicates that callback was called at least one time */
+  size_t req_body_size; /**< The number of bytes in @a req_body */
+  size_t req_body_uploaded; /* Updated by callback */
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int marker;
+  enum MHD_Result ret;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+  (void) connection; /* Unused */
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+  param->cb_called++;
+
+  if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+    mhdErrorExitDesc ("Unexpected HTTP version");
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+  {
+    const char *const upload_body = param->req_body;
+    if (NULL == upload_data)
+      mhdErrorExitDesc ("'upload_data' is NULL while " \
+                        "'*upload_data_size' value is not zero");
+    if (NULL == upload_body)
+      mhdErrorExitDesc ("'*upload_data_size' value is not zero " \
+                        "while no request body is expected");
+    if (param->req_body_uploaded + *upload_data_size > param->req_body_size)
+    {
+      fprintf (stderr, "Too large upload body received. Got %u, expected %u",
+               (unsigned int) (param->req_body_uploaded + *upload_data_size),
+               (unsigned int) param->req_body_size);
+      mhdErrorExit ();
+    }
+    if (0 != memcmp (upload_data, upload_body + param->req_body_uploaded,
+                     *upload_data_size))
+    {
+      fprintf (stderr, "Unexpected request body at offset %u: " \
+               "'%.*s', expected: '%.*s'\n",
+               (unsigned int) param->req_body_uploaded,
+               (int) *upload_data_size, upload_data,
+               (int) *upload_data_size, upload_body + param->req_body_uploaded);
+      mhdErrorExit ();
+    }
+    param->req_body_uploaded += *upload_data_size;
+    *upload_data_size = 0;
+  }
+
+  if (&marker != *req_cls)
+  {
+    /* The first call of the callback for this connection */
+    mhd_assert (NULL == upload_data);
+    param->req_body_uploaded = 0;
+
+    *req_cls = &marker;
+    return MHD_YES;
+  }
+
+  if (NULL != upload_data)
+    return MHD_YES; /* Full request has not been received so far */
+
+#if 0 /* Code unused in this test */
+  struct MHD_Response *response;
+  response = MHD_create_response_from_buffer (param->rp_data_size,
+                                              (void *) param->rp_data,
+                                              MHD_RESPMEM_MUST_COPY);
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+#else
+  if (NULL == upload_data)
+    mhdErrorExitDesc ("Full request received, " \
+                      "while incomplete request expected");
+  ret = MHD_NO;
+#endif
+
+  return ret;
+}
+
+
+struct simpleQueryParams
+{
+  /* Destination path for HTTP query */
+  const char *queryPath;
+
+  /* Custom query method, NULL for default */
+  const char *method;
+
+  /* Destination port for HTTP query */
+  uint16_t queryPort;
+
+  /* Additional request headers, static */
+  const char *headers;
+
+  /* NULL for request without body */
+  const uint8_t *req_body;
+  size_t req_body_size;
+
+  /* Non-zero to use chunked encoding for request body */
+  int chunked;
+
+  /* HTTP query result error flag */
+  volatile int queryError;
+
+  /* Response HTTP code, zero if no response */
+  volatile int responseCode;
+};
+
+
+/* returns non-zero if timed-out */
+static int
+performQueryExternal (struct MHD_Daemon *d, struct _MHD_dumbClient *clnt)
+{
+  time_t start;
+  struct timeval tv;
+  int ret;
+  const union MHD_DaemonInfo *di;
+  MHD_socket lstn_sk;
+  int client_accepted;
+  int full_req_recieved;
+  int full_req_sent;
+  int some_data_recieved;
+
+  di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
+  if (NULL == di)
+    mhdErrorExitDesc ("Cannot get listener socket");
+  lstn_sk = di->listen_fd;
+
+  ret = 1; /* will be replaced with real result */
+  client_accepted = 0;
+
+  _MHD_dumbClient_start_connect (clnt);
+
+  full_req_recieved = 0;
+  some_data_recieved = 0;
+  start = time (NULL);
+  do
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int num_ready;
+    int do_client; /**< Process data in client */
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL == clnt)
+    {
+      /* client has finished, check whether MHD is still
+       * processing any connections */
+      full_req_sent = 1;
+      do_client = 0;
+      if (client_accepted && (0 > MHD_get_timeout64s (d)))
+      {
+        ret = 0;
+        break; /* MHD finished as well */
+      }
+    }
+    else
+    {
+      full_req_sent = _MHD_dumbClient_is_req_sent (clnt);
+      if (! full_req_sent)
+        do_client = 1; /* Request hasn't been sent yet, send the data */
+      else
+      {
+        /* All request data has been sent.
+         * Client will close the socket as the next step. */
+        if (full_req_recieved)
+          do_client = 1; /* All data has been received by the MHD */
+        else if (some_data_recieved)
+        {
+          /* at least something was received by the MHD */
+          do_client = 1;
+        }
+        else
+        {
+          /* The MHD must receive at least something before closing
+           * the connection. */
+          do_client = 0;
+        }
+      }
+
+      if (do_client)
+        _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es);
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    if (do_client)
+    {
+      tv.tv_sec = 1;
+      tv.tv_usec = 250 * 1000;
+    }
+    else
+    { /* Request completely sent but not yet fully received */
+      tv.tv_sec = 0;
+      tv.tv_usec = FINAL_PACKETS_MS * 1000;
+    }
+    num_ready = select ((int) (maxMhdSk + 1), &rs, &ws, &es, &tv);
+    if (-1 == num_ready)
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      _MHD_sleep ((uint32_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
+#endif
+      continue;
+    }
+    if (0 == num_ready)
+    { /* select() finished by timeout, looks like no more packets are pending */
+      if (do_client)
+        externalErrorExitDesc ("Timeout waiting for sockets");
+      if (full_req_sent && (! full_req_recieved))
+        full_req_recieved = 1;
+    }
+    if (full_req_recieved)
+      mhdErrorExitDesc ("Full request has been received by MHD, while it "
+                        "must be aborted by the panic function");
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+    if (! client_accepted)
+      client_accepted = FD_ISSET (lstn_sk, &rs);
+    else
+    { /* Client connection was already accepted by MHD */
+      if (! some_data_recieved)
+      {
+        if (! do_client)
+        {
+          if (0 != num_ready)
+          { /* Connection was accepted before, "ready" socket means data */
+            some_data_recieved = 1;
+          }
+        }
+        else
+        {
+          if (2 == num_ready)
+            some_data_recieved = 1;
+          else if ((1 == num_ready) &&
+                   ((MHD_INVALID_SOCKET == clnt->sckt) ||
+                    ! FD_ISSET (clnt->sckt, &ws)))
+            some_data_recieved = 1;
+        }
+      }
+    }
+    if (do_client)
+    {
+      if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es))
+        clnt = NULL;
+    }
+    /* Use double timeout value here so MHD would be able to catch timeout
+     * internally */
+  } while (time (NULL) - start <= (TIMEOUTS_VAL * 2));
+
+  return ret;
+}
+
+
+/* Returns zero for successful response and non-zero for failed response */
+static int
+doClientQueryInThread (struct MHD_Daemon *d,
+                       struct simpleQueryParams *p)
+{
+  const union MHD_DaemonInfo *dinfo;
+  struct _MHD_dumbClient *c;
+  int errornum;
+  int use_external_poll;
+
+  dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  use_external_poll = (0 == (dinfo->flags
+                             & MHD_USE_INTERNAL_POLLING_THREAD));
+
+  if (0 == p->queryPort)
+    externalErrorExit ();
+
+  c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath,
+                              p->headers, p->req_body, p->req_body_size,
+                              p->chunked);
+  _MHD_dumbClient_set_send_limits (c, 1, 0);
+
+  /* 'internal' polling should not be used in this test */
+  mhd_assert (use_external_poll);
+  if (! use_external_poll)
+    errornum = _MHD_dumbClient_perform (c);
+  else
+    errornum = performQueryExternal (d, c);
+
+  if (errornum)
+    fprintf (stderr, "Request timeout out.\n");
+  else
+    mhdErrorExitDesc ("Request succeed, but it must fail");
+
+  _MHD_dumbClient_close (c);
+
+  return errornum;
+}
+
+
+/* Perform test queries, shut down MHD daemon, and free parameters */
+static unsigned int
+performTestQueries (struct MHD_Daemon *d, uint16_t d_port,
+                    struct ahc_cls_type *ahc_param)
+{
+  struct simpleQueryParams qParam;
+
+  /* Common parameters, to be individually overridden by specific test cases
+   * if needed */
+  qParam.queryPort = d_port;
+  qParam.method = MHD_HTTP_METHOD_PUT;
+  qParam.queryPath = EXPECTED_URI_BASE_PATH;
+  qParam.headers = REQ_HEADER_CT;
+  qParam.req_body = (const uint8_t *) REQ_BODY;
+  qParam.req_body_size = MHD_STATICSTR_LEN_ (REQ_BODY);
+  qParam.chunked = 0;
+
+  ahc_param->rq_url = EXPECTED_URI_BASE_PATH;
+  ahc_param->rq_method = MHD_HTTP_METHOD_PUT;
+  ahc_param->rp_data = "~";
+  ahc_param->rp_data_size = 1;
+  ahc_param->req_body = (const char *) qParam.req_body;
+  ahc_param->req_body_size = qParam.req_body_size;
+
+  /* Make sure that maximum size is tested */
+  /* To be updated by callbacks */
+  ahc_param->cb_called = 0;
+
+  if (0 != doClientQueryInThread (d, &qParam))
+    fprintf (stderr, "FAILED: client query failed.");
+
+  MHD_stop_daemon (d);
+  free (ahc_param);
+
+  return 1; /* Always error if reached this point */
+}
+
+
+enum testMhdThreadsType
+{
+  testMhdThreadExternal              = 0,
+  testMhdThreadInternal              = MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION
+                                       | MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPool
+};
+
+enum testMhdPollType
+{
+  testMhdPollBySelect = 0,
+  testMhdPollByPoll   = MHD_USE_POLL,
+  testMhdPollByEpoll  = MHD_USE_EPOLL,
+  testMhdPollAuto     = MHD_USE_AUTO
+};
+
+/* Get number of threads for thread pool depending
+ * on used poll function and test type. */
+static unsigned int
+testNumThreadsForPool (enum testMhdPollType pollType)
+{
+  unsigned int numThreads = MHD_CPU_COUNT;
+  (void) pollType; /* Don't care about pollType for this test */
+  return numThreads; /* No practical limit for non-cleanup test */
+}
+
+
+#define PANIC_MAGIC_CHECK 1133
+
+_MHD_NORETURN static void
+myPanicCallback (void *cls,
+                 const char *file,
+                 unsigned int line,
+                 const char *reason)
+{
+  int *const param = (int *) cls;
+  if (NULL == cls)
+    mhdErrorExitDesc ("The 'cls' parameter is NULL");
+  if (PANIC_MAGIC_CHECK != *param)
+    mhdErrorExitDesc ("Wrong '*cls' value");
+#ifdef HAVE_MESSAGES
+  if (NULL == file)
+    mhdErrorExitDesc ("The 'file' parameter is NULL");
+  if (NULL == reason)
+    mhdErrorExitDesc ("The 'reason' parameter is NULL");
+#else  /* ! HAVE_MESSAGES */
+  if (NULL != file)
+    mhdErrorExitDesc ("The 'file' parameter is not NULL");
+  if (NULL != reason)
+    mhdErrorExitDesc ("The 'reason' parameter is not NULL");
+#endif /* ! HAVE_MESSAGES */
+  fflush (stderr);
+  fflush (stdout);
+  printf ("User panic function has been called from file '%s' at line '%u' "
+          "with the reason:\n%s", file, line,
+          ((NULL != reason) ? reason : "(NULL)\n"));
+  fflush (stdout);
+  exit (0);
+}
+
+
+static struct MHD_Daemon *
+startTestMhdDaemon (enum testMhdThreadsType thrType,
+                    enum testMhdPollType pollType, uint16_t *pport,
+                    struct ahc_cls_type **ahc_param)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *dinfo;
+  static int magic_panic_param = PANIC_MAGIC_CHECK;
+
+  if (NULL == ahc_param)
+    externalErrorExit ();
+
+  *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type));
+  if (NULL == *ahc_param)
+    externalErrorExit ();
+
+  if ( (0 == *pport) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    *pport = 4190;
+  }
+
+  MHD_set_panic_func (&myPanicCallback, (void *) &magic_panic_param);
+
+  if (testMhdThreadInternalPool != thrType)
+    d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_NOTIFY_CONNECTION, &socket_cb,
+                          NULL,
+                          MHD_OPTION_CONNECTION_TIMEOUT,
+                          (unsigned) TIMEOUTS_VAL,
+                          MHD_OPTION_END);
+  else
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                          | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          testNumThreadsForPool (pollType),
+                          MHD_OPTION_NOTIFY_CONNECTION, &socket_cb,
+                          NULL,
+                          MHD_OPTION_CONNECTION_TIMEOUT,
+                          (unsigned) TIMEOUTS_VAL,
+                          MHD_OPTION_END);
+
+  if (NULL == d)
+    mhdErrorExitDesc ("Failed to start MHD daemon");
+
+  if (0 == *pport)
+  {
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port))
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    *pport = dinfo->port;
+    if (0 == global_port)
+      global_port = *pport; /* Reuse the same port for all tests */
+  }
+
+  return d;
+}
+
+
+/* Test runners */
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+
+  d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port,
+                          &ahc_param);
+
+  return performTestQueries (d, d_port, ahc_param);
+}
+
+
+#if 0 /* disabled runners, not suitable for this test */
+static unsigned int
+testInternalGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port,
+                          &ahc_param, &uri_cb_param, &term_result);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result);
+}
+
+
+static int
+testMultithreadedGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result);
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+  struct term_notif_cb_param *term_result;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result);
+}
+
+
+#endif /* disabled runners, not suitable for this test */
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  verbose = 0;
+
+  (void) has_in_name; /* Unused, mute compiler warning */
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+
+  test_global_init ();
+
+  /* Could be set to non-zero value to enforce using specific port
+   * in the test */
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet (). Result: %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+#if 0 /* disabled runners, not suitable for this test */
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result = testInternalGet (testMhdPollAuto);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+#ifdef _MHD_HEAVY_TESTS
+    /* Actually tests are not heavy, but took too long to complete while
+     * not really provide any additional results. */
+    test_result = testInternalGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedPoolGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedPoolGet (testMhdPollBySelect). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedGet (testMhdPollBySelect). "
+               "Result: %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result = testInternalGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll). "
+                 "Result: %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result = testInternalGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll). "
+                 "Result: %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+    }
+#else
+    /* Mute compiler warnings */
+    (void) testMultithreadedGet;
+    (void) testMultithreadedPoolGet;
+#endif /* _MHD_HEAVY_TESTS */
+  }
+#endif /* disabled runners, not suitable for this test */
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+
+  test_global_cleanup ();
+
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/microhttpd/test_sha1.c b/src/microhttpd/test_sha1.c
new file mode 100644
index 0000000..3d412c2
--- /dev/null
+++ b/src/microhttpd/test_sha1.c
@@ -0,0 +1,418 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2019-2021 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_sha1.h
+ * @brief  Unit tests for SHA-1 functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "sha1.h"
+#include "test_helpers.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int verbose = 0; /* verbose level (0-1)*/
+
+
+struct str_with_len
+{
+  const char *const str;
+  const size_t len;
+};
+
+#define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1}
+
+struct data_unit1
+{
+  const struct str_with_len str_l;
+  const uint8_t digest[SHA1_DIGEST_SIZE];
+};
+
+static const struct data_unit1 data_units1[] = {
+  {D_STR_W_LEN ("abc"),
+   {0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71,
+    0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D}},
+  {D_STR_W_LEN ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
+   {0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, 0x4A, 0xA1,
+    0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1}},
+  {D_STR_W_LEN (""),
+   {0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef,
+    0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09}},
+  {D_STR_W_LEN ("The quick brown fox jumps over the lazy dog"),
+   {0x2f, 0xd4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc, 0xed, 0x84, 0x9e, 0xe1,
+    0xbb, 0x76, 0xe7, 0x39, 0x1b, 0x93, 0xeb, 0x12}},
+  {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."),
+   {0xa7, 0x08, 0x9e, 0x3d, 0xe1, 0x6b, 0x63, 0xa3, 0x2a, 0x43, 0xa5, 0xe7,
+    0xf3, 0xb5, 0x4f, 0x80, 0x6a, 0xc8, 0x4f, 0x53}},
+  {D_STR_W_LEN ("Simple string."),
+   {0x6c, 0x6c, 0x9c, 0xef, 0x53, 0xff, 0x22, 0x39, 0x0c, 0x54, 0xc7, 0xba,
+    0x6d, 0x98, 0xe0, 0xd5, 0x6c, 0x24, 0x0d, 0x55}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"),
+   {0x32, 0xd1, 0x0c, 0x7b, 0x8c, 0xf9, 0x65, 0x70, 0xca, 0x04, 0xce, 0x37,
+    0xf2, 0xa1, 0x9d, 0x84, 0x24, 0x0d, 0x3a, 0x89}},
+  {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"),
+   {0x59, 0x0f, 0xc8, 0xea, 0xde, 0xa2, 0x78, 0x65, 0x5a, 0xf2, 0xa1, 0xe5,
+    0xb4, 0xc9, 0x61, 0xa4, 0x3a, 0xc3, 0x6a, 0x83}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"
+                "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"),
+   {0xa7, 0x87, 0x4c, 0x16, 0xc0, 0x4e, 0xd6, 0x24, 0x5f, 0x25, 0xbe, 0x06,
+    0x7b, 0x1b, 0x6b, 0xaf, 0xf4, 0x0e, 0x74, 0x0b}},
+};
+
+static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]);
+
+struct bin_with_len
+{
+  const uint8_t bin[512];
+  const size_t len;
+};
+
+struct data_unit2
+{
+  const struct bin_with_len bin_l;
+  const uint8_t digest[SHA1_DIGEST_SIZE];
+};
+
+/* Size must be less than 512 bytes! */
+static const struct data_unit2 data_units2[] = {
+  { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+       112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */
+    {0x32, 0xd1, 0x0c, 0x7b, 0x8c, 0xf9, 0x65, 0x70, 0xca, 0x04, 0xce, 0x37,
+     0xf2, 0xa1, 0x9d, 0x84, 0x24, 0x0d, 0x3a, 0x89}},
+  { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65},
+      72 }, /* 'A' x 72 times */
+    {0x41, 0xf9, 0x07, 0x05, 0x04, 0xf9, 0xc8, 0x1a, 0xbf, 0xbb, 0x61, 0x4d,
+     0xaa, 0xec, 0x3b, 0x26, 0xa2, 0xf9, 0x23, 0x7e}},
+  { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
+       37, 38, 39, 40, 41, 42,43, 44, 45, 46, 47, 48, 49, 50, 51, 52,53, 54,
+       55, 56, 57, 58, 59, 60,61, 62, 63, 64, 65, 66, 67,68, 69, 70, 71, 72,
+       73}, 55}, /* 19..73 sequence */
+    {0xf2, 0x50, 0xb2, 0x79, 0x62, 0xcc, 0xff, 0x4b, 0x1b, 0x61, 0x4a, 0x6f,
+     0x80, 0xec, 0x9b, 0x4d, 0xd0, 0xc0, 0xfb, 0x7b}},
+  { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+       26, 27, 28, 29, 30, 31,32, 33, 34, 35, 36, 37, 38, 39, 40, 41,42, 43,
+       44, 45, 46, 47, 48, 49,50, 51, 52, 53, 54, 55, 56,57, 58, 59, 60, 61,
+       62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */
+    {0xf0, 0xa3, 0xfc, 0x4b, 0x90, 0x6f, 0x1b, 0x41, 0x68, 0xc8, 0x3e, 0x05,
+     0xb0, 0xc5, 0xac, 0xb7, 0x3d, 0xcd, 0x6b, 0x0f}},
+  { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
+       56, 57, 58, 59, 60, 61,62, 63, 64, 65, 66, 67, 68, 69, 70, 71,72, 73,
+       74, 75, 76, 77, 78, 79,80, 81, 82, 83, 84, 85, 86,87, 88, 89, 90, 91,
+       92}, 55},  /* 38..92 sequence */
+    {0x93, 0xa4, 0x9c, 0x5f, 0xda, 0x22, 0x63, 0x73, 0x85, 0xeb, 0x70, 0xd2,
+     0x00, 0x52, 0x0c, 0xb0, 0x2e, 0x86, 0x9b, 0xa0 }},
+  { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,21,
+       22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,37, 38, 39,
+       40, 41, 42, 43, 44, 45,46, 47, 48, 49, 50, 51, 52,53, 54, 55, 56, 57,
+       58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,71, 72},72}, /* 1..72 sequence */
+    {0x8b, 0x30, 0xd3, 0x41, 0x89, 0xb6, 0x1b, 0x66, 0x5a, 0x1a, 0x9a, 0x51,
+     0x64, 0x93, 0xab, 0x5e, 0x78, 0x81, 0x52, 0xb5}},
+  { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,37, 38,
+       39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52, 53, 54, 55, 56,
+       57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,70, 71, 72, 73, 74,
+       75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,86, 87, 88, 89, 90, 91, 92,
+       93, 94, 95, 96, 97, 98, 99, 100,101, 102, 103, 104, 105, 106, 107, 108,
+       109, 110, 111, 112, 113, 114,115, 116, 117, 118, 119, 120, 121, 122,
+       123, 124, 125, 126, 127,128, 129, 130, 131, 132, 133, 134, 135, 136,
+       137, 138, 139, 140,141, 142, 143, 144, 145, 146, 147, 148, 149, 150,
+       151, 152, 153, 154,155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
+       165, 166, 167,168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
+       179, 180,181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192,
+       193, 194,195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206,
+       207,208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220,221,
+       222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,235,
+       236, 237, 238, 239, 240,241, 242, 243, 244, 245, 246, 247,248, 249, 250,
+       251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */
+    {0x49, 0x16, 0xd6, 0xbd, 0xb7, 0xf7, 0x8e, 0x68, 0x03, 0x69, 0x8c, 0xab,
+     0x32, 0xd1, 0x58, 0x6e, 0xa4, 0x57, 0xdf, 0xc8}},
+  { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,185,
+       184, 183, 182, 181, 180,179, 178, 177, 176, 175, 174, 173,172, 171, 170,
+       169, 168, 167, 166,165, 164, 163, 162, 161, 160,159, 158, 157, 156, 155,
+       154, 153, 152, 151, 150, 149, 148, 147, 146,145, 144, 143, 142, 141,
+       140,139}, 61}, /* 199..139 sequence */
+    {0xb3, 0xec, 0x61, 0x3c, 0xf7, 0x36, 0x57, 0x94, 0x61, 0xdb, 0xb2, 0x16,
+     0x75, 0xfe, 0x34, 0x60, 0x99, 0x94, 0xb5, 0xfc}},
+  { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242,
+       241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228,
+       227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214,
+       213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200,
+       199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,
+       185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172,
+       171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158,
+       157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144,
+       143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130,
+       129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116,
+       115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102,
+       101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85,
+       84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67,
+       66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49,
+       48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31,
+       30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13,
+       12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */
+    {0x99, 0x1d, 0xc6, 0x95, 0xe1, 0xaa, 0xcc, 0xc9, 0x35, 0x60, 0xbe, 0xe3,
+     0xe2, 0x41, 0x2b, 0xa7, 0xab, 0x49, 0x32, 0xf7}},
+  { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233,
+       235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71,
+       222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31,
+       93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50,
+       32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220,
+       173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34,
+       246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157,
+       73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191,
+       103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97,
+       255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240,
+       132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116,
+       158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244,
+       204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192,
+       247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5,
+       21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62,
+       105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247,
+       74, 74, 208, 87, 104}, 255}, /* pseudo-random data */
+    {0x9e, 0xb6, 0xce, 0x48, 0xf4, 0x6e, 0x9c, 0xf4, 0x1b, 0x4f, 0x9f, 0x66,
+     0xdd, 0xe8, 0x41, 0x01, 0x71, 0xf6, 0xf5, 0xd6}}
+};
+
+static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]);
+
+
+/*
+ *  Helper functions
+ */
+
+/**
+ * Print bin as hex
+ *
+ * @param bin binary data
+ * @param len number of bytes in bin
+ * @param hex pointer to len*2+1 bytes buffer
+ */
+static void
+bin2hex (const uint8_t *bin,
+         size_t len,
+         char *hex)
+{
+  while (len-- > 0)
+  {
+    unsigned int b1, b2;
+    b1 = (*bin >> 4) & 0xf;
+    *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0'));
+    b2 = *bin++ & 0xf;
+    *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0'));
+  }
+  *hex = 0;
+}
+
+
+static int
+check_result (const char *test_name,
+              unsigned int check_num,
+              const uint8_t calculated[SHA1_DIGEST_SIZE],
+              const uint8_t expected[SHA1_DIGEST_SIZE])
+{
+  int failed = memcmp (calculated, expected, SHA1_DIGEST_SIZE);
+  check_num++; /* Print 1-based numbers */
+  if (failed)
+  {
+    char calc_str[SHA1_DIGEST_STRING_SIZE];
+    char expc_str[SHA1_DIGEST_STRING_SIZE];
+    bin2hex (calculated, SHA1_DIGEST_SIZE, calc_str);
+    bin2hex (expected, SHA1_DIGEST_SIZE, expc_str);
+    fprintf (stderr,
+             "FAILED: %s check %u: calculated digest %s, expected digest %s.\n",
+             test_name, check_num, calc_str, expc_str);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    char calc_str[SHA1_DIGEST_STRING_SIZE];
+    bin2hex (calculated, SHA1_DIGEST_SIZE, calc_str);
+    printf ("PASSED: %s check %u: calculated digest %s matches " \
+            "expected digest.\n",
+            test_name, check_num, calc_str);
+    fflush (stdout);
+  }
+  return failed ? 1 : 0;
+}
+
+
+/*
+ *  Tests
+ */
+
+/* Calculated SHA-256 as one pass for whole data */
+static int
+test1_str (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+
+  for (i = 0; i < units1_num; i++)
+  {
+    struct sha1_ctx ctx;
+    uint8_t digest[SHA1_DIGEST_SIZE];
+
+    MHD_SHA1_init (&ctx);
+    MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str,
+                     data_units1[i].str_l.len);
+    MHD_SHA1_finish (&ctx, digest);
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units1[i].digest);
+  }
+  return num_failed;
+}
+
+
+static int
+test1_bin (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+
+  for (i = 0; i < units2_num; i++)
+  {
+    struct sha1_ctx ctx;
+    uint8_t digest[SHA1_DIGEST_SIZE];
+
+    MHD_SHA1_init (&ctx);
+    MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin,
+                     data_units2[i].bin_l.len);
+    MHD_SHA1_finish (&ctx, digest);
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units2[i].digest);
+  }
+  return num_failed;
+}
+
+
+/* Calculated SHA-256 as two iterations for whole data */
+static int
+test2_str (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+
+  for (i = 0; i < units1_num; i++)
+  {
+    struct sha1_ctx ctx;
+    uint8_t digest[SHA1_DIGEST_SIZE];
+    size_t part_s = data_units1[i].str_l.len / 4;
+
+    MHD_SHA1_init (&ctx);
+    MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s);
+    MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s,
+                     data_units1[i].str_l.len - part_s);
+    MHD_SHA1_finish (&ctx, digest);
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units1[i].digest);
+  }
+  return num_failed;
+}
+
+
+static int
+test2_bin (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+
+  for (i = 0; i < units2_num; i++)
+  {
+    struct sha1_ctx ctx;
+    uint8_t digest[SHA1_DIGEST_SIZE];
+    size_t part_s = data_units2[i].bin_l.len * 2 / 3;
+
+    MHD_SHA1_init (&ctx);
+    MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin, part_s);
+    MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin + part_s,
+                     data_units2[i].bin_l.len - part_s);
+    MHD_SHA1_finish (&ctx, digest);
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units2[i].digest);
+  }
+  return num_failed;
+}
+
+
+/* Use data set number 7 as it has the longest sequence */
+#define DATA_POS 6
+#define MAX_OFFSET 31
+
+static int
+test_unaligned (void)
+{
+  int num_failed = 0;
+  unsigned int offset;
+  uint8_t *buf;
+  uint8_t *digest_buf;
+
+  const struct data_unit2 *const tdata = data_units2 + DATA_POS;
+
+  buf = malloc (tdata->bin_l.len + MAX_OFFSET);
+  digest_buf = malloc (SHA1_DIGEST_SIZE + MAX_OFFSET);
+  if ((NULL == buf) || (NULL == digest_buf))
+    exit (99);
+
+  for (offset = MAX_OFFSET; offset >= 1; --offset)
+  {
+    struct sha1_ctx ctx;
+    uint8_t *unaligned_digest;
+    uint8_t *unaligned_buf;
+
+    unaligned_buf = buf + offset;
+    memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len);
+    unaligned_digest = digest_buf + MAX_OFFSET - offset;
+    memset (unaligned_digest, 0, SHA1_DIGEST_SIZE);
+
+    MHD_SHA1_init (&ctx);
+    MHD_SHA1_update (&ctx, unaligned_buf, tdata->bin_l.len);
+    MHD_SHA1_finish (&ctx, unaligned_digest);
+    num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset,
+                                unaligned_digest, tdata->digest);
+  }
+  free (digest_buf);
+  free (buf);
+  return num_failed;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int num_failed = 0;
+  (void) has_in_name; /* Mute compiler warning. */
+  if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose"))
+    verbose = 1;
+
+  num_failed += test1_str ();
+  num_failed += test1_bin ();
+
+  num_failed += test2_str ();
+  num_failed += test2_bin ();
+
+  num_failed += test_unaligned ();
+
+  return num_failed ? 1 : 0;
+}
diff --git a/src/microhttpd/test_sha256.c b/src/microhttpd/test_sha256.c
new file mode 100644
index 0000000..e6ccc7c
--- /dev/null
+++ b/src/microhttpd/test_sha256.c
@@ -0,0 +1,547 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2019-2023 Evgeny Grin (Karlson2k)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_sha256.h
+ * @brief  Unit tests for SHA-256 functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "mhd_sha256_wrap.h"
+#include "test_helpers.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#if defined(MHD_SHA256_TLSLIB) && defined(MHD_HTTPS_REQUIRE_GCRYPT)
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_SHA256_TLSLIB && MHD_HTTPS_REQUIRE_GCRYPT */
+
+static int verbose = 0; /* verbose level (0-1)*/
+
+
+struct str_with_len
+{
+  const char *const str;
+  const size_t len;
+};
+
+#define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1}
+
+struct data_unit1
+{
+  const struct str_with_len str_l;
+  const uint8_t digest[SHA256_DIGEST_SIZE];
+};
+
+static const struct data_unit1 data_units1[] = {
+  {D_STR_W_LEN ("abc"),
+   {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde,
+    0x5d, 0xae, 0x22, 0x23,
+    0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
+    0xf2, 0x00, 0x15, 0xad}},
+  {D_STR_W_LEN ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
+   {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93,
+    0x0c, 0x3e, 0x60, 0x39,
+    0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4,
+    0x19, 0xdb, 0x06, 0xc1}},
+  {D_STR_W_LEN (""),
+   {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8,
+    0x99, 0x6f, 0xb9, 0x24,
+    0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
+    0x78, 0x52, 0xb8, 0x55}},
+  {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."),
+   {0x2f, 0xad, 0x7a, 0xff, 0x7d, 0xfe, 0xcd, 0x78, 0xe4, 0xa6, 0xf3, 0x85,
+    0x97, 0x9d, 0xdc, 0x39,
+    0x55, 0x24, 0x35, 0x4a, 0x00, 0x6f, 0x42, 0x72, 0x41, 0xc1, 0x52, 0xa7,
+    0x01, 0x0b, 0x2c, 0x41}},
+  {D_STR_W_LEN ("Simple string."),
+   {0x01, 0x73, 0x17, 0xc4, 0x0a, 0x9a, 0x0e, 0x81, 0xb3, 0xa4, 0xb1, 0x8e,
+    0xe9, 0xd6, 0xc2, 0xdf,
+    0xfa, 0x7d, 0x53, 0x4e, 0xa1, 0xda, 0xb2, 0x5a, 0x75, 0xbb, 0x2c, 0x30,
+    0x2f, 0x5f, 0x7a, 0xf4}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"),
+   {0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44,
+    0x7c, 0x66, 0xc9, 0x52,
+    0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d, 0x9e, 0xd8, 0x32, 0xf2,
+    0xda, 0xf1, 0x8b, 0x73}},
+  {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"),
+   {0xce, 0x7d, 0xde, 0xb6, 0x1f, 0x7c, 0x1d, 0x83, 0x7c, 0x60, 0xd8, 0x36,
+    0x73, 0x82, 0xac, 0x92,
+    0xca, 0x37, 0xfd, 0x72, 0x8b, 0x0c, 0xd1, 0x6c, 0x55, 0xd5, 0x88, 0x98,
+    0x24, 0xfa, 0x16, 0xf2}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \
+                "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"),
+   {0x27, 0xd1, 0xe8, 0xbc, 0x6a, 0x79, 0x16, 0x83, 0x61, 0x73, 0xa9, 0xa8,
+    0x9b, 0xaf, 0xaf, 0xcf,
+    0x47, 0x4d, 0x09, 0xef, 0x6d, 0x50, 0x35, 0x12, 0x25, 0x72, 0xd8, 0x68,
+    0xdc, 0x1f, 0xd2, 0xf4}},
+  {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/path?with%20some=parameters"),
+   {0x73, 0x85, 0xc5, 0xb9, 0x8f, 0xaf, 0x7d, 0x5e, 0xad, 0xd8, 0x0b, 0x8e,
+    0x12, 0xdb, 0x28, 0x60, 0xc7, 0xc7, 0x55, 0x05, 0x2f, 0x7c, 0x6f, 0xfa,
+    0xd1, 0xe3, 0xe1, 0x7b, 0x04, 0xd4, 0xb0, 0x21}}
+};
+
+static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]);
+
+struct bin_with_len
+{
+  const uint8_t bin[512];
+  const size_t len;
+};
+
+struct data_unit2
+{
+  const struct bin_with_len bin_l;
+  const uint8_t digest[SHA256_DIGEST_SIZE];
+};
+
+/* Size must be less than 512 bytes! */
+static const struct data_unit2 data_units2[] = {
+  { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+       112, 113, 114, 115, 116,
+       117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */
+    {0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44,
+     0x7c, 0x66, 0xc9, 0x52,
+     0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d, 0x9e, 0xd8, 0x32, 0xf2,
+     0xda, 0xf1, 0x8b, 0x73}},
+  { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65}, 72 },/* 'A' x 72 times */
+    {0x6a, 0x6d, 0x69, 0x1a, 0xc9, 0xba, 0x70, 0x95, 0x50, 0x46, 0x75, 0x7c,
+     0xd6, 0x85, 0xb6, 0x25,
+     0x77, 0x73, 0xff, 0x3a, 0xd9, 0x3f, 0x43, 0xd4, 0xd4, 0x81, 0x2c, 0x5b,
+     0x10, 0x6f, 0x4b, 0x5b}},
+  { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
+       37, 38, 39, 40, 41, 42,
+       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
+       61, 62, 63, 64, 65, 66, 67,
+       68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */
+    {0x06, 0xe4, 0xb3, 0x9e, 0xf1, 0xfb, 0x6c, 0xcf, 0xd7, 0x3f, 0x50, 0x9e,
+     0xf4, 0x16, 0x17, 0xd4,
+     0x63, 0x7c, 0x39, 0x1e, 0xa8, 0x0f, 0xa9, 0x88, 0x03, 0x44, 0x98, 0x0e,
+     0x95, 0x81, 0xf0, 0x2a}},
+  { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+       26, 27, 28, 29, 30, 31,
+       32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
+       50, 51, 52, 53, 54, 55, 56,
+       57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */
+    {0x4a, 0xd3, 0xc6, 0x87, 0x1f, 0xd1, 0xc5, 0xe2, 0x3e, 0x52, 0xdc, 0x22,
+     0xd1, 0x10, 0xd2, 0x05,
+     0x15, 0x23, 0xcd, 0x15, 0xac, 0x24, 0x88, 0x26, 0x02, 0x00, 0x70, 0x78,
+     0x9f, 0x17, 0xf8, 0xd9}},
+  { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
+       56, 57, 58, 59, 60, 61,
+       62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+       80, 81, 82, 83, 84, 85, 86,
+       87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */
+    {0xe6, 0x03, 0x0f, 0xc9, 0x0d, 0xca, 0x0c, 0x26, 0x41, 0xcf, 0x43, 0x27,
+     0xec, 0xd6, 0x28, 0x2a,
+     0x98, 0x24, 0x55, 0xd3, 0x5a, 0xed, 0x8b, 0x32, 0x19, 0x78, 0xeb, 0x83,
+     0x1d, 0x19, 0x92, 0x79}},
+  { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26, 27,
+       28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
+       46, 47, 48, 49, 50, 51, 52,
+       53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
+       71, 72},
+      72},/* 1..72 sequence */
+    {0x87, 0xa2, 0xfa, 0x2e, 0xec, 0x53, 0x05, 0x3c, 0xb1, 0xee, 0x07, 0xd7,
+     0x59, 0x70, 0xf6, 0x50,
+     0xcd, 0x9d, 0xc5, 0x8b, 0xdc, 0xb8, 0x65, 0x30, 0x4f, 0x70, 0x82, 0x9e,
+     0xbd, 0xe2, 0x7d, 0xac}},
+  { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26,
+       27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
+       45, 46, 47, 48, 49, 50, 51,
+       52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
+       70, 71, 72, 73, 74, 75, 76,
+       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
+       95, 96, 97, 98, 99, 100,
+       101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
+       115, 116, 117, 118, 119, 120,
+       121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
+       135, 136, 137, 138, 139, 140,
+       141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
+       155, 156, 157, 158, 159, 160,
+       161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
+       175, 176, 177, 178, 179, 180,
+       181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
+       195, 196, 197, 198, 199, 200,
+       201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214,
+       215, 216, 217, 218, 219, 220,
+       221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
+       235, 236, 237, 238, 239, 240,
+       241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
+       255}, 256},                                                                        /* 0..255 sequence */
+    {0x40, 0xaf, 0xf2, 0xe9, 0xd2, 0xd8, 0x92, 0x2e, 0x47, 0xaf, 0xd4, 0x64,
+     0x8e, 0x69, 0x67, 0x49,
+     0x71, 0x58, 0x78, 0x5f, 0xbd, 0x1d, 0xa8, 0x70, 0xe7, 0x11, 0x02, 0x66,
+     0xbf, 0x94, 0x48, 0x80}},
+  { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,
+       185, 184, 183, 182, 181, 180,
+       179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166,
+       165, 164, 163, 162, 161, 160,
+       159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146,
+       145, 144, 143, 142, 141, 140,
+       139}, 61},  /* 199..139 sequence */
+    {0x85, 0xf8, 0xa2, 0x83, 0xd6, 0x3c, 0x76, 0x8e, 0xea, 0x8f, 0x1c, 0x57,
+     0x2d, 0x85, 0xb6, 0xff,
+     0xd8, 0x33, 0x57, 0x62, 0x1d, 0x37, 0xae, 0x0e, 0xfc, 0x22, 0xd3, 0xd5,
+     0x8f, 0x53, 0x21, 0xb7}},
+  { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242,
+       241, 240, 239, 238, 237, 236,
+       235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222,
+       221, 220, 219, 218, 217, 216,
+       215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202,
+       201, 200, 199, 198, 197, 196,
+       195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182,
+       181, 180, 179, 178, 177, 176,
+       175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162,
+       161, 160, 159, 158, 157, 156,
+       155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142,
+       141, 140, 139, 138, 137, 136,
+       135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122,
+       121, 120, 119, 118, 117, 116,
+       115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102,
+       101, 100, 99, 98, 97, 96, 95,
+       94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77,
+       76, 75, 74, 73, 72, 71, 70,
+       69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52,
+       51, 50, 49, 48, 47, 46, 45,
+       44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27,
+       26, 25, 24, 23, 22, 21, 20,
+       19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255},  /* 255..1 sequence */
+    {0x61, 0x86, 0x96, 0xab, 0x3e, 0xaa, 0x0e, 0x64, 0xb2, 0xf7, 0x2d, 0x75,
+     0x47, 0x5a, 0x14, 0x97,
+     0xa3, 0x3d, 0x59, 0xa4, 0x08, 0xd9, 0x9e, 0x73, 0xf2, 0x78, 0x00, 0x5b,
+     0x4b, 0x55, 0xca, 0x43}},
+  { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233,
+       235, 179, 166, 219, 60, 135,
+       12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187,
+       139, 166, 31, 3, 90, 125, 9,
+       56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28,
+       219, 174, 50, 32, 154, 80, 238,
+       64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242,
+       68, 64, 102, 208, 107, 196,
+       48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202,
+       153, 2, 185, 114, 157, 73,
+       44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103,
+       214, 191, 20, 214, 126, 45,
+       220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30,
+       157, 156, 22, 114, 114, 230,
+       29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51,
+       116, 158, 12, 244, 213,
+       212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144,
+       45, 72, 211, 143, 117, 230,
+       217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212,
+       97, 141, 190, 123, 5, 21, 7,
+       59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21,
+       248, 70, 106, 4, 150, 115,
+       14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255},  /* pseudo-random data */
+    {0x08, 0x7f, 0x86, 0xac, 0xe2, 0x2e, 0x28, 0x56, 0x74, 0x53, 0x4f, 0xc0,
+     0xfb, 0xb8, 0x79, 0x57,
+     0xc5, 0xc8, 0xd1, 0xb7, 0x47, 0xb7, 0xd9, 0xea, 0x97, 0xa8, 0x67, 0xe9,
+     0x26, 0x93, 0xee, 0xa3}}
+};
+
+static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]);
+
+
+/*
+ *  Helper functions
+ */
+
+/**
+ * Print bin as hex
+ *
+ * @param bin binary data
+ * @param len number of bytes in bin
+ * @param hex pointer to len*2+1 bytes buffer
+ */
+static void
+bin2hex (const uint8_t *bin,
+         size_t len,
+         char *hex)
+{
+  while (len-- > 0)
+  {
+    unsigned int b1, b2;
+    b1 = (*bin >> 4) & 0xf;
+    *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0'));
+    b2 = *bin++ & 0xf;
+    *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0'));
+  }
+  *hex = 0;
+}
+
+
+static int
+check_result (const char *test_name,
+              unsigned int check_num,
+              const uint8_t calculated[SHA256_DIGEST_SIZE],
+              const uint8_t expected[SHA256_DIGEST_SIZE])
+{
+  int failed = memcmp (calculated, expected, SHA256_DIGEST_SIZE);
+  check_num++; /* Print 1-based numbers */
+  if (failed)
+  {
+    char calc_str[SHA256_DIGEST_STRING_SIZE];
+    char expc_str[SHA256_DIGEST_STRING_SIZE];
+    bin2hex (calculated, SHA256_DIGEST_SIZE, calc_str);
+    bin2hex (expected, SHA256_DIGEST_SIZE, expc_str);
+    fprintf (stderr,
+             "FAILED: %s check %u: calculated digest %s, expected digest %s.\n",
+             test_name, check_num, calc_str, expc_str);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    char calc_str[SHA256_DIGEST_STRING_SIZE];
+    bin2hex (calculated, SHA256_DIGEST_SIZE, calc_str);
+    printf ("PASSED: %s check %u: calculated digest %s "
+            "matches expected digest.\n",
+            test_name, check_num, calc_str);
+    fflush (stdout);
+  }
+  return failed ? 1 : 0;
+}
+
+
+/*
+ *  Tests
+ */
+
+/* Calculated SHA-256 as one pass for whole data */
+static int
+test1_str (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha256CtxWr ctx;
+
+  MHD_SHA256_init_one_time (&ctx);
+  for (i = 0; i < units1_num; i++)
+  {
+    uint8_t digest[SHA256_DIGEST_SIZE];
+
+    MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str,
+                       data_units1[i].str_l.len);
+    MHD_SHA256_finish_reset (&ctx, digest);
+#ifdef MHD_SHA256_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif /* MHD_SHA256_HAS_EXT_ERROR */
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units1[i].digest);
+  }
+  MHD_SHA256_deinit (&ctx);
+  return num_failed;
+}
+
+
+static int
+test1_bin (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha256CtxWr ctx;
+
+  MHD_SHA256_init_one_time (&ctx);
+  for (i = 0; i < units2_num; i++)
+  {
+    uint8_t digest[SHA256_DIGEST_SIZE];
+
+    MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin,
+                       data_units2[i].bin_l.len);
+    MHD_SHA256_finish_reset (&ctx, digest);
+#ifdef MHD_SHA256_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif /* MHD_SHA256_HAS_EXT_ERROR */
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units2[i].digest);
+  }
+  MHD_SHA256_deinit (&ctx);
+  return num_failed;
+}
+
+
+/* Calculated SHA-256 as two iterations for whole data */
+static int
+test2_str (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha256CtxWr ctx;
+
+  MHD_SHA256_init_one_time (&ctx);
+  for (i = 0; i < units1_num; i++)
+  {
+    uint8_t digest[SHA256_DIGEST_SIZE];
+    size_t part_s = data_units1[i].str_l.len / 4;
+
+    MHD_SHA256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str,
+                       part_s);
+    MHD_SHA256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str
+                       + part_s,
+                       data_units1[i].str_l.len - part_s);
+    MHD_SHA256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA256_finish_reset (&ctx, digest);
+#ifdef MHD_SHA256_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif /* MHD_SHA256_HAS_EXT_ERROR */
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units1[i].digest);
+  }
+  MHD_SHA256_deinit (&ctx);
+  return num_failed;
+}
+
+
+static int
+test2_bin (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha256CtxWr ctx;
+
+  MHD_SHA256_init_one_time (&ctx);
+  for (i = 0; i < units2_num; i++)
+  {
+    uint8_t digest[SHA256_DIGEST_SIZE];
+    size_t part_s = data_units2[i].bin_l.len * 2 / 3;
+
+    MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin, part_s);
+    MHD_SHA256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin + part_s,
+                       data_units2[i].bin_l.len - part_s);
+    MHD_SHA256_finish_reset (&ctx, digest);
+#ifdef MHD_SHA256_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif /* MHD_SHA256_HAS_EXT_ERROR */
+    num_failed += check_result (MHD_FUNC_, i, digest,
+                                data_units2[i].digest);
+  }
+  MHD_SHA256_deinit (&ctx);
+  return num_failed;
+}
+
+
+/* Use data set number 7 as it has the longest sequence */
+#define DATA_POS 6
+#define MAX_OFFSET 31
+
+static int
+test_unaligned (void)
+{
+  int num_failed = 0;
+  unsigned int offset;
+  uint8_t *buf;
+  uint8_t *digest_buf;
+  struct Sha256CtxWr ctx;
+
+  const struct data_unit2 *const tdata = data_units2 + DATA_POS;
+
+  MHD_SHA256_init_one_time (&ctx);
+  buf = malloc (tdata->bin_l.len + MAX_OFFSET);
+  digest_buf = malloc (SHA256_DIGEST_SIZE + MAX_OFFSET);
+  if ((NULL == buf) || (NULL == digest_buf))
+    exit (99);
+
+  for (offset = MAX_OFFSET; offset >= 1; --offset)
+  {
+    uint8_t *unaligned_digest;
+    uint8_t *unaligned_buf;
+
+    unaligned_buf = buf + offset;
+    memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len);
+    unaligned_digest = digest_buf + MAX_OFFSET - offset;
+    memset (unaligned_digest, 0, SHA256_DIGEST_SIZE);
+
+    MHD_SHA256_update (&ctx, unaligned_buf, tdata->bin_l.len);
+    MHD_SHA256_finish_reset (&ctx, unaligned_digest);
+#ifdef MHD_SHA256_HAS_EXT_ERROR
+    if (0 != ctx.ext_error)
+    {
+      fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error);
+      exit (99);
+    }
+#endif /* MHD_SHA256_HAS_EXT_ERROR */
+    num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset,
+                                unaligned_digest, tdata->digest);
+  }
+  free (digest_buf);
+  free (buf);
+  MHD_SHA256_deinit (&ctx);
+  return num_failed;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int num_failed = 0;
+  (void) has_in_name; /* Mute compiler warning. */
+  if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose"))
+    verbose = 1;
+
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+
+  num_failed += test1_str ();
+  num_failed += test1_bin ();
+
+  num_failed += test2_str ();
+  num_failed += test2_bin ();
+
+  num_failed += test_unaligned ();
+
+  return num_failed ? 1 : 0;
+}
diff --git a/src/microhttpd/test_sha512_256.c b/src/microhttpd/test_sha512_256.c
new file mode 100644
index 0000000..192cb1f
--- /dev/null
+++ b/src/microhttpd/test_sha512_256.c
@@ -0,0 +1,602 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2019-2022 Evgeny Grin (Karlson2k)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_sha512_256.h
+ * @brief  Unit tests for SHA-512/256 functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "sha512_256.h"
+#include "test_helpers.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+static int verbose = 0; /* verbose level (0-1)*/
+
+
+struct str_with_len
+{
+  const char *const str;
+  const size_t len;
+};
+
+#define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1}
+
+struct data_unit1
+{
+  const struct str_with_len str_l;
+  const uint8_t digest[SHA512_256_DIGEST_SIZE];
+};
+
+static const struct data_unit1 data_units1[] = {
+  {D_STR_W_LEN ("abc"),
+   {0x53, 0x04, 0x8E, 0x26, 0x81, 0x94, 0x1E, 0xF9, 0x9B, 0x2E, 0x29, 0xB7,
+    0x6B, 0x4C, 0x7D, 0xAB, 0xE4, 0xC2, 0xD0, 0xC6, 0x34, 0xFC, 0x6D, 0x46,
+    0xE0, 0xE2, 0xF1, 0x31, 0x07, 0xE7, 0xAF, 0x23}},
+  {D_STR_W_LEN ("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhi" \
+                "jklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"),
+   {0x39, 0x28, 0xE1, 0x84, 0xFB, 0x86, 0x90, 0xF8, 0x40, 0xDA, 0x39, 0x88,
+    0x12, 0x1D, 0x31, 0xBE, 0x65, 0xCB, 0x9D, 0x3E, 0xF8, 0x3E, 0xE6, 0x14,
+    0x6F, 0xEA, 0xC8, 0x61, 0xE1, 0x9B, 0x56, 0x3A}},
+  {D_STR_W_LEN (""), /* The empty zero-size input */
+   {0xc6, 0x72, 0xb8, 0xd1, 0xef, 0x56, 0xed, 0x28, 0xab, 0x87, 0xc3, 0x62,
+    0x2c, 0x51, 0x14, 0x06, 0x9b, 0xdd, 0x3a, 0xd7, 0xb8, 0xf9, 0x73, 0x74,
+    0x98, 0xd0, 0xc0, 0x1e, 0xce, 0xf0, 0x96, 0x7a}},
+  {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."),
+   {0xc8, 0x7c, 0x5a, 0x55, 0x27, 0x77, 0x1b, 0xe7, 0x69, 0x3c, 0x50, 0x79,
+    0x32, 0xad, 0x7c, 0x79, 0xe9, 0x60, 0xa0, 0x18, 0xb7, 0x78, 0x2b, 0x6f,
+    0xa9, 0x7b, 0xa3, 0xa0, 0xb5, 0x18, 0x17, 0xa5}},
+  {D_STR_W_LEN ("Simple string."),
+   {0xde, 0xcb, 0x3c, 0x81, 0x65, 0x4b, 0xa0, 0xf5, 0xf0, 0x45, 0x6b, 0x7e,
+    0x61, 0xf5, 0x0d, 0xf5, 0x38, 0xa4, 0xfc, 0xb1, 0x8a, 0x95, 0xff, 0x59,
+    0xbc, 0x04, 0x82, 0xcf, 0x23, 0xb2, 0x32, 0x56}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"),
+   {0xfc, 0x31, 0x89, 0x44, 0x3f, 0x9c, 0x26, 0x8f, 0x62, 0x6a, 0xea, 0x08,
+    0xa7, 0x56, 0xab, 0xe7, 0xb7, 0x26, 0xb0, 0x5f, 0x70, 0x1c, 0xb0, 0x82,
+    0x22, 0x31, 0x2c, 0xcf, 0xd6, 0x71, 0x0a, 0x26, }},
+  {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"),
+   {0xd2, 0x6d, 0x24, 0x81, 0xa4, 0xf9, 0x0a, 0x72, 0xd2, 0x7f, 0xc1, 0xac,
+    0xac, 0xe1, 0xc0, 0x6b, 0x39, 0x94, 0xac, 0x73, 0x50, 0x2e, 0x27, 0x97,
+    0xa3, 0x65, 0x37, 0x4e, 0xbb, 0x5c, 0x27, 0xe9}},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \
+                "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"),
+   {0xad, 0xe9, 0x5d, 0x55, 0x3b, 0x9e, 0x45, 0x69, 0xdb, 0x53, 0xa4, 0x04,
+    0x92, 0xe7, 0x87, 0x94, 0xff, 0xc9, 0x98, 0x5f, 0x93, 0x03, 0x86, 0x45,
+    0xe1, 0x97, 0x17, 0x72, 0x7c, 0xbc, 0x31, 0x15}},
+  {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/long/long/long/long/long/long/long" \
+                "/long/long/long/long/path?with%20some=parameters"),
+   {0xbc, 0xab, 0xc6, 0x2c, 0x0a, 0x22, 0xd5, 0xcb, 0xac, 0xac, 0xe9, 0x25,
+    0xcf, 0xce, 0xaa, 0xaf, 0x0e, 0xa1, 0xed, 0x42, 0x46, 0x8a, 0xe2, 0x01,
+    0xee, 0x2f, 0xdb, 0x39, 0x75, 0x47, 0x73, 0xf1}}
+};
+
+static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]);
+
+struct bin_with_len
+{
+  const uint8_t bin[512];
+  const size_t len;
+};
+
+struct data_unit2
+{
+  const struct bin_with_len bin_l;
+  const uint8_t digest[SHA512_256_DIGEST_SIZE];
+};
+
+/* Size must be less than 512 bytes! */
+static const struct data_unit2 data_units2[] = {
+  { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+       112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */
+    {0xfc, 0x31, 0x89, 0x44, 0x3f, 0x9c, 0x26, 0x8f, 0x62, 0x6a, 0xea, 0x08,
+     0xa7, 0x56, 0xab, 0xe7, 0xb7, 0x26, 0xb0, 0x5f, 0x70, 0x1c, 0xb0, 0x82,
+     0x22, 0x31, 0x2c, 0xcf, 0xd6, 0x71, 0x0a, 0x26}},
+  { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
+       65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65},
+      72 }, /* 'A' x 72 times */
+    {0x36, 0x5d, 0x41, 0x0e, 0x55, 0xd1, 0xfd, 0xe6, 0xc3, 0xb8, 0x68, 0xcc,
+     0xed, 0xeb, 0xcd, 0x0d, 0x2e, 0x34, 0xb2, 0x5c, 0xdf, 0xe7, 0x79, 0xe2,
+     0xe9, 0x65, 0x07, 0x33, 0x78, 0x0d, 0x01, 0x89}},
+  { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
+       37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
+       55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
+       73}, 55}, /* 19..73 sequence */
+    {0xb9, 0xe5, 0x74, 0x11, 0xbf, 0xa2, 0x0e, 0x98, 0xbe, 0x08, 0x69, 0x2e,
+     0x17, 0x9e, 0xc3, 0xfe, 0x61, 0xe3, 0x7a, 0x80, 0x2e, 0x25, 0x8c, 0xf3,
+     0x76, 0xda, 0x9f, 0x5f, 0xcd, 0x87, 0x48, 0x0d}},
+  { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+       26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
+       44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
+       62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */
+    {0x80, 0x15, 0x83, 0xed, 0x7d, 0xef, 0x9f, 0xdf, 0xfb, 0x83, 0x1f, 0xc5,
+     0x8b, 0x50, 0x37, 0x81, 0x00, 0xc3, 0x4f, 0xfd, 0xfe, 0xc2, 0x9b, 0xaf,
+     0xfe, 0x15, 0x66, 0xe5, 0x08, 0x42, 0x5e, 0xae}},
+  { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
+       56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
+       74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
+       92}, 55}, /* 38..92 sequence */
+    {0x76, 0x2f, 0x27, 0x4d, 0xfa, 0xd5, 0xa9, 0x21, 0x4e, 0xe9, 0x56, 0x22,
+     0x54, 0x38, 0x71, 0x3e, 0xef, 0x14, 0xa9, 0x22, 0x37, 0xf3, 0xb0, 0x50,
+     0x3d, 0x95, 0x40, 0xb7, 0x08, 0x64, 0xa9, 0xfd}},
+  { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
+       39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+       57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72}, /* 1..72 sequence */
+    {0x3f, 0x5c, 0xd3, 0xec, 0x40, 0xc4, 0xb9, 0x78, 0x35, 0x57, 0xc6, 0x4f,
+     0x3e, 0x46, 0x82, 0xdc, 0xd4, 0x46, 0x11, 0xd0, 0xb3, 0x0a, 0xbb, 0x89,
+     0xf1, 0x1d, 0x34, 0xb5, 0xf9, 0xd5, 0x10, 0x35}},
+  { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+       21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
+       39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+       57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
+       75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
+       93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
+       109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
+       123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136,
+       137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150,
+       151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
+       165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
+       179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192,
+       193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206,
+       207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220,
+       221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
+       235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
+       249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */
+    {0x08, 0x37, 0xa1, 0x1d, 0x99, 0x4d, 0x5a, 0xa8, 0x60, 0xd0, 0x69, 0x17,
+     0xa8, 0xa0, 0xf6, 0x3e, 0x31, 0x11, 0xb9, 0x56, 0x33, 0xde, 0xeb, 0x15,
+     0xee, 0xd9, 0x94, 0x93, 0x76, 0xf3, 0x7d, 0x36, }},
+  { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,
+       185, 184, 183, 182, 181, 180,
+       179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166,
+       165, 164, 163, 162, 161, 160,
+       159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146,
+       145, 144, 143, 142, 141, 140,
+       139}, 61},  /* 199..139 sequence */
+    {0xcf, 0x21, 0x4b, 0xb2, 0xdd, 0x40, 0x98, 0xdf, 0x3a, 0xb7, 0x21, 0xb4,
+     0x69, 0x0e, 0x19, 0x36, 0x24, 0xa9, 0xbe, 0x30, 0xf7, 0xd0, 0x75, 0xb0,
+     0x39, 0x94, 0x82, 0xda, 0x55, 0x97, 0xe4, 0x79}},
+  { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242,
+       241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228,
+       227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214,
+       213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200,
+       199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,
+       185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172,
+       171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158,
+       157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144,
+       143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130,
+       129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116,
+       115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102,
+       101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85,
+       84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67,
+       66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49,
+       48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31,
+       30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13,
+       12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255},  /* 255..1 sequence */
+    {0x22, 0x31, 0xf2, 0xa1, 0xb4, 0x89, 0xb2, 0x44, 0xf7, 0x66, 0xa0, 0xb8,
+     0x31, 0xed, 0xb7, 0x73, 0x8a, 0x34, 0xdc, 0x11, 0xc8, 0x2c, 0xf2, 0xb5,
+     0x88, 0x60, 0x39, 0x6b, 0x5c, 0x06, 0x70, 0x37}},
+  { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233,
+       235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71,
+       222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37,
+       31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174,
+       50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73,
+       220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59,
+       161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185,
+       114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201,
+       204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239,
+       87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114,
+       230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18,
+       30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207,
+       50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29,
+       42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141,
+       190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206,
+       177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103,
+       104, 212, 247, 74, 74, 208, 87, 104}, 255},  /* pseudo-random data */
+    {0xb8, 0xdb, 0x2c, 0x2e, 0xf3, 0x12, 0x77, 0x14, 0xf9, 0x34, 0x2d, 0xfa,
+     0xda, 0x42, 0xbe, 0xfe, 0x67, 0x3a, 0x8a, 0xf6, 0x71, 0x36, 0x00, 0xff,
+     0x77, 0xa5, 0x83, 0x14, 0x55, 0x2a, 0x05, 0xaf}},
+  { { {66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
+       66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
+       66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
+       66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
+       66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
+       66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
+       66, 66}, 110},  /* 'B' x 110 times */
+    {0xc8, 0x9e, 0x0d, 0x8f, 0x7b, 0x35, 0xfd, 0x3e, 0xdc, 0x90, 0x87, 0x64,
+     0x45, 0x94, 0x94, 0x21, 0xb3, 0x8e, 0xb5, 0xc7, 0x54, 0xc8, 0xee, 0xde,
+     0xfc, 0x77, 0xd6, 0xe3, 0x9f, 0x81, 0x8e, 0x78}},
+  { { {67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67,
+       67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67,
+       67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67,
+       67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67,
+       67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67,
+       67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67,
+       67, 67, 67}, 111},  /* 'C' x 111 times */
+    {0x86, 0xca, 0x6d, 0x2a, 0x72, 0xe2, 0x8c, 0x17, 0x89, 0x86, 0x89, 0x1b,
+     0x36, 0xf9, 0x6d, 0xda, 0x8c, 0xd6, 0x30, 0xb2, 0xd3, 0x60, 0x39, 0xfb,
+     0xc9, 0x04, 0xc5, 0x11, 0xcd, 0x2d, 0xe3, 0x62}},
+  { { {68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+       68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+       68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+       68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+       68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+       68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,
+       68, 68, 68, 68}, 112},  /* 'D' x 112 times */
+    {0xdf, 0x9d, 0x4a, 0xcf, 0x81, 0x0d, 0x3a, 0xd4, 0x8e, 0xa4, 0x65, 0x9e,
+     0x1e, 0x15, 0xe4, 0x15, 0x1b, 0x37, 0xb6, 0xeb, 0x17, 0xab, 0xf6, 0xb1,
+     0xbc, 0x30, 0x46, 0x34, 0x24, 0x56, 0x1c, 0x06}},
+  { { {69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
+       69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
+       69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
+       69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
+       69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
+       69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
+       69, 69, 69, 69, 69}, 113},  /* 'E' x 113 times */
+    {0xa5, 0xf1, 0x47, 0x74, 0xf8, 0x2b, 0xed, 0x23, 0xe4, 0x10, 0x59, 0x8f,
+     0x7e, 0xb1, 0x30, 0xe5, 0x7e, 0xd1, 0x4b, 0xbc, 0x72, 0x58, 0x58, 0x81,
+     0xbb, 0xa0, 0xa5, 0xb6, 0x15, 0x39, 0x49, 0xa1}},
+  { { {70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
+       70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
+       70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
+       70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
+       70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
+       70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
+       70, 70, 70, 70, 70, 70}, 114},  /* 'F' x 114 times */
+    {0xe6, 0xa3, 0xc9, 0x63, 0xd5, 0x28, 0x6e, 0x2d, 0xfb, 0x71, 0xdf, 0xd4,
+     0xff, 0xc2, 0xd4, 0x2b, 0x5d, 0x9b, 0x76, 0x28, 0xd2, 0xcb, 0x15, 0xc8,
+     0x81, 0x57, 0x14, 0x09, 0xc3, 0x8e, 0x92, 0xce}},
+  { { {76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
+       76}, 127},  /* 'L' x 127 times */
+    {0x5d, 0x18, 0xff, 0xd7, 0xbe, 0x23, 0xb2, 0xb2, 0xbd, 0xe3, 0x13, 0x12,
+     0x1c, 0x16, 0x89, 0x14, 0x4a, 0x42, 0xb4, 0x3f, 0xab, 0xc8, 0x41, 0x14,
+     0x62, 0x00, 0xb5, 0x53, 0xa7, 0xd6, 0xd5, 0x35}},
+  { { {77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77,
+       77, 77}, 128},  /* 'M' x 128 times */
+    {0x6e, 0xf0, 0xda, 0x81, 0x3d, 0x50, 0x1d, 0x31, 0xf1, 0x4a, 0xf8, 0xd9,
+     0x7d, 0xd2, 0x13, 0xdd, 0xa4, 0x46, 0x15, 0x0b, 0xb8, 0x5a, 0x8a, 0xc6,
+     0x1e, 0x3a, 0x1f, 0x21, 0x35, 0xa2, 0xbb, 0x4f}},
+  { { {78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
+       78, 78, 78}, 129},  /* 'N' x 129 times */
+    {0xee, 0xce, 0xd5, 0x34, 0xab, 0x14, 0x13, 0x9e, 0x8f, 0x5c, 0xb4, 0xef,
+     0xac, 0xaf, 0xc5, 0xeb, 0x1d, 0x2f, 0xe3, 0xc5, 0xca, 0x09, 0x29, 0x96,
+     0xfa, 0x84, 0xff, 0x12, 0x26, 0x6a, 0x50, 0x49}},
+  { { {97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97,
+       97, 97, 97, 97}, 238},  /* 'a' x 238 times */
+    {0xb4, 0x24, 0xe5, 0x7b, 0xa7, 0x37, 0xe3, 0xc4, 0xac, 0x35, 0x21, 0x17,
+     0x98, 0xec, 0xb9, 0xae, 0x45, 0x13, 0x24, 0xa4, 0x2c, 0x76, 0xae, 0x7d,
+     0x17, 0x75, 0x27, 0x8a, 0xaa, 0x4a, 0x48, 0x60}},
+  { { {98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+       98, 98, 98, 98, 98}, 239},  /* 'b' x 239 times */
+    {0xcd, 0x93, 0xb8, 0xab, 0x6a, 0x74, 0xbd, 0x34, 0x8c, 0x43, 0x76, 0x0c,
+     0x2a, 0xd0, 0x6e, 0xd8, 0x76, 0xcf, 0xdf, 0x2a, 0x21, 0x04, 0xfb, 0xf6,
+     0x16, 0x53, 0x68, 0xf6, 0x10, 0xc3, 0xa1, 0xac}},
+  { { {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
+       99, 99, 99, 99, 99, 99}, 240},  /* 'c' x 240 times */
+    {0x5f, 0x60, 0xea, 0x44, 0xb6, 0xc6, 0x9e, 0xfe, 0xfc, 0x0e, 0x6a, 0x0a,
+     0x99, 0x40, 0x1b, 0x61, 0x43, 0x58, 0xba, 0x4a, 0x0a, 0xee, 0x6b, 0x52,
+     0x10, 0xdb, 0x32, 0xd9, 0x7f, 0x12, 0xba, 0x70}},
+  { { {48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
+       48, 48, 48, 48, 48, 48, 48}, 241}, /* '0' x 241 times */
+    {0x3c, 0xcb, 0xcf, 0x50, 0x79, 0xd5, 0xb6, 0xf5, 0xbf, 0x25, 0x07, 0xfb,
+     0x4d, 0x1f, 0xa3, 0x77, 0xc3, 0x6f, 0xe8, 0xe3, 0xc4, 0x4b, 0xf8, 0xcd,
+     0x90, 0x93, 0xf1, 0x3e, 0x08, 0x09, 0xa7, 0x69}}
+};
+
+static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]);
+
+
+/*
+ *  Helper functions
+ */
+
+/**
+ * Print bin as hex
+ *
+ * @param bin binary data
+ * @param len number of bytes in bin
+ * @param hex pointer to len*2+1 bytes buffer
+ */
+static void
+bin2hex (const uint8_t *bin,
+         size_t len,
+         char *hex)
+{
+  while (len-- > 0)
+  {
+    unsigned int b1, b2;
+    b1 = (*bin >> 4) & 0xf;
+    *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0'));
+    b2 = *bin++ & 0xf;
+    *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0'));
+  }
+  *hex = 0;
+}
+
+
+static int
+check_result (const char *test_name,
+              unsigned int check_num,
+              const uint8_t calculated[SHA512_256_DIGEST_SIZE],
+              const uint8_t expected[SHA512_256_DIGEST_SIZE])
+{
+  int failed = memcmp (calculated, expected, SHA512_256_DIGEST_SIZE);
+  check_num++; /* Print 1-based numbers */
+  if (failed)
+  {
+    char calc_str[SHA512_256_DIGEST_SIZE * 2 + 1];
+    char expc_str[SHA512_256_DIGEST_SIZE * 2 + 1];
+    bin2hex (calculated, SHA512_256_DIGEST_SIZE, calc_str);
+    bin2hex (expected, SHA512_256_DIGEST_SIZE, expc_str);
+    fprintf (stderr,
+             "FAILED: %s check %u: calculated digest %s, expected digest %s.\n",
+             test_name, check_num, calc_str, expc_str);
+    fflush (stderr);
+  }
+  else if (verbose)
+  {
+    char calc_str[SHA512_256_DIGEST_SIZE * 2 + 1];
+    bin2hex (calculated, SHA512_256_DIGEST_SIZE, calc_str);
+    printf ("PASSED: %s check %u: calculated digest %s matches " \
+            "expected digest.\n",
+            test_name, check_num, calc_str);
+    fflush (stdout);
+  }
+  return failed ? 1 : 0;
+}
+
+
+/*
+ *  Tests
+ */
+
+/* Calculated SHA-512/256 as one pass for whole data */
+static int
+test1_str (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha512_256Ctx ctx;
+
+  for (i = 0; i < units1_num; i++)
+  {
+    uint8_t digest[SHA512_256_DIGEST_SIZE];
+
+    MHD_SHA512_256_init (&ctx);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str,
+                           data_units1[i].str_l.len);
+    MHD_SHA512_256_finish (&ctx, digest);
+    num_failed += check_result (__FUNCTION__, i, digest,
+                                data_units1[i].digest);
+  }
+  return num_failed;
+}
+
+
+static int
+test1_bin (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha512_256Ctx ctx;
+
+  for (i = 0; i < units2_num; i++)
+  {
+    uint8_t digest[SHA512_256_DIGEST_SIZE];
+
+    MHD_SHA512_256_init (&ctx);
+    MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin,
+                           data_units2[i].bin_l.len);
+    MHD_SHA512_256_finish (&ctx, digest);
+    num_failed += check_result (__FUNCTION__, i, digest,
+                                data_units2[i].digest);
+  }
+  return num_failed;
+}
+
+
+/* Calculated SHA-512/256 as two iterations for whole data */
+static int
+test2_str (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha512_256Ctx ctx;
+
+  for (i = 0; i < units1_num; i++)
+  {
+    uint8_t digest[SHA512_256_DIGEST_SIZE];
+    size_t part_s = data_units1[i].str_l.len / 4;
+
+    MHD_SHA512_256_init (&ctx);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str,
+                           part_s);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str
+                           + part_s,
+                           data_units1[i].str_l.len - part_s);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA512_256_finish (&ctx, digest);
+    num_failed += check_result (__FUNCTION__, i, digest,
+                                data_units1[i].digest);
+  }
+  return num_failed;
+}
+
+
+static int
+test2_bin (void)
+{
+  int num_failed = 0;
+  unsigned int i;
+  struct Sha512_256Ctx ctx;
+
+  for (i = 0; i < units2_num; i++)
+  {
+    uint8_t digest[SHA512_256_DIGEST_SIZE];
+    size_t part_s = data_units2[i].bin_l.len * 2 / 3;
+
+    MHD_SHA512_256_init (&ctx);
+    MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin, part_s);
+    MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0);
+    MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin + part_s,
+                           data_units2[i].bin_l.len - part_s);
+    MHD_SHA512_256_finish (&ctx, digest);
+    num_failed += check_result (__FUNCTION__, i, digest,
+                                data_units2[i].digest);
+  }
+  return num_failed;
+}
+
+
+/* Use data set number 7 as it has the longest sequence */
+#define DATA_POS 6
+#define MAX_OFFSET 63
+
+static int
+test_unaligned (void)
+{
+  int num_failed = 0;
+  unsigned int offset;
+  uint8_t *buf;
+  uint8_t *digest_buf;
+  struct Sha512_256Ctx ctx;
+
+  const struct data_unit2 *const tdata = data_units2 + DATA_POS;
+
+  buf = malloc (tdata->bin_l.len + MAX_OFFSET);
+  digest_buf = malloc (SHA512_256_DIGEST_SIZE + MAX_OFFSET);
+  if ((NULL == buf) || (NULL == digest_buf))
+    exit (99);
+
+  for (offset = MAX_OFFSET; offset >= 1; --offset)
+  {
+    uint8_t *unaligned_digest;
+    uint8_t *unaligned_buf;
+
+    unaligned_buf = buf + offset;
+    memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len);
+    unaligned_digest = digest_buf + MAX_OFFSET - offset;
+    memset (unaligned_digest, 0, SHA512_256_DIGEST_SIZE);
+
+    MHD_SHA512_256_init (&ctx);
+    MHD_SHA512_256_update (&ctx, unaligned_buf, tdata->bin_l.len);
+    MHD_SHA512_256_finish (&ctx, unaligned_digest);
+    num_failed += check_result (__FUNCTION__, MAX_OFFSET - offset,
+                                unaligned_digest, tdata->digest);
+  }
+  free (digest_buf);
+  free (buf);
+  return num_failed;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int num_failed = 0;
+  (void) has_in_name; /* Mute compiler warning. */
+  if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose"))
+    verbose = 1;
+
+  num_failed += test1_str ();
+  num_failed += test1_bin ();
+
+  num_failed += test2_str ();
+  num_failed += test2_bin ();
+
+  num_failed += test_unaligned ();
+
+  return num_failed ? 1 : 0;
+}
diff --git a/src/microhttpd/test_shutdown_select.c b/src/microhttpd/test_shutdown_select.c
new file mode 100644
index 0000000..437d27a
--- /dev/null
+++ b/src/microhttpd/test_shutdown_select.c
@@ -0,0 +1,390 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+     libmicrohttpd 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, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file microhttpd/test_shutdown_select.c
+ * @brief  Test whether shutdown socket triggers select()/poll()
+ * @details On some platforms shutting down the socket in one thread
+ *          triggers select() or poll() waiting for this socket in
+ *          other thread. libmicrohttpd depends on this behavior on
+ *          these platforms. This program check whether select()
+ *          and poll() (if available) work as expected.
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "MHD_config.h"
+#include "platform.h"
+#include "mhd_sockets.h"
+#include <stdlib.h>
+#include <stdio.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+
+#if defined(MHD_USE_POSIX_THREADS)
+#include <pthread.h>
+#endif /* MHD_USE_POSIX_THREADS */
+
+#if defined(MHD_WINSOCK_SOCKETS)
+#include <winsock2.h>
+#include <windows.h>
+#define sock_errno (WSAGetLastError ())
+#elif defined(MHD_POSIX_SOCKETS)
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif /* HAVE_SYS_SOCKET_H */
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif /* HAVE_NETINET_IN_H */
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif /* HAVE_ARPA_INET_H */
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif /* HAVE_SYS_SELECT_H */
+#if defined(HAVE_POLL) && defined(HAVE_POLL_H)
+#include <poll.h>
+#endif /* HAVE_POLL && HAVE_POLL_H */
+#define sock_errno (errno)
+#endif /* MHD_POSIX_SOCKETS */
+
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+#include "mhd_threads.h"
+
+#ifndef SOMAXCONN
+#define SOMAXCONN 511
+#endif /* ! SOMAXCONN */
+
+#if ! defined(SHUT_RDWR) && defined(SD_BOTH)
+#define SHUT_RDWR SD_BOTH
+#endif
+
+static bool check_err;
+
+
+static bool
+has_in_name (const char *prog_name, const char *marker)
+{
+  size_t name_pos;
+  size_t pos;
+
+  if (! prog_name || ! marker)
+    return 0;
+
+  pos = 0;
+  name_pos = 0;
+  while (prog_name[pos])
+  {
+    if ('/' == prog_name[pos])
+      name_pos = pos + 1;
+#if defined(_WIN32) || defined(__CYGWIN__)
+    else if ('\\' == prog_name[pos])
+      name_pos = pos + 1;
+#endif /* _WIN32 || __CYGWIN__ */
+    pos++;
+  }
+  if (name_pos == pos)
+    return true;
+  return strstr (prog_name + name_pos, marker) != NULL;
+}
+
+
+static MHD_socket
+start_socket_listen (int domain)
+{
+/* Create sockets similarly to daemon.c */
+  MHD_socket fd;
+  int cloexec_set;
+  struct sockaddr_in sock_addr;
+  socklen_t addrlen;
+
+#ifdef MHD_WINSOCK_SOCKETS
+  unsigned long flags = 1;
+#else  /* MHD_POSIX_SOCKETS */
+  int flags;
+#endif /* MHD_POSIX_SOCKETS */
+
+#if defined(MHD_POSIX_SOCKETS) && defined(SOCK_CLOEXEC)
+  fd = socket (domain, SOCK_STREAM | SOCK_CLOEXEC, 0);
+  cloexec_set = 1;
+#elif defined(MHD_WINSOCK_SOCKETS) && defined(WSA_FLAG_NO_HANDLE_INHERIT)
+  fd = WSASocketW (domain, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT);
+  cloexec_set = 1;
+#else  /* !SOCK_CLOEXEC */
+  fd = socket (domain, SOCK_STREAM, 0);
+  cloexec_set = 0;
+#endif /* !SOCK_CLOEXEC */
+  if ( (MHD_INVALID_SOCKET == fd) && (cloexec_set) )
+  {
+    fd = socket (domain, SOCK_STREAM, 0);
+    cloexec_set = 0;
+  }
+  if (MHD_INVALID_SOCKET == fd)
+  {
+    fprintf (stderr, "Can't create socket: %u\n",
+             (unsigned) sock_errno);
+    return MHD_INVALID_SOCKET;
+  }
+
+  if (! cloexec_set)
+  {
+#ifdef MHD_WINSOCK_SOCKETS
+    if (! SetHandleInformation ((HANDLE) fd, HANDLE_FLAG_INHERIT, 0))
+      fprintf (stderr, "Failed to make socket non-inheritable: %u\n",
+               (unsigned int) GetLastError ());
+#else  /* MHD_POSIX_SOCKETS */
+    flags = fcntl (fd, F_GETFD);
+    if ( ( (-1 == flags) ||
+           ( (flags != (flags | FD_CLOEXEC)) &&
+             (0 != fcntl (fd, F_SETFD, flags | FD_CLOEXEC)) ) ) )
+      fprintf (stderr, "Failed to make socket non-inheritable: %s\n",
+               MHD_socket_last_strerr_ ());
+#endif /* MHD_POSIX_SOCKETS */
+  }
+
+  memset (&sock_addr, 0, sizeof (struct sockaddr_in));
+  sock_addr.sin_family = AF_INET;
+  sock_addr.sin_port = htons (0);
+#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+  sock_addr.sin_len = sizeof (struct sockaddr_in);
+#endif
+  addrlen = sizeof (struct sockaddr_in);
+
+  if (bind (fd, (const struct sockaddr *) &sock_addr, addrlen) < 0)
+  {
+    fprintf (stderr, "Failed to bind socket: %u\n",
+             (unsigned) sock_errno);
+    MHD_socket_close_chk_ (fd);
+    return MHD_INVALID_SOCKET;
+  }
+
+#ifdef MHD_WINSOCK_SOCKETS
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+  {
+    fprintf (stderr, "Failed to make socket non-blocking: %u\n",
+             (unsigned) sock_errno);
+    MHD_socket_close_chk_ (fd);
+    return MHD_INVALID_SOCKET;
+  }
+#else  /* MHD_POSIX_SOCKETS */
+  flags = fcntl (fd, F_GETFL);
+  if ( ( (-1 == flags) ||
+         ( (flags != (flags | O_NONBLOCK)) &&
+           (0 != fcntl (fd, F_SETFL, flags | O_NONBLOCK)) ) ) )
+  {
+    fprintf (stderr, "Failed to make socket non-blocking: %s\n",
+             MHD_socket_last_strerr_ ());
+    MHD_socket_close_chk_ (fd);
+    return MHD_INVALID_SOCKET;
+  }
+#endif /* MHD_POSIX_SOCKETS */
+
+  if (listen (fd, SOMAXCONN) < 0)
+  {
+    fprintf (stderr, "Failed to listen on socket: %u\n",
+             (unsigned) sock_errno);
+    MHD_socket_close_chk_ (fd);
+    return MHD_INVALID_SOCKET;
+  }
+
+  return fd;
+}
+
+
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+select_thread (void *data)
+{
+  /* use select() like in daemon.c */
+  MHD_socket listen_sock = *((MHD_socket *) data);
+  fd_set rs, ws;
+  struct timeval timeout;
+
+  FD_ZERO (&rs);
+  FD_ZERO (&ws);
+  FD_SET (listen_sock, &rs);
+  timeout.tv_usec = 0;
+  timeout.tv_sec = 7;
+
+  check_err = (0 > MHD_SYS_select_ (listen_sock + 1, &rs, &ws, NULL, &timeout));
+
+  return (MHD_THRD_RTRN_TYPE_) 0;
+}
+
+
+#ifdef HAVE_POLL
+static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
+poll_thread (void *data)
+{
+  /* use poll() like in daemon.c */
+  struct pollfd p[1];
+  MHD_socket listen_sock = *((MHD_socket *) data);
+
+  p[0].fd = listen_sock;
+  p[0].events = POLLIN;
+  p[0].revents = 0;
+
+  check_err = (0 > MHD_sys_poll_ (p, 1, 7000));
+
+  return (MHD_THRD_RTRN_TYPE_) 0;
+}
+
+
+#endif /* HAVE_POLL */
+
+
+static void
+local_sleep (unsigned seconds)
+{
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+  Sleep (seconds * 1000);
+#else
+  unsigned seconds_left = seconds;
+  do
+  {
+    seconds_left = sleep (seconds_left);
+  } while (seconds_left > 0);
+#endif
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  int i;
+  time_t start_t, end_t;
+  int result = 0;
+  MHD_THRD_RTRN_TYPE_ (MHD_THRD_CALL_SPEC_ * test_func)(void *data);
+#ifdef MHD_WINSOCK_SOCKETS
+  WORD ver_req;
+  WSADATA wsa_data;
+  int err;
+#endif /* MHD_WINSOCK_SOCKETS */
+  bool test_poll;
+  bool must_ignore;
+  (void) argc; /* Unused. Silent compiler warning. */
+
+  test_poll = has_in_name (argv[0], "_poll");
+  must_ignore = has_in_name (argv[0], "_ignore");
+  if (! test_poll)
+    test_func = &select_thread;
+  else
+  {
+#ifndef HAVE_POLL
+    return 77;
+#else  /* ! HAVE_POLL */
+    test_func = &poll_thread;
+#endif /* ! HAVE_POLL */
+  }
+
+#ifdef MHD_WINSOCK_SOCKETS
+  ver_req = MAKEWORD (2, 2);
+
+  err = WSAStartup (ver_req, &wsa_data);
+  if ((err != 0) || (MAKEWORD (2, 2) != wsa_data.wVersion))
+  {
+    printf ("WSAStartup() failed\n");
+    WSACleanup ();
+    return 99;
+  }
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  /* try several times to ensure that accidental incoming connection
+   * didn't interfere with test results
+   */
+  for (i = 0; i < 5 && result == 0; i++)
+  {
+    MHD_thread_handle_ sel_thrd;
+    /* fprintf(stdout, "Creating, binding and listening socket...\n"); */
+    MHD_socket listen_socket = start_socket_listen (AF_INET);
+    if (MHD_INVALID_SOCKET == listen_socket)
+      return 99;
+
+    check_err = true;
+    /* fprintf (stdout, "Starting select() thread...\n"); */
+#if defined(MHD_USE_POSIX_THREADS)
+    if (0 != pthread_create (&sel_thrd, NULL, test_func, &listen_socket))
+    {
+      MHD_socket_close_chk_ (listen_socket);
+      fprintf (stderr, "Can't start thread\n");
+      return 99;
+    }
+#elif defined(MHD_USE_W32_THREADS)
+    sel_thrd = (HANDLE) _beginthreadex (NULL, 0, test_func, &listen_socket, 0,
+                                        NULL);
+    if (0 == (sel_thrd))
+    {
+      MHD_socket_close_chk_ (listen_socket);
+      fprintf (stderr, "Can't start select() thread\n");
+      return 99;
+    }
+#else
+#error No threading lib available
+#endif
+    /* fprintf (stdout, "Waiting...\n"); */
+    local_sleep (1);  /* make sure that select() is started */
+
+    /* fprintf (stdout, "Shutting down socket...\n"); */
+    start_t = time (NULL);
+    shutdown (listen_socket, SHUT_RDWR);
+
+    /* fprintf (stdout, "Waiting for thread to finish...\n"); */
+    if (! MHD_join_thread_ (sel_thrd))
+    {
+      MHD_socket_close_chk_ (listen_socket);
+      fprintf (stderr, "Can't join select() thread\n");
+      return 99;
+    }
+    if (check_err)
+    {
+      MHD_socket_close_chk_ (listen_socket);
+      fprintf (stderr, "Error in waiting thread\n");
+      return 99;
+    }
+    end_t = time (NULL);
+    /* fprintf (stdout, "Thread finished.\n"); */
+    MHD_socket_close_chk_ (listen_socket);
+
+    if ((start_t == (time_t) -1) || (end_t == (time_t) -1) )
+    {
+      MHD_socket_close_chk_ (listen_socket);
+      fprintf (stderr, "Can't get current time\n");
+      return 99;
+    }
+    if (end_t - start_t > 3)
+      result++;
+  }
+
+#ifdef MHD_WINSOCK_SOCKETS
+  WSACleanup ();
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  return must_ignore ? (! result) : (result);
+}
diff --git a/src/microhttpd/test_start_stop.c b/src/microhttpd/test_start_stop.c
new file mode 100644
index 0000000..a64f301
--- /dev/null
+++ b/src/microhttpd/test_start_stop.c
@@ -0,0 +1,155 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2011 Christian Grothoff
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_start_stop.c
+ * @brief  test for #1901 (start+stop)
+ * @author Christian Grothoff
+ */
+#include "mhd_options.h"
+#include "platform.h"
+#include <microhttpd.h>
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  (void) cls; (void) connection; (void) url;         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls;           /* Unused. Silent compiler warning. */
+
+  return MHD_NO;
+}
+
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+static unsigned int
+testInternalGet (unsigned int poll_flag)
+{
+  struct MHD_Daemon *d;
+
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | poll_flag,
+                        0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  MHD_stop_daemon (d);
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedGet (unsigned int poll_flag)
+{
+  struct MHD_Daemon *d;
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | poll_flag,
+                        0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  if (d == NULL)
+    return 2;
+  MHD_stop_daemon (d);
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (unsigned int poll_flag)
+{
+  struct MHD_Daemon *d;
+
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | poll_flag,
+                        0, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 4;
+  MHD_stop_daemon (d);
+  return 0;
+}
+
+
+#endif
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        0, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
+  if (NULL == d)
+    return 8;
+  MHD_stop_daemon (d);
+  return 0;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc;
+  (void) argv; /* Unused. Silence compiler warning. */
+
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  errorCount += testInternalGet (0);
+  errorCount += testMultithreadedGet (0);
+  errorCount += testMultithreadedPoolGet (0);
+#endif
+  errorCount += testExternalGet ();
+#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+  {
+    errorCount += testInternalGet (MHD_USE_POLL);
+    errorCount += testMultithreadedGet (MHD_USE_POLL);
+    errorCount += testMultithreadedPoolGet (MHD_USE_POLL);
+  }
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+  {
+    errorCount += testInternalGet (MHD_USE_EPOLL);
+    errorCount += testMultithreadedPoolGet (MHD_USE_EPOLL);
+  }
+#endif
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/microhttpd/test_str.c b/src/microhttpd/test_str.c
new file mode 100644
index 0000000..650510a
--- /dev/null
+++ b/src/microhttpd/test_str.c
@@ -0,0 +1,4516 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/unit_str_test.h
+ * @brief  Unit tests for mhd_str functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <stdio.h>
+#include <locale.h>
+#include <string.h>
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#else  /* ! HAVE_INTTYPES_H */
+#define PRIu64  "llu"
+#define PRIuPTR "u"
+#define PRIX64 "llX"
+#endif /* ! HAVE_INTTYPES_H */
+#include <stdint.h>
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
+#include "mhd_limits.h"
+#include "mhd_str.h"
+#include "test_helpers.h"
+
+
+static int verbose = 0; /* verbose level (0-3)*/
+
+/* Locale names to test.
+ * Functions must not depend of current current locale,
+ * so result must be the same in any locale.
+ */
+static const char *const locale_names[] = {
+  "C",
+  "",        /* System default locale */
+#if defined(_WIN32) && ! defined(__CYGWIN__)
+  ".OCP",    /* W32 system default OEM code page */
+  ".ACP",    /* W32 system default ANSI code page */
+  ".65001",  /* UTF-8 */
+  ".437",
+  ".850",
+  ".857",
+  ".866",
+  ".1250",
+  ".1251",
+  ".1252",
+  ".1254",
+  ".20866",   /* number for KOI8-R */
+  ".28591",   /* number for ISO-8859-1 */
+  ".28595",   /* number for ISO-8859-5 */
+  ".28599",   /* number for ISO-8859-9 */
+  ".28605",   /* number for ISO-8859-15 */
+  "en",
+  "english",
+  "en-US",
+  "English-US",
+  "en-US.437",
+  "English_United States.437",
+  "en-US.1252",
+  "English_United States.1252",
+  "English_United States.28591",
+  "English_United States.65001",
+  "fra",
+  "french",
+  "fr-FR",
+  "French_France",
+  "fr-FR.850",
+  "french_france.850",
+  "fr-FR.1252",
+  "French_france.1252",
+  "French_france.28605",
+  "French_France.65001",
+  "de",
+  "de-DE",
+  "de-DE.850",
+  "German_Germany.850",
+  "German_Germany.1250",
+  "de-DE.1252",
+  "German_Germany.1252",
+  "German_Germany.28605",
+  "German_Germany.65001",
+  "tr",
+  "trk",
+  "turkish",
+  "tr-TR",
+  "tr-TR.1254",
+  "Turkish_Turkey.1254",
+  "tr-TR.857",
+  "Turkish_Turkey.857",
+  "Turkish_Turkey.28599",
+  "Turkish_Turkey.65001",
+  "ru",
+  "ru-RU",
+  "Russian",
+  "ru-RU.866",
+  "Russian_Russia.866",
+  "ru-RU.1251",
+  "Russian_Russia.1251",
+  "Russian_Russia.20866",
+  "Russian_Russia.28595",
+  "Russian_Russia.65001",
+  "zh-Hans",
+  "zh-Hans.936",
+  "chinese-simplified"
+#else /* ! _WIN32 || __CYGWIN__ */
+  "C.UTF-8",
+  "POSIX",
+  "en",
+  "en_US",
+  "en_US.ISO-8859-1",
+  "en_US.ISO_8859-1",
+  "en_US.ISO8859-1",
+  "en_US.iso88591",
+  "en_US.ISO-8859-15",
+  "en_US.DIS_8859-15",
+  "en_US.ISO8859-15",
+  "en_US.iso885915",
+  "en_US.1252",
+  "en_US.CP1252",
+  "en_US.UTF-8",
+  "en_US.utf8",
+  "fr",
+  "fr_FR",
+  "fr_FR.850",
+  "fr_FR.IBM850",
+  "fr_FR.1252",
+  "fr_FR.CP1252",
+  "fr_FR.ISO-8859-1",
+  "fr_FR.ISO_8859-1",
+  "fr_FR.ISO8859-1",
+  "fr_FR.iso88591",
+  "fr_FR.ISO-8859-15",
+  "fr_FR.DIS_8859-15",
+  "fr_FR.ISO8859-15",
+  "fr_FR.iso8859-15",
+  "fr_FR.UTF-8",
+  "fr_FR.utf8",
+  "de",
+  "de_DE",
+  "de_DE.850",
+  "de_DE.IBM850",
+  "de_DE.1250",
+  "de_DE.CP1250",
+  "de_DE.1252",
+  "de_DE.CP1252",
+  "de_DE.ISO-8859-1",
+  "de_DE.ISO_8859-1",
+  "de_DE.ISO8859-1",
+  "de_DE.iso88591",
+  "de_DE.ISO-8859-15",
+  "de_DE.DIS_8859-15",
+  "de_DE.ISO8859-15",
+  "de_DE.iso885915",
+  "de_DE.UTF-8",
+  "de_DE.utf8",
+  "tr",
+  "tr_TR",
+  "tr_TR.1254",
+  "tr_TR.CP1254",
+  "tr_TR.857",
+  "tr_TR.IBM857",
+  "tr_TR.ISO-8859-9",
+  "tr_TR.ISO8859-9",
+  "tr_TR.iso88599",
+  "tr_TR.UTF-8",
+  "tr_TR.utf8",
+  "ru",
+  "ru_RU",
+  "ru_RU.1251",
+  "ru_RU.CP1251",
+  "ru_RU.866",
+  "ru_RU.IBM866",
+  "ru_RU.KOI8-R",
+  "ru_RU.koi8-r",
+  "ru_RU.KOI8-RU",
+  "ru_RU.ISO-8859-5",
+  "ru_RU.ISO_8859-5",
+  "ru_RU.ISO8859-5",
+  "ru_RU.iso88595",
+  "ru_RU.UTF-8",
+  "zh_CN",
+  "zh_CN.GB2312",
+  "zh_CN.UTF-8",
+#endif /* ! _WIN32 || __CYGWIN__ */
+};
+
+static const unsigned int locale_name_count = sizeof(locale_names)
+                                              / sizeof(locale_names[0]);
+
+
+/*
+ *  Helper functions
+ */
+
+static int
+set_test_locale (size_t num)
+{
+  if (num >= locale_name_count)
+  {
+    fprintf (stderr, "Unexpected number of locale.\n");
+    exit (99);
+  }
+  if (verbose > 2)
+    printf ("Setting locale \"%s\":", locale_names[num]);
+  if (setlocale (LC_ALL, locale_names[num]))
+  {
+    if (verbose > 2)
+      printf (" succeed.\n");
+    return 1;
+  }
+  if (verbose > 2)
+    printf (" failed.\n");
+  return 0;
+}
+
+
+static const char *
+get_current_locale_str (void)
+{
+  char const *loc_str = setlocale (LC_ALL, NULL);
+  return loc_str ? loc_str : "unknown";
+}
+
+
+static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */
+static size_t buf_idx = 0;
+
+/* print non-printable chars as char codes */
+static char *
+n_prnt (const char *str)
+{
+  static char *buf;  /* should be enough for testing */
+  static const size_t buf_size = sizeof(tmp_bufs[0]);
+  const unsigned char *p = (const unsigned char *) str;
+  size_t w_pos = 0;
+  if (++buf_idx > 3)
+    buf_idx = 0;
+  buf = tmp_bufs[buf_idx];
+
+  while (*p && w_pos + 1 < buf_size)
+  {
+    const unsigned char c = *p;
+    if ((c == '\\') || (c == '"') )
+    {
+      if (w_pos + 2 >= buf_size)
+        break;
+      buf[w_pos++] = '\\';
+      buf[w_pos++] = (char) c;
+    }
+    else if ((c >= 0x20) && (c <= 0x7E) )
+      buf[w_pos++] = (char) c;
+    else
+    {
+      if (w_pos + 4 >= buf_size)
+        break;
+      if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned
+                                                                int) c) != 4)
+        break;
+      w_pos += 4;
+    }
+    p++;
+  }
+  if (*p)
+  {   /* not full string is printed */
+      /* enough space for "..." ? */
+    if (w_pos + 3 > buf_size)
+      w_pos = buf_size - 4;
+    buf[w_pos++] = '.';
+    buf[w_pos++] = '.';
+    buf[w_pos++] = '.';
+  }
+  buf[w_pos] = 0;
+  return buf;
+}
+
+
+struct str_with_len
+{
+  const char *const str;
+  const size_t len;
+};
+
+#define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1}
+
+/*
+ * String caseless equality functions tests
+ */
+
+struct two_eq_strs
+{
+  const struct str_with_len s1;
+  const struct str_with_len s2;
+};
+
+static const struct two_eq_strs eq_strings[] = {
+  {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."),
+   D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`.")},
+  {D_STR_W_LEN ("Simple string."), D_STR_W_LEN ("Simple string.")},
+  {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("SIMPLE STRING.")},
+  {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("simple string.")},
+  {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("Simple String.")},
+  {D_STR_W_LEN ("sImPlE StRiNg."), D_STR_W_LEN ("SiMpLe sTrInG.")},
+  {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("simple string.")},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"),
+   D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz")},
+  {D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
+   D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"),
+   D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")},
+  {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"),
+   D_STR_W_LEN ("ZYXWVUTSRQPONmlkjihgfedcba")},
+
+  {D_STR_W_LEN ("Cha\x8cne pour le test."),
+   D_STR_W_LEN ("Cha\x8cne pour le test.")},      /* "Chaîne pour le test." in CP850 */
+  {D_STR_W_LEN ("cha\x8cne pOur Le TEst."),
+   D_STR_W_LEN ("Cha\x8cne poUr Le teST.")},
+  {D_STR_W_LEN ("Cha\xeene pour le test."),
+   D_STR_W_LEN ("Cha\xeene pour le test.")},      /* "Chaîne pour le test." in CP1252/ISO-8859-1/ISO-8859-15 */
+  {D_STR_W_LEN ("CHa\xeene POUR le test."),
+   D_STR_W_LEN ("Cha\xeeNe pour lE TEST.")},
+  {D_STR_W_LEN ("Cha\xc3\xaene pour le Test."),
+   D_STR_W_LEN ("Cha\xc3\xaene pour le Test.")},  /* "Chaîne pour le test." in UTF-8 */
+  {D_STR_W_LEN ("ChA\xc3\xaene pouR lE TesT."),
+   D_STR_W_LEN ("Cha\xc3\xaeNe Pour le teSt.")},
+
+  {D_STR_W_LEN (".Beispiel Zeichenfolge"),
+   D_STR_W_LEN (".Beispiel Zeichenfolge")},
+  {D_STR_W_LEN (".bEisPiel ZEIchenfoLgE"),
+   D_STR_W_LEN (".BEiSpiEl zeIcheNfolge")},
+
+  {D_STR_W_LEN ("Do\xa7rulama \x87izgi!"),
+   D_STR_W_LEN ("Do\xa7rulama \x87izgi!")},       /* "Doğrulama çizgi!" in CP857 */
+  {D_STR_W_LEN ("Do\xa7rulama \x87IzgI!"),        /* Spelling intentionally incorrect here */
+   D_STR_W_LEN ("Do\xa7rulama \x87izgi!")},       /* Note: 'i' is not caseless equal to 'I' in Turkish */
+  {D_STR_W_LEN ("Do\xf0rulama \xe7izgi!"),
+   D_STR_W_LEN ("Do\xf0rulama \xe7izgi!")},       /* "Doğrulama çizgi!" in CP1254/ISO-8859-9 */
+  {D_STR_W_LEN ("Do\xf0rulamA \xe7Izgi!"),
+   D_STR_W_LEN ("do\xf0rulama \xe7izgi!")},
+  {D_STR_W_LEN ("Do\xc4\x9frulama \xc3\xa7izgi!"),
+   D_STR_W_LEN ("Do\xc4\x9frulama \xc3\xa7izgi!")},         /* "Doğrulama çizgi!" in UTF-8 */
+  {D_STR_W_LEN ("do\xc4\x9fruLAMA \xc3\xa7Izgi!"),          /* Spelling intentionally incorrect here */
+   D_STR_W_LEN ("DO\xc4\x9frulama \xc3\xa7izgI!")},         /* Spelling intentionally incorrect here */
+
+  {D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0."),
+   D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0.")},  /* "Тестовая Строка." in CP866 */
+  {D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0."),
+   D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0.")},  /* "Тестовая Строка." in CP1251 */
+  {D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1."),
+   D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1.")},  /* "Тестовая Строка." in KOI8-R */
+  {D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0."),
+   D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0.")},  /* "Тестовая Строка." in ISO-8859-5 */
+  {D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1"
+                "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0."),
+   D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1"
+                "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0.")},      /* "Тестовая Строка." in UTF-8 */
+
+  {D_STR_W_LEN (
+     "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
+     "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@[\\]"
+     "^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
+     "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4"
+     "\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8"
+     "\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc"
+     "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
+     "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4"
+     "\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"),
+   D_STR_W_LEN (
+     "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
+     "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@[\\]"
+     "^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
+     "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4"
+     "\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8"
+     "\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc"
+     "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
+     "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4"
+     "\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")},             /* Full sequence without a-z */
+  {D_STR_W_LEN (
+     "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
+     "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB"
+     "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83"
+     "\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97"
+     "\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab"
+     "\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf"
+     "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
+     "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7"
+     "\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb"
+     "\xfc\xfd\xfe\xff"),
+   D_STR_W_LEN (
+     "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
+     "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB"
+     "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83"
+     "\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97"
+     "\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab"
+     "\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf"
+     "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
+     "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7"
+     "\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb"
+     "\xfc\xfd\xfe\xff")},             /* Full sequence */
+  {D_STR_W_LEN (
+     "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
+     "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB"
+     "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89"
+     "\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d"
+     "\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1"
+     "\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
+     "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9"
+     "\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed"
+     "\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"),
+   D_STR_W_LEN (
+     "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
+     "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ab"
+     "cdefghijklmnopqrstuvwxyz[\\]^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89"
+     "\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d"
+     "\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1"
+     "\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
+     "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9"
+     "\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed"
+     "\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")}             /* Full with A/a match */
+};
+
+struct two_neq_strs
+{
+  const struct str_with_len s1;
+  const struct str_with_len s2;
+  const size_t dif_pos;
+};
+
+static const struct two_neq_strs neq_strings[] = {
+  {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."),
+   D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`"), 27},
+  {D_STR_W_LEN (".1234567890!@~%&$@#{}[]\\/!?`."),
+   D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`"), 0},
+  {D_STR_W_LEN ("Simple string."), D_STR_W_LEN ("Simple ctring."), 7},
+  {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("simple string"), 13},
+  {D_STR_W_LEN ("simple strings"), D_STR_W_LEN ("Simple String."), 13},
+  {D_STR_W_LEN ("sImPlE StRiNg."), D_STR_W_LEN ("SYMpLe sTrInG."), 1},
+  {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("simple string.2"), 14},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz,"),
+   D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz."), 26},
+  {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz!"),
+   D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ?"), 26},
+  {D_STR_W_LEN ("zyxwvutsrqponwMLKJIHGFEDCBA"),
+   D_STR_W_LEN ("ZYXWVUTSRQPON%mlkjihgfedcba"), 13},
+
+  {D_STR_W_LEN ("S\xbdur veulent plus d'\xbdufs."),         /* "Sœur veulent plus d'œufs." in ISO-8859-15 */
+   D_STR_W_LEN ("S\xbcUR VEULENT PLUS D'\xbcUFS."), 1}, /* "SŒUR VEULENT PLUS D'ŒUFS." in ISO-8859-15 */
+  {D_STR_W_LEN ("S\x9cur veulent plus d'\x9cufs."),         /* "Sœur veulent plus d'œufs." in CP1252 */
+   D_STR_W_LEN ("S\x8cUR VEULENT PLUS D'\x8cUFS."), 1}, /* "SŒUR VEULENT PLUS D'ŒUFS." in CP1252 */
+  {D_STR_W_LEN ("S\xc5\x93ur veulent plus d'\xc5\x93ufs."), /* "Sœur veulent plus d'œufs." in UTF-8 */
+   D_STR_W_LEN ("S\xc5\x92UR VEULENT PLUS D'\xc5\x92UFS."), 2}, /* "SŒUR VEULENT PLUS D'ŒUFS." in UTF-8 */
+
+  {D_STR_W_LEN ("Um ein sch\x94nes M\x84" "dchen zu k\x81ssen."),              /* "Um ein schönes Mädchen zu küssen." in CP850 */
+   D_STR_W_LEN ("UM EIN SCH\x99NES M\x8e" "DCHEN ZU K\x9aSSEN."), 10}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in CP850 */
+  {D_STR_W_LEN ("Um ein sch\xf6nes M\xe4" "dchen zu k\xfcssen."),              /* "Um ein schönes Mädchen zu küssen." in ISO-8859-1/ISO-8859-15/CP1250/CP1252 */
+   D_STR_W_LEN ("UM EIN SCH\xd6NES M\xc4" "DCHEN ZU K\xdcSSEN."), 10}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in ISO-8859-1/ISO-8859-15/CP1250/CP1252 */
+  {D_STR_W_LEN ("Um ein sch\xc3\xb6nes M\xc3\xa4" "dchen zu k\xc3\xbcssen."),  /* "Um ein schönes Mädchen zu küssen." in UTF-8 */
+   D_STR_W_LEN ("UM EIN SCH\xc3\x96NES M\xc3\x84" "DCHEN ZU K\xc3\x9cSSEN."),
+   11},                                                                        /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in UTF-8 */
+
+  {D_STR_W_LEN ("\x98stanbul"),                                                /* "İstanbul" in CP857 */
+   D_STR_W_LEN ("istanbul"), 0},                                               /* "istanbul" in CP857 */
+  {D_STR_W_LEN ("\xddstanbul"),                                                /* "İstanbul" in ISO-8859-9/CP1254 */
+   D_STR_W_LEN ("istanbul"), 0},                                               /* "istanbul" in ISO-8859-9/CP1254 */
+  {D_STR_W_LEN ("\xc4\xb0stanbul"),                                            /* "İstanbul" in UTF-8 */
+   D_STR_W_LEN ("istanbul"), 0},                                               /* "istanbul" in UTF-8 */
+  {D_STR_W_LEN ("Diyarbak\x8dr"),                                              /* "Diyarbakır" in CP857 */
+   D_STR_W_LEN ("DiyarbakIR"), 8},                                             /* "DiyarbakIR" in CP857 */
+  {D_STR_W_LEN ("Diyarbak\xfdr"),                                              /* "Diyarbakır" in ISO-8859-9/CP1254 */
+   D_STR_W_LEN ("DiyarbakIR"), 8},                                             /* "DiyarbakIR" in ISO-8859-9/CP1254 */
+  {D_STR_W_LEN ("Diyarbak\xc4\xb1r"),                                          /* "Diyarbakır" in UTF-8 */
+   D_STR_W_LEN ("DiyarbakIR"), 8},                                             /* "DiyarbakIR" in UTF-8 */
+
+  {D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0."), /* "Тестовая Строка." in CP866 */
+   D_STR_W_LEN ("\x92\x85\x91\x92\x8e\x82\x80\x9f \x91\x92\x90\x8e\x8a\x80."),
+   1},                                                                         /* "ТЕСТОВАЯ СТРОКА." in CP866 */
+  {D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0."), /* "Тестовая Строка." in CP1251 */
+   D_STR_W_LEN ("\xd2\xc5\xd1\xd2\xce\xc2\xc0\xdf \xd1\xd2\xd0\xce\xca\xc0."),
+   1},                                                                         /* "ТЕСТОВАЯ СТРОКА." in CP1251 */
+  {D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1."), /* "Тестовая Строка." in KOI8-R */
+   D_STR_W_LEN ("\xf4\xe5\xf3\xf4\xef\xf7\xe1\xf1 \xf3\xf4\xf2\xef\xeb\xe1."),
+   1},                                                                         /* "ТЕСТОВАЯ СТРОКА." in KOI8-R */
+  {D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0."), /* "Тестовая Строка." in ISO-8859-5 */
+   D_STR_W_LEN ("\xc2\xb5\xc1\xc2\xbe\xb2\xb0\xcf \xc1\xc2\xc0\xbe\xba\xb0."),
+   1},                                                                         /* "ТЕСТОВАЯ СТРОКА." in ISO-8859-5 */
+  {D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1"
+                "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0."),     /* "Тестовая Строка." in UTF-8 */
+   D_STR_W_LEN ("\xd0\xa2\xd0\x95\xd0\xa1\xd0\xa2\xd0\x9e\xd0\x92\xd0\x90\xd0"
+                "\xaf \xd0\xa1\xd0\xa2\xd0\xa0\xd0\x9e\xd0\x9a\xd0\x90."), 3}  /* "ТЕСТОВАЯ СТРОКА." in UTF-8 */
+};
+
+
+static size_t
+check_eq_strings (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(eq_strings) / sizeof(eq_strings[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      const struct two_eq_strs *const t = eq_strings + i;
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+      if (! MHD_str_equal_caseless_ (t->s1.str, t->s2.str))
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned zero, while expected non-zero."
+                 " Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str),
+                 get_current_locale_str ());
+      }
+      else if (! MHD_str_equal_caseless_ (t->s2.str, t->s1.str))
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned zero, while expected non-zero."
+                 " Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str),
+                 get_current_locale_str ());
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_equal_caseless_(\"%s\", \"%s\") != 0 && \\\n"
+                "        MHD_str_equal_caseless_(\"%s\", \"%s\") != 0\n",
+                n_prnt (t->s1.str), n_prnt (t->s2.str),
+                n_prnt (t->s2.str), n_prnt (t->s1.str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_neq_strings (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(neq_strings) / sizeof(neq_strings[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      const struct two_neq_strs *const t = neq_strings + i;
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+      if (MHD_str_equal_caseless_ (t->s1.str, t->s2.str))
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned non-zero, while expected zero."
+                 " Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str),
+                 get_current_locale_str ());
+      }
+      else if (MHD_str_equal_caseless_ (t->s2.str, t->s1.str))
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned non-zero, while expected zero."
+                 " Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str),
+                 get_current_locale_str ());
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_equal_caseless_(\"%s\", \"%s\") == 0 && \\\n"
+                "        MHD_str_equal_caseless_(\"%s\", \"%s\") == 0\n",
+                n_prnt (t->s1.str), n_prnt (t->s2.str),
+                n_prnt (t->s2.str), n_prnt (t->s1.str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_eq_strings_n (void)
+{
+  size_t t_failed = 0;
+  size_t i, j, k;
+  int c_failed[sizeof(eq_strings) / sizeof(eq_strings[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t m_len;
+      const struct two_eq_strs *const t = eq_strings + i;
+      m_len = (t->s1.len > t->s2.len) ? t->s1.len : t->s2.len;
+      for (k = 0; k <= m_len + 1 && ! c_failed[i]; k++)
+      {
+        if (! MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k))
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero,"
+                   " while expected non-zero. Locale: %s\n",
+                   n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k,
+                   get_current_locale_str ());
+        }
+        else if (! MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k))
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero,"
+                   " while expected non-zero. Locale: %s\n",
+                   n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k,
+                   get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) " \
+                "!= 0 && \\\n" \
+                "        MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) " \
+                "!= 0, where N is 0..%u\n",
+                n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str),
+                n_prnt (t->s1.str), (unsigned int) m_len + 1);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_neq_strings_n (void)
+{
+  size_t t_failed = 0;
+  size_t i, j, k;
+  int c_failed[sizeof(neq_strings) / sizeof(neq_strings[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t m_len;
+      const struct two_neq_strs *const t = neq_strings + i;
+      m_len = t->s1.len > t->s2.len ? t->s1.len : t->s2.len;
+      if (t->dif_pos >= m_len)
+      {
+        fprintf (stderr,
+                 "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less than "
+                 "s1.len (%u) or s2.len (%u).\n", (unsigned int) i, (unsigned
+                                                                     int) t->
+                 dif_pos,
+                 (unsigned int) t->s1.len, (unsigned int) t->s2.len);
+        exit (99);
+      }
+      if (t->dif_pos > t->s1.len)
+      {
+        fprintf (stderr,
+                 "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less or "
+                 "equal to s1.len (%u).\n", (unsigned int) i, (unsigned
+                                                               int) t->dif_pos,
+                 (unsigned int) t->s1.len);
+        exit (99);
+      }
+      if (t->dif_pos > t->s2.len)
+      {
+        fprintf (stderr,
+                 "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less or "
+                 "equal to s2.len (%u).\n", (unsigned int) i, (unsigned
+                                                               int) t->dif_pos,
+                 (unsigned int) t->s2.len);
+        exit (99);
+      }
+      for (k = 0; k <= m_len + 1 && ! c_failed[i]; k++)
+      {
+        if (k <= t->dif_pos)
+        {
+          if (! MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k))
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero,"
+                     " while expected non-zero. Locale: %s\n",
+                     n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k,
+                     get_current_locale_str ());
+          }
+          else if (! MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k))
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero,"
+                     " while expected non-zero. Locale: %s\n",
+                     n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k,
+                     get_current_locale_str ());
+          }
+        }
+        else
+        {
+          if (MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k))
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned non-zero,"
+                     " while expected zero. Locale: %s\n",
+                     n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k,
+                     get_current_locale_str ());
+          }
+          else if (MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k))
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned non-zero,"
+                     " while expected zero. Locale: %s\n",
+                     n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+      {
+        printf (
+          "PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) != 0 && \\\n"
+          "        MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) != 0, where N is 0..%u\n",
+          n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str),
+          n_prnt (t->s1.str),
+          (unsigned int) t->dif_pos);
+
+        printf (
+          "PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) == 0 && \\\n"
+          "        MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) == 0, where N is %u..%u\n",
+          n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str),
+          n_prnt (t->s1.str),
+          (unsigned int) t->dif_pos + 1, (unsigned int) m_len + 1);
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+/*
+ * Run eq/neq strings tests
+ */
+static int
+run_eq_neq_str_tests (void)
+{
+  size_t str_equal_caseless_fails = 0;
+  size_t str_equal_caseless_n_fails = 0;
+  size_t res;
+
+  res = check_eq_strings ();
+  if (res != 0)
+  {
+    str_equal_caseless_fails += res;
+    fprintf (stderr, "FAILED: testcase check_eq_strings() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_eq_strings() successfully passed.\n\n");
+
+  res = check_neq_strings ();
+  if (res != 0)
+  {
+    str_equal_caseless_fails += res;
+    fprintf (stderr, "FAILED: testcase check_neq_strings() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_neq_strings() successfully passed.\n\n");
+
+  if (str_equal_caseless_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_str_equal_caseless_() failed %lu time%s.\n\n",
+             (unsigned long) str_equal_caseless_fails,
+             str_equal_caseless_fails == 1 ? "" :
+             "s");
+  else if (verbose > 0)
+    printf (
+      "PASSED: function MHD_str_equal_caseless_() successfully passed all checks.\n\n");
+
+  res = check_eq_strings_n ();
+  if (res != 0)
+  {
+    str_equal_caseless_n_fails += res;
+    fprintf (stderr, "FAILED: testcase check_eq_strings_n() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_eq_strings_n() successfully passed.\n\n");
+
+  res = check_neq_strings_n ();
+  if (res != 0)
+  {
+    str_equal_caseless_n_fails += res;
+    fprintf (stderr, "FAILED: testcase check_neq_strings_n() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_neq_strings_n() successfully passed.\n\n");
+
+  if (str_equal_caseless_n_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_str_equal_caseless_n_() failed %lu time%s.\n\n",
+             (unsigned long) str_equal_caseless_n_fails,
+             str_equal_caseless_n_fails == 1 ? "" :
+             "s");
+  else if (verbose > 0)
+    printf (
+      "PASSED: function MHD_str_equal_caseless_n_() successfully passed all checks.\n\n");
+
+  if (str_equal_caseless_fails || str_equal_caseless_n_fails)
+  {
+    if (verbose > 0)
+      printf ("At least one test failed.\n");
+
+    return 1;
+  }
+
+  if (verbose > 0)
+    printf ("All tests passed successfully.\n");
+
+  return 0;
+}
+
+
+/*
+ * Digits in string -> value tests
+ */
+
+struct str_with_value
+{
+  const struct str_with_len str;
+  const size_t num_of_digt;
+  const uint64_t val;
+};
+
+/* valid string for conversion to unsigned integer value */
+static const struct str_with_value dstrs_w_values[] = {
+  /* simplest strings */
+  {D_STR_W_LEN ("1"), 1, 1},
+  {D_STR_W_LEN ("0"), 1, 0},
+  {D_STR_W_LEN ("10000"), 5, 10000},
+
+  /* all digits */
+  {D_STR_W_LEN ("1234"), 4, 1234},
+  {D_STR_W_LEN ("4567"), 4, 4567},
+  {D_STR_W_LEN ("7890"), 4, 7890},
+  {D_STR_W_LEN ("8021"), 4, 8021},
+  {D_STR_W_LEN ("9754"), 4, 9754},
+  {D_STR_W_LEN ("6392"), 4, 6392},
+
+  /* various prefixes */
+  {D_STR_W_LEN ("00000000"), 8, 0},
+  {D_STR_W_LEN ("0755"), 4, 755},  /* not to be interpreted as octal value! */
+  {D_STR_W_LEN ("002"), 3, 2},
+  {D_STR_W_LEN ("0001"), 4, 1},
+  {D_STR_W_LEN ("00000000000000000000000031295483"), 32, 31295483},
+
+  /* numbers below and above limits */
+  {D_STR_W_LEN ("127"), 3, 127},                /* 0x7F, SCHAR_MAX */
+  {D_STR_W_LEN ("128"), 3, 128},                /* 0x80, SCHAR_MAX+1 */
+  {D_STR_W_LEN ("255"), 3, 255},                /* 0xFF, UCHAR_MAX */
+  {D_STR_W_LEN ("256"), 3, 256},                /* 0x100, UCHAR_MAX+1 */
+  {D_STR_W_LEN ("32767"), 5, 32767},            /* 0x7FFF, INT16_MAX */
+  {D_STR_W_LEN ("32768"), 5, 32768},            /* 0x8000, INT16_MAX+1 */
+  {D_STR_W_LEN ("65535"), 5, 65535},            /* 0xFFFF, UINT16_MAX */
+  {D_STR_W_LEN ("65536"), 5, 65536},            /* 0x10000, UINT16_MAX+1 */
+  {D_STR_W_LEN ("2147483647"), 10, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */
+  {D_STR_W_LEN ("2147483648"), 10, UINT64_C (2147483648)}, /* 0x80000000, INT32_MAX+1 */
+  {D_STR_W_LEN ("4294967295"), 10, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */
+  {D_STR_W_LEN ("4294967296"), 10, UINT64_C (4294967296)}, /* 0x100000000, UINT32_MAX+1 */
+  {D_STR_W_LEN ("9223372036854775807"), 19, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */
+  {D_STR_W_LEN ("9223372036854775808"), 19, UINT64_C (9223372036854775808)}, /* 0x8000000000000000, INT64_MAX+1 */
+  {D_STR_W_LEN ("18446744073709551615"), 20, UINT64_C (18446744073709551615)},  /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */
+
+  /* random numbers */
+  {D_STR_W_LEN ("10186753"), 8, 10186753},
+  {D_STR_W_LEN ("144402566"), 9, 144402566},
+  {D_STR_W_LEN ("151903144"), 9, 151903144},
+  {D_STR_W_LEN ("139264621"), 9, 139264621},
+  {D_STR_W_LEN ("730348"), 6, 730348},
+  {D_STR_W_LEN ("21584377"), 8, 21584377},
+  {D_STR_W_LEN ("709"), 3, 709},
+  {D_STR_W_LEN ("54"), 2, 54},
+  {D_STR_W_LEN ("8452"), 4, 8452},
+  {D_STR_W_LEN ("17745098750013624977"), 20, UINT64_C (17745098750013624977)},
+  {D_STR_W_LEN ("06786878769931678000"), 20, UINT64_C (6786878769931678000)},
+
+  /* non-digit suffixes */
+  {D_STR_W_LEN ("1234oa"), 4, 1234},
+  {D_STR_W_LEN ("20h"), 2, 20},  /* not to be interpreted as hex value! */
+  {D_STR_W_LEN ("0x1F"), 1, 0},  /* not to be interpreted as hex value! */
+  {D_STR_W_LEN ("0564`~}"), 4, 564},
+  {D_STR_W_LEN ("7240146.724"), 7, 7240146},
+  {D_STR_W_LEN ("2,9"), 1, 2},
+  {D_STR_W_LEN ("200+1"), 3, 200},
+  {D_STR_W_LEN ("1a"), 1, 1},
+  {D_STR_W_LEN ("2E"), 1, 2},
+  {D_STR_W_LEN ("6c"), 1, 6},
+  {D_STR_W_LEN ("8F"), 1, 8},
+  {D_STR_W_LEN ("287416997! And the not too long string."), 9, 287416997}
+};
+
+/* strings that should overflow uint64_t */
+static const struct str_with_len str_ovflw[] = {
+  D_STR_W_LEN ("18446744073709551616"),  /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("18446744073709551620"),
+  D_STR_W_LEN ("18446744083709551615"),
+  D_STR_W_LEN ("19234761020556472143"),
+  D_STR_W_LEN ("184467440737095516150"),
+  D_STR_W_LEN ("1844674407370955161500"),
+  D_STR_W_LEN ("000018446744073709551616"),  /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("20000000000000000000"),
+  D_STR_W_LEN ("020000000000000000000"),
+  D_STR_W_LEN ("0020000000000000000000"),
+  D_STR_W_LEN ("100000000000000000000"),
+  D_STR_W_LEN ("434532891232591226417"),
+  D_STR_W_LEN ("99999999999999999999"),
+  D_STR_W_LEN ("18446744073709551616abcd"),  /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("20000000000000000000 suffix"),
+  D_STR_W_LEN ("020000000000000000000x")
+};
+
+/* strings that should not be convertible to numeric value */
+static const struct str_with_len str_no_num[] = {
+  D_STR_W_LEN ("zero"),
+  D_STR_W_LEN ("one"),
+  D_STR_W_LEN ("\xb9\xb2\xb3"),                                    /* superscript "123" in ISO-8859-1/CP1252 */
+  D_STR_W_LEN ("\xc2\xb9\xc2\xb2\xc2\xb3"),                        /* superscript "123" in UTF-8 */
+  D_STR_W_LEN ("\xd9\xa1\xd9\xa2\xd9\xa3"),                        /* Arabic-Indic "١٢٣" in UTF-8 */
+  D_STR_W_LEN ("\xdb\xb1\xdb\xb2\xdb\xb3"),                        /* Ext Arabic-Indic "۱۲۳" in UTF-8 */
+  D_STR_W_LEN ("\xe0\xa5\xa7\xe0\xa5\xa8\xe0\xa5\xa9"),            /* Devanagari "१२३" in UTF-8 */
+  D_STR_W_LEN ("\xe4\xb8\x80\xe4\xba\x8c\xe4\xb8\x89"),            /* Chinese "一二三" in UTF-8 */
+  D_STR_W_LEN ("\xd2\xbb\xb6\xfe\xc8\xfd"),                        /* Chinese "一二三" in GB2312/CP936 */
+  D_STR_W_LEN ("\x1B\x24\x29\x41\x0E\x52\x3B\x36\x7E\x48\x7D\x0F") /* Chinese "一二三" in ISO-2022-CN */
+};
+
+/* valid hex string for conversion to unsigned integer value */
+static const struct str_with_value xdstrs_w_values[] = {
+  /* simplest strings */
+  {D_STR_W_LEN ("1"), 1, 0x1},
+  {D_STR_W_LEN ("0"), 1, 0x0},
+  {D_STR_W_LEN ("10000"), 5, 0x10000},
+
+  /* all digits */
+  {D_STR_W_LEN ("1234"), 4, 0x1234},
+  {D_STR_W_LEN ("4567"), 4, 0x4567},
+  {D_STR_W_LEN ("7890"), 4, 0x7890},
+  {D_STR_W_LEN ("8021"), 4, 0x8021},
+  {D_STR_W_LEN ("9754"), 4, 0x9754},
+  {D_STR_W_LEN ("6392"), 4, 0x6392},
+  {D_STR_W_LEN ("abcd"), 4, 0xABCD},
+  {D_STR_W_LEN ("cdef"), 4, 0xCDEF},
+  {D_STR_W_LEN ("FEAB"), 4, 0xFEAB},
+  {D_STR_W_LEN ("BCED"), 4, 0xBCED},
+  {D_STR_W_LEN ("bCeD"), 4, 0xBCED},
+  {D_STR_W_LEN ("1A5F"), 4, 0x1A5F},
+  {D_STR_W_LEN ("12AB"), 4, 0x12AB},
+  {D_STR_W_LEN ("CD34"), 4, 0xCD34},
+  {D_STR_W_LEN ("56EF"), 4, 0x56EF},
+  {D_STR_W_LEN ("7a9f"), 4, 0x7A9F},
+
+  /* various prefixes */
+  {D_STR_W_LEN ("00000000"), 8, 0x0},
+  {D_STR_W_LEN ("0755"), 4, 0x755},  /* not to be interpreted as octal value! */
+  {D_STR_W_LEN ("002"), 3, 0x2},
+  {D_STR_W_LEN ("0001"), 4, 0x1},
+  {D_STR_W_LEN ("00a"), 3, 0xA},
+  {D_STR_W_LEN ("0F"), 2, 0xF},
+  {D_STR_W_LEN ("0000000000000000000000003A29e4C3"), 32, 0x3A29E4C3},
+
+  /* numbers below and above limits */
+  {D_STR_W_LEN ("7F"), 2, 127},              /* 0x7F, SCHAR_MAX */
+  {D_STR_W_LEN ("7f"), 2, 127},              /* 0x7F, SCHAR_MAX */
+  {D_STR_W_LEN ("80"), 2, 128},              /* 0x80, SCHAR_MAX+1 */
+  {D_STR_W_LEN ("fF"), 2, 255},              /* 0xFF, UCHAR_MAX */
+  {D_STR_W_LEN ("Ff"), 2, 255},              /* 0xFF, UCHAR_MAX */
+  {D_STR_W_LEN ("FF"), 2, 255},              /* 0xFF, UCHAR_MAX */
+  {D_STR_W_LEN ("ff"), 2, 255},              /* 0xFF, UCHAR_MAX */
+  {D_STR_W_LEN ("100"), 3, 256},             /* 0x100, UCHAR_MAX+1 */
+  {D_STR_W_LEN ("7fff"), 4, 32767},          /* 0x7FFF, INT16_MAX */
+  {D_STR_W_LEN ("7FFF"), 4, 32767},          /* 0x7FFF, INT16_MAX */
+  {D_STR_W_LEN ("7Fff"), 4, 32767},          /* 0x7FFF, INT16_MAX */
+  {D_STR_W_LEN ("8000"), 4, 32768},          /* 0x8000, INT16_MAX+1 */
+  {D_STR_W_LEN ("ffff"), 4, 65535},          /* 0xFFFF, UINT16_MAX */
+  {D_STR_W_LEN ("FFFF"), 4, 65535},          /* 0xFFFF, UINT16_MAX */
+  {D_STR_W_LEN ("FffF"), 4, 65535},          /* 0xFFFF, UINT16_MAX */
+  {D_STR_W_LEN ("10000"), 5, 65536},         /* 0x10000, UINT16_MAX+1 */
+  {D_STR_W_LEN ("7FFFFFFF"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */
+  {D_STR_W_LEN ("7fffffff"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */
+  {D_STR_W_LEN ("7FFffFff"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */
+  {D_STR_W_LEN ("80000000"), 8, UINT64_C (2147483648)}, /* 0x80000000, INT32_MAX+1 */
+  {D_STR_W_LEN ("FFFFFFFF"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */
+  {D_STR_W_LEN ("ffffffff"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */
+  {D_STR_W_LEN ("FfFfFfFf"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */
+  {D_STR_W_LEN ("100000000"), 9, UINT64_C (4294967296)}, /* 0x100000000, UINT32_MAX+1 */
+  {D_STR_W_LEN ("7fffffffffffffff"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */
+  {D_STR_W_LEN ("7FFFFFFFFFFFFFFF"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */
+  {D_STR_W_LEN ("7FfffFFFFffFFffF"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */
+  {D_STR_W_LEN ("8000000000000000"), 16, UINT64_C (9223372036854775808)}, /* 0x8000000000000000, INT64_MAX+1 */
+  {D_STR_W_LEN ("ffffffffffffffff"), 16, UINT64_C (18446744073709551615)},  /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */
+  {D_STR_W_LEN ("FFFFFFFFFFFFFFFF"), 16, UINT64_C (18446744073709551615)},  /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */
+  {D_STR_W_LEN ("FffFffFFffFFfFFF"), 16, UINT64_C (18446744073709551615)},  /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */
+
+  /* random numbers */
+  {D_STR_W_LEN ("10186753"), 8, 0x10186753},
+  {D_STR_W_LEN ("144402566"), 9, 0x144402566},
+  {D_STR_W_LEN ("151903144"), 9, 0x151903144},
+  {D_STR_W_LEN ("139264621"), 9, 0x139264621},
+  {D_STR_W_LEN ("730348"), 6, 0x730348},
+  {D_STR_W_LEN ("21584377"), 8, 0x21584377},
+  {D_STR_W_LEN ("709"), 3, 0x709},
+  {D_STR_W_LEN ("54"), 2, 0x54},
+  {D_STR_W_LEN ("8452"), 4, 0x8452},
+  {D_STR_W_LEN ("22353EC6"), 8, 0x22353EC6},
+  {D_STR_W_LEN ("307F1655"), 8, 0x307F1655},
+  {D_STR_W_LEN ("1FCB7226"), 8, 0x1FCB7226},
+  {D_STR_W_LEN ("82480560"), 8, 0x82480560},
+  {D_STR_W_LEN ("7386D95"), 7, 0x7386D95},
+  {D_STR_W_LEN ("EC3AB"), 5, 0xEC3AB},
+  {D_STR_W_LEN ("6DD05"), 5, 0x6DD05},
+  {D_STR_W_LEN ("C5DF"), 4, 0xC5DF},
+  {D_STR_W_LEN ("6CE"), 3, 0x6CE},
+  {D_STR_W_LEN ("CE6"), 3, 0xCE6},
+  {D_STR_W_LEN ("ce6"), 3, 0xCE6},
+  {D_STR_W_LEN ("F27"), 3, 0xF27},
+  {D_STR_W_LEN ("8497D54277D7E1"), 14, UINT64_C (37321639124785121)},
+  {D_STR_W_LEN ("8497d54277d7e1"), 14, UINT64_C (37321639124785121)},
+  {D_STR_W_LEN ("8497d54277d7E1"), 14, UINT64_C (37321639124785121)},
+  {D_STR_W_LEN ("8C8112D0A06"), 11, UINT64_C (9655374645766)},
+  {D_STR_W_LEN ("8c8112d0a06"), 11, UINT64_C (9655374645766)},
+  {D_STR_W_LEN ("8c8112d0A06"), 11, UINT64_C (9655374645766)},
+  {D_STR_W_LEN ("1774509875001362"), 16, UINT64_C (1690064375898968930)},
+  {D_STR_W_LEN ("0678687876998000"), 16, UINT64_C (466237428027981824)},
+
+  /* non-digit suffixes */
+  {D_STR_W_LEN ("1234oa"), 4, 0x1234},
+  {D_STR_W_LEN ("20h"), 2, 0x20},
+  {D_STR_W_LEN ("2CH"), 2, 0x2C},
+  {D_STR_W_LEN ("2ch"), 2, 0x2C},
+  {D_STR_W_LEN ("0x1F"), 1, 0x0},  /* not to be interpreted as hex prefix! */
+  {D_STR_W_LEN ("0564`~}"), 4, 0x564},
+  {D_STR_W_LEN ("0A64`~}"), 4, 0xA64},
+  {D_STR_W_LEN ("056c`~}"), 4, 0X56C},
+  {D_STR_W_LEN ("7240146.724"), 7, 0x7240146},
+  {D_STR_W_LEN ("7E4c1AB.724"), 7, 0X7E4C1AB},
+  {D_STR_W_LEN ("F24B1B6.724"), 7, 0xF24B1B6},
+  {D_STR_W_LEN ("2,9"), 1, 0x2},
+  {D_STR_W_LEN ("a,9"), 1, 0xA},
+  {D_STR_W_LEN ("200+1"), 3, 0x200},
+  {D_STR_W_LEN ("2cc+1"), 3, 0x2CC},
+  {D_STR_W_LEN ("2cC+1"), 3, 0x2CC},
+  {D_STR_W_LEN ("27416997! And the not too long string."), 8, 0x27416997},
+  {D_STR_W_LEN ("27555416997! And the not too long string."), 11,
+   0x27555416997},
+  {D_STR_W_LEN ("416997And the not too long string."), 7, 0x416997A},
+  {D_STR_W_LEN ("0F4C3Dabstract addition to make string even longer"), 8,
+   0xF4C3DAB}
+};
+
+/* hex strings that should overflow uint64_t */
+static const struct str_with_len strx_ovflw[] = {
+  D_STR_W_LEN ("10000000000000000"),            /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("10000000000000001"),
+  D_STR_W_LEN ("10000000000000002"),
+  D_STR_W_LEN ("1000000000000000A"),
+  D_STR_W_LEN ("11000000000000000"),
+  D_STR_W_LEN ("010000000000000000"),           /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("000010000000000000000"),        /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("20000000000000000000"),
+  D_STR_W_LEN ("020000000000000000000"),
+  D_STR_W_LEN ("0020000000000000000000"),
+  D_STR_W_LEN ("20000000000000000"),
+  D_STR_W_LEN ("A0000000000000000"),
+  D_STR_W_LEN ("F0000000000000000"),
+  D_STR_W_LEN ("a0000000000000000"),
+  D_STR_W_LEN ("11111111111111111"),
+  D_STR_W_LEN ("CcCcCCccCCccCCccC"),
+  D_STR_W_LEN ("f0000000000000000"),
+  D_STR_W_LEN ("100000000000000000000"),
+  D_STR_W_LEN ("434532891232591226417"),
+  D_STR_W_LEN ("10000000000000000a"),
+  D_STR_W_LEN ("10000000000000000E"),
+  D_STR_W_LEN ("100000000000000000 and nothing"), /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("100000000000000000xx"),           /* 0x10000000000000000, UINT64_MAX+1 */
+  D_STR_W_LEN ("99999999999999999999"),
+  D_STR_W_LEN ("18446744073709551616abcd"),
+  D_STR_W_LEN ("20000000000000000000 suffix"),
+  D_STR_W_LEN ("020000000000000000000x")
+};
+
+
+static size_t
+check_str_to_uint64_valid (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(dstrs_w_values)
+               / sizeof(dstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      uint64_t rv;
+      size_t rs;
+      const struct str_with_value *const t = dstrs_w_values + i;
+
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      rv = 9435223;     /* some random value */
+      rs = MHD_str_to_uint64_ (t->str.str, &rv);
+      if (rs != t->num_of_digt)
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %"
+                 PRIuPTR
+                 ", while expecting %d."
+                 " Locale: %s\n", n_prnt (t->str.str), rv, (uintptr_t) rs,
+                 (int) t->num_of_digt, get_current_locale_str ());
+      }
+      if (rv != t->val)
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64
+                 ") converted string to value %"
+                 PRIu64 ","
+                 " while expecting result %" PRIu64 ". Locale: %s\n",
+                 n_prnt (t->str.str), rv, rv,
+                 t->val, get_current_locale_str ());
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") == %" \
+                PRIuPTR "\n",
+                n_prnt (t->str.str), rv, rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_all_chars (void)
+{
+  int c_failed[256]; /* from 0 to 255 */
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+  size_t t_failed = 0;
+  size_t j;
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    unsigned int c;
+    uint64_t test_val;
+
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (c = 0; c < n_checks; c++)
+    {
+      static const uint64_t rnd_val = 24941852;
+      size_t rs;
+      if ((c >= '0') && (c <= '9') )
+        continue;     /* skip digits */
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val +=
+             rnd_val)
+      {
+        char test_str[] = "0123";
+        uint64_t rv = test_val;
+
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+        rs = MHD_str_to_uint64_ (test_str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[c] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64
+                   ") returned %" PRIuPTR
+                   ", while expecting zero."
+                   " Locale: %s\n", n_prnt (test_str), rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[c] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: %" PRIu64 ", after call %" PRIu64
+                   "). Locale: %s\n",
+                   n_prnt (test_str), test_val, rv, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c])
+      {
+        char test_str[] = "0123";
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+
+        printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (test_str));
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_overflow (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_ovflw) / sizeof(str_ovflw[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_ovflw + i;
+      static const uint64_t rnd_val = 2;
+      uint64_t test_val;
+
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+             rnd_val)
+      {
+        uint64_t rv = test_val;
+
+        rs = MHD_str_to_uint64_ (t->str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64
+                   ") returned %" PRIuPTR
+                   ", while expecting zero."
+                   " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: %" PRIu64 ", after call %" PRIu64
+                   "). Locale: %s\n",
+                   n_prnt (t->str), test_val, rv, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (t->str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_no_val (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_no_num + i;
+      static const uint64_t rnd_val = 74218431;
+      uint64_t test_val;
+
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+             rnd_val)
+      {
+        uint64_t rv = test_val;
+
+        rs = MHD_str_to_uint64_ (t->str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64
+                   ") returned %" PRIuPTR
+                   ", while expecting zero."
+                   " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: %" PRIu64 ", after call %" PRIu64
+                   "). Locale: %s\n",
+                   n_prnt (t->str), test_val, rv, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (t->str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_n_valid (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(dstrs_w_values)
+               / sizeof(dstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      uint64_t rv = 1235572;     /* some random value */
+      size_t rs = 0;
+      size_t len;
+      const struct str_with_value *const t = dstrs_w_values + i;
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++)
+      {
+        rs = MHD_str_to_uint64_n_ (t->str.str, len, &rv);
+        if (rs != t->num_of_digt)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%"
+                   PRIu64 ")"
+                   " returned %" PRIuPTR ", while expecting %d. Locale: %s\n",
+                   n_prnt (t->str.str), (uintptr_t) len, rv, (uintptr_t) rs,
+                   (int) t->num_of_digt, get_current_locale_str ());
+        }
+        if (rv != t->val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%"
+                   PRIu64 ")"
+                   " converted string to value %" PRIu64
+                   ", while expecting result %" PRIu64
+                   ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv,
+                   rv,
+                   t->val, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR "..%"
+                PRIuPTR ", ->%" PRIu64 ")" " == %" PRIuPTR "\n",
+                n_prnt (t->str.str),
+                (uintptr_t) t->num_of_digt,
+                (uintptr_t) t->str.len + 1, rv, rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_n_all_chars (void)
+{
+  int c_failed[256]; /* from 0 to 255 */
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+  size_t t_failed = 0;
+  size_t j;
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    unsigned int c;
+    uint64_t test_val;
+
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (c = 0; c < n_checks; c++)
+    {
+      static const uint64_t rnd_val = 98372558;
+      size_t rs;
+      size_t len;
+
+      if ((c >= '0') && (c <= '9') )
+        continue;     /* skip digits */
+
+      for (len = 0; len <= 5; len++)
+      {
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val +=
+               rnd_val)
+        {
+          char test_str[] = "0123";
+          uint64_t rv = test_val;
+
+          test_str[0] = (char) (unsigned char) c;        /* replace first char with non-digit char */
+          rs = MHD_str_to_uint64_n_ (test_str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[c] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%"
+                     PRIu64 ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (test_str), (uintptr_t) len, rv, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[c] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: %" PRIu64
+                     ", after call %" PRIu64 ")."
+                     " Locale: %s\n",
+                     n_prnt (test_str), (uintptr_t) len, test_val, rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c])
+      {
+        char test_str[] = "0123";
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+
+        printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", 0..5, &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (test_str));
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_n_overflow (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_ovflw) / sizeof(str_ovflw[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_ovflw + i;
+      static const uint64_t rnd_val = 3;
+      size_t len;
+
+      for (len = t->len; len <= t->len + 1; len++)
+      {
+        uint64_t test_val;
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+               rnd_val)
+        {
+          uint64_t rv = test_val;
+
+          rs = MHD_str_to_uint64_n_ (t->str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%"
+                     PRIu64 ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: %" PRIu64
+                     ", after call %" PRIu64 ")."
+                     " Locale: %s\n", n_prnt (t->str), (uintptr_t) len,
+                     test_val, rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR
+                ", &ret_val) == 0,"
+                " value of ret_val is unmodified\n", n_prnt (t->str),
+                (uintptr_t) t->len,
+                (uintptr_t) t->len + 1);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_to_uint64_n_no_val (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_no_num + i;
+      static const uint64_t rnd_val = 43255654342;
+      size_t len;
+
+      for (len = 0; len <= t->len + 1; len++)
+      {
+        uint64_t test_val;
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+               rnd_val)
+        {
+          uint64_t rv = test_val;
+
+          rs = MHD_str_to_uint64_n_ (t->str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%"
+                     PRIu64 ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: %" PRIu64
+                     ", after call %" PRIu64 ")."
+                     " Locale: %s\n", n_prnt (t->str), (uintptr_t) len,
+                     test_val, rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", 0..%" PRIuPTR
+                ", &ret_val) == 0,"
+                " value of ret_val is unmodified\n", n_prnt (t->str),
+                (uintptr_t) t->len + 1);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_valid (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(xdstrs_w_values)
+               / sizeof(xdstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      uint32_t rv;
+      size_t rs;
+      const struct str_with_value *const t = xdstrs_w_values + i;
+
+      if (t->val > UINT32_MAX)
+        continue;     /* number is too high for this function */
+
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      rv = 1458532;     /* some random value */
+      rs = MHD_strx_to_uint32_ (t->str.str, &rv);
+      if (rs != t->num_of_digt)
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64
+                 ") returned %"
+                 PRIuPTR ", while expecting %d."
+                 " Locale: %s\n", n_prnt (t->str.str), (uint64_t) rv,
+                 (uintptr_t) rs, (int) t->num_of_digt,
+                 get_current_locale_str ());
+      }
+      if (rv != t->val)
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64
+                 ") converted string to value 0x%"
+                 PRIX64 ","
+                 " while expecting result 0x%" PRIX64 ". Locale: %s\n",
+                 n_prnt (t->str.str), (uint64_t) rv, (uint64_t) rv,
+                 t->val, get_current_locale_str ());
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") == %"
+                PRIuPTR "\n",
+                n_prnt (t->str.str), (uint64_t) rv, rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_all_chars (void)
+{
+  int c_failed[256]; /* from 0 to 255 */
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+  size_t t_failed = 0;
+  size_t j;
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    unsigned int c;
+    uint32_t test_val;
+
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (c = 0; c < n_checks; c++)
+    {
+      static const uint32_t rnd_val = 234234;
+      size_t rs;
+      if (((c >= '0') && (c <= '9') ) || ((c >= 'A') && (c <= 'F') ) || ((c >=
+                                                                          'a')
+                                                                         &&
+                                                                         (c <=
+                                                                          'f') ))
+        continue;     /* skip xdigits */
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val +=
+             rnd_val)
+      {
+        char test_str[] = "0123";
+        uint32_t rv = test_val;
+
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+        rs = MHD_strx_to_uint32_ (test_str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[c] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64
+                   ") returned %"
+                   PRIuPTR ", while expecting zero."
+                   " Locale: %s\n", n_prnt (test_str), (uint64_t) rv,
+                   (uintptr_t) rs, get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[c] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64
+                   "). Locale: %s\n",
+                   n_prnt (test_str), (uint64_t) test_val, (uint64_t) rv,
+                   get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c])
+      {
+        char test_str[] = "0123";
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+
+        printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (test_str));
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_overflow (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  static const size_t n_checks1 = sizeof(strx_ovflw) / sizeof(strx_ovflw[0]);
+  int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])
+               + sizeof(xdstrs_w_values)
+               / sizeof(xdstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      static const uint32_t rnd_val = 74218431;
+      uint32_t test_val;
+      const char *str;
+      if (i < n_checks1)
+      {
+        const struct str_with_len *const t = strx_ovflw + i;
+        str = t->str;
+      }
+      else
+      {
+        const struct str_with_value *const t = xdstrs_w_values + (i
+                                                                  - n_checks1);
+        if (t->val <= UINT32_MAX)
+          continue;       /* check only strings that should overflow uint32_t */
+        str = t->str.str;
+      }
+
+
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+             rnd_val)
+      {
+        uint32_t rv = test_val;
+
+        rs = MHD_strx_to_uint32_ (str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64
+                   ") returned %"
+                   PRIuPTR ", while expecting zero."
+                   " Locale: %s\n", n_prnt (str), (uint64_t) rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64
+                   "). Locale: %s\n",
+                   n_prnt (str), (uint64_t) test_val, (uint64_t) rv,
+                   get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_no_val (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_no_num + i;
+      static const uint32_t rnd_val = 74218431;
+      uint32_t test_val;
+
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+             rnd_val)
+      {
+        uint32_t rv = test_val;
+
+        rs = MHD_strx_to_uint32_ (t->str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64
+                   ") returned %"
+                   PRIuPTR ", while expecting zero."
+                   " Locale: %s\n", n_prnt (t->str), (uint64_t) rv,
+                   (uintptr_t) rs, get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64
+                   "). Locale: %s\n",
+                   n_prnt (t->str), (uint64_t) test_val, (uint64_t) rv,
+                   get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (t->str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_n_valid (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(xdstrs_w_values)
+               / sizeof(xdstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      uint32_t rv = 2352932;      /* some random value */
+      size_t rs = 0;
+      size_t len;
+      const struct str_with_value *const t = xdstrs_w_values + i;
+
+      if (t->val > UINT32_MAX)
+        continue;     /* number is too high for this function */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++)
+      {
+        rs = MHD_strx_to_uint32_n_ (t->str.str, len, &rv);
+        if (rs != t->num_of_digt)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                   PRIX64 ")"
+                   " returned %" PRIuPTR ", while expecting %d. Locale: %s\n",
+                   n_prnt (t->str.str), (uintptr_t) len, (uint64_t) rv,
+                   (uintptr_t) rs,
+                   (int) t->num_of_digt, get_current_locale_str ());
+        }
+        if (rv != t->val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                   PRIX64 ")"
+                   " converted string to value 0x%" PRIX64
+                   ", while expecting result 0x%" PRIX64
+                   ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len,
+                   (uint64_t) rv, (uint64_t) rv,
+                   t->val, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf (
+          "PASSED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR
+          ", ->0x%"
+          PRIX64 ")"
+          " == %" PRIuPTR "\n", n_prnt (t->str.str),
+          (uintptr_t) t->num_of_digt,
+          (uintptr_t) t->str.len + 1, (uint64_t) rv, rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_n_all_chars (void)
+{
+  int c_failed[256]; /* from 0 to 255 */
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+  size_t t_failed = 0;
+  size_t j;
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    unsigned int c;
+    uint32_t test_val;
+
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (c = 0; c < n_checks; c++)
+    {
+      static const uint32_t rnd_val = 98372558;
+      size_t rs;
+      size_t len;
+
+      if (((c >= '0') && (c <= '9') ) || ((c >= 'A') && (c <= 'F') ) || ((c >=
+                                                                          'a')
+                                                                         &&
+                                                                         (c <=
+                                                                          'f') ))
+        continue;     /* skip xdigits */
+
+      for (len = 0; len <= 5; len++)
+      {
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val +=
+               rnd_val)
+        {
+          char test_str[] = "0123";
+          uint32_t rv = test_val;
+
+          test_str[0] = (char) (unsigned char) c;        /* replace first char with non-digit char */
+          rs = MHD_strx_to_uint32_n_ (test_str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[c] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                     PRIX64
+                     ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (test_str), (uintptr_t) len, (uint64_t) rv,
+                     (uintptr_t) rs, get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[c] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: 0x%" PRIX64
+                     ", after call 0x%" PRIX64 ")."
+                     " Locale: %s\n",
+                     n_prnt (test_str), (uintptr_t) len, (uint64_t) test_val,
+                     (uint64_t) rv, get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c])
+      {
+        char test_str[] = "0123";
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+
+        printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", 0..5, &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (test_str));
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_n_overflow (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  static const size_t n_checks1 = sizeof(strx_ovflw) / sizeof(strx_ovflw[0]);
+  int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])
+               + sizeof(xdstrs_w_values)
+               / sizeof(xdstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      static const uint32_t rnd_val = 4;
+      size_t len;
+      const char *str;
+      size_t min_len, max_len;
+      if (i < n_checks1)
+      {
+        const struct str_with_len *const t = strx_ovflw + i;
+        str = t->str;
+        min_len = t->len;
+        max_len = t->len + 1;
+      }
+      else
+      {
+        const struct str_with_value *const t = xdstrs_w_values + (i
+                                                                  - n_checks1);
+        if (t->val <= UINT32_MAX)
+          continue;       /* check only strings that should overflow uint32_t */
+
+        if (t->str.len < t->num_of_digt)
+        {
+          fprintf (stderr,
+                   "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                   " to be less or equal to str.len (%u).\n",
+                   (unsigned int) (i - n_checks1), (unsigned
+                                                    int) t->num_of_digt,
+                   (unsigned int) t->str.len);
+          exit (99);
+        }
+        str = t->str.str;
+        min_len = t->num_of_digt;
+        max_len = t->str.len + 1;
+      }
+
+      for (len = min_len; len <= max_len; len++)
+      {
+        uint32_t test_val;
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+               rnd_val)
+        {
+          uint32_t rv = test_val;
+
+          rs = MHD_strx_to_uint32_n_ (str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                     PRIX64
+                     ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (str), (uintptr_t) len, (uint64_t) rv,
+                     (uintptr_t) rs, get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: 0x%" PRIX64
+                     ", after call 0x%" PRIX64 ")."
+                     " Locale: %s\n", n_prnt (str), (uintptr_t) len,
+                     (uint64_t) test_val, (uint64_t) rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR
+                ", &ret_val) == 0,"
+                " value of ret_val is unmodified\n", n_prnt (str),
+                (uintptr_t) min_len,
+                (uintptr_t) max_len);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint32_n_no_val (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_no_num + i;
+      static const uint32_t rnd_val = 3214314212UL;
+      size_t len;
+
+      for (len = 0; len <= t->len + 1; len++)
+      {
+        uint32_t test_val;
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+               rnd_val)
+        {
+          uint32_t rv = test_val;
+
+          rs = MHD_strx_to_uint32_n_ (t->str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                     PRIX64
+                     ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (t->str), (uintptr_t) len, (uint64_t) rv,
+                     (uintptr_t) rs, get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: 0x%" PRIX64
+                     ", after call 0x%" PRIX64 ")."
+                     " Locale: %s\n", n_prnt (t->str), (uintptr_t) len,
+                     (uint64_t) test_val, (uint64_t) rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", 0..%" PRIuPTR
+                ", &ret_val) == 0,"
+                " value of ret_val is unmodified\n", n_prnt (t->str),
+                (uintptr_t) t->len + 1);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_valid (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(xdstrs_w_values)
+               / sizeof(xdstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      uint64_t rv;
+      size_t rs;
+      const struct str_with_value *const t = xdstrs_w_values + i;
+
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      rv = 1458532;     /* some random value */
+      rs = MHD_strx_to_uint64_ (t->str.str, &rv);
+      if (rs != t->num_of_digt)
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64
+                 ") returned %"
+                 PRIuPTR ", while expecting %d."
+                 " Locale: %s\n", n_prnt (t->str.str), rv, (uintptr_t) rs,
+                 (int) t->num_of_digt, get_current_locale_str ());
+      }
+      if (rv != t->val)
+      {
+        t_failed++;
+        c_failed[i] = ! 0;
+        fprintf (stderr,
+                 "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64
+                 ") converted string to value 0x%"
+                 PRIX64 ","
+                 " while expecting result 0x%" PRIX64 ". Locale: %s\n",
+                 n_prnt (t->str.str), rv, rv,
+                 t->val, get_current_locale_str ());
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") == %"
+                PRIuPTR "\n",
+                n_prnt (t->str.str), rv, rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_all_chars (void)
+{
+  int c_failed[256]; /* from 0 to 255 */
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+  size_t t_failed = 0;
+  size_t j;
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    unsigned int c;
+    uint64_t test_val;
+
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (c = 0; c < n_checks; c++)
+    {
+      static const uint64_t rnd_val = 234234;
+      size_t rs;
+      if (((c >= '0') && (c <= '9') ) || ((c >= 'A') && (c <= 'F') ) || ((c >=
+                                                                          'a')
+                                                                         &&
+                                                                         (c <=
+                                                                          'f') ))
+        continue;     /* skip xdigits */
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val +=
+             rnd_val)
+      {
+        char test_str[] = "0123";
+        uint64_t rv = test_val;
+
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+        rs = MHD_strx_to_uint64_ (test_str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[c] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64
+                   ") returned %"
+                   PRIuPTR ", while expecting zero."
+                   " Locale: %s\n", n_prnt (test_str), rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[c] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64
+                   "). Locale: %s\n",
+                   n_prnt (test_str), test_val, rv, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c])
+      {
+        char test_str[] = "0123";
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+
+        printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (test_str));
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_overflow (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = strx_ovflw + i;
+      static const uint64_t rnd_val = 74218431;
+      uint64_t test_val;
+
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+             rnd_val)
+      {
+        uint64_t rv = test_val;
+
+        rs = MHD_strx_to_uint64_ (t->str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64
+                   ") returned %"
+                   PRIuPTR ", while expecting zero."
+                   " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64
+                   "). Locale: %s\n",
+                   n_prnt (t->str), test_val, rv, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (t->str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_no_val (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_no_num + i;
+      static const uint64_t rnd_val = 74218431;
+      uint64_t test_val;
+
+      for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+             rnd_val)
+      {
+        uint64_t rv = test_val;
+
+        rs = MHD_strx_to_uint64_ (t->str, &rv);
+        if (rs != 0)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64
+                   ") returned %"
+                   PRIuPTR ", while expecting zero."
+                   " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs,
+                   get_current_locale_str ());
+        }
+        else if (rv != test_val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val"
+                   " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64
+                   "). Locale: %s\n",
+                   n_prnt (t->str), test_val, rv, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (t->str));
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_n_valid (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  static const size_t n_checks = sizeof(xdstrs_w_values)
+                                 / sizeof(xdstrs_w_values[0]);
+  int c_failed[n_checks];
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      uint64_t rv = 2352932;     /* some random value */
+      size_t rs = 0;
+      size_t len;
+      const struct str_with_value *const t = xdstrs_w_values + i;
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++)
+      {
+        rs = MHD_strx_to_uint64_n_ (t->str.str, len, &rv);
+        if (rs != t->num_of_digt)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                   PRIX64 ")"
+                   " returned %" PRIuPTR ", while expecting %d. Locale: %s\n",
+                   n_prnt (t->str.str), (uintptr_t) len, rv, (uintptr_t) rs,
+                   (int) t->num_of_digt, get_current_locale_str ());
+        }
+        if (rv != t->val)
+        {
+          t_failed++;
+          c_failed[i] = ! 0;
+          fprintf (stderr,
+                   "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                   PRIX64 ")"
+                   " converted string to value 0x%" PRIX64
+                   ", while expecting result 0x%" PRIX64
+                   ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv,
+                   rv,
+                   t->val, get_current_locale_str ());
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR
+                ", ->0x%"
+                PRIX64 ")"
+                " == %" PRIuPTR "\n", n_prnt (t->str.str),
+                (uintptr_t) t->num_of_digt,
+                (uintptr_t) t->str.len + 1, rv, rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_n_all_chars (void)
+{
+  int c_failed[256]; /* from 0 to 255 */
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+  size_t t_failed = 0;
+  size_t j;
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    unsigned int c;
+    uint64_t test_val;
+
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (c = 0; c < n_checks; c++)
+    {
+      static const uint64_t rnd_val = 98372558;
+      size_t rs;
+      size_t len;
+
+      if (((c >= '0') && (c <= '9') ) || ((c >= 'A') && (c <= 'F') ) || ((c >=
+                                                                          'a')
+                                                                         &&
+                                                                         (c <=
+                                                                          'f') ))
+        continue;     /* skip xdigits */
+
+      for (len = 0; len <= 5; len++)
+      {
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val +=
+               rnd_val)
+        {
+          char test_str[] = "0123";
+          uint64_t rv = test_val;
+
+          test_str[0] = (char) (unsigned char) c;        /* replace first char with non-digit char */
+          rs = MHD_strx_to_uint64_n_ (test_str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[c] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                     PRIX64
+                     ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (test_str), (uintptr_t) len, rv, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[c] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: 0x%" PRIX64
+                     ", after call 0x%" PRIX64 ")."
+                     " Locale: %s\n",
+                     n_prnt (test_str), (uintptr_t) len, test_val, rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c])
+      {
+        char test_str[] = "0123";
+        test_str[0] = (char) (unsigned char) c;      /* replace first char with non-digit char */
+
+        printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", 0..5, &ret_val) == 0, "
+                "value of ret_val is unmodified\n",
+                n_prnt (test_str));
+      }
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_n_overflow (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = strx_ovflw + i;
+      static const uint64_t rnd_val = 4;
+      size_t len;
+
+      for (len = t->len; len <= t->len + 1; len++)
+      {
+        uint64_t test_val;
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+               rnd_val)
+        {
+          uint64_t rv = test_val;
+
+          rs = MHD_strx_to_uint64_n_ (t->str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                     PRIX64
+                     ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: 0x%" PRIX64
+                     ", after call 0x%" PRIX64 ")."
+                     " Locale: %s\n", n_prnt (t->str), (uintptr_t) len,
+                     test_val, rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR
+                ", &ret_val) == 0,"
+                " value of ret_val is unmodified\n", n_prnt (t->str),
+                (uintptr_t) t->len,
+                (uintptr_t) t->len + 1);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_to_uint64_n_no_val (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      size_t rs;
+      const struct str_with_len *const t = str_no_num + i;
+      static const uint64_t rnd_val = 3214314212UL;
+      size_t len;
+
+      for (len = 0; len <= t->len + 1; len++)
+      {
+        uint64_t test_val;
+        for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val +=
+               rnd_val)
+        {
+          uint64_t rv = test_val;
+
+          rs = MHD_strx_to_uint64_n_ (t->str, len, &rv);
+          if (rs != 0)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%"
+                     PRIX64
+                     ")"
+                     " returned %" PRIuPTR
+                     ", while expecting zero. Locale: %s\n",
+                     n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+          else if (rv != test_val)
+          {
+            t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR
+                     ", &ret_val)"
+                     " modified value of ret_val (before call: 0x%" PRIX64
+                     ", after call 0x%" PRIX64 ")."
+                     " Locale: %s\n", n_prnt (t->str), (uintptr_t) len,
+                     test_val, rv,
+                     get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", 0..%" PRIuPTR
+                ", &ret_val) == 0,"
+                " value of ret_val is unmodified\n", n_prnt (t->str),
+                (uintptr_t) t->len + 1);
+    }
+  }
+  return t_failed;
+}
+
+
+static int
+run_str_to_X_tests (void)
+{
+  size_t str_to_uint64_fails = 0;
+  size_t str_to_uint64_n_fails = 0;
+  size_t strx_to_uint32_fails = 0;
+  size_t strx_to_uint32_n_fails = 0;
+  size_t strx_to_uint64_fails = 0;
+  size_t strx_to_uint64_n_fails = 0;
+  size_t res;
+
+  res = check_str_to_uint64_valid ();
+  if (res != 0)
+  {
+    str_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_valid() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf (
+      "PASSED: testcase check_str_to_uint64_valid() successfully passed.\n\n");
+
+  res = check_str_to_uint64_all_chars ();
+  if (res != 0)
+  {
+    str_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_all_chars() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_all_chars() "
+            "successfully passed.\n\n");
+
+  res = check_str_to_uint64_overflow ();
+  if (res != 0)
+  {
+    str_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_overflow() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_overflow() "
+            "successfully passed.\n\n");
+
+  res = check_str_to_uint64_no_val ();
+  if (res != 0)
+  {
+    str_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_no_val() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_no_val() "
+            "successfully passed.\n\n");
+
+  if (str_to_uint64_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_str_to_uint64_() failed %lu time%s.\n\n",
+             (unsigned long) str_to_uint64_fails,
+             str_to_uint64_fails == 1 ? "" : "s");
+  else if (verbose > 0)
+    printf ("PASSED: function MHD_str_to_uint64_() successfully "
+            "passed all checks.\n\n");
+
+  res = check_str_to_uint64_n_valid ();
+  if (res != 0)
+  {
+    str_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_n_valid() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_n_valid() "
+            "successfully passed.\n\n");
+
+  res = check_str_to_uint64_n_all_chars ();
+  if (res != 0)
+  {
+    str_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_n_all_chars() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_n_all_chars() "
+            "successfully passed.\n\n");
+
+  res = check_str_to_uint64_n_overflow ();
+  if (res != 0)
+  {
+    str_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_n_overflow() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_n_overflow() "
+            "successfully passed.\n\n");
+
+  res = check_str_to_uint64_n_no_val ();
+  if (res != 0)
+  {
+    str_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_str_to_uint64_n_no_val() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_to_uint64_n_no_val() "
+            "successfully passed.\n\n");
+
+  if (str_to_uint64_n_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_str_to_uint64_n_() failed %lu time%s.\n\n",
+             (unsigned long) str_to_uint64_n_fails,
+             str_to_uint64_n_fails == 1 ? "" : "s");
+  else if (verbose > 0)
+    printf ("PASSED: function MHD_str_to_uint64_n_() successfully "
+            "passed all checks.\n\n");
+
+  res = check_strx_to_uint32_valid ();
+  if (res != 0)
+  {
+    strx_to_uint32_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_valid() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_valid() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint32_all_chars ();
+  if (res != 0)
+  {
+    strx_to_uint32_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_all_chars() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_all_chars() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint32_overflow ();
+  if (res != 0)
+  {
+    strx_to_uint32_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_overflow() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_overflow() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint32_no_val ();
+  if (res != 0)
+  {
+    strx_to_uint32_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_no_val() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_no_val() "
+            "successfully passed.\n\n");
+
+  if (strx_to_uint32_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_strx_to_uint32_() failed %lu time%s.\n\n",
+             (unsigned long) strx_to_uint32_fails,
+             strx_to_uint32_fails == 1 ? "" : "s");
+  else if (verbose > 0)
+    printf ("PASSED: function MHD_strx_to_uint32_() successfully "
+            "passed all checks.\n\n");
+
+  res = check_strx_to_uint32_n_valid ();
+  if (res != 0)
+  {
+    strx_to_uint32_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_n_valid() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_n_valid() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint32_n_all_chars ();
+  if (res != 0)
+  {
+    strx_to_uint32_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_n_all_chars() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_n_all_chars() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint32_n_overflow ();
+  if (res != 0)
+  {
+    strx_to_uint32_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_n_overflow() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_n_overflow() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint32_n_no_val ();
+  if (res != 0)
+  {
+    strx_to_uint32_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint32_n_no_val() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint32_n_no_val() "
+            "successfully passed.\n\n");
+
+  if (strx_to_uint32_n_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_strx_to_uint32_n_() failed %lu time%s.\n\n",
+             (unsigned long) strx_to_uint32_n_fails,
+             strx_to_uint32_n_fails == 1 ? "" : "s");
+  else if (verbose > 0)
+    printf ("PASSED: function MHD_strx_to_uint32_n_() successfully "
+            "passed all checks.\n\n");
+
+  res = check_strx_to_uint64_valid ();
+  if (res != 0)
+  {
+    strx_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_valid() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_valid() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint64_all_chars ();
+  if (res != 0)
+  {
+    strx_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_all_chars() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_all_chars() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint64_overflow ();
+  if (res != 0)
+  {
+    strx_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_overflow() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_overflow() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint64_no_val ();
+  if (res != 0)
+  {
+    strx_to_uint64_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_no_val() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_no_val() "
+            "successfully passed.\n\n");
+
+  if (strx_to_uint64_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_strx_to_uint64_() failed %lu time%s.\n\n",
+             (unsigned long) strx_to_uint64_fails,
+             strx_to_uint64_fails == 1 ? "" : "s");
+  else if (verbose > 0)
+    printf ("PASSED: function MHD_strx_to_uint64_() successfully "
+            "passed all checks.\n\n");
+
+  res = check_strx_to_uint64_n_valid ();
+  if (res != 0)
+  {
+    strx_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_n_valid() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_n_valid() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint64_n_all_chars ();
+  if (res != 0)
+  {
+    strx_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_n_all_chars() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_n_all_chars() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint64_n_overflow ();
+  if (res != 0)
+  {
+    strx_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_n_overflow() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_n_overflow() "
+            "successfully passed.\n\n");
+
+  res = check_strx_to_uint64_n_no_val ();
+  if (res != 0)
+  {
+    strx_to_uint64_n_fails += res;
+    fprintf (stderr,
+             "FAILED: testcase check_strx_to_uint64_n_no_val() failed.\n\n");
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_to_uint64_n_no_val() "
+            "successfully passed.\n\n");
+
+  if (strx_to_uint64_n_fails)
+    fprintf (stderr,
+             "FAILED: function MHD_strx_to_uint64_n_() failed %lu time%s.\n\n",
+             (unsigned long) strx_to_uint64_n_fails,
+             strx_to_uint64_n_fails == 1 ? "" : "s");
+  else if (verbose > 0)
+    printf ("PASSED: function MHD_strx_to_uint64_n_() successfully "
+            "passed all checks.\n\n");
+
+  if (str_to_uint64_fails || str_to_uint64_n_fails ||
+      strx_to_uint32_fails || strx_to_uint32_n_fails ||
+      strx_to_uint64_fails || strx_to_uint64_n_fails)
+  {
+    if (verbose > 0)
+      printf ("At least one test failed.\n");
+
+    return 1;
+  }
+
+  if (verbose > 0)
+    printf ("All tests passed successfully.\n");
+
+  return 0;
+}
+
+
+static size_t
+check_str_from_uint16 (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  char buf[70];
+  const char *erase =
+    "-@=sd#+&(pdiren456qwe#@C3S!DAS45AOIPUQWESAdFzxcv1s*()&#$%34`"
+    "32452d098poiden45SADFFDA3S4D3SDFdfgsdfgsSADFzxdvs$*()&#2342`"
+    "adsf##$$@&*^%*^&56qwe#3C@S!DAScFAOIP$#%#$Ad1zs3v1$*()&#1228`";
+  int c_failed[sizeof(dstrs_w_values)
+               / sizeof(dstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      const struct str_with_value *const t = dstrs_w_values + i;
+      size_t b_size;
+      size_t rs;
+
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      if ('0' == t->str.str[0])
+        continue;  /* Skip strings prefixed with zeros */
+      if (t->num_of_digt != t->str.len)
+        continue;  /* Skip strings with suffixes */
+      if (UINT16_MAX < t->val)
+        continue;  /* Too large value to convert */
+      if (sizeof(buf) < t->str.len + 1)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has too long (%u) string, "
+                 "size of 'buf' should be increased.\n",
+                 (unsigned int) i, (unsigned int) t->str.len);
+        exit (99);
+      }
+      rs = 0; /* Only to mute compiler warning */
+      for (b_size = 0; b_size <= t->str.len + 1; ++b_size)
+      {
+        /* fill buffer with pseudo-random values */
+        memcpy (buf, erase, sizeof(buf));
+
+        rs = MHD_uint16_to_str ((uint16_t) t->val, buf, b_size);
+
+        if (t->num_of_digt > b_size)
+        {
+          /* Must fail, buffer is too small for result */
+          if (0 != rs)
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting 0."
+                     " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+        }
+        else
+        {
+          if (t->num_of_digt != rs)
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting %d."
+                     " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs,
+                     (int) t->num_of_digt, get_current_locale_str ());
+          }
+          else if (0 != memcmp (buf, t->str.str, t->num_of_digt))
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\","
+                     " %d) returned %" PRIuPTR "."
+                     " Locale: %s\n", t->val, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs,  get_current_locale_str ());
+          }
+          else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs))
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\","
+                     " %d) returned %" PRIuPTR
+                     " and touched data after the resulting string."
+                     " Locale: %s\n", t->val, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs,  get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\", %d) "
+                "== %" PRIuPTR "\n",
+                t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_str_from_uint64 (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  char buf[70];
+  const char *erase =
+    "-@=sd#+&(pdirenDSFGSe#@C&S!DAS*!AOIPUQWESAdFzxcvSs*()&#$%KH`"
+    "32452d098poiden45SADFFDA3S4D3SDFdfgsdfgsSADFzxdvs$*()&#2342`"
+    "adsf##$$@&*^%*^&56qwe#3C@S!DAScFAOIP$#%#$Ad1zs3v1$*()&#1228`";
+  int c_failed[sizeof(dstrs_w_values)
+               / sizeof(dstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      const struct str_with_value *const t = dstrs_w_values + i;
+      size_t b_size;
+      size_t rs;
+
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      if ('0' == t->str.str[0])
+        continue;  /* Skip strings prefixed with zeros */
+      if (t->num_of_digt != t->str.len)
+        continue;  /* Skip strings with suffixes */
+      if (sizeof(buf) < t->str.len + 1)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has too long (%u) string, "
+                 "size of 'buf' should be increased.\n",
+                 (unsigned int) i, (unsigned int) t->str.len);
+        exit (99);
+      }
+      rs = 0; /* Only to mute compiler warning */
+      for (b_size = 0; b_size <= t->str.len + 1; ++b_size)
+      {
+        /* fill buffer with pseudo-random values */
+        memcpy (buf, erase, sizeof(buf));
+
+        rs = MHD_uint64_to_str (t->val, buf, b_size);
+
+        if (t->num_of_digt > b_size)
+        {
+          /* Must fail, buffer is too small for result */
+          if (0 != rs)
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting 0."
+                     " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+        }
+        else
+        {
+          if (t->num_of_digt != rs)
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting %d."
+                     " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs,
+                     (int) t->num_of_digt, get_current_locale_str ());
+          }
+          else if (0 != memcmp (buf, t->str.str, t->num_of_digt))
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\","
+                     " %d) returned %" PRIuPTR "."
+                     " Locale: %s\n", t->val, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs,  get_current_locale_str ());
+          }
+          else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs))
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\","
+                     " %d) returned %" PRIuPTR
+                     " and touched data after the resulting string."
+                     " Locale: %s\n", t->val, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs,  get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\", %d) "
+                "== %" PRIuPTR "\n",
+                t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static size_t
+check_strx_from_uint32 (void)
+{
+  size_t t_failed = 0;
+  size_t i, j;
+  char buf[70];
+  const char *erase =
+    "jrlkjssfhjfvrjntJHLJ$@%$#adsfdkj;k$##$%#$%FGDF%$#^FDFG%$#$D`"
+    ";skjdhjflsdkjhdjfalskdjhdfalkjdhf$%##%$$#%FSDGFSDDGDFSSDSDF`"
+    "#5#$%#$#$DFSFDDFSGSDFSDF354FDDSGFDFfdssfddfswqemn,.zxih,.sx`";
+  int c_failed[sizeof(xdstrs_w_values)
+               / sizeof(xdstrs_w_values[0])];
+  static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]);
+
+  memset (c_failed, 0, sizeof(c_failed));
+
+  for (j = 0; j < locale_name_count; j++)
+  {
+    set_test_locale (j);  /* setlocale() can be slow! */
+    for (i = 0; i < n_checks; i++)
+    {
+      const struct str_with_value *const t = xdstrs_w_values + i;
+      size_t b_size;
+      size_t rs;
+
+      if (c_failed[i])
+        continue;     /* skip already failed checks */
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      if ('0' == t->str.str[0])
+        continue;  /* Skip strings prefixed with zeros */
+      if (t->num_of_digt != t->str.len)
+        continue;  /* Skip strings with suffixes */
+      if (UINT32_MAX < t->val)
+        continue;  /* Too large value to convert */
+      if (sizeof(buf) < t->str.len + 1)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has too long (%u) string, "
+                 "size of 'buf' should be increased.\n",
+                 (unsigned int) i, (unsigned int) t->str.len);
+        exit (99);
+      }
+      rs = 0; /* Only to mute compiler warning */
+      for (b_size = 0; b_size <= t->str.len + 1; ++b_size)
+      {
+        /* fill buffer with pseudo-random values */
+        memcpy (buf, erase, sizeof(buf));
+
+        rs = MHD_uint32_to_strx ((uint32_t) t->val, buf, b_size);
+
+        if (t->num_of_digt > b_size)
+        {
+          /* Must fail, buffer is too small for result */
+          if (0 != rs)
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting 0."
+                     " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs,
+                     get_current_locale_str ());
+          }
+        }
+        else
+        {
+          if (t->num_of_digt != rs)
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting %d."
+                     " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs,
+                     (int) t->num_of_digt, get_current_locale_str ());
+          }
+          else if (0 == MHD_str_equal_caseless_bin_n_ (buf, t->str.str,
+                                                       t->num_of_digt))
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\","
+                     " %d) returned %" PRIuPTR "."
+                     " Locale: %s\n", t->val, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs,  get_current_locale_str ());
+          }
+          else if (sizeof(buf) <= rs)
+          {
+            fprintf (stderr,
+                     "ERROR: dstrs_w_values[%u] has string with too many"
+                     "(%u) digits, size of 'buf' should be increased.\n",
+                     (unsigned int) i, (unsigned int) rs);
+            exit (99);
+          }
+          else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs))
+          {
+            if (0 == c_failed[i])
+              t_failed++;
+            c_failed[i] = ! 0;
+            fprintf (stderr,
+                     "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\","
+                     " %d) returned %" PRIuPTR
+                     " and touched data after the resulting string."
+                     " Locale: %s\n", t->val, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs,  get_current_locale_str ());
+          }
+        }
+      }
+      if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i])
+        printf ("PASSED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\", %d) "
+                "== %" PRIuPTR "\n",
+                t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs);
+    }
+  }
+  return t_failed;
+}
+
+
+static const struct str_with_value duint8_w_values_p1[] = {
+  {D_STR_W_LEN ("0"), 1, 0},
+  {D_STR_W_LEN ("1"), 1, 1},
+  {D_STR_W_LEN ("2"), 1, 2},
+  {D_STR_W_LEN ("3"), 1, 3},
+  {D_STR_W_LEN ("4"), 1, 4},
+  {D_STR_W_LEN ("5"), 1, 5},
+  {D_STR_W_LEN ("6"), 1, 6},
+  {D_STR_W_LEN ("7"), 1, 7},
+  {D_STR_W_LEN ("8"), 1, 8},
+  {D_STR_W_LEN ("9"), 1, 9},
+  {D_STR_W_LEN ("10"), 2, 10},
+  {D_STR_W_LEN ("11"), 2, 11},
+  {D_STR_W_LEN ("12"), 2, 12},
+  {D_STR_W_LEN ("13"), 2, 13},
+  {D_STR_W_LEN ("14"), 2, 14},
+  {D_STR_W_LEN ("15"), 2, 15},
+  {D_STR_W_LEN ("16"), 2, 16},
+  {D_STR_W_LEN ("17"), 2, 17},
+  {D_STR_W_LEN ("18"), 2, 18},
+  {D_STR_W_LEN ("19"), 2, 19},
+  {D_STR_W_LEN ("20"), 2, 20},
+  {D_STR_W_LEN ("21"), 2, 21},
+  {D_STR_W_LEN ("22"), 2, 22},
+  {D_STR_W_LEN ("23"), 2, 23},
+  {D_STR_W_LEN ("24"), 2, 24},
+  {D_STR_W_LEN ("25"), 2, 25},
+  {D_STR_W_LEN ("26"), 2, 26},
+  {D_STR_W_LEN ("27"), 2, 27},
+  {D_STR_W_LEN ("28"), 2, 28},
+  {D_STR_W_LEN ("29"), 2, 29},
+  {D_STR_W_LEN ("30"), 2, 30},
+  {D_STR_W_LEN ("31"), 2, 31},
+  {D_STR_W_LEN ("32"), 2, 32},
+  {D_STR_W_LEN ("33"), 2, 33},
+  {D_STR_W_LEN ("34"), 2, 34},
+  {D_STR_W_LEN ("35"), 2, 35},
+  {D_STR_W_LEN ("36"), 2, 36},
+  {D_STR_W_LEN ("37"), 2, 37},
+  {D_STR_W_LEN ("38"), 2, 38},
+  {D_STR_W_LEN ("39"), 2, 39},
+  {D_STR_W_LEN ("40"), 2, 40},
+  {D_STR_W_LEN ("41"), 2, 41},
+  {D_STR_W_LEN ("42"), 2, 42},
+  {D_STR_W_LEN ("43"), 2, 43},
+  {D_STR_W_LEN ("44"), 2, 44},
+  {D_STR_W_LEN ("45"), 2, 45},
+  {D_STR_W_LEN ("46"), 2, 46},
+  {D_STR_W_LEN ("47"), 2, 47},
+  {D_STR_W_LEN ("48"), 2, 48},
+  {D_STR_W_LEN ("49"), 2, 49},
+  {D_STR_W_LEN ("50"), 2, 50},
+  {D_STR_W_LEN ("51"), 2, 51},
+  {D_STR_W_LEN ("52"), 2, 52},
+  {D_STR_W_LEN ("53"), 2, 53},
+  {D_STR_W_LEN ("54"), 2, 54},
+  {D_STR_W_LEN ("55"), 2, 55},
+  {D_STR_W_LEN ("56"), 2, 56},
+  {D_STR_W_LEN ("57"), 2, 57},
+  {D_STR_W_LEN ("58"), 2, 58},
+  {D_STR_W_LEN ("59"), 2, 59},
+  {D_STR_W_LEN ("60"), 2, 60},
+  {D_STR_W_LEN ("61"), 2, 61},
+  {D_STR_W_LEN ("62"), 2, 62},
+  {D_STR_W_LEN ("63"), 2, 63},
+  {D_STR_W_LEN ("64"), 2, 64},
+  {D_STR_W_LEN ("65"), 2, 65},
+  {D_STR_W_LEN ("66"), 2, 66},
+  {D_STR_W_LEN ("67"), 2, 67},
+  {D_STR_W_LEN ("68"), 2, 68},
+  {D_STR_W_LEN ("69"), 2, 69},
+  {D_STR_W_LEN ("70"), 2, 70},
+  {D_STR_W_LEN ("71"), 2, 71},
+  {D_STR_W_LEN ("72"), 2, 72},
+  {D_STR_W_LEN ("73"), 2, 73},
+  {D_STR_W_LEN ("74"), 2, 74},
+  {D_STR_W_LEN ("75"), 2, 75},
+  {D_STR_W_LEN ("76"), 2, 76},
+  {D_STR_W_LEN ("77"), 2, 77},
+  {D_STR_W_LEN ("78"), 2, 78},
+  {D_STR_W_LEN ("79"), 2, 79},
+  {D_STR_W_LEN ("80"), 2, 80},
+  {D_STR_W_LEN ("81"), 2, 81},
+  {D_STR_W_LEN ("82"), 2, 82},
+  {D_STR_W_LEN ("83"), 2, 83},
+  {D_STR_W_LEN ("84"), 2, 84},
+  {D_STR_W_LEN ("85"), 2, 85},
+  {D_STR_W_LEN ("86"), 2, 86},
+  {D_STR_W_LEN ("87"), 2, 87},
+  {D_STR_W_LEN ("88"), 2, 88},
+  {D_STR_W_LEN ("89"), 2, 89},
+  {D_STR_W_LEN ("90"), 2, 90},
+  {D_STR_W_LEN ("91"), 2, 91},
+  {D_STR_W_LEN ("92"), 2, 92},
+  {D_STR_W_LEN ("93"), 2, 93},
+  {D_STR_W_LEN ("94"), 2, 94},
+  {D_STR_W_LEN ("95"), 2, 95},
+  {D_STR_W_LEN ("96"), 2, 96},
+  {D_STR_W_LEN ("97"), 2, 97},
+  {D_STR_W_LEN ("98"), 2, 98},
+  {D_STR_W_LEN ("99"), 2, 99},
+  {D_STR_W_LEN ("100"), 3, 100},
+  {D_STR_W_LEN ("101"), 3, 101},
+  {D_STR_W_LEN ("102"), 3, 102},
+  {D_STR_W_LEN ("103"), 3, 103},
+  {D_STR_W_LEN ("104"), 3, 104},
+  {D_STR_W_LEN ("105"), 3, 105},
+  {D_STR_W_LEN ("106"), 3, 106},
+  {D_STR_W_LEN ("107"), 3, 107},
+  {D_STR_W_LEN ("108"), 3, 108},
+  {D_STR_W_LEN ("109"), 3, 109},
+  {D_STR_W_LEN ("110"), 3, 110},
+  {D_STR_W_LEN ("111"), 3, 111},
+  {D_STR_W_LEN ("112"), 3, 112},
+  {D_STR_W_LEN ("113"), 3, 113},
+  {D_STR_W_LEN ("114"), 3, 114},
+  {D_STR_W_LEN ("115"), 3, 115},
+  {D_STR_W_LEN ("116"), 3, 116},
+  {D_STR_W_LEN ("117"), 3, 117},
+  {D_STR_W_LEN ("118"), 3, 118},
+  {D_STR_W_LEN ("119"), 3, 119},
+  {D_STR_W_LEN ("120"), 3, 120},
+  {D_STR_W_LEN ("121"), 3, 121},
+  {D_STR_W_LEN ("122"), 3, 122},
+  {D_STR_W_LEN ("123"), 3, 123},
+  {D_STR_W_LEN ("124"), 3, 124},
+  {D_STR_W_LEN ("125"), 3, 125},
+  {D_STR_W_LEN ("126"), 3, 126},
+  {D_STR_W_LEN ("127"), 3, 127},
+  {D_STR_W_LEN ("128"), 3, 128},
+  {D_STR_W_LEN ("129"), 3, 129},
+  {D_STR_W_LEN ("130"), 3, 130},
+  {D_STR_W_LEN ("131"), 3, 131},
+  {D_STR_W_LEN ("132"), 3, 132},
+  {D_STR_W_LEN ("133"), 3, 133},
+  {D_STR_W_LEN ("134"), 3, 134},
+  {D_STR_W_LEN ("135"), 3, 135},
+  {D_STR_W_LEN ("136"), 3, 136},
+  {D_STR_W_LEN ("137"), 3, 137},
+  {D_STR_W_LEN ("138"), 3, 138},
+  {D_STR_W_LEN ("139"), 3, 139},
+  {D_STR_W_LEN ("140"), 3, 140},
+  {D_STR_W_LEN ("141"), 3, 141},
+  {D_STR_W_LEN ("142"), 3, 142},
+  {D_STR_W_LEN ("143"), 3, 143},
+  {D_STR_W_LEN ("144"), 3, 144},
+  {D_STR_W_LEN ("145"), 3, 145},
+  {D_STR_W_LEN ("146"), 3, 146},
+  {D_STR_W_LEN ("147"), 3, 147},
+  {D_STR_W_LEN ("148"), 3, 148},
+  {D_STR_W_LEN ("149"), 3, 149},
+  {D_STR_W_LEN ("150"), 3, 150},
+  {D_STR_W_LEN ("151"), 3, 151},
+  {D_STR_W_LEN ("152"), 3, 152},
+  {D_STR_W_LEN ("153"), 3, 153},
+  {D_STR_W_LEN ("154"), 3, 154},
+  {D_STR_W_LEN ("155"), 3, 155},
+  {D_STR_W_LEN ("156"), 3, 156},
+  {D_STR_W_LEN ("157"), 3, 157},
+  {D_STR_W_LEN ("158"), 3, 158},
+  {D_STR_W_LEN ("159"), 3, 159},
+  {D_STR_W_LEN ("160"), 3, 160},
+  {D_STR_W_LEN ("161"), 3, 161},
+  {D_STR_W_LEN ("162"), 3, 162},
+  {D_STR_W_LEN ("163"), 3, 163},
+  {D_STR_W_LEN ("164"), 3, 164},
+  {D_STR_W_LEN ("165"), 3, 165},
+  {D_STR_W_LEN ("166"), 3, 166},
+  {D_STR_W_LEN ("167"), 3, 167},
+  {D_STR_W_LEN ("168"), 3, 168},
+  {D_STR_W_LEN ("169"), 3, 169},
+  {D_STR_W_LEN ("170"), 3, 170},
+  {D_STR_W_LEN ("171"), 3, 171},
+  {D_STR_W_LEN ("172"), 3, 172},
+  {D_STR_W_LEN ("173"), 3, 173},
+  {D_STR_W_LEN ("174"), 3, 174},
+  {D_STR_W_LEN ("175"), 3, 175},
+  {D_STR_W_LEN ("176"), 3, 176},
+  {D_STR_W_LEN ("177"), 3, 177},
+  {D_STR_W_LEN ("178"), 3, 178},
+  {D_STR_W_LEN ("179"), 3, 179},
+  {D_STR_W_LEN ("180"), 3, 180},
+  {D_STR_W_LEN ("181"), 3, 181},
+  {D_STR_W_LEN ("182"), 3, 182},
+  {D_STR_W_LEN ("183"), 3, 183},
+  {D_STR_W_LEN ("184"), 3, 184},
+  {D_STR_W_LEN ("185"), 3, 185},
+  {D_STR_W_LEN ("186"), 3, 186},
+  {D_STR_W_LEN ("187"), 3, 187},
+  {D_STR_W_LEN ("188"), 3, 188},
+  {D_STR_W_LEN ("189"), 3, 189},
+  {D_STR_W_LEN ("190"), 3, 190},
+  {D_STR_W_LEN ("191"), 3, 191},
+  {D_STR_W_LEN ("192"), 3, 192},
+  {D_STR_W_LEN ("193"), 3, 193},
+  {D_STR_W_LEN ("194"), 3, 194},
+  {D_STR_W_LEN ("195"), 3, 195},
+  {D_STR_W_LEN ("196"), 3, 196},
+  {D_STR_W_LEN ("197"), 3, 197},
+  {D_STR_W_LEN ("198"), 3, 198},
+  {D_STR_W_LEN ("199"), 3, 199},
+  {D_STR_W_LEN ("200"), 3, 200},
+  {D_STR_W_LEN ("201"), 3, 201},
+  {D_STR_W_LEN ("202"), 3, 202},
+  {D_STR_W_LEN ("203"), 3, 203},
+  {D_STR_W_LEN ("204"), 3, 204},
+  {D_STR_W_LEN ("205"), 3, 205},
+  {D_STR_W_LEN ("206"), 3, 206},
+  {D_STR_W_LEN ("207"), 3, 207},
+  {D_STR_W_LEN ("208"), 3, 208},
+  {D_STR_W_LEN ("209"), 3, 209},
+  {D_STR_W_LEN ("210"), 3, 210},
+  {D_STR_W_LEN ("211"), 3, 211},
+  {D_STR_W_LEN ("212"), 3, 212},
+  {D_STR_W_LEN ("213"), 3, 213},
+  {D_STR_W_LEN ("214"), 3, 214},
+  {D_STR_W_LEN ("215"), 3, 215},
+  {D_STR_W_LEN ("216"), 3, 216},
+  {D_STR_W_LEN ("217"), 3, 217},
+  {D_STR_W_LEN ("218"), 3, 218},
+  {D_STR_W_LEN ("219"), 3, 219},
+  {D_STR_W_LEN ("220"), 3, 220},
+  {D_STR_W_LEN ("221"), 3, 221},
+  {D_STR_W_LEN ("222"), 3, 222},
+  {D_STR_W_LEN ("223"), 3, 223},
+  {D_STR_W_LEN ("224"), 3, 224},
+  {D_STR_W_LEN ("225"), 3, 225},
+  {D_STR_W_LEN ("226"), 3, 226},
+  {D_STR_W_LEN ("227"), 3, 227},
+  {D_STR_W_LEN ("228"), 3, 228},
+  {D_STR_W_LEN ("229"), 3, 229},
+  {D_STR_W_LEN ("230"), 3, 230},
+  {D_STR_W_LEN ("231"), 3, 231},
+  {D_STR_W_LEN ("232"), 3, 232},
+  {D_STR_W_LEN ("233"), 3, 233},
+  {D_STR_W_LEN ("234"), 3, 234},
+  {D_STR_W_LEN ("235"), 3, 235},
+  {D_STR_W_LEN ("236"), 3, 236},
+  {D_STR_W_LEN ("237"), 3, 237},
+  {D_STR_W_LEN ("238"), 3, 238},
+  {D_STR_W_LEN ("239"), 3, 239},
+  {D_STR_W_LEN ("240"), 3, 240},
+  {D_STR_W_LEN ("241"), 3, 241},
+  {D_STR_W_LEN ("242"), 3, 242},
+  {D_STR_W_LEN ("243"), 3, 243},
+  {D_STR_W_LEN ("244"), 3, 244},
+  {D_STR_W_LEN ("245"), 3, 245},
+  {D_STR_W_LEN ("246"), 3, 246},
+  {D_STR_W_LEN ("247"), 3, 247},
+  {D_STR_W_LEN ("248"), 3, 248},
+  {D_STR_W_LEN ("249"), 3, 249},
+  {D_STR_W_LEN ("250"), 3, 250},
+  {D_STR_W_LEN ("251"), 3, 251},
+  {D_STR_W_LEN ("252"), 3, 252},
+  {D_STR_W_LEN ("253"), 3, 253},
+  {D_STR_W_LEN ("254"), 3, 254},
+  {D_STR_W_LEN ("255"), 3, 255},
+};
+
+static const struct str_with_value duint8_w_values_p2[] = {
+  {D_STR_W_LEN ("00"), 2, 0},
+  {D_STR_W_LEN ("01"), 2, 1},
+  {D_STR_W_LEN ("02"), 2, 2},
+  {D_STR_W_LEN ("03"), 2, 3},
+  {D_STR_W_LEN ("04"), 2, 4},
+  {D_STR_W_LEN ("05"), 2, 5},
+  {D_STR_W_LEN ("06"), 2, 6},
+  {D_STR_W_LEN ("07"), 2, 7},
+  {D_STR_W_LEN ("08"), 2, 8},
+  {D_STR_W_LEN ("09"), 2, 9},
+  {D_STR_W_LEN ("10"), 2, 10},
+  {D_STR_W_LEN ("11"), 2, 11},
+  {D_STR_W_LEN ("12"), 2, 12},
+  {D_STR_W_LEN ("13"), 2, 13},
+  {D_STR_W_LEN ("14"), 2, 14},
+  {D_STR_W_LEN ("15"), 2, 15},
+  {D_STR_W_LEN ("16"), 2, 16},
+  {D_STR_W_LEN ("17"), 2, 17},
+  {D_STR_W_LEN ("18"), 2, 18},
+  {D_STR_W_LEN ("19"), 2, 19},
+  {D_STR_W_LEN ("20"), 2, 20},
+  {D_STR_W_LEN ("21"), 2, 21},
+  {D_STR_W_LEN ("22"), 2, 22},
+  {D_STR_W_LEN ("23"), 2, 23},
+  {D_STR_W_LEN ("24"), 2, 24},
+  {D_STR_W_LEN ("25"), 2, 25},
+  {D_STR_W_LEN ("26"), 2, 26},
+  {D_STR_W_LEN ("27"), 2, 27},
+  {D_STR_W_LEN ("28"), 2, 28},
+  {D_STR_W_LEN ("29"), 2, 29},
+  {D_STR_W_LEN ("30"), 2, 30},
+  {D_STR_W_LEN ("31"), 2, 31},
+  {D_STR_W_LEN ("32"), 2, 32},
+  {D_STR_W_LEN ("33"), 2, 33},
+  {D_STR_W_LEN ("34"), 2, 34},
+  {D_STR_W_LEN ("35"), 2, 35},
+  {D_STR_W_LEN ("36"), 2, 36},
+  {D_STR_W_LEN ("37"), 2, 37},
+  {D_STR_W_LEN ("38"), 2, 38},
+  {D_STR_W_LEN ("39"), 2, 39},
+  {D_STR_W_LEN ("40"), 2, 40},
+  {D_STR_W_LEN ("41"), 2, 41},
+  {D_STR_W_LEN ("42"), 2, 42},
+  {D_STR_W_LEN ("43"), 2, 43},
+  {D_STR_W_LEN ("44"), 2, 44},
+  {D_STR_W_LEN ("45"), 2, 45},
+  {D_STR_W_LEN ("46"), 2, 46},
+  {D_STR_W_LEN ("47"), 2, 47},
+  {D_STR_W_LEN ("48"), 2, 48},
+  {D_STR_W_LEN ("49"), 2, 49},
+  {D_STR_W_LEN ("50"), 2, 50},
+  {D_STR_W_LEN ("51"), 2, 51},
+  {D_STR_W_LEN ("52"), 2, 52},
+  {D_STR_W_LEN ("53"), 2, 53},
+  {D_STR_W_LEN ("54"), 2, 54},
+  {D_STR_W_LEN ("55"), 2, 55},
+  {D_STR_W_LEN ("56"), 2, 56},
+  {D_STR_W_LEN ("57"), 2, 57},
+  {D_STR_W_LEN ("58"), 2, 58},
+  {D_STR_W_LEN ("59"), 2, 59},
+  {D_STR_W_LEN ("60"), 2, 60},
+  {D_STR_W_LEN ("61"), 2, 61},
+  {D_STR_W_LEN ("62"), 2, 62},
+  {D_STR_W_LEN ("63"), 2, 63},
+  {D_STR_W_LEN ("64"), 2, 64},
+  {D_STR_W_LEN ("65"), 2, 65},
+  {D_STR_W_LEN ("66"), 2, 66},
+  {D_STR_W_LEN ("67"), 2, 67},
+  {D_STR_W_LEN ("68"), 2, 68},
+  {D_STR_W_LEN ("69"), 2, 69},
+  {D_STR_W_LEN ("70"), 2, 70},
+  {D_STR_W_LEN ("71"), 2, 71},
+  {D_STR_W_LEN ("72"), 2, 72},
+  {D_STR_W_LEN ("73"), 2, 73},
+  {D_STR_W_LEN ("74"), 2, 74},
+  {D_STR_W_LEN ("75"), 2, 75},
+  {D_STR_W_LEN ("76"), 2, 76},
+  {D_STR_W_LEN ("77"), 2, 77},
+  {D_STR_W_LEN ("78"), 2, 78},
+  {D_STR_W_LEN ("79"), 2, 79},
+  {D_STR_W_LEN ("80"), 2, 80},
+  {D_STR_W_LEN ("81"), 2, 81},
+  {D_STR_W_LEN ("82"), 2, 82},
+  {D_STR_W_LEN ("83"), 2, 83},
+  {D_STR_W_LEN ("84"), 2, 84},
+  {D_STR_W_LEN ("85"), 2, 85},
+  {D_STR_W_LEN ("86"), 2, 86},
+  {D_STR_W_LEN ("87"), 2, 87},
+  {D_STR_W_LEN ("88"), 2, 88},
+  {D_STR_W_LEN ("89"), 2, 89},
+  {D_STR_W_LEN ("90"), 2, 90},
+  {D_STR_W_LEN ("91"), 2, 91},
+  {D_STR_W_LEN ("92"), 2, 92},
+  {D_STR_W_LEN ("93"), 2, 93},
+  {D_STR_W_LEN ("94"), 2, 94},
+  {D_STR_W_LEN ("95"), 2, 95},
+  {D_STR_W_LEN ("96"), 2, 96},
+  {D_STR_W_LEN ("97"), 2, 97},
+  {D_STR_W_LEN ("98"), 2, 98},
+  {D_STR_W_LEN ("99"), 2, 99},
+  {D_STR_W_LEN ("100"), 3, 100},
+  {D_STR_W_LEN ("101"), 3, 101},
+  {D_STR_W_LEN ("102"), 3, 102},
+  {D_STR_W_LEN ("103"), 3, 103},
+  {D_STR_W_LEN ("104"), 3, 104},
+  {D_STR_W_LEN ("105"), 3, 105},
+  {D_STR_W_LEN ("106"), 3, 106},
+  {D_STR_W_LEN ("107"), 3, 107},
+  {D_STR_W_LEN ("108"), 3, 108},
+  {D_STR_W_LEN ("109"), 3, 109},
+  {D_STR_W_LEN ("110"), 3, 110},
+  {D_STR_W_LEN ("111"), 3, 111},
+  {D_STR_W_LEN ("112"), 3, 112},
+  {D_STR_W_LEN ("113"), 3, 113},
+  {D_STR_W_LEN ("114"), 3, 114},
+  {D_STR_W_LEN ("115"), 3, 115},
+  {D_STR_W_LEN ("116"), 3, 116},
+  {D_STR_W_LEN ("117"), 3, 117},
+  {D_STR_W_LEN ("118"), 3, 118},
+  {D_STR_W_LEN ("119"), 3, 119},
+  {D_STR_W_LEN ("120"), 3, 120},
+  {D_STR_W_LEN ("121"), 3, 121},
+  {D_STR_W_LEN ("122"), 3, 122},
+  {D_STR_W_LEN ("123"), 3, 123},
+  {D_STR_W_LEN ("124"), 3, 124},
+  {D_STR_W_LEN ("125"), 3, 125},
+  {D_STR_W_LEN ("126"), 3, 126},
+  {D_STR_W_LEN ("127"), 3, 127},
+  {D_STR_W_LEN ("128"), 3, 128},
+  {D_STR_W_LEN ("129"), 3, 129},
+  {D_STR_W_LEN ("130"), 3, 130},
+  {D_STR_W_LEN ("131"), 3, 131},
+  {D_STR_W_LEN ("132"), 3, 132},
+  {D_STR_W_LEN ("133"), 3, 133},
+  {D_STR_W_LEN ("134"), 3, 134},
+  {D_STR_W_LEN ("135"), 3, 135},
+  {D_STR_W_LEN ("136"), 3, 136},
+  {D_STR_W_LEN ("137"), 3, 137},
+  {D_STR_W_LEN ("138"), 3, 138},
+  {D_STR_W_LEN ("139"), 3, 139},
+  {D_STR_W_LEN ("140"), 3, 140},
+  {D_STR_W_LEN ("141"), 3, 141},
+  {D_STR_W_LEN ("142"), 3, 142},
+  {D_STR_W_LEN ("143"), 3, 143},
+  {D_STR_W_LEN ("144"), 3, 144},
+  {D_STR_W_LEN ("145"), 3, 145},
+  {D_STR_W_LEN ("146"), 3, 146},
+  {D_STR_W_LEN ("147"), 3, 147},
+  {D_STR_W_LEN ("148"), 3, 148},
+  {D_STR_W_LEN ("149"), 3, 149},
+  {D_STR_W_LEN ("150"), 3, 150},
+  {D_STR_W_LEN ("151"), 3, 151},
+  {D_STR_W_LEN ("152"), 3, 152},
+  {D_STR_W_LEN ("153"), 3, 153},
+  {D_STR_W_LEN ("154"), 3, 154},
+  {D_STR_W_LEN ("155"), 3, 155},
+  {D_STR_W_LEN ("156"), 3, 156},
+  {D_STR_W_LEN ("157"), 3, 157},
+  {D_STR_W_LEN ("158"), 3, 158},
+  {D_STR_W_LEN ("159"), 3, 159},
+  {D_STR_W_LEN ("160"), 3, 160},
+  {D_STR_W_LEN ("161"), 3, 161},
+  {D_STR_W_LEN ("162"), 3, 162},
+  {D_STR_W_LEN ("163"), 3, 163},
+  {D_STR_W_LEN ("164"), 3, 164},
+  {D_STR_W_LEN ("165"), 3, 165},
+  {D_STR_W_LEN ("166"), 3, 166},
+  {D_STR_W_LEN ("167"), 3, 167},
+  {D_STR_W_LEN ("168"), 3, 168},
+  {D_STR_W_LEN ("169"), 3, 169},
+  {D_STR_W_LEN ("170"), 3, 170},
+  {D_STR_W_LEN ("171"), 3, 171},
+  {D_STR_W_LEN ("172"), 3, 172},
+  {D_STR_W_LEN ("173"), 3, 173},
+  {D_STR_W_LEN ("174"), 3, 174},
+  {D_STR_W_LEN ("175"), 3, 175},
+  {D_STR_W_LEN ("176"), 3, 176},
+  {D_STR_W_LEN ("177"), 3, 177},
+  {D_STR_W_LEN ("178"), 3, 178},
+  {D_STR_W_LEN ("179"), 3, 179},
+  {D_STR_W_LEN ("180"), 3, 180},
+  {D_STR_W_LEN ("181"), 3, 181},
+  {D_STR_W_LEN ("182"), 3, 182},
+  {D_STR_W_LEN ("183"), 3, 183},
+  {D_STR_W_LEN ("184"), 3, 184},
+  {D_STR_W_LEN ("185"), 3, 185},
+  {D_STR_W_LEN ("186"), 3, 186},
+  {D_STR_W_LEN ("187"), 3, 187},
+  {D_STR_W_LEN ("188"), 3, 188},
+  {D_STR_W_LEN ("189"), 3, 189},
+  {D_STR_W_LEN ("190"), 3, 190},
+  {D_STR_W_LEN ("191"), 3, 191},
+  {D_STR_W_LEN ("192"), 3, 192},
+  {D_STR_W_LEN ("193"), 3, 193},
+  {D_STR_W_LEN ("194"), 3, 194},
+  {D_STR_W_LEN ("195"), 3, 195},
+  {D_STR_W_LEN ("196"), 3, 196},
+  {D_STR_W_LEN ("197"), 3, 197},
+  {D_STR_W_LEN ("198"), 3, 198},
+  {D_STR_W_LEN ("199"), 3, 199},
+  {D_STR_W_LEN ("200"), 3, 200},
+  {D_STR_W_LEN ("201"), 3, 201},
+  {D_STR_W_LEN ("202"), 3, 202},
+  {D_STR_W_LEN ("203"), 3, 203},
+  {D_STR_W_LEN ("204"), 3, 204},
+  {D_STR_W_LEN ("205"), 3, 205},
+  {D_STR_W_LEN ("206"), 3, 206},
+  {D_STR_W_LEN ("207"), 3, 207},
+  {D_STR_W_LEN ("208"), 3, 208},
+  {D_STR_W_LEN ("209"), 3, 209},
+  {D_STR_W_LEN ("210"), 3, 210},
+  {D_STR_W_LEN ("211"), 3, 211},
+  {D_STR_W_LEN ("212"), 3, 212},
+  {D_STR_W_LEN ("213"), 3, 213},
+  {D_STR_W_LEN ("214"), 3, 214},
+  {D_STR_W_LEN ("215"), 3, 215},
+  {D_STR_W_LEN ("216"), 3, 216},
+  {D_STR_W_LEN ("217"), 3, 217},
+  {D_STR_W_LEN ("218"), 3, 218},
+  {D_STR_W_LEN ("219"), 3, 219},
+  {D_STR_W_LEN ("220"), 3, 220},
+  {D_STR_W_LEN ("221"), 3, 221},
+  {D_STR_W_LEN ("222"), 3, 222},
+  {D_STR_W_LEN ("223"), 3, 223},
+  {D_STR_W_LEN ("224"), 3, 224},
+  {D_STR_W_LEN ("225"), 3, 225},
+  {D_STR_W_LEN ("226"), 3, 226},
+  {D_STR_W_LEN ("227"), 3, 227},
+  {D_STR_W_LEN ("228"), 3, 228},
+  {D_STR_W_LEN ("229"), 3, 229},
+  {D_STR_W_LEN ("230"), 3, 230},
+  {D_STR_W_LEN ("231"), 3, 231},
+  {D_STR_W_LEN ("232"), 3, 232},
+  {D_STR_W_LEN ("233"), 3, 233},
+  {D_STR_W_LEN ("234"), 3, 234},
+  {D_STR_W_LEN ("235"), 3, 235},
+  {D_STR_W_LEN ("236"), 3, 236},
+  {D_STR_W_LEN ("237"), 3, 237},
+  {D_STR_W_LEN ("238"), 3, 238},
+  {D_STR_W_LEN ("239"), 3, 239},
+  {D_STR_W_LEN ("240"), 3, 240},
+  {D_STR_W_LEN ("241"), 3, 241},
+  {D_STR_W_LEN ("242"), 3, 242},
+  {D_STR_W_LEN ("243"), 3, 243},
+  {D_STR_W_LEN ("244"), 3, 244},
+  {D_STR_W_LEN ("245"), 3, 245},
+  {D_STR_W_LEN ("246"), 3, 246},
+  {D_STR_W_LEN ("247"), 3, 247},
+  {D_STR_W_LEN ("248"), 3, 248},
+  {D_STR_W_LEN ("249"), 3, 249},
+  {D_STR_W_LEN ("250"), 3, 250},
+  {D_STR_W_LEN ("251"), 3, 251},
+  {D_STR_W_LEN ("252"), 3, 252},
+  {D_STR_W_LEN ("253"), 3, 253},
+  {D_STR_W_LEN ("254"), 3, 254},
+  {D_STR_W_LEN ("255"), 3, 255}
+};
+
+static const struct str_with_value duint8_w_values_p3[] = {
+  {D_STR_W_LEN ("000"), 3, 0},
+  {D_STR_W_LEN ("001"), 3, 1},
+  {D_STR_W_LEN ("002"), 3, 2},
+  {D_STR_W_LEN ("003"), 3, 3},
+  {D_STR_W_LEN ("004"), 3, 4},
+  {D_STR_W_LEN ("005"), 3, 5},
+  {D_STR_W_LEN ("006"), 3, 6},
+  {D_STR_W_LEN ("007"), 3, 7},
+  {D_STR_W_LEN ("008"), 3, 8},
+  {D_STR_W_LEN ("009"), 3, 9},
+  {D_STR_W_LEN ("010"), 3, 10},
+  {D_STR_W_LEN ("011"), 3, 11},
+  {D_STR_W_LEN ("012"), 3, 12},
+  {D_STR_W_LEN ("013"), 3, 13},
+  {D_STR_W_LEN ("014"), 3, 14},
+  {D_STR_W_LEN ("015"), 3, 15},
+  {D_STR_W_LEN ("016"), 3, 16},
+  {D_STR_W_LEN ("017"), 3, 17},
+  {D_STR_W_LEN ("018"), 3, 18},
+  {D_STR_W_LEN ("019"), 3, 19},
+  {D_STR_W_LEN ("020"), 3, 20},
+  {D_STR_W_LEN ("021"), 3, 21},
+  {D_STR_W_LEN ("022"), 3, 22},
+  {D_STR_W_LEN ("023"), 3, 23},
+  {D_STR_W_LEN ("024"), 3, 24},
+  {D_STR_W_LEN ("025"), 3, 25},
+  {D_STR_W_LEN ("026"), 3, 26},
+  {D_STR_W_LEN ("027"), 3, 27},
+  {D_STR_W_LEN ("028"), 3, 28},
+  {D_STR_W_LEN ("029"), 3, 29},
+  {D_STR_W_LEN ("030"), 3, 30},
+  {D_STR_W_LEN ("031"), 3, 31},
+  {D_STR_W_LEN ("032"), 3, 32},
+  {D_STR_W_LEN ("033"), 3, 33},
+  {D_STR_W_LEN ("034"), 3, 34},
+  {D_STR_W_LEN ("035"), 3, 35},
+  {D_STR_W_LEN ("036"), 3, 36},
+  {D_STR_W_LEN ("037"), 3, 37},
+  {D_STR_W_LEN ("038"), 3, 38},
+  {D_STR_W_LEN ("039"), 3, 39},
+  {D_STR_W_LEN ("040"), 3, 40},
+  {D_STR_W_LEN ("041"), 3, 41},
+  {D_STR_W_LEN ("042"), 3, 42},
+  {D_STR_W_LEN ("043"), 3, 43},
+  {D_STR_W_LEN ("044"), 3, 44},
+  {D_STR_W_LEN ("045"), 3, 45},
+  {D_STR_W_LEN ("046"), 3, 46},
+  {D_STR_W_LEN ("047"), 3, 47},
+  {D_STR_W_LEN ("048"), 3, 48},
+  {D_STR_W_LEN ("049"), 3, 49},
+  {D_STR_W_LEN ("050"), 3, 50},
+  {D_STR_W_LEN ("051"), 3, 51},
+  {D_STR_W_LEN ("052"), 3, 52},
+  {D_STR_W_LEN ("053"), 3, 53},
+  {D_STR_W_LEN ("054"), 3, 54},
+  {D_STR_W_LEN ("055"), 3, 55},
+  {D_STR_W_LEN ("056"), 3, 56},
+  {D_STR_W_LEN ("057"), 3, 57},
+  {D_STR_W_LEN ("058"), 3, 58},
+  {D_STR_W_LEN ("059"), 3, 59},
+  {D_STR_W_LEN ("060"), 3, 60},
+  {D_STR_W_LEN ("061"), 3, 61},
+  {D_STR_W_LEN ("062"), 3, 62},
+  {D_STR_W_LEN ("063"), 3, 63},
+  {D_STR_W_LEN ("064"), 3, 64},
+  {D_STR_W_LEN ("065"), 3, 65},
+  {D_STR_W_LEN ("066"), 3, 66},
+  {D_STR_W_LEN ("067"), 3, 67},
+  {D_STR_W_LEN ("068"), 3, 68},
+  {D_STR_W_LEN ("069"), 3, 69},
+  {D_STR_W_LEN ("070"), 3, 70},
+  {D_STR_W_LEN ("071"), 3, 71},
+  {D_STR_W_LEN ("072"), 3, 72},
+  {D_STR_W_LEN ("073"), 3, 73},
+  {D_STR_W_LEN ("074"), 3, 74},
+  {D_STR_W_LEN ("075"), 3, 75},
+  {D_STR_W_LEN ("076"), 3, 76},
+  {D_STR_W_LEN ("077"), 3, 77},
+  {D_STR_W_LEN ("078"), 3, 78},
+  {D_STR_W_LEN ("079"), 3, 79},
+  {D_STR_W_LEN ("080"), 3, 80},
+  {D_STR_W_LEN ("081"), 3, 81},
+  {D_STR_W_LEN ("082"), 3, 82},
+  {D_STR_W_LEN ("083"), 3, 83},
+  {D_STR_W_LEN ("084"), 3, 84},
+  {D_STR_W_LEN ("085"), 3, 85},
+  {D_STR_W_LEN ("086"), 3, 86},
+  {D_STR_W_LEN ("087"), 3, 87},
+  {D_STR_W_LEN ("088"), 3, 88},
+  {D_STR_W_LEN ("089"), 3, 89},
+  {D_STR_W_LEN ("090"), 3, 90},
+  {D_STR_W_LEN ("091"), 3, 91},
+  {D_STR_W_LEN ("092"), 3, 92},
+  {D_STR_W_LEN ("093"), 3, 93},
+  {D_STR_W_LEN ("094"), 3, 94},
+  {D_STR_W_LEN ("095"), 3, 95},
+  {D_STR_W_LEN ("096"), 3, 96},
+  {D_STR_W_LEN ("097"), 3, 97},
+  {D_STR_W_LEN ("098"), 3, 98},
+  {D_STR_W_LEN ("099"), 3, 99},
+  {D_STR_W_LEN ("100"), 3, 100},
+  {D_STR_W_LEN ("101"), 3, 101},
+  {D_STR_W_LEN ("102"), 3, 102},
+  {D_STR_W_LEN ("103"), 3, 103},
+  {D_STR_W_LEN ("104"), 3, 104},
+  {D_STR_W_LEN ("105"), 3, 105},
+  {D_STR_W_LEN ("106"), 3, 106},
+  {D_STR_W_LEN ("107"), 3, 107},
+  {D_STR_W_LEN ("108"), 3, 108},
+  {D_STR_W_LEN ("109"), 3, 109},
+  {D_STR_W_LEN ("110"), 3, 110},
+  {D_STR_W_LEN ("111"), 3, 111},
+  {D_STR_W_LEN ("112"), 3, 112},
+  {D_STR_W_LEN ("113"), 3, 113},
+  {D_STR_W_LEN ("114"), 3, 114},
+  {D_STR_W_LEN ("115"), 3, 115},
+  {D_STR_W_LEN ("116"), 3, 116},
+  {D_STR_W_LEN ("117"), 3, 117},
+  {D_STR_W_LEN ("118"), 3, 118},
+  {D_STR_W_LEN ("119"), 3, 119},
+  {D_STR_W_LEN ("120"), 3, 120},
+  {D_STR_W_LEN ("121"), 3, 121},
+  {D_STR_W_LEN ("122"), 3, 122},
+  {D_STR_W_LEN ("123"), 3, 123},
+  {D_STR_W_LEN ("124"), 3, 124},
+  {D_STR_W_LEN ("125"), 3, 125},
+  {D_STR_W_LEN ("126"), 3, 126},
+  {D_STR_W_LEN ("127"), 3, 127},
+  {D_STR_W_LEN ("128"), 3, 128},
+  {D_STR_W_LEN ("129"), 3, 129},
+  {D_STR_W_LEN ("130"), 3, 130},
+  {D_STR_W_LEN ("131"), 3, 131},
+  {D_STR_W_LEN ("132"), 3, 132},
+  {D_STR_W_LEN ("133"), 3, 133},
+  {D_STR_W_LEN ("134"), 3, 134},
+  {D_STR_W_LEN ("135"), 3, 135},
+  {D_STR_W_LEN ("136"), 3, 136},
+  {D_STR_W_LEN ("137"), 3, 137},
+  {D_STR_W_LEN ("138"), 3, 138},
+  {D_STR_W_LEN ("139"), 3, 139},
+  {D_STR_W_LEN ("140"), 3, 140},
+  {D_STR_W_LEN ("141"), 3, 141},
+  {D_STR_W_LEN ("142"), 3, 142},
+  {D_STR_W_LEN ("143"), 3, 143},
+  {D_STR_W_LEN ("144"), 3, 144},
+  {D_STR_W_LEN ("145"), 3, 145},
+  {D_STR_W_LEN ("146"), 3, 146},
+  {D_STR_W_LEN ("147"), 3, 147},
+  {D_STR_W_LEN ("148"), 3, 148},
+  {D_STR_W_LEN ("149"), 3, 149},
+  {D_STR_W_LEN ("150"), 3, 150},
+  {D_STR_W_LEN ("151"), 3, 151},
+  {D_STR_W_LEN ("152"), 3, 152},
+  {D_STR_W_LEN ("153"), 3, 153},
+  {D_STR_W_LEN ("154"), 3, 154},
+  {D_STR_W_LEN ("155"), 3, 155},
+  {D_STR_W_LEN ("156"), 3, 156},
+  {D_STR_W_LEN ("157"), 3, 157},
+  {D_STR_W_LEN ("158"), 3, 158},
+  {D_STR_W_LEN ("159"), 3, 159},
+  {D_STR_W_LEN ("160"), 3, 160},
+  {D_STR_W_LEN ("161"), 3, 161},
+  {D_STR_W_LEN ("162"), 3, 162},
+  {D_STR_W_LEN ("163"), 3, 163},
+  {D_STR_W_LEN ("164"), 3, 164},
+  {D_STR_W_LEN ("165"), 3, 165},
+  {D_STR_W_LEN ("166"), 3, 166},
+  {D_STR_W_LEN ("167"), 3, 167},
+  {D_STR_W_LEN ("168"), 3, 168},
+  {D_STR_W_LEN ("169"), 3, 169},
+  {D_STR_W_LEN ("170"), 3, 170},
+  {D_STR_W_LEN ("171"), 3, 171},
+  {D_STR_W_LEN ("172"), 3, 172},
+  {D_STR_W_LEN ("173"), 3, 173},
+  {D_STR_W_LEN ("174"), 3, 174},
+  {D_STR_W_LEN ("175"), 3, 175},
+  {D_STR_W_LEN ("176"), 3, 176},
+  {D_STR_W_LEN ("177"), 3, 177},
+  {D_STR_W_LEN ("178"), 3, 178},
+  {D_STR_W_LEN ("179"), 3, 179},
+  {D_STR_W_LEN ("180"), 3, 180},
+  {D_STR_W_LEN ("181"), 3, 181},
+  {D_STR_W_LEN ("182"), 3, 182},
+  {D_STR_W_LEN ("183"), 3, 183},
+  {D_STR_W_LEN ("184"), 3, 184},
+  {D_STR_W_LEN ("185"), 3, 185},
+  {D_STR_W_LEN ("186"), 3, 186},
+  {D_STR_W_LEN ("187"), 3, 187},
+  {D_STR_W_LEN ("188"), 3, 188},
+  {D_STR_W_LEN ("189"), 3, 189},
+  {D_STR_W_LEN ("190"), 3, 190},
+  {D_STR_W_LEN ("191"), 3, 191},
+  {D_STR_W_LEN ("192"), 3, 192},
+  {D_STR_W_LEN ("193"), 3, 193},
+  {D_STR_W_LEN ("194"), 3, 194},
+  {D_STR_W_LEN ("195"), 3, 195},
+  {D_STR_W_LEN ("196"), 3, 196},
+  {D_STR_W_LEN ("197"), 3, 197},
+  {D_STR_W_LEN ("198"), 3, 198},
+  {D_STR_W_LEN ("199"), 3, 199},
+  {D_STR_W_LEN ("200"), 3, 200},
+  {D_STR_W_LEN ("201"), 3, 201},
+  {D_STR_W_LEN ("202"), 3, 202},
+  {D_STR_W_LEN ("203"), 3, 203},
+  {D_STR_W_LEN ("204"), 3, 204},
+  {D_STR_W_LEN ("205"), 3, 205},
+  {D_STR_W_LEN ("206"), 3, 206},
+  {D_STR_W_LEN ("207"), 3, 207},
+  {D_STR_W_LEN ("208"), 3, 208},
+  {D_STR_W_LEN ("209"), 3, 209},
+  {D_STR_W_LEN ("210"), 3, 210},
+  {D_STR_W_LEN ("211"), 3, 211},
+  {D_STR_W_LEN ("212"), 3, 212},
+  {D_STR_W_LEN ("213"), 3, 213},
+  {D_STR_W_LEN ("214"), 3, 214},
+  {D_STR_W_LEN ("215"), 3, 215},
+  {D_STR_W_LEN ("216"), 3, 216},
+  {D_STR_W_LEN ("217"), 3, 217},
+  {D_STR_W_LEN ("218"), 3, 218},
+  {D_STR_W_LEN ("219"), 3, 219},
+  {D_STR_W_LEN ("220"), 3, 220},
+  {D_STR_W_LEN ("221"), 3, 221},
+  {D_STR_W_LEN ("222"), 3, 222},
+  {D_STR_W_LEN ("223"), 3, 223},
+  {D_STR_W_LEN ("224"), 3, 224},
+  {D_STR_W_LEN ("225"), 3, 225},
+  {D_STR_W_LEN ("226"), 3, 226},
+  {D_STR_W_LEN ("227"), 3, 227},
+  {D_STR_W_LEN ("228"), 3, 228},
+  {D_STR_W_LEN ("229"), 3, 229},
+  {D_STR_W_LEN ("230"), 3, 230},
+  {D_STR_W_LEN ("231"), 3, 231},
+  {D_STR_W_LEN ("232"), 3, 232},
+  {D_STR_W_LEN ("233"), 3, 233},
+  {D_STR_W_LEN ("234"), 3, 234},
+  {D_STR_W_LEN ("235"), 3, 235},
+  {D_STR_W_LEN ("236"), 3, 236},
+  {D_STR_W_LEN ("237"), 3, 237},
+  {D_STR_W_LEN ("238"), 3, 238},
+  {D_STR_W_LEN ("239"), 3, 239},
+  {D_STR_W_LEN ("240"), 3, 240},
+  {D_STR_W_LEN ("241"), 3, 241},
+  {D_STR_W_LEN ("242"), 3, 242},
+  {D_STR_W_LEN ("243"), 3, 243},
+  {D_STR_W_LEN ("244"), 3, 244},
+  {D_STR_W_LEN ("245"), 3, 245},
+  {D_STR_W_LEN ("246"), 3, 246},
+  {D_STR_W_LEN ("247"), 3, 247},
+  {D_STR_W_LEN ("248"), 3, 248},
+  {D_STR_W_LEN ("249"), 3, 249},
+  {D_STR_W_LEN ("250"), 3, 250},
+  {D_STR_W_LEN ("251"), 3, 251},
+  {D_STR_W_LEN ("252"), 3, 252},
+  {D_STR_W_LEN ("253"), 3, 253},
+  {D_STR_W_LEN ("254"), 3, 254},
+  {D_STR_W_LEN ("255"), 3, 255}
+};
+
+
+static const struct str_with_value *duint8_w_values_p[3] =
+{duint8_w_values_p1, duint8_w_values_p2, duint8_w_values_p3};
+
+static size_t
+check_str_from_uint8_pad (void)
+{
+  int i;
+  uint8_t pad;
+  size_t t_failed = 0;
+
+  if ((256 != sizeof(duint8_w_values_p1) / sizeof(duint8_w_values_p1[0])) ||
+      (256 != sizeof(duint8_w_values_p2) / sizeof(duint8_w_values_p2[0])) ||
+      (256 != sizeof(duint8_w_values_p3) / sizeof(duint8_w_values_p3[0])))
+  {
+    fprintf (stderr,
+             "ERROR: wrong number of items in duint8_w_values_p*.\n");
+    exit (99);
+  }
+  for (pad = 0; pad <= 3; pad++)
+  {
+    size_t table_num;
+    if (0 != pad)
+      table_num = pad - 1;
+    else
+      table_num = 0;
+
+    for (i = 0; i <= 255; i++)
+    {
+      const struct str_with_value *const t = duint8_w_values_p[table_num] + i;
+      size_t b_size;
+      size_t rs;
+      char buf[8];
+
+      if (t->str.len < t->num_of_digt)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected"
+                 " to be less or equal to str.len (%u).\n",
+                 (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned
+                                                                   int) t->str.
+                 len);
+        exit (99);
+      }
+      if (sizeof(buf) < t->str.len + 1)
+      {
+        fprintf (stderr,
+                 "ERROR: dstrs_w_values[%u] has too long (%u) string, "
+                 "size of 'buf' should be increased.\n",
+                 (unsigned int) i, (unsigned int) t->str.len);
+        exit (99);
+      }
+      for (b_size = 0; b_size <= t->str.len + 1; ++b_size)
+      {
+        /* fill buffer with pseudo-random values */
+        memset (buf, '#', sizeof(buf));
+
+        rs = MHD_uint8_to_str_pad ((uint8_t) t->val, pad, buf, b_size);
+
+        if (t->num_of_digt > b_size)
+        {
+          /* Must fail, buffer is too small for result */
+          if (0 != rs)
+          {
+            t_failed++;
+            fprintf (stderr,
+                     "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting 0.\n", t->val, (int) pad, (int) b_size,
+                     (uintptr_t) rs);
+          }
+        }
+        else
+        {
+          if (t->num_of_digt != rs)
+          {
+            t_failed++;
+            fprintf (stderr,
+                     "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, -> buf,"
+                     " %d) returned %" PRIuPTR
+                     ", while expecting %d.\n", t->val, (int) pad,
+                     (int) b_size, (uintptr_t) rs, (int) t->num_of_digt);
+          }
+          else if (0 != memcmp (buf, t->str.str, t->num_of_digt))
+          {
+            t_failed++;
+            fprintf (stderr,
+                     "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, "
+                     "-> \"%.*s\", %d) returned %" PRIuPTR ".\n",
+                     t->val, (int) pad, (int) rs, buf,
+                     (int) b_size, (uintptr_t) rs);
+          }
+          else if (0 != memcmp (buf + rs, "########", sizeof(buf) - rs))
+          {
+            t_failed++;
+            fprintf (stderr,
+                     "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d,"
+                     " -> \"%.*s\", %d) returned %" PRIuPTR
+                     " and touched data after the resulting string.\n",
+                     t->val, (int) pad, (int) rs, buf, (int) b_size,
+                     (uintptr_t) rs);
+          }
+        }
+      }
+    }
+  }
+  if ((verbose > 1) && (0 == t_failed))
+    printf ("PASSED: MHD_uint8_to_str_pad.\n");
+
+  return t_failed;
+}
+
+
+static int
+run_str_from_X_tests (void)
+{
+  size_t str_from_uint16;
+  size_t str_from_uint64;
+  size_t strx_from_uint32;
+  size_t str_from_uint8_pad;
+  size_t failures;
+
+  failures = 0;
+
+  str_from_uint16 = check_str_from_uint16 ();
+  if (str_from_uint16 != 0)
+  {
+    fprintf (stderr,
+             "FAILED: testcase check_str_from_uint16() failed.\n\n");
+    failures += str_from_uint16;
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_from_uint16() successfully "
+            "passed.\n\n");
+
+  str_from_uint64 = check_str_from_uint64 ();
+  if (str_from_uint64 != 0)
+  {
+    fprintf (stderr,
+             "FAILED: testcase check_str_from_uint16() failed.\n\n");
+    failures += str_from_uint64;
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_from_uint16() successfully "
+            "passed.\n\n");
+  strx_from_uint32 = check_strx_from_uint32 ();
+  if (strx_from_uint32 != 0)
+  {
+    fprintf (stderr,
+             "FAILED: testcase check_strx_from_uint32() failed.\n\n");
+    failures += strx_from_uint32;
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_strx_from_uint32() successfully "
+            "passed.\n\n");
+
+  str_from_uint8_pad = check_str_from_uint8_pad ();
+  if (str_from_uint8_pad != 0)
+  {
+    fprintf (stderr,
+             "FAILED: testcase check_str_from_uint8_pad() failed.\n\n");
+    failures += str_from_uint8_pad;
+  }
+  else if (verbose > 1)
+    printf ("PASSED: testcase check_str_from_uint8_pad() successfully "
+            "passed.\n\n");
+
+  if (failures)
+  {
+    if (verbose > 0)
+      printf ("At least one test failed.\n");
+
+    return 1;
+  }
+
+  if (verbose > 0)
+    printf ("All tests passed successfully.\n");
+
+  return 0;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose") ||
+      has_param (argc, argv, "--verbose1"))
+    verbose = 1;
+  if (has_param (argc, argv, "-vv") || has_param (argc, argv, "--verbose2"))
+    verbose = 2;
+  if (has_param (argc, argv, "-vvv") || has_param (argc, argv, "--verbose3"))
+    verbose = 3;
+
+  if (has_in_name (argv[0], "_to_value"))
+    return run_str_to_X_tests ();
+
+  if (has_in_name (argv[0], "_from_value"))
+    return run_str_from_X_tests ();
+
+  return run_eq_neq_str_tests ();
+}
diff --git a/src/microhttpd/test_str_base64.c b/src/microhttpd/test_str_base64.c
new file mode 100644
index 0000000..1821d11
--- /dev/null
+++ b/src/microhttpd/test_str_base64.c
@@ -0,0 +1,748 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_base64.c
+ * @brief  Unit tests for base64 strings processing
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+#define TEST_BIN_MAX_SIZE 1024
+
+/* return zero if succeed, one otherwise */
+static unsigned int
+expect_decoded_n (const char *const encoded, const size_t encoded_len,
+                  const uint8_t *const decoded, const size_t decoded_size,
+                  const unsigned int line_num)
+{
+  static const char fill_chr = '#';
+  static uint8_t buf[TEST_BIN_MAX_SIZE];
+  size_t res_size;
+  unsigned int ret;
+
+  mhd_assert (NULL != encoded);
+  mhd_assert (NULL != decoded);
+  mhd_assert (TEST_BIN_MAX_SIZE > decoded_size);
+  mhd_assert (encoded_len >= decoded_size);
+  mhd_assert (0 == encoded_len || encoded_len > decoded_size);
+
+  ret = 0;
+  memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+  res_size = MHD_base64_to_bin_n (encoded, encoded_len, buf, decoded_size);
+
+  if (res_size != decoded_size)
+  {
+    ret = 1;
+    fprintf (stderr,
+             "'MHD_base64_to_bin_n ()' FAILED: Wrong returned value:\n");
+  }
+  else if ((0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size)))
+  {
+    ret = 1;
+    fprintf (stderr,
+             "'MHD_base64_to_bin_n ()' FAILED: Wrong output binary:\n");
+  }
+  if (0 != ret)
+  {
+    static char prnt[TEST_BIN_MAX_SIZE * 2 + 1];
+    size_t prnt_size;
+    if (TEST_BIN_MAX_SIZE <= res_size * 2)
+    {
+      fprintf (stderr,
+               "\tRESULT  : MHD_base64_to_bin_n ('%.*s', %u, ->(too long), %u)"
+               " -> %u\n",
+               (int) encoded_len, encoded, (unsigned) encoded_len,
+               (unsigned) decoded_size, (unsigned) res_size);
+    }
+    else
+    {
+      prnt_size = MHD_bin_to_hex_z (buf, res_size, prnt);
+      mhd_assert (2 * res_size == prnt_size);
+
+      fprintf (stderr,
+               "\tRESULT  : MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)"
+               " -> %u\n",
+               (int) encoded_len, encoded, (unsigned) encoded_len,
+               (int) prnt_size, prnt, (unsigned) decoded_size,
+               (unsigned) res_size);
+    }
+    prnt_size = MHD_bin_to_hex_z (decoded, decoded_size, prnt);
+    mhd_assert (2 * decoded_size == prnt_size);
+    fprintf (stderr,
+             "\tEXPECTED: MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)"
+             " -> %u\n",
+             (int) encoded_len, encoded, (unsigned) encoded_len,
+             (int) prnt_size, prnt, (unsigned) decoded_size,
+             (unsigned) decoded_size);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  return ret;
+}
+
+
+#define expect_decoded(e,d) \
+        expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\
+                         (const uint8_t*)(d),MHD_STATICSTR_LEN_(d), \
+                         __LINE__)
+
+static unsigned int
+check_decode_str (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_decoded ("", "");
+
+  /* Base sequences without padding */
+  r += expect_decoded ("YWFh", "aaa");
+  r += expect_decoded ("YmJi", "bbb");
+  r += expect_decoded ("Y2Nj", "ccc");
+  r += expect_decoded ("ZGRk", "ddd");
+  r += expect_decoded ("bGxs", "lll");
+  r += expect_decoded ("bW1t", "mmm");
+  r += expect_decoded ("bm5u", "nnn");
+  r += expect_decoded ("b29v", "ooo");
+  r += expect_decoded ("d3d3", "www");
+  r += expect_decoded ("eHh4", "xxx");
+  r += expect_decoded ("eXl5", "yyy");
+  r += expect_decoded ("enp6", "zzz");
+  r += expect_decoded ("QUFB", "AAA");
+  r += expect_decoded ("R0dH", "GGG");
+  r += expect_decoded ("TU1N", "MMM");
+  r += expect_decoded ("VFRU", "TTT");
+  r += expect_decoded ("Wlpa", "ZZZ");
+  r += expect_decoded ("MDEy", "012");
+  r += expect_decoded ("MzQ1", "345");
+  r += expect_decoded ("Njc4", "678");
+  r += expect_decoded ("OTAx", "901");
+  r += expect_decoded ("YWFhYWFh", "aaaaaa");
+  r += expect_decoded ("YmJiYmJi", "bbbbbb");
+  r += expect_decoded ("Y2NjY2Nj", "cccccc");
+  r += expect_decoded ("ZGRkZGRk", "dddddd");
+  r += expect_decoded ("bGxsbGxs", "llllll");
+  r += expect_decoded ("bW1tbW1t", "mmmmmm");
+  r += expect_decoded ("bm5ubm5u", "nnnnnn");
+  r += expect_decoded ("b29vb29v", "oooooo");
+  r += expect_decoded ("d3d3d3d3", "wwwwww");
+  r += expect_decoded ("eHh4eHh4", "xxxxxx");
+  r += expect_decoded ("eXl5eXl5", "yyyyyy");
+  r += expect_decoded ("enp6enp6", "zzzzzz");
+  r += expect_decoded ("QUFBQUFB", "AAAAAA");
+  r += expect_decoded ("R0dHR0dH", "GGGGGG");
+  r += expect_decoded ("TU1NTU1N", "MMMMMM");
+  r += expect_decoded ("VFRUVFRU", "TTTTTT");
+  r += expect_decoded ("WlpaWlpa", "ZZZZZZ");
+  r += expect_decoded ("MDEyMDEy", "012012");
+  r += expect_decoded ("MzQ1MzQ1", "345345");
+  r += expect_decoded ("Njc4Njc4", "678678");
+  r += expect_decoded ("OTAxOTAx", "901901");
+
+  /* Various lengths */
+  r += expect_decoded ("YQ==", "a");
+  r += expect_decoded ("YmM=", "bc");
+  r += expect_decoded ("REVGRw==", "DEFG");
+  r += expect_decoded ("MTIzdA==", "123t");
+  r += expect_decoded ("MTIzNDU=", "12345");
+  r += expect_decoded ("VGVzdCBTdHI=", "Test Str");
+  r += expect_decoded ("VGVzdCBzdHJpbmc=", "Test string");
+  r += expect_decoded ("VGVzdCBzdHJpbmcu", "Test string.");
+  r += expect_decoded ("TG9uZ2VyIHN0cmluZw==", "Longer string");
+  r += expect_decoded ("TG9uZ2VyIHN0cmluZy4=", "Longer string.");
+  r += expect_decoded ("TG9uZ2VyIHN0cmluZzIu", "Longer string2.");
+
+  return r;
+}
+
+
+#define expect_decoded_arr(e,a) \
+        expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\
+                         a,(sizeof(a)/sizeof(a[0])), \
+                         __LINE__)
+
+static unsigned int
+check_decode_bin (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe,
+     0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
+     0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26,
+     0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
+     0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+     0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+     0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
+     0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
+     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
+     0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+     0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86,
+     0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92,
+     0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e,
+     0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
+     0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+     0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
+     0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+     0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+     0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
+     0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2,
+     0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
+     0xff };
+    r += expect_decoded_arr ("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISI" \
+                             "jJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERU" \
+                             "ZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoa" \
+                             "WprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouM" \
+                             "jY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+" \
+                             "wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0t" \
+                             "PU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19" \
+                             "vf4+fr7/P3+/w==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf,
+     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
+     0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
+     0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33,
+     0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
+     0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b,
+     0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
+     0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,
+     0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
+     0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b,
+     0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93,
+     0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
+     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab,
+     0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
+     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3,
+     0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
+     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb,
+     0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
+     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3,
+     0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
+     0x0 };
+    r += expect_decoded_arr ("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiM" \
+                             "kJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRk" \
+                             "dISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpa" \
+                             "mtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yN" \
+                             "jo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7C" \
+                             "xsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09" \
+                             "TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29" \
+                             "/j5+vv8/f7/AA==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10,
+     0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
+     0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
+     0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34,
+     0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
+     0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
+     0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
+     0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64,
+     0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
+     0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c,
+     0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
+     0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94,
+     0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0,
+     0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac,
+     0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8,
+     0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4,
+     0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0,
+     0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc,
+     0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8,
+     0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4,
+     0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0,
+     0x1 };
+    r += expect_decoded_arr ("AgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQ" \
+                             "lJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0" \
+                             "hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa" \
+                             "2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2O" \
+                             "j5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLG" \
+                             "ys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1N" \
+                             "XW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+" \
+                             "Pn6+/z9/v8AAQ==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10,
+     0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
+     0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
+     0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34,
+     0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
+     0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
+     0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
+     0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64,
+     0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
+     0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c,
+     0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
+     0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94,
+     0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0,
+     0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac,
+     0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8,
+     0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4,
+     0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0,
+     0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc,
+     0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8,
+     0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4,
+     0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0,
+     0x1, 0x2 };
+    r += expect_decoded_arr ("AwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCU" \
+                             "mJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSE" \
+                             "lKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprb" \
+                             "G1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P" \
+                             "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbK" \
+                             "ztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1d" \
+                             "bX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+" \
+                             "fr7/P3+/wABAg==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4,
+     0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8,
+     0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc,
+     0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0,
+     0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4,
+     0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8,
+     0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac,
+     0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0,
+     0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94,
+     0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88,
+     0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c,
+     0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70,
+     0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64,
+     0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58,
+     0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c,
+     0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40,
+     0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34,
+     0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
+     0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c,
+     0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
+     0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1,
+     0x0 };
+    r += expect_decoded_arr ("//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3" \
+                             "c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7ur" \
+                             "m4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXl" \
+                             "pWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRz" \
+                             "cnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVB" \
+                             "PTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLS" \
+                             "wrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKC" \
+                             "QgHBgUEAwIBAA==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5,
+     0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9,
+     0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd,
+     0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1,
+     0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5,
+     0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9,
+     0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad,
+     0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1,
+     0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95,
+     0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89,
+     0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d,
+     0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71,
+     0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65,
+     0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59,
+     0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d,
+     0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41,
+     0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35,
+     0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29,
+     0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d,
+     0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11,
+     0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3,
+     0x2, 0x1};
+    r += expect_decoded_arr ("AP/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397" \
+                             "d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7" \
+                             "q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl" \
+                             "5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0" \
+                             "c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlF" \
+                             "QT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi" \
+                             "0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLC" \
+                             "gkIBwYFBAMCAQ==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x1, 0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5,
+     0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9,
+     0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd,
+     0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1,
+     0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5,
+     0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9,
+     0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad,
+     0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1,
+     0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95,
+     0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89,
+     0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d,
+     0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71,
+     0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65,
+     0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59,
+     0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d,
+     0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41,
+     0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35,
+     0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29,
+     0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d,
+     0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11,
+     0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3,
+     0x2};
+    r += expect_decoded_arr ("AQD//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/" \
+                             "e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vL" \
+                             "u6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZm" \
+                             "JeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1" \
+                             "dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1J" \
+                             "RUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy" \
+                             "4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MC" \
+                             "woJCAcGBQQDAg==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x2, 0x1, 0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6,
+     0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea,
+     0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde,
+     0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2,
+     0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6,
+     0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba,
+     0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae,
+     0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2,
+     0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96,
+     0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a,
+     0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e,
+     0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72,
+     0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66,
+     0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a,
+     0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e,
+     0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42,
+     0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36,
+     0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a,
+     0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e,
+     0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12,
+     0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4,
+     0x3};
+    r += expect_decoded_arr ("AgEA//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eD" \
+                             "f3t3c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vb" \
+                             "y7urm4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuam" \
+                             "ZiXlpWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2" \
+                             "dXRzcnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFN" \
+                             "SUVBPTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC" \
+                             "8uLSwrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4ND" \
+                             "AsKCQgHBgUEAw==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3,
+     0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7,
+     0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb,
+     0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf,
+     0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3,
+     0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7,
+     0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab,
+     0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f,
+     0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93,
+     0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87,
+     0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b,
+     0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f,
+     0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63,
+     0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57,
+     0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b,
+     0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f,
+     0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33,
+     0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27,
+     0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b,
+     0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf,
+     0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0,
+     0xff};
+    r += expect_decoded_arr ("/v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dz" \
+                             "b2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ub" \
+                             "i3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWl" \
+                             "ZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNy" \
+                             "cXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9" \
+                             "OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLC" \
+                             "sqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJC" \
+                             "AcGBQQDAgEA/w==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2,
+     0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6,
+     0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda,
+     0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce,
+     0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2,
+     0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6,
+     0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa,
+     0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e,
+     0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92,
+     0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86,
+     0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a,
+     0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e,
+     0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62,
+     0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56,
+     0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a,
+     0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e,
+     0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32,
+     0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26,
+     0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a,
+     0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd,
+     0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff,
+     0xfe};
+    r += expect_decoded_arr ("/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nv" \
+                             "a2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uL" \
+                             "e2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVl" \
+                             "JOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3Jx" \
+                             "cG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05" \
+                             "NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKy" \
+                             "opKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIB" \
+                             "wYFBAMCAQD//g==", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1,
+     0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5,
+     0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9,
+     0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd,
+     0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1,
+     0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5,
+     0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9,
+     0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d,
+     0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91,
+     0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85,
+     0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79,
+     0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d,
+     0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61,
+     0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55,
+     0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49,
+     0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d,
+     0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31,
+     0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25,
+     0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19,
+     0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc,
+     0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff, 0xfe,
+     0xfd };
+    r += expect_decoded_arr ("/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3c29r" \
+                             "Z2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7urm4t7" \
+                             "a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXlpWUk" \
+                             "5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRzcnFw" \
+                             "b25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVBPTk1" \
+                             "MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLSwrKi" \
+                             "koJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKCQgHB" \
+                             "gUEAwIBAP/+/Q==", bin);
+  }
+
+  return r;
+}
+
+
+/* return zero if succeed, one otherwise */
+static unsigned int
+expect_fail_n (const char *const encoded, const size_t encoded_len,
+               const unsigned int line_num)
+{
+  static const char fill_chr = '#';
+  static uint8_t buf[TEST_BIN_MAX_SIZE];
+  size_t res_size;
+  unsigned int ret;
+
+  mhd_assert (NULL != encoded);
+  mhd_assert (TEST_BIN_MAX_SIZE > encoded_len);
+
+  ret = 0;
+  memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+  res_size = MHD_base64_to_bin_n (encoded, encoded_len, buf, sizeof(buf));
+
+  if (res_size != 0)
+  {
+    ret = 1;
+    fprintf (stderr,
+             "'MHD_base64_to_bin_n ()' FAILED: Wrong returned value:\n");
+  }
+  if (0 != ret)
+  {
+    static char prnt[TEST_BIN_MAX_SIZE * 2 + 1];
+    size_t prnt_size;
+    if (TEST_BIN_MAX_SIZE <= res_size * 2)
+    {
+      fprintf (stderr,
+               "\tRESULT  : MHD_base64_to_bin_n ('%.*s', %u, ->(too long), %u)"
+               " -> %u\n",
+               (int) encoded_len, encoded, (unsigned) encoded_len,
+               (unsigned) sizeof(buf), (unsigned) res_size);
+    }
+    else
+    {
+      prnt_size = MHD_bin_to_hex_z (buf, res_size, prnt);
+      mhd_assert (2 * res_size == prnt_size);
+
+      fprintf (stderr,
+               "\tRESULT  : MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)"
+               " -> %u\n",
+               (int) encoded_len, encoded, (unsigned) encoded_len,
+               (int) prnt_size, prnt, (unsigned) sizeof(buf),
+               (unsigned) res_size);
+    }
+    fprintf (stderr,
+             "\tEXPECTED: MHD_base64_to_bin_n ('%.*s', %u, ->(empty), %u)"
+             " -> 0\n",
+             (int) encoded_len, encoded, (unsigned) encoded_len,
+             (unsigned) sizeof(buf));
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  return ret;
+}
+
+
+#define expect_fail(e) \
+        expect_fail_n(e,MHD_STATICSTR_LEN_(e),__LINE__)
+
+
+static unsigned int
+check_fail (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  /* Base sequences with wrong length */
+  r += expect_fail ("YWFh/");
+  r += expect_fail ("YWFh/Q");
+  r += expect_fail ("YWFhE/Q");
+  r += expect_fail ("bW1tbW1t/");
+  r += expect_fail ("bW1tbW1t/Q");
+  r += expect_fail ("bW1tbW1tE/Q");
+
+  /* Base sequences with wrong char */
+  r += expect_fail ("%mJi");
+  r += expect_fail ("Y%Nj");
+  r += expect_fail ("ZG%k");
+  r += expect_fail ("bGx%");
+  r += expect_fail ("#W1t");
+  r += expect_fail ("b#5u");
+  r += expect_fail ("b2#v");
+  r += expect_fail ("d3d#");
+  r += expect_fail ("^Hh4");
+  r += expect_fail ("e^l5");
+  r += expect_fail ("en^6");
+  r += expect_fail ("QUF^");
+  r += expect_fail ("~0dH");
+  r += expect_fail ("T~1N");
+  r += expect_fail ("VF~U");
+  r += expect_fail ("Wlp~");
+  r += expect_fail ("*DEy");
+  r += expect_fail ("M*Q1");
+  r += expect_fail ("Nj*4");
+  r += expect_fail ("OTA*");
+  r += expect_fail ("&WFhYWFh");
+  r += expect_fail ("Y&JiYmJi");
+  r += expect_fail ("Y2&jY2Nj");
+  r += expect_fail ("ZGR&ZGRk");
+  r += expect_fail ("bGxs&Gxs");
+  r += expect_fail ("bW1tb&1t");
+  r += expect_fail ("bm5ubm&u");
+  r += expect_fail ("b29vb29&");
+  r += expect_fail ("!3d3d3d3");
+  r += expect_fail ("e!h4eHh4");
+  r += expect_fail ("eX!5eXl5");
+  r += expect_fail ("enp!enp6");
+  r += expect_fail ("QUFB!UFB");
+  r += expect_fail ("R0dHR!dH");
+  r += expect_fail ("TU1NTU!N");
+  r += expect_fail ("VFRUVFR!");
+
+  /* Bad high-ASCII char */
+  r += expect_fail ("\xff" "WFhYWFh");
+  r += expect_fail ("Y\xfe" "JiYmJi");
+  r += expect_fail ("Y2\xfd" "jY2Nj");
+  r += expect_fail ("ZGR\xfc" "ZGRk");
+  r += expect_fail ("bGxs\xfb" "Gxs");
+  r += expect_fail ("bW1tbW\xfa" "1t");
+  r += expect_fail ("bm5ubm\xf9" "u");
+  r += expect_fail ("b29vb29\xf8");
+  r += expect_fail ("d3d3d3d\x80");
+  r += expect_fail ("eHh4eH\x81" "4");
+  r += expect_fail ("eXl5e\x82" "l5");
+  r += expect_fail ("enp6\x83" "np6");
+  r += expect_fail ("QUF\x84" "QUFB");
+  r += expect_fail ("TU\x85" "NTU1N");
+  r += expect_fail ("V\x86" "RUVFRU");
+  r += expect_fail ("\x87" "lpaWlpa");
+
+  /* Base sequences with wrong padding char */
+  r += expect_fail ("=lpaWlpa");
+  r += expect_fail ("M=EyMDEy");
+  r += expect_fail ("Mz=1MzQ1");
+  r += expect_fail ("Njc=Njc4");
+  r += expect_fail ("OTAx=TAx");
+  r += expect_fail ("ZGRkZ=Rk");
+  r += expect_fail ("bGxsbG=s");
+  r += expect_fail ("bW1tb===");
+  r += expect_fail ("bm5u====");
+
+  /* Bad last char (valid for Base64, but padding part is not zero */
+  r += expect_fail ("TG9uZ2VyIHN0cmluZo==");
+  r += expect_fail ("TG9uZ2VyIHN0cmluZyK=");
+
+  return r;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_decode_str ();
+  errcount += check_decode_bin ();
+  errcount += check_fail ();
+  if (0 == errcount)
+    printf ("All tests were passed without errors.\n");
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_str_bin_hex.c b/src/microhttpd/test_str_bin_hex.c
new file mode 100644
index 0000000..557146e
--- /dev/null
+++ b/src/microhttpd/test_str_bin_hex.c
@@ -0,0 +1,448 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_bin_hex.c
+ * @brief  Unit tests for hex strings <-> binary data processing
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */
+static size_t buf_idx = 0;
+
+/* print non-printable chars as char codes */
+static char *
+n_prnt (const char *str, size_t len)
+{
+  static char *buf;  /* should be enough for testing */
+  static const size_t buf_size = sizeof(tmp_bufs[0]);
+  size_t r_pos = 0;
+  size_t w_pos = 0;
+  if (++buf_idx >= (sizeof(tmp_bufs) / sizeof(tmp_bufs[0])))
+    buf_idx = 0;
+  buf = tmp_bufs[buf_idx];
+
+  while (len > r_pos && w_pos + 1 < buf_size)
+  {
+    const unsigned char c = (unsigned char) str[r_pos];
+    if ((c == '\\') || (c == '"') )
+    {
+      if (w_pos + 2 >= buf_size)
+        break;
+      buf[w_pos++] = '\\';
+      buf[w_pos++] = (char) c;
+    }
+    else if ((c >= 0x20) && (c <= 0x7E) )
+      buf[w_pos++] = (char) c;
+    else
+    {
+      if (w_pos + 4 >= buf_size)
+        break;
+      if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned
+                                                                int) c) != 4)
+        break;
+      w_pos += 4;
+    }
+    r_pos++;
+  }
+
+  if (len != r_pos)
+  {   /* not full string is printed */
+      /* enough space for "..." ? */
+    if (w_pos + 3 > buf_size)
+      w_pos = buf_size - 4;
+    buf[w_pos++] = '.';
+    buf[w_pos++] = '.';
+    buf[w_pos++] = '.';
+  }
+  buf[w_pos] = 0;
+  return buf;
+}
+
+
+#define TEST_BIN_MAX_SIZE (2 * 1024)
+
+/* return zero if succeed, number of failures otherwise */
+static unsigned int
+expect_decoded_n (const char *const hex, const size_t hex_len,
+                  const uint8_t *const bin, const size_t bin_size,
+                  const unsigned int line_num)
+{
+  static const char fill_chr = '#';
+  static char buf[TEST_BIN_MAX_SIZE];
+  size_t res_size;
+  unsigned int ret;
+
+  mhd_assert (NULL != hex);
+  mhd_assert (NULL != bin);
+  mhd_assert (TEST_BIN_MAX_SIZE > bin_size + 1);
+  mhd_assert (TEST_BIN_MAX_SIZE > hex_len + 1);
+  mhd_assert (hex_len >= bin_size);
+  mhd_assert (1 >= hex_len || hex_len > bin_size);
+
+  ret = 0;
+
+  /* check MHD_hex_to_bin() */
+  if (1)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_hex_to_bin (hex, hex_len, buf);
+    if (res_size != bin_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_hex_to_bin ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if ((0 != bin_size) &&
+          (0 != memcmp (buf, bin, bin_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_hex_to_bin ()' FAILED: "
+                 "Wrong output data:\n");
+      }
+    }
+    if (fill_chr != buf[res_size])
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+               "A char written outside the buffer:\n");
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_hex_to_bin (\"%s\", %u, "
+               "->\"%s\") -> %u\n",
+               n_prnt (hex, hex_len), (unsigned) hex_len,
+               n_prnt (buf, res_size),
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, "
+               "->\"%s\") -> %u\n",
+               n_prnt (hex, hex_len), (unsigned) hex_len,
+               n_prnt ((const char *) bin, bin_size),
+               (unsigned) bin_size);
+    }
+  }
+
+  /* check MHD_bin_to_hex() */
+  if (0 == hex_len % 2)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_bin_to_hex_z (bin, bin_size, buf);
+
+    if (res_size != hex_len)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_bin_to_hex ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if ((0 != hex_len) &&
+          (! MHD_str_equal_caseless_bin_n_ (buf, hex, hex_len)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_bin_to_hex ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (fill_chr != buf[res_size + 1])
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_bin_to_hex ()' FAILED: "
+               "A char written outside the buffer:\n");
+    }
+    if (0 != buf[res_size])
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_bin_to_hex ()' FAILED: "
+               "The result is not zero-terminated:\n");
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_bin_to_hex (\"%s\", %u, "
+               "->\"%s\") -> %u\n",
+               n_prnt ((const char *) bin, bin_size), (unsigned) bin_size,
+               n_prnt (buf, res_size),
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_bin_to_hex (\"%s\", %u, "
+               "->(lower case)\"%s\") -> %u\n",
+               n_prnt ((const char *) bin, bin_size), (unsigned) bin_size,
+               n_prnt (hex, hex_len),
+               (unsigned) bin_size);
+    }
+  }
+
+  if (0 != ret)
+  {
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  return ret;
+}
+
+
+#define expect_decoded_arr(h,a) \
+        expect_decoded_n(h,MHD_STATICSTR_LEN_(h),\
+                         a,(sizeof(a)/sizeof(a[0])), \
+                         __LINE__)
+
+static unsigned int
+check_decode_bin (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe,
+     0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
+     0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26,
+     0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
+     0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+     0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+     0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
+     0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
+     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
+     0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+     0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86,
+     0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92,
+     0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e,
+     0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
+     0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+     0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
+     0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+     0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+     0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
+     0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2,
+     0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
+     0xff };
+    /* The lower case */
+    r += expect_decoded_arr ("000102030405060708090a0b0c0d0e" \
+                             "0f101112131415161718191a1b1c1d" \
+                             "1e1f202122232425262728292a2b2c" \
+                             "2d2e2f303132333435363738393a3b" \
+                             "3c3d3e3f404142434445464748494a" \
+                             "4b4c4d4e4f50515253545556575859" \
+                             "5a5b5c5d5e5f606162636465666768" \
+                             "696a6b6c6d6e6f7071727374757677" \
+                             "78797a7b7c7d7e7f80818283848586" \
+                             "8788898a8b8c8d8e8f909192939495" \
+                             "969798999a9b9c9d9e9fa0a1a2a3a4" \
+                             "a5a6a7a8a9aaabacadaeafb0b1b2b3" \
+                             "b4b5b6b7b8b9babbbcbdbebfc0c1c2" \
+                             "c3c4c5c6c7c8c9cacbcccdcecfd0d1" \
+                             "d2d3d4d5d6d7d8d9dadbdcdddedfe0" \
+                             "e1e2e3e4e5e6e7e8e9eaebecedeeef" \
+                             "f0f1f2f3f4f5f6f7f8f9fafbfcfdfe" \
+                             "ff", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe,
+     0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
+     0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26,
+     0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
+     0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+     0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+     0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
+     0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
+     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
+     0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+     0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86,
+     0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92,
+     0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e,
+     0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
+     0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+     0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
+     0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+     0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+     0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
+     0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2,
+     0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
+     0xff };
+    /* The upper case */
+    r += expect_decoded_arr ("000102030405060708090A0B0C0D0E" \
+                             "0F101112131415161718191A1B1C1D" \
+                             "1E1F202122232425262728292A2B2C" \
+                             "2D2E2F303132333435363738393A3B" \
+                             "3C3D3E3F404142434445464748494A" \
+                             "4B4C4D4E4F50515253545556575859" \
+                             "5A5B5C5D5E5F606162636465666768" \
+                             "696A6B6C6D6E6F7071727374757677" \
+                             "78797A7B7C7D7E7F80818283848586" \
+                             "8788898A8B8C8D8E8F909192939495" \
+                             "969798999A9B9C9D9E9FA0A1A2A3A4" \
+                             "A5A6A7A8A9AAABACADAEAFB0B1B2B3" \
+                             "B4B5B6B7B8B9BABBBCBDBEBFC0C1C2" \
+                             "C3C4C5C6C7C8C9CACBCCCDCECFD0D1" \
+                             "D2D3D4D5D6D7D8D9DADBDCDDDEDFE0" \
+                             "E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" \
+                             "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFE" \
+                             "FF", bin);
+  }
+  if (1)
+  {
+    static const uint8_t bin[3] =
+    {0x1, 0x2, 0x3};
+    r += expect_decoded_arr ("010203", bin);
+  }
+  if (1)
+  {
+    static const uint8_t bin[3] =
+    {0x1, 0x2, 0x3};
+    r += expect_decoded_arr ("10203", bin);
+  }
+  if (1)
+  {
+    static const uint8_t bin[1] =
+    {0x1};
+    r += expect_decoded_arr ("01", bin);
+  }
+  if (1)
+  {
+    static const uint8_t bin[1] =
+    {0x1};
+    r += expect_decoded_arr ("1", bin);
+  }
+
+  return r;
+}
+
+
+/* return zero if succeed, number of failures otherwise */
+static unsigned int
+expect_failed_n (const char *const hex, const size_t hex_len,
+                 const unsigned int line_num)
+{
+  static const char fill_chr = '#';
+  static char buf[TEST_BIN_MAX_SIZE];
+  size_t res_size;
+  unsigned int ret;
+
+  mhd_assert (NULL != hex);
+  mhd_assert (TEST_BIN_MAX_SIZE > hex_len + 1);
+
+  ret = 0;
+
+  /* check MHD_hex_to_bin() */
+  if (1)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_hex_to_bin (hex, hex_len, buf);
+    if (res_size != 0)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_hex_to_bin ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_hex_to_bin (\"%s\", %u, "
+               "->\"%s\") -> %u\n",
+               n_prnt (hex, hex_len), (unsigned) hex_len,
+               n_prnt (buf, res_size),
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, "
+               "->(not defined)) -> 0\n",
+               n_prnt (hex, hex_len), (unsigned) hex_len);
+    }
+  }
+
+  if (0 != ret)
+  {
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  return ret;
+}
+
+
+#define expect_failed(h) \
+        expect_failed_n(h,MHD_STATICSTR_LEN_(h), \
+                         __LINE__)
+
+
+static unsigned int
+check_broken_str (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_failed ("abcx");
+  r += expect_failed ("X");
+  r += expect_failed ("!");
+  r += expect_failed ("01z");
+  r += expect_failed ("0z");
+  r += expect_failed ("00z");
+  r += expect_failed ("000Y");
+
+  return r;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_decode_bin ();
+  errcount += check_broken_str ();
+  if (0 == errcount)
+    printf ("All tests have been passed without errors.\n");
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_str_pct.c b/src/microhttpd/test_str_pct.c
new file mode 100644
index 0000000..8c3375c
--- /dev/null
+++ b/src/microhttpd/test_str_pct.c
@@ -0,0 +1,1060 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_pct.c
+ * @brief  Unit tests for percent (URL) encoded strings processing
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */
+static size_t buf_idx = 0;
+
+/* print non-printable chars as char codes */
+static char *
+n_prnt (const char *str, size_t len)
+{
+  static char *buf;  /* should be enough for testing */
+  static const size_t buf_size = sizeof(tmp_bufs[0]);
+  size_t r_pos = 0;
+  size_t w_pos = 0;
+  if (++buf_idx >= (sizeof(tmp_bufs) / sizeof(tmp_bufs[0])))
+    buf_idx = 0;
+  buf = tmp_bufs[buf_idx];
+
+  while (len > r_pos && w_pos + 1 < buf_size)
+  {
+    const unsigned char c = (unsigned char) str[r_pos];
+    if ((c == '\\') || (c == '"') )
+    {
+      if (w_pos + 2 >= buf_size)
+        break;
+      buf[w_pos++] = '\\';
+      buf[w_pos++] = (char) c;
+    }
+    else if ((c >= 0x20) && (c <= 0x7E) )
+      buf[w_pos++] = (char) c;
+    else
+    {
+      if (w_pos + 4 >= buf_size)
+        break;
+      if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned
+                                                                int) c) != 4)
+        break;
+      w_pos += 4;
+    }
+    r_pos++;
+  }
+
+  if (len != r_pos)
+  {   /* not full string is printed */
+      /* enough space for "..." ? */
+    if (w_pos + 3 > buf_size)
+      w_pos = buf_size - 4;
+    buf[w_pos++] = '.';
+    buf[w_pos++] = '.';
+    buf[w_pos++] = '.';
+  }
+  buf[w_pos] = 0;
+  return buf;
+}
+
+
+#define TEST_BIN_MAX_SIZE 1024
+
+/* return zero if succeed, number of failures otherwise */
+static unsigned int
+expect_decoded_n (const char *const encoded, const size_t encoded_len,
+                  const char *const decoded, const size_t decoded_size,
+                  const unsigned int line_num)
+{
+  static const char fill_chr = '#';
+  static char buf[TEST_BIN_MAX_SIZE];
+  size_t res_size;
+  unsigned int ret;
+
+  mhd_assert (NULL != encoded);
+  mhd_assert (NULL != decoded);
+  mhd_assert (TEST_BIN_MAX_SIZE > decoded_size + 1);
+  mhd_assert (TEST_BIN_MAX_SIZE > encoded_len + 1);
+  mhd_assert (encoded_len >= decoded_size);
+
+  ret = 0;
+
+  /* check MHD_str_pct_decode_strict_n_() with small out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf,
+                                             decoded_size + 1);
+    if (res_size != decoded_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if (fill_chr != buf[res_size])
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+                 "A char written outside the buffer:\n");
+      }
+      else
+      {
+        memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+        res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf,
+                                                 decoded_size);
+        if (res_size != decoded_size)
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+                   "Wrong returned value:\n");
+        }
+      }
+      if ((res_size == decoded_size) && (0 != decoded_size) &&
+          (0 != memcmp (buf, decoded, decoded_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->\"%s\", %u) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) decoded_size,
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->\"%s\", %u) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (decoded, decoded_size), (unsigned) decoded_size,
+               (unsigned) decoded_size);
+    }
+  }
+
+  /* check MHD_str_pct_decode_strict_n_() with large out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf,
+                                             encoded_len + 1);
+    if (res_size != decoded_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if (fill_chr != buf[res_size])
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+                 "A char written outside the buffer:\n");
+      }
+      if ((res_size == decoded_size) && (0 != decoded_size) &&
+          (0 != memcmp (buf, decoded, decoded_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->\"%s\", %u) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) (encoded_len + 1),
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->\"%s\", %u) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1),
+               (unsigned) decoded_size);
+    }
+  }
+
+  /* check MHD_str_pct_decode_lenient_n_() with small out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+    bool is_broken = true;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf,
+                                              decoded_size + 1, &is_broken);
+    if (res_size != decoded_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if (fill_chr != buf[res_size])
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "A char written outside the buffer:\n");
+      }
+      else
+      {
+        is_broken = true;
+        memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+        res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf,
+                                                  decoded_size, &is_broken);
+        if (res_size != decoded_size)
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                   "Wrong returned value:\n");
+        }
+      }
+      if (is_broken)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong 'broken_encoding' result:\n");
+      }
+      if ((res_size == decoded_size) && (0 != decoded_size) &&
+          (0 != memcmp (buf, decoded, decoded_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->%s) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) decoded_size,
+               is_broken ? "true" : "false",
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->false) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (decoded, decoded_size), (unsigned) decoded_size,
+               (unsigned) decoded_size);
+    }
+  }
+
+  /* check MHD_str_pct_decode_lenient_n_() with large out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+    bool is_broken = true;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf,
+                                              encoded_len + 1, &is_broken);
+    if (res_size != decoded_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if (fill_chr != buf[res_size])
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "A char written outside the buffer:\n");
+      }
+      if (is_broken)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong 'broken_encoding' result:\n");
+      }
+      if ((res_size == decoded_size) && (0 != decoded_size) &&
+          (0 != memcmp (buf, decoded, decoded_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->%s) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) (encoded_len + 1),
+               is_broken ? "true" : "false",
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->false) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1),
+               (unsigned) decoded_size);
+    }
+  }
+
+  if (strlen (encoded) == encoded_len)
+  {
+    /* check MHD_str_pct_decode_in_place_strict_() */
+    if (1)
+    {
+      unsigned int check_res = 0;
+
+      memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+      memcpy (buf, encoded, encoded_len);
+      buf[encoded_len] = 0;
+      res_size = MHD_str_pct_decode_in_place_strict_ (buf);
+      if (res_size != decoded_size)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: "
+                 "Wrong returned value:\n");
+      }
+      else
+      {
+        if (0 != buf[res_size])
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: "
+                   "The result is not zero-terminated:\n");
+        }
+        if (((res_size + 1) < encoded_len) ?
+            (encoded[res_size + 1] != buf[res_size + 1]) :
+            (fill_chr != buf[res_size + 1]))
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: "
+                   "A char written outside the buffer:\n");
+        }
+        if ((res_size == decoded_size) && (0 != decoded_size) &&
+            (0 != memcmp (buf, decoded, decoded_size)))
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: "
+                   "Wrong output string:\n");
+        }
+      }
+      if (0 != check_res)
+      {
+        ret++;
+        fprintf (stderr,
+                 "\tRESULT  : MHD_str_pct_decode_in_place_strict_ (\"%s\" "
+                 "-> \"%s\") -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (buf, res_size),
+                 (unsigned) res_size);
+        fprintf (stderr,
+                 "\tEXPECTED: MHD_str_pct_decode_in_place_strict_ (\"%s\" "
+                 "-> \"%s\") -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (decoded, decoded_size),
+                 (unsigned) decoded_size);
+      }
+    }
+
+    /* check MHD_str_pct_decode_in_place_lenient_() */
+    if (1)
+    {
+      unsigned int check_res = 0;
+      bool is_broken = true;
+
+      memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+      memcpy (buf, encoded, encoded_len);
+      buf[encoded_len] = 0;
+      res_size = MHD_str_pct_decode_in_place_lenient_ (buf, &is_broken);
+      if (res_size != decoded_size)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                 "Wrong returned value:\n");
+      }
+      else
+      {
+        if (0 != buf[res_size])
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "The result is not zero-terminated:\n");
+        }
+        if (((res_size + 1) < encoded_len) ?
+            (encoded[res_size + 1] != buf[res_size + 1]) :
+            (fill_chr != buf[res_size + 1]))
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "A char written outside the buffer:\n");
+        }
+        if (is_broken)
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "Wrong 'broken_encoding' result:\n");
+        }
+        if ((res_size == decoded_size) && (0 != decoded_size) &&
+            (0 != memcmp (buf, decoded, decoded_size)))
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "Wrong output string:\n");
+        }
+      }
+      if (0 != check_res)
+      {
+        ret++;
+        fprintf (stderr,
+                 "\tRESULT  : MHD_str_pct_decode_in_place_lenient_ (\"%s\" "
+                 "-> \"%s\", ->%s) -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (buf, res_size),
+                 is_broken ? "true" : "false",
+                 (unsigned) res_size);
+        fprintf (stderr,
+                 "\tEXPECTED: MHD_str_pct_decode_in_place_lenient_ (\"%s\" "
+                 "-> \"%s\", ->false) -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (decoded, decoded_size),
+                 (unsigned) decoded_size);
+      }
+    }
+  }
+
+  if (0 != ret)
+  {
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  return ret;
+}
+
+
+#define expect_decoded(e,d) \
+        expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\
+                         d,MHD_STATICSTR_LEN_(d), \
+                         __LINE__)
+
+static unsigned int
+check_decode_str (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_decoded ("", "");
+
+  /* Base sequences without percent symbol */
+  r += expect_decoded ("aaa", "aaa");
+  r += expect_decoded ("bbb", "bbb");
+  r += expect_decoded ("ccc", "ccc");
+  r += expect_decoded ("ddd", "ddd");
+  r += expect_decoded ("lll", "lll");
+  r += expect_decoded ("mmm", "mmm");
+  r += expect_decoded ("nnn", "nnn");
+  r += expect_decoded ("ooo", "ooo");
+  r += expect_decoded ("www", "www");
+  r += expect_decoded ("xxx", "xxx");
+  r += expect_decoded ("yyy", "yyy");
+  r += expect_decoded ("zzz", "zzz");
+  r += expect_decoded ("AAA", "AAA");
+  r += expect_decoded ("GGG", "GGG");
+  r += expect_decoded ("MMM", "MMM");
+  r += expect_decoded ("TTT", "TTT");
+  r += expect_decoded ("ZZZ", "ZZZ");
+  r += expect_decoded ("012", "012");
+  r += expect_decoded ("345", "345");
+  r += expect_decoded ("678", "678");
+  r += expect_decoded ("901", "901");
+  r += expect_decoded ("aaaaaa", "aaaaaa");
+  r += expect_decoded ("bbbbbb", "bbbbbb");
+  r += expect_decoded ("cccccc", "cccccc");
+  r += expect_decoded ("dddddd", "dddddd");
+  r += expect_decoded ("llllll", "llllll");
+  r += expect_decoded ("mmmmmm", "mmmmmm");
+  r += expect_decoded ("nnnnnn", "nnnnnn");
+  r += expect_decoded ("oooooo", "oooooo");
+  r += expect_decoded ("wwwwww", "wwwwww");
+  r += expect_decoded ("xxxxxx", "xxxxxx");
+  r += expect_decoded ("yyyyyy", "yyyyyy");
+  r += expect_decoded ("zzzzzz", "zzzzzz");
+  r += expect_decoded ("AAAAAA", "AAAAAA");
+  r += expect_decoded ("GGGGGG", "GGGGGG");
+  r += expect_decoded ("MMMMMM", "MMMMMM");
+  r += expect_decoded ("TTTTTT", "TTTTTT");
+  r += expect_decoded ("ZZZZZZ", "ZZZZZZ");
+  r += expect_decoded ("012012", "012012");
+  r += expect_decoded ("345345", "345345");
+  r += expect_decoded ("678678", "678678");
+  r += expect_decoded ("901901", "901901");
+  r += expect_decoded ("a", "a");
+  r += expect_decoded ("bc", "bc");
+  r += expect_decoded ("DEFG", "DEFG");
+  r += expect_decoded ("123t", "123t");
+  r += expect_decoded ("12345", "12345");
+  r += expect_decoded ("TestStr", "TestStr");
+  r += expect_decoded ("Teststring", "Teststring");
+  r += expect_decoded ("Teststring.", "Teststring.");
+  r += expect_decoded ("Longerstring", "Longerstring");
+  r += expect_decoded ("Longerstring.", "Longerstring.");
+  r += expect_decoded ("Longerstring2.", "Longerstring2.");
+
+  /* Simple percent-encoded strings */
+  r += expect_decoded ("Test%20string", "Test string");
+  r += expect_decoded ("Test%3Fstring.", "Test?string.");
+  r += expect_decoded ("100%25", "100%");
+  r += expect_decoded ("a%2C%20b%3Dc%26e%3Dg", "a, b=c&e=g");
+  r += expect_decoded ("%20%21%23%24%25%26%27%28%29%2A%2B%2C"
+                       "%2F%3A%3B%3D%3F%40%5B%5D%09",
+                       " !#$%&'()*+,/:;=?@[]\t");
+
+  return r;
+}
+
+
+#define expect_decoded_arr(e,a) \
+        expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\
+                         (const char *)a,(sizeof(a)/sizeof(a[0])), \
+                         __LINE__)
+
+static unsigned int
+check_decode_bin (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe,
+     0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
+     0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26,
+     0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
+     0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+     0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+     0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
+     0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
+     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
+     0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+     0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86,
+     0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92,
+     0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e,
+     0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
+     0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+     0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
+     0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+     0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+     0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
+     0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2,
+     0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
+     0xff };
+    /* The lower case */
+    r += expect_decoded_arr ("%00%01%02%03%04%05%06%07%08%09%0a%0b%0c%0d%0e" \
+                             "%0f%10%11%12%13%14%15%16%17%18%19%1a%1b%1c%1d" \
+                             "%1e%1f%20%21%22%23%24%25%26%27%28%29%2a%2b%2c" \
+                             "%2d%2e%2f%30%31%32%33%34%35%36%37%38%39%3a%3b" \
+                             "%3c%3d%3e%3f%40%41%42%43%44%45%46%47%48%49%4a" \
+                             "%4b%4c%4d%4e%4f%50%51%52%53%54%55%56%57%58%59" \
+                             "%5a%5b%5c%5d%5e%5f%60%61%62%63%64%65%66%67%68" \
+                             "%69%6a%6b%6c%6d%6e%6f%70%71%72%73%74%75%76%77" \
+                             "%78%79%7a%7b%7c%7d%7e%7f%80%81%82%83%84%85%86" \
+                             "%87%88%89%8a%8b%8c%8d%8e%8f%90%91%92%93%94%95" \
+                             "%96%97%98%99%9a%9b%9c%9d%9e%9f%a0%a1%a2%a3%a4" \
+                             "%a5%a6%a7%a8%a9%aa%ab%ac%ad%ae%af%b0%b1%b2%b3" \
+                             "%b4%b5%b6%b7%b8%b9%ba%bb%bc%bd%be%bf%c0%c1%c2" \
+                             "%c3%c4%c5%c6%c7%c8%c9%ca%cb%cc%cd%ce%cf%d0%d1" \
+                             "%d2%d3%d4%d5%d6%d7%d8%d9%da%db%dc%dd%de%df%e0" \
+                             "%e1%e2%e3%e4%e5%e6%e7%e8%e9%ea%eb%ec%ed%ee%ef" \
+                             "%f0%f1%f2%f3%f4%f5%f6%f7%f8%f9%fa%fb%fc%fd%fe" \
+                             "%ff", bin);
+  }
+
+  if (1)
+  {
+    static const uint8_t bin[256] =
+    {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe,
+     0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
+     0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26,
+     0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
+     0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+     0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+     0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56,
+     0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
+     0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
+     0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+     0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86,
+     0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92,
+     0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e,
+     0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
+     0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
+     0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
+     0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+     0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
+     0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
+     0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2,
+     0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
+     0xff };
+    /* The upper case */
+    r += expect_decoded_arr ("%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E" \
+                             "%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D" \
+                             "%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C" \
+                             "%2D%2E%2F%30%31%32%33%34%35%36%37%38%39%3A%3B" \
+                             "%3C%3D%3E%3F%40%41%42%43%44%45%46%47%48%49%4A" \
+                             "%4B%4C%4D%4E%4F%50%51%52%53%54%55%56%57%58%59" \
+                             "%5A%5B%5C%5D%5E%5F%60%61%62%63%64%65%66%67%68" \
+                             "%69%6A%6B%6C%6D%6E%6F%70%71%72%73%74%75%76%77" \
+                             "%78%79%7A%7B%7C%7D%7E%7F%80%81%82%83%84%85%86" \
+                             "%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95" \
+                             "%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4" \
+                             "%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3" \
+                             "%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2" \
+                             "%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1" \
+                             "%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0" \
+                             "%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF" \
+                             "%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE" \
+                             "%FF", bin);
+  }
+
+  return r;
+}
+
+
+/* return zero if succeed, number of failures otherwise */
+static unsigned int
+expect_decoded_bad_n (const char *const encoded, const size_t encoded_len,
+                      const char *const decoded, const size_t decoded_size,
+                      const unsigned int line_num)
+{
+  static const char fill_chr = '#';
+  static char buf[TEST_BIN_MAX_SIZE];
+  size_t res_size;
+  unsigned int ret;
+
+  mhd_assert (NULL != encoded);
+  mhd_assert (NULL != decoded);
+  mhd_assert (TEST_BIN_MAX_SIZE > decoded_size + 1);
+  mhd_assert (TEST_BIN_MAX_SIZE > encoded_len + 1);
+  mhd_assert (encoded_len >= decoded_size);
+
+  ret = 0;
+
+  /* check MHD_str_pct_decode_strict_n_() with small out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf,
+                                             decoded_size);
+    if (res_size != 0)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->\"%s\", %u) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) decoded_size,
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->(not defined), %u) -> 0\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               (unsigned) decoded_size);
+    }
+  }
+
+  /* check MHD_str_pct_decode_strict_n_() with large out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf,
+                                             encoded_len + 1);
+    if (res_size != 0)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_strict_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->\"%s\", %u) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) (encoded_len + 1),
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, "
+               "->(not defined), %u) -> 0\n",
+               n_prnt (encoded, encoded_len), (unsigned) (encoded_len + 1),
+               (unsigned) decoded_size);
+    }
+  }
+
+  /* check MHD_str_pct_decode_lenient_n_() with small out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+    bool is_broken = false;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf,
+                                              decoded_size + 1, &is_broken);
+    if (res_size != decoded_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if (fill_chr != buf[res_size])
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "A char written outside the buffer:\n");
+      }
+      else
+      {
+        is_broken = false;
+        memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+        res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf,
+                                                  decoded_size, &is_broken);
+        if (res_size != decoded_size)
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                   "Wrong returned value:\n");
+        }
+      }
+      if (! is_broken)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong 'broken_encoding' result:\n");
+      }
+      if ((res_size == decoded_size) && (0 != decoded_size) &&
+          (0 != memcmp (buf, decoded, decoded_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->%s) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) decoded_size,
+               is_broken ? "true" : "false",
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->true) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (decoded, decoded_size), (unsigned) decoded_size,
+               (unsigned) decoded_size);
+    }
+  }
+
+  /* check MHD_str_pct_decode_lenient_n_() with large out buffer */
+  if (1)
+  {
+    unsigned int check_res = 0;
+    bool is_broken = false;
+
+    memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+    res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf,
+                                              encoded_len + 1, &is_broken);
+    if (res_size != decoded_size)
+    {
+      check_res = 1;
+      fprintf (stderr,
+               "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+               "Wrong returned value:\n");
+    }
+    else
+    {
+      if (fill_chr != buf[res_size])
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "A char written outside the buffer:\n");
+      }
+      if (! is_broken)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong 'broken_encoding' result:\n");
+      }
+      if ((res_size == decoded_size) && (0 != decoded_size) &&
+          (0 != memcmp (buf, decoded, decoded_size)))
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_lenient_n_ ()' FAILED: "
+                 "Wrong output string:\n");
+      }
+    }
+    if (0 != check_res)
+    {
+      ret++;
+      fprintf (stderr,
+               "\tRESULT  : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->%s) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (buf, res_size), (unsigned) (encoded_len + 1),
+               is_broken ? "true" : "false",
+               (unsigned) res_size);
+      fprintf (stderr,
+               "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, "
+               "->\"%s\", %u, ->true) -> %u\n",
+               n_prnt (encoded, encoded_len), (unsigned) encoded_len,
+               n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1),
+               (unsigned) decoded_size);
+    }
+  }
+
+  if (strlen (encoded) == encoded_len)
+  {
+    /* check MHD_str_pct_decode_in_place_strict_() */
+    if (1)
+    {
+      unsigned int check_res = 0;
+
+      memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+      memcpy (buf, encoded, encoded_len);
+      buf[encoded_len] = 0;
+      res_size = MHD_str_pct_decode_in_place_strict_ (buf);
+      if (res_size != 0)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: "
+                 "Wrong returned value:\n");
+      }
+      if (0 != check_res)
+      {
+        ret++;
+        fprintf (stderr,
+                 "\tRESULT  : MHD_str_pct_decode_in_place_strict_ (\"%s\" "
+                 "-> \"%s\") -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (buf, res_size),
+                 (unsigned) res_size);
+        fprintf (stderr,
+                 "\tEXPECTED: MHD_str_pct_decode_in_place_strict_ (\"%s\" "
+                 "-> (not defined)) -> 0\n",
+                 n_prnt (encoded, encoded_len));
+      }
+    }
+
+    /* check MHD_str_pct_decode_in_place_lenient_() */
+    if (1)
+    {
+      unsigned int check_res = 0;
+      bool is_broken = false;
+
+      memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */
+      memcpy (buf, encoded, encoded_len);
+      buf[encoded_len] = 0;
+      res_size = MHD_str_pct_decode_in_place_lenient_ (buf, &is_broken);
+      if (res_size != decoded_size)
+      {
+        check_res = 1;
+        fprintf (stderr,
+                 "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                 "Wrong returned value:\n");
+      }
+      else
+      {
+        if (0 != buf[res_size])
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "The result is not zero-terminated:\n");
+        }
+        if (((res_size + 1) < encoded_len) ?
+            (encoded[res_size + 1] != buf[res_size + 1]) :
+            (fill_chr != buf[res_size + 1]))
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "A char written outside the buffer:\n");
+        }
+        if (! is_broken)
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "Wrong 'broken_encoding' result:\n");
+        }
+        if ((res_size == decoded_size) && (0 != decoded_size) &&
+            (0 != memcmp (buf, decoded, decoded_size)))
+        {
+          check_res = 1;
+          fprintf (stderr,
+                   "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: "
+                   "Wrong output string:\n");
+        }
+      }
+      if (0 != check_res)
+      {
+        ret++;
+        fprintf (stderr,
+                 "\tRESULT  : MHD_str_pct_decode_in_place_lenient_ (\"%s\" "
+                 "-> \"%s\", ->%s) -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (buf, res_size),
+                 is_broken ? "true" : "false",
+                 (unsigned) res_size);
+        fprintf (stderr,
+                 "\tEXPECTED: MHD_str_pct_decode_in_place_lenient_ (\"%s\" "
+                 "-> \"%s\", ->true) -> %u\n",
+                 n_prnt (encoded, encoded_len),
+                 n_prnt (decoded, decoded_size),
+                 (unsigned) decoded_size);
+      }
+    }
+  }
+
+  if (0 != ret)
+  {
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+  return ret;
+}
+
+
+#define expect_decoded_bad(e,d) \
+        expect_decoded_bad_n(e,MHD_STATICSTR_LEN_(e),\
+                             d,MHD_STATICSTR_LEN_(d), \
+                             __LINE__)
+
+static unsigned int
+check_decode_bad_str (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_decoded_bad ("50%/50%", "50%/50%");
+  r += expect_decoded_bad ("This is 100% incorrect.",
+                           "This is 100% incorrect.");
+  r += expect_decoded_bad ("Some %%", "Some %%");
+  r += expect_decoded_bad ("1 %", "1 %");
+  r += expect_decoded_bad ("%", "%");
+  r += expect_decoded_bad ("%a", "%a");
+  r += expect_decoded_bad ("%0", "%0");
+  r += expect_decoded_bad ("%0x", "%0x");
+  r += expect_decoded_bad ("%FX", "%FX");
+  r += expect_decoded_bad ("Valid%20and%2invalid", "Valid and%2invalid");
+
+  return r;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_decode_str ();
+  errcount += check_decode_bin ();
+  errcount += check_decode_bad_str ();
+  if (0 == errcount)
+    printf ("All tests have been passed without errors.\n");
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_str_quote.c b/src/microhttpd/test_str_quote.c
new file mode 100644
index 0000000..1ad6697
--- /dev/null
+++ b/src/microhttpd/test_str_quote.c
@@ -0,0 +1,798 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2022 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_quote.c
+ * @brief  Unit tests for quoted strings processing
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+#define TEST_STR_MAX_LEN 1024
+
+/* return zero if succeed, non-zero otherwise */
+static unsigned int
+expect_result_unquote_n (const char *const quoted, const size_t quoted_len,
+                         const char *const unquoted, const size_t unquoted_len,
+                         const unsigned int line_num)
+{
+  static char buf[TEST_STR_MAX_LEN];
+  size_t res_len;
+  unsigned int ret1;
+  unsigned int ret2;
+  unsigned int ret3;
+  unsigned int ret4;
+
+  mhd_assert (NULL != quoted);
+  mhd_assert (NULL != unquoted);
+  mhd_assert (TEST_STR_MAX_LEN > quoted_len);
+  mhd_assert (quoted_len >= unquoted_len);
+
+  /* First check: MHD_str_unquote () */
+  ret1 = 0;
+  memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */
+  res_len = MHD_str_unquote (quoted, quoted_len, buf);
+
+  if (res_len != unquoted_len)
+  {
+    ret1 = 1;
+    fprintf (stderr,
+             "'MHD_str_unquote ()' FAILED: Wrong result size:\n");
+  }
+  else if ((0 != unquoted_len) && (0 != memcmp (buf, unquoted, unquoted_len)))
+  {
+    ret1 = 1;
+    fprintf (stderr,
+             "'MHD_str_unquote ()' FAILED: Wrong result string:\n");
+  }
+  if (0 != ret1)
+  {
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_unquote('%.*s', %u, ->'%.*s') -> %u\n"
+             "\tEXPECTED: MHD_str_unquote('%.*s', %u, ->'%.*s') -> %u\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) res_len, buf, (unsigned) res_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+
+  /* Second check: MHD_str_equal_quoted_bin_n () */
+  ret2 = 0;
+  if (! MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret2 = 1;
+  }
+
+  /* Third check: MHD_str_equal_caseless_quoted_bin_n () */
+  ret3 = 0;
+  if (! MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted,
+                                             unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret3 = 1;
+  }
+
+  /* Fourth check: MHD_str_unquote () */
+  ret4 = 0;
+  memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */
+  res_len = MHD_str_quote (unquoted, unquoted_len, buf, quoted_len);
+  if (res_len != quoted_len)
+  {
+    ret4 = 1;
+    fprintf (stderr,
+             "'MHD_str_quote ()' FAILED: Wrong result size:\n");
+  }
+  else if ((0 != quoted_len) && (0 != memcmp (buf, quoted, quoted_len)))
+  {
+    ret4 = 1;
+    fprintf (stderr,
+             "'MHD_str_quote ()' FAILED: Wrong result string:\n");
+  }
+  if (0 != ret4)
+  {
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n"
+             "\tEXPECTED: MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n",
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) res_len, buf, (unsigned) quoted_len, (unsigned) res_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+
+  return ret1 + ret2 + ret3 + ret4;
+}
+
+
+#define expect_result_unquote(q,u) \
+    expect_result_unquote_n(q,MHD_STATICSTR_LEN_(q),\
+                            u,MHD_STATICSTR_LEN_(u),__LINE__)
+
+
+static unsigned int
+check_match (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_result_unquote ("", "");
+  r += expect_result_unquote ("a", "a");
+  r += expect_result_unquote ("abc", "abc");
+  r += expect_result_unquote ("abcdef", "abcdef");
+  r += expect_result_unquote ("a\0" "bc", "a\0" "bc");
+  r += expect_result_unquote ("abc\\\"", "abc\"");
+  r += expect_result_unquote ("\\\"", "\"");
+  r += expect_result_unquote ("\\\"abc", "\"abc");
+  r += expect_result_unquote ("abc\\\\", "abc\\");
+  r += expect_result_unquote ("\\\\", "\\");
+  r += expect_result_unquote ("\\\\abc", "\\abc");
+  r += expect_result_unquote ("123\\\\\\\\\\\\\\\\", "123\\\\\\\\");
+  r += expect_result_unquote ("\\\\\\\\\\\\\\\\", "\\\\\\\\");
+  r += expect_result_unquote ("\\\\\\\\\\\\\\\\123", "\\\\\\\\123");
+  r += expect_result_unquote ("\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"" \
+                              "\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"", \
+                              "\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"");
+
+  return r;
+}
+
+
+/* return zero if succeed, non-zero otherwise */
+static unsigned int
+expect_result_quote_failed_n (const char *const unquoted,
+                              const size_t unquoted_len,
+                              const size_t buf_size,
+                              const unsigned int line_num)
+{
+  static char buf[TEST_STR_MAX_LEN];
+  size_t res_len;
+  unsigned int ret4;
+
+  mhd_assert (TEST_STR_MAX_LEN > buf_size);
+
+  /* The check: MHD_str_unquote () */
+  ret4 = 0;
+  memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */
+  res_len = MHD_str_quote (unquoted, unquoted_len, buf, buf_size);
+  if (0 != res_len)
+  {
+    ret4 = 1;
+    fprintf (stderr,
+             "'MHD_str_quote ()' FAILED: Wrong result size:\n");
+  }
+  if (0 != ret4)
+  {
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n"
+             "\tEXPECTED: MHD_str_quote('%.*s', %u, (not checked), %u) -> 0\n",
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) res_len, buf,
+             (unsigned) buf_size, (unsigned) res_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (unsigned) buf_size);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+
+  return ret4;
+}
+
+
+#define expect_result_quote_failed(q,s) \
+    expect_result_quote_failed_n(q,MHD_STATICSTR_LEN_(q),\
+                            s,__LINE__)
+
+
+static unsigned int
+check_quote_failed (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_result_quote_failed ("a", 0);
+  r += expect_result_quote_failed ("aa", 1);
+  r += expect_result_quote_failed ("abc\\", 4);
+  r += expect_result_quote_failed ("abc\"", 4);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 6);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 7);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 8);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 9);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 10);
+  r += expect_result_quote_failed ("abc\\\\\\\\", 9);
+  r += expect_result_quote_failed ("abc\\\\\\\\", 10);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 9);
+  r += expect_result_quote_failed ("abc\"\"\"\"", 10);
+  r += expect_result_quote_failed ("abc\"\\\"\\", 9);
+  r += expect_result_quote_failed ("abc\\\"\\\"", 10);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 6);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 7);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 8);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 9);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 10);
+  r += expect_result_quote_failed ("\\\\\\\\abc", 9);
+  r += expect_result_quote_failed ("\\\\\\\\abc", 10);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 9);
+  r += expect_result_quote_failed ("\"\"\"\"abc", 10);
+  r += expect_result_quote_failed ("\"\\\"\\abc", 9);
+  r += expect_result_quote_failed ("\\\"\\\"abc", 10);
+
+  return r;
+}
+
+
+/* return zero if succeed, one otherwise */
+static unsigned int
+expect_match_caseless_n (const char *const quoted, const size_t quoted_len,
+                         const char *const unquoted, const size_t unquoted_len,
+                         const unsigned int line_num)
+{
+  unsigned int ret3;
+
+  mhd_assert (NULL != quoted);
+  mhd_assert (NULL != unquoted);
+  mhd_assert (TEST_STR_MAX_LEN > quoted_len);
+
+  /* The check: MHD_str_equal_caseless_quoted_bin_n () */
+  ret3 = 0;
+  if (! MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted,
+                                             unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret3 = 1;
+  }
+
+  return ret3;
+}
+
+
+#define expect_match_caseless(q,u) \
+    expect_match_caseless_n(q,MHD_STATICSTR_LEN_(q),\
+                            u,MHD_STATICSTR_LEN_(u),__LINE__)
+
+static unsigned int
+check_match_caseless (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_match_caseless ("a", "A");
+  r += expect_match_caseless ("abC", "aBc");
+  r += expect_match_caseless ("AbCdeF", "aBCdEF");
+  r += expect_match_caseless ("a\0" "Bc", "a\0" "bC");
+  r += expect_match_caseless ("Abc\\\"", "abC\"");
+  r += expect_match_caseless ("\\\"", "\"");
+  r += expect_match_caseless ("\\\"aBc", "\"abc");
+  r += expect_match_caseless ("abc\\\\", "ABC\\");
+  r += expect_match_caseless ("\\\\", "\\");
+  r += expect_match_caseless ("\\\\ABC", "\\abc");
+  r += expect_match_caseless ("\\\\ZYX", "\\ZYX");
+  r += expect_match_caseless ("abc", "ABC");
+  r += expect_match_caseless ("ABCabc", "abcABC");
+  r += expect_match_caseless ("abcXYZ", "ABCxyz");
+  r += expect_match_caseless ("AbCdEfABCabc", "ABcdEFabcABC");
+  r += expect_match_caseless ("a\\\\bc", "A\\BC");
+  r += expect_match_caseless ("ABCa\\\\bc", "abcA\\BC");
+  r += expect_match_caseless ("abcXYZ\\\\", "ABCxyz\\");
+  r += expect_match_caseless ("\\\\AbCdEfABCabc", "\\ABcdEFabcABC");
+
+  return r;
+}
+
+
+/* return zero if succeed, one otherwise */
+static unsigned int
+expect_result_invalid_n (const char *const quoted, const size_t quoted_len,
+                         const unsigned int line_num)
+{
+  static char buf[TEST_STR_MAX_LEN];
+  size_t res_len;
+  unsigned int ret1;
+
+  mhd_assert (NULL != quoted);
+  mhd_assert (TEST_STR_MAX_LEN > quoted_len);
+
+  /* The check: MHD_str_unquote () */
+  ret1 = 0;
+  memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */
+  res_len = MHD_str_unquote (quoted, quoted_len, buf);
+
+  if (res_len != 0)
+  {
+    ret1 = 1;
+    fprintf (stderr,
+             "'MHD_str_unquote ()' FAILED: Wrong result size:\n");
+  }
+  if (0 != ret1)
+  {
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_unquote('%.*s', %u, (not checked)) -> %u\n"
+             "\tEXPECTED: MHD_str_unquote('%.*s', %u, (not checked)) -> 0\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (unsigned) res_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+  }
+
+  return ret1;
+}
+
+
+#define expect_result_invalid(q) \
+    expect_result_invalid_n(q,MHD_STATICSTR_LEN_(q),__LINE__)
+
+
+static unsigned int
+check_invalid (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_result_invalid ("\\");
+  r += expect_result_invalid ("\\\\\\");
+  r += expect_result_invalid ("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
+  r += expect_result_invalid ("xyz\\");
+  r += expect_result_invalid ("\\\"\\");
+  r += expect_result_invalid ("\\\"\\\"\\\"\\");
+
+  return r;
+}
+
+
+/* return zero if succeed, non-zero otherwise */
+static unsigned int
+expect_result_unmatch_n (const char *const quoted, const size_t quoted_len,
+                         const char *const unquoted,
+                         const size_t unquoted_len,
+                         const unsigned int line_num)
+{
+  unsigned int ret2;
+  unsigned int ret3;
+
+  mhd_assert (NULL != quoted);
+  mhd_assert (NULL != unquoted);
+
+  /* The check: MHD_str_equal_quoted_bin_n () */
+  ret2 = 0;
+  if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret2 = 1;
+  }
+
+  /* The check: MHD_str_equal_quoted_bin_n () */
+  ret3 = 0;
+  if (MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted,
+                                           unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret3 = 1;
+  }
+
+  return ret2 + ret3;
+}
+
+
+#define expect_result_unmatch(q,u) \
+    expect_result_unmatch_n(q,MHD_STATICSTR_LEN_(q),\
+                            u,MHD_STATICSTR_LEN_(u),__LINE__)
+
+
+static unsigned int
+check_unmatch (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  /* Matched sequence except invalid backslash at the end */
+  r += expect_result_unmatch ("\\", "");
+  r += expect_result_unmatch ("a\\", "a");
+  r += expect_result_unmatch ("abc\\", "abc");
+  r += expect_result_unmatch ("a\0" "bc\\", "a\0" "bc");
+  r += expect_result_unmatch ("abc\\\"\\", "abc\"");
+  r += expect_result_unmatch ("\\\"\\", "\"");
+  r += expect_result_unmatch ("\\\"abc\\", "\"abc");
+  r += expect_result_unmatch ("abc\\\\\\", "abc\\");
+  r += expect_result_unmatch ("\\\\\\", "\\");
+  r += expect_result_unmatch ("\\\\abc\\", "\\abc");
+  r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\", "123\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\", "\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\", "\\\\\\\\123");
+  /* Invalid backslash at the end and empty string */
+  r += expect_result_unmatch ("\\", "");
+  r += expect_result_unmatch ("a\\", "");
+  r += expect_result_unmatch ("abc\\", "");
+  r += expect_result_unmatch ("a\0" "bc\\", "");
+  r += expect_result_unmatch ("abc\\\"\\", "");
+  r += expect_result_unmatch ("\\\"\\", "");
+  r += expect_result_unmatch ("\\\"abc\\", "");
+  r += expect_result_unmatch ("abc\\\\\\", "");
+  r += expect_result_unmatch ("\\\\\\", "");
+  r += expect_result_unmatch ("\\\\abc\\", "");
+  r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\", "");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\", "");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\", "");
+  /* Difference at binary zero */
+  r += expect_result_unmatch ("\0", "");
+  r += expect_result_unmatch ("", "\0");
+  r += expect_result_unmatch ("a\0", "a");
+  r += expect_result_unmatch ("a", "a\0");
+  r += expect_result_unmatch ("abc\0", "abc");
+  r += expect_result_unmatch ("abc", "abc\0");
+  r += expect_result_unmatch ("a\0" "bc\0", "a\0" "bc");
+  r += expect_result_unmatch ("a\0" "bc", "a\0" "bc\0");
+  r += expect_result_unmatch ("abc\\\"\0", "abc\"");
+  r += expect_result_unmatch ("abc\\\"", "abc\"\0");
+  r += expect_result_unmatch ("\\\"\0", "\"");
+  r += expect_result_unmatch ("\\\"", "\"\0");
+  r += expect_result_unmatch ("\\\"abc\0", "\"abc");
+  r += expect_result_unmatch ("\\\"abc", "\"abc\0");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\0", "\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\0");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\0" "\\\\", "\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\0" "\\");
+  r += expect_result_unmatch ("\0" "abc", "abc");
+  r += expect_result_unmatch ("abc", "\0" "abc");
+  r += expect_result_unmatch ("\0" "abc", "0abc");
+  r += expect_result_unmatch ("0abc", "\0" "abc");
+  r += expect_result_unmatch ("xyz", "xy" "\0" "z");
+  r += expect_result_unmatch ("xy" "\0" "z", "xyz");
+  /* Difference after binary zero */
+  r += expect_result_unmatch ("abc\0" "1", "abc\0" "2");
+  r += expect_result_unmatch ("a\0" "bcx", "a\0" "bcy");
+  r += expect_result_unmatch ("\0" "abc\\\"2", "\0" "abc\"1");
+  r += expect_result_unmatch ("\0" "abc1\\\"", "\0" "abc2\"");
+  r += expect_result_unmatch ("\0" "\\\"c", "\0" "\"d");
+  r += expect_result_unmatch ("\\\"ab" "\0" "1c", "\"ab" "\0" "2c");
+  r += expect_result_unmatch ("a\0" "bcdef2", "a\0" "bcdef1");
+  r += expect_result_unmatch ("a\0" "bc2def", "a\0" "bc1def");
+  r += expect_result_unmatch ("a\0" "1bcdef", "a\0" "2bcdef");
+  r += expect_result_unmatch ("abcde\0" "f2", "abcde\0" "f1");
+  r += expect_result_unmatch ("123\\\\\\\\\\\\\0" "\\\\1", "123\\\\\\\0" "\\2");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\0" "1\\\\", "\\\\\\" "2\\");
+  /* One side is empty */
+  r += expect_result_unmatch ("abc", "");
+  r += expect_result_unmatch ("", "abc");
+  r += expect_result_unmatch ("1234567890", "");
+  r += expect_result_unmatch ("", "1234567890");
+  r += expect_result_unmatch ("abc\\\"", "");
+  r += expect_result_unmatch ("", "abc\"");
+  r += expect_result_unmatch ("\\\"", "");
+  r += expect_result_unmatch ("", "\"");
+  r += expect_result_unmatch ("\\\"abc", "");
+  r += expect_result_unmatch ("", "\"abc");
+  r += expect_result_unmatch ("abc\\\\", "");
+  r += expect_result_unmatch ("", "abc\\");
+  r += expect_result_unmatch ("\\\\", "");
+  r += expect_result_unmatch ("", "\\");
+  r += expect_result_unmatch ("\\\\abc", "");
+  r += expect_result_unmatch ("", "\\abc");
+  r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\", "");
+  r += expect_result_unmatch ("", "123\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "");
+  r += expect_result_unmatch ("", "\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123", "");
+  r += expect_result_unmatch ("", "\\\\\\\\123");
+  /* Various unmatched strings */
+  r += expect_result_unmatch ("a", "x");
+  r += expect_result_unmatch ("abc", "abcabc");
+  r += expect_result_unmatch ("abc", "abcabcabc");
+  r += expect_result_unmatch ("abc", "abcabcabcabc");
+  r += expect_result_unmatch ("ABCABC", "ABC");
+  r += expect_result_unmatch ("ABCABCABC", "ABC");
+  r += expect_result_unmatch ("ABCABCABCABC", "ABC");
+  r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\\\", "123\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\\\", "\\\\\\\\");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\\\", "\\\\\\\\123");
+  r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\\");
+
+  return r;
+}
+
+
+/* return zero if succeed, one otherwise */
+static unsigned int
+expect_result_case_unmatch_n (const char *const quoted,
+                              const size_t quoted_len,
+                              const char *const unquoted,
+                              const size_t unquoted_len,
+                              const unsigned int line_num)
+{
+  unsigned int ret2;
+
+  mhd_assert (NULL != quoted);
+  mhd_assert (NULL != unquoted);
+
+  /* THe check: MHD_str_equal_quoted_bin_n () */
+  ret2 = 0;
+  if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret2 = 1;
+  }
+
+  return ret2;
+}
+
+
+#define expect_result_case_unmatch(q,u) \
+    expect_result_case_unmatch_n(q,MHD_STATICSTR_LEN_(q),\
+                                 u,MHD_STATICSTR_LEN_(u),__LINE__)
+
+static unsigned int
+check_unmatch_case (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  r += expect_result_case_unmatch ("a", "A");
+  r += expect_result_case_unmatch ("abC", "aBc");
+  r += expect_result_case_unmatch ("AbCdeF", "aBCdEF");
+  r += expect_result_case_unmatch ("a\0" "Bc", "a\0" "bC");
+  r += expect_result_case_unmatch ("Abc\\\"", "abC\"");
+  r += expect_result_case_unmatch ("\\\"aBc", "\"abc");
+  r += expect_result_case_unmatch ("abc\\\\", "ABC\\");
+  r += expect_result_case_unmatch ("\\\\ABC", "\\abc");
+  r += expect_result_case_unmatch ("\\\\ZYX", "\\ZYx");
+  r += expect_result_case_unmatch ("abc", "ABC");
+  r += expect_result_case_unmatch ("ABCabc", "abcABC");
+  r += expect_result_case_unmatch ("abcXYZ", "ABCxyz");
+  r += expect_result_case_unmatch ("AbCdEfABCabc", "ABcdEFabcABC");
+  r += expect_result_case_unmatch ("a\\\\bc", "A\\BC");
+  r += expect_result_case_unmatch ("ABCa\\\\bc", "abcA\\BC");
+  r += expect_result_case_unmatch ("abcXYZ\\\\", "ABCxyz\\");
+  r += expect_result_case_unmatch ("\\\\AbCdEfABCabc", "\\ABcdEFabcABC");
+
+  return r;
+}
+
+
+/* return zero if succeed, one otherwise */
+static unsigned int
+expect_result_caseless_unmatch_n (const char *const quoted,
+                                  const size_t quoted_len,
+                                  const char *const unquoted,
+                                  const size_t unquoted_len,
+                                  const unsigned int line_num)
+{
+  unsigned int ret2;
+  unsigned int ret3;
+
+  mhd_assert (NULL != quoted);
+  mhd_assert (NULL != unquoted);
+
+  /* The check: MHD_str_equal_quoted_bin_n () */
+  ret2 = 0;
+  if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret2 = 1;
+  }
+
+  /* The check: MHD_str_equal_quoted_bin_n () */
+  ret3 = 0;
+  if (MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted,
+                                           unquoted_len))
+  {
+    fprintf (stderr,
+             "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n");
+    /* This does NOT print part of the string after binary zero */
+    fprintf (stderr,
+             "\tRESULT  : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> true\n"
+             "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, "
+             "'%.*s', %u) -> false\n",
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len,
+             (int) quoted_len, quoted, (unsigned) quoted_len,
+             (int) unquoted_len, unquoted, (unsigned) unquoted_len);
+    fprintf (stderr,
+             "The check is at line: %u\n\n", line_num);
+    ret3 = 1;
+  }
+
+  return ret2 + ret3;
+}
+
+
+#define expect_result_caseless_unmatch(q,u) \
+    expect_result_caseless_unmatch_n(q,MHD_STATICSTR_LEN_(q),\
+                                     u,MHD_STATICSTR_LEN_(u),__LINE__)
+
+
+static unsigned int
+check_unmatch_caseless (void)
+{
+  unsigned int r = 0; /**< The number of errors */
+
+  /* Matched sequence except invalid backslash at the end */
+  r += expect_result_caseless_unmatch ("a\\", "A");
+  r += expect_result_caseless_unmatch ("abC\\", "abc");
+  r += expect_result_caseless_unmatch ("a\0" "Bc\\", "a\0" "bc");
+  r += expect_result_caseless_unmatch ("abc\\\"\\", "ABC\"");
+  r += expect_result_caseless_unmatch ("\\\"\\", "\"");
+  r += expect_result_caseless_unmatch ("\\\"ABC\\", "\"abc");
+  r += expect_result_caseless_unmatch ("Abc\\\\\\", "abC\\");
+  r += expect_result_caseless_unmatch ("\\\\\\", "\\");
+  r += expect_result_caseless_unmatch ("\\\\aBc\\", "\\abC");
+  /* Difference at binary zero */
+  r += expect_result_caseless_unmatch ("a\0", "A");
+  r += expect_result_caseless_unmatch ("A", "a\0");
+  r += expect_result_caseless_unmatch ("abC\0", "abc");
+  r += expect_result_caseless_unmatch ("abc", "ABc\0");
+  r += expect_result_caseless_unmatch ("a\0" "bC\0", "a\0" "bc");
+  r += expect_result_caseless_unmatch ("a\0" "bc", "A\0" "bc\0");
+  r += expect_result_caseless_unmatch ("ABC\\\"\0", "abc\"");
+  r += expect_result_caseless_unmatch ("abc\\\"", "ABC\"\0");
+  r += expect_result_caseless_unmatch ("\\\"aBc\0", "\"abc");
+  r += expect_result_caseless_unmatch ("\\\"Abc", "\"abc\0");
+  r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\\0", "\\\\\\\\");
+  r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\0");
+  r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\0" "\\\\", "\\\\\\\\");
+  r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\0" "\\");
+  r += expect_result_caseless_unmatch ("\0" "aBc", "abc");
+  r += expect_result_caseless_unmatch ("abc", "\0" "abC");
+  r += expect_result_caseless_unmatch ("\0" "abc", "0abc");
+  r += expect_result_caseless_unmatch ("0abc", "\0" "aBc");
+  r += expect_result_caseless_unmatch ("xyZ", "xy" "\0" "z");
+  r += expect_result_caseless_unmatch ("Xy" "\0" "z", "xyz");
+  /* Difference after binary zero */
+  r += expect_result_caseless_unmatch ("abc\0" "1", "aBC\0" "2");
+  r += expect_result_caseless_unmatch ("a\0" "bcX", "a\0" "bcy");
+  r += expect_result_caseless_unmatch ("\0" "abc\\\"2", "\0" "Abc\"1");
+  r += expect_result_caseless_unmatch ("\0" "Abc1\\\"", "\0" "abc2\"");
+  r += expect_result_caseless_unmatch ("\0" "\\\"c", "\0" "\"d");
+  r += expect_result_caseless_unmatch ("\\\"ab" "\0" "1C", "\"ab" "\0" "2C");
+  r += expect_result_caseless_unmatch ("a\0" "BCDef2", "a\0" "bcdef1");
+  r += expect_result_caseless_unmatch ("a\0" "bc2def", "a\0" "BC1def");
+  r += expect_result_caseless_unmatch ("a\0" "1bcdeF", "a\0" "2bcdef");
+  r += expect_result_caseless_unmatch ("abcde\0" "f2", "ABCDE\0" "f1");
+  r += expect_result_caseless_unmatch ("\\\"ab" "\0" "XC", "\"ab" "\0" "yC");
+  r += expect_result_caseless_unmatch ("a\0" "BCDefY", "a\0" "bcdefx");
+  r += expect_result_caseless_unmatch ("a\0" "bczdef", "a\0" "BCXdef");
+  r += expect_result_caseless_unmatch ("a\0" "YbcdeF", "a\0" "zbcdef");
+  r += expect_result_caseless_unmatch ("abcde\0" "fy", "ABCDE\0" "fX");
+
+  return r;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  unsigned int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_match ();
+  errcount += check_quote_failed ();
+  errcount += check_match_caseless ();
+  errcount += check_invalid ();
+  errcount += check_unmatch ();
+  errcount += check_unmatch_case ();
+  errcount += check_unmatch_caseless ();
+  if (0 == errcount)
+    printf ("All tests were passed without errors.\n");
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_str_token.c b/src/microhttpd/test_str_token.c
new file mode 100644
index 0000000..fe7b111
--- /dev/null
+++ b/src/microhttpd/test_str_token.c
@@ -0,0 +1,128 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_token.c
+ * @brief  Unit tests for some mhd_str functions
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <stdio.h>
+#include "mhd_str.h"
+
+
+static int
+expect_found_n (const char *str, const char *token, size_t token_len)
+{
+  if (! MHD_str_has_token_caseless_ (str, token, token_len))
+  {
+    fprintf (stderr,
+             "MHD_str_has_token_caseless_() FAILED:\n\tMHD_str_has_token_caseless_(%s, %s, %lu) return false\n",
+             str, token, (unsigned long) token_len);
+    return 1;
+  }
+  return 0;
+}
+
+
+#define expect_found(s,t) expect_found_n ((s),(t),MHD_STATICSTR_LEN_ (t))
+
+static int
+expect_not_found_n (const char *str, const char *token, size_t token_len)
+{
+  if (MHD_str_has_token_caseless_ (str, token, token_len))
+  {
+    fprintf (stderr,
+             "MHD_str_has_token_caseless_() FAILED:\n\tMHD_str_has_token_caseless_(%s, %s, %lu) return true\n",
+             str, token, (unsigned long) token_len);
+    return 1;
+  }
+  return 0;
+}
+
+
+#define expect_not_found(s,t) expect_not_found_n ((s),(t),MHD_STATICSTR_LEN_ ( \
+                                                    t))
+
+static int
+check_match (void)
+{
+  int errcount = 0;
+  errcount += expect_found ("string", "string");
+  errcount += expect_found ("String", "string");
+  errcount += expect_found ("string", "String");
+  errcount += expect_found ("strinG", "String");
+  errcount += expect_found ("\t strinG", "String");
+  errcount += expect_found ("strinG\t ", "String");
+  errcount += expect_found (" \t tOkEn  ", "toKEN");
+  errcount += expect_found ("not token\t,  tOkEn  ", "toKEN");
+  errcount += expect_found ("not token,\t  tOkEn, more token", "toKEN");
+  errcount += expect_found ("not token,\t  tOkEn\t, more token", "toKEN");
+  errcount += expect_found (",,,,,,test,,,,", "TESt");
+  errcount += expect_found (",,,,,\t,test,,,,", "TESt");
+  errcount += expect_found (",,,,,,test, ,,,", "TESt");
+  errcount += expect_found (",,,,,, test,,,,", "TESt");
+  errcount += expect_found (",,,,,, test not,test,,", "TESt");
+  errcount += expect_found (",,,,,, test not,,test,,", "TESt");
+  errcount += expect_found (",,,,,, test not ,test,,", "TESt");
+  errcount += expect_found (",,,,,, test", "TESt");
+  errcount += expect_found (",,,,,, test      ", "TESt");
+  errcount += expect_found ("no test,,,,,, test      ", "TESt");
+  return errcount;
+}
+
+
+static int
+check_not_match (void)
+{
+  int errcount = 0;
+  errcount += expect_not_found ("strin", "string");
+  errcount += expect_not_found ("Stringer", "string");
+  errcount += expect_not_found ("sstring", "String");
+  errcount += expect_not_found ("string", "Strin");
+  errcount += expect_not_found ("\t( strinG", "String");
+  errcount += expect_not_found (")strinG\t ", "String");
+  errcount += expect_not_found (" \t tOkEn t ", "toKEN");
+  errcount += expect_not_found ("not token\t,  tOkEner  ", "toKEN");
+  errcount += expect_not_found ("not token,\t  tOkEns, more token", "toKEN");
+  errcount += expect_not_found ("not token,\t  tOkEns\t, more token", "toKEN");
+  errcount += expect_not_found (",,,,,,testing,,,,", "TESt");
+  errcount += expect_not_found (",,,,,\t,test,,,,", "TESting");
+  errcount += expect_not_found ("tests,,,,,,quest, ,,,", "TESt");
+  errcount += expect_not_found (",,,,,, testы,,,,", "TESt");
+  errcount += expect_not_found (",,,,,, test not,хtest,,", "TESt");
+  errcount += expect_not_found ("testing,,,,,, test not,,test2,,", "TESt");
+  errcount += expect_not_found (",testi,,,,, test not ,test,,", "TESting");
+  errcount += expect_not_found (",,,,,,2 test", "TESt");
+  errcount += expect_not_found (",,,,,,test test      ", "test");
+  errcount += expect_not_found ("no test,,,,,, test      test", "test");
+  return errcount;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_match ();
+  errcount += check_not_match ();
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_str_token_remove.c b/src/microhttpd/test_str_token_remove.c
new file mode 100644
index 0000000..3e9b61e
--- /dev/null
+++ b/src/microhttpd/test_str_token_remove.c
@@ -0,0 +1,249 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017-2021 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_token.c
+ * @brief  Unit tests for MHD_str_remove_token_caseless_() function
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+
+static int
+expect_result_n (const char *str, size_t str_len,
+                 const char *token, size_t token_len,
+                 const char *expected, size_t expected_len,
+                 const bool expected_removed)
+{
+  char buf_in[1024];
+  char buf_token[256];
+  char buf_out[1024];
+  size_t buf_len;
+
+  mhd_assert (sizeof(buf_in) > str_len + 2);
+  mhd_assert (sizeof(buf_token) > token_len + 2);
+  mhd_assert (sizeof(buf_out) > expected_len + 2);
+
+  memset (buf_in, '#', sizeof(buf_in));
+  memset (buf_token, '#', sizeof(buf_token));
+  memcpy (buf_in, str, str_len); /* Copy without zero-termination */
+  memcpy (buf_token, token, token_len); /* Copy without zero-termination */
+
+  for (buf_len = 0; buf_len <= expected_len + 3; ++buf_len)
+  {
+    bool res;
+    ssize_t result_len;
+    memset (buf_out, '$', sizeof(buf_out));
+
+    result_len = (ssize_t) buf_len;
+    mhd_assert (0 <= result_len);
+
+    res = MHD_str_remove_token_caseless_ (buf_in, str_len, buf_token, token_len,
+                                          buf_out, &result_len);
+    if (buf_len < expected_len)
+    { /* The result should not fit into the buffer */
+      if (res || (0 < result_len))
+      {
+        fprintf (stderr,
+                 "MHD_str_remove_token_caseless_() FAILED:\n"
+                 "\tMHD_str_remove_token_caseless_(\"%.*s\", %lu,"
+                 " \"%.*s\", %lu, buf, &(%ld->%ld)) returned %s\n",
+                 (int) str_len + 2, buf_in, (unsigned long) str_len,
+                 (int) token_len + 2, buf_token, (unsigned long) token_len,
+                 (long) buf_len, (long) result_len, res ? "true" : "false");
+        return 1;
+      }
+    }
+    else
+    { /* The result should fit into the buffer */
+      if ( (expected_removed != res) ||
+           (expected_len != (size_t) result_len) ||
+           ((0 != result_len) && (0 != memcmp (expected, buf_out,
+                                               (size_t) result_len))) ||
+           ('$' != buf_out[result_len]))
+      {
+        fprintf (stderr,
+                 "MHD_str_remove_token_caseless_() FAILED:\n"
+                 "\tMHD_str_remove_token_caseless_(\"%.*s\", %lu,"
+                 " \"%.*s\", %lu, \"%.*s\", &(%ld->%ld)) returned %s\n",
+                 (int) str_len + 2, buf_in, (unsigned long) str_len,
+                 (int) token_len + 2, buf_token, (unsigned long) token_len,
+                 (int) expected_len + 2, buf_out,
+                 (long) buf_len, (long) result_len,
+                 res ? "true" : "false");
+        return 1;
+      }
+    }
+  }
+  return 0;
+}
+
+
+#define expect_result(s,t,e,found) \
+  expect_result_n ((s),MHD_STATICSTR_LEN_ (s), \
+                   (t),MHD_STATICSTR_LEN_ (t), \
+                   (e),MHD_STATICSTR_LEN_ (e), found)
+
+static int
+check_result (void)
+{
+  int errcount = 0;
+  errcount += expect_result ("string", "string", "", true);
+  errcount += expect_result ("String", "string", "", true);
+  errcount += expect_result ("string", "String", "", true);
+  errcount += expect_result ("strinG", "String", "", true);
+  errcount += expect_result ("\t strinG", "String", "", true);
+  errcount += expect_result ("strinG\t ", "String", "", true);
+  errcount += expect_result (" \t tOkEn  ", "toKEN", "", true);
+  errcount += expect_result ("not token\t,  tOkEn  ", "toKEN", "not token",
+                             true);
+  errcount += expect_result ("not token,\t  tOkEn, more token", "toKEN",
+                             "not token, more token", true);
+  errcount += expect_result ("not token,\t  tOkEn\t, more token", "toKEN",
+                             "not token, more token", true);
+  errcount += expect_result (",,,,,,test,,,,", "TESt", "", true);
+  errcount += expect_result (",,,,,\t,test,,,,", "TESt", "", true);
+  errcount += expect_result (",,,,,,test, ,,,", "TESt", "", true);
+  errcount += expect_result (",,,,,, test,,,,", "TESt", "", true);
+  errcount += expect_result (",,,,,, test not,test,,", "TESt", "test not",
+                             true);
+  errcount += expect_result (",,,,,, test not,,test,,", "TESt", "test not",
+                             true);
+  errcount += expect_result (",,,,,, test not ,test,,", "TESt", "test not",
+                             true);
+  errcount += expect_result (",,,,,, test", "TESt", "", true);
+  errcount += expect_result (",,,,,, test      ", "TESt", "", true);
+  errcount += expect_result ("no test,,,,,, test      ", "TESt", "no test",
+                             true);
+  errcount += expect_result ("the-token,, the-token , the-token" \
+                             ",the-token ,the-token", "the-token", "", true);
+  errcount += expect_result (" the-token,, the-token , the-token," \
+                             "the-token ,the-token ", "the-token", "", true);
+  errcount += expect_result (" the-token ,, the-token , the-token," \
+                             "the-token , the-token ", "the-token", "", true);
+  errcount += expect_result ("the-token,a, the-token , the-token,b," \
+                             "the-token , c,the-token", "the-token", "a, b, c",
+                             true);
+  errcount += expect_result (" the-token, a, the-token , the-token, b," \
+                             "the-token ,c ,the-token ", "the-token",
+                             "a, b, c", true);
+  errcount += expect_result (" the-token , a , the-token , the-token, b ," \
+                             "the-token , c , the-token ", "the-token",
+                             "a, b, c",true);
+  errcount += expect_result ("the-token,aa, the-token , the-token,bb," \
+                             "the-token , cc,the-token", "the-token",
+                             "aa, bb, cc", true);
+  errcount += expect_result (" the-token, aa, the-token , the-token, bb," \
+                             "the-token ,cc ,the-token ", "the-token",
+                             "aa, bb, cc", true);
+  errcount += expect_result (" the-token , aa , the-token , the-token, bb ," \
+                             "the-token , cc , the-token ", "the-token",
+                             "aa, bb, cc", true);
+
+  errcount += expect_result ("strin", "string", "strin", false);
+  errcount += expect_result ("Stringer", "string", "Stringer", false);
+  errcount += expect_result ("sstring", "String", "sstring", false);
+  errcount += expect_result ("string", "Strin", "string", false);
+  errcount += expect_result ("\t( strinG", "String", "( strinG", false);
+  errcount += expect_result (")strinG\t ", "String", ")strinG", false);
+  errcount += expect_result (" \t tOkEn t ", "toKEN", "tOkEn t", false);
+  errcount += expect_result ("not token\t,  tOkEner  ", "toKEN",
+                             "not token, tOkEner", false);
+  errcount += expect_result ("not token,\t  tOkEns, more token", "toKEN",
+                             "not token, tOkEns, more token", false);
+  errcount += expect_result ("not token,\t  tOkEns\t, more token", "toKEN",
+                             "not token, tOkEns, more token", false);
+  errcount += expect_result (",,,,,,testing,,,,", "TESt", "testing", false);
+  errcount += expect_result (",,,,,\t,test,,,,", "TESting", "test", false);
+  errcount += expect_result ("tests,,,,,,quest, ,,,", "TESt", "tests, quest",
+                             false);
+  errcount += expect_result (",,,,,, testы,,,,", "TESt", "testы", false);
+  errcount += expect_result (",,,,,, test not,хtest,,", "TESt",
+                             "test not, хtest", false);
+  errcount += expect_result ("testing,,,,,, test not,,test2,,", "TESt",
+                             "testing, test not, test2", false);
+  errcount += expect_result (",testi,,,,, test not ,test,,", "TESting",
+                             "testi, test not, test", false);
+  errcount += expect_result (",,,,,,2 test", "TESt", "2 test", false);
+  errcount += expect_result (",,,,,,test test      ", "test", "test test",
+                             false);
+  errcount += expect_result ("no test,,,,,,test test", "test",
+                             "no test, test test", false);
+  errcount += expect_result (",,,,,,,,,,,,,,,,,,,", "the-token", "", false);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,", "the-token",
+                             "a, b, c, d, e, f, g", false);
+  errcount += expect_result (",,,,,,,,,,,,,,,,,,,", "", "", false);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,", "",
+                             "a, b, c, d, e, f, g", false);
+  errcount += expect_result ("a,b,c,d,e,f,g", "", "a, b, c, d, e, f, g",
+                             false);
+  errcount += expect_result ("a1,b1,c1,d1,e1,f1,g1", "",
+                             "a1, b1, c1, d1, e1, f1, g1", false);
+
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token",
+                             "the-token", "a, b, c, d, e, f, g", true);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token,",
+                             "the-token", "a, b, c, d, e, f, g", true);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token,x",
+                             "the-token", "a, b, c, d, e, f, g, x", true);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x",
+                             "the-token", "a, b, c, d, e, f, g, the-token x",
+                             false);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x,",
+                             "the-token", "a, b, c, d, e, f, g, the-token x",
+                             false);
+  errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x,x",
+                             "the-token", "a, b, c, d, e, f, g," \
+                             " the-token x, x", false);
+  errcount += expect_result ("the-token,a,b,c,d,e,f,g,,,,,,,,,,,,the-token",
+                             "the-token", "a, b, c, d, e, f, g", true);
+  errcount += expect_result ("the-token ,a,b,c,d,e,f,g,,,,,,,,,,,,the-token,",
+                             "the-token", "a, b, c, d, e, f, g", true);
+  errcount += expect_result ("the-token,a,b,c,d,e,f,g,,,,,,,,,,,,the-token,x",
+                             "the-token", "a, b, c, d, e, f, g, x", true);
+  errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \
+                             "the-token x", "the-token",
+                             "the-token x, a, b, c, d, e, f, g, the-token x",
+                             false);
+  errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \
+                             "the-token x,", "the-token",
+                             "the-token x, a, b, c, d, e, f, g, the-token x",
+                             false);
+  errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \
+                             "the-token x,x", "the-token",
+                             "the-token x, a, b, c, d, e, f, g, " \
+                             "the-token x, x", false);
+
+  return errcount;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_result ();
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_str_tokens_remove.c b/src/microhttpd/test_str_tokens_remove.c
new file mode 100644
index 0000000..b6b3caa
--- /dev/null
+++ b/src/microhttpd/test_str_tokens_remove.c
@@ -0,0 +1,282 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2017-2021 Karlson2k (Evgeny Grin)
+
+  This test tool 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 2, or
+  (at your option) any later version.
+
+  This test tool 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file microhttpd/test_str_token.c
+ * @brief  Unit tests for MHD_str_remove_tokens_caseless_() function
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <string.h>
+#include <stdio.h>
+#include "mhd_str.h"
+#include "mhd_assert.h"
+
+
+static int
+expect_result_n (const char *str, size_t str_len,
+                 const char *tokens, size_t tokens_len,
+                 const char *expected, size_t expected_len,
+                 const bool expected_removed)
+{
+  char buf_in[1024];
+  char buf_tokens[256];
+  bool res;
+  size_t result_len;
+
+  mhd_assert (sizeof(buf_in) > str_len + 2);
+  mhd_assert (sizeof(buf_tokens) > tokens_len + 2);
+
+  memset (buf_tokens, '#', sizeof(buf_tokens));
+  memcpy (buf_tokens, tokens, tokens_len); /* Copy without zero-termination */
+  memset (buf_in, '$', sizeof(buf_in));
+  memcpy (buf_in, str, str_len); /* Copy without zero-termination */
+
+  result_len = str_len;
+
+  res = MHD_str_remove_tokens_caseless_ (buf_in, &result_len,
+                                         buf_tokens, tokens_len);
+
+  if ( (expected_removed != res) ||
+       (expected_len != result_len) ||
+       ((0 != result_len) && (0 != memcmp (expected, buf_in, result_len))) ||
+       ('$' != buf_in[str_len]))
+  {
+    fprintf (stderr,
+             "MHD_str_remove_tokens_caseless_() FAILED:\n"
+             "\tRESULT: "
+             "\tMHD_str_remove_token_caseless_(\"%s\"->\"%.*s\", &(%lu->%lu),"
+             " \"%.*s\", %lu) returned %s\n",
+             str,
+             (int) result_len, buf_in,
+             (unsigned long) str_len, (unsigned long) result_len,
+             (int) tokens_len, buf_tokens, (unsigned long) tokens_len,
+             res ? "true" : "false");
+    fprintf (stderr,
+             "\tEXPECTED: "
+             "\tMHD_str_remove_token_caseless_(\"%s\"->\"%s\", &(%lu->%lu),"
+             " \"%.*s\", %lu) returned %s\n",
+             str,
+             expected,
+             (unsigned long) str_len, (unsigned long) expected_len,
+             (int) tokens_len, buf_tokens, (unsigned long) tokens_len,
+             expected_removed ? "true" : "false");
+    return 1;
+  }
+  return 0;
+}
+
+
+#define expect_result(s,t,e,found) \
+  expect_result_n ((s),MHD_STATICSTR_LEN_ (s), \
+                   (t),MHD_STATICSTR_LEN_ (t), \
+                   (e),MHD_STATICSTR_LEN_ (e), found)
+
+static int
+check_result (void)
+{
+  int errcount = 0;
+  errcount += expect_result ("string", "string", "", true);
+  errcount += expect_result ("String", "string", "", true);
+  errcount += expect_result ("string", "String", "", true);
+  errcount += expect_result ("strinG", "String", "", true);
+  errcount += expect_result ("strinG", "String\t", "", true);
+  errcount += expect_result ("strinG", "\tString", "", true);
+  errcount += expect_result ("tOkEn", " \t toKEN  ", "", true);
+  errcount += expect_result ("not-token, tOkEn", "token", "not-token",
+                             true);
+  errcount += expect_result ("not-token1, tOkEn1, token", "token1",
+                             "not-token1, token",
+                             true);
+  errcount += expect_result ("token, tOkEn1", "token1", "token",
+                             true);
+  errcount += expect_result ("not-token, tOkEn", " \t toKEN", "not-token",
+                             true);
+  errcount += expect_result ("not-token, tOkEn, more-token", "toKEN\t",
+                             "not-token, more-token", true);
+  errcount += expect_result ("not-token, tOkEn, more-token", "\t  toKEN,,,,,",
+                             "not-token, more-token", true);
+  errcount += expect_result ("a, b, c, d", ",,,,,a", "b, c, d", true);
+  errcount += expect_result ("a, b, c, d", "a,,,,,,", "b, c, d", true);
+  errcount += expect_result ("a, b, c, d", ",,,,a,,,,,,", "b, c, d", true);
+  errcount += expect_result ("a, b, c, d", "\t \t,,,,a,,   ,   ,,,\t",
+                             "b, c, d", true);
+  errcount += expect_result ("a, b, c, d", "b, c, d", "a", true);
+  errcount += expect_result ("a, b, c, d", "a, b, c, d", "", true);
+  errcount += expect_result ("a, b, c, d", "d, c, b, a", "", true);
+  errcount += expect_result ("a, b, c, d", "b, d, a, c", "", true);
+  errcount += expect_result ("a, b, c, d, e", "b, d, a, c", "e", true);
+  errcount += expect_result ("e, a, b, c, d", "b, d, a, c", "e", true);
+  errcount += expect_result ("e, a, b, c, d, e", "b, d, a, c", "e, e", true);
+  errcount += expect_result ("a, b, c, d", "b,c,d", "a", true);
+  errcount += expect_result ("a, b, c, d", "a,b,c,d", "", true);
+  errcount += expect_result ("a, b, c, d", "d,c,b,a", "", true);
+  errcount += expect_result ("a, b, c, d", "b,d,a,c", "", true);
+  errcount += expect_result ("a, b, c, d, e", "b,d,a,c", "e", true);
+  errcount += expect_result ("e, a, b, c, d", "b,d,a,c", "e", true);
+  errcount += expect_result ("e, a, b, c, d, e", "b,d,a,c", "e, e", true);
+  errcount += expect_result ("a, b, c, d", "d,,,,,,,,,c,b,a", "", true);
+  errcount += expect_result ("a, b, c, d", "b,d,a,c,,,,,,,,,,", "", true);
+  errcount += expect_result ("a, b, c, d, e", ",,,,\t,,,,b,d,a,c,\t", "e",
+                             true);
+  errcount += expect_result ("e, a, b, c, d", "b,d,a,c", "e", true);
+  errcount += expect_result ("token, a, b, c, d", "token", "a, b, c, d", true);
+  errcount += expect_result ("token1, a, b, c, d", "token1", "a, b, c, d",
+                             true);
+  errcount += expect_result ("token12, a, b, c, d", "token12", "a, b, c, d",
+                             true);
+  errcount += expect_result ("token123, a, b, c, d", "token123", "a, b, c, d",
+                             true);
+  errcount += expect_result ("token1234, a, b, c, d", "token1234", "a, b, c, d",
+                             true);
+  errcount += expect_result ("token12345, a, b, c, d", "token12345",
+                             "a, b, c, d", true);
+  errcount += expect_result ("token123456, a, b, c, d", "token123456",
+                             "a, b, c, d", true);
+  errcount += expect_result ("token1234567, a, b, c, d", "token1234567",
+                             "a, b, c, d", true);
+  errcount += expect_result ("token12345678, a, b, c, d", "token12345678",
+                             "a, b, c, d", true);
+
+  errcount += expect_result ("", "a", "", false);
+  errcount += expect_result ("", "", "", false);
+  errcount += expect_result ("a, b, c, d", "bb, dd, aa, cc", "a, b, c, d",
+                             false);
+  errcount += expect_result ("a, b, c, d, e", "bb, dd, aa, cc", "a, b, c, d, e",
+                             false);
+  errcount += expect_result ("e, a, b, c, d", "bb, dd, aa, cc", "e, a, b, c, d",
+                             false);
+  errcount += expect_result ("e, a, b, c, d, e", "bb, dd, aa, cc",
+                             "e, a, b, c, d, e", false);
+  errcount += expect_result ("aa, bb, cc, dd", "b, d, a, c", "aa, bb, cc, dd",
+                             false);
+  errcount += expect_result ("aa, bb, cc, dd, ee", "b, d, a, c",
+                             "aa, bb, cc, dd, ee", false);
+  errcount += expect_result ("ee, aa, bb, cc, dd", "b, d, a, c",
+                             "ee, aa, bb, cc, dd", false);
+  errcount += expect_result ("ee, aa, bb, cc, dd, ee", "b, d, a, c",
+                             "ee, aa, bb, cc, dd, ee", false);
+
+  errcount += expect_result ("TESt", ",,,,,,test,,,,", "", true);
+  errcount += expect_result ("TESt", ",,,,,\t,test,,,,", "", true);
+  errcount += expect_result ("TESt", ",,,,,,test, ,,,", "", true);
+  errcount += expect_result ("TESt", ",,,,,, test,,,,", "", true);
+  errcount += expect_result ("TESt", ",,,,,, test-not,test,,", "",
+                             true);
+  errcount += expect_result ("TESt", ",,,,,, test-not,,test,,", "",
+                             true);
+  errcount += expect_result ("TESt", ",,,,,, test-not ,test,,", "",
+                             true);
+  errcount += expect_result ("TESt", ",,,,,, test", "", true);
+  errcount += expect_result ("TESt", ",,,,,, test      ", "", true);
+  errcount += expect_result ("TESt", "no-test,,,,,, test      ", "",
+                             true);
+
+  errcount += expect_result ("the-token, a, the-token, b, the-token, " \
+                             "the-token, c, the-token", "the-token", "a, b, c",
+                             true);
+  errcount += expect_result ("aa, the-token, bb, the-token, cc, the-token, " \
+                             "the-token, dd, the-token", "the-token",
+                             "aa, bb, cc, dd", true);
+  errcount += expect_result ("the-token, a, the-token, b, the-token, " \
+                             "the-token, c, the-token, e", "the-token",
+                             "a, b, c, e", true);
+  errcount += expect_result ("aa, the-token, bb, the-token, cc, the-token, " \
+                             "the-token, dd, the-token, ee", "the-token",
+                             "aa, bb, cc, dd, ee", true);
+  errcount += expect_result ("the-token, the-token, the-token, " \
+                             "the-token, the-token", "the-token", "", true);
+  errcount += expect_result ("the-token, a, the-token, the-token, b, " \
+                             "the-token, c, the-token, a", "c,a,b",
+                             "the-token, the-token, the-token, the-token, the-token",
+                             true);
+  errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \
+                             "the-token, yy, the-token, ww", "ww,zz,yy",
+                             "the-token, xx, the-token, the-token, the-token, the-token",
+                             true);
+  errcount += expect_result ("the-token, a, the-token, the-token, b, " \
+                             "the-token, c, the-token, a", " c,\t a,b,,,",
+                             "the-token, the-token, the-token, the-token, the-token",
+                             true);
+  errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \
+                             "the-token, yy, the-token, ww",
+                             ",,,,ww,\t zz,  yy",
+                             "the-token, xx, the-token, the-token, the-token, the-token",
+                             true);
+  errcount += expect_result ("the-token, a, the-token, the-token, b, " \
+                             "the-token, c, the-token, a", ",,,,c,\t a,b",
+                             "the-token, the-token, the-token, the-token, the-token",
+                             true);
+  errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \
+                             "the-token, yy, the-token, ww", " ww,\t zz,yy,,,,",
+                             "the-token, xx, the-token, the-token, the-token, the-token",
+                             true);
+  errcount += expect_result ("close, 2", "close",
+                             "2", true);
+  errcount += expect_result ("close, 22", "close",
+                             "22", true);
+  errcount += expect_result ("close, nothing", "close",
+                             "nothing", true);
+  errcount += expect_result ("close, 2", "2",
+                             "close", true);
+  errcount += expect_result ("close", "close",
+                             "", true);
+  errcount += expect_result ("close, nothing", "close, token",
+                             "nothing", true);
+  errcount += expect_result ("close, nothing", "nothing, token",
+                             "close", true);
+  errcount += expect_result ("close, 2", "close, 10, 12, 22, nothing",
+                             "2", true);
+
+  errcount += expect_result ("strin", "string", "strin", false);
+  errcount += expect_result ("Stringer", "string", "Stringer", false);
+  errcount += expect_result ("sstring", "String", "sstring", false);
+  errcount += expect_result ("string", "Strin", "string", false);
+  errcount += expect_result ("String", "\t(-strinG", "String", false);
+  errcount += expect_result ("String", ")strinG\t ", "String", false);
+  errcount += expect_result ("not-token, tOkEner", "toKEN",
+                             "not-token, tOkEner", false);
+  errcount += expect_result ("not-token, tOkEns, more-token", "toKEN",
+                             "not-token, tOkEns, more-token", false);
+  errcount += expect_result ("tests, quest", "TESt", "tests, quest",
+                             false);
+  errcount += expect_result ("testы", "TESt", "testы", false);
+  errcount += expect_result ("test-not, хtest", "TESt",
+                             "test-not, хtest", false);
+  errcount += expect_result ("testing, test not, test2", "TESt",
+                             "testing, test not, test2", false);
+  errcount += expect_result ("", ",,,,,,,,,,,,,,,,,,,the-token", "", false);
+  errcount += expect_result ("a1, b1, c1, d1, e1, f1, g1", "",
+                             "a1, b1, c1, d1, e1, f1, g1", false);
+
+  return errcount;
+}
+
+
+int
+main (int argc, char *argv[])
+{
+  int errcount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  errcount += check_result ();
+  if (0 == errcount)
+    printf ("All tests were passed without errors.\n");
+  return errcount == 0 ? 0 : 1;
+}
diff --git a/src/microhttpd/test_upgrade.c b/src/microhttpd/test_upgrade.c
new file mode 100644
index 0000000..4a24c3c
--- /dev/null
+++ b/src/microhttpd/test_upgrade.c
@@ -0,0 +1,1608 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2016-2020 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_upgrade.c
+ * @brief  Testcase for libmicrohttpd upgrading a connection
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <stddef.h>
+#ifndef WINDOWS
+#include <unistd.h>
+#endif
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+#include "mhd_sockets.h"
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+
+#include "platform.h"
+#include "microhttpd.h"
+
+#include "test_helpers.h"
+
+#ifdef HTTPS_SUPPORT
+#include <gnutls/gnutls.h>
+#include "../testcurl/https/tls_test_keys.h"
+
+#if defined(HAVE_FORK) && defined(HAVE_WAITPID)
+#include <sys/types.h>
+#include <sys/wait.h>
+#endif /* HAVE_FORK && HAVE_WAITPID */
+#endif /* HTTPS_SUPPORT */
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+static void
+_testErrorLog_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call resulted in error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+}
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#define testErrorLog(ignore) \
+    _testErrorLog_func(NULL, __func__, __LINE__)
+#define testErrorLogDesc(errDesc) \
+    _testErrorLog_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define testErrorLog(ignore) \
+    _testErrorLog_func(NULL, __FUNCTION__, __LINE__)
+#define testErrorLogDesc(errDesc) \
+    _testErrorLog_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#define testErrorLog(ignore) _testErrorLog_func(NULL, NULL, __LINE__)
+#define testErrorLogDesc(errDesc) _testErrorLog_func(errDesc, NULL, __LINE__)
+#endif
+
+
+static void
+fflush_allstd (void)
+{
+  fflush (stderr);
+  fflush (stdout);
+}
+
+
+static int verbose = 0;
+
+static uint16_t global_port;
+
+enum tls_tool
+{
+  TLS_CLI_NO_TOOL = 0,
+  TLS_CLI_GNUTLS,
+  TLS_CLI_OPENSSL,
+  TLS_LIB_GNUTLS
+};
+
+static enum tls_tool use_tls_tool;
+
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+/**
+ * Fork child that connects via GnuTLS-CLI to our @a port.  Allows us to
+ * talk to our port over a socket in @a sp without having to worry
+ * about TLS.
+ *
+ * @param location where the socket is returned
+ * @return -1 on error, otherwise PID of TLS child process
+ */
+static pid_t
+gnutlscli_connect (int *sock,
+                   uint16_t port)
+{
+  pid_t chld;
+  int sp[2];
+  char destination[30];
+
+  if (0 != socketpair (AF_UNIX,
+                       SOCK_STREAM,
+                       0,
+                       sp))
+  {
+    testErrorLogDesc ("socketpair() failed");
+    return (pid_t) -1;
+  }
+  chld = fork ();
+  if (0 != chld)
+  {
+    *sock = sp[1];
+    MHD_socket_close_chk_ (sp[0]);
+    return chld;
+  }
+  MHD_socket_close_chk_ (sp[1]);
+  (void) close (0);
+  (void) close (1);
+  if (-1 == dup2 (sp[0], 0))
+    externalErrorExitDesc ("dup2() failed");
+  if (-1 == dup2 (sp[0], 1))
+    externalErrorExitDesc ("dup2() failed");
+  MHD_socket_close_chk_ (sp[0]);
+  if (TLS_CLI_GNUTLS == use_tls_tool)
+  {
+    snprintf (destination,
+              sizeof(destination),
+              "%u",
+              (unsigned int) port);
+    execlp ("gnutls-cli",
+            "gnutls-cli",
+            "--insecure",
+            "-p",
+            destination,
+            "127.0.0.1",
+            (char *) NULL);
+  }
+  else if (TLS_CLI_OPENSSL == use_tls_tool)
+  {
+    snprintf (destination,
+              sizeof(destination),
+              "127.0.0.1:%u",
+              (unsigned int) port);
+    execlp ("openssl",
+            "openssl",
+            "s_client",
+            "-connect",
+            destination,
+            "-verify",
+            "1",
+            (char *) NULL);
+  }
+  _exit (1);
+}
+
+
+#endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */
+
+
+/**
+ * Wrapper structure for plain&TLS sockets
+ */
+struct wr_socket
+{
+  /**
+   * Real network socket
+   */
+  MHD_socket fd;
+
+  /**
+   * Type of this socket
+   */
+  enum wr_type
+  {
+    wr_invalid = 0,
+    wr_plain = 1,
+    wr_tls = 2
+  } t;
+#ifdef HTTPS_SUPPORT
+  /**
+   * TLS credentials
+   */
+  gnutls_certificate_credentials_t tls_crd;
+
+  /**
+   * TLS session.
+   */
+  gnutls_session_t tls_s;
+
+  /**
+   * TLS handshake already succeed?
+   */
+  bool tls_connected;
+#endif
+};
+
+
+/**
+ * Get underlying real socket.
+ * @return FD of real socket
+ */
+#define wr_fd(s) ((s)->fd)
+
+
+/**
+ * Create wr_socket with plain TCP underlying socket
+ * @return created socket on success, NULL otherwise
+ */
+static struct wr_socket *
+wr_create_plain_sckt (void)
+{
+  struct wr_socket *s = malloc (sizeof(struct wr_socket));
+  if (NULL == s)
+  {
+    testErrorLogDesc ("malloc() failed");
+    return NULL;
+  }
+  s->t = wr_plain;
+  s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET != s->fd)
+    return s; /* Success */
+  testErrorLogDesc ("socket() failed");
+  free (s);
+  return NULL;
+}
+
+
+/**
+ * Create wr_socket with TLS TCP underlying socket
+ * @return created socket on success, NULL otherwise
+ */
+static struct wr_socket *
+wr_create_tls_sckt (void)
+{
+#ifdef HTTPS_SUPPORT
+  struct wr_socket *s = malloc (sizeof(struct wr_socket));
+  if (NULL == s)
+  {
+    testErrorLogDesc ("malloc() failed");
+    return NULL;
+  }
+  s->t = wr_tls;
+  s->tls_connected = 0;
+  s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET != s->fd)
+  {
+    if (GNUTLS_E_SUCCESS == gnutls_init (&(s->tls_s), GNUTLS_CLIENT))
+    {
+      if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (s->tls_s))
+      {
+        if (GNUTLS_E_SUCCESS ==
+            gnutls_certificate_allocate_credentials (&(s->tls_crd)))
+        {
+          if (GNUTLS_E_SUCCESS == gnutls_credentials_set (s->tls_s,
+                                                          GNUTLS_CRD_CERTIFICATE,
+                                                          s->tls_crd))
+          {
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64)
+            gnutls_transport_set_int (s->tls_s, (int) (s->fd));
+#else  /* GnuTLS before 3.1.9 or Win x64 */
+            gnutls_transport_set_ptr (s->tls_s,
+                                      (gnutls_transport_ptr_t) (intptr_t) (s->fd));
+#endif /* GnuTLS before 3.1.9 or Win x64 */
+            return s;
+          }
+          else
+            testErrorLogDesc ("gnutls_credentials_set() failed");
+          gnutls_certificate_free_credentials (s->tls_crd);
+        }
+        else
+          testErrorLogDesc ("gnutls_certificate_allocate_credentials() failed");
+      }
+      else
+        testErrorLogDesc ("gnutls_set_default_priority() failed");
+      gnutls_deinit (s->tls_s);
+    }
+    else
+      testErrorLogDesc ("gnutls_init() failed");
+    (void) MHD_socket_close_ (s->fd);
+  }
+  else
+    testErrorLogDesc ("socket() failed");
+  free (s);
+#endif /* HTTPS_SUPPORT */
+  return NULL;
+}
+
+
+/**
+ * Create wr_socket with plain TCP underlying socket
+ * from already created TCP socket.
+ * @param plain_sk real TCP socket
+ * @return created socket on success, NULL otherwise
+ */
+static struct wr_socket *
+wr_create_from_plain_sckt (MHD_socket plain_sk)
+{
+  struct wr_socket *s = malloc (sizeof(struct wr_socket));
+
+  if (NULL == s)
+  {
+    testErrorLogDesc ("malloc() failed");
+    return NULL;
+  }
+  s->t = wr_plain;
+  s->fd = plain_sk;
+  return s;
+}
+
+
+/**
+ * Connect socket to specified address.
+ * @param s socket to use
+ * @param addr address to connect
+ * @param length of structure pointed by @a addr
+ * @return zero on success, -1 otherwise.
+ */
+static int
+wr_connect (struct wr_socket *s,
+            const struct sockaddr *addr,
+            unsigned int length)
+{
+  if (0 != connect (s->fd, addr, (socklen_t) length))
+  {
+    testErrorLogDesc ("connect() failed");
+    return -1;
+  }
+  if (wr_plain == s->t)
+    return 0;
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    /* Do not try handshake here as
+     * it require processing on MHD side and
+     * when testing with "external" polling,
+     * test will call MHD processing only
+     * after return from wr_connect(). */
+    s->tls_connected = 0;
+    return 0;
+  }
+#endif /* HTTPS_SUPPORT */
+  testErrorLogDesc ("HTTPS socket connect called, but code does not support" \
+                    " HTTPS sockets");
+  return -1;
+}
+
+
+#ifdef HTTPS_SUPPORT
+/* Only to be called from wr_send() and wr_recv() ! */
+static bool
+wr_handshake (struct wr_socket *s)
+{
+  int res = gnutls_handshake (s->tls_s);
+  if (GNUTLS_E_SUCCESS == res)
+    s->tls_connected = true;
+  else if (GNUTLS_E_AGAIN == res)
+    MHD_socket_set_error_ (MHD_SCKT_EAGAIN_);
+  else
+  {
+    testErrorLogDesc ("gnutls_handshake() failed with hard error");
+    MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */
+  }
+  return s->tls_connected;
+}
+
+
+#endif /* HTTPS_SUPPORT */
+
+
+/**
+ * Send data to remote by socket.
+ * @param s the socket to use
+ * @param buf the buffer with data to send
+ * @param len the length of data in @a buf
+ * @return number of bytes were sent if succeed,
+ *         -1 if failed. Use #MHD_socket_get_error_()
+ *         to get socket error.
+ */
+static ssize_t
+wr_send (struct wr_socket *s,
+         const void *buf,
+         size_t len)
+{
+  if (wr_plain == s->t)
+    return MHD_send_ (s->fd, buf, len);
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    ssize_t ret;
+    if (! s->tls_connected && ! wr_handshake (s))
+      return -1;
+
+    ret = gnutls_record_send (s->tls_s, buf, len);
+    if (ret > 0)
+      return ret;
+    if (GNUTLS_E_AGAIN == ret)
+      MHD_socket_set_error_ (MHD_SCKT_EAGAIN_);
+    else
+    {
+      testErrorLogDesc ("gnutls_record_send() failed with hard error");
+      MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_);   /* hard error */
+      return -1;
+    }
+  }
+#endif /* HTTPS_SUPPORT */
+  testErrorLogDesc ("HTTPS socket send called, but code does not support" \
+                    " HTTPS sockets");
+  return -1;
+}
+
+
+/**
+ * Receive data from remote by socket.
+ * @param s the socket to use
+ * @param buf the buffer to store received data
+ * @param len the length of @a buf
+ * @return number of bytes were received if succeed,
+ *         -1 if failed. Use #MHD_socket_get_error_()
+ *         to get socket error.
+ */
+static ssize_t
+wr_recv (struct wr_socket *s,
+         void *buf,
+         size_t len)
+{
+  if (wr_plain == s->t)
+    return MHD_recv_ (s->fd, buf, len);
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    ssize_t ret;
+    if (! s->tls_connected && ! wr_handshake (s))
+      return -1;
+
+    ret = gnutls_record_recv (s->tls_s, buf, len);
+    if (ret > 0)
+      return ret;
+    if (GNUTLS_E_AGAIN == ret)
+      MHD_socket_set_error_ (MHD_SCKT_EAGAIN_);
+    else
+    {
+      testErrorLogDesc ("gnutls_record_recv() failed with hard error");
+      MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_);   /* hard error */
+      return -1;
+    }
+  }
+#endif /* HTTPS_SUPPORT */
+  return -1;
+}
+
+
+/**
+ * Close socket and release allocated resourced
+ * @param s the socket to close
+ * @return zero on succeed, -1 otherwise
+ */
+static int
+wr_close (struct wr_socket *s)
+{
+  int ret = (MHD_socket_close_ (s->fd)) ? 0 : -1;
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    gnutls_deinit (s->tls_s);
+    gnutls_certificate_free_credentials (s->tls_crd);
+  }
+#endif /* HTTPS_SUPPORT */
+  free (s);
+  return ret;
+}
+
+
+/**
+ * Thread we use to run the interaction with the upgraded socket.
+ */
+static pthread_t pt;
+
+/**
+ * Will be set to the upgraded socket.
+ */
+static struct wr_socket *volatile usock;
+
+/**
+ * Thread we use to run the interaction with the upgraded socket.
+ */
+static pthread_t pt_client;
+
+/**
+ * Flag set to 1 once the test is finished.
+ */
+static volatile bool done;
+
+
+static const char *
+term_reason_str (enum MHD_RequestTerminationCode term_code)
+{
+  switch ((int) term_code)
+  {
+  case MHD_REQUEST_TERMINATED_COMPLETED_OK:
+    return "COMPLETED_OK";
+  case MHD_REQUEST_TERMINATED_WITH_ERROR:
+    return "TERMINATED_WITH_ERROR";
+  case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED:
+    return "TIMEOUT_REACHED";
+  case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN:
+    return "DAEMON_SHUTDOWN";
+  case MHD_REQUEST_TERMINATED_READ_ERROR:
+    return "READ_ERROR";
+  case MHD_REQUEST_TERMINATED_CLIENT_ABORT:
+    return "CLIENT_ABORT";
+  case -1:
+    return "(not called)";
+  default:
+    return "(unknown code)";
+  }
+  return "(problem)"; /* unreachable */
+}
+
+
+/**
+ * Callback used by MHD to notify the application about completed
+ * requests.  Frees memory.
+ *
+ * @param cls client-defined closure
+ * @param connection connection handle
+ * @param req_cls value as set by the last call to
+ *        the #MHD_AccessHandlerCallback
+ * @param toe reason for request termination
+ */
+static void
+notify_completed_cb (void *cls,
+                     struct MHD_Connection *connection,
+                     void **req_cls,
+                     enum MHD_RequestTerminationCode toe)
+{
+  (void) cls;
+  (void) connection;  /* Unused. Silent compiler warning. */
+  if (verbose)
+    printf ("notify_completed_cb() has been called with '%s' code.\n",
+            term_reason_str (toe));
+  if ( (toe != MHD_REQUEST_TERMINATED_COMPLETED_OK) &&
+       (toe != MHD_REQUEST_TERMINATED_CLIENT_ABORT) &&
+       (toe != MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN) )
+    mhdErrorExitDesc ("notify_completed_cb() called with wrong code");
+  if (NULL == req_cls)
+    mhdErrorExitDesc ("'req_cls' parameter is NULL");
+  if (NULL == *req_cls)
+    mhdErrorExitDesc ("'*req_cls' pointer is NULL");
+  if (! pthread_equal (**((pthread_t **) req_cls),
+                       pthread_self ()))
+    mhdErrorExitDesc ("notify_completed_cb() is called in wrong thread");
+  free (*req_cls);
+  *req_cls = NULL;
+}
+
+
+/**
+ * Logging callback.
+ *
+ * @param cls logging closure (NULL)
+ * @param uri access URI
+ * @param connection connection handle
+ * @return #TEST_PTR
+ */
+static void *
+log_cb (void *cls,
+        const char *uri,
+        struct MHD_Connection *connection)
+{
+  pthread_t *ppth;
+
+  (void) cls;
+  (void) connection;  /* Unused. Silent compiler warning. */
+  if (NULL == uri)
+    mhdErrorExitDesc ("The 'uri' parameter is NULL");
+  if (0 != strcmp (uri, "/"))
+  {
+    fprintf (stderr, "Wrong 'uri' value: '%s'. ", uri);
+    mhdErrorExit ();
+  }
+  ppth = malloc (sizeof (pthread_t));
+  if (NULL == ppth)
+    externalErrorExitDesc ("malloc() failed");
+  *ppth = pthread_self ();
+  return (void *) ppth;
+}
+
+
+/**
+ * Function to check that MHD properly notifies about starting
+ * and stopping.
+ *
+ * @param cls client-defined closure
+ * @param connection connection handle
+ * @param socket_context socket-specific pointer where the
+ *                       client can associate some state specific
+ *                       to the TCP connection; note that this is
+ *                       different from the "req_cls" which is per
+ *                       HTTP request.  The client can initialize
+ *                       during #MHD_CONNECTION_NOTIFY_STARTED and
+ *                       cleanup during #MHD_CONNECTION_NOTIFY_CLOSED
+ *                       and access in the meantime using
+ *                       #MHD_CONNECTION_INFO_SOCKET_CONTEXT.
+ * @param toe reason for connection notification
+ * @see #MHD_OPTION_NOTIFY_CONNECTION
+ * @ingroup request
+ */
+static void
+notify_connection_cb (void *cls,
+                      struct MHD_Connection *connection,
+                      void **socket_context,
+                      enum MHD_ConnectionNotificationCode toe)
+{
+  static int started = MHD_NO;
+
+  (void) cls;
+  (void) connection;  /* Unused. Silent compiler warning. */
+  switch (toe)
+  {
+  case MHD_CONNECTION_NOTIFY_STARTED:
+    if (MHD_NO != started)
+      mhdErrorExitDesc ("The connection has been already started");
+    started = MHD_YES;
+    *socket_context = &started;
+    break;
+  case MHD_CONNECTION_NOTIFY_CLOSED:
+    if (MHD_YES != started)
+      mhdErrorExitDesc ("The connection has not been started before");
+    if (&started != *socket_context)
+      mhdErrorExitDesc ("Wrong '*socket_context' value");
+    *socket_context = NULL;
+    started = MHD_NO;
+    break;
+  }
+}
+
+
+/**
+ * Change socket to blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    externalErrorExitDesc ("fcntl() failed");
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      externalErrorExitDesc ("fcntl() failed");
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    externalErrorExitDesc ("ioctlsocket() failed");
+#endif /* MHD_WINSOCK_SOCKETS */
+
+}
+
+
+static void
+send_all (struct wr_socket *sock,
+          const char *text)
+{
+  size_t len = strlen (text);
+  ssize_t ret;
+  size_t off;
+
+  make_blocking (wr_fd (sock));
+  for (off = 0; off < len; off += (size_t) ret)
+  {
+    ret = wr_send (sock,
+                   &text[off],
+                   len - off);
+    if (0 > ret)
+    {
+      if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) ||
+          MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ()))
+      {
+        ret = 0;
+        continue;
+      }
+      externalErrorExitDesc ("send() failed");
+    }
+  }
+}
+
+
+/**
+ * Read character-by-character until we
+ * get 'CRLNCRLN'.
+ */
+static void
+recv_hdr (struct wr_socket *sock)
+{
+  unsigned int i;
+  char next;
+  char c;
+  ssize_t ret;
+
+  make_blocking (wr_fd (sock));
+  next = '\r';
+  i = 0;
+  while (i < 4)
+  {
+    ret = wr_recv (sock,
+                   &c,
+                   1);
+    if (0 > ret)
+    {
+      if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()))
+        continue;
+      if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ()))
+        continue;
+      externalErrorExitDesc ("recv() failed");
+    }
+    if (0 == ret)
+      mhdErrorExitDesc ("The server unexpectedly closed connection");
+    if (c == next)
+    {
+      i++;
+      if (next == '\r')
+        next = '\n';
+      else
+        next = '\r';
+      continue;
+    }
+    if (c == '\r')
+    {
+      i = 1;
+      next = '\n';
+      continue;
+    }
+    i = 0;
+    next = '\r';
+  }
+}
+
+
+static void
+recv_all (struct wr_socket *sock,
+          const char *text)
+{
+  size_t len = strlen (text);
+  char buf[len];
+  ssize_t ret;
+  size_t off;
+
+  make_blocking (wr_fd (sock));
+  for (off = 0; off < len; off += (size_t) ret)
+  {
+    ret = wr_recv (sock,
+                   &buf[off],
+                   len - off);
+    if (0 > ret)
+    {
+      if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) ||
+          MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ()))
+      {
+        ret = 0;
+        continue;
+      }
+      externalErrorExitDesc ("recv() failed");
+    }
+    if (0 == ret)
+      mhdErrorExitDesc ("The server unexpectedly closed connection");
+  }
+  if (0 != strncmp (text, buf, len))
+  {
+    fprintf (stderr, "Wrong received text. Expected: '%s' ."
+             "Got: '%.*s'. ", text, (int) len, buf);
+    mhdErrorExit ();
+  }
+}
+
+
+/**
+ * Main function for the thread that runs the interaction with
+ * the upgraded socket.
+ *
+ * @param cls the handle for the upgrade
+ */
+static void *
+run_usock (void *cls)
+{
+  struct MHD_UpgradeResponseHandle *urh = cls;
+
+  send_all (usock,
+            "Hello");
+  recv_all (usock,
+            "World");
+  send_all (usock,
+            "Finished");
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+  free (usock);
+  usock = NULL;
+  return NULL;
+}
+
+
+/**
+ * Main function for the thread that runs the client-side of the
+ * interaction with the upgraded socket.
+ *
+ * @param cls the client socket
+ */
+static void *
+run_usock_client (void *cls)
+{
+  struct wr_socket *sock = cls;
+
+  send_all (sock,
+            "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\n\r\n");
+  recv_hdr (sock);
+  recv_all (sock,
+            "Hello");
+  send_all (sock,
+            "World");
+  recv_all (sock,
+            "Finished");
+  wr_close (sock);
+  done = true;
+  return NULL;
+}
+
+
+/**
+ * Function called after a protocol "upgrade" response was sent
+ * successfully and the socket should now be controlled by some
+ * protocol other than HTTP.
+ *
+ * Any data already received on the socket will be made available in
+ * @e extra_in.  This can happen if the application sent extra data
+ * before MHD send the upgrade response.  The application should
+ * treat data from @a extra_in as if it had read it from the socket.
+ *
+ * Note that the application must not close() @a sock directly,
+ * but instead use #MHD_upgrade_action() for special operations
+ * on @a sock.
+ *
+ * Except when in 'thread-per-connection' mode, implementations
+ * of this function should never block (as it will still be called
+ * from within the main event loop).
+ *
+ * @param cls closure, whatever was given to #MHD_create_response_for_upgrade().
+ * @param connection original HTTP connection handle,
+ *                   giving the function a last chance
+ *                   to inspect the original HTTP request
+ * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback`
+ * @param extra_in if we happened to have read bytes after the
+ *                 HTTP header already (because the client sent
+ *                 more than the HTTP header of the request before
+ *                 we sent the upgrade response),
+ *                 these are the extra bytes already read from @a sock
+ *                 by MHD.  The application should treat these as if
+ *                 it had read them from @a sock.
+ * @param extra_in_size number of bytes in @a extra_in
+ * @param sock socket to use for bi-directional communication
+ *        with the client.  For HTTPS, this may not be a socket
+ *        that is directly connected to the client and thus certain
+ *        operations (TCP-specific setsockopt(), getsockopt(), etc.)
+ *        may not work as expected (as the socket could be from a
+ *        socketpair() or a TCP-loopback).  The application is expected
+ *        to perform read()/recv() and write()/send() calls on the socket.
+ *        The application may also call shutdown(), but must not call
+ *        close() directly.
+ * @param urh argument for #MHD_upgrade_action()s on this @a connection.
+ *        Applications must eventually use this callback to (indirectly)
+ *        perform the close() action on the @a sock.
+ */
+static void
+upgrade_cb (void *cls,
+            struct MHD_Connection *connection,
+            void *req_cls,
+            const char *extra_in,
+            size_t extra_in_size,
+            MHD_socket sock,
+            struct MHD_UpgradeResponseHandle *urh)
+{
+  (void) cls;
+  (void) connection;
+  (void) req_cls;
+  (void) extra_in; /* Unused. Silent compiler warning. */
+
+  usock = wr_create_from_plain_sckt (sock);
+  if (0 != extra_in_size)
+    mhdErrorExitDesc ("'extra_in_size' is not zero");
+  if (0 != pthread_create (&pt,
+                           NULL,
+                           &run_usock,
+                           urh))
+    externalErrorExitDesc ("pthread_create() failed");
+}
+
+
+/**
+ * A client has requested the given url using the given method
+ * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT,
+ * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc).  The callback
+ * must call MHD callbacks to provide content to give back to the
+ * client and return an HTTP status code (i.e. #MHD_HTTP_OK,
+ * #MHD_HTTP_NOT_FOUND, etc.).
+ *
+ * @param cls argument given together with the function
+ *        pointer when the handler was registered with MHD
+ * @param url the requested url
+ * @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
+ *        #MHD_HTTP_METHOD_PUT, etc.)
+ * @param version the HTTP version string (i.e.
+ *        #MHD_HTTP_VERSION_1_1)
+ * @param upload_data the data being uploaded (excluding HEADERS,
+ *        for a POST that fits into memory and that is encoded
+ *        with a supported encoding, the POST data will NOT be
+ *        given in upload_data and is instead available as
+ *        part of #MHD_get_connection_values; very large POST
+ *        data *will* be made available incrementally in
+ *        @a upload_data)
+ * @param upload_data_size set initially to the size of the
+ *        @a upload_data provided; the method must update this
+ *        value to the number of bytes NOT processed;
+ * @param req_cls pointer that the callback can set to some
+ *        address and that will be preserved by MHD for future
+ *        calls for this request; since the access handler may
+ *        be called many times (i.e., for a PUT/POST operation
+ *        with plenty of upload data) this allows the application
+ *        to easily associate some request-specific state.
+ *        If necessary, this state can be cleaned up in the
+ *        global #MHD_RequestCompletedCallback (which
+ *        can be set with the #MHD_OPTION_NOTIFY_COMPLETED).
+ *        Initially, `*req_cls` will be NULL.
+ * @return #MHD_YES if the connection was handled successfully,
+ *         #MHD_NO if the socket must be closed due to a serious
+ *         error while handling the request
+ */
+static enum MHD_Result
+ahc_upgrade (void *cls,
+             struct MHD_Connection *connection,
+             const char *url,
+             const char *method,
+             const char *version,
+             const char *upload_data,
+             size_t *upload_data_size,
+             void **req_cls)
+{
+  struct MHD_Response *resp;
+  (void) cls;
+  (void) url;
+  (void) method;                        /* Unused. Silent compiler warning. */
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (NULL == req_cls)
+    mhdErrorExitDesc ("'req_cls' is NULL");
+  if (NULL == *req_cls)
+    mhdErrorExitDesc ("'*req_cls' value is NULL");
+  if (! pthread_equal (**((pthread_t **) req_cls), pthread_self ()))
+    mhdErrorExitDesc ("ahc_upgrade() is called in wrong thread");
+  resp = MHD_create_response_for_upgrade (&upgrade_cb,
+                                          NULL);
+  if (NULL == resp)
+    mhdErrorExitDesc ("MHD_create_response_for_upgrade() failed");
+  if (MHD_YES != MHD_add_response_header (resp,
+                                          MHD_HTTP_HEADER_UPGRADE,
+                                          "Hello World Protocol"))
+    mhdErrorExitDesc ("MHD_add_response_header() failed");
+  if (MHD_YES != MHD_queue_response (connection,
+                                     MHD_HTTP_SWITCHING_PROTOCOLS,
+                                     resp))
+    mhdErrorExitDesc ("MHD_queue_response() failed");
+  MHD_destroy_response (resp);
+  return MHD_YES;
+}
+
+
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+static void
+run_mhd_select_loop (struct MHD_Daemon *daemon)
+{
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket max_fd;
+  uint64_t to64;
+  struct timeval tv;
+
+  while (! done)
+  {
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    max_fd = MHD_INVALID_SOCKET;
+    to64 = 1000;
+
+    if (MHD_YES !=
+        MHD_get_fdset (daemon,
+                       &rs,
+                       &ws,
+                       &es,
+                       &max_fd))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    (void) MHD_get_timeout64 (daemon,
+                              &to64);
+    if (1000 < to64)
+      to64 = 1000;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    tv.tv_sec = (time_t) (to64 / 1000);
+#else  /* Native W32 */
+    tv.tv_sec = (long) (to64 / 1000);
+#endif /* Native W32 */
+    tv.tv_usec = (long) (1000 * (to64 % 1000));
+    if (0 > MHD_SYS_select_ (max_fd + 1,
+                             &rs,
+                             &ws,
+                             &es,
+                             &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
+#endif
+    }
+    MHD_run_from_select (daemon,
+                         &rs,
+                         &ws,
+                         &es);
+  }
+}
+
+
+#ifdef HAVE_POLL
+
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+_MHD_NORETURN static void
+run_mhd_poll_loop (struct MHD_Daemon *daemon)
+{
+  (void) daemon; /* Unused. Silent compiler warning. */
+  externalErrorExitDesc ("Not implementable with MHD API");
+}
+
+
+#endif /* HAVE_POLL */
+
+
+#ifdef EPOLL_SUPPORT
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+static void
+run_mhd_epoll_loop (struct MHD_Daemon *daemon)
+{
+  const union MHD_DaemonInfo *di;
+  MHD_socket ep;
+  fd_set rs;
+  uint64_t to64;
+  struct timeval tv;
+  int ret;
+
+  di = MHD_get_daemon_info (daemon,
+                            MHD_DAEMON_INFO_EPOLL_FD);
+  if (NULL == di)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  ep = di->listen_fd;
+  while (! done)
+  {
+    FD_ZERO (&rs);
+    to64 = 1000;
+
+    FD_SET (ep, &rs);
+    (void) MHD_get_timeout64 (daemon,
+                              &to64);
+    if (1000 < to64)
+      to64 = 1000;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    tv.tv_sec = (time_t) (to64 / 1000);
+#else  /* Native W32 */
+    tv.tv_sec = (long) (to64 / 1000);
+#endif /* Native W32 */
+    tv.tv_usec = (int) (1000 * (to64 % 1000));
+    ret = select (ep + 1,
+                  &rs,
+                  NULL,
+                  NULL,
+                  &tv);
+    if (0 > ret)
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (tv.tv_sec * 1000 + tv.tv_usec / 1000);
+#endif
+    }
+    MHD_run (daemon);
+  }
+}
+
+
+#endif /* EPOLL_SUPPORT */
+
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+static void
+run_mhd_loop (struct MHD_Daemon *daemon,
+              unsigned int flags)
+{
+  if (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL)))
+    run_mhd_select_loop (daemon);
+#ifdef HAVE_POLL
+  else if (0 != (flags & MHD_USE_POLL))
+    run_mhd_poll_loop (daemon);
+#endif /* HAVE_POLL */
+#ifdef EPOLL_SUPPORT
+  else if (0 != (flags & MHD_USE_EPOLL))
+    run_mhd_epoll_loop (daemon);
+#endif
+  else
+    externalErrorExitDesc ("Wrong 'flags' value");
+}
+
+
+static bool test_tls;
+
+/**
+ * Test upgrading a connection.
+ *
+ * @param flags which event loop style should be tested
+ * @param pool size of the thread pool, 0 to disable
+ */
+static unsigned int
+test_upgrade (unsigned int flags,
+              unsigned int pool)
+{
+  struct MHD_Daemon *d = NULL;
+  struct wr_socket *sock;
+  struct sockaddr_in sa;
+  enum MHD_FLAG used_flags;
+  const union MHD_DaemonInfo *dinfo;
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+  pid_t pid = -1;
+#endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */
+
+  done = false;
+
+  if (! test_tls)
+    d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE,
+                          global_port,
+                          NULL, NULL,
+                          &ahc_upgrade, NULL,
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_NOTIFY_COMPLETED, &notify_completed_cb,
+                          NULL,
+                          MHD_OPTION_NOTIFY_CONNECTION, &notify_connection_cb,
+                          NULL,
+                          MHD_OPTION_THREAD_POOL_SIZE, pool,
+                          MHD_OPTION_END);
+#ifdef HTTPS_SUPPORT
+  else
+    d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE
+                          | MHD_USE_TLS,
+                          global_port,
+                          NULL, NULL,
+                          &ahc_upgrade, NULL,
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_NOTIFY_COMPLETED, &notify_completed_cb,
+                          NULL,
+                          MHD_OPTION_NOTIFY_CONNECTION, &notify_connection_cb,
+                          NULL,
+                          MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
+                          MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
+                          MHD_OPTION_THREAD_POOL_SIZE, pool,
+                          MHD_OPTION_END);
+#endif /* HTTPS_SUPPORT */
+  if (NULL == d)
+    mhdErrorExitDesc ("MHD_start_daemon() failed");
+  dinfo = MHD_get_daemon_info (d,
+                               MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  used_flags = dinfo->flags;
+  dinfo = MHD_get_daemon_info (d,
+                               MHD_DAEMON_INFO_BIND_PORT);
+  if ( (NULL == dinfo) ||
+       (0 == dinfo->port) )
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  global_port = dinfo->port; /* Re-use the same port for the next checks */
+  if (! test_tls || (TLS_LIB_GNUTLS == use_tls_tool))
+  {
+    sock = test_tls ? wr_create_tls_sckt () : wr_create_plain_sckt ();
+    if (NULL == sock)
+      externalErrorExitDesc ("Create socket failed");
+    sa.sin_family = AF_INET;
+    sa.sin_port = htons (dinfo->port);
+    sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+    if (0 != wr_connect (sock,
+                         (struct sockaddr *) &sa,
+                         sizeof (sa)))
+      externalErrorExitDesc ("Connect socket failed");
+  }
+  else
+  {
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+    MHD_socket tls_fork_sock;
+    uint16_t port;
+
+    port = dinfo->port;
+    if (-1 == (pid = gnutlscli_connect (&tls_fork_sock,
+                                        port)))
+      externalErrorExitDesc ("gnutlscli_connect() failed");
+
+    sock =  wr_create_from_plain_sckt (tls_fork_sock);
+    if (NULL == sock)
+      externalErrorExitDesc ("wr_create_from_plain_sckt() failed");
+#else  /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */
+    externalErrorExitDesc ("Unsupported 'use_tls_tool' value");
+#endif /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */
+  }
+
+  if (0 != pthread_create (&pt_client,
+                           NULL,
+                           &run_usock_client,
+                           sock))
+    externalErrorExitDesc ("pthread_create() failed");
+  if (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD) )
+    run_mhd_loop (d, used_flags);
+  if (0 != pthread_join (pt_client,
+                         NULL))
+    externalErrorExitDesc ("pthread_join() failed");
+  if (0 != pthread_join (pt,
+                         NULL))
+    externalErrorExitDesc ("pthread_join() failed");
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+  if (test_tls && (TLS_LIB_GNUTLS != use_tls_tool))
+  {
+    if ((pid_t) -1 == waitpid (pid, NULL, 0))
+      externalErrorExitDesc ("waitpid() failed");
+  }
+#endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */
+  MHD_stop_daemon (d);
+  return 0;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  unsigned int error_count = 0;
+  unsigned int res;
+
+  use_tls_tool = TLS_CLI_NO_TOOL;
+  test_tls = has_in_name (argv[0], "_tls");
+
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+
+  if (test_tls)
+  {
+    use_tls_tool = TLS_LIB_GNUTLS;   /* Should be always available as MHD uses it. */
+#ifdef HTTPS_SUPPORT
+    if (has_param (argc, argv, "--use-gnutls-cli"))
+      use_tls_tool = TLS_CLI_GNUTLS;
+    else if (has_param (argc, argv, "--use-openssl"))
+      use_tls_tool = TLS_CLI_OPENSSL;
+    else if (has_param (argc, argv, "--use-gnutls-lib"))
+      use_tls_tool = TLS_LIB_GNUTLS;
+#if defined(HAVE_FORK) && defined(HAVE_WAITPID)
+    else if (0 == system ("gnutls-cli --version 1> /dev/null 2> /dev/null"))
+      use_tls_tool = TLS_CLI_GNUTLS;
+    else if (0 == system ("openssl version 1> /dev/null 2> /dev/null"))
+      use_tls_tool = TLS_CLI_OPENSSL;
+#endif /* HAVE_FORK && HAVE_WAITPID */
+    if (verbose)
+    {
+      switch (use_tls_tool)
+      {
+      case TLS_CLI_GNUTLS:
+        printf ("GnuTLS-CLI will be used for testing.\n");
+        break;
+      case TLS_CLI_OPENSSL:
+        printf ("Command line version of OpenSSL will be used for testing.\n");
+        break;
+      case TLS_LIB_GNUTLS:
+        printf ("GnuTLS library will be used for testing.\n");
+        break;
+      case TLS_CLI_NO_TOOL:
+      default:
+        externalErrorExitDesc ("Wrong 'use_tls_tool' value");
+      }
+    }
+    if ( (TLS_LIB_GNUTLS == use_tls_tool) &&
+         (GNUTLS_E_SUCCESS != gnutls_global_init ()) )
+      externalErrorExitDesc ("gnutls_global_init() failed");
+
+#else  /* ! HTTPS_SUPPORT */
+    fprintf (stderr, "HTTPS support was disabled by configure.\n");
+    return 77;
+#endif /* ! HTTPS_SUPPORT */
+  }
+
+  global_port = MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT) ?
+                0 : (test_tls ? 1091 : 1090);
+
+  /* run tests */
+  if (verbose)
+    printf ("Starting HTTP \"Upgrade\" tests with %s connections.\n",
+            test_tls ? "TLS" : "plain");
+  /* try external select */
+  res = test_upgrade (0,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with external select, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with external select.\n");
+
+  /* Try external auto */
+  res = test_upgrade (MHD_USE_AUTO,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with external 'auto', return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with external 'auto'.\n");
+
+#ifdef EPOLL_SUPPORT
+  res = test_upgrade (MHD_USE_EPOLL,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with external select with EPOLL, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with external select with EPOLL.\n");
+#endif
+
+  /* Test thread-per-connection */
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD
+                      | MHD_USE_THREAD_PER_CONNECTION,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with thread per connection, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with thread per connection.\n");
+
+  res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD
+                      | MHD_USE_THREAD_PER_CONNECTION,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with thread per connection and 'auto', return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with thread per connection and 'auto'.\n");
+#ifdef HAVE_POLL
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD
+                      | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with thread per connection and poll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with thread per connection and poll.\n");
+#endif /* HAVE_POLL */
+
+  /* Test different event loops, with and without thread pool */
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal select, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal select.\n");
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD,
+                      2);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal select with thread pool, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal select with thread pool.\n");
+  res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal 'auto' return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal 'auto'.\n");
+  res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                      2);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal 'auto' with thread pool, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal 'auto' with thread pool.\n");
+#ifdef HAVE_POLL
+  res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal poll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal poll.\n");
+  res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD,
+                      2);
+  fflush_allstd ();
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal poll with thread pool, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal poll with thread pool.\n");
+#endif
+#ifdef EPOLL_SUPPORT
+  res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD,
+                      0);
+  fflush_allstd ();
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal epoll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal epoll.\n");
+  res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD,
+                      2);
+  fflush_allstd ();
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal epoll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal epoll.\n");
+#endif
+  /* report result */
+  if (0 != error_count)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             error_count);
+#ifdef HTTPS_SUPPORT
+  if (test_tls && (TLS_LIB_GNUTLS == use_tls_tool))
+    gnutls_global_deinit ();
+#endif /* HTTPS_SUPPORT */
+  return error_count != 0;       /* 0 == pass */
+}
diff --git a/src/microhttpd/test_upgrade_large.c b/src/microhttpd/test_upgrade_large.c
new file mode 100644
index 0000000..9d34440
--- /dev/null
+++ b/src/microhttpd/test_upgrade_large.c
@@ -0,0 +1,1808 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2016-2020 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_upgrade_large.c
+ * @brief  Testcase for libmicrohttpd upgrading a connection,
+ *         modified to test the "large" corner case reported
+ *         by Viet on the mailinglist in 6'2019
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <stddef.h>
+#ifndef WINDOWS
+#include <unistd.h>
+#endif
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif /* HAVE_STDBOOL_H */
+
+#include "mhd_sockets.h"
+#ifdef HAVE_NETINET_IP_H
+#include <netinet/ip.h>
+#endif /* HAVE_NETINET_IP_H */
+
+#ifdef HTTPS_SUPPORT
+#include <gnutls/gnutls.h>
+#include "../testcurl/https/tls_test_keys.h"
+
+#if defined(HAVE_FORK) && defined(HAVE_WAITPID)
+#include <sys/types.h>
+#include <sys/wait.h>
+#endif /* HAVE_FORK && HAVE_WAITPID */
+#endif /* HTTPS_SUPPORT */
+
+#include "platform.h"
+#include "microhttpd.h"
+#include "mhd_itc.h"
+
+#include "test_helpers.h"
+
+
+#define LARGE_STRING \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelXloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello" \
+  "HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello\n"
+
+
+#define LARGE_REPLY_STRING \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld" \
+  "WorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorldWorld\n"
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+static void
+_testErrorLog_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call resulted in error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+}
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#define testErrorLog(ignore) \
+    _testErrorLog_func(NULL, __func__, __LINE__)
+#define testErrorLogDesc(errDesc) \
+    _testErrorLog_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define testErrorLog(ignore) \
+    _testErrorLog_func(NULL, __FUNCTION__, __LINE__)
+#define testErrorLogDesc(errDesc) \
+    _testErrorLog_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#define testErrorLog(ignore) _testErrorLog_func(NULL, NULL, __LINE__)
+#define testErrorLogDesc(errDesc) _testErrorLog_func(errDesc, NULL, __LINE__)
+#endif
+
+
+static void
+fflush_allstd (void)
+{
+  fflush (stderr);
+  fflush (stdout);
+}
+
+
+static int verbose = 0;
+
+static uint16_t global_port;
+
+static struct MHD_itc_ kicker = MHD_ITC_STATIC_INIT_INVALID;
+
+enum tls_tool
+{
+  TLS_CLI_NO_TOOL = 0,
+  TLS_CLI_GNUTLS,
+  TLS_CLI_OPENSSL,
+  TLS_LIB_GNUTLS
+};
+
+static enum tls_tool use_tls_tool;
+
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+/**
+ * Fork child that connects via GnuTLS-CLI to our @a port.  Allows us to
+ * talk to our port over a socket in @a sp without having to worry
+ * about TLS.
+ *
+ * @param location where the socket is returned
+ * @return -1 on error, otherwise PID of TLS child process
+ */
+static pid_t
+gnutlscli_connect (int *sock,
+                   uint16_t port)
+{
+  pid_t chld;
+  int sp[2];
+  char destination[30];
+
+  if (0 != socketpair (AF_UNIX,
+                       SOCK_STREAM,
+                       0,
+                       sp))
+  {
+    testErrorLogDesc ("socketpair() failed");
+    return (pid_t) -1;
+  }
+  chld = fork ();
+  if (0 != chld)
+  {
+    *sock = sp[1];
+    MHD_socket_close_chk_ (sp[0]);
+    return chld;
+  }
+  MHD_socket_close_chk_ (sp[1]);
+  (void) close (0);
+  (void) close (1);
+  if (-1 == dup2 (sp[0], 0))
+    externalErrorExitDesc ("dup2() failed");
+  if (-1 == dup2 (sp[0], 1))
+    externalErrorExitDesc ("dup2() failed");
+  MHD_socket_close_chk_ (sp[0]);
+  if (TLS_CLI_GNUTLS == use_tls_tool)
+  {
+    snprintf (destination,
+              sizeof(destination),
+              "%u",
+              (unsigned int) port);
+    execlp ("gnutls-cli",
+            "gnutls-cli",
+            "--insecure",
+            "-p",
+            destination,
+            "127.0.0.1",
+            (char *) NULL);
+  }
+  else if (TLS_CLI_OPENSSL == use_tls_tool)
+  {
+    snprintf (destination,
+              sizeof(destination),
+              "127.0.0.1:%u",
+              (unsigned int) port);
+    execlp ("openssl",
+            "openssl",
+            "s_client",
+            "-connect",
+            destination,
+            "-verify",
+            "1",
+            (char *) NULL);
+  }
+  _exit (1);
+}
+
+
+#endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */
+
+
+/**
+ * Wrapper structure for plain&TLS sockets
+ */
+struct wr_socket
+{
+  /**
+   * Real network socket
+   */
+  MHD_socket fd;
+
+  /**
+   * Type of this socket
+   */
+  enum wr_type
+  {
+    wr_invalid = 0,
+    wr_plain = 1,
+    wr_tls = 2
+  } t;
+#ifdef HTTPS_SUPPORT
+  /**
+   * TLS credentials
+   */
+  gnutls_certificate_credentials_t tls_crd;
+
+  /**
+   * TLS session.
+   */
+  gnutls_session_t tls_s;
+
+  /**
+   * TLS handshake already succeed?
+   */
+  bool tls_connected;
+#endif
+};
+
+
+/**
+ * Get underlying real socket.
+ * @return FD of real socket
+ */
+#define wr_fd(s) ((s)->fd)
+
+
+/**
+ * Create wr_socket with plain TCP underlying socket
+ * @return created socket on success, NULL otherwise
+ */
+static struct wr_socket *
+wr_create_plain_sckt (void)
+{
+  struct wr_socket *s = malloc (sizeof(struct wr_socket));
+  if (NULL == s)
+  {
+    testErrorLogDesc ("malloc() failed");
+    return NULL;
+  }
+  s->t = wr_plain;
+  s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET != s->fd)
+    return s; /* Success */
+  testErrorLogDesc ("socket() failed");
+  free (s);
+  return NULL;
+}
+
+
+/**
+ * Create wr_socket with TLS TCP underlying socket
+ * @return created socket on success, NULL otherwise
+ */
+static struct wr_socket *
+wr_create_tls_sckt (void)
+{
+#ifdef HTTPS_SUPPORT
+  struct wr_socket *s = malloc (sizeof(struct wr_socket));
+  if (NULL == s)
+  {
+    testErrorLogDesc ("malloc() failed");
+    return NULL;
+  }
+  s->t = wr_tls;
+  s->tls_connected = 0;
+  s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET != s->fd)
+  {
+    if (GNUTLS_E_SUCCESS == gnutls_init (&(s->tls_s), GNUTLS_CLIENT))
+    {
+      if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (s->tls_s))
+      {
+        if (GNUTLS_E_SUCCESS ==
+            gnutls_certificate_allocate_credentials (&(s->tls_crd)))
+        {
+          if (GNUTLS_E_SUCCESS == gnutls_credentials_set (s->tls_s,
+                                                          GNUTLS_CRD_CERTIFICATE,
+                                                          s->tls_crd))
+          {
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64)
+            gnutls_transport_set_int (s->tls_s, (int) (s->fd));
+#else  /* GnuTLS before 3.1.9 or Win x64 */
+            gnutls_transport_set_ptr (s->tls_s,
+                                      (gnutls_transport_ptr_t) (intptr_t) (s->fd));
+#endif /* GnuTLS before 3.1.9 or Win x64 */
+            return s;
+          }
+          else
+            testErrorLogDesc ("gnutls_credentials_set() failed");
+          gnutls_certificate_free_credentials (s->tls_crd);
+        }
+        else
+          testErrorLogDesc ("gnutls_certificate_allocate_credentials() failed");
+      }
+      else
+        testErrorLogDesc ("gnutls_set_default_priority() failed");
+      gnutls_deinit (s->tls_s);
+    }
+    else
+      testErrorLogDesc ("gnutls_init() failed");
+    (void) MHD_socket_close_ (s->fd);
+  }
+  else
+    testErrorLogDesc ("socket() failed");
+  free (s);
+#endif /* HTTPS_SUPPORT */
+  return NULL;
+}
+
+
+/**
+ * Create wr_socket with plain TCP underlying socket
+ * from already created TCP socket.
+ * @param plain_sk real TCP socket
+ * @return created socket on success, NULL otherwise
+ */
+static struct wr_socket *
+wr_create_from_plain_sckt (MHD_socket plain_sk)
+{
+  struct wr_socket *s = malloc (sizeof(struct wr_socket));
+
+  if (NULL == s)
+  {
+    testErrorLogDesc ("malloc() failed");
+    return NULL;
+  }
+  s->t = wr_plain;
+  s->fd = plain_sk;
+  return s;
+}
+
+
+/**
+ * Connect socket to specified address.
+ * @param s socket to use
+ * @param addr address to connect
+ * @param length of structure pointed by @a addr
+ * @return zero on success, -1 otherwise.
+ */
+static int
+wr_connect (struct wr_socket *s,
+            const struct sockaddr *addr,
+            unsigned int length)
+{
+  if (0 != connect (s->fd, addr, (socklen_t) length))
+  {
+    testErrorLogDesc ("connect() failed");
+    return -1;
+  }
+  if (wr_plain == s->t)
+    return 0;
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    /* Do not try handshake here as
+     * it require processing on MHD side and
+     * when testing with "external" polling,
+     * test will call MHD processing only
+     * after return from wr_connect(). */
+    s->tls_connected = 0;
+    return 0;
+  }
+#endif /* HTTPS_SUPPORT */
+  testErrorLogDesc ("HTTPS socket connect called, but code does not support" \
+                    " HTTPS sockets");
+  return -1;
+}
+
+
+#ifdef HTTPS_SUPPORT
+/* Only to be called from wr_send() and wr_recv() ! */
+static bool
+wr_handshake (struct wr_socket *s)
+{
+  int res = gnutls_handshake (s->tls_s);
+  if (GNUTLS_E_SUCCESS == res)
+    s->tls_connected = true;
+  else if (GNUTLS_E_AGAIN == res)
+    MHD_socket_set_error_ (MHD_SCKT_EAGAIN_);
+  else
+  {
+    testErrorLogDesc ("gnutls_handshake() failed with hard error");
+    MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */
+  }
+  return s->tls_connected;
+}
+
+
+#endif /* HTTPS_SUPPORT */
+
+
+/**
+ * Send data to remote by socket.
+ *
+ * @param s the socket to use
+ * @param buf the buffer with data to send
+ * @param len the length of data in @a buf
+ * @return number of bytes were sent if succeed,
+ *         -1 if failed. Use #MHD_socket_get_error_()
+ *         to get socket error.
+ */
+static ssize_t
+wr_send (struct wr_socket *s,
+         const void *buf,
+         size_t len)
+{
+  if (wr_plain == s->t)
+    return MHD_send_ (s->fd, buf, len);
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    ssize_t ret;
+
+    if (! s->tls_connected && ! wr_handshake (s))
+      return -1;
+
+    ret = gnutls_record_send (s->tls_s, buf, len);
+    if (ret > 0)
+      return ret;
+    if (GNUTLS_E_AGAIN == ret)
+      MHD_socket_set_error_ (MHD_SCKT_EAGAIN_);
+    else
+    {
+      testErrorLogDesc ("gnutls_record_send() failed with hard error");
+      MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_);  /* hard error */
+      return -1;
+    }
+  }
+#endif /* HTTPS_SUPPORT */
+  testErrorLogDesc ("HTTPS socket send called, but code does not support" \
+                    " HTTPS sockets");
+  return -1;
+}
+
+
+/**
+ * Receive data from remote by socket.
+ * @param s the socket to use
+ * @param buf the buffer to store received data
+ * @param len the length of @a buf
+ * @return number of bytes were received if succeed,
+ *         -1 if failed. Use #MHD_socket_get_error_()
+ *         to get socket error.
+ */
+static ssize_t
+wr_recv (struct wr_socket *s,
+         void *buf,
+         size_t len)
+{
+  if (wr_plain == s->t)
+    return MHD_recv_ (s->fd, buf, len);
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    ssize_t ret;
+    if (! s->tls_connected && ! wr_handshake (s))
+      return -1;
+
+    ret = gnutls_record_recv (s->tls_s, buf, len);
+    if (ret > 0)
+      return ret;
+    if (GNUTLS_E_AGAIN == ret)
+      MHD_socket_set_error_ (MHD_SCKT_EAGAIN_);
+    else
+    {
+      testErrorLogDesc ("gnutls_record_recv() failed with hard error");
+      MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_);  /* hard error */
+      return -1;
+    }
+  }
+#endif /* HTTPS_SUPPORT */
+  return -1;
+}
+
+
+/**
+ * Close socket and release allocated resourced
+ * @param s the socket to close
+ * @return zero on succeed, -1 otherwise
+ */
+static int
+wr_close (struct wr_socket *s)
+{
+  int ret = (MHD_socket_close_ (s->fd)) ? 0 : -1;
+#ifdef HTTPS_SUPPORT
+  if (wr_tls == s->t)
+  {
+    gnutls_deinit (s->tls_s);
+    gnutls_certificate_free_credentials (s->tls_crd);
+  }
+#endif /* HTTPS_SUPPORT */
+  free (s);
+  return ret;
+}
+
+
+/**
+ * Thread we use to run the interaction with the upgraded socket.
+ */
+static pthread_t pt;
+
+/**
+ * Will be set to the upgraded socket.
+ */
+static struct wr_socket *volatile usock;
+
+/**
+ * Thread we use to run the interaction with the upgraded socket.
+ */
+static pthread_t pt_client;
+
+/**
+ * Flag set to 1 once the test is finished.
+ */
+static volatile bool done;
+
+
+static const char *
+term_reason_str (enum MHD_RequestTerminationCode term_code)
+{
+  switch ((int) term_code)
+  {
+  case MHD_REQUEST_TERMINATED_COMPLETED_OK:
+    return "COMPLETED_OK";
+  case MHD_REQUEST_TERMINATED_WITH_ERROR:
+    return "TERMINATED_WITH_ERROR";
+  case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED:
+    return "TIMEOUT_REACHED";
+  case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN:
+    return "DAEMON_SHUTDOWN";
+  case MHD_REQUEST_TERMINATED_READ_ERROR:
+    return "READ_ERROR";
+  case MHD_REQUEST_TERMINATED_CLIENT_ABORT:
+    return "CLIENT_ABORT";
+  case -1:
+    return "(not called)";
+  default:
+    return "(unknown code)";
+  }
+  return "(problem)"; /* unreachable */
+}
+
+
+/**
+ * Callback used by MHD to notify the application about completed
+ * requests.  Frees memory.
+ *
+ * @param cls client-defined closure
+ * @param connection connection handle
+ * @param req_cls value as set by the last call to
+ *        the #MHD_AccessHandlerCallback
+ * @param toe reason for request termination
+ */
+static void
+notify_completed_cb (void *cls,
+                     struct MHD_Connection *connection,
+                     void **req_cls,
+                     enum MHD_RequestTerminationCode toe)
+{
+  (void) cls;
+  (void) connection;  /* Unused. Silent compiler warning. */
+  if (verbose)
+    printf ("notify_completed_cb() has been called with '%s' code.\n",
+            term_reason_str (toe));
+  if ( (toe != MHD_REQUEST_TERMINATED_COMPLETED_OK) &&
+       (toe != MHD_REQUEST_TERMINATED_CLIENT_ABORT) &&
+       (toe != MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN) )
+    mhdErrorExitDesc ("notify_completed_cb() called with wrong code");
+  if (NULL == req_cls)
+    mhdErrorExitDesc ("'req_cls' parameter is NULL");
+  if (NULL == *req_cls)
+    mhdErrorExitDesc ("'*req_cls' pointer is NULL");
+  if (! pthread_equal (**((pthread_t **) req_cls),
+                       pthread_self ()))
+    mhdErrorExitDesc ("notify_completed_cb() is called in wrong thread");
+  free (*req_cls);
+  *req_cls = NULL;
+}
+
+
+/**
+ * Logging callback.
+ *
+ * @param cls logging closure (NULL)
+ * @param uri access URI
+ * @param connection connection handle
+ * @return #TEST_PTR
+ */
+static void *
+log_cb (void *cls,
+        const char *uri,
+        struct MHD_Connection *connection)
+{
+  pthread_t *ppth;
+
+  (void) cls;
+  (void) connection;  /* Unused. Silent compiler warning. */
+  if (NULL == uri)
+    mhdErrorExitDesc ("The 'uri' parameter is NULL");
+  if (0 != strcmp (uri, "/"))
+  {
+    fprintf (stderr, "Wrong 'uri' value: '%s'. ", uri);
+    mhdErrorExit ();
+  }
+  ppth = malloc (sizeof (pthread_t));
+  if (NULL == ppth)
+    externalErrorExitDesc ("malloc() failed");
+  *ppth = pthread_self ();
+  return (void *) ppth;
+}
+
+
+/**
+ * Function to check that MHD properly notifies about starting
+ * and stopping.
+ *
+ * @param cls client-defined closure
+ * @param connection connection handle
+ * @param socket_context socket-specific pointer where the
+ *                       client can associate some state specific
+ *                       to the TCP connection; note that this is
+ *                       different from the "req_cls" which is per
+ *                       HTTP request.  The client can initialize
+ *                       during #MHD_CONNECTION_NOTIFY_STARTED and
+ *                       cleanup during #MHD_CONNECTION_NOTIFY_CLOSED
+ *                       and access in the meantime using
+ *                       #MHD_CONNECTION_INFO_SOCKET_CONTEXT.
+ * @param toe reason for connection notification
+ * @see #MHD_OPTION_NOTIFY_CONNECTION
+ * @ingroup request
+ */
+static void
+notify_connection_cb (void *cls,
+                      struct MHD_Connection *connection,
+                      void **socket_context,
+                      enum MHD_ConnectionNotificationCode toe)
+{
+  static int started = MHD_NO;
+
+  (void) cls;
+  (void) connection;  /* Unused. Silent compiler warning. */
+  switch (toe)
+  {
+  case MHD_CONNECTION_NOTIFY_STARTED:
+    if (MHD_NO != started)
+      mhdErrorExitDesc ("The connection has been already started");
+    started = MHD_YES;
+    *socket_context = &started;
+    break;
+  case MHD_CONNECTION_NOTIFY_CLOSED:
+    if (MHD_YES != started)
+      mhdErrorExitDesc ("The connection has not been started before");
+    if (&started != *socket_context)
+      mhdErrorExitDesc ("Wrong '*socket_context' value");
+    *socket_context = NULL;
+    started = MHD_NO;
+    break;
+  }
+}
+
+
+/**
+ * Change socket to blocking.
+ *
+ * @param fd the socket to manipulate
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#if defined(MHD_POSIX_SOCKETS)
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    externalErrorExitDesc ("fcntl() failed");
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      externalErrorExitDesc ("fcntl() failed");
+#elif defined(MHD_WINSOCK_SOCKETS)
+  unsigned long flags = 0;
+
+  if (0 != ioctlsocket (fd, (int) FIONBIO, &flags))
+    externalErrorExitDesc ("ioctlsocket() failed");
+#endif /* MHD_WINSOCK_SOCKETS */
+}
+
+
+static void
+kick_select (void)
+{
+  if (MHD_ITC_IS_VALID_ (kicker))
+  {
+    (void) MHD_itc_activate_ (kicker, "K");
+  }
+}
+
+
+static void
+send_all (struct wr_socket *sock,
+          const char *text)
+{
+  size_t len = strlen (text);
+  ssize_t ret;
+  size_t off;
+
+  make_blocking (wr_fd (sock));
+  for (off = 0; off < len; off += (size_t) ret)
+  {
+    ret = wr_send (sock,
+                   &text[off],
+                   len - off);
+    if (0 > ret)
+    {
+      if (! MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) &&
+          ! MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ()))
+        externalErrorExitDesc ("send() failed");
+      else
+        ret = 0;
+    }
+    kick_select ();
+  }
+}
+
+
+/**
+ * Read character-by-character until we
+ * get 'CRLNCRLN'.
+ */
+static void
+recv_hdr (struct wr_socket *sock)
+{
+  unsigned int i;
+  char next;
+  char c;
+  ssize_t ret;
+
+  make_blocking (wr_fd (sock));
+  next = '\r';
+  i = 0;
+  while (i < 4)
+  {
+    ret = wr_recv (sock,
+                   &c,
+                   1);
+    if (0 > ret)
+    {
+      if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()))
+        continue;
+      if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ()))
+        continue;
+      externalErrorExitDesc ("recv() failed");
+    }
+    if (0 == ret)
+      mhdErrorExitDesc ("The server unexpectedly closed connection");
+    kick_select ();
+    if (c == next)
+    {
+      i++;
+      if (next == '\r')
+        next = '\n';
+      else
+        next = '\r';
+      continue;
+    }
+    if (c == '\r')
+    {
+      i = 1;
+      next = '\n';
+      continue;
+    }
+    i = 0;
+    next = '\r';
+  }
+}
+
+
+static void
+recv_all (struct wr_socket *sock,
+          const char *text)
+{
+  size_t len = strlen (text);
+  char buf[len];
+  ssize_t ret;
+  size_t off;
+
+  make_blocking (wr_fd (sock));
+  for (off = 0; off < len; off += (size_t) ret)
+  {
+    ret = wr_recv (sock,
+                   &buf[off],
+                   len - off);
+    if (0 > ret)
+    {
+      if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) ||
+          MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ()))
+      {
+        ret = 0;
+        continue;
+      }
+      externalErrorExitDesc ("recv() failed");
+    }
+    if (0 == ret)
+      mhdErrorExitDesc ("The server unexpectedly closed connection");
+    if (0 != strncmp (text, buf, off + (size_t) ret))
+    {
+      fprintf (stderr, "Wrong received text. Expected: '%s' ."
+               "Got: '%.*s'. ", text, (int) (off + (size_t) ret), buf);
+      mhdErrorExit ();
+    }
+  }
+  if (0 != strncmp (text, buf, len))
+  {
+    fprintf (stderr, "Wrong received text. Expected: '%s' ."
+             "Got: '%.*s'. ", text, (int) len, buf);
+    mhdErrorExit ();
+  }
+}
+
+
+/**
+ * Main function for the thread that runs the interaction with
+ * the upgraded socket.
+ *
+ * @param cls the handle for the upgrade
+ */
+static void *
+run_usock (void *cls)
+{
+  struct MHD_UpgradeResponseHandle *urh = cls;
+
+  send_all (usock,
+            LARGE_STRING);
+  recv_all (usock,
+            LARGE_REPLY_STRING);
+  send_all (usock,
+            "Finished");
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+  free (usock);
+  usock = NULL;
+  return NULL;
+}
+
+
+/**
+ * Main function for the thread that runs the client-side of the
+ * interaction with the upgraded socket.
+ *
+ * @param cls the client socket
+ */
+static void *
+run_usock_client (void *cls)
+{
+  struct wr_socket *sock = cls;
+
+  send_all (sock,
+            "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\n\r\n");
+  recv_hdr (sock);
+  recv_all (sock,
+            LARGE_STRING);
+  send_all (sock,
+            LARGE_REPLY_STRING);
+  recv_all (sock,
+            "Finished");
+  wr_close (sock);
+  done = true;
+  return NULL;
+}
+
+
+/**
+ * Function called after a protocol "upgrade" response was sent
+ * successfully and the socket should now be controlled by some
+ * protocol other than HTTP.
+ *
+ * Any data already received on the socket will be made available in
+ * @e extra_in.  This can happen if the application sent extra data
+ * before MHD send the upgrade response.  The application should
+ * treat data from @a extra_in as if it had read it from the socket.
+ *
+ * Note that the application must not close() @a sock directly,
+ * but instead use #MHD_upgrade_action() for special operations
+ * on @a sock.
+ *
+ * Except when in 'thread-per-connection' mode, implementations
+ * of this function should never block (as it will still be called
+ * from within the main event loop).
+ *
+ * @param cls closure, whatever was given to #MHD_create_response_for_upgrade().
+ * @param connection original HTTP connection handle,
+ *                   giving the function a last chance
+ *                   to inspect the original HTTP request
+ * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback`
+ * @param extra_in if we happened to have read bytes after the
+ *                 HTTP header already (because the client sent
+ *                 more than the HTTP header of the request before
+ *                 we sent the upgrade response),
+ *                 these are the extra bytes already read from @a sock
+ *                 by MHD.  The application should treat these as if
+ *                 it had read them from @a sock.
+ * @param extra_in_size number of bytes in @a extra_in
+ * @param sock socket to use for bi-directional communication
+ *        with the client.  For HTTPS, this may not be a socket
+ *        that is directly connected to the client and thus certain
+ *        operations (TCP-specific setsockopt(), getsockopt(), etc.)
+ *        may not work as expected (as the socket could be from a
+ *        socketpair() or a TCP-loopback).  The application is expected
+ *        to perform read()/recv() and write()/send() calls on the socket.
+ *        The application may also call shutdown(), but must not call
+ *        close() directly.
+ * @param urh argument for #MHD_upgrade_action()s on this @a connection.
+ *        Applications must eventually use this callback to (indirectly)
+ *        perform the close() action on the @a sock.
+ */
+static void
+upgrade_cb (void *cls,
+            struct MHD_Connection *connection,
+            void *req_cls,
+            const char *extra_in,
+            size_t extra_in_size,
+            MHD_socket sock,
+            struct MHD_UpgradeResponseHandle *urh)
+{
+  (void) cls;
+  (void) connection;
+  (void) req_cls;
+  (void) extra_in; /* Unused. Silent compiler warning. */
+
+  usock = wr_create_from_plain_sckt (sock);
+  if (0 != extra_in_size)
+    mhdErrorExitDesc ("'extra_in_size' is not zero");
+  if (0 != pthread_create (&pt,
+                           NULL,
+                           &run_usock,
+                           urh))
+    externalErrorExitDesc ("pthread_create() failed");
+}
+
+
+/**
+ * A client has requested the given url using the given method
+ * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT,
+ * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc).  The callback
+ * must call MHD callbacks to provide content to give back to the
+ * client and return an HTTP status code (i.e. #MHD_HTTP_OK,
+ * #MHD_HTTP_NOT_FOUND, etc.).
+ *
+ * @param cls argument given together with the function
+ *        pointer when the handler was registered with MHD
+ * @param url the requested url
+ * @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
+ *        #MHD_HTTP_METHOD_PUT, etc.)
+ * @param version the HTTP version string (i.e.
+ *        #MHD_HTTP_VERSION_1_1)
+ * @param upload_data the data being uploaded (excluding HEADERS,
+ *        for a POST that fits into memory and that is encoded
+ *        with a supported encoding, the POST data will NOT be
+ *        given in upload_data and is instead available as
+ *        part of #MHD_get_connection_values; very large POST
+ *        data *will* be made available incrementally in
+ *        @a upload_data)
+ * @param upload_data_size set initially to the size of the
+ *        @a upload_data provided; the method must update this
+ *        value to the number of bytes NOT processed;
+ * @param req_cls pointer that the callback can set to some
+ *        address and that will be preserved by MHD for future
+ *        calls for this request; since the access handler may
+ *        be called many times (i.e., for a PUT/POST operation
+ *        with plenty of upload data) this allows the application
+ *        to easily associate some request-specific state.
+ *        If necessary, this state can be cleaned up in the
+ *        global #MHD_RequestCompletedCallback (which
+ *        can be set with the #MHD_OPTION_NOTIFY_COMPLETED).
+ *        Initially, `*req_cls` will be NULL.
+ * @return #MHD_YES if the connection was handled successfully,
+ *         #MHD_NO if the socket must be closed due to a serious
+ *         error while handling the request
+ */
+static enum MHD_Result
+ahc_upgrade (void *cls,
+             struct MHD_Connection *connection,
+             const char *url,
+             const char *method,
+             const char *version,
+             const char *upload_data,
+             size_t *upload_data_size,
+             void **req_cls)
+{
+  struct MHD_Response *resp;
+  (void) cls;
+  (void) url;
+  (void) method;                        /* Unused. Silent compiler warning. */
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (NULL == req_cls)
+    mhdErrorExitDesc ("'req_cls' is NULL");
+  if (NULL == *req_cls)
+    mhdErrorExitDesc ("'*req_cls' value is NULL");
+  if (! pthread_equal (**((pthread_t **) req_cls), pthread_self ()))
+    mhdErrorExitDesc ("ahc_upgrade() is called in wrong thread");
+  resp = MHD_create_response_for_upgrade (&upgrade_cb,
+                                          NULL);
+  if (NULL == resp)
+    mhdErrorExitDesc ("MHD_create_response_for_upgrade() failed");
+  if (MHD_YES != MHD_add_response_header (resp,
+                                          MHD_HTTP_HEADER_UPGRADE,
+                                          "Hello World Protocol"))
+    mhdErrorExitDesc ("MHD_add_response_header() failed");
+  if (MHD_YES != MHD_queue_response (connection,
+                                     MHD_HTTP_SWITCHING_PROTOCOLS,
+                                     resp))
+    mhdErrorExitDesc ("MHD_queue_response() failed");
+  MHD_destroy_response (resp);
+  return MHD_YES;
+}
+
+
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+static void
+run_mhd_select_loop (struct MHD_Daemon *daemon)
+{
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket max_fd;
+  uint64_t to64;
+  struct timeval tv;
+
+  while (! done)
+  {
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    max_fd = MHD_INVALID_SOCKET;
+    to64 = 1000;
+
+    FD_SET (MHD_itc_r_fd_ (kicker), &rs);
+    if (MHD_YES !=
+        MHD_get_fdset (daemon,
+                       &rs,
+                       &ws,
+                       &es,
+                       &max_fd))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    (void) MHD_get_timeout64 (daemon,
+                              &to64);
+    if (1000 < to64)
+      to64 = 1000;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    tv.tv_sec = (time_t) (to64 / 1000);
+#else  /* Native W32 */
+    tv.tv_sec = (long) (to64 / 1000);
+#endif /* Native W32 */
+    tv.tv_usec = (long) (1000 * (to64 % 1000));
+    if (0 > MHD_SYS_select_ (max_fd + 1,
+                             &rs,
+                             &ws,
+                             &es,
+                             &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
+#endif
+    }
+    if (FD_ISSET (MHD_itc_r_fd_ (kicker), &rs))
+      MHD_itc_clear_ (kicker);
+    MHD_run_from_select (daemon,
+                         &rs,
+                         &ws,
+                         &es);
+  }
+}
+
+
+#ifdef HAVE_POLL
+
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+_MHD_NORETURN static void
+run_mhd_poll_loop (struct MHD_Daemon *daemon)
+{
+  (void) daemon; /* Unused. Silent compiler warning. */
+  externalErrorExitDesc ("Not implementable with MHD API");
+}
+
+
+#endif /* HAVE_POLL */
+
+
+#ifdef EPOLL_SUPPORT
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+static void
+run_mhd_epoll_loop (struct MHD_Daemon *daemon)
+{
+  const union MHD_DaemonInfo *di;
+  MHD_socket ep;
+  fd_set rs;
+  uint64_t to64;
+  struct timeval tv;
+  int ret;
+
+  di = MHD_get_daemon_info (daemon,
+                            MHD_DAEMON_INFO_EPOLL_FD);
+  if (NULL == di)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  ep = di->listen_fd;
+  while (! done)
+  {
+    FD_ZERO (&rs);
+    to64 = 1000;
+    FD_SET (MHD_itc_r_fd_ (kicker), &rs);
+    FD_SET (ep, &rs);
+    (void) MHD_get_timeout64 (daemon,
+                              &to64);
+    if (1000 < to64)
+      to64 = 1000;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    tv.tv_sec = (time_t) (to64 / 1000);
+#else  /* Native W32 */
+    tv.tv_sec = (long) (to64 / 1000);
+#endif /* Native W32 */
+    tv.tv_usec = (int) (1000 * (to64 % 1000));
+    ret = select (ep + 1,
+                  &rs,
+                  NULL,
+                  NULL,
+                  &tv);
+    if (0 > ret)
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (tv.tv_sec * 1000 + tv.tv_usec / 1000);
+#endif
+    }
+    if (FD_ISSET (MHD_itc_r_fd_ (kicker), &rs))
+      MHD_itc_clear_ (kicker);
+    MHD_run (daemon);
+  }
+}
+
+
+#endif /* EPOLL_SUPPORT */
+
+/**
+ * Run the MHD external event loop using select.
+ *
+ * @param daemon daemon to run it for
+ */
+static void
+run_mhd_loop (struct MHD_Daemon *daemon,
+              unsigned int flags)
+{
+  if (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL)))
+    run_mhd_select_loop (daemon);
+#ifdef HAVE_POLL
+  else if (0 != (flags & MHD_USE_POLL))
+    run_mhd_poll_loop (daemon);
+#endif /* HAVE_POLL */
+#ifdef EPOLL_SUPPORT
+  else if (0 != (flags & MHD_USE_EPOLL))
+    run_mhd_epoll_loop (daemon);
+#endif
+  else
+    externalErrorExitDesc ("Wrong 'flags' value");
+}
+
+
+static bool test_tls;
+
+/**
+ * Test upgrading a connection.
+ *
+ * @param flags which event loop style should be tested
+ * @param pool size of the thread pool, 0 to disable
+ */
+static unsigned int
+test_upgrade (unsigned int flags,
+              unsigned int pool)
+{
+  struct MHD_Daemon *d = NULL;
+  struct wr_socket *sock;
+  struct sockaddr_in sa;
+  enum MHD_FLAG used_flags;
+  const union MHD_DaemonInfo *dinfo;
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+  pid_t pid = -1;
+#endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */
+
+  done = false;
+
+  if (! test_tls)
+    d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE,
+                          global_port,
+                          NULL, NULL,
+                          &ahc_upgrade, NULL,
+                          MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) 512,
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_NOTIFY_COMPLETED, &notify_completed_cb,
+                          NULL,
+                          MHD_OPTION_NOTIFY_CONNECTION, &notify_connection_cb,
+                          NULL,
+                          MHD_OPTION_THREAD_POOL_SIZE, pool,
+                          MHD_OPTION_END);
+#ifdef HTTPS_SUPPORT
+  else
+    d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE
+                          | MHD_USE_TLS,
+                          global_port,
+                          NULL, NULL,
+                          &ahc_upgrade, NULL,
+                          MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) 512,
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_NOTIFY_COMPLETED, &notify_completed_cb,
+                          NULL,
+                          MHD_OPTION_NOTIFY_CONNECTION, &notify_connection_cb,
+                          NULL,
+                          MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
+                          MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
+                          MHD_OPTION_THREAD_POOL_SIZE, pool,
+                          MHD_OPTION_END);
+#endif /* HTTPS_SUPPORT */
+  if (NULL == d)
+    mhdErrorExitDesc ("MHD_start_daemon() failed");
+  dinfo = MHD_get_daemon_info (d,
+                               MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  used_flags = dinfo->flags;
+  dinfo = MHD_get_daemon_info (d,
+                               MHD_DAEMON_INFO_BIND_PORT);
+  if ( (NULL == dinfo) ||
+       (0 == dinfo->port) )
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  global_port = dinfo->port; /* Re-use the same port for the next checks */
+  if (! test_tls || (TLS_LIB_GNUTLS == use_tls_tool))
+  {
+    sock = test_tls ? wr_create_tls_sckt () : wr_create_plain_sckt ();
+    if (NULL == sock)
+      externalErrorExitDesc ("Create socket failed");
+    sa.sin_family = AF_INET;
+    sa.sin_port = htons (dinfo->port);
+    sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+    if (0 != wr_connect (sock,
+                         (struct sockaddr *) &sa,
+                         sizeof (sa)))
+      externalErrorExitDesc ("Connect socket failed");
+  }
+  else
+  {
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+    MHD_socket tls_fork_sock;
+    uint16_t port;
+
+    port = dinfo->port;
+    if (-1 == (pid = gnutlscli_connect (&tls_fork_sock,
+                                        port)))
+      externalErrorExitDesc ("gnutlscli_connect() failed");
+
+    sock =  wr_create_from_plain_sckt (tls_fork_sock);
+    if (NULL == sock)
+      externalErrorExitDesc ("wr_create_from_plain_sckt() failed");
+#else  /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */
+    externalErrorExitDesc ("Unsupported 'use_tls_tool' value");
+#endif /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */
+  }
+
+  if (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD) )
+  {
+    if (! MHD_itc_init_ (kicker))
+      externalErrorExitDesc ("MHD_itc_init_() failed");
+  }
+
+  if (0 != pthread_create (&pt_client,
+                           NULL,
+                           &run_usock_client,
+                           sock))
+    externalErrorExitDesc ("pthread_create() failed");
+  if (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD) )
+    run_mhd_loop (d, used_flags);
+  if (0 != pthread_join (pt_client,
+                         NULL))
+    externalErrorExitDesc ("pthread_join() failed");
+  if (0 != pthread_join (pt,
+                         NULL))
+    externalErrorExitDesc ("pthread_join() failed");
+#if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID)
+  if (test_tls && (TLS_LIB_GNUTLS != use_tls_tool))
+  {
+    if ((pid_t) -1 == waitpid (pid, NULL, 0))
+      externalErrorExitDesc ("waitpid() failed");
+  }
+#endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */
+  if (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD) )
+  {
+    (void) MHD_itc_destroy_ (kicker);
+    MHD_itc_set_invalid_ (kicker);
+  }
+  MHD_stop_daemon (d);
+  return 0;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  unsigned int error_count = 0;
+  unsigned int res;
+
+  use_tls_tool = TLS_CLI_NO_TOOL;
+  test_tls = has_in_name (argv[0], "_tls");
+
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  if (test_tls)
+  {
+#ifdef HTTPS_SUPPORT
+    use_tls_tool = TLS_LIB_GNUTLS;   /* Should be always available as MHD uses it. */
+    if (has_param (argc, argv, "--use-gnutls-cli"))
+      use_tls_tool = TLS_CLI_GNUTLS;
+    else if (has_param (argc, argv, "--use-openssl"))
+      use_tls_tool = TLS_CLI_OPENSSL;
+    else if (has_param (argc, argv, "--use-gnutls-lib"))
+      use_tls_tool = TLS_LIB_GNUTLS;
+#if defined(HAVE_FORK) && defined(HAVE_WAITPID)
+    else if (0 == system ("gnutls-cli --version 1> /dev/null 2> /dev/null"))
+      use_tls_tool = TLS_CLI_GNUTLS;
+    else if (0 == system ("openssl version 1> /dev/null 2> /dev/null"))
+      use_tls_tool = TLS_CLI_OPENSSL;
+#endif /* HAVE_FORK && HAVE_WAITPID */
+    if (verbose)
+    {
+      switch (use_tls_tool)
+      {
+      case TLS_CLI_GNUTLS:
+        printf ("GnuTLS-CLI will be used for testing.\n");
+        break;
+      case TLS_CLI_OPENSSL:
+        printf ("Command line version of OpenSSL will be used for testing.\n");
+        break;
+      case TLS_LIB_GNUTLS:
+        printf ("GnuTLS library will be used for testing.\n");
+        break;
+      case TLS_CLI_NO_TOOL:
+      default:
+        externalErrorExitDesc ("Wrong 'use_tls_tool' value");
+      }
+    }
+    if ( (TLS_LIB_GNUTLS == use_tls_tool) &&
+         (GNUTLS_E_SUCCESS != gnutls_global_init ()) )
+      externalErrorExitDesc ("gnutls_global_init() failed");
+
+#else  /* ! HTTPS_SUPPORT */
+    fprintf (stderr, "HTTPS support was disabled by configure.\n");
+    return 77;
+#endif /* ! HTTPS_SUPPORT */
+  }
+
+  global_port = MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT) ?
+                0 : (test_tls ? 1093 : 1092);
+
+  /* run tests */
+  if (verbose)
+    printf ("Starting HTTP \"Upgrade\" tests with %s connections.\n",
+            test_tls ? "TLS" : "plain");
+  /* try external select */
+  res = test_upgrade (0,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with external select, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with external select.\n");
+
+  /* Try external auto */
+  res = test_upgrade (MHD_USE_AUTO,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with external 'auto', return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with external 'auto'.\n");
+
+#ifdef EPOLL_SUPPORT
+  res = test_upgrade (MHD_USE_EPOLL,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with external select with EPOLL, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with external select with EPOLL.\n");
+#endif
+
+  /* Test thread-per-connection */
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD
+                      | MHD_USE_THREAD_PER_CONNECTION,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with thread per connection, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with thread per connection.\n");
+
+  res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD
+                      | MHD_USE_THREAD_PER_CONNECTION,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with thread per connection and 'auto', return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with thread per connection and 'auto'.\n");
+#ifdef HAVE_POLL
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD
+                      | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with thread per connection and poll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with thread per connection and poll.\n");
+#endif /* HAVE_POLL */
+
+  /* Test different event loops, with and without thread pool */
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal select, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal select.\n");
+  res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD,
+                      2);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal select with thread pool, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal select with thread pool.\n");
+  res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal 'auto' return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal 'auto'.\n");
+  res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD,
+                      2);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal 'auto' with thread pool, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal 'auto' with thread pool.\n");
+#ifdef HAVE_POLL
+  res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD,
+                      0);
+  fflush_allstd ();
+  error_count += res;
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal poll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal poll.\n");
+  res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD,
+                      2);
+  fflush_allstd ();
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal poll with thread pool, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal poll with thread pool.\n");
+#endif
+#ifdef EPOLL_SUPPORT
+  res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD,
+                      0);
+  fflush_allstd ();
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal epoll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal epoll.\n");
+  res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD,
+                      2);
+  fflush_allstd ();
+  if (res)
+    fprintf (stderr,
+             "FAILED: Upgrade with internal epoll, return code %u.\n",
+             res);
+  else if (verbose)
+    printf ("PASSED: Upgrade with internal epoll.\n");
+#endif
+  /* report result */
+  if (0 != error_count)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             error_count);
+#ifdef HTTPS_SUPPORT
+  if (test_tls && (TLS_LIB_GNUTLS == use_tls_tool))
+    gnutls_global_deinit ();
+#endif /* HTTPS_SUPPORT */
+  return error_count != 0;       /* 0 == pass */
+}
diff --git a/src/microhttpd/tsearch.c b/src/microhttpd/tsearch.c
index 8889f32..af373fc 100644
--- a/src/microhttpd/tsearch.c
+++ b/src/microhttpd/tsearch.c
@@ -1,5 +1,3 @@
-/*	$NetBSD: tsearch.c,v 1.3 1999/09/16 11:45:37 lukem Exp $	*/
-
 /*
  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
  * the AT&T man page says.
@@ -11,115 +9,128 @@
  * Totally public domain.
  */
 
-#ifndef _MSC_FULL_VER
-#include <sys/cdefs.h>
-#endif //! _MSC_FULL_VER
-#define _SEARCH_PRIVATE
+#include "mhd_options.h"
 #include "tsearch.h"
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif /* HAVE_STDDEF_H */
+#ifdef HAVE_STDLIB_H
 #include <stdlib.h>
+#endif /* HAVE_STDLIB_H */
 
+
+typedef struct node
+{
+  const void *key;
+  struct node  *llink, *rlink;
+} node_t;
+
+
+/*  $NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $  */
 /* find or insert datum into search tree */
 void *
-tsearch(vkey, vrootp, compar)
-	const void *vkey;		/* key to be located */
-	void **vrootp;			/* address of tree root */
-	int (*compar)(const void *, const void *);
+tsearch (const void *vkey, void **vrootp,
+         int (*compar)(const void *, const void *))
 {
-	node_t *q;
-	node_t **rootp = (node_t **)vrootp;
+  node_t *q;
+  node_t **rootp = (node_t **) vrootp;
 
-	if (rootp == NULL)
-		return NULL;
+  if (rootp == NULL)
+    return NULL;
 
-	while (*rootp != NULL) {	/* Knuth's T1: */
-		int r;
+  while (*rootp != NULL)        /* Knuth's T1: */
+  {
+    int r;
 
-		if ((r = (*compar)(vkey, (*rootp)->key)) == 0)	/* T2: */
-			return *rootp;		/* we found it! */
+    if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
+      return *rootp;                               /* we found it! */
 
-		rootp = (r < 0) ?
-		    &(*rootp)->llink :		/* T3: follow left branch */
-		    &(*rootp)->rlink;		/* T4: follow right branch */
-	}
+    rootp = (r < 0) ?
+            &(*rootp)->llink :      /* T3: follow left branch */
+            &(*rootp)->rlink;       /* T4: follow right branch */
+  }
 
-	q = malloc(sizeof(node_t));		/* T5: key not found */
-	if (q != 0) {				/* make new node */
-		*rootp = q;			/* link new node to old */
-		/* LINTED const castaway ok */
-		q->key = (void *)vkey;		/* initialize new node */
-		q->llink = q->rlink = NULL;
-	}
-	return q;
+  q = malloc (sizeof(node_t)); /* T5: key not found */
+  if (q != NULL)               /* make new node */
+  {
+    *rootp = q;                /* link new node to old */
+    q->key = vkey; /* initialize new node */
+    q->llink = q->rlink = NULL;
+  }
+  return q;
 }
 
-/* find a node, or return 0 */
+
+/*  $NetBSD: tfind.c,v 1.7 2012/06/25 22:32:45 abs Exp $    */
+/* find a node by key "vkey" in tree "vrootp", or return 0 */
 void *
-tfind(vkey, vrootp, compar)
-	const void *vkey;		/* key to be found */
-	void * const *vrootp;		/* address of the tree root */
-	int (*compar)(const void *, const void *);
+tfind (const void *vkey, void * const *vrootp,
+       int (*compar)(const void *, const void *))
 {
-	node_t **rootp = (node_t **)vrootp;
+  node_t * const *rootp = (node_t * const *) vrootp;
 
-	if (rootp == NULL)
-		return NULL;
+  if (rootp == NULL)
+    return NULL;
 
-	while (*rootp != NULL) {		/* T1: */
-		int r;
+  while (*rootp != NULL)            /* T1: */
+  {
+    int r;
 
-		if ((r = (*compar)(vkey, (*rootp)->key)) == 0)	/* T2: */
-			return *rootp;		/* key found */
-		rootp = (r < 0) ?
-		    &(*rootp)->llink :		/* T3: follow left branch */
-		    &(*rootp)->rlink;		/* T4: follow right branch */
-	}
-	return NULL;
+    if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */
+      return *rootp;                               /* key found */
+    rootp = (r < 0) ?
+            &(*rootp)->llink :                     /* T3: follow left branch */
+            &(*rootp)->rlink;                      /* T4: follow right branch */
+  }
+  return NULL;
 }
 
-/*
- * delete node with given key
- *
- * vkey:   key to be deleted
- * vrootp: address of the root of the tree
- * compar: function to carry out node comparisons
- */
+
+/*  $NetBSD: tdelete.c,v 1.8 2016/01/20 20:47:41 christos Exp $ */
+/* find a node with key "vkey" in tree "vrootp" */
 void *
-tdelete(const void * __restrict vkey, void ** __restrict vrootp,
-    int (*compar)(const void *, const void *))
+tdelete (const void *vkey, void **vrootp,
+         int (*compar)(const void *, const void *))
 {
-	node_t **rootp = (node_t **)vrootp;
-	node_t *p, *q, *r;
-	int cmp;
+  node_t **rootp = (node_t **) vrootp;
+  node_t *p, *q, *r;
+  int cmp;
 
-	if (rootp == NULL || (p = *rootp) == NULL)
-		return NULL;
+  if ((rootp == NULL) || ((p = *rootp) == NULL) )
+    return NULL;
 
-	while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
-		p = *rootp;
-		rootp = (cmp < 0) ?
-		    &(*rootp)->llink :		/* follow llink branch */
-		    &(*rootp)->rlink;		/* follow rlink branch */
-		if (*rootp == NULL)
-			return NULL;		/* key not found */
-	}
-	r = (*rootp)->rlink;			/* D1: */
-	if ((q = (*rootp)->llink) == NULL)	/* Left NULL? */
-		q = r;
-	else if (r != NULL) {			/* Right link is NULL? */
-		if (r->llink == NULL) {		/* D2: Find successor */
-			r->llink = q;
-			q = r;
-		} else {			/* D3: Find NULL link */
-			for (q = r->llink; q->llink != NULL; q = r->llink)
-				r = q;
-			r->llink = q->rlink;
-			q->llink = (*rootp)->llink;
-			q->rlink = (*rootp)->rlink;
-		}
-	}
-	free(*rootp);				/* D4: Free node */
-	*rootp = q;				/* link parent to new node */
-	return p;
+  while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0)
+  {
+    p = *rootp;
+    rootp = (cmp < 0) ?
+            &(*rootp)->llink :       /* follow llink branch */
+            &(*rootp)->rlink;        /* follow rlink branch */
+    if (*rootp == NULL)
+      return NULL;                   /* key not found */
+  }
+  r = (*rootp)->rlink;               /* D1: */
+  if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
+    q = r;
+  else if (r != NULL)                /* Right link is NULL? */
+  {
+    if (r->llink == NULL)            /* D2: Find successor */
+    {
+      r->llink = q;
+      q = r;
+    }
+    else                    /* D3: Find NULL link */
+    {
+      for (q = r->llink; q->llink != NULL; q = r->llink)
+        r = q;
+      r->llink = q->rlink;
+      q->llink = (*rootp)->llink;
+      q->rlink = (*rootp)->rlink;
+    }
+  }
+  free (*rootp);            /* D4: Free node */
+  *rootp = q;               /* link parent to new node */
+  return p;
 }
 
+
 /* end of tsearch.c */
diff --git a/src/microhttpd/tsearch.h b/src/microhttpd/tsearch.h
index ec9c92d..c6d873b 100644
--- a/src/microhttpd/tsearch.h
+++ b/src/microhttpd/tsearch.h
@@ -3,48 +3,27 @@
  * Public domain.
  *
  *	$NetBSD: search.h,v 1.12 1999/02/22 10:34:28 christos Exp $
- * $FreeBSD: release/9.0.0/include/search.h 105250 2002-10-16 14:29:23Z robert $
  */
 
-#ifndef _SEARCH_H_
-#define _SEARCH_H_
+#ifndef _TSEARCH_H_
+#define _TSEARCH_H_
 
-#ifndef _MSC_FULL_VER
-#include <sys/cdefs.h>
-#endif  /* _MSC_FULL_VER */
-#if !defined(__BEGIN_DECLS) || !defined(__END_DECLS)
-#if defined(__cplusplus)
-#define	__BEGIN_DECLS	extern "C" {
-#define	__END_DECLS	};
-#else  /* !__cplusplus */
-#define	__BEGIN_DECLS
-#define	__END_DECLS
-#endif /* !__cplusplus */
-#endif /* !__BEGIN_DECLS || !__END_DECLS */
-#include <sys/types.h>
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
 
-typedef	enum {
-	preorder,
-	postorder,
-	endorder,
-	leaf
-} VISIT;
+void    *tdelete (const void *, void **,
+                  int (*)(const void *, const void *));
 
-#ifdef _SEARCH_PRIVATE
-typedef	struct node {
-	char         *key;
-	struct node  *llink, *rlink;
-} node_t;
-#endif
+void    *tfind (const void *, void * const *,
+                int (*)(const void *, const void *));
 
-__BEGIN_DECLS
-void	*tdelete(const void * __restrict, void ** __restrict,
-	    int (*)(const void *, const void *));
-void	*tfind(const void *, void * const *,
-	    int (*)(const void *, const void *));
-void	*tsearch(const void *, void **, int (*)(const void *, const void *));
-void	 twalk(const void *, void (*)(const void *, VISIT, int));
-void	 tdestroy(void *, void (*)(void *));
-__END_DECLS
+void    *tsearch (const void *, void **,
+                  int (*)(const void *, const void *));
 
-#endif /* !_SEARCH_H_ */
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* !_TSEARCH_H_ */
diff --git a/src/microhttpd_ws/Makefile.am b/src/microhttpd_ws/Makefile.am
new file mode 100644
index 0000000..3ce8a9f
--- /dev/null
+++ b/src/microhttpd_ws/Makefile.am
@@ -0,0 +1,43 @@
+# This Makefile.am is in the public domain
+AM_CPPFLAGS = \
+  -I$(top_srcdir)/src/include \
+  -I$(top_srcdir)/src/microhttpd
+
+AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS)
+
+$(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile
+	@echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \
+	$(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la
+
+noinst_DATA =
+MOSTLYCLEANFILES =
+
+SUBDIRS = .
+
+lib_LTLIBRARIES = \
+  libmicrohttpd_ws.la
+libmicrohttpd_ws_la_SOURCES = \
+  sha1.c sha1.h \
+  mhd_websocket.c
+libmicrohttpd_ws_la_CPPFLAGS = \
+  $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) \
+  -DBUILDING_MHD_LIB=1
+libmicrohttpd_ws_la_CFLAGS = \
+  $(AM_CFLAGS) $(MHD_LIB_CFLAGS)
+libmicrohttpd_ws_la_LDFLAGS = \
+  $(MHD_LIB_LDFLAGS) \
+  $(W32_MHD_LIB_LDFLAGS) \
+  -version-info 0:0:0
+libmicrohttpd_ws_la_LIBADD = \
+  $(MHD_LIBDEPS)
+
+TESTS = $(check_PROGRAMS)
+
+check_PROGRAMS = \
+  test_websocket
+
+test_websocket_SOURCES = \
+  test_websocket.c
+test_websocket_LDADD = \
+  $(top_builddir)/src/microhttpd_ws/libmicrohttpd_ws.la \
+  $(top_builddir)/src/microhttpd/libmicrohttpd.la
diff --git a/src/microhttpd_ws/mhd_websocket.c b/src/microhttpd_ws/mhd_websocket.c
new file mode 100644
index 0000000..935deee
--- /dev/null
+++ b/src/microhttpd_ws/mhd_websocket.c
@@ -0,0 +1,2443 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2021 David Gausmann
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+*/
+
+/**
+ * @file microhttpd_ws/mhd_websocket.c
+ * @brief  Support for the websocket protocol
+ * @author David Gausmann
+ */
+#include "platform.h"
+#include "microhttpd.h"
+#include "microhttpd_ws.h"
+#include "sha1.h"
+
+struct MHD_WebSocketStream
+{
+  /* The function pointer to malloc for payload (can be used to use different memory management) */
+  MHD_WebSocketMallocCallback malloc;
+  /* The function pointer to realloc for payload (can be used to use different memory management) */
+  MHD_WebSocketReallocCallback realloc;
+  /* The function pointer to free for payload (can be used to use different memory management) */
+  MHD_WebSocketFreeCallback free;
+  /* A closure for the random number generator (only used for client mode; usually not required) */
+  void *cls_rng;
+  /* The random number generator (only used for client mode; usually not required) */
+  MHD_WebSocketRandomNumberGenerator rng;
+  /* The flags specified upon initialization. It may alter the behavior of decoding/encoding */
+  int flags;
+  /* The current step for the decoder. 0 means start of a frame. */
+  char decode_step;
+  /* Specifies whether the stream is valid (1) or not (0),
+     if a close frame has been received this is (-1) to indicate that no data frames are allowed anymore  */
+  char validity;
+  /* The current step of the UTF-8 encoding check in the data payload */
+  char data_utf8_step;
+  /* The current step of the UTF-8 encoding check in the control payload */
+  char control_utf8_step;
+  /* if != 0 means that we expect a CONTINUATION frame */
+  char data_type;
+  /* The start of the current frame (may differ from data_payload for CONTINUATION frames) */
+  char *data_payload_start;
+  /* The buffer for the data frame */
+  char *data_payload;
+  /* The buffer for the control frame */
+  char *control_payload;
+  /* Configuration for the maximum allowed buffer size for payload data */
+  size_t max_payload_size;
+  /* The current frame header size */
+  size_t frame_header_size;
+  /* The current data payload size (can be greater than payload_size for fragmented frames) */
+  size_t data_payload_size;
+  /* The size of the payload of the current frame (control or data) */
+  size_t payload_size;
+  /* The processing offset to the start of the payload of the current frame (control or data) */
+  size_t payload_index;
+  /* The frame header of the current frame (control or data) */
+  char frame_header[32];
+  /* The mask key of the current frame (control or data); this is 0 if no masking used */
+  char mask_key[4];
+};
+
+#define MHD_WEBSOCKET_FLAG_MASK_SERVERCLIENT          MHD_WEBSOCKET_FLAG_CLIENT
+#define MHD_WEBSOCKET_FLAG_MASK_FRAGMENTATION         \
+  MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS
+#define MHD_WEBSOCKET_FLAG_MASK_GENERATE_CLOSE_FRAMES \
+  MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR
+#define MHD_WEBSOCKET_FLAG_MASK_ALL                   \
+  (MHD_WEBSOCKET_FLAG_MASK_SERVERCLIENT                                                       \
+   | MHD_WEBSOCKET_FLAG_MASK_FRAGMENTATION   \
+   | MHD_WEBSOCKET_FLAG_MASK_GENERATE_CLOSE_FRAMES)
+
+enum MHD_WebSocket_Opcode
+{
+  MHD_WebSocket_Opcode_Continuation = 0x0,
+  MHD_WebSocket_Opcode_Text         = 0x1,
+  MHD_WebSocket_Opcode_Binary       = 0x2,
+  MHD_WebSocket_Opcode_Close        = 0x8,
+  MHD_WebSocket_Opcode_Ping         = 0x9,
+  MHD_WebSocket_Opcode_Pong         = 0xA
+};
+
+enum MHD_WebSocket_DecodeStep
+{
+  MHD_WebSocket_DecodeStep_Start                 =  0,
+  MHD_WebSocket_DecodeStep_Length1ofX            =  1,
+  MHD_WebSocket_DecodeStep_Length1of2            =  2,
+  MHD_WebSocket_DecodeStep_Length2of2            =  3,
+  MHD_WebSocket_DecodeStep_Length1of8            =  4,
+  MHD_WebSocket_DecodeStep_Length2of8            =  5,
+  MHD_WebSocket_DecodeStep_Length3of8            =  6,
+  MHD_WebSocket_DecodeStep_Length4of8            =  7,
+  MHD_WebSocket_DecodeStep_Length5of8            =  8,
+  MHD_WebSocket_DecodeStep_Length6of8            =  9,
+  MHD_WebSocket_DecodeStep_Length7of8            = 10,
+  MHD_WebSocket_DecodeStep_Length8of8            = 11,
+  MHD_WebSocket_DecodeStep_Mask1Of4              = 12,
+  MHD_WebSocket_DecodeStep_Mask2Of4              = 13,
+  MHD_WebSocket_DecodeStep_Mask3Of4              = 14,
+  MHD_WebSocket_DecodeStep_Mask4Of4              = 15,
+  MHD_WebSocket_DecodeStep_HeaderCompleted       = 16,
+  MHD_WebSocket_DecodeStep_PayloadOfDataFrame    = 17,
+  MHD_WebSocket_DecodeStep_PayloadOfControlFrame = 18,
+  MHD_WebSocket_DecodeStep_BrokenStream          = 99
+};
+
+enum MHD_WebSocket_UTF8Result
+{
+  MHD_WebSocket_UTF8Result_Invalid    = 0,
+  MHD_WebSocket_UTF8Result_Valid      = 1,
+  MHD_WebSocket_UTF8Result_Incomplete = 2
+};
+
+static void
+MHD_websocket_copy_payload (char *dst,
+                            const char *src,
+                            size_t len,
+                            uint32_t mask,
+                            unsigned long mask_offset);
+
+static int
+MHD_websocket_check_utf8 (const char *buf,
+                          size_t buf_len,
+                          int *utf8_step,
+                          size_t *buf_offset);
+
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_decode_header_complete (struct MHD_WebSocketStream *ws,
+                                      char **payload,
+                                      size_t *payload_len);
+
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_decode_payload_complete (struct MHD_WebSocketStream *ws,
+                                       char **payload,
+                                       size_t *payload_len);
+
+static char
+MHD_websocket_encode_is_masked (struct MHD_WebSocketStream *ws);
+static char
+MHD_websocket_encode_overhead_size (struct MHD_WebSocketStream *ws,
+                                    size_t payload_len);
+
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_data (struct MHD_WebSocketStream *ws,
+                           const char *payload,
+                           size_t payload_len,
+                           int fragmentation,
+                           char **frame,
+                           size_t *frame_len,
+                           char opcode);
+
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_ping_pong (struct MHD_WebSocketStream *ws,
+                                const char *payload,
+                                size_t payload_len,
+                                char **frame,
+                                size_t *frame_len,
+                                char opcode);
+
+static uint32_t
+MHD_websocket_generate_mask (struct MHD_WebSocketStream *ws);
+
+static uint16_t
+MHD_htons (uint16_t value);
+
+static uint64_t
+MHD_htonll (uint64_t value);
+
+
+/**
+ * Checks whether the HTTP version is 1.1 or above.
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_http_version (const char *http_version)
+{
+  /* validate parameters */
+  if (NULL == http_version)
+  {
+    /* Like with the other check routines, */
+    /* NULL is threated as "value not given" and not as parameter error */
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+
+  /* Check whether the version has a valid format */
+  /* RFC 1945 3.1: The format must be "HTTP/x.x" where x is */
+  /* any digit and must appear at least once */
+  if (('H' != http_version[0]) ||
+      ('T' != http_version[1]) ||
+      ('T' != http_version[2]) ||
+      ('P' != http_version[3]) ||
+      ('/' != http_version[4]))
+  {
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+
+  /* Find the major and minor part of the version */
+  /* RFC 1945 3.1: Both numbers must be threated as separate integers. */
+  /* Leading zeros must be ignored and both integers may have multiple digits */
+  const char *major = NULL;
+  const char *dot   = NULL;
+  size_t i = 5;
+  for (;;)
+  {
+    char c = http_version[i];
+    if (('0' <= c) && ('9' >= c))
+    {
+      if ((NULL == major) ||
+          ((http_version + i == major + 1) && ('0' == *major)) )
+      {
+        major = http_version + i;
+      }
+      ++i;
+    }
+    else if ('.' == http_version[i])
+    {
+      dot = http_version + i;
+      ++i;
+      break;
+    }
+    else
+    {
+      return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+    }
+  }
+  const char *minor = NULL;
+  const char *end   = NULL;
+  for (;;)
+  {
+    char c = http_version[i];
+    if (('0' <= c) && ('9' >= c))
+    {
+      if ((NULL == minor) ||
+          ((http_version + i == minor + 1) && ('0' == *minor)) )
+      {
+        minor = http_version + i;
+      }
+      ++i;
+    }
+    else if (0 == c)
+    {
+      end = http_version + i;
+      break;
+    }
+    else
+    {
+      return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+    }
+  }
+  if ((NULL == major) || (NULL == dot) || (NULL == minor) || (NULL == end))
+  {
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+  if ((2 <= dot - major) || ('2' <= *major) ||
+      (('1' == *major) && ((2 <= end - minor) || ('1' <= *minor))) )
+  {
+    return MHD_WEBSOCKET_STATUS_OK;
+  }
+
+  return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+}
+
+
+/**
+ * Checks whether the "Connection" request header has the 'Upgrade' token.
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_connection_header (const char *connection_header)
+{
+  /* validate parameters */
+  if (NULL == connection_header)
+  {
+    /* To be compatible with the return value */
+    /* of MHD_lookup_connection_value, */
+    /* NULL is threated as "value not given" and not as parameter error */
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+
+  /* Check whether the Connection includes an Upgrade token */
+  /* RFC 7230 6.1: Multiple tokens may appear. */
+  /* RFC 7230 3.2.6: Tokens are comma separated */
+  const char *token_start = NULL;
+  const char *token_end   = NULL;
+  for (size_t i = 0; ; ++i)
+  {
+    char c = connection_header[i];
+
+    /* RFC 7230 3.2.6: The list of allowed characters is a token is: */
+    /* "!" / "#" / "$" / "%" / "&" / "'" / "*" / */
+    /* "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" */
+    /* DIGIT / ALPHA */
+    if (('!' == c) || ('#' == c) || ('$' == c) || ('%' == c) ||
+        ('&' == c) || ('\'' == c) || ('*' == c) ||
+        ('+' == c) || ('-' == c) || ('.' == c) || ('^' == c) ||
+        ('_' == c) || ('`' == c) || ('|' == c) || ('~' == c) ||
+        (('0' <= c) && ('9' >= c)) ||
+        (('A' <= c) && ('Z' >= c)) || (('a' <= c) && ('z' >= c)) )
+    {
+      /* This is a valid token character */
+      if (NULL == token_start)
+      {
+        token_start = connection_header + i;
+      }
+      token_end = connection_header + i + 1;
+    }
+    else if ((' ' == c) || ('\t' == c))
+    {
+      /* White-spaces around tokens will be ignored */
+    }
+    else if ((',' == c) || (0 == c))
+    {
+      /* Check the token (case-insensitive) */
+      if (NULL != token_start)
+      {
+        if (7 == (token_end - token_start) )
+        {
+          if ( (('U' == token_start[0]) || ('u' == token_start[0])) &&
+               (('P' == token_start[1]) || ('p' == token_start[1])) &&
+               (('G' == token_start[2]) || ('g' == token_start[2])) &&
+               (('R' == token_start[3]) || ('r' == token_start[3])) &&
+               (('A' == token_start[4]) || ('a' == token_start[4])) &&
+               (('D' == token_start[5]) || ('d' == token_start[5])) &&
+               (('E' == token_start[6]) || ('e' == token_start[6])) )
+          {
+            /* The token equals to "Upgrade" */
+            return MHD_WEBSOCKET_STATUS_OK;
+          }
+        }
+      }
+      if (0 == c)
+      {
+        break;
+      }
+      token_start = NULL;
+      token_end   = NULL;
+    }
+    else
+    {
+      /* RFC 7230 3.2.6: Other characters are not allowed */
+      return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+    }
+  }
+  return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+}
+
+
+/**
+ * Checks whether the "Upgrade" request header has the "websocket" keyword.
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_upgrade_header (const char *upgrade_header)
+{
+  /* validate parameters */
+  if (NULL == upgrade_header)
+  {
+    /* To be compatible with the return value */
+    /* of MHD_lookup_connection_value, */
+    /* NULL is threated as "value not given" and not as parameter error */
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+
+  /* Check whether the Connection includes an Upgrade token */
+  /* RFC 7230 6.1: Multiple tokens may appear. */
+  /* RFC 7230 3.2.6: Tokens are comma separated */
+  const char *keyword_start = NULL;
+  const char *keyword_end   = NULL;
+  for (size_t i = 0; ; ++i)
+  {
+    char c = upgrade_header[i];
+
+    /* RFC 7230 3.2.6: The list of allowed characters is a token is: */
+    /* "!" / "#" / "$" / "%" / "&" / "'" / "*" / */
+    /* "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" */
+    /* DIGIT / ALPHA */
+    /* We also allow "/" here as the sub-delimiter for the protocol version */
+    if (('!' == c) || ('#' == c) || ('$' == c) || ('%' == c) ||
+        ('&' == c) || ('\'' == c) || ('*' == c) ||
+        ('+' == c) || ('-' == c) || ('.' == c) || ('^' == c) ||
+        ('_' == c) || ('`' == c) || ('|' == c) || ('~' == c) ||
+        ('/' == c) ||
+        (('0' <= c) && ('9' >= c)) ||
+        (('A' <= c) && ('Z' >= c)) || (('a' <= c) && ('z' >= c)) )
+    {
+      /* This is a valid token character */
+      if (NULL == keyword_start)
+      {
+        keyword_start = upgrade_header + i;
+      }
+      keyword_end = upgrade_header + i + 1;
+    }
+    else if ((' ' == c) || ('\t' == c))
+    {
+      /* White-spaces around tokens will be ignored */
+    }
+    else if ((',' == c) || (0 == c))
+    {
+      /* Check the token (case-insensitive) */
+      if (NULL != keyword_start)
+      {
+        if (9 == (keyword_end - keyword_start) )
+        {
+          if ( (('W' == keyword_start[0]) || ('w' == keyword_start[0])) &&
+               (('E' == keyword_start[1]) || ('e' == keyword_start[1])) &&
+               (('B' == keyword_start[2]) || ('b' == keyword_start[2])) &&
+               (('S' == keyword_start[3]) || ('s' == keyword_start[3])) &&
+               (('O' == keyword_start[4]) || ('o' == keyword_start[4])) &&
+               (('C' == keyword_start[5]) || ('c' == keyword_start[5])) &&
+               (('K' == keyword_start[6]) || ('k' == keyword_start[6])) &&
+               (('E' == keyword_start[7]) || ('e' == keyword_start[7])) &&
+               (('T' == keyword_start[8]) || ('t' == keyword_start[8])) )
+          {
+            /* The keyword equals to "websocket" */
+            return MHD_WEBSOCKET_STATUS_OK;
+          }
+        }
+      }
+      if (0 == c)
+      {
+        break;
+      }
+      keyword_start = NULL;
+      keyword_end   = NULL;
+    }
+    else
+    {
+      /* RFC 7230 3.2.6: Other characters are not allowed */
+      return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+    }
+  }
+  return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+}
+
+
+/**
+ * Checks whether the "Sec-WebSocket-Version" request header
+ * equals to "13"
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_check_version_header (const char *version_header)
+{
+  /* validate parameters */
+  if (NULL == version_header)
+  {
+    /* To be compatible with the return value */
+    /* of MHD_lookup_connection_value, */
+    /* NULL is threated as "value not given" and not as parameter error */
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+
+  if (('1' == version_header[0]) &&
+      ('3' == version_header[1]) &&
+      (0   == version_header[2]))
+  {
+    /* The version equals to "13" */
+    return MHD_WEBSOCKET_STATUS_OK;
+  }
+  return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+}
+
+
+/**
+ * Creates the response for the Sec-WebSocket-Accept header
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_create_accept_header (const char *sec_websocket_key,
+                                    char *sec_websocket_accept)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != sec_websocket_accept)
+    *sec_websocket_accept = 0;
+
+  /* validate parameters */
+  if (NULL == sec_websocket_accept)
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+  if (NULL == sec_websocket_key)
+  {
+    /* NULL is not a parameter error, */
+    /* because MHD_lookup_connection_value returns NULL */
+    /* if the header wasn't found */
+    return MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER;
+  }
+
+  /* build SHA1 hash of the given key and the UUID appended */
+  char sha1[20];
+  const char *suffix = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+  int length = (int) strlen (sec_websocket_key);
+  struct sha1_ctx ctx;
+  MHD_SHA1_init (&ctx);
+  MHD_SHA1_update (&ctx, (const uint8_t *) sec_websocket_key, length);
+  MHD_SHA1_update (&ctx, (const uint8_t *) suffix, 36);
+  MHD_SHA1_finish (&ctx, (uint8_t *) sha1);
+
+  /* base64 encode that SHA1 hash */
+  /* (simple algorithm here; SHA1 has always 20 bytes, */
+  /* which will always result in a 28 bytes base64 hash) */
+  const char *base64_encoding_table =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+  for (int i = 0, j = 0; i < 20;)
+  {
+    uint32_t octet_a = i < 20 ? (unsigned char) sha1[i++] : 0;
+    uint32_t octet_b = i < 20 ? (unsigned char) sha1[i++] : 0;
+    uint32_t octet_c = i < 20 ? (unsigned char) sha1[i++] : 0;
+    uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
+
+    sec_websocket_accept[j++] = base64_encoding_table[(triple >> 3 * 6) & 0x3F];
+    sec_websocket_accept[j++] = base64_encoding_table[(triple >> 2 * 6) & 0x3F];
+    sec_websocket_accept[j++] = base64_encoding_table[(triple >> 1 * 6) & 0x3F];
+    sec_websocket_accept[j++] = base64_encoding_table[(triple >> 0 * 6) & 0x3F];
+
+  }
+  sec_websocket_accept[27] = '=';
+  sec_websocket_accept[28] = 0;
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Initializes a new websocket stream
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_init (struct MHD_WebSocketStream **ws,
+                           int flags,
+                           size_t max_payload_size)
+{
+  return MHD_websocket_stream_init2 (ws,
+                                     flags,
+                                     max_payload_size,
+                                     malloc,
+                                     realloc,
+                                     free,
+                                     NULL,
+                                     NULL);
+}
+
+
+/**
+ * Initializes a new websocket stream with
+ * additional parameters for allocation functions
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_init2 (struct MHD_WebSocketStream **ws,
+                            int flags,
+                            size_t max_payload_size,
+                            MHD_WebSocketMallocCallback callback_malloc,
+                            MHD_WebSocketReallocCallback callback_realloc,
+                            MHD_WebSocketFreeCallback callback_free,
+                            void *cls_rng,
+                            MHD_WebSocketRandomNumberGenerator callback_rng)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != ws)
+    *ws = NULL;
+
+  /* validate parameters */
+  if ((NULL == ws) ||
+      (0 != (flags & ~MHD_WEBSOCKET_FLAG_MASK_ALL)) ||
+      ((uint64_t) 0x7FFFFFFFFFFFFFFF < max_payload_size) ||
+      (NULL == callback_malloc) ||
+      (NULL == callback_realloc) ||
+      (NULL == callback_free) ||
+      ((0 != (flags & MHD_WEBSOCKET_FLAG_CLIENT)) &&
+       (NULL == callback_rng)))
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  /* allocate stream */
+  struct MHD_WebSocketStream *ws_ = (struct MHD_WebSocketStream *) malloc (
+    sizeof (struct MHD_WebSocketStream));
+  if (NULL == ws_)
+    return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+
+  /* initialize stream */
+  memset (ws_, 0, sizeof (struct MHD_WebSocketStream));
+  ws_->flags   = flags;
+  ws_->max_payload_size = max_payload_size;
+  ws_->malloc   = callback_malloc;
+  ws_->realloc  = callback_realloc;
+  ws_->free     = callback_free;
+  ws_->cls_rng  = cls_rng;
+  ws_->rng      = callback_rng;
+  ws_->validity = MHD_WEBSOCKET_VALIDITY_VALID;
+
+  /* return stream */
+  *ws = ws_;
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Frees a previously allocated websocket stream
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_free (struct MHD_WebSocketStream *ws)
+{
+  /* validate parameters */
+  if (NULL == ws)
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+
+  /* free allocated payload data */
+  if (ws->data_payload)
+    ws->free (ws->data_payload);
+  if (ws->control_payload)
+    ws->free (ws->control_payload);
+
+  /* free the stream */
+  free (ws);
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Invalidates a websocket stream (no more decoding possible)
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_stream_invalidate (struct MHD_WebSocketStream *ws)
+{
+  /* validate parameters */
+  if (NULL == ws)
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+
+  /* invalidate stream */
+  ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Returns whether a websocket stream is valid
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_VALIDITY
+MHD_websocket_stream_is_valid (struct MHD_WebSocketStream *ws)
+{
+  /* validate parameters */
+  if (NULL == ws)
+    return MHD_WEBSOCKET_VALIDITY_INVALID;
+
+  return ws->validity;
+}
+
+
+/**
+ * Decodes incoming data to a websocket frame
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_decode (struct MHD_WebSocketStream *ws,
+                      const char *streambuf,
+                      size_t streambuf_len,
+                      size_t *streambuf_read_len,
+                      char **payload,
+                      size_t *payload_len)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != streambuf_read_len)
+    *streambuf_read_len = 0;
+  if (NULL != payload)
+    *payload = NULL;
+  if (NULL != payload_len)
+    *payload_len = 0;
+
+  /* validate parameters */
+  if ((NULL == ws) ||
+      ((NULL == streambuf) && (0 != streambuf_len)) ||
+      (NULL == streambuf_read_len) ||
+      (NULL == payload) ||
+      (NULL == payload_len) )
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  /* validate stream validity */
+  if (MHD_WEBSOCKET_VALIDITY_INVALID == ws->validity)
+    return MHD_WEBSOCKET_STATUS_STREAM_BROKEN;
+
+  /* decode loop */
+  size_t current = 0;
+  while (current < streambuf_len)
+  {
+    switch (ws->decode_step)
+    {
+    /* start of frame */
+    case MHD_WebSocket_DecodeStep_Start:
+      {
+        /* The first byte contains the opcode, the fin flag and three reserved bits */
+        if (MHD_WEBSOCKET_VALIDITY_INVALID != ws->validity)
+        {
+          char opcode = streambuf [current];
+          if (0 != (opcode & 0x70))
+          {
+            /* RFC 6455 5.2 RSV1-3: If a reserved flag is set */
+            /* (while it isn't specified by an extension) the communication must fail. */
+            ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+            if (0 != (ws->flags
+                      & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+            {
+              MHD_websocket_encode_close (ws,
+                                          MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                          0,
+                                          0,
+                                          payload,
+                                          payload_len);
+            }
+            *streambuf_read_len = current;
+            return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+          }
+          switch (opcode & 0x0F)
+          {
+          case MHD_WebSocket_Opcode_Continuation:
+            if (0 == ws->data_type)
+            {
+              /* RFC 6455 5.4: Continuation frame without previous data frame */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+            if (MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES ==
+                ws->validity)
+            {
+              /* RFC 6455 5.5.1: After a close frame has been sent, */
+              /* no data frames may be sent (so we don't accept data frames */
+              /* for decoding anymore) */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+            break;
+
+          case MHD_WebSocket_Opcode_Text:
+          case MHD_WebSocket_Opcode_Binary:
+            if (0 != ws->data_type)
+            {
+              /* RFC 6455 5.4: Continuation expected, but new data frame */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+            if (MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES ==
+                ws->validity)
+            {
+              /* RFC 6455 5.5.1: After a close frame has been sent, */
+              /* no data frames may be sent (so we don't accept data frames */
+              /* for decoding anymore) */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+            break;
+
+          case MHD_WebSocket_Opcode_Close:
+          case MHD_WebSocket_Opcode_Ping:
+          case MHD_WebSocket_Opcode_Pong:
+            if ((opcode & 0x80) == 0)
+            {
+              /* RFC 6455 5.4: Control frames may not be fragmented */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+            if (MHD_WebSocket_Opcode_Close == (opcode & 0x0F))
+            {
+              /* RFC 6455 5.5.1: After a close frame has been sent, */
+              /* no data frames may be sent (so we don't accept data frames */
+              /* for decoding anymore) */
+              ws->validity =
+                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES;
+            }
+            break;
+
+          default:
+            /* RFC 6455 5.2 OPCODE: Only six opcodes are specified. */
+            /* All other are invalid in version 13 of the protocol. */
+            ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+            if (0 != (ws->flags
+                      & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+            {
+              MHD_websocket_encode_close (ws,
+                                          MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                          0,
+                                          0,
+                                          payload,
+                                          payload_len);
+            }
+            *streambuf_read_len = current;
+            return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+          }
+        }
+        ws->frame_header [ws->frame_header_size++] = streambuf [current++];
+        ws->decode_step = MHD_WebSocket_DecodeStep_Length1ofX;
+      }
+      break;
+
+    case MHD_WebSocket_DecodeStep_Length1ofX:
+      {
+        /* The second byte specifies whether the data is masked and the size */
+        /* (the client MUST mask the payload, the server MUST NOT mask the payload) */
+        char frame_len = streambuf [current];
+        char is_masked = (frame_len & 0x80);
+        frame_len &= 0x7f;
+        if (MHD_WEBSOCKET_VALIDITY_INVALID != ws->validity)
+        {
+          if (0 != is_masked)
+          {
+            if (MHD_WEBSOCKET_FLAG_CLIENT == (ws->flags
+                                              & MHD_WEBSOCKET_FLAG_CLIENT))
+            {
+              /* RFC 6455 5.1: All frames from the server must be unmasked */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+          }
+          else
+          {
+            if (MHD_WEBSOCKET_FLAG_SERVER == (ws->flags
+                                              & MHD_WEBSOCKET_FLAG_CLIENT))
+            {
+              /* RFC 6455 5.1: All frames from the client must be masked */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+          }
+          if (126 <= frame_len)
+          {
+            if (0 != (ws->frame_header [0] & 0x08))
+            {
+              /* RFC 6455 5.5: Control frames may not have more payload than 125 bytes */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+          }
+          if (1 == frame_len)
+          {
+            if (MHD_WebSocket_Opcode_Close == (ws->frame_header [0] & 0x0F))
+            {
+              /* RFC 6455 5.5.1: The close frame must have at least */
+              /* two bytes of payload if payload is used */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current;
+              return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+            }
+          }
+        }
+        ws->frame_header [ws->frame_header_size++] = streambuf [current++];
+
+        if (126 == frame_len)
+        {
+          ws->decode_step = MHD_WebSocket_DecodeStep_Length1of2;
+        }
+        else if (127 == frame_len)
+        {
+          ws->decode_step = MHD_WebSocket_DecodeStep_Length1of8;
+        }
+        else
+        {
+          size_t size = (size_t) frame_len;
+          if ((SIZE_MAX < size) ||
+              (ws->max_payload_size && (ws->max_payload_size < size)) )
+          {
+            /* RFC 6455 7.4.1 1009: If the message is too big to process, we may close the connection */
+            ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+            if (0 != (ws->flags
+                      & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+            {
+              MHD_websocket_encode_close (ws,
+                                          MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED,
+                                          0,
+                                          0,
+                                          payload,
+                                          payload_len);
+            }
+            *streambuf_read_len = current;
+            return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+          }
+          ws->payload_size = size;
+          if (0 != is_masked)
+          {
+            /* with mask */
+            ws->decode_step = MHD_WebSocket_DecodeStep_Mask1Of4;
+          }
+          else
+          {
+            /* without mask */
+            *((uint32_t *) ws->mask_key) = 0;
+            ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted;
+          }
+        }
+      }
+      break;
+
+    /* Payload size first byte of 2 bytes */
+    case MHD_WebSocket_DecodeStep_Length1of2:
+    /* Payload size first 7 bytes of 8 bytes */
+    case MHD_WebSocket_DecodeStep_Length1of8:
+    case MHD_WebSocket_DecodeStep_Length2of8:
+    case MHD_WebSocket_DecodeStep_Length3of8:
+    case MHD_WebSocket_DecodeStep_Length4of8:
+    case MHD_WebSocket_DecodeStep_Length5of8:
+    case MHD_WebSocket_DecodeStep_Length6of8:
+    case MHD_WebSocket_DecodeStep_Length7of8:
+    /* Mask first 3 bytes of 4 bytes */
+    case MHD_WebSocket_DecodeStep_Mask1Of4:
+    case MHD_WebSocket_DecodeStep_Mask2Of4:
+    case MHD_WebSocket_DecodeStep_Mask3Of4:
+      ws->frame_header [ws->frame_header_size++] = streambuf [current++];
+      ++ws->decode_step;
+      break;
+
+    /* 2 byte length finished */
+    case MHD_WebSocket_DecodeStep_Length2of2:
+      {
+        ws->frame_header [ws->frame_header_size++] = streambuf [current++];
+        size_t size = (size_t) MHD_htons (
+          *((uint16_t *) &ws->frame_header [2]));
+        if (125 >= size)
+        {
+          /* RFC 6455 5.2 Payload length: The minimal number of bytes */
+          /* must be used for the length */
+          ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+          if (0 != (ws->flags
+                    & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+          {
+            MHD_websocket_encode_close (ws,
+                                        MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                        0,
+                                        0,
+                                        payload,
+                                        payload_len);
+          }
+          *streambuf_read_len = current;
+          return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+        }
+        if ((SIZE_MAX < size) ||
+            (ws->max_payload_size && (ws->max_payload_size < size)) )
+        {
+          /* RFC 6455 7.4.1 1009: If the message is too big to process, */
+          /* we may close the connection */
+          ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+          if (0 != (ws->flags
+                    & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+          {
+            MHD_websocket_encode_close (ws,
+                                        MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED,
+                                        0,
+                                        0,
+                                        payload,
+                                        payload_len);
+          }
+          *streambuf_read_len = current;
+          return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+        }
+        ws->payload_size = size;
+        if (0 != (ws->frame_header [1] & 0x80))
+        {
+          /* with mask */
+          ws->decode_step = MHD_WebSocket_DecodeStep_Mask1Of4;
+        }
+        else
+        {
+          /* without mask */
+          *((uint32_t *) ws->mask_key) = 0;
+          ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted;
+        }
+      }
+      break;
+
+    /* 8 byte length finished */
+    case MHD_WebSocket_DecodeStep_Length8of8:
+      {
+        ws->frame_header [ws->frame_header_size++] = streambuf [current++];
+        uint64_t size = MHD_htonll (*((uint64_t *) &ws->frame_header [2]));
+        if (0x7fffffffffffffff < size)
+        {
+          /* RFC 6455 5.2 frame-payload-length-63: The length may */
+          /* not exceed 0x7fffffffffffffff */
+          ws->decode_step = MHD_WebSocket_DecodeStep_BrokenStream;
+          ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+          if (0 != (ws->flags
+                    & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+          {
+            MHD_websocket_encode_close (ws,
+                                        MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                        0,
+                                        0,
+                                        payload,
+                                        payload_len);
+          }
+          *streambuf_read_len = current;
+          return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+        }
+        if (65535 >= size)
+        {
+          /* RFC 6455 5.2 Payload length: The minimal number of bytes */
+          /* must be used for the length */
+          ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+          if (0 != (ws->flags
+                    & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+          {
+            MHD_websocket_encode_close (ws,
+                                        MHD_WEBSOCKET_CLOSEREASON_PROTOCOL_ERROR,
+                                        0,
+                                        0,
+                                        payload,
+                                        payload_len);
+          }
+          *streambuf_read_len = current;
+          return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+        }
+        if ((SIZE_MAX < size) ||
+            (ws->max_payload_size && (ws->max_payload_size < size)) )
+        {
+          /* RFC 6455 7.4.1 1009: If the message is too big to process, */
+          /* we may close the connection */
+          ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+          if (0 != (ws->flags
+                    & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+          {
+            MHD_websocket_encode_close (ws,
+                                        MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED,
+                                        0,
+                                        0,
+                                        payload,
+                                        payload_len);
+          }
+          *streambuf_read_len = current;
+          return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+        }
+        ws->payload_size = (size_t) size;
+
+        if (0 != (ws->frame_header [1] & 0x80))
+        {
+          /* with mask */
+          ws->decode_step = MHD_WebSocket_DecodeStep_Mask1Of4;
+        }
+        else
+        {
+          /* without mask */
+          *((uint32_t *) ws->mask_key) = 0;
+          ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted;
+        }
+      }
+      break;
+
+    /* mask finished */
+    case MHD_WebSocket_DecodeStep_Mask4Of4:
+      ws->frame_header [ws->frame_header_size++] = streambuf [current++];
+      *((uint32_t *) ws->mask_key) = *((uint32_t *) &ws->frame_header [ws->
+                                                                       frame_header_size
+                                                                       - 4]);
+      ws->decode_step = MHD_WebSocket_DecodeStep_HeaderCompleted;
+      break;
+
+    /* header finished */
+    case MHD_WebSocket_DecodeStep_HeaderCompleted:
+      /* return or assign either to data or control */
+      {
+        int ret = MHD_websocket_decode_header_complete (ws,
+                                                        payload,
+                                                        payload_len);
+        if (MHD_WEBSOCKET_STATUS_OK != ret)
+        {
+          *streambuf_read_len = current;
+          return ret;
+        }
+      }
+      break;
+
+    /* payload data */
+    case MHD_WebSocket_DecodeStep_PayloadOfDataFrame:
+    case MHD_WebSocket_DecodeStep_PayloadOfControlFrame:
+      {
+        size_t bytes_needed    = ws->payload_size - ws->payload_index;
+        size_t bytes_remaining = streambuf_len - current;
+        size_t bytes_to_take   = bytes_needed < bytes_remaining ? bytes_needed :
+                                 bytes_remaining;
+        if (0 != bytes_to_take)
+        {
+          size_t utf8_start     = ws->payload_index;
+          char *decode_payload = ws->decode_step ==
+                                 MHD_WebSocket_DecodeStep_PayloadOfDataFrame ?
+                                 ws->data_payload_start :
+                                 ws->control_payload;
+
+          /* copy the new payload data (with unmasking if necessary */
+          MHD_websocket_copy_payload (decode_payload + ws->payload_index,
+                                      &streambuf [current],
+                                      bytes_to_take,
+                                      *((uint32_t *) ws->mask_key),
+                                      (unsigned long) (ws->payload_index
+                                                       & 0x03));
+          current += bytes_to_take;
+          ws->payload_index += bytes_to_take;
+          if (((MHD_WebSocket_DecodeStep_PayloadOfDataFrame ==
+                ws->decode_step) &&
+               (MHD_WebSocket_Opcode_Text == ws->data_type)) ||
+              ((MHD_WebSocket_DecodeStep_PayloadOfControlFrame ==
+                ws->decode_step) &&
+               (MHD_WebSocket_Opcode_Close == (ws->frame_header [0] & 0x0f)) &&
+               (2 < ws->payload_index)) )
+          {
+            /* RFC 6455 8.1: We need to check the UTF-8 validity */
+            int utf8_step;
+            char *decode_payload_utf8;
+            size_t bytes_to_check;
+            size_t utf8_error_offset = 0;
+            if (MHD_WebSocket_DecodeStep_PayloadOfDataFrame == ws->decode_step)
+            {
+              utf8_step           = ws->data_utf8_step;
+              decode_payload_utf8 = decode_payload + utf8_start;
+              bytes_to_check      = bytes_to_take;
+            }
+            else
+            {
+              utf8_step = ws->control_utf8_step;
+              if ((MHD_WebSocket_Opcode_Close == (ws->frame_header [0]
+                                                  & 0x0f)) &&
+                  (2 > utf8_start) )
+              {
+                /* The first two bytes of the close frame are binary content and */
+                /* must be skipped in the UTF-8 check */
+                utf8_start = 2;
+                utf8_error_offset = 2;
+              }
+              decode_payload_utf8 = decode_payload + utf8_start;
+              bytes_to_check      = bytes_to_take - utf8_start;
+            }
+            size_t utf8_check_offset = 0;
+            int utf8_result = MHD_websocket_check_utf8 (decode_payload_utf8,
+                                                        bytes_to_check,
+                                                        &utf8_step,
+                                                        &utf8_check_offset);
+            if (MHD_WebSocket_UTF8Result_Invalid != utf8_result)
+            {
+              /* memorize current validity check step to continue later */
+              ws->data_utf8_step = utf8_step;
+            }
+            else
+            {
+              /* RFC 6455 8.1: We must fail on broken UTF-8 sequence */
+              ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+              if (0 != (ws->flags
+                        & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+              {
+                MHD_websocket_encode_close (ws,
+                                            MHD_WEBSOCKET_CLOSEREASON_MALFORMED_UTF8,
+                                            0,
+                                            0,
+                                            payload,
+                                            payload_len);
+              }
+              *streambuf_read_len = current - bytes_to_take
+                                    + utf8_check_offset + utf8_error_offset;
+              return MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR;
+            }
+          }
+        }
+      }
+
+      if (ws->payload_size == ws->payload_index)
+      {
+        /* all payload data of the current frame has been received */
+        int ret = MHD_websocket_decode_payload_complete (ws,
+                                                         payload,
+                                                         payload_len);
+        if (MHD_WEBSOCKET_STATUS_OK != ret)
+        {
+          *streambuf_read_len = current;
+          return ret;
+        }
+      }
+      break;
+
+    case MHD_WebSocket_DecodeStep_BrokenStream:
+      *streambuf_read_len = current;
+      return MHD_WEBSOCKET_STATUS_STREAM_BROKEN;
+    }
+  }
+
+  /* Special treatment for zero payload length messages */
+  if (MHD_WebSocket_DecodeStep_HeaderCompleted == ws->decode_step)
+  {
+    int ret = MHD_websocket_decode_header_complete (ws,
+                                                    payload,
+                                                    payload_len);
+    if (MHD_WEBSOCKET_STATUS_OK != ret)
+    {
+      *streambuf_read_len = current;
+      return ret;
+    }
+  }
+  switch (ws->decode_step)
+  {
+  case MHD_WebSocket_DecodeStep_PayloadOfDataFrame:
+  case MHD_WebSocket_DecodeStep_PayloadOfControlFrame:
+    if (ws->payload_size == ws->payload_index)
+    {
+      /* all payload data of the current frame has been received */
+      int ret = MHD_websocket_decode_payload_complete (ws,
+                                                       payload,
+                                                       payload_len);
+      if (MHD_WEBSOCKET_STATUS_OK != ret)
+      {
+        *streambuf_read_len = current;
+        return ret;
+      }
+    }
+    break;
+  }
+  *streambuf_read_len = current;
+
+  /* more data needed */
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_decode_header_complete (struct MHD_WebSocketStream *ws,
+                                      char **payload,
+                                      size_t *payload_len)
+{
+  /* assign either to data or control */
+  char opcode = ws->frame_header [0] & 0x0f;
+  switch (opcode)
+  {
+  case MHD_WebSocket_Opcode_Continuation:
+    {
+      /* validate payload size */
+      size_t new_size_total = ws->payload_size + ws->data_payload_size;
+      if ((0 != ws->max_payload_size) && (ws->max_payload_size <
+                                          new_size_total) )
+      {
+        /* RFC 6455 7.4.1 1009: If the message is too big to process, */
+        /* we may close the connection */
+        ws->decode_step = MHD_WebSocket_DecodeStep_BrokenStream;
+        ws->validity = MHD_WEBSOCKET_VALIDITY_INVALID;
+        if (0 != (ws->flags
+                  & MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR))
+        {
+          MHD_websocket_encode_close (ws,
+                                      MHD_WEBSOCKET_CLOSEREASON_MAXIMUM_ALLOWED_PAYLOAD_SIZE_EXCEEDED,
+                                      0,
+                                      0,
+                                      payload,
+                                      payload_len);
+        }
+        return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+      }
+      /* allocate buffer for continued data frame */
+      char *new_buf = NULL;
+      if (0 != new_size_total)
+      {
+        new_buf = ws->realloc (ws->data_payload, new_size_total + 1);
+        if (NULL == new_buf)
+        {
+          return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+        }
+        new_buf [new_size_total] = 0;
+        ws->data_payload_start = &new_buf[ws->data_payload_size];
+      }
+      else
+      {
+        ws->data_payload_start = new_buf;
+      }
+      ws->data_payload       = new_buf;
+      ws->data_payload_size  = new_size_total;
+    }
+    ws->decode_step = MHD_WebSocket_DecodeStep_PayloadOfDataFrame;
+    break;
+
+  case MHD_WebSocket_Opcode_Text:
+  case MHD_WebSocket_Opcode_Binary:
+    /* allocate buffer for data frame */
+    {
+      size_t new_size_total = ws->payload_size;
+      char *new_buf = NULL;
+      if (0 != new_size_total)
+      {
+        new_buf = ws->malloc (new_size_total + 1);
+        if (NULL == new_buf)
+        {
+          return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+        }
+        new_buf [new_size_total] = 0;
+      }
+      ws->data_payload        = new_buf;
+      ws->data_payload_start  = new_buf;
+      ws->data_payload_size   = new_size_total;
+      ws->data_type           = opcode;
+    }
+    ws->decode_step = MHD_WebSocket_DecodeStep_PayloadOfDataFrame;
+    break;
+
+  case MHD_WebSocket_Opcode_Close:
+  case MHD_WebSocket_Opcode_Ping:
+  case MHD_WebSocket_Opcode_Pong:
+    /* allocate buffer for control frame */
+    {
+      size_t new_size_total = ws->payload_size;
+      char *new_buf = NULL;
+      if (0 != new_size_total)
+      {
+        new_buf = ws->malloc (new_size_total + 1);
+        if (NULL == new_buf)
+        {
+          return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+        }
+        new_buf[new_size_total] = 0;
+      }
+      ws->control_payload = new_buf;
+    }
+    ws->decode_step = MHD_WebSocket_DecodeStep_PayloadOfControlFrame;
+    break;
+  }
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_decode_payload_complete (struct MHD_WebSocketStream *ws,
+                                       char **payload,
+                                       size_t *payload_len)
+{
+  /* all payload data of the current frame has been received */
+  char is_continue = MHD_WebSocket_Opcode_Continuation ==
+                     (ws->frame_header [0] & 0x0F);
+  char is_fin      = ws->frame_header [0] & 0x80;
+  if (0 != is_fin)
+  {
+    /* the frame is complete */
+    if (MHD_WebSocket_DecodeStep_PayloadOfDataFrame == ws->decode_step)
+    {
+      /* data frame */
+      char data_type = ws->data_type;
+      if ((0 != (ws->flags & MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS)) &&
+          (0 != is_continue))
+      {
+        data_type |= 0x40;   /* mark as last fragment */
+      }
+      *payload     = ws->data_payload;
+      *payload_len = ws->data_payload_size;
+      ws->data_payload       = 0;
+      ws->data_payload_start = 0;
+      ws->data_payload_size  = 0;
+      ws->decode_step        = MHD_WebSocket_DecodeStep_Start;
+      ws->payload_index      = 0;
+      ws->data_type          = 0;
+      ws->frame_header_size  = 0;
+      return data_type;
+    }
+    else
+    {
+      /* control frame */
+      *payload     = ws->control_payload;
+      *payload_len = ws->payload_size;
+      ws->control_payload   = 0;
+      ws->decode_step       = MHD_WebSocket_DecodeStep_Start;
+      ws->payload_index     = 0;
+      ws->frame_header_size = 0;
+      return (ws->frame_header [0] & 0x0f);
+    }
+  }
+  else if (0 != (ws->flags & MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS))
+  {
+    /* RFC 6455 5.4: To allow streaming, the user can choose */
+    /* to return fragments */
+    if ((MHD_WebSocket_Opcode_Text == ws->data_type) &&
+        (MHD_WEBSOCKET_UTF8STEP_NORMAL != ws->data_utf8_step) )
+    {
+      /* the last UTF-8 sequence is incomplete, so we keep the start of
+      that and only return the part before */
+      size_t given_utf8 = 0;
+      switch (ws->data_utf8_step)
+      {
+      /* one byte given */
+      case MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1:
+      case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2:
+      case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2:
+      case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2:
+      case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3:
+      case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3:
+      case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3:
+        given_utf8 = 1;
+        break;
+      /* two bytes given */
+      case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2:
+      case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3:
+        given_utf8 = 2;
+        break;
+      /* three bytes given */
+      case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3:
+        given_utf8 = 3;
+        break;
+      }
+      size_t new_len = ws->data_payload_size - given_utf8;
+      if (0 != new_len)
+      {
+        char *next_payload = ws->malloc (given_utf8 + 1);
+        if (NULL == next_payload)
+        {
+          return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+        }
+        memcpy (next_payload,
+                ws->data_payload_start + ws->payload_index - given_utf8,
+                given_utf8);
+        next_payload[given_utf8] = 0;
+
+        ws->data_payload[new_len] = 0;
+        *payload     = ws->data_payload;
+        *payload_len = new_len;
+        ws->data_payload      = next_payload;
+        ws->data_payload_size = given_utf8;
+      }
+      else
+      {
+        *payload     = NULL;
+        *payload_len = 0;
+      }
+      ws->decode_step       = MHD_WebSocket_DecodeStep_Start;
+      ws->payload_index     = 0;
+      ws->frame_header_size = 0;
+      if (0 != is_continue)
+        return ws->data_type | 0x20;    /* mark as middle fragment */
+      else
+        return ws->data_type | 0x10;    /* mark as first fragment */
+    }
+    else
+    {
+      /* we simply pass the entire data frame */
+      *payload     = ws->data_payload;
+      *payload_len = ws->data_payload_size;
+      ws->data_payload       = 0;
+      ws->data_payload_start = 0;
+      ws->data_payload_size  = 0;
+      ws->decode_step        = MHD_WebSocket_DecodeStep_Start;
+      ws->payload_index      = 0;
+      ws->frame_header_size  = 0;
+      if (0 != is_continue)
+        return ws->data_type | 0x20;    /* mark as middle fragment */
+      else
+        return ws->data_type | 0x10;    /* mark as first fragment */
+    }
+  }
+  else
+  {
+    /* RFC 6455 5.4: We must await a continuation frame to get */
+    /* the remainder of this data frame */
+    ws->decode_step       = MHD_WebSocket_DecodeStep_Start;
+    ws->frame_header_size = 0;
+    ws->payload_index     = 0;
+    return MHD_WEBSOCKET_STATUS_OK;
+  }
+}
+
+
+/**
+ * Splits the received close reason
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_split_close_reason (const char *payload,
+                                  size_t payload_len,
+                                  unsigned short *reason_code,
+                                  const char **reason_utf8,
+                                  size_t *reason_utf8_len)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != reason_code)
+    *reason_code = MHD_WEBSOCKET_CLOSEREASON_NO_REASON;
+  if (NULL != reason_utf8)
+    *reason_utf8 = NULL;
+  if (NULL != reason_utf8_len)
+    *reason_utf8_len = 0;
+
+  /* validate parameters */
+  if ((NULL == payload) && (0 != payload_len))
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  if (1 == payload_len)
+    return MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR;
+  if (125 < payload_len)
+    return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+
+  /* decode reason code */
+  if (2 > payload_len)
+  {
+    if (NULL != reason_code)
+      *reason_code = MHD_WEBSOCKET_CLOSEREASON_NO_REASON;
+  }
+  else
+  {
+    if (NULL != reason_code)
+      *reason_code = MHD_htons (*((uint16_t *) payload));
+  }
+
+  /* decode reason text */
+  if (2 >= payload_len)
+  {
+    if (NULL != reason_utf8)
+      *reason_utf8 = NULL;
+    if (NULL != reason_utf8_len)
+      *reason_utf8_len = 0;
+  }
+  else
+  {
+    if (NULL != reason_utf8)
+      *reason_utf8 = payload + 2;
+    if (NULL != reason_utf8_len)
+      *reason_utf8_len = payload_len - 2;
+  }
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Encodes a text into a websocket text frame
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_text (struct MHD_WebSocketStream *ws,
+                           const char *payload_utf8,
+                           size_t payload_utf8_len,
+                           int fragmentation,
+                           char **frame,
+                           size_t *frame_len,
+                           int *utf8_step)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != frame)
+    *frame = NULL;
+  if (NULL != frame_len)
+    *frame_len = 0;
+  if ((NULL != utf8_step) &&
+      ((MHD_WEBSOCKET_FRAGMENTATION_FIRST == fragmentation) ||
+       (MHD_WEBSOCKET_FRAGMENTATION_NONE == fragmentation) ))
+  {
+    /* the old UTF-8 step will be ignored for new fragments */
+    *utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL;
+  }
+
+  /* validate parameters */
+  if ((NULL == ws) ||
+      ((0 != payload_utf8_len) && (NULL == payload_utf8)) ||
+      (NULL == frame) ||
+      (NULL == frame_len) ||
+      (MHD_WEBSOCKET_FRAGMENTATION_NONE > fragmentation) ||
+      (MHD_WEBSOCKET_FRAGMENTATION_LAST < fragmentation) ||
+      ((MHD_WEBSOCKET_FRAGMENTATION_NONE != fragmentation) &&
+       (NULL == utf8_step)) )
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  /* check max length */
+  if ((uint64_t) 0x7FFFFFFFFFFFFFFF < (uint64_t) payload_utf8_len)
+  {
+    return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+  }
+
+  /* check UTF-8 */
+  int utf8_result = MHD_websocket_check_utf8 (payload_utf8,
+                                              payload_utf8_len,
+                                              utf8_step,
+                                              NULL);
+  if ((MHD_WebSocket_UTF8Result_Invalid == utf8_result) ||
+      ((MHD_WebSocket_UTF8Result_Incomplete == utf8_result) &&
+       (MHD_WEBSOCKET_FRAGMENTATION_NONE == fragmentation)) )
+  {
+    return MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR;
+  }
+
+  /* encode data */
+  return MHD_websocket_encode_data (ws,
+                                    payload_utf8,
+                                    payload_utf8_len,
+                                    fragmentation,
+                                    frame,
+                                    frame_len,
+                                    MHD_WebSocket_Opcode_Text);
+}
+
+
+/**
+ * Encodes binary data into a websocket binary frame
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_binary (struct MHD_WebSocketStream *ws,
+                             const char *payload,
+                             size_t payload_len,
+                             int fragmentation,
+                             char **frame,
+                             size_t *frame_len)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != frame)
+    *frame = NULL;
+  if (NULL != frame_len)
+    *frame_len = 0;
+
+  /* validate parameters */
+  if ((NULL == ws) ||
+      ((0 != payload_len) && (NULL == payload)) ||
+      (NULL == frame) ||
+      (NULL == frame_len) ||
+      (MHD_WEBSOCKET_FRAGMENTATION_NONE > fragmentation) ||
+      (MHD_WEBSOCKET_FRAGMENTATION_LAST < fragmentation) )
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  /* check max length */
+  if ((uint64_t) 0x7FFFFFFFFFFFFFFF < (uint64_t) payload_len)
+  {
+    return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+  }
+
+  return MHD_websocket_encode_data (ws,
+                                    payload,
+                                    payload_len,
+                                    fragmentation,
+                                    frame,
+                                    frame_len,
+                                    MHD_WebSocket_Opcode_Binary);
+}
+
+
+/**
+ * Internal function for encoding text/binary data into a websocket frame
+ */
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_data (struct MHD_WebSocketStream *ws,
+                           const char *payload,
+                           size_t payload_len,
+                           int fragmentation,
+                           char **frame,
+                           size_t *frame_len,
+                           char opcode)
+{
+  /* calculate length and masking */
+  char is_masked      = MHD_websocket_encode_is_masked (ws);
+  size_t overhead_len = MHD_websocket_encode_overhead_size (ws, payload_len);
+  size_t total_len    = overhead_len + payload_len;
+  uint32_t mask       = 0 != is_masked ? MHD_websocket_generate_mask (ws) : 0;
+
+  /* allocate memory */
+  char *result = ws->malloc (total_len + 1);
+  if (NULL == result)
+    return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+  result [total_len] = 0;
+  *frame     = result;
+  *frame_len = total_len;
+
+  /* add the opcode */
+  switch (fragmentation)
+  {
+  case MHD_WEBSOCKET_FRAGMENTATION_NONE:
+    *(result++) = 0x80 | opcode;
+    break;
+  case MHD_WEBSOCKET_FRAGMENTATION_FIRST:
+    *(result++) = opcode;
+    break;
+  case MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING:
+    *(result++) = MHD_WebSocket_Opcode_Continuation;
+    break;
+  case MHD_WEBSOCKET_FRAGMENTATION_LAST:
+    *(result++) = 0x80 | MHD_WebSocket_Opcode_Continuation;
+    break;
+  }
+
+  /* add the length */
+  if (126 > payload_len)
+  {
+    *(result++) = is_masked | (char) payload_len;
+  }
+  else if (65536 > payload_len)
+  {
+    *(result++) = is_masked | 126;
+    *((uint16_t *) result) = MHD_htons ((uint16_t) payload_len);
+    result += 2;
+  }
+  else
+  {
+    *(result++) = is_masked | 127;
+    *((uint64_t *) result) = MHD_htonll ((uint64_t) payload_len);
+    result += 8;
+
+  }
+
+  /* add the mask */
+  if (0 != is_masked)
+  {
+    *(result++) = ((char *) &mask)[0];
+    *(result++) = ((char *) &mask)[1];
+    *(result++) = ((char *) &mask)[2];
+    *(result++) = ((char *) &mask)[3];
+  }
+
+  /* add the payload */
+  if (0 != payload_len)
+  {
+    MHD_websocket_copy_payload (result,
+                                payload,
+                                payload_len,
+                                mask,
+                                0);
+  }
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Encodes a websocket ping frame
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_ping (struct MHD_WebSocketStream *ws,
+                           const char *payload,
+                           size_t payload_len,
+                           char **frame,
+                           size_t *frame_len)
+{
+  /* encode the ping frame */
+  return MHD_websocket_encode_ping_pong (ws,
+                                         payload,
+                                         payload_len,
+                                         frame,
+                                         frame_len,
+                                         MHD_WebSocket_Opcode_Ping);
+}
+
+
+/**
+ * Encodes a websocket pong frame
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_pong (struct MHD_WebSocketStream *ws,
+                           const char *payload,
+                           size_t payload_len,
+                           char **frame,
+                           size_t *frame_len)
+{
+  /* encode the pong frame */
+  return MHD_websocket_encode_ping_pong (ws,
+                                         payload,
+                                         payload_len,
+                                         frame,
+                                         frame_len,
+                                         MHD_WebSocket_Opcode_Pong);
+}
+
+
+/**
+ * Internal function for encoding ping/pong frames
+ */
+static enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_ping_pong (struct MHD_WebSocketStream *ws,
+                                const char *payload,
+                                size_t payload_len,
+                                char **frame,
+                                size_t *frame_len,
+                                char opcode)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != frame)
+    *frame = NULL;
+  if (NULL != frame_len)
+    *frame_len = 0;
+
+  /* validate the parameters */
+  if ((NULL == ws) ||
+      ((0 != payload_len) && (NULL == payload)) ||
+      (NULL == frame) ||
+      (NULL == frame_len) )
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  /* RFC 6455 5.5: Control frames may only have up to 125 bytes of payload data */
+  if (125 < payload_len)
+    return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+
+  /* calculate length and masking */
+  char is_masked      = MHD_websocket_encode_is_masked (ws);
+  size_t overhead_len = MHD_websocket_encode_overhead_size (ws, payload_len);
+  size_t total_len    = overhead_len + payload_len;
+  uint32_t mask       = is_masked != 0 ? MHD_websocket_generate_mask (ws) : 0;
+
+  /* allocate memory */
+  char *result = ws->malloc (total_len + 1);
+  if (NULL == result)
+    return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+  result [total_len] = 0;
+  *frame     = result;
+  *frame_len = total_len;
+
+  /* add the opcode */
+  *(result++) = 0x80 | opcode;
+
+  /* add the length */
+  *(result++) = is_masked | (char) payload_len;
+
+  /* add the mask */
+  if (0 != is_masked)
+  {
+    *(result++) = ((char *) &mask)[0];
+    *(result++) = ((char *) &mask)[1];
+    *(result++) = ((char *) &mask)[2];
+    *(result++) = ((char *) &mask)[3];
+  }
+
+  /* add the payload */
+  if (0 != payload_len)
+  {
+    MHD_websocket_copy_payload (result,
+                                payload,
+                                payload_len,
+                                mask,
+                                0);
+  }
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Encodes a websocket close frame
+ */
+_MHD_EXTERN enum MHD_WEBSOCKET_STATUS
+MHD_websocket_encode_close (struct MHD_WebSocketStream *ws,
+                            unsigned short reason_code,
+                            const char *reason_utf8,
+                            size_t reason_utf8_len,
+                            char **frame,
+                            size_t *frame_len)
+{
+  /* initialize output variables for errors cases */
+  if (NULL != frame)
+    *frame = NULL;
+  if (NULL != frame_len)
+    *frame_len = 0;
+
+  /* validate the parameters */
+  if ((NULL == ws) ||
+      ((0 != reason_utf8_len) && (NULL == reason_utf8)) ||
+      (NULL == frame) ||
+      (NULL == frame_len) ||
+      ((MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) &&
+       (1000 > reason_code)) ||
+      ((0 != reason_utf8_len) &&
+       (MHD_WEBSOCKET_CLOSEREASON_NO_REASON == reason_code)) )
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  /* RFC 6455 5.5: Control frames may only have up to 125 bytes of payload data, */
+  /* but in this case only 123 bytes, because 2 bytes are reserved */
+  /* for the close reason code. */
+  if (123 < reason_utf8_len)
+    return MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED;
+
+  /* RFC 6455 5.5.1: If close payload data is given, it must be valid UTF-8 */
+  if (0 != reason_utf8_len)
+  {
+    int utf8_result = MHD_websocket_check_utf8 (reason_utf8,
+                                                reason_utf8_len,
+                                                NULL,
+                                                NULL);
+    if (MHD_WebSocket_UTF8Result_Valid != utf8_result)
+      return MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR;
+  }
+
+  /* calculate length and masking */
+  char is_masked      = MHD_websocket_encode_is_masked (ws);
+  size_t payload_len  = (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code ?
+                         2 + reason_utf8_len : 0);
+  size_t overhead_len = MHD_websocket_encode_overhead_size (ws, payload_len);
+  size_t total_len    = overhead_len + payload_len;
+  uint32_t mask       = is_masked != 0 ? MHD_websocket_generate_mask (ws) : 0;
+
+  /* allocate memory */
+  char *result = ws->malloc (total_len + 1);
+  if (NULL == result)
+    return MHD_WEBSOCKET_STATUS_MEMORY_ERROR;
+  result [total_len] = 0;
+  *frame     = result;
+  *frame_len = total_len;
+
+  /* add the opcode */
+  *(result++) = 0x88;
+
+  /* add the length */
+  *(result++) = is_masked | (char) payload_len;
+
+  /* add the mask */
+  if (0 != is_masked)
+  {
+    *(result++) = ((char *) &mask)[0];
+    *(result++) = ((char *) &mask)[1];
+    *(result++) = ((char *) &mask)[2];
+    *(result++) = ((char *) &mask)[3];
+  }
+
+  /* add the payload */
+  if (0 != reason_code)
+  {
+    /* close reason code */
+    uint16_t reason_code_nb = MHD_htons (reason_code);
+    MHD_websocket_copy_payload (result,
+                                (const char *) &reason_code_nb,
+                                2,
+                                mask,
+                                0);
+    result += 2;
+
+    /* custom reason payload */
+    if (0 != reason_utf8_len)
+    {
+      MHD_websocket_copy_payload (result,
+                                  reason_utf8,
+                                  reason_utf8_len,
+                                  mask,
+                                  2);
+    }
+  }
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Returns the 0x80 prefix for masked data, 0x00 otherwise
+ */
+static char
+MHD_websocket_encode_is_masked (struct MHD_WebSocketStream *ws)
+{
+  return (ws->flags & MHD_WEBSOCKET_FLAG_MASK_SERVERCLIENT) ==
+         MHD_WEBSOCKET_FLAG_CLIENT ? 0x80 : 0x00;
+}
+
+
+/**
+ * Calculates the size of the overhead in bytes
+ */
+static char
+MHD_websocket_encode_overhead_size (struct MHD_WebSocketStream *ws,
+                                    size_t payload_len)
+{
+  return 2 + (MHD_websocket_encode_is_masked (ws) != 0 ? 4 : 0) + (125 <
+                                                                   payload_len ?
+                                                                   (65535 <
+                                                                    payload_len
+  ? 8 : 2) : 0);
+}
+
+
+/**
+ * Copies the payload to the destination (using mask)
+ */
+static void
+MHD_websocket_copy_payload (char *dst,
+                            const char *src,
+                            size_t len,
+                            uint32_t mask,
+                            unsigned long mask_offset)
+{
+  if (0 != len)
+  {
+    if (0 == mask)
+    {
+      /* when the mask is zero, we can just copy the data */
+      memcpy (dst, src, len);
+    }
+    else
+    {
+      /* mask is used */
+      char mask_[4];
+      *((uint32_t *) mask_) = mask;
+      for (size_t i = 0; i < len; ++i)
+      {
+        dst[i] = src[i] ^ mask_[(i + mask_offset) & 3];
+      }
+    }
+  }
+}
+
+
+/**
+ * Checks a UTF-8 sequence
+ */
+static int
+MHD_websocket_check_utf8 (const char *buf,
+                          size_t buf_len,
+                          int *utf8_step,
+                          size_t *buf_offset)
+{
+  int utf8_step_ = (NULL != utf8_step) ? *utf8_step :
+                   MHD_WEBSOCKET_UTF8STEP_NORMAL;
+
+  for (size_t i = 0; i < buf_len; ++i)
+  {
+    unsigned char character = (unsigned char) buf[i];
+    switch (utf8_step_)
+    {
+    case MHD_WEBSOCKET_UTF8STEP_NORMAL:
+      if ((0x00 <= character) && (0x7F >= character))
+      {
+        /* RFC 3629 4: single byte UTF-8 sequence */
+        /* (nothing to do here) */
+      }
+      else if ((0xC2 <= character) && (0xDF >= character))
+      {
+        /* RFC 3629 4: two byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1;
+      }
+      else if (0xE0 == character)
+      {
+        /* RFC 3629 4: three byte UTF-8 sequence, but the second byte must be 0xA0-0xBF */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2;
+      }
+      else if (0xED == character)
+      {
+        /* RFC 3629 4: three byte UTF-8 sequence, but the second byte must be 0x80-0x9F */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2;
+      }
+      else if (((0xE1 <= character) && (0xEC >= character)) ||
+               ((0xEE <= character) && (0xEF >= character)) )
+      {
+        /* RFC 3629 4: three byte UTF-8 sequence, both tail bytes must be 0x80-0xBF */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2;
+      }
+      else if (0xF0 == character)
+      {
+        /* RFC 3629 4: four byte UTF-8 sequence, but the second byte must be 0x90-0xBF */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3;
+      }
+      else if (0xF4 == character)
+      {
+        /* RFC 3629 4: four byte UTF-8 sequence, but the second byte must be 0x80-0x8F */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3;
+      }
+      else if ((0xF1 <= character) && (0xF3 >= character))
+      {
+        /* RFC 3629 4: four byte UTF-8 sequence, all three tail bytes must be 0x80-0xBF */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2:
+      if ((0xA0 <= character) && (0xBF >= character))
+      {
+        /* RFC 3629 4: Second byte of three byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2:
+      if ((0x80 <= character) && (0x9F >= character))
+      {
+        /* RFC 3629 4: Second byte of three byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2:
+      if ((0x80 <= character) && (0xBF >= character))
+      {
+        /* RFC 3629 4: Second byte of three byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3:
+      if ((0x90 <= character) && (0xBF >= character))
+      {
+        /* RFC 3629 4: Second byte of four byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3:
+      if ((0x80 <= character) && (0x8F >= character))
+      {
+        /* RFC 3629 4: Second byte of four byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3:
+      if ((0x80 <= character) && (0xBF >= character))
+      {
+        /* RFC 3629 4: Second byte of four byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3:
+      if ((0x80 <= character) && (0xBF >= character))
+      {
+        /* RFC 3629 4: Third byte of four byte UTF-8 sequence */
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    /* RFC 3629 4: Second byte of two byte UTF-8 sequence */
+    case MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1:
+    /* RFC 3629 4: Third byte of three byte UTF-8 sequence */
+    case MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2:
+    /* RFC 3629 4: Fourth byte of four byte UTF-8 sequence */
+    case MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3:
+      if ((0x80 <= character) && (0xBF >= character))
+      {
+        utf8_step_ = MHD_WEBSOCKET_UTF8STEP_NORMAL;
+      }
+      else
+      {
+        /* RFC 3629 4: Invalid UTF-8 byte */
+        if (NULL != buf_offset)
+          *buf_offset = i;
+        return MHD_WebSocket_UTF8Result_Invalid;
+      }
+      break;
+
+    default:
+      /* Invalid last step...? */
+      if (NULL != buf_offset)
+        *buf_offset = i;
+      return MHD_WebSocket_UTF8Result_Invalid;
+    }
+  }
+
+  /* return values */
+  if (NULL != utf8_step)
+    *utf8_step = utf8_step_;
+  if (NULL != buf_offset)
+    *buf_offset = buf_len;
+  if (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step_)
+  {
+    return MHD_WebSocket_UTF8Result_Incomplete;
+  }
+  return MHD_WebSocket_UTF8Result_Valid;
+}
+
+
+/**
+ * Generates a mask for masking by calling
+ * a random number generator.
+ */
+static uint32_t
+MHD_websocket_generate_mask (struct MHD_WebSocketStream *ws)
+{
+  unsigned char mask_[4];
+  if (NULL != ws->rng)
+  {
+    size_t offset = 0;
+    while (offset < 4)
+    {
+      size_t encoded = ws->rng (ws->cls_rng,
+                                mask_ + offset,
+                                4 - offset);
+      offset += encoded;
+    }
+  }
+  else
+  {
+    /* this case should never happen */
+    mask_ [0] = 0;
+    mask_ [1] = 0;
+    mask_ [2] = 0;
+    mask_ [3] = 0;
+  }
+
+  return *((uint32_t *) mask_);
+}
+
+
+/**
+ * Calls the malloc function associated with the websocket steam
+ */
+_MHD_EXTERN void *
+MHD_websocket_malloc (struct MHD_WebSocketStream *ws,
+                      size_t buf_len)
+{
+  if (NULL == ws)
+  {
+    return NULL;
+  }
+
+  return ws->malloc (buf_len);
+}
+
+
+/**
+ * Calls the realloc function associated with the websocket steam
+ */
+_MHD_EXTERN void *
+MHD_websocket_realloc (struct MHD_WebSocketStream *ws,
+                       void *buf,
+                       size_t new_buf_len)
+{
+  if (NULL == ws)
+  {
+    return NULL;
+  }
+
+  return ws->realloc (buf, new_buf_len);
+}
+
+
+/**
+ * Calls the free function associated with the websocket steam
+ */
+_MHD_EXTERN int
+MHD_websocket_free (struct MHD_WebSocketStream *ws,
+                    void *buf)
+{
+  if (NULL == ws)
+  {
+    return MHD_WEBSOCKET_STATUS_PARAMETER_ERROR;
+  }
+
+  ws->free (buf);
+
+  return MHD_WEBSOCKET_STATUS_OK;
+}
+
+
+/**
+ * Converts a 16 bit value into network byte order (MSB first)
+ * in dependence of the host system
+ */
+static uint16_t
+MHD_htons (uint16_t value)
+{
+  uint16_t endian = 0x0001;
+
+  if (((char *) &endian)[0] == 0x01)
+  {
+    /* least significant byte first */
+    ((char *) &endian)[0] = ((char *) &value)[1];
+    ((char *) &endian)[1] = ((char *) &value)[0];
+    return endian;
+  }
+  else
+  {
+    /* most significant byte first */
+    return value;
+  }
+}
+
+
+/**
+ * Converts a 64 bit value into network byte order (MSB first)
+ * in dependence of the host system
+ */
+static uint64_t
+MHD_htonll (uint64_t value)
+{
+  uint64_t endian = 0x0000000000000001;
+
+  if (((char *) &endian)[0] == 0x01)
+  {
+    /* least significant byte first */
+    ((char *) &endian)[0] = ((char *) &value)[7];
+    ((char *) &endian)[1] = ((char *) &value)[6];
+    ((char *) &endian)[2] = ((char *) &value)[5];
+    ((char *) &endian)[3] = ((char *) &value)[4];
+    ((char *) &endian)[4] = ((char *) &value)[3];
+    ((char *) &endian)[5] = ((char *) &value)[2];
+    ((char *) &endian)[6] = ((char *) &value)[1];
+    ((char *) &endian)[7] = ((char *) &value)[0];
+    return endian;
+  }
+  else
+  {
+    /* most significant byte first */
+    return value;
+  }
+}
diff --git a/src/microhttpd_ws/sha1.c b/src/microhttpd_ws/sha1.c
new file mode 100644
index 0000000..1e9da5c
--- /dev/null
+++ b/src/microhttpd_ws/sha1.c
@@ -0,0 +1,378 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019-2021 Karlson2k (Evgeny Grin)
+
+     libmicrohttpd 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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha1.c
+ * @brief  Calculation of SHA-1 digest as defined in FIPS PUB 180-4 (2015)
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "sha1.h"
+
+#include <string.h>
+#ifdef HAVE_MEMORY_H
+#include <memory.h>
+#endif /* HAVE_MEMORY_H */
+#include "mhd_bithelpers.h"
+#include "mhd_assert.h"
+
+/**
+ * Initialise structure for SHA-1 calculation.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ */
+void
+MHD_SHA1_init (void *ctx_)
+{
+  struct sha1_ctx *const ctx = ctx_;
+  /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.1 */
+  /* Just some "magic" numbers defined by standard */
+  ctx->H[0] = UINT32_C (0x67452301);
+  ctx->H[1] = UINT32_C (0xefcdab89);
+  ctx->H[2] = UINT32_C (0x98badcfe);
+  ctx->H[3] = UINT32_C (0x10325476);
+  ctx->H[4] = UINT32_C (0xc3d2e1f0);
+
+  /* Initialise number of bytes. */
+  ctx->count = 0;
+}
+
+
+/**
+ * Base of SHA-1 transformation.
+ * Gets full 512 bits / 64 bytes block of data and updates hash values;
+ * @param H     hash values
+ * @param data  data, must be exactly 64 bytes long
+ */
+static void
+sha1_transform (uint32_t H[_SHA1_DIGEST_LENGTH],
+                const uint8_t data[SHA1_BLOCK_SIZE])
+{
+  /* Working variables,
+     see FIPS PUB 180-4 paragraph 6.1.3 */
+  uint32_t a = H[0];
+  uint32_t b = H[1];
+  uint32_t c = H[2];
+  uint32_t d = H[3];
+  uint32_t e = H[4];
+
+  /* Data buffer, used as cyclic buffer.
+     See FIPS PUB 180-4 paragraphs 5.2.1, 6.1.3 */
+  uint32_t W[16];
+
+  /* 'Ch' and 'Maj' macro functions are defined with
+     widely-used optimization.
+     See FIPS PUB 180-4 formulae 4.1. */
+#define Ch(x,y,z)     ( (z) ^ ((x) & ((y) ^ (z))) )
+#define Maj(x,y,z)    ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) )
+  /* Unoptimized (original) versions: */
+/* #define Ch(x,y,z)  ( ( (x) & (y) ) ^ ( ~(x) & (z) ) )          */
+/* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */
+#define Par(x,y,z)    ( (x) ^ (y) ^ (z) )
+
+  /* Single step of SHA-1 computation,
+     see FIPS PUB 180-4 paragraph 6.1.3 step 3.
+   * Note: instead of reassigning all working variables on each step,
+           variables are rotated for each step:
+             SHA1STEP32 (a, b, c, d, e, func, K00, W[0]);
+             SHA1STEP32 (e, a, b, c, d, func, K00, W[1]);
+           so current 'vC' will be used as 'vD' on the next step,
+           current 'vE' will be used as 'vA' on the next step.
+   * Note: 'wt' must be used exactly one time in this macro as it change other data as well
+           every time when used. */
+
+#define SHA1STEP32(vA,vB,vC,vD,vE,ft,kt,wt) do {                         \
+    (vE) += _MHD_ROTL32 ((vA), 5) + ft ((vB), (vC), (vD)) + (kt) + (wt); \
+    (vB) = _MHD_ROTL32 ((vB), 30); } while (0)
+
+  /* Get value of W(t) from input data buffer,
+     See FIPS PUB 180-4 paragraph 6.1.3.
+     Input data must be read in big-endian bytes order,
+     see FIPS PUB 180-4 paragraph 3.1.2. */
+#define GET_W_FROM_DATA(buf,t) \
+  _MHD_GET_32BIT_BE (((const uint8_t*) (buf)) + (t) * SHA1_BYTES_IN_WORD)
+
+#ifndef _MHD_GET_32BIT_BE_UNALIGNED
+  if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN))
+  {
+    /* Copy the unaligned input data to the aligned buffer */
+    memcpy (W, data, SHA1_BLOCK_SIZE);
+    /* The W[] buffer itself will be used as the source of the data,
+     * but data will be reloaded in correct bytes order during
+     * the next steps */
+    data = (uint8_t *) W;
+  }
+#endif /* _MHD_GET_32BIT_BE_UNALIGNED */
+
+/* SHA-1 values of Kt for t=0..19, see FIPS PUB 180-4 paragraph 4.2.1. */
+#define K00      UINT32_C(0x5a827999)
+/* SHA-1 values of Kt for t=20..39, see FIPS PUB 180-4 paragraph 4.2.1.*/
+#define K20      UINT32_C(0x6ed9eba1)
+/* SHA-1 values of Kt for t=40..59, see FIPS PUB 180-4 paragraph 4.2.1.*/
+#define K40      UINT32_C(0x8f1bbcdc)
+/* SHA-1 values of Kt for t=60..79, see FIPS PUB 180-4 paragraph 4.2.1.*/
+#define K60      UINT32_C(0xca62c1d6)
+
+  /* During first 16 steps, before making any calculations on each step,
+     the W element is read from input data buffer as big-endian value and
+     stored in array of W elements. */
+  /* Note: instead of using K constants as array, all K values are specified
+     individually for each step. */
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[0] = GET_W_FROM_DATA (data, 0));
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[1] = GET_W_FROM_DATA (data, 1));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[2] = GET_W_FROM_DATA (data, 2));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[3] = GET_W_FROM_DATA (data, 3));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[4] = GET_W_FROM_DATA (data, 4));
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[5] = GET_W_FROM_DATA (data, 5));
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[6] = GET_W_FROM_DATA (data, 6));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[7] = GET_W_FROM_DATA (data, 7));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[8] = GET_W_FROM_DATA (data, 8));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[9] = GET_W_FROM_DATA (data, 9));
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[10] = GET_W_FROM_DATA (data, 10));
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[11] = GET_W_FROM_DATA (data, 11));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[12] = GET_W_FROM_DATA (data, 12));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[13] = GET_W_FROM_DATA (data, 13));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[14] = GET_W_FROM_DATA (data, 14));
+  SHA1STEP32 (a, b, c, d, e, Ch, K00, W[15] = GET_W_FROM_DATA (data, 15));
+
+  /* 'W' generation and assignment for 16 <= t <= 79.
+     See FIPS PUB 180-4 paragraph 6.1.3.
+     As only last 16 'W' are used in calculations, it is possible to
+     use 16 elements array of W as cyclic buffer. */
+#define Wgen(w,t) _MHD_ROTL32((w)[(t + 13) & 0xf] ^ (w)[(t + 8) & 0xf] \
+                              ^ (w)[(t + 2) & 0xf] ^ (w)[t & 0xf], 1)
+
+  /* During last 60 steps, before making any calculations on each step,
+     W element is generated from W elements of cyclic buffer and generated value
+     stored back in cyclic buffer. */
+  /* Note: instead of using K constants as array, all K values are specified
+     individually for each step, see FIPS PUB 180-4 paragraph 4.2.1. */
+  SHA1STEP32 (e, a, b, c, d, Ch, K00, W[16 & 0xf] = Wgen (W, 16));
+  SHA1STEP32 (d, e, a, b, c, Ch, K00, W[17 & 0xf] = Wgen (W, 17));
+  SHA1STEP32 (c, d, e, a, b, Ch, K00, W[18 & 0xf] = Wgen (W, 18));
+  SHA1STEP32 (b, c, d, e, a, Ch, K00, W[19 & 0xf] = Wgen (W, 19));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[20 & 0xf] = Wgen (W, 20));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[21 & 0xf] = Wgen (W, 21));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[22 & 0xf] = Wgen (W, 22));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[23 & 0xf] = Wgen (W, 23));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[24 & 0xf] = Wgen (W, 24));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[25 & 0xf] = Wgen (W, 25));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[26 & 0xf] = Wgen (W, 26));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[27 & 0xf] = Wgen (W, 27));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[28 & 0xf] = Wgen (W, 28));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[29 & 0xf] = Wgen (W, 29));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[30 & 0xf] = Wgen (W, 30));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[31 & 0xf] = Wgen (W, 31));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[32 & 0xf] = Wgen (W, 32));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[33 & 0xf] = Wgen (W, 33));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[34 & 0xf] = Wgen (W, 34));
+  SHA1STEP32 (a, b, c, d, e, Par, K20, W[35 & 0xf] = Wgen (W, 35));
+  SHA1STEP32 (e, a, b, c, d, Par, K20, W[36 & 0xf] = Wgen (W, 36));
+  SHA1STEP32 (d, e, a, b, c, Par, K20, W[37 & 0xf] = Wgen (W, 37));
+  SHA1STEP32 (c, d, e, a, b, Par, K20, W[38 & 0xf] = Wgen (W, 38));
+  SHA1STEP32 (b, c, d, e, a, Par, K20, W[39 & 0xf] = Wgen (W, 39));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[40 & 0xf] = Wgen (W, 40));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[41 & 0xf] = Wgen (W, 41));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[42 & 0xf] = Wgen (W, 42));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[43 & 0xf] = Wgen (W, 43));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[44 & 0xf] = Wgen (W, 44));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[45 & 0xf] = Wgen (W, 45));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[46 & 0xf] = Wgen (W, 46));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[47 & 0xf] = Wgen (W, 47));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[48 & 0xf] = Wgen (W, 48));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[49 & 0xf] = Wgen (W, 49));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[50 & 0xf] = Wgen (W, 50));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[51 & 0xf] = Wgen (W, 51));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[52 & 0xf] = Wgen (W, 52));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[53 & 0xf] = Wgen (W, 53));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[54 & 0xf] = Wgen (W, 54));
+  SHA1STEP32 (a, b, c, d, e, Maj, K40, W[55 & 0xf] = Wgen (W, 55));
+  SHA1STEP32 (e, a, b, c, d, Maj, K40, W[56 & 0xf] = Wgen (W, 56));
+  SHA1STEP32 (d, e, a, b, c, Maj, K40, W[57 & 0xf] = Wgen (W, 57));
+  SHA1STEP32 (c, d, e, a, b, Maj, K40, W[58 & 0xf] = Wgen (W, 58));
+  SHA1STEP32 (b, c, d, e, a, Maj, K40, W[59 & 0xf] = Wgen (W, 59));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[60 & 0xf] = Wgen (W, 60));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[61 & 0xf] = Wgen (W, 61));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[62 & 0xf] = Wgen (W, 62));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[63 & 0xf] = Wgen (W, 63));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[64 & 0xf] = Wgen (W, 64));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[65 & 0xf] = Wgen (W, 65));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[66 & 0xf] = Wgen (W, 66));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[67 & 0xf] = Wgen (W, 67));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[68 & 0xf] = Wgen (W, 68));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[69 & 0xf] = Wgen (W, 69));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[70 & 0xf] = Wgen (W, 70));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[71 & 0xf] = Wgen (W, 71));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[72 & 0xf] = Wgen (W, 72));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[73 & 0xf] = Wgen (W, 73));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[74 & 0xf] = Wgen (W, 74));
+  SHA1STEP32 (a, b, c, d, e, Par, K60, W[75 & 0xf] = Wgen (W, 75));
+  SHA1STEP32 (e, a, b, c, d, Par, K60, W[76 & 0xf] = Wgen (W, 76));
+  SHA1STEP32 (d, e, a, b, c, Par, K60, W[77 & 0xf] = Wgen (W, 77));
+  SHA1STEP32 (c, d, e, a, b, Par, K60, W[78 & 0xf] = Wgen (W, 78));
+  SHA1STEP32 (b, c, d, e, a, Par, K60, W[79 & 0xf] = Wgen (W, 79));
+
+  /* Compute intermediate hash.
+     See FIPS PUB 180-4 paragraph 6.1.3 step 4. */
+  H[0] += a;
+  H[1] += b;
+  H[2] += c;
+  H[3] += d;
+  H[4] += e;
+}
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA1_update (void *ctx_,
+                 const uint8_t *data,
+                 size_t length)
+{
+  struct sha1_ctx *const ctx = ctx_;
+  unsigned bytes_have; /**< Number of bytes in buffer */
+
+  mhd_assert ((data != NULL) || (length == 0));
+
+  if (0 == length)
+    return; /* Do nothing */
+
+  /* Note: (count & (SHA1_BLOCK_SIZE-1))
+           equal (count % SHA1_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1));
+  ctx->count += length;
+
+  if (0 != bytes_have)
+  {
+    unsigned bytes_left = SHA1_BLOCK_SIZE - bytes_have;
+    if (length >= bytes_left)
+    {     /* Combine new data with the data in the buffer and
+             process the full block. */
+      memcpy (ctx->buffer + bytes_have,
+              data,
+              bytes_left);
+      data += bytes_left;
+      length -= bytes_left;
+      sha1_transform (ctx->H, ctx->buffer);
+      bytes_have = 0;
+    }
+  }
+
+  while (SHA1_BLOCK_SIZE <= length)
+  {   /* Process any full blocks of new data directly,
+         without copying to the buffer. */
+    sha1_transform (ctx->H, data);
+    data += SHA1_BLOCK_SIZE;
+    length -= SHA1_BLOCK_SIZE;
+  }
+
+  if (0 != length)
+  {   /* Copy incomplete block of new data (if any)
+         to the buffer. */
+    memcpy (ctx->buffer + bytes_have, data, length);
+  }
+}
+
+
+/**
+ * Size of "length" padding addition in bytes.
+ * See FIPS PUB 180-4 paragraph 5.1.1.
+ */
+#define SHA1_SIZE_OF_LEN_ADD (64 / 8)
+
+/**
+ * Finalise SHA-1 calculation, return digest.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA1_finish (void *ctx_,
+                 uint8_t digest[SHA1_DIGEST_SIZE])
+{
+  struct sha1_ctx *const ctx = ctx_;
+  uint64_t num_bits;   /**< Number of processed bits */
+  unsigned bytes_have; /**< Number of bytes in buffer */
+
+  num_bits = ctx->count << 3;
+  /* Note: (count & (SHA1_BLOCK_SIZE-1))
+           equals (count % SHA1_BLOCK_SIZE) for this block size. */
+  bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1));
+
+  /* Input data must be padded with bit "1" and with length of data in bits.
+     See FIPS PUB 180-4 paragraph 5.1.1. */
+  /* Data is always processed in form of bytes (not by individual bits),
+     therefore position of first padding bit in byte is always predefined (0x80). */
+  /* Buffer always have space at least for one byte (as full buffers are
+     processed immediately). */
+  ctx->buffer[bytes_have++] = 0x80;
+
+  if (SHA1_BLOCK_SIZE - bytes_have < SHA1_SIZE_OF_LEN_ADD)
+  {   /* No space in current block to put total length of message.
+         Pad current block with zeros and process it. */
+    if (SHA1_BLOCK_SIZE > bytes_have)
+      memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - bytes_have);
+    /* Process full block. */
+    sha1_transform (ctx->H, ctx->buffer);
+    /* Start new block. */
+    bytes_have = 0;
+  }
+
+  /* Pad the rest of the buffer with zeros. */
+  memset (ctx->buffer + bytes_have, 0,
+          SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD - bytes_have);
+  /* Put the number of bits in the processed message as a big-endian value. */
+  _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD,
+                          num_bits);
+  /* Process the full final block. */
+  sha1_transform (ctx->H, ctx->buffer);
+
+  /* Put final hash/digest in BE mode */
+#ifndef _MHD_PUT_32BIT_BE_UNALIGNED
+  if (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN)
+  {
+    uint32_t alig_dgst[_SHA1_DIGEST_LENGTH];
+    _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]);
+    _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]);
+    /* Copy result to unaligned destination address */
+    memcpy (digest, alig_dgst, SHA1_DIGEST_SIZE);
+  }
+  else
+#else  /* _MHD_PUT_32BIT_BE_UNALIGNED */
+  if (1)
+#endif /* _MHD_PUT_32BIT_BE_UNALIGNED */
+  {
+    _MHD_PUT_32BIT_BE (digest + 0 * SHA1_BYTES_IN_WORD, ctx->H[0]);
+    _MHD_PUT_32BIT_BE (digest + 1 * SHA1_BYTES_IN_WORD, ctx->H[1]);
+    _MHD_PUT_32BIT_BE (digest + 2 * SHA1_BYTES_IN_WORD, ctx->H[2]);
+    _MHD_PUT_32BIT_BE (digest + 3 * SHA1_BYTES_IN_WORD, ctx->H[3]);
+    _MHD_PUT_32BIT_BE (digest + 4 * SHA1_BYTES_IN_WORD, ctx->H[4]);
+  }
+
+  /* Erase potentially sensitive data. */
+  memset (ctx, 0, sizeof(struct sha1_ctx));
+}
diff --git a/src/microhttpd_ws/sha1.h b/src/microhttpd_ws/sha1.h
new file mode 100644
index 0000000..851a442
--- /dev/null
+++ b/src/microhttpd_ws/sha1.h
@@ -0,0 +1,110 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2019-2021 Karlson2k (Evgeny Grin)
+
+     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 2.1 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/>.
+*/
+
+/**
+ * @file microhttpd/sha1.h
+ * @brief  Calculation of SHA-1 digest
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#ifndef MHD_SHA1_H
+#define MHD_SHA1_H 1
+
+#include "mhd_options.h"
+#include <stdint.h>
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>  /* for size_t */
+#endif /* HAVE_STDDEF_H */
+
+/**
+ *  SHA-1 digest is kept internally as 5 32-bit words.
+ */
+#define _SHA1_DIGEST_LENGTH 5
+
+/**
+ * Number of bits in single SHA-1 word
+ */
+#define SHA1_WORD_SIZE_BITS 32
+
+/**
+ * Number of bytes in single SHA-1 word
+ */
+#define SHA1_BYTES_IN_WORD (SHA1_WORD_SIZE_BITS / 8)
+
+/**
+ * Size of SHA-1 digest in bytes
+ */
+#define SHA1_DIGEST_SIZE (_SHA1_DIGEST_LENGTH * SHA1_BYTES_IN_WORD)
+
+/**
+ * Size of SHA-1 digest string in chars including termination NUL
+ */
+#define SHA1_DIGEST_STRING_SIZE ((SHA1_DIGEST_SIZE) * 2 + 1)
+
+/**
+ * Size of single processing block in bits
+ */
+#define SHA1_BLOCK_SIZE_BITS 512
+
+/**
+ * Size of single processing block in bytes
+ */
+#define SHA1_BLOCK_SIZE (SHA1_BLOCK_SIZE_BITS / 8)
+
+
+struct sha1_ctx
+{
+  uint32_t H[_SHA1_DIGEST_LENGTH];    /**< Intermediate hash value / digest at end of calculation */
+  uint8_t buffer[SHA1_BLOCK_SIZE];    /**< SHA256 input data buffer */
+  uint64_t count;                     /**< number of bytes, mod 2^64 */
+};
+
+/**
+ * Initialise structure for SHA-1 calculation.
+ *
+ * @param ctx must be a `struct sha1_ctx *`
+ */
+void
+MHD_SHA1_init (void *ctx_);
+
+
+/**
+ * Process portion of bytes.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param data bytes to add to hash
+ * @param length number of bytes in @a data
+ */
+void
+MHD_SHA1_update (void *ctx_,
+                 const uint8_t *data,
+                 size_t length);
+
+
+/**
+ * Finalise SHA-1 calculation, return digest.
+ *
+ * @param ctx_ must be a `struct sha1_ctx *`
+ * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes
+ */
+void
+MHD_SHA1_finish (void *ctx_,
+                 uint8_t digest[SHA1_DIGEST_SIZE]);
+
+#endif /* MHD_SHA1_H */
diff --git a/src/microhttpd_ws/test_websocket.c b/src/microhttpd_ws/test_websocket.c
new file mode 100644
index 0000000..b824b9c
--- /dev/null
+++ b/src/microhttpd_ws/test_websocket.c
@@ -0,0 +1,10105 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021 David Gausmann
+
+     libmicrohttpd 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, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_websocket.c
+ * @brief  Testcase for WebSocket decoding/encoding
+ * @author David Gausmann
+ */
+#include "microhttpd.h"
+#include "microhttpd_ws.h"
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <time.h>
+
+#if SIZE_MAX >= 0x100000000
+  #define ENABLE_64BIT_TESTS 1
+#endif
+
+int disable_alloc = 0;
+size_t open_allocs = 0;
+
+/**
+ * Custom `malloc()` function used for memory tests
+ */
+static void *
+test_malloc (size_t buf_len)
+{
+  if (0 != disable_alloc)
+    return NULL;
+  void *result = malloc (buf_len);
+  if (NULL != result)
+    ++open_allocs;
+  return result;
+}
+
+
+/**
+ * Custom `realloc()` function used for memory tests
+ */
+static void *
+test_realloc (void *buf, size_t buf_len)
+{
+  if (0 != disable_alloc)
+    return NULL;
+  void *result = realloc (buf, buf_len);
+  if ((NULL != result) && (NULL == buf))
+    ++open_allocs;
+  return result;
+}
+
+
+/**
+ * Custom `free()` function used for memory tests
+ */
+static void
+test_free (void *buf)
+{
+  if (NULL != buf)
+    --open_allocs;
+  free (buf);
+}
+
+
+/**
+ * Custom `rng()` function used for client mode tests
+ */
+static size_t
+test_rng (void *cls, void *buf, size_t buf_len)
+{
+  for (size_t i = 0; i < buf_len; ++i)
+  {
+    ((char *) buf) [i] = (char) (rand () % 0xFF);
+  }
+
+  return buf_len;
+}
+
+
+/**
+ * Helper function which allocates a big amount of data
+ */
+static void
+allocate_length_test_data (char **buf1,
+                           char **buf2,
+                           size_t buf_len,
+                           const char *buf1_prefix,
+                           size_t buf1_prefix_len)
+{
+  if (NULL != *buf1)
+    free (*buf1);
+  if (NULL != *buf2)
+    free (*buf2);
+  *buf1 = (char *) malloc (buf_len + buf1_prefix_len);
+  *buf2 = (char *) malloc (buf_len);
+  if ((NULL == buf1) || (NULL == buf2))
+    return;
+  memcpy (*buf1,
+          buf1_prefix,
+          buf1_prefix_len);
+  for (size_t i = 0; i < buf_len; i += 64)
+  {
+    size_t bytes_to_copy = buf_len - i;
+    if (64 < bytes_to_copy)
+      bytes_to_copy = 64;
+    memcpy (*buf1 + i + buf1_prefix_len,
+            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-",
+            bytes_to_copy);
+    memcpy (*buf2 + i,
+            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-",
+            bytes_to_copy);
+  }
+}
+
+
+/**
+ * Helper function which performs a single decoder test
+ */
+static int
+test_decode_single (unsigned int test_line,
+                    int flags, size_t max_payload_size, size_t decode_count,
+                    size_t buf_step,
+                    const char *buf, size_t buf_len,
+                    const char *expected_payload, size_t expected_payload_len,
+                    int expected_return, int expected_valid, size_t
+                    expected_streambuf_read_len)
+{
+  struct MHD_WebSocketStream *ws = NULL;
+  int ret = MHD_WEBSOCKET_STATUS_OK;
+
+  /* initialize stream */
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    flags,
+                                    max_payload_size,
+                                    malloc,
+                                    realloc,
+                                    free,
+                                    NULL,
+                                    test_rng);
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "Allocation failed for decode test in line %u.\n",
+             (unsigned int) test_line);
+    return 1;
+  }
+
+  /* perform decoding in a loop */
+  size_t streambuf_read_len = 0;
+  size_t payload_len = 0;
+  char *payload = NULL;
+  for (size_t i = 0; i < decode_count; ++i)
+  {
+    size_t streambuf_read_len_ = 0;
+    size_t bytes_to_take = buf_len - streambuf_read_len;
+    if ((0 != buf_step) && (buf_step < bytes_to_take))
+      bytes_to_take = buf_step;
+    ret = MHD_websocket_decode (ws, buf + streambuf_read_len, bytes_to_take,
+                                &streambuf_read_len_, &payload, &payload_len);
+    streambuf_read_len += streambuf_read_len_;
+    if (i + 1 < decode_count)
+    {
+      if (payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+        payload_len = 0;
+      }
+    }
+  }
+
+  /* check the (last) result */
+  if (ret != expected_return)
+  {
+    fprintf (stderr,
+             "Decode test failed in line %u: The return value should be %d, but is %d\n",
+             (unsigned int) test_line,
+             (int) expected_return,
+             (int) ret);
+    MHD_websocket_free (ws, payload);
+    MHD_websocket_stream_free (ws);
+    return 1;
+  }
+  if (payload_len != expected_payload_len)
+  {
+    fprintf (stderr,
+             "Decode test failed in line %u: The payload_len should be %u, but is %u\n",
+             (unsigned int) test_line,
+             (unsigned int) expected_payload_len,
+             (unsigned int) payload_len);
+    MHD_websocket_free (ws, payload);
+    MHD_websocket_stream_free (ws);
+    return 1;
+  }
+  if (0 != payload_len)
+  {
+    if (NULL == payload)
+    {
+      fprintf (stderr,
+               "Decode test failed in line %u: The payload is NULL\n",
+               (unsigned int) test_line);
+      MHD_websocket_free (ws, payload);
+      MHD_websocket_stream_free (ws);
+      return 1;
+    }
+    else if (NULL == expected_payload)
+    {
+      fprintf (stderr,
+               "Decode test failed in line %u: The expected_payload is NULL (wrong test declaration)\n",
+               (unsigned int) test_line);
+      MHD_websocket_free (ws, payload);
+      MHD_websocket_stream_free (ws);
+      return 1;
+    }
+    else if (0 != memcmp (payload, expected_payload, payload_len))
+    {
+      fprintf (stderr,
+               "Decode test failed in line %u: The payload differs from the expected_payload\n",
+               (unsigned int) test_line);
+      MHD_websocket_free (ws, payload);
+      MHD_websocket_stream_free (ws);
+      return 1;
+    }
+  }
+  else
+  {
+    if (NULL != payload)
+    {
+      fprintf (stderr,
+               "Decode test failed in line %u: The payload is not NULL, but payload_len is 0\n",
+               (unsigned int) test_line);
+      MHD_websocket_free (ws, payload);
+      MHD_websocket_stream_free (ws);
+      return 1;
+    }
+    else if (NULL != expected_payload)
+    {
+      fprintf (stderr,
+               "Decode test failed in line %u: The expected_payload is not NULL, but expected_payload_len is 0 (wrong test declaration)\n",
+               (unsigned int) test_line);
+      MHD_websocket_free (ws, payload);
+      MHD_websocket_stream_free (ws);
+      return 1;
+    }
+  }
+  if (streambuf_read_len != expected_streambuf_read_len)
+  {
+    fprintf (stderr,
+             "Decode test failed in line %u: The streambuf_read_len should be %u, but is %u\n",
+             (unsigned int) test_line,
+             (unsigned int) expected_streambuf_read_len,
+             (unsigned int) streambuf_read_len);
+    MHD_websocket_free (ws, payload);
+    MHD_websocket_stream_free (ws);
+    return 1;
+  }
+  ret = MHD_websocket_stream_is_valid (ws);
+  if (ret != expected_valid)
+  {
+    fprintf (stderr,
+             "Decode test failed in line %u: The stream validity should be %u, but is %u\n",
+             (unsigned int) test_line,
+             (int) expected_valid,
+             (int) ret);
+    MHD_websocket_free (ws, payload);
+    MHD_websocket_stream_free (ws);
+    return 1;
+  }
+
+  /* cleanup */
+  MHD_websocket_free (ws, payload);
+  MHD_websocket_stream_free (ws);
+
+  return 0;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_stream_init()` and
+ * `MHD_websocket_stream_init2()`
+ */
+int
+test_inits ()
+{
+  int failed = 0;
+  struct MHD_WebSocketStream *ws;
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    All valid flags
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: all valid flags for init (only the even ones work) */
+  for (int i = 0; i < 7; ++i)
+  {
+    ws = NULL;
+    ret = MHD_websocket_stream_init (&ws,
+                                     i,
+                                     0);
+    if (((0 == (i & MHD_WEBSOCKET_FLAG_CLIENT)) &&
+         ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (NULL == ws))) ||
+        ((0 != (i & MHD_WEBSOCKET_FLAG_CLIENT)) &&
+         ((MHD_WEBSOCKET_STATUS_OK == ret) ||
+          (NULL != ws))))
+    {
+      fprintf (stderr,
+               "Init test failed in line %u for flags %d.\n",
+               (unsigned int) __LINE__,
+               (int) i);
+      ++failed;
+    }
+    if (NULL != ws)
+    {
+      MHD_websocket_stream_free (ws);
+      ws = NULL;
+    }
+  }
+  /* Regular test: all valid flags for init2 */
+  for (int i = 0; i < 7; ++i)
+  {
+    ws = NULL;
+    ret = MHD_websocket_stream_init2 (&ws,
+                                      i,
+                                      0,
+                                      test_malloc,
+                                      test_realloc,
+                                      test_free,
+                                      NULL,
+                                      test_rng);
+    if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+        (NULL == ws) )
+    {
+      fprintf (stderr,
+               "Init test failed in line %u for flags %d.\n",
+               (unsigned int) __LINE__,
+               (int) i);
+      ++failed;
+    }
+    if (NULL != ws)
+    {
+      MHD_websocket_stream_free (ws);
+      ws = NULL;
+    }
+  }
+  /* Fail test: Invalid flags for init */
+  for (int i = 4; i < 32; ++i)
+  {
+    int flags = 1 << i;
+    ws = NULL;
+    ret = MHD_websocket_stream_init (&ws,
+                                     flags,
+                                     0);
+    if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+        (NULL != ws) )
+    {
+      fprintf (stderr,
+               "Init test failed in line %u for invalid flags %d.\n",
+               (unsigned int) __LINE__,
+               (int) flags);
+      ++failed;
+    }
+    if (NULL != ws)
+    {
+      MHD_websocket_stream_free (ws);
+      ws = NULL;
+    }
+  }
+  /* Fail test: Invalid flag for init2 */
+  for (int i = 4; i < 32; ++i)
+  {
+    int flags = 1 << i;
+    ws = NULL;
+    ret = MHD_websocket_stream_init2 (&ws,
+                                      flags,
+                                      0,
+                                      test_malloc,
+                                      test_realloc,
+                                      test_free,
+                                      NULL,
+                                      NULL);
+    if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+        (NULL != ws) )
+    {
+      fprintf (stderr,
+               "Init test failed in line %u for invalid flags %d.\n",
+               (unsigned int) __LINE__,
+               (int) flags);
+      ++failed;
+    }
+    if (NULL != ws)
+    {
+      MHD_websocket_stream_free (ws);
+      ws = NULL;
+    }
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    max_payload_size
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: max_payload_size = 0 for init */
+  ws = NULL;
+  ret = MHD_websocket_stream_init (&ws,
+                                   MHD_WEBSOCKET_FLAG_SERVER
+                                   | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                   0);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 0.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Regular test: max_payload_size = 0 for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 0.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Edge test (success): max_payload_size = 1 for init */
+  ws = NULL;
+  ret = MHD_websocket_stream_init (&ws,
+                                   MHD_WEBSOCKET_FLAG_SERVER
+                                   | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                   1);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 1.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Edge test (success): max_payload_size = 1 for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    1,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 1.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Regular test: max_payload_size = 1000 for init */
+  ws = NULL;
+  ret = MHD_websocket_stream_init (&ws,
+                                   MHD_WEBSOCKET_FLAG_SERVER
+                                   | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                   1000);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 1000.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Regular test: max_payload_size = 1000 for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    1000,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 1000.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+#ifdef ENABLE_64BIT_TESTS
+  /* Edge test (success): max_payload_size = 0x7FFFFFFFFFFFFFFF for init */
+  ws = NULL;
+  ret = MHD_websocket_stream_init (&ws,
+                                   MHD_WEBSOCKET_FLAG_SERVER
+                                   | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                   (uint64_t) 0x7FFFFFFFFFFFFFFF);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 0x7FFFFFFFFFFFFFFF.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Edge test (success): max_payload_size = 0x7FFFFFFFFFFFFFFF for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    (uint64_t) 0x7FFFFFFFFFFFFFFF,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 0x7FFFFFFFFFFFFFFF.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Edge test (fail): max_payload_size = 0x8000000000000000 for init */
+  ws = NULL;
+  ret = MHD_websocket_stream_init (&ws,
+                                   MHD_WEBSOCKET_FLAG_SERVER
+                                   | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                   (uint64_t) 0x8000000000000000);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 0x8000000000000000.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Edge test (fail): max_payload_size = 0x8000000000000000 for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    (uint64_t) 0x8000000000000000,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u for max_payload_size 0x8000000000000000.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+#endif
+
+  /*
+  ------------------------------------------------------------------------------
+    Missing parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: websocket stream variable missing for init */
+  ws = NULL;
+  ret = MHD_websocket_stream_init (NULL,
+                                   MHD_WEBSOCKET_FLAG_SERVER
+                                   | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                   0);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Fail test: websocket stream variable missing for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (NULL,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Fail test: malloc missing for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    NULL,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Fail test: realloc missing for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    NULL,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Fail test: free missing for init2 */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    NULL,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Regular test: rng given for server mode (will be ignored) */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    test_rng);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Regular test: cls_rng given for server mode (will be ignored) */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_SERVER
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    (void *) 12345,
+                                    test_rng);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Regular test: rng given for client mode */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_CLIENT
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    test_rng);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (NULL == ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+  /* Fail test: rng not given for client mode */
+  ws = NULL;
+  ret = MHD_websocket_stream_init2 (&ws,
+                                    MHD_WEBSOCKET_FLAG_CLIENT
+                                    | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                    0,
+                                    test_malloc,
+                                    test_realloc,
+                                    test_free,
+                                    NULL,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != ws) )
+  {
+    fprintf (stderr,
+             "Init test failed in line %u %u.\n",
+             (unsigned int) __LINE__, ret);
+    ++failed;
+  }
+  if (NULL != ws)
+  {
+    MHD_websocket_stream_free (ws);
+    ws = NULL;
+  }
+
+  return failed != 0 ? 0x01 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_create_accept_header()`
+ */
+int
+test_accept ()
+{
+  int failed = 0;
+  char accept_key[29];
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    accepting
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Test case from RFC6455 4.2.2 */
+  memset (accept_key, 0, 29);
+  ret = MHD_websocket_create_accept_header ("dGhlIHNhbXBsZSBub25jZQ==",
+                                            accept_key);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (0 != memcmp (accept_key, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", 29)))
+  {
+    fprintf (stderr,
+             "Accept test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Missing parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: missing sec-key value */
+  memset (accept_key, 0, 29);
+  ret = MHD_websocket_create_accept_header (NULL,
+                                            accept_key);
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "Accept test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: missing accept variable */
+  memset (accept_key, 0, 29);
+  ret = MHD_websocket_create_accept_header ("dGhlIHNhbXBsZSBub25jZQ==",
+                                            NULL);
+  if (MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret)
+  {
+    fprintf (stderr,
+             "Accept test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  return failed != 0 ? 0x02 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_decode()`
+ */
+int
+test_decodes ()
+{
+  int failed = 0;
+  char *buf1 = NULL, *buf2 = NULL;
+
+  /*
+  ------------------------------------------------------------------------------
+    text frame
+  ------------------------------------------------------------------------------
+   */
+  /* Regular test: Masked text frame from RFC 6455, must succeed for server */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58",
+                                11,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Unmasked text frame from RFC 6455, must succeed for client */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x05\x48\x65\x6c\x6c\x6f",
+                                7,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                7);
+  /* Fail test: Unmasked text frame from RFC 6455, must fail for server */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x05\x48\x65\x6c\x6c\x6f",
+                                7,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Masked text frame from RFC 6455, must fail for client */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Text frame with UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x90\x00\x00\x00\x00" "This is my n"
+                                "\xC3\xB6" "te",
+                                22,
+                                "This is my n" "\xC3\xB6" "te",
+                                16,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                22);
+  /* Fail test: Text frame with with invalid UTF-8 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8F\x00\x00\x00\x00" "This is my n" "\xFF"
+                                "te",
+                                21,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                18);
+  /* Fail test: Text frame with broken UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8F\x00\x00\x00\x00" "This is my n" "\xC3"
+                                "te",
+                                21,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                19);
+  /* Regular test: Text frame without payload and mask (caller = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x80\x01\x02\x03\x04",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                6);
+  /* Fail test: Text frame without payload and no mask (caller = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Text frame without payload and mask (caller = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                2);
+  /* Fail test: Text frame without payload and no mask (caller = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x80\x01\x02\x03\x04",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+
+  /*
+  ------------------------------------------------------------------------------
+    binary frame
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Masked binary frame (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58",
+                                11,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Unmasked binary frame (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x05\x48\x65\x6c\x6c\x6f",
+                                7,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                7);
+  /* Fail test: Unmasked binary frame (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x05\x48\x65\x6c\x6c\x6f",
+                                7,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Masked binary frame (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Binary frame without payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                6);
+  /* Regular test: Fragmented binary frame without payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x80\x00\x00\x00\x00\x80\x80\x00\x00\x00\x00",
+                                12,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                12);
+  /* Regular test: Fragmented binary frame without payload, fragments to the caller, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x80\x00\x00\x00\x00\x80\x80\x00\x00\x00\x00",
+                                12,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                6);
+  /* Regular test: Fragmented binary frame without payload, fragments to the caller, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x02\x80\x00\x00\x00\x00\x80\x80\x00\x00\x00\x00",
+                                12,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                12);
+  /* Regular test: Fragmented binary frame with payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x80\x83\x00\x00\x00\x00\x04\x05\x06",
+                                18,
+                                "\x01\x02\x03\x04\x05\x06",
+                                6,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                18);
+  /* Regular test: Fragmented binary frame with payload, fragments to the caller, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x80\x83\x00\x00\x00\x00\x04\x05\x06",
+                                18,
+                                "\x01\x02\x03",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                9);
+  /* Regular test: Fragmented binary frame without payload, fragments to the caller, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x80\x83\x00\x00\x00\x00\x04\x05\x06",
+                                18,
+                                "\x04\x05\x06",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                18);
+  /* Regular test: Fragmented binary frame with payload, fragments to the caller, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C",
+                                36,
+                                "\x01\x02\x03",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                9);
+  /* Regular test: Fragmented binary frame without payload, fragments to the caller, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C",
+                                36,
+                                "\x04\x05\x06",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                18);
+  /* Regular test: Fragmented binary frame without payload, fragments to the caller, 3rd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                3,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C",
+                                36,
+                                "\x07\x08\x09",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_NEXT_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                27);
+  /* Regular test: Fragmented binary frame without payload, fragments to the caller, 4th call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                4,
+                                0,
+                                "\x02\x83\x00\x00\x00\x00\x01\x02\x03\x00\x83\x00\x00\x00\x00\x04\x05\x06\x00\x83\x00\x00\x00\x00\x07\x08\x09\x80\x83\x00\x00\x00\x00\x0A\x0B\x0C",
+                                36,
+                                "\x0A\x0B\x0C",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                36);
+  /* Regular test: Binary frame with bytes which look like invalid UTF-8 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x85\x00\x00\x00\x00" "Hell\xf6",
+                                11,
+                                "Hell\xf6",
+                                5,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Binary frame with bytes which look like broken UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x85\x00\x00\x00\x00" "H\xC3llo",
+                                11,
+                                "H\xC3llo",
+                                5,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Binary frame with bytes which look like valid UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x82\x85\x00\x00\x00\x00" "H\xC3\xA4lo",
+                                11,
+                                "H\xC3\xA4lo",
+                                5,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Fragmented binary frame with bytes which look like valid UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x82\x00\x00\x00\x00" "H\xC3"
+                                "\x80\x83\x00\x00\x00\x00" "\xA4lo",
+                                17,
+                                "H\xC3\xA4lo",
+                                5,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented binary frame with bytes which look like valid UTF-8 sequence,
+     fragments to the caller, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x02\x82\x00\x00\x00\x00" "H\xC3"
+                                "\x80\x83\x00\x00\x00\x00" "\xA4lo",
+                                17,
+                                "H\xC3",
+                                2,
+                                MHD_WEBSOCKET_STATUS_BINARY_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                8);
+  /* Regular test: Fragmented binary frame with bytes which look like valid UTF-8 sequence,
+     fragments to the caller, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x02\x82\x00\x00\x00\x00" "H\xC3"
+                                "\x80\x83\x00\x00\x00\x00" "\xA4lo",
+                                17,
+                                "\xA4lo",
+                                3,
+                                MHD_WEBSOCKET_STATUS_BINARY_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+
+  /*
+  ------------------------------------------------------------------------------
+    close frame
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Close frame with no payload but with mask (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                6);
+  /* Regular test: Close frame with no payload (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                2);
+  /* Fail test: Close frame with no payload and no mask (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Close frame with no payload but with mask (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Close frame with 2 byte payload for close reason */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x82\x00\x00\x00\x00\x03\xEB",
+                                8,
+                                "\x03\xEB",
+                                2,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                8);
+  /* Fail test: Close frame with 1 byte payload (no valid close reason) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x81\x00\x00\x00\x00\x03",
+                                7,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Close frame with close reason and UTF-8 description */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x95\x00\x00\x00\x00\x03\xEB"
+                                "Something was wrong",
+                                27,
+                                "\x03\xEB" "Something was wrong",
+                                21,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                27);
+  /* Regular test: Close frame with close reason and UTF-8 description (with UTF-8 sequence) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x96\x00\x00\x00\x00\x03\xEB"
+                                "Something was wr" "\xC3\xB6" "ng",
+                                28,
+                                "\x03\xEB" "Something was wr" "\xC3\xB6" "ng",
+                                22,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                28);
+  /* Fail test: Close frame with close reason and invalid UTF-8 in description */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x95\x00\x00\x00\x00\x03\xEB"
+                                "Something was wr" "\xFF" "ng",
+                                27,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                24);
+  /* Fail test: Close frame with close reason and broken UTF-8 sequence in description */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x95\x00\x00\x00\x00\x03\xEB"
+                                "Something was wr" "\xC3" "ng",
+                                27,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                25);
+  /* Edge test (success): Close frame with 125 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\xFD\x00\x00\x00\x00\x03\xEB"
+                                "Something was wrong, so I decided to close this websocket. I hope you are not angry. But this is also the 123 cap test. :-)",
+                                131,
+                                "\x03\xEB"
+                                "Something was wrong, so I decided to close this websocket. I hope you are not angry. But this is also the 123 cap test. :-)",
+                                125,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                131);
+  /* Edge test (failure): Close frame with 126 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\xFE\x00\x7e\x00\x00\x00\x00\x03\xEB"
+                                "Something was wrong, so I decided to close this websocket. I hope you are not angry. But this is also the 123 cap test. >:-)",
+                                134,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Close frame with 500 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\xFE\x01\xf4\x00\x00\x00\x00\x03\xEB"
+                                "The payload of this test isn't parsed.",
+                                49,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Edge test (failure): Close frame with 65535 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\xFE\xff\xff\x00\x00\x00\x00\x03\xEB"
+                                "The payload of this test isn't parsed.",
+                                49,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Edge test (failure): Close frame with 65536 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\xFF\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03\xEB"
+                                "The payload of this test isn't parsed.",
+                                54,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Close frame with 1000000 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\xFF\x00\x00\x00\x00\x00\x0F\x42\x40\x00\x00\x00\x00\x03\xEB"
+                                "The payload of this test isn't parsed.",
+                                54,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+
+  /*
+  ------------------------------------------------------------------------------
+    ping frame
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Ping frame with no payload but with mask (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                6);
+  /* Regular test: Ping frame with no payload (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                2);
+  /* Fail test: Ping frame with no payload and no mask (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Ping frame with no payload but with mask (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Ping frame with some (masked) payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x88\x01\x20\x03\x40\xFF\xFF\xFF\xFF\x00\x00\x00\x00",
+                                14,
+                                "\xFE\xDF\xFC\xBF\x01\x20\x03\x40",
+                                8,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                14);
+  /* Edge test (success): Ping frame with one byte of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x81\x00\x00\x00\x00" "a",
+                                7,
+                                "a",
+                                1,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                7);
+  /* Edge test (success): Ping frame with 125 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\xFD\x00\x00\x00\x00"
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                131,
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                125,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                131);
+  /* Edge test (fail): Ping frame with 126 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\xFE\x00\x7E\x00\x00\x00\x00"
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                134,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Ping frame with UTF-8 data */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x90\x00\x00\x00\x00" "Ping is bin"
+                                "\xC3\xA4" "ry.",
+                                22,
+                                "Ping is bin" "\xC3\xA4" "ry.",
+                                16,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                22);
+  /* Regular test: Ping frame with invalid UTF-8 data */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x8F\x00\x00\x00\x00" "Ping is bin" "\xFF"
+                                "ry.",
+                                21,
+                                "Ping is bin" "\xFF" "ry.",
+                                15,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                21);
+  /* Regular test: Ping frame with broken UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x8F\x00\x00\x00\x00" "Ping is bin" "\xC3"
+                                "ry.",
+                                21,
+                                "Ping is bin" "\xC3" "ry.",
+                                15,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                21);
+
+  /*
+  ------------------------------------------------------------------------------
+    pong frame
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Pong frame with no payload but with mask (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                6);
+  /* Regular test: Pong frame with no payload (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                2);
+  /* Fail test: Pong frame with no payload and no mask (decoder = server) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x00",
+                                2,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Fail test: Pong frame with no payload but with mask (decoder = client) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_CLIENT
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Pong frame with some (masked) payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x88\x01\x20\x03\x40\xFF\xFF\xFF\xFF\x00\x00\x00\x00",
+                                14,
+                                "\xFE\xDF\xFC\xBF\x01\x20\x03\x40",
+                                8,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                14);
+  /* Edge test (success): Pong frame with one byte of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x81\x00\x00\x00\x00" "a",
+                                7,
+                                "a",
+                                1,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                7);
+  /* Edge test (success): Pong frame with 125 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\xFD\x00\x00\x00\x00"
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                131,
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                125,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                131);
+  /* Edge test (fail): Pong frame with 126 bytes of payload */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\xFE\x00\x7E\x00\x00\x00\x00"
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                134,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                1);
+  /* Regular test: Pong frame with UTF-8 data */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x90\x00\x00\x00\x00" "Pong is bin"
+                                "\xC3\xA4" "ry.",
+                                22,
+                                "Pong is bin" "\xC3\xA4" "ry.",
+                                16,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                22);
+  /* Regular test: Pong frame with invalid UTF-8 data */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x8F\x00\x00\x00\x00" "Pong is bin" "\xFF"
+                                "ry.",
+                                21,
+                                "Pong is bin" "\xFF" "ry.",
+                                15,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                21);
+  /* Regular test: Pong frame with broken UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8A\x8F\x00\x00\x00\x00" "Pong is bin" "\xC3"
+                                "ry.",
+                                21,
+                                "Pong is bin" "\xC3" "ry.",
+                                15,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                21);
+
+  /*
+  ------------------------------------------------------------------------------
+    fragmentation
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Fragmented, masked text frame, we are the server and don't want fragments as caller */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58",
+                                17,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented, masked text frame, we are the server and don't want fragments as caller, but call decode two times */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented, masked text frame, we are the server and want fragments, one call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58",
+                                17,
+                                "Hel",
+                                3,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                9);
+  /* Regular test: Fragmented, masked text frame, we are the server and want fragments, second call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58",
+                                17,
+                                "lo",
+                                2,
+                                MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented, masked text frame, we are the server and want fragments, third call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                3,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x80\x82\x3d\x37\xfa\x21\x51\x58",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented, masked text frame, we are the server and want fragments, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x00\x81\x3d\x37\xfa\x21\x51\x80\x81\x37\x37\xfa\x21\x58",
+                                23,
+                                "Hel",
+                                3,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                9);
+  /* Regular test: Fragmented, masked text frame, we are the server and want fragments, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x00\x81\x3d\x37\xfa\x21\x51\x80\x81\x37\x37\xfa\x21\x58",
+                                23,
+                                "l",
+                                1,
+                                MHD_WEBSOCKET_STATUS_TEXT_NEXT_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Regular test: Fragmented, masked text frame, we are the server and want fragments, 3rd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                3,
+                                0,
+                                "\x01\x83\x37\xfa\x21\x3d\x7f\x9f\x4d\x00\x81\x3d\x37\xfa\x21\x51\x80\x81\x37\x37\xfa\x21\x58",
+                                23,
+                                "o",
+                                1,
+                                MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                23);
+
+
+  /*
+  ------------------------------------------------------------------------------
+    invalid flags
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Template with valid data for the next tests (this one must succeed) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00Hello",
+                                11,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Fail test: RSV1 flag set */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x91\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: RSV2 flag set */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\xA1\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: RSV3 flag set */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\xC1\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+
+  /*
+  ------------------------------------------------------------------------------
+    invalid opcodes
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: Invalid opcode 0 (0 is usually valid, but only if there was a data frame before) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x80\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 3 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x83\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 4 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x84\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 5 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x85\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 6 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x86\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 7 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x87\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 0x0B */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8B\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 0x0C */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8c\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 0x0D */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8d\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 0x0E */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8e\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Invalid opcode 0x0F */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x8f\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+
+
+  /*
+  ------------------------------------------------------------------------------
+    control frames without FIN flag
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: Close frame without FIN flag */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x08\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Ping frame without FIN flag */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x09\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Fail test: Pong frame without FIN flag */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x0a\x85\x00\x00\x00\x00Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+
+  /*
+  ------------------------------------------------------------------------------
+    length checks (without max_payload_len)
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): 0 bytes of payload (requires 1 byte length) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x80\x00\x00\x00\x00",
+                                6,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                6);
+  /* Edge test (success): 1 byte of payload (requires 1 byte length) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x81\x00\x00\x00\x00" "a",
+                                7,
+                                "a",
+                                1,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                7);
+  /* Edge test (success): 125 bytes of payload (requires 1 byte length) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xfd\x00\x00\x00\x00"
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                131,
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                125,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                131);
+  /* Edge test (success): 126 bytes of payload (requires 2 byte length) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xfe\x00\x7e\x00\x00\x00\x00"
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                134,
+                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                126,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                134);
+  /* Edge test (success): 65535 bytes of payload (requires 2 byte length) */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             65535,
+                             "\x81\xfe\xff\xff\x00\x00\x00\x00",
+                             8);
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                buf1,
+                                65535 + 8,
+                                buf2,
+                                65535,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                65535 + 8);
+  /* Edge test (success): 65536 bytes of payload (requires 8 byte length) */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             65536,
+                             "\x81\xff\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00",
+                             14);
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                buf1,
+                                65536 + 14,
+                                buf2,
+                                65536,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                65536 + 14);
+  /* Regular test: 1 MB of payload */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             1048576,
+                             "\x81\xff\x00\x00\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00",
+                             14);
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                buf1,
+                                1048576 + 14,
+                                buf2,
+                                1048576,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                1048576 + 14);
+  /* Regular test: 100 MB of payload */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             104857600,
+                             "\x81\xff\x00\x00\x00\x00\x06\x40\x00\x00\x00\x00\x00\x00",
+                             14);
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                buf1,
+                                104857600 + 14,
+                                buf2,
+                                104857600,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                104857600 + 14);
+  if (NULL != buf1)
+  {
+    free (buf1);
+    buf1 = NULL;
+  }
+  if (NULL != buf2)
+  {
+    free (buf2);
+    buf2 = NULL;
+  }
+#ifdef ENABLE_64BIT_TESTS
+  /* Edge test (success): Maximum allowed length (here is only the header checked) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xff\x7f\xff\xff\xff\xff\xff\xff\xff",
+                                10,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                10);
+#else
+  /* Edge test (fail): Maximum allowed length
+     (the size is allowed, but the system cannot handle this amount of memory) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xff\x7f\xff\xff\xff\xff\xff\xff\xff",
+                                10,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+#endif
+  /* Edge test (fail): Too big payload length */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xff\x80\x00\x00\x00\x00\x00\x00\x00",
+                                10,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+  /* Edge test (fail): Too big payload length */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xff\xff\xff\xff\xff\xff\xff\xff\xff",
+                                10,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+  /* Fail test: Not the smallest payload length syntax used (2 byte instead of 1 byte) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xfe\x00\x05\x00\x00\x00\x00" "abcde",
+                                13,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                4);
+  /* Fail test: Not the smallest payload length syntax used (8 byte instead of 1 byte) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xff\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00"
+                                "abcde",
+                                13,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+  /* Fail test: Not the smallest payload length syntax used (8 byte instead of 2 byte) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\xff\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00"
+                                "abcde",
+                                13,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+
+  /*
+  ------------------------------------------------------------------------------
+    length checks (with max_payload_len)
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Frame with less payload than specified as limit */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                100,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00" "Hello",
+                                11,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Edge test (success): Frame with the same payload as the specified limit */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                5,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00" "Hello",
+                                11,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Edge test (fail): Frame with more payload than specified as limit */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                4,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00" "Hello",
+                                11,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                2);
+  /* Regular test: Fragmented frames with the sum of payload less than specified as limit */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                100,
+                                1,
+                                0,
+                                "\x01\x83\x00\x00\x00\x00"
+                                "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                17,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Edge test (success): Fragmented frames with the sum of payload equal to the specified limit */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                5,
+                                1,
+                                0,
+                                "\x01\x83\x00\x00\x00\x00"
+                                "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                17,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Edge test (fail): Fragmented frames with the sum of payload more than specified as limit */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                4,
+                                1,
+                                0,
+                                "\x01\x83\x00\x00\x00\x00"
+                                "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                15);
+  /* Edge test (success): Fragmented frames with the sum of payload greater than
+     the specified limit, but we take fragments (one call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                5,
+                                1,
+                                0,
+                                "\x01\x83\x00\x00\x00\x00"
+                                "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                17,
+                                "Hel",
+                                3,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                9);
+  /* Edge test (success): Fragmented frames with the sum of payload greater than
+     the specified limit, but we take fragments (two calls) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                5,
+                                2,
+                                0,
+                                "\x01\x83\x00\x00\x00\x00"
+                                "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                17,
+                                "lo",
+                                2,
+                                MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+
+  /*
+  ------------------------------------------------------------------------------
+    UTF-8 sequences
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: No UTF-8 characters  */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 a        ",
+                                16,
+                                " a        ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Fail test: A UTF-8 tail character without sequence start character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xA4        ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Regular test: A two byte UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xC3\xA4       ",
+                                16,
+                                " \xC3\xA4       ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Fail test: A broken two byte UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xC3        ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Fail test: A two byte UTF-8 sequence with one UTF-8 tail too much */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xC3\xA4\xA4      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                9);
+  /* Regular test: A three byte UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF\x8F\x8F      ",
+                                16,
+                                " \xEF\x8F\x8F      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Fail test: A broken byte UTF-8 sequence (two of three bytes) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF\x8F       ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                9);
+  /* Fail test: A broken byte UTF-8 sequence (one of three bytes) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF        ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Fail test: A three byte UTF-8 sequence followed by one UTF-8 tail byte */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF\x8F\x8F\x8F     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+  /* Regular test: A four byte UTF-8 sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF2\x8F\x8F\x8F     ",
+                                16,
+                                " \xF2\x8F\x8F\x8F     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Fail test: A broken four byte UTF-8 sequence (three of four bytes) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF2\x8F\x8F      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                10);
+  /* Fail test: A broken four byte UTF-8 sequence (two of four bytes) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF2\x8F       ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                9);
+  /* Fail test: A broken four byte UTF-8 sequence (one of four bytes) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF2        ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Fail test: A four byte UTF-8 sequence followed by UTF-8 tail */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF2\x8F\x8F\x8F\x8F    ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                11);
+  /* Fail test: A five byte UTF-8 sequence (only up to four bytes allowed) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xFB\x8F\x8F\x8F\x8F    ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Fail test: A six byte UTF-8 sequence (only up to four bytes allowed) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xFD\x8F\x8F\x8F\x8F\x8F   ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Fail test: A seven byte UTF-8 sequence (only up to four bytes allowed) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xFE\x8F\x8F\x8F\x8F\x8F\x8F  ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Fail test: A eight byte UTF-8 sequence (only up to four bytes allowed) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xFF\x8F\x8F\x8F\x8F\x8F\x8F\x8F ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Edge test (success): The maximum allowed UTF-8 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF4\x8F\xBF\xBF     ",
+                                16,
+                                " \xF4\x8F\xBF\xBF     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The maximum allowed UTF-8 character + 1 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF4\x90\x80\x80     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The last valid UTF8-1 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \x7F        ",
+                                16,
+                                " \x7F        ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the last valid UTF8-1 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \x80        ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Edge test (fail): The value before the first valid UTF8-2 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xC1\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Edge test (success): The first valid UTF8-2 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xC2\x80       ",
+                                16,
+                                " \xC2\x80       ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-2 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xDF\xBF       ",
+                                16,
+                                " \xDF\xBF       ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the lst valid UTF8-2 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xE0\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (fail): The value before the first valid UTF8-3 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xE0\x9F\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The first valid UTF8-3 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xE0\xA0\x80      ",
+                                16,
+                                " \xE0\xA0\x80      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-3 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xE0\xBF\xBF      ",
+                                16,
+                                " \xE0\xBF\xBF      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the first valid UTF8-3 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xE0\xC0\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The first valid UTF8-3 character (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xE1\x80\x80      ",
+                                16,
+                                " \xE1\x80\x80      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-3 character (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEC\xBF\xBF      ",
+                                16,
+                                " \xEC\xBF\xBF      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the last valid UTF8-3 character (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEC\xC0\xBF      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (fail): The value before the first valid UTF8-3 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xED\x7F\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The first valid UTF8-3 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xED\x80\x80      ",
+                                16,
+                                " \xED\x80\x80      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-3 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xED\x9F\xBF      ",
+                                16,
+                                " \xED\x9F\xBF      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the last valid UTF8-3 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xED\xA0\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (fail): The value before the first valid UTF8-3 character (tail 4) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEE\x7F\x80      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The first valid UTF8-3 character (tail 4) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEE\x80\x80      ",
+                                16,
+                                " \xEE\x80\x80      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-3 character (tail 4) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF\xBF\xBF      ",
+                                16,
+                                " \xEF\xBF\xBF      ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the last valid UTF8-3 character (tail 4) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF\xBF\xC0      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                9);
+  /* Edge test (fail): The value after the last valid UTF8-3 character (tail 4) #2 */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xEF\xC0\xBF      ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (fail): The value before the first valid UTF8-4 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF0\x8F\x80\x80     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The first valid UTF8-4 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF0\x90\x80\x80     ",
+                                16,
+                                " \xF0\x90\x80\x80     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-4 character (tail 1) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF0\xBF\xBF\xBF     ",
+                                16,
+                                " \xF0\xBF\xBF\xBF     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The first valid UTF8-4 character (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF1\x80\x80\x80     ",
+                                16,
+                                " \xF1\x80\x80\x80     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-4 character (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF3\xBF\xBF\xBF     ",
+                                16,
+                                " \xF3\xBF\xBF\xBF     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): A value before the last valid UTF8-4 character in the second byte (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF3\x7F\x80\x80     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (fail): A value after the last valid UTF8-4 character in the second byte (tail 2) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF3\xC0\x80\x80     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (success): The first valid UTF8-4 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF4\x80\x80\x80     ",
+                                16,
+                                " \xF4\x80\x80\x80     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (success): The last valid UTF8-4 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF4\x8F\xBF\xBF     ",
+                                16,
+                                " \xF4\x8F\xBF\xBF     ",
+                                10,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                16);
+  /* Edge test (fail): The value after the last valid UTF8-4 character (tail 3) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF4\x90\x80\x80     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                8);
+  /* Edge test (fail): The first byte value the last valid UTF8-4 character */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x8A\x00\x00\x00\x00 \xF5\x90\x80\x80     ",
+                                16,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+
+  /*
+  ------------------------------------------------------------------------------
+    Unfinished UTF-8 sequence between fragmented text frame
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: UTF-8 sequence between fragments, no fragmentation for the caller */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x8D\x00\x00\x00\x00" "This is my n"
+                                "\xC3\x80\x83\x00\x00\x00\x00\xB6" "te",
+                                28,
+                                "This is my n" "\xC3\xB6" "te",
+                                16,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                28);
+  /* Regular test: UTF-8 sequence between fragments, fragmentation for the caller, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x8D\x00\x00\x00\x00" "This is my n"
+                                "\xC3\x80\x83\x00\x00\x00\x00\xB6" "te",
+                                28,
+                                "This is my n",
+                                12,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                19);
+  /* Regular test: UTF-8 sequence between fragments, fragmentation for the caller, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x8D\x00\x00\x00\x00" "This is my n"
+                                "\xC3\x80\x83\x00\x00\x00\x00\xB6" "te",
+                                28,
+                                "\xC3\xB6" "te",
+                                4,
+                                MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                28);
+  /* Edge test (success): UTF-8 sequence between fragments, but nothing before, fragmentation for the caller, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x81\x00\x00\x00\x00\xC3\x80\x81\x00\x00\x00\x00\xB6",
+                                14,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                7);
+  /* Edge test (success): UTF-8 sequence between fragments, but nothing before, fragmentation for the caller, 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x81\x00\x00\x00\x00\xC3\x80\x81\x00\x00\x00\x00\xB6",
+                                14,
+                                "\xC3\xB6",
+                                2,
+                                MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                14);
+
+  /*
+  ------------------------------------------------------------------------------
+    Decoding with broken stream
+  ------------------------------------------------------------------------------
+  */
+  /* Failure test: Invalid sequence */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\xFF\x81\x85\x00\x00\x00\x00" "Hello",
+                                12,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Failure test: Call after invalidated stream */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\xFF\x81\x85\x00\x00\x00\x00" "Hello",
+                                12,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_STREAM_BROKEN,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Failure test: Call after invalidated stream (but with different buffer) */
+  {
+    struct MHD_WebSocketStream *ws;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws,
+                                                              MHD_WEBSOCKET_FLAG_SERVER
+                                                              |
+                                                              MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                              0))
+    {
+      size_t streambuf_read_len = 0;
+      char *payload = NULL;
+      size_t payload_len = 0;
+      int ret = 0;
+      ret = MHD_websocket_decode (ws,
+                                  "\xFF",
+                                  1,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if (MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR != ret)
+      {
+        fprintf (stderr,
+                 "Test failed in line %u: The return value should be -1, but is %d\n",
+                 (unsigned int) __LINE__,
+                 (int) ret);
+        ++failed;
+      }
+      else
+      {
+        ret = MHD_websocket_decode (ws,
+                                    "\x81\x85\x00\x00\x00\x00" "Hello",
+                                    11,
+                                    &streambuf_read_len,
+                                    &payload,
+                                    &payload_len);
+        if (MHD_WEBSOCKET_STATUS_STREAM_BROKEN != ret)
+        {
+          fprintf (stderr,
+                   "Test failed in line %u: The return value should be -2, but is %d\n",
+                   (unsigned int) __LINE__,
+                   (int) ret);
+          ++failed;
+        }
+      }
+      MHD_websocket_stream_free (ws);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Individual test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    frame after close frame
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x81\x85\x00\x00\x00\x00"
+                                "Hello",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                6);
+  /* Failure test: Text frame after close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x81\x85\x00\x00\x00\x00"
+                                "Hello",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                6);
+  /* Failure test: Binary frame after close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x82\x85\x00\x00\x00\x00"
+                                "Hello",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                6);
+  /* Failure test: Continue frame after close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x80\x85\x00\x00\x00\x00"
+                                "Hello",
+                                17,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                6);
+  /* Regular test: Ping frame after close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x89\x85\x00\x00\x00\x00"
+                                "Hello",
+                                17,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                17);
+  /* Regular test: Pong frame after close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x8A\x85\x00\x00\x00\x00"
+                                "Hello",
+                                17,
+                                "Hello",
+                                5,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                17);
+  /* Regular test: Close frame after close frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x88\x80\x00\x00\x00\x00\x88\x80\x00\x00\x00\x00",
+                                12,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                12);
+
+  /*
+  ------------------------------------------------------------------------------
+    decoding byte-by-byte
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Text frame, 2 bytes per loop, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                2,
+                                "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/",
+                                23,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                2);
+  /* Regular test: Text frame, 2 bytes per loop, 11th call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                11,
+                                2,
+                                "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/",
+                                23,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                22);
+  /* Regular test: Text frame, 2 bytes per loop, 12th call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                12,
+                                2,
+                                "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/",
+                                23,
+                                "This is the test.",
+                                17,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                23);
+  /* Regular test: Text frame, 1 byte per loop, 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                1,
+                                "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/",
+                                23,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                1);
+  /* Regular test: Text frame, 1 byte per loop, 22nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                22,
+                                1,
+                                "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/",
+                                23,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_OK,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                22);
+  /* Regular test: Text frame, 1 byte per loop, 23rd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                23,
+                                1,
+                                "\x81\x91\x01\x02\x04\x08" "Ujm{!kw(uja(ugw|/",
+                                23,
+                                "This is the test.",
+                                17,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                23);
+
+  /*
+  ------------------------------------------------------------------------------
+    mix of fragmented data frames and control frames
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Fragmented text frame mixed with one ping frame (1st call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x89\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented text frame mixed with one ping frame (2nd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x89\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                "This is the test.",
+                                17,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                35);
+  /* Regular test: Fragmented text frame mixed with one close frame (1st call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x88\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                17);
+  /* Fail test: Fragmented text frame mixed with one ping frame (2nd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x88\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                17);
+  /* Regular test: Fragmented text frame mixed with one ping frame, the caller wants fragments (1st call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x89\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                "This ",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Fragmented text frame mixed with one ping frame, the caller wants fragments (2nd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x89\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                17);
+  /* Regular test: Fragmented text frame mixed with one ping frame, the caller wants fragments (3rd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                3,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x89\x80\x00\x00\x00\x00"
+                                "\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                35,
+                                "is the test.",
+                                12,
+                                MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                35);
+
+  /*
+  ------------------------------------------------------------------------------
+    mix of fragmented data frames and data frames
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: Fragmented text frame mixed with one non-fragmented binary frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x82\x81\x00\x00\x00\x00"
+                                "a\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                36,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                11);
+  /* Regular test: Fragmented text frame mixed with one non-fragmented binary frame; the caller wants fragments; 1st call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x82\x81\x00\x00\x00\x00"
+                                "a\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                36,
+                                "This ",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Fail test: Fragmented text frame mixed with one non-fragmented binary frame; the caller wants fragments; 2nd call */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x82\x81\x00\x00\x00\x00"
+                                "a\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                36,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                11);
+  /* Fail test: Fragmented text frame mixed with one fragmented binary frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x02\x81\x00\x00\x00\x00"
+                                "a\x80\x8C\x00\x00\x00\x00" "is the test.",
+                                36,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                11);
+  /* Fail test: Fragmented text frame, continue frame, non-fragmented binary frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x00\x8C\x00\x00\x00\x00"
+                                "is the test.\x82\x81\x00\x00\x00\x00" "a",
+                                36,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                29);
+  /* Fail test: Fragmented text frame, continue frame, fragmented binary frame */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x01\x85\x00\x00\x00\x00"
+                                "This \x00\x8C\x00\x00\x00\x00"
+                                "is the test.\x02\x81\x00\x00\x00\x00" "a",
+                                36,
+                                NULL,
+                                0,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                29);
+
+  /*
+  ------------------------------------------------------------------------------
+    multiple data frames
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Text frame, binary frame, text frame (1st call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00"
+                                "This \x82\x87\x00\x00\x00\x00"
+                                "is the \x81\x85\x00\x00\x00\x00" "test.",
+                                35,
+                                "This ",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Text frame, binary frame, text frame (2nd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00"
+                                "This \x82\x87\x00\x00\x00\x00"
+                                "is the \x81\x85\x00\x00\x00\x00" "test.",
+                                35,
+                                "is the ",
+                                7,
+                                MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                24);
+  /* Regular test: Text frame, binary frame, text frame (3rd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                3,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00"
+                                "This \x82\x87\x00\x00\x00\x00"
+                                "is the \x81\x85\x00\x00\x00\x00" "test.",
+                                35,
+                                "test.",
+                                5,
+                                MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                35);
+  /*
+  ------------------------------------------------------------------------------
+    multiple control frames
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Ping frame, pong frame, close frame (1st call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                1,
+                                0,
+                                "\x89\x85\x00\x00\x00\x00"
+                                "This \x8A\x87\x00\x00\x00\x00"
+                                "is the \x88\x85\x00\x00\x00\x00" "test.",
+                                35,
+                                "This ",
+                                5,
+                                MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                11);
+  /* Regular test: Ping frame, pong frame, close frame (2nd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                2,
+                                0,
+                                "\x89\x85\x00\x00\x00\x00"
+                                "This \x8A\x87\x00\x00\x00\x00"
+                                "is the \x88\x85\x00\x00\x00\x00" "test.",
+                                35,
+                                "is the ",
+                                7,
+                                MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_VALID,
+                                24);
+  /* Regular test: Ping frame, pong frame, close frame (3rd call) */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                0,
+                                3,
+                                0,
+                                "\x89\x85\x00\x00\x00\x00"
+                                "This \x8A\x87\x00\x00\x00\x00"
+                                "is the \x88\x85\x00\x00\x00\x00" "test.",
+                                35,
+                                "test.",
+                                5,
+                                MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                35);
+
+  /*
+  ------------------------------------------------------------------------------
+    generated close frames for errors
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Close frame generated for protocol error */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS
+                                |
+                                MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR,
+                                0,
+                                1,
+                                0,
+                                "\xFF",
+                                1,
+                                "\x88\x02\x03\xEA",
+                                4,
+                                MHD_WEBSOCKET_STATUS_PROTOCOL_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                0);
+  /* Regular test: Close frame generated for UTF-8 sequence error */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS
+                                |
+                                MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR,
+                                0,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00T\xFFst.",
+                                11,
+                                "\x88\x02\x03\xEF",
+                                4,
+                                MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                7);
+  /* Regular test: Close frame generated for message size exceeded */
+  failed += test_decode_single (__LINE__,
+                                MHD_WEBSOCKET_FLAG_SERVER
+                                | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS
+                                |
+                                MHD_WEBSOCKET_FLAG_GENERATE_CLOSE_FRAMES_ON_ERROR,
+                                3,
+                                1,
+                                0,
+                                "\x81\x85\x00\x00\x00\x00T\xFFst.",
+                                11,
+                                "\x88\x02\x03\xF1",
+                                4,
+                                MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED,
+                                MHD_WEBSOCKET_VALIDITY_INVALID,
+                                2);
+
+  /*
+  ------------------------------------------------------------------------------
+    terminating NUL character
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *ws;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws,
+                                                              MHD_WEBSOCKET_FLAG_SERVER
+                                                              |
+                                                              MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                              0))
+    {
+      size_t streambuf_read_len = 0;
+      char *payload = NULL;
+      size_t payload_len = 0;
+      int ret = 0;
+
+      /* Regular test: text frame */
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00" "Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_TEXT_FRAME != ret) ||
+          (5 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("Hello", payload, 5 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      /* Regular test: text frame fragment */
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x83\x00\x00\x00\x00"
+                                  "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                  17,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_TEXT_FRAME != ret) ||
+          (5 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("Hello", payload, 5 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      /* Regular test: binary frame */
+      ret = MHD_websocket_decode (ws,
+                                  "\x82\x85\x00\x00\x00\x00" "Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_BINARY_FRAME != ret) ||
+          (5 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("Hello", payload, 5 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      /* Regular test: binary frame fragment */
+      ret = MHD_websocket_decode (ws,
+                                  "\x02\x83\x00\x00\x00\x00"
+                                  "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                  17,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_BINARY_FRAME != ret) ||
+          (5 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("Hello", payload, 5 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      MHD_websocket_stream_free (ws);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Individual decode test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+  {
+    struct MHD_WebSocketStream *ws;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws,
+                                                              MHD_WEBSOCKET_FLAG_SERVER
+                                                              |
+                                                              MHD_WEBSOCKET_FLAG_WANT_FRAGMENTS,
+                                                              0))
+    {
+      size_t streambuf_read_len = 0;
+      char *payload = NULL;
+      size_t payload_len = 0;
+      int ret = 0;
+
+      /* Regular test: text frame fragment (caller wants fragment, 1st call) */
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x83\x00\x00\x00\x00"
+                                  "Hel\x80\x82\x00\x00\x00\x00" "lo",
+                                  17,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT != ret) ||
+          (3 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("Hel", payload, 3 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      /* Regular test: text frame fragment (caller wants fragment, 2nd call) */
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x83\x00\x00\x00\x00"
+                                  "Hel\x80\x82\x00\x00\x00\x00" "lo"
+                                  + streambuf_read_len,
+                                  17 - streambuf_read_len,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT != ret) ||
+          (2 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("lo", payload, 2 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      /* Regular test: text frame fragment with broken UTF-8 sequence (caller wants fragment, 1st call) */
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x83\x00\x00\x00\x00"
+                                  "He\xC3\x80\x82\x00\x00\x00\x00" "\xB6o",
+                                  17,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_TEXT_FIRST_FRAGMENT != ret) ||
+          (2 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("He", payload, 2 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      /* Regular test: text frame fragment with broken UTF-8 sequence (caller wants fragment, 2nd call) */
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x83\x00\x00\x00\x00"
+                                  "He\xC3\x80\x82\x00\x00\x00\x00" "\xB6o"
+                                  + streambuf_read_len,
+                                  17 - streambuf_read_len,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_TEXT_LAST_FRAGMENT != ret) ||
+          (3 != payload_len) ||
+          (NULL == payload) ||
+          (0 != memcmp ("\xC3\xB6o", payload, 3 + 1)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+        payload = NULL;
+      }
+
+      MHD_websocket_stream_free (ws);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Individual decode test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+
+  /*
+  ------------------------------------------------------------------------------
+    invalid parameters
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *ws;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init (&ws,
+                                                              MHD_WEBSOCKET_FLAG_SERVER
+                                                              |
+                                                              MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                              0))
+    {
+      size_t streambuf_read_len = 0;
+      char *payload = NULL;
+      size_t payload_len = 0;
+      int ret = 0;
+
+      /* Failure test: `ws` is NULL */
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      payload_len = 0x87654321;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (NULL,
+                                  "\x81\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+          (NULL != payload) ||
+          (0 != payload_len) ||
+          (0 != streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+      /* Failure test: `buf` is NULL, while `buf_len` != 0 */
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      payload_len = 0x87654321;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (ws,
+                                  NULL,
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+          (NULL != payload) ||
+          (0 != payload_len) ||
+          (0 != streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+      /* Failure test: `streambuf_read_len` is NULL */
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      payload_len = 0x87654321;
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  NULL,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+          (NULL != payload) ||
+          (0 != payload_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+      /* Failure test: `payload` is NULL */
+      payload_len = 0x87654321;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  NULL,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+          (0 != payload_len) ||
+          (0 != streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      /* Failure test: `payload_len` is NULL */
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  NULL);
+      if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+          (NULL != payload) ||
+          (0 != streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+      /* Regular test: `buf` is NULL and `buf_len` is 0 */
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      payload_len = 0x87654321;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (ws,
+                                  NULL,
+                                  0,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (NULL != payload) ||
+          (0 != payload_len) ||
+          (0 != streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+      /* Regular test: `buf` is not NULL and `buf_len` is 0 */
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      payload_len = 0x87654321;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00Hello",
+                                  0,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (NULL != payload) ||
+          (0 != payload_len) ||
+          (0 != streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+
+      MHD_websocket_stream_free (ws);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Parameter decode tests failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    validity after temporary out-of-memory
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *ws;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                               MHD_WEBSOCKET_FLAG_SERVER
+                                                               |
+                                                               MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      size_t streambuf_read_len = 0;
+      char *payload = NULL;
+      size_t payload_len = 0;
+      int ret = 0;
+
+      /* Failure test: No memory allocation at the start */
+      disable_alloc = 1;
+      payload = (char *) (uintptr_t) 0xBAADF00D;
+      payload_len = 0x87654321;
+      streambuf_read_len = 1000;
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+          (NULL != payload) ||
+          (0 != payload_len) ||
+          (1000 == streambuf_read_len) ||
+          (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (ws)))
+      {
+        fprintf (stderr,
+                 "Decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+      {
+        payload = NULL;
+      }
+      if (NULL != payload)
+      {
+        MHD_websocket_free (ws, payload);
+      }
+      MHD_websocket_stream_free (ws);
+      if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                                 MHD_WEBSOCKET_FLAG_SERVER
+                                                                 |
+                                                                 MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                                 0,
+                                                                 test_malloc,
+                                                                 test_realloc,
+                                                                 test_free,
+                                                                 NULL,
+                                                                 NULL))
+      {
+        /* Failure test: No memory allocation after fragmented frame */
+        disable_alloc = 0;
+        payload = (char *) (uintptr_t) 0xBAADF00D;
+        payload_len = 0x87654321;
+        streambuf_read_len = 1000;
+        ret = MHD_websocket_decode (ws,
+                                    "\x01\x83\x00\x00\x00\x00" "Hel",
+                                    9,
+                                    &streambuf_read_len,
+                                    &payload,
+                                    &payload_len);
+        if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+            (NULL != payload) ||
+            (0 != payload_len) ||
+            (9 != streambuf_read_len) ||
+            (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (
+               ws)))
+        {
+          fprintf (stderr,
+                   "Decode test failed in line %u\n",
+                   (unsigned int) __LINE__);
+          ++failed;
+        }
+        if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+        {
+          payload = NULL;
+        }
+        if (NULL != payload)
+        {
+          MHD_websocket_free (ws, payload);
+        }
+        disable_alloc = 1;
+        payload = (char *) (uintptr_t) 0xBAADF00D;
+        payload_len = 0x87654321;
+        streambuf_read_len = 1000;
+        ret = MHD_websocket_decode (ws,
+                                    "\x80\x82\x00\x00\x00\x00" "lo",
+                                    8,
+                                    &streambuf_read_len,
+                                    &payload,
+                                    &payload_len);
+        if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+            (NULL != payload) ||
+            (0 != payload_len) ||
+            (1000 == streambuf_read_len) ||
+            (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (
+               ws)))
+        {
+          fprintf (stderr,
+                   "Decode test failed in line %u\n",
+                   (unsigned int) __LINE__);
+          ++failed;
+        }
+        if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+        {
+          payload = NULL;
+        }
+        if (NULL != payload)
+        {
+          MHD_websocket_free (ws, payload);
+        }
+        /* Regular test: Success after memory allocation ok again */
+        /* (streambuf_read_len may not be overwritten for this test) */
+        disable_alloc = 0;
+        payload = (char *) (uintptr_t) 0xBAADF00D;
+        payload_len = 0x87654321;
+        size_t old_streambuf_read_len = streambuf_read_len;
+        ret = MHD_websocket_decode (ws,
+                                    "\x80\x82\x00\x00\x00\x00lo"
+                                    + old_streambuf_read_len,
+                                    8 - old_streambuf_read_len,
+                                    &streambuf_read_len,
+                                    &payload,
+                                    &payload_len);
+        if ((MHD_WEBSOCKET_STATUS_TEXT_FRAME != ret) ||
+            (NULL == payload) ||
+            (5 != payload_len) ||
+            (8 != streambuf_read_len + old_streambuf_read_len) ||
+            (MHD_WEBSOCKET_VALIDITY_VALID != MHD_websocket_stream_is_valid (
+               ws)) ||
+            (0 != memcmp ("Hello", payload, 5)))
+        {
+          fprintf (stderr,
+                   "Decode test failed in line %u\n",
+                   (unsigned int) __LINE__);
+          ++failed;
+        }
+        if (((char *) (uintptr_t) 0xBAADF00D) == payload)
+        {
+          payload = NULL;
+        }
+        if (NULL != payload)
+        {
+          MHD_websocket_free (ws, payload);
+        }
+
+        MHD_websocket_stream_free (ws);
+      }
+      else
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+    }
+    else
+    {
+      fprintf (stderr,
+               "Memory decode tests failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    memory leak test, when freeing while decoding
+  ------------------------------------------------------------------------------
+  */
+  {
+    disable_alloc = 0;
+    struct MHD_WebSocketStream *ws;
+    size_t streambuf_read_len = 0;
+    char *payload = NULL;
+    size_t payload_len = 0;
+    int ret = 0;
+
+    /* Regular test: Free while decoding of data frame */
+    open_allocs = 0;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                               MHD_WEBSOCKET_FLAG_SERVER
+                                                               |
+                                                               MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      ret = MHD_websocket_decode (ws,
+                                  "\x81\x85\x00\x00\x00\x00Hel",
+                                  9,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (9 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_stream_free (ws);
+      if (MHD_WEBSOCKET_STATUS_OK != ret)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (0 != open_allocs)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u (memory leak detected)\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+    }
+    else
+    {
+      fprintf (stderr,
+               "Memory test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+
+    /* Regular test: Free while decoding of control frame */
+    open_allocs = 0;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                               MHD_WEBSOCKET_FLAG_SERVER
+                                                               |
+                                                               MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      ret = MHD_websocket_decode (ws,
+                                  "\x88\x85\x00\x00\x00\x00Hel",
+                                  9,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (9 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_stream_free (ws);
+      if (MHD_WEBSOCKET_STATUS_OK != ret)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (0 != open_allocs)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u (memory leak detected)\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+    }
+    else
+    {
+      fprintf (stderr,
+               "Memory test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+
+    /* Regular test: Free while decoding of fragmented data frame */
+    open_allocs = 0;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                               MHD_WEBSOCKET_FLAG_SERVER
+                                                               |
+                                                               MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (11 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_stream_free (ws);
+      if (MHD_WEBSOCKET_STATUS_OK != ret)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (0 != open_allocs)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u (memory leak detected)\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+    }
+    else
+    {
+      fprintf (stderr,
+               "Memory test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+    /* Regular test: Free while decoding of continued fragmented data frame */
+    open_allocs = 0;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                               MHD_WEBSOCKET_FLAG_SERVER
+                                                               |
+                                                               MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (11 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_decode (ws,
+                                  "\x80\x85\x00\x00\x00\x00Hel",
+                                  9,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (9 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_stream_free (ws);
+      if (MHD_WEBSOCKET_STATUS_OK != ret)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (0 != open_allocs)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u (memory leak detected)\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+    }
+    else
+    {
+      fprintf (stderr,
+               "Memory test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+    /* Regular test: Free while decoding of control frame during fragmented data frame */
+    open_allocs = 0;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&ws,
+                                                               MHD_WEBSOCKET_FLAG_SERVER
+                                                               |
+                                                               MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      ret = MHD_websocket_decode (ws,
+                                  "\x01\x85\x00\x00\x00\x00Hello",
+                                  11,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (11 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_decode (ws,
+                                  "\x88\x85\x00\x00\x00\x00Hel",
+                                  9,
+                                  &streambuf_read_len,
+                                  &payload,
+                                  &payload_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (0 != payload_len) ||
+          (NULL != payload) ||
+          (9 != streambuf_read_len) )
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      ret = MHD_websocket_stream_free (ws);
+      if (MHD_WEBSOCKET_STATUS_OK != ret)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (0 != open_allocs)
+      {
+        fprintf (stderr,
+                 "Memory decode test failed in line %u (memory leak detected)\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+    }
+    else
+    {
+      fprintf (stderr,
+               "Memory test failed in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  if (NULL != buf1)
+  {
+    free (buf1);
+    buf1 = NULL;
+  }
+  if (NULL != buf2)
+  {
+    free (buf2);
+    buf2 = NULL;
+  }
+  return failed != 0 ? 0x04 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_encode_text()`
+ */
+int
+test_encodes_text ()
+{
+  int failed = 0;
+  struct MHD_WebSocketStream *wss;
+  struct MHD_WebSocketStream *wsc;
+  int ret;
+  char *buf1 = NULL, *buf2 = NULL;
+  char *frame = NULL;
+  size_t frame_len = 0;
+  int utf8_step = 0;
+
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc,
+                                                             MHD_WEBSOCKET_FLAG_CLIENT,
+                                                             0,
+                                                             malloc,
+                                                             realloc,
+                                                             free,
+                                                             NULL,
+                                                             test_rng))
+  {
+    fprintf (stderr,
+             "No encode text tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    return 0x08;
+  }
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss,
+                                                            MHD_WEBSOCKET_FLAG_SERVER,
+                                                            0))
+  {
+    fprintf (stderr,
+             "No encode text tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    if (NULL != wsc)
+      MHD_websocket_stream_free (wsc);
+    return 0x08;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Encoding
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data without UTF-8, we are server */
+  ret = MHD_websocket_encode_text (wss,
+                                   "blablabla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data without UTF-8, we are client */
+  ret = MHD_websocket_encode_text (wsc,
+                                   "blablabla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (15 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "blablabla",
+                                  9,
+                                  MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data with UTF-8, we are server */
+  ret = MHD_websocket_encode_text (wss,
+                                   "bla" "\xC3\xA4" "blabla",
+                                   11,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x0B" "bla" "\xC3\xA4" "blabla", 13)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data with UTF-8, we are client */
+  ret = MHD_websocket_encode_text (wsc,
+                                   "bla" "\xC3\xA4" "blabla",
+                                   11,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (17 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "bla" "\xC3\xA4" "blabla",
+                                  11,
+                                  MHD_WEBSOCKET_STATUS_TEXT_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Some data with NUL characters, we are server */
+  ret = MHD_websocket_encode_text (wss,
+                                   "bla" "\0\0\0" "bla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x09" "bla" "\0\0\0" "bla", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: Some data with broken UTF-8, we are server */
+  ret = MHD_websocket_encode_text (wss,
+                                   "bla" "\xC3" "blabla",
+                                   10,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Fragmentation
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data without UTF-8 */
+  ret = MHD_websocket_encode_text (wss,
+                                   "blablabla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x81\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: First fragment without UTF-8 */
+  ret = MHD_websocket_encode_text (wss,
+                                   "blablabla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FIRST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x01\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Middle fragment without UTF-8 */
+  ret = MHD_websocket_encode_text (wss,
+                                   "blablabla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x00\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment without UTF-8 */
+  ret = MHD_websocket_encode_text (wss,
+                                   "blablabla",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): First fragment with UTF-8 on the edge */
+  ret = MHD_websocket_encode_text (wss,
+                                   "blablabl\xC3",
+                                   9,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FIRST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1 != utf8_step) ||
+      (0 != memcmp (frame, "\x01\x09" "blablabl\xC3", 11)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Last fragment with UTF-8 on the edge */
+  ret = MHD_websocket_encode_text (wss,
+                                   "\xA4" "blablabla",
+                                   10,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (12 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0A" "\xA4" "blablabla", 12)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: Last fragment with UTF-8 on the edge (here with wrong old utf8_step) */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\xA4" "blablabla",
+                                   10,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF2TAIL_1OF1 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\xA4" "blablabla",
+                                   10,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (12 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0A" "\xA4" "blablabla", 12)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL1_1OF2 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL1_1OF2;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\xA0\x80" "blablabla",
+                                   11,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0B" "\xA0\x80" "blablabla", 13)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL2_1OF2 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL2_1OF2;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80\x80" "blablabla",
+                                   11,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0B" "\x80\x80" "blablabla", 13)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL_1OF2 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_1OF2;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80\x80" "blablabla",
+                                   11,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0B" "\x80\x80" "blablabla", 13)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF3TAIL_2OF2 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF3TAIL_2OF2;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80" " blablabla",
+                                   11,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0B" "\x80" " blablabla", 13)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL1_1OF3 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL1_1OF3;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x90\x80\x80" "blablabla",
+                                   12,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (14 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0C" "\x90\x80\x80" "blablabla", 14)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL2_1OF3 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL2_1OF3;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80\x80\x80" "blablabla",
+                                   12,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (14 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0C" "\x80\x80\x80" "blablabla", 14)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL_1OF3 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_1OF3;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80\x80\x80" "blablabla",
+                                   12,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (14 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0C" "\x80\x80\x80" "blablabla", 14)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL_2OF3 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_2OF3;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80\x80" " blablabla",
+                                   12,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (14 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0C" "\x80\x80" " blablabla", 14)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment with UTF-8 on the edge for UTF4TAIL_3OF3 */
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_UTF4TAIL_3OF3;
+  ret = MHD_websocket_encode_text (wss,
+                                   "\x80" "  blablabla",
+                                   12,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (14 != frame_len) ||
+      (NULL == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x0C" "\x80" "  blablabla", 14)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Length checks
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): Text frame without data */
+  ret = MHD_websocket_encode_text (wss,
+                                   NULL,
+                                   0,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Text frame with 1 byte of data */
+  ret = MHD_websocket_encode_text (wss,
+                                   "a",
+                                   1,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (3 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x01" "a", 3)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Text frame with 125 bytes of data */
+  ret = MHD_websocket_encode_text (wss,
+                                   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                   125,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (127 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x7D"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                    127)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Text frame with 126 bytes of data */
+  ret = MHD_websocket_encode_text (wss,
+                                   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                   126,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (130 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x81\x7E\x00\x7E"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                    130)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Text frame with 65535 bytes of data */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             65535,
+                             "\x81\x7E\xFF\xFF",
+                             4);
+  ret = MHD_websocket_encode_text (wss,
+                                   buf2,
+                                   65535,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (65535 + 4 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, buf1, 65535 + 4)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Text frame with 65536 bytes of data */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             65536,
+                             "\x81\x7F\x00\x00\x00\x00\x00\x01\x00\x00",
+                             10);
+  ret = MHD_websocket_encode_text (wss,
+                                   buf2,
+                                   65536,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (65536 + 10 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, buf1, 65536 + 10)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Text frame with 100 MB of data */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             104857600,
+                             "\x81\x7F\x00\x00\x00\x00\x06\x40\x00\x00",
+                             10);
+  ret = MHD_websocket_encode_text (wss,
+                                   buf2,
+                                   104857600,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (104857600 + 10 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, buf1, 104857600 + 10)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  if (NULL != buf1)
+  {
+    free (buf1);
+    buf1 = NULL;
+  }
+  if (NULL != buf2)
+  {
+    free (buf2);
+    buf2 = NULL;
+  }
+#ifdef ENABLE_64BIT_TESTS
+  /* Fail test: frame_len is greater than 0x7FFFFFFFFFFFFFFF
+     (this is the maximum allowed payload size) */
+  frame_len = 0;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   (uint64_t) 0x8000000000000000,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+#endif
+
+  /*
+  ------------------------------------------------------------------------------
+    Wrong parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: `ws` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (NULL,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `payload_utf8` not passed, but `payload_utf8_len` != 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (wss,
+                                   NULL,
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `payload_utf8` passed, but `payload_utf8_len` == 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   0,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (0 != memcmp (frame, "\x81\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `frame` not passed */
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   NULL,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: `frame_len` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   NULL,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `utf8_step` passed for non-fragmentation
+     (is allowed and `utf8_step` will be filled then) */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  utf8_step = -99;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (5 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x81\x03" "abc", 5)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `utf8_step` passed for non-fragmentation with invalid UTF-8
+     (is allowed and `utf8_step` will be filled then) */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  utf8_step = -99;
+  ret = MHD_websocket_encode_text (wss,
+                                   "ab\xC3",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_UTF2TAIL_1OF1 != utf8_step) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `utf8_step` not passed for fragmentation #1 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FIRST,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `utf8_step` not passed for fragmentation #2 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `utf8_step` not passed for fragmentation #3 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `utf8_step` passed for fragmentation #1 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  utf8_step = -99;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FIRST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (5 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x01\x03" "abc", 5)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `utf8_step` passed for fragmentation #2 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (5 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x00\x03" "abc", 5)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `utf8_step` passed for fragmentation #3 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  utf8_step = MHD_WEBSOCKET_UTF8STEP_NORMAL;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (5 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (MHD_WEBSOCKET_UTF8STEP_NORMAL != utf8_step) ||
+      (0 != memcmp (frame, "\x80\x03" "abc", 5)))
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `fragmentation` has an invalid value */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  utf8_step = -99;
+  ret = MHD_websocket_encode_text (wss,
+                                   "abc",
+                                   3,
+                                   MHD_WEBSOCKET_FRAGMENTATION_LAST + 1,
+                                   &frame,
+                                   &frame_len,
+                                   &utf8_step);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) ||
+      (-99 != utf8_step) )
+  {
+    fprintf (stderr,
+             "Encode text test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    validity after temporary out-of-memory
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *wsx;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx,
+                                                               MHD_WEBSOCKET_FLAG_SERVER,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      /* Fail test: allocation while no memory available */
+      disable_alloc = 1;
+      ret = MHD_websocket_encode_text (wsx,
+                                       "abc",
+                                       3,
+                                       MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                       &frame,
+                                       &frame_len,
+                                       NULL);
+      if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+          (0 != frame_len) ||
+          (NULL != frame) )
+      {
+        fprintf (stderr,
+                 "Encode text test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+      /* Regular test: allocation while memory is available again */
+      disable_alloc = 0;
+      ret = MHD_websocket_encode_text (wsx,
+                                       "abc",
+                                       3,
+                                       MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                       &frame,
+                                       &frame_len,
+                                       NULL);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (5 != frame_len) ||
+          (NULL == frame) ||
+          (0 != memcmp (frame, "\x81\x03" "abc", 5)))
+      {
+        fprintf (stderr,
+                 "Encode text test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+
+      MHD_websocket_stream_free (wsx);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Couldn't perform memory test for text encoding in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  if (NULL != buf1)
+    free (buf1);
+  if (NULL != buf2)
+    free (buf2);
+  if (NULL != wsc)
+    MHD_websocket_stream_free (wsc);
+  if (NULL != wss)
+    MHD_websocket_stream_free (wss);
+
+  return failed != 0 ? 0x08 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_encode_binary()`
+ */
+int
+test_encodes_binary ()
+{
+  int failed = 0;
+  struct MHD_WebSocketStream *wss;
+  struct MHD_WebSocketStream *wsc;
+  int ret;
+  char *buf1 = NULL, *buf2 = NULL;
+  char *frame = NULL;
+  size_t frame_len = 0;
+
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc,
+                                                             MHD_WEBSOCKET_FLAG_CLIENT,
+                                                             0,
+                                                             malloc,
+                                                             realloc,
+                                                             free,
+                                                             NULL,
+                                                             test_rng))
+  {
+    fprintf (stderr,
+             "No encode binary tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    return 0x10;
+  }
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss,
+                                                            MHD_WEBSOCKET_FLAG_SERVER,
+                                                            0))
+  {
+    fprintf (stderr,
+             "No encode binary tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    if (NULL != wsc)
+      MHD_websocket_stream_free (wsc);
+    return 0x10;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Encoding
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data, we are server */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "blablabla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data, we are client */
+  ret = MHD_websocket_encode_binary (wsc,
+                                     "blablabla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (15 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "blablabla",
+                                  9,
+                                  MHD_WEBSOCKET_STATUS_BINARY_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Some data with NUL characters, we are server */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "bla" "\0\0\0" "bla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x09" "bla" "\0\0\0" "bla", 11)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data which looks like broken UTF-8, we are server */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "bla" "\xC3" "blabla",
+                                     10,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (12 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x0A" "bla" "\xC3" "blabla", 12)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Fragmentation
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "blablabla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: First fragment */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "blablabla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_FIRST,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x02\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Middle fragment */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "blablabla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_FOLLOWING,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x00\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Last fragment  */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "blablabla",
+                                     9,
+                                     MHD_WEBSOCKET_FRAGMENTATION_LAST,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x80\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Length checks
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): Binary frame without data */
+  ret = MHD_websocket_encode_binary (wss,
+                                     NULL,
+                                     0,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Binary frame with 1 byte of data */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "a",
+                                     1,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (3 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x01" "a", 3)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Binary frame with 125 bytes of data */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                     125,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (127 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x7D"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                    127)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Binary frame with 126 bytes of data */
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                     126,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (130 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x82\x7E\x00\x7E"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                    130)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Binary frame with 65535 bytes of data */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             65535,
+                             "\x82\x7E\xFF\xFF",
+                             4);
+  ret = MHD_websocket_encode_binary (wss,
+                                     buf2,
+                                     65535,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (65535 + 4 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, buf1, 65535 + 4)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Binary frame with 65536 bytes of data */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             65536,
+                             "\x82\x7F\x00\x00\x00\x00\x00\x01\x00\x00",
+                             10);
+  ret = MHD_websocket_encode_binary (wss,
+                                     buf2,
+                                     65536,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (65536 + 10 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, buf1, 65536 + 10)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Binary frame with 100 MB of data */
+  allocate_length_test_data (&buf1,
+                             &buf2,
+                             104857600,
+                             "\x82\x7F\x00\x00\x00\x00\x06\x40\x00\x00",
+                             10);
+  ret = MHD_websocket_encode_binary (wss,
+                                     buf2,
+                                     104857600,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (104857600 + 10 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, buf1, 104857600 + 10)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  if (NULL != buf1)
+  {
+    free (buf1);
+    buf1 = NULL;
+  }
+  if (NULL != buf2)
+  {
+    free (buf2);
+    buf2 = NULL;
+  }
+#ifdef ENABLE_64BIT_TESTS
+  /* Fail test: `frame_len` is greater than 0x7FFFFFFFFFFFFFFF
+     (this is the maximum allowed payload size) */
+  frame_len = 0;
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abc",
+                                     (uint64_t) 0x8000000000000000,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+#endif
+
+  /*
+  ------------------------------------------------------------------------------
+    Wrong parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: `ws` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_binary (NULL,
+                                     "abc",
+                                     3,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `payload` not passed, but `payload_len` != 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_binary (wss,
+                                     NULL,
+                                     3,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `payload` passed, but `payload_len` == 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abc",
+                                     0,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (0 != memcmp (frame, "\x82\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `frame` not passed */
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abc",
+                                     3,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     NULL,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: `frame_len` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abc",
+                                     3,
+                                     MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                     &frame,
+                                     NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `fragmentation` has an invalid value */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_binary (wss,
+                                     "abc",
+                                     3,
+                                     MHD_WEBSOCKET_FRAGMENTATION_LAST + 1,
+                                     &frame,
+                                     &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode binary test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    validity after temporary out-of-memory
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *wsx;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx,
+                                                               MHD_WEBSOCKET_FLAG_SERVER,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      /* Fail test: allocation while no memory available */
+      disable_alloc = 1;
+      ret = MHD_websocket_encode_binary (wsx,
+                                         "abc",
+                                         3,
+                                         MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                         &frame,
+                                         &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+          (0 != frame_len) ||
+          (NULL != frame) )
+      {
+        fprintf (stderr,
+                 "Encode binary test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+      /* Regular test: allocation while memory is available again */
+      disable_alloc = 0;
+      ret = MHD_websocket_encode_binary (wsx,
+                                         "abc",
+                                         3,
+                                         MHD_WEBSOCKET_FRAGMENTATION_NONE,
+                                         &frame,
+                                         &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (5 != frame_len) ||
+          (NULL == frame) ||
+          (0 != memcmp (frame, "\x82\x03" "abc", 5)))
+      {
+        fprintf (stderr,
+                 "Encode binary test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+
+      MHD_websocket_stream_free (wsx);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Couldn't perform memory test for binary encoding in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  if (NULL != buf1)
+    free (buf1);
+  if (NULL != buf2)
+    free (buf2);
+  if (NULL != wsc)
+    MHD_websocket_stream_free (wsc);
+  if (NULL != wss)
+    MHD_websocket_stream_free (wss);
+
+  return failed != 0 ? 0x10 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_encode_close()`
+ */
+int
+test_encodes_close ()
+{
+  int failed = 0;
+  struct MHD_WebSocketStream *wss;
+  struct MHD_WebSocketStream *wsc;
+  int ret;
+  char *buf1 = NULL, *buf2 = NULL;
+  char *frame = NULL;
+  size_t frame_len = 0;
+
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc,
+                                                             MHD_WEBSOCKET_FLAG_CLIENT,
+                                                             0,
+                                                             malloc,
+                                                             realloc,
+                                                             free,
+                                                             NULL,
+                                                             test_rng))
+  {
+    fprintf (stderr,
+             "No encode close tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    return 0x10;
+  }
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wss,
+                                                             MHD_WEBSOCKET_FLAG_SERVER,
+                                                             0,
+                                                             malloc,
+                                                             realloc,
+                                                             free,
+                                                             NULL,
+                                                             test_rng))
+  {
+    fprintf (stderr,
+             "No encode close tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    if (NULL != wsc)
+      MHD_websocket_stream_free (wsc);
+    return 0x10;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Encoding
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data, we are server */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "blablabla",
+                                    9,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x0B\x03\xE8" "blablabla", 13)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data, we are client */
+  ret = MHD_websocket_encode_close (wsc,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "blablabla",
+                                    9,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (17 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "\x03\xE8" "blablabla",
+                                  11,
+                                  MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Close reason without text, we are server */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    NULL,
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (4 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x02\x03\xE8", 4)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Close reason without text, we are client */
+  ret = MHD_websocket_encode_close (wsc,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    NULL,
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (8 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "\x03\xE8",
+                                  2,
+                                  MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Close without reason, we are server */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_NO_REASON,
+                                    NULL,
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Close without reason, we are client */
+  ret = MHD_websocket_encode_close (wsc,
+                                    MHD_WEBSOCKET_CLOSEREASON_NO_REASON,
+                                    NULL,
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (6 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  NULL,
+                                  0,
+                                  MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Close with UTF-8 sequence in reason, we are client */
+  ret = MHD_websocket_encode_close (wsc,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "bla" "\xC3\xA4" "blabla",
+                                    11,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (19 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "\x03\xE8" "bla" "\xC3\xA4" "blabla",
+                                  13,
+                                  MHD_WEBSOCKET_STATUS_CLOSE_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_ONLY_VALID_FOR_CONTROL_FRAMES,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Close reason with NUL characters, we are server */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_GOING_AWAY,
+                                    "bla" "\0\0\0" "bla",
+                                    9,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (13 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x0B\x03\xE9" "bla" "\0\0\0" "bla", 13)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: Some data with broken UTF-8, we are server */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "bla" "\xC3" "blabla",
+                                    10,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_UTF8_ENCODING_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Length checks
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): Close frame without payload */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_NO_REASON,
+                                    NULL,
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Close frame only reason code */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    NULL,
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (4 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x02\x03\xE8", 4)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Close frame with 1 bytes of reason text */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "a",
+                                    1,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (5 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x03\x03\xE8" "a", 5)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Close frame with 123 bytes of reason text */
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456",
+                                    123,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (127 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x88\x7D\x03\xE8"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456",
+                    127)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (fail): Close frame with 124 bytes of reason text*/
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567",
+                                    124,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Wrong parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: `ws` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (NULL,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "abc",
+                                    3,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `payload` not passed, but `payload_len` != 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    NULL,
+                                    3,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `payload` passed, but `payload_len` == 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "abc",
+                                    0,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (4 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (0 != memcmp (frame, "\x88\x02\x03\xE8", 4)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `frame` not passed */
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "abc",
+                                    3,
+                                    NULL,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: `frame_len` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                    "abc",
+                                    3,
+                                    &frame,
+                                    NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: no reason code passed, but reason text */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    MHD_WEBSOCKET_CLOSEREASON_NO_REASON,
+                                    "abc",
+                                    3,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (fail): Invalid reason code */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    1,
+                                    "abc",
+                                    3,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (fail): Invalid reason code */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    999,
+                                    "abc",
+                                    3,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Custom reason code */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_close (wss,
+                                    2000,
+                                    "abc",
+                                    3,
+                                    &frame,
+                                    &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (7 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (0 != memcmp (frame, "\x88\x05\x07\xD0" "abc", 7)))
+  {
+    fprintf (stderr,
+             "Encode close test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    validity after temporary out-of-memory
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *wsx;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx,
+                                                               MHD_WEBSOCKET_FLAG_SERVER,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      /* Fail test: allocation while no memory available */
+      disable_alloc = 1;
+      ret = MHD_websocket_encode_close (wsx,
+                                        MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                        "abc",
+                                        3,
+                                        &frame,
+                                        &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+          (0 != frame_len) ||
+          (NULL != frame) )
+      {
+        fprintf (stderr,
+                 "Encode close test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+      /* Regular test: allocation while memory is available again */
+      disable_alloc = 0;
+      ret = MHD_websocket_encode_close (wsx,
+                                        MHD_WEBSOCKET_CLOSEREASON_REGULAR,
+                                        "abc",
+                                        3,
+                                        &frame,
+                                        &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (7 != frame_len) ||
+          (NULL == frame) ||
+          (0 != memcmp (frame, "\x88\x05\x03\xE8" "abc", 7)))
+      {
+        fprintf (stderr,
+                 "Encode close test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+
+      MHD_websocket_stream_free (wsx);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Couldn't perform memory test for close encoding in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  if (NULL != buf1)
+    free (buf1);
+  if (NULL != buf2)
+    free (buf2);
+  if (NULL != wsc)
+    MHD_websocket_stream_free (wsc);
+  if (NULL != wss)
+    MHD_websocket_stream_free (wss);
+
+  return failed != 0 ? 0x20 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_encode_ping()`
+ */
+int
+test_encodes_ping ()
+{
+  int failed = 0;
+  struct MHD_WebSocketStream *wss;
+  struct MHD_WebSocketStream *wsc;
+  int ret;
+  char *buf1 = NULL, *buf2 = NULL;
+  char *frame = NULL;
+  size_t frame_len = 0;
+
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc,
+                                                             MHD_WEBSOCKET_FLAG_CLIENT,
+                                                             0,
+                                                             malloc,
+                                                             realloc,
+                                                             free,
+                                                             NULL,
+                                                             test_rng))
+  {
+    fprintf (stderr,
+             "No encode ping tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    return 0x10;
+  }
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss,
+                                                            MHD_WEBSOCKET_FLAG_SERVER,
+                                                            0))
+  {
+    fprintf (stderr,
+             "No encode ping tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    if (NULL != wsc)
+      MHD_websocket_stream_free (wsc);
+    return 0x10;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Encoding
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data, we are server */
+  ret = MHD_websocket_encode_ping (wss,
+                                   "blablabla",
+                                   9,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data, we are client */
+  ret = MHD_websocket_encode_ping (wsc,
+                                   "blablabla",
+                                   9,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (15 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "blablabla",
+                                  9,
+                                  MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Ping without payload, we are server */
+  ret = MHD_websocket_encode_ping (wss,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Ping without payload, we are client */
+  ret = MHD_websocket_encode_ping (wsc,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (6 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  NULL,
+                                  0,
+                                  MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Ping with something like UTF-8 sequence in payload, we are client */
+  ret = MHD_websocket_encode_ping (wsc,
+                                   "bla" "\xC3\xA4" "blabla",
+                                   11,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (17 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "bla" "\xC3\xA4" "blabla",
+                                  11,
+                                  MHD_WEBSOCKET_STATUS_PING_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Ping payload with NUL characters, we are server */
+  ret = MHD_websocket_encode_ping (wss,
+                                   "bla" "\0\0\0" "bla",
+                                   9,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x09" "bla" "\0\0\0" "bla", 11)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Ping payload with with something which looks like broken UTF-8, we are server */
+  ret = MHD_websocket_encode_ping (wss,
+                                   "bla" "\xC3" "blabla",
+                                   10,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (12 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x0A" "bla" "\xC3" "blabla", 12)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Length checks
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): Ping frame without payload */
+  ret = MHD_websocket_encode_ping (wss,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Ping frame with one byte of payload */
+  ret = MHD_websocket_encode_ping (wss,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Ping frame with 125 bytes of payload */
+  ret = MHD_websocket_encode_ping (wss,
+                                   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                   125,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (127 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x89\x7D"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                    127)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (fail): Ping frame with 126 bytes of payload */
+  ret = MHD_websocket_encode_ping (wss,
+                                   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                   126,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Wrong parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: `ws` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_ping (NULL,
+                                   "abc",
+                                   3,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `payload` not passed, but `payload_len` != 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_ping (wss,
+                                   NULL,
+                                   3,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `payload` passed, but `payload_len` == 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_ping (wss,
+                                   "abc",
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (0 != memcmp (frame, "\x89\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `frame` not passed */
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_ping (wss,
+                                   "abc",
+                                   3,
+                                   NULL,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: `frame_len` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  ret = MHD_websocket_encode_ping (wss,
+                                   "abc",
+                                   3,
+                                   &frame,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode ping test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    validity after temporary out-of-memory
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *wsx;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx,
+                                                               MHD_WEBSOCKET_FLAG_SERVER,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      /* Fail test: allocation while no memory available */
+      disable_alloc = 1;
+      ret = MHD_websocket_encode_ping (wsx,
+                                       "abc",
+                                       3,
+                                       &frame,
+                                       &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+          (0 != frame_len) ||
+          (NULL != frame) )
+      {
+        fprintf (stderr,
+                 "Encode ping test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+      /* Regular test: allocation while memory is available again */
+      disable_alloc = 0;
+      ret = MHD_websocket_encode_ping (wsx,
+                                       "abc",
+                                       3,
+                                       &frame,
+                                       &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (5 != frame_len) ||
+          (NULL == frame) ||
+          (0 != memcmp (frame, "\x89\x03" "abc", 5)))
+      {
+        fprintf (stderr,
+                 "Encode ping test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+
+      MHD_websocket_stream_free (wsx);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Couldn't perform memory test for ping encoding in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  if (NULL != buf1)
+    free (buf1);
+  if (NULL != buf2)
+    free (buf2);
+  if (NULL != wsc)
+    MHD_websocket_stream_free (wsc);
+  if (NULL != wss)
+    MHD_websocket_stream_free (wss);
+
+  return failed != 0 ? 0x40 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_encode_pong()`
+ */
+int
+test_encodes_pong ()
+{
+  int failed = 0;
+  struct MHD_WebSocketStream *wss;
+  struct MHD_WebSocketStream *wsc;
+  int ret;
+  char *buf1 = NULL, *buf2 = NULL;
+  char *frame = NULL;
+  size_t frame_len = 0;
+
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init2 (&wsc,
+                                                             MHD_WEBSOCKET_FLAG_CLIENT,
+                                                             0,
+                                                             malloc,
+                                                             realloc,
+                                                             free,
+                                                             NULL,
+                                                             test_rng))
+  {
+    fprintf (stderr,
+             "No encode pong tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    return 0x10;
+  }
+  if (MHD_WEBSOCKET_STATUS_OK != MHD_websocket_stream_init (&wss,
+                                                            MHD_WEBSOCKET_FLAG_SERVER,
+                                                            0))
+  {
+    fprintf (stderr,
+             "No encode pong tests possible due to failed stream init in line %u\n",
+             (unsigned int) __LINE__);
+    if (NULL != wsc)
+      MHD_websocket_stream_free (wsc);
+    return 0x10;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Encoding
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Some data, we are server */
+  ret = MHD_websocket_encode_pong (wss,
+                                   "blablabla",
+                                   9,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x09" "blablabla", 11)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Some data, we are client */
+  ret = MHD_websocket_encode_pong (wsc,
+                                   "blablabla",
+                                   9,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (15 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "blablabla",
+                                  9,
+                                  MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Pong without payload, we are server */
+  ret = MHD_websocket_encode_pong (wss,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Pong without payload, we are client */
+  ret = MHD_websocket_encode_pong (wsc,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (6 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  NULL,
+                                  0,
+                                  MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Regular test: Pong with something like UTF-8 sequence in payload, we are client */
+  ret = MHD_websocket_encode_pong (wsc,
+                                   "bla" "\xC3\xA4" "blabla",
+                                   11,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (17 != frame_len) ||
+      (NULL == frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  else
+  {
+    failed += test_decode_single (__LINE__,
+                                  MHD_WEBSOCKET_FLAG_SERVER
+                                  | MHD_WEBSOCKET_FLAG_NO_FRAGMENTS,
+                                  0,
+                                  1,
+                                  0,
+                                  frame,
+                                  frame_len,
+                                  "bla" "\xC3\xA4" "blabla",
+                                  11,
+                                  MHD_WEBSOCKET_STATUS_PONG_FRAME,
+                                  MHD_WEBSOCKET_VALIDITY_VALID,
+                                  frame_len);
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wsc, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Pong payload with NUL characters, we are server */
+  ret = MHD_websocket_encode_pong (wss,
+                                   "bla" "\0\0\0" "bla",
+                                   9,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (11 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x09" "bla" "\0\0\0" "bla", 11)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: Pong payload with with something which looks like broken UTF-8, we are server */
+  ret = MHD_websocket_encode_pong (wss,
+                                   "bla" "\xC3" "blabla",
+                                   10,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (12 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x0A" "bla" "\xC3" "blabla", 12)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Length checks
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): Pong frame without payload */
+  ret = MHD_websocket_encode_pong (wss,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Pong frame with one byte of payload */
+  ret = MHD_websocket_encode_pong (wss,
+                                   NULL,
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (success): Pong frame with 125 bytes of payload */
+  ret = MHD_websocket_encode_pong (wss,
+                                   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                                   125,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (127 != frame_len) ||
+      (NULL == frame) ||
+      (0 != memcmp (frame, "\x8A\x7D"
+                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678",
+                    127)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Edge test (fail): Pong frame with 126 bytes of payload */
+  ret = MHD_websocket_encode_pong (wss,
+                                   "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+                                   126,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_MAXIMUM_SIZE_EXCEEDED != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Wrong parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: `ws` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_pong (NULL,
+                                   "abc",
+                                   3,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `payload` not passed, but `payload_len` != 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_pong (wss,
+                                   NULL,
+                                   3,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Regular test: `payload` passed, but `payload_len` == 0 */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_pong (wss,
+                                   "abc",
+                                   0,
+                                   &frame,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (2 != frame_len) ||
+      (NULL == frame) ||
+      (((char *) (uintptr_t) 0xBAADF00D) == frame) ||
+      (0 != memcmp (frame, "\x8A\x00", 2)))
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+  /* Fail test: `frame` not passed */
+  frame_len = 0x87654321;
+  ret = MHD_websocket_encode_pong (wss,
+                                   "abc",
+                                   3,
+                                   NULL,
+                                   &frame_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (0 != frame_len) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: `frame_len` not passed */
+  frame = (char *) (uintptr_t) 0xBAADF00D;
+  ret = MHD_websocket_encode_pong (wss,
+                                   "abc",
+                                   3,
+                                   &frame,
+                                   NULL);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (NULL != frame) )
+  {
+    fprintf (stderr,
+             "Encode pong test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  if (((char *) (uintptr_t) 0xBAADF00D) == frame)
+  {
+    frame = NULL;
+  }
+  if (NULL != frame)
+  {
+    MHD_websocket_free (wss, frame);
+    frame = NULL;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    validity after temporary out-of-memory
+  ------------------------------------------------------------------------------
+  */
+  {
+    struct MHD_WebSocketStream *wsx;
+    if (MHD_WEBSOCKET_STATUS_OK == MHD_websocket_stream_init2 (&wsx,
+                                                               MHD_WEBSOCKET_FLAG_SERVER,
+                                                               0,
+                                                               test_malloc,
+                                                               test_realloc,
+                                                               test_free,
+                                                               NULL,
+                                                               NULL))
+    {
+      /* Fail test: allocation while no memory available */
+      disable_alloc = 1;
+      ret = MHD_websocket_encode_pong (wsx,
+                                       "abc",
+                                       3,
+                                       &frame,
+                                       &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_MEMORY_ERROR != ret) ||
+          (0 != frame_len) ||
+          (NULL != frame) )
+      {
+        fprintf (stderr,
+                 "Encode pong test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+      /* Regular test: allocation while memory is available again */
+      disable_alloc = 0;
+      ret = MHD_websocket_encode_pong (wsx,
+                                       "abc",
+                                       3,
+                                       &frame,
+                                       &frame_len);
+      if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+          (5 != frame_len) ||
+          (NULL == frame) ||
+          (0 != memcmp (frame, "\x8A\x03" "abc", 5)))
+      {
+        fprintf (stderr,
+                 "Encode pong test failed in line %u\n",
+                 (unsigned int) __LINE__);
+        ++failed;
+      }
+      if (NULL != frame)
+      {
+        MHD_websocket_free (wsx, frame);
+        frame = NULL;
+      }
+
+      MHD_websocket_stream_free (wsx);
+    }
+    else
+    {
+      fprintf (stderr,
+               "Couldn't perform memory test for pong encoding in line %u\n",
+               (unsigned int) __LINE__);
+      ++failed;
+    }
+  }
+
+  if (NULL != buf1)
+    free (buf1);
+  if (NULL != buf2)
+    free (buf2);
+  if (NULL != wsc)
+    MHD_websocket_stream_free (wsc);
+  if (NULL != wss)
+    MHD_websocket_stream_free (wss);
+
+  return failed != 0 ? 0x80 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_split_close_reason()`
+ */
+int
+test_split_close_reason ()
+{
+  int failed = 0;
+  const char *payload;
+  unsigned short reason_code;
+  const char *reason_utf8;
+  size_t reason_utf8_len;
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    Normal splits
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Reason code + Reason text */
+  reason_code = 9999;
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  reason_utf8_len = 12345;
+  payload = "\x03\xE8" "abc";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          5,
+                                          &reason_code,
+                                          &reason_utf8,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) ||
+      (3 != reason_utf8_len) ||
+      (payload + 2 != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: Reason code */
+  reason_code = 9999;
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  reason_utf8_len = 12345;
+  payload = "\x03\xE8";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          2,
+                                          &reason_code,
+                                          &reason_utf8,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) ||
+      (0 != reason_utf8_len) ||
+      (NULL != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: No payload */
+  reason_code = 9999;
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  reason_utf8_len = 12345;
+  payload = NULL;
+  ret = MHD_websocket_split_close_reason (payload,
+                                          0,
+                                          &reason_code,
+                                          &reason_utf8,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) ||
+      (0 != reason_utf8_len) ||
+      (NULL != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: `payload` is not NULL given, but `payload_len` == 0 */
+  reason_code = 9999;
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  reason_utf8_len = 12345;
+  payload = "abc";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          0,
+                                          &reason_code,
+                                          &reason_utf8,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) ||
+      (0 != reason_utf8_len) ||
+      (NULL != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Wrong parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: `payload` not passed, but `payload_len` != 0 */
+  reason_code = 9999;
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  reason_utf8_len = 12345;
+  payload = NULL;
+  ret = MHD_websocket_split_close_reason (payload,
+                                          3,
+                                          &reason_code,
+                                          &reason_utf8,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_PARAMETER_ERROR != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_NO_REASON != reason_code) ||
+      (0 != reason_utf8_len) ||
+      (NULL != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: `reason_code` not passed */
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  reason_utf8_len = 12345;
+  payload = "\x03\xE8" "abc";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          5,
+                                          NULL,
+                                          &reason_utf8,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (3 != reason_utf8_len) ||
+      (payload + 2 != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: `reason_utf8` not passed */
+  reason_code = 9999;
+  reason_utf8_len = 12345;
+  payload = "\x03\xE8" "abc";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          5,
+                                          &reason_code,
+                                          NULL,
+                                          &reason_utf8_len);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) ||
+      (3 != reason_utf8_len) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: `reason_utf8_len` not passed */
+  reason_code = 9999;
+  reason_utf8 = (const char *) (intptr_t) 0xBAADF00D;
+  payload = "\x03\xE8" "abc";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          5,
+                                          &reason_code,
+                                          &reason_utf8,
+                                          NULL);
+  if ((MHD_WEBSOCKET_STATUS_OK != ret) ||
+      (MHD_WEBSOCKET_CLOSEREASON_REGULAR != reason_code) ||
+      (payload + 2 != reason_utf8) )
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: `reason_code`, `reason_utf8` and `reason_utf8_len` not passed */
+  /* (this is not prohibited, although it doesn't really make sense) */
+  payload = "\x03\xE8" "abc";
+  ret = MHD_websocket_split_close_reason (payload,
+                                          5,
+                                          NULL,
+                                          NULL,
+                                          NULL);
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "split close reason test failed in line %u\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  return failed != 0 ? 0x100 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_check_http_version()`
+ */
+int
+test_check_http_version ()
+{
+  int failed = 0;
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    Version check with valid HTTP version syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: HTTP/1.1 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.1");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: HTTP/1.2 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.2");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: HTTP/1.10 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.10");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: HTTP/2.0 */
+  ret = MHD_websocket_check_http_version ("HTTP/2.0");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: HTTP/3.0 */
+  ret = MHD_websocket_check_http_version ("HTTP/3.0");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: HTTP/1.0 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.0");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: HTTP/0.9 */
+  ret = MHD_websocket_check_http_version ("HTTP/0.9");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Version check edge cases
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): HTTP/123.45 */
+  ret = MHD_websocket_check_http_version ("HTTP/123.45");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/1.45 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.45");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/01.1 */
+  ret = MHD_websocket_check_http_version ("HTTP/01.1");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/0001.1 */
+  ret = MHD_websocket_check_http_version ("HTTP/0001.1");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/1.01 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.01");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/1.0001 */
+  ret = MHD_websocket_check_http_version ("HTTP/1.0001");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/0001.0001 */
+  ret = MHD_websocket_check_http_version ("HTTP/0001.0001");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/2.000 */
+  ret = MHD_websocket_check_http_version ("HTTP/2.000");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): HTTP/0.0 */
+  ret = MHD_websocket_check_http_version ("HTTP/0.0");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): HTTP/00.0 */
+  ret = MHD_websocket_check_http_version ("HTTP/00.0");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): HTTP/00.0 */
+  ret = MHD_websocket_check_http_version ("HTTP/0.00");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Invalid version syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: (empty string) */
+  ret = MHD_websocket_check_http_version ("");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: http/1.1 */
+  ret = MHD_websocket_check_http_version ("http/1.1");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: "HTTP / 1.1" */
+  ret = MHD_websocket_check_http_version ("HTTP / 1.1");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Missing parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: NULL as version */
+  ret = MHD_websocket_check_http_version (NULL);
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_http_version test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  return failed != 0 ? 0x200 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_check_connection_header()`
+ */
+int
+test_check_connection_header ()
+{
+  int failed = 0;
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    Check with valid Connection header syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: Upgrade */
+  ret = MHD_websocket_check_connection_header ("Upgrade");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Regular test: keep-alive, Upgrade */
+  ret = MHD_websocket_check_connection_header ("keep-alive, Upgrade");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: keep-alive */
+  ret = MHD_websocket_check_connection_header ("keep-alive");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: close */
+  ret = MHD_websocket_check_connection_header ("close");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Connection check edge cases
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): keep-alive,Upgrade */
+  ret = MHD_websocket_check_connection_header ("keep-alive,Upgrade");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): Upgrade, keep-alive */
+  ret = MHD_websocket_check_connection_header ("Upgrade, keep-alive");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): Upgrade,keep-alive */
+  ret = MHD_websocket_check_connection_header ("Upgrade,keep-alive");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): Transfer-Encoding,Upgrade,keep-alive */
+  ret = MHD_websocket_check_connection_header (
+    "Transfer-Encoding,Upgrade,keep-alive");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): Transfer-Encoding  ,  Upgrade  ,  keep-alive */
+  ret = MHD_websocket_check_connection_header (
+    "Transfer-Encoding  ,  Upgrade  ,  keep-alive");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): upgrade */
+  ret = MHD_websocket_check_connection_header ("upgrade");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): UPGRADE */
+  ret = MHD_websocket_check_connection_header ("UPGRADE");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): All allowed token characters, then upgrade token */
+  ret = MHD_websocket_check_connection_header (
+    "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz,Upgrade");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): Different, allowed whitespaces */
+  ret = MHD_websocket_check_connection_header (" \tUpgrade \t");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_connection_header ("\rUpgrade");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_connection_header ("\nUpgrade");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_connection_header ("\vUpgrade");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_connection_header ("\fUpgrade");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Invalid header syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: (empty string) */
+  ret = MHD_websocket_check_connection_header ("");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: (Disallowed) multiple word token with the term "Upgrade" in it */
+  ret = MHD_websocket_check_connection_header ("Upgrade or Downgrade");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: Invalid characters */
+  ret = MHD_websocket_check_connection_header ("\"Upgrade\"");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Missing parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: NULL as connection */
+  ret = MHD_websocket_check_connection_header (NULL);
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_connection_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  return failed != 0 ? 0x400 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_check_upgrade_header()`
+ */
+int
+test_check_upgrade_header ()
+{
+  int failed = 0;
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    Check with valid Upgrade header syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: websocket */
+  ret = MHD_websocket_check_upgrade_header ("websocket");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: HTTP/2.0 */
+  ret = MHD_websocket_check_upgrade_header ("HTTP/2.0");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Upgrade check edge cases
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (success): websocket,HTTP/2.0 */
+  ret = MHD_websocket_check_upgrade_header ("websocket,HTTP/2.0");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): websocket ,HTTP/2.0 */
+  ret = MHD_websocket_check_upgrade_header (" websocket ,HTTP/2.0");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): HTTP/2.0, websocket */
+  ret = MHD_websocket_check_upgrade_header ("HTTP/2.0, websocket ");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): websocket/13 */
+  ret = MHD_websocket_check_upgrade_header ("websocket/13");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): WeBsOcKeT */
+  ret = MHD_websocket_check_upgrade_header ("WeBsOcKeT");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): WEBSOCKET */
+  ret = MHD_websocket_check_upgrade_header ("WEBSOCKET");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): All allowed token characters plus /, then websocket keyword */
+  ret = MHD_websocket_check_upgrade_header (
+    "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/,websocket");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (success): Different, allowed whitespaces */
+  ret = MHD_websocket_check_upgrade_header (" \twebsocket \t");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_upgrade_header ("\rwebsocket");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_upgrade_header ("\nwebsocket");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_upgrade_header ("\vwebsocket");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): Different, disallowed whitespaces */
+  ret = MHD_websocket_check_upgrade_header ("\fwebsocket");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Invalid header syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: (empty string) */
+  ret = MHD_websocket_check_upgrade_header ("");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: (Disallowed) multiple word token with the term "websocket" in it */
+  ret = MHD_websocket_check_upgrade_header ("websocket or something");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: Invalid characters */
+  ret = MHD_websocket_check_upgrade_header ("\"websocket\"");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Missing parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: NULL as upgrade */
+  ret = MHD_websocket_check_upgrade_header (NULL);
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_upgrade_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  return failed != 0 ? 0x800 : 0x00;
+}
+
+
+/**
+ * Test procedure for `MHD_websocket_check_version_header()`
+ */
+int
+test_check_version_header ()
+{
+  int failed = 0;
+  int ret;
+
+  /*
+  ------------------------------------------------------------------------------
+    Check with valid Upgrade header syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Regular test: 13 */
+  ret = MHD_websocket_check_version_header ("13");
+  if (MHD_WEBSOCKET_STATUS_OK != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Version check edge cases
+  ------------------------------------------------------------------------------
+  */
+  /* Edge test (fail): 14 */
+  ret = MHD_websocket_check_version_header ("14");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): 12 */
+  ret = MHD_websocket_check_version_header ("12");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): 0 */
+  ret = MHD_websocket_check_version_header ("1");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): 1 */
+  ret = MHD_websocket_check_version_header ("1");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): 130 */
+  ret = MHD_websocket_check_version_header ("130");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Edge test (fail): " 13" */
+  ret = MHD_websocket_check_version_header (" 13");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Invalid header syntax
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: (empty string) */
+  ret = MHD_websocket_check_version_header ("");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+  /* Fail test: Invalid characters */
+  ret = MHD_websocket_check_version_header ("abc");
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  /*
+  ------------------------------------------------------------------------------
+    Missing parameters
+  ------------------------------------------------------------------------------
+  */
+  /* Fail test: NULL as version */
+  ret = MHD_websocket_check_version_header (NULL);
+  if (MHD_WEBSOCKET_STATUS_NO_WEBSOCKET_HANDSHAKE_HEADER != ret)
+  {
+    fprintf (stderr,
+             "check_version_header test failed in line %u.\n",
+             (unsigned int) __LINE__);
+    ++failed;
+  }
+
+  return failed != 0 ? 0x1000 : 0x00;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc; (void) argv;  /* Unused. Silent compiler warning. */
+
+  /* seed random number generator */
+  srand ((unsigned long) time (NULL));
+
+  /* perform tests */
+  errorCount += test_inits ();
+  errorCount += test_accept ();
+  errorCount += test_decodes ();
+  errorCount += test_encodes_text ();
+  errorCount += test_encodes_binary ();
+  errorCount += test_encodes_close ();
+  errorCount += test_encodes_ping ();
+  errorCount += test_encodes_pong ();
+  errorCount += test_split_close_reason ();
+  errorCount += test_check_http_version ();
+  errorCount += test_check_connection_header ();
+  errorCount += test_check_upgrade_header ();
+  errorCount += test_check_version_header ();
+
+  /* output result */
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+
+  return errorCount != 0;       /* 0 == pass */
+}
diff --git a/src/microhttpd_ws/test_websocket_browser.c b/src/microhttpd_ws/test_websocket_browser.c
new file mode 100644
index 0000000..d7416a5
--- /dev/null
+++ b/src/microhttpd_ws/test_websocket_browser.c
@@ -0,0 +1,567 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2021 David Gausmann
+
+     libmicrohttpd 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, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_websocket_browser.c
+ * @brief  Testcase for WebSocket decoding/encoding with external browser
+ * @author David Gausmann
+ */
+#include <sys/types.h>
+#ifndef _WIN32
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <fcntl.h>
+#else
+#include <winsock2.h>
+#endif
+#include "microhttpd.h"
+#include "microhttpd_ws.h"
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <time.h>
+#include <errno.h>
+
+#define PORT 80
+
+#define PAGE \
+  "<!DOCTYPE html>\n" \
+  "<html>\n" \
+  "<head>\n" \
+  "<meta charset=\"UTF-8\">\n" \
+  "<title>Websocket External Test with Webbrowser</title>\n" \
+  "<script>\n" \
+  "\n" \
+  "let current_mode  = 0;\n" \
+  "let current_step  = 0;\n" \
+  "let sent_payload  = null;\n" \
+  "let charset       = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_!@%&/\\\\';\n" \
+  "let step_to_bytes = [ 0, 1, 2, 3, 122, 123, 124, 125, 126, 127, 128, 32766, 32767, 32768, 65534, 65535, 65536, 65537, 1048576, 10485760 ];\n" \
+  "let url = 'ws' + (window.location.protocol === 'https:' ? 's' : '')" \
+    "  + ':/" "/' +\n" \
+  "          window.location.host + '/websocket';\n" \
+  "let socket = null;\n" \
+  "\n" \
+  "window.onload = function (event) {\n" \
+  "  if (!window.WebSocket) {\n" \
+  "    document.write ('ERROR: The WebSocket class is not supported by your browser.<br>');\n" \
+  "  }\n" \
+  "  if (!window.fetch) {\n" \
+  "    document.write ('ERROR: The fetch-API is not supported by your browser.<br>');\n" \
+  "  }\n" \
+  "  document.write ('Starting tests.<br>');\n" \
+  "  runTest ();\n" \
+  "}\n" \
+  "\n" \
+  "function runTest () {\n" \
+  "  switch (current_mode) {\n" \
+  "  case 0:\n" \
+  "    document.write ('TEXT');\n" \
+  "    break;\n" \
+  "  case 1:\n" \
+  "    document.write ('BINARY');\n" \
+  "    break;\n" \
+  "  }\n" \
+  "  document.write (', ' + step_to_bytes[current_step] + ' Bytes: ');\n" \
+  "  socket = new WebSocket(url);\n" \
+  "  socket.binaryType = 'arraybuffer';\n" \
+  "  socket.onopen = function (event) {\n" \
+  "    switch (current_mode) {\n" \
+  "    case 0:\n" \
+  "      sent_payload = randomText (step_to_bytes[current_step]);\n" \
+  "      socket.send (sent_payload);\n" \
+  "      break;\n" \
+  "    case 1:\n" \
+  "      sent_payload = randomBinary (step_to_bytes[current_step]);\n" \
+  "      socket.send (sent_payload);\n" \
+  "      break;\n" \
+  "    }\n" \
+  "  }\n" \
+  "\n" \
+  "  socket.onclose = function (event) {\n" \
+  "    socket.onmessage = null;\n" \
+  "    socket.onclose   = null;\n" \
+  "    socket.onerror   = null;\n" \
+  "    document.write ('CLOSED unexpectedly.<br>');\n" \
+  "    notifyError ();\n" \
+  "  }\n" \
+  "\n" \
+  "  socket.onerror = function (event) {\n" \
+  "    socket.onmessage = null;\n" \
+  "    socket.onclose   = null;\n" \
+  "    socket.onerror   = null;\n" \
+  "    document.write ('ERROR.<br>');\n" \
+  "    notifyError ();\n" \
+  "  }\n" \
+  "\n" \
+  "  socket.onmessage = async function (event) {\n" \
+  "    if (compareData (event.data, sent_payload)) {\n" \
+  "      document.write ('SUCCESS.<br>');\n" \
+  "      socket.onmessage = null;\n" \
+  "      socket.onclose   = null;\n" \
+  "      socket.onerror   = null;\n" \
+  "      socket.close();\n" \
+  "      socket = null;\n" \
+  "      if (step_to_bytes.length <= ++current_step) {\n" \
+  "        current_step = 0;\n" \
+  "        if (1 < ++current_mode) {\n" \
+  "          document.write ('FINISHED ALL TESTS.<br>');\n" \
+  "          return;\n" \
+  "        }\n" \
+  "      }\n" \
+  "      runTest ();\n" \
+  "    }" \
+  "  }\n" \
+  "}\n" \
+  "\n" \
+  "function compareData (data, data2) {\n" \
+  "  if (typeof (data) === 'string' && typeof (data2) === 'string') {\n" \
+  "    return (data === data2); \n" \
+  "  } \n" \
+  "  else if ((data instanceof ArrayBuffer) && (data2 instanceof ArrayBuffer)) {\n" \
+  "    let view1 = new Uint8Array (data);\n" \
+  "    let view2 = new Uint8Array (data2);\n" \
+  "    if (view1.length != view2.length)\n" \
+  "      return false;\n" \
+  "    for (let i = 0; i < view1.length; ++i) {\n" \
+  "      if (view1[i] !== view2[i])\n" \
+  "        return false;\n" \
+  "    }\n" \
+  "    return true;\n" \
+  "  }\n" \
+  "  else\n" \
+  "  {\n" \
+  "    return false;\n" \
+  "  }\n" \
+  "}\n" \
+  "\n" \
+  "function randomText (length) {\n" \
+  "  let result = new Array (length);\n" \
+  "  for (let i = 0; i < length; ++i)\n" \
+  "    result [i] = charset [~~(Math.random () * charset.length)];\n" \
+  "  return result.join ('');\n" \
+  "}\n" \
+  "\n" \
+  "function randomBinary (length) {\n" \
+  "  let buffer = new ArrayBuffer (length);\n" \
+  "  let view   = new Uint8Array (buffer);\n" \
+  "  for (let i = 0; i < length; ++i)\n" \
+  "    view [i] = ~~(Math.random () * 256);\n" \
+  "  return buffer;\n" \
+  "}\n" \
+  "\n" \
+  "function notifyError () {\n" \
+  "  fetch('error/' + (0 == current_mode ? 'text' : 'binary') + '/' + step_to_bytes[current_step]);\n" \
+  "}\n" \
+  "\n" \
+  "</script>\n" \
+  "</head>\n" \
+  "<body>\n" \
+  "</body>\n" \
+  "</html>"
+
+#define PAGE_NOT_FOUND \
+  "404 Not Found"
+
+#define PAGE_INVALID_WEBSOCKET_REQUEST \
+  "Invalid WebSocket request!"
+
+static void
+send_all (MHD_socket fd,
+          const char *buf,
+          size_t len);
+
+static void
+make_blocking (MHD_socket fd);
+
+static void
+upgrade_handler (void *cls,
+                 struct MHD_Connection *connection,
+                 void *req_cls,
+                 const char *extra_in,
+                 size_t extra_in_size,
+                 MHD_socket fd,
+                 struct MHD_UpgradeResponseHandle *urh)
+{
+  /* make the socket blocking (operating-system-dependent code) */
+  make_blocking (fd);
+
+  /* create a websocket stream for this connection */
+  struct MHD_WebSocketStream *ws;
+  int result = MHD_websocket_stream_init (&ws,
+                                          0,
+                                          0);
+  if (0 != result)
+  {
+    /* Couldn't create the websocket stream.
+     * So we close the socket and leave
+     */
+    MHD_upgrade_action (urh,
+                        MHD_UPGRADE_ACTION_CLOSE);
+    return;
+  }
+
+  /* Let's wait for incoming data */
+  const size_t buf_len = 256;
+  char buf[buf_len];
+  ssize_t got;
+  while (MHD_WEBSOCKET_VALIDITY_VALID == MHD_websocket_stream_is_valid (ws))
+  {
+    got = recv (fd,
+                buf,
+                sizeof (buf),
+                0);
+    if (0 >= got)
+    {
+      /* the TCP/IP socket has been closed */
+      fprintf (stderr,
+               "Error (The socket has been closed unexpectedly)\n");
+      break;
+    }
+
+    /* parse the entire received data */
+    size_t buf_offset = 0;
+    while (buf_offset < (size_t) got)
+    {
+      size_t new_offset  = 0;
+      char *payload_data = NULL;
+      size_t payload_len = 0;
+      char *frame_data   = NULL;
+      size_t frame_len   = 0;
+      int status = MHD_websocket_decode (ws,
+                                         buf + buf_offset,
+                                         ((size_t) got) - buf_offset,
+                                         &new_offset,
+                                         &payload_data,
+                                         &payload_len);
+      if (0 > status)
+      {
+        /* an error occurred and the connection must be closed */
+        printf ("Decoding failed: status=%d, passed=%u\n", status,
+                ((size_t) got) - buf_offset);
+        if (NULL != payload_data)
+        {
+          MHD_websocket_free (ws, payload_data);
+        }
+        break;
+      }
+      else
+      {
+        buf_offset += new_offset;
+        if (0 < status)
+        {
+          /* the frame is complete */
+          printf (
+            "Decoding succeeded: type=%d, passed=%u, parsed=%u, payload_len=%d\n",
+            status, ((size_t) got) - buf_offset, new_offset, payload_len);
+          switch (status)
+          {
+          case MHD_WEBSOCKET_STATUS_TEXT_FRAME:
+          case MHD_WEBSOCKET_STATUS_BINARY_FRAME:
+            /* The client has sent some data. */
+            if ((NULL != payload_data) || (0 == payload_len))
+            {
+              /* Send the received data back to the client */
+              if (MHD_WEBSOCKET_STATUS_TEXT_FRAME == status)
+              {
+                result = MHD_websocket_encode_text (ws,
+                                                    payload_data,
+                                                    payload_len,
+                                                    0,
+                                                    &frame_data,
+                                                    &frame_len,
+                                                    NULL);
+              }
+              else
+              {
+                result = MHD_websocket_encode_binary (ws,
+                                                      payload_data,
+                                                      payload_len,
+                                                      0,
+                                                      &frame_data,
+                                                      &frame_len);
+              }
+              if (0 == result)
+              {
+                send_all (fd,
+                          frame_data,
+                          frame_len);
+              }
+            }
+            else
+            {
+              /* should never happen */
+              fprintf (stderr,
+                       "Error (Empty buffer with payload_len != 0)\n");
+            }
+            break;
+
+          default:
+            /* Other frame types are ignored
+             * in this test script.
+             */
+            break;
+          }
+        }
+        if (NULL != payload_data)
+        {
+          MHD_websocket_free (ws, payload_data);
+        }
+        if (NULL != frame_data)
+        {
+          MHD_websocket_free (ws, frame_data);
+        }
+      }
+    }
+  }
+
+  /* free the websocket stream */
+  MHD_websocket_stream_free (ws);
+
+  /* close the socket when it is not needed anymore */
+  MHD_upgrade_action (urh,
+                      MHD_UPGRADE_ACTION_CLOSE);
+}
+
+
+/* This helper function is used for the case that
+ * we need to resend some data
+ */
+static void
+send_all (MHD_socket fd,
+          const char *buf,
+          size_t len)
+{
+  ssize_t ret;
+  size_t off;
+
+  for (off = 0; off < len; off += ret)
+  {
+    ret = send (fd,
+                &buf[off],
+                (int) (len - off),
+                0);
+    if (0 > ret)
+    {
+      if (EAGAIN == errno)
+      {
+        ret = 0;
+        continue;
+      }
+      break;
+    }
+    if (0 == ret)
+      break;
+  }
+}
+
+
+/* This helper function contains operating-system-dependent code and
+ * is used to make a socket blocking.
+ */
+static void
+make_blocking (MHD_socket fd)
+{
+#ifndef _WIN32
+  int flags;
+
+  flags = fcntl (fd, F_GETFL);
+  if (-1 == flags)
+    return;
+  if ((flags & ~O_NONBLOCK) != flags)
+    if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK))
+      abort ();
+#else
+  unsigned long flags = 0;
+
+  ioctlsocket (fd, FIONBIO, &flags);
+#endif
+}
+
+
+static enum MHD_Result
+access_handler (void *cls,
+                struct MHD_Connection *connection,
+                const char *url,
+                const char *method,
+                const char *version,
+                const char *upload_data,
+                size_t *upload_data_size,
+                void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  int ret;
+
+  (void) cls;               /* Unused. Silent compiler warning. */
+  (void) upload_data;       /* Unused. Silent compiler warning. */
+  (void) upload_data_size;  /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, "GET"))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+
+  if (0 == strcmp (url, "/"))
+  {
+    /* Default page for visiting the server */
+    struct MHD_Response *response = MHD_create_response_from_buffer (
+      strlen (PAGE),
+      PAGE,
+      MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else if (0 == strncmp (url, "/error/", 7))
+  {
+    /* Report error */
+    fprintf (stderr, "Error in test (%s)\n", url + 7);
+
+    struct MHD_Response *response = MHD_create_response_from_buffer (
+      0,
+      "",
+      MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_OK,
+                              response);
+    MHD_destroy_response (response);
+  }
+  else if (0 == strcmp (url, "/websocket"))
+  {
+    char is_valid = 1;
+    const char *value = NULL;
+    char sec_websocket_accept[29];
+
+    if (0 != MHD_websocket_check_http_version (version))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_CONNECTION);
+    if (0 != MHD_websocket_check_connection_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_UPGRADE);
+    if (0 != MHD_websocket_check_upgrade_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION);
+    if (0 != MHD_websocket_check_version_header (value))
+    {
+      is_valid = 0;
+    }
+    value = MHD_lookup_connection_value (connection,
+                                         MHD_HEADER_KIND,
+                                         MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY);
+    if (0 != MHD_websocket_create_accept_header (value, sec_websocket_accept))
+    {
+      is_valid = 0;
+    }
+
+    if (1 == is_valid)
+    {
+      /* upgrade the connection */
+      response = MHD_create_response_for_upgrade (&upgrade_handler,
+                                                  NULL);
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_UPGRADE,
+                               "websocket");
+      MHD_add_response_header (response,
+                               MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT,
+                               sec_websocket_accept);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_SWITCHING_PROTOCOLS,
+                                response);
+      MHD_destroy_response (response);
+    }
+    else
+    {
+      /* return error page */
+      struct MHD_Response *response = MHD_create_response_from_buffer (
+        strlen (PAGE_INVALID_WEBSOCKET_REQUEST),
+        PAGE_INVALID_WEBSOCKET_REQUEST,
+        MHD_RESPMEM_PERSISTENT);
+      ret = MHD_queue_response (connection,
+                                MHD_HTTP_BAD_REQUEST,
+                                response);
+      MHD_destroy_response (response);
+    }
+  }
+  else
+  {
+    struct MHD_Response *response = MHD_create_response_from_buffer (
+      strlen (PAGE_NOT_FOUND),
+      PAGE_NOT_FOUND,
+      MHD_RESPMEM_PERSISTENT);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_NOT_FOUND,
+                              response);
+    MHD_destroy_response (response);
+  }
+
+  return ret;
+}
+
+
+int
+main (int argc,
+      char *const *argv)
+{
+  (void) argc;               /* Unused. Silent compiler warning. */
+  (void) argv;               /* Unused. Silent compiler warning. */
+  struct MHD_Daemon *daemon;
+
+  daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                             | MHD_USE_THREAD_PER_CONNECTION
+                             | MHD_ALLOW_UPGRADE
+                             | MHD_USE_ERROR_LOG,
+                             PORT, NULL, NULL,
+                             &access_handler, NULL,
+                             MHD_OPTION_END);
+
+  if (NULL == daemon)
+  {
+    fprintf (stderr, "Error (Couldn't start daemon for testing)\n");
+    return 1;
+  }
+  printf ("The server is listening now.\n");
+  printf ("Access the server now with a websocket-capable webbrowser.\n\n");
+  printf ("Press return to close.\n");
+
+  (void) getc (stdin);
+
+  MHD_stop_daemon (daemon);
+
+  return 0;
+}
diff --git a/src/microspdy/Makefile.am b/src/microspdy/Makefile.am
deleted file mode 100644
index 7fb2c37..0000000
--- a/src/microspdy/Makefile.am
+++ /dev/null
@@ -1,40 +0,0 @@
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include \
-  -I$(top_srcdir)/src/microspdy
-
-AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS)
-
-
-lib_LTLIBRARIES = \
-  libmicrospdy.la
-
-libmicrospdy_la_SOURCES = \
-  io.h io.c \
-  io_openssl.h io_openssl.c \
-  io_raw.h io_raw.c \
-  structures.h structures.c \
-  internal.h internal.c \
-  daemon.h daemon.c \
-  stream.h stream.c \
-  compression.h compression.c \
-  session.h session.c \
-  applicationlayer.c applicationlayer.h \
-  alstructures.c alstructures.h 
-libmicrospdy_la_LIBADD = \
-  $(SPDY_LIBDEPS)
-
-libmicrospdy_la_LDFLAGS = \
-  $(SPDY_LIB_LDFLAGS)
-
-libmicrospdy_la_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(SPDY_LIB_CPPFLAGS) \
-  -DBUILDING_MHD_LIB=1
-
-libmicrospdy_la_CFLAGS = -Wextra \
-  $(AM_CFLAGS) $(SPDY_LIB_CFLAGS)
-
-
-if USE_COVERAGE
-  AM_CFLAGS += --coverage
-endif
diff --git a/src/microspdy/Makefile.in b/src/microspdy/Makefile.in
deleted file mode 100644
index d1a4588..0000000
--- a/src/microspdy/Makefile.in
+++ /dev/null
@@ -1,820 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@USE_COVERAGE_TRUE@am__append_1 = --coverage
-subdir = src/microspdy
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__installdirs = "$(DESTDIR)$(libdir)"
-LTLIBRARIES = $(lib_LTLIBRARIES)
-am__DEPENDENCIES_1 =
-libmicrospdy_la_DEPENDENCIES = $(am__DEPENDENCIES_1)
-am_libmicrospdy_la_OBJECTS = libmicrospdy_la-io.lo \
-	libmicrospdy_la-io_openssl.lo libmicrospdy_la-io_raw.lo \
-	libmicrospdy_la-structures.lo libmicrospdy_la-internal.lo \
-	libmicrospdy_la-daemon.lo libmicrospdy_la-stream.lo \
-	libmicrospdy_la-compression.lo libmicrospdy_la-session.lo \
-	libmicrospdy_la-applicationlayer.lo \
-	libmicrospdy_la-alstructures.lo
-libmicrospdy_la_OBJECTS = $(am_libmicrospdy_la_OBJECTS)
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-libmicrospdy_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(libmicrospdy_la_CFLAGS) $(CFLAGS) $(libmicrospdy_la_LDFLAGS) \
-	$(LDFLAGS) -o $@
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(libmicrospdy_la_SOURCES)
-DIST_SOURCES = $(libmicrospdy_la_SOURCES)
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include \
-  -I$(top_srcdir)/src/microspdy
-
-AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS) $(am__append_1)
-lib_LTLIBRARIES = \
-  libmicrospdy.la
-
-libmicrospdy_la_SOURCES = \
-  io.h io.c \
-  io_openssl.h io_openssl.c \
-  io_raw.h io_raw.c \
-  structures.h structures.c \
-  internal.h internal.c \
-  daemon.h daemon.c \
-  stream.h stream.c \
-  compression.h compression.c \
-  session.h session.c \
-  applicationlayer.c applicationlayer.h \
-  alstructures.c alstructures.h 
-
-libmicrospdy_la_LIBADD = \
-  $(SPDY_LIBDEPS)
-
-libmicrospdy_la_LDFLAGS = \
-  $(SPDY_LIB_LDFLAGS)
-
-libmicrospdy_la_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(SPDY_LIB_CPPFLAGS) \
-  -DBUILDING_MHD_LIB=1
-
-libmicrospdy_la_CFLAGS = -Wextra \
-  $(AM_CFLAGS) $(SPDY_LIB_CFLAGS)
-
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/microspdy/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/microspdy/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-install-libLTLIBRARIES: $(lib_LTLIBRARIES)
-	@$(NORMAL_INSTALL)
-	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
-	list2=; for p in $$list; do \
-	  if test -f $$p; then \
-	    list2="$$list2 $$p"; \
-	  else :; fi; \
-	done; \
-	test -z "$$list2" || { \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \
-	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
-	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
-	}
-
-uninstall-libLTLIBRARIES:
-	@$(NORMAL_UNINSTALL)
-	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
-	for p in $$list; do \
-	  $(am__strip_dir) \
-	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
-	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
-	done
-
-clean-libLTLIBRARIES:
-	-test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
-	@list='$(lib_LTLIBRARIES)'; \
-	locs=`for p in $$list; do echo $$p; done | \
-	      sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \
-	      sort -u`; \
-	test -z "$$locs" || { \
-	  echo rm -f $${locs}; \
-	  rm -f $${locs}; \
-	}
-
-libmicrospdy.la: $(libmicrospdy_la_OBJECTS) $(libmicrospdy_la_DEPENDENCIES) $(EXTRA_libmicrospdy_la_DEPENDENCIES) 
-	$(AM_V_CCLD)$(libmicrospdy_la_LINK) -rpath $(libdir) $(libmicrospdy_la_OBJECTS) $(libmicrospdy_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-alstructures.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-applicationlayer.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-compression.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-daemon.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-internal.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-io.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-io_openssl.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-io_raw.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-session.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-stream.Plo@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrospdy_la-structures.Plo@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-libmicrospdy_la-io.lo: io.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-io.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-io.Tpo -c -o libmicrospdy_la-io.lo `test -f 'io.c' || echo '$(srcdir)/'`io.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-io.Tpo $(DEPDIR)/libmicrospdy_la-io.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='io.c' object='libmicrospdy_la-io.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-io.lo `test -f 'io.c' || echo '$(srcdir)/'`io.c
-
-libmicrospdy_la-io_openssl.lo: io_openssl.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-io_openssl.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-io_openssl.Tpo -c -o libmicrospdy_la-io_openssl.lo `test -f 'io_openssl.c' || echo '$(srcdir)/'`io_openssl.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-io_openssl.Tpo $(DEPDIR)/libmicrospdy_la-io_openssl.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='io_openssl.c' object='libmicrospdy_la-io_openssl.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-io_openssl.lo `test -f 'io_openssl.c' || echo '$(srcdir)/'`io_openssl.c
-
-libmicrospdy_la-io_raw.lo: io_raw.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-io_raw.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-io_raw.Tpo -c -o libmicrospdy_la-io_raw.lo `test -f 'io_raw.c' || echo '$(srcdir)/'`io_raw.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-io_raw.Tpo $(DEPDIR)/libmicrospdy_la-io_raw.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='io_raw.c' object='libmicrospdy_la-io_raw.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-io_raw.lo `test -f 'io_raw.c' || echo '$(srcdir)/'`io_raw.c
-
-libmicrospdy_la-structures.lo: structures.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-structures.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-structures.Tpo -c -o libmicrospdy_la-structures.lo `test -f 'structures.c' || echo '$(srcdir)/'`structures.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-structures.Tpo $(DEPDIR)/libmicrospdy_la-structures.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='structures.c' object='libmicrospdy_la-structures.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-structures.lo `test -f 'structures.c' || echo '$(srcdir)/'`structures.c
-
-libmicrospdy_la-internal.lo: internal.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-internal.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-internal.Tpo -c -o libmicrospdy_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-internal.Tpo $(DEPDIR)/libmicrospdy_la-internal.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='internal.c' object='libmicrospdy_la-internal.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c
-
-libmicrospdy_la-daemon.lo: daemon.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-daemon.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-daemon.Tpo -c -o libmicrospdy_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-daemon.Tpo $(DEPDIR)/libmicrospdy_la-daemon.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='daemon.c' object='libmicrospdy_la-daemon.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c
-
-libmicrospdy_la-stream.lo: stream.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-stream.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-stream.Tpo -c -o libmicrospdy_la-stream.lo `test -f 'stream.c' || echo '$(srcdir)/'`stream.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-stream.Tpo $(DEPDIR)/libmicrospdy_la-stream.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='stream.c' object='libmicrospdy_la-stream.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-stream.lo `test -f 'stream.c' || echo '$(srcdir)/'`stream.c
-
-libmicrospdy_la-compression.lo: compression.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-compression.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-compression.Tpo -c -o libmicrospdy_la-compression.lo `test -f 'compression.c' || echo '$(srcdir)/'`compression.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-compression.Tpo $(DEPDIR)/libmicrospdy_la-compression.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='compression.c' object='libmicrospdy_la-compression.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-compression.lo `test -f 'compression.c' || echo '$(srcdir)/'`compression.c
-
-libmicrospdy_la-session.lo: session.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-session.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-session.Tpo -c -o libmicrospdy_la-session.lo `test -f 'session.c' || echo '$(srcdir)/'`session.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-session.Tpo $(DEPDIR)/libmicrospdy_la-session.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='session.c' object='libmicrospdy_la-session.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-session.lo `test -f 'session.c' || echo '$(srcdir)/'`session.c
-
-libmicrospdy_la-applicationlayer.lo: applicationlayer.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-applicationlayer.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-applicationlayer.Tpo -c -o libmicrospdy_la-applicationlayer.lo `test -f 'applicationlayer.c' || echo '$(srcdir)/'`applicationlayer.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-applicationlayer.Tpo $(DEPDIR)/libmicrospdy_la-applicationlayer.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='applicationlayer.c' object='libmicrospdy_la-applicationlayer.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-applicationlayer.lo `test -f 'applicationlayer.c' || echo '$(srcdir)/'`applicationlayer.c
-
-libmicrospdy_la-alstructures.lo: alstructures.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -MT libmicrospdy_la-alstructures.lo -MD -MP -MF $(DEPDIR)/libmicrospdy_la-alstructures.Tpo -c -o libmicrospdy_la-alstructures.lo `test -f 'alstructures.c' || echo '$(srcdir)/'`alstructures.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libmicrospdy_la-alstructures.Tpo $(DEPDIR)/libmicrospdy_la-alstructures.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='alstructures.c' object='libmicrospdy_la-alstructures.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrospdy_la_CPPFLAGS) $(CPPFLAGS) $(libmicrospdy_la_CFLAGS) $(CFLAGS) -c -o libmicrospdy_la-alstructures.lo `test -f 'alstructures.c' || echo '$(srcdir)/'`alstructures.c
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-am
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-am
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-am
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES)
-installdirs:
-	for dir in "$(DESTDIR)$(libdir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \
-	mostlyclean-am
-
-distclean: distclean-am
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am: install-libLTLIBRARIES
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-libLTLIBRARIES
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \
-	clean-libLTLIBRARIES clean-libtool cscopelist-am ctags \
-	ctags-am distclean distclean-compile distclean-generic \
-	distclean-libtool distclean-tags distdir dvi dvi-am html \
-	html-am info info-am install install-am install-data \
-	install-data-am install-dvi install-dvi-am install-exec \
-	install-exec-am install-html install-html-am install-info \
-	install-info-am install-libLTLIBRARIES install-man install-pdf \
-	install-pdf-am install-ps install-ps-am install-strip \
-	installcheck installcheck-am installdirs maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-compile \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags tags-am uninstall uninstall-am uninstall-libLTLIBRARIES
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/microspdy/alstructures.c b/src/microspdy/alstructures.c
deleted file mode 100644
index b588a1c..0000000
--- a/src/microspdy/alstructures.c
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file alstructures.c
- * @brief  structures only for the application layer
- * @author Andrey Uzunov
- */
- 
-#include "platform.h"
-#include "alstructures.h"
-#include "internal.h"
-
-void
-SPDY_destroy_request (struct SPDY_Request *request)
-{
-	if(NULL == request)
-	{
-		SPDYF_DEBUG("request is NULL");
-		return;
-	}
-	//strings into request struct are just references to strings in
-	//headers, so no need to free them twice
-	SPDY_name_value_destroy(request->headers);
-	free(request);
-}
diff --git a/src/microspdy/alstructures.h b/src/microspdy/alstructures.h
deleted file mode 100644
index 2eb36e8..0000000
--- a/src/microspdy/alstructures.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file alstructures.h
- * @brief  structures only for the application layer
- * @author Andrey Uzunov
- */
-
-#ifndef ALSTRUCTURES_H
-#define ALSTRUCTURES_H
-
-#include "platform.h"
-
-
-/**
- * Represents a SPDY request.
- */
-struct SPDY_Request
-{
-	/**
-	 * SPDY stream in whose context the request was received
-	 */
-	struct SPDYF_Stream *stream;
-	
-	/**
-	 * Other HTTP headers from the request
-	 */
-	struct SPDY_NameValue *headers;
-	
-	/**
-	 * HTTP method
-	 */
-	char *method;
-	
-	/**
-	 * HTTP path
-	 */
-	char *path;
-	
-	/**
-	 * HTTP version just like in HTTP request/response: 
-	 * 			"HTTP/1.0" or "HTTP/1.1" currently
-	 */
-	char *version;
-	
-	/**
-	 * called host as in HTTP
-	 */
-	char *host;
-	
-	/**
-	 * The scheme used ("http" or "https")
-	 */
-	char *scheme;
-
-	/**
-	 * Extra field to be used by the user with set/get func for whatever
-	 * purpose he wants.
-	 */
-	void *user_cls;
-};
-
-#endif
diff --git a/src/microspdy/applicationlayer.c b/src/microspdy/applicationlayer.c
deleted file mode 100644
index bf16b78..0000000
--- a/src/microspdy/applicationlayer.c
+++ /dev/null
@@ -1,748 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file applicationlayer.c
- * @brief  SPDY application or HTTP layer
- * @author Andrey Uzunov
- */
- 
-#include "platform.h"
-#include "applicationlayer.h"
-#include "alstructures.h"
-#include "structures.h"
-#include "internal.h"
-#include "daemon.h"
-#include "session.h"
-
-
-void
-spdy_callback_response_done(void *cls,
-						struct SPDY_Response *response,
-						struct SPDY_Request *request,
-						enum SPDY_RESPONSE_RESULT status,
-						bool streamopened)
-{
-	(void)cls;
-	(void)status;
-	(void)streamopened;
-  
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-}
-
-
-/**
- * Callback called when new stream is created. It extracts the info from
- * the stream to create (HTTP) request object and pass it to the client.
- *
- * @param cls
- * @param stream the new SPDY stream
- * @return SPDY_YES on success, SPDY_NO on memomry error
- */
-static int
-spdy_handler_new_stream (void *cls,
-						struct SPDYF_Stream * stream)
-{
-	(void)cls;
-	unsigned int i;
-	char *method = NULL;
-	char *path = NULL;
-	char *version = NULL;
-	char *host = NULL;
-	char *scheme = NULL;
-	struct SPDY_Request * request = NULL;
-	struct SPDY_NameValue * headers = NULL;
-	struct SPDY_NameValue * iterator = stream->headers;
-	struct SPDY_Daemon *daemon;
-	
-	daemon = stream->session->daemon;
-	
-	//if the user doesn't care, ignore it
-	if(NULL == daemon->new_request_cb)
-		return SPDY_YES;
-	
-	if(NULL == (headers=SPDY_name_value_create()))
-		goto free_and_fail;
-	
-	if(NULL==(request = malloc(sizeof(struct SPDY_Request))))
-		goto free_and_fail;
-	
-	memset(request, 0, sizeof(struct SPDY_Request));
-	request->stream = stream;
-	
-	/* extract the mandatory fields from stream->headers' structure
-	 * to pass them to the client */
-	while(iterator != NULL)
-	{
-		if(strcmp(":method",iterator->name) == 0)
-		{
-			if(1 != iterator->num_values)
-				break;
-			method = iterator->value[0];
-		}
-		else if(strcmp(":path",iterator->name) == 0)
-		{
-			if(1 != iterator->num_values)
-				break;
-			path = iterator->value[0];
-		}
-		else if(strcmp(":version",iterator->name) == 0)
-		{
-			if(1 != iterator->num_values)
-				break;
-			version = iterator->value[0];
-		}
-		else if(strcmp(":host",iterator->name) == 0)
-		{
-			//TODO can it have more values?
-			if(1 != iterator->num_values)
-				break;
-			host = iterator->value[0];
-		}
-		else if(strcmp(":scheme",iterator->name) == 0)
-		{
-			if(1 != iterator->num_values)
-				break;
-			scheme = iterator->value[0];
-		}
-		else
-			for(i=0; i<iterator->num_values; ++i)
-				if (SPDY_YES != SPDY_name_value_add(headers,iterator->name,iterator->value[i]))
-        {
-          SPDY_destroy_request(request);
-					goto free_and_fail;
-        }
-		
-		iterator = iterator->next;
-	}
-	
-	request->method=method;
-  request->path=path;
-  request->version=version;
-  request->host=host;
-  request->scheme=scheme;
-  request->headers=headers;
-	
-	//check request validity, all these fields are mandatory for a request
-	if(NULL == method || strlen(method) == 0
-		|| NULL == path || strlen(path) == 0
-		|| NULL == version || strlen(version) == 0
-		|| NULL == host || strlen(host) == 0
-		|| NULL == scheme || strlen(scheme) == 0
-		)
-	{
-		//TODO HTTP 400 Bad Request must be answered
-		
-		SPDYF_DEBUG("Bad request");
-		
-		SPDY_destroy_request(request);
-		
-		return SPDY_YES;
-	}
-	
-	//call client's callback function to notify
-	daemon->new_request_cb(daemon->cls,
-						request,
-						stream->priority,
-                        method,
-                        path,
-                        version,
-                        host,
-                        scheme,
-						headers,
-            !stream->is_in_closed);
-            
-  stream->cls = request;
-
-	return SPDY_YES;
-
-	//for GOTO
-	free_and_fail:
-	
-	SPDY_name_value_destroy(headers);
-	return SPDY_NO;
-}
-
-
-/**
- * TODO
- */
-static int
-spdy_handler_new_data (void * cls,
-					 struct SPDYF_Stream *stream,
-					 const void * buf,
-					 size_t size,
-					 bool more)
-{
-  return stream->session->daemon->received_data_cb(cls, stream->cls, buf, size, more);
-}
-
-
-
-/**
- * Callback to be called when the response queue object was handled and 
- * the data was already sent or discarded. 
- *
- * @param cls
- * @param response_queue the object which is being handled
- * @param status shows if actually the response was sent or it was
- * 			discarded by the lib for any reason (e.g., closing session,
- * 			closing stream, stopping daemon, etc.). It is possible that
- * 			status indicates an error but parts of the response headers
- * 			and/or body (in one
- * 			or several frames) were already sent to the client.
- */
-static void
-spdy_handler_response_queue_result(void * cls,
-								struct SPDYF_Response_Queue *response_queue,
-								enum SPDY_RESPONSE_RESULT status)
-{
-	int streamopened;
-	struct SPDY_Request *request = (struct SPDY_Request *)cls;
-	
-	SPDYF_ASSERT( ( (NULL == response_queue->data_frame) &&
-			(NULL != response_queue->control_frame) ) ||
-		      ( (NULL != response_queue->data_frame) &&
-			(NULL == response_queue->control_frame) ),
-		     "response queue must have either control frame or data frame");
-	
-	streamopened = !response_queue->stream->is_out_closed;
-	
-	response_queue->rrcb(response_queue->rrcb_cls, response_queue->response, request, status, streamopened);
-}
-
-
-int
-(SPDY_init) (enum SPDY_IO_SUBSYSTEM io_subsystem, ...)
-{
-	SPDYF_ASSERT(SPDYF_BUFFER_SIZE >= SPDY_MAX_SUPPORTED_FRAME_SIZE,
-		"Buffer size is less than max supported frame size!");
-	SPDYF_ASSERT(SPDY_MAX_SUPPORTED_FRAME_SIZE >= 32,
-		"Max supported frame size must be bigger than the minimal value!");
-	SPDYF_ASSERT(SPDY_IO_SUBSYSTEM_NONE == spdyf_io_initialized,
-		"SPDY_init must be called only once per program or after SPDY_deinit");
-    
-  if(SPDY_IO_SUBSYSTEM_OPENSSL & io_subsystem)
-  {
-    SPDYF_openssl_global_init();
-    spdyf_io_initialized |= SPDY_IO_SUBSYSTEM_OPENSSL;
-  }
-  else if(SPDY_IO_SUBSYSTEM_RAW & io_subsystem)
-  {
-    SPDYF_raw_global_init();
-    spdyf_io_initialized |= SPDY_IO_SUBSYSTEM_RAW;
-  }
-  
-	SPDYF_ASSERT(SPDY_IO_SUBSYSTEM_NONE != spdyf_io_initialized,
-		"SPDY_init could not find even one IO subsystem");
-    
-	return SPDY_YES;
-}
-
-
-void
-SPDY_deinit ()
-{
-	SPDYF_ASSERT(SPDY_IO_SUBSYSTEM_NONE != spdyf_io_initialized,
-		"SPDY_init has not been called!");
-    
-  if(SPDY_IO_SUBSYSTEM_OPENSSL & spdyf_io_initialized)
-    SPDYF_openssl_global_deinit();
-  else if(SPDY_IO_SUBSYSTEM_RAW & spdyf_io_initialized)
-    SPDYF_raw_global_deinit();
-  
-  spdyf_io_initialized = SPDY_IO_SUBSYSTEM_NONE;
-}
-
-
-void 
-SPDY_run (struct SPDY_Daemon *daemon)
-{
-	if(NULL == daemon)
-	{
-		SPDYF_DEBUG("daemon is NULL");
-		return;
-	}
-	
-	SPDYF_run(daemon);
-}
-
-
-int
-SPDY_get_timeout (struct SPDY_Daemon *daemon, 
-		     unsigned long long *timeout)
-{
-	if(NULL == daemon)
-	{
-		SPDYF_DEBUG("daemon is NULL");
-		return SPDY_INPUT_ERROR;
-	}
-	
-	return SPDYF_get_timeout(daemon,timeout);
-}
-
-
-int
-SPDY_get_fdset (struct SPDY_Daemon *daemon,
-				fd_set *read_fd_set,
-				fd_set *write_fd_set, 
-				fd_set *except_fd_set)
-{
-	if(NULL == daemon
-		|| NULL == read_fd_set
-		|| NULL == write_fd_set
-		|| NULL == except_fd_set)
-	{
-		SPDYF_DEBUG("a parameter is NULL");
-		return SPDY_INPUT_ERROR;
-	}
-	
-	return SPDYF_get_fdset(daemon,
-				read_fd_set,
-				write_fd_set, 
-				except_fd_set,
-				false);
-}
-
-
-struct SPDY_Daemon *
-SPDY_start_daemon (uint16_t port,
-				const char *certfile,
-				const char *keyfile,
-		     SPDY_NewSessionCallback nscb,
-		     SPDY_SessionClosedCallback sccb,
-		     SPDY_NewRequestCallback nrcb,
-		     SPDY_NewDataCallback npdcb,
-		     void * cls,
-		     ...)
-{
-	struct SPDY_Daemon *daemon;
-	va_list valist;
-	
-	if(SPDY_IO_SUBSYSTEM_NONE == spdyf_io_initialized)
-	{
-		SPDYF_DEBUG("library not initialized");
-		return NULL;
-	}
-  /*
-   * for now make this checks in framing layer
-	if(NULL == certfile)
-	{
-		SPDYF_DEBUG("certfile is NULL");
-		return NULL;
-	}
-	if(NULL == keyfile)
-	{
-		SPDYF_DEBUG("keyfile is NULL");
-		return NULL;
-	}
-  */
-	
-	va_start(valist, cls);
-	daemon = SPDYF_start_daemon_va ( port,
-				certfile,
-				keyfile,
-		      nscb,
-		      sccb,
-		      nrcb,
-		      npdcb,
-		      &spdy_handler_new_stream,
-		      &spdy_handler_new_data,
-		      cls,
-		      NULL,
-		      valist
-		     );
-	va_end(valist);
-	
-	return daemon;
-}
-
-
-void 
-SPDY_stop_daemon (struct SPDY_Daemon *daemon)
-{	
-	if(NULL == daemon)
-	{
-		SPDYF_DEBUG("daemon is NULL");
-		return;
-	}
-
-	SPDYF_stop_daemon(daemon);
-}
-
-
-struct SPDY_Response *
-SPDY_build_response(int status,
-					const char * statustext,
-					const char * version,
-					struct SPDY_NameValue * headers,
-					const void * data,
-					size_t size)
-{
-	struct SPDY_Response *response = NULL;
-	struct SPDY_NameValue ** all_headers = NULL; //TODO maybe array in stack is enough
-	char *fullstatus = NULL;
-	int ret;
-	int num_hdr_containers = 1;
-	
-	if(NULL == version)
-	{
-		SPDYF_DEBUG("version is NULL");
-		return NULL;
-	}
-	
-	if(NULL == (response = malloc(sizeof(struct SPDY_Response))))
-		goto free_and_fail;
-	memset(response, 0, sizeof(struct SPDY_Response));
-	
-	if(NULL != headers && !SPDYF_name_value_is_empty(headers))
-		num_hdr_containers = 2;
-	
-	if(NULL == (all_headers = malloc(num_hdr_containers * sizeof(struct SPDY_NameValue *))))
-		goto free_and_fail;
-	memset(all_headers, 0, num_hdr_containers * sizeof(struct SPDY_NameValue *));
-	
-	if(2 == num_hdr_containers)
-		all_headers[1] = headers;
-	
-	if(NULL == (all_headers[0] = SPDY_name_value_create()))
-		goto free_and_fail;
-	
-	if(NULL == statustext)
-		ret = asprintf(&fullstatus, "%i", status);
-	else
-		ret = asprintf(&fullstatus, "%i %s", status, statustext); 
-	if(-1 == ret)
-		goto free_and_fail;
-		
-	if(SPDY_YES != SPDY_name_value_add(all_headers[0], ":status", fullstatus))
-		goto free_and_fail;
-		
-	free(fullstatus);
-	fullstatus = NULL;
-	
-	if(SPDY_YES != SPDY_name_value_add(all_headers[0], ":version", version))
-		goto free_and_fail;
-	
-	if(0 >= (response->headers_size = SPDYF_name_value_to_stream(all_headers,
-												num_hdr_containers,
-												&(response->headers))))
-		goto free_and_fail;
-		
-	SPDY_name_value_destroy(all_headers[0]);
-	free(all_headers);
-  all_headers = NULL;
-	
-	if(size > 0)
-	{
-		//copy the data to the response object
-		if(NULL == (response->data = malloc(size)))
-		{
-			free(response->headers);
-			goto free_and_fail;
-		}
-		memcpy(response->data, data, size);
-		response->data_size = size;
-	}
-	
-	return response;
-	
-	//for GOTO
-	free_and_fail:
-	
-	free(fullstatus);
-	if(NULL != all_headers)
-		SPDY_name_value_destroy(all_headers[0]);
-	free(all_headers);
-	free(response);
-	
-	return NULL;
-}
-
-
-struct SPDY_Response *
-SPDY_build_response_with_callback(int status,
-					const char * statustext,
-					const char * version,
-					struct SPDY_NameValue * headers,
-					SPDY_ResponseCallback rcb,
-					void *rcb_cls,
-					uint32_t block_size)
-{
-	struct SPDY_Response *response;
-	
-	if(NULL == rcb)
-	{
-		SPDYF_DEBUG("rcb is NULL");
-		return NULL;
-	}
-	if(block_size > SPDY_MAX_SUPPORTED_FRAME_SIZE)
-	{
-		SPDYF_DEBUG("block_size is wrong");
-		return NULL;
-	}
-	
-	if(0 == block_size)
-		block_size = SPDY_MAX_SUPPORTED_FRAME_SIZE;
-	
-	response = SPDY_build_response(status,
-					statustext,
-					version,
-					headers,
-					NULL,
-					0);
-	
-	if(NULL == response)
-	{
-		return NULL;
-	}
-			
-	response->rcb = rcb;
-	response->rcb_cls = rcb_cls;
-	response->rcb_block_size = block_size;
-	
-	return response;
-}
-
-
-int
-SPDY_queue_response (struct SPDY_Request * request,
-					struct SPDY_Response *response,
-					bool closestream,
-					bool consider_priority,
-					SPDY_ResponseResultCallback rrcb,
-					void * rrcb_cls)
-{
-	struct SPDYF_Response_Queue *headers_to_queue;
-	struct SPDYF_Response_Queue *body_to_queue;
-	SPDYF_ResponseQueueResultCallback frqcb = NULL;
-	void *frqcb_cls = NULL;
-	int int_consider_priority = consider_priority ? SPDY_YES : SPDY_NO;
-	
-	if(NULL == request)
-	{
-		SPDYF_DEBUG("request is NULL");
-		return SPDY_INPUT_ERROR;
-	}
-	if(NULL == response)
-	{
-		SPDYF_DEBUG("request is NULL");
-		return SPDY_INPUT_ERROR;
-	}
-	
-	if(request->stream->is_out_closed
-		|| SPDY_SESSION_STATUS_CLOSING == request->stream->session->status)
-		return SPDY_NO;
-	
-	if(NULL != rrcb)
-	{
-		frqcb_cls = request;
-		frqcb = &spdy_handler_response_queue_result;
-	}
-	
-	if(response->data_size > 0)
-	{	
-		//SYN_REPLY and DATA will be queued
-		
-		if(NULL == (headers_to_queue = SPDYF_response_queue_create(false,
-							response->headers,
-							response->headers_size,
-							response,
-							request->stream,
-							false,
-							NULL,
-							NULL,
-							NULL,
-							NULL)))
-		{
-			return SPDY_NO;
-		}
-		
-		if(NULL == (body_to_queue = SPDYF_response_queue_create(true,
-							response->data,
-							response->data_size,
-							response,
-							request->stream,
-							closestream,
-							frqcb,
-							frqcb_cls,
-							rrcb,
-							rrcb_cls)))
-		{
-			SPDYF_response_queue_destroy(headers_to_queue);
-			return SPDY_NO;
-		}
-							
-		SPDYF_queue_response (headers_to_queue,
-							request->stream->session,
-							int_consider_priority);
-							
-		SPDYF_queue_response (body_to_queue,
-							request->stream->session,
-							int_consider_priority);
-	}
-	else if(NULL == response->rcb)
-	{
-		//no "body" will be queued, e.g. HTTP 404 without body
-		
-		if(NULL == (headers_to_queue = SPDYF_response_queue_create(false,
-							response->headers,
-							response->headers_size,
-							response,
-							request->stream,
-							closestream,
-							frqcb,
-							frqcb_cls,
-							rrcb,
-							rrcb_cls)))
-		{
-			return SPDY_NO;
-		}
-							
-		SPDYF_queue_response (headers_to_queue,
-							request->stream->session,
-							int_consider_priority);
-	}
-	else
-	{
-		//response with callbacks
-		
-		if(NULL == (headers_to_queue = SPDYF_response_queue_create(false,
-							response->headers,
-							response->headers_size,
-							response,
-							request->stream,
-							false,
-							NULL,
-							NULL,
-							NULL,
-							NULL)))
-		{
-			return SPDY_NO;
-		}
-		
-		if(NULL == (body_to_queue = SPDYF_response_queue_create(true,
-							response->data,
-							response->data_size,
-							response,
-							request->stream,
-							closestream,
-							frqcb,
-							frqcb_cls,
-							rrcb,
-							rrcb_cls)))
-		{
-			SPDYF_response_queue_destroy(headers_to_queue);
-			return SPDY_NO;
-		}
-							
-		SPDYF_queue_response (headers_to_queue,
-							request->stream->session,
-							int_consider_priority);
-							
-		SPDYF_queue_response (body_to_queue,
-							request->stream->session,
-							int_consider_priority);
-	}
-		
-	return SPDY_YES;
-}
-
-
-socklen_t
-SPDY_get_remote_addr(struct SPDY_Session * session,
-					 struct sockaddr ** addr)
-{
-	if(NULL == session)
-	{
-		SPDYF_DEBUG("session is NULL");
-		return 0;
-	}
-	
-	*addr = session->addr;
-	
-	return session->addr_len;
-}
-
-
-struct SPDY_Session *
-SPDY_get_session_for_request(const struct SPDY_Request * request)
-{
-	if(NULL == request)
-	{
-		SPDYF_DEBUG("request is NULL");
-		return NULL;
-	}
-	
-	return request->stream->session;
-}
-
-
-void *
-SPDY_get_cls_from_session(struct SPDY_Session * session)
-{
-	if(NULL == session)
-	{
-		SPDYF_DEBUG("session is NULL");
-		return NULL;
-	}
-	
-	return session->user_cls;
-}
-
-
-void
-SPDY_set_cls_to_session(struct SPDY_Session * session,
-							void * cls)
-{
-	if(NULL == session)
-	{
-		SPDYF_DEBUG("session is NULL");
-		return;
-	}
-	
-	session->user_cls = cls;
-}
-
-
-void *
-SPDY_get_cls_from_request(struct SPDY_Request * request)
-{
-	if(NULL == request)
-	{
-		SPDYF_DEBUG("request is NULL");
-		return NULL;
-	}
-	
-	return request->user_cls;
-}
-
-
-void
-SPDY_set_cls_to_request(struct SPDY_Request * request,
-							void * cls)
-{
-	if(NULL == request)
-	{
-		SPDYF_DEBUG("request is NULL");
-		return;
-	}
-	
-	request->user_cls = cls;
-}
diff --git a/src/microspdy/applicationlayer.h b/src/microspdy/applicationlayer.h
deleted file mode 100644
index a36760f..0000000
--- a/src/microspdy/applicationlayer.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file applicationlayer.h
- * @brief  SPDY application or HTTP layer
- * @author Andrey Uzunov
- */
-
-#ifndef APPLICATIONLAYER_H
-#define APPLICATIONLAYER_H
-
-#include "platform.h"
-
-
-#endif
diff --git a/src/microspdy/compression.c b/src/microspdy/compression.c
deleted file mode 100644
index 532ab64..0000000
--- a/src/microspdy/compression.c
+++ /dev/null
@@ -1,441 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file compression.c
- * @brief  zlib handling functions
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "structures.h"
-#include "internal.h"
-#include "compression.h"
-
-/* spdy ver 3 specific dictionary used by zlib */
-static const unsigned char
-spdyf_zlib_dictionary[] = {
-	0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69,   // - - - - o p t i
-	0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68,   // o n s - - - - h
-	0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70,   // e a d - - - - p
-	0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70,   // o s t - - - - p
-	0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65,   // u t - - - - d e
-	0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05,   // l e t e - - - -
-	0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00,   // t r a c e - - -
-	0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00,   // - a c c e p t -
-	0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70,   // - - - a c c e p
-	0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65,   // t - c h a r s e
-	0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63,   // t - - - - a c c
-	0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f,   // e p t - e n c o
-	0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f,   // d i n g - - - -
-	0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c,   // a c c e p t - l
-	0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00,   // a n g u a g e -
-	0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70,   // - - - a c c e p
-	0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73,   // t - r a n g e s
-	0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00,   // - - - - a g e -
-	0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77,   // - - - a l l o w
-	0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68,   // - - - - a u t h
-	0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f,   // o r i z a t i o
-	0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63,   // n - - - - c a c
-	0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72,   // h e - c o n t r
-	0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f,   // o l - - - - c o
-	0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e,   // n n e c t i o n
-	0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74,   // - - - - c o n t
-	0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65,   // e n t - b a s e
-	0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74,   // - - - - c o n t
-	0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f,   // e n t - e n c o
-	0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10,   // d i n g - - - -
-	0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d,   // c o n t e n t -
-	0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65,   // l a n g u a g e
-	0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74,   // - - - - c o n t
-	0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67,   // e n t - l e n g
-	0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f,   // t h - - - - c o
-	0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f,   // n t e n t - l o
-	0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00,   // c a t i o n - -
-	0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e,   // - - c o n t e n
-	0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00,   // t - m d 5 - - -
-	0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,   // - c o n t e n t
-	0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00,   // - r a n g e - -
-	0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e,   // - - c o n t e n
-	0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00,   // t - t y p e - -
-	0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00,   // - - d a t e - -
-	0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00,   // - - e t a g - -
-	0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74,   // - - e x p e c t
-	0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69,   // - - - - e x p i
-	0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66,   // r e s - - - - f
-	0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68,   // r o m - - - - h
-	0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69,   // o s t - - - - i
-	0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00,   // f - m a t c h -
-	0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f,   // - - - i f - m o
-	0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73,   // d i f i e d - s
-	0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d,   // i n c e - - - -
-	0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d,   // i f - n o n e -
-	0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00,   // m a t c h - - -
-	0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67,   // - i f - r a n g
-	0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d,   // e - - - - i f -
-	0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69,   // u n m o d i f i
-	0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65,   // e d - s i n c e
-	0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74,   // - - - - l a s t
-	0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65,   // - m o d i f i e
-	0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63,   // d - - - - l o c
-	0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00,   // a t i o n - - -
-	0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72,   // - m a x - f o r
-	0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00,   // w a r d s - - -
-	0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00,   // - p r a g m a -
-	0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79,   // - - - p r o x y
-	0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74,   // - a u t h e n t
-	0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00,   // i c a t e - - -
-	0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61,   // - p r o x y - a
-	0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61,   // u t h o r i z a
-	0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05,   // t i o n - - - -
-	0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00,   // r a n g e - - -
-	0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72,   // - r e f e r e r
-	0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72,   // - - - - r e t r
-	0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00,   // y - a f t e r -
-	0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65,   // - - - s e r v e
-	0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00,   // r - - - - t e -
-	0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c,   // - - - t r a i l
-	0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72,   // e r - - - - t r
-	0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65,   // a n s f e r - e
-	0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00,   // n c o d i n g -
-	0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61,   // - - - u p g r a
-	0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73,   // d e - - - - u s
-	0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74,   // e r - a g e n t
-	0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79,   // - - - - v a r y
-	0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00,   // - - - - v i a -
-	0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69,   // - - - w a r n i
-	0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77,   // n g - - - - w w
-	0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e,   // w - a u t h e n
-	0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00,   // t i c a t e - -
-	0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64,   // - - m e t h o d
-	0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00,   // - - - - g e t -
-	0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75,   // - - - s t a t u
-	0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30,   // s - - - - 2 0 0
-	0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76,   // - O K - - - - v
-	0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00,   // e r s i o n - -
-	0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31,   // - - H T T P - 1
-	0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72,   // - 1 - - - - u r
-	0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62,   // l - - - - p u b
-	0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73,   // l i c - - - - s
-	0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69,   // e t - c o o k i
-	0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65,   // e - - - - k e e
-	0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00,   // p - a l i v e -
-	0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69,   // - - - o r i g i
-	0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32,   // n 1 0 0 1 0 1 2
-	0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35,   // 0 1 2 0 2 2 0 5
-	0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30,   // 2 0 6 3 0 0 3 0
-	0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33,   // 2 3 0 3 3 0 4 3
-	0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37,   // 0 5 3 0 6 3 0 7
-	0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30,   // 4 0 2 4 0 5 4 0
-	0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34,   // 6 4 0 7 4 0 8 4
-	0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31,   // 0 9 4 1 0 4 1 1
-	0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31,   // 4 1 2 4 1 3 4 1
-	0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34,   // 4 4 1 5 4 1 6 4
-	0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34,   // 1 7 5 0 2 5 0 4
-	0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e,   // 5 0 5 2 0 3 - N
-	0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f,   // o n - A u t h o
-	0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65,   // r i t a t i v e
-	0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61,   // - I n f o r m a
-	0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20,   // t i o n 2 0 4 -
-	0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65,   // N o - C o n t e
-	0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f,   // n t 3 0 1 - M o
-	0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d,   // v e d - P e r m
-	0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34,   // a n e n t l y 4
-	0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52,   // 0 0 - B a d - R
-	0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30,   // e q u e s t 4 0
-	0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68,   // 1 - U n a u t h
-	0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30,   // o r i z e d 4 0
-	0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64,   // 3 - F o r b i d
-	0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e,   // d e n 4 0 4 - N
-	0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64,   // o t - F o u n d
-	0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65,   // 5 0 0 - I n t e
-	0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72,   // r n a l - S e r
-	0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f,   // v e r - E r r o
-	0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74,   // r 5 0 1 - N o t
-	0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65,   // - I m p l e m e
-	0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20,   // n t e d 5 0 3 -
-	0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20,   // S e r v i c e -
-	0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61,   // U n a v a i l a
-	0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46,   // b l e J a n - F
-	0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41,   // e b - M a r - A
-	0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a,   // p r - M a y - J
-	0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41,   // u n - J u l - A
-	0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20,   // u g - S e p t -
-	0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20,   // O c t - N o v -
-	0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30,   // D e c - 0 0 - 0
-	0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e,   // 0 - 0 0 - M o n
-	0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57,   // - - T u e - - W
-	0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c,   // e d - - T h u -
-	0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61,   // - F r i - - S a
-	0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20,   // t - - S u n - -
-	0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b,   // G M T c h u n k
-	0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f,   // e d - t e x t -
-	0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61,   // h t m l - i m a
-	0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69,   // g e - p n g - i
-	0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67,   // m a g e - j p g
-	0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67,   // - i m a g e - g
-	0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69,   // i f - a p p l i
-	0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78,   // c a t i o n - x
-	0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69,   // m l - a p p l i
-	0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78,   // c a t i o n - x
-	0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c,   // h t m l - x m l
-	0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c,   // - t e x t - p l
-	0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74,   // a i n - t e x t
-	0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72,   // - j a v a s c r
-	0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c,   // i p t - p u b l
-	0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74,   // i c p r i v a t
-	0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65,   // e m a x - a g e
-	0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65,   // - g z i p - d e
-	0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64,   // f l a t e - s d
-	0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65,   // c h c h a r s e
-	0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63,   // t - u t f - 8 c
-	0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69,   // h a r s e t - i
-	0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d,   // s o - 8 8 5 9 -
-	0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a,   // 1 - u t f - - -
-	0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e          // - e n q - 0 -
-};
-
-
-int
-SPDYF_zlib_deflate_init(z_stream *strm)
-{
-	int ret;
-	
-	strm->zalloc = Z_NULL;
-	strm->zfree = Z_NULL;
-	strm->opaque = Z_NULL;
-	//the second argument is "level of compression"
-	//use 0 for no compression; 9 for best compression
-	ret = deflateInit(strm, Z_DEFAULT_COMPRESSION);
-	if(ret != Z_OK)
-	{
-		SPDYF_DEBUG("deflate init");
-		return SPDY_NO;
-	}
-	ret = deflateSetDictionary(strm,
-				   spdyf_zlib_dictionary,
-				   sizeof(spdyf_zlib_dictionary));
-	if(ret != Z_OK)
-	{
-		SPDYF_DEBUG("deflate set dict");
-		deflateEnd(strm);
-		return SPDY_NO;
-	}
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_zlib_deflate_end(z_stream *strm)
-{
-	deflateEnd(strm);
-}
-
-int
-SPDYF_zlib_deflate(z_stream *strm,
-					const void *src,
-					size_t src_size,
-					size_t *data_used,
-					void **dest,
-					size_t *dest_size)
-{
-	int ret;
-	int flush;
-	unsigned int have;
-	Bytef out[SPDYF_ZLIB_CHUNK];
-	
-	*dest = NULL;
-	*dest_size = 0;
-
-	do
-	{
-		/* check for big data bigger than the buffer used */
-		if(src_size > SPDYF_ZLIB_CHUNK)
-		{
-			strm->avail_in = SPDYF_ZLIB_CHUNK;
-			src_size -= SPDYF_ZLIB_CHUNK;
-			/* flush is used for the loop to detect if we still
-			 * need to supply additional
-			 * data to the stream via avail_in and next_in. */
-			flush = Z_NO_FLUSH;
-		}
-		else
-		{
-			strm->avail_in = src_size;
-			flush = Z_SYNC_FLUSH;
-		}
-		*data_used += strm->avail_in;
-
-		strm->next_in = (Bytef *)src;
-
-		/* Loop while output data is available */
-		do
-		{
-			strm->avail_out = SPDYF_ZLIB_CHUNK;
-			strm->next_out = out;
-
-			/* No need to check return value of deflate.
-			* (See zlib documentation at http://www.zlib.net/zlib_how.html */
-			ret = deflate(strm, flush);
-			have = SPDYF_ZLIB_CHUNK - strm->avail_out;
-
-			/* (Re)allocate memory for dest and keep track of it's size. */
-			*dest_size += have;
-			*dest = realloc(*dest, *dest_size);
-			if(!*dest)
-			{
-				SPDYF_DEBUG("realloc data for result");
-				deflateEnd(strm);
-				return SPDY_NO;
-			}
-			memcpy((*dest) + ((*dest_size) - have), out, have);
-		}
-		while(strm->avail_out == 0);
-		/* At this point, all of the input data should already
-		* have been used. */
-		SPDYF_ASSERT(strm->avail_in == 0,"compressing bug");
-	}
-	while(flush != Z_SYNC_FLUSH);
-	
-	return Z_OK == ret ? SPDY_YES : SPDY_NO;
-}
-
-
-int
-SPDYF_zlib_inflate_init(z_stream *strm)
-{
-	int ret;
-	
-	strm->zalloc = Z_NULL;
-	strm->zfree = Z_NULL;
-	strm->opaque = Z_NULL;
-	strm->avail_in = 0;
-	strm->next_in = Z_NULL;
-	//change 15 to lower value for performance and benchmark
-	//"The windowBits parameter is the base two logarithm of the
-	// maximum window size (the size of the history buffer)."
-	ret = inflateInit2(strm, 15);
-	if(ret != Z_OK)
-	{
-		SPDYF_DEBUG("Cannot inflateInit2 the stream");
-		return SPDY_NO;
-	}
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_zlib_inflate_end(z_stream *strm)
-{
-	inflateEnd(strm);
-}
-
-
-int
-SPDYF_zlib_inflate(z_stream *strm,
-					const void *src,
-					size_t src_size,
-					void **dest,
-					size_t *dest_size)
-{
-	int ret = Z_OK;
-	uint32_t have;
-	Bytef out[SPDYF_ZLIB_CHUNK];
-	
-	*dest = NULL;
-	*dest_size = 0;
-
-	/* decompress until deflate stream ends or end of file */
-	do
-	{		
-		if(src_size > SPDYF_ZLIB_CHUNK)
-		{
-			strm->avail_in = SPDYF_ZLIB_CHUNK;
-			src_size -= SPDYF_ZLIB_CHUNK;
-		}
-		else
-		{
-			strm->avail_in = src_size;
-			src_size = 0;
-		}
-		
-		if(strm->avail_in == 0){
-			//the loop breaks always here as the stream never ends
-			break;
-		}
-			
-		strm->next_in = (Bytef *) src;
-		/* run inflate() on input until output buffer not full */
-		do {
-			strm->avail_out = SPDYF_ZLIB_CHUNK;
-			strm->next_out = out;
-			ret = inflate(strm, Z_SYNC_FLUSH);
-			
-			switch (ret)
-			{
-				case Z_STREAM_ERROR:
-					SPDYF_DEBUG("Error on inflate");
-					//no inflateEnd here, same in zlib example
-					return SPDY_NO;
-				
-				case Z_NEED_DICT:
-					ret = inflateSetDictionary(strm,
-										   spdyf_zlib_dictionary,
-										   sizeof(spdyf_zlib_dictionary));
-					if(ret != Z_OK)
-					{
-						SPDYF_DEBUG("Error on inflateSetDictionary");
-						inflateEnd(strm);
-						return SPDY_NO;
-					}
-					ret = inflate(strm, Z_SYNC_FLUSH);
-					if(Z_STREAM_ERROR == ret)
-					{
-						SPDYF_DEBUG("Error on inflate");
-						return SPDY_NO;
-					}
-					break;
-					
-				case Z_DATA_ERROR:
-					SPDYF_DEBUG("Z_DATA_ERROR");
-					inflateEnd(strm);
-					return SPDY_NO;
-					
-				case Z_MEM_ERROR:
-					SPDYF_DEBUG("Z_MEM_ERROR");
-					inflateEnd(strm);
-					return SPDY_NO;
-			}
-			have = SPDYF_ZLIB_CHUNK - strm->avail_out;
-			*dest_size += have;
-			/* (re)alloc memory for the output buffer */
-			*dest = realloc(*dest, *dest_size);
-			if(!*dest)
-			{
-				SPDYF_DEBUG("Cannot realloc memory");
-				inflateEnd(strm);
-				return SPDY_NO;
-			}
-			memcpy((*dest) + ((*dest_size) - have), out, have);
-		}
-		while (0 == strm->avail_out);
-	}
-	while (Z_STREAM_END != ret);
-	
-	return Z_OK == ret || Z_STREAM_END == ret ? SPDY_YES : SPDY_NO;
-}
diff --git a/src/microspdy/compression.h b/src/microspdy/compression.h
deleted file mode 100644
index 40746e7..0000000
--- a/src/microspdy/compression.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file compression.h
- * @brief  zlib handling functions
- * @author Andrey Uzunov
- */
-
-#ifndef COMPRESSION_H
-#define COMPRESSION_H
-
-#include "platform.h"
-
-/* size of buffers used by zlib on (de)compressing */
-#define SPDYF_ZLIB_CHUNK 16384
-
-
-/**
- * Initializes the zlib stream for compression. Must be called once
- * for a session on initialization.
- *
- * @param strm Zlib stream on which we work
- * @return SPDY_NO if zlib failed. SPDY_YES otherwise
- */		
-int
-SPDYF_zlib_deflate_init(z_stream *strm);
-
-
-/**
- * Deinitializes the zlib stream for compression. Should be called once
- * for a session on cleaning up.
- *
- * @param strm Zlib stream on which we work
- */	
-void
-SPDYF_zlib_deflate_end(z_stream *strm);
-
-
-/**
- * Compressing stream with zlib.
- *
- * @param strm Zlib stream on which we work
- * @param src stream of the data to be compressed
- * @param src_size size of the data
- * @param data_used the number of bytes from src_stream that were used
- * 					TODO do we need
- * @param dest the resulting compressed stream. Should be NULL. Must be
- * 					freed later manually.
- * @param dest_size size of the data after compression
- * @return SPDY_NO if malloc or zlib failed. SPDY_YES otherwise
- */
-int
-SPDYF_zlib_deflate(z_stream *strm,
-					const void *src,
-					size_t src_size,
-					size_t *data_used,
-					void **dest,
-					size_t *dest_size);
-     
-
-/**
- * Initializes the zlib stream for decompression. Must be called once
- * for a session.
- *
- * @param strm Zlib stream on which we work
- * @return SPDY_NO if zlib failed. SPDY_YES otherwise
- */	                 
-int
-SPDYF_zlib_inflate_init(z_stream *strm);
-
-
-/**
- * Deinitializes the zlib stream for decompression. Should be called once
- * for a session on cleaning up.
- *
- * @param strm Zlib stream on which we work
- */	
-void
-SPDYF_zlib_inflate_end(z_stream *strm);
-
-
-/**
- * Decompressing stream with zlib.
- *
- * @param strm Zlib stream on which we work
- * @param src stream of the data to be decompressed
- * @param src_size size of the data
- * @param dest the resulting decompressed stream. Should be NULL. Must
- * 				be freed manually.
- * @param dest_size size of the data after decompression
- * @return SPDY_NO if malloc or zlib failed. SPDY_YES otherwise. If the
- * 			function fails, the SPDY session must be closed
- */
-int
-SPDYF_zlib_inflate(z_stream *strm,
-					const void *src,
-					size_t src_size,
-					void **dest,
-					size_t *dest_size);
-
-#endif
diff --git a/src/microspdy/daemon.c b/src/microspdy/daemon.c
deleted file mode 100644
index 32285ae..0000000
--- a/src/microspdy/daemon.c
+++ /dev/null
@@ -1,544 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file microspdy/daemon.c
- * @brief  daemon functionality
- * @author Andrey Uzunov
- */
- 
-#include "platform.h"
-#include "structures.h"
-#include "internal.h"
-#include "session.h"
-#include "io.h"
-
-
-/**
- * Default implementation of the panic function,
- * prints an error message and aborts.
- *
- * @param cls unused
- * @param file name of the file with the problem
- * @param line line number with the problem
- * @param reason error message with details
- */
-static void 
-spdyf_panic_std (void *cls,
-	       const char *file,
-	       unsigned int line,
-	       const char *reason)
-{
-	(void)cls;
-	fprintf (stdout, "Fatal error in libmicrospdy %s:%u: %s\n",
-		file, line, reason);
-	//raise(SIGINT); //used for gdb
-	abort ();
-}
-
-
-/**
- * Global handler for fatal errors.
- */
-SPDY_PanicCallback spdyf_panic = &spdyf_panic_std;
-
-
-/**
- * Global closure argument for "spdyf_panic".
- */
-void *spdyf_panic_cls;
-
-
-/**
- * Free resources associated with all closed connections.
- * (destroy responses, free buffers, etc.).
- *
- * @param daemon daemon to clean up
- */
-static void
-spdyf_cleanup_sessions (struct SPDY_Daemon *daemon)
-{
-	struct SPDY_Session *session;
-	
-	while (NULL != (session = daemon->cleanup_head))
-	{
-		DLL_remove (daemon->cleanup_head,
-			daemon->cleanup_tail,
-			session);
-			
-		SPDYF_session_destroy(session);
-	}
-}
-
-
-/**
- * Closing of all connections handled by the daemon.
- *
- * @param daemon SPDY daemon
- */
-static void
-spdyf_close_all_sessions (struct SPDY_Daemon *daemon)
-{
-	struct SPDY_Session *session;
-	
-	while (NULL != (session = daemon->sessions_head))
-	{	
-		//prepare GOAWAY frame
-		SPDYF_prepare_goaway(session, SPDY_GOAWAY_STATUS_OK, true);
-		//try to send the frame (it is best effort, so it will maybe sent)
-		SPDYF_session_write(session,true);
-		SPDYF_session_close(session);
-	}
-	
-	spdyf_cleanup_sessions(daemon);
-}
-
-
-/**
- * Parse a list of options given as varargs.
- * 
- * @param daemon the daemon to initialize
- * @param valist the options
- * @return SPDY_YES on success, SPDY_NO on error
- */
-static int
-spdyf_parse_options_va (struct SPDY_Daemon *daemon,
-		  va_list valist)
-{
-	enum SPDY_DAEMON_OPTION opt;
-
-	while (SPDY_DAEMON_OPTION_END != (opt = (enum SPDY_DAEMON_OPTION) va_arg (valist, int)))
-	{
-		if(opt & daemon->options)
-		{
-			SPDYF_DEBUG("Daemon option %i used twice",opt);
-			return SPDY_NO;
-		}
-		daemon->options |= opt;
-		
-		switch (opt)
-		{
-			case SPDY_DAEMON_OPTION_SESSION_TIMEOUT:
-				daemon->session_timeout = va_arg (valist, unsigned int) * 1000;
-				break;
-			case SPDY_DAEMON_OPTION_SOCK_ADDR:
-				daemon->address = va_arg (valist, struct sockaddr *);
-				break;
-			case SPDY_DAEMON_OPTION_FLAGS:
-				daemon->flags = va_arg (valist, enum SPDY_DAEMON_FLAG);
-				break;
-			case SPDY_DAEMON_OPTION_IO_SUBSYSTEM:
-				daemon->io_subsystem = va_arg (valist, enum SPDY_IO_SUBSYSTEM);
-				break;
-			case SPDY_DAEMON_OPTION_MAX_NUM_FRAMES:
-				daemon->max_num_frames = va_arg (valist, uint32_t);
-				break;
-			default:
-				SPDYF_DEBUG("Wrong option for the daemon %i",opt);
-				return SPDY_NO;
-		}
-	}
-	return SPDY_YES;
-}
-
-
-void 
-SPDY_set_panic_func (SPDY_PanicCallback cb,
-					void *cls)
-{
-	spdyf_panic = cb;
-	spdyf_panic_cls = cls;
-}
-
-
-struct SPDY_Daemon *
-SPDYF_start_daemon_va (uint16_t port,
-					const char *certfile,
-					const char *keyfile,
-					SPDY_NewSessionCallback nscb,
-					SPDY_SessionClosedCallback sccb,
-					SPDY_NewRequestCallback nrcb,
-					SPDY_NewDataCallback npdcb,
-					SPDYF_NewStreamCallback fnscb,
-					SPDYF_NewDataCallback fndcb,
-					void * cls,
-					void * fcls,
-					va_list valist)
-{
-	struct SPDY_Daemon *daemon = NULL;
-	int afamily;
-	int option_on = 1;
-	int ret;
-	struct sockaddr_in* servaddr4 = NULL;
-#if HAVE_INET6
-	struct sockaddr_in6* servaddr6 = NULL;
-#endif
-	socklen_t addrlen;
-
-	if (NULL == (daemon = malloc (sizeof (struct SPDY_Daemon))))
-	{
-		SPDYF_DEBUG("malloc");
-		return NULL;
-	}
-	memset (daemon, 0, sizeof (struct SPDY_Daemon));
-	daemon->socket_fd = -1;
-	daemon->port = port;
-
-	if(SPDY_YES != spdyf_parse_options_va (daemon, valist))
-	{
-		SPDYF_DEBUG("parse");
-		goto free_and_fail;
-	}
-  
-  if(0 == daemon->max_num_frames)
-    daemon->max_num_frames = SPDYF_NUM_SENT_FRAMES_AT_ONCE;
-	
-	if(!port && NULL == daemon->address)
-	{
-		SPDYF_DEBUG("Port is 0");
-		goto free_and_fail;
-	}
-  if(0 == daemon->io_subsystem)
-    daemon->io_subsystem = SPDY_IO_SUBSYSTEM_OPENSSL;
-  
-  if(SPDY_YES != SPDYF_io_set_daemon(daemon, daemon->io_subsystem))
-		goto free_and_fail;
-  
-  if(SPDY_IO_SUBSYSTEM_RAW != daemon->io_subsystem)
-  {
-    if (NULL == certfile
-      || NULL == (daemon->certfile = strdup (certfile)))
-    {
-      SPDYF_DEBUG("strdup (certfile)");
-      goto free_and_fail;
-    }
-    if (NULL == keyfile
-      || NULL == (daemon->keyfile = strdup (keyfile)))
-    {
-      SPDYF_DEBUG("strdup (keyfile)");
-      goto free_and_fail;
-    }
-  }
-  
-	daemon->new_session_cb = nscb;
-	daemon->session_closed_cb = sccb;
-	daemon->new_request_cb = nrcb;
-	daemon->received_data_cb = npdcb;
-	daemon->cls = cls;
-	daemon->fcls = fcls;
-	daemon->fnew_stream_cb = fnscb;
-	daemon->freceived_data_cb = fndcb;
-
-#if HAVE_INET6
-	//handling IPv6
-	if((daemon->flags & SPDY_DAEMON_FLAG_ONLY_IPV6)
-		&& NULL != daemon->address && AF_INET6 != daemon->address->sa_family)
-	{
-		SPDYF_DEBUG("SPDY_DAEMON_FLAG_ONLY_IPV6 set but IPv4 address provided");
-		goto free_and_fail;
-	}
-  
-  addrlen = sizeof (struct sockaddr_in6);
-    
-	if(NULL == daemon->address)
-	{		
-		if (NULL == (servaddr6 = malloc (addrlen)))
-		{
-			SPDYF_DEBUG("malloc");
-			goto free_and_fail;
-		}
-		memset (servaddr6, 0, addrlen);
-		servaddr6->sin6_family = AF_INET6;
-		servaddr6->sin6_addr = in6addr_any;
-		servaddr6->sin6_port = htons (port);
-		daemon->address = (struct sockaddr *) servaddr6;
-	}
-	
-  if(AF_INET6 == daemon->address->sa_family)
-  {
-    afamily = PF_INET6;
-  }
-  else
-  {
-    afamily = PF_INET;
-  }
-#else
-	//handling IPv4
-	if(daemon->flags & SPDY_DAEMON_FLAG_ONLY_IPV6)
-	{
-		SPDYF_DEBUG("SPDY_DAEMON_FLAG_ONLY_IPV6 set but no support");
-		goto free_and_fail;
-	}
-	
-  addrlen = sizeof (struct sockaddr_in);
-    
-	if(NULL == daemon->address)
-	{		
-		if (NULL == (servaddr4 = malloc (addrlen)))
-		{
-			SPDYF_DEBUG("malloc");
-			goto free_and_fail;
-		}
-		memset (servaddr4, 0, addrlen);
-		servaddr4->sin_family = AF_INET;
-		servaddr4->sin_addr = INADDR_ANY;
-		servaddr4->sin_port = htons (port);
-		daemon->address = (struct sockaddr *) servaddr4;
-	}
-	
-	afamily = PF_INET;
-#endif	
-
-	daemon->socket_fd = socket (afamily, SOCK_STREAM, 0);
-	if (-1 == daemon->socket_fd)
-	{
-		SPDYF_DEBUG("sock");
-		goto free_and_fail;
-	}
-
-	//setting option for the socket to reuse address
-	ret = setsockopt(daemon->socket_fd, SOL_SOCKET, SO_REUSEADDR, &option_on, sizeof(option_on));
-	if(ret)
-	{
-		SPDYF_DEBUG("WARNING: SO_REUSEADDR was not set for the server");
-	}
-	
-#if HAVE_INET6
-	if(daemon->flags & SPDY_DAEMON_FLAG_ONLY_IPV6)
-	{
-		ret = setsockopt(daemon->socket_fd, IPPROTO_IPV6, IPV6_V6ONLY, &option_on, sizeof(option_on));
-		if(ret)
-		{
-			SPDYF_DEBUG("setsockopt with IPPROTO_IPV6 failed");
-			goto free_and_fail;
-		}
-	}
-#endif
-	
-	if (-1 == bind (daemon->socket_fd, daemon->address, addrlen))
-	{
-		SPDYF_DEBUG("bind %i",errno);
-		goto free_and_fail;
-	}
-
-	if (listen (daemon->socket_fd, 20) < 0)
-	{
-		SPDYF_DEBUG("listen %i",errno);
-		goto free_and_fail;
-	}
-
-	if(SPDY_YES != daemon->fio_init(daemon))
-	{
-		SPDYF_DEBUG("tls");
-		goto free_and_fail;
-	}
-
-	return daemon;
-
-	//for GOTO
-	free_and_fail:
-	if(daemon->socket_fd > 0)
-		(void)close (daemon->socket_fd);
-		
-	free(servaddr4);
-#if HAVE_INET6
-	free(servaddr6);
-#endif
-	if(NULL != daemon->certfile)
-		free(daemon->certfile);
-	if(NULL != daemon->keyfile)
-		free(daemon->keyfile);
-	free (daemon);
-	
-	return NULL;
-}
-
-
-void 
-SPDYF_stop_daemon (struct SPDY_Daemon *daemon)
-{
-	daemon->fio_deinit(daemon);
-	
-	shutdown (daemon->socket_fd, SHUT_RDWR);
-	spdyf_close_all_sessions (daemon);
-	(void)close (daemon->socket_fd);
-	
-	if(!(SPDY_DAEMON_OPTION_SOCK_ADDR & daemon->options))
-		free(daemon->address);
-	
-	free(daemon->certfile);
-	free(daemon->keyfile);
-	
-	free(daemon);
-}
-
-
-int
-SPDYF_get_timeout (struct SPDY_Daemon *daemon, 
-		     unsigned long long *timeout)
-{
-	unsigned long long earliest_deadline = 0;
-	unsigned long long now;
-	struct SPDY_Session *pos;
-	bool have_timeout;
-	
-	if(0 == daemon->session_timeout)
-		return SPDY_NO;
-
-	now = SPDYF_monotonic_time();
-	have_timeout = false;
-	for (pos = daemon->sessions_head; NULL != pos; pos = pos->next)
-	{
-		if ( (! have_timeout) ||
-			(earliest_deadline > pos->last_activity + daemon->session_timeout) )
-			earliest_deadline = pos->last_activity + daemon->session_timeout;
-
-		have_timeout = true;
-		
-		if (SPDY_YES == pos->fio_is_pending(pos))
-		{
-			earliest_deadline = 0;
-			break;
-		}
-	}
-	
-	if (!have_timeout)
-		return SPDY_NO;
-	if (earliest_deadline <= now)
-		*timeout = 0;
-	else
-		*timeout = earliest_deadline - now;
-		
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_get_fdset (struct SPDY_Daemon *daemon,
-				fd_set *read_fd_set,
-				fd_set *write_fd_set, 
-				fd_set *except_fd_set,
-				bool all)
-{
-	(void)except_fd_set;
-	struct SPDY_Session *pos;
-	int fd;
-	int max_fd = -1;
-
-	fd = daemon->socket_fd;
-	if (-1 != fd)
-	{
-		FD_SET (fd, read_fd_set);
-		/* update max file descriptor */
-		max_fd = fd;
-	}
-
-	for (pos = daemon->sessions_head; NULL != pos; pos = pos->next)
-	{
-		fd = pos->socket_fd;
-		FD_SET(fd, read_fd_set);
-		if (all
-		    || (NULL != pos->response_queue_head) //frames pending
-		    || (NULL != pos->write_buffer) //part of last frame pending
-		    || (SPDY_SESSION_STATUS_CLOSING == pos->status) //the session is about to be closed
-		    || (daemon->session_timeout //timeout passed for the session
-			&& (pos->last_activity + daemon->session_timeout < SPDYF_monotonic_time()))
-		    || (SPDY_YES == pos->fio_is_pending(pos)) //data in TLS' read buffer pending
-		    || ((pos->read_buffer_offset - pos->read_buffer_beginning) > 0) // data in lib's read buffer pending
-		    )
-			FD_SET(fd, write_fd_set);
-		if(fd > max_fd)
-			max_fd = fd;
-	}
-
-	return max_fd;
-}
-
-
-void 
-SPDYF_run (struct SPDY_Daemon *daemon)
-{
-	struct SPDY_Session *pos;
-	struct SPDY_Session *next;
-	int num_ready;
-	fd_set rs;
-	fd_set ws;
-	fd_set es;
-	int max;
-	struct timeval timeout;
-	int ds;
-
-	timeout.tv_sec = 0;
-	timeout.tv_usec = 0;
-	FD_ZERO (&rs);
-	FD_ZERO (&ws);
-	FD_ZERO (&es);
-	//here we need really all descriptors to see later which are ready
-	max = SPDYF_get_fdset(daemon,&rs,&ws,&es, true);
-
-	num_ready = select (max + 1, &rs, &ws, &es, &timeout);
-
-	if(num_ready < 1)
-		return;
-
-	if ( (-1 != (ds = daemon->socket_fd)) &&
-		(FD_ISSET (ds, &rs)) ){
-		SPDYF_session_accept(daemon);
-	}
-
-	next = daemon->sessions_head;
-	while (NULL != (pos = next))
-	{
-		next = pos->next;
-		ds = pos->socket_fd;
-		if (ds != -1)
-		{
-			//fill the read buffer
-			if (FD_ISSET (ds, &rs) || pos->fio_is_pending(pos)){
-				SPDYF_session_read(pos);
-			}
-			
-			//do something with the data in read buffer
-			if(SPDY_NO == SPDYF_session_idle(pos))
-			{
-				//the session was closed, cannot write anymore
-				//continue;
-			}
-			
-			//write whatever has been put to the response queue
-			//during read or idle operation, something might be put
-			//on the response queue, thus call write operation
-			if (FD_ISSET (ds, &ws)){
-				if(SPDY_NO == SPDYF_session_write(pos, false))
-				{
-					//SPDYF_session_close(pos);
-					//continue;
-				}
-			}
-			
-			/* the response queue has been flushed for half closed
-			 * connections, so let close them */
-			/*if(pos->read_closed)
-			{
-				SPDYF_session_close(pos);
-			}*/
-		}
-	}
-	
-	spdyf_cleanup_sessions(daemon);
-}
diff --git a/src/microspdy/daemon.h b/src/microspdy/daemon.h
deleted file mode 100644
index cb3ed5f..0000000
--- a/src/microspdy/daemon.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file daemon.h
- * @brief  daemon functionality
- * @author Andrey Uzunov
- */
-
-#ifndef DAEMON_H
-#define DAEMON_H
-
-#include "platform.h"
-
-
-/**
- * Global flags containing the initialized IO subsystems.
- */
-enum SPDY_IO_SUBSYSTEM spdyf_io_initialized;
-
-
-/**
- * Start a SPDDY webserver on the given port.
- *
- * @param port port to bind to
- * @param certfile path to the certificate that will be used by server
- * @param keyfile path to the keyfile for the certificate
- * @param nscb callback called when a new SPDY session is
- * 			established	by a client
- * @param sccb callback called when a client closes the session
- * @param nrcb callback called when a client sends request
- * @param npdcb callback called when HTTP POST params are received
- * 			after request
- * @param fnscb callback called when new stream is opened by a client
- * @param fndcb callback called when new data -- within a data frame --
- *        is received by the server
- * @param cls extra argument to all of the callbacks without those
- * 				 specific only for the framing layer
- * @param fcls extra argument to all of the callbacks, specific only for
- * 				the framing layer (those vars starting with 'f').
- * @param valist va_list of options (type-value pairs,
- *        terminated with SPDY_DAEMON_OPTION_END).
- * @return NULL on error, handle to daemon on success
- */
-struct SPDY_Daemon *
-SPDYF_start_daemon_va (uint16_t port,
-					const char *certfile,
-					const char *keyfile,
-					SPDY_NewSessionCallback nscb,
-					SPDY_SessionClosedCallback sccb,
-					SPDY_NewRequestCallback nrcb,
-					SPDY_NewDataCallback npdcb,
-					SPDYF_NewStreamCallback fnscb,
-					SPDYF_NewDataCallback fndcb,
-					void * cls,
-					void * fcls,
-					va_list valist);
-
-
-/**
- * Run webserver operations (without blocking unless
- * in client callbacks). This method must be called in the client event
- * loop.
- *
- * @param daemon daemon to run
- */
-void 
-SPDYF_run (struct SPDY_Daemon *daemon);
-
-
-/**
- * Obtain timeout value for select for this daemon. The returned value
- * is how long select
- * should at most block, not the timeout value set for connections.
- *
- * @param daemon daemon to query for timeout
- * @param timeout set to the timeout (in milliseconds)
- * @return SPDY_YES on success, SPDY_NO if no connections exist that
- * 			would necessiate the use of a timeout right now
- */
-int
-SPDYF_get_timeout (struct SPDY_Daemon *daemon, 
-		     unsigned long long *timeout);
-
-
-/**
- * Obtain the select sets for this daemon. The idea of SPDYF_get_fdset
- * is to return such descriptors that the select in the application can
- * return and SPDY_run can be called only when this is really needed.
- * That means not all sockets will be added to write_fd_set.
- *
- * @param daemon daemon to get sets from
- * @param read_fd_set read set
- * @param write_fd_set write set
- * @param except_fd_set except set
- * @param all add all session's descriptors to write_fd_set or not
- * @return largest FD added
- */
-int
-SPDYF_get_fdset (struct SPDY_Daemon *daemon,
-				fd_set *read_fd_set,
-				fd_set *write_fd_set, 
-				fd_set *except_fd_set,
-				bool all);
-
-
-/**
- * Shutdown the daemon.
- *
- * @param daemon daemon to stop
- */				
-void 
-SPDYF_stop_daemon (struct SPDY_Daemon *daemon);
-
-#endif
diff --git a/src/microspdy/internal.c b/src/microspdy/internal.c
deleted file mode 100644
index f0d2fc1..0000000
--- a/src/microspdy/internal.c
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file microspdy/internal.c
- * @brief  internal functions and macros for the framing layer
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "structures.h"
-
-
-unsigned long long
-SPDYF_monotonic_time (void)
-{
-#ifdef HAVE_CLOCK_GETTIME
-#ifdef CLOCK_MONOTONIC
-  struct timespec ts;
-  if (0 == clock_gettime (CLOCK_MONOTONIC, &ts))
-    return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
-#endif
-#endif
-  return time (NULL) * 1000;
-}
diff --git a/src/microspdy/internal.h b/src/microspdy/internal.h
deleted file mode 100644
index e618a5a..0000000
--- a/src/microspdy/internal.h
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file microspdy/internal.h
- * @brief  internal functions and macros for the framing layer
- * @author Andrey Uzunov
- */
-
-#ifndef INTERNAL_H_H
-#define INTERNAL_H_H
-
-#include "platform.h"
-#include "microspdy.h"
-
-/**
- * size of read buffers for each connection
- * must be at least the size of SPDY_MAX_SUPPORTED_FRAME_SIZE
- */
-#define SPDYF_BUFFER_SIZE 8192
-
-/**
- * initial size of window for each stream (this is for the data
- * within data frames that can be handled)
- */
-#define SPDYF_INITIAL_WINDOW_SIZE 65536
-
-/**
- * number of frames written to the socket at once. After X frames
- * everything should be run again. In this way the application can
- * response to more important requests while a big file is still
- * being transmitted to the client
- */
-#define SPDYF_NUM_SENT_FRAMES_AT_ONCE 10
-
-
-/**
- * Handler for fatal errors.
- */
-extern SPDY_PanicCallback spdyf_panic;
-
-
-/**
- * Closure argument for "mhd_panic".
- */
-extern void *spdyf_panic_cls;
-
-
-/**
- * Trigger 'panic' action based on fatal errors.
- * 
- * @param msg error message (const char *)
- */
-#define SPDYF_PANIC(msg) \
-	spdyf_panic (spdyf_panic_cls, __FILE__, __LINE__, msg)
-
-
-/**
- * Asserts the validity of an expression.
- *
- * @param expr (bool)
- * @param msg message to print on error (const char *)
- */
-#define SPDYF_ASSERT(expr, msg) \
-	if(!(expr)){\
-		SPDYF_PANIC(msg);\
-		abort();\
-	}
-
-
-/**
- * Convert 24 bit integer from host byte order to network byte order.
- *
- * @param n input value (int32_t)
- * @return converted value (uint32_t)
- */
-#if HAVE_BIG_ENDIAN
-#define HTON24(n) n
-#else
-#define HTON24(n) (((((uint32_t)(n) & 0xFF)) << 16)\
-	| (((uint32_t)(n) & 0xFF00))\
-	| ((((uint32_t)(n) & 0xFF0000)) >> 16))
-#endif
-
-
-/**
- * Convert 24 bit integer from network byte order to host byte order.
- *
- * @param n input value (int32_t)
- * @return converted value (uint32_t)
- */	
-#if HAVE_BIG_ENDIAN
-#define NTOH24(n) n
-#else
-#define NTOH24(n) (((((uint32_t)(n) & 0xFF)) << 16)\
-	| (((uint32_t)(n) & 0xFF00))\
-	| ((((uint32_t)(n) & 0xFF0000)) >> 16))
-#endif
-
-
-/**
- * Convert 31 bit integer from network byte order to host byte order.
- *
- * @param n input value (int32_t)
- * @return converted value (uint32_t)
- */
-#if HAVE_BIG_ENDIAN
-#define NTOH31(n) n
-#else
-#define NTOH31(n) (((((uint32_t)(n) & 0x7F)) << 24) | \
-                  ((((uint32_t)(n) & 0xFF00)) << 8) | \
-                  ((((uint32_t)(n) & 0xFF0000)) >> 8) | \
-                  ((((uint32_t)(n) & 0xFF000000)) >> 24))
-#endif
-
-
-/**
- * Convert 31 bit integer from host byte order to network byte order.
- *
- * @param n input value (int32_t)
- * @return converted value (uint32_t)
- */
-#if HAVE_BIG_ENDIAN
-#define HTON31(n) n
-#else
-#define HTON31(n) (((((uint32_t)(n) & 0xFF)) << 24) | \
-                  ((((uint32_t)(n) & 0xFF00)) << 8) | \
-                  ((((uint32_t)(n) & 0xFF0000)) >> 8) | \
-                  ((((uint32_t)(n) & 0x7F000000)) >> 24))
-#endif
-
-
-/**
- * Print formatted debug value.
- *
- * @param fmt format (const char *)
- * @param ... args for format
- */
-#define SPDYF_DEBUG(fmt, ...) do { \
-	fprintf (stdout, "%s\n%u: ",__FILE__, __LINE__);\
-	fprintf(stdout,fmt,##__VA_ARGS__);\
-	fprintf(stdout,"\n");\
-	fflush(stdout); } while (0)
-
-
-/**
- * Print stream for debuging.
- *
- * @param strm (void *)
- * @param size (int)
- */
-#define SPDYF_PRINT_STREAM(strm, size) do { \
-	int ___i;\
-	for(___i=0;___i<size;___i++){\
-		fprintf(stdout,"%x ",*((uint8_t *) strm + ___i));\
-		fflush(stdout);\
-	}\
-	fprintf(stdout,"\n");\
-	} while (0)
-
-
-/**
- * Print message and raise SIGINT for debug purposes.
- *
- * @param msg message (const char *)
- */
-#define SPDYF_SIGINT(msg) do { \
-	fprintf(stdout,"%i : %s\n", __LINE__,__FILE__);\
-	fprintf(stdout,msg);\
-	fprintf(stdout,"\n");\
-	fflush(stdout);\
-	raise(SIGINT); } while (0)
-
-
-/**
- * Returns monotonic time, to be used for session timeouts.
- *
- * @return time in milliseconds
- */
-unsigned long long
-SPDYF_monotonic_time(void);
-
-#endif
diff --git a/src/microspdy/io.c b/src/microspdy/io.c
deleted file mode 100644
index c333c89..0000000
--- a/src/microspdy/io.c
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file io.c
- * @brief Generic functions for IO.
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "structures.h"
-#include "internal.h"
-#include "io.h"
-
-
-int
-SPDYF_io_set_daemon(struct SPDY_Daemon *daemon,
-                    enum SPDY_IO_SUBSYSTEM io_subsystem)
-{
-  switch(io_subsystem)
-  {
-    case SPDY_IO_SUBSYSTEM_OPENSSL:
-      daemon->fio_init = &SPDYF_openssl_init;
-      daemon->fio_deinit = &SPDYF_openssl_deinit;
-      break;
-      
-    case SPDY_IO_SUBSYSTEM_RAW:
-      daemon->fio_init = &SPDYF_raw_init;
-      daemon->fio_deinit = &SPDYF_raw_deinit;
-      break;
-      
-    case SPDY_IO_SUBSYSTEM_NONE:
-    default:
-      SPDYF_DEBUG("Unsupported subsystem");
-      return SPDY_NO;
-  }
-  
-  return SPDY_YES;
-}
-
-
-int
-SPDYF_io_set_session(struct SPDY_Session *session,
-                     enum SPDY_IO_SUBSYSTEM io_subsystem)
-{
-  switch(io_subsystem)
-  {
-    case SPDY_IO_SUBSYSTEM_OPENSSL:
-      session->fio_new_session = &SPDYF_openssl_new_session;
-      session->fio_close_session = &SPDYF_openssl_close_session;
-      session->fio_is_pending = &SPDYF_openssl_is_pending;
-      session->fio_recv = &SPDYF_openssl_recv;
-      session->fio_send = &SPDYF_openssl_send;
-      session->fio_before_write = &SPDYF_openssl_before_write;
-      session->fio_after_write = &SPDYF_openssl_after_write;
-      break;
-      
-    case SPDY_IO_SUBSYSTEM_RAW:
-      session->fio_new_session = &SPDYF_raw_new_session;
-      session->fio_close_session = &SPDYF_raw_close_session;
-      session->fio_is_pending = &SPDYF_raw_is_pending;
-      session->fio_recv = &SPDYF_raw_recv;
-      session->fio_send = &SPDYF_raw_send;
-      session->fio_before_write = &SPDYF_raw_before_write;
-      session->fio_after_write = &SPDYF_raw_after_write;
-      break;
-      
-    case SPDY_IO_SUBSYSTEM_NONE:
-    default:
-      SPDYF_DEBUG("Unsupported subsystem");
-      return SPDY_NO;
-  }
-  
-  return SPDY_YES;
-}
diff --git a/src/microspdy/io.h b/src/microspdy/io.h
deleted file mode 100644
index c28ba21..0000000
--- a/src/microspdy/io.h
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file io.h
- * @brief  Signatures for IO functions.
- * @author Andrey Uzunov
- */
-
-#ifndef IO_H
-#define IO_H
-
-#include "platform.h"
-#include "io_openssl.h"
-#include "io_raw.h"
-
-
-/**
- * Used for return code when reading and writing to the TLS socket.
- */
-enum SPDY_IO_ERROR
-{
-	/**
-	 * The connection was closed by the other party.
-	 */
-	SPDY_IO_ERROR_CLOSED = 0,
-	
-	/**
-	 * Any kind of error ocurred. The session has to be closed.
-	 */
-	SPDY_IO_ERROR_ERROR = -2,
-	
-	/**
-	 * The function had to return without processing any data. The whole
-	 * cycle of events has to be called again (SPDY_run) as something
-	 * either has to be written or read or the the syscall was
-	 * interrupted by a signal.
-	 */
-	SPDY_IO_ERROR_AGAIN = -3,
-};
-
-
-/**
- * Global initializing. Must be called only once in the program.
- *
- */
-typedef void
-(*SPDYF_IOGlobalInit) ();
-
-
-/**
- * Global deinitializing for the whole program. Should be called
- * at the end of the program.
- *
- */
-typedef void
-(*SPDYF_IOGlobalDeinit) ();
-
-
-/**
- * Initializing of io context for a specific daemon.
- * Must be called when the daemon starts.
- *
- * @param daemon SPDY_Daemon for which io will be used. Daemon's
- * 				certificate and key file are used for tls.
- * @return SPDY_YES on success or SPDY_NO on error
- */
-typedef int
-(*SPDYF_IOInit) (struct SPDY_Daemon *daemon);
-
-
-/**
- * Deinitializing io context for a daemon. Should be called
- * when the deamon is stopped.
- *
- * @param daemon SPDY_Daemon which is being stopped
- */
-typedef void
-(*SPDYF_IODeinit) (struct SPDY_Daemon *daemon);
-
-
-/**
- * Initializing io for a specific connection. Must be called
- * after the connection has been accepted.
- *
- * @param session SPDY_Session whose socket will be used
- * @return SPDY_NO if some funcs inside fail. SPDY_YES otherwise
- */
-typedef int
-(*SPDYF_IONewSession) (struct SPDY_Session *session);
-
-
-/**
- * Deinitializing io for a specific connection. Should be called
- * closing session's socket.
- *
- * @param session SPDY_Session whose socket is used
- */
-typedef void
-(*SPDYF_IOCloseSession) (struct SPDY_Session *session);
-
-
-/**
- * Reading from session's socket. Reads available data and put it to the
- * buffer.
- *
- * @param session for which data is received
- * @param buffer where data from the socket will be written to
- * @param size of the buffer
- * @return number of bytes (at most size) read from the connection
- *         0 if the other party has closed the connection
- *         SPDY_IO_ERROR code on error
- */
-typedef int
-(*SPDYF_IORecv) (struct SPDY_Session *session,
-				void * buffer,
-				size_t size);
-
-
-/**
- * Writing to session's socket. Writes the data given into the buffer to the
- *  socket.
- *
- * @param session whose context is used
- * @param buffer from where data will be written to the socket
- * @param size number of bytes to be taken from the buffer
- * @return number of bytes (at most size) from the buffer that has been
- * 			written to the connection
- *         0 if the other party has closed the connection
- *         SPDY_IO_ERROR code on error
- */
-typedef int
-(*SPDYF_IOSend) (struct SPDY_Session *session,
-				const void * buffer,
-				size_t size);
-
-
-/**
- * Checks if there is data staying in the buffers of the underlying
- * system that waits to be read. In case of TLS, this will call
- * something like SSL_pending().
- *
- * @param session which is checked
- * @return SPDY_YES if data is pending or SPDY_NO otherwise
- */
-typedef int
-(*SPDYF_IOIsPending) (struct SPDY_Session *session);
-
-
-/**
- * Called just before frames are about to be processed and written
- * to the socket.
- *
- * @param session
- * @return SPDY_NO if writing must not happen in the call;
- *         SPDY_YES otherwise
- */
-typedef int
-(*SPDYF_IOBeforeWrite) (struct SPDY_Session *session);
-
-
-/**
- * Called just after frames have been processed and written
- * to the socket.
- *
- * @param session
- * @param was_written has the same value as the write function for the
- *        session will return 
- * @return returned value will be used by the write function to return
- */
-typedef int
-(*SPDYF_IOAfterWrite) (struct SPDY_Session *session,
-                       int was_written);
-
-
-/**
- * Sets callbacks for the daemon with regard to the IO subsystem.
- *
- * @param daemon
- * @param io_subsystem the IO subsystem that will
- *        be initialized and used by daemon.
- * @return SPDY_YES on success or SPDY_NO otherwise
- */
-int
-SPDYF_io_set_daemon(struct SPDY_Daemon *daemon,
-                    enum SPDY_IO_SUBSYSTEM io_subsystem);
-
-
-/**
- * Sets callbacks for the session with regard to the IO subsystem.
- *
- * @param session
- * @param io_subsystem the IO subsystem that will
- *        be initialized and used by session.
- * @return SPDY_YES on success or SPDY_NO otherwise
- */
-int
-SPDYF_io_set_session(struct SPDY_Session *session,
-                     enum SPDY_IO_SUBSYSTEM io_subsystem);
-
-#endif
diff --git a/src/microspdy/io_openssl.c b/src/microspdy/io_openssl.c
deleted file mode 100644
index f71a923..0000000
--- a/src/microspdy/io_openssl.c
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file io_openssl.c
- * @brief  TLS handling using libssl. The current code assumes that
- * 			blocking I/O is in use.
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "internal.h"
-#include "session.h"
-#include "io_openssl.h"
-
-
-/**
- * Callback to advertise spdy ver. 3 in Next Protocol Negotiation
- *
- * @param ssl openssl context for a connection
- * @param out must be set to the raw data that is advertised in NPN
- * @param outlen must be set to size of out
- * @param arg
- * @return SSL_TLSEXT_ERR_OK to do advertising
- */
-static int
-spdyf_next_protos_advertised_cb (SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg)
-{
-	(void)ssl;
-	(void)arg;
-	static unsigned char npn_spdy3[] = {0x06, // length of "spdy/3"
-		0x73,0x70,0x64,0x79,0x2f,0x33};// spdy/3
-
-	*out = npn_spdy3;
-	*outlen = 7; // total length of npn_spdy3
-	return SSL_TLSEXT_ERR_OK;
-}
-
-
-void
-SPDYF_openssl_global_init()
-{
-	//error strings are now not used by the lib
-    //SSL_load_error_strings();
-    //init libssl
-    SSL_library_init(); //always returns 1
-    //the table for looking up algos is not used now by the lib
-    //OpenSSL_add_all_algorithms();
-}
-
-
-void
-SPDYF_openssl_global_deinit()
-{
-	//if SSL_load_error_strings was called
-    //ERR_free_strings();
-    //if OpenSSL_add_all_algorithms was called
-    //EVP_cleanup();
-}
-
-
-int
-SPDYF_openssl_init(struct SPDY_Daemon *daemon)
-{
-    int options;
-    //create ssl context. TLSv1 used
-    if(NULL == (daemon->io_context = SSL_CTX_new(TLSv1_server_method())))
-    {
-		SPDYF_DEBUG("Couldn't create ssl context");
-		return SPDY_NO;
-        }
-	//set options for tls
-	//TODO DH is not enabled for easier debugging
-    //SSL_CTX_set_options(daemon->io_context, SSL_OP_SINGLE_DH_USE);
-
-    //TODO here session tickets are disabled for easier debuging with
-    //wireshark when using Chrome
-    // SSL_OP_NO_COMPRESSION disables TLS compression to avoid CRIME attack
-    options = SSL_OP_NO_TICKET;
-#ifdef SSL_OP_NO_COMPRESSION
-    options |= SSL_OP_NO_COMPRESSION;
-#elif OPENSSL_VERSION_NUMBER >= 0x00908000L /* workaround for OpenSSL 0.9.8 */
-    sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
-#endif
-
-    SSL_CTX_set_options(daemon->io_context, options);
-    if(1 != SSL_CTX_use_certificate_file(daemon->io_context, daemon->certfile , SSL_FILETYPE_PEM))
-    {
-		SPDYF_DEBUG("Couldn't load the cert file");
-		SSL_CTX_free(daemon->io_context);
-		return SPDY_NO;
-	}
-    if(1 != SSL_CTX_use_PrivateKey_file(daemon->io_context, daemon->keyfile, SSL_FILETYPE_PEM))
-    {
-		SPDYF_DEBUG("Couldn't load the name file");
-		SSL_CTX_free(daemon->io_context);
-		return SPDY_NO;
-	}
-    SSL_CTX_set_next_protos_advertised_cb(daemon->io_context, &spdyf_next_protos_advertised_cb, NULL);
-    if (1 != SSL_CTX_set_cipher_list(daemon->io_context, "HIGH"))
-    {
-		SPDYF_DEBUG("Couldn't set the desired cipher list");
-		SSL_CTX_free(daemon->io_context);
-		return SPDY_NO;
-	}
-
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_openssl_deinit(struct SPDY_Daemon *daemon)
-{
-    SSL_CTX_free(daemon->io_context);
-}
-
-
-int
-SPDYF_openssl_new_session(struct SPDY_Session *session)
-{
-	int ret;
-
-	if(NULL == (session->io_context = SSL_new(session->daemon->io_context)))
-    {
-		SPDYF_DEBUG("Couldn't create ssl structure");
-		return SPDY_NO;
-	}
-	if(1 != (ret = SSL_set_fd(session->io_context, session->socket_fd)))
-    {
-		SPDYF_DEBUG("SSL_set_fd %i",ret);
-		SSL_free(session->io_context);
-		session->io_context = NULL;
-		return SPDY_NO;
-	}
-
-	//for non-blocking I/O SSL_accept may return -1
-	//and this function won't work
-	if(1 != (ret = SSL_accept(session->io_context)))
-    {
-		SPDYF_DEBUG("SSL_accept %i",ret);
-		SSL_free(session->io_context);
-		session->io_context = NULL;
-		return SPDY_NO;
-	}
-	/* alternatively
-	SSL_set_accept_state(session->io_context);
-	* may be called and then the negotiation will be done on reading
-	*/
-
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_openssl_close_session(struct SPDY_Session *session)
-{
-	//SSL_shutdown sends TLS "close notify" as in TLS standard.
-	//The function may fail as it waits for the other party to also close
-	//the TLS session. The lib just sends it and will close the socket
-	//after that because the browsers don't seem to care much about
-	//"close notify"
-	SSL_shutdown(session->io_context);
-
-	SSL_free(session->io_context);
-}
-
-
-int
-SPDYF_openssl_recv(struct SPDY_Session *session,
-				void * buffer,
-				size_t size)
-{
-	int ret;
-	int n = SSL_read(session->io_context,
-					buffer,
-					size);
-	//if(n > 0) SPDYF_DEBUG("recvd: %i",n);
-	if (n <= 0)
-	{
-		ret = SSL_get_error(session->io_context, n);
-		switch(ret)
-		{
-			case SSL_ERROR_ZERO_RETURN:
-				return 0;
-
-			case SSL_ERROR_WANT_READ:
-			case SSL_ERROR_WANT_WRITE:
-				return SPDY_IO_ERROR_AGAIN;
-
-			case SSL_ERROR_SYSCALL:
-				if(EINTR == errno)
-					return SPDY_IO_ERROR_AGAIN;
-				return SPDY_IO_ERROR_ERROR;
-			default:
-				return SPDY_IO_ERROR_ERROR;
-		}
-	}
-
-	return n;
-}
-
-
-int
-SPDYF_openssl_send(struct SPDY_Session *session,
-				const void * buffer,
-				size_t size)
-{
-	int ret;
-
-	int n = SSL_write(session->io_context,
-					buffer,
-					size);
-	//if(n > 0) SPDYF_DEBUG("sent: %i",n);
-	if (n <= 0)
-	{
-		ret = SSL_get_error(session->io_context, n);
-		switch(ret)
-		{
-			case SSL_ERROR_ZERO_RETURN:
-				return 0;
-
-			case SSL_ERROR_WANT_READ:
-			case SSL_ERROR_WANT_WRITE:
-				return SPDY_IO_ERROR_AGAIN;
-
-			case SSL_ERROR_SYSCALL:
-				if(EINTR == errno)
-					return SPDY_IO_ERROR_AGAIN;
-				return SPDY_IO_ERROR_ERROR;
-			default:
-				return SPDY_IO_ERROR_ERROR;
-		}
-	}
-
-	return n;
-}
-
-
-int
-SPDYF_openssl_is_pending(struct SPDY_Session *session)
-{
-	/* From openssl docs:
-	 * BUGS
-SSL_pending() takes into account only bytes from the TLS/SSL record that is currently being processed (if any). If the SSL object's read_ahead flag is set, additional protocol bytes may have been read containing more TLS/SSL records; these are ignored by SSL_pending().
-	 */
-	return SSL_pending(session->io_context) > 0 ? SPDY_YES : SPDY_NO;
-}
-
-
-int
-SPDYF_openssl_before_write(struct SPDY_Session *session)
-{
-  (void)session;
-
-  return SPDY_YES;
-}
-
-
-int
-SPDYF_openssl_after_write(struct SPDY_Session *session, int was_written)
-{
-  (void)session;
-
-  return was_written;
-}
diff --git a/src/microspdy/io_openssl.h b/src/microspdy/io_openssl.h
deleted file mode 100644
index a4e9429..0000000
--- a/src/microspdy/io_openssl.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file io_openssl.h
- * @brief  TLS handling. openssl with NPN is used, but as long as the
- * 			functions conform to this interface file, other libraries
- * 			can be used.
- * @author Andrey Uzunov
- */
-
-#ifndef IO_OPENSSL_H
-#define IO_OPENSSL_H
-
-#include "platform.h"
-#include "io.h"
-#include <openssl/err.h>
-#include <openssl/ssl.h>
-#include <openssl/rand.h>
-
-
-/**
- * Global initializing of openssl. Must be called only once in the program.
- *
- */
-void
-SPDYF_openssl_global_init();
-
-
-/**
- * Global deinitializing of openssl for the whole program. Should be called
- * at the end of the program.
- *
- */
-void
-SPDYF_openssl_global_deinit();
-
-
-/**
- * Initializing of openssl for a specific daemon.
- * Must be called when the daemon starts.
- *
- * @param daemon SPDY_Daemon for which openssl will be used. Daemon's
- * 				certificate and key file are used.
- * @return SPDY_YES on success or SPDY_NO on error
- */
-int
-SPDYF_openssl_init(struct SPDY_Daemon *daemon);
-
-
-/**
- * Deinitializing openssl for a daemon. Should be called
- * when the deamon is stopped.
- *
- * @param daemon SPDY_Daemon which is being stopped
- */
-void
-SPDYF_openssl_deinit(struct SPDY_Daemon *daemon);
-
-
-/**
- * Initializing openssl for a specific connection. Must be called
- * after the connection has been accepted.
- *
- * @param session SPDY_Session whose socket will be used by openssl
- * @return SPDY_NO if some openssl funcs fail. SPDY_YES otherwise
- */
-int
-SPDYF_openssl_new_session(struct SPDY_Session *session);
-
-
-/**
- * Deinitializing openssl for a specific connection. Should be called
- * closing session's socket.
- *
- * @param session SPDY_Session whose socket is used by openssl
- */
-void
-SPDYF_openssl_close_session(struct SPDY_Session *session);
-
-
-/**
- * Reading from a TLS socket. Reads available data and put it to the
- * buffer.
- *
- * @param session for which data is received
- * @param buffer where data from the socket will be written to
- * @param size of the buffer
- * @return number of bytes (at most size) read from the TLS connection
- *         0 if the other party has closed the connection
- *         SPDY_IO_ERROR code on error
- */
-int
-SPDYF_openssl_recv(struct SPDY_Session *session,
-				void * buffer,
-				size_t size);
-
-
-/**
- * Writing to a TLS socket. Writes the data given into the buffer to the
- * TLS socket.
- *
- * @param session whose context is used
- * @param buffer from where data will be written to the socket
- * @param size number of bytes to be taken from the buffer
- * @return number of bytes (at most size) from the buffer that has been
- * 			written to the TLS connection
- *         0 if the other party has closed the connection
- *         SPDY_IO_ERROR code on error
- */
-int
-SPDYF_openssl_send(struct SPDY_Session *session,
-				const void * buffer,
-				size_t size);
-
-
-/**
- * Checks if there is data staying in the buffers of the underlying
- * system that waits to be read.
- *
- * @param session which is checked
- * @return SPDY_YES if data is pending or SPDY_NO otherwise
- */
-int
-SPDYF_openssl_is_pending(struct SPDY_Session *session);
-
-
-/**
- * Nothing.
- *
- * @param session
- * @return SPDY_NO if writing must not happen in the call;
- *         SPDY_YES otherwise
- */
-int
-SPDYF_openssl_before_write(struct SPDY_Session *session);
-
-
-/**
- * Nothing.
- *
- * @param session
- * @param was_written has the same value as the write function for the
- *        session will return 
- * @return returned value will be used by the write function to return
- */
-int
-SPDYF_openssl_after_write(struct SPDY_Session *session, int was_written);
-
-
-#endif
diff --git a/src/microspdy/io_raw.c b/src/microspdy/io_raw.c
deleted file mode 100644
index 722f347..0000000
--- a/src/microspdy/io_raw.c
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file io_raw.c
- * @brief  IO for SPDY without TLS.
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "internal.h"
-#include "session.h"
-#include "io_raw.h"
-//TODO put in in the right place
-#include <netinet/tcp.h>
-
-
-void
-SPDYF_raw_global_init()
-{
-}
-
-
-void
-SPDYF_raw_global_deinit()
-{
-}
-
-
-int
-SPDYF_raw_init(struct SPDY_Daemon *daemon)
-{
-  (void)daemon;
-  
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_raw_deinit(struct SPDY_Daemon *daemon)
-{
-  (void)daemon;
-}
-
-
-int
-SPDYF_raw_new_session(struct SPDY_Session *session)
-{	
-  int fd_flags;
-  int val = 1;
-  int ret;
-  
-	//setting the socket to be non-blocking
-	fd_flags = fcntl (session->socket_fd, F_GETFL);
-	if ( -1 == fd_flags
-		|| 0 != fcntl (session->socket_fd, F_SETFL, fd_flags | O_NONBLOCK))
-		SPDYF_DEBUG("WARNING: Couldn't set the new connection to be non-blocking");
-  
-  if(SPDY_DAEMON_FLAG_NO_DELAY & session->daemon->flags)
-  {
-    ret = setsockopt(session->socket_fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
-    if(-1 == ret)
-      SPDYF_DEBUG("WARNING: Couldn't set the new connection to TCP_NODELAY");
-  }
-  
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_raw_close_session(struct SPDY_Session *session)
-{
-  (void)session;
-}
-
-
-int
-SPDYF_raw_recv(struct SPDY_Session *session,
-				void * buffer,
-				size_t size)
-{
-	int n = read(session->socket_fd, 
-					buffer,
-					size);
-	//if(n > 0) SPDYF_DEBUG("recvd: %i",n);
-	if (n < 0)
-	{
-		switch(errno)
-		{				
-			case EAGAIN:
-#if EAGAIN != EWOULDBLOCK
-      case EWOULDBLOCK:
-#endif
-			case EINTR:
-        return SPDY_IO_ERROR_AGAIN;
-				
-			default:
-				return SPDY_IO_ERROR_ERROR;
-		}
-	}
-
-	return n;
-}
-
-
-int
-SPDYF_raw_send(struct SPDY_Session *session,
-				const void * buffer,
-				size_t size)
-{
-	int n = write(session->socket_fd, 
-					buffer,
-					size);
-	//if(n > 0) SPDYF_DEBUG("sent: %i",n);
-	if (n < 0)
-	{
-		switch(errno)
-		{				
-			case EAGAIN:
-#if EAGAIN != EWOULDBLOCK
-      case EWOULDBLOCK:
-#endif
-			case EINTR:
-        return SPDY_IO_ERROR_AGAIN;
-				
-			default:
-				return SPDY_IO_ERROR_ERROR;
-		}
-	}
-	
-	return n;
-}
-
-
-int
-SPDYF_raw_is_pending(struct SPDY_Session *session)
-{
-  (void)session;
-  
-	return SPDY_NO;
-}
-
-
-int
-SPDYF_raw_before_write(struct SPDY_Session *session)
-{
-#if HAVE_DECL_TCP_CORK
-  if(0 == (SPDY_DAEMON_FLAG_NO_DELAY & session->daemon->flags))
-  {
-    int val = 1;
-    int ret;
-    
-    ret = setsockopt(session->socket_fd, IPPROTO_TCP, TCP_CORK, &val, (socklen_t)sizeof(val));
-    if(-1 == ret)
-      SPDYF_DEBUG("WARNING: Couldn't set the new connection to TCP_CORK");
-  }
-#endif
-  
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_raw_after_write(struct SPDY_Session *session, int was_written)
-{
-#if HAVE_DECL_TCP_CORK
-  if(SPDY_YES == was_written && 0 == (SPDY_DAEMON_FLAG_NO_DELAY & session->daemon->flags))
-  {
-    int val = 0;
-    int ret;
-    
-    ret = setsockopt(session->socket_fd, IPPROTO_TCP, TCP_CORK, &val, (socklen_t)sizeof(val));
-    if(-1 == ret)
-      SPDYF_DEBUG("WARNING: Couldn't unset the new connection to TCP_CORK");
-  }
-  
-#endif
-	return was_written;
-}
diff --git a/src/microspdy/io_raw.h b/src/microspdy/io_raw.h
deleted file mode 100644
index 8ca830b..0000000
--- a/src/microspdy/io_raw.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file io_raw.h
- * @brief  IO for SPDY without TLS.
- * @author Andrey Uzunov
- */
-
-#ifndef IO_RAW_H
-#define IO_RAW_H
-
-#include "platform.h"
-
-
-/**
- * Must be called only once in the program.
- *
- */
-void
-SPDYF_raw_global_init();
-
-
-/**
- * Should be called
- * at the end of the program.
- *
- */
-void
-SPDYF_raw_global_deinit();
-
-
-/**
- * Must be called when the daemon starts.
- *
- * @param daemon SPDY_Daemon 
- * @return SPDY_YES on success or SPDY_NO on error
- */
-int
-SPDYF_raw_init(struct SPDY_Daemon *daemon);
-
-
-/**
- * Should be called
- * when the deamon is stopped.
- *
- * @param daemon SPDY_Daemon which is being stopped
- */
-void
-SPDYF_raw_deinit(struct SPDY_Daemon *daemon);
-
-
-/**
- * Must be called
- * after the connection has been accepted.
- *
- * @param session SPDY_Session whose socket will be used
- * @return SPDY_NO if some funcs fail. SPDY_YES otherwise
- */
-int
-SPDYF_raw_new_session(struct SPDY_Session *session);
-
-
-/**
- * Should be called
- * closing session's socket.
- *
- * @param session SPDY_Session whose socket is used
- */
-void
-SPDYF_raw_close_session(struct SPDY_Session *session);
-
-
-/**
- * Reading from socket. Reads available data and put it to the
- * buffer.
- *
- * @param session for which data is received
- * @param buffer where data from the socket will be written to
- * @param size of the buffer
- * @return number of bytes (at most size) read from the connection
- *         0 if the other party has closed the connection
- *         SPDY_IO_ERROR code on error
- */
-int
-SPDYF_raw_recv(struct SPDY_Session *session,
-				void * buffer,
-				size_t size);
-
-
-/**
- * Writing to socket. Writes the data given into the buffer to the
- * socket.
- *
- * @param session whose context is used
- * @param buffer from where data will be written to the socket
- * @param size number of bytes to be taken from the buffer
- * @return number of bytes (at most size) from the buffer that has been
- * 			written to the connection
- *         0 if the other party has closed the connection
- *         SPDY_IO_ERROR code on error
- */
-int
-SPDYF_raw_send(struct SPDY_Session *session,
-				const void * buffer,
-				size_t size);
-
-
-/**
- * Checks if there is data staying in the buffers of the underlying
- * system that waits to be read. Always returns SPDY_NO, as we do not
- * use a subsystem here.
- *
- * @param session which is checked
- * @return SPDY_YES if data is pending or SPDY_NO otherwise
- */
-int
-SPDYF_raw_is_pending(struct SPDY_Session *session);
-
-
-/**
- * Sets TCP_CORK.
- *
- * @param session
- * @return SPDY_NO if writing must not happen in the call;
- *         SPDY_YES otherwise
- */
-int
-SPDYF_raw_before_write(struct SPDY_Session *session);
-
-
-/**
- * Unsets TCP_CORK.
- *
- * @param session
- * @param was_written has the same value as the write function for the
- *        session will return 
- * @return returned value will be used by the write function to return
- */
-int
-SPDYF_raw_after_write(struct SPDY_Session *session, int was_written);
-
-#endif
diff --git a/src/microspdy/session.c b/src/microspdy/session.c
deleted file mode 100644
index 3714c25..0000000
--- a/src/microspdy/session.c
+++ /dev/null
@@ -1,1769 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file session.c
- * @brief  TCP connection/SPDY session handling. So far most of the
- * 			functions for handling SPDY framing layer are here.
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "structures.h"
-#include "internal.h"
-#include "session.h"
-#include "compression.h"
-#include "stream.h"
-#include "io.h"
-
-
-/**
- * Handler for reading the full SYN_STREAM frame after we know that
- * the frame is such.
- * The function waits for the full frame and then changes status
- * of the session. New stream is created.
- *
- * @param session SPDY_Session whose read buffer is used.
- */
-static void
-spdyf_handler_read_syn_stream (struct SPDY_Session *session)
-{
-  size_t name_value_strm_size = 0;
-  unsigned int compressed_data_size;
-  int ret;
-  void *name_value_strm = NULL;
-  struct SPDYF_Control_Frame *frame;
-  struct SPDY_NameValue *headers;
-
-  SPDYF_ASSERT(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status
-               || SPDY_SESSION_STATUS_WAIT_FOR_BODY == session->status,
-               "the function is called wrong");
-
-  frame = (struct SPDYF_Control_Frame *)session->frame_handler_cls;
-
-  //handle subheaders
-  if(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status)
-    {
-      if(0 == frame->length)
-        {
-          //protocol error: incomplete frame
-          //we just ignore it since there is no stream id for which to
-          //send RST_STREAM
-          //TODO maybe GOAWAY and closing session is appropriate
-          SPDYF_DEBUG("zero long SYN_STREAM received");
-          session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-          free(frame);
-          return;
-        }
-
-      if(SPDY_YES != SPDYF_stream_new(session))
-        {
-          /* waiting for some more fields to create new stream
-             or something went wrong, SPDYF_stream_new has handled the
-             situation */
-          return;
-        }
-
-      session->current_stream_id = session->streams_head->stream_id;
-      if(frame->length > SPDY_MAX_SUPPORTED_FRAME_SIZE)
-        {
-          //TODO no need to create stream if this happens
-          session->status = SPDY_SESSION_STATUS_IGNORE_BYTES;
-          return;
-        }
-      else
-        session->status = SPDY_SESSION_STATUS_WAIT_FOR_BODY;
-    }
-
-  //handle body
-
-  //start reading the compressed name/value pairs (http headers)
-  compressed_data_size = frame->length //everything after length field
-    - 10;//4B stream id, 4B assoc strem id, 2B priority, unused and slot
-
-  if(session->read_buffer_offset - session->read_buffer_beginning < compressed_data_size)
-    {
-      // the full frame is not yet here, try later
-      return;
-    }
-
-  if ( (compressed_data_size > 0) &&
-       (SPDY_YES !=
-        SPDYF_zlib_inflate(&session->zlib_recv_stream,
-                           session->read_buffer + session->read_buffer_beginning,
-                           compressed_data_size,
-                           &name_value_strm,
-                           &name_value_strm_size)) )
-    {
-      /* something went wrong on inflating,
-       * the state of the stream for decompression is unknown
-       * and we may not be able to read anything more received on
-       * this session,
-       * so it is better to close the session */
-      free(name_value_strm);
-      free(frame);
-
-      /* mark the session for closing and close it, when
-       * everything on the output queue is already written */
-      session->status = SPDY_SESSION_STATUS_FLUSHING;
-
-      SPDYF_prepare_goaway(session, SPDY_GOAWAY_STATUS_INTERNAL_ERROR, false);
-
-      return;
-    }
-
-  if(0 == name_value_strm_size || 0 == compressed_data_size)
-    {
-      //Protocol error: send RST_STREAM
-      if(SPDY_YES != SPDYF_prepare_rst_stream(session, session->streams_head,
-                                              SPDY_RST_STREAM_STATUS_PROTOCOL_ERROR))
-        {
-          //no memory, try later to send RST
-          free(name_value_strm);
-          return;
-        }
-    }
-  else
-    {
-      ret = SPDYF_name_value_from_stream(name_value_strm, name_value_strm_size, &headers);
-      if(SPDY_NO == ret)
-        {
-          //memory error, try later
-          free(name_value_strm);
-          return;
-        }
-
-      session->streams_head->headers = headers;
-      //inform the application layer for the new stream received
-      if(SPDY_YES != session->daemon->fnew_stream_cb(session->daemon->fcls, session->streams_head))
-        {
-          //memory error, try later
-          free(name_value_strm);
-          return;
-        }
-
-      session->read_buffer_beginning += compressed_data_size;
-    }
-
-  //SPDYF_DEBUG("syn_stream received: id %i", session->current_stream_id);
-
-  //change state to wait for new frame
-  free(name_value_strm);
-  session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-  free(frame);
-}
-
-
-/**
- * Handler for reading the GOAWAY frame after we know that
- * the frame is such.
- * The function waits for the full frame and then changes status
- * of the session.
- *
- * @param session SPDY_Session whose read buffer is used.
- */
-static void
-spdyf_handler_read_goaway (struct SPDY_Session *session)
-{
-	struct SPDYF_Control_Frame *frame;
-	uint32_t last_good_stream_id;
-	uint32_t status_int;
-	enum SPDY_GOAWAY_STATUS status;
-
-	SPDYF_ASSERT(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status,
-		"the function is called wrong");
-
-	frame = (struct SPDYF_Control_Frame *)session->frame_handler_cls;
-
-	if(frame->length > SPDY_MAX_SUPPORTED_FRAME_SIZE)
-	{
-		//this is a protocol error/attack
-		session->status = SPDY_SESSION_STATUS_IGNORE_BYTES;
-		return;
-	}
-
-	if(0 != frame->flags || 8 != frame->length)
-	{
-		//this is a protocol error
-		SPDYF_DEBUG("wrong GOAWAY received");
-		//anyway, it will be handled
-	}
-
-	if((session->read_buffer_offset - session->read_buffer_beginning) < frame->length)
-	{
-		//not all fields are received
-		//try later
-		return;
-	}
-
-	//mark that the session is almost closed
-	session->is_goaway_received = true;
-
-	if(8 == frame->length)
-	{
-		memcpy(&last_good_stream_id, session->read_buffer + session->read_buffer_beginning, 4);
-		last_good_stream_id = NTOH31(last_good_stream_id);
-		session->read_buffer_beginning += 4;
-
-		memcpy(&status_int, session->read_buffer + session->read_buffer_beginning, 4);
-		status = ntohl(status_int);
-		session->read_buffer_beginning += 4;
-
-		//TODO do something with last_good
-
-		//SPDYF_DEBUG("Received GOAWAY; status=%i; lastgood=%i",status,last_good_stream_id);
-
-		//do something according to the status
-		//TODO
-		switch(status)
-		{
-			case SPDY_GOAWAY_STATUS_OK:
-				break;
-			case SPDY_GOAWAY_STATUS_PROTOCOL_ERROR:
-				break;
-			case SPDY_GOAWAY_STATUS_INTERNAL_ERROR:
-				break;
-		}
-
-    //SPDYF_DEBUG("goaway received: status %i", status);
-	}
-
-	session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-	free(frame);
-}
-
-
-/**
- * Handler for reading RST_STREAM frames. After receiving the frame
- * the stream moves into closed state and status
- * of the session is changed. Frames, belonging to this stream, which
- * are still at the output queue, will be ignored later.
- *
- * @param session SPDY_Session whose read buffer is used.
- */
-static void
-spdyf_handler_read_rst_stream (struct SPDY_Session *session)
-{
-	struct SPDYF_Control_Frame *frame;
-	uint32_t stream_id;
-	int32_t status_int;
-	//enum SPDY_RST_STREAM_STATUS status; //for debug
-	struct SPDYF_Stream *stream;
-
-	SPDYF_ASSERT(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status,
-		"the function is called wrong");
-
-	frame = (struct SPDYF_Control_Frame *)session->frame_handler_cls;
-
-	if(0 != frame->flags || 8 != frame->length)
-	{
-		//this is a protocol error
-		SPDYF_DEBUG("wrong RST_STREAM received");
-		//ignore as a large frame
-		session->status = SPDY_SESSION_STATUS_IGNORE_BYTES;
-		return;
-	}
-
-	if((session->read_buffer_offset - session->read_buffer_beginning) < frame->length)
-	{
-		//not all fields are received
-		//try later
-		return;
-	}
-
-    memcpy(&stream_id, session->read_buffer + session->read_buffer_beginning, 4);
-	stream_id = NTOH31(stream_id);
-	session->read_buffer_beginning += 4;
-
-    memcpy(&status_int, session->read_buffer + session->read_buffer_beginning, 4);
-	//status = ntohl(status_int); //for debug
-	session->read_buffer_beginning += 4;
-
-	session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-	free(frame);
-
-	//mark the stream as closed
-	stream = session->streams_head;
-	while(NULL != stream)
-	{
-		if(stream_id == stream->stream_id)
-		{
-			stream->is_in_closed = true;
-			stream->is_out_closed = true;
-			break;
-		}
-		stream = stream->next;
-	}
-
-	//SPDYF_DEBUG("Received RST_STREAM; status=%i; id=%i",status,stream_id);
-
-	//do something according to the status
-	//TODO
-	/*switch(status)
-	{
-		case SPDY_RST_STREAM_STATUS_PROTOCOL_ERROR:
-			break;
-	}*/
-}
-
-
-/**
- * Handler for reading DATA frames. In requests they are used for POST
- * arguments.
- *
- * @param session SPDY_Session whose read buffer is used.
- */
-static void
-spdyf_handler_read_data (struct SPDY_Session *session)
-{
-  int ret;
-  struct SPDYF_Data_Frame * frame;
-  struct SPDYF_Stream * stream;
-
-	SPDYF_ASSERT(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status
-		|| SPDY_SESSION_STATUS_WAIT_FOR_BODY == session->status,
-		"the function is called wrong");
-
-  //SPDYF_DEBUG("DATA frame received (POST?). Ignoring");
-
-  //SPDYF_SIGINT("");
-
-	frame = (struct SPDYF_Data_Frame *)session->frame_handler_cls;
-
-	//handle subheaders
-	if(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status)
-	{
-		if(frame->length > SPDY_MAX_SUPPORTED_FRAME_SIZE)
-		{
-			session->status = SPDY_SESSION_STATUS_IGNORE_BYTES;
-			return;
-		}
-		else
-			session->status = SPDY_SESSION_STATUS_WAIT_FOR_BODY;
-	}
-
-	//handle body
-
-	if(session->read_buffer_offset - session->read_buffer_beginning
-		>= frame->length)
-	{
-    stream = SPDYF_stream_find(frame->stream_id, session);
-
-    if(NULL == stream || stream->is_in_closed || NULL == session->daemon->received_data_cb)
-    {
-      if(NULL == session->daemon->received_data_cb)
-      SPDYF_DEBUG("No callback for DATA frame set; Ignoring DATA frame!");
-
-      //TODO send error?
-
-      //TODO for now ignore frame
-      session->read_buffer_beginning += frame->length;
-      session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-      free(frame);
-      return;
-    }
-
-    ret = session->daemon->freceived_data_cb(session->daemon->cls,
-                                      stream,
-                                      session->read_buffer + session->read_buffer_beginning,
-                                      frame->length,
-                                      0 == (SPDY_DATA_FLAG_FIN & frame->flags));
-
-    session->read_buffer_beginning += frame->length;
-
-    stream->window_size -= frame->length;
-
-    //TODO close in and send rst maybe
-    SPDYF_ASSERT(SPDY_YES == ret, "Cancel POST data is not yet implemented");
-
-    if(SPDY_DATA_FLAG_FIN & frame->flags)
-    {
-      stream->is_in_closed = true;
-    }
-    else if(stream->window_size < SPDYF_INITIAL_WINDOW_SIZE / 2)
-    {
-      //very simple implementation of flow control
-      //when the window's size is under the half of the initial value,
-      //increase it again up to the initial value
-
-      //prepare WINDOW_UPDATE
-      if(SPDY_YES == SPDYF_prepare_window_update(session, stream,
-            SPDYF_INITIAL_WINDOW_SIZE - stream->window_size))
-      {
-        stream->window_size = SPDYF_INITIAL_WINDOW_SIZE;
-      }
-      //else: do it later
-    }
-
-    //SPDYF_DEBUG("data received: id %i", frame->stream_id);
-
-    session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-    free(frame);
-	}
-}
-
-
-int
-SPDYF_handler_write_syn_reply (struct SPDY_Session *session)
-{
-	struct SPDYF_Response_Queue *response_queue = session->response_queue_head;
-	struct SPDYF_Stream *stream = response_queue->stream;
-	struct SPDYF_Control_Frame control_frame;
-	void *compressed_headers = NULL;
-	size_t compressed_headers_size=0;
-	size_t used_data=0;
-	size_t total_size;
-	uint32_t stream_id_nbo;
-
-	SPDYF_ASSERT(NULL == session->write_buffer, "the function is called not in the correct moment");
-
-	memcpy(&control_frame, response_queue->control_frame, sizeof(control_frame));
-
-	if(SPDY_YES != SPDYF_zlib_deflate(&session->zlib_send_stream,
-		response_queue->data,
-		response_queue->data_size,
-		&used_data,
-		&compressed_headers,
-		&compressed_headers_size))
-	{
-		/* something went wrong on compressing,
-		* the state of the stream for compression is unknown
-		* and we may not be able to send anything more on
-		* this session,
-		* so it is better to close the session right now */
-		session->status = SPDY_SESSION_STATUS_CLOSING;
-
-		free(compressed_headers);
-
-		return SPDY_NO;
-	}
-
-	//TODO do we need this used_Data
-	SPDYF_ASSERT(used_data == response_queue->data_size, "not everything was used by zlib");
-
-	total_size = sizeof(struct SPDYF_Control_Frame) //SPDY header
-		+ 4 // stream id as "subheader"
-		+ compressed_headers_size;
-
-	if(NULL == (session->write_buffer = malloc(total_size)))
-	{
-		/* no memory
-		 * since we do not save the compressed data anywhere and
-		 * the sending zlib stream is already in new state, we must
-		 * close the session */
-		session->status = SPDY_SESSION_STATUS_CLOSING;
-
-		free(compressed_headers);
-
-		return SPDY_NO;
-	}
-	session->write_buffer_beginning = 0;
-	session->write_buffer_offset = 0;
-	session->write_buffer_size = total_size;
-
-	control_frame.length = compressed_headers_size + 4; // compressed data + stream_id
-	SPDYF_CONTROL_FRAME_HTON(&control_frame);
-
-	//put frame headers to write buffer
-	memcpy(session->write_buffer + session->write_buffer_offset,&control_frame,sizeof(struct SPDYF_Control_Frame));
-	session->write_buffer_offset +=  sizeof(struct SPDYF_Control_Frame);
-
-	//put stream id to write buffer
-	stream_id_nbo = HTON31(stream->stream_id);
-	memcpy(session->write_buffer + session->write_buffer_offset, &stream_id_nbo, 4);
-	session->write_buffer_offset += 4;
-
-	//put compressed name/value pairs to write buffer
-	memcpy(session->write_buffer + session->write_buffer_offset, compressed_headers, compressed_headers_size);
-	session->write_buffer_offset +=  compressed_headers_size;
-
-	SPDYF_ASSERT(0 == session->write_buffer_beginning, "bug1");
-	SPDYF_ASSERT(session->write_buffer_offset == session->write_buffer_size, "bug2");
-
-	//DEBUG CODE, break compression state to see what happens
-/*	SPDYF_zlib_deflate(&session->zlib_send_stream,
-		"1234567890",
-		10,
-		&used_data,
-		&compressed_headers,
-		&compressed_headers_size);
-*/
-	free(compressed_headers);
-
-	session->last_replied_to_stream_id = stream->stream_id;
-
-  //SPDYF_DEBUG("syn_reply sent: id %i", stream->stream_id);
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_handler_write_goaway (struct SPDY_Session *session)
-{
-	struct SPDYF_Response_Queue *response_queue = session->response_queue_head;
-	struct SPDYF_Control_Frame control_frame;
-	size_t total_size;
-	int last_good_stream_id;
-
-	SPDYF_ASSERT(NULL == session->write_buffer, "the function is called not in the correct moment");
-
-	memcpy(&control_frame, response_queue->control_frame, sizeof(control_frame));
-
-	session->is_goaway_sent = true;
-
-	total_size = sizeof(struct SPDYF_Control_Frame) //SPDY header
-		+ 4 // last good stream id as "subheader"
-		+ 4; // status code as "subheader"
-
-	if(NULL == (session->write_buffer = malloc(total_size)))
-	{
-		return SPDY_NO;
-	}
-	session->write_buffer_beginning = 0;
-	session->write_buffer_offset = 0;
-	session->write_buffer_size = total_size;
-
-	control_frame.length = 8; // always for GOAWAY
-	SPDYF_CONTROL_FRAME_HTON(&control_frame);
-
-	//put frame headers to write buffer
-	memcpy(session->write_buffer + session->write_buffer_offset,&control_frame,sizeof(struct SPDYF_Control_Frame));
-	session->write_buffer_offset +=  sizeof(struct SPDYF_Control_Frame);
-
-	//put last good stream id to write buffer
-	last_good_stream_id = HTON31(session->last_replied_to_stream_id);
-	memcpy(session->write_buffer + session->write_buffer_offset, &last_good_stream_id, 4);
-	session->write_buffer_offset +=  4;
-
-	//put "data" to write buffer. This is the status
-	memcpy(session->write_buffer + session->write_buffer_offset, response_queue->data, 4);
-	session->write_buffer_offset +=  4;
-	//data is not freed by the destroy function so:
-	//free(response_queue->data);
-
-  //SPDYF_DEBUG("goaway sent: status %i", NTOH31(*(uint32_t*)(response_queue->data)));
-
-	SPDYF_ASSERT(0 == session->write_buffer_beginning, "bug1");
-	SPDYF_ASSERT(session->write_buffer_offset == session->write_buffer_size, "bug2");
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_handler_write_data (struct SPDY_Session *session)
-{
-	struct SPDYF_Response_Queue *response_queue = session->response_queue_head;
-	struct SPDYF_Response_Queue *new_response_queue;
-	size_t total_size;
-	struct SPDYF_Data_Frame data_frame;
-	ssize_t ret;
-	bool more;
-
-	SPDYF_ASSERT(NULL == session->write_buffer, "the function is called not in the correct moment");
-
-	memcpy(&data_frame, response_queue->data_frame, sizeof(data_frame));
-
-	if(NULL == response_queue->response->rcb)
-	{
-		//standard response with data into the struct
-		SPDYF_ASSERT(NULL != response_queue->data, "no data for the response");
-
-		total_size = sizeof(struct SPDYF_Data_Frame) //SPDY header
-			+ response_queue->data_size;
-
-		if(NULL == (session->write_buffer = malloc(total_size)))
-		{
-			return SPDY_NO;
-		}
-		session->write_buffer_beginning = 0;
-		session->write_buffer_offset = 0;
-		session->write_buffer_size = total_size;
-
-		data_frame.length = response_queue->data_size;
-		SPDYF_DATA_FRAME_HTON(&data_frame);
-
-		//put SPDY headers to the writing buffer
-		memcpy(session->write_buffer + session->write_buffer_offset,&data_frame,sizeof(struct SPDYF_Data_Frame));
-		session->write_buffer_offset +=  sizeof(struct SPDYF_Data_Frame);
-
-		//put data to the writing buffer
-		memcpy(session->write_buffer + session->write_buffer_offset, response_queue->data, response_queue->data_size);
-		session->write_buffer_offset +=  response_queue->data_size;
-	}
-	else
-	{
-		/* response with callbacks. The lib will produce more than 1
-		 * data frames
-		 */
-
-		total_size = sizeof(struct SPDYF_Data_Frame) //SPDY header
-			+ SPDY_MAX_SUPPORTED_FRAME_SIZE; //max possible size
-
-		if(NULL == (session->write_buffer = malloc(total_size)))
-		{
-			return SPDY_NO;
-		}
-		session->write_buffer_beginning = 0;
-		session->write_buffer_offset = 0;
-		session->write_buffer_size = total_size;
-
-		ret = response_queue->response->rcb(response_queue->response->rcb_cls,
-			session->write_buffer + sizeof(struct SPDYF_Data_Frame),
-			response_queue->response->rcb_block_size,
-			&more);
-
-		if(ret < 0 || ret > response_queue->response->rcb_block_size)
-		{
-			free(session->write_buffer);
-      session->write_buffer = NULL;
-
-      //send RST_STREAM
-      if(SPDY_YES == (ret = SPDYF_prepare_rst_stream(session,
-        response_queue->stream,
-        SPDY_RST_STREAM_STATUS_INTERNAL_ERROR)))
-      {
-        return SPDY_NO;
-      }
-
-      //else no memory
-			//for now close session
-			//TODO what?
-			session->status = SPDY_SESSION_STATUS_CLOSING;
-
-			return SPDY_NO;
-		}
-		if(0 == ret && more)
-		{
-			//the app couldn't write anything to buf but later will
-			free(session->write_buffer);
-			session->write_buffer = NULL;
-			session->write_buffer_size = 0;
-
-			if(NULL != response_queue->next)
-			{
-				//put the frame at the end of the queue
-				//otherwise - head of line blocking
-				session->response_queue_head = response_queue->next;
-				session->response_queue_head->prev = NULL;
-				session->response_queue_tail->next = response_queue;
-				response_queue->prev = session->response_queue_tail;
-				response_queue->next = NULL;
-				session->response_queue_tail = response_queue;
-			}
-
-			return SPDY_YES;
-		}
-
-		if(more)
-		{
-			//create another response queue object to call the user cb again
-			if(NULL == (new_response_queue = SPDYF_response_queue_create(true,
-							NULL,
-							0,
-							response_queue->response,
-							response_queue->stream,
-							false,
-							response_queue->frqcb,
-							response_queue->frqcb_cls,
-							response_queue->rrcb,
-							response_queue->rrcb_cls)))
-			{
-				//TODO send RST_STREAM
-				//for now close session
-				session->status = SPDY_SESSION_STATUS_CLOSING;
-
-				free(session->write_buffer);
-        session->write_buffer = NULL;
-				return SPDY_NO;
-			}
-
-			//put it at second position on the queue
-			new_response_queue->prev = response_queue;
-			new_response_queue->next = response_queue->next;
-			if(NULL == response_queue->next)
-			{
-				session->response_queue_tail = new_response_queue;
-			}
-			else
-			{
-				response_queue->next->prev = new_response_queue;
-			}
-			response_queue->next = new_response_queue;
-
-			response_queue->frqcb = NULL;
-			response_queue->frqcb_cls = NULL;
-			response_queue->rrcb = NULL;
-			response_queue->rrcb_cls = NULL;
-		}
-		else
-		{
-			data_frame.flags |= SPDY_DATA_FLAG_FIN;
-		}
-
-		data_frame.length = ret;
-		SPDYF_DATA_FRAME_HTON(&data_frame);
-
-		//put SPDY headers to the writing buffer
-		memcpy(session->write_buffer + session->write_buffer_offset,
-			&data_frame,
-			sizeof(struct SPDYF_Data_Frame));
-		session->write_buffer_offset +=  sizeof(struct SPDYF_Data_Frame);
-		session->write_buffer_offset +=  ret;
-		session->write_buffer_size = session->write_buffer_offset;
-	}
-
-  //SPDYF_DEBUG("data sent: id %i", NTOH31(data_frame.stream_id));
-
-	SPDYF_ASSERT(0 == session->write_buffer_beginning, "bug1");
-	SPDYF_ASSERT(session->write_buffer_offset == session->write_buffer_size, "bug2");
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_handler_write_rst_stream (struct SPDY_Session *session)
-{
-	struct SPDYF_Response_Queue *response_queue = session->response_queue_head;
-	struct SPDYF_Control_Frame control_frame;
-	size_t total_size;
-
-	SPDYF_ASSERT(NULL == session->write_buffer, "the function is called not in the correct moment");
-
-	memcpy(&control_frame, response_queue->control_frame, sizeof(control_frame));
-
-	total_size = sizeof(struct SPDYF_Control_Frame) //SPDY header
-		+ 4 // stream id as "subheader"
-		+ 4; // status code as "subheader"
-
-	if(NULL == (session->write_buffer = malloc(total_size)))
-	{
-		return SPDY_NO;
-	}
-	session->write_buffer_beginning = 0;
-	session->write_buffer_offset = 0;
-	session->write_buffer_size = total_size;
-
-	control_frame.length = 8; // always for RST_STREAM
-	SPDYF_CONTROL_FRAME_HTON(&control_frame);
-
-	//put frame headers to write buffer
-	memcpy(session->write_buffer + session->write_buffer_offset,&control_frame,sizeof(struct SPDYF_Control_Frame));
-	session->write_buffer_offset +=  sizeof(struct SPDYF_Control_Frame);
-
-	//put stream id to write buffer. This is the status
-	memcpy(session->write_buffer + session->write_buffer_offset, response_queue->data, 8);
-	session->write_buffer_offset +=  8;
-	//data is not freed by the destroy function so:
-	//free(response_queue->data);
-
-  //SPDYF_DEBUG("rst_stream sent: id %i", NTOH31((((uint64_t)response_queue->data) & 0xFFFF0000) >> 32));
-
-	SPDYF_ASSERT(0 == session->write_buffer_beginning, "bug1");
-	SPDYF_ASSERT(session->write_buffer_offset == session->write_buffer_size, "bug2");
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_handler_write_window_update (struct SPDY_Session *session)
-{
-	struct SPDYF_Response_Queue *response_queue = session->response_queue_head;
-	struct SPDYF_Control_Frame control_frame;
-	size_t total_size;
-
-	SPDYF_ASSERT(NULL == session->write_buffer, "the function is called not in the correct moment");
-
-	memcpy(&control_frame, response_queue->control_frame, sizeof(control_frame));
-
-	total_size = sizeof(struct SPDYF_Control_Frame) //SPDY header
-		+ 4 // stream id as "subheader"
-		+ 4; // delta-window-size as "subheader"
-
-	if(NULL == (session->write_buffer = malloc(total_size)))
-	{
-		return SPDY_NO;
-	}
-	session->write_buffer_beginning = 0;
-	session->write_buffer_offset = 0;
-	session->write_buffer_size = total_size;
-
-	control_frame.length = 8; // always for WINDOW_UPDATE
-	SPDYF_CONTROL_FRAME_HTON(&control_frame);
-
-	//put frame headers to write buffer
-	memcpy(session->write_buffer + session->write_buffer_offset,&control_frame,sizeof(struct SPDYF_Control_Frame));
-	session->write_buffer_offset +=  sizeof(struct SPDYF_Control_Frame);
-
-	//put stream id and delta-window-size to write buffer
-	memcpy(session->write_buffer + session->write_buffer_offset, response_queue->data, 8);
-	session->write_buffer_offset +=  8;
-
-  //SPDYF_DEBUG("window_update sent: id %i", NTOH31((((uint64_t)response_queue->data) & 0xFFFF0000) >> 32));
-
-	SPDYF_ASSERT(0 == session->write_buffer_beginning, "bug1");
-	SPDYF_ASSERT(session->write_buffer_offset == session->write_buffer_size, "bug2");
-
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_handler_ignore_frame (struct SPDY_Session *session)
-{
-	struct SPDYF_Control_Frame *frame;
-
-	SPDYF_ASSERT(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status
-		|| SPDY_SESSION_STATUS_WAIT_FOR_BODY == session->status,
-		"the function is called wrong");
-
-
-	frame = (struct SPDYF_Control_Frame *)session->frame_handler_cls;
-
-	//handle subheaders
-	if(SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER == session->status)
-	{
-		if(frame->length > SPDY_MAX_SUPPORTED_FRAME_SIZE)
-		{
-			session->status = SPDY_SESSION_STATUS_IGNORE_BYTES;
-			return;
-		}
-		else
-			session->status = SPDY_SESSION_STATUS_WAIT_FOR_BODY;
-	}
-
-	//handle body
-
-	if(session->read_buffer_offset - session->read_buffer_beginning
-		>= frame->length)
-	{
-		session->read_buffer_beginning += frame->length;
-		session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-		free(frame);
-	}
-}
-
-
-int
-SPDYF_session_read (struct SPDY_Session *session)
-{
-	int bytes_read;
-	bool reallocate;
-	size_t actual_buf_size;
-
-	if(SPDY_SESSION_STATUS_CLOSING == session->status
-		|| SPDY_SESSION_STATUS_FLUSHING == session->status)
-		return SPDY_NO;
-
-	//if the read buffer is full to the end, we need to reallocate space
-	if (session->read_buffer_size == session->read_buffer_offset)
-	{
-		//but only if the state of the session requires it
-		//i.e. no further proceeding is possible without reallocation
-		reallocate = false;
-		actual_buf_size = session->read_buffer_offset
-			- session->read_buffer_beginning;
-		switch(session->status)
-		{
-			case SPDY_SESSION_STATUS_WAIT_FOR_HEADER:
-
-			case SPDY_SESSION_STATUS_IGNORE_BYTES:
-				//we need space for a whole control frame header
-				if(actual_buf_size < sizeof(struct SPDYF_Control_Frame))
-					reallocate = true;
-				break;
-
-			case SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER:
-
-			case SPDY_SESSION_STATUS_WAIT_FOR_BODY:
-				//we need as many bytes as set in length field of the
-				//header
-				SPDYF_ASSERT(NULL != session->frame_handler_cls,
-					"no frame for session");
-				if(session->frame_handler != &spdyf_handler_read_data)
-				{
-					if(actual_buf_size
-						< ((struct SPDYF_Control_Frame *)session->frame_handler_cls)->length)
-						reallocate = true;
-				}
-				else
-				{
-					if(actual_buf_size
-						< ((struct SPDYF_Data_Frame *)session->frame_handler_cls)->length)
-						reallocate = true;
-				}
-				break;
-
-			case SPDY_SESSION_STATUS_CLOSING:
-			case SPDY_SESSION_STATUS_FLUSHING:
-				//nothing needed
-				break;
-		}
-
-		if(reallocate)
-		{
-			//reuse the space in the buffer that was already read by the lib
-			memmove(session->read_buffer,
-				session->read_buffer + session->read_buffer_beginning,
-				session->read_buffer_offset - session->read_buffer_beginning);
-
-			session->read_buffer_offset -= session->read_buffer_beginning;
-			session->read_buffer_beginning = 0;
-		}
-		else
-		{
-			//will read next time
-			//TODO optimize it, memmove more often?
-			return SPDY_NO;
-		}
-	}
-
-	session->last_activity = SPDYF_monotonic_time();
-
-	//actual read from the TLS socket
-	bytes_read = session->fio_recv(session,
-					session->read_buffer + session->read_buffer_offset,
-					session->read_buffer_size - session->read_buffer_offset);
-
-	switch(bytes_read)
-	{
-		case SPDY_IO_ERROR_CLOSED:
-			//The TLS connection was closed by the other party, clean
-			//or not
-			shutdown (session->socket_fd, SHUT_RD);
-			session->read_closed = true;
-			session->status = SPDY_SESSION_STATUS_CLOSING;
-			return SPDY_YES;
-
-		case SPDY_IO_ERROR_ERROR:
-			//any kind of error in the TLS subsystem
-			//try to prepare GOAWAY frame
-			SPDYF_prepare_goaway(session, SPDY_GOAWAY_STATUS_INTERNAL_ERROR, false);
-			//try to flush the queue when write is called
-			session->status = SPDY_SESSION_STATUS_FLUSHING;
-			return SPDY_YES;
-
-		case SPDY_IO_ERROR_AGAIN:
-			//read or write should be called again; leave it for the
-			//next time
-			return SPDY_NO;
-
-		//default:
-			//something was really read from the TLS subsystem
-			//just continue
-	}
-
-	session->read_buffer_offset += bytes_read;
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_session_write (struct SPDY_Session *session,
-                     bool only_one_frame)
-{
-	unsigned int i;
-	int bytes_written;
-	struct SPDYF_Response_Queue *queue_head;
-	struct SPDYF_Response_Queue *response_queue;
-
-	if(SPDY_SESSION_STATUS_CLOSING == session->status)
-		return SPDY_NO;
-
-  if(SPDY_NO == session->fio_before_write(session))
-    return SPDY_NO;
-
-	for(i=0;
-		only_one_frame
-		? i < 1
-		: i < session->max_num_frames;
-		++i)
-	{
-		//if the buffer is not null, part of the last frame is still
-		//pending to be sent
-		if(NULL == session->write_buffer)
-		{
-			//discard frames on closed streams
-			response_queue = session->response_queue_head;
-
-			while(NULL != response_queue)
-			{
-				//if stream is closed, remove not yet sent frames
-				//associated with it
-				//GOAWAY frames are not associated to streams
-				//and still need to be sent
-				if(NULL == response_queue->stream
-					|| !response_queue->stream->is_out_closed)
-					break;
-
-				DLL_remove(session->response_queue_head,session->response_queue_tail,response_queue);
-
-				if(NULL != response_queue->frqcb)
-				{
-					response_queue->frqcb(response_queue->frqcb_cls, response_queue, SPDY_RESPONSE_RESULT_STREAM_CLOSED);
-				}
-
-				SPDYF_response_queue_destroy(response_queue);
-				response_queue = session->response_queue_head;
-			}
-
-			if(NULL == session->response_queue_head)
-				break;//nothing on the queue
-
-			//get next data from queue and put it to the write buffer
-			// to send it
-			if(SPDY_NO == session->response_queue_head->process_response_handler(session))
-			{
-				//error occured and the handler changed or not the
-				//session's status appropriately
-				if(SPDY_SESSION_STATUS_CLOSING == session->status)
-				{
-					//try to send GOAWAY first if the current frame is different
-					if(session->response_queue_head->is_data
-						|| SPDY_CONTROL_FRAME_TYPES_GOAWAY
-							!= session->response_queue_head->control_frame->type)
-					{
-						session->status = SPDY_SESSION_STATUS_FLUSHING;
-						SPDYF_prepare_goaway(session, SPDY_GOAWAY_STATUS_INTERNAL_ERROR, true);
-						SPDYF_session_write(session,true);
-						session->status = SPDY_SESSION_STATUS_CLOSING;
-					}
-					return SPDY_YES;
-				}
-
-				//just return from the loop to return from this function
-        ++i;
-				break;
-			}
-
-			//check if something was prepared for writing
-			//on respones with callbacks it is possible that their is no
-			//data available
-			if(0 == session->write_buffer_size)//nothing to write
-      {
-				if(response_queue != session->response_queue_head)
-				{
-					//the handler modified the queue
-					continue;
-				}
-				else
-				{
-					//no need to try the same frame again
-          ++i;
-					break;
-				}
-      }
-		}
-
-		session->last_activity = SPDYF_monotonic_time();
-
-		//actual write to the IO
-		bytes_written = session->fio_send(session,
-			session->write_buffer + session->write_buffer_beginning,
-			session->write_buffer_offset - session->write_buffer_beginning);
-
-		switch(bytes_written)
-		{
-			case SPDY_IO_ERROR_CLOSED:
-				//The TLS connection was closed by the other party, clean
-				//or not
-				shutdown (session->socket_fd, SHUT_RD);
-				session->read_closed = true;
-				session->status = SPDY_SESSION_STATUS_CLOSING;
-				return SPDY_YES;
-
-			case SPDY_IO_ERROR_ERROR:
-				//any kind of error in the TLS subsystem
-				//forbid more writing
-				session->status = SPDY_SESSION_STATUS_CLOSING;
-				return SPDY_YES;
-
-			case SPDY_IO_ERROR_AGAIN:
-				//read or write should be called again; leave it for the
-				//next time; return from the function as we do not now
-				//whether reading or writing is needed
-				return i>0 ? SPDY_YES : SPDY_NO;
-
-			//default:
-				//something was really read from the TLS subsystem
-				//just continue
-		}
-
-		session->write_buffer_beginning += bytes_written;
-
-		//check if the full buffer was written
-		if(session->write_buffer_beginning == session->write_buffer_size)
-		{
-			//that response is handled, remove it from queue
-      free(session->write_buffer);
-			session->write_buffer = NULL;
-			session->write_buffer_size = 0;
-			queue_head = session->response_queue_head;
-			if(NULL == queue_head->next)
-			{
-				session->response_queue_head = NULL;
-				session->response_queue_tail = NULL;
-			}
-			else
-			{
-				session->response_queue_head = queue_head->next;
-				session->response_queue_head->prev = NULL;
-			}
-
-			//set stream to closed if the frame's fin flag is set
-			SPDYF_stream_set_flags_on_write(queue_head);
-
-			if(NULL != queue_head->frqcb)
-			{
-				//application layer callback to notify sending of the response
-				queue_head->frqcb(queue_head->frqcb_cls, queue_head, SPDY_RESPONSE_RESULT_SUCCESS);
-			}
-
-			SPDYF_response_queue_destroy(queue_head);
-		}
-	}
-
-	if(SPDY_SESSION_STATUS_FLUSHING == session->status
-		&& NULL == session->response_queue_head)
-		session->status = SPDY_SESSION_STATUS_CLOSING;
-
-	//return i>0 ? SPDY_YES : SPDY_NO;
-	return session->fio_after_write(session, i>0 ? SPDY_YES : SPDY_NO);
-}
-
-
-int
-SPDYF_session_idle (struct SPDY_Session *session)
-{
-	size_t read_buffer_beginning;
-	size_t frame_length;
-	struct SPDYF_Control_Frame* control_frame;
-	struct SPDYF_Data_Frame *data_frame;
-
-	//prepare session for closing if timeout is used and already passed
-	if(SPDY_SESSION_STATUS_CLOSING != session->status
-		&& session->daemon->session_timeout
-		&& (session->last_activity + session->daemon->session_timeout < SPDYF_monotonic_time()))
-	{
-		session->status = SPDY_SESSION_STATUS_CLOSING;
-		//best effort for sending GOAWAY
-		SPDYF_prepare_goaway(session, SPDY_GOAWAY_STATUS_OK, true);
-		SPDYF_session_write(session,true);
-	}
-
-	switch(session->status)
-	{
-		//expect new frame to arrive
-		case SPDY_SESSION_STATUS_WAIT_FOR_HEADER:
-			session->current_stream_id = 0;
-			//check if the whole frame header is already here
-			//both frame types have the same length
-			if(session->read_buffer_offset - session->read_buffer_beginning
-				< sizeof(struct SPDYF_Control_Frame))
-				return SPDY_NO;
-
-			/* check the first bit to see if it is data or control frame
-			 * and also if the version is supported */
-			if(0x80 == *(uint8_t *)(session->read_buffer + session->read_buffer_beginning)
-				&& SPDY_VERSION == *((uint8_t *)session->read_buffer + session->read_buffer_beginning + 1))
-			{
-				//control frame
-				if(NULL == (control_frame = malloc(sizeof(struct SPDYF_Control_Frame))))
-				{
-					SPDYF_DEBUG("No memory");
-					return SPDY_NO;
-				}
-
-				//get frame headers
-				memcpy(control_frame,
-					session->read_buffer + session->read_buffer_beginning,
-					sizeof(struct SPDYF_Control_Frame));
-				session->read_buffer_beginning += sizeof(struct SPDYF_Control_Frame);
-				SPDYF_CONTROL_FRAME_NTOH(control_frame);
-
-				session->status = SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER;
-				//assign different frame handler according to frame type
-				switch(control_frame->type){
-					case SPDY_CONTROL_FRAME_TYPES_SYN_STREAM:
-						session->frame_handler = &spdyf_handler_read_syn_stream;
-						break;
-					case SPDY_CONTROL_FRAME_TYPES_GOAWAY:
-						session->frame_handler = &spdyf_handler_read_goaway;
-						break;
-					case SPDY_CONTROL_FRAME_TYPES_RST_STREAM:
-						session->frame_handler = &spdyf_handler_read_rst_stream;
-						break;
-					default:
-						session->frame_handler = &SPDYF_handler_ignore_frame;
-				}
-				session->frame_handler_cls = control_frame;
-				//DO NOT break the outer case
-			}
-			else if(0 == *(uint8_t *)(session->read_buffer + session->read_buffer_beginning))
-			{
-				//needed for POST
-				//data frame
-				if(NULL == (data_frame = malloc(sizeof(struct SPDYF_Data_Frame))))
-				{
-					SPDYF_DEBUG("No memory");
-					return SPDY_NO;
-				}
-
-				//get frame headers
-				memcpy(data_frame,
-					session->read_buffer + session->read_buffer_beginning,
-					sizeof(struct SPDYF_Data_Frame));
-				session->read_buffer_beginning += sizeof(struct SPDYF_Data_Frame);
-				SPDYF_DATA_FRAME_NTOH(data_frame);
-
-				session->status = SPDY_SESSION_STATUS_WAIT_FOR_BODY;
-				session->frame_handler = &spdyf_handler_read_data;
-				session->frame_handler_cls = data_frame;
-				//DO NOT brake the outer case
-			}
-			else
-			{
-				SPDYF_DEBUG("another protocol or version received!");
-
-				/* According to the draft the lib should send here
-				 * RST_STREAM with status UNSUPPORTED_VERSION. I don't
-				 * see any sense of keeping the session open since
-				 * we don't know how many bytes is the bogus "frame".
-				 * And the latter normally will be HTTP request.
-				 *
-				 */
-
-				//shutdown(session->socket_fd, SHUT_RD);
-				session->status = SPDY_SESSION_STATUS_FLUSHING;
-				SPDYF_prepare_goaway(session, SPDY_GOAWAY_STATUS_PROTOCOL_ERROR,false);
-				//SPDYF_session_write(session,false);
-				/* close connection since the client expects another
-				protocol from us */
-				//SPDYF_session_close(session);
-				return SPDY_YES;
-			}
-
-		//expect specific header fields after the standard header
-		case SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER:
-			if(NULL!=session->frame_handler)
-			{
-				read_buffer_beginning = session->read_buffer_beginning;
-				//if everything is ok, the "body" will also be processed
-				//by the handler
-				session->frame_handler(session);
-
-				if(SPDY_SESSION_STATUS_IGNORE_BYTES == session->status)
-				{
-					//check for larger than max supported frame
-					if(session->frame_handler != &spdyf_handler_read_data)
-					{
-						frame_length = ((struct SPDYF_Control_Frame *)session->frame_handler_cls)->length;
-					}
-					else
-					{
-						frame_length = ((struct SPDYF_Data_Frame *)session->frame_handler_cls)->length;
-					}
-
-					//if(SPDY_MAX_SUPPORTED_FRAME_SIZE < frame_length)
-					{
-						SPDYF_DEBUG("received frame with unsupported size: %zu", frame_length);
-						//the data being received must be ignored and
-						//RST_STREAM sent
-
-						//ignore bytes that will arive later
-						session->read_ignore_bytes = frame_length
-							+ read_buffer_beginning
-							- session->read_buffer_offset;
-						//ignore what is already in read buffer
-						session->read_buffer_beginning = session->read_buffer_offset;
-
-						SPDYF_prepare_rst_stream(session,
-							session->current_stream_id > 0 ? session->streams_head : NULL, //may be 0 here which is not good
-							SPDY_RST_STREAM_STATUS_FRAME_TOO_LARGE);
-
-						//actually the read buffer can be bigger than the
-						//max supported size
-						session->status = session->read_ignore_bytes
-							? SPDY_SESSION_STATUS_IGNORE_BYTES
-							: SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-
-						free(session->frame_handler_cls);
-					}
-				}
-			}
-
-			if(SPDY_SESSION_STATUS_IGNORE_BYTES != session->status)
-			{
-				break;
-			}
-
-		//ignoring data in read buffer
-		case SPDY_SESSION_STATUS_IGNORE_BYTES:
-			SPDYF_ASSERT(session->read_ignore_bytes > 0,
-				"Session is in wrong state");
-			if(session->read_ignore_bytes
-				> session->read_buffer_offset - session->read_buffer_beginning)
-			{
-				session->read_ignore_bytes -=
-					session->read_buffer_offset - session->read_buffer_beginning;
-				session->read_buffer_beginning = session->read_buffer_offset;
-			}
-			else
-			{
-				session->read_buffer_beginning += session->read_ignore_bytes;
-				session->read_ignore_bytes = 0;
-				session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-			}
-			break;
-
-		//expect frame body (name/value pairs)
-		case SPDY_SESSION_STATUS_WAIT_FOR_BODY:
-			if(NULL!=session->frame_handler)
-				session->frame_handler(session);
-			break;
-
-		case SPDY_SESSION_STATUS_FLUSHING:
-
-			return SPDY_NO;
-
-		//because of error the session needs to be closed
-		case SPDY_SESSION_STATUS_CLOSING:
-			//error should be already sent to the client
-			SPDYF_session_close(session);
-			return SPDY_YES;
-	}
-
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_session_close (struct SPDY_Session *session)
-{
-	struct SPDY_Daemon *daemon = session->daemon;
-	int by_client = session->read_closed ? SPDY_YES : SPDY_NO;
-
-	//shutdown the tls and deinit the tls context
-	session->fio_close_session(session);
-	shutdown (session->socket_fd,
-		session->read_closed ? SHUT_WR : SHUT_RDWR);
-	session->read_closed = true;
-
-	//remove session from the list
-	DLL_remove (daemon->sessions_head,
-		daemon->sessions_tail,
-		session);
-	//add the session for the list for cleaning up
-	DLL_insert (daemon->cleanup_head,
-		daemon->cleanup_tail,
-		session);
-
-	//call callback for closed session
-	if(NULL != daemon->session_closed_cb)
-	{
-		daemon->session_closed_cb(daemon->cls, session, by_client);
-	}
-}
-
-
-int
-SPDYF_session_accept(struct SPDY_Daemon *daemon)
-{
-	int new_socket_fd;
-  int ret;
-	struct SPDY_Session *session = NULL;
-	socklen_t addr_len;
-	struct sockaddr *addr;
-
-#if HAVE_INET6
-	struct sockaddr_in6 addr6;
-
-	addr = (struct sockaddr *)&addr6;
-	addr_len = sizeof(addr6);
-#else
-	struct sockaddr_in addr4;
-
-	addr = (struct sockaddr *)&addr4;
-	addr_len = sizeof(addr6);
-#endif
-
-  new_socket_fd = accept (daemon->socket_fd, addr, &addr_len);
-
-  if(new_socket_fd < 1)
-		return SPDY_NO;
-
-	if (NULL == (session = malloc (sizeof (struct SPDY_Session))))
-  {
-		goto free_and_fail;
-	}
-	memset (session, 0, sizeof (struct SPDY_Session));
-
-	session->daemon = daemon;
-	session->socket_fd = new_socket_fd;
-  session->max_num_frames = daemon->max_num_frames;
-
-  ret = SPDYF_io_set_session(session, daemon->io_subsystem);
-  SPDYF_ASSERT(SPDY_YES == ret, "Somehow daemon->io_subsystem iswrong here");
-
-	//init TLS context, handshake will be done
-	if(SPDY_YES != session->fio_new_session(session))
-	{
-		goto free_and_fail;
-	}
-
-	//read buffer
-	session->read_buffer_size = SPDYF_BUFFER_SIZE;
-	if (NULL == (session->read_buffer = malloc (session->read_buffer_size)))
-    {
-		session->fio_close_session(session);
-		goto free_and_fail;
-	}
-
-	//address of the client
-	if (NULL == (session->addr = malloc (addr_len)))
-    {
-		session->fio_close_session(session);
-		goto free_and_fail;
-	}
-	memcpy (session->addr, addr, addr_len);
-
-	session->addr_len = addr_len;
-	session->status = SPDY_SESSION_STATUS_WAIT_FOR_HEADER;
-
-	//init zlib context for the whole session
-	if(SPDY_YES != SPDYF_zlib_deflate_init(&session->zlib_send_stream))
-    {
-		session->fio_close_session(session);
-		goto free_and_fail;
-	}
-	if(SPDY_YES != SPDYF_zlib_inflate_init(&session->zlib_recv_stream))
-    {
-		session->fio_close_session(session);
-		SPDYF_zlib_deflate_end(&session->zlib_send_stream);
-		goto free_and_fail;
-	}
-
-	//add it to daemon's list
-	DLL_insert(daemon->sessions_head,daemon->sessions_tail,session);
-
-	session->last_activity = SPDYF_monotonic_time();
-
-	if(NULL != daemon->new_session_cb)
-		daemon->new_session_cb(daemon->cls, session);
-
-	return SPDY_YES;
-
-	//for GOTO
-	free_and_fail:
-	/* something failed, so shutdown, close and free memory */
-	shutdown (new_socket_fd, SHUT_RDWR);
-	(void)close (new_socket_fd);
-
-	if(NULL != session)
-	{
-		if(NULL != session->addr)
-			free (session->addr);
-		if(NULL != session->read_buffer)
-			free (session->read_buffer);
-		free (session);
-	}
-	return SPDY_NO;
-}
-
-
-void
-SPDYF_queue_response (struct SPDYF_Response_Queue *response_to_queue,
-						struct SPDY_Session *session,
-						int consider_priority)
-{
-	struct SPDYF_Response_Queue *pos;
-	struct SPDYF_Response_Queue *last;
-	uint8_t priority;
-
-	SPDYF_ASSERT(SPDY_YES != consider_priority || NULL != response_to_queue->stream,
-		"called with consider_priority but no stream provided");
-
-	last = response_to_queue;
-	while(NULL != last->next)
-	{
-		last = last->next;
-	}
-
-	if(SPDY_NO == consider_priority)
-	{
-		//put it at the end of the queue
-		response_to_queue->prev = session->response_queue_tail;
-		if (NULL == session->response_queue_head)
-			session->response_queue_head = response_to_queue;
-		else
-			session->response_queue_tail->next = response_to_queue;
-		session->response_queue_tail = last;
-		return;
-	}
-	else if(-1 == consider_priority)
-	{
-		//put it at the head of the queue
-		last->next = session->response_queue_head;
-		if (NULL == session->response_queue_tail)
-			session->response_queue_tail = last;
-		else
-			session->response_queue_head->prev = response_to_queue;
-		session->response_queue_head = response_to_queue;
-		return;
-	}
-
-	if(NULL == session->response_queue_tail)
-	{
-		session->response_queue_head = response_to_queue;
-		session->response_queue_tail = last;
-		return;
-	}
-
-	//search for the right position to put it
-	pos = session->response_queue_tail;
-	priority = response_to_queue->stream->priority;
-	while(NULL != pos
-		&& pos->stream->priority > priority)
-	{
-		pos = pos->prev;
-	}
-
-	if(NULL == pos)
-	{
-		//put it on the head
-		session->response_queue_head->prev = last;
-		last->next = session->response_queue_head;
-		session->response_queue_head = response_to_queue;
-	}
-	else if(NULL == pos->next)
-	{
-		//put it at the end
-		response_to_queue->prev = pos;
-		pos->next = response_to_queue;
-		session->response_queue_tail = last;
-	}
-	else
-	{
-		response_to_queue->prev = pos;
-		last->next = pos->next;
-		pos->next = response_to_queue;
-		last->next->prev = last;
-	}
-}
-
-
-void
-SPDYF_session_destroy(struct SPDY_Session *session)
-{
-	struct SPDYF_Stream *stream;
-	struct SPDYF_Response_Queue *response_queue;
-
-	(void)close (session->socket_fd);
-	SPDYF_zlib_deflate_end(&session->zlib_send_stream);
-	SPDYF_zlib_inflate_end(&session->zlib_recv_stream);
-
-	//clean up unsent data in the output queue
-	while (NULL != (response_queue = session->response_queue_head))
-	{
-		DLL_remove (session->response_queue_head,
-			session->response_queue_tail,
-			response_queue);
-
-		if(NULL != response_queue->frqcb)
-		{
-			response_queue->frqcb(response_queue->frqcb_cls, response_queue, SPDY_RESPONSE_RESULT_SESSION_CLOSED);
-		}
-
-		SPDYF_response_queue_destroy(response_queue);
-	}
-
-	//clean up the streams belonging to this session
-	while (NULL != (stream = session->streams_head))
-	{
-		DLL_remove (session->streams_head,
-			session->streams_tail,
-			stream);
-
-		SPDYF_stream_destroy(stream);
-	}
-
-	free(session->addr);
-	free(session->read_buffer);
-	free(session->write_buffer);
-	free(session);
-}
-
-
-int
-SPDYF_prepare_goaway (struct SPDY_Session *session,
-					enum SPDY_GOAWAY_STATUS status,
-					bool in_front)
-{
-	struct SPDYF_Response_Queue *response_to_queue;
-	struct SPDYF_Control_Frame *control_frame;
-	uint32_t *data;
-
-	if(NULL == (response_to_queue = malloc(sizeof(struct SPDYF_Response_Queue))))
-	{
-		return SPDY_NO;
-	}
-	memset(response_to_queue, 0, sizeof(struct SPDYF_Response_Queue));
-
-	if(NULL == (control_frame = malloc(sizeof(struct SPDYF_Control_Frame))))
-	{
-		free(response_to_queue);
-		return SPDY_NO;
-	}
-	memset(control_frame, 0, sizeof(struct SPDYF_Control_Frame));
-
-	if(NULL == (data = malloc(4)))
-	{
-		free(control_frame);
-		free(response_to_queue);
-		return SPDY_NO;
-	}
-	*(data) = htonl(status);
-
-	control_frame->control_bit = 1;
-	control_frame->version = SPDY_VERSION;
-	control_frame->type = SPDY_CONTROL_FRAME_TYPES_GOAWAY;
-	control_frame->flags = 0;
-
-	response_to_queue->control_frame = control_frame;
-	response_to_queue->process_response_handler = &SPDYF_handler_write_goaway;
-	response_to_queue->data = data;
-	response_to_queue->data_size = 4;
-
-	SPDYF_queue_response (response_to_queue,
-						session,
-						in_front ? -1 : SPDY_NO);
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_prepare_rst_stream (struct SPDY_Session *session,
-					struct SPDYF_Stream * stream,
-					enum SPDY_RST_STREAM_STATUS status)
-{
-	struct SPDYF_Response_Queue *response_to_queue;
-	struct SPDYF_Control_Frame *control_frame;
-	uint32_t *data;
-	uint32_t stream_id;
-
-  if(NULL == stream)
-    stream_id = 0;
-  else
-    stream_id = stream->stream_id;
-
-	if(NULL == (response_to_queue = malloc(sizeof(struct SPDYF_Response_Queue))))
-	{
-		return SPDY_NO;
-	}
-	memset(response_to_queue, 0, sizeof(struct SPDYF_Response_Queue));
-
-	if(NULL == (control_frame = malloc(sizeof(struct SPDYF_Control_Frame))))
-	{
-		free(response_to_queue);
-		return SPDY_NO;
-	}
-	memset(control_frame, 0, sizeof(struct SPDYF_Control_Frame));
-
-	if(NULL == (data = malloc(8)))
-	{
-		free(control_frame);
-		free(response_to_queue);
-		return SPDY_NO;
-	}
-	*(data) = HTON31(stream_id);
-	*(data + 1) = htonl(status);
-
-	control_frame->control_bit = 1;
-	control_frame->version = SPDY_VERSION;
-	control_frame->type = SPDY_CONTROL_FRAME_TYPES_RST_STREAM;
-	control_frame->flags = 0;
-
-	response_to_queue->control_frame = control_frame;
-	response_to_queue->process_response_handler = &SPDYF_handler_write_rst_stream;
-	response_to_queue->data = data;
-	response_to_queue->data_size = 8;
-	response_to_queue->stream = stream;
-
-	SPDYF_queue_response (response_to_queue,
-						session,
-						-1);
-
-	return SPDY_YES;
-}
-
-
-int
-SPDYF_prepare_window_update (struct SPDY_Session *session,
-					struct SPDYF_Stream * stream,
-					int32_t delta_window_size)
-{
-	struct SPDYF_Response_Queue *response_to_queue;
-	struct SPDYF_Control_Frame *control_frame;
-	uint32_t *data;
-
-  SPDYF_ASSERT(NULL != stream, "stream cannot be NULL");
-
-	if(NULL == (response_to_queue = malloc(sizeof(struct SPDYF_Response_Queue))))
-	{
-		return SPDY_NO;
-	}
-	memset(response_to_queue, 0, sizeof(struct SPDYF_Response_Queue));
-
-	if(NULL == (control_frame = malloc(sizeof(struct SPDYF_Control_Frame))))
-	{
-		free(response_to_queue);
-		return SPDY_NO;
-	}
-	memset(control_frame, 0, sizeof(struct SPDYF_Control_Frame));
-
-	if(NULL == (data = malloc(8)))
-	{
-		free(control_frame);
-		free(response_to_queue);
-		return SPDY_NO;
-	}
-	*(data) = HTON31(stream->stream_id);
-	*(data + 1) = HTON31(delta_window_size);
-
-	control_frame->control_bit = 1;
-	control_frame->version = SPDY_VERSION;
-	control_frame->type = SPDY_CONTROL_FRAME_TYPES_WINDOW_UPDATE;
-	control_frame->flags = 0;
-
-	response_to_queue->control_frame = control_frame;
-	response_to_queue->process_response_handler = &SPDYF_handler_write_window_update;
-	response_to_queue->data = data;
-	response_to_queue->data_size = 8;
-	response_to_queue->stream = stream;
-
-	SPDYF_queue_response (response_to_queue,
-						session,
-						-1);
-
-	return SPDY_YES;
-}
diff --git a/src/microspdy/session.h b/src/microspdy/session.h
deleted file mode 100644
index 29ab550..0000000
--- a/src/microspdy/session.h
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file session.h
- * @brief  TCP connection/SPDY session handling
- * @author Andrey Uzunov
- */
-
-#ifndef SESSION_H
-#define SESSION_H
-
-#include "platform.h"
-#include "structures.h"
-
-/**
- * Called by the daemon when the socket for the session has available
- * data to be read. Reads data from the TLS socket and puts it to the
- * session's read buffer. The latte
- *
- * @param session SPDY_Session for which data will be read.
- * @return SPDY_YES if something was read or session's status was
- *         changed. It is possible that error occurred but was handled
- *         and the status was therefore changed.
- *         SPDY_NO if nothing happened, e.g. the subsystem wants read/
- *         write to be called again.
- */
-int
-SPDYF_session_read (struct SPDY_Session *session);
-
-
-/**
- * Called by the daemon when the socket for the session is ready for some
- * data to be written to it. For one or more objects on the response
- * queue tries to fill in the write buffer, based on the frame on the
- * queue, and to write data to the TLS socket. 
- *
- * @param session SPDY_Session for which data will be written.
- * @param only_one_frame when true, the function will write at most one
- *        SPDY frame to the underlying IO subsystem;
- *        when false, the function will write up to
- *        session->max_num_frames SPDY frames
- * @return SPDY_YES if the session's internal writing state has changed:
- *         something was written and/or session's status was
- *         changed and/or response callback was called but did not provide
- *         data. It is possible that error occurred but was handled
- *         and the status was therefore changed.
- *         SPDY_NO if nothing happened. However, it is possible that some
- *         frames were discarded within the call, e.g. frames belonging
- *         to a closed stream.
- */
-int
-SPDYF_session_write (struct SPDY_Session *session,
-                     bool only_one_frame);
-
-
-/**
- * Called by the daemon on SPDY_run to handle the data in the read and write
- * buffer of a session. Based on the state and the content of the read
- * buffer new frames are received and interpreted, appropriate user
- * callbacks are called and maybe something is put on the response queue
- * ready to be handled by session_write.
- * 
- * @param session SPDY_Session which will be handled.
- * @return SPDY_YES if something from the read buffers was processed,
- *         session's status was changed and/or the session was closed.
- *         SPDY_NO if nothing happened, e.g. the session is in a state,
- *         not allowing processing read buffers.
- */
-int
-SPDYF_session_idle (struct SPDY_Session *session);
-
-
-/**
- * This function shutdowns the socket, moves the session structure to
- * daemon's queue for sessions to be cleaned up.
- * 
- * @param session SPDY_Session which will be handled.
- */
-void
-SPDYF_session_close (struct SPDY_Session *session);
-
-
-/**
- * Called to accept new TCP connection and create SPDY session.
- * 
- * @param daemon SPDY_Daemon whose listening socket is used.
- * @return SPDY_NO on any kind of error while accepting new TCP connection
- * 			and initializing new SPDY_Session.
- *         SPDY_YES otherwise.
- */
-int
-SPDYF_session_accept(struct SPDY_Daemon *daemon);
-
-
-/**
- * Puts SPDYF_Response_Queue object on the queue to be sent to the
- * client later.
- *
- * @param response_to_queue linked list of objects containing SPDY
- * 			frame and data to be added to the queue
- * @param session SPDY session for which the response is sent
- * @param consider_priority if SPDY_NO, the list will be added to the
- * 			end of the queue.
- * 			If SPDY_YES, the response will be added after
- * 			the last previously added response with priority of the
- * 			request grater or equal to that of the current one.
- * 			If -1, the object will be put at the head of the queue.
- */
-void
-SPDYF_queue_response (struct SPDYF_Response_Queue *response_to_queue,
-						struct SPDY_Session *session,
-						int consider_priority);
-
-
-/**
- * Cleans up the TSL context for the session, closes the TCP connection,
- * cleans up any data pointed by members of the session structure
- * (buffers, queue of responses, etc.) and frees the memory allocated by
- * the session itself.
- */						
-void
-SPDYF_session_destroy(struct SPDY_Session *session);
-
-
-/**
- * Prepares GOAWAY frame to tell the client to stop creating new streams.
- * The session should be closed soon after this call.
- * 
- * @param session SPDY session
- * @param status code for the GOAWAY frame
- * @param in_front whether or not to put the frame in front of everything
- * 			on the response queue
- * @return SPDY_NO on error (not enough memory) or
- * 			SPDY_YES on success
- */
-int
-SPDYF_prepare_goaway (struct SPDY_Session *session,
-					enum SPDY_GOAWAY_STATUS status,
-					bool in_front);
-
-
-/**
- * Prepares RST_STREAM frame to terminate a stream. This frame may or
- * not indicate an error. The frame will be put at the head of the queue.
- * This means that frames for this stream which are still in the queue
- * will be discarded soon.
- * 
- * @param session SPDY session
- * @param stream stream to terminate
- * @param status code for the RST_STREAM frame
- * @return SPDY_NO on memory error or
- * 			SPDY_YES on success
- */
-int
-SPDYF_prepare_rst_stream (struct SPDY_Session *session,
-					struct SPDYF_Stream * stream,
-					enum SPDY_RST_STREAM_STATUS status);
-
-
-/**
- * Prepares WINDOW_UPDATE frame to tell the other party that more
- * data can be sent on the stream. The frame will be put at the head of
- * the queue.
- * 
- * @param session SPDY session
- * @param stream stream to which the changed window will apply
- * @param delta_window_size how much the window grows
- * @return SPDY_NO on memory error or
- * 			SPDY_YES on success
- */
-int
-SPDYF_prepare_window_update (struct SPDY_Session *session,
-					struct SPDYF_Stream * stream,
-					int32_t delta_window_size);
-          
-
-/**
- * Handler called by session_write to fill the write buffer according to
- * the data frame waiting in the response queue.
- * When response data is given by user callback, the lib does not know
- * how many frames are needed. In such case this call produces
- * another ResponseQueue object and puts it on the queue while the the
- * user callback says that there will be more data.
- * 
- * @return SPDY_NO on error (not enough memory or the user calback for
- *         providing response data did something wrong). If
- *         the error is unrecoverable the handler changes session's
- *         status.
- *         SPDY_YES on success
- */	
-int
-SPDYF_handler_write_data (struct SPDY_Session *session);
-
-
-/**
- * Handler called by session_write to fill the write buffer based on the
- * control frame (SYN_REPLY) waiting in the response queue.
- * 
- * @param session SPDY session
- * @return SPDY_NO on error (zlib state is broken; the session MUST be
- *         closed). If
- *         the error is unrecoverable the handler changes session's
- *         status.
- * 			SPDY_YES on success
- */ 			
-int
-SPDYF_handler_write_syn_reply (struct SPDY_Session *session);
-
-
-/**
- * Handler called by session_write to fill the write buffer based on the
- * control frame (GOAWAY) waiting in the response queue.
- * 
- * @param session SPDY session
- * @return SPDY_NO on error (not enough memory; by specification the
- *         session must be closed
- *         soon, thus there is no need to handle the error) or
- * 			SPDY_YES on success
- */					
-int
-SPDYF_handler_write_goaway (struct SPDY_Session *session);
-
-
-/**
- * Handler called by session_write to fill the write buffer based on the
- * control frame (RST_STREAM) waiting in the response queue.
- * 
- * @param session SPDY session
- * @return SPDY_NO on error (not enough memory). If
- *         the error is unrecoverable the handler changes session's
- *         status.
- * 			SPDY_YES on success
- */				
-int
-SPDYF_handler_write_rst_stream (struct SPDY_Session *session);
-
-
-/**
- * Handler called by session_write to fill the write buffer based on the
- * control frame (WINDOW_UPDATE) waiting in the response queue.
- * 
- * @param session SPDY session
- * @return SPDY_NO on error (not enough memory). If
- *         the error is unrecoverable the handler changes session's
- *         status.
- * 			SPDY_YES on success
- */			
-int
-SPDYF_handler_write_window_update (struct SPDY_Session *session);
-
-
-/**
- * Carefully ignore the full size of frames which are not yet supported
- * by the lib.
- * TODO Ignoring frames containing compressed bodies means that the
- * compress state will be corrupted on next received frame. According to
- * the draft the lib SHOULD try to decompress data also in corrupted
- * frames just to keep right compression state.
- * 
- * @param session SPDY_Session whose read buffer is used.
- */
-void
-SPDYF_handler_ignore_frame (struct SPDY_Session *session);
-
-#endif
diff --git a/src/microspdy/stream.c b/src/microspdy/stream.c
deleted file mode 100644
index 9b6dc08..0000000
--- a/src/microspdy/stream.c
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file stream.c
- * @brief  SPDY streams handling
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "structures.h"
-#include "internal.h"
-#include "session.h"
-
-
-int
-SPDYF_stream_new (struct SPDY_Session *session)
-{
-	uint32_t stream_id;
-	uint32_t assoc_stream_id;
-	uint8_t priority;
-	uint8_t slot;
-	size_t buffer_pos = session->read_buffer_beginning;
-	struct SPDYF_Stream *stream;
-	struct SPDYF_Control_Frame *frame;
-	
-	if((session->read_buffer_offset - session->read_buffer_beginning) < 10)
-	{
-		//not all fields are received to create new stream
-		return SPDY_NO;
-	}
-	
-	frame = (struct SPDYF_Control_Frame *)session->frame_handler_cls;
-	
-	//get stream id of the new stream
-    memcpy(&stream_id, session->read_buffer + session->read_buffer_beginning, 4);
-	stream_id = NTOH31(stream_id);
-	session->read_buffer_beginning += 4;
-	if(stream_id <= session->last_in_stream_id || 0==(stream_id % 2))
-	{
-		//wrong stream id sent by client
-		//GOAWAY with PROTOCOL_ERROR MUST be sent
-		//TODO
-		
-		//ignore frame
-		session->frame_handler = &SPDYF_handler_ignore_frame;
-		return SPDY_NO;
-	}
-	else if(session->is_goaway_sent)
-	{
-		//the client is not allowed to create new streams anymore
-		//we MUST ignore the frame
-		session->frame_handler = &SPDYF_handler_ignore_frame;
-		return SPDY_NO;
-	}
-	
-	//set highest stream id for session
-	session->last_in_stream_id = stream_id;
-	
-	//get assoc stream id of the new stream
-	//this value is used with SPDY PUSH, thus nothing to do with it here
-    memcpy(&assoc_stream_id, session->read_buffer + session->read_buffer_beginning, 4);
-	assoc_stream_id = NTOH31(assoc_stream_id);
-	session->read_buffer_beginning += 4;
-
-	//get stream priority (3 bits)
-	//after it there are 5 bits that are not used
-	priority = *(uint8_t *)(session->read_buffer + session->read_buffer_beginning) >> 5;
-	session->read_buffer_beginning++;
-	
-	//get slot (see SPDY draft)
-	slot = *(uint8_t *)(session->read_buffer + session->read_buffer_beginning);
-	session->read_buffer_beginning++;
-	
-	if(NULL == (stream = malloc(sizeof(struct SPDYF_Stream))))
-	{
-		SPDYF_DEBUG("No memory");
-		//revert buffer state
-		session->read_buffer_beginning = buffer_pos;
-		return SPDY_NO;
-	}
-	memset(stream,0, sizeof(struct SPDYF_Stream));
-	stream->session = session;
-	stream->stream_id = stream_id;
-	stream->assoc_stream_id = assoc_stream_id;
-	stream->priority = priority;
-	stream->slot = slot;
-	stream->is_in_closed = (frame->flags & SPDY_SYN_STREAM_FLAG_FIN) != 0;
-	stream->flag_unidirectional = (frame->flags & SPDY_SYN_STREAM_FLAG_UNIDIRECTIONAL) != 0;
-	stream->is_out_closed = stream->flag_unidirectional;
-	stream->is_server_initiator = false;
-	stream->window_size = SPDYF_INITIAL_WINDOW_SIZE;
-	
-	//put the stream to the list of streams for the session
-	DLL_insert(session->streams_head, session->streams_tail, stream);
-	
-	return SPDY_YES;
-}
-
-
-void
-SPDYF_stream_destroy(struct SPDYF_Stream *stream)
-{
-	SPDY_name_value_destroy(stream->headers);
-	free(stream);
-	stream = NULL;
-}
-
-
-void
-SPDYF_stream_set_flags_on_write(struct SPDYF_Response_Queue *response_queue)
-{
-	struct SPDYF_Stream * stream = response_queue->stream;
-	
-	if(NULL != response_queue->data_frame)
-	{
-		stream->is_out_closed = (bool)(response_queue->data_frame->flags & SPDY_DATA_FLAG_FIN);
-	}
-	else if(NULL != response_queue->control_frame)
-	{
-		switch(response_queue->control_frame->type)
-		{
-			case SPDY_CONTROL_FRAME_TYPES_SYN_REPLY:
-				stream->is_out_closed = (bool)(response_queue->control_frame->flags & SPDY_SYN_REPLY_FLAG_FIN);
-				break;
-				
-			case SPDY_CONTROL_FRAME_TYPES_RST_STREAM:
-				if(NULL != stream)
-				{
-					stream->is_out_closed = true;
-					stream->is_in_closed = true;
-				}
-				break;
-				
-		}
-	}
-}
-
-
-//TODO add function *on_read
-
-
-struct SPDYF_Stream * 
-SPDYF_stream_find(uint32_t stream_id, struct SPDY_Session * session)
-{
-  struct SPDYF_Stream * stream = session->streams_head;
-  
-  while(NULL != stream && stream_id != stream->stream_id)
-  {
-    stream = stream->next;
-  }
-  
-  return stream;
-}
diff --git a/src/microspdy/stream.h b/src/microspdy/stream.h
deleted file mode 100644
index 220231f..0000000
--- a/src/microspdy/stream.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file stream.h
- * @brief  SPDY streams handling
- * @author Andrey Uzunov
- */
-
-#ifndef STREAM_H
-#define STREAM_H
-
-#include "platform.h"
-
-
-/**
- * Reads data from session's read buffer and tries to create a new SPDY
- * stream. This function is called after control frame's header has been
- * read from the buffer (after the length field). If bogus frame is
- * received the function changes the read handler of the session and
- * fails, i.e. there is no need of further error handling by the caller.
- *
- * @param session SPDY_Session whose read buffer is being read
- * @return SPDY_YES if a new SPDY stream request was correctly received
- * 			and handled. SPDY_NO if the whole SPDY frame was not yet
- * 			received or memory error occurred.
- */
-int
-SPDYF_stream_new (struct SPDY_Session *session);
-
-
-/**
- * Destroys stream structure and whatever is in it.
- *
- * @param stream SPDY_Stream to destroy
- */
-void
-SPDYF_stream_destroy(struct SPDYF_Stream *stream);
-
-
-/**
- * Set stream flags if needed based on the type of the frame that was
- * just sent (e.g., close stream if it was RST_STREAM).
- *
- * @param response_queue sent for this stream
- */
-void
-SPDYF_stream_set_flags_on_write(struct SPDYF_Response_Queue *response_queue);
-
-
-/**
- * Find and return a session's stream, based on stream's ID.
- *
- * @param stream_id to search for
- * @param session whose streams are considered
- * @return SPDY_Stream with the desired ID. Can be NULL.
- */
-struct SPDYF_Stream * 
-SPDYF_stream_find(uint32_t stream_id, struct SPDY_Session * session);
-
-#endif
diff --git a/src/microspdy/structures.c b/src/microspdy/structures.c
deleted file mode 100644
index f00806b..0000000
--- a/src/microspdy/structures.c
+++ /dev/null
@@ -1,638 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file structures.c
- * @brief  Functions for handling most of the structures in defined
- * 			in structures.h
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "structures.h"
-#include "internal.h"
-#include "session.h"
-//TODO not for here?
-#include <ctype.h>
-
-
-int
-SPDYF_name_value_is_empty(struct SPDY_NameValue *container)
-{
-  SPDYF_ASSERT(NULL != container, "NULL is not an empty container!");
-  return (NULL == container->name && NULL == container->value) ? SPDY_YES : SPDY_NO;
-}
-
-struct SPDY_NameValue *
-SPDY_name_value_create ()
-{
-	struct SPDY_NameValue *pair;
-
-	if(NULL == (pair = malloc(sizeof(struct SPDY_NameValue))))
-		return NULL;
-
-	memset (pair, 0, sizeof (struct SPDY_NameValue));
-
-	return pair;
-}
-
-
-int
-SPDY_name_value_add (struct SPDY_NameValue *container,
-					const char *name,
-					const char *value)
-{
-	unsigned int i;
-	unsigned int len;
-	struct SPDY_NameValue *pair;
-	struct SPDY_NameValue *temp;
-	char **temp_value;
-	char *temp_string;
-
-	if(NULL == container || NULL == name || NULL == value || 0 == (len = strlen(name)))
-		return SPDY_INPUT_ERROR;
-  //TODO there is old code handling value==NULL
-  //update it to handle strlen(value)==0
-
-	for(i=0; i<len; ++i)
-	{
-	  if(isupper((int) name[i]))
-			return SPDY_INPUT_ERROR;
-	}
-
-	if(SPDYF_name_value_is_empty(container))
-	{
-		//container is empty/just created
-		if (NULL == (container->name = strdup (name)))
-		{
-			return SPDY_NO;
-		}
-		if (NULL == (container->value = malloc(sizeof(char *))))
-		{
-			free(container->name);
-			return SPDY_NO;
-		}
-    /*if(NULL == value)
-      container->value[0] = NULL;
-		else */if (NULL == (container->value[0] = strdup (value)))
-		{
-			free(container->value);
-			free(container->name);
-			return SPDY_NO;
-		}
-		container->num_values = 1;
-		return SPDY_YES;
-	}
-
-	pair = container;
-	while(NULL != pair)
-	{
-		if(0 == strcmp(pair->name, name))
-		{
-			//the value will be added to this pair
-			break;
-		}
-		pair = pair->next;
-	}
-
-	if(NULL == pair)
-	{
-		//the name doesn't exist in container, add new pair
-		if(NULL == (pair = malloc(sizeof(struct SPDY_NameValue))))
-			return SPDY_NO;
-
-		memset(pair, 0, sizeof(struct SPDY_NameValue));
-
-		if (NULL == (pair->name = strdup (name)))
-		{
-			free(pair);
-			return SPDY_NO;
-		}
-		if (NULL == (pair->value = malloc(sizeof(char *))))
-		{
-			free(pair->name);
-			free(pair);
-			return SPDY_NO;
-		}
-    /*if(NULL == value)
-      pair->value[0] = NULL;
-		else */if (NULL == (pair->value[0] = strdup (value)))
-		{
-			free(pair->value);
-			free(pair->name);
-			free(pair);
-			return SPDY_NO;
-		}
-		pair->num_values = 1;
-
-		temp = container;
-		while(NULL != temp->next)
-			temp = temp->next;
-		temp->next = pair;
-		pair->prev = temp;
-
-		return SPDY_YES;
-	}
-
-	//check for duplication (case sensitive)
-	for(i=0; i<pair->num_values; ++i)
-		if(0 == strcmp(pair->value[i], value))
-			return SPDY_NO;
-
-	if(strlen(pair->value[0]) > 0)
-	{
-		//the value will be appended to the others for this name
-		if (NULL == (temp_value = malloc((pair->num_values + 1) * sizeof(char *))))
-		{
-			return SPDY_NO;
-		}
-		memcpy(temp_value, pair->value, pair->num_values * sizeof(char *));
-		if (NULL == (temp_value[pair->num_values] = strdup (value)))
-		{
-			free(temp_value);
-			return SPDY_NO;
-		}
-		free(pair->value);
-		pair->value = temp_value;
-		++pair->num_values;
-		return SPDY_YES;
-	}
-
-	//just replace the empty value
-
-	if (NULL == (temp_string = strdup (value)))
-	{
-		return SPDY_NO;
-	}
-	free(pair->value[0]);
-	pair->value[0] = temp_string;
-
-	return SPDY_YES;
-}
-
-
-const char * const *
-SPDY_name_value_lookup (struct SPDY_NameValue *container,
-						const char *name,
-						int *num_values)
-{
-	struct SPDY_NameValue *temp = container;
-
-	if(NULL == container || NULL == name || NULL == num_values)
-		return NULL;
-	if(SPDYF_name_value_is_empty(container))
-		return NULL;
-
-	do
-	{
-		if(strcmp(name, temp->name) == 0)
-		{
-			*num_values = temp->num_values;
-			return (const char * const *)temp->value;
-		}
-
-		temp = temp->next;
-	}
-	while(NULL != temp);
-
-	return NULL;
-}
-
-
-void
-SPDY_name_value_destroy (struct SPDY_NameValue *container)
-{
-	unsigned int i;
-	struct SPDY_NameValue *temp = container;
-
-	while(NULL != temp)
-	{
-		container = container->next;
-		free(temp->name);
-		for(i=0; i<temp->num_values; ++i)
-			free(temp->value[i]);
-		free(temp->value);
-		free(temp);
-		temp=container;
-	}
-}
-
-
-int
-SPDY_name_value_iterate (struct SPDY_NameValue *container,
-                           SPDY_NameValueIterator iterator,
-                           void *iterator_cls)
-{
-	int count;
-	int ret;
-	struct SPDY_NameValue *temp = container;
-
-	if(NULL == container)
-		return SPDY_INPUT_ERROR;
-
-	//check if container is an empty struct
-	if(SPDYF_name_value_is_empty(container))
-		return 0;
-
-	count = 0;
-
-	if(NULL == iterator)
-	{
-		do
-		{
-			++count;
-			temp=temp->next;
-		}
-		while(NULL != temp);
-
-		return count;
-	}
-
-	//code duplication for avoiding if here
-	do
-	{
-		++count;
-		ret = iterator(iterator_cls, temp->name, (const char * const *)temp->value, temp->num_values);
-		temp=temp->next;
-	}
-	while(NULL != temp && SPDY_YES == ret);
-
-	return count;
-}
-
-void
-SPDY_destroy_response(struct SPDY_Response *response)
-{
-  if(NULL == response)
-    return;
-	free(response->data);
-	free(response->headers);
-	free(response);
-}
-
-
-struct SPDYF_Response_Queue *
-SPDYF_response_queue_create(bool is_data,
-						void *data,
-						size_t data_size,
-						struct SPDY_Response *response,
-						struct SPDYF_Stream *stream,
-						bool closestream,
-						SPDYF_ResponseQueueResultCallback frqcb,
-						void *frqcb_cls,
-						SPDY_ResponseResultCallback rrcb,
-						void *rrcb_cls)
-{
-	struct SPDYF_Response_Queue *head = NULL;
-	struct SPDYF_Response_Queue *prev;
-	struct SPDYF_Response_Queue *response_to_queue;
-	struct SPDYF_Control_Frame *control_frame;
-	struct SPDYF_Data_Frame *data_frame;
-	unsigned int i;
-	bool is_last;
-
-	SPDYF_ASSERT((! is_data)
-		     || ((0 == data_size) && (NULL != response->rcb))
-		     || ((0 < data_size) && (NULL == response->rcb)),
-		     "either data or request->rcb must not be null");
-
-	if (is_data && (data_size > SPDY_MAX_SUPPORTED_FRAME_SIZE))
-	{
-		//separate the data in more frames and add them to the queue
-
-		prev=NULL;
-		for(i = 0; i < data_size; i += SPDY_MAX_SUPPORTED_FRAME_SIZE)
-		{
-			is_last = (i + SPDY_MAX_SUPPORTED_FRAME_SIZE) >= data_size;
-
-			if(NULL == (response_to_queue = malloc(sizeof(struct SPDYF_Response_Queue))))
-				goto free_and_fail;
-
-			memset(response_to_queue, 0, sizeof(struct SPDYF_Response_Queue));
-			if(0 == i)
-				head = response_to_queue;
-
-			if(NULL == (data_frame = malloc(sizeof(struct SPDYF_Data_Frame))))
-			{
-				free(response_to_queue);
-				goto free_and_fail;
-			}
-			memset(data_frame, 0, sizeof(struct SPDYF_Data_Frame));
-			data_frame->control_bit = 0;
-			data_frame->stream_id = stream->stream_id;
-			if(is_last && closestream)
-				data_frame->flags |= SPDY_DATA_FLAG_FIN;
-
-			response_to_queue->data_frame = data_frame;
-			response_to_queue->process_response_handler = &SPDYF_handler_write_data;
-			response_to_queue->is_data = is_data;
-			response_to_queue->stream = stream;
-			if(is_last)
-			{
-				response_to_queue->frqcb = frqcb;
-				response_to_queue->frqcb_cls = frqcb_cls;
-				response_to_queue->rrcb = rrcb;
-				response_to_queue->rrcb_cls = rrcb_cls;
-			}
-			response_to_queue->data = data + i;
-			response_to_queue->data_size = is_last
-				? (data_size - 1) % SPDY_MAX_SUPPORTED_FRAME_SIZE + 1
-				: SPDY_MAX_SUPPORTED_FRAME_SIZE;
-			response_to_queue->response = response;
-
-			response_to_queue->prev = prev;
-			if(NULL != prev)
-				prev->next = response_to_queue;
-			prev = response_to_queue;
-		}
-
-		return head;
-
-		//for GOTO
-		free_and_fail:
-		while(NULL != head)
-		{
-			response_to_queue = head;
-			head = head->next;
-			free(response_to_queue->data_frame);
-			free(response_to_queue);
-		}
-		return NULL;
-	}
-
-	//create only one frame for data, data with callback or control frame
-
-	if(NULL == (response_to_queue = malloc(sizeof(struct SPDYF_Response_Queue))))
-	{
-		return NULL;
-	}
-	memset(response_to_queue, 0, sizeof(struct SPDYF_Response_Queue));
-
-	if(is_data)
-	{
-		if(NULL == (data_frame = malloc(sizeof(struct SPDYF_Data_Frame))))
-		{
-			free(response_to_queue);
-			return NULL;
-		}
-		memset(data_frame, 0, sizeof(struct SPDYF_Data_Frame));
-		data_frame->control_bit = 0;
-		data_frame->stream_id = stream->stream_id;
-		if(closestream && NULL == response->rcb)
-			data_frame->flags |= SPDY_DATA_FLAG_FIN;
-
-		response_to_queue->data_frame = data_frame;
-		response_to_queue->process_response_handler = &SPDYF_handler_write_data;
-	}
-	else
-	{
-		if(NULL == (control_frame = malloc(sizeof(struct SPDYF_Control_Frame))))
-		{
-			free(response_to_queue);
-			return NULL;
-		}
-		memset(control_frame, 0, sizeof(struct SPDYF_Control_Frame));
-		control_frame->control_bit = 1;
-		control_frame->version = SPDY_VERSION;
-		control_frame->type = SPDY_CONTROL_FRAME_TYPES_SYN_REPLY;
-		if(closestream)
-			control_frame->flags |= SPDY_SYN_REPLY_FLAG_FIN;
-
-		response_to_queue->control_frame = control_frame;
-		response_to_queue->process_response_handler = &SPDYF_handler_write_syn_reply;
-	}
-
-	response_to_queue->is_data = is_data;
-	response_to_queue->stream = stream;
-	response_to_queue->frqcb = frqcb;
-	response_to_queue->frqcb_cls = frqcb_cls;
-	response_to_queue->rrcb = rrcb;
-	response_to_queue->rrcb_cls = rrcb_cls;
-	response_to_queue->data = data;
-	response_to_queue->data_size = data_size;
-	response_to_queue->response = response;
-
-	return response_to_queue;
-}
-
-
-void
-SPDYF_response_queue_destroy(struct SPDYF_Response_Queue *response_queue)
-{
-	//data is not copied to the struct but only linked
-	//but this is not valid for GOAWAY and RST_STREAM
-	if(!response_queue->is_data
-		&& (SPDY_CONTROL_FRAME_TYPES_RST_STREAM == response_queue->control_frame->type
-		|| SPDY_CONTROL_FRAME_TYPES_GOAWAY == response_queue->control_frame->type))
-	{
-		free(response_queue->data);
-	}
-	if(response_queue->is_data)
-		free(response_queue->data_frame);
-	else
-		free(response_queue->control_frame);
-
-	free(response_queue);
-}
-
-
-/* Needed by testcase to be extern -- should this be
-   in the header? */
-_MHD_EXTERN ssize_t
-SPDYF_name_value_to_stream(struct SPDY_NameValue * container[],
-                           int num_containers,
-                           void **stream)
-{
-	size_t size;
-	int32_t num_pairs = 0;
-	int32_t value_size;
-	int32_t name_size;
-	int32_t temp;
-	unsigned int i;
-	unsigned int offset;
-	unsigned int value_offset;
-	struct SPDY_NameValue * iterator;
-	int j;
-
-	size = 4; //for num pairs
-
-	for(j=0; j<num_containers; ++j)
-	{
-    iterator = container[j];
-    while(iterator != NULL)
-    {
-      ++num_pairs;
-      size += 4 + strlen(iterator->name); //length + string
-
-      SPDYF_ASSERT(iterator->num_values>0, "num_values is 0");
-
-      size += 4; //value length
-
-      for(i=0; i<iterator->num_values; ++i)
-      {
-        //if(NULL == iterator->value[i])
-        //  continue;
-        size += strlen(iterator->value[i]); // string
-        if(i/* || !strlen(iterator->value[i])*/) ++size; //NULL separator
-      }
-
-      iterator = iterator->next;
-    }
-  }
-
-	if(NULL == (*stream = malloc(size)))
-	{
-		return -1;
-	}
-
-	//put num_pairs to the stream
-	num_pairs = htonl(num_pairs);
-	memcpy(*stream, &num_pairs, 4);
-	offset = 4;
-
-	//put all other headers to the stream
-	for(j=0; j<num_containers; ++j)
-	{
-    iterator = container[j];
-    while(iterator != NULL)
-    {
-      name_size = strlen(iterator->name);
-      temp = htonl(name_size);
-      memcpy(*stream + offset, &temp, 4);
-      offset += 4;
-      strncpy(*stream + offset, iterator->name, name_size);
-      offset += name_size;
-
-      value_offset = offset;
-      offset += 4;
-      for(i=0; i<iterator->num_values; ++i)
-      {
-        if(i /*|| !strlen(iterator->value[0])*/)
-        {
-          memset(*stream + offset, 0, 1);
-          ++offset;
-          //if(!i) continue;
-        }
-        //else if(NULL != iterator->value[i])
-        //{
-          strncpy(*stream + offset, iterator->value[i], strlen(iterator->value[i]));
-          offset += strlen(iterator->value[i]);
-        //}
-      }
-      value_size = offset - value_offset - 4;
-      value_size = htonl(value_size);
-      memcpy(*stream + value_offset, &value_size, 4);
-
-      iterator = iterator->next;
-    }
-  }
-
-	SPDYF_ASSERT(offset == size,"offset is wrong");
-
-	return size;
-}
-
-
-/* Needed by testcase to be extern -- should this be
-   in the header? */
-_MHD_EXTERN int
-SPDYF_name_value_from_stream(void *stream,
-							size_t size,
-							struct SPDY_NameValue ** container)
-{
-	int32_t num_pairs;
-	int32_t value_size;
-	int32_t name_size;
-	int i;
-	unsigned int offset = 0;
-	unsigned int value_end_offset;
-	char *name;
-	char *value;
-
-	if(NULL == (*container = SPDY_name_value_create ()))
-	{
-		return SPDY_NO;
-	}
-
-	//get number of pairs
-	memcpy(&num_pairs, stream, 4);
-	offset = 4;
-	num_pairs = ntohl(num_pairs);
-
-	if(num_pairs > 0)
-	{
-		for(i = 0; i < num_pairs; ++i)
-		{
-			//get name size
-			memcpy(&name_size, stream + offset, 4);
-			offset += 4;
-			name_size = ntohl(name_size);
-			//get name
-			if(NULL == (name = strndup(stream + offset, name_size)))
-			{
-				SPDY_name_value_destroy(*container);
-				return SPDY_NO;
-			}
-			offset+=name_size;
-
-			//get value size
-			memcpy(&value_size, stream + offset, 4);
-			offset += 4;
-			value_size = ntohl(value_size);
-			value_end_offset = offset + value_size;
-			//get value
-			do
-			{
-				if(NULL == (value = strndup(stream + offset, value_size)))
-				{
-					free(name);
-					SPDY_name_value_destroy(*container);
-					return SPDY_NO;
-				}
-				offset += strlen(value);
-				if(offset < value_end_offset)
-					++offset; //NULL separator
-
-				//add name/value to the struct
-				if(SPDY_YES != SPDY_name_value_add(*container, name, value))
-				{
-					free(name);
-					free(value);
-					SPDY_name_value_destroy(*container);
-					return SPDY_NO;
-				}
-				free(value);
-			}
-			while(offset < value_end_offset);
-
-			free(name);
-
-			if(offset != value_end_offset)
-			{
-				SPDY_name_value_destroy(*container);
-				return SPDY_INPUT_ERROR;
-			}
-		}
-	}
-
-	if(offset == size)
-		return SPDY_YES;
-
-	SPDY_name_value_destroy(*container);
-	return SPDY_INPUT_ERROR;
-}
diff --git a/src/microspdy/structures.h b/src/microspdy/structures.h
deleted file mode 100644
index e1f8797..0000000
--- a/src/microspdy/structures.h
+++ /dev/null
@@ -1,1246 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file structures.h
- * @brief  internal and public structures -- most of the structs used by
- * 			the library are defined here
- * @author Andrey Uzunov
- */
-
-#ifndef STRUCTURES_H
-#define STRUCTURES_H
-
-#include "platform.h"
-#include "microspdy.h"
-#include "io.h"
-
-
-/**
- * All possible SPDY control frame types. The number is used in the header
- * of the control frame.
- */
-enum SPDY_CONTROL_FRAME_TYPES
-{
-	/**
-	 * The SYN_STREAM control frame allows the sender to asynchronously
-	 * create a stream between the endpoints.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_SYN_STREAM = 1,
-	
-	/**
-	 * SYN_REPLY indicates the acceptance of a stream creation by
-	 * the recipient of a SYN_STREAM frame.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_SYN_REPLY = 2,
-	
-	/**
-	 * The RST_STREAM frame allows for abnormal termination of a stream.
-	 * When sent by the creator of a stream, it indicates the creator
-	 * wishes to cancel the stream. When sent by the recipient of a
-	 * stream, it indicates an error or that the recipient did not want
-	 * to accept the stream, so the stream should be closed.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_RST_STREAM = 3,
-	
-	/**
-	 * A SETTINGS frame contains a set of id/value pairs for
-	 * communicating configuration data about how the two endpoints may
-	 * communicate. SETTINGS frames can be sent at any time by either
-	 * endpoint, are optionally sent, and are fully asynchronous. When
-	 * the server is the sender, the sender can request that
-	 * configuration data be persisted by the client across SPDY
-	 * sessions and returned to the server in future communications.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_SETTINGS = 4,
-	
-	/**
-	 * The PING control frame is a mechanism for measuring a minimal
-	 * round-trip time from the sender. It can be sent from the client
-	 * or the server. Recipients of a PING frame should send an
-	 * identical frame to the sender as soon as possible (if there is
-	 * other pending data waiting to be sent, PING should take highest
-	 * priority). Each ping sent by a sender should use a unique ID.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_PING = 6,
-	
-	/**
-	 * The GOAWAY control frame is a mechanism to tell the remote side
-	 * of the connection to stop creating streams on this session. It
-	 * can be sent from the client or the server.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_GOAWAY = 7,
-	
-	/**
-	 * The HEADERS frame augments a stream with additional headers. It
-	 * may be optionally sent on an existing stream at any time.
-	 * Specific application of the headers in this frame is
-	 * application-dependent. The name/value header block within this
-	 * frame is compressed.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_HEADERS = 8,
-	
-	/**
-	 * The WINDOW_UPDATE control frame is used to implement per stream
-	 * flow control in SPDY. Flow control in SPDY is per hop, that is,
-	 * only between the two endpoints of a SPDY connection. If there are
-	 * one or more intermediaries between the client and the origin
-	 * server, flow control signals are not explicitly forwarded by the
-	 * intermediaries.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_WINDOW_UPDATE = 9,
-	
-	/**
-	 * The CREDENTIAL control frame is used by the client to send
-	 * additional client certificates to the server. A SPDY client may
-	 * decide to send requests for resources from different origins on
-	 * the same SPDY session if it decides that that server handles both
-	 * origins. For example if the IP address associated with both
-	 * hostnames matches and the SSL server certificate presented in the
-	 * initial handshake is valid for both hostnames. However, because
-	 * the SSL connection can contain at most one client certificate,
-	 * the client needs a mechanism to send additional client
-	 * certificates to the server.
-	 */
-	SPDY_CONTROL_FRAME_TYPES_CREDENTIAL = 11
-};
-
-
-/**
- * SPDY_SESSION_STATUS is used to show the current receiving state 
- * of each session, i.e. what is expected to come now, and how it should
- * be handled.
- */
-enum SPDY_SESSION_STATUS
-{
-	/**
-	 * The session is in closing state, do not read read anything from
-	 * it. Do not write anything to it.
-	 */
-	SPDY_SESSION_STATUS_CLOSING = 0,
-	
-	/**
-	 * Wait for new SPDY frame to come.
-	 */
-	SPDY_SESSION_STATUS_WAIT_FOR_HEADER = 1,
-	
-	/**
-	 * The standard 8 byte header of the SPDY frame was received and
-	 * handled. Wait for the specific (sub)headers according to the
-	 * frame type.
-	 */
-	SPDY_SESSION_STATUS_WAIT_FOR_SUBHEADER = 2,
-	
-	/**
-	 * The specific (sub)headers were received and handled. Wait for the
-	 * "body", i.e. wait for the name/value pairs compressed by zlib.
-	 */
-	SPDY_SESSION_STATUS_WAIT_FOR_BODY = 3,
-	
-	/**
-	 * Ignore all the bytes read from the socket, e.g. larger frames.
-	 */
-	SPDY_SESSION_STATUS_IGNORE_BYTES= 4,
-	
-	/**
-	 * The session is in pre-closing state, do not read read anything
-	 * from it. In this state the output queue will be written to the
-	 * socket.
-	 */
-	SPDY_SESSION_STATUS_FLUSHING = 5,
-};
-
-
-/**
- * Specific flags for the SYN_STREAM control frame.
- */
-enum SPDY_SYN_STREAM_FLAG
-{
-	/**
-	 * The sender won't send any more frames on this stream.
-	 */
-	SPDY_SYN_STREAM_FLAG_FIN = 1,
-	
-	/**
-	 * The sender creates this stream as unidirectional.
-	 */
-	SPDY_SYN_STREAM_FLAG_UNIDIRECTIONAL = 2
-};
-
-
-/**
- * Specific flags for the SYN_REPLY control frame.
- */
-enum SPDY_SYN_REPLY_FLAG
-{
-	/**
-	 * The sender won't send any more frames on this stream.
-	 */
-	SPDY_SYN_REPLY_FLAG_FIN = 1
-};
-
-
-/**
- * Specific flags for the data frame.
- */
-enum SPDY_DATA_FLAG
-{
-	/**
-	 * The sender won't send any more frames on this stream.
-	 */
-	SPDY_DATA_FLAG_FIN = 1,
-	
-	/**
-	 * The data in the frame is compressed. 
-	 * This flag appears only in the draft on ietf.org but not on
-	 * chromium.org.
-	 */
-	SPDY_DATA_FLAG_COMPRESS = 2
-};
-
-/**
- * Status code within RST_STREAM control frame.
- */
-enum SPDY_RST_STREAM_STATUS
-{
-	/**
-	 * This is a generic error, and should only be used if a more
-	 * specific error is not available.
-	 */
-	SPDY_RST_STREAM_STATUS_PROTOCOL_ERROR = 1,
-	
-	/**
-	 * This is returned when a frame is received for a stream which is
-	 * not active.
-	 */
-	SPDY_RST_STREAM_STATUS_INVALID_STREAM = 2,
-	
-	/**
-	 * Indicates that the stream was refused before any processing has
-	 * been done on the stream.
-	 */
-	SPDY_RST_STREAM_STATUS_REFUSED_STREAM = 3,
-	
-	/**
-	 * Indicates that the recipient of a stream does not support the
-	 * SPDY version requested.
-	 */
-	SPDY_RST_STREAM_STATUS_UNSUPPORTED_VERSION = 4,
-	
-	/**
-	 * Used by the creator of a stream to indicate that the stream is
-	 * no longer needed.
-	 */
-	SPDY_RST_STREAM_STATUS_CANCEL = 5,
-	
-	/**
-	 * This is a generic error which can be used when the implementation
-	 * has internally failed, not due to anything in the protocol.
-	 */
-	SPDY_RST_STREAM_STATUS_INTERNAL_ERROR = 6,
-	
-	/**
-	 * The endpoint detected that its peer violated the flow control
-	 * protocol.
-	 */
-	SPDY_RST_STREAM_STATUS_FLOW_CONTROL_ERROR = 7,
-	
-	/**
-	 * The endpoint received a SYN_REPLY for a stream already open.
-	 */
-	SPDY_RST_STREAM_STATUS_STREAM_IN_USE = 8,
-	
-	/**
-	 * The endpoint received a data or SYN_REPLY frame for a stream
-	 * which is half closed.
-	 */
-	SPDY_RST_STREAM_STATUS_STREAM_ALREADY_CLOSED = 9,
-	
-	/**
-	 * The server received a request for a resource whose origin does
-	 * not have valid credentials in the client certificate vector.
-	 */
-	SPDY_RST_STREAM_STATUS_INVALID_CREDENTIALS = 10,
-	
-	/**
-	 * The endpoint received a frame which this implementation could not
-	 * support. If FRAME_TOO_LARGE is sent for a SYN_STREAM, HEADERS,
-	 * or SYN_REPLY frame without fully processing the compressed
-	 * portion of those frames, then the compression state will be
-	 * out-of-sync with the other endpoint. In this case, senders of
-	 * FRAME_TOO_LARGE MUST close the session.
-	 */
-	SPDY_RST_STREAM_STATUS_FRAME_TOO_LARGE = 11
-};
-
-
-/**
- * Status code within GOAWAY control frame.
- */
-enum SPDY_GOAWAY_STATUS
-{
-	/**
-	 * This is a normal session teardown.
-	 */
-	SPDY_GOAWAY_STATUS_OK = 0,
-	
-	/**
-	 * This is a generic error, and should only be used if a more
-	 * specific error is not available.
-	 */
-	SPDY_GOAWAY_STATUS_PROTOCOL_ERROR = 1,
-	
-	/**
-	 * This is a generic error which can be used when the implementation
-	 * has internally failed, not due to anything in the protocol.
-	 */
-	SPDY_GOAWAY_STATUS_INTERNAL_ERROR = 11
-};
-
-
-struct SPDYF_Stream;
-
-struct SPDYF_Response_Queue;
-
-
-/**
- * Callback for received new data chunk.
- *
- * @param cls client-defined closure
- * @param stream handler
- * @param buf data chunk from the data
- * @param size the size of the data chunk 'buf' in bytes
- * @param more false if this is the last frame received on this stream. Note:
- *             true does not mean that more data will come, exceptional
- *             situation is possible
- * @return SPDY_YES to continue calling the function,
- *         SPDY_NO to stop calling the function for this stream
- */
-typedef int
-(*SPDYF_NewDataCallback) (void * cls,
-					 struct SPDYF_Stream *stream,
-					 const void * buf,
-					 size_t size,
-					 bool more);
-           
-           
-/**
- * Callback for new stream. To be used in the application layer of the
- * lib.
- *
- * @param cls
- * @param stream the new stream
- * @return SPDY_YES on success,
- *         SPDY_NO if error occurs
- */
-typedef int
-(*SPDYF_NewStreamCallback) (void *cls,
-						struct SPDYF_Stream * stream);
-
-
-/**
- * Callback to be called when the response queue object was handled and 
- * the data was already sent. 
- *
- * @param cls
- * @param response_queue the SPDYF_Response_Queue structure which will
- * 			be cleaned very soon
- * @param status shows if actually the response was sent or it was
- * 			discarded by the lib for any reason (e.g., closing session,
- * 			closing stream, stopping daemon, etc.). It is possible that
- * 			status indicates an error but part of the response (in one
- * 			or several frames) was sent to the client.
- */
-typedef void
-(*SPDYF_ResponseQueueResultCallback) (void * cls,
-								struct SPDYF_Response_Queue *response_queue,
-								enum SPDY_RESPONSE_RESULT status);
-
-
-/**
- * Representation of the control frame's headers, which are common for
- * all types.
- */
-struct __attribute__((__packed__)) SPDYF_Control_Frame
-{
-	uint16_t version : 15;
-	uint16_t control_bit : 1; /* always 1 for control frames */
-	uint16_t type;
-	uint32_t flags : 8;
-	uint32_t length : 24;
-};
-
-
-/**
- * Representation of the data frame's headers.
- */
-struct __attribute__((__packed__)) SPDYF_Data_Frame
-{
-	uint32_t stream_id : 31;
-	uint32_t control_bit : 1; /* always 0 for data frames */
-	uint32_t flags : 8;
-	uint32_t length : 24;
-};
-
-
-/**
- * Queue of the responses, to be handled (e.g. compressed) and sent later.
- */
-struct SPDYF_Response_Queue
-{
-	/**
-	 * This is a doubly-linked list.
-	 */
-	struct SPDYF_Response_Queue *next;
-
-	/**
-	 * This is a doubly-linked list.
-	 */
-	struct SPDYF_Response_Queue *prev;
-
-	/**
-	 * Stream (Request) for which is the response.
-	 */
-	struct SPDYF_Stream *stream;
-
-	/**
-	 * Response structure with all the data (uncompressed headers) to be sent.
-	 */
-	struct SPDY_Response *response;
-
-	/**
-	 * Control frame. The length field should be set after compressing
-	 * the headers!
-	 */
-	struct SPDYF_Control_Frame *control_frame;
-
-	/**
-	 * Data frame. The length field should be set after compressing
-	 * the body!
-	 */
-	struct SPDYF_Data_Frame *data_frame;
-
-	/**
-	 * Data to be sent: name/value pairs in control frames or body in data frames.
-	 */
-	void *data;
-
-	/**
-	 * Specific handler for different frame types.
-	 */
-	int (* process_response_handler)(struct SPDY_Session *session);
-
-	/**
-	 * Callback to be called when the last bytes from the response was sent
-	 * to the client.
-	 */
-	SPDYF_ResponseQueueResultCallback frqcb;
-	
-	/**
-	 * Closure for frqcb.
-	 */
-	void *frqcb_cls;
-
-	/**
-	 * Callback to be used by the application layer.
-	 */
-	SPDY_ResponseResultCallback rrcb;
-	
-	/**
-	 * Closure for rcb.
-	 */
-	void *rrcb_cls;
-
-	/**
-	 * Data size.
-	 */
-	size_t data_size;
-
-	/**
-	 * True if data frame should be sent. False if control frame should
-	 * be sent.
-	 */
-	bool is_data;
-};
-
-
-
-/**
- * Collection of HTTP headers used in requests and responses.
- */
-struct SPDY_NameValue
-{
-	/**
-	* This is a doubly-linked list.
-	*/
-	struct SPDY_NameValue *next;
-
-	/**
-	* This is a doubly-linked list.
-	*/
-	struct SPDY_NameValue *prev;
-
-	/**
-	* Null terminated string for name.
-	*/
-    char *name;
-
-	/**
-	* Array of Null terminated strings for value. num_values is the
-	* length of the array.
-	*/
-	char **value;
-
-	/**
-	* Number of values, this is >= 0.
-	*/
-	unsigned int num_values;
-};
-
-
-/**
- * Represents a SPDY stream
- */ 
-struct SPDYF_Stream
-{
-	/**
-	 * This is a doubly-linked list.
-	 */
-	struct SPDYF_Stream *next;
-
-	/**
-	 * This is a doubly-linked list.
-	 */
-	struct SPDYF_Stream *prev;
-
-	/**
-	 * Reference to the SPDY_Session struct.
-	 */
-	struct SPDY_Session *session;
-	
-	/**
-	 * Name value pairs, sent within the frame which created the stream.
-	 */
-	struct SPDY_NameValue *headers;
-	
-	/**
-	 * Any object to be used by the application layer.
-	 */
-	void *cls;
-  
-	/**
-	 * This stream's ID.
-	 */
-	uint32_t stream_id;
-	
-	/**
-	 * Stream to which this one is associated.
-	 */
-	uint32_t assoc_stream_id;
-	
-	/**
-	 * The window of the data within data frames.
-	 */
-	uint32_t window_size;
-	
-	/**
-	 * Stream priority. 0 is the highest, 7 is the lowest.
-	 */
-	uint8_t priority;
-	
-	/**
-	 * Integer specifying the index in the server's CREDENTIAL vector of
-	 * the client certificate to be used for this request The value 0
-	 * means no client certificate should be associated with this stream.
-	 */
-	uint8_t slot;
-	
-	/**
-	 * If initially the stream was created as unidirectional.
-	 */
-	bool flag_unidirectional;
-	
-	/**
-	 * If the stream won't be used for receiving frames anymore. The 
-	 * client has sent FLAG_FIN or the stream was terminated with
-	 * RST_STREAM.
-	 */
-	bool is_in_closed;
-	
-	/**
-	 * If the stream won't be used for sending out frames anymore. The 
-	 * server has sent FLAG_FIN or the stream was terminated with
-	 * RST_STREAM.
-	 */
-	bool is_out_closed;
-	
-	/**
-	 * Which entity (server/client) has created the stream.
-	 */
-	bool is_server_initiator;
-};
-
-
-/**
- * Represents a SPDY session which is just a TCP connection
- */ 
-struct SPDY_Session
-{
-	/**
-	 * zlib stream for decompressing all the name/pair values from the
-	 * received frames. All the received compressed data must be
-	 * decompressed within one context: this stream. Thus, it should be
-	 * unique for the session and initialized at its creation.
-	 */
-	z_stream zlib_recv_stream;
-
-	/**
-	 * zlib stream for compressing all the name/pair values from the
-	 * frames to be sent. All the sent compressed data must be
-	 * compressed within one context: this stream. Thus, it should be
-	 * unique for the session and initialized at its creation.
-	 */
-	z_stream zlib_send_stream;
-	
-	/**
-	 * This is a doubly-linked list.
-	 */
-	struct SPDY_Session *next;
-
-	/**
-	 * This is a doubly-linked list.
-	 */
-	struct SPDY_Session *prev;
-
-	/**
-	 * Reference to the SPDY_Daemon struct.
-	 */
-	struct SPDY_Daemon *daemon;
-
-	/**
-	 * Foreign address (of length addr_len).
-	 */
-	struct sockaddr *addr;
-
-	/**
-	 * Head of doubly-linked list of the SPDY streams belonging to the
-	 * session.
-	 */
-	struct SPDYF_Stream *streams_head;
-
-	/**
-	 * Tail of doubly-linked list of the streams.
-	 */
-	struct SPDYF_Stream *streams_tail;
-
-	/**
-	 * Unique IO context for the session. Initialized on each creation
-	 * (actually when the TCP connection is established).
-	 */
-	void *io_context;
-	
-	/**
-	 * Head of doubly-linked list of the responses.
-	 */
-	struct SPDYF_Response_Queue *response_queue_head;
-	
-	/**
-	 * Tail of doubly-linked list of the responses.
-	 */
-	struct SPDYF_Response_Queue *response_queue_tail;
-
-	/**
-	 * Buffer for reading requests.
-	 */
-	void *read_buffer;
-
-	/**
-	 * Buffer for writing responses.
-	 */
-	void *write_buffer;
-
-	/**
-	 * Specific handler for the frame that is currently being received.
-	 */
-	void (*frame_handler) (struct SPDY_Session * session);
-
-	/**
-	 * Closure for frame_handler.
-	 */
-	void *frame_handler_cls;
-
-	/**
-	 * Extra field to be used by the user with set/get func for whatever
-	 * purpose he wants.
-	 */
-	void *user_cls;
-
-	/**
-	 * Function to initialize the IO context for a new session.
-	 */
-	SPDYF_IONewSession fio_new_session;
-
-	/**
-	 * Function to deinitialize the IO context for a session.
-	 */
-	SPDYF_IOCloseSession fio_close_session;
-
-	/**
-	 * Function to read data from socket.
-	 */
-	SPDYF_IORecv fio_recv;
-
-	/**
-	 * Function to write data to socket.
-	 */
-	SPDYF_IOSend fio_send;
-
-	/**
-	 * Function to check for pending data in IO buffers.
-	 */
-	SPDYF_IOIsPending fio_is_pending;
-
-	/**
-	 * Function to call before writing set of frames.
-	 */
-	SPDYF_IOBeforeWrite fio_before_write;
-
-	/**
-	 * Function to call after writing set of frames.
-	 */
-	SPDYF_IOAfterWrite fio_after_write;
-
-	/**
-	 * Number of bytes that the lib must ignore immediately after they 
-	 * are read from the TLS socket without adding them to the read buf.
-	 * This is needed, for instance, when receiving frame bigger than
-	 * the buffer to avoid deadlock situations.
-	 */
-	size_t read_ignore_bytes;
-
-	/**
-	 * Size of read_buffer (in bytes).  This value indicates
-	 * how many bytes we're willing to read into the buffer;
-	 * the real buffer is one byte longer to allow for
-	 * adding zero-termination (when needed).
-	 */
-	size_t read_buffer_size;
-
-	/**
-	 * Position where we currently append data in
-	 * read_buffer (last valid position).
-	 */
-	size_t read_buffer_offset;
-
-	/**
-	 * Position until where everything was already read
-	 */
-	size_t read_buffer_beginning;
-
-	/**
-	 * Size of write_buffer (in bytes).  This value indicates
-	 * how many bytes we're willing to prepare for writing.
-	 */
-	size_t write_buffer_size;
-
-	/**
-	 * Position where we currently append data in
-	 * write_buffer (last valid position).
-	 */
-	size_t write_buffer_offset;
-
-	/**
-	 * Position until where everything was already written to the socket
-	 */
-	size_t write_buffer_beginning;
-	
-	/**
-	 * Last time this connection had any activity
-	 * (reading or writing). In milliseconds.
-	 */
-	unsigned long long last_activity;
-
-	/**
-	 * Socket for this connection.  Set to -1 if
-	 * this connection has died (daemon should clean
-	 * up in that case).
-	 */
-	int socket_fd;
-
-	/**
-	 * Length of the foreign address.
-	 */
-	socklen_t addr_len;
-	
-	/**
-	 * The biggest stream ID for this session for streams initiated
-	 * by the client.
-	 */
-	uint32_t last_in_stream_id;
-	
-	/**
-	 * The biggest stream ID for this session for streams initiated
-	 * by the server.
-	 */
-	uint32_t last_out_stream_id;
-	
-	/**
-	 * This value is updated whenever SYN_REPLY or RST_STREAM are sent
-	 * and is used later in GOAWAY frame.
-	 * TODO it is not clear in the draft what happens when streams are
-	 * not answered in the order of their IDs. Moreover, why should we
-	 * send GOAWAY with the ID of received bogus SYN_STREAM with huge ID?
-	 */
-	uint32_t last_replied_to_stream_id;
-	
-	/**
-	 * Shows the stream id of the currently handled frame. This value is
-	 * to be used when sending RST_STREAM in answer to a problematic
-	 * frame, e.g. larger than supported.
-	 */
-	uint32_t current_stream_id;
-	
-	/**
-	 * Maximum number of frames to be written to the socket at once. The
-   * library tries to send max_num_frames in a single call to SPDY_run
-   * for a single session. This means no requests can be received nor
-   * other sessions can send data as long the current one has enough
-   * frames to send and there is no error on writing.
-	 */
-	uint32_t max_num_frames;
-
-	/**
-	 * Shows the current receiving state the session, i.e. what is
-	 * expected to come now, and how it shold be handled.
-	 */
-	enum SPDY_SESSION_STATUS status;
-
-	/**
-	 * Has this socket been closed for reading (i.e.
-	 * other side closed the connection)?  If so,
-	 * we must completely close the connection once
-	 * we are done sending our response (and stop
-	 * trying to read from this socket).
-	 */
-	bool read_closed;
-
-	/**
-	 * If the server sends GOAWAY, it must ignore all SYN_STREAMS for
-	 * this session. Normally the server will soon close the TCP session.
-	 */
-	bool is_goaway_sent;
-
-	/**
-	 * If the server receives GOAWAY, it must not send new SYN_STREAMS 
-	 * on this session. Normally the client will soon close the TCP
-	 * session.
-	 */
-	bool is_goaway_received;
-};
-
-
-/**
- * State and settings kept for each SPDY daemon.
- */
-struct SPDY_Daemon
-{
-
-	/**
-	 * Tail of doubly-linked list of our current, active sessions.
-	 */
-	struct SPDY_Session *sessions_head;
-
-	/**
-	 * Tail of doubly-linked list of our current, active sessions.
-	 */
-	struct SPDY_Session *sessions_tail;
-	
-	/**
-	 * Tail of doubly-linked list of connections to clean up.
-	 */
-	struct SPDY_Session *cleanup_head;
-
-	/**
-	 * Tail of doubly-linked list of connections to clean up.
-	 */
-	struct SPDY_Session *cleanup_tail;
-
-	/**
-	 * Unique IO context for the daemon. Initialized on daemon start.
-	 */
-	void *io_context;
-
-	/**
-	 * Certificate file of the server. File path is kept here.
-	 */
-	char *certfile;
-
-	/**
-	 * Key file for the certificate of the server. File path is
-	 * kept here.
-	 */
-	char *keyfile;
-	
-
-	/**
-	 * The address to which the listening socket is bound.
-	 */
-	struct sockaddr *address;
-	
-	/**
-	 * Callback called when a new SPDY session is
-	 * established by a client
-	 */
-	SPDY_NewSessionCallback new_session_cb;
-
-	/**
-	 * Callback called when a client closes the session
-	 */
-	SPDY_SessionClosedCallback session_closed_cb;
-
-	/**
-	 * Callback called when a client sends request
-	 */
-	SPDY_NewRequestCallback new_request_cb;
-
-	/**
-	* Callback called when HTTP POST params are received
-	* after request. To be used by the application layer
-	*/
-	SPDY_NewDataCallback received_data_cb;
-
-	/**
-	* Callback called when DATA frame is received.
-	*/
-	SPDYF_NewDataCallback freceived_data_cb;
-
-	/**
-	 * Closure argument for all the callbacks that can be used by the client.
-	 */
-	void *cls;
-
-	/**
-	 * Callback called when new stream is created.
-	 */
-	SPDYF_NewStreamCallback fnew_stream_cb;
-
-	/**
-	 * Closure argument for all the callbacks defined in the framing layer.
-	 */
-	void *fcls;
-
-	/**
-	 * Function to initialize the IO context for the daemon.
-	 */
-	SPDYF_IOInit fio_init;
-
-	/**
-	 * Function to deinitialize the IO context for the daemon.
-	 */
-	SPDYF_IODeinit fio_deinit;
-
-	/**
-	 * After how many milliseconds of inactivity should
-	 * connections time out? Zero for no timeout.
-	 */
-	unsigned long long session_timeout;
-
-	/**
-	 * Listen socket.
-	 */
-	int socket_fd;
-	
-	/**
-   * This value is inherited by all sessions of the daemon.
-	 * Maximum number of frames to be written to the socket at once. The
-   * library tries to send max_num_frames in a single call to SPDY_run
-   * for a single session. This means no requests can be received nor
-   * other sessions can send data as long the current one has enough
-   * frames to send and there is no error on writing.
-	 */
-	uint32_t max_num_frames;
-
-	/**
-	 * Daemon's options.
-	 */
-	enum SPDY_DAEMON_OPTION options;
-
-	/**
-	 * Daemon's flags.
-	 */
-	enum SPDY_DAEMON_FLAG flags;
-
-	/**
-	 * IO subsystem type used by daemon and all its sessions.
-	 */
-	enum SPDY_IO_SUBSYSTEM io_subsystem;
-
-	/**
-	 * Listen port.
-	 */
-	uint16_t port;
-};
-
-
-/**
- * Represents a SPDY response.
- */
-struct SPDY_Response
-{
-	/**
-	 * Raw uncompressed stream of the name/value pairs in SPDY frame
-	 * used for the HTTP headers.
-	 */
-    void *headers;
-	
-	/**
-	 * Raw stream of the data to be sent. Equivalent to the body in HTTP
-	 * response.
-	 */
-	void *data;
-	
-	/**
-	 * Callback function to be used when the response data is provided
-	 * with callbacks. In this case data must be NULL and data_size must
-	 * be 0.
-	 */
-	SPDY_ResponseCallback rcb;
-	
-	/**
-	 * Extra argument to rcb.
-	 */
-	void *rcb_cls;
-	
-	/**
-	 * Length of headers.
-	 */
-	size_t headers_size;
-	
-	/**
-	 * Length of data.
-	 */
-	size_t data_size;
-	
-	/**
-	 * The callback func will be called to get that amount of bytes to
-	 * put them into a DATA frame. It is either user preffered or
-	 * the maximum supported by the lib value.
-	 */
-	uint32_t rcb_block_size;
-};
-
-
-/* Macros for handling data and structures */
-
-
-/**
- * Insert an element at the head of a DLL. Assumes that head, tail and
- * element are structs with prev and next fields.
- *
- * @param head pointer to the head of the DLL (struct ? *)
- * @param tail pointer to the tail of the DLL (struct ? *)
- * @param element element to insert (struct ? *)
- */
-#define DLL_insert(head,tail,element) do { \
-	(element)->next = (head); \
-	(element)->prev = NULL; \
-	if ((tail) == NULL) \
-		(tail) = element; \
-	else \
-		(head)->prev = element; \
-	(head) = (element); } while (0)
-
-
-/**
- * Remove an element from a DLL. Assumes
- * that head, tail and element are structs
- * with prev and next fields.
- *
- * @param head pointer to the head of the DLL (struct ? *)
- * @param tail pointer to the tail of the DLL (struct ? *)
- * @param element element to remove (struct ? *)
- */
-#define DLL_remove(head,tail,element) do { \
-	if ((element)->prev == NULL) \
-		(head) = (element)->next;  \
-	else \
-		(element)->prev->next = (element)->next; \
-	if ((element)->next == NULL) \
-		(tail) = (element)->prev;  \
-	else \
-		(element)->next->prev = (element)->prev; \
-	(element)->next = NULL; \
-	(element)->prev = NULL; } while (0)
-
-
-/**
- * Convert all integers in a SPDY control frame headers structure from
- * host byte order to network byte order.
- *
- * @param frame input and output structure (struct SPDY_Control_Frame *)
- */
-#if HAVE_BIG_ENDIAN
-#define SPDYF_CONTROL_FRAME_HTON(frame)
-#else
-#define SPDYF_CONTROL_FRAME_HTON(frame) do { \
-	(*((uint16_t *) frame  )) = (*((uint8_t *) (frame) +1 )) | ((*((uint8_t *) frame  ))<<8);\
-	(frame)->type = htons((frame)->type); \
-	(frame)->length = HTON24((frame)->length); \
-	} while (0)
-#endif
-
-
-/**
- * Convert all integers in a SPDY control frame headers structure from
- * network byte order to host byte order.
- *
- * @param frame input and output structure (struct SPDY_Control_Frame *)
- */	
-#if HAVE_BIG_ENDIAN
-#define SPDYF_CONTROL_FRAME_NTOH(frame)
-#else
-#define SPDYF_CONTROL_FRAME_NTOH(frame) do { \
-	(*((uint16_t *) frame  )) = (*((uint8_t *) (frame) +1 )) | ((*((uint8_t *) frame  ))<<8);\
-	(frame)->type = ntohs((frame)->type); \
-	(frame)->length = NTOH24((frame)->length); \
-	} while (0)
-#endif
-
-
-/**
- * Convert all integers in a SPDY data frame headers structure from
- * host byte order to network byte order.
- *
- * @param frame input and output structure (struct SPDY_Data_Frame *)
- */
-#if HAVE_BIG_ENDIAN
-#define SPDYF_DATA_FRAME_HTON(frame)
-#else
-#define SPDYF_DATA_FRAME_HTON(frame) do { \
-	*((uint32_t *) frame  ) = htonl(*((uint32_t *) frame  ));\
-	(frame)->length = HTON24((frame)->length); \
-	} while (0)
-#endif
-
-
-/**
- * Convert all integers in a SPDY data frame headers structure from
- * network byte order to host byte order.
- *
- * @param frame input and output structure (struct SPDY_Data_Frame *)
- */	
-#if HAVE_BIG_ENDIAN
-#define SPDYF_DATA_FRAME_NTOH(frame)
-#else
-#define SPDYF_DATA_FRAME_NTOH(frame) do { \
-	*((uint32_t *) frame  ) = ntohl(*((uint32_t *) frame  ));\
-	(frame)->length = NTOH24((frame)->length); \
-	} while (0)
-#endif
-
-
-/**
- * Creates one or more new SPDYF_Response_Queue object to be put on the
- * response queue.
- *
- * @param is_data whether new data frame or new control frame will be
- *                crerated
- * @param data the row stream which will be used as the body of the frame
- * @param data_size length of data
- * @param response object, part of which is the frame
- * @param stream on which data is to be sent 
- * @param closestream TRUE if the frame must close the stream (with flag) 
- * @param frqcb callback to notify application layer when the frame
- *              has been sent or discarded 
- * @param frqcb_cls closure for frqcb
- * @param rrcb callback used by the application layer to notify the
- *             application when the frame has been sent or discarded.
- *             frqcb will call it 
- * @param rrcb_cls closure for rrcb
- * @return double linked list of SPDYF_Response_Queue structures: one or
- *         more frames are returned based on the size of the data
- */
-struct SPDYF_Response_Queue *
-SPDYF_response_queue_create(bool is_data,
-						void *data,
-						size_t data_size,
-						struct SPDY_Response *response,
-						struct SPDYF_Stream *stream,
-						bool closestream,
-						SPDYF_ResponseQueueResultCallback frqcb,
-						void *frqcb_cls,
-						SPDY_ResponseResultCallback rrcb,
-						void *rrcb_cls);
-
-
-/**
- * Destroys SPDYF_Response_Queue structure and whatever is in it.
- *
- * @param response_queue to destroy
- */
-void
-SPDYF_response_queue_destroy(struct SPDYF_Response_Queue *response_queue);
-
-
-/**
- * Checks if the container is empty, i.e. created but no values were
- * added to it.
- *
- * @param container
- * @return SPDY_YES if empty
- *         SPDY_NO if not
- */
-int
-SPDYF_name_value_is_empty(struct SPDY_NameValue *container);
-
-
-/**
- * Transforms raw binary decomressed stream of headers
- * into SPDY_NameValue, containing all of the headers and values.
- *
- * @param stream that is to be transformed
- * @param size length of the stream
- * @param container will contain the newly created SPDY_NameValue
- *        container. Should point to NULL.
- * @return SPDY_YES on success
- *         SPDY_NO on memory error
- *         SPDY_INPUT_ERROR if the provided stream is not valid
- */
-int
-SPDYF_name_value_from_stream(void *stream,
-							size_t size,
-							struct SPDY_NameValue ** container);
-
-
-/**
- * Transforms array of objects of name/values tuples, containing HTTP
- * headers, into raw binary stream. The resulting stream is ready to
- * be compressed and sent.
- *
- * @param container one or more SPDY_NameValue objects. Each object
- *        contains multiple number of name/value tuples.
- * @param num_containers length of the array
- * @param stream will contain the resulting stream. Should point to NULL.
- * @return length of stream or value less than 0 indicating error
- */
-ssize_t
-SPDYF_name_value_to_stream(struct SPDY_NameValue * container[],
-							int num_containers,
-							void **stream);
-
-#endif
diff --git a/src/platform/Makefile.am b/src/platform/Makefile.am
deleted file mode 100644
index 448efae..0000000
--- a/src/platform/Makefile.am
+++ /dev/null
@@ -1,20 +0,0 @@
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include
-
-AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS)
-
-if USE_COVERAGE
-  AM_CFLAGS += --coverage
-endif
-
-if HAVE_W32
-noinst_LTLIBRARIES = \
-  libplatform_interface.la
-libplatform_interface_la_CPPFLAGS = \
-  $(AM_CPPFLAGS) \
-  -DBUILDING_MHD_LIB=1
-libplatform_interface_la_SOURCES = \
-  w32functions.c
-endif
-
diff --git a/src/platform/Makefile.in b/src/platform/Makefile.in
deleted file mode 100644
index 31c85e8..0000000
--- a/src/platform/Makefile.in
+++ /dev/null
@@ -1,658 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@USE_COVERAGE_TRUE@am__append_1 = --coverage
-subdir = src/platform
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-LTLIBRARIES = $(noinst_LTLIBRARIES)
-libplatform_interface_la_LIBADD =
-am__libplatform_interface_la_SOURCES_DIST = w32functions.c
-@HAVE_W32_TRUE@am_libplatform_interface_la_OBJECTS =  \
-@HAVE_W32_TRUE@	libplatform_interface_la-w32functions.lo
-libplatform_interface_la_OBJECTS =  \
-	$(am_libplatform_interface_la_OBJECTS)
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-@HAVE_W32_TRUE@am_libplatform_interface_la_rpath =
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(libplatform_interface_la_SOURCES)
-DIST_SOURCES = $(am__libplatform_interface_la_SOURCES_DIST)
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include
-
-AM_CFLAGS = $(HIDDEN_VISIBILITY_CFLAGS) $(am__append_1)
-@HAVE_W32_TRUE@noinst_LTLIBRARIES = \
-@HAVE_W32_TRUE@  libplatform_interface.la
-
-@HAVE_W32_TRUE@libplatform_interface_la_CPPFLAGS = \
-@HAVE_W32_TRUE@  $(AM_CPPFLAGS) \
-@HAVE_W32_TRUE@  -DBUILDING_MHD_LIB=1
-
-@HAVE_W32_TRUE@libplatform_interface_la_SOURCES = \
-@HAVE_W32_TRUE@  w32functions.c
-
-all: all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/platform/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/platform/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-noinstLTLIBRARIES:
-	-test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
-	@list='$(noinst_LTLIBRARIES)'; \
-	locs=`for p in $$list; do echo $$p; done | \
-	      sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \
-	      sort -u`; \
-	test -z "$$locs" || { \
-	  echo rm -f $${locs}; \
-	  rm -f $${locs}; \
-	}
-
-libplatform_interface.la: $(libplatform_interface_la_OBJECTS) $(libplatform_interface_la_DEPENDENCIES) $(EXTRA_libplatform_interface_la_DEPENDENCIES) 
-	$(AM_V_CCLD)$(LINK) $(am_libplatform_interface_la_rpath) $(libplatform_interface_la_OBJECTS) $(libplatform_interface_la_LIBADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libplatform_interface_la-w32functions.Plo@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-libplatform_interface_la-w32functions.lo: w32functions.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libplatform_interface_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libplatform_interface_la-w32functions.lo -MD -MP -MF $(DEPDIR)/libplatform_interface_la-w32functions.Tpo -c -o libplatform_interface_la-w32functions.lo `test -f 'w32functions.c' || echo '$(srcdir)/'`w32functions.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/libplatform_interface_la-w32functions.Tpo $(DEPDIR)/libplatform_interface_la-w32functions.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='w32functions.c' object='libplatform_interface_la-w32functions.lo' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libplatform_interface_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libplatform_interface_la-w32functions.lo `test -f 'w32functions.c' || echo '$(srcdir)/'`w32functions.c
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-am
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-am
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-am
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-am
-all-am: Makefile $(LTLIBRARIES)
-installdirs:
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
-	mostlyclean-am
-
-distclean: distclean-am
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-html-am:
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-am
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-am
-
-install-html-am:
-
-install-info: install-info-am
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-am
-
-install-pdf-am:
-
-install-ps: install-ps-am
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: install-am install-strip
-
-.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \
-	clean-libtool clean-noinstLTLIBRARIES cscopelist-am ctags \
-	ctags-am distclean distclean-compile distclean-generic \
-	distclean-libtool distclean-tags distdir dvi dvi-am html \
-	html-am info info-am install install-am install-data \
-	install-data-am install-dvi install-dvi-am install-exec \
-	install-exec-am install-html install-html-am install-info \
-	install-info-am install-man install-pdf install-pdf-am \
-	install-ps install-ps-am install-strip installcheck \
-	installcheck-am installdirs maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-compile \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags tags-am uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/platform/w32functions.c b/src/platform/w32functions.c
deleted file mode 100644
index bc42fef..0000000
--- a/src/platform/w32functions.c
+++ /dev/null
@@ -1,704 +0,0 @@
-/*
-  This file is part of libmicrohttpd
-  Copyright (C) 2014 Karlson2k (Evgeny Grin)
-
-  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 2.1 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/>.
-*/
-
-/**
- * @file platform/w32functions.h
- * @brief  internal functions for W32 systems
- * @author Karlson2k (Evgeny Grin)
- */
-
-#include "w32functions.h"
-#include <errno.h>
-#include <winsock2.h>
-#include <string.h>
-#include <stdint.h>
-#include <time.h>
-#include <stdio.h>
-#include <stdarg.h>
-
-
-/**
- * Return errno equivalent of last winsock error
- * @return errno equivalent of last winsock error
- */
-int MHD_W32_errno_from_winsock_(void)
-{
-  switch(WSAGetLastError())
-  {
-  case 0:                      return 0;
-  case WSA_INVALID_HANDLE:     return EBADF;
-  case WSA_NOT_ENOUGH_MEMORY:  return ENOMEM;
-  case WSA_INVALID_PARAMETER:  return EINVAL;
-  case WSAEINTR:               return EINTR;
-  case WSAEWOULDBLOCK:         return EWOULDBLOCK;
-  case WSAEINPROGRESS:         return EINPROGRESS;
-  case WSAEALREADY:            return EALREADY;
-  case WSAENOTSOCK:            return ENOTSOCK;
-  case WSAEDESTADDRREQ:        return EDESTADDRREQ;
-  case WSAEMSGSIZE:            return EMSGSIZE;
-  case WSAEPROTOTYPE:          return EPROTOTYPE;
-  case WSAENOPROTOOPT:         return ENOPROTOOPT;
-  case WSAEPROTONOSUPPORT:     return EPROTONOSUPPORT;
-  case WSAESOCKTNOSUPPORT:     return ESOCKTNOSUPPORT;
-  case WSAEOPNOTSUPP:          return EOPNOTSUPP;
-  case WSAEPFNOSUPPORT:        return EPFNOSUPPORT;
-  case WSAEAFNOSUPPORT:        return EAFNOSUPPORT;
-  case WSAEADDRINUSE:          return EADDRINUSE;
-  case WSAEADDRNOTAVAIL:       return EADDRNOTAVAIL;
-  case WSAENETDOWN:            return ENETDOWN;
-  case WSAENETUNREACH:         return ENETUNREACH;
-  case WSAENETRESET:           return ENETRESET;
-  case WSAECONNABORTED:        return ECONNABORTED;
-  case WSAECONNRESET:          return ECONNRESET;
-  case WSAENOBUFS:             return ENOBUFS;
-  case WSAEISCONN:             return EISCONN;
-  case WSAENOTCONN:            return ENOTCONN;
-  case WSAESHUTDOWN:           return ESHUTDOWN;
-  case WSAETOOMANYREFS:        return ETOOMANYREFS;
-  case WSAETIMEDOUT:           return ETIMEDOUT;
-  case WSAECONNREFUSED:        return ECONNREFUSED;
-  case WSAELOOP:               return ELOOP;
-  case WSAENAMETOOLONG:        return ENAMETOOLONG;
-  case WSAEHOSTDOWN:           return EHOSTDOWN;
-  case WSAEHOSTUNREACH:        return EHOSTUNREACH;
-  case WSAENOTEMPTY:           return ENOTEMPTY;
-  case WSAEPROCLIM:            return EPROCLIM;
-  case WSAEUSERS:              return EUSERS;
-  case WSAEDQUOT:              return EDQUOT;
-  case WSAESTALE:              return ESTALE;
-  case WSAEREMOTE:             return EREMOTE;
-  case WSAEINVAL:              return EINVAL;
-  case WSAEFAULT:              return EFAULT;
-  case WSANO_DATA:             return ENODATA;
-  /* Rough equivalents */
-  case WSAEDISCON:             return ECONNRESET;
-  case WSAEINVALIDPROCTABLE:   return EFAULT;
-  case WSASYSNOTREADY:
-  case WSANOTINITIALISED:
-  case WSASYSCALLFAILURE:      return ENOBUFS;
-  case WSAVERNOTSUPPORTED:     return EOPNOTSUPP;
-  case WSAEREFUSED:            return EIO;
-  }
-  return EINVAL;
-}
-
-/**
- * Return pointer to string description of errnum error
- * Works fine with both standard errno errnums
- * and errnums from MHD_W32_errno_from_winsock_
- * @param errnum the errno or value from MHD_W32_errno_from_winsock_()
- * @return pointer to string description of error
- */
-const char* MHD_W32_strerror_(int errnum)
-{
-  switch(errnum)
-  {
-  case 0:
-    return "No error";
-  case EWOULDBLOCK:
-    return "Operation would block";
-  case EINPROGRESS:
-    return "Connection already in progress";
-  case EALREADY:
-    return "Socket already connected";
-  case ENOTSOCK:
-    return "Socket operation on non-socket";
-  case EDESTADDRREQ:
-    return "Destination address required";
-  case EMSGSIZE:
-    return "Message too long";
-  case EPROTOTYPE:
-    return "Protocol wrong type for socket";
-  case ENOPROTOOPT:
-    return "Protocol not available";
-  case EPROTONOSUPPORT:
-    return "Unknown protocol";
-  case ESOCKTNOSUPPORT:
-    return "Socket type not supported";
-  case EOPNOTSUPP:
-    return "Operation not supported on socket";
-  case EPFNOSUPPORT:
-    return "Protocol family not supported";
-  case EAFNOSUPPORT:
-    return "Address family not supported by protocol family";
-  case EADDRINUSE:
-    return "Address already in use";
-  case EADDRNOTAVAIL:
-    return "Cannot assign requested address";
-  case ENETDOWN:
-    return "Network is down";
-  case ENETUNREACH:
-    return "Network is unreachable";
-  case ENETRESET:
-    return "Network dropped connection on reset";
-  case ECONNABORTED:
-    return "Software caused connection abort";
-  case ECONNRESET:
-    return "Connection reset by peer";
-  case ENOBUFS:
-    return "No system resources available";
-  case EISCONN:
-    return "Socket is already connected";
-  case ENOTCONN:
-    return "Socket is not connected";
-  case ESHUTDOWN:
-    return "Can't send after socket shutdown";
-  case ETOOMANYREFS:
-    return "Too many references: cannot splice";
-  case ETIMEDOUT:
-    return "Connection timed out";
-  case ECONNREFUSED:
-    return "Connection refused";
-  case ELOOP:
-    return "Cannot translate name";
-  case EHOSTDOWN:
-    return "Host is down";
-  case EHOSTUNREACH:
-    return "Host is unreachable";
-  case EPROCLIM:
-    return "Too many processes";
-  case EUSERS:
-    return "Too many users";
-  case EDQUOT:
-    return "Disk quota exceeded";
-  case ESTALE:
-    return "Stale file handle reference";
-  case EREMOTE:
-    return "Resource is remote";
-  case ENODATA:
-    return "No data available";
-  }
-  return strerror(errnum);
-}
-
-/**
- * Return pointer to string description of last winsock error
- * @return pointer to string description of last winsock error
- */
-const char* MHD_W32_strerror_last_winsock_(void)
-{
-  switch (WSAGetLastError())
-    {
-  case 0:
-    return "No error";
-  case WSA_INVALID_HANDLE:
-    return "Specified event object handle is invalid";
-  case WSA_NOT_ENOUGH_MEMORY:
-    return "Insufficient memory available";
-  case WSA_INVALID_PARAMETER:
-    return "One or more parameters are invalid";
-  case WSA_OPERATION_ABORTED:
-    return "Overlapped operation aborted";
-  case WSA_IO_INCOMPLETE:
-    return "Overlapped I/O event object not in signaled state";
-  case WSA_IO_PENDING:
-    return "Overlapped operations will complete later";
-  case WSAEINTR:
-    return "Interrupted function call";
-  case WSAEBADF:
-    return "File handle is not valid";
-  case WSAEACCES:
-    return "Permission denied";
-  case WSAEFAULT:
-    return "Bad address";
-  case WSAEINVAL:
-    return "Invalid argument";
-  case WSAEMFILE:
-    return "Too many open files";
-  case WSAEWOULDBLOCK:
-    return "Resource temporarily unavailable";
-  case WSAEINPROGRESS:
-    return "Operation now in progress";
-  case WSAEALREADY:
-    return "Operation already in progress";
-  case WSAENOTSOCK:
-    return "Socket operation on nonsocket";
-  case WSAEDESTADDRREQ:
-    return "Destination address required";
-  case WSAEMSGSIZE:
-    return "Message too long";
-  case WSAEPROTOTYPE:
-    return "Protocol wrong type for socket";
-  case WSAENOPROTOOPT:
-    return "Bad protocol option";
-  case WSAEPROTONOSUPPORT:
-    return "Protocol not supported";
-  case WSAESOCKTNOSUPPORT:
-    return "Socket type not supported";
-  case WSAEOPNOTSUPP:
-    return "Operation not supported";
-  case WSAEPFNOSUPPORT:
-    return "Protocol family not supported";
-  case WSAEAFNOSUPPORT:
-    return "Address family not supported by protocol family";
-  case WSAEADDRINUSE:
-    return "Address already in use";
-  case WSAEADDRNOTAVAIL:
-    return "Cannot assign requested address";
-  case WSAENETDOWN:
-    return "Network is down";
-  case WSAENETUNREACH:
-    return "Network is unreachable";
-  case WSAENETRESET:
-    return "Network dropped connection on reset";
-  case WSAECONNABORTED:
-    return "Software caused connection abort";
-  case WSAECONNRESET:
-    return "Connection reset by peer";
-  case WSAENOBUFS:
-    return "No buffer space available";
-  case WSAEISCONN:
-    return "Socket is already connected";
-  case WSAENOTCONN:
-    return "Socket is not connected";
-  case WSAESHUTDOWN:
-    return "Cannot send after socket shutdown";
-  case WSAETOOMANYREFS:
-    return "Too many references";
-  case WSAETIMEDOUT:
-    return "Connection timed out";
-  case WSAECONNREFUSED:
-    return "Connection refused";
-  case WSAELOOP:
-    return "Cannot translate name";
-  case WSAENAMETOOLONG:
-    return "Name too long";
-  case WSAEHOSTDOWN:
-    return "Host is down";
-  case WSAEHOSTUNREACH:
-    return "No route to host";
-  case WSAENOTEMPTY:
-    return "Directory not empty";
-  case WSAEPROCLIM:
-    return "Too many processes";
-  case WSAEUSERS:
-    return "User quota exceeded";
-  case WSAEDQUOT:
-    return "Disk quota exceeded";
-  case WSAESTALE:
-    return "Stale file handle reference";
-  case WSAEREMOTE:
-    return "Item is remote";
-  case WSASYSNOTREADY:
-    return "Network subsystem is unavailable";
-  case WSAVERNOTSUPPORTED:
-    return "Winsock.dll version out of range";
-  case WSANOTINITIALISED:
-    return "Successful WSAStartup not yet performed";
-  case WSAEDISCON:
-    return "Graceful shutdown in progress";
-  case WSAENOMORE:
-    return "No more results";
-  case WSAECANCELLED:
-    return "Call has been canceled";
-  case WSAEINVALIDPROCTABLE:
-    return "Procedure call table is invalid";
-  case WSAEINVALIDPROVIDER:
-    return "Service provider is invalid";
-  case WSAEPROVIDERFAILEDINIT:
-    return "Service provider failed to initialize";
-  case WSASYSCALLFAILURE:
-    return "System call failure";
-  case WSASERVICE_NOT_FOUND:
-    return "Service not found";
-  case WSATYPE_NOT_FOUND:
-    return "Class type not found";
-  case WSA_E_NO_MORE:
-    return "No more results";
-  case WSA_E_CANCELLED:
-    return "Call was canceled";
-  case WSAEREFUSED:
-    return "Database query was refused";
-  case WSAHOST_NOT_FOUND:
-    return "Host not found";
-  case WSATRY_AGAIN:
-    return "Nonauthoritative host not found";
-  case WSANO_RECOVERY:
-    return "This is a nonrecoverable error";
-  case WSANO_DATA:
-    return "Valid name, no data record of requested type";
-  case WSA_QOS_RECEIVERS:
-    return "QoS receivers";
-  case WSA_QOS_SENDERS:
-    return "QoS senders";
-  case WSA_QOS_NO_SENDERS:
-    return "No QoS senders";
-  case WSA_QOS_NO_RECEIVERS:
-    return "QoS no receivers";
-  case WSA_QOS_REQUEST_CONFIRMED:
-    return "QoS request confirmed";
-  case WSA_QOS_ADMISSION_FAILURE:
-    return "QoS admission error";
-  case WSA_QOS_POLICY_FAILURE:
-    return "QoS policy failure";
-  case WSA_QOS_BAD_STYLE:
-    return "QoS bad style";
-  case WSA_QOS_BAD_OBJECT:
-    return "QoS bad object";
-  case WSA_QOS_TRAFFIC_CTRL_ERROR:
-    return "QoS traffic control error";
-  case WSA_QOS_GENERIC_ERROR:
-    return "QoS generic error";
-  case WSA_QOS_ESERVICETYPE:
-    return "QoS service type error";
-  case WSA_QOS_EFLOWSPEC:
-    return "QoS flowspec error";
-  case WSA_QOS_EPROVSPECBUF:
-    return "Invalid QoS provider buffer";
-  case WSA_QOS_EFILTERSTYLE:
-    return "Invalid QoS filter style";
-  case WSA_QOS_EFILTERTYPE:
-    return "Invalid QoS filter type";
-  case WSA_QOS_EFILTERCOUNT:
-    return "Incorrect QoS filter count";
-  case WSA_QOS_EOBJLENGTH:
-    return "Invalid QoS object length";
-  case WSA_QOS_EFLOWCOUNT:
-    return "Incorrect QoS flow count";
-  case WSA_QOS_EUNKOWNPSOBJ:
-    return "Unrecognized QoS object";
-  case WSA_QOS_EPOLICYOBJ:
-    return "Invalid QoS policy object";
-  case WSA_QOS_EFLOWDESC:
-    return "Invalid QoS flow descriptor";
-  case WSA_QOS_EPSFLOWSPEC:
-    return "Invalid QoS provider-specific flowspec";
-  case WSA_QOS_EPSFILTERSPEC:
-    return "Invalid QoS provider-specific filterspec";
-  case WSA_QOS_ESDMODEOBJ:
-    return "Invalid QoS shape discard mode object";
-  case WSA_QOS_ESHAPERATEOBJ:
-    return "Invalid QoS shaping rate object";
-  case WSA_QOS_RESERVED_PETYPE:
-    return "Reserved policy QoS element type";
-    }
-  return "Unknown winsock error";
-}
-
-/**
- * Set last winsock error to equivalent of given errno value
- * @param errnum the errno value to set
- */
-void MHD_W32_set_last_winsock_error_(int errnum)
-{
-  switch (errnum)
-    {
-  case 0:
-    WSASetLastError(0);
-    break;
-  case EBADF:
-    WSASetLastError(WSA_INVALID_HANDLE);
-    break;
-  case ENOMEM:
-    WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
-    break;
-  case EINVAL:
-    WSASetLastError(WSA_INVALID_PARAMETER);
-    break;
-  case EINTR:
-    WSASetLastError(WSAEINTR);
-    break;
-  case EWOULDBLOCK:
-    WSASetLastError(WSAEWOULDBLOCK);
-    break;
-  case EINPROGRESS:
-    WSASetLastError(WSAEINPROGRESS);
-    break;
-  case EALREADY:
-    WSASetLastError(WSAEALREADY);
-    break;
-  case ENOTSOCK:
-    WSASetLastError(WSAENOTSOCK);
-    break;
-  case EDESTADDRREQ:
-    WSASetLastError(WSAEDESTADDRREQ);
-    break;
-  case EMSGSIZE:
-    WSASetLastError(WSAEMSGSIZE);
-    break;
-  case EPROTOTYPE:
-    WSASetLastError(WSAEPROTOTYPE);
-    break;
-  case ENOPROTOOPT:
-    WSASetLastError(WSAENOPROTOOPT);
-    break;
-  case EPROTONOSUPPORT:
-    WSASetLastError(WSAEPROTONOSUPPORT);
-    break;
-  case ESOCKTNOSUPPORT:
-    WSASetLastError(WSAESOCKTNOSUPPORT);
-    break;
-  case EOPNOTSUPP:
-    WSASetLastError(WSAEOPNOTSUPP);
-    break;
-  case EPFNOSUPPORT:
-    WSASetLastError(WSAEPFNOSUPPORT);
-    break;
-  case EAFNOSUPPORT:
-    WSASetLastError(WSAEAFNOSUPPORT);
-    break;
-  case EADDRINUSE:
-    WSASetLastError(WSAEADDRINUSE);
-    break;
-  case EADDRNOTAVAIL:
-    WSASetLastError(WSAEADDRNOTAVAIL);
-    break;
-  case ENETDOWN:
-    WSASetLastError(WSAENETDOWN);
-    break;
-  case ENETUNREACH:
-    WSASetLastError(WSAENETUNREACH);
-    break;
-  case ENETRESET:
-    WSASetLastError(WSAENETRESET);
-    break;
-  case ECONNABORTED:
-    WSASetLastError(WSAECONNABORTED);
-    break;
-  case ECONNRESET:
-    WSASetLastError(WSAECONNRESET);
-    break;
-  case ENOBUFS:
-    WSASetLastError(WSAENOBUFS);
-    break;
-  case EISCONN:
-    WSASetLastError(WSAEISCONN);
-    break;
-  case ENOTCONN:
-    WSASetLastError(WSAENOTCONN);
-    break;
-  case ESHUTDOWN:
-    WSASetLastError(WSAESHUTDOWN);
-    break;
-  case ETOOMANYREFS:
-    WSASetLastError(WSAETOOMANYREFS);
-    break;
-  case ETIMEDOUT:
-    WSASetLastError(WSAETIMEDOUT);
-    break;
-  case ECONNREFUSED:
-    WSASetLastError(WSAECONNREFUSED);
-    break;
-  case ELOOP:
-    WSASetLastError(WSAELOOP);
-    break;
-  case ENAMETOOLONG:
-    WSASetLastError(WSAENAMETOOLONG);
-    break;
-  case EHOSTDOWN:
-    WSASetLastError(WSAEHOSTDOWN);
-    break;
-  case EHOSTUNREACH:
-    WSASetLastError(WSAEHOSTUNREACH);
-    break;
-  case ENOTEMPTY:
-    WSASetLastError(WSAENOTEMPTY);
-    break;
-  case EPROCLIM:
-    WSASetLastError(WSAEPROCLIM);
-    break;
-  case EUSERS:
-    WSASetLastError(WSAEUSERS);
-    break;
-  case EDQUOT:
-    WSASetLastError(WSAEDQUOT);
-    break;
-  case ESTALE:
-    WSASetLastError(WSAESTALE);
-    break;
-  case EREMOTE:
-    WSASetLastError(WSAEREMOTE);
-    break;
-  case EFAULT:
-    WSASetLastError(WSAEFAULT);
-    break;
-  case ENODATA:
-    WSASetLastError(WSANO_DATA);
-    break;
-#if EAGAIN != EWOULDBLOCK
-  case EAGAIN:
-    WSASetLastError(WSAEWOULDBLOCK);
-    break;
-#endif
-  /* Rough equivalent */
-  case EIO:
-    WSASetLastError(WSAEREFUSED);
-    break;
-
-  default: /* Unmapped errors */
-    WSASetLastError(WSAENOBUFS);
-    break;
-    }
-}
-
-/**
- * Create pair of mutually connected TCP/IP sockets on loopback address
- * @param sockets_pair array to receive resulted sockets
- * @return zero on success, -1 otherwise
- */
-int MHD_W32_pair_of_sockets_(SOCKET sockets_pair[2])
-{
-  int i;
-  if (!sockets_pair)
-    {
-      errno = EINVAL;
-      return -1;
-    }
-
-#define PAIRMAXTRYIES 800
-  for (i = 0; i < PAIRMAXTRYIES; i++)
-    {
-      struct sockaddr_in listen_addr;
-      SOCKET listen_s;
-      static const int c_addinlen = sizeof(struct sockaddr_in); /* help compiler to optimize */
-      int addr_len = c_addinlen;
-      int opt = 1;
-
-      listen_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-      if (INVALID_SOCKET == listen_s)
-        break; /* can't create even single socket */
-
-      listen_addr.sin_family = AF_INET;
-      listen_addr.sin_port = htons(0);
-      listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-      if (0 == bind(listen_s, (struct sockaddr*) &listen_addr, c_addinlen)
-          && 0 == listen(listen_s, 1)
-          && 0 == getsockname(listen_s, (struct sockaddr*) &listen_addr,
-                  &addr_len))
-        {
-          SOCKET client_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-          if (INVALID_SOCKET != client_s)
-            {
-              if (0 == ioctlsocket(client_s, FIONBIO, (u_long*) &opt)
-                  && (0 == connect(client_s, (struct sockaddr*) &listen_addr, c_addinlen)
-                      || WSAGetLastError() == WSAEWOULDBLOCK))
-                {
-                  struct sockaddr_in accepted_from_addr;
-                  addr_len = c_addinlen;
-                  SOCKET server_s = accept(listen_s,
-                      (struct sockaddr*) &accepted_from_addr, &addr_len);
-                  if (INVALID_SOCKET != server_s)
-                    {
-                      struct sockaddr_in client_addr;
-                      addr_len = c_addinlen;
-                      opt = 0;
-                      if (0 == getsockname(client_s, (struct sockaddr*) &client_addr, &addr_len)
-                          && accepted_from_addr.sin_family == client_addr.sin_family
-                          && accepted_from_addr.sin_port == client_addr.sin_port
-                          && accepted_from_addr.sin_addr.s_addr == client_addr.sin_addr.s_addr
-                          && 0 == ioctlsocket(client_s, FIONBIO, (u_long*) &opt)
-                          && 0 == ioctlsocket(server_s, FIONBIO, (u_long*) &opt))
-                        {
-                          closesocket(listen_s);
-                          sockets_pair[0] = client_s;
-                          sockets_pair[1] = server_s;
-                          return 0;
-                        }
-                      closesocket(server_s);
-                    }
-                }
-              closesocket(client_s);
-            }
-        }
-      closesocket(listen_s);
-    }
-
-  sockets_pair[0] = INVALID_SOCKET;
-  sockets_pair[1] = INVALID_SOCKET;
-  return -1;
-}
-
-/**
- * Static variable used by pseudo random number generator
- */
-static int32_t rnd_val = 0;
-/**
- * Generate 31-bit pseudo random number.
- * Function initialize itself at first call to current time.
- * @return 31-bit pseudo random number.
- */
-int MHD_W32_random_(void)
-{
-  if (0 == rnd_val)
-    rnd_val = (int32_t)time(NULL);
-  /* stolen from winsup\cygwin\random.cc */
-  rnd_val = (16807 * (rnd_val % 127773) - 2836 * (rnd_val / 127773))
-               & 0x7fffffff;
-  return (int)rnd_val;
-}
-
-/* Emulate snprintf function on W32 */
-int W32_snprintf(char *__restrict s, size_t n, const char *__restrict format, ...)
-{
-  int ret;
-  va_list args;
-  if (0 != n && NULL != s )
-  {
-    va_start(args, format);
-    ret = _vsnprintf(s, n, format, args);
-    va_end(args);
-    if (n == ret)
-      s[n - 1] = 0;
-    if (ret >= 0)
-      return ret;
-  }
-  va_start(args, format);
-  ret = _vscprintf(format, args);
-  va_end(args);
-  if (0 <= ret && 0 != n && NULL == s)
-    return -1;
-
-  return ret;
-}
-
-#ifdef _MSC_FULL_VER
-/**
- * Set thread name
- * @param thread_id ID of thread, -1 for current thread
- * @param thread_name name to set
- */
-void W32_SetThreadName(const DWORD thread_id, const char *thread_name)
-{
-  static const DWORD VC_SETNAME_EXC = 0x406D1388;
-#pragma pack(push,8)
-  struct thread_info_struct
-  {
-    DWORD type;   // Must be 0x1000.
-    LPCSTR name;  // Pointer to name (in user address space).
-    DWORD ID;     // Thread ID (-1=caller thread).
-    DWORD flags;  // Reserved for future use, must be zero.
-  } thread_info;
-#pragma pack(pop)
-
-  if (NULL == thread_name)
-    return;
-
-  thread_info.type  = 0x1000;
-  thread_info.name  = thread_name;
-  thread_info.ID    = thread_id;
-  thread_info.flags = 0;
-
-  __try
-  { /* This exception is intercepted by debugger */
-    RaiseException(VC_SETNAME_EXC, 0, sizeof(thread_info) / sizeof(ULONG_PTR), (ULONG_PTR*)&thread_info);
-  }
-  __except (EXCEPTION_EXECUTE_HANDLER)
-  {}
-}
-#endif /* _MSC_FULL_VER */
diff --git a/src/spdy2http/Makefile.am b/src/spdy2http/Makefile.am
deleted file mode 100644
index f7432a9..0000000
--- a/src/spdy2http/Makefile.am
+++ /dev/null
@@ -1,29 +0,0 @@
-# This Makefile.am is in the public domain
-SUBDIRS  = .
-
-AM_CFLAGS =
-
-if USE_COVERAGE
-  AM_CFLAGS += -fprofile-arcs -ftest-coverage
-endif
-
-AM_CPPFLAGS = \
- -I$(top_srcdir) \
- -I$(top_srcdir)/src/include \
- -I$(top_srcdir)/src/applicationlayer \
- -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" \
- $(LIBCURL_CPPFLAGS)
-
-if !HAVE_W32
-PERF_GET_CONCURRENT=perf_get_concurrent
-endif
-
-bin_PROGRAMS = \
- microspdy2http
-
-microspdy2http_SOURCES = \
- proxy.c 
-microspdy2http_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz \
- $(LIBCURL)
diff --git a/src/spdy2http/Makefile.in b/src/spdy2http/Makefile.in
deleted file mode 100644
index ef67ffc..0000000
--- a/src/spdy2http/Makefile.in
+++ /dev/null
@@ -1,813 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage
-bin_PROGRAMS = microspdy2http$(EXEEXT)
-subdir = src/spdy2http
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am__installdirs = "$(DESTDIR)$(bindir)"
-PROGRAMS = $(bin_PROGRAMS)
-am_microspdy2http_OBJECTS = proxy.$(OBJEXT)
-microspdy2http_OBJECTS = $(am_microspdy2http_OBJECTS)
-am__DEPENDENCIES_1 =
-microspdy2http_DEPENDENCIES =  \
-	$(top_builddir)/src/microspdy/libmicrospdy.la \
-	$(am__DEPENDENCIES_1)
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(microspdy2http_SOURCES)
-DIST_SOURCES = $(microspdy2http_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-AM_CFLAGS = $(am__append_1)
-AM_CPPFLAGS = \
- -I$(top_srcdir) \
- -I$(top_srcdir)/src/include \
- -I$(top_srcdir)/src/applicationlayer \
- -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" \
- $(LIBCURL_CPPFLAGS)
-
-@HAVE_W32_FALSE@PERF_GET_CONCURRENT = perf_get_concurrent
-microspdy2http_SOURCES = \
- proxy.c 
-
-microspdy2http_LDADD = \
-  $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz \
- $(LIBCURL)
-
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .o .obj
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/spdy2http/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/spdy2http/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-install-binPROGRAMS: $(bin_PROGRAMS)
-	@$(NORMAL_INSTALL)
-	@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
-	if test -n "$$list"; then \
-	  echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \
-	  $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \
-	fi; \
-	for p in $$list; do echo "$$p $$p"; done | \
-	sed 's/$(EXEEXT)$$//' | \
-	while read p p1; do if test -f $$p \
-	 || test -f $$p1 \
-	  ; then echo "$$p"; echo "$$p"; else :; fi; \
-	done | \
-	sed -e 'p;s,.*/,,;n;h' \
-	    -e 's|.*|.|' \
-	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
-	sed 'N;N;N;s,\n, ,g' | \
-	$(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \
-	  { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
-	    if ($$2 == $$4) files[d] = files[d] " " $$1; \
-	    else { print "f", $$3 "/" $$4, $$1; } } \
-	  END { for (d in files) print "f", d, files[d] }' | \
-	while read type dir files; do \
-	    if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
-	    test -z "$$files" || { \
-	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \
-	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
-	    } \
-	; done
-
-uninstall-binPROGRAMS:
-	@$(NORMAL_UNINSTALL)
-	@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
-	files=`for p in $$list; do echo "$$p"; done | \
-	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
-	      -e 's/$$/$(EXEEXT)/' \
-	`; \
-	test -n "$$list" || exit 0; \
-	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
-	cd "$(DESTDIR)$(bindir)" && rm -f $$files
-
-clean-binPROGRAMS:
-	@list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-microspdy2http$(EXEEXT): $(microspdy2http_OBJECTS) $(microspdy2http_DEPENDENCIES) $(EXTRA_microspdy2http_DEPENDENCIES) 
-	@rm -f microspdy2http$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(microspdy2http_OBJECTS) $(microspdy2http_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/proxy.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-check: check-recursive
-all-am: Makefile $(PROGRAMS)
-installdirs: installdirs-recursive
-installdirs-am:
-	for dir in "$(DESTDIR)$(bindir)"; do \
-	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
-	done
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am: install-binPROGRAMS
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-binPROGRAMS
-
-.MAKE: $(am__recursive_targets) install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-am clean clean-binPROGRAMS clean-generic clean-libtool \
-	cscopelist-am ctags ctags-am distclean distclean-compile \
-	distclean-generic distclean-libtool distclean-tags distdir dvi \
-	dvi-am html html-am info info-am install install-am \
-	install-binPROGRAMS install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
-	uninstall-am uninstall-binPROGRAMS
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/spdy2http/proxy.c b/src/spdy2http/proxy.c
deleted file mode 100644
index 02144ad..0000000
--- a/src/spdy2http/proxy.c
+++ /dev/null
@@ -1,1411 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file proxy.c
- * @brief   Translates incoming SPDY requests to http server on localhost.
- * 			Uses libcurl.
- * 			No error handling for curl requests.
- *      TODO:
- * - test all options!
- * - don't abort on lack of memory
- * - Correct recapitalizetion of header names before giving the headers
- * to curl.
- * - curl does not close sockets when connection is closed and no
- * new sockets are opened (they stay in CLOSE_WAIT)
- * - add '/' when a user requests http://example.com . Now this is a bad
- * request
- * - curl returns 0 or 1 ms for timeout even when nothing will be done;
- * thus the loop uses CPU for nothing
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <string.h>
-#include <stdio.h>
-#include <ctype.h>
-#include <errno.h>
-#include "microspdy.h"
-#include <curl/curl.h>
-#include <assert.h>
-#include <getopt.h>
-#include <regex.h>
-
-#define ERROR_RESPONSE "502 Bad Gateway"
-
-
-struct global_options
-{
-  char *http_backend;
-  char *cert;
-  char *cert_key;
-  char *listen_host;
-  unsigned int timeout;
-  uint16_t listen_port;
-  bool verbose;
-  bool curl_verbose;
-  bool transparent;
-  bool http10;
-  bool notls;
-  bool nodelay;
-  bool ipv4;
-  bool ipv6;
-} glob_opt;
-
-
-struct URI
-{
-  char * full_uri;
-  char * scheme;
-  char * host_and_port;
-  //char * host_and_port_for_connecting;
-  char * host;
-  char * path;
-  char * path_and_more;
-  char * query;
-  char * fragment;
-  uint16_t port;
-};
-
-
-#define PRINT_INFO(msg) do{\
-	fprintf(stdout, "%i:%s\n", __LINE__, msg);\
-	fflush(stdout);\
-	}\
-	while(0)
-
-
-#define PRINT_INFO2(fmt, ...) do{\
-	fprintf(stdout, "%i\n", __LINE__);\
-	fprintf(stdout, fmt,##__VA_ARGS__);\
-	fprintf(stdout, "\n");\
-	fflush(stdout);\
-	}\
-	while(0)
-
-
-#define PRINT_VERBOSE(msg) do{\
-  if(glob_opt.verbose){\
-	fprintf(stdout, "%i:%s\n", __LINE__, msg);\
-	fflush(stdout);\
-	}\
-  }\
-	while(0)
-
-
-#define PRINT_VERBOSE2(fmt, ...) do{\
-  if(glob_opt.verbose){\
-	fprintf(stdout, "%i\n", __LINE__);\
-	fprintf(stdout, fmt,##__VA_ARGS__);\
-	fprintf(stdout, "\n");\
-	fflush(stdout);\
-	}\
-	}\
-	while(0)
-
-
-#define CURL_SETOPT(handle, opt, val) do{\
-	int ret; \
-	if(CURLE_OK != (ret = curl_easy_setopt(handle, opt, val))) \
-	{ \
-		PRINT_INFO2("curl_easy_setopt failed (%i = %i)", opt, ret); \
-		abort(); \
-	} \
-	}\
-	while(0)
-
-
-#define DIE(msg) do{\
-	printf("FATAL ERROR (line %i): %s\n", __LINE__, msg);\
-	fflush(stdout);\
-  exit(EXIT_FAILURE);\
-	}\
-	while(0)
-
-
-static int loop = 1;
-
-static CURLM *multi_handle;
-
-static int still_running = 0; /* keep number of running handles */
-
-static regex_t uri_preg;
-
-static bool call_spdy_run;
-static bool call_curl_run;
-
-int debug_num_curls;
-
-
-struct Proxy
-{
-	char *url;
-	struct SPDY_Request *request;
-	struct SPDY_Response *response;
-	CURL *curl_handle;
-	struct curl_slist *curl_headers;
-	struct SPDY_NameValue *headers;
-	char *version;
-	char *status_msg;
-	void *http_body;
-	void *received_body;
-  bool *session_alive;
-	size_t http_body_size;
-	size_t received_body_size;
-	//ssize_t length;
-	int status;
-  //bool done;
-  bool receiving_done;
-  bool is_curl_read_paused;
-  bool is_with_body_data;
-  //bool error;
-  bool curl_done;
-  bool curl_error;
-  bool spdy_done;
-  bool spdy_error;
-};
-
-
-static void
-free_uri(struct URI * uri)
-{
-  if(NULL != uri)
-  {
-    free(uri->full_uri);
-    free(uri->scheme);
-    free(uri->host_and_port);
-    //free(uri->host_and_port_for_connecting);
-    free(uri->host);
-    free(uri->path);
-    free(uri->path_and_more);
-    free(uri->query);
-    free(uri->fragment);
-    uri->port = 0;
-    free(uri);
-  }
-}
-
-
-static int
-init_parse_uri(regex_t * preg)
-{
-  // RFC 2396
-  // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
-      /*
-        scheme    = $2
-      authority = $4
-      path      = $5
-      query     = $7
-      fragment  = $9
-      */
-
-  return regcomp(preg, "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", REG_EXTENDED);
-}
-
-
-static void
-deinit_parse_uri(regex_t * preg)
-{
-  regfree(preg);
-}
-
-
-static int
-parse_uri(regex_t * preg, const char * full_uri, struct URI ** uri)
-{
-  //TODO memeory checks
-  int ret;
-  char *colon;
-  long long port;
-  size_t nmatch = 10;
-  regmatch_t pmatch[10];
-
-  if (0 != (ret = regexec(preg, full_uri, nmatch, pmatch, 0)))
-    return ret;
-
-  *uri = malloc(sizeof(struct URI));
-  if(NULL == *uri)
-    return -200;
-
-  (*uri)->full_uri = strdup(full_uri);
-
-  asprintf(&((*uri)->scheme),
-	   "%.*s",
-	   (int) (pmatch[2].rm_eo - pmatch[2].rm_so),
-	   &full_uri[pmatch[2].rm_so]);
-  asprintf(&((*uri)->host_and_port), "%.*s",
-	   (int) (pmatch[4].rm_eo - pmatch[4].rm_so),
-	   &full_uri[pmatch[4].rm_so]);
-  asprintf(&((*uri)->path),
-	   "%.*s",
-	   (int) (pmatch[5].rm_eo - pmatch[5].rm_so),
-	   &full_uri[pmatch[5].rm_so]);
-  asprintf(&((*uri)->path_and_more),
-	   "%.*s",
-	   (int) (pmatch[9].rm_eo - pmatch[5].rm_so),
-	   &full_uri[pmatch[5].rm_so]);
-  asprintf(&((*uri)->query),
-	   "%.*s",
-	   (int) (pmatch[7].rm_eo - pmatch[7].rm_so),
-	   &full_uri[pmatch[7].rm_so]);
-  asprintf(&((*uri)->fragment),
-	   "%.*s",
-	   (int) (pmatch[9].rm_eo - pmatch[9].rm_so),
-	   &full_uri[pmatch[9].rm_so]);
-
-  colon = strrchr((*uri)->host_and_port, ':');
-  if(NULL == colon)
-  {
-    (*uri)->host = strdup((*uri)->host_and_port);
-    /*if(0 == strcasecmp("http", uri->scheme))
-    {
-      uri->port = 80;
-      asprintf(&(uri->host_and_port_for_connecting), "%s:80", uri->host_and_port);
-    }
-    else if(0 == strcasecmp("https", uri->scheme))
-    {
-      uri->port = 443;
-      asprintf(&(uri->host_and_port_for_connecting), "%s:443", uri->host_and_port);
-    }
-    else
-    {
-      PRINT_INFO("no standard scheme!");
-      */(*uri)->port = 0;
-      /*uri->host_and_port_for_connecting = strdup(uri->host_and_port);
-    }*/
-    return 0;
-  }
-
-  port = atoi(colon  + 1);
-  if(port<1 || port >= 256 * 256)
-  {
-    free_uri(*uri);
-    return -100;
-  }
-  (*uri)->port = port;
-  asprintf(&((*uri)->host), "%.*s", (int)(colon - (*uri)->host_and_port), (*uri)->host_and_port);
-
-  return 0;
-}
-
-
-static bool
-store_in_buffer(const void *src, size_t src_size, void **dst, size_t *dst_size)
-{
-  if(0 == src_size)
-    return true;
-
-  if(NULL == *dst)
-		*dst = malloc(src_size);
-	else
-		*dst = realloc(*dst, src_size + *dst_size);
-	if(NULL == *dst)
-		return false;
-
-	memcpy(*dst + *dst_size, src, src_size);
-	*dst_size += src_size;
-
-  return true;
-}
-
-
-static ssize_t
-get_from_buffer(void **src, size_t *src_size, void *dst, size_t max_size)
-{
-  size_t ret;
-  void *newbody;
-
-	if(max_size >= *src_size)
-	{
-		ret = *src_size;
-		newbody = NULL;
-	}
-	else
-	{
-		ret = max_size;
-		if(NULL == (newbody = malloc(*src_size - max_size)))
-			return -1;
-		memcpy(newbody, *src + ret, *src_size - ret);
-	}
-	memcpy(dst, *src, ret);
-	free(*src);
-	*src = newbody;
-	*src_size -= ret;
-
-  return ret;
-}
-
-
-static void
-catch_signal(int signal)
-{
-  (void)signal;
-
-  loop = 0;
-}
-
-static void
-new_session_cb (void * cls,
-							struct SPDY_Session * session)
-{
-  (void)cls;
-
-  bool *session_alive;
-
-  PRINT_VERBOSE("new session");
-  //TODO clean this memory
-  if(NULL == (session_alive = malloc(sizeof(bool))))
-  {
-			DIE("no memory");
-  }
-  *session_alive = true;
-  SPDY_set_cls_to_session(session,
-						session_alive);
-}
-
-static void
-session_closed_cb (void * cls,
-								struct SPDY_Session * session,
-								int by_client)
-{
-  (void)cls;
-
-  bool *session_alive;
-
-  PRINT_VERBOSE2("session closed; by client: %i", by_client);
-
-  session_alive = SPDY_get_cls_from_session(session);
-  assert(NULL != session_alive);
-
-  *session_alive = false;
-}
-
-
-static int
-spdy_post_data_cb (void * cls,
-					 struct SPDY_Request *request,
-					 const void * buf,
-					 size_t size,
-					 bool more)
-{
-  (void)cls;
-  int ret;
-	struct Proxy *proxy = (struct Proxy *)SPDY_get_cls_from_request(request);
-
-  if(!store_in_buffer(buf, size, &proxy->received_body, &proxy->received_body_size))
-	{
-		PRINT_INFO("not enough memory (malloc/realloc returned NULL)");
-		return 0;
-	}
-
-  proxy->receiving_done = !more;
-
-  PRINT_VERBOSE2("POST bytes from SPDY: %zu", size);
-
-  call_curl_run = true;
-
-  if(proxy->is_curl_read_paused)
-  {
-    if(CURLE_OK != (ret = curl_easy_pause(proxy->curl_handle, CURLPAUSE_CONT)))
-    {
-      PRINT_INFO2("curl_easy_pause returned %i", ret);
-      abort();
-    }
-    PRINT_VERBOSE("curl_read_cb pause resumed");
-  }
-
-  return SPDY_YES;
-}
-
-
-ssize_t
-response_callback (void *cls,
-						void *buffer,
-						size_t max,
-						bool *more)
-{
-	ssize_t ret;
-	struct Proxy *proxy = (struct Proxy *)cls;
-
-  *more = true;
-
-  assert(!proxy->spdy_error);
-
-  if(proxy->curl_error)
-  {
-    PRINT_VERBOSE("tell spdy about the error");
-    return -1;
-  }
-
-	if(!proxy->http_body_size)//nothing to write now
-  {
-    PRINT_VERBOSE("nothing to write now");
-    if(proxy->curl_done || proxy->curl_error) *more = false;
-		return 0;
-  }
-
-  ret = get_from_buffer(&(proxy->http_body), &(proxy->http_body_size), buffer, max);
-  if(ret < 0)
-  {
-    PRINT_INFO("no memory");
-    //TODO error?
-    return -1;
-  }
-
-  if((proxy->curl_done || proxy->curl_error) && 0 == proxy->http_body_size) *more = false;
-
-  PRINT_VERBOSE2("given bytes to microspdy: %zd", ret);
-
-	return ret;
-}
-
-
-static void
-cleanup(struct Proxy *proxy)
-{
-  int ret;
-
-  //fprintf(stderr, "free proxy for %s\n", proxy->url);
-
-	if(CURLM_OK != (ret = curl_multi_remove_handle(multi_handle, proxy->curl_handle)))
-	{
-		PRINT_INFO2("curl_multi_remove_handle failed (%i)", ret);
-    DIE("bug in cleanup");
-	}
-  debug_num_curls--;
-  //TODO bug on ku6.com or amazon.cn
-  // after curl_multi_remove_handle returned CURLM_BAD_EASY_HANDLE
-	curl_slist_free_all(proxy->curl_headers);
-	curl_easy_cleanup(proxy->curl_handle);
-
-	free(proxy->url);
-	free(proxy);
-}
-
-
-static void
-response_done_callback(void *cls,
-						struct SPDY_Response *response,
-						struct SPDY_Request *request,
-						enum SPDY_RESPONSE_RESULT status,
-						bool streamopened)
-{
-	(void)streamopened;
-	struct Proxy *proxy = (struct Proxy *)cls;
-
-	if(SPDY_RESPONSE_RESULT_SUCCESS != status)
-	{
-    free(proxy->http_body);
-    proxy->http_body = NULL;
-    proxy->spdy_error = true;
-	}
-	cleanup(proxy);
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-}
-
-
-static size_t
-curl_header_cb(void *ptr, size_t size, size_t nmemb, void *userp)
-{
-	size_t realsize = size * nmemb;
-	struct Proxy *proxy = (struct Proxy *)userp;
-	char *line = (char *)ptr;
-	char *name;
-	char *value;
-	char *status;
-	unsigned int i;
-	unsigned int pos;
-	int ret;
-  int num_values;
-  const char * const * values;
-  bool abort_it;
-
-	//printf("curl_header_cb %s\n", line);
-  if(!*(proxy->session_alive))
-  {
-    PRINT_VERBOSE("headers received, but session is dead");
-    proxy->spdy_error = true;
-    proxy->curl_error = true;
-    return 0;
-  }
-
-  //trailer
-  if(NULL != proxy->response) return 0;
-
-	if('\r' == line[0] || '\n' == line[0])
-	{
-		//all headers were already handled; prepare spdy frames
-		if(NULL == (proxy->response = SPDY_build_response_with_callback(proxy->status,
-							proxy->status_msg,
-							proxy->version,
-							proxy->headers,
-							&response_callback,
-							proxy,
-							0)))
-							//256)))
-			DIE("no response");
-
-		SPDY_name_value_destroy(proxy->headers);
-    proxy->headers = NULL;
-		free(proxy->status_msg);
-    proxy->status_msg = NULL;
-		free(proxy->version);
-    proxy->version = NULL;
-
-		if(SPDY_YES != SPDY_queue_response(proxy->request,
-							proxy->response,
-							true,
-							false,
-							&response_done_callback,
-							proxy))
-    {
-			//DIE("no queue");
-      //TODO right?
-      proxy->spdy_error = true;
-      proxy->curl_error = true;
-      PRINT_VERBOSE2("no queue in curl_header_cb for %s", proxy->url);
-      SPDY_destroy_response(proxy->response);
-      proxy->response = NULL;
-      return 0;
-    }
-
-    call_spdy_run = true;
-
-		return realsize;
-	}
-
-	pos = 0;
-	if(NULL == proxy->version)
-	{
-		//first line from headers
-		//version
-		for(i=pos; i<realsize && ' '!=line[i]; ++i);
-		if(i == realsize)
-			DIE("error on parsing headers");
-		if(NULL == (proxy->version = strndup(line, i - pos)))
-        DIE("No memory");
-		pos = i+1;
-
-		//status (number)
-		for(i=pos; i<realsize && ' '!=line[i] && '\r'!=line[i] && '\n'!=line[i]; ++i);
-		if(NULL == (status = strndup(&(line[pos]), i - pos)))
-        DIE("No memory");
-		proxy->status = atoi(status);
-		free(status);
-		if(i<realsize && '\r'!=line[i] && '\n'!=line[i])
-		{
-			//status (message)
-			pos = i+1;
-			for(i=pos; i<realsize && '\r'!=line[i] && '\n'!=line[i]; ++i);
-			if(NULL == (proxy->status_msg = strndup(&(line[pos]), i - pos)))
-        DIE("No memory");
-		}
-    PRINT_VERBOSE2("Header line received '%s' '%i' '%s' ", proxy->version, proxy->status, proxy->status_msg);
-		return realsize;
-	}
-
-	//other lines
-	//header name
-	for(i=pos; i<realsize && ':'!=line[i] && '\r'!=line[i] && '\n'!=line[i]; ++i)
-		line[i] = tolower(line[i]); //spdy requires lower case
-	if(NULL == (name = strndup(line, i - pos)))
-        DIE("No memory");
-	if(0 == strcmp(SPDY_HTTP_HEADER_CONNECTION, name)
-		|| 0 == strcmp(SPDY_HTTP_HEADER_KEEP_ALIVE, name)
-		|| 0 == strcmp(SPDY_HTTP_HEADER_TRANSFER_ENCODING, name)
-    )
-	{
-		//forbidden in spdy, ignore
-		free(name);
-		return realsize;
-	}
-	if(i == realsize || '\r'==line[i] || '\n'==line[i])
-	{
-		//no value. is it possible?
-		if(SPDY_YES != SPDY_name_value_add(proxy->headers, name, ""))
-			DIE("SPDY_name_value_add failed");
-		return realsize;
-	}
-
-	//header value
-	pos = i+1;
-	while(pos<realsize && isspace(line[pos])) ++pos; //remove leading space
-	for(i=pos; i<realsize && '\r'!=line[i] && '\n'!=line[i]; ++i);
-	if(NULL == (value = strndup(&(line[pos]), i - pos)))
-        DIE("No memory");
-  PRINT_VERBOSE2("Adding header: '%s': '%s'", name, value);
-	if(SPDY_YES != (ret = SPDY_name_value_add(proxy->headers, name, value)))
-	{
-    abort_it=true;
-    if(NULL != (values = SPDY_name_value_lookup(proxy->headers, name, &num_values)))
-      for(i=0; i<(unsigned int)num_values; ++i)
-        if(0 == strcasecmp(value, values[i]))
-        {
-          abort_it=false;
-          PRINT_VERBOSE2("header appears more than once with same value '%s: %s'", name, value);
-          break;
-        }
-
-    if(abort_it)
-    {
-      PRINT_INFO2("SPDY_name_value_add failed (%i) for '%s'", ret, name);
-      abort();
-    }
-	}
-	free(name);
-	free(value);
-
-	return realsize;
-}
-
-
-static size_t
-curl_write_cb(void *contents, size_t size, size_t nmemb, void *userp)
-{
-	size_t realsize = size * nmemb;
-	struct Proxy *proxy = (struct Proxy *)userp;
-
-	//printf("curl_write_cb %i\n", realsize);
-  if(!*(proxy->session_alive))
-  {
-    PRINT_VERBOSE("data received, but session is dead");
-      proxy->spdy_error = true;
-      proxy->curl_error = true;
-    return 0;
-  }
-
-  if(!store_in_buffer(contents, realsize, &proxy->http_body, &proxy->http_body_size))
-	{
-		PRINT_INFO("not enough memory (malloc/realloc returned NULL)");
-      proxy->curl_error = true;
-		return 0;
-	}
-  /*
-	if(NULL == proxy->http_body)
-		proxy->http_body = malloc(realsize);
-	else
-		proxy->http_body = realloc(proxy->http_body, proxy->http_body_size + realsize);
-	if(NULL == proxy->http_body)
-	{
-		PRINT_INFO("not enough memory (realloc returned NULL)");
-		return 0;
-	}
-
-	memcpy(proxy->http_body + proxy->http_body_size, contents, realsize);
-	proxy->http_body_size += realsize;
-  */
-
-  PRINT_VERBOSE2("received bytes from curl: %zu", realsize);
-
-  call_spdy_run = true;
-
-	return realsize;
-}
-
-
-static size_t
-curl_read_cb(void *ptr, size_t size, size_t nmemb, void *userp)
-{
-	ssize_t ret;
-	size_t max = size * nmemb;
-	struct Proxy *proxy = (struct Proxy *)userp;
-	//void *newbody;
-
-
-  if((proxy->receiving_done && !proxy->received_body_size) || !proxy->is_with_body_data || max < 1)
-  {
-    PRINT_VERBOSE("curl_read_cb last call");
-    return 0;
-  }
-
-  if(!*(proxy->session_alive))
-  {
-    PRINT_VERBOSE("POST is still being sent, but session is dead");
-    return CURL_READFUNC_ABORT;
-  }
-
-	if(!proxy->received_body_size)//nothing to write now
-  {
-    PRINT_VERBOSE("curl_read_cb called paused");
-    proxy->is_curl_read_paused = true;
-		return CURL_READFUNC_PAUSE;//TODO curl pause should be used
-  }
-
-  ret = get_from_buffer(&(proxy->received_body), &(proxy->received_body_size), ptr, max);
-  if(ret < 0)
-  {
-    PRINT_INFO("no memory");
-    return CURL_READFUNC_ABORT;
-  }
-
-	/*
-	if(max >= proxy->received_body_size)
-	{
-		ret = proxy->received_body_size;
-		newbody = NULL;
-	}
-	else
-	{
-		ret = max;
-		if(NULL == (newbody = malloc(proxy->received_body_size - max)))
-		{
-			PRINT_INFO("no memory");
-			return CURL_READFUNC_ABORT;
-		}
-		memcpy(newbody, proxy->received_body + max, proxy->received_body_size - max);
-	}
-	memcpy(ptr, proxy->received_body, ret);
-	free(proxy->received_body);
-	proxy->received_body = newbody;
-	proxy->received_body_size -= ret;
-  * */
-
-  PRINT_VERBOSE2("given POST bytes to curl: %zd", ret);
-
-	return ret;
-}
-
-
-static int
-iterate_cb (void *cls, const char *name, const char * const * value, int num_values)
-{
-	struct Proxy *proxy = (struct Proxy *)cls;
-  struct curl_slist **curl_headers = (&(proxy->curl_headers));
-  char *line;
-  int line_len = strlen(name) + 3; //+ ": \0"
-  int i;
-
-  for(i=0; i<num_values; ++i)
-  {
-		if(i) line_len += 2; //", "
-		line_len += strlen(value[i]);
-	}
-
-	if(NULL == (line = malloc(line_len)))//no recovery
-    DIE("No memory");
-	line[0] = 0;
-
-  strcat(line, name);
-  strcat(line, ": ");
-  //all spdy header names are lower case;
-  //for simplicity here we just capitalize the first letter
-  line[0] = toupper(line[0]);
-
-	for(i=0; i<num_values; ++i)
-	{
-		if(i) strcat(line, ", ");
-  PRINT_VERBOSE2("Adding request header: '%s' len %ld", value[i], strlen(value[i]));
-		strcat(line, value[i]);
-	}
-  PRINT_VERBOSE2("Adding request header: '%s'", line);
-  if(NULL == (*curl_headers = curl_slist_append(*curl_headers, line)))
-		DIE("curl_slist_append failed");
-	free(line);
-
-	return SPDY_YES;
-}
-
-
-static void
-standard_request_handler(void *cls,
-                        struct SPDY_Request * request,
-                        uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-                        struct SPDY_NameValue * headers,
-                        bool more)
-{
-	(void)cls;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-
-	struct Proxy *proxy;
-	int ret;
-  struct URI *uri;
-  struct SPDY_Session *session;
-
-  proxy = SPDY_get_cls_from_request(request);
-  if(NULL != proxy)
-  {
-    //ignore trailers or more headers
-    return;
-  }
-
-	PRINT_VERBOSE2("received request for '%s %s %s'\n", method, path, version);
-
-  //TODO not freed once in a while
-	if(NULL == (proxy = malloc(sizeof(struct Proxy))))
-    DIE("No memory");
-	memset(proxy, 0, sizeof(struct Proxy));
-
-  //fprintf(stderr, "new  proxy for %s\n", path);
-
-  session = SPDY_get_session_for_request(request);
-  assert(NULL != session);
-  proxy->session_alive = SPDY_get_cls_from_session(session);
-  assert(NULL != proxy->session_alive);
-
-  SPDY_set_cls_to_request(request, proxy);
-
-	proxy->request = request;
-	proxy->is_with_body_data = more;
-	if(NULL == (proxy->headers = SPDY_name_value_create()))
-        DIE("No memory");
-
-  if(glob_opt.transparent)
-  {
-    if(NULL != glob_opt.http_backend) //use always same host
-      ret = asprintf(&(proxy->url),"%s://%s%s", scheme, glob_opt.http_backend, path);
-    else //use host header
-      ret = asprintf(&(proxy->url),"%s://%s%s", scheme, host, path);
-    if(-1 == ret)
-        DIE("No memory");
-
-    ret = parse_uri(&uri_preg, proxy->url, &uri);
-    if(ret != 0)
-      DIE("parsing built uri failed");
-  }
-  else
-  {
-    ret = parse_uri(&uri_preg, path, &uri);
-    PRINT_INFO2("path %s '%s' '%s'", path, uri->scheme, uri->host);
-    if(ret != 0 || !strlen(uri->scheme) || !strlen(uri->host))
-      DIE("parsing received uri failed");
-
-    if(NULL != glob_opt.http_backend) //use backend host
-    {
-      ret = asprintf(&(proxy->url),"%s://%s%s", uri->scheme, glob_opt.http_backend, uri->path_and_more);
-      if(-1 == ret)
-        DIE("No memory");
-    }
-    else //use request path
-      if(NULL == (proxy->url = strdup(path)))
-        DIE("No memory");
-  }
-
-  free_uri(uri);
-
-  PRINT_VERBOSE2("curl will request '%s'", proxy->url);
-
-  SPDY_name_value_iterate(headers, &iterate_cb, proxy);
-
-	if(NULL == (proxy->curl_handle = curl_easy_init()))
-    {
-		PRINT_INFO("curl_easy_init failed");
-		abort();
-	}
-
-	if(glob_opt.curl_verbose)
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_VERBOSE, 1);
-
-  if(0 == strcmp(SPDY_HTTP_METHOD_POST,method))
-  {
-    if(NULL == (proxy->curl_headers = curl_slist_append(proxy->curl_headers, "Expect:")))
-      DIE("curl_slist_append failed");
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_POST, 1);
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_READFUNCTION, curl_read_cb);
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_READDATA, proxy);
-  }
-
-  if(glob_opt.timeout)
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_TIMEOUT, glob_opt.timeout);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_URL, proxy->url);
-	if(glob_opt.http10)
-		CURL_SETOPT(proxy->curl_handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_WRITEFUNCTION, curl_write_cb);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_WRITEDATA, proxy);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_HEADERFUNCTION, curl_header_cb);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_HEADERDATA, proxy);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_PRIVATE, proxy);
-	CURL_SETOPT(proxy->curl_handle, CURLOPT_HTTPHEADER, proxy->curl_headers);
-  CURL_SETOPT(proxy->curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);//TODO
-  CURL_SETOPT(proxy->curl_handle, CURLOPT_SSL_VERIFYHOST, 0L);
-  if(glob_opt.ipv4 && !glob_opt.ipv6)
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
-  else if(glob_opt.ipv6 && !glob_opt.ipv4)
-    CURL_SETOPT(proxy->curl_handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
-
-	if(CURLM_OK != (ret = curl_multi_add_handle(multi_handle, proxy->curl_handle)))
-	{
-		PRINT_INFO2("curl_multi_add_handle failed (%i)", ret);
-		abort();
-	}
-  debug_num_curls++;
-
-  //~5ms additional latency for calling this
-	if(CURLM_OK != (ret = curl_multi_perform(multi_handle, &still_running))
-		&& CURLM_CALL_MULTI_PERFORM != ret)
-	{
-		PRINT_INFO2("curl_multi_perform failed (%i)", ret);
-		abort();
-	}
-
-  call_curl_run = true;
-}
-
-
-static int
-run ()
-{
-  unsigned long long timeoutlong = 0;
-  unsigned long long timeout_spdy = 0;
-  long timeout_curl = -1;
-	struct timeval timeout;
-	int ret;
-	int ret_curl;
-	int ret_spdy;
-	fd_set rs;
-	fd_set ws;
-	fd_set es;
-	int maxfd = -1;
-	int maxfd_curl = -1;
-	struct SPDY_Daemon *daemon;
-  CURLMsg *msg;
-  int msgs_left;
-  struct Proxy *proxy;
-  struct sockaddr_in *addr;
-  struct addrinfo hints;
-  char service[NI_MAXSERV];
-  struct addrinfo *gai;
-  enum SPDY_IO_SUBSYSTEM io = glob_opt.notls ? SPDY_IO_SUBSYSTEM_RAW : SPDY_IO_SUBSYSTEM_OPENSSL;
-  enum SPDY_DAEMON_FLAG flags = SPDY_DAEMON_FLAG_NO;
-  //struct SPDY_Response *error_response;
-  char *curl_private;
-
-	signal(SIGPIPE, SIG_IGN);
-
-  if (signal(SIGINT, catch_signal) == SIG_ERR)
-    PRINT_VERBOSE("signal failed");
-
-  srand(time(NULL));
-  if(init_parse_uri(&uri_preg))
-    DIE("Regexp compilation failed");
-
-	SPDY_init();
-
-  if(glob_opt.nodelay)
-    flags |= SPDY_DAEMON_FLAG_NO_DELAY;
-
-  if(NULL == glob_opt.listen_host)
-	{
-    daemon = SPDY_start_daemon(glob_opt.listen_port,
-								glob_opt.cert,
-								glob_opt.cert_key,
-								&new_session_cb,
-								&session_closed_cb,
-								&standard_request_handler,
-								&spdy_post_data_cb,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								1800,
-                SPDY_DAEMON_OPTION_IO_SUBSYSTEM,
-                io,
-                SPDY_DAEMON_OPTION_FLAGS,
-                flags,
-								SPDY_DAEMON_OPTION_END);
-  }
-  else
-  {
-    snprintf (service, sizeof(service), "%u", glob_opt.listen_port);
-    memset (&hints, 0, sizeof(struct addrinfo));
-    hints.ai_family = AF_INET;
-    hints.ai_socktype = SOCK_STREAM;
-
-    ret = getaddrinfo(glob_opt.listen_host, service, &hints, &gai);
-    if(ret != 0)
-      DIE("problem with specified host");
-
-    addr = (struct sockaddr_in *) gai->ai_addr;
-
-    daemon = SPDY_start_daemon(0,
-								glob_opt.cert,
-								glob_opt.cert_key,
-								&new_session_cb,
-								&session_closed_cb,
-								&standard_request_handler,
-								&spdy_post_data_cb,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								1800,
-                SPDY_DAEMON_OPTION_IO_SUBSYSTEM,
-                io,
-                SPDY_DAEMON_OPTION_FLAGS,
-                flags,
-                SPDY_DAEMON_OPTION_SOCK_ADDR,
-                addr,
-                //SPDY_DAEMON_OPTION_MAX_NUM_FRAMES,
-                //1,
-								SPDY_DAEMON_OPTION_END);
-  }
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	multi_handle = curl_multi_init();
-	if(NULL==multi_handle)
-		DIE("no multi_handle");
-
-	timeout.tv_usec = 0;
-
-	do
-	{
-		FD_ZERO(&rs);
-		FD_ZERO(&ws);
-		FD_ZERO(&es);
-
-    PRINT_VERBOSE2("num  curls %i", debug_num_curls);
-
-    ret_spdy = SPDY_get_timeout(daemon, &timeout_spdy);
-    if(SPDY_NO == ret_spdy || timeout_spdy > 5000)
-      timeoutlong = 5000;
-    else
-      timeoutlong = timeout_spdy;
-    PRINT_VERBOSE2("SPDY timeout %lld; %i", timeout_spdy, ret_spdy);
-
-    if(CURLM_OK != (ret_curl = curl_multi_timeout(multi_handle, &timeout_curl)))
-    {
-      PRINT_VERBOSE2("curl_multi_timeout failed (%i)", ret_curl);
-      //curl_timeo = timeoutlong;
-    }
-    else if(timeout_curl >= 0 && timeoutlong > (unsigned long)timeout_curl)
-      timeoutlong = (unsigned long)timeout_curl;
-
-    PRINT_VERBOSE2("curl timeout %ld", timeout_curl);
-
-    timeout.tv_sec = timeoutlong / 1000;
-		timeout.tv_usec = (timeoutlong % 1000) * 1000;
-
-		maxfd = SPDY_get_fdset (daemon,
-								&rs,
-								&ws,
-								&es);
-		assert(-1 != maxfd);
-
-		if(CURLM_OK != (ret = curl_multi_fdset(multi_handle, &rs,
-								&ws,
-								&es, &maxfd_curl)))
-		{
-			PRINT_INFO2("curl_multi_fdset failed (%i)", ret);
-			abort();
-		}
-
-    if(maxfd_curl > maxfd)
-      maxfd = maxfd_curl;
-
-    PRINT_VERBOSE2("timeout before %lld %lld", (unsigned long long)timeout.tv_sec, (unsigned long long)timeout.tv_usec);
-    ret = select(maxfd+1, &rs, &ws, &es, &timeout);
-    PRINT_VERBOSE2("timeout after %lld %lld; ret is %i", (unsigned long long)timeout.tv_sec, (unsigned long long)timeout.tv_usec, ret);
-
-		/*switch(ret) {
-			case -1:
-				PRINT_INFO2("select error: %i", errno);
-				break;
-			case 0:
-				break;
-			default:*/
-
-      //the second part should not happen with current implementation
-      if(ret > 0 || (SPDY_YES == ret_spdy && 0 == timeout_spdy))
-      {
-				PRINT_VERBOSE("run spdy");
-				SPDY_run(daemon);
-        call_spdy_run = false;
-      }
-
-      //if(ret > 0 || (CURLM_OK == ret_curl && 0 == timeout_curl) || call_curl_run)
-      {
-				PRINT_VERBOSE("run curl");
-				if(CURLM_OK != (ret = curl_multi_perform(multi_handle, &still_running))
-					&& CURLM_CALL_MULTI_PERFORM != ret)
-				{
-					PRINT_INFO2("curl_multi_perform failed (%i)", ret);
-					abort();
-				}
-        call_curl_run = false;
-      }
-			/*break;
-		}*/
-
-    while ((msg = curl_multi_info_read(multi_handle, &msgs_left))) {
-      if (msg->msg == CURLMSG_DONE) {
-        PRINT_VERBOSE("A curl handler is done");
-        if(CURLE_OK != (ret = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &curl_private)))
-        {
-          PRINT_INFO2("err %i",ret);
-          abort();
-        }
-        assert(NULL != curl_private);
-        proxy = (struct Proxy *)curl_private;
-        if(CURLE_OK == msg->data.result)
-        {
-          proxy->curl_done = true;
-          call_spdy_run = true;
-          //TODO what happens with proxy when the client resets a stream
-          //and response_done is not yet set for the last frame? is it
-          //possible?
-        }
-        else
-        {
-          PRINT_VERBOSE2("bad curl result (%i) for '%s'", msg->data.result, proxy->url);
-          if(proxy->spdy_done || proxy->spdy_error || (NULL == proxy->response && !*(proxy->session_alive)))
-          {
-            PRINT_VERBOSE("cleaning");
-            SPDY_name_value_destroy(proxy->headers);
-            SPDY_destroy_request(proxy->request);
-            SPDY_destroy_response(proxy->response);
-            cleanup(proxy);
-          }
-          else if(NULL == proxy->response && *(proxy->session_alive))
-          {
-            //generate error for the client
-            PRINT_VERBOSE("will send Bad Gateway");
-            SPDY_name_value_destroy(proxy->headers);
-            proxy->headers = NULL;
-            if(NULL == (proxy->response = SPDY_build_response(SPDY_HTTP_BAD_GATEWAY,
-                  NULL,
-                  SPDY_HTTP_VERSION_1_1,
-                  NULL,
-                  ERROR_RESPONSE,
-                  strlen(ERROR_RESPONSE))))
-              DIE("no response");
-            if(SPDY_YES != SPDY_queue_response(proxy->request,
-                      proxy->response,
-                      true,
-                      false,
-                      &response_done_callback,
-                      proxy))
-            {
-              //clean and forget
-              PRINT_VERBOSE("cleaning");
-              SPDY_destroy_request(proxy->request);
-              SPDY_destroy_response(proxy->response);
-              cleanup(proxy);
-            }
-          }
-          else
-          {
-            proxy->curl_error = true;
-          }
-          call_spdy_run = true;
-          //TODO spdy should be notified to send RST_STREAM
-        }
-      }
-      else PRINT_INFO("shouldn't happen");
-    }
-
-    if(call_spdy_run)
-    {
-      PRINT_VERBOSE("second call to SPDY_run");
-      SPDY_run(daemon);
-      call_spdy_run = false;
-    }
-
-    if(glob_opt.verbose)
-    {
-
-#ifdef HAVE_CLOCK_GETTIME
-#ifdef CLOCK_MONOTONIC
-    struct timespec ts;
-
-    if (0 == clock_gettime(CLOCK_MONOTONIC, &ts))
-    PRINT_VERBOSE2 ("time now %lld %lld",
-		    (unsigned long long) ts.tv_sec,
-		    (unsigned long long) ts.tv_nsec);
-#endif
-#endif
-    }
-
-  }
-  while(loop);
-
-	SPDY_stop_daemon(daemon);
-
-	curl_multi_cleanup(multi_handle);
-
-	SPDY_deinit();
-
-  deinit_parse_uri(&uri_preg);
-
-	return 0;
-}
-
-
-static void
-display_usage()
-{
-  printf(
-    "Usage: microspdy2http -p <PORT> [-c <CERTIFICATE>] [-k <CERT-KEY>]\n"
-    "                      [-rvh0DtT] [-b <HTTP-SERVER>] [-l <HOST>]\n\n"
-    "OPTIONS:\n"
-    "    -p, --port            Listening port.\n"
-    "    -l, --host            Listening host. If not set, will listen on [::]\n"
-    "    -c, --certificate     Path to a certificate file. Requiered if\n"
-    "                          --no-tls is not set.\n"
-    "    -k, --certificate-key Path to a key file for the certificate.\n"
-    "                          Requiered if --no-tls is not set.\n"
-    "    -b, --backend-server  If set, the proxy will connect always to it.\n"
-    "                          Otherwise the proxy will connect to the URL\n"
-    "                          which is specified in the path or 'Host:'.\n"
-    "    -v, --verbose         Print debug information.\n"
-    "    -r, --no-tls          Do not use TLS. Client must use SPDY/3.\n"
-    "    -h, --curl-verbose    Print debug information for curl.\n"
-    "    -0, --http10          Prefer HTTP/1.0 connections to the next hop.\n"
-    "    -D, --no-delay        This makes sense only if --no-tls is used.\n"
-    "                          TCP_NODELAY will be used for all sessions' sockets.\n"
-    "    -4, --curl-ipv4       Curl may use IPv4 to connect to the final destination.\n"
-    "    -6, --curl-ipv6       Curl may use IPv6 to connect to the final destination.\n"
-    "                          If neither --curl-ipv4 nor --curl-ipv6 is set,\n"
-    "                          both will be used by default.\n"
-    "    -T, --timeout         Maximum time in seconds for each HTTP transfer.\n"
-    "                          Use 0 for no timeout; this is the default value.\n"
-    "    -t, --transparent     If set, the proxy will fetch an URL which\n"
-    "                          is based on 'Host:' header and requested path.\n"
-    "                          Otherwise, full URL in the requested path is required.\n\n"
-
-  );
-}
-
-
-int
-main (int argc, char *const *argv)
-{
-
-  int getopt_ret;
-  int option_index;
-  struct option long_options[] = {
-    {"port",  required_argument, 0, 'p'},
-    {"certificate",  required_argument, 0, 'c'},
-    {"certificate-key",  required_argument, 0, 'k'},
-    {"backend-server",  required_argument, 0, 'b'},
-    {"no-tls",  no_argument, 0, 'r'},
-    {"verbose",  no_argument, 0, 'v'},
-    {"curl-verbose",  no_argument, 0, 'h'},
-    {"http10",  no_argument, 0, '0'},
-    {"no-delay",  no_argument, 0, 'D'},
-    {"transparent",  no_argument, 0, 't'},
-    {"curl-ipv4",  no_argument, 0, '4'},
-    {"curl-ipv6",  no_argument, 0, '6'},
-    {"timeout",  required_argument, 0, 'T'},
-    {0, 0, 0, 0}
-  };
-
-  while (1)
-  {
-    getopt_ret = getopt_long( argc, argv, "p:l:c:k:b:rv0Dth46T:", long_options, &option_index);
-    if (getopt_ret == -1)
-      break;
-
-    switch(getopt_ret)
-    {
-      case 'p':
-        glob_opt.listen_port = atoi(optarg);
-        break;
-
-      case 'l':
-        glob_opt.listen_host= strdup(optarg);
-        if(NULL == glob_opt.listen_host)
-          return 1;
-        break;
-
-      case 'c':
-        glob_opt.cert = strdup(optarg);
-        break;
-
-      case 'k':
-        glob_opt.cert_key = strdup(optarg);
-        break;
-
-      case 'b':
-        glob_opt.http_backend = strdup(optarg);
-        if(NULL == glob_opt.http_backend)
-          return 1;
-        break;
-
-      case 'r':
-        glob_opt.notls = true;
-        break;
-
-      case 'v':
-        glob_opt.verbose = true;
-        break;
-
-      case 'h':
-        glob_opt.curl_verbose = true;
-        break;
-
-      case '0':
-        glob_opt.http10 = true;
-        break;
-
-      case 'D':
-        glob_opt.nodelay = true;
-        break;
-
-      case 't':
-        glob_opt.transparent = true;
-        break;
-
-      case '4':
-        glob_opt.ipv4 = true;
-        break;
-
-      case '6':
-        glob_opt.ipv6 = true;
-        break;
-
-      case 'T':
-        glob_opt.timeout = atoi(optarg);
-        break;
-
-      case 0:
-        PRINT_INFO("0 from getopt");
-        break;
-
-      case '?':
-        display_usage();
-        return 1;
-
-      default:
-        DIE("default from getopt");
-    }
-  }
-
-  if(
-    0 == glob_opt.listen_port
-    || (!glob_opt.notls && (NULL == glob_opt.cert || NULL == glob_opt.cert_key))
-    //|| !glob_opt.transparent && NULL != glob_opt.http_backend
-    )
-  {
-    display_usage();
-    return 1;
-  }
-
-  return run();
-}
-
diff --git a/src/testcurl/.gitignore b/src/testcurl/.gitignore
new file mode 100644
index 0000000..fde1485
--- /dev/null
+++ b/src/testcurl/.gitignore
@@ -0,0 +1,182 @@
+/test_concurrent_stop
+/libcurl_version_check.a
+/test_quiesce
+/test_urlparse
+/test_timeout
+/test_termination
+/test_put_chunked
+/test_put11
+/test_put
+/test_process_headers
+/test_process_arguments
+/test_postform11
+/test_postform
+/test_post_loop11
+/test_post_loop
+/test_post11
+/test_post
+/test_parse_cookies
+/test_options
+/test_long_header11
+/test_long_header
+/test_large_put11
+/test_large_put
+/test_iplimit11
+/test_get_sendfile11
+/test_get_sendfile
+/test_get_close
+/test_get_close10
+/test_get_keep_alive
+/test_get_keep_alive10
+/test_get_response_cleanup
+/test_get_chunked
+/test_get_chunked_close
+/test_get_chunked_string
+/test_get_chunked_close_string
+/test_get_chunked_empty
+/test_get_chunked_close_empty
+/test_get_chunked_string_empty
+/test_get_chunked_close_string_empty
+/test_get_chunked_sized
+/test_get_chunked_close_sized
+/test_get_chunked_empty_sized
+/test_get_chunked_close_empty_sized
+/test_get_chunked_forced
+/test_get_chunked_close_forced
+/test_get_chunked_empty_forced
+/test_get_chunked_close_empty_forced
+/test_get11
+/test_get
+/test_digestauth_with_arguments
+/test_digestauth
+/daemontest_digestauth_with_arguments
+/test_start_stop
+/daemontest_urlparse
+/daemontest_get_response_cleanup
+/test_callback
+/perf_get_concurrent
+/perf_get
+/daemontest_timeout.gcno
+/daemontest_timeout.gcda
+/daemontest_termination.gcno
+/daemontest_termination.gcda
+/daemontest_get_sendfile.gcno
+/daemontest_get_sendfile.gcda
+/daemontest_digestauth.gcno
+/daemontest_digestauth.gcda
+/daemontest_digestauth
+/daemontest_timeout
+/daemontest_get_sendfile11
+/daemontest_get_sendfile
+/daemontest_iplimit.gcno
+/daemontest_iplimit.gcda
+/daemontest_termination
+/daemontest_iplimit11
+/daemontest_long_header.gcda
+/daemontest_process_headers.gcda
+/daemontest_large_put.gcno
+/daemontest_postform.gcno
+/daemontest_put_chunked.gcno
+/daemontest_post_loop.gcno
+/daemontest_get_chunked.gcno
+/daemontest_post.gcno
+/daemontest_parse_cookies.gcno
+/daemontest_large_put.gcda
+/daemontest_process_arguments.gcno
+/daemon_options_test
+/daemontest_put.gcno
+/daemontest_get.gcno
+/daemontest_postform.gcda
+/daemontest_put_chunked.gcda
+/curl_version_check.gcno
+/daemontest_process_headers
+/daemontest_long_header11
+/daemontest_post_loop.gcda
+/daemontest_get_chunked.gcda
+/daemontest_post.gcda
+/daemontest_parse_cookies.gcda
+/daemontest_long_header.gcno
+/daemontest_process_headers.gcno
+/daemontest_process_arguments.gcda
+/daemontest_process_arguments
+/daemontest_put.gcda
+/daemontest_get.gcda
+/daemon_options_test.gcno
+/curl_version_check.gcda
+/daemontest_process_arguments.c
+/daemontest_parse_cookies
+/daemontest_put11
+/daemontest_put_chunked
+/daemontest_put
+/daemontest_large_put11
+/daemontest_postform11
+/daemontest_postform
+/daemontest_post
+/daemontest_large_put
+/daemontest_get
+/daemontest_post_loop11
+/daemontest_post11
+/daemontest_get_chunked
+/daemontest_long_header
+/daemontest_post_loop
+/daemontest_get11
+*.exe
+test_quiesce_stream
+test_large_put_inc11
+/test_deletetest_digestauth_sha256
+test_delete
+test_digestauth_sha256
+perf_get_concurrent11
+test_get_empty
+test_patch
+test_patch11
+/test_add_conn
+/test_add_conn_nolisten
+/test_add_conn_cleanup
+/test_add_conn_cleanup_nolisten
+core
+/test_get_iovec
+/test_get_iovec11
+/test_get_wait
+/test_get_wait11
+/test_toolarge_method
+/test_toolarge_url
+/test_toolarge_request_header_name
+/test_toolarge_request_header_value
+/test_toolarge_request_headers
+/test_toolarge_reply_header_name
+/test_toolarge_reply_header_value
+/test_toolarge_reply_headers
+/test_tricky_url
+/test_tricky_header2
+/test_digestauth_concurrent
+/test_basicauth
+/test_parse_cookies_invalid
+/test_basicauth_preauth
+/test_basicauth_oldapi
+/test_basicauth_preauth_oldapi
+/test_digestauth_emu_ext
+/test_digestauth_emu_ext_oldapi
+/test_digestauth2
+/test_digestauth2_rfc2069
+/test_digestauth2_rfc2069_userdigest
+/test_digestauth2_oldapi1
+/test_digestauth2_oldapi2
+/test_digestauth2_userhash
+/test_digestauth2_sha256
+/test_digestauth2_sha256_userhash
+/test_digestauth2_oldapi2_sha256
+/test_digestauth2_userdigest
+/test_digestauth2_oldapi1_userdigest
+/test_digestauth2_oldapi2_userdigest
+/test_digestauth2_userhash_userdigest
+/test_digestauth2_sha256_userdigest
+/test_digestauth2_oldapi2_sha256_userdigest
+/test_digestauth2_sha256_userhash_userdigest
+/test_digestauth2_bind_all
+/test_digestauth2_bind_uri
+/test_digestauth2_oldapi1_bind_all
+/test_digestauth2_oldapi1_bind_uri
+test_*[a-z0-9_][a-z0-9_][a-z0-9_]
+!*.c
+!*.h
diff --git a/src/testcurl/Makefile.am b/src/testcurl/Makefile.am
index eb165bd..834c077 100644
--- a/src/testcurl/Makefile.am
+++ b/src/testcurl/Makefile.am
@@ -1,63 +1,166 @@
 # This Makefile.am is in the public domain
-SUBDIRS  = .
+EMPTY_ITEM =
+
+@HEAVY_TESTS_NOTPARALLEL@
+
+SUBDIRS = .
+
+AM_CPPFLAGS = \
+  -I$(top_srcdir)/src/include \
+  -I$(top_srcdir)/src/microhttpd \
+  -DMHD_CPU_COUNT=$(CPU_COUNT) \
+  $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS)
+
+AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@
+
+AM_LDFLAGS = $(LDFLAGS_ac)
+
+AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac)
 
 if USE_COVERAGE
-  AM_CFLAGS = -fprofile-arcs -ftest-coverage
+  AM_CFLAGS += -fprofile-arcs -ftest-coverage
 endif
 
 if ENABLE_HTTPS
   SUBDIRS += https
 endif
 
-AM_CPPFLAGS = \
--DCPU_COUNT=$(CPU_COUNT) \
--I$(top_srcdir) \
--I$(top_srcdir)/src/microhttpd \
--I$(top_srcdir)/src/include \
-$(LIBCURL_CPPFLAGS)
+LDADD = \
+  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
+  @LIBCURL@
 
-if !HAVE_W32
-PERF_GET_CONCURRENT=perf_get_concurrent
-TEST_CONCURRENT_STOP=test_concurrent_stop
-if HAVE_CURL_BINARY
-CURL_FORK_TEST = test_get_response_cleanup
-endif
-endif
+$(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile
+	@echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \
+	$(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la
 
-if HAVE_CURL
-check_PROGRAMS = \
-  test_start_stop \
-  test_get \
-  test_get_sendfile \
+THREAD_ONLY_TESTS = \
   test_urlparse \
-  test_put \
-  $(TEST_CONCURRENT_STOP) \
-  test_process_headers \
-  test_process_arguments \
-  test_parse_cookies \
-  test_large_put \
-  test_get11 \
-  test_get_sendfile11 \
-  test_put11 \
-  test_large_put11 \
   test_long_header \
   test_long_header11 \
-  test_get_chunked \
-  test_put_chunked \
   test_iplimit11 \
   test_termination \
+  $(EMPTY_ITEM)
+
+if HEAVY_TESTS
+THREAD_ONLY_TESTS += \
+  test_add_conn_cleanup \
+  test_add_conn_cleanup_nolisten \
   test_timeout \
-  test_callback \
-  $(CURL_FORK_TEST) \
-  perf_get $(PERF_GET_CONCURRENT)
+  $(EMPTY_ITEM)
+endif
 
 if HAVE_POSIX_THREADS
+if HEAVY_TESTS
+THREAD_ONLY_TESTS += \
+  perf_get_concurrent11 \
+  $(EMPTY_ITEM)
+endif
+
+THREAD_ONLY_TESTS += \
+  test_get_wait \
+  test_get_wait11 \
+  test_quiesce \
+  $(EMPTY_ITEM)
+
+if HEAVY_TESTS
+THREAD_ONLY_TESTS += \
+  test_concurrent_stop \
+  $(EMPTY_ITEM)
+endif
+
+if HAVE_CURL_BINARY
+THREAD_ONLY_TESTS += \
+  test_quiesce_stream
+endif
+endif
+
+if HEAVY_TESTS
+if HAVE_POSIX_THREADS
+THREAD_ONLY_TESTS += \
+  perf_get_concurrent
+endif
+endif
+
+if RUN_LIBCURL_TESTS
+check_PROGRAMS = \
+  test_get \
+  test_head \
+  test_head10 \
+  test_get_iovec \
+  test_get_sendfile \
+  test_get_close \
+  test_get_close10 \
+  test_get_keep_alive \
+  test_get_keep_alive10 \
+  test_delete \
+  test_patch \
+  test_put \
+  test_add_conn \
+  test_add_conn_nolisten \
+  test_process_headers \
+  test_process_arguments \
+  test_toolarge_method \
+  test_toolarge_url \
+  test_toolarge_request_header_name \
+  test_toolarge_request_header_value \
+  test_toolarge_request_headers \
+  test_toolarge_reply_header_name \
+  test_toolarge_reply_header_value \
+  test_toolarge_reply_headers \
+  test_tricky_url \
+  test_tricky_header2 \
+  test_large_put \
+  test_get11 \
+  test_get_iovec11 \
+  test_get_sendfile11 \
+  test_patch11 \
+  test_put11 \
+  test_large_put11 \
+  test_large_put_inc11 \
+  test_put_broken_len10 \
+  test_put_broken_len \
+  test_get_chunked \
+  test_get_chunked_close \
+  test_get_chunked_string \
+  test_get_chunked_close_string \
+  test_get_chunked_empty \
+  test_get_chunked_close_empty \
+  test_get_chunked_string_empty \
+  test_get_chunked_close_string_empty \
+  test_get_chunked_sized \
+  test_get_chunked_close_sized \
+  test_get_chunked_empty_sized \
+  test_get_chunked_close_empty_sized \
+  test_get_chunked_forced \
+  test_get_chunked_close_forced \
+  test_get_chunked_empty_forced \
+  test_get_chunked_close_empty_forced \
+  test_put_chunked \
+  test_callback \
+  $(EMPTY_ITEM)
+
+if ENABLE_COOKIE
 check_PROGRAMS += \
-  test_quiesce
+  test_parse_cookies_discp_p2 \
+  test_parse_cookies_discp_p1 \
+  test_parse_cookies_discp_zero \
+  test_parse_cookies_discp_n2 \
+  test_parse_cookies_discp_n3
+endif
+
+if HEAVY_TESTS
+check_PROGRAMS += \
+  perf_get
+endif
+
+if ENABLE_BAUTH
+check_PROGRAMS += \
+  test_basicauth test_basicauth_preauth \
+  test_basicauth_oldapi test_basicauth_preauth_oldapi
 endif
 
 if HAVE_POSTPROCESSOR
- check_PROGRAMS += \
+check_PROGRAMS += \
   test_post \
   test_postform \
   test_post_loop \
@@ -66,245 +169,463 @@
   test_post_loop11
 endif
 
-noinst_PROGRAMS = \
-  test_options
 
 if ENABLE_DAUTH
-  check_PROGRAMS += \
-	test_digestauth test_digestauth_with_arguments
+if ENABLE_MD5
+THREAD_ONLY_TESTS += \
+  test_digestauth \
+  test_digestauth_with_arguments \
+  test_digestauth_concurrent
+endif
+if ENABLE_SHA256
+THREAD_ONLY_TESTS += \
+  test_digestauth_sha256
+endif
+
+if ENABLE_MD5
+check_PROGRAMS += \
+  test_digestauth_emu_ext \
+  test_digestauth_emu_ext_oldapi \
+  test_digestauth2 \
+  test_digestauth2_rfc2069 \
+  test_digestauth2_rfc2069_userdigest \
+  test_digestauth2_oldapi1 \
+  test_digestauth2_oldapi2 \
+  test_digestauth2_userhash \
+  test_digestauth2_userdigest \
+  test_digestauth2_oldapi1_userdigest \
+  test_digestauth2_oldapi2_userdigest \
+  test_digestauth2_userhash_userdigest \
+  test_digestauth2_bind_all \
+  test_digestauth2_bind_uri \
+  test_digestauth2_oldapi1_bind_all \
+  test_digestauth2_oldapi1_bind_uri
+endif
+if ENABLE_SHA256
+check_PROGRAMS += \
+  test_digestauth2_sha256 \
+  test_digestauth2_sha256_userhash \
+  test_digestauth2_oldapi2_sha256 \
+  test_digestauth2_sha256_userdigest \
+  test_digestauth2_oldapi2_sha256_userdigest \
+  test_digestauth2_sha256_userhash_userdigest
+endif
+endif
+
+if HEAVY_TESTS
+if HAVE_FORK_WAITPID
+if HAVE_CURL_BINARY
+check_PROGRAMS += test_get_response_cleanup
+endif
+endif
+endif
+
+if USE_POSIX_THREADS
+check_PROGRAMS += \
+  $(THREAD_ONLY_TESTS)
+endif
+if USE_W32_THREADS
+check_PROGRAMS += \
+  $(THREAD_ONLY_TESTS)
 endif
 
 TESTS = $(check_PROGRAMS)
-
-noinst_LIBRARIES = libcurl_version_check.a
 endif
 
-libcurl_version_check_a_SOURCES = \
-  curl_version_check.c
-
-test_start_stop_SOURCES = \
-  test_start_stop.c
-test_start_stop_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
 test_concurrent_stop_SOURCES = \
   test_concurrent_stop.c
+test_concurrent_stop_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
 test_concurrent_stop_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
- @LIBCURL@
-
-test_options_SOURCES = \
-  test_options.c
-test_options_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
+  $(PTHREAD_LIBS) $(LDADD)
 
 test_get_SOURCES = \
-  test_get.c
-test_get_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_get.c mhd_has_in_name.h mhd_has_param.h
+
+test_head_SOURCES = \
+  test_head.c mhd_has_in_name.h mhd_has_param.h
+
+test_head10_SOURCES = \
+  test_head.c mhd_has_in_name.h mhd_has_param.h
 
 test_quiesce_SOURCES = \
-  test_quiesce.c
+  test_quiesce.c mhd_has_param.h mhd_has_in_name.h
 test_quiesce_CFLAGS = \
-  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
 test_quiesce_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(PTHREAD_LIBS) @LIBCURL@
+  $(PTHREAD_LIBS) $(LDADD)
+
+test_quiesce_stream_SOURCES = \
+  test_quiesce_stream.c
+test_quiesce_stream_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
+test_quiesce_stream_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
 
 test_callback_SOURCES = \
   test_callback.c
-test_callback_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
 
 perf_get_SOURCES = \
   perf_get.c \
-  gauger.h
-perf_get_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  mhd_has_in_name.h
 
 perf_get_concurrent_SOURCES = \
   perf_get_concurrent.c \
-  gauger.h
+  mhd_has_in_name.h
+perf_get_concurrent_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
 perf_get_concurrent_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  $(PTHREAD_LIBS) $(LDADD)
+
+perf_get_concurrent11_SOURCES = \
+  perf_get_concurrent.c \
+  mhd_has_in_name.h
+perf_get_concurrent11_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
+perf_get_concurrent11_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
+
+test_basicauth_SOURCES = \
+  test_basicauth.c
+
+test_basicauth_preauth_SOURCES = \
+  test_basicauth.c
+
+test_basicauth_oldapi_SOURCES = \
+  test_basicauth.c
+
+test_basicauth_preauth_oldapi_SOURCES = \
+  test_basicauth.c
 
 test_digestauth_SOURCES = \
   test_digestauth.c
 test_digestauth_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
+  @LIBGCRYPT_LIBS@ $(LDADD)
+
+test_digestauth_sha256_SOURCES = \
+  test_digestauth_sha256.c
+test_digestauth_sha256_LDADD = \
+  @LIBGCRYPT_LIBS@ $(LDADD)
 
 test_digestauth_with_arguments_SOURCES = \
   test_digestauth_with_arguments.c
 test_digestauth_with_arguments_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
+  @LIBGCRYPT_LIBS@ $(LDADD)
+
+test_digestauth_concurrent_SOURCES = \
+  test_digestauth_concurrent.c
+test_digestauth_concurrent_CFLAGS = \
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
+test_digestauth_concurrent_LDADD = \
+  @LIBGCRYPT_LIBS@ $(LDADD) $(PTHREAD_LIBS) $(LDADD)
+
+test_digestauth_emu_ext_SOURCES = \
+  test_digestauth_emu_ext.c
+
+test_digestauth_emu_ext_oldapi_SOURCES = \
+  test_digestauth_emu_ext.c
+
+test_digestauth2_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_rfc2069_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_rfc2069_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi1_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi2_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_userhash_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_sha256_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi2_sha256_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_sha256_userhash_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi1_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi2_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_userhash_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_sha256_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi2_sha256_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_sha256_userhash_userdigest_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_bind_all_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_bind_uri_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi1_bind_all_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_digestauth2_oldapi1_bind_uri_SOURCES = \
+  test_digestauth2.c mhd_has_param.h mhd_has_in_name.h
+
+test_get_iovec_SOURCES = \
+  test_get_iovec.c mhd_has_in_name.h
 
 test_get_sendfile_SOURCES = \
-  test_get_sendfile.c
-test_get_sendfile_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-test_get_sendfile_DEPENDENCIES =
+  test_get_sendfile.c mhd_has_in_name.h
 
-if HAVE_W32
-test_get_sendfile_LDADD += \
- $(top_builddir)/src/platform/libplatform_interface.la
-test_get_sendfile_DEPENDENCIES += \
- $(top_builddir)/src/platform/libplatform_interface.la
-endif
+test_get_wait_SOURCES = \
+  test_get_wait.c \
+  mhd_has_in_name.h
+test_get_wait_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+test_get_wait_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
+
+test_get_wait11_SOURCES = \
+  test_get_wait.c \
+  mhd_has_in_name.h
+test_get_wait11_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+test_get_wait11_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
 
 test_urlparse_SOURCES = \
-  test_urlparse.c
-test_urlparse_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_urlparse.c mhd_has_in_name.h
 
 test_get_response_cleanup_SOURCES = \
-  test_get_response_cleanup.c
-test_get_response_cleanup_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
+  test_get_response_cleanup.c mhd_has_in_name.h
 
 test_get_chunked_SOURCES = \
-  test_get_chunked.c
-test_get_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_string_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_string_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_empty_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_empty_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_string_empty_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_string_empty_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_sized_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_sized_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_empty_sized_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_empty_sized_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_forced_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_forced_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_empty_forced_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
+
+test_get_chunked_close_empty_forced_SOURCES = \
+  test_get_chunked.c mhd_has_in_name.h
 
 test_post_SOURCES = \
-  test_post.c
-test_post_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_post.c mhd_has_in_name.h
 
 test_process_headers_SOURCES = \
-  test_process_headers.c
-test_process_headers_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_process_headers.c mhd_has_in_name.h
 
-test_parse_cookies_SOURCES = \
-  test_parse_cookies.c
-test_parse_cookies_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+test_parse_cookies_discp_zero_SOURCES = \
+  test_parse_cookies.c mhd_has_in_name.h mhd_has_param.h
+
+test_parse_cookies_discp_p2_SOURCES = \
+  $(test_parse_cookies_discp_zero_SOURCES)
+
+test_parse_cookies_discp_p1_SOURCES = \
+  $(test_parse_cookies_discp_zero_SOURCES)
+
+test_parse_cookies_discp_n2_SOURCES = \
+  $(test_parse_cookies_discp_zero_SOURCES)
+
+test_parse_cookies_discp_n3_SOURCES = \
+  $(test_parse_cookies_discp_zero_SOURCES)
 
 test_process_arguments_SOURCES = \
-  test_process_arguments.c
-test_process_arguments_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_process_arguments.c mhd_has_in_name.h
 
 test_postform_SOURCES = \
-  test_postform.c
+  test_postform.c mhd_has_in_name.h
 test_postform_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
+  @LIBGCRYPT_LIBS@ $(LDADD)
 
 test_post_loop_SOURCES = \
-  test_post_loop.c
-test_post_loop_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_post_loop.c mhd_has_in_name.h
+
+test_delete_SOURCES = \
+  test_delete.c mhd_has_in_name.h
+
+test_patch_SOURCES = \
+  test_patch.c mhd_has_in_name.h
+
+test_patch11_SOURCES = \
+  test_patch.c mhd_has_in_name.h
 
 test_put_SOURCES = \
-  test_put.c
-test_put_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_put.c mhd_has_in_name.h
 
 test_put_chunked_SOURCES = \
   test_put_chunked.c
-test_put_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+
+test_add_conn_SOURCES = \
+  test_add_conn.c mhd_has_in_name.h mhd_has_param.h
+test_add_conn_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+test_add_conn_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
+
+test_add_conn_nolisten_SOURCES = \
+  test_add_conn.c mhd_has_in_name.h mhd_has_param.h
+test_add_conn_nolisten_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+test_add_conn_nolisten_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
+
+test_add_conn_cleanup_SOURCES = \
+  test_add_conn.c mhd_has_in_name.h mhd_has_param.h
+test_add_conn_cleanup_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+test_add_conn_cleanup_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
+
+test_add_conn_cleanup_nolisten_SOURCES = \
+  test_add_conn.c mhd_has_in_name.h mhd_has_param.h
+test_add_conn_cleanup_nolisten_CFLAGS = \
+  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+test_add_conn_cleanup_nolisten_LDADD = \
+  $(PTHREAD_LIBS) $(LDADD)
 
 test_get11_SOURCES = \
-  test_get.c
-test_get11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_get.c mhd_has_in_name.h mhd_has_param.h
+
+test_get_iovec11_SOURCES = \
+  test_get_iovec.c mhd_has_in_name.h
 
 test_get_sendfile11_SOURCES = \
-  test_get_sendfile.c
-test_get_sendfile11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-test_get_sendfile11_DEPENDENCIES =
+  test_get_sendfile.c mhd_has_in_name.h
 
-if HAVE_W32
-test_get_sendfile11_LDADD += \
-  $(top_builddir)/src/platform/libplatform_interface.la
-test_get_sendfile11_DEPENDENCIES += \
-  $(top_builddir)/src/platform/libplatform_interface.la
-endif
+test_get_close_SOURCES = \
+  test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h
+
+test_get_close10_SOURCES = \
+  test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h
+
+test_get_keep_alive_SOURCES = \
+  test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h
+
+test_get_keep_alive10_SOURCES = \
+  test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h
 
 test_post11_SOURCES = \
-  test_post.c
-test_post11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_post.c mhd_has_in_name.h
 
 test_postform11_SOURCES = \
-  test_postform.c
+  test_postform.c mhd_has_in_name.h
 test_postform11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
+  @LIBGCRYPT_LIBS@ $(LDADD)
 
 test_post_loop11_SOURCES = \
-  test_post_loop.c
-test_post_loop11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_post_loop.c mhd_has_in_name.h
 
 test_put11_SOURCES = \
-  test_put.c
-test_put11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_put.c mhd_has_in_name.h
 
 test_large_put_SOURCES = \
-  test_large_put.c
-test_large_put_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_large_put.c mhd_has_in_name.h mhd_has_param.h
 
 test_large_put11_SOURCES = \
-  test_large_put.c
-test_large_put11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_large_put.c mhd_has_in_name.h mhd_has_param.h
+
+test_large_put_inc11_SOURCES = \
+  test_large_put.c mhd_has_in_name.h mhd_has_param.h
 
 test_long_header_SOURCES = \
-  test_long_header.c
-test_long_header_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_long_header.c mhd_has_in_name.h
 
 test_long_header11_SOURCES = \
-  test_long_header.c
-test_long_header11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_long_header.c mhd_has_in_name.h
 
 test_iplimit11_SOURCES = \
-  test_iplimit.c
-test_iplimit11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_iplimit.c mhd_has_in_name.h
 
 test_termination_SOURCES = \
   test_termination.c
-test_termination_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
 
 test_timeout_SOURCES = \
-  test_timeout.c
-test_timeout_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
+  test_timeout.c mhd_has_in_name.h
+
+test_toolarge_method_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_url_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_request_header_name_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_request_header_value_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_request_headers_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_reply_header_name_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_reply_header_value_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_toolarge_reply_headers_SOURCES = \
+  test_toolarge.c mhd_has_in_name.h mhd_has_param.h
+
+test_tricky_url_SOURCES = \
+  test_tricky.c mhd_has_in_name.h mhd_has_param.h
+
+test_tricky_header2_SOURCES = \
+  test_tricky.c mhd_has_in_name.h mhd_has_param.h
+
+test_put_broken_len_SOURCES = \
+  test_put_broken_len.c mhd_has_in_name.h mhd_has_param.h
+
+test_put_broken_len10_SOURCES = $(test_put_broken_len_SOURCES)
diff --git a/src/testcurl/Makefile.in b/src/testcurl/Makefile.in
deleted file mode 100644
index 937bf26..0000000
--- a/src/testcurl/Makefile.in
+++ /dev/null
@@ -1,2059 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-
-
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@ENABLE_HTTPS_TRUE@am__append_1 = https
-@HAVE_CURL_TRUE@check_PROGRAMS = test_start_stop$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_get$(EXEEXT) test_get_sendfile$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_urlparse$(EXEEXT) test_put$(EXEEXT) \
-@HAVE_CURL_TRUE@	$(am__EXEEXT_1) test_process_headers$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_process_arguments$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_parse_cookies$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_large_put$(EXEEXT) test_get11$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_get_sendfile11$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_put11$(EXEEXT) test_large_put11$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_long_header$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_long_header11$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_get_chunked$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_put_chunked$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_iplimit11$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_termination$(EXEEXT) \
-@HAVE_CURL_TRUE@	test_timeout$(EXEEXT) test_callback$(EXEEXT) \
-@HAVE_CURL_TRUE@	$(am__EXEEXT_2) perf_get$(EXEEXT) \
-@HAVE_CURL_TRUE@	$(am__EXEEXT_3) $(am__EXEEXT_4) \
-@HAVE_CURL_TRUE@	$(am__EXEEXT_5) $(am__EXEEXT_6)
-@HAVE_CURL_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_2 = \
-@HAVE_CURL_TRUE@@HAVE_POSIX_THREADS_TRUE@  test_quiesce
-
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__append_3 = \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@  test_post \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@  test_postform \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@  test_post_loop \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@  test_post11 \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@  test_postform11 \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@  test_post_loop11
-
-@HAVE_CURL_TRUE@noinst_PROGRAMS = test_options$(EXEEXT)
-@ENABLE_DAUTH_TRUE@@HAVE_CURL_TRUE@am__append_4 = \
-@ENABLE_DAUTH_TRUE@@HAVE_CURL_TRUE@	test_digestauth test_digestauth_with_arguments
-
-@HAVE_W32_TRUE@am__append_5 = \
-@HAVE_W32_TRUE@ $(top_builddir)/src/platform/libplatform_interface.la
-
-@HAVE_W32_TRUE@am__append_6 = \
-@HAVE_W32_TRUE@ $(top_builddir)/src/platform/libplatform_interface.la
-
-@HAVE_W32_TRUE@am__append_7 = \
-@HAVE_W32_TRUE@  $(top_builddir)/src/platform/libplatform_interface.la
-
-@HAVE_W32_TRUE@am__append_8 = \
-@HAVE_W32_TRUE@  $(top_builddir)/src/platform/libplatform_interface.la
-
-subdir = src/testcurl
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp $(top_srcdir)/test-driver
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-LIBRARIES = $(noinst_LIBRARIES)
-ARFLAGS = cru
-AM_V_AR = $(am__v_AR_@AM_V@)
-am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@)
-am__v_AR_0 = @echo "  AR      " $@;
-am__v_AR_1 = 
-libcurl_version_check_a_AR = $(AR) $(ARFLAGS)
-libcurl_version_check_a_LIBADD =
-am_libcurl_version_check_a_OBJECTS = curl_version_check.$(OBJEXT)
-libcurl_version_check_a_OBJECTS =  \
-	$(am_libcurl_version_check_a_OBJECTS)
-@HAVE_W32_FALSE@am__EXEEXT_1 = test_concurrent_stop$(EXEEXT)
-@HAVE_CURL_BINARY_TRUE@@HAVE_W32_FALSE@am__EXEEXT_2 = test_get_response_cleanup$(EXEEXT)
-@HAVE_W32_FALSE@am__EXEEXT_3 = perf_get_concurrent$(EXEEXT)
-@HAVE_CURL_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_4 = test_quiesce$(EXEEXT)
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_5 =  \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@	test_post$(EXEEXT) \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@	test_postform$(EXEEXT) \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@	test_post_loop$(EXEEXT) \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@	test_post11$(EXEEXT) \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@	test_postform11$(EXEEXT) \
-@HAVE_CURL_TRUE@@HAVE_POSTPROCESSOR_TRUE@	test_post_loop11$(EXEEXT)
-@ENABLE_DAUTH_TRUE@@HAVE_CURL_TRUE@am__EXEEXT_6 =  \
-@ENABLE_DAUTH_TRUE@@HAVE_CURL_TRUE@	test_digestauth$(EXEEXT) \
-@ENABLE_DAUTH_TRUE@@HAVE_CURL_TRUE@	test_digestauth_with_arguments$(EXEEXT)
-PROGRAMS = $(noinst_PROGRAMS)
-am_perf_get_OBJECTS = perf_get.$(OBJEXT)
-perf_get_OBJECTS = $(am_perf_get_OBJECTS)
-perf_get_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-am_perf_get_concurrent_OBJECTS = perf_get_concurrent.$(OBJEXT)
-perf_get_concurrent_OBJECTS = $(am_perf_get_concurrent_OBJECTS)
-perf_get_concurrent_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_callback_OBJECTS = test_callback.$(OBJEXT)
-test_callback_OBJECTS = $(am_test_callback_OBJECTS)
-test_callback_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_concurrent_stop_OBJECTS = test_concurrent_stop.$(OBJEXT)
-test_concurrent_stop_OBJECTS = $(am_test_concurrent_stop_OBJECTS)
-test_concurrent_stop_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_digestauth_OBJECTS = test_digestauth.$(OBJEXT)
-test_digestauth_OBJECTS = $(am_test_digestauth_OBJECTS)
-test_digestauth_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_digestauth_with_arguments_OBJECTS =  \
-	test_digestauth_with_arguments.$(OBJEXT)
-test_digestauth_with_arguments_OBJECTS =  \
-	$(am_test_digestauth_with_arguments_OBJECTS)
-test_digestauth_with_arguments_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_get_OBJECTS = test_get.$(OBJEXT)
-test_get_OBJECTS = $(am_test_get_OBJECTS)
-test_get_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_get11_OBJECTS = test_get.$(OBJEXT)
-test_get11_OBJECTS = $(am_test_get11_OBJECTS)
-test_get11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_get_chunked_OBJECTS = test_get_chunked.$(OBJEXT)
-test_get_chunked_OBJECTS = $(am_test_get_chunked_OBJECTS)
-test_get_chunked_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_get_response_cleanup_OBJECTS =  \
-	test_get_response_cleanup.$(OBJEXT)
-test_get_response_cleanup_OBJECTS =  \
-	$(am_test_get_response_cleanup_OBJECTS)
-test_get_response_cleanup_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_get_sendfile_OBJECTS = test_get_sendfile.$(OBJEXT)
-test_get_sendfile_OBJECTS = $(am_test_get_sendfile_OBJECTS)
-am_test_get_sendfile11_OBJECTS = test_get_sendfile.$(OBJEXT)
-test_get_sendfile11_OBJECTS = $(am_test_get_sendfile11_OBJECTS)
-am_test_iplimit11_OBJECTS = test_iplimit.$(OBJEXT)
-test_iplimit11_OBJECTS = $(am_test_iplimit11_OBJECTS)
-test_iplimit11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_large_put_OBJECTS = test_large_put.$(OBJEXT)
-test_large_put_OBJECTS = $(am_test_large_put_OBJECTS)
-test_large_put_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_large_put11_OBJECTS = test_large_put.$(OBJEXT)
-test_large_put11_OBJECTS = $(am_test_large_put11_OBJECTS)
-test_large_put11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_long_header_OBJECTS = test_long_header.$(OBJEXT)
-test_long_header_OBJECTS = $(am_test_long_header_OBJECTS)
-test_long_header_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_long_header11_OBJECTS = test_long_header.$(OBJEXT)
-test_long_header11_OBJECTS = $(am_test_long_header11_OBJECTS)
-test_long_header11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_options_OBJECTS = test_options.$(OBJEXT)
-test_options_OBJECTS = $(am_test_options_OBJECTS)
-test_options_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_parse_cookies_OBJECTS = test_parse_cookies.$(OBJEXT)
-test_parse_cookies_OBJECTS = $(am_test_parse_cookies_OBJECTS)
-test_parse_cookies_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post_OBJECTS = test_post.$(OBJEXT)
-test_post_OBJECTS = $(am_test_post_OBJECTS)
-test_post_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post11_OBJECTS = test_post.$(OBJEXT)
-test_post11_OBJECTS = $(am_test_post11_OBJECTS)
-test_post11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post_loop_OBJECTS = test_post_loop.$(OBJEXT)
-test_post_loop_OBJECTS = $(am_test_post_loop_OBJECTS)
-test_post_loop_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post_loop11_OBJECTS = test_post_loop.$(OBJEXT)
-test_post_loop11_OBJECTS = $(am_test_post_loop11_OBJECTS)
-test_post_loop11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_postform_OBJECTS = test_postform.$(OBJEXT)
-test_postform_OBJECTS = $(am_test_postform_OBJECTS)
-test_postform_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_postform11_OBJECTS = test_postform.$(OBJEXT)
-test_postform11_OBJECTS = $(am_test_postform11_OBJECTS)
-test_postform11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_process_arguments_OBJECTS = test_process_arguments.$(OBJEXT)
-test_process_arguments_OBJECTS = $(am_test_process_arguments_OBJECTS)
-test_process_arguments_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_process_headers_OBJECTS = test_process_headers.$(OBJEXT)
-test_process_headers_OBJECTS = $(am_test_process_headers_OBJECTS)
-test_process_headers_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put_OBJECTS = test_put.$(OBJEXT)
-test_put_OBJECTS = $(am_test_put_OBJECTS)
-test_put_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put11_OBJECTS = test_put.$(OBJEXT)
-test_put11_OBJECTS = $(am_test_put11_OBJECTS)
-test_put11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put_chunked_OBJECTS = test_put_chunked.$(OBJEXT)
-test_put_chunked_OBJECTS = $(am_test_put_chunked_OBJECTS)
-test_put_chunked_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_quiesce_OBJECTS = test_quiesce-test_quiesce.$(OBJEXT)
-test_quiesce_OBJECTS = $(am_test_quiesce_OBJECTS)
-am__DEPENDENCIES_1 =
-test_quiesce_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1)
-test_quiesce_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_quiesce_CFLAGS) \
-	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
-am_test_start_stop_OBJECTS = test_start_stop.$(OBJEXT)
-test_start_stop_OBJECTS = $(am_test_start_stop_OBJECTS)
-test_start_stop_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_termination_OBJECTS = test_termination.$(OBJEXT)
-test_termination_OBJECTS = $(am_test_termination_OBJECTS)
-test_termination_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_timeout_OBJECTS = test_timeout.$(OBJEXT)
-test_timeout_OBJECTS = $(am_test_timeout_OBJECTS)
-test_timeout_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_urlparse_OBJECTS = test_urlparse.$(OBJEXT)
-test_urlparse_OBJECTS = $(am_test_urlparse_OBJECTS)
-test_urlparse_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(libcurl_version_check_a_SOURCES) $(perf_get_SOURCES) \
-	$(perf_get_concurrent_SOURCES) $(test_callback_SOURCES) \
-	$(test_concurrent_stop_SOURCES) $(test_digestauth_SOURCES) \
-	$(test_digestauth_with_arguments_SOURCES) $(test_get_SOURCES) \
-	$(test_get11_SOURCES) $(test_get_chunked_SOURCES) \
-	$(test_get_response_cleanup_SOURCES) \
-	$(test_get_sendfile_SOURCES) $(test_get_sendfile11_SOURCES) \
-	$(test_iplimit11_SOURCES) $(test_large_put_SOURCES) \
-	$(test_large_put11_SOURCES) $(test_long_header_SOURCES) \
-	$(test_long_header11_SOURCES) $(test_options_SOURCES) \
-	$(test_parse_cookies_SOURCES) $(test_post_SOURCES) \
-	$(test_post11_SOURCES) $(test_post_loop_SOURCES) \
-	$(test_post_loop11_SOURCES) $(test_postform_SOURCES) \
-	$(test_postform11_SOURCES) $(test_process_arguments_SOURCES) \
-	$(test_process_headers_SOURCES) $(test_put_SOURCES) \
-	$(test_put11_SOURCES) $(test_put_chunked_SOURCES) \
-	$(test_quiesce_SOURCES) $(test_start_stop_SOURCES) \
-	$(test_termination_SOURCES) $(test_timeout_SOURCES) \
-	$(test_urlparse_SOURCES)
-DIST_SOURCES = $(libcurl_version_check_a_SOURCES) $(perf_get_SOURCES) \
-	$(perf_get_concurrent_SOURCES) $(test_callback_SOURCES) \
-	$(test_concurrent_stop_SOURCES) $(test_digestauth_SOURCES) \
-	$(test_digestauth_with_arguments_SOURCES) $(test_get_SOURCES) \
-	$(test_get11_SOURCES) $(test_get_chunked_SOURCES) \
-	$(test_get_response_cleanup_SOURCES) \
-	$(test_get_sendfile_SOURCES) $(test_get_sendfile11_SOURCES) \
-	$(test_iplimit11_SOURCES) $(test_large_put_SOURCES) \
-	$(test_large_put11_SOURCES) $(test_long_header_SOURCES) \
-	$(test_long_header11_SOURCES) $(test_options_SOURCES) \
-	$(test_parse_cookies_SOURCES) $(test_post_SOURCES) \
-	$(test_post11_SOURCES) $(test_post_loop_SOURCES) \
-	$(test_post_loop11_SOURCES) $(test_postform_SOURCES) \
-	$(test_postform11_SOURCES) $(test_process_arguments_SOURCES) \
-	$(test_process_headers_SOURCES) $(test_put_SOURCES) \
-	$(test_put11_SOURCES) $(test_put_chunked_SOURCES) \
-	$(test_quiesce_SOURCES) $(test_start_stop_SOURCES) \
-	$(test_termination_SOURCES) $(test_timeout_SOURCES) \
-	$(test_urlparse_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	check recheck distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-am__tty_colors_dummy = \
-  mgn= red= grn= lgn= blu= brg= std=; \
-  am__color_tests=no
-am__tty_colors = { \
-  $(am__tty_colors_dummy); \
-  if test "X$(AM_COLOR_TESTS)" = Xno; then \
-    am__color_tests=no; \
-  elif test "X$(AM_COLOR_TESTS)" = Xalways; then \
-    am__color_tests=yes; \
-  elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \
-    am__color_tests=yes; \
-  fi; \
-  if test $$am__color_tests = yes; then \
-    red=''; \
-    grn=''; \
-    lgn=''; \
-    blu=''; \
-    mgn=''; \
-    brg=''; \
-    std=''; \
-  fi; \
-}
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__recheck_rx = ^[ 	]*:recheck:[ 	]*
-am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
-am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
-# A command that, given a newline-separated list of test names on the
-# standard input, print the name of the tests that are to be re-run
-# upon "make recheck".
-am__list_recheck_tests = $(AWK) '{ \
-  recheck = 1; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-        { \
-          if ((getline line2 < ($$0 ".log")) < 0) \
-	    recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \
-        { \
-          recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \
-        { \
-          break; \
-        } \
-    }; \
-  if (recheck) \
-    print $$0; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# A command that, given a newline-separated list of test names on the
-# standard input, create the global log from their .trs and .log files.
-am__create_global_log = $(AWK) ' \
-function fatal(msg) \
-{ \
-  print "fatal: making $@: " msg | "cat >&2"; \
-  exit 1; \
-} \
-function rst_section(header) \
-{ \
-  print header; \
-  len = length(header); \
-  for (i = 1; i <= len; i = i + 1) \
-    printf "="; \
-  printf "\n\n"; \
-} \
-{ \
-  copy_in_global_log = 1; \
-  global_test_result = "RUN"; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-         fatal("failed to read from " $$0 ".trs"); \
-      if (line ~ /$(am__global_test_result_rx)/) \
-        { \
-          sub("$(am__global_test_result_rx)", "", line); \
-          sub("[ 	]*$$", "", line); \
-          global_test_result = line; \
-        } \
-      else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \
-        copy_in_global_log = 0; \
-    }; \
-  if (copy_in_global_log) \
-    { \
-      rst_section(global_test_result ": " $$0); \
-      while ((rc = (getline line < ($$0 ".log"))) != 0) \
-      { \
-        if (rc < 0) \
-          fatal("failed to read from " $$0 ".log"); \
-        print line; \
-      }; \
-      printf "\n"; \
-    }; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# Restructured Text title.
-am__rst_title = { sed 's/.*/   &   /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; }
-# Solaris 10 'make', and several other traditional 'make' implementations,
-# pass "-e" to $(SHELL), and POSIX 2008 even requires this.  Work around it
-# by disabling -e (using the XSI extension "set +e") if it's set.
-am__sh_e_setup = case $$- in *e*) set +e;; esac
-# Default flags passed to test drivers.
-am__common_driver_flags = \
-  --color-tests "$$am__color_tests" \
-  --enable-hard-errors "$$am__enable_hard_errors" \
-  --expect-failure "$$am__expect_failure"
-# To be inserted before the command running the test.  Creates the
-# directory for the log if needed.  Stores in $dir the directory
-# containing $f, in $tst the test, in $log the log.  Executes the
-# developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and
-# passes TESTS_ENVIRONMENT.  Set up options for the wrapper that
-# will run the test scripts (or their associated LOG_COMPILER, if
-# thy have one).
-am__check_pre = \
-$(am__sh_e_setup);					\
-$(am__vpath_adj_setup) $(am__vpath_adj)			\
-$(am__tty_colors);					\
-srcdir=$(srcdir); export srcdir;			\
-case "$@" in						\
-  */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;;	\
-    *) am__odir=.;; 					\
-esac;							\
-test "x$$am__odir" = x"." || test -d "$$am__odir" 	\
-  || $(MKDIR_P) "$$am__odir" || exit $$?;		\
-if test -f "./$$f"; then dir=./;			\
-elif test -f "$$f"; then dir=;				\
-else dir="$(srcdir)/"; fi;				\
-tst=$$dir$$f; log='$@'; 				\
-if test -n '$(DISABLE_HARD_ERRORS)'; then		\
-  am__enable_hard_errors=no; 				\
-else							\
-  am__enable_hard_errors=yes; 				\
-fi; 							\
-case " $(XFAIL_TESTS) " in				\
-  *[\ \	]$$f[\ \	]* | *[\ \	]$$dir$$f[\ \	]*) \
-    am__expect_failure=yes;;				\
-  *)							\
-    am__expect_failure=no;;				\
-esac; 							\
-$(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT)
-# A shell command to get the names of the tests scripts with any registered
-# extension removed (i.e., equivalently, the names of the test logs, with
-# the '.log' extension removed).  The result is saved in the shell variable
-# '$bases'.  This honors runtime overriding of TESTS and TEST_LOGS.  Sadly,
-# we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)",
-# since that might cause problem with VPATH rewrites for suffix-less tests.
-# See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'.
-am__set_TESTS_bases = \
-  bases='$(TEST_LOGS)'; \
-  bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \
-  bases=`echo $$bases`
-RECHECK_LOGS = $(TEST_LOGS)
-TEST_SUITE_LOG = test-suite.log
-TEST_EXTENSIONS = @EXEEXT@ .test
-LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)
-am__set_b = \
-  case '$@' in \
-    */*) \
-      case '$*' in \
-        */*) b='$*';; \
-          *) b=`echo '$@' | sed 's/\.log$$//'`; \
-       esac;; \
-    *) \
-      b='$*';; \
-  esac
-am__test_logs1 = $(TESTS:=.log)
-am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log)
-TEST_LOGS = $(am__test_logs2:.test.log=.log)
-TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
-	$(TEST_LOG_FLAGS)
-DIST_SUBDIRS = . https
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = . $(am__append_1)
-@USE_COVERAGE_TRUE@AM_CFLAGS = -fprofile-arcs -ftest-coverage
-AM_CPPFLAGS = \
--DCPU_COUNT=$(CPU_COUNT) \
--I$(top_srcdir) \
--I$(top_srcdir)/src/microhttpd \
--I$(top_srcdir)/src/include \
-$(LIBCURL_CPPFLAGS)
-
-@HAVE_W32_FALSE@PERF_GET_CONCURRENT = perf_get_concurrent
-@HAVE_W32_FALSE@TEST_CONCURRENT_STOP = test_concurrent_stop
-@HAVE_CURL_BINARY_TRUE@@HAVE_W32_FALSE@CURL_FORK_TEST = test_get_response_cleanup
-@HAVE_CURL_TRUE@TESTS = $(check_PROGRAMS)
-@HAVE_CURL_TRUE@noinst_LIBRARIES = libcurl_version_check.a
-libcurl_version_check_a_SOURCES = \
-  curl_version_check.c
-
-test_start_stop_SOURCES = \
-  test_start_stop.c
-
-test_start_stop_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-test_concurrent_stop_SOURCES = \
-  test_concurrent_stop.c
-
-test_concurrent_stop_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
- @LIBCURL@
-
-test_options_SOURCES = \
-  test_options.c
-
-test_options_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-test_get_SOURCES = \
-  test_get.c
-
-test_get_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_quiesce_SOURCES = \
-  test_quiesce.c
-
-test_quiesce_CFLAGS = \
-  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
-
-test_quiesce_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(PTHREAD_LIBS) @LIBCURL@
-
-test_callback_SOURCES = \
-  test_callback.c
-
-test_callback_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-perf_get_SOURCES = \
-  perf_get.c \
-  gauger.h
-
-perf_get_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-perf_get_concurrent_SOURCES = \
-  perf_get_concurrent.c \
-  gauger.h
-
-perf_get_concurrent_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_digestauth_SOURCES = \
-  test_digestauth.c
-
-test_digestauth_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_digestauth_with_arguments_SOURCES = \
-  test_digestauth_with_arguments.c
-
-test_digestauth_with_arguments_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_get_sendfile_SOURCES = \
-  test_get_sendfile.c
-
-test_get_sendfile_LDADD =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la @LIBCURL@ \
-	$(am__append_5)
-test_get_sendfile_DEPENDENCIES = $(am__append_6)
-test_urlparse_SOURCES = \
-  test_urlparse.c
-
-test_urlparse_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_get_response_cleanup_SOURCES = \
-  test_get_response_cleanup.c
-
-test_get_response_cleanup_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la
-
-test_get_chunked_SOURCES = \
-  test_get_chunked.c
-
-test_get_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_post_SOURCES = \
-  test_post.c
-
-test_post_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_process_headers_SOURCES = \
-  test_process_headers.c
-
-test_process_headers_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_parse_cookies_SOURCES = \
-  test_parse_cookies.c
-
-test_parse_cookies_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_process_arguments_SOURCES = \
-  test_process_arguments.c
-
-test_process_arguments_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_postform_SOURCES = \
-  test_postform.c
-
-test_postform_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_post_loop_SOURCES = \
-  test_post_loop.c
-
-test_post_loop_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_put_SOURCES = \
-  test_put.c
-
-test_put_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_put_chunked_SOURCES = \
-  test_put_chunked.c
-
-test_put_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_get11_SOURCES = \
-  test_get.c
-
-test_get11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_get_sendfile11_SOURCES = \
-  test_get_sendfile.c
-
-test_get_sendfile11_LDADD =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la @LIBCURL@ \
-	$(am__append_7)
-test_get_sendfile11_DEPENDENCIES = $(am__append_8)
-test_post11_SOURCES = \
-  test_post.c
-
-test_post11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_postform11_SOURCES = \
-  test_postform.c
-
-test_postform11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_post_loop11_SOURCES = \
-  test_post_loop.c
-
-test_post_loop11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_put11_SOURCES = \
-  test_put.c
-
-test_put11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_large_put_SOURCES = \
-  test_large_put.c
-
-test_large_put_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_large_put11_SOURCES = \
-  test_large_put.c
-
-test_large_put11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_long_header_SOURCES = \
-  test_long_header.c
-
-test_long_header_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_long_header11_SOURCES = \
-  test_long_header.c
-
-test_long_header11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_iplimit11_SOURCES = \
-  test_iplimit.c
-
-test_iplimit11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_termination_SOURCES = \
-  test_termination.c
-
-test_termination_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-test_timeout_SOURCES = \
-  test_timeout.c
-
-test_timeout_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@
-
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testcurl/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/testcurl/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-noinstLIBRARIES:
-	-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
-
-libcurl_version_check.a: $(libcurl_version_check_a_OBJECTS) $(libcurl_version_check_a_DEPENDENCIES) $(EXTRA_libcurl_version_check_a_DEPENDENCIES) 
-	$(AM_V_at)-rm -f libcurl_version_check.a
-	$(AM_V_AR)$(libcurl_version_check_a_AR) libcurl_version_check.a $(libcurl_version_check_a_OBJECTS) $(libcurl_version_check_a_LIBADD)
-	$(AM_V_at)$(RANLIB) libcurl_version_check.a
-
-clean-checkPROGRAMS:
-	@list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-clean-noinstPROGRAMS:
-	@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-perf_get$(EXEEXT): $(perf_get_OBJECTS) $(perf_get_DEPENDENCIES) $(EXTRA_perf_get_DEPENDENCIES) 
-	@rm -f perf_get$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(perf_get_OBJECTS) $(perf_get_LDADD) $(LIBS)
-
-perf_get_concurrent$(EXEEXT): $(perf_get_concurrent_OBJECTS) $(perf_get_concurrent_DEPENDENCIES) $(EXTRA_perf_get_concurrent_DEPENDENCIES) 
-	@rm -f perf_get_concurrent$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(perf_get_concurrent_OBJECTS) $(perf_get_concurrent_LDADD) $(LIBS)
-
-test_callback$(EXEEXT): $(test_callback_OBJECTS) $(test_callback_DEPENDENCIES) $(EXTRA_test_callback_DEPENDENCIES) 
-	@rm -f test_callback$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_callback_OBJECTS) $(test_callback_LDADD) $(LIBS)
-
-test_concurrent_stop$(EXEEXT): $(test_concurrent_stop_OBJECTS) $(test_concurrent_stop_DEPENDENCIES) $(EXTRA_test_concurrent_stop_DEPENDENCIES) 
-	@rm -f test_concurrent_stop$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_concurrent_stop_OBJECTS) $(test_concurrent_stop_LDADD) $(LIBS)
-
-test_digestauth$(EXEEXT): $(test_digestauth_OBJECTS) $(test_digestauth_DEPENDENCIES) $(EXTRA_test_digestauth_DEPENDENCIES) 
-	@rm -f test_digestauth$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_digestauth_OBJECTS) $(test_digestauth_LDADD) $(LIBS)
-
-test_digestauth_with_arguments$(EXEEXT): $(test_digestauth_with_arguments_OBJECTS) $(test_digestauth_with_arguments_DEPENDENCIES) $(EXTRA_test_digestauth_with_arguments_DEPENDENCIES) 
-	@rm -f test_digestauth_with_arguments$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_digestauth_with_arguments_OBJECTS) $(test_digestauth_with_arguments_LDADD) $(LIBS)
-
-test_get$(EXEEXT): $(test_get_OBJECTS) $(test_get_DEPENDENCIES) $(EXTRA_test_get_DEPENDENCIES) 
-	@rm -f test_get$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_OBJECTS) $(test_get_LDADD) $(LIBS)
-
-test_get11$(EXEEXT): $(test_get11_OBJECTS) $(test_get11_DEPENDENCIES) $(EXTRA_test_get11_DEPENDENCIES) 
-	@rm -f test_get11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get11_OBJECTS) $(test_get11_LDADD) $(LIBS)
-
-test_get_chunked$(EXEEXT): $(test_get_chunked_OBJECTS) $(test_get_chunked_DEPENDENCIES) $(EXTRA_test_get_chunked_DEPENDENCIES) 
-	@rm -f test_get_chunked$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_chunked_OBJECTS) $(test_get_chunked_LDADD) $(LIBS)
-
-test_get_response_cleanup$(EXEEXT): $(test_get_response_cleanup_OBJECTS) $(test_get_response_cleanup_DEPENDENCIES) $(EXTRA_test_get_response_cleanup_DEPENDENCIES) 
-	@rm -f test_get_response_cleanup$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_response_cleanup_OBJECTS) $(test_get_response_cleanup_LDADD) $(LIBS)
-
-test_get_sendfile$(EXEEXT): $(test_get_sendfile_OBJECTS) $(test_get_sendfile_DEPENDENCIES) $(EXTRA_test_get_sendfile_DEPENDENCIES) 
-	@rm -f test_get_sendfile$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_sendfile_OBJECTS) $(test_get_sendfile_LDADD) $(LIBS)
-
-test_get_sendfile11$(EXEEXT): $(test_get_sendfile11_OBJECTS) $(test_get_sendfile11_DEPENDENCIES) $(EXTRA_test_get_sendfile11_DEPENDENCIES) 
-	@rm -f test_get_sendfile11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_sendfile11_OBJECTS) $(test_get_sendfile11_LDADD) $(LIBS)
-
-test_iplimit11$(EXEEXT): $(test_iplimit11_OBJECTS) $(test_iplimit11_DEPENDENCIES) $(EXTRA_test_iplimit11_DEPENDENCIES) 
-	@rm -f test_iplimit11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_iplimit11_OBJECTS) $(test_iplimit11_LDADD) $(LIBS)
-
-test_large_put$(EXEEXT): $(test_large_put_OBJECTS) $(test_large_put_DEPENDENCIES) $(EXTRA_test_large_put_DEPENDENCIES) 
-	@rm -f test_large_put$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_large_put_OBJECTS) $(test_large_put_LDADD) $(LIBS)
-
-test_large_put11$(EXEEXT): $(test_large_put11_OBJECTS) $(test_large_put11_DEPENDENCIES) $(EXTRA_test_large_put11_DEPENDENCIES) 
-	@rm -f test_large_put11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_large_put11_OBJECTS) $(test_large_put11_LDADD) $(LIBS)
-
-test_long_header$(EXEEXT): $(test_long_header_OBJECTS) $(test_long_header_DEPENDENCIES) $(EXTRA_test_long_header_DEPENDENCIES) 
-	@rm -f test_long_header$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_long_header_OBJECTS) $(test_long_header_LDADD) $(LIBS)
-
-test_long_header11$(EXEEXT): $(test_long_header11_OBJECTS) $(test_long_header11_DEPENDENCIES) $(EXTRA_test_long_header11_DEPENDENCIES) 
-	@rm -f test_long_header11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_long_header11_OBJECTS) $(test_long_header11_LDADD) $(LIBS)
-
-test_options$(EXEEXT): $(test_options_OBJECTS) $(test_options_DEPENDENCIES) $(EXTRA_test_options_DEPENDENCIES) 
-	@rm -f test_options$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_options_OBJECTS) $(test_options_LDADD) $(LIBS)
-
-test_parse_cookies$(EXEEXT): $(test_parse_cookies_OBJECTS) $(test_parse_cookies_DEPENDENCIES) $(EXTRA_test_parse_cookies_DEPENDENCIES) 
-	@rm -f test_parse_cookies$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_parse_cookies_OBJECTS) $(test_parse_cookies_LDADD) $(LIBS)
-
-test_post$(EXEEXT): $(test_post_OBJECTS) $(test_post_DEPENDENCIES) $(EXTRA_test_post_DEPENDENCIES) 
-	@rm -f test_post$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post_OBJECTS) $(test_post_LDADD) $(LIBS)
-
-test_post11$(EXEEXT): $(test_post11_OBJECTS) $(test_post11_DEPENDENCIES) $(EXTRA_test_post11_DEPENDENCIES) 
-	@rm -f test_post11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post11_OBJECTS) $(test_post11_LDADD) $(LIBS)
-
-test_post_loop$(EXEEXT): $(test_post_loop_OBJECTS) $(test_post_loop_DEPENDENCIES) $(EXTRA_test_post_loop_DEPENDENCIES) 
-	@rm -f test_post_loop$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post_loop_OBJECTS) $(test_post_loop_LDADD) $(LIBS)
-
-test_post_loop11$(EXEEXT): $(test_post_loop11_OBJECTS) $(test_post_loop11_DEPENDENCIES) $(EXTRA_test_post_loop11_DEPENDENCIES) 
-	@rm -f test_post_loop11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post_loop11_OBJECTS) $(test_post_loop11_LDADD) $(LIBS)
-
-test_postform$(EXEEXT): $(test_postform_OBJECTS) $(test_postform_DEPENDENCIES) $(EXTRA_test_postform_DEPENDENCIES) 
-	@rm -f test_postform$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_postform_OBJECTS) $(test_postform_LDADD) $(LIBS)
-
-test_postform11$(EXEEXT): $(test_postform11_OBJECTS) $(test_postform11_DEPENDENCIES) $(EXTRA_test_postform11_DEPENDENCIES) 
-	@rm -f test_postform11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_postform11_OBJECTS) $(test_postform11_LDADD) $(LIBS)
-
-test_process_arguments$(EXEEXT): $(test_process_arguments_OBJECTS) $(test_process_arguments_DEPENDENCIES) $(EXTRA_test_process_arguments_DEPENDENCIES) 
-	@rm -f test_process_arguments$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_process_arguments_OBJECTS) $(test_process_arguments_LDADD) $(LIBS)
-
-test_process_headers$(EXEEXT): $(test_process_headers_OBJECTS) $(test_process_headers_DEPENDENCIES) $(EXTRA_test_process_headers_DEPENDENCIES) 
-	@rm -f test_process_headers$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_process_headers_OBJECTS) $(test_process_headers_LDADD) $(LIBS)
-
-test_put$(EXEEXT): $(test_put_OBJECTS) $(test_put_DEPENDENCIES) $(EXTRA_test_put_DEPENDENCIES) 
-	@rm -f test_put$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put_OBJECTS) $(test_put_LDADD) $(LIBS)
-
-test_put11$(EXEEXT): $(test_put11_OBJECTS) $(test_put11_DEPENDENCIES) $(EXTRA_test_put11_DEPENDENCIES) 
-	@rm -f test_put11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put11_OBJECTS) $(test_put11_LDADD) $(LIBS)
-
-test_put_chunked$(EXEEXT): $(test_put_chunked_OBJECTS) $(test_put_chunked_DEPENDENCIES) $(EXTRA_test_put_chunked_DEPENDENCIES) 
-	@rm -f test_put_chunked$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put_chunked_OBJECTS) $(test_put_chunked_LDADD) $(LIBS)
-
-test_quiesce$(EXEEXT): $(test_quiesce_OBJECTS) $(test_quiesce_DEPENDENCIES) $(EXTRA_test_quiesce_DEPENDENCIES) 
-	@rm -f test_quiesce$(EXEEXT)
-	$(AM_V_CCLD)$(test_quiesce_LINK) $(test_quiesce_OBJECTS) $(test_quiesce_LDADD) $(LIBS)
-
-test_start_stop$(EXEEXT): $(test_start_stop_OBJECTS) $(test_start_stop_DEPENDENCIES) $(EXTRA_test_start_stop_DEPENDENCIES) 
-	@rm -f test_start_stop$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_start_stop_OBJECTS) $(test_start_stop_LDADD) $(LIBS)
-
-test_termination$(EXEEXT): $(test_termination_OBJECTS) $(test_termination_DEPENDENCIES) $(EXTRA_test_termination_DEPENDENCIES) 
-	@rm -f test_termination$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_termination_OBJECTS) $(test_termination_LDADD) $(LIBS)
-
-test_timeout$(EXEEXT): $(test_timeout_OBJECTS) $(test_timeout_DEPENDENCIES) $(EXTRA_test_timeout_DEPENDENCIES) 
-	@rm -f test_timeout$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_timeout_OBJECTS) $(test_timeout_LDADD) $(LIBS)
-
-test_urlparse$(EXEEXT): $(test_urlparse_OBJECTS) $(test_urlparse_DEPENDENCIES) $(EXTRA_test_urlparse_DEPENDENCIES) 
-	@rm -f test_urlparse$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_urlparse_OBJECTS) $(test_urlparse_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/curl_version_check.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get_concurrent.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_callback.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_concurrent_stop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_with_arguments.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_chunked.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_response_cleanup.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_sendfile.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_iplimit.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_large_put.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_long_header.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_options.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_parse_cookies.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post_loop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postform.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_process_arguments.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_process_headers.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_chunked.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_quiesce-test_quiesce.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_start_stop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_termination.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_timeout.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_urlparse.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-test_quiesce-test_quiesce.o: test_quiesce.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -MT test_quiesce-test_quiesce.o -MD -MP -MF $(DEPDIR)/test_quiesce-test_quiesce.Tpo -c -o test_quiesce-test_quiesce.o `test -f 'test_quiesce.c' || echo '$(srcdir)/'`test_quiesce.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce-test_quiesce.Tpo $(DEPDIR)/test_quiesce-test_quiesce.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_quiesce.c' object='test_quiesce-test_quiesce.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -c -o test_quiesce-test_quiesce.o `test -f 'test_quiesce.c' || echo '$(srcdir)/'`test_quiesce.c
-
-test_quiesce-test_quiesce.obj: test_quiesce.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -MT test_quiesce-test_quiesce.obj -MD -MP -MF $(DEPDIR)/test_quiesce-test_quiesce.Tpo -c -o test_quiesce-test_quiesce.obj `if test -f 'test_quiesce.c'; then $(CYGPATH_W) 'test_quiesce.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce-test_quiesce.Tpo $(DEPDIR)/test_quiesce-test_quiesce.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_quiesce.c' object='test_quiesce-test_quiesce.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -c -o test_quiesce-test_quiesce.obj `if test -f 'test_quiesce.c'; then $(CYGPATH_W) 'test_quiesce.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce.c'; fi`
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-# Recover from deleted '.trs' file; this should ensure that
-# "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create
-# both 'foo.log' and 'foo.trs'.  Break the recipe in two subshells
-# to avoid problems with "make -n".
-.log.trs:
-	rm -f $< $@
-	$(MAKE) $(AM_MAKEFLAGS) $<
-
-# Leading 'am--fnord' is there to ensure the list of targets does not
-# expand to empty, as could happen e.g. with make check TESTS=''.
-am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck)
-am--force-recheck:
-	@:
-
-$(TEST_SUITE_LOG): $(TEST_LOGS)
-	@$(am__set_TESTS_bases); \
-	am__f_ok () { test -f "$$1" && test -r "$$1"; }; \
-	redo_bases=`for i in $$bases; do \
-	              am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \
-	            done`; \
-	if test -n "$$redo_bases"; then \
-	  redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \
-	  redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \
-	  if $(am__make_dryrun); then :; else \
-	    rm -f $$redo_logs && rm -f $$redo_results || exit 1; \
-	  fi; \
-	fi; \
-	if test -n "$$am__remaking_logs"; then \
-	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
-	       "recursion detected" >&2; \
-	else \
-	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
-	fi; \
-	if $(am__make_dryrun); then :; else \
-	  st=0;  \
-	  errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \
-	  for i in $$redo_bases; do \
-	    test -f $$i.trs && test -r $$i.trs \
-	      || { echo "$$errmsg $$i.trs" >&2; st=1; }; \
-	    test -f $$i.log && test -r $$i.log \
-	      || { echo "$$errmsg $$i.log" >&2; st=1; }; \
-	  done; \
-	  test $$st -eq 0 || exit 1; \
-	fi
-	@$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \
-	ws='[ 	]'; \
-	results=`for b in $$bases; do echo $$b.trs; done`; \
-	test -n "$$results" || results=/dev/null; \
-	all=`  grep "^$$ws*:test-result:"           $$results | wc -l`; \
-	pass=` grep "^$$ws*:test-result:$$ws*PASS"  $$results | wc -l`; \
-	fail=` grep "^$$ws*:test-result:$$ws*FAIL"  $$results | wc -l`; \
-	skip=` grep "^$$ws*:test-result:$$ws*SKIP"  $$results | wc -l`; \
-	xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \
-	xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \
-	error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \
-	if test `expr $$fail + $$xpass + $$error` -eq 0; then \
-	  success=true; \
-	else \
-	  success=false; \
-	fi; \
-	br='==================='; br=$$br$$br$$br$$br; \
-	result_count () \
-	{ \
-	    if test x"$$1" = x"--maybe-color"; then \
-	      maybe_colorize=yes; \
-	    elif test x"$$1" = x"--no-color"; then \
-	      maybe_colorize=no; \
-	    else \
-	      echo "$@: invalid 'result_count' usage" >&2; exit 4; \
-	    fi; \
-	    shift; \
-	    desc=$$1 count=$$2; \
-	    if test $$maybe_colorize = yes && test $$count -gt 0; then \
-	      color_start=$$3 color_end=$$std; \
-	    else \
-	      color_start= color_end=; \
-	    fi; \
-	    echo "$${color_start}# $$desc $$count$${color_end}"; \
-	}; \
-	create_testsuite_report () \
-	{ \
-	  result_count $$1 "TOTAL:" $$all   "$$brg"; \
-	  result_count $$1 "PASS: " $$pass  "$$grn"; \
-	  result_count $$1 "SKIP: " $$skip  "$$blu"; \
-	  result_count $$1 "XFAIL:" $$xfail "$$lgn"; \
-	  result_count $$1 "FAIL: " $$fail  "$$red"; \
-	  result_count $$1 "XPASS:" $$xpass "$$red"; \
-	  result_count $$1 "ERROR:" $$error "$$mgn"; \
-	}; \
-	{								\
-	  echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" |	\
-	    $(am__rst_title);						\
-	  create_testsuite_report --no-color;				\
-	  echo;								\
-	  echo ".. contents:: :depth: 2";				\
-	  echo;								\
-	  for b in $$bases; do echo $$b; done				\
-	    | $(am__create_global_log);					\
-	} >$(TEST_SUITE_LOG).tmp || exit 1;				\
-	mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG);			\
-	if $$success; then						\
-	  col="$$grn";							\
-	 else								\
-	  col="$$red";							\
-	  test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG);		\
-	fi;								\
-	echo "$${col}$$br$${std}"; 					\
-	echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}";	\
-	echo "$${col}$$br$${std}"; 					\
-	create_testsuite_report --maybe-color;				\
-	echo "$$col$$br$$std";						\
-	if $$success; then :; else					\
-	  echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}";		\
-	  if test -n "$(PACKAGE_BUGREPORT)"; then			\
-	    echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}";	\
-	  fi;								\
-	  echo "$$col$$br$$std";					\
-	fi;								\
-	$$success || exit 1
-
-check-TESTS:
-	@list='$(RECHECK_LOGS)';           test -z "$$list" || rm -f $$list
-	@list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	trs_list=`for i in $$bases; do echo $$i.trs; done`; \
-	log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \
-	exit $$?;
-recheck: all $(check_PROGRAMS)
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	bases=`for i in $$bases; do echo $$i; done \
-	         | $(am__list_recheck_tests)` || exit 1; \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	log_list=`echo $$log_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \
-	        am__force_recheck=am--force-recheck \
-	        TEST_LOGS="$$log_list"; \
-	exit $$?
-test_start_stop.log: test_start_stop$(EXEEXT)
-	@p='test_start_stop$(EXEEXT)'; \
-	b='test_start_stop'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get.log: test_get$(EXEEXT)
-	@p='test_get$(EXEEXT)'; \
-	b='test_get'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get_sendfile.log: test_get_sendfile$(EXEEXT)
-	@p='test_get_sendfile$(EXEEXT)'; \
-	b='test_get_sendfile'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_urlparse.log: test_urlparse$(EXEEXT)
-	@p='test_urlparse$(EXEEXT)'; \
-	b='test_urlparse'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put.log: test_put$(EXEEXT)
-	@p='test_put$(EXEEXT)'; \
-	b='test_put'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_concurrent_stop.log: test_concurrent_stop$(EXEEXT)
-	@p='test_concurrent_stop$(EXEEXT)'; \
-	b='test_concurrent_stop'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_process_headers.log: test_process_headers$(EXEEXT)
-	@p='test_process_headers$(EXEEXT)'; \
-	b='test_process_headers'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_process_arguments.log: test_process_arguments$(EXEEXT)
-	@p='test_process_arguments$(EXEEXT)'; \
-	b='test_process_arguments'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_parse_cookies.log: test_parse_cookies$(EXEEXT)
-	@p='test_parse_cookies$(EXEEXT)'; \
-	b='test_parse_cookies'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_large_put.log: test_large_put$(EXEEXT)
-	@p='test_large_put$(EXEEXT)'; \
-	b='test_large_put'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get11.log: test_get11$(EXEEXT)
-	@p='test_get11$(EXEEXT)'; \
-	b='test_get11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get_sendfile11.log: test_get_sendfile11$(EXEEXT)
-	@p='test_get_sendfile11$(EXEEXT)'; \
-	b='test_get_sendfile11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put11.log: test_put11$(EXEEXT)
-	@p='test_put11$(EXEEXT)'; \
-	b='test_put11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_large_put11.log: test_large_put11$(EXEEXT)
-	@p='test_large_put11$(EXEEXT)'; \
-	b='test_large_put11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_long_header.log: test_long_header$(EXEEXT)
-	@p='test_long_header$(EXEEXT)'; \
-	b='test_long_header'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_long_header11.log: test_long_header11$(EXEEXT)
-	@p='test_long_header11$(EXEEXT)'; \
-	b='test_long_header11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get_chunked.log: test_get_chunked$(EXEEXT)
-	@p='test_get_chunked$(EXEEXT)'; \
-	b='test_get_chunked'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put_chunked.log: test_put_chunked$(EXEEXT)
-	@p='test_put_chunked$(EXEEXT)'; \
-	b='test_put_chunked'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_iplimit11.log: test_iplimit11$(EXEEXT)
-	@p='test_iplimit11$(EXEEXT)'; \
-	b='test_iplimit11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_termination.log: test_termination$(EXEEXT)
-	@p='test_termination$(EXEEXT)'; \
-	b='test_termination'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_timeout.log: test_timeout$(EXEEXT)
-	@p='test_timeout$(EXEEXT)'; \
-	b='test_timeout'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_callback.log: test_callback$(EXEEXT)
-	@p='test_callback$(EXEEXT)'; \
-	b='test_callback'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get_response_cleanup.log: test_get_response_cleanup$(EXEEXT)
-	@p='test_get_response_cleanup$(EXEEXT)'; \
-	b='test_get_response_cleanup'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-perf_get.log: perf_get$(EXEEXT)
-	@p='perf_get$(EXEEXT)'; \
-	b='perf_get'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-perf_get_concurrent.log: perf_get_concurrent$(EXEEXT)
-	@p='perf_get_concurrent$(EXEEXT)'; \
-	b='perf_get_concurrent'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_quiesce.log: test_quiesce$(EXEEXT)
-	@p='test_quiesce$(EXEEXT)'; \
-	b='test_quiesce'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post.log: test_post$(EXEEXT)
-	@p='test_post$(EXEEXT)'; \
-	b='test_post'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_postform.log: test_postform$(EXEEXT)
-	@p='test_postform$(EXEEXT)'; \
-	b='test_postform'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post_loop.log: test_post_loop$(EXEEXT)
-	@p='test_post_loop$(EXEEXT)'; \
-	b='test_post_loop'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post11.log: test_post11$(EXEEXT)
-	@p='test_post11$(EXEEXT)'; \
-	b='test_post11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_postform11.log: test_postform11$(EXEEXT)
-	@p='test_postform11$(EXEEXT)'; \
-	b='test_postform11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post_loop11.log: test_post_loop11$(EXEEXT)
-	@p='test_post_loop11$(EXEEXT)'; \
-	b='test_post_loop11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_digestauth.log: test_digestauth$(EXEEXT)
-	@p='test_digestauth$(EXEEXT)'; \
-	b='test_digestauth'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_digestauth_with_arguments.log: test_digestauth_with_arguments$(EXEEXT)
-	@p='test_digestauth_with_arguments$(EXEEXT)'; \
-	b='test_digestauth_with_arguments'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-.test.log:
-	@p='$<'; \
-	$(am__set_b); \
-	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-@am__EXEEXT_TRUE@.test$(EXEEXT).log:
-@am__EXEEXT_TRUE@	@p='$<'; \
-@am__EXEEXT_TRUE@	$(am__set_b); \
-@am__EXEEXT_TRUE@	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-@am__EXEEXT_TRUE@	--log-file $$b.log --trs-file $$b.trs \
-@am__EXEEXT_TRUE@	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-@am__EXEEXT_TRUE@	"$$tst" $(AM_TESTS_FD_REDIRECT)
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
-	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
-check: check-recursive
-all-am: Makefile $(LIBRARIES) $(PROGRAMS)
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-	-test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS)
-	-test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs)
-	-test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-checkPROGRAMS clean-generic clean-libtool \
-	clean-noinstLIBRARIES clean-noinstPROGRAMS mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) check-am install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-TESTS check-am clean clean-checkPROGRAMS clean-generic \
-	clean-libtool clean-noinstLIBRARIES clean-noinstPROGRAMS \
-	cscopelist-am ctags ctags-am distclean distclean-compile \
-	distclean-generic distclean-libtool distclean-tags distdir dvi \
-	dvi-am html html-am info info-am install install-am \
-	install-data install-data-am install-dvi install-dvi-am \
-	install-exec install-exec-am install-html install-html-am \
-	install-info install-info-am install-man install-pdf \
-	install-pdf-am install-ps install-ps-am install-strip \
-	installcheck installcheck-am installdirs installdirs-am \
-	maintainer-clean maintainer-clean-generic mostlyclean \
-	mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
-	pdf pdf-am ps ps-am recheck tags tags-am uninstall \
-	uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/testcurl/curl_version_check.c b/src/testcurl/curl_version_check.c
deleted file mode 100644
index 518cb86..0000000
--- a/src/testcurl/curl_version_check.c
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
-     This file is part of libmicrohttpd
-     Copyright (C) 2007 Christian Grothoff
-
-     libmicrohttpd 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 2, or (at your
-     option) any later version.
-
-     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
-*/
-
-/**
- * @file curl_version_check.c
- * @brief  verify required cURL version is available to run tests
- * @author Sagie Amir
- */
-
-#include "MHD_config.h"
-#include "platform.h"
-#include <curl/curl.h>
-
-#ifndef WINDOWS
-#include <unistd.h>
-#endif
-
-static int
-parse_version_number (const char **s)
-{
-  int i = 0;
-  char num[17];
-
-  while (i < 16 && ((**s >= '0') & (**s <= '9')))
-    {
-      num[i] = **s;
-      (*s)++;
-      i++;
-    }
-
-  num[i] = '\0';
-
-  return atoi (num);
-}
-
-const char *
-parse_version_string (const char *s, int *major, int *minor, int *micro)
-{
-  if (!s)
-    return NULL;
-  *major = parse_version_number (&s);
-  if (*s != '.')
-    return NULL;
-  s++;
-  *minor = parse_version_number (&s);
-  if (*s != '.')
-    return NULL;
-  s++;
-  *micro = parse_version_number (&s);
-  return s;
-}
-
-#if HTTPS_SUPPORT
-int
-curl_uses_nss_ssl()
-{
-  return (strstr(curl_version(), " NSS/") != NULL) ? 0 : -1;
-}
-#endif
-
-/*
- * check local libcurl version matches required version
- */
-int
-curl_check_version (const char *req_version)
-{
-  const char *ver;
-  const char *curl_ver;
-#if HTTPS_SUPPORT
-  const char *ssl_ver;
-  const char *req_ssl_ver;
-#endif
-
-  int loc_major, loc_minor, loc_micro;
-  int rq_major, rq_minor, rq_micro;
-
-  ver = curl_version ();
-#if HAVE_MESSAGES
-  fprintf (stderr, "curl version: %s\n", ver);
-#endif
-  /*
-   * this call relies on the cURL string to be of the exact following format :
-   * 'libcurl/7.16.4 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/0.6.5' OR
-   * 'libcurl/7.18.2 GnuTLS/2.4.0 zlib/1.2.3.3 libidn/0.6.5'
-   */
-  curl_ver = strchr (ver, '/');
-  if (curl_ver == NULL)
-    return -1;
-  curl_ver++;
-  /* Parse version numbers */
-  if ( (NULL == parse_version_string (req_version, &rq_major, &rq_minor, &rq_micro)) ||
-       (NULL == parse_version_string (curl_ver, &loc_major, &loc_minor, &loc_micro)) )
-    return -1;
-
-  /* Compare version numbers.  */
-  if ((loc_major > rq_major
-       || (loc_major == rq_major && loc_minor > rq_minor)
-       || (loc_major == rq_major && loc_minor == rq_minor
-           && loc_micro > rq_micro) || (loc_major == rq_major
-                                        && loc_minor == rq_minor
-                                        && loc_micro == rq_micro)) == 0)
-    {
-      fprintf (stderr,
-               "Error: running curl test depends on local libcurl version > %s\n",
-               req_version);
-      return -1;
-    }
-
-  /*
-   * enforce required gnutls/openssl version.
-   * TODO use curl version string to assert use of gnutls
-   */
-#if HTTPS_SUPPORT
-  ssl_ver = strchr (curl_ver, ' ');
-  if (ssl_ver == NULL)
-    return -1;
-  ssl_ver++;
-  if (strncmp ("GnuTLS", ssl_ver, strlen ("GNUtls")) == 0)
-    {
-      ssl_ver = strchr (ssl_ver, '/');
-      req_ssl_ver = MHD_REQ_CURL_GNUTLS_VERSION;
-    }
-  else if (strncmp ("OpenSSL", ssl_ver, strlen ("OpenSSL")) == 0)
-    {
-      ssl_ver = strchr (ssl_ver, '/');
-      req_ssl_ver = MHD_REQ_CURL_OPENSSL_VERSION;
-    }
-  else if (strncmp ("NSS", ssl_ver, strlen ("NSS")) == 0)
-    {
-      ssl_ver = strchr (ssl_ver, '/');
-      req_ssl_ver = MHD_REQ_CURL_NSS_VERSION;
-    }
-  else
-    {
-      fprintf (stderr, "Error: unrecognized curl ssl library\n");
-      return -1;
-    }
-  if (ssl_ver == NULL)
-    return -1;
-  ssl_ver++;
-  if ( (NULL == parse_version_string (req_ssl_ver, &rq_major, &rq_minor, &rq_micro)) ||
-       (NULL == parse_version_string (ssl_ver, &loc_major, &loc_minor, &loc_micro)) )
-    return -1;
-
-  if ((loc_major > rq_major
-       || (loc_major == rq_major && loc_minor > rq_minor)
-       || (loc_major == rq_major && loc_minor == rq_minor
-           && loc_micro > rq_micro) || (loc_major == rq_major
-                                        && loc_minor == rq_minor
-                                        && loc_micro == rq_micro)) == 0)
-    {
-      fprintf (stderr,
-               "Error: running curl test depends on local libcurl SSL version > %s\n",
-               req_ssl_ver);
-      return -1;
-    }
-#endif
-  return 0;
-}
diff --git a/src/testcurl/gauger.h b/src/testcurl/gauger.h
deleted file mode 100644
index 3a0dd22..0000000
--- a/src/testcurl/gauger.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/** ---------------------------------------------------------------------------
- * This software is in the public domain, furnished "as is", without technical
- * support, and with no warranty, express or implied, as to its usefulness for
- * any purpose.
- *
- * gauger.h
- * Interface for C programs to log remotely to a gauger server
- *
- * Author: Bartlomiej Polot
- * -------------------------------------------------------------------------*/
-#ifndef __GAUGER_H__
-#define __GAUGER_H__
-
-#ifndef WINDOWS
-
-#include <unistd.h>
-#include <stdio.h>
-#include <sys/wait.h>
-
-#define GAUGER(category, counter, value, unit)\
-{\
-    const char * __gauger_v[10];			\
-    char __gauger_s[32];\
-    pid_t __gauger_p;\
-    if(!(__gauger_p=fork())){\
-      if(!fork()){ \
-            sprintf(__gauger_s,"%Lf", (long double) (value));\
-            __gauger_v[0] = "gauger";\
-            __gauger_v[1] = "-n";\
-            __gauger_v[2] = counter;	\
-            __gauger_v[3] = "-d";\
-            __gauger_v[4] = __gauger_s;\
-            __gauger_v[5] = "-u";\
-            __gauger_v[6] = unit;	\
-            __gauger_v[7] = "-c";\
-            __gauger_v[8] = category;	\
-            __gauger_v[9] = (char *)NULL;\
-            execvp("gauger", (char*const*) __gauger_v);	\
-            _exit(1);\
-        }else{\
-            _exit(0);\
-        }\
-    }else{\
-        waitpid(__gauger_p,NULL,0);\
-    }\
-}
-
-#define GAUGER_ID(category, counter, value, unit, id)\
-{\
-    char* __gauger_v[12];\
-    char __gauger_s[32];\
-    pid_t __gauger_p;\
-    if(!(__gauger_p=fork())){\
-        if(!fork()){\
-            sprintf(__gauger_s,"%Lf", (long double) (value));\
-            __gauger_v[0] = "gauger";\
-            __gauger_v[1] = "-n";\
-            __gauger_v[2] = counter;\
-            __gauger_v[3] = "-d";\
-            __gauger_v[4] = __gauger_s;\
-            __gauger_v[5] = "-u";\
-            __gauger_v[6] = unit;\
-            __gauger_v[7] = "-i";\
-            __gauger_v[8] = id;\
-            __gauger_v[9] = "-c";\
-            __gauger_v[10] = category;\
-            __gauger_v[11] = (char *)NULL;\
-            execvp("gauger",__gauger_v);\
-            perror("gauger");\
-            _exit(1);\
-        }else{\
-            _exit(0);\
-        }\
-    }else{\
-        waitpid(__gauger_p,NULL,0);\
-    }\
-}
-
-#else
-
-#define GAUGER_ID(category, counter, value, unit, id) {}
-#define GAUGER(category, counter, value, unit) {}
-
-#endif // WINDOWS
-
-#endif
diff --git a/src/testcurl/https/.gitignore b/src/testcurl/https/.gitignore
new file mode 100644
index 0000000..7175906
--- /dev/null
+++ b/src/testcurl/https/.gitignore
@@ -0,0 +1,57 @@
+/test_https_sni
+/test_tls_options
+/test_tls_authentication
+/test_https_time_out
+/test_https_session_info
+/test_https_multi_daemon
+/test_https_get_select
+/test_https_get_parallel_threads
+/test_https_get_parallel
+/test_https_get
+/test_empty_response
+/mhds_get_test_select.gcno
+/mhds_get_test_select.gcda
+/mhds_get_test_select
+/tls_test_common.gcno
+/tls_test_common.gcda
+/tls_session_time_out_test.gcno
+/tls_session_time_out_test.gcda
+/tls_multi_thread_mode_test.gcno
+/tls_multi_thread_mode_test.gcda
+/tls_extension_test.gcno
+/tls_extension_test.gcda
+/tls_cipher_change_test.gcno
+/tls_cipher_change_test.gcda
+/tls_alert_test.gcno
+/tls_alert_test.gcda
+/mhds_get_test.gcno
+/mhds_get_test.gcda
+/tls_multi_thread_mode_test
+/tls_extension_test
+/https_test_file
+/tls_daemon_options_test.gcno
+/tls_authentication_test.gcno
+/tls_thread_mode_test.gcda
+/tls_thread_mode_test
+/mhds_session_info_test.gcno
+/tls_daemon_options_test
+/tls_cipher_change_test
+/.deps
+/tls_thread_mode_test.gcno
+/mhds_multi_daemon_test.gcda
+/tls_alert_test
+/tls_daemon_options_test.gcda
+/tls_authentication_test.gcda
+/mhds_session_info_test.gcda
+/tls_session_time_out_test
+/tls_daemon_options_dh_test
+/tls_daemon_options_adh_test
+/mhds_multi_daemon_test.gcno
+/mhds_get_test
+/mhds_test_session_info
+/mhds_session_info_test
+/mhds_multi_daemon_test
+/tls_authentication_test
+/tmp_ca_cert.pem
+/test_https_get_iovec
+*.exe
diff --git a/src/testcurl/https/Makefile.am b/src/testcurl/https/Makefile.am
index 47deb70..f07eceb 100644
--- a/src/testcurl/https/Makefile.am
+++ b/src/testcurl/https/Makefile.am
@@ -1,153 +1,159 @@
 # This Makefile.am is in the public domain
+EMPTY_ITEM =
+
 SUBDIRS = .
 
+@HEAVY_TESTS_NOTPARALLEL@
+
+AM_CPPFLAGS = \
+  -I$(top_srcdir)/src/include \
+  -I$(top_srcdir)/src/microhttpd \
+  -DMHD_CPU_COUNT=$(CPU_COUNT) \
+  -DSRCDIR=\"$(srcdir)\" \
+  $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS)
+
+AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@
+
+AM_LDFLAGS = $(LDFLAGS_ac)
+
+AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac)
+
 if USE_COVERAGE
-  AM_CFLAGS = --coverage
+  AM_CFLAGS += --coverage
 endif
 
+$(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile
+	@echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \
+	$(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la
+
+LDADD = \
+  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
+  $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) @LIBGCRYPT_LIBS@ @LIBCURL@
+
 if HAVE_GNUTLS_SNI
   TEST_HTTPS_SNI = test_https_sni
 endif
 
 if HAVE_POSIX_THREADS
-  HTTPS_PARALLEL_TESTS = test_https_get_parallel \
-  test_https_get_parallel_threads
+HTTPS_PARALLEL_TESTS = \
+    test_https_get_parallel \
+    test_https_get_parallel_threads
 endif
 
-CPU_COUNT_DEF = -DCPU_COUNT=$(CPU_COUNT)
+THREAD_ONLY_TESTS = \
+  test_tls_options \
+  test_tls_authentication \
+  $(HTTPS_PARALLEL_TESTS) \
+  $(TEST_HTTPS_SNI) \
+  test_https_session_info \
+  test_https_session_info_append \
+  test_https_multi_daemon \
+  test_https_get \
+  test_empty_response \
+  test_https_get_iovec \
+  $(EMPTY_ITEM)
 
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include \
-  -I$(top_srcdir)/src/microhttpd \
-  -I$(top_srcdir)/src/platform \
-  $(LIBCURL_CPPFLAGS) $(GNUTLS_CPPFLAGS)
+if !HAVE_GNUTLS_MTHREAD_BROKEN
+THREAD_ONLY_TESTS += \
+  test_https_time_out \
+  $(EMPTY_ITEM)
+endif
 
 check_PROGRAMS = \
-  test_tls_options \
-  test_tls_authentication \
-  test_https_multi_daemon \
-  test_https_get \
-  $(TEST_HTTPS_SNI) \
-  test_https_get_select \
-  $(HTTPS_PARALLEL_TESTS) \
-  test_https_session_info \
-  test_https_time_out \
-  test_empty_response
+  test_https_get_select
 
-EXTRA_DIST = cert.pem key.pem tls_test_keys.h tls_test_common.h \
-  host1.crt host1.key host2.crt host2.key
+if USE_THREADS
+check_PROGRAMS += \
+  $(THREAD_ONLY_TESTS)
+endif
+
+EXTRA_DIST = \
+  test-ca.crt test-ca.key \
+  mhdhost1.crt mhdhost1.key \
+  mhdhost2.crt mhdhost2.key
 
 TESTS = \
-  test_tls_options \
-  test_https_multi_daemon \
-  test_https_get \
-  $(TEST_HTTPS_SNI) \
-  test_https_get_select \
-  $(HTTPS_PARALLEL_TESTS) \
-  test_https_session_info \
-  test_https_time_out \
-  test_tls_authentication \
-  test_empty_response
+  $(check_PROGRAMS)
 
 
 test_https_time_out_SOURCES = \
   test_https_time_out.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_time_out_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
 
 test_tls_options_SOURCES = \
   test_tls_options.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_tls_options_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
 
 test_https_get_parallel_SOURCES = \
   test_https_get_parallel.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_get_parallel_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
 test_https_get_parallel_CFLAGS = \
-  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
 test_https_get_parallel_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(PTHREAD_LIBS) $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
+  $(PTHREAD_LIBS) $(LDADD)
 
 test_empty_response_SOURCES = \
   test_empty_response.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_empty_response_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
 
 test_https_get_parallel_threads_SOURCES = \
   test_https_get_parallel_threads.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_get_parallel_threads_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
 test_https_get_parallel_threads_CFLAGS = \
-  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
+  $(AM_CFLAGS) $(PTHREAD_CFLAGS)
 test_https_get_parallel_threads_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(PTHREAD_LIBS) $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
+  $(PTHREAD_LIBS) $(LDADD)
 
 test_tls_authentication_SOURCES = \
   test_tls_authentication.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_tls_authentication_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
 
 test_https_session_info_SOURCES = \
   test_https_session_info.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_session_info_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
+
+test_https_session_info_append_SOURCES = $(test_https_session_info_SOURCES)
 
 test_https_multi_daemon_SOURCES = \
   test_https_multi_daemon.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_multi_daemon_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
 
 test_https_get_SOURCES = \
   test_https_get.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_get_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
 
-if HAVE_GNUTLS_SNI
+test_https_get_iovec_SOURCES = \
+  test_https_get_iovec.c \
+  tls_test_keys.h \
+  tls_test_common.h \
+  tls_test_common.c
+
 test_https_sni_SOURCES = \
   test_https_sni.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_sni_CPPFLAGS = \
-  $(AM_CPPFLAGS) \
-  -DABS_SRCDIR=\"$(abs_srcdir)\"
-test_https_sni_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-endif
 
 test_https_get_select_SOURCES = \
   test_https_get_select.c \
+  tls_test_keys.h \
+  tls_test_common.h \
   tls_test_common.c
-test_https_get_select_LDADD  = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
diff --git a/src/testcurl/https/Makefile.in b/src/testcurl/https/Makefile.in
deleted file mode 100644
index 8815b21..0000000
--- a/src/testcurl/https/Makefile.in
+++ /dev/null
@@ -1,1578 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-check_PROGRAMS = test_tls_options$(EXEEXT) \
-	test_tls_authentication$(EXEEXT) \
-	test_https_multi_daemon$(EXEEXT) test_https_get$(EXEEXT) \
-	$(am__EXEEXT_1) test_https_get_select$(EXEEXT) $(am__EXEEXT_2) \
-	test_https_session_info$(EXEEXT) test_https_time_out$(EXEEXT) \
-	test_empty_response$(EXEEXT)
-TESTS = test_tls_options$(EXEEXT) test_https_multi_daemon$(EXEEXT) \
-	test_https_get$(EXEEXT) $(am__EXEEXT_1) \
-	test_https_get_select$(EXEEXT) $(am__EXEEXT_2) \
-	test_https_session_info$(EXEEXT) test_https_time_out$(EXEEXT) \
-	test_tls_authentication$(EXEEXT) test_empty_response$(EXEEXT)
-subdir = src/testcurl/https
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp $(top_srcdir)/test-driver
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-@HAVE_GNUTLS_SNI_TRUE@am__EXEEXT_1 = test_https_sni$(EXEEXT)
-@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_2 =  \
-@HAVE_POSIX_THREADS_TRUE@	test_https_get_parallel$(EXEEXT) \
-@HAVE_POSIX_THREADS_TRUE@	test_https_get_parallel_threads$(EXEEXT)
-am_test_empty_response_OBJECTS = test_empty_response.$(OBJEXT) \
-	tls_test_common.$(OBJEXT)
-test_empty_response_OBJECTS = $(am_test_empty_response_OBJECTS)
-am__DEPENDENCIES_1 =
-test_empty_response_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-am_test_https_get_OBJECTS = test_https_get.$(OBJEXT) \
-	tls_test_common.$(OBJEXT)
-test_https_get_OBJECTS = $(am_test_https_get_OBJECTS)
-test_https_get_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am_test_https_get_parallel_OBJECTS =  \
-	test_https_get_parallel-test_https_get_parallel.$(OBJEXT) \
-	test_https_get_parallel-tls_test_common.$(OBJEXT)
-test_https_get_parallel_OBJECTS =  \
-	$(am_test_https_get_parallel_OBJECTS)
-test_https_get_parallel_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-test_https_get_parallel_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(test_https_get_parallel_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-	$(LDFLAGS) -o $@
-am_test_https_get_parallel_threads_OBJECTS = test_https_get_parallel_threads-test_https_get_parallel_threads.$(OBJEXT) \
-	test_https_get_parallel_threads-tls_test_common.$(OBJEXT)
-test_https_get_parallel_threads_OBJECTS =  \
-	$(am_test_https_get_parallel_threads_OBJECTS)
-test_https_get_parallel_threads_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-test_https_get_parallel_threads_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-am_test_https_get_select_OBJECTS = test_https_get_select.$(OBJEXT) \
-	tls_test_common.$(OBJEXT)
-test_https_get_select_OBJECTS = $(am_test_https_get_select_OBJECTS)
-test_https_get_select_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am_test_https_multi_daemon_OBJECTS =  \
-	test_https_multi_daemon.$(OBJEXT) tls_test_common.$(OBJEXT)
-test_https_multi_daemon_OBJECTS =  \
-	$(am_test_https_multi_daemon_OBJECTS)
-test_https_multi_daemon_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am_test_https_session_info_OBJECTS =  \
-	test_https_session_info.$(OBJEXT) tls_test_common.$(OBJEXT)
-test_https_session_info_OBJECTS =  \
-	$(am_test_https_session_info_OBJECTS)
-test_https_session_info_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am__test_https_sni_SOURCES_DIST = test_https_sni.c tls_test_common.c
-@HAVE_GNUTLS_SNI_TRUE@am_test_https_sni_OBJECTS =  \
-@HAVE_GNUTLS_SNI_TRUE@	test_https_sni-test_https_sni.$(OBJEXT) \
-@HAVE_GNUTLS_SNI_TRUE@	test_https_sni-tls_test_common.$(OBJEXT)
-test_https_sni_OBJECTS = $(am_test_https_sni_OBJECTS)
-@HAVE_GNUTLS_SNI_TRUE@test_https_sni_DEPENDENCIES = $(top_builddir)/src/testcurl/libcurl_version_check.a \
-@HAVE_GNUTLS_SNI_TRUE@	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-@HAVE_GNUTLS_SNI_TRUE@	$(am__DEPENDENCIES_1) \
-@HAVE_GNUTLS_SNI_TRUE@	$(am__DEPENDENCIES_1)
-am_test_https_time_out_OBJECTS = test_https_time_out.$(OBJEXT) \
-	tls_test_common.$(OBJEXT)
-test_https_time_out_OBJECTS = $(am_test_https_time_out_OBJECTS)
-test_https_time_out_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am_test_tls_authentication_OBJECTS =  \
-	test_tls_authentication.$(OBJEXT) tls_test_common.$(OBJEXT)
-test_tls_authentication_OBJECTS =  \
-	$(am_test_tls_authentication_OBJECTS)
-test_tls_authentication_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am_test_tls_options_OBJECTS = test_tls_options.$(OBJEXT) \
-	tls_test_common.$(OBJEXT)
-test_tls_options_OBJECTS = $(am_test_tls_options_OBJECTS)
-test_tls_options_DEPENDENCIES =  \
-	$(top_builddir)/src/testcurl/libcurl_version_check.a \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(test_empty_response_SOURCES) $(test_https_get_SOURCES) \
-	$(test_https_get_parallel_SOURCES) \
-	$(test_https_get_parallel_threads_SOURCES) \
-	$(test_https_get_select_SOURCES) \
-	$(test_https_multi_daemon_SOURCES) \
-	$(test_https_session_info_SOURCES) $(test_https_sni_SOURCES) \
-	$(test_https_time_out_SOURCES) \
-	$(test_tls_authentication_SOURCES) $(test_tls_options_SOURCES)
-DIST_SOURCES = $(test_empty_response_SOURCES) \
-	$(test_https_get_SOURCES) $(test_https_get_parallel_SOURCES) \
-	$(test_https_get_parallel_threads_SOURCES) \
-	$(test_https_get_select_SOURCES) \
-	$(test_https_multi_daemon_SOURCES) \
-	$(test_https_session_info_SOURCES) \
-	$(am__test_https_sni_SOURCES_DIST) \
-	$(test_https_time_out_SOURCES) \
-	$(test_tls_authentication_SOURCES) $(test_tls_options_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	check recheck distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-am__tty_colors_dummy = \
-  mgn= red= grn= lgn= blu= brg= std=; \
-  am__color_tests=no
-am__tty_colors = { \
-  $(am__tty_colors_dummy); \
-  if test "X$(AM_COLOR_TESTS)" = Xno; then \
-    am__color_tests=no; \
-  elif test "X$(AM_COLOR_TESTS)" = Xalways; then \
-    am__color_tests=yes; \
-  elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \
-    am__color_tests=yes; \
-  fi; \
-  if test $$am__color_tests = yes; then \
-    red=''; \
-    grn=''; \
-    lgn=''; \
-    blu=''; \
-    mgn=''; \
-    brg=''; \
-    std=''; \
-  fi; \
-}
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__recheck_rx = ^[ 	]*:recheck:[ 	]*
-am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
-am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
-# A command that, given a newline-separated list of test names on the
-# standard input, print the name of the tests that are to be re-run
-# upon "make recheck".
-am__list_recheck_tests = $(AWK) '{ \
-  recheck = 1; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-        { \
-          if ((getline line2 < ($$0 ".log")) < 0) \
-	    recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \
-        { \
-          recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \
-        { \
-          break; \
-        } \
-    }; \
-  if (recheck) \
-    print $$0; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# A command that, given a newline-separated list of test names on the
-# standard input, create the global log from their .trs and .log files.
-am__create_global_log = $(AWK) ' \
-function fatal(msg) \
-{ \
-  print "fatal: making $@: " msg | "cat >&2"; \
-  exit 1; \
-} \
-function rst_section(header) \
-{ \
-  print header; \
-  len = length(header); \
-  for (i = 1; i <= len; i = i + 1) \
-    printf "="; \
-  printf "\n\n"; \
-} \
-{ \
-  copy_in_global_log = 1; \
-  global_test_result = "RUN"; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-         fatal("failed to read from " $$0 ".trs"); \
-      if (line ~ /$(am__global_test_result_rx)/) \
-        { \
-          sub("$(am__global_test_result_rx)", "", line); \
-          sub("[ 	]*$$", "", line); \
-          global_test_result = line; \
-        } \
-      else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \
-        copy_in_global_log = 0; \
-    }; \
-  if (copy_in_global_log) \
-    { \
-      rst_section(global_test_result ": " $$0); \
-      while ((rc = (getline line < ($$0 ".log"))) != 0) \
-      { \
-        if (rc < 0) \
-          fatal("failed to read from " $$0 ".log"); \
-        print line; \
-      }; \
-      printf "\n"; \
-    }; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# Restructured Text title.
-am__rst_title = { sed 's/.*/   &   /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; }
-# Solaris 10 'make', and several other traditional 'make' implementations,
-# pass "-e" to $(SHELL), and POSIX 2008 even requires this.  Work around it
-# by disabling -e (using the XSI extension "set +e") if it's set.
-am__sh_e_setup = case $$- in *e*) set +e;; esac
-# Default flags passed to test drivers.
-am__common_driver_flags = \
-  --color-tests "$$am__color_tests" \
-  --enable-hard-errors "$$am__enable_hard_errors" \
-  --expect-failure "$$am__expect_failure"
-# To be inserted before the command running the test.  Creates the
-# directory for the log if needed.  Stores in $dir the directory
-# containing $f, in $tst the test, in $log the log.  Executes the
-# developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and
-# passes TESTS_ENVIRONMENT.  Set up options for the wrapper that
-# will run the test scripts (or their associated LOG_COMPILER, if
-# thy have one).
-am__check_pre = \
-$(am__sh_e_setup);					\
-$(am__vpath_adj_setup) $(am__vpath_adj)			\
-$(am__tty_colors);					\
-srcdir=$(srcdir); export srcdir;			\
-case "$@" in						\
-  */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;;	\
-    *) am__odir=.;; 					\
-esac;							\
-test "x$$am__odir" = x"." || test -d "$$am__odir" 	\
-  || $(MKDIR_P) "$$am__odir" || exit $$?;		\
-if test -f "./$$f"; then dir=./;			\
-elif test -f "$$f"; then dir=;				\
-else dir="$(srcdir)/"; fi;				\
-tst=$$dir$$f; log='$@'; 				\
-if test -n '$(DISABLE_HARD_ERRORS)'; then		\
-  am__enable_hard_errors=no; 				\
-else							\
-  am__enable_hard_errors=yes; 				\
-fi; 							\
-case " $(XFAIL_TESTS) " in				\
-  *[\ \	]$$f[\ \	]* | *[\ \	]$$dir$$f[\ \	]*) \
-    am__expect_failure=yes;;				\
-  *)							\
-    am__expect_failure=no;;				\
-esac; 							\
-$(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT)
-# A shell command to get the names of the tests scripts with any registered
-# extension removed (i.e., equivalently, the names of the test logs, with
-# the '.log' extension removed).  The result is saved in the shell variable
-# '$bases'.  This honors runtime overriding of TESTS and TEST_LOGS.  Sadly,
-# we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)",
-# since that might cause problem with VPATH rewrites for suffix-less tests.
-# See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'.
-am__set_TESTS_bases = \
-  bases='$(TEST_LOGS)'; \
-  bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \
-  bases=`echo $$bases`
-RECHECK_LOGS = $(TEST_LOGS)
-TEST_SUITE_LOG = test-suite.log
-TEST_EXTENSIONS = @EXEEXT@ .test
-LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)
-am__set_b = \
-  case '$@' in \
-    */*) \
-      case '$*' in \
-        */*) b='$*';; \
-          *) b=`echo '$@' | sed 's/\.log$$//'`; \
-       esac;; \
-    *) \
-      b='$*';; \
-  esac
-am__test_logs1 = $(TESTS:=.log)
-am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log)
-TEST_LOGS = $(am__test_logs2:.test.log=.log)
-TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
-	$(TEST_LOG_FLAGS)
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-@USE_COVERAGE_TRUE@AM_CFLAGS = --coverage
-@HAVE_GNUTLS_SNI_TRUE@TEST_HTTPS_SNI = test_https_sni
-@HAVE_POSIX_THREADS_TRUE@HTTPS_PARALLEL_TESTS = test_https_get_parallel \
-@HAVE_POSIX_THREADS_TRUE@  test_https_get_parallel_threads
-
-CPU_COUNT_DEF = -DCPU_COUNT=$(CPU_COUNT)
-AM_CPPFLAGS = \
-  -I$(top_srcdir)/src/include \
-  -I$(top_srcdir)/src/microhttpd \
-  -I$(top_srcdir)/src/platform \
-  $(LIBCURL_CPPFLAGS) $(GNUTLS_CPPFLAGS)
-
-EXTRA_DIST = cert.pem key.pem tls_test_keys.h tls_test_common.h \
-  host1.crt host1.key host2.crt host2.key
-
-test_https_time_out_SOURCES = \
-  test_https_time_out.c \
-  tls_test_common.c
-
-test_https_time_out_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_tls_options_SOURCES = \
-  test_tls_options.c \
-  tls_test_common.c
-
-test_tls_options_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_https_get_parallel_SOURCES = \
-  test_https_get_parallel.c \
-  tls_test_common.c
-
-test_https_get_parallel_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
-
-test_https_get_parallel_CFLAGS = \
-  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
-
-test_https_get_parallel_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(PTHREAD_LIBS) $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_empty_response_SOURCES = \
-  test_empty_response.c \
-  tls_test_common.c
-
-test_empty_response_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_https_get_parallel_threads_SOURCES = \
-  test_https_get_parallel_threads.c \
-  tls_test_common.c
-
-test_https_get_parallel_threads_CPPFLAGS = \
-  $(AM_CPPFLAGS) $(CPU_COUNT_DEF)
-
-test_https_get_parallel_threads_CFLAGS = \
-  $(PTHREAD_CFLAGS) $(AM_CFLAGS)
-
-test_https_get_parallel_threads_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(PTHREAD_LIBS) $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_tls_authentication_SOURCES = \
-  test_tls_authentication.c \
-  tls_test_common.c
-
-test_tls_authentication_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_https_session_info_SOURCES = \
-  test_https_session_info.c \
-  tls_test_common.c
-
-test_https_session_info_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_https_multi_daemon_SOURCES = \
-  test_https_multi_daemon.c \
-  tls_test_common.c
-
-test_https_multi_daemon_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_https_get_SOURCES = \
-  test_https_get.c \
-  tls_test_common.c
-
-test_https_get_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-@HAVE_GNUTLS_SNI_TRUE@test_https_sni_SOURCES = \
-@HAVE_GNUTLS_SNI_TRUE@  test_https_sni.c \
-@HAVE_GNUTLS_SNI_TRUE@  tls_test_common.c
-
-@HAVE_GNUTLS_SNI_TRUE@test_https_sni_CPPFLAGS = \
-@HAVE_GNUTLS_SNI_TRUE@  $(AM_CPPFLAGS) \
-@HAVE_GNUTLS_SNI_TRUE@  -DABS_SRCDIR=\"$(abs_srcdir)\"
-
-@HAVE_GNUTLS_SNI_TRUE@test_https_sni_LDADD = \
-@HAVE_GNUTLS_SNI_TRUE@  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-@HAVE_GNUTLS_SNI_TRUE@  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-@HAVE_GNUTLS_SNI_TRUE@  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-test_https_get_select_SOURCES = \
-  test_https_get_select.c \
-  tls_test_common.c
-
-test_https_get_select_LDADD = \
-  $(top_builddir)/src/testcurl/libcurl_version_check.a \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  $(GNUTLS_LDFLAGS) $(GNUTLS_LIBS) @LIBGCRYPT_LIBS@ @LIBCURL@
-
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testcurl/https/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/testcurl/https/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-checkPROGRAMS:
-	@list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-test_empty_response$(EXEEXT): $(test_empty_response_OBJECTS) $(test_empty_response_DEPENDENCIES) $(EXTRA_test_empty_response_DEPENDENCIES) 
-	@rm -f test_empty_response$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_empty_response_OBJECTS) $(test_empty_response_LDADD) $(LIBS)
-
-test_https_get$(EXEEXT): $(test_https_get_OBJECTS) $(test_https_get_DEPENDENCIES) $(EXTRA_test_https_get_DEPENDENCIES) 
-	@rm -f test_https_get$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_https_get_OBJECTS) $(test_https_get_LDADD) $(LIBS)
-
-test_https_get_parallel$(EXEEXT): $(test_https_get_parallel_OBJECTS) $(test_https_get_parallel_DEPENDENCIES) $(EXTRA_test_https_get_parallel_DEPENDENCIES) 
-	@rm -f test_https_get_parallel$(EXEEXT)
-	$(AM_V_CCLD)$(test_https_get_parallel_LINK) $(test_https_get_parallel_OBJECTS) $(test_https_get_parallel_LDADD) $(LIBS)
-
-test_https_get_parallel_threads$(EXEEXT): $(test_https_get_parallel_threads_OBJECTS) $(test_https_get_parallel_threads_DEPENDENCIES) $(EXTRA_test_https_get_parallel_threads_DEPENDENCIES) 
-	@rm -f test_https_get_parallel_threads$(EXEEXT)
-	$(AM_V_CCLD)$(test_https_get_parallel_threads_LINK) $(test_https_get_parallel_threads_OBJECTS) $(test_https_get_parallel_threads_LDADD) $(LIBS)
-
-test_https_get_select$(EXEEXT): $(test_https_get_select_OBJECTS) $(test_https_get_select_DEPENDENCIES) $(EXTRA_test_https_get_select_DEPENDENCIES) 
-	@rm -f test_https_get_select$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_https_get_select_OBJECTS) $(test_https_get_select_LDADD) $(LIBS)
-
-test_https_multi_daemon$(EXEEXT): $(test_https_multi_daemon_OBJECTS) $(test_https_multi_daemon_DEPENDENCIES) $(EXTRA_test_https_multi_daemon_DEPENDENCIES) 
-	@rm -f test_https_multi_daemon$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_https_multi_daemon_OBJECTS) $(test_https_multi_daemon_LDADD) $(LIBS)
-
-test_https_session_info$(EXEEXT): $(test_https_session_info_OBJECTS) $(test_https_session_info_DEPENDENCIES) $(EXTRA_test_https_session_info_DEPENDENCIES) 
-	@rm -f test_https_session_info$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_https_session_info_OBJECTS) $(test_https_session_info_LDADD) $(LIBS)
-
-test_https_sni$(EXEEXT): $(test_https_sni_OBJECTS) $(test_https_sni_DEPENDENCIES) $(EXTRA_test_https_sni_DEPENDENCIES) 
-	@rm -f test_https_sni$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_https_sni_OBJECTS) $(test_https_sni_LDADD) $(LIBS)
-
-test_https_time_out$(EXEEXT): $(test_https_time_out_OBJECTS) $(test_https_time_out_DEPENDENCIES) $(EXTRA_test_https_time_out_DEPENDENCIES) 
-	@rm -f test_https_time_out$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_https_time_out_OBJECTS) $(test_https_time_out_LDADD) $(LIBS)
-
-test_tls_authentication$(EXEEXT): $(test_tls_authentication_OBJECTS) $(test_tls_authentication_DEPENDENCIES) $(EXTRA_test_tls_authentication_DEPENDENCIES) 
-	@rm -f test_tls_authentication$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_tls_authentication_OBJECTS) $(test_tls_authentication_LDADD) $(LIBS)
-
-test_tls_options$(EXEEXT): $(test_tls_options_OBJECTS) $(test_tls_options_DEPENDENCIES) $(EXTRA_test_tls_options_DEPENDENCIES) 
-	@rm -f test_tls_options$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_tls_options_OBJECTS) $(test_tls_options_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_empty_response.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_select.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_multi_daemon.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_session_info.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_sni-test_https_sni.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_sni-tls_test_common.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_time_out.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tls_authentication.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tls_options.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tls_test_common.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-test_https_get_parallel-test_https_get_parallel.o: test_https_get_parallel.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-test_https_get_parallel.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo -c -o test_https_get_parallel-test_https_get_parallel.o `test -f 'test_https_get_parallel.c' || echo '$(srcdir)/'`test_https_get_parallel.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_https_get_parallel.c' object='test_https_get_parallel-test_https_get_parallel.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-test_https_get_parallel.o `test -f 'test_https_get_parallel.c' || echo '$(srcdir)/'`test_https_get_parallel.c
-
-test_https_get_parallel-test_https_get_parallel.obj: test_https_get_parallel.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-test_https_get_parallel.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo -c -o test_https_get_parallel-test_https_get_parallel.obj `if test -f 'test_https_get_parallel.c'; then $(CYGPATH_W) 'test_https_get_parallel.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_https_get_parallel.c' object='test_https_get_parallel-test_https_get_parallel.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-test_https_get_parallel.obj `if test -f 'test_https_get_parallel.c'; then $(CYGPATH_W) 'test_https_get_parallel.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel.c'; fi`
-
-test_https_get_parallel-tls_test_common.o: tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo -c -o test_https_get_parallel-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel-tls_test_common.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel-tls_test_common.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c
-
-test_https_get_parallel-tls_test_common.obj: tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo -c -o test_https_get_parallel-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel-tls_test_common.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi`
-
-test_https_get_parallel_threads-test_https_get_parallel_threads.o: test_https_get_parallel_threads.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-test_https_get_parallel_threads.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.o `test -f 'test_https_get_parallel_threads.c' || echo '$(srcdir)/'`test_https_get_parallel_threads.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_https_get_parallel_threads.c' object='test_https_get_parallel_threads-test_https_get_parallel_threads.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.o `test -f 'test_https_get_parallel_threads.c' || echo '$(srcdir)/'`test_https_get_parallel_threads.c
-
-test_https_get_parallel_threads-test_https_get_parallel_threads.obj: test_https_get_parallel_threads.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-test_https_get_parallel_threads.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.obj `if test -f 'test_https_get_parallel_threads.c'; then $(CYGPATH_W) 'test_https_get_parallel_threads.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel_threads.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_https_get_parallel_threads.c' object='test_https_get_parallel_threads-test_https_get_parallel_threads.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.obj `if test -f 'test_https_get_parallel_threads.c'; then $(CYGPATH_W) 'test_https_get_parallel_threads.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel_threads.c'; fi`
-
-test_https_get_parallel_threads-tls_test_common.o: tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo -c -o test_https_get_parallel_threads-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel_threads-tls_test_common.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c
-
-test_https_get_parallel_threads-tls_test_common.obj: tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo -c -o test_https_get_parallel_threads-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel_threads-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_get_parallel_threads_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi`
-
-test_https_sni-test_https_sni.o: test_https_sni.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_https_sni-test_https_sni.o -MD -MP -MF $(DEPDIR)/test_https_sni-test_https_sni.Tpo -c -o test_https_sni-test_https_sni.o `test -f 'test_https_sni.c' || echo '$(srcdir)/'`test_https_sni.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_sni-test_https_sni.Tpo $(DEPDIR)/test_https_sni-test_https_sni.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_https_sni.c' object='test_https_sni-test_https_sni.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_https_sni-test_https_sni.o `test -f 'test_https_sni.c' || echo '$(srcdir)/'`test_https_sni.c
-
-test_https_sni-test_https_sni.obj: test_https_sni.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_https_sni-test_https_sni.obj -MD -MP -MF $(DEPDIR)/test_https_sni-test_https_sni.Tpo -c -o test_https_sni-test_https_sni.obj `if test -f 'test_https_sni.c'; then $(CYGPATH_W) 'test_https_sni.c'; else $(CYGPATH_W) '$(srcdir)/test_https_sni.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_sni-test_https_sni.Tpo $(DEPDIR)/test_https_sni-test_https_sni.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='test_https_sni.c' object='test_https_sni-test_https_sni.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_https_sni-test_https_sni.obj `if test -f 'test_https_sni.c'; then $(CYGPATH_W) 'test_https_sni.c'; else $(CYGPATH_W) '$(srcdir)/test_https_sni.c'; fi`
-
-test_https_sni-tls_test_common.o: tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_https_sni-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_sni-tls_test_common.Tpo -c -o test_https_sni-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_sni-tls_test_common.Tpo $(DEPDIR)/test_https_sni-tls_test_common.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tls_test_common.c' object='test_https_sni-tls_test_common.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_https_sni-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c
-
-test_https_sni-tls_test_common.obj: tls_test_common.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_https_sni-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_sni-tls_test_common.Tpo -c -o test_https_sni-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/test_https_sni-tls_test_common.Tpo $(DEPDIR)/test_https_sni-tls_test_common.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='tls_test_common.c' object='test_https_sni-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_https_sni_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_https_sni-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi`
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-# Recover from deleted '.trs' file; this should ensure that
-# "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create
-# both 'foo.log' and 'foo.trs'.  Break the recipe in two subshells
-# to avoid problems with "make -n".
-.log.trs:
-	rm -f $< $@
-	$(MAKE) $(AM_MAKEFLAGS) $<
-
-# Leading 'am--fnord' is there to ensure the list of targets does not
-# expand to empty, as could happen e.g. with make check TESTS=''.
-am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck)
-am--force-recheck:
-	@:
-
-$(TEST_SUITE_LOG): $(TEST_LOGS)
-	@$(am__set_TESTS_bases); \
-	am__f_ok () { test -f "$$1" && test -r "$$1"; }; \
-	redo_bases=`for i in $$bases; do \
-	              am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \
-	            done`; \
-	if test -n "$$redo_bases"; then \
-	  redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \
-	  redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \
-	  if $(am__make_dryrun); then :; else \
-	    rm -f $$redo_logs && rm -f $$redo_results || exit 1; \
-	  fi; \
-	fi; \
-	if test -n "$$am__remaking_logs"; then \
-	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
-	       "recursion detected" >&2; \
-	else \
-	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
-	fi; \
-	if $(am__make_dryrun); then :; else \
-	  st=0;  \
-	  errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \
-	  for i in $$redo_bases; do \
-	    test -f $$i.trs && test -r $$i.trs \
-	      || { echo "$$errmsg $$i.trs" >&2; st=1; }; \
-	    test -f $$i.log && test -r $$i.log \
-	      || { echo "$$errmsg $$i.log" >&2; st=1; }; \
-	  done; \
-	  test $$st -eq 0 || exit 1; \
-	fi
-	@$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \
-	ws='[ 	]'; \
-	results=`for b in $$bases; do echo $$b.trs; done`; \
-	test -n "$$results" || results=/dev/null; \
-	all=`  grep "^$$ws*:test-result:"           $$results | wc -l`; \
-	pass=` grep "^$$ws*:test-result:$$ws*PASS"  $$results | wc -l`; \
-	fail=` grep "^$$ws*:test-result:$$ws*FAIL"  $$results | wc -l`; \
-	skip=` grep "^$$ws*:test-result:$$ws*SKIP"  $$results | wc -l`; \
-	xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \
-	xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \
-	error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \
-	if test `expr $$fail + $$xpass + $$error` -eq 0; then \
-	  success=true; \
-	else \
-	  success=false; \
-	fi; \
-	br='==================='; br=$$br$$br$$br$$br; \
-	result_count () \
-	{ \
-	    if test x"$$1" = x"--maybe-color"; then \
-	      maybe_colorize=yes; \
-	    elif test x"$$1" = x"--no-color"; then \
-	      maybe_colorize=no; \
-	    else \
-	      echo "$@: invalid 'result_count' usage" >&2; exit 4; \
-	    fi; \
-	    shift; \
-	    desc=$$1 count=$$2; \
-	    if test $$maybe_colorize = yes && test $$count -gt 0; then \
-	      color_start=$$3 color_end=$$std; \
-	    else \
-	      color_start= color_end=; \
-	    fi; \
-	    echo "$${color_start}# $$desc $$count$${color_end}"; \
-	}; \
-	create_testsuite_report () \
-	{ \
-	  result_count $$1 "TOTAL:" $$all   "$$brg"; \
-	  result_count $$1 "PASS: " $$pass  "$$grn"; \
-	  result_count $$1 "SKIP: " $$skip  "$$blu"; \
-	  result_count $$1 "XFAIL:" $$xfail "$$lgn"; \
-	  result_count $$1 "FAIL: " $$fail  "$$red"; \
-	  result_count $$1 "XPASS:" $$xpass "$$red"; \
-	  result_count $$1 "ERROR:" $$error "$$mgn"; \
-	}; \
-	{								\
-	  echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" |	\
-	    $(am__rst_title);						\
-	  create_testsuite_report --no-color;				\
-	  echo;								\
-	  echo ".. contents:: :depth: 2";				\
-	  echo;								\
-	  for b in $$bases; do echo $$b; done				\
-	    | $(am__create_global_log);					\
-	} >$(TEST_SUITE_LOG).tmp || exit 1;				\
-	mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG);			\
-	if $$success; then						\
-	  col="$$grn";							\
-	 else								\
-	  col="$$red";							\
-	  test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG);		\
-	fi;								\
-	echo "$${col}$$br$${std}"; 					\
-	echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}";	\
-	echo "$${col}$$br$${std}"; 					\
-	create_testsuite_report --maybe-color;				\
-	echo "$$col$$br$$std";						\
-	if $$success; then :; else					\
-	  echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}";		\
-	  if test -n "$(PACKAGE_BUGREPORT)"; then			\
-	    echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}";	\
-	  fi;								\
-	  echo "$$col$$br$$std";					\
-	fi;								\
-	$$success || exit 1
-
-check-TESTS:
-	@list='$(RECHECK_LOGS)';           test -z "$$list" || rm -f $$list
-	@list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	trs_list=`for i in $$bases; do echo $$i.trs; done`; \
-	log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \
-	exit $$?;
-recheck: all $(check_PROGRAMS)
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	bases=`for i in $$bases; do echo $$i; done \
-	         | $(am__list_recheck_tests)` || exit 1; \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	log_list=`echo $$log_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \
-	        am__force_recheck=am--force-recheck \
-	        TEST_LOGS="$$log_list"; \
-	exit $$?
-test_tls_options.log: test_tls_options$(EXEEXT)
-	@p='test_tls_options$(EXEEXT)'; \
-	b='test_tls_options'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_multi_daemon.log: test_https_multi_daemon$(EXEEXT)
-	@p='test_https_multi_daemon$(EXEEXT)'; \
-	b='test_https_multi_daemon'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_get.log: test_https_get$(EXEEXT)
-	@p='test_https_get$(EXEEXT)'; \
-	b='test_https_get'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_sni.log: test_https_sni$(EXEEXT)
-	@p='test_https_sni$(EXEEXT)'; \
-	b='test_https_sni'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_get_select.log: test_https_get_select$(EXEEXT)
-	@p='test_https_get_select$(EXEEXT)'; \
-	b='test_https_get_select'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_get_parallel.log: test_https_get_parallel$(EXEEXT)
-	@p='test_https_get_parallel$(EXEEXT)'; \
-	b='test_https_get_parallel'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_get_parallel_threads.log: test_https_get_parallel_threads$(EXEEXT)
-	@p='test_https_get_parallel_threads$(EXEEXT)'; \
-	b='test_https_get_parallel_threads'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_session_info.log: test_https_session_info$(EXEEXT)
-	@p='test_https_session_info$(EXEEXT)'; \
-	b='test_https_session_info'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_https_time_out.log: test_https_time_out$(EXEEXT)
-	@p='test_https_time_out$(EXEEXT)'; \
-	b='test_https_time_out'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_tls_authentication.log: test_tls_authentication$(EXEEXT)
-	@p='test_tls_authentication$(EXEEXT)'; \
-	b='test_tls_authentication'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_empty_response.log: test_empty_response$(EXEEXT)
-	@p='test_empty_response$(EXEEXT)'; \
-	b='test_empty_response'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-.test.log:
-	@p='$<'; \
-	$(am__set_b); \
-	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-@am__EXEEXT_TRUE@.test$(EXEEXT).log:
-@am__EXEEXT_TRUE@	@p='$<'; \
-@am__EXEEXT_TRUE@	$(am__set_b); \
-@am__EXEEXT_TRUE@	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-@am__EXEEXT_TRUE@	--log-file $$b.log --trs-file $$b.trs \
-@am__EXEEXT_TRUE@	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-@am__EXEEXT_TRUE@	"$$tst" $(AM_TESTS_FD_REDIRECT)
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
-	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-	-test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS)
-	-test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs)
-	-test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-checkPROGRAMS clean-generic clean-libtool \
-	mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) check-am install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-TESTS check-am clean clean-checkPROGRAMS clean-generic \
-	clean-libtool cscopelist-am ctags ctags-am distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \
-	uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/testcurl/https/cert.pem b/src/testcurl/https/cert.pem
deleted file mode 100644
index 2c766df..0000000
--- a/src/testcurl/https/cert.pem
+++ /dev/null
@@ -1,17 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICpjCCAZCgAwIBAgIESEPtjjALBgkqhkiG9w0BAQUwADAeFw0wODA2MDIxMjU0
-MzhaFw0wOTA2MDIxMjU0NDZaMAAwggEfMAsGCSqGSIb3DQEBAQOCAQ4AMIIBCQKC
-AQC03TyUvK5HmUAirRp067taIEO4bibh5nqolUoUdo/LeblMQV+qnrv/RNAMTx5X
-fNLZ45/kbM9geF8qY0vsPyQvP4jumzK0LOJYuIwmHaUm9vbXnYieILiwCuTgjaud
-3VkZDoQ9fteIo+6we9UTpVqZpxpbLulBMh/VsvX0cPJ1VFC7rT59o9hAUlFf9jX/
-GmKdYI79MtgVx0OPBjmmSD6kicBBfmfgkO7bIGwlRtsIyMznxbHu6VuoX/eVxrTv
-rmCwgEXLWRZ6ru8MQl5YfqeGXXRVwMeXU961KefbuvmEPccgCxm8FZ1C1cnDHFXh
-siSgAzMBjC/b6KVhNQ4KnUdZAgMBAAGjLzAtMAwGA1UdEwEB/wQCMAAwHQYDVR0O
-BBYEFJcUvpjvE5fF/yzUshkWDpdYiQh/MAsGCSqGSIb3DQEBBQOCAQEARP7eKSB2
-RNd6XjEjK0SrxtoTnxS3nw9sfcS7/qD1+XHdObtDFqGNSjGYFB3Gpx8fpQhCXdoN
-8QUs3/5ZVa5yjZMQewWBgz8kNbnbH40F2y81MHITxxCe1Y+qqHWwVaYLsiOTqj2/
-0S3QjEJ9tvklmg7JX09HC4m5QRYfWBeQLD1u8ZjA1Sf1xJriomFVyRLI2VPO2bNe
-JDMXWuP+8kMC7gEvUnJ7A92Y2yrhu3QI3bjPk8uSpHea19Q77tul1UVBJ5g+zpH3
-OsF5p0MyaVf09GTzcLds5nE/osTdXGUyHJapWReVmPm3Zn6gqYlnzD99z+DPIgIV
-RhZvQx74NQnS6g==
------END CERTIFICATE-----
diff --git a/src/testcurl/https/host1.crt b/src/testcurl/https/host1.crt
deleted file mode 100644
index d9b8b99..0000000
--- a/src/testcurl/https/host1.crt
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICWTCCAcICCQDc4McLp7j56DANBgkqhkiG9w0BAQUFADBwMQswCQYDVQQGEwJa
-WjETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
-cyBQdHkgTHRkMQ4wDAYDVQQDDAVob3N0MTEZMBcGCSqGSIb3DQEJARYKdGVzdEBo
-b3N0MTAgFw0xMzExMTcxNTE2MzdaGA8yMTEzMTAyNDE1MTYzN1owcDELMAkGA1UE
-BhMCWloxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdp
-ZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAwwFaG9zdDExGTAXBgkqhkiG9w0BCQEWCnRl
-c3RAaG9zdDEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKxYiRUzfQnekQn3
-6e+hP/mt/JEkiFzX5TV+E19ue2v4tc7lf+SoLEk2dVt5tGQkHjIGeFFNwCLrgXoi
-h3KfP4R1IYe7NFbM+lFVwPceF3inJ75dZD80BxaXQANeh0yC/DhaVJUFNaof2S4+
-7xd8zTL6M11gME+XmR8uaDvW7EBtAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAf62m
-Nstj9p9u8T5A5fRnJWfoglH/zfm7IHzht0Wi047O3NFZJ0pOPqV97HuErUA5oBGg
-qswnyRGyGMcvL08Bki7Q6NkY7K0ON3lq+ofTkIAHlOKMF+Y/otbjuIDHBfo63tmE
-uOcr8XDQGu9R0cfh+qLgicJQd/8cFBhxsL0ls6I=
------END CERTIFICATE-----
diff --git a/src/testcurl/https/host1.key b/src/testcurl/https/host1.key
deleted file mode 100644
index f549a4d..0000000
--- a/src/testcurl/https/host1.key
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXQIBAAKBgQCsWIkVM30J3pEJ9+nvoT/5rfyRJIhc1+U1fhNfbntr+LXO5X/k
-qCxJNnVbebRkJB4yBnhRTcAi64F6Iodynz+EdSGHuzRWzPpRVcD3Hhd4pye+XWQ/
-NAcWl0ADXodMgvw4WlSVBTWqH9kuPu8XfM0y+jNdYDBPl5kfLmg71uxAbQIDAQAB
-AoGBAJvq9QmjLSnymtCj4pYSEai2iNpebKdiAlEkoC4j67DArupgohWhN398ryt0
-rYgzTMYBKHSVnI969AYkmtlNzM1yNckRQb/G/tWrkl9re28y2nbAExtHbvLoTk2C
-a/EEl1Op+JZNzLoSje7IQMVZoArD3d4aUbfux4XzlO2eRNmZAkEA2pV49QgcOTOJ
-PrR5cgekonNdeMtkbZm9dhxgDk9IsYkC0iOxjn/IbeCQN3wuTQ5/yLoiiQ/CQ8w5
-JndF/XpICwJBAMnY37BSRb+XKZeJWP0yjqyFJwzHXkh6IsoSF2OOXSixdiMpthLh
-IPzvo6Qxsnha4VvwuDxljHzQFPgMT//CTGcCQQDMs9S+LKU50JDEX4Goj43X8RBl
-cp0Poz3yYap3XDqowLYalADRgcvzUq3cuHgoA98Z3W9ASrjUg2o2ItcyBhV3AkAK
-bCBgwl7Hnc6P/I+Tw2CKl/WEO2cq5uOU+4opodg9maw39JdqMiW56cXRXJ+Sh17L
-mIpq0/OFHll21WvsEORRAkAnDDn/vmW25PSxPVY7tKKJCCkmtBeLQpySfpDgBF+O
-QvvokKs2COivc50rmOYNvD1WSsAOspdaSoZUgFw5ikti
------END RSA PRIVATE KEY-----
diff --git a/src/testcurl/https/host2.crt b/src/testcurl/https/host2.crt
deleted file mode 100644
index ac28b0e..0000000
--- a/src/testcurl/https/host2.crt
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICWTCCAcICCQCJ9nhDYTUBKjANBgkqhkiG9w0BAQUFADBwMQswCQYDVQQGEwJa
-WjETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
-cyBQdHkgTHRkMQ4wDAYDVQQDDAVob3N0MjEZMBcGCSqGSIb3DQEJARYKdGVzdEBo
-b3N0MjAgFw0xMzExMTcxNTE2NDNaGA8yMTEzMTAyNDE1MTY0M1owcDELMAkGA1UE
-BhMCWloxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdp
-ZGdpdHMgUHR5IEx0ZDEOMAwGA1UEAwwFaG9zdDIxGTAXBgkqhkiG9w0BCQEWCnRl
-c3RAaG9zdDIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALVK8QKMvU96iNL2
-66PKm6xXw9NPHDn+o1TLF1CQRxXMrBYUrObk0961+3n3Z3BXOFHKfSV4E55CpVyz
-D1Wcadlt3B9z3ke3HOi0lEa1xNJTMQK/QT3Fx/NURmNg5s9HAsqY4ocb9KHaF5Ex
-0TgC0L0aRP0cK1x2TgPEHBNcgGl9AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAEXOi
-9rSmVrTN5olIdowctr1vWbGwRCjCnAFXDsqakcDASNthr15LB5kr/mrA3olJjbZh
-o+JDvWMY6FN8r1QXW0RL9/obbHxtJpwvAmYVMY9jrR8Rpo38p4RfXlN85g3q9PVx
-5IGLaOqLf4hSnKArFL/fzXwxX9b5HBCKlXfiuqM=
------END CERTIFICATE-----
diff --git a/src/testcurl/https/host2.key b/src/testcurl/https/host2.key
deleted file mode 100644
index 4bbd617..0000000
--- a/src/testcurl/https/host2.key
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICWwIBAAKBgQC1SvECjL1PeojS9uujypusV8PTTxw5/qNUyxdQkEcVzKwWFKzm
-5NPetft592dwVzhRyn0leBOeQqVcsw9VnGnZbdwfc95HtxzotJRGtcTSUzECv0E9
-xcfzVEZjYObPRwLKmOKHG/Sh2heRMdE4AtC9GkT9HCtcdk4DxBwTXIBpfQIDAQAB
-AoGAR5Do6TfDt69IefdNeCAQKg2PWUg+fUpfEacGciAyX5GnUSQiSReF58HxHumi
-ZL+ZlPgZRQRMwknO23Q4FnSjd66A3E9iHLqkWxRFJWME6E7zgtBrIjctnNu9uYM9
-cw4R6qmXOL7C5sK00KXF2ep8+s+JjrZz61o85QnGGRYA94ECQQDbG6f1B8NKY9T1
-1GDR/++rJbdTVQlZQcKSXMumpU6V3mEV0O9GkYaZzoYvWa3kx6c0np4karrm3QWa
-u5E0q1YdAkEA09FPcmzVvIR0+sMWca8QJ/tJUxD6qYo8vLOpO4wt4iTPhGBEU+Q5
-cgXmde3/plVsp0vYxK/NG5XZkoC1fbuC4QJATRGxRlLwsl3jLoUBeVxY5Q5jKYCj
-xS2ITwss5vUGa1jJNW9EesH9YmRudoFI1UwU2EFixtRz4Xik3ARV0vzhUQJAfabT
-50ASxqMYtczW2peMEPurMqCG4d4ES7iUMqPkcBuAErn8rntbbH19igWmOyi/rLp8
-m6jiFnQdPiAmCbEbYQJAFAKiQl2ZOe3gkSh8MaQilD8Ppog6rod4SQiSmRNsDWPi
-IxqXneaGDWhzynC9xr4SwuJ9D5VxW1phNyiveDuYXw==
------END RSA PRIVATE KEY-----
diff --git a/src/testcurl/https/key.pem b/src/testcurl/https/key.pem
deleted file mode 100644
index a5848ee..0000000
--- a/src/testcurl/https/key.pem
+++ /dev/null
@@ -1,27 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIEowIBAAKCAQEAtN08lLyuR5lAIq0adOu7WiBDuG4m4eZ6qJVKFHaPy3m5TEFf
-qp67/0TQDE8eV3zS2eOf5GzPYHhfKmNL7D8kLz+I7psytCziWLiMJh2lJvb2152I
-niC4sArk4I2rnd1ZGQ6EPX7XiKPusHvVE6VamacaWy7pQTIf1bL19HDydVRQu60+
-faPYQFJRX/Y1/xpinWCO/TLYFcdDjwY5pkg+pInAQX5n4JDu2yBsJUbbCMjM58Wx
-7ulbqF/3lca0765gsIBFy1kWeq7vDEJeWH6nhl10VcDHl1PetSnn27r5hD3HIAsZ
-vBWdQtXJwxxV4bIkoAMzAYwv2+ilYTUOCp1HWQIDAQABAoIBAArOQv3R7gmqDspj
-lDaTFOz0C4e70QfjGMX0sWnakYnDGn6DU19iv3GnX1S072ejtgc9kcJ4e8VUO79R
-EmqpdRR7k8dJr3RTUCyjzf/C+qiCzcmhCFYGN3KRHA6MeEnkvRuBogX4i5EG1k5l
-/5t+YBTZBnqXKWlzQLKoUAiMLPg0eRWh+6q7H4N7kdWWBmTpako7TEqpIwuEnPGx
-u3EPuTR+LN6lF55WBePbCHccUHUQaXuav18NuDkcJmCiMArK9SKb+h0RqLD6oMI/
-dKD6n8cZXeMBkK+C8U/K0sN2hFHACsu30b9XfdnljgP9v+BP8GhnB0nCB6tNBCPo
-32srOwECgYEAxWh3iBT4lWqL6bZavVbnhmvtif4nHv2t2/hOs/CAq8iLAw0oWGZc
-+JEZTUDMvFRlulr0kcaWra+4fN3OmJnjeuFXZq52lfMgXBIKBmoSaZpIh2aDY1Rd
-RbEse7nQl9hTEPmYspiXLGtnAXW7HuWqVfFFP3ya8rUS3t4d07Hig8ECgYEA6ou6
-OHiBRTbtDqLIv8NghARc/AqwNWgEc9PelCPe5bdCOLBEyFjqKiT2MttnSSUc2Zob
-XhYkHC6zN1Mlq30N0e3Q61YK9LxMdU1vsluXxNq2rfK1Scb1oOlOOtlbV3zA3VRF
-hV3t1nOA9tFmUrwZi0CUMWJE/zbPAyhwWotKyZkCgYEAh0kFicPdbABdrCglXVae
-SnfSjVwYkVuGd5Ze0WADvjYsVkYBHTvhgRNnRJMg+/vWz3Sf4Ps4rgUbqK8Vc20b
-AU5G6H6tlCvPRGm0ZxrwTWDHTcuKRVs+pJE8C/qWoklE/AAhjluWVoGwUMbPGuiH
-6Gf1bgHF6oj/Sq7rv/VLZ8ECgYBeq7ml05YyLuJutuwa4yzQ/MXfghzv4aVyb0F3
-QCdXR6o2IYgR6jnSewrZKlA9aPqFJrwHNR6sNXlnSmt5Fcf/RWO/qgJQGLUv3+rG
-7kuLTNDR05azSdiZc7J89ID3Bkb+z2YkV+6JUiPq/Ei1+nDBEXb/m+/HqALU/nyj
-P3gXeQKBgBusb8Rbd+KgxSA0hwY6aoRTPRt8LNvXdsB9vRcKKHUFQvxUWiUSS+L9
-/Qu1sJbrUquKOHqksV5wCnWnAKyJNJlhHuBToqQTgKXjuNmVdYSe631saiI7PHyC
-eRJ6DxULPxABytJrYCRrNqmXi5TCiqR2mtfalEMOPxz8rUU8dYyx
------END RSA PRIVATE KEY-----
diff --git a/src/testcurl/https/mhdhost1.crt b/src/testcurl/https/mhdhost1.crt
new file mode 100644
index 0000000..775620e
--- /dev/null
+++ b/src/testcurl/https/mhdhost1.crt
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFJjCCAw6gAwIBAgIBBTANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQ1MDVaGA8yMTIyMDMyNjE4
+NDUwNVowXzELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxETAPBgNVBAMMCG1o
+ZGhvc3QxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxb5LkwTfvNtW
+eFSYAPoEzqwVARWxDDR2PfQmmBtrHhMNEQyUCTg+Na00hEQbcZbz7fgS0FOY1hjy
+MFJamNGP031HvMS7zHNQJ4HbEz0d1EuePgjEvWaFMFncTKGn07Cn9e3Rcv2ihJ/I
+I8wf3ph/k/UTOv62YhIs2fMQM5LD6oX9ulKJhAaOvFT6hyrB1xe3nVhPT0PsrUXl
+ky253k7XXEAIWO6dLZnK377UiRDJInFS9FN/hojFb+8gcByo/n39LHMBtp5WGM5+
+xGwEHyYkwtnaM8IEKofbUNERQT3cgPv4zN7ny3LwljR2A1c5gHXmKO7G245tbfqb
+VtOh3+1bJQIDAQABo4HHMIHEMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8EAjAAMBYG
+A1UdJQEB/wQMMAoGCCsGAQUFBwMBMBMGA1UdEQQMMAqCCG1oZGhvc3QxMB0GA1Ud
+DgQWBBTTxzQ/fcuT83JlCzPx8qJzuHCG4jAnBglghkgBhvhCAQ0EGhYYVGVzdCBs
+aWJtaWNyb2h0dHBkIGhvc3QxMBEGCWCGSAGG+EIBAQQEAwIGQDAfBgNVHSMEGDAW
+gBRYdUPApWoxw4U13Rqsjf9AHdbpLDANBgkqhkiG9w0BAQsFAAOCAgEAMdHjWHxt
+51LH3V8Um3djUh+QYVnYhxFVX4CIXMq2DAg7iYw6tg2S1SOm3R+qEB/rAHxRw/cd
+nekjx0zm2rAnn4SsIQg5rXzniM4dJ2UQJrn7m88fb/czjXCrvf6hGIXCSAw/YyU0
+IkxXlOYv1mYNZBuVvFREUbqqK2Fn+ooIi816Q2UCQFMd+QI8+mn8eqK8XeJElKkt
+SR0WCLW7UkwYxOk73FCdrr1TlX9hAF76gTAK71OJN3F35hzg+pTAEe3nwFMZbG/k
+xHmVob51L+Op4Y15j1HoJxW0Ox+PuxVcp9EpC7Qb8UmtExAsYOuN2PP8hU+pmtE4
+iYpCDckx6kT66ssjndaKziRmoxX/czvKCAwVDder6Ofl4SwGUEpE+0oO2ux6iNrl
+iKxRCvyBqErFlzlEj7oO3agqe83jtTH8bXzOCtx36lNVjCuADYI4o7r5NVHaGIx6
+1q5BiZ5pj22EYgBZbRAgE1ZPxVBIZJKoHewmQqpcR5WsSeBIf8XDuytnadhv8NDN
+tpLMDry8KkUh7rtjrQIGb66BqCt0n1tz1/6nLlL9OF5kUt4902wCtN3SbotssfV3
+NCX9X4udquRdcFwNLCSfZ505FqhYbeSLraDHJ46/96V//Vx4oAnULdcCm4QgGQmP
+EGEJDJkaCKKTGMHAvZAtgRchc/RTf59jhoc=
+-----END CERTIFICATE-----
diff --git a/src/testcurl/https/mhdhost1.key b/src/testcurl/https/mhdhost1.key
new file mode 100644
index 0000000..8cc2dc4
--- /dev/null
+++ b/src/testcurl/https/mhdhost1.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFvkuTBN+821Z4
+VJgA+gTOrBUBFbEMNHY99CaYG2seEw0RDJQJOD41rTSERBtxlvPt+BLQU5jWGPIw
+UlqY0Y/TfUe8xLvMc1AngdsTPR3US54+CMS9ZoUwWdxMoafTsKf17dFy/aKEn8gj
+zB/emH+T9RM6/rZiEizZ8xAzksPqhf26UomEBo68VPqHKsHXF7edWE9PQ+ytReWT
+LbneTtdcQAhY7p0tmcrfvtSJEMkicVL0U3+GiMVv7yBwHKj+ff0scwG2nlYYzn7E
+bAQfJiTC2dozwgQqh9tQ0RFBPdyA+/jM3ufLcvCWNHYDVzmAdeYo7sbbjm1t+ptW
+06Hf7VslAgMBAAECggEALshrttezW0oFNijFYY3FL2Q0//Gy1nFe/B9UNi5edFoL
+gFoad+fvh+F3iEdYutH82fMT+GeexCBYxCfnuTnzLhT4sOdWivNJJl+phe6yrPRK
+9uA6M5kar6rC3Ppt6z5jLmLaZ7ssBPaMcjOr4ozvugCEUTPL0H3+UH4Z+imh4kzw
+MgLsF8QkWPCF/fxsVhCwC3y3Dctl3oLh6qQFudYKtymRjk2I7zFAuQGsGoYonPbF
+1LZ6xHOjegXtqhC0pK8Kpn4N7LgYVVNPT1TAckQ9GDDi0IgMYwIsSQb/ncaV5Cwb
+9tPqBv1Oi2ayINeXrG5J/G8S1cEbIzdSL8ZqG+CcjQKBgQD1c89Rh/Hbc0zxxgdR
+eGx6oOtNjAZ3zgnNyVnXiZ7mXtbCcjMHJhcW41RL8lg+mhKfj9MgXamDP/R4X2In
+H358dEekfN4wjogeXs9lmh48cGC7zez4/RS752OmrwmhOqkKDa7dy+SLR5QJ3L2n
+4k/2eQwTlXpuPIMrBT1hUvsA3wKBgQDOPaTy03oXX1bwwX6sHUTrQTKAC52v4hQl
+bya+6t+VGpj+cdWzxRFoR5mN85b9Kkj1nAFx+6zioOPLUOZhnnqihlQBwm06gH1p
+v3qkxuXOhnMPJsNg4lltUq/18UlSQwFZuKr7G2vDhckHwZdlu06P/rlA9K5Kxjzi
+gX3I+XoQewKBgQDrn/YYXXmW4jOuMR0bX5A7lDjuY4pd/iO5Mh6V453vpoFhfoFv
+zmgB588nbQi7Z+qS1F2nx2IQBhgoaeBukDQ7QuD3jYs6b8lJ5lgQQAfgmzyxbPic
++U6rJ3CpNYT4Crj1VrdUYgQOlHMPmKFUBdQfVop6TleOdXaxmMEYqbEdXwKBgQCz
+xZwQZjJYSSyZc7CdCm5Wul/wqS9sbp6s+rRFWqpFaAfQUx26M582zKKWz6vfRYqP
+PMsttfk/Gos1YHFQyjmPjZOQbQ+VHQc0tEmNdCpA2YVVwa4wt1zIJHlo4kfNQsbc
+lFHFzGMk7WsMLb1wWdLjRV/ptN5wI1hTABjKpFu4HQKBgExQNTHMxzpAAh9XFiJ3
+oGvf+9+JtjmrgKsR0T7q60xjOYH0E2rznvvBVNeZlAc+tjawmedxiuiitmjQUteG
+hW4ncX0UcqFPm7Ahqo9+NDemJlV7DYHRcvL/xVNUbr8yV7OpHILd4Hk/s8J4QGl/
+bC1zEehy8q0jMywvSR8vsS1v
+-----END PRIVATE KEY-----
diff --git a/src/testcurl/https/mhdhost2.crt b/src/testcurl/https/mhdhost2.crt
new file mode 100644
index 0000000..c32fb6e
--- /dev/null
+++ b/src/testcurl/https/mhdhost2.crt
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFJjCCAw6gAwIBAgIBBjANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQ1MDVaGA8yMTIyMDMyNjE4
+NDUwNVowXzELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxETAPBgNVBAMMCG1o
+ZGhvc3QyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy2v1c39RQPgG
+EqhYisiQX5QDTJFCr93B/KC96AqxXfUqxYHQZHHByeh2yHX5XeY+cwiza9Pb8kB5
+Wyu5IV7pHYbLXetUQ7Ha8oCXcXZBihzMGjdTQApBvKES2rotkgxIArzFRk/KnO3D
+2r87E2/fHqlHjg0Y8d58i846m7GSFpH2uAYogm2Zhi2ojE4O/qfaO6cSTdjUhDbM
+iDkQlf/fkq9o3ZeGzKXdzLC5PeIJ/7HbEcBJ0e6lyAFbYZtpTAtQ6/tuqAZTs3tM
+G5Yq3cAZY7x4vGECZaAWZAlgstBpCYd8b/dlXa8qvx4JuMF4q+7vVbgwHVoXsAzm
+ZAxSNy+dmQIDAQABo4HHMIHEMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8EAjAAMBYG
+A1UdJQEB/wQMMAoGCCsGAQUFBwMBMBMGA1UdEQQMMAqCCG1oZGhvc3QyMB0GA1Ud
+DgQWBBSB0kA6mqq1/wMzKke35+L6aZym9zAnBglghkgBhvhCAQ0EGhYYVGVzdCBs
+aWJtaWNyb2h0dHBkIGhvc3QyMBEGCWCGSAGG+EIBAQQEAwIGQDAfBgNVHSMEGDAW
+gBRYdUPApWoxw4U13Rqsjf9AHdbpLDANBgkqhkiG9w0BAQsFAAOCAgEAhEeSsKYb
+KWVhC3bVxXX4EynaHVWwrQaqNMtogt2akKBfZRzM6CHVvts8IrvcMdS4ZvXB2kL8
+wDsYpVsNVgLLuSKXH2xJPZmYrGsUu++UcR4umvuV1kwFcA/Dc5XkW1EMcMvSPDs2
+/gJFRCpx3UAs2/KCL2KASHGiOcNSf8aRLxI6KqWqQLxsZdK02HUNodqiG2UXIaHg
+shD7rAMSDN4CdG4cdSX3l45aL+BoYcEKi5XUoJMRjNrAGKMWUku089hr1gI617Jx
+gHKZxvSizGxCHhMkAPTT+9UyNFzd+3dS6cHx8oTFpnamNgMin3C88GCmu5YN6gCi
+af3imb8OaHFJ0k9M9acM++5sRfvRgZ/tQWnPdyg5TlLwwF14yLbz6e/DbxlmP7PG
+3W3FbVST/creb2KTtwWFu187uKl4v1Xe5DC0I2gcOzq2g0GHbu8WjuD45Os/lc4v
+cqGctYRMUfqshmsK9PQCZmPcC5nqXf6iO8L1P9Gi0VDwT/WeHUvi87UVYsUgVuVt
+0RxCE5Nqad8S7ziQj9Aa3xspPf7CKw6Obbp/UNui/YwaDufJho7qsBpp1lMnG5f4
+qA8+yKUVADTnV5tJqgcDiRyBxOzb2CaGezTqNshUkVIpkHZsCpSdu9QrEOIzcaaA
+WXmQOPOpxW5QVf22mPJh/GZaqZ3/ZMmFabI=
+-----END CERTIFICATE-----
diff --git a/src/testcurl/https/mhdhost2.key b/src/testcurl/https/mhdhost2.key
new file mode 100644
index 0000000..7e87031
--- /dev/null
+++ b/src/testcurl/https/mhdhost2.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLa/Vzf1FA+AYS
+qFiKyJBflANMkUKv3cH8oL3oCrFd9SrFgdBkccHJ6HbIdfld5j5zCLNr09vyQHlb
+K7khXukdhstd61RDsdrygJdxdkGKHMwaN1NACkG8oRLaui2SDEgCvMVGT8qc7cPa
+vzsTb98eqUeODRjx3nyLzjqbsZIWkfa4BiiCbZmGLaiMTg7+p9o7pxJN2NSENsyI
+ORCV/9+Sr2jdl4bMpd3MsLk94gn/sdsRwEnR7qXIAVthm2lMC1Dr+26oBlOze0wb
+lirdwBljvHi8YQJloBZkCWCy0GkJh3xv92Vdryq/Hgm4wXir7u9VuDAdWhewDOZk
+DFI3L52ZAgMBAAECggEBAIS8cXFoBpEqRmwuRXhp3ys+3dg8gRNY1JgQG1sqfwoc
+TEiMqHqicB1b/wZXVNycvOs7JjiaCc9NmuKO6UKJN/v4VQN354g0qfXLSwbSb3m7
+yMLijwQerT50rGTlT48ZTHPc0a1Lq54y17YJSncobKMJOpPKoBhTYVmovD2T5Qus
+EDFg8wLBA79YZnrImbt9hcRsi/bM341V3aSoPFdHz6NTi+5WA08oTiGCv6gThV8T
+PUCiy1uDJZ1gk3xne+APZfdTutVtwCYVw7mhgTHiL5tL1KCjDjzK3XgnfAWaN+wG
+ex9EYbn/uAxN57UrvdyvGtuBo01vs/XtsVlpRpmlBnECgYEA+L8D8UY36IubeMAl
+xFCoFSXSmT+2YtA6ISg4/8a14wpwAskJPW/Nf8CzzwbGA7QaDVeK4rTGDOwNQJV8
+/fiTaG6vDI7GS3UkvSKStfJzoMRBTzCYp/TbkG/jW2i8tR1AATlQlGllx0BQVXhC
+iYpR/WzbxGi5iyB4K6WPbSKboh8CgYEA0VqUR7w+2PEEFXyFRL2drpzkWKk5RiIa
+cIzQk3VlrHztJp0g6w8MiWCIpzL+7BuBy72byxJwpFmOz4HYsEqc6mOF4xXezfYh
+oN0P1+/aH4NrpWmjb65TGrtwrmi2sJrmATmr9WKFxEIpgrbotOTDF7pIx9pY2ScA
+aohOxqb7eUcCgYAHtHL80D3/GAPy05DX6d+q+Abz9ENEAEssp8BMO+16YOJjU7LT
+klj9MgzfxsfvaW69Jw8IQq03zUAD1h2PCFoYjAUkEHAX+kLvENkWhbILMskLGOhB
+m5YJfU2/kRj3SzamUw4p6rHaYCWc4CK/e+daQDr2dH/6zUCrqW8t5DqJ5QKBgF8E
+voIkhV3PXiwmXRJLAXNMEDPRcoZLWja1IsGaqe/0r2o0LMmjBeygHMXOVndxMKL5
+RumPUAK4ByJVa7Tv2HJlg1IDDiHq0W6ChvtaCGT/L+9el+hLdbqPUmBGdIyJcVUj
+CNIRyma+JLsIK2xW29k8GmZiyqqckgrIHQD6ru5nAoGAAcdAHQojvGs5dQ2Agqcn
+EOgF1dic7VgCjAEG4CNCydzskE92jEOgv2DI+oBPoLrtktHbewFrsxBBNbS+PcHY
+DyV5/WXf8wwwdkG1VLyw+dPeWNGWanvjllplckDXSGz1ia0s7ENNAt8o2MXdlZrQ
+MMHn0wo/1rTa1YroHF8cKVA=
+-----END PRIVATE KEY-----
diff --git a/src/testcurl/https/test-ca.crt b/src/testcurl/https/test-ca.crt
new file mode 100644
index 0000000..3f75479
--- /dev/null
+++ b/src/testcurl/https/test-ca.crt
@@ -0,0 +1,35 @@
+-----BEGIN CERTIFICATE-----
+MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3
+MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM
+Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN
+AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G
+CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36
+ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI
+IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/
+B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6
+6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP
+t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw
+Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN
+x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH
+QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH
+KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR
+bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR
+q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG
+AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK
+BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB
+MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA
+A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1
+kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay
+ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj
+ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9
+9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD
+TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl
+WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s
+E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/
+nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM
+Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg
+4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA==
+-----END CERTIFICATE-----
diff --git a/src/testcurl/https/test-ca.key b/src/testcurl/https/test-ca.key
new file mode 100644
index 0000000..eec9578
--- /dev/null
+++ b/src/testcurl/https/test-ca.key
@@ -0,0 +1,51 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIJKgIBAAKCAgEA3WlrqQOKmYwgTZCaCTpucZwmos5d+mS1MKeMQS/2H1z1hNy5
+JgERIlSP2JwG/JehuwiZ8/HU7DiVpDVxuk9SlT+f9kbwSCGmmrn0SAJe4RJ49Y/R
+NoUJVdn8RdmTYc/p6otC6ileCyUqXJZFwA39hQPR7FUT/we82Ifgz9H0lPFem7Lv
+FwnkRrIa6AD63PKx/JRRBF6TSzSKkK/MisekpnQeoX42uukkNPvqgYZdGibZ+Cx1
+maIYIwZpCGhhT2CCS4MUP8cqdhq89qu5RiifswZARfIjj7d8fhdYUggZ6/wxmFpo
+xJubWJvu6crq4j3XV3QnPPqmti8TGaNxF8S6OWCEqTwssGe1d2ADmU695tQtuC4m
+Lz3oQqtQkyJIYZqrZVSV1OyEg+PHMfcvuT4t+MLW0yP4DceL6MkywH8mryjJiKcc
+SEbFpXYhdp9Oh3bwkVXYoQ0FGnddMoE5ln9Sf7NmREwLR0GknezA9/Pbep0BbUyF
+4oLDSp5wz5a7cbe6zi7y0HkdCtOBs63/7HIXjmp0QHzlxyjQRVO2JAxRvK6os5Qu
+ua8fanlxWF0HB2U7qsSu7YGZ0oCWrdxO9FW00grBBBu3kWzV/3woVCgCCKVmoluh
+w5Si5eptsvgczPdbpgbCjqk757TFRQUhfaVWJVyvOeGiEavANl7o3dNdrHkCAwEA
+AQKCAgEA2nPJ4j75P9gOgxj5scMx9uve/uDnvkYgszmMW0DL8FPSdd0k3AdPdXTD
+XC9NgWjGDHhHFXXz44FMu3BzniPnUhQtalrBdhmlfKGeEHIuVJjaOUZFYCpQdKEX
+k39BN89gdqYiRlC8Vfi8XA90EDJ9gQCs3SVwDj7/JxChUcpQK6gd9TbNSQjcbpgJ
+jgBxgw/9Zjyb1tjNMPVNBcY95Gtn20dUdXfG3hFrRM+Mp3D/aO8OPhr3iLZyZBRO
+CxqZcCzDQWe50dda4J4u9J2ntj4cmxC+14Q5a/HYZbv4yy7tDHWOJUiGd/0jf4CS
+b59isgfb8JBMqpCPbc7yZGhrC81xAZdsw0jvDYgGUf86785983clipdCVJIKMqZm
+yjoo2DuSaivCGnaWUV1f+W2CgigpSXcDQ1/gDMt7xVoZNpfmdTgZzthUxXK3dFYO
+Jwem/ls6KD5THKpkHuA9BpnoksnpZqREK5FdMw8hCUpJEe1kXy4ZlQB91Ya74HQ0
+tgygL9BwEXDJ2vU14Onq8CH+Ul4kOzXnqMae35eKj1+/QI2PP1Wuk/vypSmrurfm
+3YLsnwm7OYSuWrAfFRmGTMhfny3v1xlw1ynmVBvxgQ2v2czxKGw8JG+9LoqbSB5O
+GP05Gpcys1CwR9Z2EjfExFNcWFIJQjwcZemlgHHwvHCBy1fz0AUCggEBAPSnznDv
+Wuj3gTkUDfNFTplsa8z3GIyrfBYDUyGJ51YiN5C2myGRcu60r5iMl4hxXC6mL4Cd
+5ew8LsXojPmC0sWZ2Cp+uhSH5FZaMNRumg4R8EA0Phwi0iBgDXM5318reMZF3BUr
+FSTn9a3nBkFpYMw1hxBlLj0o6S0TfZBmviTJUO7eiq6mAdO43l320Pw7E6xSWble
+QQaXzk2yGr2bV02heZcWfw+Fnui6xLruWZbVdvh+Q5KEJv90y9HcXm14LXiPRMBg
+zYvbW6tVZSQeXTs4wGC1RAZWZC7MG0XOoVj18WGx8hSZQND6awxFwHbItSlv05TX
+QkJ9ybZ7bcOQT78CggEBAOetsug2BQejAwRbbAsC078Vlr6PUspHmeT1Efp8ArFq
+rsmx2n2EoIcZSLkedZK1cXN7HMxVz1U0yx7k/OLIKlsfGNQdAQhCW875mbn0ET0c
+jUNpeJRXL6U5pwdPrsENyyAPsDyCsBT4ArGuEIFIxPlWtZTBzOAhJN9AwB5KW8g/
+zg1mwv1TCNNlQu3Ex46egI3cCUk+6b1BNwPuSKhuP+P22Vg+JBhIY+/iSJvgSRfP
+3LCNU0ds2D5xiwJNVwzVtrn3wIaYHj6S7lhfVGWdvQb8RsF9kyR06yJNTUyyybZ0
+pTHeRwNtbUoTeBUlwoBac6izNyGGguA42pDYmoAcEccCggEAfXgZrV1zWAqmoOki
+BmLC3nf2CRWn52yCpJ9r4MVieI/vwy2C/YIkWTsc2rUveW/5gIsFzYYsxixPKHwM
+4GExStmNPK3lLGZMueRjKm7WXuTgO20PdUp+TNA11aQWZC5dMAHfzpNbsqOrIVZb
+pOwwEkpZTBU303HJs65NNOMcHK2J7hb/NHY6daRXlgTgRJrfif5puWEXJBRyXvI6
+OIcUDOIFA3EsFH/IcT5nah6Wn342F1ZZvSg8/8GcTbIgUy/Q0gVXkvmSMGl8569R
+wWY5FggS0QXlLwLbOgy+59wCbycidaHWrq2xyfrDL3YOMFzaW7fX4HtMpeDws781
+GZhG7QKCAQEAhCfJTjzCUcDjD7E2yHEsaGvgOYN4Lnr5hmllgAUNZDb+zX7uq3rk
+NyxtF2wQlUd7F+y6WLT6OBiNZWop9xNHVgM/HoAM/rEbvc0Tq8dVrg6DZljbt4Kk
+YxOn+7uwa996ZyeL2HiUCOIQZ1prf9QKyFB19A042QEPD2rYLG8uO+RpnatovyiG
+eE/jBc6iJvCzVDiX83g3zQVOZKegOrPpLhi5kmSgIlno6AWkdYZTK4oe0XdMcgnc
+sIIEUaPcbC3ctehlomFTn04hN7fpZK2+DiYKFoWTUdB/8Gk4FvBFsBaJxRCOYZ4i
+IYdJkIahlKYEI89XO4CHV3AW/VkRiNJ6MQKCAQEAhosdYqtpJtdRJ3FWM4i6Miua
+OBEg7FU4JTH/0cekj0UMYFww3KK9c4KEdgVwRtsvLTZ++CXZ3XF9Er+6nPmC6nAo
+46b3Ow7rPzpm18jUNWMW0s+CZwKWkGe1sbek81L8SBCDRJKKhl6XgiPHGB/i8g65
+ZQv3B47BPflrjxJCQVADHpdW5vo0xY7xRr9zKYoAl4LQBTwLVMTP229iIcBFvRPp
+rs4KUecFQfEyXrJLwgQTl0uBItO86BWopCdh7T/0A7BjBk9jdklJNgml8Ctq+Yt9
+nqduIeW3c1aNqbNhn+IA27WW+tv+yzA4gNPS/OWr8J67HDGm4WSUAFGMLwmcSw==
+-----END RSA PRIVATE KEY-----
diff --git a/src/testcurl/https/test_empty_response.c b/src/testcurl/https/test_empty_response.c
index f9f8001..b1de350 100644
--- a/src/testcurl/https/test_empty_response.c
+++ b/src/testcurl/https/test_empty_response.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2013 Christian Grothoff
+ Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,52 +15,52 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
  * @file test_empty_response.c
- * @brief  Testcase for libmicrohttpd HTTPS GET operations with emtpy reply
+ * @brief  Testcase for libmicrohttpd HTTPS GET operations with empty reply
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "platform.h"
 #include "microhttpd.h"
 #include <limits.h>
 #include <sys/stat.h>
 #include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
-
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
-extern const char srv_signed_cert_pem[];
-extern const char srv_signed_key_pem[];
+#include "tls_test_keys.h"
 
 static int oneone;
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) url; (void) method; (void) version;             /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size; (void) req_cls;       /* Unused. Silent compiler warning. */
 
-  response = MHD_create_response_from_buffer (0, NULL,
-					      MHD_RESPMEM_PERSISTENT);
+  response = MHD_create_response_empty (MHD_RF_NONE);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testInternalSelectGet ()
+static unsigned int
+testInternalSelectGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -70,40 +71,55 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  int maxposixs; /* Max socket number unused on W32 */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3000;
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_SELECT_INTERNALLY,
-                        1082, NULL, NULL, &ahc_echo, "GET", 
-                        MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_TLS
+                        | MHD_USE_INTERNAL_POLLING_THREAD,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
-			MHD_OPTION_END);
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
 
-  char *aes256_sha = "AES256-SHA";
-  if (curl_uses_nss_ssl() == 0)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      aes256_sha = "rsa_aes_256_sha";
+      MHD_stop_daemon (d); return 32;
     }
+    port = dinfo->port;
+  }
 
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1:1082/hello_world");
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+#endif
+  curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   /* TLS options */
-  curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
-  curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, aes256_sha);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
@@ -113,70 +129,101 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 != maxposixs)
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
+      if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+      {
+#ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+          abort ();
+#else
+        if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 !=
+                                                                        ws.
+                                                                        fd_count)
+            || (0 != es.fd_count) )
+          abort ();
+        Sleep (1000);
+#endif
+      }
     }
-  if (multi != NULL)
+    else
+      (void) sleep (1);
+    curl_multi_perform (multi, &running);
+    if (0 == running)
     {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
     }
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != 0)
     return 8192;
@@ -188,14 +235,19 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return -1;
-    }
+  oneone = 1;
+  if (! testsuite_curl_global_init ())
+    return 99;
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
   if (0 != (errorCount = testInternalSelectGet ()))
-    fprintf (stderr, "Fail: %d\n", errorCount);
+    fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_get.c b/src/testcurl/https/test_https_get.c
index f7957c3..f3f0e1f 100644
--- a/src/testcurl/https/test_https_get.c
+++ b/src/testcurl/https/test_https_get.c
@@ -1,6 +1,7 @@
 /*
   This file is part of libmicrohttpd
   Copyright (C) 2007 Christian Grothoff
+  Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
   libmicrohttpd is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published
@@ -14,84 +15,225 @@
 
   You should have received a copy of the GNU General Public License
   along with libmicrohttpd; see the file COPYING.  If not, write to the
-  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-  Boston, MA 02111-1307, USA.
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+  Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_https_get.c
  * @brief  Testcase for libmicrohttpd HTTPS GET operations
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include "microhttpd.h"
-#include <limits.h>
-#include <sys/stat.h>
 #include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
-
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
-extern const char srv_signed_cert_pem[];
-extern const char srv_signed_key_pem[];
+#include "tls_test_keys.h"
 
 
-static int
-test_cipher_option (FILE * test_fd,
-		    const char *cipher_suite,
-		    int proto_version)
+static uint16_t global_port;
+
+
+/* perform a HTTP GET request via SSL/TLS */
+static unsigned int
+test_secure_get (const char *cipher_suite,
+                 int proto_version)
 {
-
-  int ret;
+  unsigned int ret;
   struct MHD_Daemon *d;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                        MHD_USE_DEBUG, 4233,
-                        NULL, NULL, &http_ahc, NULL,
-                        MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
-                        MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3041;
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                        | MHD_USE_ERROR_LOG, port,
+                        NULL, NULL,
+                        &http_ahc, NULL,
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
+                        MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
                         MHD_OPTION_END);
 
   if (d == NULL)
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return 1;
+  }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      MHD_stop_daemon (d);
+      return 1;
     }
+    port = dinfo->port;
+  }
 
-  ret = test_https_transfer (test_fd, cipher_suite, proto_version);
+  ret = test_https_transfer (NULL,
+                             port,
+                             cipher_suite,
+                             proto_version);
 
   MHD_stop_daemon (d);
   return ret;
 }
 
 
-/* perform a HTTP GET request via SSL/TLS */
-static int
-test_secure_get (FILE * test_fd,
-		 const char *cipher_suite,
-		 int proto_version)
+static enum MHD_Result
+ahc_empty (void *cls,
+           struct MHD_Connection *connection,
+           const char *url,
+           const char *method,
+           const char *version,
+           const char *upload_data,
+           size_t *upload_data_size,
+           void **req_cls)
 {
-  int ret;
-  struct MHD_Daemon *d;
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url;
+  (void) url;
+  (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size; /* Unused. Silent compiler warning. */
 
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                        MHD_USE_DEBUG, 4233,
-                        NULL, NULL, &http_ahc, NULL,
+  if (0 != strcmp (MHD_HTTP_METHOD_GET,
+                   method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (20);
+  }
+  return ret;
+}
+
+
+static int
+curlExcessFound (CURL *c,
+                 curl_infotype type,
+                 char *data,
+                 size_t size,
+                 void *cls)
+{
+  static const char *excess_found = "Excess found";
+  const size_t str_size = strlen (excess_found);
+  (void) c;      /* Unused. Silence compiler warning. */
+
+#ifdef _DEBUG
+  if ((CURLINFO_TEXT == type) ||
+      (CURLINFO_HEADER_IN == type) ||
+      (CURLINFO_HEADER_OUT == type))
+    fprintf (stderr, "%.*s", (int) size, data);
+#endif /* _DEBUG */
+  if ((CURLINFO_TEXT == type)
+      && (size >= str_size)
+      && (0 == strncmp (excess_found, data, str_size)))
+    *(int *) cls = 1;
+  return 0;
+}
+
+
+static unsigned int
+testEmptyGet (unsigned int poll_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+  int excess_found = 0;
+
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1225;
+
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | poll_flag | MHD_USE_TLS,
+                        global_port, NULL, NULL,
+                        &ahc_empty, NULL,
                         MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
                         MHD_OPTION_END);
-
   if (d == NULL)
+    return 4194304;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      MHD_stop_daemon (d); return 32;
     }
-
-  ret = test_https_transfer (test_fd, cipher_suite, proto_version);
-
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+#endif
+  curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound);
+  curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found);
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 8388608;
+  }
+  curl_easy_cleanup (c);
   MHD_stop_daemon (d);
-  return ret;
+  if (cbc.pos != 0)
+    return 16777216;
+  if (excess_found)
+    return 33554432;
+  return 0;
 }
 
 
@@ -99,32 +241,26 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
-  const char *aes256_sha_tlsv1   = "AES256-SHA";
-  const char *des_cbc3_sha_tlsv1 = "DES-CBC3-SHA";
+  (void) argc; (void) argv;   /* Unused. Silent compiler warning. */
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return -1;
-    }
-
-  if (curl_uses_nss_ssl() == 0)
-    {
-      aes256_sha_tlsv1 = "rsa_aes_256_sha";
-      des_cbc3_sha_tlsv1 = "rsa_aes_128_sha";
-    }
-
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (! testsuite_curl_global_init ())
+    return 99;
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
   errorCount +=
-    test_secure_get (NULL, aes256_sha_tlsv1, CURL_SSLVERSION_TLSv1);
-  errorCount +=
-    test_cipher_option (NULL, des_cbc3_sha_tlsv1, CURL_SSLVERSION_TLSv1);
-  print_test_result (errorCount, argv[0]);
-
+    test_secure_get (NULL, CURL_SSLVERSION_DEFAULT);
+  errorCount += testEmptyGet (0);
   curl_global_cleanup ();
 
-  return errorCount != 0;
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_get_iovec.c b/src/testcurl/https/test_https_get_iovec.c
new file mode 100644
index 0000000..33a2e32
--- /dev/null
+++ b/src/testcurl/https/test_https_get_iovec.c
@@ -0,0 +1,425 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2007-2021 Christian Grothoff
+  Copyright (C) 2016-2022 Evgeny Grin
+
+  libmicrohttpd 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, or (at your
+  option) any later version.
+
+  libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+  Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_https_get_iovec.c
+ * @brief  Testcase for libmicrohttpd HTTPS GET operations using an iovec
+ * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
+ * @author Lawrence Sebald
+ */
+
+/*
+ * This testcase is derived from the test_https_get.c testcase. This version
+ * adds the usage of a scatter/gather array for storing the response data.
+ */
+
+#include "platform.h"
+#include "microhttpd.h"
+#include <limits.h>
+#include <sys/stat.h>
+#include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+#include "tls_test_common.h"
+#include "tls_test_keys.h"
+
+
+static uint16_t global_port;
+
+/* Use large enough pieces (>16KB) to test partially consumed
+ * data as TLS doesn't take more than 16KB by a single call. */
+#define TESTSTR_IOVLEN 20480
+#define TESTSTR_IOVCNT 30
+#define TESTSTR_SIZE   (TESTSTR_IOVCNT * TESTSTR_IOVLEN)
+
+
+static void
+iov_free_callback (void *cls)
+{
+  free (cls);
+}
+
+
+static int
+check_read_data (const void *ptr, size_t len)
+{
+  const int *buf;
+  size_t i;
+
+  if (len % sizeof(int))
+    return -1;
+
+  buf = (const int *) ptr;
+
+  for (i = 0; i < len / sizeof(int); ++i)
+  {
+    if (buf[i] != (int) i)
+      return -1;
+  }
+
+  return 0;
+}
+
+
+static enum MHD_Result
+iovec_ahc (void *cls,
+           struct MHD_Connection *connection,
+           const char *url,
+           const char *method,
+           const char *version,
+           const char *upload_data,
+           size_t *upload_data_size,
+           void **req_cls)
+{
+  static int aptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  int *data;
+  struct MHD_IoVec iov[TESTSTR_IOVCNT];
+  int i;
+  int j;
+  (void) cls; (void) url; (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+    return MHD_NO;              /* unexpected method */
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+
+  /* Create some test data. */
+  if (NULL == (data = malloc (TESTSTR_SIZE)))
+    return MHD_NO;
+
+  for (j = 0; j < TESTSTR_IOVCNT; ++j)
+  {
+    int *chunk;
+    /* Assign chunks of memory area in the reverse order
+     * to make non-continous set of data therefore
+     * possible buffer overruns could be detected */
+    chunk = data + (((TESTSTR_IOVCNT - 1) - (unsigned int) j)
+                    * (TESTSTR_SIZE / TESTSTR_IOVCNT / sizeof(int)));
+    iov[j].iov_base = chunk;
+    iov[j].iov_len = TESTSTR_SIZE / TESTSTR_IOVCNT;
+
+    for (i = 0; i < (int) (TESTSTR_IOVLEN / sizeof(int)); ++i)
+      chunk[i] = i + (j * (int) (TESTSTR_IOVLEN / sizeof(int)));
+  }
+
+  response = MHD_create_response_from_iovec (iov,
+                                             TESTSTR_IOVCNT,
+                                             &iov_free_callback,
+                                             data);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static unsigned int
+test_iovec_transfer (void *cls,
+                     uint16_t port,
+                     const char *cipher_suite,
+                     int proto_version)
+{
+  size_t len;
+  unsigned int ret = 0;
+  struct CBC cbc;
+  char url[255];
+  (void) cls;    /* Unused. Silent compiler warning. */
+
+  len = TESTSTR_SIZE;
+  if (NULL == (cbc.buf = malloc (sizeof (char) * len)))
+  {
+    fprintf (stderr, MHD_E_MEM);
+    return 1;
+  }
+  cbc.size = len;
+  cbc.pos = 0;
+
+  if (gen_test_uri (url,
+                    sizeof (url),
+                    port))
+  {
+    ret = 1;
+    goto cleanup;
+  }
+
+  if (CURLE_OK !=
+      send_curl_req (url, &cbc, cipher_suite, proto_version))
+  {
+    ret = 1;
+    goto cleanup;
+  }
+
+  if ((cbc.pos != TESTSTR_SIZE) ||
+      (0 != check_read_data (cbc.buf, cbc.pos)))
+  {
+    fprintf (stderr, "Error: local file & received file differ.\n");
+    ret = 1;
+  }
+cleanup:
+  free (cbc.buf);
+  return ret;
+}
+
+
+/* perform a HTTP GET request via SSL/TLS */
+static unsigned int
+test_secure_get (FILE *test_fd,
+                 const char *cipher_suite,
+                 int proto_version)
+{
+  unsigned int ret;
+  struct MHD_Daemon *d;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3045;
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                        | MHD_USE_ERROR_LOG, port,
+                        NULL, NULL,
+                        &iovec_ahc, NULL,
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
+                        MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
+                        MHD_OPTION_END);
+
+  if (d == NULL)
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return 1;
+  }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d);
+      return 1;
+    }
+    port = dinfo->port;
+  }
+
+  ret = test_iovec_transfer (test_fd,
+                             port,
+                             cipher_suite,
+                             proto_version);
+
+  MHD_stop_daemon (d);
+  return ret;
+}
+
+
+static enum MHD_Result
+ahc_empty (void *cls,
+           struct MHD_Connection *connection,
+           const char *url,
+           const char *method,
+           const char *version,
+           const char *upload_data,
+           size_t *upload_data_size,
+           void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct MHD_IoVec iov;
+  (void) cls;
+  (void) url;
+  (void) url;
+  (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size; /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET,
+                   method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  iov.iov_base = NULL;
+  iov.iov_len = 0;
+
+  response = MHD_create_response_from_iovec (&iov,
+                                             1,
+                                             NULL,
+                                             NULL);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (20);
+  }
+  return ret;
+}
+
+
+static int
+curlExcessFound (CURL *c,
+                 curl_infotype type,
+                 char *data,
+                 size_t size,
+                 void *cls)
+{
+  static const char *excess_found = "Excess found";
+  const size_t str_size = strlen (excess_found);
+  (void) c;      /* Unused. Silence compiler warning. */
+
+#ifdef _DEBUG
+  if ((CURLINFO_TEXT == type) ||
+      (CURLINFO_HEADER_IN == type) ||
+      (CURLINFO_HEADER_OUT == type))
+    fprintf (stderr, "%.*s", (int) size, data);
+#endif /* _DEBUG */
+  if ((CURLINFO_TEXT == type)
+      && (size >= str_size)
+      && (0 == strncmp (excess_found, data, str_size)))
+    *(int *) cls = 1;
+  return 0;
+}
+
+
+static unsigned int
+testEmptyGet (unsigned int poll_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+  int excess_found = 0;
+
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1225;
+
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | poll_flag | MHD_USE_TLS,
+                        global_port, NULL, NULL,
+                        &ahc_empty, NULL,
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
+                        MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 4194304;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+#endif
+  curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound);
+  curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found);
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 8388608;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 16777216;
+  if (excess_found)
+    return 33554432;
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc; (void) argv;   /* Unused. Silent compiler warning. */
+
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (! testsuite_curl_global_init ())
+    return 99;
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
+
+  errorCount +=
+    test_secure_get (NULL, NULL, CURL_SSLVERSION_DEFAULT);
+  errorCount += testEmptyGet (0);
+  curl_global_cleanup ();
+
+  return errorCount != 0 ? 1 : 0;
+}
diff --git a/src/testcurl/https/test_https_get_parallel.c b/src/testcurl/https/test_https_get_parallel.c
index 166e400..3d7db91 100644
--- a/src/testcurl/https/test_https_get_parallel.c
+++ b/src/testcurl/https/test_https_get_parallel.c
@@ -1,6 +1,7 @@
 /*
   This file is part of libmicrohttpd
   Copyright (C) 2007 Christian Grothoff
+  Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
   libmicrohttpd is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published
@@ -14,15 +15,17 @@
 
   You should have received a copy of the GNU General Public License
   along with libmicrohttpd; see the file COPYING.  If not, write to the
-  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-  Boston, MA 02111-1307, USA.
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+  Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_https_get_parallel.c
- * @brief  Testcase for libmicrohttpd HTTPS GET operations
+ * @brief  Testcase for libmicrohttpd HTTPS GET operations with single-threaded
+ *         MHD daemon and several clients working in parallel
  * @author Sagie Amir
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -31,21 +34,19 @@
 #include <limits.h>
 #include <curl/curl.h>
 #include <pthread.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
+#include "tls_test_keys.h"
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 4
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 4
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 4
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 4
 #endif
 
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
-
-int curl_check_version (const char *req_version, ...);
-
 
 /**
  * used when spawning multiple threads executing curl server requests
@@ -56,11 +57,9 @@
 {
   static int nonnull;
   struct https_test_data *cargs = args;
-  int ret;
+  unsigned int ret;
 
-  /* time spread incomming requests */
-  usleep ((useconds_t) 10.0 * ((double) rand ()) / ((double) RAND_MAX));
-  ret = test_https_transfer (NULL,
+  ret = test_https_transfer (NULL, cargs->port,
                              cargs->cipher_suite, cargs->proto_version);
   if (ret == 0)
     return NULL;
@@ -71,21 +70,22 @@
 /**
  * Test non-parallel requests.
  *
- * @return: 0 upon all client requests returning '0', -1 otherwise.
+ * @return: 0 upon all client requests returning '0', 1 otherwise.
  *
  * TODO : make client_count a parameter - number of curl client threads to spawn
  */
-static int
-test_single_client (void *cls, const char *cipher_suite,
+static unsigned int
+test_single_client (void *cls, uint16_t port, const char *cipher_suite,
                     int curl_proto_version)
 {
   void *client_thread_ret;
   struct https_test_data client_args =
-    { NULL, cipher_suite, curl_proto_version };
+  { NULL, port, cipher_suite, curl_proto_version };
+  (void) cls;    /* Unused. Silent compiler warning. */
 
   client_thread_ret = https_transfer_thread_adapter (&client_args);
   if (client_thread_ret != NULL)
-    return -1;
+    return 1;
   return 0;
 }
 
@@ -93,38 +93,39 @@
 /**
  * Test parallel request handling.
  *
- * @return: 0 upon all client requests returning '0', -1 otherwise.
+ * @return: 0 upon all client requests returning '0', 1 otherwise.
  *
- * TODO : make client_count a parameter - numver of curl client threads to spawn
+ * TODO : make client_count a parameter - number of curl client threads to spawn
  */
-static int
-test_parallel_clients (void * cls, const char *cipher_suite,
+static unsigned int
+test_parallel_clients (void *cls, uint16_t port, const char *cipher_suite,
                        int curl_proto_version)
 {
   int i;
-  int client_count = (CPU_COUNT - 1);
+  int client_count = (MHD_CPU_COUNT - 1);
   void *client_thread_ret;
   pthread_t client_arr[client_count];
   struct https_test_data client_args =
-    { NULL, cipher_suite, curl_proto_version };
+  { NULL, port, cipher_suite, curl_proto_version };
+  (void) cls;    /* Unused. Silent compiler warning. */
 
   for (i = 0; i < client_count; ++i)
+  {
+    if (pthread_create (&client_arr[i], NULL,
+                        &https_transfer_thread_adapter, &client_args) != 0)
     {
-      if (pthread_create (&client_arr[i], NULL,
-                          &https_transfer_thread_adapter, &client_args) != 0)
-        {
-          fprintf (stderr, "Error: failed to spawn test client threads.\n");
-          return -1;
-        }
+      fprintf (stderr, "Error: failed to spawn test client threads.\n");
+      return 1;
     }
+  }
 
   /* check all client requests fulfilled correctly */
   for (i = 0; i < client_count; ++i)
-    {
-      if ((pthread_join (client_arr[i], &client_thread_ret) != 0) ||
-          (client_thread_ret != NULL))
-        return -1;
-    }
+  {
+    if ((pthread_join (client_arr[i], &client_thread_ret) != 0) ||
+        (client_thread_ret != NULL))
+      return 1;
+  }
 
   return 0;
 }
@@ -132,54 +133,68 @@
 
 int
 main (int argc, char *const *argv)
-{  
+{
   unsigned int errorCount = 0;
-  const char *aes256_sha = "AES256-SHA";
+  uint16_t port;
+  unsigned int iseed;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3020;
 
   /* initialize random seed used by curl clients */
-  unsigned int iseed = (unsigned int) time (NULL);
+  iseed = (unsigned int) time (NULL);
   srand (iseed);
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return -1;
-    }
+  if (! testsuite_curl_global_init ())
+    return 99;
 
-  if (curl_uses_nss_ssl() == 0)
-    aes256_sha = "rsa_aes_256_sha";    
-#if EPOLL_SUPPORT
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    return 77;
+  }
+#ifdef EPOLL_SUPPORT
   errorCount +=
-    test_wrap ("single threaded daemon, single client, epoll", &test_single_client,
-               NULL,
-               MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL | MHD_USE_DEBUG | MHD_USE_EPOLL_LINUX_ONLY,
-               aes256_sha, CURL_SSLVERSION_TLSv1, MHD_OPTION_HTTPS_MEM_KEY,
-               srv_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
+    test_wrap ("single threaded daemon, single client, epoll",
+               &test_single_client,
+               NULL, port,
+               MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+               | MHD_USE_ERROR_LOG | MHD_USE_EPOLL,
+               NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY,
+               srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
                srv_self_signed_cert_pem, MHD_OPTION_END);
 #endif
   errorCount +=
     test_wrap ("single threaded daemon, single client", &test_single_client,
-               NULL,
-               MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL | MHD_USE_DEBUG,
-               aes256_sha, CURL_SSLVERSION_TLSv1, MHD_OPTION_HTTPS_MEM_KEY,
-               srv_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
+               NULL, port,
+               MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+               | MHD_USE_ERROR_LOG,
+               NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY,
+               srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
                srv_self_signed_cert_pem, MHD_OPTION_END);
-#if EPOLL_SUPPORT
+#ifdef EPOLL_SUPPORT
   errorCount +=
     test_wrap ("single threaded daemon, parallel clients, epoll",
-               &test_parallel_clients, NULL,
-               MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL | MHD_USE_DEBUG | MHD_USE_EPOLL_LINUX_ONLY,
-               aes256_sha, CURL_SSLVERSION_TLSv1, MHD_OPTION_HTTPS_MEM_KEY,
-               srv_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
+               &test_parallel_clients, NULL, port,
+               MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+               | MHD_USE_ERROR_LOG | MHD_USE_EPOLL,
+               NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY,
+               srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
                srv_self_signed_cert_pem, MHD_OPTION_END);
 #endif
   errorCount +=
     test_wrap ("single threaded daemon, parallel clients",
-               &test_parallel_clients, NULL,
-               MHD_USE_SELECT_INTERNALLY | MHD_USE_SSL | MHD_USE_DEBUG,
-               aes256_sha, CURL_SSLVERSION_TLSv1, MHD_OPTION_HTTPS_MEM_KEY,
-               srv_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
+               &test_parallel_clients, NULL, port,
+               MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+               | MHD_USE_ERROR_LOG,
+               NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY,
+               srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
                srv_self_signed_cert_pem, MHD_OPTION_END);
 
   curl_global_cleanup ();
-  return errorCount != 0;
+  if (errorCount != 0)
+    fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount);
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_get_parallel_threads.c b/src/testcurl/https/test_https_get_parallel_threads.c
index 4cb2128..6e639f4 100644
--- a/src/testcurl/https/test_https_get_parallel_threads.c
+++ b/src/testcurl/https/test_https_get_parallel_threads.c
@@ -1,6 +1,7 @@
 /*
   This file is part of libmicrohttpd
   Copyright (C) 2007 Christian Grothoff
+  Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
   libmicrohttpd is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published
@@ -14,15 +15,17 @@
 
   You should have received a copy of the GNU General Public License
   along with libmicrohttpd; see the file COPYING.  If not, write to the
-  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-  Boston, MA 02111-1307, USA.
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+  Boston, MA 02110-1301, USA.
 */
 
 /**
- * @file tls_thread_mode_test.c
- * @brief  Testcase for libmicrohttpd HTTPS GET operations
+ * @file test_https_get_parallel_threads.c
+ * @brief  Testcase for libmicrohttpd HTTPS GET operations with multi-threaded
+ *         MHD daemon and several clients working in parallel
  * @author Sagie Amir
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  *
  * TODO: add test for external select!
  */
@@ -33,21 +36,19 @@
 #include <limits.h>
 #include <curl/curl.h>
 #include <pthread.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
+#include "tls_test_keys.h"
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 4
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 4
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 4
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 4
 #endif
 
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
-
-int curl_check_version (const char *req_version, ...);
-
 /**
  * used when spawning multiple threads executing curl server requests
  *
@@ -57,35 +58,35 @@
 {
   static int nonnull;
   struct https_test_data *cargs = args;
-  int ret;
+  unsigned int ret;
 
-  /* time spread incomming requests */
-  usleep ((useconds_t) 10.0 * ((double) rand ()) / ((double) RAND_MAX));
-  ret = test_https_transfer (cargs->cls,
+  ret = test_https_transfer (cargs->cls, cargs->port,
                              cargs->cipher_suite, cargs->proto_version);
   if (ret == 0)
     return NULL;
   return &nonnull;
 }
 
+
 /**
  * Test non-parallel requests.
  *
- * @return: 0 upon all client requests returning '0', -1 otherwise.
+ * @return: 0 upon all client requests returning '0', 1 otherwise.
  *
- * TODO : make client_count a parameter - numver of curl client threads to spawn
+ * TODO : make client_count a parameter - number of curl client threads to spawn
  */
-static int
-test_single_client (void *cls, const char *cipher_suite,
+static unsigned int
+test_single_client (void *cls, uint16_t port, const char *cipher_suite,
                     int curl_proto_version)
 {
   void *client_thread_ret;
   struct https_test_data client_args =
-    { NULL, cipher_suite, curl_proto_version };
+  { NULL, port, cipher_suite, curl_proto_version };
+  (void) cls;    /* Unused. Silent compiler warning. */
 
   client_thread_ret = https_transfer_thread_adapter (&client_args);
   if (client_thread_ret != NULL)
-    return -1;
+    return 1;
   return 0;
 }
 
@@ -93,39 +94,40 @@
 /**
  * Test parallel request handling.
  *
- * @return: 0 upon all client requests returning '0', -1 otherwise.
+ * @return: 0 upon all client requests returning '0', 1 otherwise.
  *
- * TODO : make client_count a parameter - numver of curl client threads to spawn
+ * TODO : make client_count a parameter - number of curl client threads to spawn
  */
-static int
-test_parallel_clients (void *cls, const char *cipher_suite,
+static unsigned int
+test_parallel_clients (void *cls, uint16_t port, const char *cipher_suite,
                        int curl_proto_version)
 {
   int i;
-  int client_count = (CPU_COUNT - 1);
+  int client_count = (MHD_CPU_COUNT - 1);
   void *client_thread_ret;
   pthread_t client_arr[client_count];
   struct https_test_data client_args =
-    { NULL, cipher_suite, curl_proto_version };
+  { NULL, port, cipher_suite, curl_proto_version };
+  (void) cls;    /* Unused. Silent compiler warning. */
 
   for (i = 0; i < client_count; ++i)
+  {
+    if (pthread_create (&client_arr[i], NULL,
+                        &https_transfer_thread_adapter, &client_args) != 0)
     {
-      if (pthread_create (&client_arr[i], NULL,
-                          &https_transfer_thread_adapter, &client_args) != 0)
-        {
-          fprintf (stderr, "Error: failed to spawn test client threads.\n");
+      fprintf (stderr, "Error: failed to spawn test client threads.\n");
 
-          return -1;
-        }
+      return 1;
     }
+  }
 
   /* check all client requests fulfilled correctly */
   for (i = 0; i < client_count; ++i)
-    {
-      if ((pthread_join (client_arr[i], &client_thread_ret) != 0) ||
-          (client_thread_ret != NULL))
-        return -1;
-    }
+  {
+    if ((pthread_join (client_arr[i], &client_thread_ret) != 0) ||
+        (client_thread_ret != NULL))
+      return 1;
+  }
 
   return 0;
 }
@@ -136,56 +138,55 @@
 {
   unsigned int errorCount = 0;
   const char *ssl_version;
+  uint16_t port;
+  unsigned int iseed;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3010;
 
   /* initialize random seed used by curl clients */
-  unsigned int iseed = (unsigned int) time (NULL);
+  iseed = (unsigned int) time (NULL);
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
   srand (iseed);
+  if (! testsuite_curl_global_init ())
+    return 99;
   ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version;
   if (NULL == ssl_version)
   {
     fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
-    return 0;
+    curl_global_cleanup ();
+    return 77;
   }
-  if (0 != strncmp (ssl_version, "GnuTLS", 6))
-  {
-    fprintf (stderr, "This test can be run only with libcurl-gnutls.\n");
-    return 0;
-  }
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return -1;
-    }
-
-  char *aes256_sha = "AES256-SHA";
-  if (curl_uses_nss_ssl() == 0)
-    {
-      aes256_sha = "rsa_aes_256_sha";
-    }
 
   errorCount +=
     test_wrap ("multi threaded daemon, single client", &test_single_client,
-               NULL,
-               MHD_USE_SSL | MHD_USE_DEBUG | MHD_USE_THREAD_PER_CONNECTION,
-               aes256_sha, CURL_SSLVERSION_TLSv1, MHD_OPTION_HTTPS_MEM_KEY,
-               srv_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
+               NULL, port,
+               MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_THREAD_PER_CONNECTION
+               | MHD_USE_INTERNAL_POLLING_THREAD,
+               NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY,
+               srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
                srv_self_signed_cert_pem, MHD_OPTION_END);
 
   errorCount +=
     test_wrap ("multi threaded daemon, parallel client",
-               &test_parallel_clients, NULL,
-               MHD_USE_SSL | MHD_USE_DEBUG | MHD_USE_THREAD_PER_CONNECTION,
-               aes256_sha, CURL_SSLVERSION_TLSv1, MHD_OPTION_HTTPS_MEM_KEY,
-               srv_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
+               &test_parallel_clients, NULL, port,
+               MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_THREAD_PER_CONNECTION
+               | MHD_USE_INTERNAL_POLLING_THREAD,
+               NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY,
+               srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT,
                srv_self_signed_cert_pem, MHD_OPTION_END);
 
   if (errorCount != 0)
-    fprintf (stderr, "Failed test: %s.\n", argv[0]);
+    fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount);
 
   curl_global_cleanup ();
-  return errorCount != 0;
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_get_select.c b/src/testcurl/https/test_https_get_select.c
index 9f9ba99..1939ccf 100644
--- a/src/testcurl/https/test_https_get_select.c
+++ b/src/testcurl/https/test_https_get_select.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
  * @file test_https_get_select.c
- * @brief  Testcase for libmicrohttpd HTTPS GET operations
+ * @brief  Testcase for libmicrohttpd HTTPS GET operations using external select
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -29,41 +31,39 @@
 #include <limits.h>
 #include <sys/stat.h>
 #include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
-
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
-extern const char srv_signed_cert_pem[];
-extern const char srv_signed_key_pem[];
+#include "tls_test_keys.h"
 
 static int oneone;
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
@@ -72,8 +72,8 @@
 }
 
 
-static int
-testExternalGet (int flags)
+static unsigned int
+testExternalGet (unsigned int flags)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -84,38 +84,58 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
-  const char *aes256_sha = "AES256-SHA";
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3030;
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | flags,
-                        1082, NULL, NULL, &ahc_echo, "GET", 
-                        MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_TLS | flags,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
-			MHD_OPTION_END);
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
-
-  if (curl_uses_nss_ssl() == 0)
-    aes256_sha = "rsa_aes_256_sha";   
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
 
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1:1082/hello_world");
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+#endif
+  curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   /* TLS options */
-  curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
-  curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, aes256_sha);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
@@ -125,79 +145,111 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 != maxposixs)
+    {
+      if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+      {
+#ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+          abort ();
+#else
+        if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 !=
+                                                                        ws.
+                                                                        fd_count)
+            || (0 != es.fd_count) )
+          abort ();
+        Sleep (1000);
+#endif
+      }
+    }
+    else
+      (void) sleep (1);
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -211,18 +263,24 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return -1;
-    }
-#if EPOLL_SUPPORT
-  if (0 != (errorCount = testExternalGet (MHD_USE_EPOLL_LINUX_ONLY)))
-    fprintf (stderr, "Fail: %d\n", errorCount);
+  oneone = 1;
+  if (! testsuite_curl_global_init ())
+    return 99;
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
+
+#ifdef EPOLL_SUPPORT
+  errorCount += testExternalGet (MHD_USE_EPOLL);
 #endif
-  if (0 != (errorCount = testExternalGet (0)))
-    fprintf (stderr, "Fail: %d\n", errorCount);
+  errorCount += testExternalGet (0);
   curl_global_cleanup ();
-  return errorCount != 0;
+  if (errorCount != 0)
+    fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount);
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_multi_daemon.c b/src/testcurl/https/test_https_multi_daemon.c
index 293aff4..b7b9b06 100644
--- a/src/testcurl/https/test_https_multi_daemon.c
+++ b/src/testcurl/https/test_https_multi_daemon.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
- * @file mhds_multi_daemon_test.c
+ * @file test_https_multi_daemon.c
  * @brief  Testcase for libmicrohttpd multiple HTTPS daemon scenario
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -29,63 +31,126 @@
 #include <curl/curl.h>
 #include <limits.h>
 #include <sys/stat.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
-
-extern int curl_check_version (const char *req_version, ...);
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
+#include "tls_test_keys.h"
 
 /*
  * assert initiating two separate daemons and having one shut down
  * doesn't affect the other
  */
-static int
-test_concurent_daemon_pair (void *cls, 
-			    const char *cipher_suite,
+static unsigned int
+test_concurent_daemon_pair (void *cls,
+                            const char *cipher_suite,
                             int proto_version)
 {
-
-  int ret;
+  unsigned int ret;
+  enum test_get_result res;
   struct MHD_Daemon *d1;
   struct MHD_Daemon *d2;
+  uint16_t port1, port2;
+  (void) cls;    /* Unused. Silent compiler warning. */
 
-  d1 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                         MHD_USE_DEBUG, DEAMON_TEST_PORT,
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port1 = port2 = 0;
+  else
+  {
+    port1 = 3050;
+    port2 = 3051;
+  }
+
+  d1 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                         | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                         | MHD_USE_ERROR_LOG, port1,
                          NULL, NULL, &http_ahc, NULL,
-                         MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
+                         MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
                          MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
                          MHD_OPTION_END);
 
   if (d1 == NULL)
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return 1;
+  }
+  if (0 == port1)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d1, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      fprintf (stderr, "Cannot detect daemon bind port.\n");
+      MHD_stop_daemon (d1);
+      return 1;
     }
+    port1 = (int) dinfo->port;
+  }
 
-  d2 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                         MHD_USE_DEBUG, DEAMON_TEST_PORT + 1,
+  d2 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                         | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                         | MHD_USE_ERROR_LOG, port2,
                          NULL, NULL, &http_ahc, NULL,
-                         MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
+                         MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
                          MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
                          MHD_OPTION_END);
 
   if (d2 == NULL)
+  {
+    MHD_stop_daemon (d1);
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return 1;
+  }
+  if (0 == port2)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d2, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
+      fprintf (stderr, "Cannot detect daemon bind port.\n");
       MHD_stop_daemon (d1);
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      MHD_stop_daemon (d2);
+      return 1;
     }
+    port2 = (int) dinfo->port;
+  }
 
-  ret =
-    test_daemon_get (NULL, cipher_suite, proto_version, DEAMON_TEST_PORT, 0);
-  ret +=
+  res =
+    test_daemon_get (NULL, cipher_suite, proto_version, port1, 0);
+  ret = (unsigned int) res;
+  if ((TEST_GET_HARD_ERROR == res) ||
+      (TEST_GET_CURL_GEN_ERROR == res))
+  {
+    fprintf (stderr, "libcurl error.\nTest aborted.\n");
+    MHD_stop_daemon (d2);
+    MHD_stop_daemon (d1);
+    return 99;
+  }
+
+  res =
     test_daemon_get (NULL, cipher_suite, proto_version,
-                     DEAMON_TEST_PORT + 1, 0);
+                     port2, 0);
+  ret += (unsigned int) res;
+  if ((TEST_GET_HARD_ERROR == res) ||
+      (TEST_GET_CURL_GEN_ERROR == res))
+  {
+    fprintf (stderr, "libcurl error.\nTest aborted.\n");
+    MHD_stop_daemon (d2);
+    MHD_stop_daemon (d1);
+    return 99;
+  }
 
   MHD_stop_daemon (d2);
-  ret +=
-    test_daemon_get (NULL, cipher_suite, proto_version, DEAMON_TEST_PORT, 0);
+  res =
+    test_daemon_get (NULL, cipher_suite, proto_version, port1, 0);
+  ret += (unsigned int) res;
+  if ((TEST_GET_HARD_ERROR == res) ||
+      (TEST_GET_CURL_GEN_ERROR == res))
+  {
+    fprintf (stderr, "libcurl error.\nTest aborted.\n");
+    MHD_stop_daemon (d1);
+    return 99;
+  }
   MHD_stop_daemon (d1);
   return ret;
 }
@@ -94,41 +159,32 @@
 int
 main (int argc, char *const *argv)
 {
-  unsigned int errorCount = 0;
-  FILE *cert;
+  unsigned int errorCount;
+  (void) argc; (void) argv;       /* Unused. Silent compiler warning. */
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error (code: %u). l:%d f:%s\n", errorCount, __LINE__,
-               __FUNCTION__);
-      return -1;
-    }
-  if ((cert = setup_ca_cert ()) == NULL)
-    {
-      fprintf (stderr, MHD_E_TEST_FILE_CREAT);
-      return -1;
-    }
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (! testsuite_curl_global_init ())
+    return 99;
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
 
-  const char *aes256_sha = "AES256-SHA";
-  if (curl_uses_nss_ssl() == 0)
-    {
-      aes256_sha = "rsa_aes_256_sha";
-    }
-  
-  errorCount +=
-    test_concurent_daemon_pair (NULL, aes256_sha, CURL_SSLVERSION_TLSv1);
+  errorCount =
+    test_concurent_daemon_pair (NULL, NULL, CURL_SSLVERSION_DEFAULT);
 
   print_test_result (errorCount, "concurent_daemon_pair");
 
   curl_global_cleanup ();
-  fclose (cert);
-  if (0 != remove (ca_cert_file_name))
-    fprintf (stderr,
-	     "Failed to remove `%s'\n",
-	     ca_cert_file_name);
-  return errorCount != 0;
+  if (99 == errorCount)
+    return 99;
+
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_session_info.c b/src/testcurl/https/test_https_session_info.c
index 8dac253..084ffe6 100644
--- a/src/testcurl/https/test_https_session_info.c
+++ b/src/testcurl/https/test_https_session_info.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
- Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2007, 2016 Christian Grothoff
+ Copyright (C) 2016-2021 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,73 +15,76 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
- * @file mhds_session_info_test.c
+ * @file test_https_session_info.c
  * @brief  Testcase for libmicrohttpd HTTPS connection querying operations
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include "microhttpd.h"
 #include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
+#include "tls_test_keys.h"
 
-extern int curl_check_version (const char *req_version, ...);
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
 
-struct MHD_Daemon *d;
+static int test_append_prio;
 
 /*
  * HTTP access handler call back
  * used to query negotiated security parameters
  */
-static int
-query_session_ahc (void *cls, struct MHD_Connection *connection,
-                   const char *url, const char *method,
-                   const char *upload_data, const char *version,
-                   size_t *upload_data_size, void **ptr)
+static enum MHD_Result
+query_info_ahc (void *cls, struct MHD_Connection *connection,
+                const char *url, const char *method,
+                const char *version, const char *upload_data,
+                size_t *upload_data_size, void **req_cls)
 {
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  const union MHD_ConnectionInfo *conn_info;
+  enum know_gnutls_tls_id *used_tls_ver;
+  (void) url; (void) method; (void) version;   /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */
+  used_tls_ver = (enum know_gnutls_tls_id *) cls;
 
-  if (NULL == *ptr)
-    {
-      *ptr = &query_session_ahc;
-      return MHD_YES;
-    }
+  if (NULL == *req_cls)
+  {
+    *req_cls = (void *) &query_info_ahc;
+    return MHD_YES;
+  }
 
-  if (GNUTLS_TLS1_1 !=
-      (ret = MHD_get_connection_info
-       (connection,
-	MHD_CONNECTION_INFO_PROTOCOL)->protocol))
-    {
-      if (GNUTLS_TLS1_2 == ret)
-      {
-        /* as usual, TLS implementations sometimes don't
-           quite do what was asked, just mildly complain... */
-        fprintf (stderr,
-                 "Warning: requested TLS 1.1, got TLS 1.2\n");
-      }
-      else
-      {
-        /* really different version... */
-        fprintf (stderr,
-                 "Error: requested protocol mismatch (wanted %d, got %d)\n",
-                 GNUTLS_TLS1_1,
-                 ret);
-        return -1;
-      }
-    }
+  conn_info = MHD_get_connection_info (connection,
+                                       MHD_CONNECTION_INFO_PROTOCOL);
+  if (NULL == conn_info)
+  {
+    fflush (stderr);
+    fflush (stdout);
+    fprintf (stderr, "MHD_get_connection_info() failed.\n");
+    fflush (stderr);
+    return MHD_NO;
+  }
+  if (0 == (unsigned int) conn_info->protocol)
+  {
+    fflush (stderr);
+    fflush (stdout);
+    fprintf (stderr, "MHD_get_connection_info()->protocol has "
+             "wrong zero value.\n");
+    fflush (stderr);
+    return MHD_NO;
+  }
+  *used_tls_ver = (enum know_gnutls_tls_id) conn_info->protocol;
 
-  response = MHD_create_response_from_buffer (strlen (EMPTY_PAGE),
-					      (void *) EMPTY_PAGE,
-					      MHD_RESPMEM_PERSISTENT);
+  response = MHD_create_response_from_buffer_static (strlen (EMPTY_PAGE),
+                                                     EMPTY_PAGE);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
@@ -90,97 +94,283 @@
 /**
  * negotiate a secure connection with server & query negotiated security parameters
  */
-static int
-test_query_session ()
+static unsigned int
+test_query_session (enum know_gnutls_tls_id tls_ver, uint16_t *pport)
 {
   CURL *c;
   struct CBC cbc;
   CURLcode errornum;
   char url[256];
+  enum know_gnutls_tls_id found_tls_ver;
+  struct MHD_Daemon *d;
 
   if (NULL == (cbc.buf = malloc (sizeof (char) * 255)))
-    return 16;
+    return 99;
   cbc.size = 255;
   cbc.pos = 0;
 
-  gen_test_file_url (url, DEAMON_TEST_PORT);
-
   /* setup test */
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                        MHD_USE_DEBUG, DEAMON_TEST_PORT,
-                        NULL, NULL, &query_session_ahc, NULL,
-			MHD_OPTION_HTTPS_PRIORITIES, "NORMAL:+ARCFOUR-128",
-                        MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
+  found_tls_ver = KNOWN_BAD;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                        | MHD_USE_ERROR_LOG, *pport,
+                        NULL, NULL,
+                        &query_info_ahc, &found_tls_ver,
+                        test_append_prio ?
+                        MHD_OPTION_HTTPS_PRIORITIES_APPEND :
+                        MHD_OPTION_HTTPS_PRIORITIES,
+                        test_append_prio ?
+                        priorities_append_map[tls_ver] :
+                        priorities_map[tls_ver],
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
                         MHD_OPTION_END);
 
   if (d == NULL)
-    return 2;
-
-  const char *aes256_sha = "AES256-SHA";
-  if (curl_uses_nss_ssl() == 0)
+  {
+    free (cbc.buf);
+    fprintf (stderr, "MHD_start_daemon() with %s failed.\n",
+             tls_names[tls_ver]);
+    fflush (stderr);
+    return 77;
+  }
+  if (0 == *pport)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      aes256_sha = "rsa_aes_256_sha";
+      MHD_stop_daemon (d);
+      free (cbc.buf);
+      fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+      fflush (stderr);
+      return 10;
     }
+    *pport = dinfo->port; /* Use the same port for rest of the checks */
+  }
 
+  gen_test_uri (url,
+                sizeof (url),
+                *pport);
   c = curl_easy_init ();
-#if DEBUG_HTTPS_TEST
-  curl_easy_setopt (c, CURLOPT_VERBOSE, 1);
+  fflush (stderr);
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    fflush (stderr);
+    MHD_stop_daemon (d);
+    free (cbc.buf);
+    return 99;
+  }
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
 #endif
-  curl_easy_setopt (c, CURLOPT_URL, url);
-  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L);
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_FILE, &cbc);
-  /* TLS options */
-  curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_1);
-  curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, aes256_sha);
-  /* currently skip any peer authentication */
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
 
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  if ((CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_URL, url))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                                 CURL_HTTP_VERSION_1_1))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEDATA,
+                                                 &cbc))) ||
+      /* TLS options */
+      /* currently skip any peer authentication */
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))))
+  {
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    MHD_stop_daemon (d);
+    fflush (stderr);
+    fflush (stdout);
+    fprintf (stderr, "Error setting libcurl option: %s.\n",
+             curl_easy_strerror (errornum));
+    fflush (stderr);
+    return 99;
+  }
+
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    unsigned int ret;
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    MHD_stop_daemon (d);
+
+    fflush (stderr);
+    fflush (stdout);
+    if ((CURLE_SSL_CONNECT_ERROR == errornum) ||
+        (CURLE_SSL_CIPHER == errornum))
     {
-      fprintf (stderr, "curl_easy_perform failed: `%s'\n",
+      ret = 77;
+      fprintf (stderr, "libcurl request failed due to TLS error: '%s'\n",
                curl_easy_strerror (errornum));
 
-      MHD_stop_daemon (d);
-      curl_easy_cleanup (c);
-      free (cbc.buf);
-      return -1;
     }
+    else
+    {
+      ret = 1;
+      fprintf (stderr, "curl_easy_perform failed: '%s'\n",
+               curl_easy_strerror (errornum));
+    }
+    fflush (stderr);
+
+    return ret;
+  }
 
   curl_easy_cleanup (c);
-  MHD_stop_daemon (d);
   free (cbc.buf);
+  MHD_stop_daemon (d);
+
+  if (tls_ver != found_tls_ver)
+  {
+    fflush (stderr);
+    fflush (stdout);
+    fprintf (stderr, "MHD_get_connection_info (conn, "
+             "MHD_CONNECTION_INFO_PROTOCOL) returned unexpected "
+             "protocol version.\n"
+             "\tReturned: %s (%u)\tExpected: %s (%u)\n",
+             ((unsigned int) found_tls_ver) > KNOWN_TLS_MAX ?
+             "[wrong value]" : tls_names[found_tls_ver],
+             (unsigned int) found_tls_ver,
+             tls_names[tls_ver], (unsigned int) tls_ver);
+    fflush (stderr);
+    return 2;
+  }
   return 0;
 }
 
 
+static unsigned int
+test_all_supported_versions (void)
+{
+  enum know_gnutls_tls_id ver_for_test; /**< TLS version used for test */
+  const gnutls_protocol_t *vers_list;    /**< The list of GnuTLS supported TLS versions */
+  uint16_t port;
+  unsigned int num_success; /**< Number of tests succeeded */
+  unsigned int num_failed;  /**< Number of tests failed */
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;     /* Use system automatic assignment */
+  else
+    port = 3060;  /* Use predefined port, may break parallel testing of another MHD build */
+
+  vers_list = gnutls_protocol_list ();
+  if (NULL == vers_list)
+  {
+    fprintf (stderr, "Error getting GnuTLS supported TLS versions");
+    return 99;
+  }
+  num_success = 0;
+  num_failed = 0;
+
+  for (ver_for_test = KNOWN_TLS_MIN; KNOWN_TLS_MAX >= ver_for_test;
+       ++ver_for_test)
+  {
+    const gnutls_protocol_t *ver_ptr;      /**< The pointer to the position on the @a vers_list */
+    unsigned int res;
+    for (ver_ptr = vers_list; 0 != *ver_ptr; ++ver_ptr)
+    {
+      if (ver_for_test == (enum know_gnutls_tls_id) *ver_ptr)
+        break;
+    }
+    if (0 == *ver_ptr)
+    {
+      printf ("%s is not supported by GnuTLS, skipping.\n\n",
+              tls_names[ver_for_test]);
+      fflush (stdout);
+      continue;
+    }
+    printf ("Starting check for %s...\n",
+            tls_names[ver_for_test]);
+    fflush (stdout);
+    res = test_query_session (ver_for_test, &port);
+    fflush (stderr);
+    fflush (stdout);
+    if (99 == res)
+    {
+      fprintf (stderr, "Hard error. Test stopped.\n");
+      fflush (stderr);
+      return 99;
+    }
+    else if (77 == res)
+    {
+      printf ("%s does not work with libcurl client and GnuTLS "
+              "server combination, skipping.\n",
+              tls_names[ver_for_test]);
+      fflush (stdout);
+    }
+    else if (0 != res)
+    {
+      fprintf (stderr, "Check failed for %s.\n",
+               tls_names[ver_for_test]);
+      fflush (stderr);
+      num_failed++;
+    }
+    else
+    {
+      printf ("Check succeeded for %s.\n",
+              tls_names[ver_for_test]);
+      fflush (stdout);
+      num_success++;
+    }
+    printf ("\n");
+    fflush (stdout);
+  }
+
+  if (0 == num_failed)
+  {
+    if (0 == num_success)
+    {
+      fprintf (stderr, "No supported TLS version was found.\n");
+      fflush (stderr);
+      return 77;
+    }
+    return 0;
+  }
+  return num_failed;
+}
+
+
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  const char *ssl_version;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error (code: %u)\n", errorCount);
-      return -1;
-    }
-  errorCount += test_query_session ();
-  print_test_result (errorCount, argv[0]);
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  test_append_prio = has_in_name (argv[0], "_append");
+  if (! testsuite_curl_global_init ())
+    return 99;
+
+  ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
+  errorCount = test_all_supported_versions ();
+  fflush (stderr);
+  fflush (stdout);
   curl_global_cleanup ();
-  if (errorCount > 0)
-    fprintf (stderr, "Error (code: %u)\n", errorCount);
-  return errorCount;
+  if (77 == errorCount)
+    return 77;
+  else if (99 == errorCount)
+    return 99;
+  print_test_result (errorCount, argv[0]);
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_https_sni.c b/src/testcurl/https/test_https_sni.c
index 8c4dea6..c4e9400 100644
--- a/src/testcurl/https/test_https_sni.c
+++ b/src/testcurl/https/test_https_sni.c
@@ -1,6 +1,7 @@
 /*
   This file is part of libmicrohttpd
-  Copyright (C) 2013 Christian Grothoff
+  Copyright (C) 2013, 2016 Christian Grothoff
+  Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
   libmicrohttpd is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published
@@ -14,21 +15,24 @@
 
   You should have received a copy of the GNU General Public License
   along with libmicrohttpd; see the file COPYING.  If not, write to the
-  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-  Boston, MA 02111-1307, USA.
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+  Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_https_sni.c
  * @brief  Testcase for libmicrohttpd HTTPS with SNI operations
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "platform.h"
 #include "microhttpd.h"
 #include <limits.h>
 #include <sys/stat.h>
 #include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
 #include <gnutls/gnutls.h>
 
@@ -58,9 +62,9 @@
  * (This code is largely taken from GnuTLS).
  */
 static void
-load_keys(const char *hostname,
-          const char *CERT_FILE,
-          const char *KEY_FILE)
+load_keys (const char *hostname,
+           const char *CERT_FILE,
+           const char *KEY_FILE)
 {
   int ret;
   gnutls_datum_t data;
@@ -75,32 +79,32 @@
 
   ret = gnutls_load_file (CERT_FILE, &data);
   if (ret < 0)
-    {
-      fprintf (stderr,
-               "*** Error loading certificate file %s.\n",
-               CERT_FILE);
-      exit (1);
-    }
+  {
+    fprintf (stderr,
+             "*** Error loading certificate file %s.\n",
+             CERT_FILE);
+    exit (1);
+  }
   ret =
     gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM,
                                   0);
   if (ret < 0)
-    {
-      fprintf (stderr,
-               "*** Error loading certificate file: %s\n",
-               gnutls_strerror (ret));
-      exit (1);
-    }
+  {
+    fprintf (stderr,
+             "*** Error loading certificate file: %s\n",
+             gnutls_strerror (ret));
+    exit (1);
+  }
   gnutls_free (data.data);
 
   ret = gnutls_load_file (KEY_FILE, &data);
   if (ret < 0)
-    {
-      fprintf (stderr,
-               "*** Error loading key file %s.\n",
-               KEY_FILE);
-      exit (1);
-    }
+  {
+    fprintf (stderr,
+             "*** Error loading key file %s.\n",
+             KEY_FILE);
+    exit (1);
+  }
 
   gnutls_privkey_init (&host->key);
   ret =
@@ -108,17 +112,16 @@
                                     &data, GNUTLS_X509_FMT_PEM,
                                     NULL, 0);
   if (ret < 0)
-    {
-      fprintf (stderr,
-               "*** Error loading key file: %s\n",
-               gnutls_strerror (ret));
-      exit (1);
-    }
+  {
+    fprintf (stderr,
+             "*** Error loading key file: %s\n",
+             gnutls_strerror (ret));
+    exit (1);
+  }
   gnutls_free (data.data);
 }
 
 
-
 /**
  * @param session the session we are giving a cert for
  * @param req_ca_dn NULL on server side
@@ -131,18 +134,19 @@
  */
 static int
 sni_callback (gnutls_session_t session,
-              const gnutls_datum_t* req_ca_dn,
+              const gnutls_datum_t *req_ca_dn,
               int nreqs,
-              const gnutls_pk_algorithm_t* pk_algos,
+              const gnutls_pk_algorithm_t *pk_algos,
               int pk_algos_length,
-              gnutls_pcert_st** pcert,
+              gnutls_pcert_st **pcert,
               unsigned int *pcert_length,
-              gnutls_privkey_t * pkey)
+              gnutls_privkey_t *pkey)
 {
   char name[256];
   size_t name_len;
   struct Hosts *host;
   unsigned int type;
+  (void) req_ca_dn; (void) nreqs; (void) pk_algos; (void) pk_algos_length;   /* Unused. Silent compiler warning. */
 
   name_len = sizeof (name);
   if (GNUTLS_E_SUCCESS !=
@@ -156,13 +160,13 @@
     if (0 == strncmp (name, host->hostname, name_len))
       break;
   if (NULL == host)
-    {
-      fprintf (stderr,
-               "Need certificate for %.*s\n",
-               (int) name_len,
-               name);
-      return -1;
-    }
+  {
+    fprintf (stderr,
+             "Need certificate for %.*s\n",
+             (int) name_len,
+             name);
+    return -1;
+  }
 #if 0
   fprintf (stderr,
            "Returning certificate for %.*s\n",
@@ -178,65 +182,70 @@
 
 /* perform a HTTP GET request via SSL/TLS */
 static int
-do_get (const char *url)
+do_get (const char *url, uint16_t port)
 {
   CURL *c;
   struct CBC cbc;
   CURLcode errornum;
   size_t len;
   struct curl_slist *dns_info;
+  char buf[256];
 
   len = strlen (test_data);
   if (NULL == (cbc.buf = malloc (sizeof (char) * len)))
-    {
-      fprintf (stderr, MHD_E_MEM);
-      return -1;
-    }
+  {
+    fprintf (stderr, MHD_E_MEM);
+    return -1;
+  }
   cbc.size = len;
   cbc.pos = 0;
 
   c = curl_easy_init ();
-#if DEBUG_HTTPS_TEST
-  curl_easy_setopt (c, CURLOPT_VERBOSE, 1);
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
 #endif
   curl_easy_setopt (c, CURLOPT_URL, url);
-  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_FILE, &cbc);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_CAINFO, SRCDIR "/test-ca.crt");
 
   /* perform peer authentication */
   /* TODO merge into send_curl_req */
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 2);
-  dns_info = curl_slist_append (NULL, "host1:4233:127.0.0.1");
-  dns_info = curl_slist_append (dns_info, "host2:4233:127.0.0.1");
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L);
+  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 2L);
+  sprintf (buf, "mhdhost1:%u:127.0.0.1", (unsigned int) port);
+  dns_info = curl_slist_append (NULL, buf);
+  sprintf (buf, "mhdhost2:%u:127.0.0.1", (unsigned int) port);
+  dns_info = curl_slist_append (dns_info, buf);
   curl_easy_setopt (c, CURLOPT_RESOLVE, dns_info);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
 
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr, "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      free (cbc.buf);
-      curl_slist_free_all (dns_info);
-      return errornum;
-    }
+  {
+    fprintf (stderr, "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    curl_slist_free_all (dns_info);
+    return errornum;
+  }
 
   curl_easy_cleanup (c);
   curl_slist_free_all (dns_info);
   if (memcmp (cbc.buf, test_data, len) != 0)
-    {
-      fprintf (stderr, "Error: local file & received file differ.\n");
-      free (cbc.buf);
-      return -1;
-    }
+  {
+    fprintf (stderr, "Error: local file & received file differ.\n");
+    free (cbc.buf);
+    return -1;
+  }
 
   free (cbc.buf);
   return 0;
@@ -248,44 +257,88 @@
 {
   unsigned int error_count = 0;
   struct MHD_Daemon *d;
+  uint16_t port;
+  const char *tls_backend;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3065;
+
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return -1;
-    }
-  load_keys ("host1", ABS_SRCDIR "/host1.crt", ABS_SRCDIR "/host1.key");
-  load_keys ("host2", ABS_SRCDIR "/host2.crt", ABS_SRCDIR "/host2.key");
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL | MHD_USE_DEBUG,
-                        4233,
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (! testsuite_curl_global_init ())
+    return 99;
+  tls_backend = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == tls_backend)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
+  if (! curl_tls_is_gnutls () && ! curl_tls_is_openssl ())
+  {
+    fprintf (stderr, "This test is reliable only with libcurl with GnuTLS or "
+             "OpenSSL backends.\nSkipping the test as libcurl has '%s' "
+             "backend.\n", tls_backend);
+    curl_global_cleanup ();
+    return 77;
+  }
+
+  load_keys ("mhdhost1", SRCDIR "/mhdhost1.crt",
+             SRCDIR "/mhdhost1.key");
+  load_keys ("mhdhost2", SRCDIR "/mhdhost2.crt",
+             SRCDIR "/mhdhost2.key");
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                        | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL,
                         &http_ahc, NULL,
                         MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback,
                         MHD_OPTION_END);
   if (d == NULL)
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return -1;
+  }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      MHD_stop_daemon (d); return -1;
     }
-  error_count += do_get ("https://host1:4233/");
-  error_count += do_get ("https://host2:4233/");
+    port = dinfo->port;
+  }
+  if (0 != do_get ("https://mhdhost1/", port))
+    error_count++;
+  if (0 != do_get ("https://mhdhost2/", port))
+    error_count++;
 
   MHD_stop_daemon (d);
   curl_global_cleanup ();
-  return error_count != 0;
+  if (error_count != 0)
+    fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], error_count);
+  return (0 != error_count) ? 1 : 0;
 }
 
 
 #else
 
-int main ()
+int
+main (void)
 {
   fprintf (stderr,
            "SNI not supported by GnuTLS < 3.0\n");
-  return 0;
+  return 77;
 }
+
+
 #endif
diff --git a/src/testcurl/https/test_https_time_out.c b/src/testcurl/https/test_https_time_out.c
index 124a280..24159fc 100644
--- a/src/testcurl/https/test_https_time_out.c
+++ b/src/testcurl/https/test_https_time_out.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,22 +15,36 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
- * @file mhds_get_test.c
- * @brief: daemon TLS alert response test-case
+ * @file test_https_time_out.c
+ * @brief: daemon TLS timeout test
  *
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include "microhttpd.h"
-#include "internal.h"
 #include "tls_test_common.h"
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif /* HAVE_SIGNAL_H */
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+
+#include "mhd_sockets.h" /* only macros used */
+
 
 #ifdef _WIN32
 #ifndef WIN32_LEAN_AND_MEAN
@@ -37,62 +52,143 @@
 #endif /* !WIN32_LEAN_AND_MEAN */
 #include <windows.h>
 #endif
+#include "tls_test_keys.h"
 
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
+static const unsigned int timeout_val = 2;
 
-static const int TIME_OUT = 3;
+static volatile unsigned int num_connects = 0;
+static volatile unsigned int num_disconnects = 0;
 
-static int
-test_tls_session_time_out (gnutls_session_t session)
+
+/**
+ * Pause execution for specified number of milliseconds.
+ * @param ms the number of milliseconds to sleep
+ */
+static void
+_MHD_sleep (uint32_t ms)
+{
+#if defined(_WIN32)
+  Sleep (ms);
+#elif defined(HAVE_NANOSLEEP)
+  struct timespec slp = {ms / 1000, (ms % 1000) * 1000000};
+  struct timespec rmn;
+  int num_retries = 0;
+  while (0 != nanosleep (&slp, &rmn))
+  {
+    if (num_retries++ > 8)
+      break;
+    slp = rmn;
+  }
+#elif defined(HAVE_USLEEP)
+  uint64_t us = ms * 1000;
+  do
+  {
+    uint64_t this_sleep;
+    if (999999 < us)
+      this_sleep = 999999;
+    else
+      this_sleep = us;
+    /* Ignore return value as it could be void */
+    usleep (this_sleep);
+    us -= this_sleep;
+  } while (us > 0);
+#else
+  sleep ((ms + 999) / 1000);
+#endif
+}
+
+
+static void
+socket_cb (void *cls,
+           struct MHD_Connection *c,
+           void **socket_context,
+           enum MHD_ConnectionNotificationCode toe)
+{
+  if (NULL == socket_context)
+    abort ();
+  if (NULL == c)
+    abort ();
+  if (NULL != cls)
+    abort ();
+
+  if (MHD_CONNECTION_NOTIFY_STARTED == toe)
+  {
+    num_connects++;
+#ifdef _DEBUG
+    fprintf (stderr, "MHD: Connection has started.\n");
+#endif /* _DEBUG */
+  }
+  else if (MHD_CONNECTION_NOTIFY_CLOSED == toe)
+  {
+    num_disconnects++;
+#ifdef _DEBUG
+    fprintf (stderr, "MHD: Connection has closed.\n");
+#endif /* _DEBUG */
+  }
+  else
+    abort ();
+}
+
+
+static unsigned int
+test_tls_session_time_out (gnutls_session_t session, uint16_t port)
 {
   int ret;
   MHD_socket sd;
   struct sockaddr_in sa;
 
   sd = socket (AF_INET, SOCK_STREAM, 0);
-  if (sd == -1)
-    {
-      fprintf (stderr, "Failed to create socket: %s\n", strerror (errno));
-      return -1;
-    }
+  if (sd == MHD_INVALID_SOCKET)
+  {
+    fprintf (stderr, "Failed to create socket: %s\n", strerror (errno));
+    return 2;
+  }
 
   memset (&sa, '\0', sizeof (struct sockaddr_in));
   sa.sin_family = AF_INET;
-  sa.sin_port = htons (DEAMON_TEST_PORT);
+  sa.sin_port = htons (port);
   sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
 
-  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) (intptr_t) sd);
-
-  ret = connect (sd, &sa, sizeof (struct sockaddr_in));
+  ret = connect (sd, (struct sockaddr *) &sa, sizeof (struct sockaddr_in));
 
   if (ret < 0)
-    {
-      fprintf (stderr, "Error: %s\n", MHD_E_FAILED_TO_CONNECT);
-      close (sd);
-      return -1;
-    }
+  {
+    fprintf (stderr, "Error: %s\n", MHD_E_FAILED_TO_CONNECT);
+    MHD_socket_close_chk_ (sd);
+    return 2;
+  }
+
+#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64)
+  gnutls_transport_set_int (session, (int) (sd));
+#else  /* GnuTLS before 3.1.9 or Win64 */
+  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) (intptr_t) (sd));
+#endif /* GnuTLS before 3.1.9 or Win64 */
 
   ret = gnutls_handshake (session);
   if (ret < 0)
-    {
-      fprintf (stderr, "Handshake failed\n");
-      close (sd);
-      return -1;
-    }
+  {
+    fprintf (stderr, "Handshake failed\n");
+    MHD_socket_close_chk_ (sd);
+    return 2;
+  }
 
-  sleep (TIME_OUT + 1);
+  _MHD_sleep (timeout_val * 1000 + 1700);
 
+  if (0 == num_connects)
+  {
+    fprintf (stderr, "MHD has not detected any connection attempt.\n");
+    MHD_socket_close_chk_ (sd);
+    return 4;
+  }
   /* check that server has closed the connection */
-  /* TODO better RST trigger */
-  if (send (sd, "", 1, 0) == 0)
-    {
-      fprintf (stderr, "Connection failed to time-out\n");
-      close (sd);
-      return -1;
-    }
+  if (0 == num_disconnects)
+  {
+    fprintf (stderr, "MHD has not detected any disconnections.\n");
+    MHD_socket_close_chk_ (sd);
+    return 1;
+  }
 
-  close (sd);
+  MHD_socket_close_chk_ (sd);
   return 0;
 }
 
@@ -100,47 +196,84 @@
 int
 main (int argc, char *const *argv)
 {
-  int errorCount = 0;;
+  unsigned int errorCount = 0;
   struct MHD_Daemon *d;
   gnutls_session_t session;
-  gnutls_datum_t key;
-  gnutls_datum_t cert;
   gnutls_certificate_credentials_t xcred;
+  uint16_t port;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3070;
 
+#ifdef MHD_SEND_SPIPE_SUPPRESS_NEEDED
+#if defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
+  if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
+  {
+    fprintf (stderr, "Error suppressing SIGPIPE signal.\n");
+    exit (99);
+  }
+#else /* ! HAVE_SIGNAL_H || ! SIGPIPE */
+  fprintf (stderr, "Cannot suppress SIGPIPE signal.\n");
+  /* exit (77); */
+#endif
+#endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED */
+
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
-  gnutls_global_init ();
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (GNUTLS_E_SUCCESS != gnutls_global_init ())
+  {
+    fprintf (stderr, "Cannot initialize GnuTLS.\n");
+    exit (99);
+  }
   gnutls_global_set_log_level (11);
 
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                        MHD_USE_DEBUG, DEAMON_TEST_PORT,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                        | MHD_USE_ERROR_LOG, port,
                         NULL, NULL, &http_dummy_ahc, NULL,
-                        MHD_OPTION_CONNECTION_TIMEOUT, TIME_OUT,
-                        MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
+                        MHD_OPTION_CONNECTION_TIMEOUT,
+                        (unsigned int) timeout_val,
+                        MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL,
+                        MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
                         MHD_OPTION_END);
 
-  if (d == NULL)
+  if (NULL == d)
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return -1;
+  }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      MHD_stop_daemon (d);
+      return 99;
     }
+    port = dinfo->port;
+  }
 
-  if (0 != setup_session (&session, &key, &cert, &xcred))
-    {
-      fprintf (stderr, "failed to setup session\n");
-      return 1;
-    }
-  errorCount += test_tls_session_time_out (session);
-  teardown_session (session, &key, &cert, xcred);
+  if (0 != setup_session (&session, &xcred))
+  {
+    fprintf (stderr, "failed to setup session\n");
+    return 1;
+  }
+  errorCount += test_tls_session_time_out (session, port);
+  teardown_session (session, xcred);
 
   print_test_result (errorCount, argv[0]);
 
   MHD_stop_daemon (d);
   gnutls_global_deinit ();
 
-  return errorCount != 0;
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_tls_authentication.c b/src/testcurl/https/test_tls_authentication.c
index cc9c76d..56b61c9 100644
--- a/src/testcurl/https/test_tls_authentication.c
+++ b/src/testcurl/https/test_tls_authentication.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
- * @file tls_authentication_test.c
- * @brief  Testcase for libmicrohttpd HTTPS GET operations
+ * @file test_tls_authentication.c
+ * @brief  Testcase for libmicrohttpd HTTPS GET operations with CA-signed TLS server certificate
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
@@ -29,82 +31,113 @@
 #include <curl/curl.h>
 #include <limits.h>
 #include <sys/stat.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
-
-extern int curl_check_version (const char *req_version, ...);
-extern const char test_file_data[];
-
-extern const char ca_key_pem[];
-extern const char ca_cert_pem[];
-extern const char srv_signed_cert_pem[];
-extern const char srv_signed_key_pem[];
-
+#include "tls_test_keys.h"
 
 
 /* perform a HTTP GET request via SSL/TLS */
-static int
-test_secure_get (void * cls, char *cipher_suite, int proto_version)
+static unsigned int
+test_secure_get (void *cls, const char *cipher_suite, int proto_version)
 {
-  int ret;
+  enum test_get_result ret;
   struct MHD_Daemon *d;
+  uint16_t port;
+  (void) cls;    /* Unused. Silent compiler warning. */
 
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
-                        MHD_USE_DEBUG, DEAMON_TEST_PORT,
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 3075;
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                        | MHD_USE_ERROR_LOG, port,
                         NULL, NULL, &http_ahc, NULL,
                         MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem,
                         MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem,
                         MHD_OPTION_END);
 
   if (d == NULL)
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return 1;
+  }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
+      MHD_stop_daemon (d);
+      return 1;
     }
+    port = dinfo->port;
+  }
 
-  ret = test_daemon_get (NULL, cipher_suite, proto_version, DEAMON_TEST_PORT, 0);
+  ret = test_daemon_get (NULL, cipher_suite, proto_version, port, 1);
 
   MHD_stop_daemon (d);
-  return ret;
+  if (TEST_GET_HARD_ERROR == ret)
+    return 99;
+  if (TEST_GET_CURL_GEN_ERROR == ret)
+  {
+    fprintf (stderr, "libcurl error.\nTest aborted.\n");
+    return 99;
+  }
+  if ((TEST_GET_CURL_CA_ERROR == ret) ||
+      (TEST_GET_CURL_NOT_IMPLT == ret))
+  {
+    fprintf (stderr, "libcurl TLS backend does not support custom CA.\n"
+             "Test skipped.\n");
+    return 77;
+  }
+  return TEST_GET_OK == ret ? 0 : 1;
 }
 
 
 int
 main (int argc, char *const *argv)
 {
-  unsigned int errorCount = 0;
+  unsigned int errorCount;
+  (void) argc;
+  (void) argv;       /* Unused. Silent compiler warning. */
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
-  if (setup_ca_cert () == NULL)
-    {
-      fprintf (stderr, MHD_E_TEST_FILE_CREAT);
-      return -1;
-    }
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (! testsuite_curl_global_init ())
+    return 99;
+  if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version)
+  {
+    fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
+#if ! CURL_AT_LEAST_VERSION (7,60,0)
+  if (curl_tls_is_schannel ())
+  {
+    fprintf (stderr, "libcurl before version 7.60.0 does not support "
+             "custom CA with Schannel backend.\nTest skipped.\n");
+    curl_global_cleanup ();
+    return 77;
+  }
+#endif /* ! CURL_AT_LEAST_VERSION(7,60,0) */
 
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error (code: %u)\n", errorCount);
-      return -1;
-    }
-
-  char *aes256_sha = "AES256-SHA";
-  if (curl_uses_nss_ssl() == 0)
-    {
-      aes256_sha = "rsa_aes_256_sha";
-    }
-
-  errorCount +=
-    test_secure_get (NULL, aes256_sha, CURL_SSLVERSION_TLSv1);
+  errorCount =
+    test_secure_get (NULL, NULL, CURL_SSLVERSION_DEFAULT);
 
   print_test_result (errorCount, argv[0]);
 
   curl_global_cleanup ();
-  if (0 != remove (ca_cert_file_name))
-    fprintf (stderr,
-	     "Failed to remove `%s'\n",
-	     ca_cert_file_name);
-  return errorCount != 0;
+  if (77 == errorCount)
+    return 77;
+  if (99 == errorCount)
+    return 77;
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/test_tls_options.c b/src/testcurl/https/test_tls_options.c
index 7dd01a7..09e0c9c 100644
--- a/src/testcurl/https/test_tls_options.c
+++ b/src/testcurl/https/test_tls_options.c
@@ -1,155 +1,458 @@
 /*
   This file is part of libmicrohttpd
-  Copyright (C) 2007, 2010 Christian Grothoff
-  
+  Copyright (C) 2007, 2016 Christian Grothoff
+  Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
   libmicrohttpd 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 2, or (at your
   option) any later version.
-  
+
   libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
-  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-  Boston, MA 02111-1307, USA.
-*/
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+  Boston, MA 02110-1301, USA.
+ */
 
 /**
- * @file tls_daemon_options_test.c
- * @brief  Testcase for libmicrohttpd HTTPS GET operations
+ * @file test_tls_options.c
+ * @brief  Testcase for libmicrohttpd HTTPS TLS version match/mismatch
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "platform.h"
 #include "microhttpd.h"
-#include <sys/stat.h>
-#include <limits.h>
+#include <curl/curl.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 #include "tls_test_common.h"
+#include "tls_test_keys.h"
 
-extern const char srv_key_pem[];
-extern const char srv_self_signed_cert_pem[];
-
-int curl_check_version (const char *req_version, ...);
-
-/**
- * test server refuses to negotiate connections with unsupported protocol versions
- *
+/*
+ * HTTP access handler call back
+ * used to query negotiated security parameters
  */
-static int
-test_unmatching_ssl_version (void * cls, const char *cipher_suite,
-                             int curl_req_ssl_version)
+static enum MHD_Result
+simple_ahc (void *cls, struct MHD_Connection *connection,
+            const char *url, const char *method,
+            const char *version, const char *upload_data,
+            size_t *upload_data_size, void **req_cls)
 {
-  struct CBC cbc;
-  if (NULL == (cbc.buf = malloc (sizeof (char) * 256)))
-    {
-      fprintf (stderr, "Error: failed to allocate: %s\n",
-               strerror (errno));
-      return -1;
-    }
-  cbc.size = 256;
-  cbc.pos = 0;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) cls; (void) url; (void) method; (void) version;   /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */
 
-  char url[255];
-  if (gen_test_file_url (url, DEAMON_TEST_PORT))
-    {
-      free (cbc.buf);
-      fprintf (stderr, "Internal error in gen_test_file_url\n");
-      return -1;
-    }
+  if (NULL == *req_cls)
+  {
+    *req_cls = (void *) &simple_ahc;
+    return MHD_YES;
+  }
 
-  /* assert daemon *rejected* request */
-  if (CURLE_OK ==
-      send_curl_req (url, &cbc, cipher_suite, curl_req_ssl_version))
-    {
-      free (cbc.buf);
-      fprintf (stderr, "cURL failed to reject request despite SSL version missmatch!\n");
-      return -1;
-    }
-
-  free (cbc.buf);
-  return 0;
+  response =
+    MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE),
+                                            EMPTY_PAGE);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  return ret;
 }
 
 
-/* setup a temporary transfer test file */
+enum check_result
+{
+  CHECK_RES_OK = 0,
+  CHECK_RES_ERR = 1,
+
+  CHECK_RES_MHD_START_FAILED = 17,
+  CHECK_RES_CURL_TLS_INIT_FAIL = 18,
+  CHECK_RES_CURL_TLS_CONN_FAIL = 19,
+
+  CHECK_RES_HARD_ERROR = 99
+};
+
+static enum check_result
+check_tls_match_inner (enum know_gnutls_tls_id tls_ver_mhd,
+                       enum know_gnutls_tls_id tls_ver_libcurl,
+                       uint16_t *pport,
+                       struct MHD_Daemon **d_ptr,
+                       struct CBC *pcbc,
+                       CURL **c_ptr)
+{
+  CURLcode errornum;
+  char url[256];
+  int libcurl_tls_set;
+  CURL *c;
+  struct MHD_Daemon *d;
+
+  /* setup test */
+  d =
+    MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                      | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS
+                      | MHD_USE_ERROR_LOG, *pport,
+                      NULL, NULL,
+                      &simple_ahc, NULL,
+                      MHD_OPTION_HTTPS_PRIORITIES, priorities_map[tls_ver_mhd],
+                      MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem,
+                      MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
+                      MHD_OPTION_END);
+  fflush (stderr);
+  fflush (stdout);
+  *d_ptr = d;
+
+  if (d == NULL)
+  {
+    fprintf (stderr, "MHD_start_daemon() with %s failed.\n",
+             tls_names[tls_ver_mhd]);
+    return CHECK_RES_MHD_START_FAILED;
+  }
+  if (0 == *pport)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+      return CHECK_RES_ERR;
+    }
+    *pport = dinfo->port; /* Use the same port for rest of the checks */
+  }
+
+  if (0 != gen_test_uri (url,
+                         sizeof (url),
+                         *pport))
+  {
+    fprintf (stderr, "failed to generate URI.\n");
+    return CHECK_RES_CURL_TLS_INIT_FAIL;
+  }
+  c = curl_easy_init ();
+  fflush (stderr);
+  fflush (stdout);
+  *c_ptr = c;
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    return CHECK_RES_HARD_ERROR;
+  }
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+#endif
+
+  if ((CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_URL, url))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                                 CURL_HTTP_VERSION_1_1))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEDATA,
+                                                 pcbc))) ||
+      /* TLS options */
+      /* currently skip any peer authentication */
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))) ||
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) ||
+      (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))))
+  {
+    fflush (stderr);
+    fflush (stdout);
+    fprintf (stderr, "Error setting libcurl option: %s.\n",
+             curl_easy_strerror (errornum));
+    return CHECK_RES_HARD_ERROR;
+  }
+  libcurl_tls_set = 0;
+#if CURL_AT_LEAST_VERSION (7,54,0)
+  if (CURL_SSLVERSION_MAX_DEFAULT !=
+      libcurl_tls_max_vers_map[tls_ver_libcurl])
+  {
+    errornum = curl_easy_setopt (c, CURLOPT_SSLVERSION,
+                                 libcurl_tls_vers_map[tls_ver_libcurl]
+                                 | libcurl_tls_max_vers_map[tls_ver_libcurl]);
+    if (CURLE_OK == errornum)
+      libcurl_tls_set = 1;
+    else
+    {
+      fprintf (stderr, "Error setting libcurl TLS version range: "
+               "%s.\nRetrying with minimum TLS version only.\n",
+               curl_easy_strerror (errornum));
+    }
+  }
+#endif /* CURL_AT_LEAST_VERSION(7,54,0) */
+  if (! libcurl_tls_set &&
+      (CURLE_OK !=
+       (errornum = curl_easy_setopt (c, CURLOPT_SSLVERSION,
+                                     libcurl_tls_vers_map[tls_ver_libcurl]))))
+  {
+    fprintf (stderr, "Error setting libcurl minimum TLS version: %s.\n",
+             curl_easy_strerror (errornum));
+    return CHECK_RES_CURL_TLS_INIT_FAIL;
+  }
+
+  errornum = curl_easy_perform (c);
+  fflush (stderr);
+  fflush (stdout);
+  if (CURLE_OK != errornum)
+  {
+    if ((CURLE_SSL_CONNECT_ERROR == errornum) ||
+        (CURLE_SSL_CIPHER == errornum))
+    {
+      fprintf (stderr, "libcurl request failed due to TLS error: '%s'\n",
+               curl_easy_strerror (errornum));
+      return CHECK_RES_CURL_TLS_CONN_FAIL;
+
+    }
+    else
+    {
+      fprintf (stderr, "curl_easy_perform failed: '%s'\n",
+               curl_easy_strerror (errornum));
+      return CHECK_RES_ERR;
+    }
+  }
+  return CHECK_RES_OK;
+}
+
+
+/**
+ * negotiate a secure connection with server with specific TLS versions
+ * set for MHD and for libcurl
+ */
+static enum check_result
+check_tls_match (enum know_gnutls_tls_id tls_ver_mhd,
+                 enum know_gnutls_tls_id tls_ver_libcurl,
+                 uint16_t *pport)
+{
+  CURL *c;
+  struct CBC cbc;
+  enum check_result ret;
+  struct MHD_Daemon *d;
+
+  if (NULL == (cbc.buf = malloc (sizeof (char) * 255)))
+    return CHECK_RES_HARD_ERROR;
+  cbc.size = 255;
+  cbc.pos = 0;
+
+  d = NULL;
+  c = NULL;
+  ret = check_tls_match_inner (tls_ver_mhd, tls_ver_libcurl, pport,
+                               &d, &cbc, &c);
+  fflush (stderr);
+  fflush (stdout);
+  if (NULL != d)
+    MHD_stop_daemon (d);
+  if (NULL != c)
+    curl_easy_cleanup (c);
+  free (cbc.buf);
+
+  return ret;
+}
+
+
+static unsigned int
+test_first_supported_versions (void)
+{
+  enum know_gnutls_tls_id ver_for_check; /**< TLS version used for test */
+  const gnutls_protocol_t *vers_list;    /**< The list of GnuTLS supported TLS versions */
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;     /* Use system automatic assignment */
+  else
+    port = 3080;  /* Use predefined port, may break parallel testing of another MHD build */
+
+  vers_list = gnutls_protocol_list ();
+  if (NULL == vers_list)
+  {
+    fprintf (stderr, "Error getting GnuTLS supported TLS versions");
+    return 99;
+  }
+
+  for (ver_for_check = KNOWN_TLS_MIN; KNOWN_TLS_MAX >= ver_for_check;
+       ++ver_for_check)
+  {
+    const gnutls_protocol_t *ver_ptr;      /**< The pointer to the position on the @a vers_list */
+    enum check_result res;
+    for (ver_ptr = vers_list; 0 != *ver_ptr; ++ver_ptr)
+    {
+      if (ver_for_check == (enum know_gnutls_tls_id) *ver_ptr)
+        break;
+    }
+    if (0 == *ver_ptr)
+    {
+      printf ("%s is not supported by GnuTLS, skipping.\n\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      continue;
+    }
+    if (CURL_SSLVERSION_LAST == libcurl_tls_vers_map[ver_for_check])
+    {
+      printf ("%s is not supported by libcurl, skipping.\n\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      continue;
+    }
+    /* Found some TLS version that supported by GnuTLS and should be supported
+       by libcurl (but in practice support depends on used TLS library) */
+
+    if (KNOWN_TLS_MIN != ver_for_check)
+      printf ("\n");
+    printf ("Starting check with MHD set to '%s' and "
+            "libcurl set to '%s' (successful connection is expected)...\n",
+            tls_names[ver_for_check], tls_names[ver_for_check]);
+    fflush (stdout);
+
+    /* Check with MHD and libcurl set to the same TLS version */
+    res = check_tls_match (ver_for_check, ver_for_check, &port);
+    if (CHECK_RES_HARD_ERROR == res)
+    {
+      fprintf (stderr, "Hard error. Test stopped.\n");
+      fflush (stderr);
+      return 99;
+    }
+    else if (CHECK_RES_ERR == res)
+    {
+      printf ("Test failed.\n");
+      fflush (stdout);
+      return 2;
+    }
+    else if (CHECK_RES_MHD_START_FAILED == res)
+    {
+      printf ("Skipping '%s' as MHD cannot be started with this setting.\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      continue;
+    }
+    else if (CHECK_RES_CURL_TLS_INIT_FAIL == res)
+    {
+      printf ("Skipping '%s' as libcurl rejected this setting.\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      continue;
+    }
+    else if (CHECK_RES_CURL_TLS_CONN_FAIL == res)
+    {
+      printf ("Skipping '%s' as it is not supported by current libcurl "
+              "and GnuTLS combination.\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      continue;
+    }
+    printf ("Connection succeeded for MHD set to '%s' and "
+            "libcurl set to '%s'.\n\n",
+            tls_names[ver_for_check], tls_names[ver_for_check]);
+
+    /* Check with libcurl set to the next TLS version relative to MHD setting */
+    if (KNOWN_TLS_MAX == ver_for_check)
+    {
+      printf ("Test is incomplete as the latest known TLS version ('%s') "
+              "was found as minimum working version.\nThere is no space to "
+              "advance to the next version.\nAssuming that test is fine.\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      return 0;
+    }
+    if (CURL_SSLVERSION_LAST == libcurl_tls_vers_map[ver_for_check + 1])
+    {
+      printf ("Test is incomplete as '%s' is the latest version supported "
+              "by libcurl.\nThere is no space to "
+              "advance to the next version.\nAssuming that test is fine.\n",
+              tls_names[ver_for_check]);
+      fflush (stdout);
+      return 0;
+    }
+    printf ("Starting check with MHD set to '%s' and "
+            "minimum libcurl TLS version set to '%s' "
+            "(failed connection is expected)...\n",
+            tls_names[ver_for_check], tls_names[ver_for_check + 1]);
+    fflush (stdout);
+    res = check_tls_match (ver_for_check, ver_for_check + 1,
+                           &port);
+    if (CHECK_RES_HARD_ERROR == res)
+    {
+      fprintf (stderr, "Hard error. Test stopped.\n");
+      fflush (stderr);
+      return 99;
+    }
+    else if (CHECK_RES_ERR == res)
+    {
+      printf ("Test failed.\n");
+      fflush (stdout);
+      return 2;
+    }
+    else if (CHECK_RES_MHD_START_FAILED == res)
+    {
+      printf ("MHD cannot be started for the second time with "
+              "the same setting.\n");
+      fflush (stdout);
+      return 4;
+    }
+    else if (CHECK_RES_CURL_TLS_INIT_FAIL == res)
+    {
+      printf ("'%s' has been rejected by libcurl.\n"
+              "Assuming that test is fine.\n",
+              tls_names[ver_for_check + 1]);
+      fflush (stdout);
+      return 0;
+    }
+    else if (CHECK_RES_CURL_TLS_CONN_FAIL == res)
+    {
+      printf ("As expected, libcurl cannot connect to MHD when libcurl "
+              "minimum TLS version is set to '%s' while MHD TLS version set "
+              "to '%s'.\n"
+              "Test succeeded.\n",
+              tls_names[ver_for_check + 1], tls_names[ver_for_check]);
+      fflush (stdout);
+      return 0;
+    }
+  }
+
+  fprintf (stderr, "The test skipped: No know TLS versions are supported by "
+           "both MHD and libcurl.\n");
+  fflush (stderr);
+  return 77;
+}
+
+
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
   const char *ssl_version;
-  int daemon_flags =
-    MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL | MHD_USE_DEBUG;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
- if (curl_check_version (MHD_REQ_CURL_VERSION))
-    {
-      return 0;
-    }
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if (! testsuite_curl_global_init ())
+    return 99;
+
   ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version;
   if (NULL == ssl_version)
   {
     fprintf (stderr, "Curl does not support SSL.  Cannot run the test.\n");
-    return 0;
+    curl_global_cleanup ();
+    return 77;
   }
-  if (0 != strncmp (ssl_version, "GnuTLS", 6))
-  {
-    fprintf (stderr, "This test can be run only with libcurl-gnutls.\n");
-    return 0;
-  }
-
-  if (0 != curl_global_init (CURL_GLOBAL_ALL))
-    {
-      fprintf (stderr, "Error: %s\n", strerror (errno));
-      return 0; 
-    }
-
-  const char *aes128_sha = "AES128-SHA";
-  const char *aes256_sha = "AES256-SHA";
-  if (curl_uses_nss_ssl() == 0)
-    {
-      aes128_sha = "rsa_aes_128_sha";
-      aes256_sha = "rsa_aes_256_sha";
-    }
-  
-
-  if (0 != 
-    test_wrap ("TLS1.0-AES-SHA1",
-	       &test_https_transfer, NULL, daemon_flags,
-	       aes128_sha,
-	       CURL_SSLVERSION_TLSv1,
-	       MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
-	       MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
-	       MHD_OPTION_HTTPS_PRIORITIES, "NONE:+VERS-TLS1.0:+AES-128-CBC:+SHA1:+RSA:+COMP-NULL",
-	       MHD_OPTION_END))
-    {
-      fprintf (stderr, "TLS1.0-AES-SHA1 test failed\n");
-      errorCount++;
-    }
-  fprintf (stderr,
-	   "The following handshake should fail (and print an error message)...\n");
-  if (0 !=
-    test_wrap ("TLS1.0 vs SSL3",
-	       &test_unmatching_ssl_version, NULL, daemon_flags,
-	       aes256_sha,
-	       CURL_SSLVERSION_SSLv3,
-	       MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
-	       MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
-	       MHD_OPTION_HTTPS_PRIORITIES, "NONE:+VERS-TLS1.0:+AES-256-CBC:+SHA1:+RSA:+COMP-NULL",
-	       MHD_OPTION_END))
-    {
-      fprintf (stderr, "TLS1.0 vs SSL3 test failed\n");
-      errorCount++;
-    }
+  errorCount = test_first_supported_versions ();
+  fflush (stderr);
+  fflush (stdout);
   curl_global_cleanup ();
-
-  return errorCount != 0;
+  if (77 == errorCount)
+    return 77;
+  else if (99 == errorCount)
+    return 99;
+  print_test_result (errorCount, argv[0]);
+  return errorCount != 0 ? 1 : 0;
 }
diff --git a/src/testcurl/https/tls_test_common.c b/src/testcurl/https/tls_test_common.c
index f917582..f28f2fb 100644
--- a/src/testcurl/https/tls_test_common.c
+++ b/src/testcurl/https/tls_test_common.c
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2017-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,189 +15,309 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 /**
  * @file tls_test_common.c
  * @brief  Common tls test functions
  * @author Sagie Amir
+ * @author Karlson2k (Evgeny Grin)
  */
+#include <string.h>
 #include "tls_test_common.h"
 #include "tls_test_keys.h"
 
+/**
+ * Map @a know_gnutls_tls_ids values to printable names.
+ */
+const char *tls_names[KNOW_TLS_IDS_COUNT] = {
+  "Bad value",
+  "SSL version 3",
+  "TLS version 1.0",
+  "TLS version 1.1",
+  "TLS version 1.2",
+  "TLS version 1.3"
+};
 
-int curl_check_version (const char *req_version, ...);
+/**
+ * Map @a know_gnutls_tls_ids values to GnuTLS priorities strings.
+ */
+const char *priorities_map[KNOW_TLS_IDS_COUNT] = {
+  "NONE",
+  "NORMAL:!VERS-ALL:+VERS-SSL3.0",
+  "NORMAL:!VERS-ALL:+VERS-TLS1.0",
+  "NORMAL:!VERS-ALL:+VERS-TLS1.1",
+  "NORMAL:!VERS-ALL:+VERS-TLS1.2",
+  "NORMAL:!VERS-ALL:+VERS-TLS1.3"
+};
 
-FILE *
-setup_ca_cert ()
-{
-  FILE *cert_fd;
+/**
+ * Map @a know_gnutls_tls_ids values to GnuTLS priorities append strings.
+ */
+const char *priorities_append_map[KNOW_TLS_IDS_COUNT] = {
+  "NONE",
+  "!VERS-ALL:+VERS-SSL3.0",
+  "!VERS-ALL:+VERS-TLS1.0",
+  "!VERS-ALL:+VERS-TLS1.1",
+  "!VERS-ALL:+VERS-TLS1.2",
+  "!VERS-ALL:+VERS-TLS1.3"
+};
 
-  if (NULL == (cert_fd = fopen (ca_cert_file_name, "wb+")))
-    {
-      fprintf (stderr, "Error: failed to open `%s': %s\n",
-               ca_cert_file_name, strerror (errno));
-      return NULL;
-    }
-  if (fwrite (ca_cert_pem, sizeof (char), strlen (ca_cert_pem) + 1, cert_fd)
-      != strlen (ca_cert_pem) + 1)
-    {
-      fprintf (stderr, "Error: failed to write `%s. %s'\n",
-               ca_cert_file_name, strerror (errno));
-      fclose (cert_fd);
-      return NULL;
-    }
-  if (fflush (cert_fd))
-    {
-      fprintf (stderr, "Error: failed to flush ca cert file stream. %s\n",
-               strerror (errno));
-      fclose (cert_fd);
-      return NULL;
-    }
-  return cert_fd;
-}
 
+/**
+ * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value.
+ */
+const long libcurl_tls_vers_map[KNOW_TLS_IDS_COUNT] = {
+  CURL_SSLVERSION_LAST, /* bad value */
+  CURL_SSLVERSION_SSLv3,
+#if CURL_AT_LEAST_VERSION (7,34,0)
+  CURL_SSLVERSION_TLSv1_0,
+#else  /* CURL VER < 7.34.0 */
+  CURL_SSLVERSION_TLSv1, /* TLS 1.0 or later */
+#endif /* CURL VER < 7.34.0 */
+#if CURL_AT_LEAST_VERSION (7,34,0)
+  CURL_SSLVERSION_TLSv1_1,
+#else  /* CURL VER < 7.34.0 */
+  CURL_SSLVERSION_LAST, /* bad value, not supported by this libcurl version */
+#endif /* CURL VER < 7.34.0 */
+#if CURL_AT_LEAST_VERSION (7,34,0)
+  CURL_SSLVERSION_TLSv1_2,
+#else  /* CURL VER < 7.34.0 */
+  CURL_SSLVERSION_LAST, /* bad value, not supported by this libcurl version */
+#endif /* CURL VER < 7.34.0 */
+#if CURL_AT_LEAST_VERSION (7,52,0)
+  CURL_SSLVERSION_TLSv1_3
+#else  /* CURL VER < 7.34.0 */
+  CURL_SSLVERSION_LAST /* bad value, not supported by this libcurl version */
+#endif /* CURL VER < 7.34.0 */
+};
+
+#if CURL_AT_LEAST_VERSION (7,54,0)
+/**
+ * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value
+ * for maximum supported TLS version.
+ */
+const long libcurl_tls_max_vers_map[KNOW_TLS_IDS_COUNT]  = {
+  CURL_SSLVERSION_MAX_DEFAULT, /* bad value */
+  CURL_SSLVERSION_MAX_DEFAULT, /* SSLv3 */
+  CURL_SSLVERSION_MAX_TLSv1_0,
+  CURL_SSLVERSION_MAX_TLSv1_1,
+  CURL_SSLVERSION_MAX_TLSv1_2,
+  CURL_SSLVERSION_MAX_TLSv1_3
+};
+#endif /* CURL_AT_LEAST_VERSION(7,54,0) */
 
 /*
  * test HTTPS transfer
  */
-int
+enum test_get_result
 test_daemon_get (void *cls,
-		 const char *cipher_suite, int proto_version,
-		 int port,
-		 int ver_peer)
+                 const char *cipher_suite,
+                 int proto_version,
+                 uint16_t port,
+                 int ver_peer)
 {
   CURL *c;
   struct CBC cbc;
   CURLcode errornum;
+  CURLcode e;
   char url[255];
   size_t len;
+  (void) cls;    /* Unused. Silence compiler warning. */
 
   len = strlen (test_data);
   if (NULL == (cbc.buf = malloc (sizeof (char) * len)))
-    {
-      fprintf (stderr, MHD_E_MEM);
-      return -1;
-    }
+  {
+    fprintf (stderr, MHD_E_MEM);
+    return TEST_GET_HARD_ERROR;
+  }
   cbc.size = len;
   cbc.pos = 0;
 
   /* construct url - this might use doc_path */
-  gen_test_file_url (url, port);
+  gen_test_uri (url,
+                sizeof (url),
+                port);
 
   c = curl_easy_init ();
-#if DEBUG_HTTPS_TEST
-  curl_easy_setopt (c, CURLOPT_VERBOSE, 1);
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
 #endif
-  curl_easy_setopt (c, CURLOPT_URL, url);
-  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L);
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_FILE, &cbc);
+  if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_URL, url))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                          CURL_HTTP_VERSION_1_1))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                          &copyBuffer))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))))
+  {
+    fprintf (stderr, "curl_easy_setopt failed: `%s'\n",
+             curl_easy_strerror (e));
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    return TEST_GET_CURL_GEN_ERROR;
+  }
 
   /* TLS options */
-  curl_easy_setopt (c, CURLOPT_SSLVERSION, proto_version);
-  curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, cipher_suite);
+  if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSLVERSION,
+                                          proto_version))) ||
+      ((NULL != cipher_suite) &&
+       (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST,
+                                           cipher_suite)))) ||
 
-  /* perform peer authentication */
-  /* TODO merge into send_curl_req */
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, ver_peer);
-  curl_easy_setopt (c, CURLOPT_CAINFO, ca_cert_file_name);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  
-  /* NOTE: use of CONNECTTIMEOUT without also
-     setting NOSIGNAL results in really weird
-     crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+      /* perform peer authentication */
+      /* TODO merge into send_curl_req */
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER,
+                                          ver_peer))) ||
+      (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))))
+  {
+    fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n",
+             curl_easy_strerror (e));
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    return TEST_GET_CURL_GEN_ERROR;
+  }
+  if (ver_peer &&
+      (CURLE_OK !=
+       (e = curl_easy_setopt (c, CURLOPT_CAINFO, ca_cert_file_name))))
+  {
+    fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n",
+             curl_easy_strerror (e));
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    return TEST_GET_CURL_CA_ERROR;
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr, "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      free (cbc.buf);
-      return errornum;
-    }
+  {
+    fprintf (stderr, "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    free (cbc.buf);
+    if ((CURLE_SSL_CACERT_BADFILE == errornum)
+#if CURL_AT_LEAST_VERSION (7,21,5)
+        || (CURLE_NOT_BUILT_IN == errornum)
+#endif /* CURL_AT_LEAST_VERSION (7,21,5) */
+        )
+      return TEST_GET_CURL_CA_ERROR;
+    if (CURLE_OUT_OF_MEMORY == errornum)
+      return TEST_GET_HARD_ERROR;
+    return TEST_GET_ERROR;
+  }
 
   curl_easy_cleanup (c);
 
   if (memcmp (cbc.buf, test_data, len) != 0)
-    {
-      fprintf (stderr, "Error: local file & received file differ.\n");
-      free (cbc.buf);
-      return -1;
-    }
+  {
+    fprintf (stderr, "Error: local data & received data differ.\n");
+    free (cbc.buf);
+    return TEST_GET_TRANSFER_ERROR;
+  }
 
   free (cbc.buf);
-  return 0;
+  return TEST_GET_OK;
 }
 
 
 void
-print_test_result (int test_outcome, char *test_name)
+print_test_result (unsigned int test_outcome,
+                   const char *test_name)
 {
-#if 0
   if (test_outcome != 0)
-    fprintf (stderr, "running test: %s [fail]\n", test_name);
+    fprintf (stderr,
+             "running test: %s [fail: %u]\n",
+             test_name, test_outcome);
+#if 0
   else
-    fprintf (stdout, "running test: %s [pass]\n", test_name);
+    fprintf (stdout,
+             "running test: %s [pass]\n",
+             test_name);
 #endif
 }
 
+
 size_t
-copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
 {
   struct CBC *cbc = ctx;
 
   if (cbc->pos + size * nmemb > cbc->size)
+  {
+    fprintf (stderr, "Server data does not fit buffer.\n");
     return 0;                   /* overflow */
+  }
   memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
   cbc->pos += size * nmemb;
   return size * nmemb;
 }
 
+
 /**
  *  HTTP access handler call back
  */
-int
-http_ahc (void *cls, struct MHD_Connection *connection,
-          const char *url, const char *method, const char *upload_data,
-          const char *version, size_t *upload_data_size, void **ptr)
+enum MHD_Result
+http_ahc (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
 {
   static int aptr;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) url; (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
   if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
-  *ptr = NULL;                  /* reset when done */
-  response = MHD_create_response_from_buffer (strlen (test_data),
-					      (void *) test_data,
-					      MHD_RESPMEM_PERSISTENT);
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;                  /* reset when done */
+  response = MHD_create_response_from_buffer_static (strlen (test_data),
+                                                     test_data);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
+
 /* HTTP access handler call back */
-int
-http_dummy_ahc (void *cls, struct MHD_Connection *connection,
-                const char *url, const char *method, const char *upload_data,
-                const char *version, size_t *upload_data_size,
-                void **ptr)
+enum MHD_Result
+http_dummy_ahc (void *cls,
+                struct MHD_Connection *connection,
+                const char *url,
+                const char *method,
+                const char *version,
+                const char *upload_data,
+                size_t *upload_data_size,
+                void **req_cls)
 {
+  (void) cls;
+  (void) connection;
+  (void) url;
+  (void) method;
+  (void) version;      /* Unused. Silent compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size;
+  (void) req_cls;                   /* Unused. Silent compiler warning. */
   return 0;
 }
 
+
 /**
  * send a test http request to the daemon
  * @param url
@@ -206,48 +327,70 @@
  * @return
  */
 /* TODO have test wrap consider a NULL cbc */
-int
-send_curl_req (char *url, struct CBC * cbc, const char *cipher_suite,
+CURLcode
+send_curl_req (char *url,
+               struct CBC *cbc,
+               const char *cipher_suite,
                int proto_version)
 {
   CURL *c;
   CURLcode errornum;
+  CURLcode e;
   c = curl_easy_init ();
-#if DEBUG_HTTPS_TEST
-  curl_easy_setopt (c, CURLOPT_VERBOSE, CURL_VERBOS_LEVEL);
+#ifdef _DEBUG
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
 #endif
-  curl_easy_setopt (c, CURLOPT_URL, url);
-  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 60L);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 60L);
+  if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_URL, url))) ||
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                           CURL_HTTP_VERSION_1_1))) ||
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, 60L))) ||
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 60L))) ||
 
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) ||
+
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))))
+  {
+    fprintf (stderr, "curl_easy_setopt failed: `%s'\n",
+             curl_easy_strerror (e));
+    curl_easy_cleanup (c);
+    return e;
+  }
   if (cbc != NULL)
+  {
+    if ((CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                             &copyBuffer))) ||
+        (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc))))
     {
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_FILE, cbc);
+      fprintf (stderr, "curl_easy_setopt failed: `%s'\n",
+               curl_easy_strerror (e));
+      curl_easy_cleanup (c);
+      return e;
     }
+  }
 
   /* TLS options */
-  curl_easy_setopt (c, CURLOPT_SSLVERSION, proto_version);
-  curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, cipher_suite);
+  if ((CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_SSLVERSION,
+                                           proto_version))) ||
+      ((NULL != cipher_suite) &&
+       (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST,
+                                           cipher_suite)))) ||
+      /* currently skip any peer authentication */
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) ||
+      (CURLE_OK  != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))))
+  {
+    fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n",
+             curl_easy_strerror (e));
+    curl_easy_cleanup (c);
+    return e;
+  }
 
-  /* currently skip any peer authentication */
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0);
-  curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0);
-
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-
-  /* NOTE: use of CONNECTTIMEOUT without also
-     setting NOSIGNAL results in really weird
-     crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr, "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      return errornum;
-    }
+  {
+    fprintf (stderr, "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    return errornum;
+  }
   curl_easy_cleanup (c);
 
   return CURLE_OK;
@@ -255,230 +398,385 @@
 
 
 /**
- * compile test file url pointing to the current running directory path
+ * compile test URI
  *
- * @param url - char buffer into which the url is compiled
+ * @param[out] uri - char buffer into which the url is compiled
+ * @param uri_len number of bytes available in @a url
  * @param port port to use for the test
- * @return -1 on error
+ * @return 1 on error
  */
-int
-gen_test_file_url (char *url, int port)
+unsigned int
+gen_test_uri (char *uri,
+              size_t uri_len,
+              uint16_t port)
 {
-  int ret = 0;
-  char *doc_path;
-  size_t doc_path_len;
-  /* setup test file path, url */
-  doc_path_len = PATH_MAX > 4096 ? 4096 : PATH_MAX;
-  if (NULL == (doc_path = malloc (doc_path_len)))
-    {
-      fprintf (stderr, MHD_E_MEM);
-      return -1;
-    }
-  if (getcwd (doc_path, doc_path_len) == NULL)
-    {
-      fprintf (stderr, "Error: failed to get working directory. %s\n",
-               strerror (errno));
-      ret = -1;
-    }
-#ifdef WINDOWS
-  {
-    int i;
-    for (i = 0; i < doc_path_len; i++)
-    {
-      if (doc_path[i] == 0)
-        break;
-      if (doc_path[i] == '\\')
-      {
-        doc_path[i] = '/';
-      }
-      if (doc_path[i] != ':')
-        continue;
-      if (i == 0)
-        break;
-      doc_path[i] = doc_path[i - 1];
-      doc_path[i - 1] = '/';
-    }
-  }
-#endif
-  /* construct url - this might use doc_path */
-  if (sprintf (url, "%s:%d%s/%s", "https://127.0.0.1", port,
-               doc_path, "urlpath") < 0)
-    ret = -1;
+  int res;
 
-  free (doc_path);
-  return ret;
+  res = snprintf (uri,
+                  uri_len,
+                  "https://127.0.0.1:%u/urlpath",
+                  (unsigned int) port);
+  if (res <= 0)
+    return 1;
+  if ((size_t) res >= uri_len)
+    return 1;
+
+  return 0;
 }
 
+
 /**
- * test HTTPS file transfer
+ * test HTTPS data transfer
  */
-int
-test_https_transfer (void *cls, const char *cipher_suite, int proto_version)
+unsigned int
+test_https_transfer (void *cls,
+                     uint16_t port,
+                     const char *cipher_suite,
+                     int proto_version)
 {
-  int len;
-  int ret = 0;
+  size_t len;
+  unsigned int ret = 0;
   struct CBC cbc;
   char url[255];
+  (void) cls;    /* Unused. Silent compiler warning. */
 
   len = strlen (test_data);
   if (NULL == (cbc.buf = malloc (sizeof (char) * len)))
-    {
-      fprintf (stderr, MHD_E_MEM);
-      return -1;
-    }
+  {
+    fprintf (stderr, MHD_E_MEM);
+    return 1;
+  }
   cbc.size = len;
   cbc.pos = 0;
 
-  if (gen_test_file_url (url, DEAMON_TEST_PORT))
-    {
-      ret = -1;
-      goto cleanup;
-    }
+  if (gen_test_uri (url,
+                    sizeof (url),
+                    port))
+  {
+    ret = 1;
+    goto cleanup;
+  }
 
-  if (CURLE_OK != send_curl_req (url, &cbc, cipher_suite, proto_version))
-    {
-      ret = -1;
-      goto cleanup;
-    }
+  if (CURLE_OK !=
+      send_curl_req (url, &cbc, cipher_suite, proto_version))
+  {
+    ret = 1;
+    goto cleanup;
+  }
 
-  /* compare test file & daemon responce */
+  /* compare test data & daemon response */
   if ( (len != strlen (test_data)) ||
-       (memcmp (cbc.buf, 
-		test_data, 
-		len) != 0) )
-    {
-      fprintf (stderr, "Error: local file & received file differ.\n");
-      ret = -1;
-    }
+       (memcmp (cbc.buf,
+                test_data,
+                len) != 0) )
+  {
+    fprintf (stderr, "Error: original data & received data differ.\n");
+    ret = 1;
+  }
 cleanup:
   free (cbc.buf);
   return ret;
 }
 
+
 /**
  * setup test case
  *
  * @param d
  * @param daemon_flags
  * @param arg_list
- * @return
+ * @return port number on success or zero on failure
  */
-int
-setup_testcase (struct MHD_Daemon **d, int daemon_flags, va_list arg_list)
+static uint16_t
+setup_testcase (struct MHD_Daemon **d, uint16_t port, unsigned int daemon_flags,
+                va_list arg_list)
 {
-  *d = MHD_start_daemon_va (daemon_flags, DEAMON_TEST_PORT,
+  *d = MHD_start_daemon_va (daemon_flags, port,
                             NULL, NULL, &http_ahc, NULL, arg_list);
 
   if (*d == NULL)
-    {
-      fprintf (stderr, MHD_E_SERVER_INIT);
-      return -1;
-    }
+  {
+    fprintf (stderr, MHD_E_SERVER_INIT);
+    return 0;
+  }
 
-  return 0;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (*d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (*d);
+      return 0;
+    }
+    port = dinfo->port;
+  }
+
+  return port;
 }
 
-void
+
+static void
 teardown_testcase (struct MHD_Daemon *d)
 {
   MHD_stop_daemon (d);
 }
 
-int
-setup_session (gnutls_session_t * session,
-               gnutls_datum_t * key,
-               gnutls_datum_t * cert, 
-	       gnutls_certificate_credentials_t * xcred)
-{
-  int ret;
-  const char *err_pos;
 
-  gnutls_certificate_allocate_credentials (xcred);
-  key->size = strlen (srv_key_pem) + 1;
-  key->data = malloc (key->size);
-  if (NULL == key->data) 
-     {
-       gnutls_certificate_free_credentials (*xcred);
-	return -1;
-     }
-  memcpy (key->data, srv_key_pem, key->size);
-  cert->size = strlen (srv_self_signed_cert_pem) + 1;
-  cert->data = malloc (cert->size);
-  if (NULL == cert->data)
+unsigned int
+setup_session (gnutls_session_t *session,
+               gnutls_certificate_credentials_t *xcred)
+{
+  if (GNUTLS_E_SUCCESS == gnutls_init (session, GNUTLS_CLIENT))
+  {
+    if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (*session))
     {
+      if (GNUTLS_E_SUCCESS == gnutls_certificate_allocate_credentials (xcred))
+      {
+        if (GNUTLS_E_SUCCESS == gnutls_credentials_set (*session,
+                                                        GNUTLS_CRD_CERTIFICATE,
+                                                        *xcred))
+        {
+          return 0;
+        }
         gnutls_certificate_free_credentials (*xcred);
-	free (key->data); 
-	return -1;
+      }
     }
-  memcpy (cert->data, srv_self_signed_cert_pem, cert->size);
-  gnutls_certificate_set_x509_key_mem (*xcred, cert, key,
-				       GNUTLS_X509_FMT_PEM);
-  gnutls_init (session, GNUTLS_CLIENT);
-  ret = gnutls_priority_set_direct (*session,
-				    "NORMAL", &err_pos);
-  if (ret < 0)
-    {
-       gnutls_deinit (*session);
-       gnutls_certificate_free_credentials (*xcred);
-       free (key->data);
-       return -1;
-    }
-  gnutls_credentials_set (*session, 
-			  GNUTLS_CRD_CERTIFICATE, 
-			  *xcred);
-  return 0;
+    gnutls_deinit (*session);
+  }
+  return 1;
 }
 
-int
+
+unsigned int
 teardown_session (gnutls_session_t session,
-                  gnutls_datum_t * key,
-                  gnutls_datum_t * cert,
                   gnutls_certificate_credentials_t xcred)
 {
-  free (key->data);
-  key->data = NULL;
-  key->size = 0;
-  free (cert->data);
-  cert->data = NULL;
-  cert->size = 0;
   gnutls_deinit (session);
   gnutls_certificate_free_credentials (xcred);
   return 0;
 }
 
+
 /* TODO test_wrap: change sig to (setup_func, test, va_list test_arg) */
-int
-test_wrap (const char *test_name, int
-           (*test_function) (void * cls, const char *cipher_suite,
-                             int proto_version), void * cls,
-           int daemon_flags, const char *cipher_suite, int proto_version, ...)
+unsigned int
+test_wrap (const char *test_name, unsigned int
+           (*test_function)(void *cls, uint16_t port, const char *cipher_suite,
+                            int proto_version), void *cls,
+           uint16_t port,
+           unsigned int daemon_flags, const char *cipher_suite,
+           int proto_version, ...)
 {
-  int ret;
+  unsigned int ret;
   va_list arg_list;
   struct MHD_Daemon *d;
+  (void) cls;    /* Unused. Silent compiler warning. */
 
   va_start (arg_list, proto_version);
-  if (setup_testcase (&d, daemon_flags, arg_list) != 0)
-    {
-      va_end (arg_list);
-      fprintf (stderr, "Failed to setup testcase %s\n", test_name);
-      return -1;
-    }
+  port = setup_testcase (&d, port, daemon_flags, arg_list);
+  if (0 == port)
+  {
+    va_end (arg_list);
+    fprintf (stderr, "Failed to setup testcase %s\n", test_name);
+    return 1;
+  }
 #if 0
   fprintf (stdout, "running test: %s ", test_name);
 #endif
-  ret = test_function (NULL, cipher_suite, proto_version);
+  ret = test_function (NULL, port, cipher_suite, proto_version);
 #if 0
   if (ret == 0)
-    {
-      fprintf (stdout, "[pass]\n");
-    }
+  {
+    fprintf (stdout, "[pass]\n");
+  }
   else
-    {
-      fprintf (stdout, "[fail]\n");
-    }
+  {
+    fprintf (stdout, "[fail]\n");
+  }
 #endif
   teardown_testcase (d);
   va_end (arg_list);
   return ret;
 }
+
+
+static int inited_tls_is_gnutls = 0;
+static int inited_tls_is_openssl = 0;
+
+int
+curl_tls_is_gnutls (void)
+{
+  const char *tlslib;
+  if (inited_tls_is_gnutls)
+    return 1;
+  if (inited_tls_is_openssl)
+    return 0;
+
+  tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == tlslib)
+    return 0;
+  if (0 == strncmp (tlslib, "GnuTLS/", 7))
+    return 1;
+
+  /* Multi-backends handled during initialization by setting variable */
+  return 0;
+}
+
+
+int
+curl_tls_is_openssl (void)
+{
+  const char *tlslib;
+  if (inited_tls_is_gnutls)
+    return 0;
+  if (inited_tls_is_openssl)
+    return 1;
+
+  tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == tlslib)
+    return 0;
+  if (0 == strncmp (tlslib, "OpenSSL/", 8))
+    return 1;
+
+  /* Multi-backends handled during initialization by setting variable */
+  return 0;
+}
+
+
+int
+curl_tls_is_nss (void)
+{
+  const char *tlslib;
+  if (inited_tls_is_gnutls)
+    return 0;
+  if (inited_tls_is_openssl)
+    return 0;
+
+  tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == tlslib)
+    return 0;
+  if (0 == strncmp (tlslib, "NSS/", 4))
+    return 1;
+
+  /* Handle multi-backends with selected backend */
+  if (NULL != strstr (tlslib," NSS/"))
+    return 1;
+
+  return 0;
+}
+
+
+int
+curl_tls_is_schannel (void)
+{
+  const char *tlslib;
+  if (inited_tls_is_gnutls)
+    return 0;
+  if (inited_tls_is_openssl)
+    return 0;
+
+  tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == tlslib)
+    return 0;
+  if ((0 == strncmp (tlslib, "Schannel", 8)) || (0 == strncmp (tlslib, "WinSSL",
+                                                               6)))
+    return 1;
+
+  /* Handle multi-backends with selected backend */
+  if ((NULL != strstr (tlslib," Schannel")) || (NULL != strstr (tlslib,
+                                                                " WinSSL")))
+    return 1;
+
+  return 0;
+}
+
+
+int
+curl_tls_is_sectransport (void)
+{
+  const char *tlslib;
+  if (inited_tls_is_gnutls)
+    return 0;
+  if (inited_tls_is_openssl)
+    return 0;
+
+  tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version;
+  if (NULL == tlslib)
+    return 0;
+  if (0 == strncmp (tlslib, "SecureTransport", 15))
+    return 1;
+
+  /* Handle multi-backends with selected backend */
+  if (NULL != strstr (tlslib," SecureTransport"))
+    return 1;
+
+  return 0;
+}
+
+
+int
+testsuite_curl_global_init (void)
+{
+  CURLcode res;
+#if LIBCURL_VERSION_NUM >= 0x073800
+  if (CURLSSLSET_OK != curl_global_sslset (CURLSSLBACKEND_GNUTLS, NULL, NULL))
+  {
+    CURLsslset e;
+    e = curl_global_sslset (CURLSSLBACKEND_OPENSSL, NULL, NULL);
+    if (CURLSSLSET_TOO_LATE == e)
+      fprintf (stderr, "WARNING: libcurl was already initialised.\n");
+    else if (CURLSSLSET_OK == e)
+      inited_tls_is_openssl = 1;
+  }
+  else
+    inited_tls_is_gnutls = 1;
+#endif /* LIBCURL_VERSION_NUM >= 0x07380 */
+  res = curl_global_init (CURL_GLOBAL_ALL);
+  if (CURLE_OK != res)
+  {
+    fprintf (stderr, "libcurl initialisation error: %s\n",
+             curl_easy_strerror (res));
+    return 0;
+  }
+  return 1;
+}
+
+
+/**
+ * Check whether program name contains specific @a marker string.
+ * Only last component in pathname is checked for marker presence,
+ * all leading directories names (if any) are ignored. Directories
+ * separators are handled correctly on both non-W32 and W32
+ * platforms.
+ * @param prog_name program name, may include path
+ * @param marker    marker to look for.
+ * @return zero if any parameter is NULL or empty string or
+ *         @prog_name ends with slash or @marker is not found in
+ *         program name, non-zero if @maker is found in program
+ *         name.
+ */
+int
+has_in_name (const char *prog_name, const char *marker)
+{
+  size_t name_pos;
+  size_t pos;
+
+  if (! prog_name || ! marker || ! prog_name[0] || ! marker[0])
+    return 0;
+
+  pos = 0;
+  name_pos = 0;
+  while (prog_name[pos])
+  {
+    if ('/' == prog_name[pos])
+      name_pos = pos + 1;
+#if defined(_WIN32) || defined(__CYGWIN__)
+    else if ('\\' == prog_name[pos])
+      name_pos = pos + 1;
+#endif /* _WIN32 || __CYGWIN__ */
+    pos++;
+  }
+  if (name_pos == pos)
+    return 0;
+  return strstr (prog_name + name_pos, marker) != (char *) 0;
+}
diff --git a/src/testcurl/https/tls_test_common.h b/src/testcurl/https/tls_test_common.h
index 20198f7..998467f 100644
--- a/src/testcurl/https/tls_test_common.h
+++ b/src/testcurl/https/tls_test_common.h
@@ -1,6 +1,7 @@
 /*
  This file is part of libmicrohttpd
  Copyright (C) 2007 Christian Grothoff
+ Copyright (C) 2017-2022 Evgeny Grin (Karlson2k)
 
  libmicrohttpd is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
@@ -14,8 +15,8 @@
 
  You should have received a copy of the GNU General Public License
  along with libmicrohttpd; see the file COPYING.  If not, write to the
- Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- Boston, MA 02111-1307, USA.
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
  */
 
 #ifndef TLS_TEST_COMMON_H_
@@ -28,29 +29,89 @@
 #include <limits.h>
 #include <gnutls/gnutls.h>
 
-/* this enables verbos CURL version checking */
-#define DEBUG_HTTPS_TEST 0
-#define CURL_VERBOS_LEVEL 0
-
-#define DEAMON_TEST_PORT 4233
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
 
 #define test_data "Hello World\n"
-#define ca_cert_file_name "tmp_ca_cert.pem"
+#define ca_cert_file_name SRCDIR "/test-ca.crt"
 
-#define EMPTY_PAGE "<html><head><title>Empty page</title></head><body>Empty page</body></html>"
-#define PAGE_NOT_FOUND "<html><head><title>File not found</title></head><body>File not found</body></html>"
+#define EMPTY_PAGE \
+  "<html><head><title>Empty page</title></head><body>Empty page</body></html>"
+#define PAGE_NOT_FOUND \
+  "<html><head><title>File not found</title></head><body>File not found</body></html>"
 
 #define MHD_E_MEM "Error: memory error\n"
 #define MHD_E_SERVER_INIT "Error: failed to start server\n"
 #define MHD_E_TEST_FILE_CREAT "Error: failed to setup test file\n"
 #define MHD_E_CERT_FILE_CREAT "Error: failed to setup test certificate\n"
 #define MHD_E_KEY_FILE_CREAT "Error: failed to setup test certificate\n"
-#define MHD_E_FAILED_TO_CONNECT "Error: server connection could not be established\n"
+#define MHD_E_FAILED_TO_CONNECT \
+  "Error: server connection could not be established\n"
 
-/* TODO rm if unused */
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+/* The local copy if GnuTLS IDs to avoid long #ifdefs list with various
+ * GnuTLS versions */
+/**
+ * The list of know (at the moment of writing) GnuTLS IDs of TLS versions.
+ * Can be safely casted to/from @a gnutls_protocol_t.
+ */
+enum know_gnutls_tls_id
+{
+  KNOWN_BAD = 0,       /**< No TLS */
+  KNOWN_TLS_SSLv3 = 1, /**< GNUTLS_SSL3 */
+  KNOWN_TLS_V1_0 =  2, /**< GNUTLS_TLS1_0 */
+  KNOWN_TLS_V1_1 =  3, /**< GNUTLS_TLS1_1 */
+  KNOWN_TLS_V1_2 =  4, /**< GNUTLS_TLS1_2 */
+  KNOWN_TLS_V1_3 =  5, /**< GNUTLS_TLS1_3 */
+  KNOWN_TLS_MIN = KNOWN_TLS_SSLv3, /**< Minimum valid value */
+  KNOWN_TLS_MAX = KNOWN_TLS_V1_3   /**< Maximum valid value */
+};
+
+#define KNOW_TLS_IDS_COUNT 6 /* KNOWN_TLS_MAX + 1 */
+/**
+ * Map @a know_gnutls_tls_ids values to printable names.
+ */
+extern const char *tls_names[KNOW_TLS_IDS_COUNT];
+
+/**
+ * Map @a know_gnutls_tls_ids values to GnuTLS priorities strings.
+ */
+extern const char *priorities_map[KNOW_TLS_IDS_COUNT];
+
+/**
+ * Map @a know_gnutls_tls_ids values to GnuTLS priorities append strings.
+ */
+extern const char *priorities_append_map[KNOW_TLS_IDS_COUNT];
+
+/**
+ * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value.
+ */
+extern const long libcurl_tls_vers_map[KNOW_TLS_IDS_COUNT];
+
+#if CURL_AT_LEAST_VERSION (7,54,0)
+/**
+ * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value
+ * for maximum supported TLS version.
+ */
+extern const long libcurl_tls_max_vers_map[KNOW_TLS_IDS_COUNT];
+#endif /* CURL_AT_LEAST_VERSION(7,54,0) */
+
 struct https_test_data
 {
   void *cls;
+  uint16_t port;
   const char *cipher_suite;
   int proto_version;
 };
@@ -62,80 +123,120 @@
   size_t size;
 };
 
-struct CipherDef
+int
+curl_tls_is_gnutls (void);
+
+int
+curl_tls_is_openssl (void);
+
+int
+curl_tls_is_nss (void);
+
+int
+curl_tls_is_schannel (void);
+
+int
+curl_tls_is_sectransport (void);
+
+
+enum test_get_result
 {
-  int options[2];
-  char *curlname;
+  TEST_GET_OK = 0,
+  TEST_GET_ERROR = 1,
+
+  TEST_GET_MHD_ERROR = 16,
+  TEST_GET_TRANSFER_ERROR = 17,
+
+  TEST_GET_CURL_GEN_ERROR = 32,
+  TEST_GET_CURL_CA_ERROR = 33,
+  TEST_GET_CURL_NOT_IMPLT = 34,
+
+  TEST_GET_HARD_ERROR = 999
 };
-
-
-int curl_check_version (const char *req_version, ...);
-int curl_uses_nss_ssl ();
-
-
-FILE *
-setup_ca_cert ();
-
 /**
  * perform cURL request for file
  */
-int
-test_daemon_get (void * cls,
-		 const char *cipher_suite, int proto_version,
-                 int port, int ver_peer);
+enum test_get_result
+test_daemon_get (void *cls,
+                 const char *cipher_suite, int proto_version,
+                 uint16_t port, int ver_peer);
 
-void print_test_result (int test_outcome, char *test_name);
+void
+print_test_result (unsigned int test_outcome,
+                   const char *test_name);
 
-size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx);
+size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx);
 
-int
+enum MHD_Result
 http_ahc (void *cls, struct MHD_Connection *connection,
           const char *url, const char *method, const char *upload_data,
-          const char *version, size_t *upload_data_size, void **ptr);
+          const char *version, size_t *upload_data_size, void **req_cls);
 
-int
+enum MHD_Result
 http_dummy_ahc (void *cls, struct MHD_Connection *connection,
                 const char *url, const char *method, const char *upload_data,
                 const char *version, size_t *upload_data_size,
-                void **ptr);
+                void **req_cls);
 
 
 /**
- * compile test file url pointing to the current running directory path
+ * compile test URI
  *
- * @param url - char buffer into which the url is compiled
+ * @param[out] uri - char buffer into which the url is compiled
+ * @param uri_len number of bytes available in @a url
  * @param port port to use for the test
- * @return -1 on error
+ * @return 1 on error
  */
-int gen_test_file_url (char *url, int port);
+unsigned int
+gen_test_uri (char *uri,
+              size_t uri_len,
+              uint16_t port);
 
-int
-send_curl_req (char *url, struct CBC *cbc, const char *cipher_suite,
+CURLcode
+send_curl_req (char *url,
+               struct CBC *cbc,
+               const char *cipher_suite,
                int proto_version);
 
-int
-test_https_transfer (void *cls, const char *cipher_suite, int proto_version);
+unsigned int
+test_https_transfer (void *cls,
+                     uint16_t port,
+                     const char *cipher_suite,
+                     int proto_version);
 
-int
-setup_testcase (struct MHD_Daemon **d, int daemon_flags, va_list arg_list);
+unsigned int
+setup_session (gnutls_session_t *session,
+               gnutls_certificate_credentials_t *xcred);
 
-void teardown_testcase (struct MHD_Daemon *d);
-
-int
-setup_session (gnutls_session_t * session,
-               gnutls_datum_t * key,
-               gnutls_datum_t * cert,
-               gnutls_certificate_credentials_t * xcred);
-
-int
+unsigned int
 teardown_session (gnutls_session_t session,
-                  gnutls_datum_t * key,
-                  gnutls_datum_t * cert,
                   gnutls_certificate_credentials_t xcred);
 
+unsigned int
+test_wrap (const char *test_name, unsigned int
+           (*test_function)(void *cls, uint16_t port, const char *cipher_suite,
+                            int proto_version), void *cls,
+           uint16_t port,
+           unsigned int daemon_flags, const char *cipher_suite,
+           int proto_version, ...);
+
+int testsuite_curl_global_init (void);
+
+/**
+ * Check whether program name contains specific @a marker string.
+ * Only last component in pathname is checked for marker presence,
+ * all leading directories names (if any) are ignored. Directories
+ * separators are handled correctly on both non-W32 and W32
+ * platforms.
+ * @param prog_name program name, may include path
+ * @param marker    marker to look for.
+ * @return zero if any parameter is NULL or empty string or
+ *         @prog_name ends with slash or @marker is not found in
+ *         program name, non-zero if @maker is found in program
+ *         name.
+ */
 int
-test_wrap (const char *test_name, int
-           (*test_function) (void * cls, const char *cipher_suite,
-                             int proto_version), void *test_function_cls,
-           int daemon_flags, const char *cipher_suite, int proto_version, ...);
+has_in_name (const char *prog_name, const char *marker);
+
 #endif /* TLS_TEST_COMMON_H_ */
diff --git a/src/testcurl/https/tls_test_keys.h b/src/testcurl/https/tls_test_keys.h
index b6e37ee..ccb7a33 100644
--- a/src/testcurl/https/tls_test_keys.h
+++ b/src/testcurl/https/tls_test_keys.h
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2006, 2007, 2008 Christian Grothoff (and other contributing authors)
+     Copyright (C) 2021-2022 Evgeny Grin (Karlson2k)
 
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
@@ -22,152 +23,161 @@
 
 /* Test Certificates */
 
-/* Certificate Authority key */
-const char ca_key_pem[] = "-----BEGIN RSA PRIVATE KEY-----\n"
-  "MIIEowIBAAKCAQEA0EdlP613rjFvEj93tGo9fzBoKWU3CW+AbbfcJ397C89MyZ9J\n"
-  "rlxyLGfa6qVX7CFVNmzgWWfcl2tHlw/fZmWtf/SFgrlkldvuGyY8H3n2HuMsWz/E\n"
-  "h7n5VgwBX8NsP4eZNmikepxpr1mYx25K8FjnsKjAR9jGUSV8UfZ7VLIY0x/yqe+3\n"
-  "32oqc4D/wJbV1AwwvC5Xf9rvHJwcZg57eqbDCL/4GDDk7d9Gark4XK6ZG+FnnxQn\n"
-  "4a4jIdf4FoPp9s0EieHrHwYzs/uBqmfCSF4wXiaO8bmEwtbAsVbZH74Le7ggUbEe\n"
-  "o+jan9XK0dE88AIImGzgoBnlic/Rr7J8OWA+iwIDAQABAoIBAEICZqXkUdpsw2F6\n"
-  "qPMOergNPO3lrKg6ZO8hBs6j2fj3tcPuzljK5sqJDboxNejZ9Zo+rmnXf3Oj5fgL\n"
-  "6UcYMYEsm4W/QRA3uEJ1fzeQnT7Ty9KNprlHaSzquCLEGlIWJSo3xu0vFlWjJUcL\n"
-  "fwemfaOhD/OVUeEU6s5FOngwy6pZUsOajs3fNRtwBGuuXjniKZZlpSf2Wqu3xpHZ\n"
-  "31OF1V0ycUCGPPFtpmUCtnZhS9L8QBTkNtfTIdXv6SfoBRFm0oXb0uL5HGft6yc7\n"
-  "eYRXIscllQciqG3ymJ/y9o0E3A0YsBVauQyi7OEk+Kg8uoYOBkZCIY69hoN2Znlk\n"
-  "OY5S5Z0CgYEA3j8pRAJzvc827KcX4vJf05HYD4aCyaI80fNmx1DgXfglTSGLQ361\n"
-  "6i05YW8WtIvgkma3wF+jJOckBCW/7iq8wAX7Kz75WKGRyyTEb0wSfjx0G8grxX4d\n"
-  "7sTIAAOnQj5WT6E/bkqxQZAYnVtIPxKtSlwts0H/bjPVYwSFchHK7t8CgYEA7+ks\n"
-  "C0EMjF8CDeCfvbOUGiiqAvU3G20LEC3WlJM3AU+J9Jzp6AMkgaIA8J5oNdsbFBn4\n"
-  "N12JPOO+7WRUk6Av8bsh4faE36ThnHohgAL8guRU7jIXvsFyO5yiY7/o/0lES0/V\n"
-  "6xkh/Epj4MReuCGkiD9ifCVAo+dhHskeE9qbYdUCgYA4yBpa7eV0UUTPIcHQkew5\n"
-  "ucFh9hPkQDcZzP4tXlR0rbmaAz/5dp4zvmoyopdCeZpezS+VTtn3y7Y/+QUYbILc\n"
-  "7KpHWkeKhX0iUbp+VQlEh12C25mTU62CG3SdzFEnc5XJsoDqRNsUzSP80B2dP8BW\n"
-  "h0aFzg7csRGLwtP1WOZoMQKBgQCrgsKd+Q8Dexh421DXyX3jhZalLrEKxlXWZy60\n"
-  "YNo98aLqYRNHbpe2pR6O5nARsGYXZMlyq0flY9um0sc0Epyz79g1NoufZrxzpUw1\n"
-  "u+zRlnKxJtaa5KjJvRzKuvPTLYnJXXXM8Na/Cl+E3F3qvQJm9QlvPyKLCmsAGz+J\n"
-  "agsTUQKBgC0wqqJ6b1tbrAD8AVeeAn/IiP1rxYpc3x2s6ikFO2FMHXHC9wgrRPOc\n"
-  "mkokV+DrUOv3I/7jG8wQA/FmBUPy562a1bObIKzg6CPXzrN68AmNnOIVU+H8fdxI\n"
-  "iGyfT8WNpcRmtN11v34qXHwOWGQhpyyk2yNa8VIBSpkShq/EseZ1\n"
-  "-----END RSA PRIVATE KEY-----\n";
-
 /* Certificate Authority cert */
-const char ca_cert_pem[] = "-----BEGIN CERTIFICATE-----\n"
-  "MIIC6DCCAdKgAwIBAgIES0KCvTALBgkqhkiG9w0BAQUwFzEVMBMGA1UEAxMMdGVz\n"
-  "dF9jYV9jZXJ0MB4XDTEwMDEwNTAwMDcyNVoXDTQ1MDMxMjAwMDcyNVowFzEVMBMG\n"
-  "A1UEAxMMdGVzdF9jYV9jZXJ0MIIBHzALBgkqhkiG9w0BAQEDggEOADCCAQkCggEA\n"
-  "0EdlP613rjFvEj93tGo9fzBoKWU3CW+AbbfcJ397C89MyZ9JrlxyLGfa6qVX7CFV\n"
-  "NmzgWWfcl2tHlw/fZmWtf/SFgrlkldvuGyY8H3n2HuMsWz/Eh7n5VgwBX8NsP4eZ\n"
-  "Nmikepxpr1mYx25K8FjnsKjAR9jGUSV8UfZ7VLIY0x/yqe+332oqc4D/wJbV1Aww\n"
-  "vC5Xf9rvHJwcZg57eqbDCL/4GDDk7d9Gark4XK6ZG+FnnxQn4a4jIdf4FoPp9s0E\n"
-  "ieHrHwYzs/uBqmfCSF4wXiaO8bmEwtbAsVbZH74Le7ggUbEeo+jan9XK0dE88AII\n"
-  "mGzgoBnlic/Rr7J8OWA+iwIDAQABo0MwQTAPBgNVHRMBAf8EBTADAQH/MA8GA1Ud\n"
-  "DwEB/wQFAwMHBAAwHQYDVR0OBBYEFP2olB4s2T/xuoQ5pT2RKojFwZo2MAsGCSqG\n"
-  "SIb3DQEBBQOCAQEAebD5m+vZkVXa8y+QZ5GtsiR9gpH+LKtdWBjk1kmfSgvQI/xA\n"
-  "aDCV/9BhdNGIBOTYGkln8urWd7g2Mj3TwKEAfNTUFpAsrBAlSSLTGYCSt72S2NsS\n"
-  "L/qUxmj1W6X95UHXCo49mSZx3LlaY3mz1L87gq/kK0XpzA3g2uF25jt84RvshsXy\n"
-  "clOc+eRrVETqFZqer96WB7kzFTv+qmROQKmW8X4a2A5r5Jl4vRwOz5/rEeB9Qs0K\n"
-  "rmK8+5HgvWd80WB8BtfFtZfoY/hHVM8nLD3ELVJrOKiTeIACunQFyT5lV0QkdmSA\n"
-  "CGInU7jzs8nu+s2avf6j+eVZUbVJ+dFMApTJgg==\n"
-  "-----END CERTIFICATE-----\n";
+static const char ca_cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n\
+MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3\n\
+MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM\n\
+Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN\n\
+AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G\n\
+CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36\n\
+ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI\n\
+IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/\n\
+B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6\n\
+6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP\n\
+t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw\n\
+Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN\n\
+x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH\n\
+QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH\n\
+KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR\n\
+bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR\n\
+q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG\n\
+AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK\n\
+BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB\n\
+MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA\n\
+A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1\n\
+kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay\n\
+ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj\n\
+ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9\n\
+9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD\n\
+TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl\n\
+WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s\n\
+E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/\n\
+nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM\n\
+Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg\n\
+4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA==\n\
+-----END CERTIFICATE-----";
+
+
+/* test server key */
+static const char srv_signed_key_pem[] =
+  "-----BEGIN PRIVATE KEY-----\n\
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\
+rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\
+UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\
++sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\
+HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\
+CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\
+dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\
++SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\
+XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\
+znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\
+pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\
+D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\
+Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\
+pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\
+zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\
+pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\
+KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\
+W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\
+OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\
+XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\
+wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\
+ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\
+0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\
+ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\
+QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\
+qdJNJ1DkyUc9dN2cliX4R+rG\n\
+-----END PRIVATE KEY-----";
 
 /* test server CA signed certificates */
-const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n"
-  "MIIDGzCCAgWgAwIBAgIES0KCvTALBgkqhkiG9w0BAQUwFzEVMBMGA1UEAxMMdGVz\n"
-  "dF9jYV9jZXJ0MB4XDTEwMDEwNTAwMDcyNVoXDTQ1MDMxMjAwMDcyNVowFzEVMBMG\n"
-  "A1UEAxMMdGVzdF9jYV9jZXJ0MIIBHzALBgkqhkiG9w0BAQEDggEOADCCAQkCggEA\n"
-  "vfTdv+3fgvVTKRnP/HVNG81cr8TrUP/iiyuve/THMzvFXhCW+K03KwEku55QvnUn\n"
-  "dwBfU/ROzLlv+5hotgiDRNFT3HxurmhouySBrJNJv7qWp8ILq4sw32vo0fbMu5BZ\n"
-  "F49bUXK9L3kW2PdhTtSQPWHEzNrCxO+YgCilKHkY3vQNfdJ020Q5EAAEseD1YtWC\n"
-  "IpRvJzYlZMpjYB1ubTl24kwrgOKUJYKqM4jmF4DVQp4oOK/6QYGGh1QmHRPAy3CB\n"
-  "II6sbb+sZT9cAqU6GYQVB35lm4XAgibXV6KgmpVxVQQ69U6xyoOl204xuekZOaG9\n"
-  "RUPId74Rtmwfi1TLbBzo2wIDAQABo3YwdDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQM\n"
-  "MAoGCCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHIAAwHQYDVR0OBBYEFOFi4ilKOP1d\n"
-  "XHlWCMwmVKr7mgy8MB8GA1UdIwQYMBaAFP2olB4s2T/xuoQ5pT2RKojFwZo2MAsG\n"
-  "CSqGSIb3DQEBBQOCAQEAHVWPxazupbOkG7Did+dY9z2z6RjTzYvurTtEKQgzM2Vz\n"
-  "GQBA+3pZ3c5mS97fPIs9hZXfnQeelMeZ2XP1a+9vp35bJjZBBhVH+pqxjCgiUflg\n"
-  "A3Zqy0XwwVCgQLE2HyaU3DLUD/aeIFK5gJaOSdNTXZLv43K8kl4cqDbMeRpVTbkt\n"
-  "YmG4AyEOYRNKGTqMEJXJoxD5E3rBUNrVI/XyTjYrulxbNPcMWEHKNeeqWpKDYTFo\n"
-  "Bb01PCthGXiq/4A2RLAFosadzRa8SBpoSjPPfZ0b2w4MJpReHqKbR5+T2t6hzml6\n"
-  "4ToyOKPDmamiTuN5KzLN3cw7DQlvWMvqSOChPLnA3Q==\n"
-  "-----END CERTIFICATE-----\n";
-
-/* test server key */
-const char srv_signed_key_pem[] = "-----BEGIN RSA PRIVATE KEY-----\n"
-  "MIIEowIBAAKCAQEAvfTdv+3fgvVTKRnP/HVNG81cr8TrUP/iiyuve/THMzvFXhCW\n"
-  "+K03KwEku55QvnUndwBfU/ROzLlv+5hotgiDRNFT3HxurmhouySBrJNJv7qWp8IL\n"
-  "q4sw32vo0fbMu5BZF49bUXK9L3kW2PdhTtSQPWHEzNrCxO+YgCilKHkY3vQNfdJ0\n"
-  "20Q5EAAEseD1YtWCIpRvJzYlZMpjYB1ubTl24kwrgOKUJYKqM4jmF4DVQp4oOK/6\n"
-  "QYGGh1QmHRPAy3CBII6sbb+sZT9cAqU6GYQVB35lm4XAgibXV6KgmpVxVQQ69U6x\n"
-  "yoOl204xuekZOaG9RUPId74Rtmwfi1TLbBzo2wIDAQABAoIBADu09WSICNq5cMe4\n"
-  "+NKCLlgAT1NiQpLls1gKRbDhKiHU9j8QWNvWWkJWrCya4QdUfLCfeddCMeiQmv3K\n"
-  "lJMvDs+5OjJSHFoOsGiuW2Ias7IjnIojaJalfBml6frhJ84G27IXmdz6gzOiTIer\n"
-  "DjeAgcwBaKH5WwIay2TxIaScl7AwHBauQkrLcyb4hTmZuQh6ArVIN6+pzoVuORXM\n"
-  "bpeNWl2l/HSN3VtUN6aCAKbN/X3o0GavCCMn5Fa85uJFsab4ss/uP+2PusU71+zP\n"
-  "sBm6p/2IbGvF5k3VPDA7X5YX61sukRjRBihY8xSnNYx1UcoOsX6AiPnbhifD8+xQ\n"
-  "Tlf8oJUCgYEA0BTfzqNpr9Wxw5/QXaSdw7S/0eP5a0C/nwURvmfSzuTD4equzbEN\n"
-  "d+dI/s2JMxrdj/I4uoAfUXRGaabevQIjFzC9uyE3LaOyR2zhuvAzX+vVcs6bSXeU\n"
-  "pKpCAcN+3Z3evMaX2f+z/nfSUAl2i4J2R+/LQAWJW4KwRky/m+cxpfUCgYEA6bN1\n"
-  "b73bMgM8wpNt6+fcmS+5n0iZihygQ2U2DEud8nZJL4Nrm1dwTnfZfJBnkGj6+0Q0\n"
-  "cOwj2KS0/wcEdJBP0jucU4v60VMhp75AQeHqidIde0bTViSRo3HWKXHBIFGYoU3T\n"
-  "LyPyKndbqsOObnsFXHn56Nwhr2HLf6nw4taGQY8CgYBoSW36FLCNbd6QGvLFXBGt\n"
-  "2lMhEM8az/K58kJ4WXSwOLtr6MD/WjNT2tkcy0puEJLm6BFCd6A6pLn9jaKou/92\n"
-  "SfltZjJPb3GUlp9zn5tAAeSSi7YMViBrfuFiHObij5LorefBXISLjuYbMwL03MgH\n"
-  "Ocl2JtA2ywMp2KFXs8GQWQKBgFyIVv5ogQrbZ0pvj31xr9HjqK6d01VxIi+tOmpB\n"
-  "4ocnOLEcaxX12BzprW55ytfOCVpF1jHD/imAhb3YrHXu0fwe6DXYXfZV4SSG2vB7\n"
-  "IB9z14KBN5qLHjNGFpMQXHSMek+b/ftTU0ZnPh9uEM5D3YqRLVd7GcdUhHvG8P8Q\n"
-  "C9aXAoGBAJtID6h8wOGMP0XYX5YYnhlC7dOLfk8UYrzlp3xhqVkzKthTQTj6wx9R\n"
-  "GtC4k7U1ki8oJsfcIlBNXd768fqDVWjYju5rzShMpo8OCTS6ipAblKjCxPPVhIpv\n"
-  "tWPlbSn1qj6wylstJ5/3Z+ZW5H4wIKp5jmLiioDhcP0L/Ex3Zx8O\n"
-  "-----END RSA PRIVATE KEY-----\n";
+static const char srv_signed_cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n\
+MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\
+DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\
+LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\
+ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\
+NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\
+TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\
+c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\
+psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\
+atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\
+7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\
+n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\
+qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\
+kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\
+AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\
+c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\
+8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\
+IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\
+Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\
+X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\
+aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\
+HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\
+hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\
+18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\
+UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\
+B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\
+SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\
+WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\
+OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\
+/w0gW9EVWzFhsFeGEssi\n\
+-----END CERTIFICATE-----";
 
 /* test server self signed certificates */
-const char srv_self_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n"
-  "MIIC+jCCAeSgAwIBAgIES0KCvTALBgkqhkiG9w0BAQUwFzEVMBMGA1UEAxMMdGVz\n"
-  "dF9jYV9jZXJ0MB4XDTEwMDEwNTAwMDcyNVoXDTQ1MDMxMjAwMDcyNVowFzEVMBMG\n"
-  "A1UEAxMMdGVzdF9jYV9jZXJ0MIIBHzALBgkqhkiG9w0BAQEDggEOADCCAQkCggEA\n"
-  "tDEagv3p9OUhUL55jMucxjNK9N5cuozhcnrwDfBSU6oVrqm5kPqO1I7Cggzw68Y5\n"
-  "jhTcBi4FXmYOZppm1R3MhSJ5JSi/67Q7X4J5rnJLXYGN27qjMpnoGQ/2xmsNG/is\n"
-  "i+h/2vbtPU+WP9SEJnTfPLLpZ7KqCAk7FUUzKsuLx3/SOKtdkrWxPKwYTgnDEN6D\n"
-  "JL7tEzCnG5DFc4mQ7YW9PaRdC3rS1T8PvQ3jB2BUnohM0cFvKRuiU35tU7h7CPbL\n"
-  "4L66VglXoiwqmgcrwI2U968bD0+wRQ5c5bzNoshJOzN6CTMh1IhbklSh/Z6FA/e8\n"
-  "hj0yVo2tdllXuJGVs3PIEwIDAQABo1UwUzAMBgNVHRMBAf8EAjAAMBMGA1UdJQQM\n"
-  "MAoGCCsGAQUFBwMBMA8GA1UdDwEB/wQFAwMHIAAwHQYDVR0OBBYEFDfU7pAv9LYn\n"
-  "n7jb4WHl4+Vgi2FnMAsGCSqGSIb3DQEBBQOCAQEAkaembPQMmv6OOjbIod8zTatr\n"
-  "x5Bwkwp3TOE1NRyy2OytzFIYRUkNrZYlcmrxcbNNycIK41CNVXbriFCF8gcmIq9y\n"
-  "vaKZn8Gcy+vGggv+1BP9IAPBGKRwSi0wmq9JoGE8hx+qqTpRSdfbM/cps/09hicO\n"
-  "0EIR7kWEbvnpMBcMKYOtYE9Gce7rdSMWVAsKc174xn8vW6TxCUvmWFv5DPg5HG1v\n"
-  "y1SUX73qafRo+W6FN4UC/DHfwRhF8RSKEnVbmgDVCs6GHdKBjU2qRgYyj6nWZqK1\n"
-  "XFUTWgia+Fl3D9vlsXaFcSZKA0Bq1eojl0B0AfeYAxTFwPWXscKvt/bXZfH8bg==\n"
+static const char srv_self_signed_cert_pem[] =
+  "-----BEGIN CERTIFICATE-----\n"
+  "MIIDJzCCAg+gAwIBAgIUOKf6e6Heee2XA+yF5St3t+fVM40wDQYJKoZIhvcNAQEF\n"
+  "BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIyMTAxMDA4MzQ0N1oYDzIxMjIw\n"
+  "OTE2MDgzNDQ3WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB\n"
+  "AQUAA4IBDwAwggEKAoIBAQClivgF8Xq0ekQli++0l7Q5JFwJCuLf04Cb1UKIS80U\n"
+  "CfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz53vOwVNyiZ+sMGi4bDX4AV9Xd+F83\n"
+  "xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtvqrRRBen30iKOwX7uNF/4dYb9vdin\n"
+  "OldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VMFZM2hwmHyiiw75/j4BhUlLCcMEvK\n"
+  "oN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1SzAltxF2gmI0jzw8r/duz18QXMNsMw\n"
+  "El/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7yg649wHTAgMBAAGjbzBtMB0GA1Ud\n"
+  "DgQWBBROVferD+YYcV1YEnFgC0jYm5X9BjAfBgNVHSMEGDAWgBROVferD+YYcV1Y\n"
+  "EnFgC0jYm5X9BjAPBgNVHRMBAf8EBTADAQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9z\n"
+  "dIcEfwAAATANBgkqhkiG9w0BAQUFAAOCAQEAoRbozsm5xXdNX3VO++s2LMzw5KM9\n"
+  "RpIInHNkMJbnyLJFKJ8DF7nTxSGCA38YMkX3tphPNKZXbg+V64Dqr/XpzOVyiinU\n"
+  "7hIwyUdSSKKyErZxIWR97lY6Q3SOyPAg8ZElbtvSsSzmd772VE23VTXGDi7AW0PQ\n"
+  "hag9N2EEnHURMvID15O+UXyFpDdyUyQIbx3HuswsGDH9xBTm4irLyrZwO0KwKg5a\n"
+  "JBeUiPs0SYRRfn9/MoE6VwAnmOCg3LLR6ZPU3hQtTPLHj2Op1g5fey3X3X6lC+JC\n"
+  "K6dNZc1zBFPz8KANGUsFYbmoP2bvAAA+6KwCnZZEflUgE7/HFEmQhVOezw==\n"
   "-----END CERTIFICATE-----\n";
 
 /* test server key */
-const char srv_key_pem[] = "-----BEGIN RSA PRIVATE KEY-----\n"
-  "MIIEpAIBAAKCAQEAtDEagv3p9OUhUL55jMucxjNK9N5cuozhcnrwDfBSU6oVrqm5\n"
-  "kPqO1I7Cggzw68Y5jhTcBi4FXmYOZppm1R3MhSJ5JSi/67Q7X4J5rnJLXYGN27qj\n"
-  "MpnoGQ/2xmsNG/isi+h/2vbtPU+WP9SEJnTfPLLpZ7KqCAk7FUUzKsuLx3/SOKtd\n"
-  "krWxPKwYTgnDEN6DJL7tEzCnG5DFc4mQ7YW9PaRdC3rS1T8PvQ3jB2BUnohM0cFv\n"
-  "KRuiU35tU7h7CPbL4L66VglXoiwqmgcrwI2U968bD0+wRQ5c5bzNoshJOzN6CTMh\n"
-  "1IhbklSh/Z6FA/e8hj0yVo2tdllXuJGVs3PIEwIDAQABAoIBAAEtcg+LFLGtoxjq\n"
-  "b+tFttBJfbRcfdG6ocYqBGmUXF+MgFs573DHX3sHNOQxlaNHtSgIclF1eYgNZFFt\n"
-  "VLIoBFTzfEQXoFosPUDoEuqVMeXLttmD7P2jwL780XJLZ4Xj6GY07npq1iGBcEZf\n"
-  "yCcdoyGkr9jgc5Auyis8DStGg/jfUBC4NBvF0GnuuNPAdYRPKUpKw9EatI+FdMjy\n"
-  "BuroD90fhdkK8EwMEVb9P17bdIc1MCIZFpUE9YHjVdK/oxCUhQ8KRfdbI4JU5Zh3\n"
-  "UtO6Jm2wFuP3VmeVpPvE/C2rxI70pyl6HMSiFGNc0rhJYCQ+yhohWj7nZ67H4vLx\n"
-  "plv5LxkCgYEAz7ewou8oFafDAMNoxaqKudvUg+lxXewdLDKaYBF5ACi9uAPCJ+v7\n"
-  "M5c/fvPFn/XHzo7xaXbtTAH3Z5xzBs+80OsvL+e1Ut4xR+ELRkybknh/s2wQeABk\n"
-  "Kb0vA59ukQGj12LV5phZMaVoXe6KJ7hZnN62d3K6m1wGE/k58i4pPLUCgYEA3hN8\n"
-  "G95zW7g0jVdSr+KUeVmephph9yh8Yb+3I3ojwOIv6d45TopGx8pFZlnBAMZf1ZQx\n"
-  "DIhzJNnaqZy/4w7RNaOGWnPA/5f+MIoHBiLGEEmfHC3lt087Yp9OuwDUHwpETYdV\n"
-  "o+KBCvVh60Et3bZUgF/1k/3YXxn8J5dsmJsjNqcCgYBLflyRa1BrRnTGMz9CEDCp\n"
-  "Si9b3h1Y4Hbd2GppHhCXMTd6yMrpDYhYANGQB3M9Juv+s88j4JhwNoq/uonH4Pqk\n"
-  "B8Y3qAQr4RuSH0WkwDUOsALhqBX4N1QwI1USAQEDbNAqeP5698X7GD3tXcQSmZrg\n"
-  "O8WfdjBCRNjkq4EW9xX/vQKBgQDONtmwJ0iHiu2BseyeVo/4fzfKlgUSNQ4K1rOA\n"
-  "xhIdMeu8Bxa/z7caHsGC4SVPSuYCtbE2Kh6BwapChcPJXCD45fgEViiJLuJiwEj1\n"
-  "caTpyvNsf1IoffJvCe9ZxtMyX549P8ZOgC3Dt0hN5CBrGLwu2Ox5l+YrqT10pi+5\n"
-  "JZX1UQKBgQCrcXrdkkDAc/a4+PxNRpJRLcU4fhv8/lr+UWItE8eUe7bd25bTQfQm\n"
-  "VpNKc/kAJ66PjIED6fy3ADhd2y4naT2a24uAgQ/M494J68qLnGh6K4JU/09uxR2v\n"
-  "1i2q/4FNLdFFk1XP4iNnTHRLZ+NYr2p5Y9RcvQfTjOauz8Ahav0lyg==\n"
-  "-----END RSA PRIVATE KEY-----\n";
+static const char srv_self_signed_key_pem[] =
+  "-----BEGIN PRIVATE KEY-----\n"
+  "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClivgF8Xq0ekQl\n"
+  "i++0l7Q5JFwJCuLf04Cb1UKIS80UCfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz5\n"
+  "3vOwVNyiZ+sMGi4bDX4AV9Xd+F83xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtv\n"
+  "qrRRBen30iKOwX7uNF/4dYb9vdinOldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VM\n"
+  "FZM2hwmHyiiw75/j4BhUlLCcMEvKoN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1Sz\n"
+  "AltxF2gmI0jzw8r/duz18QXMNsMwEl/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7\n"
+  "yg649wHTAgMBAAECggEAERbbCtYGakoy7cNX8Ac3Kiz4OVC/4gZWAQBPeX2FwrtS\n"
+  "9yHIMbK0x1mxIZ6eBpabBpZlW2vDCSOKuxLKiloAWt2qdJnhR5apesSWhe8leT7/\n"
+  "xq5dgZpAlMH6SIRKObknd2yY+qicW0A0licDrVeUcypkueL8xP9wJtiPInOuQXkI\n"
+  "QROhB13eStRuRKYwOn5gtwAHJ+J1DFKKiqpBOkrSYf4625StGegJO9+bjK0ei+0W\n"
+  "tp6unpiwA/lXTgz6Xim1Z3fzWs4XjFgVKzK5s/6yBJjr8spHX6lv7QsahP4w6HZ/\n"
+  "VcRxP6cJNd/otiTEtJXpbxiiyccwXm/AOcOn22P1cQKBgQDAnY/0G/ap/G98pneE\n"
+  "suzNXhWOQ8JoL8d66Io8vwTvfiJggfgUcwblI7pPCrSlaZMR7/q6JImE53lZtPk8\n"
+  "eI3c9lN0ocr8E7+huDpYdk7cMYj9SuxySsXoMLiMqzHFi+NcIhKMF56kk6a5CFCt\n"
+  "yP1Ofy76LVweGE3XvTwpwE7wUQKBgQDcBLyH1cC71s0I0Gz28AyELV9hPhasjAKO\n"
+  "12CVbeBVTPd+28uk/3o80wSrTksc6H5ehAA2aTvrb4OhwssWNL+D0fS8YK2cJ3V0\n"
+  "FJxGAM266+vC4d/8jRTHJnc+6PP3ix5t6vAt+K2Y0fePtefLqf4ebgXx/ODAj3J2\n"
+  "aZKBldjK4wKBgGIRFpTLk/eR/dUyEBHw4x3gdAsdtqJDCUYrlQ4+ly20Q55tLbiD\n"
+  "pBQP77CEm9rH+MgeLcKODbIsBB3HRUojet7wTydHpMhY6a1V1ebqPVZgpgWIGwBJ\n"
+  "z59bBusf0lRo15Y2Bslq0SurvSvh7um8NjO8D1fytj7gUumvgC0lq0sxAoGBAI1+\n"
+  "kkx9IBTtIDER8XGhkTsT/uoHxwcyh5abVmbjIclZ1TUFX2L+Vft17ePJVy8BKfvY\n"
+  "wlY7uShBMBNAteDTDXNV/CGFv0DUc4myk4nFjIkwng9XufeuN3WX/Eo+AF/rXSdt\n"
+  "VwcJjYLhTWdjoe1tppqlQTeN3HCaEA+s92ZVGvXnAoGAMCXGS6WZl1e5wsHRq0Yy\n"
+  "8Ef2Wrk620bBjKHolkTfvgfhlvxeZM1sv1ioZGsOeQ0z7O7wdJhvL0M/WAG+3yQj\n"
+  "HSXp81T1vOICPwNYZf8xcvbLKmvj7rHFt6ZAZF2o4EK8ReZTRyA3DUpBCDY+s3FN\n"
+  "GmBv0D7N3QP0CT3SzfQrPkc=\n"
+  "-----END PRIVATE KEY-----\n";
 
 #endif
diff --git a/src/testcurl/mhd_has_in_name.h b/src/testcurl/mhd_has_in_name.h
new file mode 100644
index 0000000..3be50b8
--- /dev/null
+++ b/src/testcurl/mhd_has_in_name.h
@@ -0,0 +1,65 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016-2021 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file testcurl/mhd_has_in_name.h
+ * @brief Static functions and macros helpers for testsuite.
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include <string.h>
+
+/**
+ * Check whether program name contains specific @a marker string.
+ * Only last component in pathname is checked for marker presence,
+ * all leading directories names (if any) are ignored. Directories
+ * separators are handled correctly on both non-W32 and W32
+ * platforms.
+ * @param prog_name program name, may include path
+ * @param marker    marker to look for.
+ * @return zero if any parameter is NULL or empty string or
+ *         @prog_name ends with slash or @marker is not found in
+ *         program name, non-zero if @maker is found in program
+ *         name.
+ */
+static int
+has_in_name (const char *prog_name, const char *marker)
+{
+  size_t name_pos;
+  size_t pos;
+
+  if (! prog_name || ! marker || ! prog_name[0] || ! marker[0])
+    return 0;
+
+  pos = 0;
+  name_pos = 0;
+  while (prog_name[pos])
+  {
+    if ('/' == prog_name[pos])
+      name_pos = pos + 1;
+#if defined(_WIN32) || defined(__CYGWIN__)
+    else if ('\\' == prog_name[pos])
+      name_pos = pos + 1;
+#endif /* _WIN32 || __CYGWIN__ */
+    pos++;
+  }
+  if (name_pos == pos)
+    return 0;
+  return strstr (prog_name + name_pos, marker) != (char *) 0;
+}
diff --git a/src/testcurl/mhd_has_param.h b/src/testcurl/mhd_has_param.h
new file mode 100644
index 0000000..0186b5d
--- /dev/null
+++ b/src/testcurl/mhd_has_param.h
@@ -0,0 +1,53 @@
+/*
+  This file is part of libmicrohttpd
+  Copyright (C) 2016-2022 Karlson2k (Evgeny Grin)
+
+  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 2.1 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, write to the Free Software
+  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+/**
+ * @file testcurl/mhd_has_param.h
+ * @brief Static functions and macros helpers for testsuite.
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include <string.h>
+
+
+/**
+ * Check whether one of strings in array is equal to @a param.
+ * String @a argv[0] is ignored.
+ * @param argc number of strings in @a argv, as passed to main function
+ * @param argv array of strings, as passed to main function
+ * @param param parameter to look for.
+ * @return zero if @a argv is NULL, @a param is NULL or empty string,
+ *         @a argc is less then 2 or @a param is not found in @a argv,
+ *         non-zero if one of strings in @a argv is equal to @a param.
+ */
+static int
+has_param (int argc, char *const argv[], const char *param)
+{
+  int i;
+  if (! argv || ! param || ! param[0])
+    return 0;
+
+  for (i = 1; i < argc; i++)
+  {
+    if (argv[i] && (strcmp (argv[i], param) == 0) )
+      return ! 0;
+  }
+
+  return 0;
+}
diff --git a/src/testcurl/perf_get.c b/src/testcurl/perf_get.c
index 1e42f7d..ba60549 100644
--- a/src/testcurl/perf_get.c
+++ b/src/testcurl/perf_get.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,8 +15,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -28,12 +29,13 @@
  *        so the performance scores calculated with this code
  *        should NOT be used to compare with other HTTP servers
  *        (since MHD is actually better); only the relative
- *        scores between MHD versions are meaningful.  
+ *        scores between MHD versions are meaningful.
  *        Furthermore, this code ONLY tests MHD processing
  *        a single request at a time.  This is again
  *        not universally meaningful (i.e. when comparing
  *        multithreaded vs. single-threaded or select/poll).
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -43,25 +45,33 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#include "gauger.h"
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
 #include <sys/socket.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 /**
  * How many rounds of operations do we do for each
  * test?
  */
+#if MHD_CPU_COUNT > 8
+#ifndef _WIN32
+#define ROUNDS (1 + (30000 / 12) / MHD_CPU_COUNT)
+#else /* _WIN32 */
+#define ROUNDS (1 + (3000 / 12) / MHD_CPU_COUNT)
+#endif /* _WIN32 */
+#else
 #define ROUNDS 500
+#endif
 
 /**
  * Do we use HTTP 1.1?
@@ -80,26 +90,26 @@
 
 
 /**
- * Get the current timestamp 
+ * Get the current timestamp
  *
  * @return current time in ms
  */
-static unsigned long long 
-now ()
+static unsigned long long
+now (void)
 {
   struct timeval tv;
 
   gettimeofday (&tv, NULL);
-  return (((unsigned long long) tv.tv_sec * 1000LL) +
-	  ((unsigned long long) tv.tv_usec / 1000LL));
+  return (((unsigned long long) tv.tv_sec * 1000LL)
+          + ((unsigned long long) tv.tv_usec / 1000LL));
 }
 
 
 /**
  * Start the timer.
  */
-static void 
-start_timer()
+static void
+start_timer (void)
 {
   start_time = now ();
 }
@@ -110,20 +120,16 @@
  *
  * @param desc description of the threading mode we used
  */
-static void 
+static void
 stop (const char *desc)
 {
-  double rps = ((double) (ROUNDS * 1000)) / ((double) (now() - start_time));
+  double rps = ((double) (ROUNDS * 1000)) / ((double) (now () - start_time));
 
   fprintf (stderr,
-	   "Sequential GETs using %s: %f %s\n",
-	   desc,
-	   rps,
-	   "requests/s");
-  GAUGER (desc,
-	  "Sequential GETs",
-	  rps,
-	  "requests/s");
+           "Sequential GETs using %s: %f %s\n",
+           desc,
+           rps,
+           "requests/s");
 }
 
 
@@ -136,9 +142,9 @@
 
 
 static size_t
-copyBuffer (void *ptr, 
-	    size_t size, size_t nmemb, 
-	    void *ctx)
+copyBuffer (void *ptr,
+            size_t size, size_t nmemb,
+            void *ctx)
 {
   struct CBC *cbc = ctx;
 
@@ -149,27 +155,30 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   if (ret == MHD_NO)
     abort ();
@@ -177,8 +186,8 @@
 }
 
 
-static int
-testInternalGet (int port, int poll_flag)
+static unsigned int
+testInternalGet (uint16_t port, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -188,46 +197,64 @@
   unsigned int i;
   char url[64];
 
-  sprintf(url, "http://127.0.0.1:%d/hello_world", port);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
 
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG  | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
-  start_timer ();
-  for (i=0;i<ROUNDS;i++)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      cbc.pos = 0;
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      if (oneone)
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      /* NOTE: use of CONNECTTIMEOUT without also
-	 setting NOSIGNAL results in really weird
-	 crashes on my system!*/
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-	{
-	  fprintf (stderr,
-		   "curl_easy_perform failed: `%s'\n",
-		   curl_easy_strerror (errornum));
-	  curl_easy_cleanup (c);
-	  MHD_stop_daemon (d);
-	  return 2;
-	}
-      curl_easy_cleanup (c);
+      MHD_stop_daemon (d); return 32;
     }
-  stop (poll_flag == MHD_USE_POLL ? "internal poll" :
-	poll_flag == MHD_USE_EPOLL_LINUX_ONLY ? "internal epoll" : "internal select");
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
+  start_timer ();
+  for (i = 0; i < ROUNDS; i++)
+  {
+    cbc.pos = 0;
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    /* NOTE: use of CONNECTTIMEOUT without also
+ setting NOSIGNAL results in really weird
+ crashes on my system!*/
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 2;
+    }
+    curl_easy_cleanup (c);
+  }
+  stop (poll_flag == MHD_USE_AUTO ? "internal thread with 'auto'" :
+        poll_flag == MHD_USE_POLL ? "internal thread with poll()" :
+        poll_flag == MHD_USE_EPOLL ? "internal thread with epoll" :
+        "internal thread with select()");
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 4;
@@ -237,8 +264,8 @@
 }
 
 
-static int
-testMultithreadedGet (int port, int poll_flag)
+static unsigned int
+testMultithreadedGet (uint16_t port, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -248,46 +275,68 @@
   unsigned int i;
   char url[64];
 
-  sprintf(url, "http://127.0.0.1:%d/hello_world", port);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
 
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG  | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 16;
-  start_timer ();
-  for (i=0;i<ROUNDS;i++)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      cbc.pos = 0;
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      /* NOTE: use of CONNECTTIMEOUT without also
-	 setting NOSIGNAL results in really weird
-	 crashes on my system! */
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-	{
-	  fprintf (stderr,
-		   "curl_easy_perform failed: `%s'\n",
-		   curl_easy_strerror (errornum));
-	  curl_easy_cleanup (c);
-	  MHD_stop_daemon (d);
-	  return 32;
-	}
-      curl_easy_cleanup (c);
+      MHD_stop_daemon (d); return 32;
     }
-  stop ((poll_flag & MHD_USE_POLL) ? "thread with poll" :
-	(poll_flag & MHD_USE_EPOLL_LINUX_ONLY) ? "thread with epoll" : "thread with select");
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
+  start_timer ();
+  for (i = 0; i < ROUNDS; i++)
+  {
+    cbc.pos = 0;
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+ setting NOSIGNAL results in really weird
+ crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 32;
+    }
+    curl_easy_cleanup (c);
+  }
+  stop ((poll_flag & MHD_USE_AUTO) ?
+        "internal thread with 'auto' and thread per connection" :
+        (poll_flag & MHD_USE_POLL) ?
+        "internal thread with poll() and thread per connection" :
+        (poll_flag & MHD_USE_EPOLL) ?
+        "internal thread with epoll and thread per connection" :
+        "internal thread with select() and thread per connection");
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 64;
@@ -296,8 +345,9 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolGet (int port, int poll_flag)
+
+static unsigned int
+testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -307,47 +357,66 @@
   unsigned int i;
   char url[64];
 
-  sprintf(url, "http://127.0.0.1:%d/hello_world", port);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
 
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
-  start_timer ();
-  for (i=0;i<ROUNDS;i++)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      cbc.pos = 0;
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      /* NOTE: use of CONNECTTIMEOUT without also
-	 setting NOSIGNAL results in really weird
-	 crashes on my system!*/
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-	{
-	  fprintf (stderr,
-		   "curl_easy_perform failed: `%s'\n",
-		   curl_easy_strerror (errornum));
-	  curl_easy_cleanup (c);
-	  MHD_stop_daemon (d);
-	  return 32;
-	}
-      curl_easy_cleanup (c);
+      MHD_stop_daemon (d); return 32;
     }
-  stop (0 != (poll_flag & MHD_USE_POLL) ? "thread pool with poll" : 
-	0 != (poll_flag & MHD_USE_EPOLL_LINUX_ONLY) ? "thread pool with epoll" : "thread pool with select");
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
+  start_timer ();
+  for (i = 0; i < ROUNDS; i++)
+  {
+    cbc.pos = 0;
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+ setting NOSIGNAL results in really weird
+ crashes on my system!*/
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 32;
+    }
+    curl_easy_cleanup (c);
+  }
+  stop (0 != (poll_flag & MHD_USE_AUTO) ? "internal thread pool with 'auto'" :
+        0 != (poll_flag & MHD_USE_POLL) ? "internal thread pool with poll()" :
+        0 != (poll_flag & MHD_USE_EPOLL) ? "internal thread pool with epoll" :
+        "internal thread pool with select()");
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 64;
@@ -356,8 +425,9 @@
   return 0;
 }
 
-static int
-testExternalGet (int port)
+
+static unsigned int
+testExternalGet (uint16_t port)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -368,7 +438,12 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
@@ -376,117 +451,170 @@
   unsigned int i;
   char url[64];
 
-  sprintf(url, "http://127.0.0.1:%d/hello_world", port);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
-  if (d == NULL)
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
+  if (NULL == d)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
   start_timer ();
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
-  for (i=0;i<ROUNDS;i++)
-    {
-      cbc.pos = 0;
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      if (oneone)
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-	curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      /* NOTE: use of CONNECTTIMEOUT without also
-	 setting NOSIGNAL results in really weird
-	 crashes on my system! */
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-	{
-	  curl_multi_cleanup (multi);
-	  curl_easy_cleanup (c);
-	  MHD_stop_daemon (d);
-	  return 1024;
-	}
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-	{
-	  max = 0;
-	  FD_ZERO (&rs);
-	  FD_ZERO (&ws);
-	  FD_ZERO (&es);
-	  curl_multi_perform (multi, &running);
-	  mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-	  if (mret != CURLM_OK)
-	    {
-	      curl_multi_remove_handle (multi, c);
-	      curl_multi_cleanup (multi);
-	      curl_easy_cleanup (c);
-	      MHD_stop_daemon (d);
-	      return 2048;
-	    }
-	  if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-	    {
-	      curl_multi_remove_handle (multi, c);
-	      curl_multi_cleanup (multi);
-	      curl_easy_cleanup (c);
-	      MHD_stop_daemon (d);
-	      return 4096;
-	    }
-	  tv.tv_sec = 0;
-	  tv.tv_usec = 1000;
-	  select (max + 1, &rs, &ws, &es, &tv);
-	  curl_multi_perform (multi, &running);
-	  if (running == 0)
-	    {
-	      msg = curl_multi_info_read (multi, &running);
-	      if (msg == NULL)
-		break;
-	      if (msg->msg == CURLMSG_DONE)
-		{
-		  if (msg->data.result != CURLE_OK)
-		    printf ("%s failed at %s:%d: `%s'\n",
-			    "curl_multi_perform",
-			    __FILE__,
-			    __LINE__, curl_easy_strerror (msg->data.result));
-		  curl_multi_remove_handle (multi, c);
-		  curl_easy_cleanup (c);
-		  c = NULL;
-		}
-	    }
-	  /* two possibilities here; as select sets are
-	     tiny, this makes virtually no difference
-	     in actual runtime right now, even though the
-	     number of select calls is virtually cut in half
-	     (and 'select' is the most expensive of our system
-	     calls according to 'strace') */
-	  if (0)
-	    MHD_run (d);
-	  else
-	    MHD_run_from_select (d, &rs, &ws, &es);
-	}
-      if (NULL != c)
-	{
-	  curl_multi_remove_handle (multi, c);
-	  curl_easy_cleanup (c);
-	  fprintf (stderr, "Timeout!?\n");
-	}
-    }
-  stop ("external select");
-  if (multi != NULL)
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
+  for (i = 0; i < ROUNDS; i++)
+  {
+    cbc.pos = 0;
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+ setting NOSIGNAL results in really weird
+ crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      maxsock = MHD_INVALID_SOCKET;
+      maxposixs = -1;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+      {
+  #ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+        {
+          fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                   (int) errno, __LINE__);
+          fflush (stderr);
+          exit (99);
+        }
+  #else
+        if ((WSAEINVAL != WSAGetLastError ()) ||
+            (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        {
+          fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                   (int) WSAGetLastError (), __LINE__);
+          fflush (stderr);
+          exit (99);
+        }
+        Sleep (1);
+  #endif
+      }
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        int pending;
+        int curl_fine = 0;
+        while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+        {
+          if (msg->msg == CURLMSG_DONE)
+          {
+            if (msg->data.result == CURLE_OK)
+              curl_fine = 1;
+            else
+            {
+              fprintf (stderr,
+                       "%s failed at %s:%d: `%s'\n",
+                       "curl_multi_perform",
+                       __FILE__,
+                       __LINE__, curl_easy_strerror (msg->data.result));
+              abort ();
+            }
+          }
+        }
+        if (! curl_fine)
+        {
+          fprintf (stderr, "libcurl haven't returned OK code\n");
+          abort ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+        break;
+      }
+      /* two possibilities here; as select sets are
+         tiny, this makes virtually no difference
+         in actual runtime right now, even though the
+         number of select calls is virtually cut in half
+         (and 'select' is the most expensive of our system
+         calls according to 'strace') */
+      if (0)
+        MHD_run (d);
+      else
+        MHD_run_from_select (d, &rs, &ws, &es);
+    }
+    if (NULL != c)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+      fprintf (stderr, "Timeout!?\n");
+    }
+  }
+  stop ("external select");
+  if (multi != NULL)
+  {
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -500,30 +628,39 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
-  int port = 1081;
+  uint16_t port = 1130;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (oneone)
+    port += 15;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  response = MHD_create_response_from_buffer (strlen ("/hello_world"),
-					      "/hello_world",
-					      MHD_RESPMEM_MUST_COPY);
+  response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"),
+                                                   "/hello_world");
   errorCount += testExternalGet (port++);
-  errorCount += testInternalGet (port++, 0);
-  errorCount += testMultithreadedGet (port++, 0);
-  errorCount += testMultithreadedPoolGet (port++, 0);
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_POLL))
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet (port++, MHD_USE_AUTO);
+    errorCount += testMultithreadedGet (port++, MHD_USE_AUTO);
+    errorCount += testMultithreadedPoolGet (port++, MHD_USE_AUTO);
+    errorCount += testInternalGet (port++, 0);
+    errorCount += testMultithreadedGet (port++, 0);
+    errorCount += testMultithreadedPoolGet (port++, 0);
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
     {
-      errorCount += testInternalGet(port++, MHD_USE_POLL);
-      errorCount += testMultithreadedGet(port++, MHD_USE_POLL);
-      errorCount += testMultithreadedPoolGet(port++, MHD_USE_POLL);
+      errorCount += testInternalGet (port++, MHD_USE_POLL);
+      errorCount += testMultithreadedGet (port++, MHD_USE_POLL);
+      errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL);
     }
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_EPOLL))
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
     {
-      errorCount += testInternalGet(port++, MHD_USE_EPOLL_LINUX_ONLY);
-      errorCount += testMultithreadedPoolGet(port++, MHD_USE_EPOLL_LINUX_ONLY);
+      errorCount += testInternalGet (port++, MHD_USE_EPOLL);
+      errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL);
     }
+  }
   MHD_destroy_response (response);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
diff --git a/src/testcurl/perf_get_concurrent.c b/src/testcurl/perf_get_concurrent.c
index 28559ee..3ba0b1b 100644
--- a/src/testcurl/perf_get_concurrent.c
+++ b/src/testcurl/perf_get_concurrent.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,8 +15,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -28,8 +29,9 @@
  *        so the performance scores calculated with this code
  *        should NOT be used to compare with other HTTP servers
  *        (since MHD is actually better); only the relative
- *        scores between MHD versions are meaningful.  
+ *        scores between MHD versions are meaningful.
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -39,25 +41,35 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#include "gauger.h"
+#include <pthread.h>
+#include "mhd_has_in_name.h"
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 /**
  * How many rounds of operations do we do for each
  * test (total number of requests will be ROUNDS * PAR).
+ * Ensure that free ports are not exhausted during test.
  */
+#if MHD_CPU_COUNT > 8
+#ifndef _WIN32
+#define ROUNDS (1 + (30000 / 12) / MHD_CPU_COUNT)
+#else /* _WIN32 */
+#define ROUNDS (1 + (3000 / 12) / MHD_CPU_COUNT)
+#endif /* _WIN32 */
+#else
 #define ROUNDS 500
+#endif
 
 /**
  * How many requests do we do in parallel?
  */
-#define PAR CPU_COUNT
+#define PAR MHD_CPU_COUNT
 
 /**
  * Do we use HTTP 1.1?
@@ -74,28 +86,33 @@
  */
 static unsigned long long start_time;
 
+/**
+ * Set to 1 if the worker threads are done.
+ */
+static volatile int signal_done;
+
 
 /**
- * Get the current timestamp 
+ * Get the current timestamp
  *
  * @return current time in ms
  */
-static unsigned long long 
-now ()
+static unsigned long long
+now (void)
 {
   struct timeval tv;
 
   gettimeofday (&tv, NULL);
-  return (((unsigned long long) tv.tv_sec * 1000LL) +
-	  ((unsigned long long) tv.tv_usec / 1000LL));
+  return (((unsigned long long) tv.tv_sec * 1000LL)
+          + ((unsigned long long) tv.tv_usec / 1000LL));
 }
 
 
 /**
  * Start the timer.
  */
-static void 
-start_timer()
+static void
+start_timer (void)
 {
   start_time = now ();
 }
@@ -106,52 +123,53 @@
  *
  * @param desc description of the threading mode we used
  */
-static void 
+static void
 stop (const char *desc)
 {
-  double rps = ((double) (PAR * ROUNDS * 1000)) / ((double) (now() - start_time));
+  double rps = ((double) (PAR * ROUNDS * 1000)) / ((double) (now ()
+                                                             - start_time));
 
   fprintf (stderr,
-	   "Parallel GETs using %s: %f %s\n",
-	   desc,
-	   rps,
-	   "requests/s");
-  GAUGER (desc,
-	  "Parallel GETs",
-	  rps,
-	  "requests/s");
+           "Parallel GETs using %s: %f %s\n",
+           desc,
+           rps,
+           "requests/s");
 }
 
 
 static size_t
-copyBuffer (void *ptr, 
-	    size_t size, size_t nmemb, 
-	    void *ctx)
+copyBuffer (void *ptr,
+            size_t size, size_t nmemb,
+            void *ctx)
 {
+  (void) ptr; (void) ctx;          /* Unused. Silent compiler warning. */
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   if (ret == MHD_NO)
     abort ();
@@ -159,173 +177,328 @@
 }
 
 
-static pid_t
-do_gets (int port)
+static void *
+thread_gets (void *param)
 {
-  pid_t ret;
   CURL *c;
   CURLcode errornum;
   unsigned int i;
-  unsigned int j;
-  pid_t par[PAR];
-  char url[64];
+  char *const url = (char *) param;
+  static char curl_err_marker[] = "curl error";
 
-  sprintf(url, "http://127.0.0.1:%d/hello_world", port);
-  
-  ret = fork ();
-  if (ret == -1) abort ();
-  if (ret != 0)
-    return ret;
-  for (j=0;j<PAR;j++)
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, url);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  for (i = 0; i < ROUNDS; i++)
+  {
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
     {
-      par[j] = fork ();
-      if (par[j] == 0)
-	{
-	  for (i=0;i<ROUNDS;i++)
-	    {
-	      c = curl_easy_init ();
-	      curl_easy_setopt (c, CURLOPT_URL, url);
-	      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-	      curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL);
-	      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-	      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-	      if (oneone)
-		curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-	      else
-		curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-	      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-	      /* NOTE: use of CONNECTTIMEOUT without also
-		 setting NOSIGNAL results in really weird
-		 crashes on my system! */
-	      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-	      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-		{
-		  fprintf (stderr,
-			   "curl_easy_perform failed: `%s'\n",
-			   curl_easy_strerror (errornum));
-		  curl_easy_cleanup (c);
-		  _exit (1);
-		}
-	      curl_easy_cleanup (c);
-	    }
-	  _exit (0);
-	}
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      return curl_err_marker;
     }
-  for (j=0;j<PAR;j++)
-    waitpid (par[j], NULL, 0);
-  _exit (0);
+  }
+  curl_easy_cleanup (c);
+
+  return NULL;
 }
 
 
-static void 
-join_gets (pid_t pid)
+static void *
+do_gets (void *param)
 {
-  int status;
-  
-  status = 1;
-  waitpid (pid, &status, 0);
-  if (0 != status)
-    abort ();
+  int j;
+  pthread_t par[PAR];
+  char url[64];
+  uint16_t port = (uint16_t) (intptr_t) param;
+  char *err = NULL;
+  static char pthr_err_marker[] = "pthread_create error";
+
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
+  for (j = 0; j < PAR; j++)
+  {
+    if (0 != pthread_create (&par[j], NULL, &thread_gets, (void *) url))
+    {
+      for (j--; j >= 0; j--)
+        pthread_join (par[j], NULL);
+      return pthr_err_marker;
+    }
+  }
+  for (j = 0; j < PAR; j++)
+  {
+    char *ret_val;
+    if ((0 != pthread_join (par[j], (void **) &ret_val)) ||
+        (NULL != ret_val) )
+      err = ret_val;
+  }
+  signal_done = 1;
+  return err;
 }
 
 
-static int
-testInternalGet (int port, int poll_flag)
+static unsigned int
+testInternalGet (uint16_t port, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
+  const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ?
+                                 "internal thread with 'auto'" :
+                                 (poll_flag & MHD_USE_POLL) ?
+                                 "internal thread with poll()" :
+                                 (poll_flag & MHD_USE_EPOLL) ?
+                                 "internal thread with epoll" :
+                                 "internal thread with select()");
+  const char *ret_val;
 
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG  | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+
+  signal_done = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   start_timer ();
-  join_gets (do_gets (port));
-  stop (poll_flag ? "internal poll" : "internal select");
+  ret_val = do_gets ((void *) (intptr_t) port);
+  if (! ret_val)
+    stop (test_desc);
   MHD_stop_daemon (d);
+  if (ret_val)
+  {
+    fprintf (stderr,
+             "Error performing %s test: %s\n", test_desc, ret_val);
+    return 4;
+  }
   return 0;
 }
 
 
-static int
-testMultithreadedGet (int port, int poll_flag)
+static unsigned int
+testMultithreadedGet (uint16_t port, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
+  const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ?
+                                 "internal thread with 'auto' and thread per connection"
+                                 :
+                                 (poll_flag & MHD_USE_POLL) ?
+                                 "internal thread with poll() and thread per connection"
+                                 :
+                                 (poll_flag & MHD_USE_EPOLL) ?
+                                 "internal thread with epoll and thread per connection"
+                                 :
+                                 "internal thread with select() and thread per connection");
+  const char *ret_val;
 
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG  | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+
+  signal_done = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   start_timer ();
-  join_gets (do_gets (port));
-  stop (poll_flag ? "thread with poll" : "thread with select");
+  ret_val = do_gets ((void *) (intptr_t) port);
+  if (! ret_val)
+    stop (test_desc);
   MHD_stop_daemon (d);
+  if (ret_val)
+  {
+    fprintf (stderr,
+             "Error performing %s test: %s\n", test_desc, ret_val);
+    return 4;
+  }
   return 0;
 }
 
-static int
-testMultithreadedPoolGet (int port, int poll_flag)
+
+static unsigned int
+testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
+  const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ?
+                                 "internal thread pool with 'auto'" :
+                                 (poll_flag & MHD_USE_POLL) ?
+                                 "internal thread pool with poll()" :
+                                 (poll_flag & MHD_USE_EPOLL) ?
+                                 "internal thread poll with epoll" :
+                                 "internal thread pool with select()");
+  const char *ret_val;
 
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+
+  signal_done = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   start_timer ();
-  join_gets (do_gets (port));
-  stop (poll_flag ? "thread pool with poll" : "thread pool with select");
+  ret_val = do_gets ((void *) (intptr_t) port);
+  if (! ret_val)
+    stop (test_desc);
   MHD_stop_daemon (d);
+  if (ret_val)
+  {
+    fprintf (stderr,
+             "Error performing %s test: %s\n", test_desc, ret_val);
+    return 4;
+  }
   return 0;
 }
 
-static int
-testExternalGet (int port)
+
+static unsigned int
+testExternalGet (uint16_t port)
 {
   struct MHD_Daemon *d;
-  pid_t pid;
+  pthread_t pid;
   fd_set rs;
   fd_set ws;
   fd_set es;
   MHD_socket max;
   struct timeval tv;
-  MHD_UNSIGNED_LONG_LONG tt;
+  uint64_t tt64;
   int tret;
+  char *ret_val;
+  int ret = 0;
 
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+
+  signal_done = 0;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
-  start_timer ();
-  pid = do_gets (port);
-  while (0 == waitpid (pid, NULL, WNOHANG))
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-	{
-	  MHD_stop_daemon (d);
-	  return 4096;
-	}
-      tret = MHD_get_timeout (d, &tt);
-      if (MHD_YES != tret) tt = 1;
-      tv.tv_sec = tt / 1000;
-      tv.tv_usec = 1000 * (tt % 1000);
-      if (-1 == select (max + 1, &rs, &ws, &es, &tv))
-	{
-	  if (EINTR == errno)
-	    continue;
-	  fprintf (stderr,
-		   "select failed: %s\n",
-		   strerror (errno));
-	  break;	      	  
-	}
-      MHD_run (d);
+      MHD_stop_daemon (d); return 32;
     }
+    port = dinfo->port;
+  }
+  if (0 != pthread_create (&pid, NULL,
+                           &do_gets, (void *) (intptr_t) port))
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
+  start_timer ();
+
+  while (0 == signal_done)
+  {
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+    {
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+    tret = MHD_get_timeout64 (d, &tt64);
+    if (MHD_YES != tret)
+      tt64 = 1;
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+    tv.tv_sec = (time_t) (tt64 / 1000);
+#else  /* Native W32 */
+    tv.tv_sec = (long) (tt64 / 1000);
+#endif /* Native W32 */
+    tv.tv_usec = ((long) (tt64 % 1000)) * 1000;
+    if (-1 == select (max + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      ret |= 1024;
+      break;
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    MHD_run_from_select (d, &rs, &ws, &es);
+  }
+
   stop ("external select");
   MHD_stop_daemon (d);
+  if ((0 != pthread_join (pid, (void **) &ret_val)) ||
+      (NULL != ret_val) )
+  {
+    fprintf (stderr,
+             "%s\n", ret_val);
+    ret |= 8;
+  }
+  if (ret)
+    fprintf (stderr, "Error performing test.\n");
   return 0;
 }
 
@@ -334,28 +507,36 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
-  int port = 1081;
+  uint16_t port = 1100;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (oneone)
+    port += 15;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  response = MHD_create_response_from_buffer (strlen ("/hello_world"),
-					      "/hello_world",
-					      MHD_RESPMEM_MUST_COPY);
+  response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"),
+                                                   "/hello_world");
   errorCount += testInternalGet (port++, 0);
   errorCount += testMultithreadedGet (port++, 0);
   errorCount += testMultithreadedPoolGet (port++, 0);
   errorCount += testExternalGet (port++);
-#ifndef WINDOWS
-  errorCount += testInternalGet (port++, MHD_USE_POLL);
-  errorCount += testMultithreadedGet (port++, MHD_USE_POLL);
-  errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL);
-#endif
-#if EPOLL_SUPPORT
-  errorCount += testInternalGet (port++, MHD_USE_EPOLL_LINUX_ONLY);
-  errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL_LINUX_ONLY);
-#endif
+  errorCount += testInternalGet (port++, MHD_USE_AUTO);
+  errorCount += testMultithreadedGet (port++, MHD_USE_AUTO);
+  errorCount += testMultithreadedPoolGet (port++, MHD_USE_AUTO);
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+  {
+    errorCount += testInternalGet (port++, MHD_USE_POLL);
+    errorCount += testMultithreadedGet (port++, MHD_USE_POLL);
+    errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL);
+  }
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+  {
+    errorCount += testInternalGet (port++, MHD_USE_EPOLL);
+    errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL);
+  }
   MHD_destroy_response (response);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
diff --git a/src/testcurl/test_add_conn.c b/src/testcurl/test_add_conn.c
new file mode 100644
index 0000000..c82fa78
--- /dev/null
+++ b/src/testcurl/test_add_conn.c
@@ -0,0 +1,1275 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) - large rework,
+                             multithreading.
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_add_conn.c
+ * @brief  Testcase for libmicrohttpd GET operations
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+#include "mhd_sockets.h" /* only macros used */
+
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#ifdef HAVE_PTHREAD_H
+#include <pthread.h>
+#endif /* HAVE_PTHREAD_H */
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+#if MHD_CPU_COUNT > 32
+#undef MHD_CPU_COUNT
+/* Limit to reasonable value */
+#define MHD_CPU_COUNT 32
+#endif /* MHD_CPU_COUNT > 32 */
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+/* Number of requests per daemon in cleanup test,
+ * the number must be more than one as the first connection
+ * will be processed and the rest will stay in the list of unprocessed */
+#define CLEANUP_NUM_REQS_PER_DAEMON 6
+
+/* Cleanup test: max number of concurrent daemons depending on maximum number
+ * of open FDs. */
+#define CLEANUP_MAX_DAEMONS(max_fds) (unsigned int) \
+  ( ((max_fds) < 10) ? \
+    0 : ( (((max_fds) - 10) / (CLEANUP_NUM_REQS_PER_DAEMON * 5 + 3)) ) )
+
+#define EXPECTED_URI_BASE_PATH  "/hello_world"
+#define EXPECTED_URI_QUERY      "a=%26&b=c"
+#define EXPECTED_URI_FULL_PATH  EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY
+
+/* Global parameters */
+static int oneone;           /**< Use HTTP/1.1 instead of HTTP/1.0 */
+static int no_listen;        /**< Start MHD daemons without listen socket */
+static uint16_t global_port; /**< MHD daemons listen port number */
+static int cleanup_test;     /**< Test for final cleanup */
+static int slow_reply = 0; /**< Slowdown MHD replies */
+static int ignore_response_errors = 0; /**< Do not fail test if CURL
+                                            returns error */
+static int response_timeout_val = TIMEOUTS_VAL;
+static int sys_max_fds;    /**< Current system limit for number of open
+                                files. */
+
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    return 0;                   /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static void *
+log_cb (void *cls,
+        const char *uri,
+        struct MHD_Connection *con)
+{
+  (void) cls;
+  (void) con;
+  if (0 != strcmp (uri,
+                   EXPECTED_URI_FULL_PATH))
+  {
+    fprintf (stderr,
+             "Wrong URI: `%s'\n",
+             uri);
+    _exit (22);
+  }
+  return NULL;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  const char *v;
+  (void) cls;
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;       /* Unused. Silence compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  v = MHD_lookup_connection_value (connection,
+                                   MHD_GET_ARGUMENT_KIND,
+                                   "a");
+  if ( (NULL == v) ||
+       (0 != strcmp ("&",
+                     v)) )
+  {
+    fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n",
+             NULL == v ? "NULL" : v);
+    _exit (17);
+  }
+  v = NULL;
+  if (MHD_YES != MHD_lookup_connection_value_n (connection,
+                                                MHD_GET_ARGUMENT_KIND,
+                                                "b",
+                                                1,
+                                                &v,
+                                                NULL))
+  {
+    fprintf (stderr, "Not found 'b' GET argument.\n");
+    _exit (18);
+  }
+  if ( (NULL == v) ||
+       (0 != strcmp ("c",
+                     v)) )
+  {
+    fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n",
+             NULL == v ? "NULL" : v);
+    _exit (19);
+  }
+  if (slow_reply)
+    usleep (200000);
+
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (19);
+  }
+  return ret;
+}
+
+
+static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  _exit (99);
+}
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+/* Static const value, indicates that result value was not set yet */
+static const unsigned int eMarker = 0xCE;
+
+
+static MHD_socket
+createListeningSocket (uint16_t *pport)
+{
+  MHD_socket skt;
+  struct sockaddr_in sin;
+  socklen_t sin_len;
+#ifdef MHD_POSIX_SOCKETS
+  static int on = 1;
+#endif /* MHD_POSIX_SOCKETS */
+
+  skt = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET == skt)
+    externalErrorExitDesc ("socket() failed");
+
+#ifdef MHD_POSIX_SOCKETS
+  setsockopt (skt, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof (on));
+  /* Ignore possible error */
+#endif /* MHD_POSIX_SOCKETS */
+
+  memset (&sin, 0, sizeof(sin));
+  sin.sin_family = AF_INET;
+  sin.sin_port = htons (*pport);
+  sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+  if (0 != bind (skt, (struct sockaddr *) &sin, sizeof(sin)))
+    externalErrorExitDesc ("bind() failed");
+
+  if (0 != listen (skt, SOMAXCONN))
+    externalErrorExitDesc ("listen() failed");
+
+  if (0 == *pport)
+  {
+    memset (&sin, 0, sizeof(sin));
+    sin_len = (socklen_t) sizeof(sin);
+    if (0 != getsockname (skt, (struct sockaddr *) &sin, &sin_len))
+      externalErrorExitDesc ("getsockname() failed");
+
+    if (sizeof(sin) < (size_t) sin_len)
+      externalErrorExitDesc ("getsockname() failed");
+
+    if (AF_INET != sin.sin_family)
+      externalErrorExitDesc ("getsockname() returned wrong socket family");
+
+    *pport = ntohs (sin.sin_port);
+  }
+
+  return skt;
+}
+
+
+static MHD_socket
+acceptTimeLimited (MHD_socket lstn_sk, struct sockaddr *paddr,
+                   socklen_t *paddr_len)
+{
+  fd_set rs;
+  struct timeval timeoutval;
+  MHD_socket accepted;
+
+  FD_ZERO (&rs);
+  FD_SET (lstn_sk, &rs);
+  timeoutval.tv_sec = TIMEOUTS_VAL;
+  timeoutval.tv_usec = 0;
+  if (1 != select (((int) lstn_sk) + 1, &rs, NULL, NULL, &timeoutval))
+    externalErrorExitDesc ("select() failed");
+
+  accepted = accept (lstn_sk, paddr, paddr_len);
+  if (MHD_INVALID_SOCKET == accepted)
+    externalErrorExitDesc ("accept() failed");
+
+  return accepted;
+}
+
+
+struct addConnParam
+{
+  struct MHD_Daemon *d;
+
+  MHD_socket lstn_sk;
+
+  MHD_socket clent_sk;
+  /* Non-zero indicate error */
+  volatile unsigned int result;
+
+#ifdef HAVE_PTHREAD_H
+  pthread_t addConnThread;
+#endif /* HAVE_PTHREAD_H */
+};
+
+static unsigned int
+doAcceptAndAddConnInThread (struct addConnParam *p)
+{
+  struct sockaddr addr;
+  socklen_t addr_len = sizeof(addr);
+
+  p->clent_sk = acceptTimeLimited (p->lstn_sk, &addr, &addr_len);
+
+  p->result = (MHD_YES == MHD_add_connection (p->d, p->clent_sk,
+                                              &addr, addr_len)) ?
+              0 : 1;
+  if (p->result)
+    fprintf (stderr, "MHD_add_connection() failed, errno=%d.\n", errno);
+  return p->result;
+}
+
+
+#ifdef HAVE_PTHREAD_H
+static void *
+doAcceptAndAddConn (void *param)
+{
+  struct addConnParam *p = param;
+
+  (void) doAcceptAndAddConnInThread (p);
+
+  return (void *) p;
+}
+
+
+static void
+startThreadAddConn (struct addConnParam *param)
+{
+  /* thread must reset this value to zero if succeed */
+  param->result = eMarker;
+
+  if (0 != pthread_create (&param->addConnThread, NULL, &doAcceptAndAddConn,
+                           (void *) param))
+    externalErrorExitDesc ("pthread_create() failed");
+}
+
+
+static unsigned int
+finishThreadAddConn (struct addConnParam *param)
+{
+  struct addConnParam *result;
+
+  if (0 != pthread_join (param->addConnThread, (void **) &result))
+    externalErrorExitDesc ("pthread_join() failed");
+
+  if (param != result)
+    abort (); /* Test used in a wrong way */
+
+  if (eMarker == param->result)
+    abort (); /* Test used in a wrong way */
+
+  return result->result;
+}
+
+
+#endif /* HAVE_PTHREAD_H */
+
+
+struct curlQueryParams
+{
+  /* Destination path for CURL query */
+  const char *queryPath;
+
+  /* Destination port for CURL query */
+  uint16_t queryPort;
+
+  /* CURL query result error flag */
+  volatile unsigned int queryError;
+
+#ifdef HAVE_PTHREAD_H
+  pthread_t queryThread;
+#endif /* HAVE_PTHREAD_H */
+};
+
+static CURL *
+curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    _exit (99);
+  }
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+  {
+    fprintf (stderr, "curl_easy_setopt() failed.\n");
+    _exit (99);
+  }
+
+  return c;
+}
+
+
+static unsigned int
+doCurlQueryInThread (struct curlQueryParams *p)
+{
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+
+  if (NULL == p->queryPath)
+    abort ();
+
+  if (0 == p->queryPort)
+    abort ();
+
+  cbc.buf = buf;
+  cbc.size = sizeof(buf);
+  cbc.pos = 0;
+
+  c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc);
+
+  errornum = curl_easy_perform (c);
+  if (ignore_response_errors)
+  {
+    p->queryError = 0;
+    curl_easy_cleanup (c);
+
+    return p->queryError;
+  }
+  if (CURLE_OK != errornum)
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    p->queryError = 2;
+  }
+  else
+  {
+    if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH))
+    {
+      fprintf (stderr, "curl reports wrong size of MHD reply body data.\n");
+      p->queryError = 4;
+    }
+    else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf,
+                           strlen (EXPECTED_URI_BASE_PATH)))
+    {
+      fprintf (stderr, "curl reports wrong MHD reply body data.\n");
+      p->queryError = 4;
+    }
+    else
+      p->queryError = 0;
+  }
+  curl_easy_cleanup (c);
+
+  return p->queryError;
+}
+
+
+#ifdef HAVE_PTHREAD_H
+static void *
+doCurlQuery (void *param)
+{
+  struct curlQueryParams *p = (struct curlQueryParams *) param;
+
+  (void) doCurlQueryInThread (p);
+
+  return param;
+}
+
+
+static void
+startThreadCurlQuery (struct curlQueryParams *param)
+{
+  /* thread must reset this value to zero if succeed */
+  param->queryError = eMarker;
+
+  if (0 != pthread_create (&param->queryThread, NULL, &doCurlQuery,
+                           (void *) param))
+    externalErrorExitDesc ("pthread_create() failed");
+}
+
+
+static unsigned int
+finishThreadCurlQuery (struct curlQueryParams *param)
+{
+  struct curlQueryParams *result;
+
+  if (0 != pthread_join (param->queryThread, (void **) &result))
+    externalErrorExitDesc ("pthread_join() failed");
+
+  if (param != result)
+    abort (); /* Test used in wrong way */
+
+  if (eMarker == param->queryError)
+    abort (); /* Test used in wrong way */
+
+  return result->queryError;
+}
+
+
+/* Perform test queries and shut down MHD daemon */
+static unsigned int
+performTestQueries (struct MHD_Daemon *d, uint16_t d_port)
+{
+  struct curlQueryParams qParam;
+  struct addConnParam aParam;
+  uint16_t a_port;      /* Additional listening socket port */
+  unsigned int ret = 0; /* Return value */
+
+  qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH;
+  a_port = 0; /* auto-assign */
+
+  aParam.d = d;
+  aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */
+
+  /* Test of adding connection in the same thread */
+  qParam.queryError = eMarker; /* to be zeroed in new thread */
+  qParam.queryPort = a_port;   /* Connect to additional socket */
+  startThreadCurlQuery (&qParam);
+  ret |= doAcceptAndAddConnInThread (&aParam);
+  ret |= finishThreadCurlQuery (&qParam);
+
+  if (! no_listen)
+  {
+    /* Test of the daemon itself can accept and process new connection. */
+    ret <<= 3;                   /* Remember errors for each step */
+    qParam.queryPort = d_port;   /* Connect to the daemon */
+    ret |= doCurlQueryInThread (&qParam);
+  }
+
+  /* Test of adding connection in an external thread */
+  ret <<= 3;                   /* Remember errors for each step */
+  aParam.result = eMarker;     /* to be zeroed in new thread */
+  qParam.queryPort = a_port;   /* Connect to the daemon */
+  startThreadAddConn (&aParam);
+  ret |= doCurlQueryInThread (&qParam);
+  ret |= finishThreadAddConn (&aParam);
+
+  (void) MHD_socket_close_ (aParam.lstn_sk);
+  MHD_stop_daemon (d);
+
+  return ret;
+}
+
+
+/* Perform test for cleanup and shutdown MHD daemon */
+static unsigned int
+performTestCleanup (struct MHD_Daemon *d, unsigned int num_queries)
+{
+  struct curlQueryParams *qParamList;
+  struct addConnParam aParam;
+  MHD_socket lstn_sk;   /* Additional listening socket */
+  MHD_socket *clntSkList;
+  uint16_t a_port;      /* Additional listening socket port */
+  unsigned int i;
+  unsigned int ret = 0; /* Return value */
+
+  a_port = 0; /* auto-assign */
+
+  if (0 >= num_queries)
+    abort (); /* Test's API violation */
+
+  lstn_sk = createListeningSocket (&a_port); /* Sets a_port */
+
+  qParamList = malloc (sizeof(struct curlQueryParams) * num_queries);
+  clntSkList = malloc (sizeof(MHD_socket) * num_queries);
+  if ((NULL == qParamList) || (NULL == clntSkList))
+    externalErrorExitDesc ("malloc failed");
+
+  /* Start CURL queries */
+  for (i = 0; i < num_queries; i++)
+  {
+    qParamList[i].queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH;
+    qParamList[i].queryError = 0;
+    qParamList[i].queryPort = a_port;
+
+    startThreadCurlQuery (qParamList + i);
+  }
+
+  /* Accept and add required number of client sockets */
+  aParam.d = d;
+  aParam.lstn_sk = lstn_sk;
+  for (i = 0; i < num_queries; i++)
+  {
+    aParam.clent_sk = MHD_INVALID_SOCKET;
+    ret |= doAcceptAndAddConnInThread (&aParam);
+    clntSkList[i] = aParam.clent_sk;
+  }
+
+  /* Stop daemon while some of new connection are not yet
+   * processed because of slow response to the first queries. */
+  MHD_stop_daemon (d);
+  (void) MHD_socket_close_ (aParam.lstn_sk);
+
+  /* Check whether all client sockets were closed by MHD.
+   * Closure of socket by MHD indicate valid cleanup performed. */
+  for (i = 0; i < num_queries; i++)
+  {
+    if (MHD_INVALID_SOCKET != clntSkList[i])
+    { /* Check whether socket could be closed one more time. */
+      if (MHD_socket_close_ (clntSkList[i]))
+      {
+        ret |= 2;
+        fprintf (stderr, "Client socket was not closed by MHD during" \
+                 "cleanup process.\n");
+      }
+    }
+  }
+
+  /* Wait for CURL threads to complete. */
+  /* Ignore soft CURL errors as many connection shouldn't get any response.
+   * Hard failures are detected in processing function. */
+  for (i = 0; i < num_queries; i++)
+    (void) finishThreadCurlQuery (qParamList + i);
+
+  free (clntSkList);
+  free (qParamList);
+
+  return ret;
+}
+
+
+#endif /* HAVE_PTHREAD_H */
+
+enum testMhdThreadsType
+{
+  testMhdThreadExternal              = 0,
+  testMhdThreadInternal              = MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION
+                                       | MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPool
+};
+
+enum testMhdPollType
+{
+  testMhdPollBySelect = 0,
+  testMhdPollByPoll   = MHD_USE_POLL,
+  testMhdPollByEpoll  = MHD_USE_EPOLL,
+  testMhdPollAuto     = MHD_USE_AUTO
+};
+
+/* Get number of threads for thread pool depending
+ * on used poll function and test type. */
+static unsigned int
+testNumThreadsForPool (enum testMhdPollType pollType)
+{
+  unsigned int numThreads = MHD_CPU_COUNT;
+  if (! cleanup_test)
+    return numThreads; /* No practical limit for non-cleanup test */
+  if (CLEANUP_MAX_DAEMONS (sys_max_fds) < numThreads)
+    numThreads = CLEANUP_MAX_DAEMONS (sys_max_fds);
+  if ((testMhdPollBySelect == pollType) &&
+      (CLEANUP_MAX_DAEMONS (FD_SETSIZE) < numThreads))
+    numThreads = CLEANUP_MAX_DAEMONS (FD_SETSIZE);
+
+  if (2 > numThreads)
+    abort ();
+  return (unsigned int) numThreads;
+}
+
+
+static struct MHD_Daemon *
+startTestMhdDaemon (enum testMhdThreadsType thrType,
+                    enum testMhdPollType pollType, uint16_t *pport)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *dinfo;
+
+  if ( (0 == *pport) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    *pport = 1550;
+    if (oneone)
+      *pport += 1;
+    if (no_listen)
+      *pport += 2;
+    if (cleanup_test)
+      *pport += 4;
+  }
+
+  if (testMhdThreadInternalPool != thrType)
+    d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType)
+                          | (thrType == testMhdThreadExternal ?
+                             0 : MHD_USE_ITC)
+                          | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0)
+                          | MHD_USE_ERROR_LOG,
+                          *pport, NULL, NULL,
+                          &ahc_echo, NULL,
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_END);
+  else
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                          | ((unsigned int) pollType)
+                          | MHD_USE_ITC
+                          | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0)
+                          | MHD_USE_ERROR_LOG,
+                          *pport, NULL, NULL,
+                          &ahc_echo, NULL,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          testNumThreadsForPool (pollType),
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_END);
+
+  if (NULL == d)
+  {
+    fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno);
+    abort ();
+  }
+
+  if ((! no_listen) && (0 == *pport))
+  {
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+      abort ();
+    }
+    *pport = dinfo->port;
+  }
+
+  return d;
+}
+
+
+/* Test runners */
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c_d;
+  char buf_d[2048];
+  struct CBC cbc_d;
+  CURL *c_a;
+  char buf_a[2048];
+  struct CBC cbc_a;
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  uint16_t d_port = global_port; /* Daemon's port */
+  uint16_t a_port = 0;      /* Additional listening socket port */
+  struct addConnParam aParam;
+  unsigned int ret = 0;     /* Return value of the test */
+  const int c_no_listen = no_listen; /* Local const value to mute analyzer */
+
+  d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port);
+
+  aParam.d = d;
+  aParam.lstn_sk = createListeningSocket (&a_port);
+
+  multi = NULL;
+  cbc_d.buf = buf_d;
+  cbc_d.size = sizeof(buf_d);
+  cbc_d.pos = 0;
+  cbc_a.buf = buf_a;
+  cbc_a.size = sizeof(buf_a);
+  cbc_a.pos = 0;
+
+  if (cleanup_test)
+    abort (); /* Not possible with "external poll" as connections are directly
+                 added to the daemon processing in the mode. */
+
+  if (! c_no_listen)
+    c_d = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH,
+                               d_port, &cbc_d);
+  else
+    c_d = NULL; /* To mute compiler warning only */
+
+  c_a = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH,
+                             a_port, &cbc_a);
+
+  multi = curl_multi_init ();
+  if (multi == NULL)
+  {
+    fprintf (stderr, "curl_multi_init() failed.\n");
+    _exit (99);
+  }
+  if (! c_no_listen)
+  {
+    if (CURLM_OK != curl_multi_add_handle (multi, c_d))
+    {
+      fprintf (stderr, "curl_multi_add_handle() failed.\n");
+      _exit (99);
+    }
+  }
+
+  if (CURLM_OK != curl_multi_add_handle (multi, c_a))
+  {
+    fprintf (stderr, "curl_multi_add_handle() failed.\n");
+    _exit (99);
+  }
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      struct CURLMsg *msg;
+      int msgLeft;
+      int totalMsgs = 0;
+      do
+      {
+        msg = curl_multi_info_read (multi, &msgLeft);
+        if (NULL == msg)
+        {
+          fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n");
+          _exit (99);
+        }
+        totalMsgs++;
+        if (CURLMSG_DONE == msg->msg)
+        {
+          if (CURLE_OK != msg->data.result)
+          {
+            fprintf (stderr, "curl_multi_info_read failed, error: '%s'\n",
+                     curl_easy_strerror (msg->data.result));
+            ret |= 2;
+          }
+        }
+      } while (msgLeft > 0);
+      if ((no_listen ? 1 : 2) != totalMsgs)
+      {
+        fprintf (stderr,
+                 "curl_multi_info_read returned wrong "
+                 "number of results (%d).\n",
+                 totalMsgs);
+        _exit (99);
+      }
+      break; /* All transfers have finished. */
+    }
+    if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+    {
+      fprintf (stderr, "curl_multi_fdset() failed.\n");
+      _exit (99);
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+    {
+      ret |= 8;
+      break;
+    }
+    FD_SET (aParam.lstn_sk, &rs);
+    if (maxMhdSk < aParam.lstn_sk)
+      maxMhdSk = aParam.lstn_sk;
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    if (FD_ISSET (aParam.lstn_sk, &rs))
+      ret |= doAcceptAndAddConnInThread (&aParam);
+
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+    {
+      fprintf (stderr, "MHD_run_from_select() failed.\n");
+      ret |= 1;
+      break;
+    }
+  }
+
+  MHD_stop_daemon (d);
+  (void) MHD_socket_close_ (aParam.lstn_sk);
+
+  if (! c_no_listen)
+  {
+    curl_multi_remove_handle (multi, c_d);
+    curl_easy_cleanup (c_d);
+    if (cbc_d.pos != strlen ("/hello_world"))
+    {
+      fprintf (stderr,
+               "curl reports wrong size of MHD reply body data at line %d.\n",
+               __LINE__);
+      ret |= 4;
+    }
+    if (0 != strncmp ("/hello_world", cbc_d.buf, strlen ("/hello_world")))
+    {
+      fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n",
+               __LINE__);
+      ret |= 4;
+    }
+  }
+  curl_multi_remove_handle (multi, c_a);
+  curl_easy_cleanup (c_a);
+  curl_multi_cleanup (multi);
+  if (cbc_a.pos != strlen ("/hello_world"))
+  {
+    fprintf (stderr,
+             "curl reports wrong size of MHD reply body data at line %d.\n",
+             __LINE__);
+    ret |= 4;
+  }
+  if (0 != strncmp ("/hello_world", cbc_a.buf, strlen ("/hello_world")))
+  {
+    fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n",
+             __LINE__);
+    ret |= 4;
+  }
+  return ret;
+}
+
+
+#ifdef HAVE_PTHREAD_H
+static unsigned int
+testInternalGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType,
+                          &d_port);
+  if (cleanup_test)
+    return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON);
+
+  return performTestQueries (d, d_port);
+}
+
+
+static unsigned int
+testMultithreadedGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType,
+                          &d_port);
+  if (cleanup_test)
+    abort (); /* Cannot be tested as main daemon thread cannot be slowed down
+                 by slow responses, so it processes all new connections before
+                 daemon could be stopped. */
+
+  return performTestQueries (d, d_port);
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadInternalPool, pollType,
+                          &d_port);
+
+  if (cleanup_test)
+    return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON
+                               * testNumThreadsForPool (pollType));
+  return performTestQueries (d, d_port);
+}
+
+
+static unsigned int
+testStopRace (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  uint16_t a_port = 0;           /* Additional listening socket port */
+  struct sockaddr_in sin;
+  MHD_socket fd1;
+  MHD_socket fd2;
+  struct addConnParam aParam;
+  unsigned int ret = 0;              /* Return value of the test */
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType,
+                          &d_port);
+
+  if (! no_listen)
+  {
+    fd1 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
+    if (MHD_INVALID_SOCKET == fd1)
+      externalErrorExitDesc ("socket() failed");
+
+    memset (&sin, 0, sizeof(sin));
+    sin.sin_family = AF_INET;
+    sin.sin_port = htons (d_port);
+    sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+    if (connect (fd1, (struct sockaddr *) (&sin), sizeof(sin)) < 0)
+      externalErrorExitDesc ("socket() failed");
+  }
+  else
+    fd1 = MHD_INVALID_SOCKET;
+
+  aParam.d = d;
+  aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */
+  startThreadAddConn (&aParam);
+
+  fd2 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
+  if (MHD_INVALID_SOCKET == fd2)
+    externalErrorExitDesc ("socket() failed");
+  memset (&sin, 0, sizeof(sin));
+  sin.sin_family = AF_INET;
+  sin.sin_port = htons (a_port);
+  sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+  if (connect (fd2, (struct sockaddr *) (&sin), sizeof(sin)) < 0)
+    externalErrorExitDesc ("socket() failed");
+  ret |= finishThreadAddConn (&aParam);
+
+  /* Let the thread get going. */
+  usleep (500000);
+
+  MHD_stop_daemon (d);
+
+  if (MHD_INVALID_SOCKET != fd1)
+    (void) MHD_socket_close_ (fd1);
+  (void) MHD_socket_close_ (aParam.lstn_sk);
+  (void) MHD_socket_close_ (fd2);
+
+  return ret;
+}
+
+
+#endif /* HAVE_PTHREAD_H */
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  int verbose = 0;
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  /* Whether to test MHD daemons without listening socket. */
+  no_listen = has_in_name (argv[0], "_nolisten");
+  /* Whether to test for correct final cleanup instead of
+   * of test of normal processing. */
+  cleanup_test = has_in_name (argv[0], "_cleanup");
+  /* There are almost nothing that could be tested externally
+   * for final cleanup. Cleanup test actually just tests that
+   * all added client connections were closed by MHD and
+   * nothing fails or crashes when final cleanup is performed.
+   * Mostly useful when configured with '--enable-asserts. */
+  slow_reply = cleanup_test;
+  ignore_response_errors = cleanup_test;
+#ifndef HAVE_PTHREAD_H
+  if (cleanup_test)
+    return 77; /* Cannot run without threads */
+#endif /* HAVE_PTHREAD_H */
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  if (cleanup_test)
+  {
+#ifndef _WIN32
+    /* Find system limit for number of open FDs. */
+#if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
+    sys_max_fds = sysconf (_SC_OPEN_MAX) > 500000 ?
+                  500000 : (int) sysconf (_SC_OPEN_MAX);
+#else  /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */
+    sys_max_fds = -1;
+#endif /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */
+    if (0 > sys_max_fds)
+    {
+#if defined(OPEN_MAX) && (0 < ((OPEN_MAX) +1))
+      sys_max_fds = OPEN_MAX > 500000 ? 500000 : (int) OPEN_MAX;
+#else  /* ! OPEN_MAX */
+      sys_max_fds = 256; /* Use reasonable value */
+#endif /* ! OPEN_MAX */
+      if (2 > CLEANUP_MAX_DAEMONS (sys_max_fds))
+        return 77; /* Multithreaded test cannot be run */
+    }
+#else  /* _WIN32 */
+    sys_max_fds = 120; /* W32 has problems with ports exhaust */
+#endif /* _WIN32 */
+  }
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 99;
+  /* Could be set to non-zero value to enforce using specific port
+   * in the test */
+  global_port = 0;
+  if (! cleanup_test)
+  {
+    test_result = testExternalGet ();
+    if (test_result)
+      fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testExternalGet ().\n");
+    errorCount += test_result;
+  }
+#ifdef HAVE_PTHREAD_H
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result = testInternalGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedPoolGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    if (! cleanup_test)
+    {
+      test_result = testMultithreadedGet (testMhdPollBySelect);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n");
+      errorCount += test_result;
+      test_result = testStopRace (testMhdPollBySelect);
+      if (test_result)
+        fprintf (stderr, "FAILED: testStopRace (testMhdPollBySelect) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testStopRace (testMhdPollBySelect).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result = testInternalGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+      test_result = testMultithreadedPoolGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedPoolGet (testMhdPollByPoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedPoolGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+      if (! cleanup_test)
+      {
+        test_result = testMultithreadedGet (testMhdPollByPoll);
+        if (test_result)
+          fprintf (stderr,
+                   "FAILED: testMultithreadedGet (testMhdPollByPoll) - %u.\n",
+                   test_result);
+        else if (verbose)
+          printf ("PASSED: testMultithreadedGet (testMhdPollByPoll).\n");
+        errorCount += test_result;
+        test_result = testStopRace (testMhdPollByPoll);
+        if (test_result)
+          fprintf (stderr, "FAILED: testStopRace (testMhdPollByPoll) - %u.\n",
+                   test_result);
+        else if (verbose)
+          printf ("PASSED: testStopRace (testMhdPollByPoll).\n");
+        errorCount += test_result;
+      }
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result = testInternalGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+      test_result = testMultithreadedPoolGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedPoolGet (testMhdPollByEpoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedPoolGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+    }
+  }
+#endif /* HAVE_PTHREAD_H */
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+  curl_global_cleanup ();
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_basicauth.c b/src/testcurl/test_basicauth.c
new file mode 100644
index 0000000..f703867
--- /dev/null
+++ b/src/testcurl/test_basicauth.c
@@ -0,0 +1,743 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_basicauth.c
+ * @brief  Testcase for libmicrohttpd Basic Authorisation
+ * @author Amr Ali
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifndef WINDOWS
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#include "mhd_has_param.h"
+#include "mhd_has_in_name.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+/* Not actually used in this test */
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+#if 0
+/* Function unused in this test */
+static void
+_checkCURLE_OK_func (CURLcode code, const char *curlFunc,
+                     const char *funcName, int lineNum)
+{
+  if (CURLE_OK == code)
+    return;
+
+  fflush (stdout);
+  if ((NULL != curlFunc) && (0 != curlFunc[0]))
+    fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
+             curl_easy_strerror (code));
+  else
+    fprintf (stderr, "libcurl function call resulted in '%s'",
+             curl_easy_strerror (code));
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (9);
+}
+
+
+#endif
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 10
+
+#define MHD_URI_BASE_PATH "/bar%20foo%3Fkey%3Dvalue"
+
+#define REALM "TestRealm"
+#define USERNAME "Aladdin"
+#define PASSWORD "open sesame"
+
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo page</title>" \
+  "</head><body>Access granted</body></html>"
+
+#define DENIED \
+  "<html><head><title>libmicrohttpd - Access denied</title>" \
+  "</head><body>Access denied</body></html>"
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+static int verbose;
+static int preauth;
+static int oldapi;
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    mhdErrorExitDesc ("Wrong too large data");       /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  static int already_called_marker;
+  (void) cls; (void) url;         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size;        /* Unused. Silent compiler warning. */
+
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+    mhdErrorExitDesc ("Unexpected HTTP method");
+
+  /* require: USERNAME with password PASSWORD */
+  if (! oldapi)
+  {
+    struct MHD_BasicAuthInfo *creds;
+
+    creds = MHD_basic_auth_get_username_password3 (connection);
+    if (NULL != creds)
+    {
+      if (NULL == creds->username)
+        mhdErrorExitDesc ("'username' is NULL");
+      else if (MHD_STATICSTR_LEN_ (USERNAME) != creds->username_len)
+      {
+        fprintf (stderr, "'username_len' does not match.\n"
+                 "Expected: %u\tRecieved: %u. ",
+                 (unsigned) MHD_STATICSTR_LEN_ (USERNAME),
+                 (unsigned) creds->username_len);
+        mhdErrorExitDesc ("Wrong 'username_len'");
+      }
+      else if (0 != memcmp (creds->username, USERNAME, creds->username_len))
+      {
+        fprintf (stderr, "'username' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%.*s'. ",
+                 USERNAME,
+                 (int) creds->username_len,
+                 creds->username);
+        mhdErrorExitDesc ("Wrong 'username'");
+      }
+      else if (0 != creds->username[creds->username_len])
+        mhdErrorExitDesc ("'username' is not zero-terminated");
+      else if (NULL == creds->password)
+        mhdErrorExitDesc ("'password' is NULL");
+      else if (MHD_STATICSTR_LEN_ (PASSWORD) != creds->password_len)
+      {
+        fprintf (stderr, "'password_len' does not match.\n"
+                 "Expected: %u\tRecieved: %u. ",
+                 (unsigned) MHD_STATICSTR_LEN_ (PASSWORD),
+                 (unsigned) creds->password_len);
+        mhdErrorExitDesc ("Wrong 'password_len'");
+      }
+      else if (0 != memcmp (creds->password, PASSWORD, creds->password_len))
+      {
+        fprintf (stderr, "'password' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%.*s'. ",
+                 PASSWORD,
+                 (int) creds->password_len,
+                 creds->password);
+        mhdErrorExitDesc ("Wrong 'username'");
+      }
+      else if (0 != creds->password[creds->password_len])
+        mhdErrorExitDesc ("'password' is not zero-terminated");
+
+      MHD_free (creds);
+
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                                (const void *) PAGE);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+      if (MHD_YES != ret)
+        mhdErrorExitDesc ("'MHD_queue_response()' failed");
+    }
+    else
+    {
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                                (const void *) DENIED);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+      ret = MHD_queue_basic_auth_fail_response3 (connection, REALM, MHD_YES,
+                                                 response);
+      if (MHD_YES != ret)
+        mhdErrorExitDesc ("'MHD_queue_basic_auth_fail_response3()' failed");
+    }
+  }
+  else
+  {
+    char *username;
+    char *password;
+
+    password = NULL;
+    username = MHD_basic_auth_get_username_password (connection,
+                                                     &password);
+    if (NULL != username)
+    {
+      if (0 != strcmp (username, USERNAME))
+      {
+        fprintf (stderr, "'username' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%s'. ", USERNAME, username);
+        mhdErrorExitDesc ("Wrong 'username'");
+      }
+      if (NULL == password)
+        mhdErrorExitDesc ("The password pointer is NULL");
+      if (0 != strcmp (password, PASSWORD))
+        fprintf (stderr, "'password' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%s'. ", PASSWORD, password);
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                                (const void *) PAGE);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+      if (MHD_YES != ret)
+        mhdErrorExitDesc ("'MHD_queue_response()' failed");
+    }
+    else
+    {
+      if (NULL != password)
+        mhdErrorExitDesc ("The password pointer is NOT NULL");
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                                (const void *) DENIED);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+      ret = MHD_queue_basic_auth_fail_response (connection, REALM, response);
+      if (MHD_YES != ret)
+        mhdErrorExitDesc ("'MHD_queue_basic_auth_fail_response()' failed");
+    }
+    if (NULL != username)
+      MHD_free (username);
+    if (NULL != password)
+      MHD_free (password);
+  }
+
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port, char *errbuf)
+{
+  CURL *c;
+  char url[512];
+
+  if (1)
+  {
+    int res;
+    /* A workaround for some old libcurl versions, which ignore the specified
+     * port by CURLOPT_PORT when authorisation is used. */
+    res = snprintf (url, (sizeof(url) / sizeof(url[0])),
+                    "http://127.0.0.1:%u%s", (unsigned int) port,
+                    MHD_URI_BASE_PATH);
+    if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res))
+      externalErrorExitDesc ("Cannot form request URL");
+  }
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     CURL_HTTP_VERSION_1_1)) ||
+      /* (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+#if CURL_AT_LEAST_VERSION (7,21,3)
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH,
+                                     CURLAUTH_BASIC
+                                     | (preauth ? 0 : CURLAUTH_ONLY))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD,
+                                     USERNAME ":" PASSWORD)))
+    libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed");
+#else  /* libcurl version before 7.21.3 */
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD,
+                                     USERNAME ":" PASSWORD)))
+    libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed");
+#endif /* libcurl version before 7.21.3 */
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  multi = NULL;
+  multi = curl_multi_init ();
+  if (multi == NULL)
+    libcurlErrorExitDesc ("curl_multi_init() failed");
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 200000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (200);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/**
+ * Check request result
+ * @param curl_code the CURL easy return code
+ * @param pcbc the pointer struct CBC
+ * @return non-zero if success, zero if failed
+ */
+static unsigned int
+check_result (CURLcode curl_code, struct CBC *pcbc)
+{
+  if (CURLE_OK != curl_code)
+  {
+    fflush (stdout);
+    if (0 != libcurl_errbuf[0])
+      fprintf (stderr, "First request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               curl_easy_strerror (curl_code),
+               libcurl_errbuf);
+    else
+      fprintf (stderr, "First request failed. "
+               "libcurl error: '%s'.\n",
+               curl_easy_strerror (curl_code));
+    fflush (stderr);
+    return 0;
+  }
+
+  if (pcbc->pos != strlen (PAGE))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf,
+             (unsigned) strlen (PAGE));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ",
+             (int) pcbc->pos, pcbc->buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
+  return 1;
+}
+
+
+static unsigned int
+testBasicAuth (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t port;
+  struct CBC cbc;
+  char buf[2048];
+  CURL *c;
+  int failed = 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 4210;
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = (uint16_t) dinfo->port;
+  }
+
+  /* First request */
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  cbc.pos = 0;
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port, libcurl_errbuf);
+  if (check_result (performQueryExternal (d, c), &cbc))
+  {
+    if (verbose)
+      printf ("First request successful.\n");
+  }
+  else
+  {
+    fprintf (stderr, "First request FAILED.\n");
+    failed = 1;
+  }
+  curl_easy_cleanup (c);
+
+  /* Second request */
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  cbc.pos = 0;
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port, libcurl_errbuf);
+  if (check_result (performQueryExternal (d, c), &cbc))
+  {
+    if (verbose)
+      printf ("Second request successful.\n");
+  }
+  else
+  {
+    fprintf (stderr, "Second request FAILED.\n");
+    failed = 1;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  preauth = has_in_name (argv[0], "_preauth");
+#if ! CURL_AT_LEAST_VERSION (7,21,3)
+  if (preauth)
+  {
+    fprintf (stderr, "libcurl version 7.21.3 or later is "
+             "required to run this test.\n");
+    return 77;
+  }
+#endif /* libcurl version before 7.21.3 */
+
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
+#ifdef HAVE_GCRYPT_H
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif
+#endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  oldapi = has_in_name (argv[0], "_oldapi");
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  errorCount += testBasicAuth ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_callback.c b/src/testcurl/test_callback.c
index 83233e6..3b293cd 100644
--- a/src/testcurl/test_callback.c
+++ b/src/testcurl/test_callback.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,81 +15,116 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
-
 /**
  * @file test_callback.c
  * @brief Testcase for MHD not calling the callback too often
- * @author Jan Seeger 
+ * @author Jan Seeger
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
-
-
 #include "MHD_config.h"
 #include "platform.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
 
-struct callback_closure {
+struct callback_closure
+{
   unsigned int called;
 };
 
 
-static ssize_t 
-called_twice(void *cls, uint64_t pos, char *buf, size_t max) 
+static ssize_t
+called_twice (void *cls, uint64_t pos, char *buf, size_t max)
 {
   struct callback_closure *cls2 = cls;
-  
-  if (cls2->called == 0) 
-    {
-      memset(buf, 0, max);
-      strcat(buf, "test");
-      cls2->called = 1;
-      return strlen(buf);
-    }
-  if (cls2->called == 1) 
-    {
-      cls2->called = 2;
-      return MHD_CONTENT_READER_END_OF_STREAM;
-    }
-  fprintf(stderr, 
-	  "Handler called after returning END_OF_STREAM!\n");
+
+  (void) pos;    /* Unused. Silence compiler warning. */
+  (void) max;
+  if (cls2->called == 0)
+  {
+    memcpy (buf, "test", 5);
+    cls2->called = 1;
+    return (ssize_t) strlen (buf);
+  }
+  if (cls2->called == 1)
+  {
+    cls2->called = 2;
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  }
+  fprintf (stderr,
+           "Handler called after returning END_OF_STREAM!\n");
+  abort ();
   return MHD_CONTENT_READER_END_WITH_ERROR;
 }
 
 
-static int
-callback(void *cls, struct MHD_Connection *connection, const char *url,
-	 const char *method, const char *version, const char *upload_data,
-	 size_t *upload_data_size, void **con_cls) {
-  struct callback_closure *cbc = calloc(1, sizeof(struct callback_closure));
+static enum MHD_Result
+callback (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  struct callback_closure *cbc = calloc (1, sizeof(struct callback_closure));
   struct MHD_Response *r;
+  enum MHD_Result ret;
 
-  r = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, 
-					 &called_twice, cbc, 
-					 &free);
-  MHD_queue_response(connection, 200, r);
-  MHD_destroy_response(r);
-  return MHD_YES;
+  (void) cls;
+  (void) url;                          /* Unused. Silent compiler warning. */
+  (void) method;
+  (void) version;
+  (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size;
+  (void) req_cls;         /* Unused. Silent compiler warning. */
+
+  if (NULL == cbc)
+    return MHD_NO;
+  r = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024,
+                                         &called_twice, cbc,
+                                         &free);
+  if (NULL == r)
+  {
+    free (cbc);
+    return MHD_NO;
+  }
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            r);
+  MHD_destroy_response (r);
+  return ret;
 }
 
 
 static size_t
-discard_buffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+discard_buffer (void *ptr,
+                size_t size,
+                size_t nmemb,
+                void *ctx)
 {
+  (void) ptr; (void) ctx;  /* Unused. Silent compiler warning. */
   return size * nmemb;
 }
 
 
-int main(int argc, char **argv) 
+int
+main (int argc, char **argv)
 {
   struct MHD_Daemon *d;
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   CURL *c;
   CURLM *multi;
   CURLMcode mret;
@@ -96,94 +132,149 @@
   int running;
   struct timeval tv;
   int extra;
+  uint16_t port;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
-  d = MHD_start_daemon(0, 
-		       8000,
-		       NULL,
-		       NULL,
-		       callback,
-		       NULL,
-		       MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1140;
+
+  d = MHD_start_daemon (0,
+                        port,
+                        NULL,
+                        NULL,
+                        &callback,
+                        NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 32;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 48;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:8000/");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &discard_buffer);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 1;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 99;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 99;
+  }
+  extra = 10;
+  while ( (c != NULL) || (--extra > 0) )
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&ws);
+    FD_ZERO (&rs);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    if (NULL != multi)
     {
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        MHD_stop_daemon (d);
+        return 99;
+      }
+    }
+    if (MHD_YES !=
+        MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 2;
+      return 4;
     }
-  extra = 10;
-  while ( (c != NULL) || (--extra > 0) )
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
     {
-      max = MHD_INVALID_SOCKET;
-      FD_ZERO(&ws);
-      FD_ZERO(&rs);
-      FD_ZERO(&es);
-      curl_multi_perform (multi, &running);
-      if (NULL != multi)
-	{
-	  mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-	  if (mret != CURLM_OK)
-	    {
-	      curl_multi_remove_handle (multi, c);
-	      curl_multi_cleanup (multi);
-	      curl_easy_cleanup (c);
-	      MHD_stop_daemon (d);
-	      return 3;
-	    }   
-	}
-      if (MHD_YES !=
-	  MHD_get_fdset(d, &rs, &ws, &es, &max))
-	{
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-	  return 4;
-	}
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select(max + 1, &rs, &ws, &es, &tv);
-      if (NULL != multi)
-	{
-	  curl_multi_perform (multi, &running);
-	  if (running == 0)
-	    {
-	      msg = curl_multi_info_read (multi, &running);
-	      if (msg == NULL)
-		break;
-	      if (msg->msg == CURLMSG_DONE)
-		{
-		  if (msg->data.result != CURLE_OK)
-		    printf ("%s failed at %s:%d: `%s'\n",
-			    "curl_multi_perform",
-			    __FILE__,
-			    __LINE__, curl_easy_strerror (msg->data.result));
-		  curl_multi_remove_handle (multi, c);
-		  curl_multi_cleanup (multi);
-		  curl_easy_cleanup (c);
-		  c = NULL;
-		  multi = NULL;
-		}
-	    }
-	}
-      MHD_run(d);
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
     }
-  MHD_stop_daemon(d);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        int pending;
+        int curl_fine = 0;
+        while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+        {
+          if (msg->msg == CURLMSG_DONE)
+          {
+            if (msg->data.result == CURLE_OK)
+              curl_fine = 1;
+            else
+            {
+              fprintf (stderr,
+                       "%s failed at %s:%d: `%s'\n",
+                       "curl_multi_perform",
+                       __FILE__,
+                       __LINE__, curl_easy_strerror (msg->data.result));
+              abort ();
+            }
+          }
+        }
+        if (! curl_fine)
+        {
+          fprintf (stderr, "libcurl haven't returned OK code\n");
+          abort ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        c = NULL;
+        multi = NULL;
+      }
+    }
+    MHD_run (d);
+  }
+  MHD_stop_daemon (d);
   return 0;
 }
diff --git a/src/testcurl/test_concurrent_stop.c b/src/testcurl/test_concurrent_stop.c
index 60cc98d..9c7df42 100644
--- a/src/testcurl/test_concurrent_stop.c
+++ b/src/testcurl/test_concurrent_stop.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2007, 2009, 2011, 2015 Christian Grothoff
+     Copyright (C) 2007, 2009, 2011, 2015, 2016 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_concurrent_stop.c
  * @brief test stopping server while concurrent GETs are ongoing
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 #include "MHD_config.h"
 #include "platform.h"
@@ -30,24 +32,19 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#include "gauger.h"
+#include <pthread.h>
 
-#ifdef CPU_COUNT
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#define CPU_COUNT 40
-
-
-/**
- * How many rounds of operations do we do for each
- * test (total number of requests will be ROUNDS * PAR).
- */
-#define ROUNDS 50000
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
 
 /**
  * How many requests do we do in parallel?
  */
-#define PAR CPU_COUNT
+#define PAR (MHD_CPU_COUNT * 4)
 
 /**
  * Do we use HTTP 1.1?
@@ -59,36 +56,108 @@
  */
 static struct MHD_Response *response;
 
+/**
+ * Continue generating new requests?
+ */
+static volatile int continue_requesting;
+
+/**
+ * Continue waiting in watchdog thread?
+ */
+static volatile int watchdog_continue;
+
+static const char *watchdog_obj;
+
+/**
+ * Indicate that client detected error
+ */
+static volatile CURLcode client_error;
+
+static void *
+thread_watchdog (void *param)
+{
+  int seconds_passed;
+  const int timeout_val = (int) (intptr_t) param;
+
+  seconds_passed = 0;
+  while (watchdog_continue) /* Poor threads sync, but works for testing. */
+  {
+    if (0 == sleep (1))   /* Poor accuracy, but enough for testing. */
+      seconds_passed++;
+    if (timeout_val < seconds_passed)
+    {
+      fprintf (stderr, "%s timeout expired.\n", watchdog_obj ? watchdog_obj :
+               "Watchdog");
+      fflush (stderr);
+      _exit (16);
+    }
+  }
+  return NULL;
+}
+
+
+pthread_t watchdog_tid;
+
+static void
+start_watchdog (int timeout, const char *obj_name)
+{
+  watchdog_continue = 1;
+  watchdog_obj = obj_name;
+  if (0 != pthread_create (&watchdog_tid, NULL, &thread_watchdog,
+                           (void *) (intptr_t) timeout))
+  {
+    fprintf (stderr, "Failed to start watchdog.\n");
+    _exit (99);
+  }
+}
+
+
+static void
+stop_watchdog (void)
+{
+  watchdog_continue = 0;
+  if (0 != pthread_join (watchdog_tid, NULL))
+  {
+    fprintf (stderr, "Failed to stop watchdog.\n");
+    _exit (99);
+  }
+}
+
 
 static size_t
 copyBuffer (void *ptr,
-	    size_t size, size_t nmemb,
-	    void *ctx)
+            size_t size, size_t nmemb,
+            void *ctx)
 {
+  (void) ptr; (void) ctx;  /* Unused. Silent compiler warning. */
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
 {
-  static int ptr;
-  const char *me = cls;
-  int ret;
+  static int marker;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&marker != *req_cls)
+  {
+    *req_cls = &marker;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   ret = MHD_queue_response (connection,
                             MHD_HTTP_OK,
                             response);
@@ -98,110 +167,187 @@
 }
 
 
-static pid_t
-do_gets (int port)
+static void *
+thread_gets (void *param)
 {
-  pid_t ret;
   CURL *c;
   CURLcode errornum;
-  unsigned int i;
-  unsigned int j;
-  pid_t par[PAR];
-  char url[64];
+  char *const url = (char *) param;
 
-  sprintf(url, "http://127.0.0.1:%d/hello_world", port);
-
-  ret = fork ();
-  if (ret == -1) abort ();
-  if (ret != 0)
-    return ret;
-  for (j=0;j<PAR;j++)
+  c = NULL;
+  c = curl_easy_init ();
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init failed.\n");
+    _exit (99);
+  }
+  curl_easy_setopt (c, CURLOPT_URL, url);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 2L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 2L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  while (continue_requesting)
+  {
+    errornum = curl_easy_perform (c);
+    if (CURLE_OK != errornum)
     {
-      par[j] = fork ();
-      if (par[j] == 0)
-	{
-	  for (i=0;i<ROUNDS;i++)
-	    {
-	      c = curl_easy_init ();
-	      curl_easy_setopt (c, CURLOPT_URL, url);
-	      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-	      curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL);
-	      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-	      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-	      if (oneone)
-		curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-	      else
-		curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-	      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-	      /* NOTE: use of CONNECTTIMEOUT without also
-		 setting NOSIGNAL results in really weird
-		 crashes on my system! */
-	      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-	      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-		{
-		  curl_easy_cleanup (c);
-		  _exit (1);
-		}
-	      curl_easy_cleanup (c);
-	    }
-	  _exit (0);
-	}
+      curl_easy_cleanup (c);
+      client_error = errornum;
+      return NULL;
     }
-  for (j=0;j<PAR;j++)
-    waitpid (par[j], NULL, 0);
-  _exit (0);
+  }
+  curl_easy_cleanup (c);
+  return NULL;
 }
 
 
-static void
-join_gets (pid_t pid)
+static void *
+do_gets (void *param)
 {
-  int status;
+  int j;
+  pthread_t par[PAR];
+  char url[64];
+  uint16_t port = (uint16_t) (intptr_t) param;
 
-  status = 1;
-  waitpid (pid, &status, 0);
-  if (0 != status)
-    abort ();
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
+
+  for (j = 0; j < PAR; j++)
+  {
+    if (0 != pthread_create (&par[j], NULL, &thread_gets, (void *) url))
+    {
+      fprintf (stderr, "pthread_create failed.\n");
+      continue_requesting = 0;
+      for (j--; j >= 0; j--)
+      {
+        pthread_join (par[j], NULL);
+      }
+      _exit (99);
+    }
+  }
+  (void) sleep (1);
+  for (j = 0; j < PAR; j++)
+  {
+    pthread_join (par[j], NULL);
+  }
+  return NULL;
 }
 
 
-static int
-testMultithreadedGet (int port, int poll_flag)
+static pthread_t
+start_gets (uint16_t port)
+{
+  pthread_t tid;
+  continue_requesting = 1;
+  if (0 != pthread_create (&tid, NULL, &do_gets, (void *) (intptr_t) port))
+  {
+    fprintf (stderr, "pthread_create failed.\n");
+    _exit (99);
+  }
+  return tid;
+}
+
+
+static unsigned int
+testMultithreadedGet (uint16_t port,
+                      uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
-  pid_t p;
+  pthread_t p;
+  unsigned int result;
 
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG  | poll_flag,
-                        port, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
-  if (d == NULL)
-    return 16;
-  p = do_gets (port);
-  sleep (1);
-  MHD_stop_daemon (d);
-  join_gets (p);
-  return 0;
-}
-
-
-static int
-testMultithreadedPoolGet (int port, int poll_flag)
-{
-  struct MHD_Daemon *d;
-  pid_t p;
-
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | poll_flag,
+  result = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
                         port,
                         NULL, NULL,
-                        &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT,
+                        &ahc_echo, NULL,
                         MHD_OPTION_END);
   if (d == NULL)
     return 16;
-  p = do_gets (port);
-  sleep (1);
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  client_error = CURLE_OK; /* clear client error state */
+  p = start_gets (port);
+  (void) sleep (1);
+  start_watchdog (10, "daemon_stop() in testMultithreadedGet");
+  if (CURLE_OK != client_error) /* poor sync, but enough for test */
+  {
+    result = 64;
+    fprintf (stderr, "libcurl reported at least one error: \"%s\"\n",
+             curl_easy_strerror (client_error));
+  }
   MHD_stop_daemon (d);
-  join_gets (p);
-  return 0;
+  stop_watchdog ();
+  continue_requesting = 0;
+  pthread_join (p, NULL);
+  return result;
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (uint16_t port,
+                          uint32_t poll_flag)
+{
+  struct MHD_Daemon *d;
+  pthread_t p;
+  unsigned int result;
+
+  result = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port,
+                        NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  client_error = CURLE_OK; /* clear client error state */
+  p = start_gets (port);
+  (void) sleep (1);
+  start_watchdog (10, "daemon_stop() in testMultithreadedPoolGet");
+  if (CURLE_OK != client_error) /* poor sync, but enough for test */
+  {
+    result = 64;
+    fprintf (stderr, "libcurl reported at least one error: \"%s\"\n",
+             curl_easy_strerror (client_error));
+  }
+  MHD_stop_daemon (d);
+  stop_watchdog ();
+  continue_requesting = 0;
+  pthread_join (p, NULL);
+  return result;
 }
 
 
@@ -209,20 +355,31 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
-  int port = 1081;
+  uint16_t port;
+  (void) argc;   /* Unused. Silent compiler warning. */
+  (void) argv;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1142;
+
+  /* Do reuse connection, otherwise all available local ports may exhausted. */
+  oneone = 1;
+
+  if ((0 != port) && oneone)
+    port += 5;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  response = MHD_create_response_from_buffer (strlen ("/hello_world"),
-					      "/hello_world",
-					      MHD_RESPMEM_MUST_COPY);
-  errorCount += testMultithreadedGet (port++, 0);
-  errorCount += testMultithreadedPoolGet (port++, 0);
+  response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"),
+                                                   "/hello_world");
+  errorCount += testMultithreadedGet (port, 0);
+  if (0 != port)
+    port++;
+  errorCount += testMultithreadedPoolGet (port, 0);
   MHD_destroy_response (response);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_delete.c b/src/testcurl/test_delete.c
new file mode 100644
index 0000000..3764745
--- /dev/null
+++ b/src/testcurl/test_delete.c
@@ -0,0 +1,566 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2016 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file daemontest_delete.c
+ * @brief  Testcase for libmicrohttpd DELETE operations
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+
+#ifndef WINDOWS
+#include <unistd.h>
+#endif
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+static int oneone;
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+static size_t
+putBuffer (void *stream, size_t size, size_t nmemb, void *ptr)
+{
+  size_t *pos = ptr;
+  size_t wrt;
+
+  wrt = size * nmemb;
+  if (wrt > 8 - (*pos))
+    wrt = 8 - (*pos);
+  memcpy (stream, &("Hello123"[*pos]), wrt);
+  (*pos) += wrt;
+  return wrt;
+}
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    return 0;                   /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  int *done = cls;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp ("DELETE", method))
+    return MHD_NO;              /* unexpected method */
+  if ((*done) == 0)
+  {
+    if (*upload_data_size != 8)
+      return MHD_YES;           /* not yet ready */
+    if (0 == memcmp (upload_data, "Hello123", 8))
+    {
+      *upload_data_size = 0;
+    }
+    else
+    {
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
+    }
+    *done = 1;
+    return MHD_YES;
+  }
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static unsigned int
+testInternalDelete (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1152;
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+  curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE");
+  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 4;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 8;
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedDelete (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1153;
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+  curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE");
+  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 64;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 128;
+
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedPoolDelete (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1154;
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+  curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE");
+  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 64;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 128;
+
+  return 0;
+}
+
+
+static unsigned int
+testExternalDelete (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLM *multi;
+  CURLMcode mret;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
+  int running;
+  struct CURLMsg *msg;
+  time_t start;
+  struct timeval tv;
+  size_t pos = 0;
+  int done_flag = 0;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1154;
+
+  multi = NULL;
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  if (d == NULL)
+    return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+  curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE");
+  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+  multi = curl_multi_init ();
+  if (multi == NULL)
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
+  mret = curl_multi_add_handle (multi, c);
+  if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 2048;
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 8192;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 16384;
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalDelete ();
+    errorCount += testMultithreadedDelete ();
+    errorCount += testMultithreadedPoolDelete ();
+  }
+  errorCount += testExternalDelete ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_digestauth.c b/src/testcurl/test_digestauth.c
index 255e086..fe221f7 100644
--- a/src/testcurl/test_digestauth.c
+++ b/src/testcurl/test_digestauth.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,26 +15,30 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_digestauth.c
  * @brief  Testcase for libmicrohttpd Digest Auth
  * @author Amr Ali
+ * @author Karlson2k (Evgeny Grin)
  */
 
-#include "MHD_config.h"
+#include "mhd_options.h"
 #include "platform.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#ifdef HAVE_GCRYPT_H
+
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
 #include <gcrypt.h>
-#endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
 
 #ifndef WINDOWS
 #include <sys/socket.h>
@@ -42,9 +47,183 @@
 #include <wincrypt.h>
 #endif
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
 
-#define DENIED "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+static void
+_checkCURLE_OK_func (CURLcode code, const char *curlFunc,
+                     const char *funcName, int lineNum)
+{
+  if (CURLE_OK == code)
+    return;
+
+  fflush (stdout);
+  if ((NULL != curlFunc) && (0 != curlFunc[0]))
+    fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
+             curl_easy_strerror (code));
+  else
+    fprintf (stderr, "libcurl function call resulted in '%s'",
+             curl_easy_strerror (code));
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (9);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+#define MHD_URI_BASE_PATH "/bar%20foo%20without%20args"
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
+
+#define DENIED \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
 
 #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4"
 
@@ -55,193 +234,278 @@
   size_t size;
 };
 
+
 static size_t
-copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
 {
   struct CBC *cbc = ctx;
 
   if (cbc->pos + size * nmemb > cbc->size)
-    return 0;                   /* overflow */
+    mhdErrorExitDesc ("Wrong too large data");       /* overflow */
   memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
   cbc->pos += size * nmemb;
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
 {
   struct MHD_Response *response;
   char *username;
   const char *password = "testpass";
   const char *realm = "test@example.com";
-  int ret;
+  enum MHD_Result ret;
+  int ret_i;
+  static int already_called_marker;
+  (void) cls; (void) url;                         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls;        /* Unused. Silent compiler warning. */
 
-  username = MHD_digest_auth_get_username(connection);
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  username = MHD_digest_auth_get_username (connection);
   if ( (username == NULL) ||
        (0 != strcmp (username, "testuser")) )
-    {
-      response = MHD_create_response_from_buffer(strlen (DENIED), 
-						 DENIED,
-						 MHD_RESPMEM_PERSISTENT);  
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 MY_OPAQUE,
-					 response,
-					 MHD_NO);    
-      MHD_destroy_response(response);  
-      return ret;
-    }
-  ret = MHD_digest_auth_check(connection, realm,
-			      username, 
-			      password, 
-			      300);
-  free(username);
-  if ( (ret == MHD_INVALID_NONCE) ||
-       (ret == MHD_NO) )
-    {
-      response = MHD_create_response_from_buffer(strlen (DENIED), 
-						 DENIED,
-						 MHD_RESPMEM_PERSISTENT);  
-      if (NULL == response) 
-	return MHD_NO;
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 MY_OPAQUE,
-					 response,
-					 (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO);  
-      MHD_destroy_response(response);  
-      return ret;
-    }
-  response = MHD_create_response_from_buffer(strlen(PAGE), PAGE,
-					     MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response(connection, MHD_HTTP_OK, response);  
-  MHD_destroy_response(response);
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    if (NULL == response)
+      mhdErrorExitDesc ("MHD_create_response_from_buffer failed");
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    if (MHD_YES != ret)
+      mhdErrorExitDesc ("MHD_queue_auth_fail_response2 failed");
+    MHD_destroy_response (response);
+    return ret;
+  }
+  ret_i = MHD_digest_auth_check2 (connection,
+                                  realm,
+                                  username,
+                                  password,
+                                  300,
+                                  MHD_DIGEST_ALG_MD5);
+  MHD_free (username);
+  if (ret_i != MHD_YES)
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    if (NULL == response)
+      mhdErrorExitDesc ("MHD_create_response_from_buffer() failed");
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         (MHD_INVALID_NONCE == ret_i) ?
+                                         MHD_YES : MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    if (MHD_YES != ret)
+      mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed");
+    MHD_destroy_response (response);
+    return ret;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                     PAGE);
+  if (NULL == response)
+    mhdErrorExitDesc ("MHD_create_response_from_buffer() failed");
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed");
+  MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testDigestAuth ()
+static CURL *
+setupCURL (void *cbc, uint16_t port)
 {
-  int fd;
   CURL *c;
-  CURLcode errornum;
+  char url[512];
+
+  if (1)
+  {
+    int res;
+    /* A workaround for some old libcurl versions, which ignore the specified
+     * port by CURLOPT_PORT when digest authorisation is used. */
+    res = snprintf (url, (sizeof(url) / sizeof(url[0])),
+                    "http://127.0.0.1:%u%s",
+                    (unsigned int) port, MHD_URI_BASE_PATH);
+    if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res))
+      externalErrorExitDesc ("Cannot form request URL");
+  }
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     CURL_HTTP_VERSION_1_1)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD,
+                                     "testuser:testpass")))
+    libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed");
+  return c;
+}
+
+
+static unsigned int
+testDigestAuth (void)
+{
+  CURL *c;
   struct MHD_Daemon *d;
   struct CBC cbc;
-  size_t len;
-  size_t off = 0;
   char buf[2048];
   char rnd[8];
+  uint16_t port;
+#ifndef WINDOWS
+  int fd;
+  size_t len;
+  size_t off = 0;
+#endif /* ! WINDOWS */
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1165;
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
 #ifndef WINDOWS
-  fd = open("/dev/urandom", O_RDONLY);
+  fd = open ("/dev/urandom",
+             O_RDONLY);
   if (-1 == fd)
-    {
-	  fprintf(stderr, "Failed to open `%s': %s\n",
-	       "/dev/urandom",
-		   strerror(errno));
-	  return 1;
-	}
+    externalErrorExitDesc ("Failed to open '/dev/urandom'");
+
   while (off < 8)
-	{
-	  len = read(fd, rnd, 8);
-	  if (len == -1)
-	    {
-		  fprintf(stderr, "Failed to read `%s': %s\n",
-		       "/dev/urandom",
-			   strerror(errno));
-		  (void) close(fd);
-		  return 1;
-		}
-	  off += len;
-	}
-  (void) close(fd);
+  {
+    len = (size_t) read (fd,
+                         rnd + off,
+                         8 - off);
+    if (len == (size_t) -1)
+      externalErrorExitDesc ("Failed to read '/dev/urandom'");
+    off += len;
+  }
+  (void) close (fd);
 #else
   {
     HCRYPTPROV cc;
     BOOL b;
-    b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
+
+    b = CryptAcquireContext (&cc,
+                             NULL,
+                             NULL,
+                             PROV_RSA_FULL,
+                             CRYPT_VERIFYCONTEXT);
     if (b == 0)
-    {
-      fprintf (stderr, "Failed to acquire crypto provider context: %lu\n",
-          GetLastError ());
-      return 1;
-    }
-    b = CryptGenRandom (cc, 8, rnd);
+      externalErrorExitDesc ("CryptAcquireContext() failed");
+    b = CryptGenRandom (cc, 8, (BYTE *) rnd);
     if (b == 0)
-    {
-      fprintf (stderr, "Failed to generate 8 random bytes: %lu\n",
-          GetLastError ());
-    }
+      externalErrorExitDesc ("CryptGenRandom() failed");
     CryptReleaseContext (cc, 0);
-    if (b == 0)
-      return 1;
   }
 #endif
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1337, NULL, NULL, &ahc_echo, PAGE,
-			MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd,
-			MHD_OPTION_NONCE_NC_SIZE, 300,
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd,
+                        MHD_OPTION_NONCE_NC_SIZE, 300,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
-  c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1337/");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
-  curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass");
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-  /* NOTE: use of CONNECTTIMEOUT without also
-     setting NOSIGNAL results in really weird
-     crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-  if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = dinfo->port;
+  }
+  c = setupCURL (&cbc, port);
+
+  checkCURLE_OK (curl_easy_perform (c));
+
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (PAGE))
-    return 4;
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen (MHD_URI_BASE_PATH));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
   if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE)))
-    return 8;
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
   return 0;
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
-#ifdef HAVE_GCRYPT_H
+#ifdef NEED_GCRYP_INIT
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
-#endif
-#endif
-if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   errorCount += testDigestAuth ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_digestauth2.c b/src/testcurl/test_digestauth2.c
new file mode 100644
index 0000000..30d19a0
--- /dev/null
+++ b/src/testcurl/test_digestauth2.c
@@ -0,0 +1,1600 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_digest2.c
+ * @brief  Testcase for MHD Digest Authorisation
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#include "mhd_has_param.h"
+#include "mhd_has_in_name.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \
+                       __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+/* Not actually used in this test */
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+#if 0
+/* Function unused in this test */
+static void
+_checkCURLE_OK_func (CURLcode code, const char *curlFunc,
+                     const char *funcName, int lineNum)
+{
+  if (CURLE_OK == code)
+    return;
+
+  fflush (stdout);
+  if ((NULL != curlFunc) && (0 != curlFunc[0]))
+    fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
+             curl_easy_strerror (code));
+  else
+    fprintf (stderr, "libcurl function call resulted in '%s'",
+             curl_easy_strerror (code));
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (9);
+}
+
+
+#endif
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 10
+
+#define MHD_URI_BASE_PATH "/bar%20foo?key=value"
+#define MHD_URI_BASE_PATH2 "/another_path"
+/* Should not fit buffer in the stack */
+#define MHD_URI_BASE_PATH3 \
+  "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \
+  "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \
+  "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \
+  "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \
+  "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \
+  "/path?with%20some=parameters"
+
+#define REALM_VAL "TestRealm"
+#define USERNAME1 "test_user"
+/* The hex form of MD5("test_user:TestRealm") */
+#define USERHASH1_MD5_HEX "c53c601503ff176f18f623725fba4281"
+#define USERHASH1_MD5_BIN 0xc5, 0x3c, 0x60, 0x15, 0x03, 0xff, 0x17, 0x6f, \
+  0x18, 0xf6, 0x23, 0x72, 0x5f, 0xba, 0x42, 0x81
+/* The hex form of SHA-256("test_user:TestRealm") */
+#define USERHASH1_SHA256_HEX \
+  "090c7e06b77d6614cf5fe6cafa004d2e5f8fb36ba45a0e35eacb2eb7728f34de"
+/* The binary form of SHA-256("test_user:TestRealm") */
+#define USERHASH1_SHA256_BIN 0x09, 0x0c, 0x7e, 0x06, 0xb7, 0x7d, 0x66, 0x14, \
+  0xcf, 0x5f, 0xe6, 0xca, 0xfa, 0x00, 0x4d, 0x2e, 0x5f, 0x8f, 0xb3, 0x6b, \
+  0xa4, 0x5a, 0x0e, 0x35, 0xea, 0xcb, 0x2e, 0xb7, 0x72, 0x8f, 0x34, 0xde
+/* The hex form of MD5("test_user:TestRealm:test pass") */
+#define USERDIGEST1_MD5_BIN 0xd8, 0xb4, 0xa6, 0xd0, 0x01, 0x13, 0x07, 0xb7, \
+  0x67, 0x94, 0xea, 0x66, 0x86, 0x03, 0x6b, 0x43
+/* The binary form of SHA-256("test_user:TestRealm:test pass") */
+#define USERDIGEST1_SHA256_BIN 0xc3, 0x4e, 0x16, 0x5a, 0x17, 0x0f, 0xe5, \
+  0xac, 0x04, 0xf1, 0x6e, 0x46, 0x48, 0x2b, 0xa0, 0xc6, 0x56, 0xc1, 0xfb, \
+  0x8f, 0x66, 0xa6, 0xd6, 0x3f, 0x91, 0x12, 0xf8, 0x56, 0xa5, 0xec, 0x6d, \
+  0x6d
+#define PASSWORD_VALUE "test pass"
+#define OPAQUE_VALUE "opaque+content" /* Base64 character set */
+
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo page</title>" \
+  "</head><body>Access granted</body></html>"
+
+#define DENIED \
+  "<html><head><title>libmicrohttpd - Access denied</title>" \
+  "</head><body>Access denied</body></html>"
+
+/* Global parameters */
+static int verbose;
+static int test_oldapi;
+static int test_userhash;
+static int test_userdigest;
+static int test_sha256;
+static int test_rfc2069;
+/* Bind DAuth nonces to everything except URI */
+static int test_bind_all;
+/* Bind DAuth nonces to URI */
+static int test_bind_uri;
+static int curl_uses_usehash;
+
+/* Static helper variables */
+static const char userhash1_md5_hex[] = USERHASH1_MD5_HEX;
+static const uint8_t userhash1_md5_bin[] = { USERHASH1_MD5_BIN };
+static const char userhash1_sha256_hex[] = USERHASH1_SHA256_HEX;
+static const uint8_t userhash1_sha256_bin[] = { USERHASH1_SHA256_BIN };
+static const char *userhash_hex;
+static size_t userhash_hex_len;
+static const uint8_t *userhash_bin;
+static const uint8_t userdigest1_md5_bin[] = { USERDIGEST1_MD5_BIN };
+static const uint8_t userdigest1_sha256_bin[] = { USERDIGEST1_SHA256_BIN };
+static const uint8_t *userdigest_bin;
+static size_t userdigest_bin_size;
+static const char *username_ptr;
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+
+  username_ptr = USERNAME1;
+  if (! test_sha256)
+  {
+    userhash_hex = userhash1_md5_hex;
+    userhash_hex_len = MHD_STATICSTR_LEN_ (userhash1_md5_hex);
+    userhash_bin = userhash1_md5_bin;
+    if ((userhash_hex_len / 2) != \
+        (sizeof(userhash1_md5_bin) / sizeof(userhash1_md5_bin[0])))
+      externalErrorExitDesc ("Wrong size of the 'userhash1_md5_bin' array");
+    userdigest_bin = userdigest1_md5_bin;
+    userdigest_bin_size =
+      (sizeof(userdigest1_md5_bin) / sizeof(userdigest1_md5_bin[0]));
+  }
+  else
+  {
+    userhash_hex = userhash1_sha256_hex;
+    userhash_hex_len = MHD_STATICSTR_LEN_ (userhash1_sha256_hex);
+    userhash_bin = userhash1_sha256_bin;
+    if ((userhash_hex_len / 2) != \
+        (sizeof(userhash1_sha256_bin)   \
+         / sizeof(userhash1_sha256_bin[0])))
+      externalErrorExitDesc ("Wrong size of the 'userhash1_sha256_bin' array");
+    userdigest_bin = userdigest1_sha256_bin;
+    userdigest_bin_size =
+      (sizeof(userdigest1_sha256_bin) / sizeof(userdigest1_sha256_bin[0]));
+  }
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_global_cleanup ();
+}
+
+
+static int
+gen_good_rnd (void *rnd_buf, size_t rnd_buf_size)
+{
+  if (1024 < rnd_buf_size)
+    externalErrorExitDesc ("Too large amount of random data " \
+                           "is requested");
+#ifndef _WIN32
+  if (1)
+  {
+    const int urand_fd = open ("/dev/urandom", O_RDONLY);
+    if (0 < urand_fd)
+    {
+      size_t pos = 0;
+      do
+      {
+        ssize_t res = read (urand_fd,
+                            ((uint8_t *) rnd_buf) + pos, rnd_buf_size - pos);
+        if (0 > res)
+          break;
+        pos += (size_t) res;
+      } while (rnd_buf_size > pos);
+      (void) close (urand_fd);
+
+      if (rnd_buf_size == pos)
+        return ! 0; /* Success */
+    }
+  }
+#else  /* _WIN32 */
+  if (1)
+  {
+    HCRYPTPROV cpr_hndl;
+    if (CryptAcquireContextW (&cpr_hndl, NULL, NULL, PROV_RSA_FULL,
+                              CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
+    {
+      if (CryptGenRandom (cpr_hndl, (DWORD) rnd_buf_size, (BYTE *) rnd_buf))
+      {
+        (void) CryptReleaseContext (cpr_hndl, 0);
+        return ! 0; /* Success */
+      }
+      (void) CryptReleaseContext (cpr_hndl, 0);
+    }
+  }
+#endif /* _WIN32 */
+  return 0; /* Failure */
+}
+
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+struct req_track
+{
+  /**
+   * The number of used URI, zero-based
+   */
+  unsigned int uri_num;
+
+  /**
+   * The number of request for URI.
+   * This includes number of unauthorised requests.
+   */
+  unsigned int req_num;
+};
+
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    mhdErrorExitDesc ("Wrong too large data");       /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  struct MHD_Response *response;
+  enum MHD_Result res;
+  static int already_called_marker;
+  struct req_track *const tr_p = (struct req_track *) cls;
+  (void) url;              /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; /* Unused. Silent compiler warning. */
+
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+    mhdErrorExitDesc ("Unexpected HTTP method");
+
+  tr_p->req_num++;
+  if (2 < tr_p->req_num)
+    mhdErrorExitDesc ("Received more than two requests for the same URI");
+
+  response = NULL;
+  if (! test_oldapi)
+  {
+    struct MHD_DigestAuthInfo *dinfo;
+    const enum MHD_DigestAuthAlgo3 algo3 =
+      test_sha256 ? MHD_DIGEST_AUTH_ALGO3_SHA256 : MHD_DIGEST_AUTH_ALGO3_MD5;
+    const enum MHD_DigestAuthQOP qop =
+      test_rfc2069 ? MHD_DIGEST_AUTH_QOP_NONE : MHD_DIGEST_AUTH_QOP_AUTH;
+
+    dinfo = MHD_digest_auth_get_request_info3 (connection);
+    if (NULL != dinfo)
+    {
+      /* Got any kind of Digest response. Check it, it must be valid */
+      struct MHD_DigestAuthUsernameInfo *uname;
+      enum MHD_DigestAuthResult check_res;
+      enum MHD_DigestAuthResult expect_res;
+
+      if (curl_uses_usehash)
+      {
+        if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH != dinfo->uname_type)
+        {
+          fprintf (stderr, "Unexpected 'uname_type'.\n"
+                   "Expected: %d\tRecieved: %d. ",
+                   (int) MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH,
+                   (int) dinfo->uname_type);
+          mhdErrorExitDesc ("Wrong 'uname_type'");
+        }
+        else if (dinfo->userhash_hex_len != userhash_hex_len)
+        {
+          fprintf (stderr, "'userhash_hex_len' does not match.\n"
+                   "Expected: %u\tRecieved: %u. ",
+                   (unsigned) userhash_hex_len,
+                   (unsigned) dinfo->userhash_hex_len);
+          mhdErrorExitDesc ("Wrong 'userhash_hex_len'");
+        }
+        else if (0 != memcmp (dinfo->userhash_hex, userhash_hex,
+                              dinfo->userhash_hex_len))
+        {
+          fprintf (stderr, "'userhash_hex' does not match.\n"
+                   "Expected: '%s'\tRecieved: '%.*s'. ",
+                   userhash_hex,
+                   (int) dinfo->userhash_hex_len,
+                   dinfo->userhash_hex);
+          mhdErrorExitDesc ("Wrong 'userhash_hex'");
+        }
+        else if (NULL == dinfo->userhash_bin)
+          mhdErrorExitDesc ("'userhash_bin' is NULL");
+        else if (0 != memcmp (dinfo->userhash_bin, userhash_bin,
+                              dinfo->username_len / 2))
+          mhdErrorExitDesc ("Wrong 'userhash_bin'");
+        else if (NULL != dinfo->username)
+          mhdErrorExitDesc ("'username' is NOT NULL");
+        else if (0 != dinfo->username_len)
+          mhdErrorExitDesc ("'username_len' is NOT zero");
+      }
+      else
+      {
+        if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != dinfo->uname_type)
+        {
+          fprintf (stderr, "Unexpected 'uname_type'.\n"
+                   "Expected: %d\tRecieved: %d. ",
+                   (int) MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD,
+                   (int) dinfo->uname_type);
+          mhdErrorExitDesc ("Wrong 'uname_type'");
+        }
+        else if (NULL == dinfo->username)
+          mhdErrorExitDesc ("'username' is NULL");
+        else if (dinfo->username_len != strlen (username_ptr))
+        {
+          fprintf (stderr, "'username_len' does not match.\n"
+                   "Expected: %u\tRecieved: %u. ",
+                   (unsigned) strlen (username_ptr),
+                   (unsigned) dinfo->username_len);
+          mhdErrorExitDesc ("Wrong 'username_len'");
+        }
+        else if (0 != memcmp (dinfo->username, username_ptr,
+                              dinfo->username_len))
+        {
+          fprintf (stderr, "'username' does not match.\n"
+                   "Expected: '%s'\tRecieved: '%.*s'. ",
+                   username_ptr,
+                   (int) dinfo->username_len,
+                   dinfo->username);
+          mhdErrorExitDesc ("Wrong 'username'");
+        }
+        else if (NULL != dinfo->userhash_hex)
+          mhdErrorExitDesc ("'userhash_hex' is NOT NULL");
+        else if (0 != dinfo->userhash_hex_len)
+          mhdErrorExitDesc ("'userhash_hex_len' is NOT zero");
+        else if (NULL != dinfo->userhash_bin)
+          mhdErrorExitDesc ("'userhash_bin' is NOT NULL");
+      }
+      if (algo3 != dinfo->algo3)
+      {
+        fprintf (stderr, "Unexpected 'algo3'.\n"
+                 "Expected: %d\tRecieved: %d. ",
+                 (int) algo3,
+                 (int) dinfo->algo3);
+        mhdErrorExitDesc ("Wrong 'algo3'");
+      }
+      if (! test_rfc2069)
+      {
+        if (10 >= dinfo->cnonce_len)
+        {
+          fprintf (stderr, "Unexpected small 'cnonce_len': %ld. ",
+                   (long) dinfo->cnonce_len);
+          mhdErrorExitDesc ("Wrong 'cnonce_len'");
+        }
+      }
+      else
+      {
+        if (0 != dinfo->cnonce_len)
+        {
+          fprintf (stderr, "'cnonce_len' is not zero: %ld. ",
+                   (long) dinfo->cnonce_len);
+          mhdErrorExitDesc ("Wrong 'cnonce_len'");
+        }
+      }
+      if (NULL == dinfo->opaque)
+        mhdErrorExitDesc ("'opaque' is NULL");
+      else if (dinfo->opaque_len != MHD_STATICSTR_LEN_ (OPAQUE_VALUE))
+      {
+        fprintf (stderr, "'opaque_len' does not match.\n"
+                 "Expected: %u\tRecieved: %u. ",
+                 (unsigned) MHD_STATICSTR_LEN_ (OPAQUE_VALUE),
+                 (unsigned) dinfo->opaque_len);
+        mhdErrorExitDesc ("Wrong 'opaque_len'");
+      }
+      else if (0 != memcmp (dinfo->opaque, OPAQUE_VALUE, dinfo->opaque_len))
+      {
+        fprintf (stderr, "'opaque' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%.*s'. ",
+                 OPAQUE_VALUE,
+                 (int) dinfo->opaque_len,
+                 dinfo->opaque);
+        mhdErrorExitDesc ("Wrong 'opaque'");
+      }
+      else if (qop != dinfo->qop)
+      {
+        fprintf (stderr, "Unexpected 'qop'.\n"
+                 "Expected: %d\tRecieved: %d. ",
+                 (int) qop,
+                 (int) dinfo->qop);
+        mhdErrorExitDesc ("Wrong 'qop'");
+      }
+      else if (NULL == dinfo->realm)
+        mhdErrorExitDesc ("'realm' is NULL");
+      else if (dinfo->realm_len != MHD_STATICSTR_LEN_ (REALM_VAL))
+      {
+        fprintf (stderr, "'realm_len' does not match.\n"
+                 "Expected: %u\tRecieved: %u. ",
+                 (unsigned) MHD_STATICSTR_LEN_ (REALM_VAL),
+                 (unsigned) dinfo->realm_len);
+        mhdErrorExitDesc ("Wrong 'realm_len'");
+      }
+      else if (0 != memcmp (dinfo->realm, REALM_VAL, dinfo->realm_len))
+      {
+        fprintf (stderr, "'realm' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%.*s'. ",
+                 OPAQUE_VALUE,
+                 (int) dinfo->realm_len,
+                 dinfo->realm);
+        mhdErrorExitDesc ("Wrong 'realm'");
+      }
+      MHD_free (dinfo);
+
+      uname = MHD_digest_auth_get_username3 (connection);
+      if (NULL == uname)
+        mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL");
+      if (curl_uses_usehash)
+      {
+        if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH != uname->uname_type)
+        {
+          fprintf (stderr, "Unexpected 'uname_type'.\n"
+                   "Expected: %d\tRecieved: %d. ",
+                   (int) MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH,
+                   (int) uname->uname_type);
+          mhdErrorExitDesc ("Wrong 'uname_type'");
+        }
+        else if (uname->userhash_hex_len != userhash_hex_len)
+        {
+          fprintf (stderr, "'userhash_hex_len' does not match.\n"
+                   "Expected: %u\tRecieved: %u. ",
+                   (unsigned) userhash_hex_len,
+                   (unsigned) uname->userhash_hex_len);
+          mhdErrorExitDesc ("Wrong 'userhash_hex_len'");
+        }
+        else if (0 != memcmp (uname->userhash_hex, userhash_hex,
+                              uname->userhash_hex_len))
+        {
+          fprintf (stderr, "'username' does not match.\n"
+                   "Expected: '%s'\tRecieved: '%.*s'. ",
+                   userhash_hex,
+                   (int) uname->userhash_hex_len,
+                   uname->userhash_hex);
+          mhdErrorExitDesc ("Wrong 'userhash_hex'");
+        }
+        else if (NULL == uname->userhash_bin)
+          mhdErrorExitDesc ("'userhash_bin' is NULL");
+        else if (0 != memcmp (uname->userhash_bin, userhash_bin,
+                              uname->username_len / 2))
+          mhdErrorExitDesc ("Wrong 'userhash_bin'");
+        else if (NULL != uname->username)
+          mhdErrorExitDesc ("'username' is NOT NULL");
+        else if (0 != uname->username_len)
+          mhdErrorExitDesc ("'username_len' is NOT zero");
+      }
+      else
+      {
+        if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != uname->uname_type)
+        {
+          fprintf (stderr, "Unexpected 'uname_type'.\n"
+                   "Expected: %d\tRecieved: %d. ",
+                   (int) MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD,
+                   (int) uname->uname_type);
+          mhdErrorExitDesc ("Wrong 'uname_type'");
+        }
+        else if (NULL == uname->username)
+          mhdErrorExitDesc ("'username' is NULL");
+        else if (uname->username_len != strlen (username_ptr))
+        {
+          fprintf (stderr, "'username_len' does not match.\n"
+                   "Expected: %u\tRecieved: %u. ",
+                   (unsigned) strlen (username_ptr),
+                   (unsigned) uname->username_len);
+          mhdErrorExitDesc ("Wrong 'username_len'");
+        }
+        else if (0 != memcmp (uname->username, username_ptr,
+                              uname->username_len))
+        {
+          fprintf (stderr, "'username' does not match.\n"
+                   "Expected: '%s'\tRecieved: '%.*s'. ",
+                   username_ptr,
+                   (int) uname->username_len,
+                   uname->username);
+          mhdErrorExitDesc ("Wrong 'username'");
+        }
+        else if (NULL != uname->userhash_hex)
+          mhdErrorExitDesc ("'userhash_hex' is NOT NULL");
+        else if (0 != uname->userhash_hex_len)
+          mhdErrorExitDesc ("'userhash_hex_len' is NOT zero");
+        else if (NULL != uname->userhash_bin)
+          mhdErrorExitDesc ("'userhash_bin' is NOT NULL");
+      }
+      if (algo3 != uname->algo3)
+      {
+        fprintf (stderr, "Unexpected 'algo3'.\n"
+                 "Expected: %d\tRecieved: %d. ",
+                 (int) algo3,
+                 (int) uname->algo3);
+        mhdErrorExitDesc ("Wrong 'algo3'");
+      }
+      MHD_free (uname);
+
+      if (! test_userdigest)
+        check_res =
+          MHD_digest_auth_check3 (connection, REALM_VAL, username_ptr,
+                                  PASSWORD_VALUE,
+                                  50 * TIMEOUTS_VAL,
+                                  0,
+                                  (enum MHD_DigestAuthMultiQOP) qop,
+                                  (enum MHD_DigestAuthMultiAlgo3) algo3);
+      else
+        check_res =
+          MHD_digest_auth_check_digest3 (connection, REALM_VAL, username_ptr,
+                                         userdigest_bin, userdigest_bin_size,
+                                         50 * TIMEOUTS_VAL,
+                                         0,
+                                         (enum MHD_DigestAuthMultiQOP) qop,
+                                         (enum MHD_DigestAuthMultiAlgo3) algo3);
+
+      if (test_rfc2069)
+      {
+        if ((0 != tr_p->uri_num) && (1 == tr_p->req_num))
+          expect_res = MHD_DAUTH_NONCE_STALE;
+        else
+          expect_res = MHD_DAUTH_OK;
+      }
+      else if (test_bind_uri)
+      {
+        if ((0 != tr_p->uri_num) && (1 == tr_p->req_num))
+          expect_res = MHD_DAUTH_NONCE_OTHER_COND;
+        else
+          expect_res = MHD_DAUTH_OK;
+      }
+      else
+        expect_res = MHD_DAUTH_OK;
+
+      switch (check_res)
+      {
+      /* Conditionally valid results */
+      case MHD_DAUTH_OK:
+        if (expect_res == MHD_DAUTH_OK)
+        {
+          if (verbose)
+            printf ("Got valid auth check result: MHD_DAUTH_OK.\n");
+        }
+        else
+          mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                            "MHD_DAUTH_OK");
+        break;
+      case MHD_DAUTH_NONCE_STALE:
+        if (expect_res == MHD_DAUTH_NONCE_STALE)
+        {
+          if (verbose)
+            printf ("Got expected auth check result: MHD_DAUTH_NONCE_STALE.\n");
+        }
+        else
+          mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                            "MHD_DAUTH_NONCE_STALE");
+        break;
+      case MHD_DAUTH_NONCE_OTHER_COND:
+        if (expect_res == MHD_DAUTH_NONCE_OTHER_COND)
+        {
+          if (verbose)
+            printf ("Got expected auth check result: "
+                    "MHD_DAUTH_NONCE_OTHER_COND.\n");
+        }
+        else
+          mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                            "MHD_DAUTH_NONCE_OTHER_COND");
+        break;
+      /* Invalid results */
+      case MHD_DAUTH_NONCE_WRONG:
+        mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                          "MHD_DAUTH_NONCE_WRONG");
+        break;
+      case MHD_DAUTH_ERROR:
+        externalErrorExitDesc ("General error returned " \
+                               "by 'MHD_digest_auth_check[_digest]3()'");
+        break;
+      case MHD_DAUTH_WRONG_USERNAME:
+        mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                          "MHD_DAUTH_WRONG_USERNAME");
+        break;
+      case MHD_DAUTH_RESPONSE_WRONG:
+        mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                          "MHD_DAUTH_RESPONSE_WRONG");
+        break;
+      case MHD_DAUTH_WRONG_HEADER:
+        mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \
+                          "MHD_DAUTH_WRONG_HEADER");
+        break;
+      case MHD_DAUTH_WRONG_REALM:
+      case MHD_DAUTH_WRONG_URI:
+      case MHD_DAUTH_WRONG_QOP:
+      case MHD_DAUTH_WRONG_ALGO:
+      case MHD_DAUTH_TOO_LARGE:
+        fprintf (stderr, "'MHD_digest_auth_check[_digest]3()' returned "
+                 "unexpected result: %d. ",
+                 check_res);
+        mhdErrorExitDesc ("Wrong returned code");
+        break;
+      default:
+        fprintf (stderr, "'MHD_digest_auth_check[_digest]3()' returned "
+                 "impossible result code: %d. ",
+                 check_res);
+        mhdErrorExitDesc ("Impossible returned code");
+      }
+      fflush (stderr);
+      fflush (stdout);
+
+      if (MHD_DAUTH_OK == check_res)
+      {
+        response =
+          MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                                  (const void *) PAGE);
+        if (NULL == response)
+          mhdErrorExitDesc ("Response creation failed");
+
+        if (MHD_YES !=
+            MHD_queue_response (connection, MHD_HTTP_OK, response))
+          mhdErrorExitDesc ("'MHD_queue_response()' failed");
+      }
+      else if ((MHD_DAUTH_NONCE_STALE == check_res) ||
+               (MHD_DAUTH_NONCE_OTHER_COND == check_res))
+      {
+        response =
+          MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                                  (const void *) DENIED);
+        if (NULL == response)
+          mhdErrorExitDesc ("Response creation failed");
+        res =
+          MHD_queue_auth_required_response3 (connection, REALM_VAL,
+                                             OPAQUE_VALUE,
+                                             "/", response, 1,
+                                             (enum MHD_DigestAuthMultiQOP) qop,
+                                             (enum MHD_DigestAuthMultiAlgo3)
+                                             algo3,
+                                             test_userhash, 0);
+        if (MHD_YES != res)
+          mhdErrorExitDesc ("'MHD_queue_auth_required_response3()' failed");
+      }
+      else
+        externalErrorExitDesc ("Wrong 'check_res' value");
+    }
+    else
+    {
+      /* No Digest auth header */
+      if ((1 != tr_p->req_num) || (0 != tr_p->uri_num))
+      {
+        fprintf (stderr, "Received request number %u for URI number %u "
+                 "without Digest Authorisation header. ",
+                 tr_p->req_num, tr_p->uri_num + 1);
+        mhdErrorExitDesc ("Wrong requests sequence");
+      }
+
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                                (const void *) DENIED);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+      res =
+        MHD_queue_auth_required_response3 (connection, REALM_VAL, OPAQUE_VALUE,
+                                           "/", response, 0,
+                                           (enum MHD_DigestAuthMultiQOP) qop,
+                                           (enum MHD_DigestAuthMultiAlgo3) algo3,
+                                           test_userhash, 0);
+      if (MHD_YES != res)
+        mhdErrorExitDesc ("'MHD_queue_auth_required_response3()' failed");
+    }
+  }
+  else if (2 == test_oldapi)
+  {
+    /* Use old API v2 */
+    char *username;
+    int check_res;
+    int expect_res;
+
+    username = MHD_digest_auth_get_username (connection);
+    if (NULL != username)
+    { /* Has a valid username in header */
+      if (0 != strcmp (username, username_ptr))
+      {
+        fprintf (stderr, "'username' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%s'. ",
+                 username_ptr,
+                 username);
+        mhdErrorExitDesc ("Wrong 'username'");
+      }
+      MHD_free (username);
+
+      if (! test_userdigest)
+        check_res =
+          MHD_digest_auth_check2 (connection, REALM_VAL, username_ptr,
+                                  PASSWORD_VALUE,
+                                  50 * TIMEOUTS_VAL,
+                                  test_sha256 ?
+                                  MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5);
+      else
+        check_res =
+          MHD_digest_auth_check_digest2 (connection, REALM_VAL, username_ptr,
+                                         userdigest_bin, userdigest_bin_size,
+                                         50 * TIMEOUTS_VAL,
+                                         test_sha256 ?
+                                         MHD_DIGEST_ALG_SHA256 :
+                                         MHD_DIGEST_ALG_MD5);
+
+      if (test_bind_uri)
+      {
+        if ((0 != tr_p->uri_num) && (1 == tr_p->req_num))
+          expect_res = MHD_INVALID_NONCE;
+        else
+          expect_res = MHD_YES;
+      }
+      else
+        expect_res = MHD_YES;
+
+      if (expect_res != check_res)
+      {
+        fprintf (stderr, "'MHD_digest_auth_check[_digest]2()' returned "
+                 "unexpected result '%d', while expected is '%d. ",
+                 check_res, expect_res);
+        mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check[_digest]2()' result");
+      }
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                                (const void *) PAGE);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+
+      if (MHD_YES == expect_res)
+      {
+        if (MHD_YES !=
+            MHD_queue_response (connection, MHD_HTTP_OK, response))
+          mhdErrorExitDesc ("'MHD_queue_response()' failed");
+      }
+      else if (MHD_INVALID_NONCE == expect_res)
+      {
+        if (MHD_YES !=
+            MHD_queue_auth_fail_response2 (connection, REALM_VAL, OPAQUE_VALUE,
+                                           response, 1,
+                                           test_sha256 ?
+                                           MHD_DIGEST_ALG_SHA256 :
+                                           MHD_DIGEST_ALG_MD5))
+          mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed");
+      }
+      else
+        externalErrorExitDesc ("Wrong 'check_res' value");
+    }
+    else
+    {
+      /* Has no valid username in header */
+      if ((1 != tr_p->req_num) || (0 != tr_p->uri_num))
+      {
+        fprintf (stderr, "Received request number %u for URI number %u "
+                 "without Digest Authorisation header. ",
+                 tr_p->req_num, tr_p->uri_num + 1);
+        mhdErrorExitDesc ("Wrong requests sequence");
+      }
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                                (const void *) DENIED);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+
+      res = MHD_queue_auth_fail_response2 (connection, REALM_VAL, OPAQUE_VALUE,
+                                           response, 0,
+                                           test_sha256 ?
+                                           MHD_DIGEST_ALG_SHA256 :
+                                           MHD_DIGEST_ALG_MD5);
+      if (MHD_YES != res)
+        mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed");
+    }
+  }
+  else if (1 == test_oldapi)
+  {
+    /* Use old API v1 */
+    char *username;
+    int check_res;
+    int expect_res;
+
+    username = MHD_digest_auth_get_username (connection);
+    if (NULL != username)
+    { /* Has a valid username in header */
+      if (0 != strcmp (username, username_ptr))
+      {
+        fprintf (stderr, "'username' does not match.\n"
+                 "Expected: '%s'\tRecieved: '%s'. ",
+                 username_ptr,
+                 username);
+        mhdErrorExitDesc ("Wrong 'username'");
+      }
+      MHD_free (username);
+
+      if (! test_userdigest)
+        check_res =
+          MHD_digest_auth_check (connection, REALM_VAL, username_ptr,
+                                 PASSWORD_VALUE,
+                                 50 * TIMEOUTS_VAL);
+      else
+        check_res =
+          MHD_digest_auth_check_digest (connection, REALM_VAL, username_ptr,
+                                        userdigest_bin,
+                                        50 * TIMEOUTS_VAL);
+
+      if (test_bind_uri)
+      {
+        if ((0 != tr_p->uri_num) && (1 == tr_p->req_num))
+          expect_res = MHD_INVALID_NONCE;
+        else
+          expect_res = MHD_YES;
+      }
+      else
+        expect_res = MHD_YES;
+
+      if (expect_res != check_res)
+      {
+        fprintf (stderr, "'MHD_digest_auth_check[_digest]()' returned "
+                 "unexpected result '%d', while expected is '%d. ",
+                 check_res, expect_res);
+        mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check[_digest]()' result");
+      }
+
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                                (const void *) PAGE);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+
+      if (MHD_YES == expect_res)
+      {
+        if (MHD_YES !=
+            MHD_queue_response (connection, MHD_HTTP_OK, response))
+          mhdErrorExitDesc ("'MHD_queue_response()' failed");
+      }
+      else if (MHD_INVALID_NONCE == expect_res)
+      {
+        if (MHD_YES !=
+            MHD_queue_auth_fail_response (connection, REALM_VAL, OPAQUE_VALUE,
+                                          response, 1))
+          mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed");
+      }
+      else
+        externalErrorExitDesc ("Wrong 'check_res' value");
+    }
+    else
+    {
+      /* Has no valid username in header */
+      if ((1 != tr_p->req_num) || (0 != tr_p->uri_num))
+      {
+        fprintf (stderr, "Received request number %u for URI number %u "
+                 "without Digest Authorisation header. ",
+                 tr_p->req_num, tr_p->uri_num + 1);
+        mhdErrorExitDesc ("Wrong requests sequence");
+      }
+      response =
+        MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                                (const void *) DENIED);
+      if (NULL == response)
+        mhdErrorExitDesc ("Response creation failed");
+
+      res = MHD_queue_auth_fail_response (connection, REALM_VAL, OPAQUE_VALUE,
+                                          response, 0);
+      if (MHD_YES != res)
+        mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed");
+    }
+  }
+  else
+    externalErrorExitDesc ("Wrong 'test_oldapi' value");
+
+  MHD_destroy_response (response);
+  return MHD_YES;
+}
+
+
+/**
+ *
+ * @param c the CURL handle to use
+ * @param port the port to set
+ * @param uri_num the number of URI, should be 0, 1 or 2
+ */
+static void
+setCURL_rq_path (CURL *c, uint16_t port, unsigned int uri_num)
+{
+  const char *req_path;
+  char uri[512];
+  int res;
+
+  if (0 == uri_num)
+    req_path = MHD_URI_BASE_PATH;
+  else if (1 == uri_num)
+    req_path = MHD_URI_BASE_PATH2;
+  else
+    req_path = MHD_URI_BASE_PATH3;
+  /* A workaround for some old libcurl versions, which ignore the specified
+   * port by CURLOPT_PORT when authorisation is used. */
+  res = snprintf (uri, (sizeof(uri) / sizeof(uri[0])),
+                  "http://127.0.0.1:%u%s", (unsigned int) port,
+                  req_path);
+  if ((0 >= res) || ((sizeof(uri) / sizeof(uri[0])) <= (size_t) res))
+    externalErrorExitDesc ("Cannot form request URL");
+
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, uri))
+    libcurlErrorExitDesc ("Cannot set request URL");
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     CURL_HTTP_VERSION_1_1)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH,
+                                     (long) CURLAUTH_DIGEST)) ||
+#if CURL_AT_LEAST_VERSION (7,19,1)
+      /* Need version 7.19.1 for separate username and password */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERNAME, username_ptr)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PASSWORD, PASSWORD_VALUE)) ||
+#endif /* CURL_AT_LEAST_VERSION(7,19,1) */
+#ifdef _DEBUG
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) ||
+#endif /* _DEBUG */
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  setCURL_rq_path (c, port, 0);
+
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  if (NULL != *multi_reuse)
+    multi = *multi_reuse;
+  else
+  {
+    multi = curl_multi_init ();
+    if (multi == NULL)
+      libcurlErrorExitDesc ("curl_multi_init() failed");
+    *multi_reuse = multi;
+  }
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 200000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (200);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/**
+ * Check request result
+ * @param curl_code the CURL easy return code
+ * @param pcbc the pointer struct CBC
+ * @return non-zero if success, zero if failed
+ */
+static unsigned int
+check_result (CURLcode curl_code, CURL *c, struct CBC *pcbc)
+{
+  long code;
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
+    libcurlErrorExit ();
+
+  if (MHD_HTTP_OK != code)
+  {
+    fprintf (stderr, "Request returned wrong code: %ld.\n",
+             code);
+    return 0;
+  }
+
+  if (CURLE_OK != curl_code)
+  {
+    fflush (stdout);
+    if (0 != libcurl_errbuf[0])
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               curl_easy_strerror (curl_code),
+               libcurl_errbuf);
+    else
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n",
+               curl_easy_strerror (curl_code));
+    fflush (stderr);
+    return 0;
+  }
+
+  if (pcbc->pos != MHD_STATICSTR_LEN_ (PAGE))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf,
+             (unsigned) MHD_STATICSTR_LEN_ (PAGE));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ",
+             (int) pcbc->pos, pcbc->buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
+  return 1;
+}
+
+
+static unsigned int
+testDigestAuth (void)
+{
+  unsigned int dauth_nonce_bind;
+  struct MHD_Daemon *d;
+  uint16_t port;
+  struct CBC cbc;
+  struct req_track rq_tr;
+  char buf[2048];
+  CURL *c;
+  CURLM *multi_reuse;
+  int failed = 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 4210;
+
+  if (1)
+  {
+    uint8_t salt[8]; /* Use local variable to test MHD "copy" function */
+    if (! gen_good_rnd (salt, sizeof(salt)))
+    {
+      fprintf (stderr, "WARNING: the random buffer (used as salt value) is not "
+               "initialised completely, nonce generation may be "
+               "predictable in this test.\n");
+      fflush (stderr);
+    }
+
+    dauth_nonce_bind = MHD_DAUTH_BIND_NONCE_NONE;
+    if (test_bind_all)
+      dauth_nonce_bind |=
+        (MHD_DAUTH_BIND_NONCE_CLIENT_IP | MHD_DAUTH_BIND_NONCE_REALM);
+    if (test_bind_uri)
+      dauth_nonce_bind |= MHD_DAUTH_BIND_NONCE_URI_PARAMS;
+
+    d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                          port, NULL, NULL,
+                          &ahc_echo, &rq_tr,
+                          MHD_OPTION_DIGEST_AUTH_RANDOM_COPY,
+                          sizeof (salt), salt,
+                          MHD_OPTION_NONCE_NC_SIZE, 300,
+                          MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE,
+                          dauth_nonce_bind,
+                          MHD_OPTION_END);
+  }
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = dinfo->port;
+  }
+
+  /* First request */
+  rq_tr.req_num = 0;
+  rq_tr.uri_num = 0;
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  cbc.pos = 0;
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port);
+  multi_reuse = NULL;
+  /* First request */
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got first expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "First request FAILED.\n");
+    failed = 1;
+  }
+  cbc.pos = 0; /* Reset buffer position */
+  rq_tr.req_num = 0;
+  /* Second request */
+  setCURL_rq_path (c, port, ++rq_tr.uri_num);
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got second expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "Second request FAILED.\n");
+    failed = 1;
+  }
+  cbc.pos = 0; /* Reset buffer position */
+  rq_tr.req_num = 0;
+  /* Third request */
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+  multi_reuse = NULL; /* Force new connection */
+  setCURL_rq_path (c, port, ++rq_tr.uri_num);
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got third expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "Third request FAILED.\n");
+    failed = 1;
+  }
+
+  curl_easy_cleanup (c);
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+
+  MHD_stop_daemon (d);
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+#if ! CURL_AT_LEAST_VERSION (7,19,1)
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+  /* Need version 7.19.1 or newer for separate username and password */
+  fprintf (stderr, "Required libcurl at least version 7.19.1"
+           " to run this test.\n");
+  return 77;
+#else  /* CURL_AT_LEAST_VERSION(7,19,1) */
+  unsigned int errorCount = 0;
+  const curl_version_info_data *const curl_info =
+    curl_version_info (CURLVERSION_NOW);
+  int curl_sspi;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+  /* Test type and test parameters */
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  test_oldapi = 0;
+  if (has_in_name (argv[0], "_oldapi1"))
+    test_oldapi = 1;
+  if (has_in_name (argv[0], "_oldapi2"))
+    test_oldapi = 2;
+  test_userhash = has_in_name (argv[0], "_userhash");
+  test_userdigest = has_in_name (argv[0], "_userdigest");
+  test_sha256 = has_in_name (argv[0], "_sha256");
+  test_rfc2069 = has_in_name (argv[0], "_rfc2069");
+  test_bind_all = has_in_name (argv[0], "_bind_all");
+  test_bind_uri = has_in_name (argv[0], "_bind_uri");
+
+  /* Wrong test types combinations */
+  if (1 == test_oldapi)
+  {
+    if (test_sha256)
+      return 99;
+  }
+  if (test_oldapi)
+  {
+    if (test_userhash || test_rfc2069)
+      return 99;
+  }
+  if (test_rfc2069)
+  {
+    if (test_userhash)
+      return 99;
+  }
+
+  /* Curl version and known bugs checks */
+  curl_sspi = 0;
+#ifdef CURL_VERSION_SSPI
+  if (0 != (curl_info->features & CURL_VERSION_SSPI))
+    curl_sspi = 1;
+#endif /* CURL_VERSION_SSPI */
+
+  if ((CURL_VERSION_BITS (7,63,0) > curl_info->version_num) &&
+      (CURL_VERSION_BITS (7,62,0) <= curl_info->version_num) )
+  {
+    fprintf (stderr, "libcurl version 7.62.x has bug in processing "
+             "URI with GET arguments for Digest Auth.\n");
+    fprintf (stderr, "This test with libcurl %u.%u.%u cannot be performed.\n",
+             0xFF & (curl_info->version_num >> 16),
+             0xFF & (curl_info->version_num >> 8),
+             0xFF & (curl_info->version_num >> 0));
+    return 77;
+  }
+  if (test_userhash)
+  {
+    if (curl_sspi)
+    {
+      printf ("WARNING: Windows SSPI API does not support 'userhash'.\n");
+      printf ("This test just checks Digest Auth compatibility with "
+              "the clients without 'userhash' support "
+              "when 'userhash=true' is specified by MHD.\n");
+      curl_uses_usehash = 0;
+    }
+    else if (CURL_VERSION_BITS (7,57,0) > curl_info->version_num)
+    {
+      printf ("WARNING: libcurl before version 7.57.0 does not "
+              "support 'userhash'.\n");
+      printf ("This test just checks Digest Auth compatibility with "
+              "libcurl version %u.%u.%u without 'userhash' support "
+              "when 'userhash=true' is specified by MHD.\n",
+              0xFF & (curl_info->version_num >> 16),
+              0xFF & (curl_info->version_num >> 8),
+              0xFF & (curl_info->version_num >> 0));
+      curl_uses_usehash = 0;
+    }
+    else if (CURL_VERSION_BITS (7,81,0) > curl_info->version_num)
+    {
+      fprintf (stderr, "Required libcurl at least version 7.81.0 "
+               "to run this test with userhash.\n");
+      fprintf (stderr, "This libcurl version %u.%u.%u has broken digest "
+               "calculation when userhash is used.\n",
+               0xFF & (curl_info->version_num >> 16),
+               0xFF & (curl_info->version_num >> 8),
+               0xFF & (curl_info->version_num >> 0));
+      return 77;
+    }
+    else
+      curl_uses_usehash = ! 0;
+  }
+  else
+    curl_uses_usehash = 0;
+
+  if (test_sha256)
+  {
+    if (curl_sspi)
+    {
+      fprintf (stderr, "Windows SSPI API does not support SHA-256 digests.\n");
+      return 77;
+    }
+    else if (CURL_VERSION_BITS (7,57,0) > curl_info->version_num)
+    {
+      fprintf (stderr, "Required libcurl at least version 7.57.0 "
+               "to run this test with SHA-256.\n");
+      fprintf (stderr, "This libcurl version %u.%u.%u "
+               "does not support SHA-256.\n",
+               0xFF & (curl_info->version_num >> 16),
+               0xFF & (curl_info->version_num >> 8),
+               0xFF & (curl_info->version_num >> 0));
+      return 77;
+    }
+  }
+
+  test_global_init ();
+
+  errorCount += testDigestAuth ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  test_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+#endif /* CURL_AT_LEAST_VERSION(7,19,1) */
+}
diff --git a/src/testcurl/test_digestauth_concurrent.c b/src/testcurl/test_digestauth_concurrent.c
new file mode 100644
index 0000000..664b5cb
--- /dev/null
+++ b/src/testcurl/test_digestauth_concurrent.c
@@ -0,0 +1,688 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_digestauth_concurrent.c
+ * @brief  Testcase for libmicrohttpd concurrent Digest Authorisation
+ * @author Amr Ali
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
+
+#ifndef WINDOWS
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#include <pthread.h>
+
+#include "mhd_has_param.h"
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \
+                       __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+/* Not actually used in this test */
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+#if 0
+/* Function unused in this test */
+static void
+_checkCURLE_OK_func (CURLcode code, const char *curlFunc,
+                     const char *funcName, int lineNum)
+{
+  if (CURLE_OK == code)
+    return;
+
+  fflush (stdout);
+  if ((NULL != curlFunc) && (0 != curlFunc[0]))
+    fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
+             curl_easy_strerror (code));
+  else
+    fprintf (stderr, "libcurl function call resulted in '%s'",
+             curl_easy_strerror (code));
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (9);
+}
+
+
+#endif
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+#define MHD_URI_BASE_PATH "/bar%20foo?key=value"
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
+
+#define DENIED \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
+
+#define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4"
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+static int verbose;
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    mhdErrorExitDesc ("Wrong too large data");       /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  struct MHD_Response *response;
+  char *username;
+  const char *password = "testpass";
+  const char *realm = "test@example.com";
+  enum MHD_Result ret;
+  enum MHD_DigestAuthResult ret_e;
+  static int already_called_marker;
+  (void) cls; (void) url;                         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls;        /* Unused. Silent compiler warning. */
+
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  username = MHD_digest_auth_get_username (connection);
+  if ( (username == NULL) ||
+       (0 != strcmp (username, "testuser")) )
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    if (NULL == response)
+      mhdErrorExitDesc ("MHD_create_response_from_buffer failed");
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    if (MHD_YES != ret)
+      mhdErrorExitDesc ("MHD_queue_auth_fail_response2 failed");
+    MHD_destroy_response (response);
+    return ret;
+  }
+  ret_e = MHD_digest_auth_check3 (connection,
+                                  realm,
+                                  username,
+                                  password,
+                                  50 * TIMEOUTS_VAL,
+                                  0, MHD_DIGEST_AUTH_MULT_QOP_AUTH,
+                                  MHD_DIGEST_AUTH_MULT_ALGO3_MD5);
+  MHD_free (username);
+  if (ret_e != MHD_DAUTH_OK)
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    if (NULL == response)
+      mhdErrorExitDesc ("MHD_create_response_from_buffer() failed");
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         (MHD_DAUTH_NONCE_STALE == ret_e) ?
+                                         MHD_YES : MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    if (MHD_YES != ret)
+      mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed");
+    MHD_destroy_response (response);
+    return ret;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                     PAGE);
+  if (NULL == response)
+    mhdErrorExitDesc ("MHD_create_response_from_buffer() failed");
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed");
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port, char *errbuf)
+{
+  CURL *c;
+  char url[512];
+
+  if (1)
+  {
+    int res;
+    /* A workaround for some old libcurl versions, which ignore the specified
+     * port by CURLOPT_PORT when digest authorisation is used. */
+    res = snprintf (url, (sizeof(url) / sizeof(url[0])),
+                    "http://127.0.0.1:%u%s", (unsigned int) port,
+                    MHD_URI_BASE_PATH);
+    if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res))
+      externalErrorExitDesc ("Cannot form request URL");
+  }
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     CURL_HTTP_VERSION_1_1)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+#ifdef _DEBUG
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) ||
+#endif /* _DEBUG */
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD,
+                                     "testuser:testpass")))
+    libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed");
+  return c;
+}
+
+
+static void
+getRnd (void *buf, size_t size)
+{
+#ifndef WINDOWS
+  int fd;
+  size_t off = 0;
+
+  fd = open ("/dev/urandom",
+             O_RDONLY);
+  if (-1 == fd)
+    externalErrorExitDesc ("Failed to open '/dev/urandom'");
+
+  do
+  {
+    ssize_t res;
+    res = read (fd, ((uint8_t *) buf) + off, size - off);
+    if (0 > res)
+      externalErrorExitDesc ("Failed to read '/dev/urandom'");
+    off += (size_t) res;
+  } while (off < size);
+  (void) close (fd);
+#else
+  HCRYPTPROV cc;
+  BOOL b;
+
+  b = CryptAcquireContext (&cc,
+                           NULL,
+                           NULL,
+                           PROV_RSA_FULL,
+                           CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
+  if (b == 0)
+    externalErrorExitDesc ("CryptAcquireContext() failed");
+  b = CryptGenRandom (cc, (DWORD) size, (BYTE *) buf);
+  if (b == 0)
+    externalErrorExitDesc ("CryptGenRandom() failed");
+  CryptReleaseContext (cc, 0);
+#endif /* ! WINDOWS */
+}
+
+
+struct curlWokerInfo
+{
+  int workerNumber;
+  struct CBC cbc;
+  pthread_t pid;
+  /**
+   * The libcurl handle to run in thread
+   */
+  CURL *c;
+  char *libcurl_errbuf;
+  /**
+   * Non-zero if worker is finished
+   */
+  volatile int finished;
+  /**
+   * The number of successful worker results
+   */
+  volatile unsigned int success;
+};
+
+
+static void *
+worker_func (void *param)
+{
+  struct curlWokerInfo *const w = (struct curlWokerInfo *) param;
+  CURLcode req_result;
+  if (NULL == w)
+    externalErrorExit ();
+
+  req_result = curl_easy_perform (w->c);
+  if (CURLE_OK != req_result)
+  {
+    if (0 != w->libcurl_errbuf[0])
+      fprintf (stderr, "Worker %d: first request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               w->workerNumber, curl_easy_strerror (req_result),
+               w->libcurl_errbuf);
+    else
+      fprintf (stderr, "Worker %d: first request failed. "
+               "libcurl error: '%s'.\n",
+               w->workerNumber, curl_easy_strerror (req_result));
+  }
+  else
+  {
+    if (w->cbc.pos != strlen (PAGE))
+    {
+      fprintf (stderr, "Worker %d: Got %u bytes ('%.*s'), expected %u bytes. ",
+               w->workerNumber,
+               (unsigned) w->cbc.pos, (int) w->cbc.pos, w->cbc.buf,
+               (unsigned) strlen (MHD_URI_BASE_PATH));
+      mhdErrorExitDesc ("Wrong returned data length");
+    }
+    if (0 != strncmp (PAGE, w->cbc.buf, strlen (PAGE)))
+    {
+      fprintf (stderr, "Worker %d: Got invalid response '%.*s'. ",
+               w->workerNumber,
+               (int) w->cbc.pos, w->cbc.buf);
+      mhdErrorExitDesc ("Wrong returned data");
+    }
+    if (verbose)
+      printf ("Worker %d: first request successful.\n", w->workerNumber);
+    w->success++;
+  }
+#ifdef _DEBUG
+  fflush (stderr);
+  fflush (stdout);
+#endif /* _DEBUG */
+
+  /* Second request */
+  w->cbc.pos = 0;
+  req_result = curl_easy_perform (w->c);
+  if (CURLE_OK != req_result)
+  {
+    if (0 != w->libcurl_errbuf[0])
+      fprintf (stderr, "Worker %d: second request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               w->workerNumber, curl_easy_strerror (req_result),
+               w->libcurl_errbuf);
+    else
+      fprintf (stderr, "Worker %d: second request failed. "
+               "libcurl error: '%s'.\n",
+               w->workerNumber, curl_easy_strerror (req_result));
+  }
+  else
+  {
+    if (w->cbc.pos != strlen (PAGE))
+    {
+      fprintf (stderr, "Worker %d: Got %u bytes ('%.*s'), expected %u bytes. ",
+               w->workerNumber,
+               (unsigned) w->cbc.pos, (int) w->cbc.pos, w->cbc.buf,
+               (unsigned) strlen (MHD_URI_BASE_PATH));
+      mhdErrorExitDesc ("Wrong returned data length");
+    }
+    if (0 != strncmp (PAGE, w->cbc.buf, strlen (PAGE)))
+    {
+      fprintf (stderr, "Worker %d: Got invalid response '%.*s'. ",
+               w->workerNumber,
+               (int) w->cbc.pos, w->cbc.buf);
+      mhdErrorExitDesc ("Wrong returned data");
+    }
+    if (verbose)
+      printf ("Worker %d: second request successful.\n", w->workerNumber);
+    w->success++;
+  }
+#ifdef _DEBUG
+  fflush (stderr);
+  fflush (stdout);
+#endif /* _DEBUG */
+
+  w->finished = ! 0;
+  return NULL;
+}
+
+
+#define CLIENT_BUF_SIZE 2048
+
+static unsigned int
+testDigestAuth (void)
+{
+  struct MHD_Daemon *d;
+  char rnd[8];
+  uint16_t port;
+  size_t i;
+  /* Run three workers in parallel so at least two workers would start within
+   * the same monotonic clock second.*/
+  struct curlWokerInfo workers[3];
+  unsigned int ret;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 4200;
+
+  getRnd (rnd, sizeof(rnd));
+
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd,
+                        MHD_OPTION_NONCE_NC_SIZE, 300,
+                        MHD_OPTION_THREAD_POOL_SIZE,
+                        (unsigned int) (sizeof(workers) / sizeof(workers[0])),
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = dinfo->port;
+  }
+
+  /* Initialise all workers */
+  for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++)
+  {
+    struct curlWokerInfo *const w = workers + i;
+    w->workerNumber = (int) i + 1; /* Use 1-based numbering */
+    w->cbc.buf = malloc (CLIENT_BUF_SIZE);
+    if (NULL == w->cbc.buf)
+      externalErrorExitDesc ("malloc() failed");
+    w->cbc.size = CLIENT_BUF_SIZE;
+    w->cbc.pos = 0;
+    w->libcurl_errbuf = malloc (CURL_ERROR_SIZE);
+    if (NULL == w->libcurl_errbuf)
+      externalErrorExitDesc ("malloc() failed");
+    w->libcurl_errbuf[0] = 0;
+    w->c = setupCURL (&w->cbc, port, w->libcurl_errbuf);
+    w->finished = 0;
+    w->success = 0;
+  }
+
+  /* Fire already initialised workers */
+  for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++)
+  {
+    struct curlWokerInfo *const w = workers + i;
+    if (0 != pthread_create (&w->pid, NULL, &worker_func, w))
+      externalErrorExitDesc ("pthread_create() failed");
+  }
+
+  /* Collect results, cleanup workers */
+  ret = 0;
+  for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++)
+  {
+    struct curlWokerInfo *const w = workers + i;
+    if (0 != pthread_join (w->pid, NULL))
+      externalErrorExitDesc ("pthread_join() failed");
+    curl_easy_cleanup (w->c);
+    free (w->libcurl_errbuf);
+    free (w->cbc.buf);
+    if (! w->finished)
+      externalErrorExitDesc ("The worker thread did't signal 'finished' state");
+    ret += 2 - w->success;
+  }
+
+  MHD_stop_daemon (d);
+  return ret;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+#if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62)
+  if (1)
+  {
+    fprintf (stderr, "libcurl version 7.62.x has bug in processing"
+             "URI with GET arguments for Digest Auth.\n");
+    fprintf (stderr, "This test cannot be performed.\n");
+    exit (77);
+  }
+#endif /* libcurl version 7.62.x */
+
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  errorCount += testDigestAuth ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_digestauth_emu_ext.c b/src/testcurl/test_digestauth_emu_ext.c
new file mode 100644
index 0000000..092a2d5
--- /dev/null
+++ b/src/testcurl/test_digestauth_emu_ext.c
@@ -0,0 +1,880 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_digest_emu_ext.c
+ * @brief  Testcase for MHD Digest Authorisation client's header parsing
+ * @author Karlson2k (Evgeny Grin)
+ *
+ * libcurl does not support extended notation for username, so this test
+ * "emulates" client request will all valid fields except nonce, cnonce and
+ * response (however syntactically these fields valid as well).
+ */
+
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifndef WINDOWS
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#include "mhd_has_param.h"
+#include "mhd_has_in_name.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+/* Not actually used in this test */
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+#if 0
+/* Function unused in this test */
+static void
+_checkCURLE_OK_func (CURLcode code, const char *curlFunc,
+                     const char *funcName, int lineNum)
+{
+  if (CURLE_OK == code)
+    return;
+
+  fflush (stdout);
+  if ((NULL != curlFunc) && (0 != curlFunc[0]))
+    fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
+             curl_easy_strerror (code));
+  else
+    fprintf (stderr, "libcurl function call resulted in '%s'",
+             curl_easy_strerror (code));
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (9);
+}
+
+
+#endif
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 10
+
+#define MHD_URI_BASE_PATH "/bar%20foo?key=value"
+
+#define REALM "TestRealm"
+/* "titkos szuperügynök" in UTF-8 */
+#define USERNAME "titkos szuper" "\xC3\xBC" "gyn" "\xC3\xB6" "k"
+/* percent-encoded username */
+#define USERNAME_PCTENC "titkos%20szuper%C3%BCgyn%C3%B6k"
+#define PASSWORD_VALUE "fake pass"
+#define OPAQUE_VALUE "opaque-content"
+#define NONCE_EMU "badbadbadbadbadbadbadbadbadbadbadbadbadbadba"
+#define CNONCE_EMU "utututututututututututututututututututututs="
+#define RESPONSE_EMU "badbadbadbadbadbadbadbadbadbadba"
+
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo page</title>" \
+  "</head><body>Access granted</body></html>"
+
+#define DENIED \
+  "<html><head><title>libmicrohttpd - Access denied</title>" \
+  "</head><body>Access denied</body></html>"
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+/* Global parameters */
+static int verbose;
+static int oldapi;
+
+/* Static helper variables */
+struct curl_slist *curl_headers;
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+
+  curl_headers = NULL;
+  curl_headers =
+    curl_slist_append (curl_headers,
+                       "Authorization: "
+                       "Digest username*=UTF-8''" USERNAME_PCTENC ", "
+                       "realm=\"" REALM "\", "
+                       "nonce=\"" NONCE_EMU "\", "
+                       "uri=\"" MHD_URI_BASE_PATH "\", "
+                       "cnonce=\"" CNONCE_EMU "\", "
+                       "nc=00000001, "
+                       "qop=auth, "
+                       "response=\"" RESPONSE_EMU "\", "
+                       "opaque=\"" OPAQUE_VALUE "\", "
+                       "algorithm=MD5");
+  if (NULL == curl_headers)
+    externalErrorExit ();
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_slist_free_all (curl_headers);
+  curl_headers = NULL;
+  curl_global_cleanup ();
+}
+
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    mhdErrorExitDesc ("Wrong too large data");       /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  static int already_called_marker;
+  (void) cls; (void) url;         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size;        /* Unused. Silent compiler warning. */
+
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))
+    mhdErrorExitDesc ("Unexpected HTTP method");
+
+  if (! oldapi)
+  {
+    struct MHD_DigestAuthUsernameInfo *creds;
+    struct MHD_DigestAuthInfo *dinfo;
+    enum MHD_DigestAuthResult check_res;
+
+    creds = MHD_digest_auth_get_username3 (connection);
+    if (NULL == creds)
+      mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL");
+    else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != creds->uname_type)
+    {
+      fprintf (stderr, "Unexpected 'uname_type'.\n"
+               "Expected: %d\tRecieved: %d. ",
+               (int) MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED,
+               (int) creds->uname_type);
+      mhdErrorExitDesc ("Wrong 'uname_type'");
+    }
+    else if (NULL == creds->username)
+      mhdErrorExitDesc ("'username' is NULL");
+    else if (creds->username_len != MHD_STATICSTR_LEN_ (USERNAME))
+    {
+      fprintf (stderr, "'username_len' does not match.\n"
+               "Expected: %u\tRecieved: %u. ",
+               (unsigned) MHD_STATICSTR_LEN_ (USERNAME),
+               (unsigned) creds->username_len);
+      mhdErrorExitDesc ("Wrong 'username_len'");
+    }
+    else if (0 != memcmp (creds->username, USERNAME, creds->username_len))
+    {
+      fprintf (stderr, "'username' does not match.\n"
+               "Expected: '%s'\tRecieved: '%.*s'. ",
+               USERNAME,
+               (int) creds->username_len,
+               creds->username);
+      mhdErrorExitDesc ("Wrong 'username'");
+    }
+    else if (NULL != creds->userhash_hex)
+      mhdErrorExitDesc ("'userhash_hex' is NOT NULL");
+    else if (0 != creds->userhash_hex_len)
+      mhdErrorExitDesc ("'userhash_hex' is NOT zero");
+    else if (NULL != creds->userhash_bin)
+      mhdErrorExitDesc ("'userhash_bin' is NOT NULL");
+    MHD_free (creds);
+
+    dinfo = MHD_digest_auth_get_request_info3 (connection);
+    if (NULL == dinfo)
+      mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL");
+    else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != dinfo->uname_type)
+    {
+      fprintf (stderr, "Unexpected 'uname_type'.\n"
+               "Expected: %d\tRecieved: %d. ",
+               (int) MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED,
+               (int) creds->uname_type);
+      mhdErrorExitDesc ("Wrong 'uname_type'");
+    }
+    else if (NULL == dinfo->username)
+      mhdErrorExitDesc ("'username' is NULL");
+    else if (dinfo->username_len != MHD_STATICSTR_LEN_ (USERNAME))
+    {
+      fprintf (stderr, "'username_len' does not match.\n"
+               "Expected: %u\tRecieved: %u. ",
+               (unsigned) MHD_STATICSTR_LEN_ (USERNAME),
+               (unsigned) dinfo->username_len);
+      mhdErrorExitDesc ("Wrong 'username_len'");
+    }
+    else if (0 != memcmp (dinfo->username, USERNAME, dinfo->username_len))
+    {
+      fprintf (stderr, "'username' does not match.\n"
+               "Expected: '%s'\tRecieved: '%.*s'. ",
+               USERNAME,
+               (int) dinfo->username_len,
+               dinfo->username);
+      mhdErrorExitDesc ("Wrong 'username'");
+    }
+    else if (NULL != dinfo->userhash_hex)
+      mhdErrorExitDesc ("'userhash_hex' is NOT NULL");
+    else if (0 != dinfo->userhash_hex_len)
+      mhdErrorExitDesc ("'userhash_hex' is NOT zero");
+    else if (NULL != dinfo->userhash_bin)
+      mhdErrorExitDesc ("'userhash_bin' is NOT NULL");
+    else if (MHD_DIGEST_AUTH_ALGO3_MD5 != dinfo->algo3)
+    {
+      fprintf (stderr, "Unexpected 'algo'.\n"
+               "Expected: %d\tRecieved: %d. ",
+               (int) MHD_DIGEST_AUTH_ALGO3_MD5,
+               (int) dinfo->algo3);
+      mhdErrorExitDesc ("Wrong 'algo'");
+    }
+    else if (MHD_STATICSTR_LEN_ (CNONCE_EMU) != dinfo->cnonce_len)
+    {
+      fprintf (stderr, "Unexpected 'cnonce_len'.\n"
+               "Expected: %d\tRecieved: %ld. ",
+               (int) MHD_STATICSTR_LEN_ (CNONCE_EMU),
+               (long) dinfo->cnonce_len);
+      mhdErrorExitDesc ("Wrong 'cnonce_len'");
+    }
+    else if (NULL == dinfo->opaque)
+      mhdErrorExitDesc ("'opaque' is NULL");
+    else if (dinfo->opaque_len != MHD_STATICSTR_LEN_ (OPAQUE_VALUE))
+    {
+      fprintf (stderr, "'opaque_len' does not match.\n"
+               "Expected: %u\tRecieved: %u. ",
+               (unsigned) MHD_STATICSTR_LEN_ (OPAQUE_VALUE),
+               (unsigned) dinfo->opaque_len);
+      mhdErrorExitDesc ("Wrong 'opaque_len'");
+    }
+    else if (0 != memcmp (dinfo->opaque, OPAQUE_VALUE, dinfo->opaque_len))
+    {
+      fprintf (stderr, "'opaque' does not match.\n"
+               "Expected: '%s'\tRecieved: '%.*s'. ",
+               OPAQUE_VALUE,
+               (int) dinfo->opaque_len,
+               dinfo->opaque);
+      mhdErrorExitDesc ("Wrong 'opaque'");
+    }
+    else if (MHD_DIGEST_AUTH_QOP_AUTH != dinfo->qop)
+    {
+      fprintf (stderr, "Unexpected 'qop'.\n"
+               "Expected: %d\tRecieved: %d. ",
+               (int) MHD_DIGEST_AUTH_QOP_AUTH,
+               (int) dinfo->qop);
+      mhdErrorExitDesc ("Wrong 'qop'");
+    }
+    else if (NULL == dinfo->realm)
+      mhdErrorExitDesc ("'realm' is NULL");
+    else if (dinfo->realm_len != MHD_STATICSTR_LEN_ (REALM))
+    {
+      fprintf (stderr, "'realm_len' does not match.\n"
+               "Expected: %u\tRecieved: %u. ",
+               (unsigned) MHD_STATICSTR_LEN_ (REALM),
+               (unsigned) dinfo->realm_len);
+      mhdErrorExitDesc ("Wrong 'realm_len'");
+    }
+    else if (0 != memcmp (dinfo->realm, REALM, dinfo->realm_len))
+    {
+      fprintf (stderr, "'realm' does not match.\n"
+               "Expected: '%s'\tRecieved: '%.*s'. ",
+               OPAQUE_VALUE,
+               (int) dinfo->realm_len,
+               dinfo->realm);
+      mhdErrorExitDesc ("Wrong 'realm'");
+    }
+    MHD_free (dinfo);
+
+    check_res = MHD_digest_auth_check3 (connection, REALM, USERNAME,
+                                        PASSWORD_VALUE,
+                                        50 * TIMEOUTS_VAL,
+                                        0, MHD_DIGEST_AUTH_MULT_QOP_AUTH,
+                                        MHD_DIGEST_AUTH_MULT_ALGO3_MD5);
+
+    switch (check_res)
+    {
+    /* Valid results */
+    case MHD_DAUTH_NONCE_STALE:
+      if (verbose)
+        printf ("Got valid auth check result: MHD_DAUTH_NONCE_STALE.\n");
+      break;
+    case MHD_DAUTH_NONCE_WRONG:
+      if (verbose)
+        printf ("Got valid auth check result: MHD_DAUTH_NONCE_WRONG.\n");
+      break;
+
+    /* Invalid results */
+    case MHD_DAUTH_OK:
+      mhdErrorExitDesc ("'MHD_digest_auth_check3()' succeed, " \
+                        "but it should not");
+      break;
+    case MHD_DAUTH_ERROR:
+      externalErrorExitDesc ("General error returned " \
+                             "by 'MHD_digest_auth_check3()'");
+      break;
+    case MHD_DAUTH_WRONG_USERNAME:
+      mhdErrorExitDesc ("MHD_digest_auth_check3()' returned " \
+                        "MHD_DAUTH_WRONG_USERNAME");
+      break;
+    case MHD_DAUTH_RESPONSE_WRONG:
+      mhdErrorExitDesc ("MHD_digest_auth_check3()' returned " \
+                        "MHD_DAUTH_RESPONSE_WRONG");
+      break;
+    case MHD_DAUTH_WRONG_HEADER:
+    case MHD_DAUTH_WRONG_REALM:
+    case MHD_DAUTH_WRONG_URI:
+    case MHD_DAUTH_WRONG_QOP:
+    case MHD_DAUTH_WRONG_ALGO:
+    case MHD_DAUTH_TOO_LARGE:
+    case MHD_DAUTH_NONCE_OTHER_COND:
+      fprintf (stderr, "'MHD_digest_auth_check3()' returned "
+               "unexpected result: %d. ",
+               check_res);
+      mhdErrorExitDesc ("Wrong returned code");
+      break;
+    default:
+      fprintf (stderr, "'MHD_digest_auth_check3()' returned "
+               "impossible result code: %d. ",
+               check_res);
+      mhdErrorExitDesc ("Impossible returned code");
+    }
+
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                              (const void *) DENIED);
+    if (NULL == response)
+      mhdErrorExitDesc ("Response creation failed");
+    ret = MHD_queue_auth_fail_response2 (connection, REALM, OPAQUE_VALUE,
+                                         response, 0, MHD_DIGEST_ALG_MD5);
+    if (MHD_YES != ret)
+      mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed");
+  }
+  else
+  {
+    char *username;
+    int check_res;
+
+    username = MHD_digest_auth_get_username (connection);
+    if (NULL == username)
+      mhdErrorExitDesc ("'MHD_digest_auth_get_username()' returned NULL");
+    else if (0 != strcmp (username, USERNAME))
+    {
+      fprintf (stderr, "'username' does not match.\n"
+               "Expected: '%s'\tRecieved: '%s'. ",
+               USERNAME,
+               username);
+      mhdErrorExitDesc ("Wrong 'username'");
+    }
+    MHD_free (username);
+
+    check_res = MHD_digest_auth_check (connection, REALM, USERNAME,
+                                       PASSWORD_VALUE,
+                                       300);
+
+    if (MHD_INVALID_NONCE != check_res)
+    {
+      fprintf (stderr, "'MHD_digest_auth_check()' returned unexpected"
+               " result: %d. ", check_res);
+      mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check()' result");
+    }
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED),
+                                              (const void *) DENIED);
+    if (NULL == response)
+      mhdErrorExitDesc ("Response creation failed");
+
+    ret = MHD_queue_auth_fail_response (connection, REALM, OPAQUE_VALUE,
+                                        response, 0);
+    if (MHD_YES != ret)
+      mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed");
+  }
+
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port)
+{
+  CURL *c;
+  char url[512];
+
+  if (1)
+  {
+    int res;
+    /* A workaround for some old libcurl versions, which ignore the specified
+     * port by CURLOPT_PORT when authorisation is used. */
+    res = snprintf (url, (sizeof(url) / sizeof(url[0])),
+                    "http://127.0.0.1:%u%s",
+                    (unsigned int) port, MHD_URI_BASE_PATH);
+    if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res))
+      externalErrorExitDesc ("Cannot form request URL");
+  }
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     CURL_HTTP_VERSION_1_1)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      /* (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_headers)) ||
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  multi = NULL;
+  multi = curl_multi_init ();
+  if (multi == NULL)
+    libcurlErrorExitDesc ("curl_multi_init() failed");
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 200000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (200);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/**
+ * Check request result
+ * @param curl_code the CURL easy return code
+ * @param pcbc the pointer struct CBC
+ * @return non-zero if success, zero if failed
+ */
+static unsigned int
+check_result (CURLcode curl_code, CURL *c, struct CBC *pcbc)
+{
+  long code;
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
+    libcurlErrorExit ();
+
+  if (401 != code)
+  {
+    fprintf (stderr, "Request returned wrong code: %ld.\n",
+             code);
+    return 0;
+  }
+
+  if (CURLE_OK != curl_code)
+  {
+    fflush (stdout);
+    if (0 != libcurl_errbuf[0])
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               curl_easy_strerror (curl_code),
+               libcurl_errbuf);
+    else
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n",
+               curl_easy_strerror (curl_code));
+    fflush (stderr);
+    return 0;
+  }
+
+  if (pcbc->pos != strlen (DENIED))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf,
+             (unsigned) strlen (DENIED));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != memcmp (DENIED, pcbc->buf, pcbc->pos))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ",
+             (int) pcbc->pos, pcbc->buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
+  return 1;
+}
+
+
+static unsigned int
+testDigestAuthEmu (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t port;
+  struct CBC cbc;
+  char buf[2048];
+  CURL *c;
+  int failed = 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 4210;
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = (uint16_t) dinfo->port;
+  }
+
+  /* First request */
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  cbc.pos = 0;
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port);
+  if (check_result (performQueryExternal (d, c), c, &cbc))
+  {
+    if (verbose)
+      printf ("Got expected response.\n");
+  }
+  else
+  {
+    fprintf (stderr, "Request FAILED.\n");
+    failed = 1;
+  }
+  curl_easy_cleanup (c);
+
+  MHD_stop_daemon (d);
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  oldapi = has_in_name (argv[0], "_oldapi");
+  test_global_init ();
+
+  errorCount += testDigestAuthEmu ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  test_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_digestauth_sha256.c b/src/testcurl/test_digestauth_sha256.c
new file mode 100644
index 0000000..d63283b
--- /dev/null
+++ b/src/testcurl/test_digestauth_sha256.c
@@ -0,0 +1,337 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2010, 2018 Christian Grothoff
+     Copyright (C) 2019-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file daemontest_digestauth_sha256.c
+ * @brief  Testcase for libmicrohttpd Digest Auth with SHA256
+ * @author Amr Ali
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
+#include <gcrypt.h>
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
+
+#ifndef WINDOWS
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
+
+#define DENIED \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
+
+#define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4"
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    return 0;                   /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data,
+          size_t *upload_data_size,
+          void **req_cls)
+{
+  struct MHD_Response *response;
+  char *username;
+  const char *password = "testpass";
+  const char *realm = "test@example.com";
+  enum MHD_Result ret;
+  int ret_i;
+  static int already_called_marker;
+  (void) cls; (void) url;                         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls;        /* Unused. Silent compiler warning. */
+
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  username = MHD_digest_auth_get_username (connection);
+  if ( (username == NULL) ||
+       (0 != strcmp (username, "testuser")) )
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         MHD_NO,
+                                         MHD_DIGEST_ALG_SHA256);
+    MHD_destroy_response (response);
+    return ret;
+  }
+  ret_i = MHD_digest_auth_check2 (connection,
+                                  realm,
+                                  username,
+                                  password,
+                                  300,
+                                  MHD_DIGEST_ALG_SHA256);
+  MHD_free (username);
+  if (ret_i != MHD_YES)
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    if (NULL == response)
+      return MHD_NO;
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         (MHD_INVALID_NONCE == ret_i) ?
+                                         MHD_YES : MHD_NO,
+                                         MHD_DIGEST_ALG_SHA256);
+    MHD_destroy_response (response);
+    return ret;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                     PAGE);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static unsigned int
+testDigestAuth (void)
+{
+  CURL *c;
+  CURLcode errornum;
+  struct MHD_Daemon *d;
+  struct CBC cbc;
+  char buf[2048];
+  char rnd[8];
+  uint16_t port;
+  char url[128];
+#ifndef WINDOWS
+  int fd;
+  size_t len;
+  size_t off = 0;
+#endif /* ! WINDOWS */
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1167;
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+#ifndef WINDOWS
+  fd = open ("/dev/urandom",
+             O_RDONLY);
+  if (-1 == fd)
+  {
+    fprintf (stderr,
+             "Failed to open `%s': %s\n",
+             "/dev/urandom",
+             strerror (errno));
+    return 1;
+  }
+  while (off < 8)
+  {
+    len = (size_t) read (fd,
+                         rnd + off,
+                         8 - off);
+    if (len == (size_t) -1)
+    {
+      fprintf (stderr,
+               "Failed to read `%s': %s\n",
+               "/dev/urandom",
+               strerror (errno));
+      (void) close (fd);
+      return 1;
+    }
+    off += len;
+  }
+  (void) close (fd);
+#else
+  {
+    HCRYPTPROV cc;
+    BOOL b;
+
+    b = CryptAcquireContext (&cc,
+                             NULL,
+                             NULL,
+                             PROV_RSA_FULL,
+                             CRYPT_VERIFYCONTEXT);
+    if (b == 0)
+    {
+      fprintf (stderr,
+               "Failed to acquire crypto provider context: %lu\n",
+               GetLastError ());
+      return 1;
+    }
+    b = CryptGenRandom (cc, 8, (BYTE *) rnd);
+    if (b == 0)
+    {
+      fprintf (stderr,
+               "Failed to generate 8 random bytes: %lu\n",
+               GetLastError ());
+    }
+    CryptReleaseContext (cc, 0);
+    if (b == 0)
+      return 1;
+  }
+#endif
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd,
+                        MHD_OPTION_NONCE_NC_SIZE, 300,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d);
+      return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/bar%%20foo?key=value",
+            (unsigned int) port);
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, url);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
+  curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass");
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen (PAGE))
+    return 4;
+  if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE)))
+    return 8;
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  curl_version_info_data *d = curl_version_info (CURLVERSION_NOW);
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+#if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62)
+  if (1)
+  {
+    fprintf (stderr, "libcurl version 7.62.x has bug in processing"
+             "URI with GET arguments for Digest Auth.\n");
+    fprintf (stderr, "This test cannot be performed.\n");
+    exit (77);
+  }
+#endif /* libcurl version 7.62.x */
+
+#ifdef CURL_VERSION_SSPI
+  if (0 != (d->features & CURL_VERSION_SSPI))
+    return 77; /* Skip test, W32 SSPI doesn't support sha256 digest */
+#endif /* CURL_VERSION_SSPI */
+
+  /* curl added SHA256 support in 7.57 = 7.0x39 */
+  if (d->version_num < 0x073900)
+    return 77; /* skip test, curl is too old */
+#ifdef NEED_GCRYP_INIT
+  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
+#ifdef GCRYCTL_INITIALIZATION_FINISHED
+  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif /* GCRYCTL_INITIALIZATION_FINISHED */
+#endif /* NEED_GCRYP_INIT */
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  errorCount += testDigestAuth ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_digestauth_with_arguments.c b/src/testcurl/test_digestauth_with_arguments.c
index 51868ab..5cf7d06 100644
--- a/src/testcurl/test_digestauth_with_arguments.c
+++ b/src/testcurl/test_digestauth_with_arguments.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2010, 2012 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,25 +15,29 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_digestauth_with_arguments.c
  * @brief  Testcase for libmicrohttpd Digest Auth with arguments
  * @author Amr Ali
+ * @author Karlson2k (Evgeny Grin)
  */
-#include "MHD_config.h"
+#include "mhd_options.h"
 #include "platform.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#ifdef HAVE_GCRYPT_H
+
+#if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \
+  (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB))
+#define NEED_GCRYP_INIT 1
 #include <gcrypt.h>
-#endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */
 
 #ifndef WINDOWS
 #include <sys/socket.h>
@@ -41,9 +46,11 @@
 #include <wincrypt.h>
 #endif
 
-#define PAGE "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access granted</body></html>"
 
-#define DENIED "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
+#define DENIED \
+  "<html><head><title>libmicrohttpd demo</title></head><body>Access denied</body></html>"
 
 #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4"
 
@@ -66,154 +73,198 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   struct MHD_Response *response;
   char *username;
   const char *password = "testpass";
   const char *realm = "test@example.com";
-  int ret;
+  enum MHD_Result ret;
+  int ret_i;
+  static int already_called_marker;
+  (void) cls; (void) url;                         /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls;        /* Unused. Silent compiler warning. */
 
-  username = MHD_digest_auth_get_username(connection);
+  if (&already_called_marker != *req_cls)
+  { /* Called for the first time, request not fully read yet */
+    *req_cls = &already_called_marker;
+    /* Wait for complete request */
+    return MHD_YES;
+  }
+
+  username = MHD_digest_auth_get_username (connection);
   if ( (username == NULL) ||
        (0 != strcmp (username, "testuser")) )
-    {
-      response = MHD_create_response_from_buffer(strlen (DENIED), 
-						 DENIED,
-						 MHD_RESPMEM_PERSISTENT);  
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 MY_OPAQUE,
-					 response,
-					 MHD_NO);    
-      MHD_destroy_response(response);  
-      return ret;
-    }
-  ret = MHD_digest_auth_check(connection, realm,
-			      username, 
-			      password, 
-			      300);
-  free(username);
-  if ( (ret == MHD_INVALID_NONCE) ||
-       (ret == MHD_NO) )
-    {
-      response = MHD_create_response_from_buffer(strlen (DENIED), 
-						 DENIED,
-						 MHD_RESPMEM_PERSISTENT);  
-      if (NULL == response) 
-	return MHD_NO;
-      ret = MHD_queue_auth_fail_response(connection, realm,
-					 MY_OPAQUE,
-					 response,
-					 (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO);  
-      MHD_destroy_response(response);  
-      return ret;
-    }
-  response = MHD_create_response_from_buffer(strlen(PAGE), PAGE,
-					     MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response(connection, MHD_HTTP_OK, response);  
-  MHD_destroy_response(response);
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    ret = MHD_queue_auth_fail_response2 (connection, realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    MHD_destroy_response (response);
+    return ret;
+  }
+  ret_i = MHD_digest_auth_check2 (connection,
+                                  realm,
+                                  username,
+                                  password,
+                                  300,
+                                  MHD_DIGEST_ALG_MD5);
+  MHD_free (username);
+  if (ret_i != MHD_YES)
+  {
+    response = MHD_create_response_from_buffer_static (strlen (DENIED),
+                                                       DENIED);
+    if (NULL == response)
+      fprintf (stderr, "MHD_create_response_from_buffer() failed.\n");
+    ret = MHD_queue_auth_fail_response2 (connection,
+                                         realm,
+                                         MY_OPAQUE,
+                                         response,
+                                         (MHD_INVALID_NONCE == ret_i) ?
+                                         MHD_YES : MHD_NO,
+                                         MHD_DIGEST_ALG_MD5);
+    if (MHD_YES != ret)
+      fprintf (stderr, "MHD_queue_auth_fail_response2() failed.\n");
+    MHD_destroy_response (response);
+    return ret;
+  }
+  response = MHD_create_response_from_buffer_static (strlen (PAGE),
+                                                     PAGE);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testDigestAuth ()
+static unsigned int
+testDigestAuth (void)
 {
-  int fd;
   CURL *c;
   CURLcode errornum;
   struct MHD_Daemon *d;
   struct CBC cbc;
-  size_t len;
-  size_t off = 0;
   char buf[2048];
   char rnd[8];
+  uint16_t port;
+  char url[128];
+#ifndef WINDOWS
+  int fd;
+  size_t len;
+  size_t off = 0;
+#endif /* ! WINDOWS */
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1160;
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
 #ifndef WINDOWS
-  fd = open("/dev/urandom", O_RDONLY);
+  fd = open ("/dev/urandom", O_RDONLY);
   if (-1 == fd)
-    {
-	  fprintf(stderr, "Failed to open `%s': %s\n",
-	       "/dev/urandom",
-		   strerror(errno));
-	  return 1;
-	}
+  {
+    fprintf (stderr, "Failed to open `%s': %s\n",
+             "/dev/urandom",
+             strerror (errno));
+    return 1;
+  }
   while (off < 8)
-	{
-	  len = read(fd, rnd, 8);
-	  if (len == -1)
-	    {
-		  fprintf(stderr, "Failed to read `%s': %s\n",
-		       "/dev/urandom",
-			   strerror(errno));
-		  (void) close(fd);
-		  return 1;
-		}
-	  off += len;
-	}
-  (void) close(fd);
+  {
+    len = (size_t) read (fd, rnd + off, 8 - off);
+    if (len == (size_t) -1)
+    {
+      fprintf (stderr,
+               "Failed to read `%s': %s\n",
+               "/dev/urandom",
+               strerror (errno));
+      (void) close (fd);
+      return 1;
+    }
+    off += len;
+  }
+  (void) close (fd);
 #else
   {
     HCRYPTPROV cc;
     BOOL b;
-    b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
+    b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL,
+                             CRYPT_VERIFYCONTEXT);
     if (b == 0)
     {
       fprintf (stderr, "Failed to acquire crypto provider context: %lu\n",
-          GetLastError ());
+               GetLastError ());
       return 1;
     }
-    b = CryptGenRandom (cc, 8, rnd);
+    b = CryptGenRandom (cc, 8, (BYTE *) rnd);
     if (b == 0)
     {
       fprintf (stderr, "Failed to generate 8 random bytes: %lu\n",
-          GetLastError ());
+               GetLastError ());
     }
     CryptReleaseContext (cc, 0);
     if (b == 0)
       return 1;
   }
 #endif
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1337, NULL, NULL, &ahc_echo, PAGE,
-			MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd,
-			MHD_OPTION_NONCE_NC_SIZE, 300,
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd,
+                        MHD_OPTION_NONCE_NC_SIZE, 300,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/bar%%20foo?"
+            "key=value&more=even%%20more&empty&=no_key&&same=one&&same=two",
+            (unsigned int) port);
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1337/foo?key=value");
+  curl_easy_setopt (c, CURLOPT_URL, url);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
   curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass");
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (PAGE))
@@ -228,18 +279,30 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
+#if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62)
+  if (1)
+  {
+    fprintf (stderr, "libcurl version 7.62.x has bug in processing"
+             "URI with GET arguments for Digest Auth.\n");
+    fprintf (stderr, "This test cannot be performed.\n");
+    exit (77);
+  }
+#endif /* libcurl version 7.62.x */
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #ifdef HAVE_GCRYPT_H
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
 #endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   errorCount += testDigestAuth ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_get.c b/src/testcurl/test_get.c
index e4c531d..c77c906 100644
--- a/src/testcurl/test_get.c
+++ b/src/testcurl/test_get.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,25 +15,28 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
-
 /**
  * @file test_get.c
  * @brief  Testcase for libmicrohttpd GET operations
- *         TODO: test parsing of query
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
-
 #include "MHD_config.h"
 #include "platform.h"
-#include "platform_interface.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+#include "mhd_sockets.h" /* only macros used */
+
+
+#define EXPECTED_URI_PATH "/hello_world?a=%26&b=c"
 
 #ifdef _WIN32
 #ifndef WIN32_LEAN_AND_MEAN
@@ -46,14 +50,15 @@
 #include <sys/socket.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 static int oneone;
+static uint16_t global_port;
 
 struct CBC
 {
@@ -62,6 +67,7 @@
   size_t size;
 };
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -74,41 +80,99 @@
   return size * nmemb;
 }
 
-static int
+
+static void *
+log_cb (void *cls,
+        const char *uri,
+        struct MHD_Connection *con)
+{
+  (void) cls;
+  (void) con;
+  if (0 != strcmp (uri,
+                   EXPECTED_URI_PATH))
+  {
+    fprintf (stderr,
+             "Wrong URI: `%s'\n",
+             uri);
+    _exit (22);
+  }
+  return NULL;
+}
+
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  const char *v;
+  (void) cls;
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;       /* Unused. Silence compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  v = MHD_lookup_connection_value (connection,
+                                   MHD_GET_ARGUMENT_KIND,
+                                   "a");
+  if ( (NULL == v) ||
+       (0 != strcmp ("&",
+                     v)) )
+  {
+    fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n",
+             NULL == v ? "NULL" : v);
+    _exit (17);
+  }
+  v = NULL;
+  if (MHD_YES != MHD_lookup_connection_value_n (connection,
+                                                MHD_GET_ARGUMENT_KIND,
+                                                "b",
+                                                1,
+                                                &v,
+                                                NULL))
+  {
+    fprintf (stderr, "Not found 'b' GET argument.\n");
+    _exit (18);
+  }
+  if ( (NULL == v) ||
+       (0 != strcmp ("c",
+                     v)) )
+  {
+    fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n",
+             NULL == v ? "NULL" : v);
+    _exit (19);
+  }
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
-    abort ();
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (19);
+  }
   return ret;
 }
 
 
-static int
-testInternalGet (int poll_flag)
+static unsigned int
+testInternalGet (uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -116,18 +180,41 @@
   struct CBC cbc;
   CURLcode errornum;
 
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1220;
+    if (oneone)
+      global_port += 20;
+  }
+
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG  | poll_flag,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -137,16 +224,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -157,8 +244,8 @@
 }
 
 
-static int
-testMultithreadedGet (int poll_flag)
+static unsigned int
+testMultithreadedGet (uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -166,18 +253,42 @@
   struct CBC cbc;
   CURLcode errornum;
 
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1221;
+    if (oneone)
+      global_port += 20;
+  }
+
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG  | poll_flag,
-                        1081, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
@@ -187,16 +298,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -207,8 +318,8 @@
 }
 
 
-static int
-testMultithreadedPoolGet (int poll_flag)
+static unsigned int
+testMultithreadedPoolGet (uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -216,19 +327,42 @@
   struct CBC cbc;
   CURLcode errornum;
 
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1222;
+    if (oneone)
+      global_port += 20;
+  }
+
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | poll_flag,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
@@ -238,16 +372,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -258,8 +392,8 @@
 }
 
 
-static int
-testExternalGet ()
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -270,25 +404,48 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+  int maxposixs;
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
 
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1223;
+    if (oneone)
+      global_port += 20;
+  }
+
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        global_port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
@@ -298,80 +455,119 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxsock > maxposixs)
+      maxposixs = maxsock;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -381,8 +577,8 @@
 }
 
 
-static int
-testUnknownPortGet (int poll_flag)
+static unsigned int
+testUnknownPortGet (uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   const union MHD_DaemonInfo *di;
@@ -390,10 +586,11 @@
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
 
   struct sockaddr_in addr;
   socklen_t addr_len = sizeof(addr);
-  memset(&addr, 0, sizeof(addr));
+  memset (&addr, 0, sizeof(addr));
   addr.sin_family = AF_INET;
   addr.sin_port = 0;
   addr.sin_addr.s_addr = INADDR_ANY;
@@ -401,31 +598,47 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG  | poll_flag,
-                        1, NULL, NULL, &ahc_echo, "GET",
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        0, NULL, NULL, &ahc_echo, NULL,
                         MHD_OPTION_SOCK_ADDR, &addr,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
                         MHD_OPTION_END);
-  if (d == NULL)
-    return 32768;
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+  {
+    di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
+    if (di == NULL)
+      return 65536;
 
-  di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
-  if (di == NULL)
-    return 65536;
+    if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len))
+      return 131072;
 
-  if (0 != getsockname(di->listen_fd, (struct sockaddr *) &addr, &addr_len))
-    return 131072;
+    if (addr.sin_family != AF_INET)
+      return 26214;
+    port = ntohs (addr.sin_port);
+  }
+  else
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
 
-  if (addr.sin_family != AF_INET)
-    return 26214;
-
-  snprintf(buf, sizeof(buf), "http://127.0.0.1:%hu/hello_world",
-           ntohs(addr.sin_port));
+  snprintf (buf,
+            sizeof(buf),
+            "http://127.0.0.1:%u%s",
+            (unsigned int) port,
+            EXPECTED_URI_PATH);
 
   c = curl_easy_init ();
   curl_easy_setopt (c, CURLOPT_URL, buf);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -435,16 +648,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 524288;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 524288;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -455,100 +668,137 @@
 }
 
 
-static int
-testStopRace (int poll_flag)
+static unsigned int
+testStopRace (uint32_t poll_flag)
 {
-    struct sockaddr_in sin;
-    MHD_socket fd;
-    struct MHD_Daemon *d;
+  struct sockaddr_in sin;
+  MHD_socket fd;
+  struct MHD_Daemon *d;
 
-    d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG | poll_flag,
-                         1081, NULL, NULL, &ahc_echo, "GET",
-                         MHD_OPTION_CONNECTION_TIMEOUT, 5, MHD_OPTION_END);
-    if (d == NULL)
-       return 16;
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1224;
+    if (oneone)
+      global_port += 20;
+  }
 
-    fd = socket (PF_INET, SOCK_STREAM, 0);
-    if (fd == MHD_INVALID_SOCKET)
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-       fprintf(stderr, "socket error\n");
-       return 256;
+      MHD_stop_daemon (d); return 32;
     }
+    global_port = dinfo->port;
+  }
 
-    memset(&sin, 0, sizeof(sin));
-    sin.sin_family = AF_INET;
-    sin.sin_port = htons(1081);
-    sin.sin_addr.s_addr = htonl(0x7f000001);
+  fd = socket (PF_INET, SOCK_STREAM, 0);
+  if (fd == MHD_INVALID_SOCKET)
+  {
+    fprintf (stderr, "socket error\n");
+    return 256;
+  }
 
-    if (connect (fd, (struct sockaddr *)(&sin), sizeof(sin)) < 0)
-    {
-       fprintf(stderr, "connect error\n");
-       MHD_socket_close_ (fd);
-       return 512;
-    }
+  memset (&sin, 0, sizeof(sin));
+  sin.sin_family = AF_INET;
+  sin.sin_port = htons (global_port);
+  sin.sin_addr.s_addr = htonl (0x7f000001);
 
-    /*  printf("Waiting\n"); */
-    /* Let the thread get going. */
-    usleep(500000);
+  if (connect (fd, (struct sockaddr *) (&sin), sizeof(sin)) < 0)
+  {
+    fprintf (stderr, "connect error\n");
+    MHD_socket_close_chk_ (fd);
+    return 512;
+  }
 
-    /* printf("Stopping daemon\n"); */
-    MHD_stop_daemon (d);
+  /*  printf("Waiting\n"); */
+  /* Let the thread get going. */
+  usleep (500000);
 
-    MHD_socket_close_ (fd);
+  /* printf("Stopping daemon\n"); */
+  MHD_stop_daemon (d);
 
-    /* printf("good\n"); */
-    return 0;
+  MHD_socket_close_chk_ (fd);
+
+  /* printf("good\n"); */
+  return 0;
 }
 
 
-static int
+static enum MHD_Result
 ahc_empty (void *cls,
-          struct MHD_Connection *connection,
-          const char *url,
-          const char *method,
-          const char *version,
-          const char *upload_data, size_t *upload_data_size,
-          void **unused)
+           struct MHD_Connection *connection,
+           const char *url,
+           const char *method,
+           const char *version,
+           const char *upload_data,
+           size_t *upload_data_size,
+           void **req_cls)
 {
   static int ptr;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url;
+  (void) url;
+  (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size; /* Unused. Silent compiler warning. */
 
   if (0 != strcmp ("GET", method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
-  response = MHD_create_response_from_buffer (0,
-					      NULL,
-					      MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
-    abort ();
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (20);
+  }
   return ret;
 }
 
 
 static int
-curlExcessFound(CURL *c, curl_infotype type, char *data, size_t size, void *cls)
+curlExcessFound (CURL *c,
+                 curl_infotype type,
+                 char *data,
+                 size_t size,
+                 void *cls)
 {
   static const char *excess_found = "Excess found";
   const size_t str_size = strlen (excess_found);
+  (void) c;      /* Unused. Silent compiler warning. */
 
-  if (CURLINFO_TEXT == type
-      && size >= str_size
-      && 0 == strncmp(excess_found, data, str_size))
-    *(int *)cls = 1;
+  if ((CURLINFO_TEXT == type)
+      && (size >= str_size)
+      && (0 == strncmp (excess_found, data, str_size)))
+    *(int *) cls = 1;
   return 0;
 }
 
 
-static int
-testEmptyGet (int poll_flag)
+static unsigned int
+testEmptyGet (uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -557,21 +807,44 @@
   CURLcode errornum;
   int excess_found = 0;
 
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1225;
+    if (oneone)
+      global_port += 20;
+  }
+
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG  | poll_flag,
-                        11081, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_empty, NULL,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 4194304;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound);
   curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found);
-  curl_easy_setopt (c, CURLOPT_VERBOSE, 1);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -581,16 +854,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 8388608;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 8388608;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != 0)
@@ -605,36 +878,146 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  int verbose = 0;
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  verbose = has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalGet (0);
-  errorCount += testMultithreadedGet (0);
-  errorCount += testMultithreadedPoolGet (0);
-  errorCount += testUnknownPortGet (0);
-  errorCount += testStopRace (0);
-  errorCount += testExternalGet ();
-  errorCount += testEmptyGet (0);
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_POLL))
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result += testInternalGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (0).\n");
+    errorCount += test_result;
+    test_result += testMultithreadedGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testMultithreadedGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (0).\n");
+    errorCount += test_result;
+    test_result += testMultithreadedPoolGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testMultithreadedPoolGet (0) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (0).\n");
+    errorCount += test_result;
+    test_result += testUnknownPortGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testUnknownPortGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testUnknownPortGet (0).\n");
+    errorCount += test_result;
+    test_result += testStopRace (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testStopRace (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testStopRace (0).\n");
+    errorCount += test_result;
+    test_result += testEmptyGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testEmptyGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testEmptyGet (0).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
     {
-      errorCount += testInternalGet(MHD_USE_POLL);
-      errorCount += testMultithreadedGet(MHD_USE_POLL);
-      errorCount += testMultithreadedPoolGet(MHD_USE_POLL);
-      errorCount += testUnknownPortGet(MHD_USE_POLL);
-      errorCount += testStopRace(MHD_USE_POLL);
-      errorCount += testEmptyGet(MHD_USE_POLL);
+      test_result += testInternalGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testMultithreadedGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testMultithreadedGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testMultithreadedPoolGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedPoolGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedPoolGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testUnknownPortGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testUnknownPortGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testStopRace (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testStopRace (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testStopRace (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testEmptyGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testEmptyGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
     }
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_EPOLL))
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
     {
-      errorCount += testInternalGet(MHD_USE_EPOLL_LINUX_ONLY);
-      errorCount += testMultithreadedPoolGet(MHD_USE_EPOLL_LINUX_ONLY);
-      errorCount += testUnknownPortGet(MHD_USE_EPOLL_LINUX_ONLY);
-      errorCount += testEmptyGet(MHD_USE_EPOLL_LINUX_ONLY);
+      test_result += testInternalGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+      test_result += testMultithreadedPoolGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedPoolGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedPoolGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+      test_result += testUnknownPortGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testUnknownPortGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+      test_result += testEmptyGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testEmptyGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
     }
-  if (errorCount != 0)
-    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  }
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_get_chunked.c b/src/testcurl/test_get_chunked.c
index 3b8bf39..a86ba14 100644
--- a/src/testcurl/test_get_chunked.c
+++ b/src/testcurl/test_get_chunked.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,18 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
- * @file daemontest_get_chunked.c
+ * @file test_get_chunked.c
  * @brief  Testcase for libmicrohttpd GET operations with chunked content encoding
- *         TODO:
- *         - how to test that chunking was actually used?
- *         - use CURLOPT_HEADERFUNCTION to validate
- *           footer was sent
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -40,13 +38,80 @@
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#include "mhd_has_in_name.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
+#define HDR_CHUNKED_ENCODING MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked"
+#define RESP_FOOTER_NAME "Footer"
+#define RESP_FOOTER_VALUE "working"
+#define RESP_FOOTER RESP_FOOTER_NAME ": " RESP_FOOTER_VALUE
+
+#define RESP_BLOCK_SIZE 128
+#define RESP_BLOCK_QUANTIY 10
+#define RESP_SIZE (RESP_BLOCK_SIZE * RESP_BLOCK_QUANTIY)
+
+/**
+ * Use "Connection: close" header?
+ */
+int conn_close;
+
+/**
+ * Use static string response instead of callback-generated?
+ */
+int resp_string;
+
+/**
+ * Use response with known size?
+ */
+int resp_sized;
+
+/**
+ * Use empty (zero-sized) response?
+ */
+int resp_empty;
+
+/**
+ * Force chunked response by response header?
+ */
+int chunked_forced;
+
+/**
+ * MHD port used for testing
+ */
+uint16_t port_global;
+
+
+struct headers_check_result
+{
+  int found_chunked;
+  int found_footer;
+};
+
+static size_t
+lcurl_hdr_callback (char *buffer, size_t size, size_t nitems,
+                    void *userdata)
+{
+  const size_t data_size = size * nitems;
+  struct headers_check_result *check_res =
+    (struct headers_check_result *) userdata;
+
+  if ((data_size == strlen (HDR_CHUNKED_ENCODING) + 2) &&
+      (0 == memcmp (buffer, HDR_CHUNKED_ENCODING "\r\n", data_size)))
+    check_res->found_chunked = 1;
+  if ((data_size == strlen (RESP_FOOTER) + 2) &&
+      (0 == memcmp (buffer, RESP_FOOTER "\r\n", data_size)))
+    check_res->found_footer = 1;
+
+  return data_size;
+}
+
+
 struct CBC
 {
   char *buf;
@@ -54,8 +119,12 @@
   size_t size;
 };
 
+
 static size_t
-copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
 {
   struct CBC *cbc = ctx;
 
@@ -66,28 +135,39 @@
   return size * nmemb;
 }
 
+
 /**
- * MHD content reader callback that returns
- * data in chunks.
+ * MHD content reader callback that returns data in chunks.
  */
 static ssize_t
-crc (void *cls, uint64_t pos, char *buf, size_t max)
+crc (void *cls,
+     uint64_t pos,
+     char *buf,
+     size_t max)
 {
   struct MHD_Response **responseptr = cls;
 
-  if (pos == 128 * 10)
-    {
-      MHD_add_response_header (*responseptr, "Footer", "working");
-      return MHD_CONTENT_READER_END_OF_STREAM;
-    }
-  if (max < 128)
+  if (resp_empty || (pos == RESP_SIZE - RESP_BLOCK_SIZE))
+  { /* Add footer with the last block */
+    if (MHD_YES != MHD_add_response_footer (*responseptr,
+                                            RESP_FOOTER_NAME,
+                                            RESP_FOOTER_VALUE))
+      abort ();
+  }
+  if (resp_empty || (pos == RESP_SIZE))
+    return MHD_CONTENT_READER_END_OF_STREAM;
+
+  if (max < RESP_BLOCK_SIZE)
     abort ();                   /* should not happen in this testcase... */
-  memset (buf, 'A' + (pos / 128), 128);
-  return 128;
+  memset (buf,
+          'A' + (char) (unsigned char) (pos / RESP_BLOCK_SIZE),
+          RESP_BLOCK_SIZE);
+  return RESP_BLOCK_SIZE;
 }
 
+
 /**
- * Dummy function that does nothing.
+ * Dummy function that frees the "responseptr".
  */
 static void
 crcf (void *ptr)
@@ -95,192 +175,392 @@
   free (ptr);
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  struct MHD_Response **responseptr;
-  int ret;
+  enum MHD_Result ret;
 
-  if (0 != strcmp (me, method))
+  (void) cls;
+  (void) url;
+  (void) version;              /* Unused. Silent compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size;     /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
+  if (! resp_string)
+  {
+    struct MHD_Response **responseptr;
+    responseptr = malloc (sizeof (struct MHD_Response *));
+    if (NULL == responseptr)
+      _exit (99);
+
+    response = MHD_create_response_from_callback (resp_sized ?
+                                                  RESP_SIZE : MHD_SIZE_UNKNOWN,
+                                                  1024,
+                                                  &crc,
+                                                  responseptr,
+                                                  &crcf);
+    *responseptr = response;
+  }
+  else
+  {
+    if (! resp_empty)
     {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
+      size_t pos;
+      static const size_t resp_size = RESP_SIZE;
+      char *buf = malloc (resp_size);
+      if (NULL == buf)
+        _exit (99);
+      for (pos = 0; pos < resp_size; pos += RESP_BLOCK_SIZE)
+        memset (buf + pos,
+                'A' + (char) (unsigned char) (pos / RESP_BLOCK_SIZE),
+                RESP_BLOCK_SIZE);
+
+      response = MHD_create_response_from_buffer_copy (resp_size, buf);
+      free (buf);
     }
-  responseptr = malloc (sizeof (struct MHD_Response *));
-  if (responseptr == NULL)
-    return MHD_NO;
-  response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
-                                                1024,
-                                                &crc, responseptr, &crcf);
-  *responseptr = response;
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    else
+      response = MHD_create_response_empty (MHD_RF_NONE);
+  }
+  if (NULL == response)
+    abort ();
+  if (chunked_forced)
+  {
+    if (MHD_NO == MHD_add_response_header (response,
+                                           MHD_HTTP_HEADER_TRANSFER_ENCODING,
+                                           "chunked"))
+      abort ();
+  }
+  if (MHD_NO == MHD_add_response_header (response,
+                                         MHD_HTTP_HEADER_TRAILER,
+                                         RESP_FOOTER_NAME))
+    abort ();
+
+  if (resp_string || (resp_sized && resp_empty))
+  {
+    /* There is no chance to add footer later */
+    if (MHD_YES != MHD_add_response_footer (response,
+                                            RESP_FOOTER_NAME,
+                                            RESP_FOOTER_VALUE))
+      abort ();
+  }
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
 
-static int
-validate (struct CBC cbc, int ebase)
+
+static unsigned int
+validate (struct CBC cbc, unsigned int ebase)
 {
   int i;
-  char buf[128];
+  char buf[RESP_BLOCK_SIZE];
 
-  if (cbc.pos != 128 * 10)
-    return ebase;
-
-  for (i = 0; i < 10; i++)
+  if (resp_empty)
+  {
+    if (0 != cbc.pos)
     {
-      memset (buf, 'A' + i, 128);
-      if (0 != memcmp (buf, &cbc.buf[i * 128], 128))
-        {
-          fprintf (stderr,
-                   "Got  `%.*s'\nWant `%.*s'\n",
-                   128, buf, 128, &cbc.buf[i * 128]);
-          return ebase * 2;
-        }
+      fprintf (stderr,
+               "Got %u bytes instead of zero!\n",
+               (unsigned int) cbc.pos);
+      return 1;
     }
+    return 0;
+  }
+
+  if (cbc.pos != RESP_SIZE)
+  {
+    fprintf (stderr,
+             "Got %u bytes instead of 1280!\n",
+             (unsigned int) cbc.pos);
+    return ebase;
+  }
+
+  for (i = 0; i < RESP_BLOCK_QUANTIY; i++)
+  {
+    memset (buf, 'A' + i, RESP_BLOCK_SIZE);
+    if (0 != memcmp (buf, &cbc.buf[i * RESP_BLOCK_SIZE], RESP_BLOCK_SIZE))
+    {
+      fprintf (stderr,
+               "Got  `%.*s'\nWant `%.*s'\n",
+               RESP_BLOCK_SIZE, &cbc.buf[i * RESP_BLOCK_SIZE],
+               RESP_BLOCK_SIZE, buf);
+      return ebase * 2;
+    }
+  }
   return 0;
 }
 
-static int
-testInternalGet ()
+
+static unsigned int
+testInternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+  struct curl_slist *h_list = NULL;
+  struct headers_check_result hdr_check;
 
+  port = port_global;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+    if (0 == port_global)
+      port_global = port; /* Re-use the same port for all checks */
+  }
+  hdr_check.found_chunked = 0;
+  hdr_check.found_footer = 0;
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback);
+  curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (conn_close)
+  {
+    h_list = curl_slist_append (h_list, "Connection: close");
+    if (NULL == h_list)
+      abort ();
+    curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list);
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    curl_slist_free_all (h_list);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
+  curl_slist_free_all (h_list);
   MHD_stop_daemon (d);
+  if (1 != hdr_check.found_chunked)
+  {
+    fprintf (stderr,
+             "Chunked encoding header was not found in the response\n");
+    return 8;
+  }
+  if (1 != hdr_check.found_footer)
+  {
+    fprintf (stderr,
+             "The specified footer was not found in the response\n");
+    return 16;
+  }
   return validate (cbc, 4);
 }
 
-static int
-testMultithreadedGet ()
+
+static unsigned int
+testMultithreadedGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+  struct curl_slist *h_list = NULL;
+  struct headers_check_result hdr_check;
 
+  port = port_global;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+    if (0 == port_global)
+      port_global = port; /* Re-use the same port for all checks */
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  hdr_check.found_chunked = 0;
+  hdr_check.found_footer = 0;
+  curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback);
+  curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check);
+  if (conn_close)
+  {
+    h_list = curl_slist_append (h_list, "Connection: close");
+    if (NULL == h_list)
+      abort ();
+    curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list);
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    curl_slist_free_all (h_list);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
+  curl_slist_free_all (h_list);
   MHD_stop_daemon (d);
+  if (1 != hdr_check.found_chunked)
+  {
+    fprintf (stderr,
+             "Chunked encoding header was not found in the response\n");
+    return 8;
+  }
+  if (1 != hdr_check.found_footer)
+  {
+    fprintf (stderr,
+             "The specified footer was not found in the response\n");
+    return 16;
+  }
   return validate (cbc, 64);
 }
 
-static int
-testMultithreadedPoolGet ()
+
+static unsigned int
+testMultithreadedPoolGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+  struct curl_slist *h_list = NULL;
+  struct headers_check_result hdr_check;
 
+  port = port_global;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+    if (0 == port_global)
+      port_global = port; /* Re-use the same port for all checks */
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  hdr_check.found_chunked = 0;
+  hdr_check.found_footer = 0;
+  curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback);
+  curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check);
+  if (conn_close)
+  {
+    h_list = curl_slist_append (h_list, "Connection: close");
+    if (NULL == h_list)
+      abort ();
+    curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list);
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    curl_slist_free_all (h_list);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
+  curl_slist_free_all (h_list);
   MHD_stop_daemon (d);
+  if (1 != hdr_check.found_chunked)
+  {
+    fprintf (stderr,
+             "Chunked encoding header was not found in the response\n");
+    return 8;
+  }
+  if (1 != hdr_check.found_footer)
+  {
+    fprintf (stderr,
+             "The specified footer was not found in the response\n");
+    return 16;
+  }
   return validate (cbc, 64);
 }
 
-static int
-testExternalGet ()
+
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -291,124 +571,237 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  uint16_t port;
+  struct curl_slist *h_list = NULL;
+  struct headers_check_result hdr_check;
 
+  port = port_global;
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+    if (0 == port_global)
+      port_global = port; /* Re-use the same port for all checks */
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  hdr_check.found_chunked = 0;
+  hdr_check.found_footer = 0;
+  curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback);
+  curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check);
+  if (conn_close)
+  {
+    h_list = curl_slist_append (h_list, "Connection: close");
+    if (NULL == h_list)
+      abort ();
+    curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list);
+  }
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    curl_slist_free_all (h_list);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
-    {
-      curl_multi_cleanup (multi);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 1024;
-    }
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    curl_slist_free_all (h_list);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
   start = time (NULL);
   while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      curl_slist_free_all (h_list);
+      MHD_stop_daemon (d);
+      return 2048;
     }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      curl_slist_free_all (h_list);
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      curl_slist_free_all (h_list);
+      h_list = NULL;
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
   MHD_stop_daemon (d);
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
+  curl_slist_free_all (h_list);
+  if (1 != hdr_check.found_chunked)
+  {
+    fprintf (stderr,
+             "Chunked encoding header was not found in the response\n");
+    return 8;
+  }
+  if (1 != hdr_check.found_footer)
+  {
+    fprintf (stderr,
+             "The specified footer was not found in the response\n");
+    return 16;
+  }
   return validate (cbc, 8192);
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalGet ();
-  errorCount += testMultithreadedGet ();
-  errorCount += testMultithreadedPoolGet ();
+  conn_close = has_in_name (argv[0], "_close");
+  resp_string = has_in_name (argv[0], "_string");
+  resp_sized = has_in_name (argv[0], "_sized");
+  resp_empty = has_in_name (argv[0], "_empty");
+  chunked_forced = has_in_name (argv[0], "_forced");
+  if (resp_string)
+    resp_sized = ! 0;
+  if (resp_sized)
+    chunked_forced = ! 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port_global = 0;
+  else
+  {
+    port_global = 4100;
+    if (conn_close)
+      port_global += 1 << 0;
+    if (resp_string)
+      port_global += 1 << 1;
+    if (resp_sized)
+      port_global += 1 << 2;
+    if (resp_empty)
+      port_global += 1 << 3;
+    if (chunked_forced)
+      port_global += 1 << 4;
+  }
+
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet ();
+    errorCount += testMultithreadedGet ();
+    errorCount += testMultithreadedPoolGet ();
+  }
   errorCount += testExternalGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_get_close_keep_alive.c b/src/testcurl/test_get_close_keep_alive.c
new file mode 100644
index 0000000..81f7576
--- /dev/null
+++ b/src/testcurl/test_get_close_keep_alive.c
@@ -0,0 +1,1136 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+     Copyright (C) 2007, 2009, 2011 Christian Grothoff
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_get_close_keep_alive.c
+ * @brief  Testcase for libmicrohttpd "Close" and "Keep-Alive" connection.
+ * @details Testcases for testing of MHD automatic choice between "Close" and
+ *          "Keep-Alive" connections. Also tested selected HTTP version and
+ *          "Connection:" headers.
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+#include "mhd_sockets.h" /* only macros used */
+
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif /* HAVE_STRINGS_H */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+#if MHD_CPU_COUNT > 32
+#undef MHD_CPU_COUNT
+/* Limit to reasonable value */
+#define MHD_CPU_COUNT 32
+#endif /* MHD_CPU_COUNT > 32 */
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+#define EXPECTED_URI_BASE_PATH  "/hello_world"
+#define EXPECTED_URI_QUERY      "a=%26&b=c"
+#define EXPECTED_URI_FULL_PATH  EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY
+#define HDR_CONN_CLOSE_VALUE      "close"
+#define HDR_CONN_CLOSE            MHD_HTTP_HEADER_CONNECTION ": " \
+                                  HDR_CONN_CLOSE_VALUE
+#define HDR_CONN_KEEP_ALIVE_VALUE "Keep-Alive"
+#define HDR_CONN_KEEP_ALIVE       MHD_HTTP_HEADER_CONNECTION ": " \
+                                  HDR_CONN_KEEP_ALIVE_VALUE
+
+/* Global parameters */
+static int oneone;           /**< Use HTTP/1.1 instead of HTTP/1.0 for requests*/
+static int conn_close;       /**< Don't use Keep-Alive */
+static uint16_t global_port; /**< MHD daemons listen port number */
+static int slow_reply = 0; /**< Slowdown MHD replies */
+static int ignore_response_errors = 0; /**< Do not fail test if CURL
+                                            returns error */
+static int response_timeout_val = TIMEOUTS_VAL;
+
+/* Current test parameters */
+/* Poor thread sync, but enough for the testing */
+static volatile int mhd_add_close; /**< Add "Connection: close" header by MHD */
+static volatile int mhd_set_10_cmptbl; /**< Set MHD_RF_HTTP_1_0_COMPATIBLE_STRICT response flag */
+static volatile int mhd_set_10_server; /**< Set MHD_RF_HTTP_1_0_SERVER response flag */
+static volatile int mhd_set_k_a_send; /**< Set MHD_RF_SEND_KEEP_ALIVE_HEADER response flag */
+
+/* Static helper variables */
+static struct curl_slist *curl_close_hdr;   /**< CURL "Connection: close" header */
+static struct curl_slist *curl_k_alive_hdr; /**< CURL "Connection: keep-alive" header */
+static struct curl_slist *curl_both_hdrs;   /**< CURL both "Connection: keep-alive" and "close" headers */
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+
+  curl_close_hdr = NULL;
+  curl_close_hdr = curl_slist_append (curl_close_hdr,
+                                      HDR_CONN_CLOSE);
+  if (NULL == curl_close_hdr)
+    externalErrorExit ();
+
+  curl_k_alive_hdr = NULL;
+  curl_k_alive_hdr = curl_slist_append (curl_k_alive_hdr,
+                                        HDR_CONN_KEEP_ALIVE);
+  if (NULL == curl_k_alive_hdr)
+    externalErrorExit ();
+
+  curl_both_hdrs = NULL;
+  curl_both_hdrs = curl_slist_append (curl_both_hdrs,
+                                      HDR_CONN_KEEP_ALIVE);
+  if (NULL == curl_both_hdrs)
+    externalErrorExit ();
+  curl_both_hdrs = curl_slist_append (curl_both_hdrs,
+                                      HDR_CONN_CLOSE);
+  if (NULL == curl_both_hdrs)
+    externalErrorExit ();
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_slist_free_all (curl_both_hdrs);
+  curl_slist_free_all (curl_k_alive_hdr);
+  curl_slist_free_all (curl_close_hdr);
+
+  curl_global_cleanup ();
+}
+
+
+struct headers_check_result
+{
+  int found_http11;
+  int found_http10;
+  int found_conn_close;
+  int found_conn_keep_alive;
+};
+
+static size_t
+lcurl_hdr_callback (char *buffer, size_t size, size_t nitems,
+                    void *userdata)
+{
+  const size_t data_size = size * nitems;
+  struct headers_check_result *check_res =
+    (struct headers_check_result *) userdata;
+
+  if ((strlen (MHD_HTTP_VERSION_1_1) < data_size) &&
+      (0 == memcmp (MHD_HTTP_VERSION_1_1, buffer,
+                    strlen (MHD_HTTP_VERSION_1_1))))
+    check_res->found_http11 = 1;
+  else if ((strlen (MHD_HTTP_VERSION_1_0) < data_size) &&
+           (0 == memcmp (MHD_HTTP_VERSION_1_0, buffer,
+                         strlen (MHD_HTTP_VERSION_1_0))))
+    check_res->found_http10 = 1;
+  else if ((data_size == strlen (HDR_CONN_CLOSE) + 2) &&
+           (0 == memcmp (buffer, HDR_CONN_CLOSE "\r\n", data_size)))
+    check_res->found_conn_close = 1;
+  else if ((data_size == strlen (HDR_CONN_KEEP_ALIVE) + 2) &&
+           (0 == memcmp (buffer, HDR_CONN_KEEP_ALIVE "\r\n", data_size)))
+    check_res->found_conn_keep_alive = 1;
+
+  return data_size;
+}
+
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    externalErrorExit ();  /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static void *
+log_cb (void *cls,
+        const char *uri,
+        struct MHD_Connection *con)
+{
+  (void) cls;
+  (void) con;
+  if (0 != strcmp (uri,
+                   EXPECTED_URI_FULL_PATH))
+  {
+    fprintf (stderr,
+             "Wrong URI: `%s', line: %d\n",
+             uri, __LINE__);
+    exit (22);
+  }
+  return NULL;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;       /* Unused. Silence compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  if (slow_reply)
+    usleep (200000);
+
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  if (NULL == response)
+  {
+    fprintf (stderr, "Failed to create response. Line: %d\n", __LINE__);
+    exit (19);
+  }
+  if (mhd_add_close)
+  {
+    if (MHD_YES != MHD_add_response_header (response,
+                                            MHD_HTTP_HEADER_CONNECTION,
+                                            HDR_CONN_CLOSE_VALUE))
+    {
+      fprintf (stderr, "Failed to add header. Line: %d\n", __LINE__);
+      exit (19);
+    }
+  }
+  if (MHD_YES != MHD_set_response_options (response,
+                                           (mhd_set_10_cmptbl ?
+                                            MHD_RF_HTTP_1_0_COMPATIBLE_STRICT
+                                               : 0)
+                                           | (mhd_set_10_server ?
+                                              MHD_RF_HTTP_1_0_SERVER
+                                               : 0)
+                                           | (mhd_set_k_a_send ?
+                                              MHD_RF_SEND_KEEP_ALIVE_HEADER
+                                               : 0), MHD_RO_END))
+  {
+    fprintf (stderr, "Failed to set response flags. Line: %d\n", __LINE__);
+    exit (19);
+  }
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+  {
+    fprintf (stderr, "Failed to queue response. Line: %d\n", __LINE__);
+    exit (19);
+  }
+  return ret;
+}
+
+
+struct curlQueryParams
+{
+  /* Destination path for CURL query */
+  const char *queryPath;
+
+  /* Destination port for CURL query */
+  uint16_t queryPort;
+
+  /* CURL query result error flag */
+  volatile unsigned int queryError;
+};
+
+
+static CURL *
+curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc,
+                     struct headers_check_result *hdr_chk_result,
+                     int add_hdr_close, int add_hdr_k_alive)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    externalErrorExit ();
+  }
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION,
+                                     lcurl_hdr_callback)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA,
+                                     hdr_chk_result)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+  {
+    fprintf (stderr, "curl_easy_setopt() failed.\n");
+    externalErrorExit ();
+  }
+  if (add_hdr_close && add_hdr_k_alive)
+  { /* This combination is actually incorrect */
+    if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_both_hdrs))
+    {
+      fprintf (stderr, "Set libcurl HTTP header failed.\n");
+      externalErrorExit ();
+    }
+  }
+  else if (add_hdr_close)
+  {
+    if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_close_hdr))
+    {
+      fprintf (stderr, "Set libcurl HTTP header failed.\n");
+      externalErrorExit ();
+    }
+  }
+  else if (add_hdr_k_alive)
+  {
+    if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_k_alive_hdr))
+    {
+      fprintf (stderr, "Set libcurl HTTP header failed.\n");
+      externalErrorExit ();
+    }
+  }
+
+  return c;
+}
+
+
+static void
+print_test_params (int add_hdr_close,
+                   int add_hdr_k_alive)
+{
+  fprintf (stderr, "Request HTTP/%s| ", oneone ? "1.1" : "1.0");
+  fprintf (stderr, "Connection must be: %s| ",
+           conn_close ? "close" : "keep-alive");
+  fprintf (stderr, "Request \"close\": %s| ",
+           add_hdr_close ? "    used" : "NOT used");
+  fprintf (stderr, "Request \"keep-alive\": %s| ",
+           add_hdr_k_alive ? "    used" : "NOT used");
+  fprintf (stderr, "MHD response \"close\": %s| ",
+           mhd_add_close ? "    used" : "NOT used");
+  fprintf (stderr, "MHD response 1.0 strict compatible: %s| ",
+           mhd_set_10_cmptbl ? "yes" : " NO");
+  fprintf (stderr, "MHD response 1.0 server: %s| ",
+           mhd_set_10_server ? "yes" : " NO");
+  fprintf (stderr, "MHD response send \"Keep-Alive\": %s|",
+           mhd_set_k_a_send ? "yes" : " NO");
+  fprintf (stderr, "\n*** ");
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  multi = NULL;
+  multi = curl_multi_init ();
+  if (multi == NULL)
+  {
+    fprintf (stderr, "curl_multi_init() failed.\n");
+    externalErrorExit ();
+  }
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+  {
+    fprintf (stderr, "curl_multi_add_handle() failed.\n");
+    externalErrorExit ();
+  }
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+          {
+            fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n");
+            externalErrorExit ();
+          }
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+        {
+          fprintf (stderr, "curl_multi_fdset() failed.\n");
+          externalErrorExit ();
+        }
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+    {
+      fprintf (stderr, "MHD_get_fdset() failed. Line: %d\n", __LINE__);
+      exit (11);
+      break;
+    }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+    {
+      fprintf (stderr, "MHD_run_from_select() failed. Line: %d\n", __LINE__);
+      exit (11);
+    }
+  }
+
+  return ret;
+}
+
+
+static unsigned int
+getMhdActiveConnections (struct MHD_Daemon *d)
+{
+  const union MHD_DaemonInfo *dinfo;
+  /* The next method is unreliable unless it's known that no
+   * connections are started or finished in parallel */
+  dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_CURRENT_CONNECTIONS);
+  if (NULL == dinfo)
+  {
+    fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+    abort ();
+  }
+  return dinfo->num_connections;
+}
+
+
+static unsigned int
+doCurlQueryInThread (struct MHD_Daemon *d,
+                     struct curlQueryParams *p,
+                     int add_hdr_close,
+                     int add_hdr_k_alive)
+{
+  const union MHD_DaemonInfo *dinfo;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  struct headers_check_result hdr_res;
+  CURLcode errornum;
+  int use_external_poll;
+
+  dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+  {
+    fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+    abort ();
+  }
+  use_external_poll = (0 == (dinfo->flags
+                             & MHD_USE_INTERNAL_POLLING_THREAD));
+
+  if (NULL == p->queryPath)
+    abort ();
+
+  if (0 == p->queryPort)
+    abort ();
+
+  cbc.buf = buf;
+  cbc.size = sizeof(buf);
+  cbc.pos = 0;
+
+  hdr_res.found_http11 = 0;
+  hdr_res.found_http10 = 0;
+  hdr_res.found_conn_close = 0;
+  hdr_res.found_conn_keep_alive = 0;
+
+  c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc, &hdr_res,
+                           add_hdr_close, add_hdr_k_alive);
+
+  if (! use_external_poll)
+    errornum = curl_easy_perform (c);
+  else
+    errornum = performQueryExternal (d, c);
+  if (ignore_response_errors)
+  {
+    p->queryError = 0;
+    curl_easy_cleanup (c);
+
+    return p->queryError;
+  }
+  if (CURLE_OK != errornum)
+  {
+    p->queryError = 1;
+    fprintf (stderr,
+             "libcurl query failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    libcurlErrorExit ();
+  }
+  else
+  {
+    if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH))
+    {
+      fprintf (stderr, "curl reports wrong size of MHD reply body data.\n");
+      p->queryError = 1;
+    }
+    else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf,
+                           strlen (EXPECTED_URI_BASE_PATH)))
+    {
+      fprintf (stderr, "curl reports wrong MHD reply body data.\n");
+      p->queryError = 1;
+    }
+    else
+      p->queryError = 0;
+  }
+
+  if (! hdr_res.found_http11 && ! hdr_res.found_http10)
+  {
+    print_test_params (add_hdr_close, add_hdr_k_alive);
+    fprintf (stderr, "No know HTTP versions were found in the "
+             "reply header. Line: %d\n", __LINE__);
+    exit (24);
+  }
+  else if (hdr_res.found_http11 && hdr_res.found_http10)
+  {
+    print_test_params (add_hdr_close, add_hdr_k_alive);
+    fprintf (stderr, "Both HTTP/1.1 and HTTP/1.0 were found in the "
+             "reply header. Line: %d\n", __LINE__);
+    exit (24);
+  }
+
+  if (conn_close)
+  {
+    if (! hdr_res.found_conn_close)
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "\"Connection: close\" was not found in"
+               " MHD reply headers.\n");
+      p->queryError |= 2;
+    }
+    if (hdr_res.found_conn_keep_alive)
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "\"Connection: keep-alive\" was found in"
+               " MHD reply headers.\n");
+      p->queryError |= 2;
+    }
+    if (use_external_poll)
+    { /* The number of MHD connection can queried only with external poll.
+       * otherwise it creates a race condition. */
+      if (0 != getMhdActiveConnections (d))
+      {
+        print_test_params (add_hdr_close, add_hdr_k_alive);
+        fprintf (stderr, "MHD still has active connection "
+                 "after response has been sent.\n");
+        p->queryError |= 2;
+      }
+    }
+  }
+  else
+  { /* Keep-Alive */
+    if (! oneone || mhd_set_10_server || mhd_set_k_a_send)
+    { /* Should have "Connection: Keep-Alive" */
+      if (! hdr_res.found_conn_keep_alive)
+      {
+        print_test_params (add_hdr_close, add_hdr_k_alive);
+        fprintf (stderr, "\"Connection: keep-alive\" was not found in"
+                 " MHD reply headers.\n");
+        p->queryError |= 2;
+      }
+    }
+    else
+    { /* Should NOT have "Connection: Keep-Alive" */
+      if (hdr_res.found_conn_keep_alive)
+      {
+        print_test_params (add_hdr_close, add_hdr_k_alive);
+        fprintf (stderr, "\"Connection: keep-alive\" was found in"
+                 " MHD reply headers.\n");
+        p->queryError |= 2;
+      }
+    }
+    if (hdr_res.found_conn_close)
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "\"Connection: close\" was found in"
+               " MHD reply headers.\n");
+      p->queryError |= 2;
+    }
+    if (use_external_poll)
+    { /* The number of MHD connection can be queried only with external poll.
+       * otherwise it creates a race condition. */
+      unsigned int num_conn = getMhdActiveConnections (d);
+      if (0 == num_conn)
+      {
+        print_test_params (add_hdr_close, add_hdr_k_alive);
+        fprintf (stderr, "MHD has no active connection "
+                 "after response has been sent.\n");
+        p->queryError |= 2;
+      }
+      else if (1 != num_conn)
+      {
+        print_test_params (add_hdr_close, add_hdr_k_alive);
+        fprintf (stderr, "MHD has wrong number of active connection (%u) "
+                 "after response has been sent. Line: %d\n", num_conn,
+                 __LINE__);
+        exit (23);
+      }
+    }
+  }
+
+#if defined(CURL_AT_LEAST_VERSION) && CURL_AT_LEAST_VERSION (7, 45, 0)
+  if (! use_external_poll)
+  {
+    /* libcurl closes connection socket with curl_multi_remove_handle () /
+       curl_multi_cleanup() */
+    curl_socket_t curl_sckt;
+    if (CURLE_OK !=  curl_easy_getinfo (c, CURLINFO_ACTIVESOCKET, &curl_sckt))
+    {
+      fprintf (stderr,
+               "Failed to get libcurl active socket.\n");
+      libcurlErrorExit ();
+    }
+
+    if (conn_close && (CURL_SOCKET_BAD != curl_sckt))
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "libcurl still has active connection "
+               "after performing the test query.\n");
+      p->queryError |= 2;
+    }
+    else if (! conn_close && (CURL_SOCKET_BAD == curl_sckt))
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "libcurl has no active connection "
+               "after performing the test query.\n");
+      p->queryError |= 2;
+    }
+  }
+#endif
+
+  if (! mhd_set_10_server)
+  { /* Response must be HTTP/1.1 */
+    if (hdr_res.found_http10)
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "Reply has HTTP/1.0 version, while it "
+               "must be HTTP/1.1.\n");
+      p->queryError |= 4;
+    }
+  }
+  else
+  { /* Response must be HTTP/1.0 */
+    if (hdr_res.found_http11)
+    {
+      print_test_params (add_hdr_close, add_hdr_k_alive);
+      fprintf (stderr, "Reply has HTTP/1.1 version, while it "
+               "must be HTTP/1.0.\n");
+      p->queryError |= 4;
+    }
+  }
+  curl_easy_cleanup (c);
+
+  return p->queryError;
+}
+
+
+/* Perform test queries and shut down MHD daemon */
+static unsigned int
+performTestQueries (struct MHD_Daemon *d, uint16_t d_port)
+{
+  struct curlQueryParams qParam;
+  unsigned int ret = 0;          /* Return value */
+  int i = 0;
+  /* masks */
+  const int m_mhd_close = 1 << (i++);
+  const int m_10_cmptbl = 1 << (i++);
+  const int m_10_server = 1 << (i++);
+  const int m_k_a_send = 1 << (i++);
+  const int m_client_close = 1 << (i++);
+  const int m_client_k_alive = 1 << (i++);
+
+  qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH;
+  qParam.queryPort = d_port;   /* Connect to the daemon */
+
+  for (i = (1 << i) - 1; 0 <= i; i--)
+  {
+    const int f_mhd_close = (0 == (i & m_mhd_close)); /**< Use MHD "close" header */
+    const int f_10_cmptbl = (0 == (i & m_10_cmptbl)); /**< Use MHD MHD_RF_HTTP_1_0_COMPATIBLE_STRICT flag */
+    const int f_10_server = (0 == (i & m_10_server)); /**< Use MHD MHD_RF_HTTP_1_0_SERVER flag */
+    const int f_k_a_send = (0 == (i & m_k_a_send));   /**< Use MHD MHD_RF_SEND_KEEP_ALIVE_HEADER flag */
+    const int f_client_close = (0 == (i & m_client_close)); /**< Use libcurl "close" header */
+    const int f_client_k_alive = (0 == (i & m_client_k_alive)); /**< Use libcurl "Keep-Alive" header */
+    int res_close; /**< Indicate the result of the test query should be closed connection */
+
+    if (f_mhd_close)         /* Connection with server's "close" header must be always closed */
+      res_close = 1;
+    else if (f_client_close) /* Connection with client's "close" header must be always closed */
+      res_close = 1;
+    else if (f_10_cmptbl)    /* Connection in strict HTTP/1.0 compatible mode must be always closed */
+      res_close = 1;
+    else if (! oneone || f_10_server)
+      /* With HTTP/1.0 client or server connection must be close unless client use "keep-alive" header */
+      res_close = ! f_client_k_alive;
+    else
+      res_close = 0; /* HTTP/1.1 is "keep-alive" by default */
+
+    if ((! ! res_close) != (! ! conn_close))
+      continue; /* Another mode is in test currently */
+
+    mhd_add_close = f_mhd_close;
+    mhd_set_10_cmptbl = f_10_cmptbl;
+    mhd_set_10_server = f_10_server;
+    mhd_set_k_a_send = f_k_a_send;
+
+    ret <<= 3;                   /* Remember errors for each step */
+    ret |= doCurlQueryInThread (d, &qParam, f_client_close, f_client_k_alive);
+  }
+
+  MHD_stop_daemon (d);
+
+  return ret;
+}
+
+
+enum testMhdThreadsType
+{
+  testMhdThreadExternal              = 0,
+  testMhdThreadInternal              = MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION
+                                       | MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPool
+};
+
+enum testMhdPollType
+{
+  testMhdPollBySelect = 0,
+  testMhdPollByPoll   = MHD_USE_POLL,
+  testMhdPollByEpoll  = MHD_USE_EPOLL,
+  testMhdPollAuto     = MHD_USE_AUTO
+};
+
+/* Get number of threads for thread pool depending
+ * on used poll function and test type. */
+static unsigned int
+testNumThreadsForPool (enum testMhdPollType pollType)
+{
+  unsigned int numThreads = MHD_CPU_COUNT;
+  (void) pollType; /* Don't care about pollType for this test */
+  return numThreads; /* No practical limit for non-cleanup test */
+}
+
+
+static struct MHD_Daemon *
+startTestMhdDaemon (enum testMhdThreadsType thrType,
+                    enum testMhdPollType pollType, uint16_t *pport)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *dinfo;
+
+  if ( (0 == *pport) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    *pport = 4050;
+    if (oneone)
+      *pport += 1;
+    if (! conn_close)
+      *pport += 2;
+  }
+
+  if (testMhdThreadInternalPool != thrType)
+    d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType)
+                          | MHD_USE_ERROR_LOG,
+                          *pport, NULL, NULL,
+                          &ahc_echo, NULL,
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_END);
+  else
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                          | ((unsigned int) pollType)
+                          | MHD_USE_ERROR_LOG,
+                          *pport, NULL, NULL,
+                          &ahc_echo, NULL,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          testNumThreadsForPool (pollType),
+                          MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                          MHD_OPTION_END);
+
+  if (NULL == d)
+  {
+    fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno);
+    abort ();
+  }
+
+  if (0 == *pport)
+  {
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+      abort ();
+    }
+    *pport = dinfo->port;
+    if (0 == global_port)
+      global_port = *pport; /* Reuse the same port for all tests */
+  }
+
+  return d;
+}
+
+
+/* Test runners */
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port);
+
+  return performTestQueries (d, d_port);
+}
+
+
+static unsigned int
+testInternalGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType,
+                          &d_port);
+
+  return performTestQueries (d, d_port);
+}
+
+
+static unsigned int
+testMultithreadedGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType,
+                          &d_port);
+  return performTestQueries (d, d_port);
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+
+  d = startTestMhdDaemon (testMhdThreadInternalPool, pollType,
+                          &d_port);
+  return performTestQueries (d, d_port);
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  int verbose = 0;
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = ! has_in_name (argv[0], "10");
+  conn_close = has_in_name (argv[0], "_close");
+  if (! conn_close && ! has_in_name (argv[0], "_keep_alive"))
+    return 99;
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+
+  test_global_init ();
+
+  /* Could be set to non-zero value to enforce using specific port
+   * in the test */
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result = testInternalGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedPoolGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result = testInternalGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result = testInternalGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+    }
+  }
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+
+  test_global_cleanup ();
+
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_get_empty.c b/src/testcurl/test_get_empty.c
new file mode 100644
index 0000000..0f20c05
--- /dev/null
+++ b/src/testcurl/test_get_empty.c
@@ -0,0 +1,962 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2009, 2011, 2019 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_get_empty.c
+ * @brief  Testcase for libmicrohttpd GET operations returning an empty body
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+#include "mhd_sockets.h" /* only macros used */
+
+
+#define EXPECTED_URI_PATH "/hello_world?a=%26&b=c"
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+static int oneone;
+static uint16_t global_port;
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    return 0;                   /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static void *
+log_cb (void *cls,
+        const char *uri,
+        struct MHD_Connection *con)
+{
+  (void) cls;
+  (void) con;
+  if (0 != strcmp (uri,
+                   EXPECTED_URI_PATH))
+  {
+    fprintf (stderr,
+             "Wrong URI: `%s'\n",
+             uri);
+    _exit (22);
+  }
+  return NULL;
+}
+
+
+static int
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  const char *me = cls;
+  struct MHD_Response *response;
+  int ret;
+  (void) version;
+  (void) upload_data;
+  (void) upload_data_size;       /* Unused. Silence compiler warning. */
+
+  if (0 != strcmp (me, method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_NO_CONTENT,
+                            response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (19);
+  }
+  return ret;
+}
+
+
+static unsigned int
+testInternalGet (uint32_t poll_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1220;
+    if (oneone)
+      global_port += 20;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, "GET",
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 4;
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedGet (uint32_t poll_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1221;
+    if (oneone)
+      global_port += 20;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, "GET",
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 64;
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (uint32_t poll_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1222;
+    if (oneone)
+      global_port += 20;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, "GET",
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 64;
+  return 0;
+}
+
+
+static unsigned int
+testExternalGet ()
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLM *multi;
+  CURLMcode mret;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket maxsock;
+  int maxposixs;
+  int running;
+  struct CURLMsg *msg;
+  time_t start;
+  struct timeval tv;
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1223;
+    if (oneone)
+      global_port += 20;
+  }
+
+  multi = NULL;
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        global_port, NULL, NULL,
+                        &ahc_echo, "GET",
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 256;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+  multi = curl_multi_init ();
+  if (multi == NULL)
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
+  mret = curl_multi_add_handle (multi, c);
+  if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 2048;
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxsock > maxposixs)
+      maxposixs = maxsock;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 8192;
+  return 0;
+}
+
+
+static unsigned int
+testUnknownPortGet (uint32_t poll_flag)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *di;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+  uint16_t port;
+
+  struct sockaddr_in addr;
+  socklen_t addr_len = sizeof(addr);
+  memset (&addr, 0, sizeof(addr));
+  addr.sin_family = AF_INET;
+  addr.sin_port = 0;
+  addr.sin_addr.s_addr = INADDR_ANY;
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        0, NULL, NULL, &ahc_echo, "GET",
+                        MHD_OPTION_SOCK_ADDR, &addr,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+  {
+    di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
+    if (di == NULL)
+      return 65536;
+
+    if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len))
+      return 131072;
+
+    if (addr.sin_family != AF_INET)
+      return 26214;
+    port = ntohs (addr.sin_port);
+  }
+  else
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+
+  snprintf (buf,
+            sizeof(buf),
+            "http://127.0.0.1:%u%s",
+            (unsigned int) port,
+            EXPECTED_URI_PATH);
+
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, buf);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 524288;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 1048576;
+  return 0;
+}
+
+
+static unsigned int
+testStopRace (uint32_t poll_flag)
+{
+  struct sockaddr_in sin;
+  MHD_socket fd;
+  struct MHD_Daemon *d;
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1224;
+    if (oneone)
+      global_port += 20;
+  }
+
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_echo, "GET",
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+
+  fd = socket (PF_INET, SOCK_STREAM, 0);
+  if (fd == MHD_INVALID_SOCKET)
+  {
+    fprintf (stderr, "socket error\n");
+    return 256;
+  }
+
+  memset (&sin, 0, sizeof(sin));
+  sin.sin_family = AF_INET;
+  sin.sin_port = htons (global_port);
+  sin.sin_addr.s_addr = htonl (0x7f000001);
+
+  if (connect (fd, (struct sockaddr *) (&sin), sizeof(sin)) < 0)
+  {
+    fprintf (stderr, "connect error\n");
+    MHD_socket_close_chk_ (fd);
+    return 512;
+  }
+
+  /*  printf("Waiting\n"); */
+  /* Let the thread get going. */
+  usleep (500000);
+
+  /* printf("Stopping daemon\n"); */
+  MHD_stop_daemon (d);
+
+  MHD_socket_close_chk_ (fd);
+
+  /* printf("good\n"); */
+  return 0;
+}
+
+
+static int
+ahc_empty (void *cls,
+           struct MHD_Connection *connection,
+           const char *url,
+           const char *method,
+           const char *version,
+           const char *upload_data, size_t *upload_data_size,
+           void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  int ret;
+  (void) cls;
+  (void) url;
+  (void) url;
+  (void) version;          /* Unused. Silence compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size; /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp ("GET", method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_empty (MHD_RF_NONE);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+  {
+    fprintf (stderr, "Failed to queue response.\n");
+    _exit (20);
+  }
+  return ret;
+}
+
+
+static int
+curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size,
+                 void *cls)
+{
+  static const char *excess_found = "Excess found";
+  const size_t str_size = strlen (excess_found);
+  (void) c;      /* Unused. Silent compiler warning. */
+
+  if ((CURLINFO_TEXT == type)
+      && (size >= str_size)
+      && (0 == strncmp (excess_found, data, str_size)))
+    *(int *) cls = 1;
+  return 0;
+}
+
+
+static unsigned int
+testEmptyGet (uint32_t poll_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLcode errornum;
+  int excess_found = 0;
+
+  if ( (0 == global_port) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    global_port = 1225;
+    if (oneone)
+      global_port += 20;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        global_port, NULL, NULL,
+                        &ahc_empty, NULL,
+                        MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 4194304;
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    global_port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) global_port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound);
+  curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found);
+  curl_easy_setopt (c, CURLOPT_VERBOSE, 1L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 8388608;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != 0)
+    return 16777216;
+  if (excess_found)
+    return 33554432;
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  int verbose = 0;
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  verbose = has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose");
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result += testInternalGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (0).\n");
+    errorCount += test_result;
+    test_result += testMultithreadedGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testMultithreadedGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (0).\n");
+    errorCount += test_result;
+    test_result += testMultithreadedPoolGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testMultithreadedPoolGet (0) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (0).\n");
+    errorCount += test_result;
+    test_result += testUnknownPortGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testUnknownPortGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testUnknownPortGet (0).\n");
+    errorCount += test_result;
+    test_result += testEmptyGet (0);
+    if (test_result)
+      fprintf (stderr, "FAILED: testEmptyGet (0) - %u.\n", test_result);
+    else if (verbose)
+      printf ("PASSED: testEmptyGet (0).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result += testInternalGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testMultithreadedGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testMultithreadedGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testMultithreadedPoolGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedPoolGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedPoolGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testUnknownPortGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testUnknownPortGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+      test_result += testEmptyGet (MHD_USE_POLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_POLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testEmptyGet (MHD_USE_POLL).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result += testInternalGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+      test_result += testMultithreadedPoolGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr,
+                 "FAILED: testMultithreadedPoolGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testMultithreadedPoolGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+      test_result += testUnknownPortGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testUnknownPortGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+      test_result += testEmptyGet (MHD_USE_EPOLL);
+      if (test_result)
+        fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_EPOLL) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testEmptyGet (MHD_USE_EPOLL).\n");
+      errorCount += test_result;
+    }
+  }
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_get_iovec.c b/src/testcurl/test_get_iovec.c
new file mode 100644
index 0000000..4d4b24e
--- /dev/null
+++ b/src/testcurl/test_get_iovec.c
@@ -0,0 +1,779 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007-2021 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_get_iovec.c
+ * @brief  Testcase for libmicrohttpd response from scatter/gather array
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ * @author Lawrence Sebald
+ */
+
+/*
+ * This test is largely derived from the test_get_sendfile.c file, with the
+ * daemon using MHD_create_response_from_iovec instead of working from an fd.
+ */
+
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#ifdef HAVE_STDBOOL_H
+#include <stdbool.h>
+#endif
+#include "mhd_sockets.h"
+#include "mhd_has_in_name.h"
+
+#ifndef WINDOWS
+#include <sys/socket.h>
+#include <unistd.h>
+#endif
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+#define TESTSTR_IOVLEN 20480
+#define TESTSTR_IOVCNT 20
+#define TESTSTR_SIZE   (TESTSTR_IOVCNT * TESTSTR_IOVLEN)
+
+static int oneone;
+
+static int readbuf[TESTSTR_SIZE * 2 / sizeof(int)];
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    _exit (7);                   /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static void
+iov_free_callback (void *cls)
+{
+  free (cls);
+}
+
+
+struct iovncont_data
+{
+  void *ptrs[TESTSTR_IOVCNT];
+};
+
+static void
+iovncont_free_callback (void *cls)
+{
+  struct iovncont_data *data = (struct iovncont_data *) cls;
+  unsigned int i;
+
+  for (i = 0; i < TESTSTR_IOVCNT; ++i)
+    free (data->ptrs[i]);
+  free (data);
+}
+
+
+static int
+check_read_data (const void *ptr, size_t len)
+{
+  const int *buf;
+  size_t i;
+
+  if (len % sizeof(int))
+    return -1;
+
+  buf = (const int *) ptr;
+
+  for (i = 0; i < len / sizeof(int); ++i)
+  {
+    if (buf[i] != (int) i)
+      return -1;
+  }
+
+  return 0;
+}
+
+
+static enum MHD_Result
+ahc_cont (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  int *data;
+  struct MHD_IoVec iov[TESTSTR_IOVCNT];
+  int i;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  /* Create some test data. */
+  if (NULL == (data = malloc (TESTSTR_SIZE)))
+    return MHD_NO;
+
+  for (i = 0; i < (int) (TESTSTR_SIZE / sizeof(int)); ++i)
+  {
+    data[i] = i;
+  }
+
+  for (i = 0; i < TESTSTR_IOVCNT; ++i)
+  {
+    iov[i].iov_base = data + (((size_t) i)
+                              * (TESTSTR_SIZE / TESTSTR_IOVCNT / sizeof(int)));
+    iov[i].iov_len = TESTSTR_SIZE / TESTSTR_IOVCNT;
+  }
+
+  response = MHD_create_response_from_iovec (iov,
+                                             TESTSTR_IOVCNT,
+                                             &iov_free_callback,
+                                             data);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+    abort ();
+  return ret;
+}
+
+
+static enum MHD_Result
+ahc_ncont (void *cls,
+           struct MHD_Connection *connection,
+           const char *url,
+           const char *method,
+           const char *version,
+           const char *upload_data, size_t *upload_data_size,
+           void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct MHD_IoVec iov[TESTSTR_IOVCNT];
+  struct iovncont_data *clear_cls;
+  int i, j;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  clear_cls = malloc (sizeof(struct iovncont_data));
+  if (NULL == clear_cls)
+    abort ();
+  memset (iov, 0, sizeof(struct MHD_IoVec) * TESTSTR_IOVCNT);
+
+  /* Create some test data. */
+  for (j = TESTSTR_IOVCNT - 1; j >= 0; --j)
+  {
+    int *data;
+    data = malloc (TESTSTR_IOVLEN);
+    if (NULL == data)
+      abort ();
+    clear_cls->ptrs[j] = (void *) data;
+
+    for (i = 0; i < (int) (TESTSTR_IOVLEN / sizeof(int)); ++i)
+    {
+      data[i] = i + (j * (int) (TESTSTR_IOVLEN / sizeof(int)));
+    }
+    iov[j].iov_base = (const void *) data;
+    iov[j].iov_len = TESTSTR_IOVLEN;
+
+  }
+
+  response = MHD_create_response_from_iovec (iov,
+                                             TESTSTR_IOVCNT,
+                                             &iovncont_free_callback,
+                                             clear_cls);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (ret == MHD_NO)
+    abort ();
+  return ret;
+}
+
+
+static unsigned int
+testInternalGet (bool contiguous)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  struct CBC cbc;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1200;
+    if (oneone)
+      port += 10;
+  }
+
+  cbc.buf = (char *) readbuf;
+  cbc.size = sizeof(readbuf);
+  cbc.pos = 0;
+
+  if (contiguous)
+  {
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                          port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END);
+  }
+  else
+  {
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                          port, NULL, NULL, &ahc_ncont, NULL, MHD_OPTION_END);
+  }
+
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != TESTSTR_SIZE)
+    return 4;
+  if (0 != check_read_data (cbc.buf, cbc.pos))
+    return 8;
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedGet (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  struct CBC cbc;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1201;
+    if (oneone)
+      port += 10;
+  }
+
+  cbc.buf = (char *) readbuf;
+  cbc.size = sizeof(readbuf);
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | MHD_USE_AUTO,
+                        port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != TESTSTR_SIZE)
+    return 64;
+  if (0 != check_read_data (cbc.buf, cbc.pos))
+    return 128;
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  struct CBC cbc;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1202;
+    if (oneone)
+      port += 10;
+  }
+
+  cbc.buf = (char *) readbuf;
+  cbc.size = sizeof(readbuf);
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | MHD_USE_AUTO,
+                        port, NULL, NULL, &ahc_cont, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system!*/
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != TESTSTR_SIZE)
+    return 64;
+  if (0 != check_read_data (cbc.buf, cbc.pos))
+    return 128;
+  return 0;
+}
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  struct CBC cbc;
+  CURLM *multi;
+  CURLMcode mret;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
+  int running;
+  struct CURLMsg *msg;
+  time_t start;
+  struct timeval tv;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1203;
+    if (oneone)
+      port += 10;
+  }
+
+  multi = NULL;
+  cbc.buf = (char *) readbuf;
+  cbc.size = sizeof(readbuf);
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END);
+  if (d == NULL)
+    return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+  multi = curl_multi_init ();
+  if (multi == NULL)
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
+  mret = curl_multi_add_handle (multi, c);
+  if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 2048;
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
+  MHD_stop_daemon (d);
+  if (cbc.pos != TESTSTR_SIZE)
+    return 8192;
+  if (0 != check_read_data (cbc.buf, cbc.pos))
+    return 16384;
+  return 0;
+}
+
+
+static unsigned int
+testUnknownPortGet (void)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *di;
+  CURL *c;
+  struct CBC cbc;
+  CURLcode errornum;
+  uint16_t port;
+  char buf[2048];
+
+  struct sockaddr_in addr;
+  socklen_t addr_len = sizeof(addr);
+  memset (&addr, 0, sizeof(addr));
+  addr.sin_family = AF_INET;
+  addr.sin_port = 0;
+  addr.sin_addr.s_addr = INADDR_ANY;
+
+  cbc.buf = (char *) readbuf;
+  cbc.size = sizeof(readbuf);
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        0, NULL, NULL, &ahc_cont, NULL,
+                        MHD_OPTION_SOCK_ADDR, &addr,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 32768;
+
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+  {
+    di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
+    if (di == NULL)
+      return 65536;
+
+    if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len))
+      return 131072;
+
+    if (addr.sin_family != AF_INET)
+      return 26214;
+    port = ntohs (addr.sin_port);
+  }
+  else
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+
+  snprintf (buf, sizeof(buf), "http://127.0.0.1:%u/",
+            (unsigned int) port);
+
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_URL, buf);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  /* NOTE: use of CONNECTTIMEOUT without also
+     setting NOSIGNAL results in really weird
+     crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 524288;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != TESTSTR_SIZE)
+    return 1048576;
+  if (0 != check_read_data (cbc.buf, cbc.pos))
+    return 2097152;
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet (true);
+    errorCount += testInternalGet (false);
+    errorCount += testMultithreadedGet ();
+    errorCount += testMultithreadedPoolGet ();
+    errorCount += testUnknownPortGet ();
+  }
+  errorCount += testExternalGet ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_get_response_cleanup.c b/src/testcurl/test_get_response_cleanup.c
index f881746..1515e62 100644
--- a/src/testcurl/test_get_response_cleanup.c
+++ b/src/testcurl/test_get_response_cleanup.c
@@ -1,7 +1,7 @@
-/* DO NOT CHANGE THIS LINE */
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -15,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_get_response_cleanup.c
  * @brief  Testcase for libmicrohttpd response cleanup
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -35,6 +36,9 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <fcntl.h>
+#ifndef _WIN32
+#include <signal.h>
+#endif /* _WIN32 */
 
 #ifndef WINDOWS
 #include <sys/socket.h>
@@ -48,14 +52,14 @@
 #include <windows.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
-#endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
-#endif
+#include "mhd_has_in_name.h"
 
-#define TESTSTR "/* DO NOT CHANGE THIS LINE */"
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
 
 static int oneone;
 
@@ -67,22 +71,23 @@
 {
   pid_t ret;
 
-  ret = fork();
+  ret = fork ();
   if (ret != 0)
     return ret;
   execlp ("curl", "curl", "-s", "-N", "-o", "/dev/null", "-GET", url, NULL);
-  fprintf (stderr, 
-	   "Failed to exec curl: %s\n",
-	   strerror (errno));
-  _exit (-1);  
+  fprintf (stderr,
+           "Failed to exec curl: %s\n",
+           strerror (errno));
+  _exit (-1);
 }
 
+
 static void
 kill_curl (pid_t pid)
 {
   int status;
 
-  //fprintf (stderr, "Killing curl\n");
+  // fprintf (stderr, "Killing curl\n");
   kill (pid, SIGTERM);
   waitpid (pid, &status, 0);
 }
@@ -91,50 +96,54 @@
 static ssize_t
 push_callback (void *cls, uint64_t pos, char *buf, size_t max)
 {
+  (void) cls; (void) pos;  /* Unused. Silent compiler warning. */
+
   if (max == 0)
     return 0;
   buf[0] = 'd';
   return 1;
 }
 
+
 static void
 push_free_callback (void *cls)
 {
-  int *ok = cls;
+  int *ok_p = cls;
 
-  //fprintf (stderr, "Cleanup callback called!\n");
-  *ok = 0;
+  // fprintf (stderr, "Cleanup callback called!\n");
+  *ok_p = 0;
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
-  //fprintf (stderr, "In CB: %s!\n", method);
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
-  response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 
-						32 * 1024,
-						&push_callback,
-						&ok,
-						&push_free_callback);
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
+                                                32 * 1024,
+                                                &push_callback,
+                                                &ok,
+                                                &push_free_callback);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
@@ -143,57 +152,109 @@
 }
 
 
-static int
-testInternalGet ()
+static unsigned int
+testInternalGet (void)
 {
   struct MHD_Daemon *d;
   pid_t curl;
+  uint16_t port;
+  char url[127];
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1180;
+    if (oneone)
+      port += 10;
+  }
 
   ok = 1;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
-  curl = fork_curl ("http://127.0.0.1:11080/");
-  sleep (1);
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/",
+            (unsigned int) port);
+  curl = fork_curl (url);
+  (void) sleep (1);
   kill_curl (curl);
-  sleep (1);
-  // fprintf (stderr, "Stopping daemon!\n");
+  (void) sleep (1);
+  /* fprintf (stderr, "Stopping daemon!\n"); */
   MHD_stop_daemon (d);
   if (ok != 0)
     return 2;
   return 0;
 }
 
-static int
-testMultithreadedGet ()
+
+static unsigned int
+testMultithreadedGet (void)
 {
   struct MHD_Daemon *d;
   pid_t curl;
+  uint16_t port;
+  char url[127];
 
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 2,
-			MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1181;
+    if (oneone)
+      port += 10;
+  }
+
+  ok = 1;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 2,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
-  ok = 1;
-  //fprintf (stderr, "Forking cURL!\n");
-  curl = fork_curl ("http://127.0.0.1:1081/");
-  sleep (1);
-  kill_curl (curl);
-  sleep (1);
-  curl = fork_curl ("http://127.0.0.1:1081/");
-  sleep (1);
-  if (ok != 0)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      kill_curl (curl);
-      MHD_stop_daemon (d);
-      return 64;
+      MHD_stop_daemon (d); return 32;
     }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/",
+            (unsigned int) port);
+  // fprintf (stderr, "Forking cURL!\n");
+  curl = fork_curl (url);
+  (void) sleep (1);
   kill_curl (curl);
-  sleep (1);
-  //fprintf (stderr, "Stopping daemon!\n");
+  (void) sleep (1);
+  curl = fork_curl (url);
+  (void) sleep (1);
+  if (ok != 0)
+  {
+    kill_curl (curl);
+    MHD_stop_daemon (d);
+    return 64;
+  }
+  kill_curl (curl);
+  (void) sleep (1);
+  // fprintf (stderr, "Stopping daemon!\n");
   MHD_stop_daemon (d);
   if (ok != 0)
     return 32;
@@ -201,31 +262,59 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolGet ()
+
+static unsigned int
+testMultithreadedPoolGet (void)
 {
   struct MHD_Daemon *d;
   pid_t curl;
+  uint16_t port;
+  char url[127];
 
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1182;
+    if (oneone)
+      port += 10;
+  }
+
+  ok = 1;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 64;
-  ok = 1;
-  curl = fork_curl ("http://127.0.0.1:1081/");
-  sleep (1);
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/",
+            (unsigned int) port);
+  curl = fork_curl (url);
+  (void) sleep (1);
   kill_curl (curl);
-  sleep (1);
-  //fprintf (stderr, "Stopping daemon!\n");
+  (void) sleep (1);
+  // fprintf (stderr, "Stopping daemon!\n");
   MHD_stop_daemon (d);
   if (ok != 0)
     return 128;
   return 0;
 }
 
-static int
-testExternalGet ()
+
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   fd_set rs;
@@ -235,49 +324,117 @@
   time_t start;
   struct timeval tv;
   pid_t curl;
+  uint16_t port;
+  char url[127];
 
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1183;
+    if (oneone)
+      port += 10;
+  }
+
+  ok = 1;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
-  curl = fork_curl ("http://127.0.0.1:1082/");
-  
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/",
+            (unsigned int) port);
+  curl = fork_curl (url);
+
   start = time (NULL);
   while ((time (NULL) - start < 2))
+  {
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      MHD_run (d);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (max + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    MHD_run (d);
+  }
   kill_curl (curl);
   start = time (NULL);
   while ((time (NULL) - start < 2))
+  {
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      MHD_run (d);
+      MHD_stop_daemon (d);
+      return 4096;
     }
-  // fprintf (stderr, "Stopping daemon!\n");
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (max + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    MHD_run (d);
+  }
+  /* fprintf (stderr, "Stopping daemon!\n"); */
   MHD_stop_daemon (d);
   if (ok != 0)
     return 1024;
@@ -289,14 +446,30 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
-  errorCount += testInternalGet ();
-  errorCount += testMultithreadedGet ();
-  errorCount += testMultithreadedPoolGet ();
+#ifndef _WIN32
+  /* Solaris has no way to disable SIGPIPE on socket disconnect. */
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE))
+  {
+    struct sigaction act;
+
+    act.sa_handler = SIG_IGN;
+    sigaction (SIGPIPE, &act, NULL);
+  }
+#endif /* _WIN32 */
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet ();
+    errorCount += testMultithreadedGet ();
+    errorCount += testMultithreadedPoolGet ();
+  }
   errorCount += testExternalGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_get_sendfile.c b/src/testcurl/test_get_sendfile.c
index f0853b2..3109239 100644
--- a/src/testcurl/test_get_sendfile.c
+++ b/src/testcurl/test_get_sendfile.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,19 +15,18 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
-
 /**
- * @file daemontest_get_sendfile.c
+ * @file test_get_sendfile.c
  * @brief  Testcase for libmicrohttpd response from FD
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
 #include "platform.h"
-#include "platform_interface.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
 #include <stdlib.h>
@@ -34,22 +34,25 @@
 #include <time.h>
 #include <sys/types.h>
 #include <fcntl.h>
+#include "mhd_sockets.h"
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <sys/socket.h>
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
-#define TESTSTR "This is the content of the test file we are sending using sendfile (if available)"
+#define TESTSTR \
+  "This is the content of the test file we are sending using sendfile (if available)"
 
-char *sourcefile;
+static char *sourcefile;
 
 static int oneone;
 
@@ -60,6 +63,7 @@
   size_t size;
 };
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -73,37 +77,39 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   int fd;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   fd = open (sourcefile, O_RDONLY);
   if (fd == -1)
-    {
-      fprintf (stderr, "Failed to open `%s': %s\n",
-	       sourcefile,
-	       MHD_strerror_ (errno));
-      exit (1);
-    }
+  {
+    fprintf (stderr, "Failed to open `%s': %s\n",
+             sourcefile,
+             strerror (errno));
+    exit (1);
+  }
   response = MHD_create_response_from_fd (strlen (TESTSTR), fd);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
@@ -113,27 +119,48 @@
 }
 
 
-static int
-testInternalGet ()
+static unsigned int
+testInternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1200;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11080/");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -143,16 +170,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (TESTSTR))
@@ -162,27 +189,50 @@
   return 0;
 }
 
-static int
-testMultithreadedGet ()
+
+static unsigned int
+testMultithreadedGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1201;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
@@ -192,16 +242,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (TESTSTR))
@@ -211,28 +261,51 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolGet ()
+
+static unsigned int
+testMultithreadedPoolGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1202;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
@@ -242,16 +315,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (TESTSTR))
@@ -261,8 +334,9 @@
   return 0;
 }
 
-static int
-testExternalGet ()
+
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -273,25 +347,51 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1203;
+    if (oneone)
+      port += 10;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
@@ -301,90 +401,133 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (TESTSTR))
+  {
+    fprintf (stderr,
+             "Got %.*s instead of %s!\n",
+             (int) cbc.pos,
+             cbc.buf,
+             TESTSTR);
     return 8192;
+  }
   if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR)))
     return 16384;
   return 0;
 }
 
-static int
-testUnknownPortGet ()
+
+static unsigned int
+testUnknownPortGet (void)
 {
   struct MHD_Daemon *d;
   const union MHD_DaemonInfo *di;
@@ -392,10 +535,11 @@
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
 
   struct sockaddr_in addr;
   socklen_t addr_len = sizeof(addr);
-  memset(&addr, 0, sizeof(addr));
+  memset (&addr, 0, sizeof(addr));
   addr.sin_family = AF_INET;
   addr.sin_port = 0;
   addr.sin_addr.s_addr = INADDR_ANY;
@@ -403,31 +547,45 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1, NULL, NULL, &ahc_echo, "GET",
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        0, NULL, NULL, &ahc_echo, NULL,
                         MHD_OPTION_SOCK_ADDR, &addr,
                         MHD_OPTION_END);
   if (d == NULL)
     return 32768;
 
-  di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
-  if (di == NULL)
-    return 65536;
+  if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+  {
+    di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD);
+    if (di == NULL)
+      return 65536;
 
-  if (0 != getsockname(di->listen_fd, (struct sockaddr *) &addr, &addr_len))
-    return 131072;
+    if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len))
+      return 131072;
 
-  if (addr.sin_family != AF_INET)
-    return 26214;
+    if (addr.sin_family != AF_INET)
+      return 26214;
+    port = (uint16_t) ntohs (addr.sin_port);
+  }
+  else
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
 
-  snprintf(buf, sizeof(buf), "http://127.0.0.1:%hu/",
-           ntohs(addr.sin_port));
+  snprintf (buf, sizeof(buf), "http://127.0.0.1:%u/",
+            (unsigned int) port);
 
   c = curl_easy_init ();
   curl_easy_setopt (c, CURLOPT_URL, buf);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -437,16 +595,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 524288;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 524288;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen (TESTSTR))
@@ -463,38 +621,48 @@
   unsigned int errorCount = 0;
   const char *tmp;
   FILE *f;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
 
   if ( (NULL == (tmp = getenv ("TMPDIR"))) &&
        (NULL == (tmp = getenv ("TMP"))) &&
        (NULL == (tmp = getenv ("TEMP"))) )
     tmp = "/tmp";
   sourcefile = malloc (strlen (tmp) + 32);
-  sprintf (sourcefile,
-	   "%s/%s",
-	   tmp,
-	   "test-mhd-sendfile");
+  snprintf (sourcefile,
+            strlen (tmp) + 32,
+            "%s/%s%s",
+            tmp,
+            "test-mhd-sendfile",
+            oneone ? "11" : "");
   f = fopen (sourcefile, "w");
   if (NULL == f)
-    {
-      fprintf (stderr, "failed to write test file\n");
-      free (sourcefile);
-      return 1;
-    }
-  fwrite (TESTSTR, strlen (TESTSTR), 1, f);
+  {
+    fprintf (stderr, "failed to write test file\n");
+    free (sourcefile);
+    return 1;
+  }
+  if (1 !=
+      fwrite (TESTSTR, strlen (TESTSTR), 1, f))
+    abort ();
   fclose (f);
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalGet ();
-  errorCount += testMultithreadedGet ();
-  errorCount += testMultithreadedPoolGet ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet ();
+    errorCount += testMultithreadedGet ();
+    errorCount += testMultithreadedPoolGet ();
+    errorCount += testUnknownPortGet ();
+  }
   errorCount += testExternalGet ();
-  errorCount += testUnknownPortGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
   unlink (sourcefile);
   free (sourcefile);
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_get_wait.c b/src/testcurl/test_get_wait.c
new file mode 100644
index 0000000..74907a6
--- /dev/null
+++ b/src/testcurl/test_get_wait.c
@@ -0,0 +1,237 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_get_wait.c
+ * @brief Test 'MHD_run_wait()' function.
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <pthread.h>
+#include "mhd_has_in_name.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+/**
+ * How many rounds of operations do we do for each
+ * test.
+ * Check all three types of requests for HTTP/1.1:
+ * * first request, new connection;
+ * * "middle" request, existing connection with stay-alive;
+ * * final request, no data processed after.
+ */
+#define ROUNDS 3
+
+/**
+ * Do we use HTTP 1.1?
+ */
+static int oneone;
+
+/**
+ * Response to return (re-used).
+ */
+static struct MHD_Response *response;
+
+/**
+ * Set to 1 if the worker threads are done.
+ */
+static volatile int signal_done;
+
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size, size_t nmemb,
+            void *ctx)
+{
+  (void) ptr; (void) ctx;          /* Unused. Silent compiler warning. */
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) url; (void) version;                      /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
+    return MHD_NO;              /* unexpected method */
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  if (ret == MHD_NO)
+    abort ();
+  return ret;
+}
+
+
+static void *
+thread_gets (void *param)
+{
+  CURL *c;
+  CURLcode errornum;
+  unsigned int i;
+  char url[64];
+  uint16_t port = (uint16_t) (intptr_t) param;
+
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u/hello_world",
+            (unsigned int) port);
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    _exit (99);
+  curl_easy_setopt (c, CURLOPT_URL, url);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 15L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  for (i = 0; i < ROUNDS; i++)
+  {
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      signal_done = 1;
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      abort ();
+    }
+  }
+  curl_easy_cleanup (c);
+  signal_done = 1;
+
+  return NULL;
+}
+
+
+static unsigned int
+testRunWaitGet (uint16_t port, uint32_t poll_flag)
+{
+  pthread_t get_tid;
+  struct MHD_Daemon *d;
+  const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ?
+                                 "MHD_USE_AUTO" :
+                                 (poll_flag & MHD_USE_POLL) ?
+                                 "MHD_USE_POLL" :
+                                 (poll_flag & MHD_USE_EPOLL) ?
+                                 "MHD_USE_EPOLL" :
+                                 "select()");
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+
+  printf ("Starting MHD_run_wait() test with MHD in %s polling mode.\n",
+          test_desc);
+  signal_done = 0;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  if (d == NULL)
+    abort ();
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      abort ();
+    port = dinfo->port;
+  }
+
+  if (0 != pthread_create (&get_tid, NULL,
+                           &thread_gets, (void *) (intptr_t) port))
+    _exit (99);
+
+  /* As another thread sets "done" flag after ending of network
+   * activity, it's required to set positive timeout value for MHD_run_wait().
+   * Alternatively, to use timeout value "-1" here, another thread should start
+   * additional connection to wake MHD after setting "done" flag. */
+  do
+  {
+    if (MHD_NO == MHD_run_wait (d, 50))
+      abort ();
+  } while (0 == signal_done);
+
+  if (0 != pthread_join (get_tid, NULL))
+    _exit (99);
+
+  MHD_stop_daemon (d);
+  printf ("Test succeeded.\n");
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  uint16_t port = 1675;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (oneone)
+    port += 5;
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  response = MHD_create_response_from_buffer_static (strlen ("/hello_world"),
+                                                     "/hello_world");
+  testRunWaitGet (port++, 0);
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    testRunWaitGet (port++, MHD_USE_EPOLL);
+  testRunWaitGet (port++, MHD_USE_AUTO);
+
+  MHD_destroy_response (response);
+  curl_global_cleanup ();
+  return 0; /* Errors produce abort() or _exit() */
+}
diff --git a/src/testcurl/test_head.c b/src/testcurl/test_head.c
new file mode 100644
index 0000000..9458f8a
--- /dev/null
+++ b/src/testcurl/test_head.c
@@ -0,0 +1,878 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     GNU libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file testcurl/test_head.c
+ * @brief  Testcase for HEAD requests
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#include "mhd_has_param.h"
+#include "mhd_has_in_name.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \
+                       __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+#define EXPECTED_URI_BASE_PATH  "/"
+
+#define EXISTING_URI  EXPECTED_URI_BASE_PATH
+
+#define EXPECTED_URI_BASE_PATH_MISSING  "/wrong_uri"
+
+#define URL_SCHEME "http:/" "/"
+
+#define URL_HOST "127.0.0.1"
+
+#define URL_SCHEME_HOST URL_SCHEME URL_HOST
+
+#define HEADER1_NAME "First"
+#define HEADER1_VALUE "1st"
+#define HEADER1 HEADER1_NAME ": " HEADER1_VALUE
+#define HEADER1_CRLF HEADER1 "\r\n"
+#define HEADER2_NAME "Normal"
+#define HEADER2_VALUE "it's fine"
+#define HEADER2 HEADER2_NAME ": " HEADER2_VALUE
+#define HEADER2_CRLF HEADER2 "\r\n"
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo page</title></head>" \
+  "<body>Success!</body></html>"
+
+#define PAGE_404 \
+  "<html><head><title>404 error</title></head>" \
+  "<body>Error 404: The requested URI does not exist</body></html>"
+
+/* Global parameters */
+static int verbose;
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_global_cleanup ();
+}
+
+
+struct headers_check_result
+{
+  unsigned int expected_size;
+  int header1_found;
+  int header2_found;
+  int size_found;
+};
+
+static size_t
+lcurl_hdr_callback (char *buffer, size_t size, size_t nitems,
+                    void *userdata)
+{
+  const size_t data_size = size * nitems;
+  struct headers_check_result *check_res =
+    (struct headers_check_result *) userdata;
+
+  if ((MHD_STATICSTR_LEN_ (HEADER1_CRLF) == data_size) &&
+      (0 == memcmp (HEADER1_CRLF, buffer, data_size)))
+    check_res->header1_found++;
+  else if ((MHD_STATICSTR_LEN_ (HEADER2_CRLF) == data_size) &&
+           (0 == memcmp (HEADER2_CRLF, buffer, data_size)))
+    check_res->header2_found++;
+  else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")
+            < data_size) &&
+           (0 ==
+            memcmp (MHD_HTTP_HEADER_CONTENT_LENGTH ": ", buffer,
+                    MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "))))
+  {
+    char cmpbuf[256];
+    int res;
+    const unsigned int numbers_pos =
+      MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ");
+    res = snprintf (cmpbuf, sizeof(cmpbuf), "%u", check_res->expected_size);
+    if ((res <= 0) || (res > ((int) (sizeof(cmpbuf) - 1))))
+      externalErrorExit ();
+    if (data_size - numbers_pos <= 2)
+      mhdErrorExitDesc ("Broken Content-Length");
+    else if ((((size_t) res + 2) != data_size - numbers_pos) ||
+             (0 != memcmp (buffer + numbers_pos, cmpbuf, (size_t) res)))
+    {
+      fprintf (stderr, "Wrong Content-Length.\n"
+               "Expected:\n%u\n"
+               "Received:\n%s", check_res->expected_size,
+               buffer + numbers_pos);
+      mhdErrorExitDesc ("Wrong Content-Length");
+    }
+    else if (0 != memcmp ("\r\n", buffer + data_size - 2, 2))
+    {
+      mhdErrorExitDesc ("The Content-Length header is not " \
+                        "terminated by CRLF");
+    }
+    check_res->size_found++;
+  }
+
+  return data_size;
+}
+
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  (void) ptr; /* Unused, mute compiler warning */
+  (void) ctx; /* Unused, mute compiler warning */
+  if ((0 != size) && (0 != nmemb))
+    libcurlErrorExitDesc ("Received unexpected body data");
+  return size * nmemb;
+}
+
+
+struct ahc_cls_type
+{
+  const char *rq_method;
+  const char *rq_url;
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int marker;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+  unsigned int http_code;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (oneone)
+  {
+    if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+      mhdErrorExitDesc ("Unexpected HTTP version");
+  }
+  else
+  {
+    if (0 != strcmp (version, MHD_HTTP_VERSION_1_0))
+      mhdErrorExitDesc ("Unexpected HTTP version");
+  }
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (NULL != upload_data)
+    mhdErrorExitDesc ("'upload_data' is not NULL");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+    mhdErrorExitDesc ("'*upload_data_size' value is not zero");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  if (&marker != *req_cls)
+  {
+    *req_cls = &marker;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  if (0 == strcmp (url, EXISTING_URI))
+  {
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                              PAGE);
+    http_code = MHD_HTTP_OK;
+  }
+  else
+  {
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_404),
+                                              PAGE_404);
+    http_code = MHD_HTTP_NOT_FOUND;
+  }
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  if (MHD_YES != MHD_add_response_header (response,
+                                          HEADER1_NAME,
+                                          HEADER1_VALUE))
+    mhdErrorExitDesc ("Cannot add header1");
+  if (MHD_YES != MHD_add_response_header (response,
+                                          HEADER2_NAME,
+                                          HEADER2_VALUE))
+    mhdErrorExitDesc ("Cannot add header2");
+
+  ret = MHD_queue_response (connection,
+                            http_code,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+
+  return ret;
+}
+
+
+/**
+ * Set required URI for the request
+ * @param c the CURL handle to use
+ * @param uri_exist if non-zero use request for "existing" URI
+ */
+static void
+setCURL_rq_path (CURL *c, int uri_exist)
+{
+  if (uri_exist)
+  {
+    if (CURLE_OK !=
+        curl_easy_setopt (c, CURLOPT_URL,
+                          URL_SCHEME_HOST EXPECTED_URI_BASE_PATH))
+      libcurlErrorExitDesc ("Cannot set request URL");
+  }
+  else
+  {
+    if (CURLE_OK !=
+        curl_easy_setopt (c, CURLOPT_URL,
+                          URL_SCHEME_HOST EXPECTED_URI_BASE_PATH_MISSING))
+      libcurlErrorExitDesc ("Cannot set request URL");
+  }
+}
+
+
+static int
+libcurl_debug_cb (CURL *handle,
+                  curl_infotype type,
+                  char *data,
+                  size_t size,
+                  void *userptr)
+{
+  static const char excess_mark[] = "Excess found";
+  static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark);
+
+  (void) handle;
+  (void) userptr;
+
+#ifdef _DEBUG
+  switch (type)
+  {
+  case CURLINFO_TEXT:
+    fprintf (stderr, "* %.*s", (int) size, data);
+    break;
+  case CURLINFO_HEADER_IN:
+    fprintf (stderr, "< %.*s", (int) size, data);
+    break;
+  case CURLINFO_HEADER_OUT:
+    fprintf (stderr, "> %.*s", (int) size, data);
+    break;
+  case CURLINFO_DATA_IN:
+#if 0
+    fprintf (stderr, "<| %.*s\n", (int) size, data);
+#endif
+    break;
+  case CURLINFO_DATA_OUT:
+  case CURLINFO_SSL_DATA_IN:
+  case CURLINFO_SSL_DATA_OUT:
+  case CURLINFO_END:
+  default:
+    break;
+  }
+#endif /* _DEBUG */
+  if (CURLINFO_TEXT == type)
+  {
+    if ((size >= excess_mark_len) &&
+        (0 == memcmp (data, excess_mark, excess_mark_len)))
+      mhdErrorExitDesc ("Extra data has been detected in MHD reply");
+  }
+  return 0;
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port,
+           struct headers_check_result *hdr_chk_result)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION,
+                                     lcurl_hdr_callback)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA,
+                                     hdr_chk_result)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) ||
+#ifdef _DEBUG
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) ||
+#endif /* _DEBUG */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION,
+                                     &libcurl_debug_cb)) ||
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  /* When 'CURLOPT_NOBODY' is set, libcurl should use HEAD request. */
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_NOBODY, (long) 1))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  if (NULL != *multi_reuse)
+    multi = *multi_reuse;
+  else
+  {
+    multi = curl_multi_init ();
+    if (multi == NULL)
+      libcurlErrorExitDesc ("curl_multi_init() failed");
+    *multi_reuse = multi;
+  }
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 200000;
+    if (0 == MHD_get_timeout64s (d))
+      tv.tv_usec = 0;
+    else
+    {
+      long curl_to = -1;
+      curl_multi_timeout (multi, &curl_to);
+      if (0 == curl_to)
+        tv.tv_usec = 0;
+    }
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep ((unsigned long) tv.tv_usec / 1000);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/**
+ * Check request result
+ * @param curl_code the CURL easy return code
+ * @param pcbc the pointer struct CBC
+ * @return non-zero if success, zero if failed
+ */
+static unsigned int
+check_result (CURLcode curl_code, CURL *c, long expected_code,
+              struct headers_check_result *hdr_res)
+{
+  long code;
+  unsigned int ret;
+
+  if (CURLE_OK != curl_code)
+  {
+    fflush (stdout);
+    if (0 != libcurl_errbuf[0])
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               curl_easy_strerror (curl_code),
+               libcurl_errbuf);
+    else
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n",
+               curl_easy_strerror (curl_code));
+    fflush (stderr);
+    return 0;
+  }
+
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
+    libcurlErrorExit ();
+
+  if (expected_code != code)
+  {
+    fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n",
+             code, expected_code);
+    return 0;
+  }
+  else if (verbose)
+    printf ("The response has expected HTTP code: %ld\n", expected_code);
+
+  ret = 1;
+  if (1 != hdr_res->header1_found)
+  {
+    if (0 == hdr_res->header1_found)
+      fprintf (stderr, "Response header1 was not found.\n");
+    else
+      fprintf (stderr, "Response header1 was found %d times "
+               "instead of one time only.\n", hdr_res->header1_found);
+    ret = 0;
+  }
+  else if (verbose)
+    printf ("Header1 is present in the response.\n");
+  if (1 != hdr_res->header2_found)
+  {
+    if (0 == hdr_res->header2_found)
+      fprintf (stderr, "Response header2 was not found.\n");
+    else
+      fprintf (stderr, "Response header2 was found %d times "
+               "instead of one time only.\n", hdr_res->header2_found);
+    ret = 0;
+  }
+  else if (verbose)
+    printf ("Header2 is present in the response.\n");
+  if (1 != hdr_res->size_found)
+  {
+    if (0 == hdr_res->size_found)
+      fprintf (stderr, "Response 'Content-Length' header was not found.\n");
+    else
+      fprintf (stderr, "Response 'Content-Length' header was found %d times "
+               "instead of one time only.\n", hdr_res->size_found);
+    ret = 0;
+  }
+  else if (verbose)
+    printf ("'Content-Length' header with correct value "
+            "is present in the response.\n");
+
+  return ret;
+}
+
+
+static unsigned int
+testHead (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t port;
+  struct CBC cbc;
+  struct ahc_cls_type ahc_param;
+  struct headers_check_result rp_headers_check;
+  char buf[2048];
+  CURL *c;
+  CURLM *multi_reuse;
+  int failed = 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 4220 + oneone ? 0 : 1;
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahcCheck, &ahc_param,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = dinfo->port;
+  }
+
+  /* First request */
+  ahc_param.rq_method = MHD_HTTP_METHOD_HEAD;
+  ahc_param.rq_url = EXPECTED_URI_BASE_PATH;
+  rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE);
+  rp_headers_check.header1_found = 0;
+  rp_headers_check.header2_found = 0;
+  rp_headers_check.size_found = 0;
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  cbc.pos = 0;
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port, &rp_headers_check);
+  setCURL_rq_path (c, 1);
+  multi_reuse = NULL;
+  /* First request */
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                    MHD_HTTP_OK, &rp_headers_check))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got first expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "First request FAILED.\n");
+    fflush (stderr);
+    failed = 1;
+  }
+  /* Second request */
+  rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE_404);
+  rp_headers_check.header1_found = 0;
+  rp_headers_check.header2_found = 0;
+  rp_headers_check.size_found = 0;
+  cbc.pos = 0; /* Reset buffer position */
+  ahc_param.rq_url = EXPECTED_URI_BASE_PATH_MISSING;
+  setCURL_rq_path (c, 0);
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                    MHD_HTTP_NOT_FOUND, &rp_headers_check))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got second expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "Second request FAILED.\n");
+    fflush (stderr);
+    failed = 1;
+  }
+  /* Third request */
+  rp_headers_check.header1_found = 0;
+  rp_headers_check.header2_found = 0;
+  rp_headers_check.size_found = 0;
+  cbc.pos = 0; /* Reset buffer position */
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+  multi_reuse = NULL; /* Force new connection */
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                    MHD_HTTP_NOT_FOUND, &rp_headers_check))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got third expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "Third request FAILED.\n");
+    fflush (stderr);
+    failed = 1;
+  }
+
+  curl_easy_cleanup (c);
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+
+  MHD_stop_daemon (d);
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+
+  /* Test type and test parameters */
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  oneone = ! has_in_name (argv[0], "10");
+
+  test_global_init ();
+
+  errorCount += testHead ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  test_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_iplimit.c b/src/testcurl/test_iplimit.c
index 813fc8b..db98556 100644
--- a/src/testcurl/test_iplimit.c
+++ b/src/testcurl/test_iplimit.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,15 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_iplimit.c
- * @brief  Testcase for libmicrohttpd GET operations
- *         TODO: test parsing of query
+ * @brief  Testcase for libmicrohttpd limits per IP
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -32,6 +33,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
@@ -44,11 +46,11 @@
 #include <windows.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 static int oneone;
@@ -72,31 +74,32 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
@@ -104,204 +107,250 @@
   return ret;
 }
 
-static int
-testMultithreadedGet ()
+
+static unsigned int
+testMultithreadedGet (void)
 {
   struct MHD_Daemon *d;
   char buf[2048];
   int k;
   unsigned int success;
   unsigned int failure;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1260;
+    if (oneone)
+      port += 5;
+  }
 
   /* Test only valid for HTTP/1.1 (uses persistent connections) */
-  if (!oneone)
+  if (! oneone)
     return 0;
 
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL,
-                        &ahc_echo, "GET",
-                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, 2,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2,
                         MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
 
   for (k = 0; k < 3; ++k)
+  {
+    struct CBC cbc[3];
+    CURL *cenv[3];
+    int i;
+
+    success = 0;
+    failure = 0;
+    for (i = 0; i < 3; ++i)
     {
-      struct CBC cbc[3];
-      CURL *cenv[3];
-      int i;
+      CURL *c;
+      CURLcode errornum;
 
-      success = 0;
-      failure = 0;
-      for (i = 0; i < 3; ++i)
-        {
-          CURL *c;
-          CURLcode errornum;
+      cenv[i] = c = curl_easy_init ();
+      cbc[i].buf = buf;
+      cbc[i].size = 2048;
+      cbc[i].pos = 0;
 
-          cenv[i] = c = curl_easy_init ();
-          cbc[i].buf = buf;
-          cbc[i].size = 2048;
-          cbc[i].pos = 0;
+      curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+      curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]);
+      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+      curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L);
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+      /* NOTE: use of CONNECTTIMEOUT without also
+       *   setting NOSIGNAL results in really weird
+       *   crashes on my system! */
+      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
-          curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
-          curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-          curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]);
-          curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-          curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-          curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L);
-          curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-          curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-          // NOTE: use of CONNECTTIMEOUT without also
-          //   setting NOSIGNAL results in really weird
-          //   crashes on my system!
-          curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
-          errornum = curl_easy_perform (c);
-          if (CURLE_OK == errornum)
-            success++;
-          else
-            failure++;
-        }
-
-      /* Cleanup the environments */
-      for (i = 0; i < 3; ++i)
-        curl_easy_cleanup (cenv[i]);
-      if ( (2 != success) ||
-           (1 != failure) )
-      {
-        fprintf (stderr,
-                 "Unexpected number of success (%u) or failure (%u)\n",
-                 success,
-                 failure);
-        MHD_stop_daemon (d);
-        return 32;
-      }
-
-      sleep(2);
-
-      for (i = 0; i < 2; ++i)
-        {
-          if (cbc[i].pos != strlen ("/hello_world"))
-            {
-              MHD_stop_daemon (d);
-              return 64;
-            }
-          if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world")))
-            {
-              MHD_stop_daemon (d);
-              return 128;
-            }
-        }
+      errornum = curl_easy_perform (c);
+      if (CURLE_OK == errornum)
+        success++;
+      else
+        failure++;
     }
+
+    /* Cleanup the environments */
+    for (i = 0; i < 3; ++i)
+      curl_easy_cleanup (cenv[i]);
+    if ( (2 != success) ||
+         (1 != failure) )
+    {
+      fprintf (stderr,
+               "Unexpected number of success (%u) or failure (%u)\n",
+               success,
+               failure);
+      MHD_stop_daemon (d);
+      return 32;
+    }
+
+    (void) sleep (2);
+
+    for (i = 0; i < 2; ++i)
+    {
+      if (cbc[i].pos != strlen ("/hello_world"))
+      {
+        MHD_stop_daemon (d);
+        return 64;
+      }
+      if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world")))
+      {
+        MHD_stop_daemon (d);
+        return 128;
+      }
+    }
+  }
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
-testMultithreadedPoolGet ()
+
+static unsigned int
+testMultithreadedPoolGet (void)
 {
   struct MHD_Daemon *d;
   char buf[2048];
   int k;
+  uint16_t port;
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1261;
+    if (oneone)
+      port += 5;
+  }
 
   /* Test only valid for HTTP/1.1 (uses persistent connections) */
-  if (!oneone)
+  if (! oneone)
     return 0;
 
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, 2,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
                         MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
 
   for (k = 0; k < 3; ++k)
+  {
+    struct CBC cbc[3];
+    CURL *cenv[3];
+    int i;
+
+    for (i = 0; i < 3; ++i)
     {
-      struct CBC cbc[3];
-      CURL *cenv[3];
-      int i;
+      CURL *c;
+      CURLcode errornum;
 
-      for (i = 0; i < 3; ++i)
-        {
-          CURL *c;
-          CURLcode errornum;
+      cenv[i] = c = curl_easy_init ();
+      cbc[i].buf = buf;
+      cbc[i].size = 2048;
+      cbc[i].pos = 0;
 
-          cenv[i] = c = curl_easy_init ();
-          cbc[i].buf = buf;
-          cbc[i].size = 2048;
-          cbc[i].pos = 0;
+      curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+      curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]);
+      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+      curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L);
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+      /* NOTE: use of CONNECTTIMEOUT without also
+       *   setting NOSIGNAL results in really weird
+       *   crashes on my system! */
+      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
-          curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
-          curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-          curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]);
-          curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-          curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-          curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L);
-          curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-          curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-          // NOTE: use of CONNECTTIMEOUT without also
-          //   setting NOSIGNAL results in really weird
-          //   crashes on my system!
-          curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+      errornum = curl_easy_perform (c);
+      if ( ( (CURLE_OK != errornum) && (i <  2) ) ||
+           ( (CURLE_OK == errornum) && (i == 2) ) )
+      {
+        int j;
 
-          errornum = curl_easy_perform (c);
-          if ( ( (CURLE_OK != errornum) && (i <  2) ) ||
-	       ( (CURLE_OK == errornum) && (i == 2) ) )
-            {
-              int j;
+        /* First 2 should succeed */
+        if (i < 2)
+          fprintf (stderr,
+                   "curl_easy_perform failed: `%s'\n",
+                   curl_easy_strerror (errornum));
 
-              /* First 2 should succeed */
-              if (i < 2)
-                fprintf (stderr,
-                         "curl_easy_perform failed: `%s'\n",
-                         curl_easy_strerror (errornum));
+        /* Last request should have failed */
+        else
+          fprintf (stderr,
+                   "No error on IP address over limit\n");
 
-              /* Last request should have failed */
-              else
-                fprintf (stderr,
-                         "No error on IP address over limit\n");
-
-              for (j = 0; j < i; ++j)
-                curl_easy_cleanup (cenv[j]);
-              MHD_stop_daemon (d);
-              return 32;
-            }
-        }
-
-      /* Cleanup the environments */
-      for (i = 0; i < 3; ++i)
-        curl_easy_cleanup (cenv[i]);
-
-      sleep(2);
-
-      for (i = 0; i < 2; ++i)
-        {
-          if (cbc[i].pos != strlen ("/hello_world"))
-            {
-              MHD_stop_daemon (d);
-              return 64;
-            }
-          if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world")))
-            {
-              MHD_stop_daemon (d);
-              return 128;
-            }
-        }
-
-
+        for (j = 0; j < i; ++j)
+          curl_easy_cleanup (cenv[j]);
+        MHD_stop_daemon (d);
+        return 32;
+      }
     }
+
+    /* Cleanup the environments */
+    for (i = 0; i < 3; ++i)
+      curl_easy_cleanup (cenv[i]);
+
+    (void) sleep (2);
+
+    for (i = 0; i < 2; ++i)
+    {
+      if (cbc[i].pos != strlen ("/hello_world"))
+      {
+        MHD_stop_daemon (d);
+        return 64;
+      }
+      if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world")))
+      {
+        MHD_stop_daemon (d);
+        return 128;
+      }
+    }
+
+
+  }
   MHD_stop_daemon (d);
   return 0;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   errorCount |= testMultithreadedGet ();
@@ -309,5 +358,5 @@
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_large_put.c b/src/testcurl/test_large_put.c
index ec0022e..b4e7267 100644
--- a/src/testcurl/test_large_put.c
+++ b/src/testcurl/test_large_put.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2008 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_large_put.c
  * @brief  Testcase for libmicrohttpd PUT operations
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -36,24 +38,125 @@
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
 static int oneone;
+static int incr_read; /* Use incremental read */
+static int verbose; /* Be verbose */
 
-/**
- * Do not make this much larger since we will hit the
- * MHD default buffer limit and the test code is not
- * written for incremental upload processing...
- * (larger values will likely cause MHD to generate
- * an internal server error -- which would be avoided
- * by writing the putBuffer method in a more general
- * fashion).
- */
 #define PUT_SIZE (256 * 1024)
 
 static char *put_buffer;
@@ -65,13 +168,43 @@
   size_t size;
 };
 
+static char *
+alloc_init (size_t buf_size)
+{
+  static const char template[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz";
+  static const size_t templ_size = sizeof(template) / sizeof(char) - 1;
+  char *buf;
+  char *fill_ptr;
+  size_t to_fill;
+
+  buf = malloc (buf_size);
+  if (NULL == buf)
+    externalErrorExit ();
+
+  fill_ptr = buf;
+  to_fill = buf_size;
+  while (to_fill > 0)
+  {
+    const size_t to_copy = to_fill > templ_size ? templ_size : to_fill;
+    memcpy (fill_ptr, template, to_copy);
+    fill_ptr += to_copy;
+    to_fill -= to_copy;
+  }
+  return buf;
+}
+
+
 static size_t
 putBuffer (void *stream, size_t size, size_t nmemb, void *ptr)
 {
-  unsigned int *pos = ptr;
-  unsigned int wrt;
+  size_t *pos = (size_t *) ptr;
+  size_t wrt;
 
   wrt = size * nmemb;
+  /* Check for overflow. */
+  if (wrt / size != nmemb)
+    libcurlErrorExitDesc ("Too large buffer size");
   if (wrt > PUT_SIZE - (*pos))
     wrt = PUT_SIZE - (*pos);
   memcpy (stream, &put_buffer[*pos], wrt);
@@ -79,248 +212,407 @@
   return wrt;
 }
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
   struct CBC *cbc = ctx;
 
   if (cbc->pos + size * nmemb > cbc->size)
-    return 0;                   /* overflow */
+    libcurlErrorExitDesc ("Too large buffer size");
   memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
   cbc->pos += size * nmemb;
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   int *done = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  static size_t processed;
+
+  if (NULL == cls)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (0 != strcmp (version, oneone ?
+                   MHD_HTTP_VERSION_1_1 : MHD_HTTP_VERSION_1_0))
+    mhdErrorExitDesc ("Unexpected HTTP version");
+
+  if (NULL == url)
+    mhdErrorExitDesc ("url parameter is NULL");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
 
   if (0 != strcmp ("PUT", method))
-    return MHD_NO;              /* unexpected method */
+    mhdErrorExitDesc ("Unexpected request method");   /* unexpected method */
+
   if ((*done) == 0)
+  {
+    size_t *pproc;
+    if (NULL == *req_cls)
     {
-      if (*upload_data_size != PUT_SIZE)
-        {
-#if 0
-          fprintf (stderr,
-                   "Waiting for more data (%u/%u)...\n",
-                   *upload_data_size, PUT_SIZE);
-#endif
-          return MHD_YES;       /* not yet ready */
-        }
-      if (0 == memcmp (upload_data, put_buffer, PUT_SIZE))
-        {
-          *upload_data_size = 0;
-        }
-      else
-        {
-          printf ("Invalid upload data!\n");
-          return MHD_NO;
-        }
-      *done = 1;
-      return MHD_YES;
+      processed = 0;
+      /* Safe as long as only one parallel request served. */
+      *req_cls = &processed;
     }
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url, 
-					      MHD_RESPMEM_MUST_COPY);
+    pproc = (size_t *) *req_cls;
+
+    if (0 == *upload_data_size)
+      return MHD_YES;   /* No data to process. */
+
+    if (*pproc + *upload_data_size > PUT_SIZE)
+      mhdErrorExitDesc ("Incoming data larger than expected");
+
+    if ( (! incr_read) && (*upload_data_size != PUT_SIZE) )
+      return MHD_YES;   /* Wait until whole request is received. */
+
+    if (0 != memcmp (upload_data, put_buffer + (*pproc), *upload_data_size))
+      mhdErrorExitDesc ("Incoming data does not match sent data");
+
+    *pproc += *upload_data_size;
+    *upload_data_size = 0;   /* Current block of data is fully processed. */
+
+    if (PUT_SIZE == *pproc)
+      *done = 1;   /* Whole request is processed. */
+    return MHD_YES;
+  }
+  response =
+    MHD_create_response_from_buffer_copy (strlen (url),
+                                          (const void *) url);
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testInternalPut ()
+static unsigned int
+testPutInternalThread (unsigned int add_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
   struct CBC cbc;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
   CURLcode errornum;
   char buf[2048];
+  uint16_t port;
 
-  cbc.buf = buf;
-  cbc.size = 2048;
-  cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080,
-                        NULL, NULL, &ahc_echo, &done_flag, 
-			MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (1024*1024),
-			MHD_OPTION_END);
-  if (d == NULL)
-    return 1;
-  c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-  curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-  if (oneone)
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
   else
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-  if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
-  curl_easy_cleanup (c);
-  MHD_stop_daemon (d);
-  if (cbc.pos != strlen ("/hello_world"))
-    return 4;
-  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    return 8;
-  return 0;
-}
-
-static int
-testMultithreadedPut ()
-{
-  struct MHD_Daemon *d;
-  CURL *c;
-  struct CBC cbc;
-  unsigned int pos = 0;
-  int done_flag = 0;
-  CURLcode errornum;
-  char buf[2048];
+  {
+    port = 1270;
+    if (oneone)
+      port += 10;
+    if (incr_read)
+      port += 20;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081,
-                        NULL, NULL, &ahc_echo, &done_flag, 
-			MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (1024*1024),
-			MHD_OPTION_END);
-  if (d == NULL)
-    return 16;
-  c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-  curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-  if (oneone)
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-  else
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-  if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
-  curl_easy_cleanup (c);
-  MHD_stop_daemon (d);
-  if (cbc.pos != strlen ("/hello_world"))
-    {
-      fprintf (stderr, "Got invalid response `%.*s'\n", (int)cbc.pos, cbc.buf);
-      return 64;
-    }
-  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    return 128;
-  return 0;
-}
-
-static int
-testMultithreadedPoolPut ()
-{
-  struct MHD_Daemon *d;
-  CURL *c;
-  struct CBC cbc;
-  unsigned int pos = 0;
-  int done_flag = 0;
-  CURLcode errornum;
-  char buf[2048];
-
-  cbc.buf = buf;
-  cbc.size = 2048;
-  cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | add_flag,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT,
-			MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (1024*1024),
-			MHD_OPTION_END);
+                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                        (size_t) (incr_read ? 1024 : (PUT_SIZE * 4 / 3)),
+                        MHD_OPTION_END);
   if (d == NULL)
-    return 16;
+    mhdErrorExit ();
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      mhdErrorExit ();
+    port = dinfo->port;
+  }
+
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-  curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-  if (oneone)
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-  else
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    externalErrorExit ();
+  }
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL,
+                                     "http://127.0.0.1/hello_world")) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION,
+                                     &putBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+
+  {
+    fprintf (stderr, "curl_easy_setopt() failed.\n");
+    externalErrorExit ();
+  }
+
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
-    {
-      fprintf (stderr, "Got invalid response `%.*s'\n", (int)cbc.pos, cbc.buf);
-      return 64;
-    }
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen ("/hello_world"));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
   if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    return 128;
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
   return 0;
 }
 
-static int
-testExternalPut ()
+
+static unsigned int
+testPutThreadPerConn (unsigned int add_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  char buf[2048];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1271;
+    if (oneone)
+      port += 10;
+    if (incr_read)
+      port += 20;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD
+                        | MHD_USE_ERROR_LOG | add_flag,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag,
+                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                        (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)),
+                        MHD_OPTION_END);
+  if (d == NULL)
+    mhdErrorExit ();
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      mhdErrorExit ();
+    port = dinfo->port;
+  }
+
+  c = curl_easy_init ();
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    externalErrorExit ();
+  }
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL,
+                                     "http://127.0.0.1/hello_world")) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION,
+                                     &putBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+  {
+    fprintf (stderr, "curl_easy_setopt() failed.\n");
+    externalErrorExit ();
+  }
+
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen ("/hello_world"));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  return 0;
+}
+
+
+static unsigned int
+testPutThreadPool (unsigned int add_flag)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  char buf[2048];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1272;
+    if (oneone)
+      port += 10;
+    if (incr_read)
+      port += 20;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | add_flag,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                        (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)),
+                        MHD_OPTION_END);
+  if (d == NULL)
+    mhdErrorExit ();
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      mhdErrorExit ();
+    port = dinfo->port;
+  }
+
+  c = curl_easy_init ();
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    externalErrorExit ();
+  }
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL,
+                                     "http://127.0.0.1/hello_world")) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION,
+                                     &putBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+  {
+    fprintf (stderr, "curl_easy_setopt() failed.\n");
+    externalErrorExit ();
+  }
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen ("/hello_world"));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  return 0;
+}
+
+
+static unsigned int
+testPutExternal (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -330,150 +622,259 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
   char buf[2048];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1273;
+    if (oneone)
+      port += 10;
+    if (incr_read)
+      port += 20;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
   multi = NULL;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag,
                         MHD_OPTION_CONNECTION_MEMORY_LIMIT,
-                        (size_t) (PUT_SIZE * 4), MHD_OPTION_END);
+                        (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)),
+                        MHD_OPTION_END);
   if (d == NULL)
-    return 256;
-  c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-  curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-  curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-  if (oneone)
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-  else
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+    mhdErrorExit ();
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      mhdErrorExit ();
+    port = dinfo->port;
+  }
 
+  c = curl_easy_init ();
+  if (NULL == c)
+  {
+    fprintf (stderr, "curl_easy_init() failed.\n");
+    externalErrorExit ();
+  }
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL,
+                                     "http://127.0.0.1/hello_world")) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION,
+                                     &putBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) 150)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+  {
+    fprintf (stderr, "curl_easy_setopt() failed.\n");
+    externalErrorExit ();
+  }
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+    libcurlErrorExit ();
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
-    {
-      curl_multi_cleanup (multi);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 1024;
-    }
+    libcurlErrorExit ();
+
   start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
+  while ((time (NULL) - start < 45) && (multi != NULL))
+  {
+    MHD_socket maxMHDsock;
+    int maxcurlsock;
+    maxMHDsock = MHD_INVALID_SOCKET;
+    maxcurlsock = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    mret = curl_multi_perform (multi, &running);
+    if ((CURLM_OK != mret) && (CURLM_CALL_MULTI_PERFORM != mret))
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
+      fprintf (stderr, "curl_multi_perform() failed. Error: '%s'. ",
+               curl_multi_strerror (mret));
+      libcurlErrorExit ();
     }
-  if (multi != NULL)
+    if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxcurlsock))
+      libcurlErrorExitDesc ("curl_multi_fdset() failed");
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMHDsock))
+      mhdErrorExit ();
+
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifndef MHD_WINSOCK_SOCKETS
+    if (maxMHDsock > maxcurlsock)
+      maxcurlsock = maxMHDsock;
+#endif /* MHD_WINSOCK_SOCKETS */
+    if (-1 == select (maxcurlsock + 1, &rs, &ws, &es, &tv))
     {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (tv.tv_sec * 1000 + tv.tv_usec / 1000);
+#endif
+    }
+
+    mret = curl_multi_perform (multi, &running);
+    if ((CURLM_OK != mret) && (CURLM_CALL_MULTI_PERFORM != mret))
+    {
+      fprintf (stderr, "curl_multi_perform() failed. Error: '%s'. ",
+               curl_multi_strerror (mret));
+      libcurlErrorExit ();
+    }
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "curl_multi_perform() failed: '%s' ",
+                     curl_easy_strerror (msg->data.result));
+            libcurlErrorExit ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code ");
+        mhdErrorExit ();
+      }
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
     }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+    mhdErrorExitDesc ("Request has been aborted by timeout");
+
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
-    {
-      fprintf (stderr, "Got invalid response `%.*s'\n", (int)cbc.pos, cbc.buf);
-      return 8192;
-    }
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen ("/hello_world"));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
   if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    return 16384;
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
   return 0;
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  unsigned int lastErr;
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  oneone = has_in_name (argv[0], "11");
+  incr_read = has_in_name (argv[0], "_inc");
+  verbose = has_param (argc, argv, "-v");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
-    return 2;
-  put_buffer = malloc (PUT_SIZE);
-  if (NULL == put_buffer) return 1;
-  memset (put_buffer, 1, PUT_SIZE);
-  errorCount += testInternalPut ();
-  errorCount += testMultithreadedPut ();
-  errorCount += testMultithreadedPoolPut ();
-  errorCount += testExternalPut ();
+    return 99;
+  put_buffer = alloc_init (PUT_SIZE);
+  if (NULL == put_buffer)
+    return 99;
+  lastErr = testPutExternal ();
+  if (verbose && (0 != lastErr))
+    fprintf (stderr, "Error during testing with external select().\n");
+  errorCount += lastErr;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    lastErr = testPutInternalThread (0);
+    if (verbose && (0 != lastErr) )
+      fprintf (stderr,
+               "Error during testing with internal thread with select().\n");
+    errorCount += lastErr;
+    lastErr = testPutThreadPerConn (0);
+    if (verbose && (0 != lastErr) )
+      fprintf (stderr,
+               "Error during testing with internal thread per connection with select().\n");
+    errorCount += lastErr;
+    lastErr = testPutThreadPool (0);
+    if (verbose && (0 != lastErr) )
+      fprintf (stderr,
+               "Error during testing with thread pool per connection with select().\n");
+    errorCount += lastErr;
+    if (MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      lastErr = testPutInternalThread (MHD_USE_POLL);
+      if (verbose && (0 != lastErr) )
+        fprintf (stderr,
+                 "Error during testing with internal thread with poll().\n");
+      errorCount += lastErr;
+      lastErr = testPutThreadPerConn (MHD_USE_POLL);
+      if (verbose && (0 != lastErr) )
+        fprintf (stderr,
+                 "Error during testing with internal thread per connection with poll().\n");
+      errorCount += lastErr;
+      lastErr = testPutThreadPool (MHD_USE_POLL);
+      if (verbose && (0 != lastErr) )
+        fprintf (stderr,
+                 "Error during testing with thread pool per connection with poll().\n");
+      errorCount += lastErr;
+    }
+    if (MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      lastErr = testPutInternalThread (MHD_USE_EPOLL);
+      if (verbose && (0 != lastErr) )
+        fprintf (stderr,
+                 "Error during testing with internal thread with epoll.\n");
+      errorCount += lastErr;
+      lastErr = testPutThreadPool (MHD_USE_EPOLL);
+      if (verbose && (0 != lastErr) )
+        fprintf (stderr,
+                 "Error during testing with thread pool per connection with epoll.\n");
+      errorCount += lastErr;
+    }
+  }
   free (put_buffer);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
+  else if (verbose)
+    printf ("All checks passed successfully.\n");
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (errorCount == 0) ? 0 : 1;
 }
diff --git a/src/testcurl/test_long_header.c b/src/testcurl/test_long_header.c
index e1e024b..a423d3b 100644
--- a/src/testcurl/test_long_header.c
+++ b/src/testcurl/test_long_header.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_long_header.c
  * @brief  Testcase for libmicrohttpd handling of very long headers
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -31,6 +33,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
@@ -41,16 +44,18 @@
  * half of this value, so the actual value does not have
  * to be big at all...
  */
-#define VERY_LONG (1024*10)
+#define VERY_LONG (1024 * 8)
 
 static int oneone;
 
-static int
+static enum MHD_Result
 apc_all (void *cls, const struct sockaddr *addr, socklen_t addrlen)
 {
+  (void) cls; (void) addr; (void) addrlen;   /* Unused. Silent compiler warning. */
   return MHD_YES;
 }
 
+
 struct CBC
 {
   char *buf;
@@ -61,35 +66,38 @@
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
+  (void) ptr; (void) ctx;  /* Unused. Silent compiler warning. */
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) version; (void) upload_data;      /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testLongUrlGet ()
+static unsigned int
+testLongUrlGet (size_t buff_size)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -97,34 +105,55 @@
   struct CBC cbc;
   char *url;
   long code;
+  uint16_t port;
 
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1330 + (uint16_t) (buff_size % 20);
+    if (oneone)
+      port += 5;
+  }
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        1080,
-                        &apc_all,
-                        NULL,
-                        &ahc_echo,
-                        "GET",
-                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
-                        (size_t) (VERY_LONG / 2), MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      port,
+                      &apc_all,
+                      NULL,
+                      &ahc_echo, NULL,
+                      MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                      (size_t) buff_size, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
   url = malloc (VERY_LONG);
-  if (url == NULL)
-    {
-	MHD_stop_daemon (d);
- 	return 1;
-    }
+  if (NULL == url)
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1;
+  }
   memset (url, 'a', VERY_LONG);
   url[VERY_LONG - 1] = '\0';
-  memcpy (url, "http://127.0.0.1:1080/", strlen ("http://127.0.0.1:1080/"));
+  memcpy (url, "http://127.0.0.1/", strlen ("http://127.0.0.1/"));
   curl_easy_setopt (c, CURLOPT_URL, url);
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -134,32 +163,32 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-  if (CURLE_OK == curl_easy_perform (c))
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      free (url);
-      return 2;
-    }
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != curl_easy_perform (c))
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    free (url);
+    return 2;
+  }
   if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      free (url);
-      return 4;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    free (url);
+    return 4;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   free (url);
-  if (code != MHD_HTTP_REQUEST_URI_TOO_LONG)
+  if (code != MHD_HTTP_URI_TOO_LONG)
     return 8;
   return 0;
 }
 
 
-static int
-testLongHeaderGet ()
+static unsigned int
+testLongHeaderGet (size_t buff_size)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -168,27 +197,48 @@
   char *url;
   long code;
   struct curl_slist *header = NULL;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1331 + (uint16_t) (buff_size % 20);
+    if (oneone)
+      port += 5;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        1080,
-                        &apc_all,
-                        NULL,
-                        &ahc_echo,
-                        "GET",
-                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
-                        (size_t) (VERY_LONG / 2), MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      port,
+                      &apc_all,
+                      NULL,
+                      &ahc_echo, NULL,
+                      MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                      (size_t) buff_size, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
   url = malloc (VERY_LONG);
-  if (url == NULL)
-     {
-	MHD_stop_daemon (d);
-	return 16;
-     }
+  if (NULL == url)
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 16;
+  }
   memset (url, 'a', VERY_LONG);
   url[VERY_LONG - 1] = '\0';
   url[VERY_LONG / 2] = ':';
@@ -196,10 +246,11 @@
   header = curl_slist_append (header, url);
 
   curl_easy_setopt (c, CURLOPT_HTTPHEADER, header);
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -209,45 +260,50 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-  if (CURLE_OK == curl_easy_perform (c))
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      curl_slist_free_all (header);
-      free (url);
-      return 32;
-    }
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (CURLE_OK != curl_easy_perform (c))
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    curl_slist_free_all (header);
+    free (url);
+    return 32;
+  }
   if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
-    {
-      curl_slist_free_all (header);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      free (url);
-      return 64;
-    }
+  {
+    curl_slist_free_all (header);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    free (url);
+    return 64;
+  }
   curl_slist_free_all (header);
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   free (url);
-  if (code != MHD_HTTP_REQUEST_ENTITY_TOO_LARGE)
+  if (code != MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE)
     return 128;
   return 0;
 }
 
+
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testLongUrlGet ();
-  errorCount += testLongHeaderGet ();
+  errorCount += testLongUrlGet (VERY_LONG / 2);
+  errorCount += testLongUrlGet (VERY_LONG / 2 + 978);
+  errorCount += testLongHeaderGet (VERY_LONG / 2);
+  errorCount += testLongHeaderGet (VERY_LONG / 2 + 1893);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_parse_cookies.c b/src/testcurl/test_parse_cookies.c
index 7d70867..5f6b847 100644
--- a/src/testcurl/test_parse_cookies.c
+++ b/src/testcurl/test_parse_cookies.c
@@ -1,31 +1,32 @@
-
 /*
-     This file is part of libmicrohttpd
+     This file is part of GNU libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
-     libmicrohttpd is free software; you can redistribute it and/or modify
+     GNU libmicrohttpd 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, or (at your
+     by the Free Software Foundation; either version 2, or (at your
      option) any later version.
 
-     libmicrohttpd is distributed in the hope that it will be useful, but
+     GNU libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_parse_cookies.c
  * @brief  Testcase for HTTP cookie parsing
+ * @author Karlson2k (Evgeny Grin)
  * @author Christian Grothoff
  */
 
-#include "MHD_config.h"
+#include "mhd_options.h"
 #include "platform.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
@@ -33,11 +34,1122 @@
 #include <string.h>
 #include <time.h>
 
-#ifndef WINDOWS
+#ifndef _WIN32
+#include <sys/socket.h>
 #include <unistd.h>
 #endif
 
-static int oneone;
+#include "mhd_has_param.h"
+#include "mhd_has_in_name.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \
+                       __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 500000
+
+#define EXPECTED_URI_BASE_PATH  "/"
+
+#define URL_SCHEME "http:/" "/"
+
+#define URL_HOST "127.0.0.1"
+
+#define URL_SCHEME_HOST URL_SCHEME URL_HOST
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd test page</title></head>" \
+  "<body>Success!</body></html>"
+
+#define PAGE_ERROR \
+  "<html><body>Cookies parsing error</body></html>"
+
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+
+struct strct_str_len
+{
+  const char *str;
+  const size_t len;
+};
+
+#define STR_LEN_(str)   {str, MHD_STATICSTR_LEN_(str)}
+#define STR_NULL_       {NULL, 0}
+
+struct strct_cookie
+{
+  struct strct_str_len name;
+  struct strct_str_len value;
+};
+
+#define COOKIE_(name,value)     {STR_LEN_(name), STR_LEN_(value)}
+#define COOKIE_NULL             {STR_NULL_, STR_NULL_}
+
+struct strct_test_data
+{
+  unsigned int line_num;
+  const char *header_str;
+  unsigned int num_cookies_strict_p2;
+  unsigned int num_cookies_strict_p1;
+  unsigned int num_cookies_strict_zero;
+  unsigned int num_cookies_strict_n2;
+  unsigned int num_cookies_strict_n3;
+  struct strct_cookie cookies[5];
+};
+
+static const struct strct_test_data test_data[] = {
+  {
+    __LINE__,
+    "name1=value1",
+    1,
+    1,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1;",
+    0,
+    1,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1; ",
+    0,
+    1,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "; name1=value1",
+    0,
+    0,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    ";name1=value1",
+    0,
+    0,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1 ",
+    1,
+    1,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1 ;",
+    0,
+    0,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1 ; ",
+    0,
+    0,
+    1,
+    1,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name2=\"value 2\"",
+    0,
+    0,
+    0,
+    1,
+    1,
+    {
+      COOKIE_ ("name2", "value 2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1;\tname2=value2",
+    0,
+    1,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1; name1=value1",
+    2,
+    2,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name1", "value1"), /* The second value is not checked actually */
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1; name2=value2",
+    2,
+    2,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1; name2=value2    ",
+    2,
+    2,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1;  name2=value2",
+    0,
+    1,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1;name2=value2",
+    0,
+    1,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1;\tname2=value2",
+    0,
+    1,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1 ; name2=value2",
+    0,
+    0,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "     name1=value1; name2=value2",
+    2,
+    2,
+    2,
+    2,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1; name2=var2; name3=; " \
+    "name4=\"var4 with spaces\"; " \
+    "name5=var_with_=_char",
+    0,
+    3,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1;name2=var2;name3=;" \
+    "name4=\"var4 with spaces\";" \
+    "name5=var_with_=_char",
+    0,
+    1,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1;  name2=var2;  name3=;  " \
+    "name4=\"var4 with spaces\";  " \
+    "name5=var_with_=_char\t \t",
+    0,
+    1,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1;;name2=var2;;name3=;;" \
+    "name4=\"var4 with spaces\";;" \
+    "name5=var_with_=_char;\t \t",
+    0,
+    1,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name3=; name1=var1; name2=var2; " \
+    "name5=var_with_=_char;" \
+    "name4=\"var4 with spaces\"",
+    0,
+    4,
+    4,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name4", "var4 with spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name2=var2; name1=var1; " \
+    "name5=var_with_=_char; name3=; " \
+    "name4=\"var4 with spaces\";",
+    0,
+    4,
+    4,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name4", "var4 with spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name2=var2; name1=var1; " \
+    "name5=var_with_=_char; " \
+    "name4=\"var4 with spaces\"; name3=",
+    0,
+    3,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name2=var2; name1=var1; " \
+    "name4=\"var4 with spaces\"; " \
+    "name5=var_with_=_char; name3=;",
+    0,
+    2,
+    2,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    ";;;;;;;;name1=var1; name2=var2; name3=; " \
+    "name4=\"var4 with spaces\"; " \
+    "name5=var_with_=_char",
+    0,
+    0,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1; name2=var2; name3=; " \
+    "name4=\"var4 with spaces\"; ; ; ; ; " \
+    "name5=var_with_=_char",
+    0,
+    3,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1; name2=var2; name3=; " \
+    "name4=\"var4 with spaces\"; " \
+    "name5=var_with_=_char;;;;;;;;",
+    0,
+    3,
+    3,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces"),
+      COOKIE_ ("name5", "var_with_=_char")
+    }
+  },
+  {
+    __LINE__,
+    "name1=var1; name2=var2; " \
+    "name4=\"var4 with spaces\";" \
+    "name5=var_with_=_char; ; ; ; ; name3=",
+    0,
+    2,
+    2,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name5=var_with_=_char ;" \
+    "name1=var1; name2=var2; name3=; " \
+    "name4=\"var4 with spaces\" ",
+    0,
+    0,
+    4,
+    5,
+    5,
+    {
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name4", "var4 with spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name5=var_with_=_char; name4=\"var4 with spaces\";" \
+    "name1=var1; name2=var2; name3=",
+    0,
+    1,
+    1,
+    5,
+    5,
+    {
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4 with spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name5=var_with_=_char; name4=\"var4_without_spaces\"; " \
+    "name1=var1; name2=var2; name3=",
+    5,
+    5,
+    5,
+    5,
+    5,
+    {
+      COOKIE_ ("name5", "var_with_=_char"),
+      COOKIE_ ("name1", "var1"),
+      COOKIE_ ("name2", "var2"),
+      COOKIE_ ("name3", ""),
+      COOKIE_ ("name4", "var4_without_spaces")
+    }
+  },
+  {
+    __LINE__,
+    "name1 = value1",
+    0,
+    0,
+    0,
+    0,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1\t=\tvalue1",
+    0,
+    0,
+    0,
+    0,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1\t = \tvalue1",
+    0,
+    0,
+    0,
+    0,
+    1,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1 = value1; name2 =\tvalue2",
+    0,
+    0,
+    0,
+    0,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1=value1; name2 =\tvalue2",
+    0,
+    1,
+    1,
+    1,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "name1 = value1; name2=value2",
+    0,
+    0,
+    0,
+    0,
+    2,
+    {
+      COOKIE_ ("name1", "value1"),
+      COOKIE_ ("name2", "value2"),
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "      ",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "\t",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "var=,",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "var=\"\\ \"",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "var=value  space",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "var=value\ttab",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "=",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "====",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    ";=",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "var",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "=;",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    "= ;",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  },
+  {
+    __LINE__,
+    ";= ;",
+    0,
+    0,
+    0,
+    0,
+    0,
+    {
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL,
+      COOKIE_NULL
+    }
+  }
+};
+
+/* Global parameters */
+static int verbose;
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+static int use_discp_n3;
+static int use_discp_n2;
+static int use_discp_zero;
+static int use_discp_p1;
+static int use_discp_p2;
+static int discp_level;
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_global_cleanup ();
+}
+
 
 struct CBC
 {
@@ -46,8 +1158,12 @@
   size_t size;
 };
 
+
 static size_t
-copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
 {
   struct CBC *cbc = ctx;
 
@@ -58,178 +1174,536 @@
   return size * nmemb;
 }
 
-static int
-ahc_echo (void *cls,
+
+struct ahc_cls_type
+{
+  const char *rq_method;
+  const char *rq_url;
+  const struct strct_test_data *check;
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
-  static int ptr;
-  const char *me = cls;
+  static int marker;
   struct MHD_Response *response;
-  int ret;
-  const char *hdr;
+  enum MHD_Result ret;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+  unsigned int expected_num_cookies;
+  unsigned int i;
+  int cookie_failed;
 
-  if (0 != strcmp (me, method))
-    return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
+  if (use_discp_p2)
+    expected_num_cookies = param->check->num_cookies_strict_p2;
+  else if (use_discp_p1)
+    expected_num_cookies = param->check->num_cookies_strict_p1;
+  else if (use_discp_zero)
+    expected_num_cookies = param->check->num_cookies_strict_zero;
+  else if (use_discp_n2)
+    expected_num_cookies = param->check->num_cookies_strict_n2;
+  else if (use_discp_n3)
+    expected_num_cookies = param->check->num_cookies_strict_n3;
+  else
+    externalErrorExit ();
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (oneone)
+  {
+    if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+      mhdErrorExitDesc ("Unexpected HTTP version");
+  }
+  else
+  {
+    if (0 != strcmp (version, MHD_HTTP_VERSION_1_0))
+      mhdErrorExitDesc ("Unexpected HTTP version");
+  }
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (NULL != upload_data)
+    mhdErrorExitDesc ("'upload_data' is not NULL");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+    mhdErrorExitDesc ("'*upload_data_size' value is not zero");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  cookie_failed = 0;
+  for (i = 0; i < expected_num_cookies; ++i)
+  {
+    const char *cookie_val;
+    size_t cookie_val_len;
+    const struct strct_cookie *const cookie_data = param->check->cookies + i;
+    if (NULL == cookie_data->name.str)
+      externalErrorExitDesc ("Broken test data");
+    if (NULL == cookie_data->value.str)
+      externalErrorExitDesc ("Broken test data");
+
+    cookie_val =
+      MHD_lookup_connection_value (connection,
+                                   MHD_COOKIE_KIND,
+                                   cookie_data->name.str);
+    if (cookie_val == NULL)
     {
-      *unused = &ptr;
-      return MHD_YES;
+      fprintf (stderr, "'%s' cookie not found.\n",
+               cookie_data->name.str);
+      cookie_failed = 1;
     }
-  *unused = NULL;
-  ret = 0;
+    else if (0 != strcmp (cookie_val,
+                          cookie_data->value.str))
+    {
+      fprintf (stderr, "'%s' cookie decoded incorrectly.\n"
+               "Expected: %s\nGot: %s\n",
+               cookie_data->name.str,
+               cookie_data->value.str,
+               cookie_val);
+      cookie_failed = 1;
+    }
+    else if (MHD_YES !=
+             MHD_lookup_connection_value_n (connection,
+                                            MHD_COOKIE_KIND,
+                                            cookie_data->name.str,
+                                            cookie_data->name.len,
+                                            &cookie_val, &cookie_val_len))
+    {
+      fprintf (stderr, "'%s' (length %lu) cookie not found.\n",
+               cookie_data->name.str,
+               (unsigned long) cookie_data->name.len);
+      cookie_failed = 1;
+    }
+    else
+    {
+      if (cookie_data->value.len != cookie_val_len)
+      {
+        fprintf (stderr, "'%s' (length %lu) cookie has wrong value length.\n"
+                 "Expected: %lu\nGot: %lu\n",
+                 cookie_data->name.str,
+                 (unsigned long) cookie_data->name.len,
+                 (unsigned long) cookie_data->value.len,
+                 (unsigned long) cookie_val_len);
+        cookie_failed = 1;
+      }
+      else if (0 != memcmp (cookie_val, cookie_data->value.str, cookie_val_len))
+      {
+        fprintf (stderr, "'%s' (length %lu) cookie has wrong value.\n"
+                 "Expected: %.*s\nGot: %.*s\n",
+                 cookie_data->name.str,
+                 (unsigned long) cookie_data->name.len,
+                 (int) cookie_data->value.len, cookie_data->value.str,
+                 (int) cookie_val_len, cookie_val);
+        cookie_failed = 1;
+      }
+    }
+  }
+  if (((int) expected_num_cookies) !=
+      MHD_get_connection_values_n (connection, MHD_COOKIE_KIND, NULL, NULL))
+  {
+    fprintf (stderr, "Wrong total number of cookies.\n"
+             "Expected: %u\nGot: %d\n",
+             expected_num_cookies,
+             MHD_get_connection_values_n (connection, MHD_COOKIE_KIND, NULL,
+                                          NULL));
+    cookie_failed = 1;
+  }
+  if (cookie_failed)
+  {
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_ERROR),
+                                              PAGE_ERROR);
+    ret = MHD_queue_response (connection,
+                              MHD_HTTP_BAD_REQUEST,
+                              response);
+    MHD_destroy_response (response);
 
-  hdr = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "name1");
-  if ((hdr == NULL) || (0 != strcmp (hdr, "var1")))
-    abort ();
-  hdr = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "name2");
-  if ((hdr == NULL) || (0 != strcmp (hdr, "var2")))
-    abort ();
-  hdr = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "name3");
-  if ((hdr == NULL) || (0 != strcmp (hdr, "")))
-    abort ();
-  hdr = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "name4");
-  if ((hdr == NULL) || (0 != strcmp (hdr, "var4 with spaces")))
-    abort ();
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_PERSISTENT);
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    return ret;
+  }
+
+  if (&marker != *req_cls)
+  {
+    *req_cls = &marker;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  response =
+    MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                            PAGE);
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
-  if (ret == MHD_NO)
-    abort ();
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+
   return ret;
 }
 
+
 static int
-testExternalGet ()
+libcurl_debug_cb (CURL *handle,
+                  curl_infotype type,
+                  char *data,
+                  size_t size,
+                  void *userptr)
 {
-  struct MHD_Daemon *d;
+  static const char excess_mark[] = "Excess found";
+  static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark);
+
+  (void) handle;
+  (void) userptr;
+
+#ifdef _DEBUG
+  switch (type)
+  {
+  case CURLINFO_TEXT:
+    fprintf (stderr, "* %.*s", (int) size, data);
+    break;
+  case CURLINFO_HEADER_IN:
+    fprintf (stderr, "< %.*s", (int) size, data);
+    break;
+  case CURLINFO_HEADER_OUT:
+    fprintf (stderr, "> %.*s", (int) size, data);
+    break;
+  case CURLINFO_DATA_IN:
+#if 0
+    fprintf (stderr, "<| %.*s\n", (int) size, data);
+#endif
+    break;
+  case CURLINFO_DATA_OUT:
+  case CURLINFO_SSL_DATA_IN:
+  case CURLINFO_SSL_DATA_OUT:
+  case CURLINFO_END:
+  default:
+    break;
+  }
+#endif /* _DEBUG */
+  if (CURLINFO_TEXT == type)
+  {
+    if ((size >= excess_mark_len) &&
+        (0 == memcmp (data, excess_mark, excess_mark_len)))
+      mhdErrorExitDesc ("Extra data has been detected in MHD reply");
+  }
+  return 0;
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port)
+{
   CURL *c;
-  char buf[2048];
-  struct CBC cbc;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) ||
+#ifdef _DEBUG
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) ||
+#endif /* _DEBUG */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION,
+                                     &libcurl_debug_cb)) ||
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK !=
+      curl_easy_setopt (c, CURLOPT_URL,
+                        URL_SCHEME_HOST EXPECTED_URI_BASE_PATH))
+    libcurlErrorExitDesc ("Cannot set request URL");
+
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse)
+{
   CURLM *multi;
-  CURLMcode mret;
-  fd_set rs;
-  fd_set ws;
-  fd_set es;
-  MHD_socket max;
-  int running;
-  struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  CURLcode ret;
 
-  multi = NULL;
-  cbc.buf = buf;
-  cbc.size = 2048;
-  cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        21080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
-  if (d == NULL)
-    return 256;
-  c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:21080/hello_world");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  /* note that the string below intentionally uses the
-     various ways cookies can be specified to exercise the
-     parser! Do not change! */
-  curl_easy_setopt (c, CURLOPT_COOKIE,
-                    "name1=var1; name2=var2,name3 ;name4=\"var4 with spaces\";");
-  if (oneone)
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  if (NULL != *multi_reuse)
+    multi = *multi_reuse;
   else
-    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  /* NOTE: use of CONNECTTIMEOUT without also
-     setting NOSIGNAL results in really weird
-     crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  {
+    multi = curl_multi_init ();
+    if (multi == NULL)
+      libcurlErrorExitDesc ("curl_multi_init() failed");
+    *multi_reuse = multi;
+  }
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
 
-
-  multi = curl_multi_init ();
-  if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
-  mret = curl_multi_add_handle (multi, c);
-  if (mret != CURLM_OK)
-    {
-      curl_multi_cleanup (multi);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 1024;
-    }
   start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
       curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
         {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
         {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
         }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
+        curl_multi_remove_handle (multi, c);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
     }
-  if (multi != NULL)
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 200000;
+    if (0 == MHD_get_timeout64s (d))
+      tv.tv_usec = 0;
+    else
     {
-      curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
-      curl_multi_cleanup (multi);
+      long curl_to = -1;
+      curl_multi_timeout (multi, &curl_to);
+      if (0 == curl_to)
+        tv.tv_usec = 0;
     }
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep ((unsigned long) tv.tv_usec / 1000);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/**
+ * Check request result
+ * @param curl_code the CURL easy return code
+ * @param pcbc the pointer struct CBC
+ * @return non-zero if success, zero if failed
+ */
+static unsigned int
+check_result (CURLcode curl_code, CURL *c, long expected_code,
+              struct CBC *pcbc)
+{
+  long code;
+
+  if (CURLE_OK != curl_code)
+  {
+    fflush (stdout);
+    if (0 != libcurl_errbuf[0])
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               curl_easy_strerror (curl_code),
+               libcurl_errbuf);
+    else
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n",
+               curl_easy_strerror (curl_code));
+    fflush (stderr);
+    return 0;
+  }
+
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
+    libcurlErrorExit ();
+
+  if (expected_code != code)
+  {
+    fprintf (stderr, "### The response has wrong HTTP code: %ld\t"
+             "Expected: %ld.\n",
+             code, expected_code);
+    return 0;
+  }
+  else if (verbose)
+    printf ("### The response has expected HTTP code: %ld\n", expected_code);
+
+  if (pcbc->pos != MHD_STATICSTR_LEN_ (PAGE))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf,
+             (unsigned) MHD_STATICSTR_LEN_ (PAGE));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ",
+             (int) pcbc->pos, pcbc->buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
+  fflush (stderr);
+  fflush (stdout);
+
+  return 1;
+}
+
+
+static unsigned int
+testExternalPolling (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t port;
+  struct CBC cbc;
+  struct ahc_cls_type ahc_param;
+  char buf[2048];
+  CURL *c;
+  CURLM *multi_reuse;
+  size_t i;
+  int failed = 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1340 + oneone ? 0 : 6 + (uint16_t) (1 + discp_level);
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahcCheck, &ahc_param,
+                        MHD_OPTION_CLIENT_DISCIPLINE_LVL,
+                        (int) (discp_level),
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = dinfo->port;
+  }
+
+  ahc_param.rq_method = MHD_HTTP_METHOD_GET;
+  ahc_param.rq_url = EXPECTED_URI_BASE_PATH;
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port);
+  multi_reuse = NULL;
+  for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); ++i)
+  {
+    cbc.pos = 0;
+    ahc_param.check = test_data + i;
+    if (CURLE_OK !=
+        curl_easy_setopt (c, CURLOPT_COOKIE,
+                          ahc_param.check->header_str))
+      libcurlErrorExitDesc ("Cannot set request cookies");
+
+    if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                      MHD_HTTP_OK, &cbc))
+    {
+      if (verbose)
+        printf ("### Got expected response for the check at line %u.\n",
+                test_data[i].line_num);
+      fflush (stdout);
+    }
+    else
+    {
+      fprintf (stderr, "### FAILED request for the check at line %u.\n",
+               test_data[i].line_num);
+      fflush (stderr);
+      failed = 1;
+    }
+  }
+
+  curl_easy_cleanup (c);
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+
   MHD_stop_daemon (d);
-  if (cbc.pos != strlen ("/hello_world"))
-    return 8192;
-  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    return 16384;
-  return 0;
+  return failed ? 1 : 0;
 }
 
 
@@ -238,13 +1712,40 @@
 {
   unsigned int errorCount = 0;
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
-  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
-    return 2;
-  errorCount += testExternalGet ();
+  /* Test type and test parameters */
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  oneone = ! has_in_name (argv[0], "10");
+  use_discp_n3 = has_in_name (argv[0], "_discp_n3");
+  use_discp_n2 = has_in_name (argv[0], "_discp_n2");
+  use_discp_zero = has_in_name (argv[0], "_discp_zero");
+  use_discp_p1 = has_in_name (argv[0], "_discp_p1");
+  use_discp_p2 = has_in_name (argv[0], "_discp_p2");
+  if (1 != ((use_discp_n3 ? 1 : 0) + (use_discp_n2 ? 1 : 0)
+            + (use_discp_zero ? 1 : 0)
+            + (use_discp_p1 ? 1 : 0) + (use_discp_p2 ? 1 : 0)))
+    return 99;
+
+  if (use_discp_n3)
+    discp_level = -3;
+  else if (use_discp_n2)
+    discp_level = -2;
+  else if (use_discp_zero)
+    discp_level = 0;
+  else if (use_discp_p1)
+    discp_level = 1;
+  else if (use_discp_p2)
+    discp_level = 2;
+
+  test_global_init ();
+
+  errorCount += testExternalPolling ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
-  curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+
+  test_global_cleanup ();
+
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_patch.c b/src/testcurl/test_patch.c
new file mode 100644
index 0000000..24da4d3
--- /dev/null
+++ b/src/testcurl/test_patch.c
@@ -0,0 +1,534 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2020 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file test_patch.c
+ * @brief  Testcase for libmicrohttpd PATCH operations
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+
+#ifndef WINDOWS
+#include <unistd.h>
+#endif
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+
+static int oneone;
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+static size_t
+putBuffer (void *stream, size_t size, size_t nmemb, void *ptr)
+{
+  size_t *pos = ptr;
+  size_t wrt;
+
+  wrt = size * nmemb;
+  if (wrt > 8 - (*pos))
+    wrt = 8 - (*pos);
+  memcpy (stream, &("Hello123"[*pos]), wrt);
+  (*pos) += wrt;
+  return wrt;
+}
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct CBC *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    return 0;                   /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+static enum MHD_Result
+ahc_echo (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  int *done = cls;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
+
+  if (0 != strcmp ("PATCH", method))
+    return MHD_NO;              /* unexpected method */
+  if ((*done) == 0)
+  {
+    if (*upload_data_size != 8)
+      return MHD_YES;           /* not yet ready */
+    if (0 == memcmp (upload_data, "Hello123", 8))
+    {
+      *upload_data_size = 0;
+    }
+    else
+    {
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
+    }
+    *done = 1;
+    return MHD_YES;
+  }
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  MHD_destroy_response (response);
+  return ret;
+}
+
+
+static CURL *
+setup_curl (long port,
+            struct CBC *cbc,
+            size_t *pos)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "PATCH");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
+  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+  curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc);
+  curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+  curl_easy_setopt (c, CURLOPT_READDATA, pos);
+  curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+  curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+  if (oneone)
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+  else
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+  return c;
+}
+
+
+static unsigned int
+testInternalPut (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1450;
+    if (oneone)
+      port += 10;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = setup_curl (port, &cbc, &pos);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 4;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 8;
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedPut (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1451;
+    if (oneone)
+      port += 10;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = setup_curl (port, &cbc, &pos);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 64;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 128;
+
+  return 0;
+}
+
+
+static unsigned int
+testMultithreadedPoolPut (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  size_t pos = 0;
+  int done_flag = 0;
+  CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1452;
+    if (oneone)
+      port += 10;
+  }
+
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = setup_curl (port, &cbc, &pos);
+  if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
+  curl_easy_cleanup (c);
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 64;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 128;
+
+  return 0;
+}
+
+
+static unsigned int
+testExternalPut (void)
+{
+  struct MHD_Daemon *d;
+  CURL *c;
+  char buf[2048];
+  struct CBC cbc;
+  CURLM *multi;
+  CURLMcode mret;
+  fd_set rs;
+  fd_set ws;
+  fd_set es;
+  MHD_socket maxsock;
+  int maxposixs; /* Max socket number unused on W32 */
+  int running;
+  struct CURLMsg *msg;
+  time_t start;
+  struct timeval tv;
+  size_t pos = 0;
+  int done_flag = 0;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1453;
+    if (oneone)
+      port += 10;
+  }
+
+  multi = NULL;
+  cbc.buf = buf;
+  cbc.size = 2048;
+  cbc.pos = 0;
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port,
+                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  if (d == NULL)
+    return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
+  c = setup_curl (port, &cbc, &pos);
+
+  multi = curl_multi_init ();
+  if (multi == NULL)
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
+  mret = curl_multi_add_handle (multi, c);
+  if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 2048;
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+#ifdef MHD_POSIX_SOCKETS
+    if (maxsock > maxposixs)
+      maxposixs = maxsock;
+#endif /* MHD_POSIX_SOCKETS */
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
+  MHD_stop_daemon (d);
+  if (cbc.pos != strlen ("/hello_world"))
+    return 8192;
+  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
+    return 16384;
+  return 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    return 2;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPut ();
+    errorCount += testMultithreadedPut ();
+    errorCount += testMultithreadedPoolPut ();
+  }
+  errorCount += testExternalPut ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  curl_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_post.c b/src/testcurl/test_post.c
index 49bf30a..658b7dd 100644
--- a/src/testcurl/test_post.c
+++ b/src/testcurl/test_post.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_post.c
  * @brief  Testcase for libmicrohttpd POST operations using URL-encoding
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -43,11 +45,13 @@
 #include <windows.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#include "mhd_has_in_name.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 #define POST_DATA "name=daniel&project=curl"
@@ -64,15 +68,16 @@
 
 static void
 completed_cb (void *cls,
-	      struct MHD_Connection *connection,
-	      void **con_cls,
-	      enum MHD_RequestTerminationCode toe)
+              struct MHD_Connection *connection,
+              void **req_cls,
+              enum MHD_RequestTerminationCode toe)
 {
-  struct MHD_PostProcessor *pp = *con_cls;
+  struct MHD_PostProcessor *pp = *req_cls;
+  (void) cls; (void) connection; (void) toe; /* Unused. Silent compiler warning. */
 
   if (NULL != pp)
-    MHD_destroy_post_processor (pp);   
-  *con_cls = NULL;
+    MHD_destroy_post_processor (pp);
+  *req_cls = NULL;
 }
 
 
@@ -94,7 +99,7 @@
  * in that it fails to support incremental processing.
  * (to be fixed in the future)
  */
-static int
+static enum MHD_Result
 post_iterator (void *cls,
                enum MHD_ValueKind kind,
                const char *key,
@@ -104,6 +109,8 @@
                const char *value, uint64_t off, size_t size)
 {
   int *eok = cls;
+  (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; (void) off;            /* Unused. Silent compiler warning. */
 
   if ((0 == strcmp (key, "name")) &&
       (size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size)))
@@ -115,94 +122,115 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int eok;
   struct MHD_Response *response;
   struct MHD_PostProcessor *pp;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) version;      /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp ("POST", method))
-    {
-      printf ("METHOD: %s\n", method);
-      return MHD_NO;            /* unexpected method */
-    }
-  pp = *unused;
+  if (0 != strcmp (MHD_HTTP_METHOD_POST, method))
+  {
+    fprintf (stderr, "METHOD: %s\n", method);
+    return MHD_NO;              /* unexpected method */
+  }
+  pp = *req_cls;
   if (pp == NULL)
-    {
-      eok = 0;
-      pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
-      *unused = pp;
-    }
+  {
+    eok = 0;
+    pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
+    *req_cls = pp;
+  }
   MHD_post_process (pp, upload_data, *upload_data_size);
   if ((eok == 3) && (0 == *upload_data_size))
-    {
-      response = MHD_create_response_from_buffer (strlen (url),
-						  (void *) url,
-						  MHD_RESPMEM_MUST_COPY);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
-      MHD_destroy_post_processor (pp);
-      *unused = NULL;
-      return ret;
-    }
+  {
+    response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                     (const void *) url);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+    MHD_destroy_post_processor (pp);
+    *req_cls = NULL;
+    return ret;
+  }
   *upload_data_size = 0;
   return MHD_YES;
 }
 
 
-static int
-testInternalPost ()
+static unsigned int
+testInternalPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1370;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
   curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
   curl_easy_setopt (c, CURLOPT_POST, 1L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -212,51 +240,74 @@
   return 0;
 }
 
-static int
-testMultithreadedPost ()
+
+static unsigned int
+testMultithreadedPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1371;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
   curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
   curl_easy_setopt (c, CURLOPT_POST, 1L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -266,52 +317,74 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolPost ()
+
+static unsigned int
+testMultithreadedPoolPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1372;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, NULL,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT,
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
   curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
   curl_easy_setopt (c, CURLOPT_POST, 1L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -321,8 +394,9 @@
   return 0;
 }
 
-static int
-testExternalPost ()
+
+static unsigned int
+testExternalPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -333,113 +407,174 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1373;
+    if (oneone)
+      port += 10;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
   curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
   curl_easy_setopt (c, CURLOPT_POST, 1L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -449,45 +584,48 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_cancel (void *cls,
-	    struct MHD_Connection *connection,
-	    const char *url,
-	    const char *method,
-	    const char *version,
-	    const char *upload_data, size_t *upload_data_size,
-	    void **unused)
+            struct MHD_Connection *connection,
+            const char *url,
+            const char *method,
+            const char *version,
+            const char *upload_data, size_t *upload_data_size,
+            void **req_cls)
 {
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) url; (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
   if (0 != strcmp ("POST", method))
-    {
-      fprintf (stderr,
-	       "Unexpected method `%s'\n", method);
-      return MHD_NO; 
-    }
+  {
+    fprintf (stderr,
+             "Unexpected method `%s'\n", method);
+    return MHD_NO;
+  }
 
-  if (*unused == NULL)
-    {
-      *unused = "wibble";
-      /* We don't want the body. Send a 500. */
-      response = MHD_create_response_from_buffer (0, NULL, 
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response(connection, 500, response);
-      if (ret != MHD_YES)
-	fprintf(stderr, "Failed to queue response\n");
-      MHD_destroy_response(response);
-      return ret;
-    }
+  if (*req_cls == NULL)
+  {
+    static int marker = 1;
+    *req_cls = &marker;
+    /* We don't want the body. Send a 500. */
+    response = MHD_create_response_empty (MHD_RF_NONE);
+    ret = MHD_queue_response (connection, 500, response);
+    if (ret != MHD_YES)
+      fprintf (stderr, "Failed to queue response\n");
+    MHD_destroy_response (response);
+    return ret;
+  }
   else
-    {
-      fprintf(stderr, 
-	      "In ahc_cancel again. This should not happen.\n");
-      return MHD_NO;
-    }
+  {
+    fprintf (stderr,
+             "In ahc_cancel again. This should not happen.\n");
+    return MHD_NO;
+  }
 }
 
+
 struct CRBC
 {
   const char *buffer;
@@ -496,28 +634,28 @@
 };
 
 
-static size_t 
-readBuffer(void *p, size_t size, size_t nmemb, void *opaque)
+static size_t
+readBuffer (void *p, size_t size, size_t nmemb, void *opaque)
 {
   struct CRBC *data = opaque;
   size_t required = size * nmemb;
   size_t left = data->size - data->pos;
-  
+
   if (required > left)
     required = left;
-  
-  memcpy(p, data->buffer + data->pos, required);
+
+  memcpy (p, data->buffer + data->pos, required);
   data->pos += required;
-  
-  return required/size;
+
+  return required / size;
 }
 
 
-static size_t 
-slowReadBuffer(void *p, size_t size, size_t nmemb, void *opaque)
+static size_t
+slowReadBuffer (void *p, size_t size, size_t nmemb, void *opaque)
 {
-  sleep(1);
-  return readBuffer(p, size, nmemb, opaque);
+  (void) sleep (1);
+  return readBuffer (p, size, nmemb, opaque);
 }
 
 
@@ -528,8 +666,8 @@
 #define FLAG_COUNT 16
 
 
-static int
-testMultithreadedPostCancelPart(int flags)
+static unsigned int
+testMultithreadedPostCancelPart (int flags)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -539,96 +677,138 @@
   struct curl_slist *headers = NULL;
   long response_code;
   CURLcode cc;
-  int result = 0;
+  unsigned int result = 0;
   struct CRBC crbc;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1374;
+    if (oneone)
+      port += 10;
+  }
 
   /* Don't test features that aren't available with HTTP/1.0 in
    * HTTP/1.0 mode. */
-  if (!oneone && (flags & (FLAG_EXPECT_CONTINUE | FLAG_CHUNKED)))
+  if (! oneone && (flags & (FLAG_EXPECT_CONTINUE | FLAG_CHUNKED)))
     return 0;
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_cancel, NULL, 
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_cancel, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 32768;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
 
   crbc.buffer = "Test content";
-  crbc.size = strlen(crbc.buffer);
+  crbc.size = strlen (crbc.buffer);
   crbc.pos = 0;
-  
+
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_READFUNCTION, (flags & FLAG_SLOW_READ) ? &slowReadBuffer : &readBuffer);
+  curl_easy_setopt (c, CURLOPT_READFUNCTION, (flags & FLAG_SLOW_READ) ?
+                    &slowReadBuffer : &readBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &crbc);
   curl_easy_setopt (c, CURLOPT_POSTFIELDS, NULL);
   curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, crbc.size);
   curl_easy_setopt (c, CURLOPT_POST, 1L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
   if (flags & FLAG_CHUNKED)
-      headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
-  if (!(flags & FLAG_FORM_DATA))
-  headers = curl_slist_append(headers, "Content-Type: application/octet-stream");
+    headers = curl_slist_append (headers, "Transfer-Encoding: chunked");
+  if (! (flags & FLAG_FORM_DATA))
+    headers = curl_slist_append (headers,
+                                 "Content-Type: application/octet-stream");
   if (flags & FLAG_EXPECT_CONTINUE)
-      headers = curl_slist_append(headers, "Expect: 100-Continue");
-  curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers);
-  
+    headers = curl_slist_append (headers, "Expect: 100-Continue");
+  curl_easy_setopt (c, CURLOPT_HTTPHEADER, headers);
+
   if (CURLE_HTTP_RETURNED_ERROR != (errornum = curl_easy_perform (c)))
+  {
+#ifdef _WIN32
+    curl_version_info_data *curlverd = curl_version_info (CURLVERSION_NOW);
+    if ((0 != (flags & FLAG_SLOW_READ)) && (CURLE_RECV_ERROR == errornum) &&
+        ((curlverd == NULL) || (curlverd->ares_num < 0x073100) ) )
+    {     /* libcurl up to version 7.49.0 didn't have workaround for WinSock bug */
+      fprintf (stderr,
+               "Ignored curl_easy_perform expected failure on W32 with \"slow read\".\n");
+      result = 0;
+    }
+    else
+#else  /* ! _WIN32 */
+    if (1)
+#endif /* ! _WIN32 */
     {
       fprintf (stderr,
-               "flibbet curl_easy_perform didn't fail as expected: `%s' %d\n",
-               curl_easy_strerror (errornum), errornum);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      curl_slist_free_all(headers);
-      return 65536;
-    }
-  
-  if (CURLE_OK != (cc = curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &response_code)))
-    {
-      fprintf(stderr, "curl_easy_getinfo failed: '%s'\n", curl_easy_strerror(errornum));
+               "flibbet curl_easy_perform didn't fail as expected: `%s' %u\n",
+               curl_easy_strerror (errornum), (unsigned int) errornum);
       result = 65536;
     }
-  
-  if (!result && (response_code != 500))
-    {
-      fprintf(stderr, "Unexpected response code: %ld\n", response_code);
-      result = 131072;
-    }
-  
-  if (!result && (cbc.pos != 0))
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    curl_slist_free_all (headers);
+    return result;
+  }
+
+  if (CURLE_OK != (cc = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE,
+                                           &response_code)))
+  {
+    fprintf (stderr, "curl_easy_getinfo failed: '%s'\n",
+             curl_easy_strerror (cc));
+    result = 65536;
+  }
+
+  if (! result && (response_code != 500))
+  {
+    fprintf (stderr, "Unexpected response code: %ld\n", response_code);
+    result = 131072;
+  }
+
+  if (! result && (cbc.pos != 0))
     result = 262144;
 
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
-  curl_slist_free_all(headers);
+  curl_slist_free_all (headers);
   return result;
 }
 
 
-static int
-testMultithreadedPostCancel()
+static unsigned int
+testMultithreadedPostCancel (void)
 {
-  int result = 0;
+  unsigned int result = 0;
   int flags;
-  for(flags = 0; flags < FLAG_COUNT; ++flags)
-    result |= testMultithreadedPostCancelPart(flags);  
+  for (flags = 0; flags < FLAG_COUNT; ++flags)
+    result |= testMultithreadedPostCancelPart (flags);
   return result;
 }
 
@@ -637,18 +817,23 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testMultithreadedPostCancel ();
-  errorCount += testInternalPost ();
-  errorCount += testMultithreadedPost ();
-  errorCount += testMultithreadedPoolPost ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testMultithreadedPostCancel ();
+    errorCount += testInternalPost ();
+    errorCount += testMultithreadedPost ();
+    errorCount += testMultithreadedPoolPost ();
+  }
   errorCount += testExternalPost ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_post_loop.c b/src/testcurl/test_post_loop.c
index fe8d25c..593599c 100644
--- a/src/testcurl/test_post_loop.c
+++ b/src/testcurl/test_post_loop.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_post_loop.c
  * @brief  Testcase for libmicrohttpd POST operations using URL-encoding
  * @author Christian Grothoff (inspired by bug report #1296)
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -31,22 +33,28 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#include <gauger.h>
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
-#define POST_DATA "<?xml version='1.0' ?>\n<xml>\n<data-id>1</data-id>\n</xml>\n"
+#define POST_DATA \
+  "<?xml version='1.0' ?>\n<xml>\n<data-id>1</data-id>\n</xml>\n"
 
+#ifndef __APPLE__
 #define LOOPCOUNT 1000
+#else  /* __APPLE__ */
+/* FIXME: macOS may fail in this test with "unable to connect". Investigate deeper? */
+#define LOOPCOUNT 200
+#endif /* __APPLE__ */
 
 static int oneone;
 
@@ -69,45 +77,48 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **mptr)
+          void **req_cls)
 {
   static int marker;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) url; (void) version;          /* Unused. Silent compiler warning. */
+  (void) upload_data; (void) upload_data_size;     /* Unused. Silent compiler warning. */
 
   if (0 != strcmp ("POST", method))
-    {
-      printf ("METHOD: %s\n", method);
-      return MHD_NO;            /* unexpected method */
-    }
-  if ((*mptr != NULL) && (0 == *upload_data_size))
-    {
-      if (*mptr != &marker)
-        abort ();
-      response = MHD_create_response_from_buffer (2, "OK", 
-						  MHD_RESPMEM_PERSISTENT);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
-      *mptr = NULL;
-      return ret;
-    }
+  {
+    printf ("METHOD: %s\n", method);
+    return MHD_NO;              /* unexpected method */
+  }
+  if ((*req_cls != NULL) && (0 == *upload_data_size))
+  {
+    if (*req_cls != &marker)
+      abort ();
+    response = MHD_create_response_from_buffer_static (2,
+                                                       "OK");
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+    *req_cls = NULL;
+    return ret;
+  }
   if (strlen (POST_DATA) != *upload_data_size)
     return MHD_YES;
   *upload_data_size = 0;
-  *mptr = &marker;
+  *req_cls = &marker;
   return MHD_YES;
 }
 
 
-static int
-testInternalPost ()
+static unsigned int
+testInternalPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -116,62 +127,87 @@
   CURLcode errornum;
   int i;
   char url[1024];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1350;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
-  for (i = 0; i < LOOPCOUNT; i++)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      if (99 == i % 100)
-        fprintf (stderr, ".");
-      c = curl_easy_init ();
-      cbc.pos = 0;
-      buf[0] = '\0';
-      sprintf (url, "http://127.0.0.1:1080/hw%d", i);
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-        {
-          fprintf (stderr,
-                   "curl_easy_perform failed: `%s'\n",
-                   curl_easy_strerror (errornum));
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2;
-        }
-      curl_easy_cleanup (c);
-      if ((buf[0] != 'O') || (buf[1] != 'K'))
-        {
-          MHD_stop_daemon (d);
-          return 4;
-        }
+      MHD_stop_daemon (d); return 32;
     }
+    port = dinfo->port;
+  }
+  for (i = 0; i < LOOPCOUNT; i++)
+  {
+    if (99 == i % 100)
+      fprintf (stderr, ".");
+    c = curl_easy_init ();
+    cbc.pos = 0;
+    buf[0] = '\0';
+    snprintf (url,
+              sizeof (url),
+              "http://127.0.0.1:%u/hw%d",
+              (unsigned int) port,
+              i);
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 2;
+    }
+    curl_easy_cleanup (c);
+    if ((buf[0] != 'O') || (buf[1] != 'K'))
+    {
+      MHD_stop_daemon (d);
+      return 4;
+    }
+  }
   MHD_stop_daemon (d);
   if (LOOPCOUNT >= 99)
     fprintf (stderr, "\n");
   return 0;
 }
 
-static int
-testMultithreadedPost ()
+
+static unsigned int
+testMultithreadedPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -180,62 +216,90 @@
   CURLcode errornum;
   int i;
   char url[1024];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1351;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
-  for (i = 0; i < LOOPCOUNT; i++)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      if (99 == i % 100)
-        fprintf (stderr, ".");
-      c = curl_easy_init ();
-      cbc.pos = 0;
-      buf[0] = '\0';
-      sprintf (url, "http://127.0.0.1:1081/hw%d", i);
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-        {
-          fprintf (stderr,
-                   "curl_easy_perform failed: `%s'\n",
-                   curl_easy_strerror (errornum));
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 32;
-        }
-      curl_easy_cleanup (c);
-      if ((buf[0] != 'O') || (buf[1] != 'K'))
-        {
-          MHD_stop_daemon (d);
-          return 64;
-        }
+      MHD_stop_daemon (d); return 32;
     }
+    port = dinfo->port;
+  }
+  for (i = 0; i < LOOPCOUNT; i++)
+  {
+    if (99 == i % 100)
+      fprintf (stderr, ".");
+    c = curl_easy_init ();
+    cbc.pos = 0;
+    buf[0] = '\0';
+    snprintf (url,
+              sizeof (url),
+              "http://127.0.0.1:%u/hw%d",
+              (unsigned int) port,
+              i);
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 32;
+    }
+    curl_easy_cleanup (c);
+    if ((buf[0] != 'O') || (buf[1] != 'K'))
+    {
+      MHD_stop_daemon (d);
+      return 64;
+    }
+  }
   MHD_stop_daemon (d);
   if (LOOPCOUNT >= 99)
     fprintf (stderr, "\n");
   return 0;
 }
 
-static int
-testMultithreadedPoolPost ()
+
+static unsigned int
+testMultithreadedPoolPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -244,63 +308,89 @@
   CURLcode errornum;
   int i;
   char url[1024];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1352;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, NULL,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
-  for (i = 0; i < LOOPCOUNT; i++)
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      if (99 == i % 100)
-        fprintf (stderr, ".");
-      c = curl_easy_init ();
-      cbc.pos = 0;
-      buf[0] = '\0';
-      sprintf (url, "http://127.0.0.1:1081/hw%d", i);
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      if (CURLE_OK != (errornum = curl_easy_perform (c)))
-        {
-          fprintf (stderr,
-                   "curl_easy_perform failed: `%s'\n",
-                   curl_easy_strerror (errornum));
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 32;
-        }
-      curl_easy_cleanup (c);
-      if ((buf[0] != 'O') || (buf[1] != 'K'))
-        {
-          MHD_stop_daemon (d);
-          return 64;
-        }
+      MHD_stop_daemon (d); return 32;
     }
+    port = dinfo->port;
+  }
+  for (i = 0; i < LOOPCOUNT; i++)
+  {
+    if (99 == i % 100)
+      fprintf (stderr, ".");
+    c = curl_easy_init ();
+    cbc.pos = 0;
+    buf[0] = '\0';
+    snprintf (url,
+              sizeof (url),
+              "http://127.0.0.1:%u/hw%d",
+              (unsigned int) port,
+              i);
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    if (CURLE_OK != (errornum = curl_easy_perform (c)))
+    {
+      fprintf (stderr,
+               "curl_easy_perform failed: `%s'\n",
+               curl_easy_strerror (errornum));
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 32;
+    }
+    curl_easy_cleanup (c);
+    if ((buf[0] != 'O') || (buf[1] != 'K'))
+    {
+      MHD_stop_daemon (d);
+      return 64;
+    }
+  }
   MHD_stop_daemon (d);
   if (LOOPCOUNT >= 99)
     fprintf (stderr, "\n");
   return 0;
 }
 
-static int
-testExternalPost ()
+
+static unsigned int
+testExternalPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -311,140 +401,200 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
   int i;
-  unsigned long long timeout;
+  uint64_t timeout64;
   long ctimeout;
   char url[1024];
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1353;
+    if (oneone)
+      port += 10;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   for (i = 0; i < LOOPCOUNT; i++)
+  {
+    if (99 == i % 100)
+      fprintf (stderr, ".");
+    c = curl_easy_init ();
+    cbc.pos = 0;
+    buf[0] = '\0';
+    snprintf (url,
+              sizeof (url),
+              "http://127.0.0.1:%u/hw%d",
+              (unsigned int) port,
+              i);
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      if (99 == i % 100)
-	fprintf (stderr, ".");
-      c = curl_easy_init ();
-      cbc.pos = 0;
-      buf[0] = '\0';
-      sprintf (url, "http://127.0.0.1:1082/hw%d", i);
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (multi != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          while (CURLM_CALL_MULTI_PERFORM ==
-                 curl_multi_perform (multi, &running));
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          if (MHD_NO == MHD_get_timeout (d, &timeout))
-            timeout = 100;      /* 100ms == INFTY -- CURL bug... */
-          if ((CURLM_OK == curl_multi_timeout (multi, &ctimeout)) &&
-              (ctimeout < timeout) && (ctimeout >= 0))
-            timeout = ctimeout;
-	  if ( (c == NULL) || (running == 0) )
-	    timeout = 0; /* terminate quickly... */
-          tv.tv_sec = timeout / 1000;
-          tv.tv_usec = (timeout % 1000) * 1000;
-          if (-1 == select (max + 1, &rs, &ws, &es, &tv))
-	    {
-	      if (EINTR == errno)
-		continue;
-	      fprintf (stderr,
-		       "select failed: %s\n",
-		       strerror (errno));
-	      break;	      
-	    }
-          while (CURLM_CALL_MULTI_PERFORM ==
-                 curl_multi_perform (multi, &running));
-          if (running == 0)
-            {
-              msg = curl_multi_info_read (multi, &running);
-              if (msg == NULL)
-                break;
-              if (msg->msg == CURLMSG_DONE)
-                {
-                  if (msg->data.result != CURLE_OK)
-                    printf ("%s failed at %s:%d: `%s'\n",
-                            "curl_multi_perform",
-                            __FILE__,
-                            __LINE__, curl_easy_strerror (msg->data.result));
-                  curl_multi_remove_handle (multi, c);
-                  curl_easy_cleanup (c);
-                  c = NULL;
-                }
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
-      if ((buf[0] != 'O') || (buf[1] != 'K'))
-        {
-          curl_multi_cleanup (multi);
-          MHD_stop_daemon (d);
-          return 8192;
-        }
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (multi != NULL))
+    {
+      maxsock = MHD_INVALID_SOCKET;
+      maxposixs = -1;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      while (CURLM_CALL_MULTI_PERFORM ==
+             curl_multi_perform (multi, &running))
+        ;
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      if (MHD_NO == MHD_get_timeout64 (d, &timeout64))
+        timeout64 = 100;          /* 100ms == INFTY -- CURL bug... */
+      if ((CURLM_OK == curl_multi_timeout (multi, &ctimeout)) &&
+          (ctimeout >= 0) && ((uint64_t) ctimeout < timeout64))
+        timeout64 = (uint64_t) ctimeout;
+      if (0 == running)
+        timeout64 = 0; /* terminate quickly... */
+#if ! defined(_WIN32) || defined(__CYGWIN__)
+      tv.tv_sec = (time_t) (timeout64 / 1000);
+#else  /* Native W32 */
+      tv.tv_sec = (long) (timeout64 / 1000);
+#endif /* Native W32 */
+      tv.tv_usec = (long) (1000 * (timeout64 % 1000));
+      if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+      {
+#ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+        {
+          fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                   (int) errno, __LINE__);
+          fflush (stderr);
+          exit (99);
+        }
+#else
+        if ((WSAEINVAL != WSAGetLastError ()) ||
+            (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        {
+          fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                   (int) WSAGetLastError (), __LINE__);
+          fflush (stderr);
+          exit (99);
+        }
+        Sleep (1);
+#endif
+      }
+      while (CURLM_CALL_MULTI_PERFORM ==
+             curl_multi_perform (multi, &running))
+        ;
+      if (0 == running)
+      {
+        int pending;
+        int curl_fine = 0;
+        while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+        {
+          if (msg->msg == CURLMSG_DONE)
+          {
+            if (msg->data.result == CURLE_OK)
+              curl_fine = 1;
+            else
+            {
+              fprintf (stderr,
+                       "%s failed at %s:%d: `%s'\n",
+                       "curl_multi_perform",
+                       __FILE__,
+                       __LINE__, curl_easy_strerror (msg->data.result));
+              abort ();
+            }
+          }
+        }
+        if (! curl_fine)
+        {
+          fprintf (stderr, "libcurl haven't returned OK code\n");
+          abort ();
+        }
+        break;
+      }
+      MHD_run (d);
+    }
+    if (NULL != c)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+    if ((buf[0] != 'O') || (buf[1] != 'K'))
+    {
+      curl_multi_cleanup (multi);
+      MHD_stop_daemon (d);
+      return 8192;
+    }
+  }
   curl_multi_cleanup (multi);
   MHD_stop_daemon (d);
   if (LOOPCOUNT >= 99)
@@ -460,18 +610,18 @@
 
 
 /**
- * Get the current timestamp 
+ * Get the current timestamp
  *
  * @return current time in ms
  */
-static unsigned long long 
-now ()
+static unsigned long long
+now (void)
 {
   struct timeval tv;
 
   gettimeofday (&tv, NULL);
-  return (((unsigned long long) tv.tv_sec * 1000LL) +
-	  ((unsigned long long) tv.tv_usec / 1000LL));
+  return (((unsigned long long) tv.tv_sec * 1000LL)
+          + ((unsigned long long) tv.tv_usec / 1000LL));
 }
 
 
@@ -479,53 +629,50 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  start_time = now();
-  errorCount += testInternalPost ();
-  fprintf (stderr,
-	   oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n",
-	   "internal select",
-	   (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0));
-  GAUGER ("internal select",
-	  oneone ? "Sequential POSTs (http/1.1)" : "Sequential POSTs (http/1.0)",
-	  (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0),
-	  "requests/s");
-  start_time = now();
-  errorCount += testMultithreadedPost ();
-  fprintf (stderr,
-	   oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n",
-	   "multithreaded post",
-	   (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0));
-  GAUGER ("Multithreaded select",
-	  oneone ? "Sequential POSTs (http/1.1)" : "Sequential POSTs (http/1.0)",
-	  (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0),
-	  "requests/s");
-  start_time = now();
-  errorCount += testMultithreadedPoolPost ();
-  fprintf (stderr,
-	   oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n",
-	   "thread with pool",
-	   (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0));
-  GAUGER ("thread with pool",
-	  oneone ? "Sequential POSTs (http/1.1)" : "Sequential POSTs (http/1.0)",
-	  (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0),
-	  "requests/s");
-  start_time = now();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    start_time = now ();
+    errorCount += testInternalPost ();
+    fprintf (stderr,
+             oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" :
+             "%s: Sequential POSTs (http/1.0) %f/s\n",
+             "internal select",
+             (double) 1000 * LOOPCOUNT
+             / ((double) (now () - start_time) + 1.0));
+    start_time = now ();
+    errorCount += testMultithreadedPost ();
+    fprintf (stderr,
+             oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" :
+             "%s: Sequential POSTs (http/1.0) %f/s\n",
+             "multithreaded post",
+             (double) 1000 * LOOPCOUNT
+             / ((double) (now () - start_time) + 1.0));
+    start_time = now ();
+    errorCount += testMultithreadedPoolPost ();
+    fprintf (stderr,
+             oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" :
+             "%s: Sequential POSTs (http/1.0) %f/s\n",
+             "thread with pool",
+             (double) 1000 * LOOPCOUNT
+             / ((double) (now () - start_time) + 1.0));
+  }
+  start_time = now ();
   errorCount += testExternalPost ();
   fprintf (stderr,
-	   oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n",
-	   "external select",
-	   (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0));
-  GAUGER ("external select",
-	  oneone ? "Sequential POSTs (http/1.1)" : "Sequential POSTs (http/1.0)",
-	  (double) 1000 * LOOPCOUNT / (now() - start_time + 1.0),
-	  "requests/s");
+           oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" :
+           "%s: Sequential POSTs (http/1.0) %f/s\n",
+           "external select",
+           (double) 1000 * LOOPCOUNT
+           / ((double) (now () - start_time) + 1.0));
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_postform.c b/src/testcurl/test_postform.c
index 450eb6f..289a95d 100644
--- a/src/testcurl/test_postform.c
+++ b/src/testcurl/test_postform.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2023 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_postform.c
  * @brief  Testcase for libmicrohttpd POST operations using multipart/postform data
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -31,19 +33,35 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #ifdef HAVE_GCRYPT_H
 #include <gcrypt.h>
 #endif
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
 
 #ifndef WINDOWS
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#if CURL_AT_LEAST_VERSION (7,56,0)
+#define HAS_CURL_MIME 1
+#endif /* CURL_AT_LEAST_VERSION(7,56,0) */
+
+#include "mhd_has_in_name.h"
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 static int oneone;
@@ -58,15 +76,16 @@
 
 static void
 completed_cb (void *cls,
-	      struct MHD_Connection *connection,
-	      void **con_cls,
-	      enum MHD_RequestTerminationCode toe)
+              struct MHD_Connection *connection,
+              void **req_cls,
+              enum MHD_RequestTerminationCode toe)
 {
-  struct MHD_PostProcessor *pp = *con_cls;
+  struct MHD_PostProcessor *pp = *req_cls;
+  (void) cls; (void) connection; (void) toe;            /* Unused. Silent compiler warning. */
 
   if (NULL != pp)
     MHD_destroy_post_processor (pp);
-  *con_cls = NULL;
+  *req_cls = NULL;
 }
 
 
@@ -88,7 +107,7 @@
  * in that it fails to support incremental processing.
  * (to be fixed in the future)
  */
-static int
+static enum MHD_Result
 post_iterator (void *cls,
                enum MHD_ValueKind kind,
                const char *key,
@@ -98,6 +117,8 @@
                const char *value, uint64_t off, size_t size)
 {
   int *eok = cls;
+  (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; (void) off;            /* Unused. Silent compiler warning. */
 
 #if 0
   fprintf (stderr, "PI sees %s-%.*s\n", key, size, value);
@@ -112,112 +133,216 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int eok;
   struct MHD_Response *response;
   struct MHD_PostProcessor *pp;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) version;      /* Unused. Silent compiler warning. */
 
   if (0 != strcmp ("POST", method))
-    {
-      printf ("METHOD: %s\n", method);
-      return MHD_NO;            /* unexpected method */
-    }
-  pp = *unused;
+  {
+    printf ("METHOD: %s\n", method);
+    return MHD_NO;              /* unexpected method */
+  }
+  pp = *req_cls;
   if (pp == NULL)
-    {
-      eok = 0;
-      pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
-      if (pp == NULL)
-        abort ();
-      *unused = pp;
-    }
-  MHD_post_process (pp, upload_data, *upload_data_size);
+  {
+    eok = 0;
+    pp = MHD_create_post_processor (connection,
+                                    1024,
+                                    &post_iterator,
+                                    &eok);
+    if (NULL == pp)
+      abort ();
+    *req_cls = pp;
+  }
+  if (MHD_YES !=
+      MHD_post_process (pp,
+                        upload_data,
+                        *upload_data_size))
+    abort ();
   if ((eok == 3) && (0 == *upload_data_size))
-    {
-      response = MHD_create_response_from_buffer (strlen (url),
-						  (void *) url,
-						  MHD_RESPMEM_MUST_COPY);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
-      MHD_destroy_post_processor (pp);
-      *unused = NULL;
-      return ret;
-    }
+  {
+    response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                     (const void *) url);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+    MHD_destroy_post_processor (pp);
+    *req_cls = NULL;
+    return ret;
+  }
   *upload_data_size = 0;
   return MHD_YES;
 }
 
-static struct curl_httppost *
-make_form ()
+
+struct mhd_test_postdata
 {
-  struct curl_httppost *post = NULL;
+#if defined(HAS_CURL_MIME)
+  curl_mime *mime;
+#else  /* ! HAS_CURL_MIME */
+  struct curl_httppost *post;
+#endif /* ! HAS_CURL_MIME */
+};
+
+/* Return non-zero if succeed */
+static int
+add_test_form (CURL *handle, struct mhd_test_postdata *postdata)
+{
+#if defined(HAS_CURL_MIME)
+  postdata->mime = curl_mime_init (handle);
+  if (NULL == postdata->mime)
+    return 0;
+  else
+  {
+    curl_mimepart *part;
+    part = curl_mime_addpart (postdata->mime);
+    if (NULL != part)
+    {
+      if ( (CURLE_OK == curl_mime_data (part, "daniel",
+                                        CURL_ZERO_TERMINATED)) &&
+           (CURLE_OK == curl_mime_name (part, "name")) )
+      {
+        part = curl_mime_addpart (postdata->mime);
+        if (NULL != part)
+        {
+          if ( (CURLE_OK == curl_mime_data (part, "curl",
+                                            CURL_ZERO_TERMINATED)) &&
+               (CURLE_OK == curl_mime_name (part, "project")) )
+          {
+            if (CURLE_OK == curl_easy_setopt (handle,
+                                              CURLOPT_MIMEPOST, postdata->mime))
+            {
+              return ! 0;
+            }
+          }
+        }
+      }
+    }
+  }
+  curl_mime_free (postdata->mime);
+  postdata->mime = NULL;
+  return 0;
+#else  /* ! HAS_CURL_MIME */
+  postdata->post = NULL;
   struct curl_httppost *last = NULL;
 
-  curl_formadd (&post, &last, CURLFORM_COPYNAME, "name",
-                CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END);
-  curl_formadd (&post, &last, CURLFORM_COPYNAME, "project",
-                CURLFORM_COPYCONTENTS, "curl", CURLFORM_END);
-  return post;
+  if (0 == curl_formadd (&postdata->post, &last,
+                         CURLFORM_COPYNAME, "name",
+                         CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END))
+  {
+    if (0 == curl_formadd (&postdata->post, &last,
+                           CURLFORM_COPYNAME, "project",
+                           CURLFORM_COPYCONTENTS, "curl", CURLFORM_END))
+    {
+      if (CURLE_OK == curl_easy_setopt (handle,
+                                        CURLOPT_HTTPPOST, postdata->post))
+      {
+        return ! 0;
+      }
+    }
+  }
+  curl_formfree (postdata->post);
+  return 0;
+#endif /* ! HAS_CURL_MIME */
 }
 
 
-static int
-testInternalPost ()
+static void
+free_test_form (struct mhd_test_postdata *postdata)
+{
+#if defined(HAS_CURL_MIME)
+  if (NULL != postdata->mime)
+    curl_mime_free (postdata->mime);
+#else  /* ! HAS_CURL_MIME */
+  if (NULL != postdata->post)
+    curl_formfree (postdata->post);
+#endif /* ! HAS_CURL_MIME */
+}
+
+
+static unsigned int
+testInternalPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
-  struct curl_httppost *pd;
+  struct mhd_test_postdata form;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1390;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  pd = make_form ();
-  curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (! add_test_form (c, &form))
+  {
+    fprintf (stderr, "libcurl form initialisation error.\n");
+    curl_easy_cleanup (c);
+    return 2;
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      curl_formfree (pd);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    free_test_form (&form);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
-  curl_formfree (pd);
+  free_test_form (&form);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 4;
@@ -226,54 +351,81 @@
   return 0;
 }
 
-static int
-testMultithreadedPost ()
+
+static unsigned int
+testMultithreadedPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
-  struct curl_httppost *pd;
+  struct mhd_test_postdata form;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1390;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  pd = make_form ();
-  curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (! add_test_form (c, &form))
+  {
+    fprintf (stderr, "libcurl form initialisation error.\n");
+    curl_easy_cleanup (c);
+    return 2;
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      curl_formfree (pd);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    free_test_form (&form);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
-  curl_formfree (pd);
+  free_test_form (&form);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 64;
@@ -282,55 +434,81 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolPost ()
+
+static unsigned int
+testMultithreadedPoolPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
-  struct curl_httppost *pd;
+  struct mhd_test_postdata form;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1391;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081, NULL, NULL, &ahc_echo, NULL,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT,
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  pd = make_form ();
-  curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (! add_test_form (c, &form))
+  {
+    fprintf (stderr, "libcurl form initialisation error.\n");
+    curl_easy_cleanup (c);
+    return 2;
+  }
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      curl_formfree (pd);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    free_test_form (&form);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
-  curl_formfree (pd);
+  free_test_form (&form);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 64;
@@ -339,8 +517,9 @@
   return 0;
 }
 
-static int
-testExternalPost ()
+
+static unsigned int
+testExternalPost (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -351,118 +530,182 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
-  struct curl_httppost *pd;
+  struct mhd_test_postdata form;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1392;
+    if (oneone)
+      port += 10;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  pd = make_form ();
-  curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  if (! add_test_form (c, &form))
+  {
+    fprintf (stderr, "libcurl form initialisation error.\n");
+    curl_easy_cleanup (c);
+    return 2;
+  }
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      curl_formfree (pd);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    free_test_form (&form);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
-    {
-      curl_multi_cleanup (multi);
-      curl_formfree (pd);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 1024;
-    }
+  {
+    curl_multi_cleanup (multi);
+    free_test_form (&form);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
   start = time (NULL);
   while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          curl_formfree (pd);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          curl_formfree (pd);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      free_test_form (&form);
+      return 2048;
     }
-  curl_formfree (pd);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      free_test_form (&form);
+      MHD_stop_daemon (d);
+      return 4096;
+    }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
+  free_test_form (&form);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -476,23 +719,30 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
+#ifdef MHD_HTTPS_REQUIRE_GCRYPT
 #ifdef HAVE_GCRYPT_H
   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
 #ifdef GCRYCTL_INITIALIZATION_FINISHED
   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
 #endif
 #endif
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPost ();
-  errorCount += testMultithreadedPost ();
-  errorCount += testMultithreadedPoolPost ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPost ();
+    errorCount += testMultithreadedPost ();
+    errorCount += testMultithreadedPoolPost ();
+  }
   errorCount += testExternalPost ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_process_arguments.c b/src/testcurl/test_process_arguments.c
index a3e5841..6fea4c1 100644
--- a/src/testcurl/test_process_arguments.c
+++ b/src/testcurl/test_process_arguments.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2013 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_process_arguments.c
  * @brief  Testcase for HTTP URI arguments
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -31,6 +33,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
@@ -59,29 +62,30 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   const char *hdr;
+  (void) cls;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "k");
   if ((hdr == NULL) || (0 != strcmp (hdr, "v x")))
     abort ();
@@ -94,12 +98,11 @@
   if ((hdr == NULL) || (0 != strcmp (hdr, "\240bar")))
     abort ();
   if (3 != MHD_get_connection_values (connection,
-				      MHD_GET_ARGUMENT_KIND,
-				      NULL, NULL))
+                                      MHD_GET_ARGUMENT_KIND,
+                                      NULL, NULL))
     abort ();
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
@@ -108,8 +111,8 @@
 }
 
 
-static int
-testExternalGet ()
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -120,26 +123,52 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1410;
+    if (oneone)
+      port += 5;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        21080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
   curl_easy_setopt (c, CURLOPT_URL,
-                    "http://127.0.0.1:21080/hello+world?k=v+x&hash=%23foo&space=%A0bar");
+                    "http://127.0.0.1/hello+world?k=v+x&hash=%23foo&space=%A0bar");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
@@ -149,80 +178,115 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello+world"))
     return 8192;
@@ -236,14 +300,16 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   errorCount += testExternalGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_process_headers.c b/src/testcurl/test_process_headers.c
index 4a219fb..9f61d98 100644
--- a/src/testcurl/test_process_headers.c
+++ b/src/testcurl/test_process_headers.c
@@ -1,7 +1,7 @@
-
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -15,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_process_headers.c
  * @brief  Testcase for HTTP header access
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -32,16 +33,17 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 static int oneone;
@@ -65,41 +67,45 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 kv_cb (void *cls, enum MHD_ValueKind kind, const char *key, const char *value)
 {
   if ((0 == strcmp (key, MHD_HTTP_HEADER_HOST)) &&
-      (0 == strcmp (value, "127.0.0.1:21080")) && (kind == MHD_HEADER_KIND))
-    {
-      *((int *) cls) = 1;
-      return MHD_NO;
-    }
+      (0 == strncmp (value, "127.0.0.1", strlen ("127.0.0.1"))) && (kind ==
+                                                                    MHD_HEADER_KIND))
+  {
+    *((int *) cls) = 1;
+    return MHD_NO;
+  }
   return MHD_YES;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   const char *hdr;
+  (void) cls;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   ret = 0;
   MHD_get_connection_values (connection, MHD_HEADER_KIND, &kv_cb, &ret);
   if (ret != 1)
@@ -113,7 +119,7 @@
     abort ();
   hdr = MHD_lookup_connection_value (connection,
                                      MHD_HEADER_KIND, MHD_HTTP_HEADER_HOST);
-  if ((hdr == NULL) || (0 != strcmp (hdr, "127.0.0.1:21080")))
+  if ((hdr == NULL) || (0 != strncmp (hdr, "127.0.0.1", strlen ("127.0.0.1"))))
     abort ();
   MHD_set_connection_value (connection,
                             MHD_HEADER_KIND, "FakeHeader", "NowPresent");
@@ -122,9 +128,10 @@
   if ((hdr == NULL) || (0 != strcmp (hdr, "NowPresent")))
     abort ();
 
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  if (NULL == response)
+    abort ();
   MHD_add_response_header (response, "MyHeader", "MyValue");
   hdr = MHD_get_response_header (response, "MyHeader");
   if (0 != strcmp ("MyValue", hdr))
@@ -145,27 +152,48 @@
 }
 
 
-static int
-testInternalGet ()
+static unsigned int
+testInternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1420;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        21080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:21080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -175,16 +203,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -194,27 +222,50 @@
   return 0;
 }
 
-static int
-testMultithreadedGet ()
+
+static unsigned int
+testMultithreadedGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1421;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        21080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:21080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
@@ -224,16 +275,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -243,28 +294,51 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolGet ()
+
+static unsigned int
+testMultithreadedPoolGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1422;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        21080, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:21080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
@@ -274,16 +348,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -293,8 +367,9 @@
   return 0;
 }
 
-static int
-testExternalGet ()
+
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -305,25 +380,51 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1423;
+    if (oneone)
+      port += 10;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        21080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:21080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
@@ -333,80 +434,115 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system! */
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -416,19 +552,24 @@
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
-  errorCount += testMultithreadedGet ();
-  errorCount += testMultithreadedPoolGet ();
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet ();
+    errorCount += testMultithreadedGet ();
+    errorCount += testMultithreadedPoolGet ();
+  }
   errorCount += testExternalGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_put.c b/src/testcurl/test_put.c
index fe1d8db..2eb6bd1 100644
--- a/src/testcurl/test_put.c
+++ b/src/testcurl/test_put.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_put.c
  * @brief  Testcase for libmicrohttpd PUT operations
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -31,16 +33,17 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
 
 #ifndef WINDOWS
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 static int oneone;
@@ -55,8 +58,8 @@
 static size_t
 putBuffer (void *stream, size_t size, size_t nmemb, void *ptr)
 {
-  unsigned int *pos = ptr;
-  unsigned int wrt;
+  size_t *pos = ptr;
+  size_t wrt;
 
   wrt = size * nmemb;
   if (wrt > 8 - (*pos))
@@ -66,6 +69,7 @@
   return wrt;
 }
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -78,92 +82,115 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   int *done = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
 
   if (0 != strcmp ("PUT", method))
     return MHD_NO;              /* unexpected method */
   if ((*done) == 0)
+  {
+    if (*upload_data_size != 8)
+      return MHD_YES;           /* not yet ready */
+    if (0 == memcmp (upload_data, "Hello123", 8))
     {
-      if (*upload_data_size != 8)
-        return MHD_YES;         /* not yet ready */
-      if (0 == memcmp (upload_data, "Hello123", 8))
-        {
-          *upload_data_size = 0;
-        }
-      else
-        {
-          printf ("Invalid upload data `%8s'!\n", upload_data);
-          return MHD_NO;
-        }
-      *done = 1;
-      return MHD_YES;
+      *upload_data_size = 0;
     }
-  response = MHD_create_response_from_buffer (strlen (url), (void*) url,
-					      MHD_RESPMEM_MUST_COPY);
+    else
+    {
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
+    }
+    *done = 1;
+    return MHD_YES;
+  }
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testInternalPut ()
+static unsigned int
+testInternalPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1450;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
   curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -173,53 +200,76 @@
   return 0;
 }
 
-static int
-testMultithreadedPut ()
+
+static unsigned int
+testMultithreadedPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1451;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        1081,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
   curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -230,54 +280,77 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolPut ()
+
+static unsigned int
+testMultithreadedPoolPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1452;
+    if (oneone)
+      port += 10;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1081,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
   curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -289,8 +362,8 @@
 }
 
 
-static int
-testExternalPut ()
+static unsigned int
+testExternalPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -301,115 +374,176 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+  int maxposixs; /* Max socket number unused on W32 */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1453;
+    if (oneone)
+      port += 10;
+  }
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
   curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+#ifdef MHD_POSIX_SOCKETS
+    if (maxsock > maxposixs)
+      maxposixs = maxsock;
+#endif /* MHD_POSIX_SOCKETS */
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -419,22 +553,26 @@
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPut ();
-  errorCount += testMultithreadedPut ();
-  errorCount += testMultithreadedPoolPut ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPut ();
+    errorCount += testMultithreadedPut ();
+    errorCount += testMultithreadedPoolPut ();
+  }
   errorCount += testExternalPut ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_put_broken_len.c b/src/testcurl/test_put_broken_len.c
new file mode 100644
index 0000000..f714ece
--- /dev/null
+++ b/src/testcurl/test_put_broken_len.c
@@ -0,0 +1,736 @@
+/*
+     This file is part of GNU libmicrohttpd
+     Copyright (C) 2010 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     GNU libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     GNU libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+
+/**
+ * @file testcurl/test_head.c
+ * @brief  Testcase for PUT requests with broken Content-Length header
+ * @author Karlson2k (Evgeny Grin)
+ */
+
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <unistd.h>
+#else
+#include <wincrypt.h>
+#endif
+
+#include "mhd_has_param.h"
+#include "mhd_has_in_name.h"
+
+#ifndef MHD_STATICSTR_LEN_
+/**
+ * Determine length of static string / macro strings at compile time.
+ */
+#define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
+#endif /* ! MHD_STATICSTR_LEN_ */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+  _externalErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+  _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+  _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+  _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \
+                       __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func (errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func (errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \
+                       __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 500000
+
+#define EXPECTED_URI_BASE_PATH  "/"
+
+#define EXISTING_URI  EXPECTED_URI_BASE_PATH
+
+#define EXPECTED_URI_BASE_PATH_MISSING  "/wrong_uri"
+
+#define URL_SCHEME "http:/" "/"
+
+#define URL_HOST "127.0.0.1"
+
+#define URL_SCHEME_HOST URL_SCHEME URL_HOST
+
+#define PAGE \
+  "<html><head><title>libmicrohttpd demo page</title></head>" \
+  "<body>Success!</body></html>"
+
+#define PAGE_404 \
+  "<html><head><title>404 error</title></head>" \
+  "<body>Error 404: The requested URI does not exist</body></html>"
+
+/* Global parameters */
+static int verbose;
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+
+static struct curl_slist *hdr_broken_cnt_len = NULL;
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+
+  hdr_broken_cnt_len =
+    curl_slist_append (hdr_broken_cnt_len,
+                       MHD_HTTP_HEADER_CONTENT_LENGTH ": 123bad");
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_slist_free_all (hdr_broken_cnt_len);
+
+  curl_global_cleanup ();
+}
+
+
+struct CBC
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr,
+            size_t size,
+            size_t nmemb,
+            void *ctx)
+{
+  (void) ptr; /* Unused, mute compiler warning */
+  (void) ctx; /* Unused, mute compiler warning */
+  /* Discard data */
+  return size * nmemb;
+}
+
+
+struct ahc_cls_type
+{
+  const char *rq_method;
+  const char *rq_url;
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int marker;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+  unsigned int http_code;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (oneone)
+  {
+    if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+      mhdErrorExitDesc ("Unexpected HTTP version");
+  }
+  else
+  {
+    if (0 != strcmp (version, MHD_HTTP_VERSION_1_0))
+      mhdErrorExitDesc ("Unexpected HTTP version");
+  }
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (NULL != upload_data)
+    mhdErrorExitDesc ("'upload_data' is not NULL");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+    mhdErrorExitDesc ("'*upload_data_size' value is not zero");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  if (&marker != *req_cls)
+  {
+    *req_cls = &marker;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  if (0 == strcmp (url, EXISTING_URI))
+  {
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE),
+                                              PAGE);
+    http_code = MHD_HTTP_OK;
+  }
+  else
+  {
+    response =
+      MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_404),
+                                              PAGE_404);
+    http_code = MHD_HTTP_NOT_FOUND;
+  }
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  ret = MHD_queue_response (connection,
+                            http_code,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+
+  return ret;
+}
+
+
+static int
+libcurl_debug_cb (CURL *handle,
+                  curl_infotype type,
+                  char *data,
+                  size_t size,
+                  void *userptr)
+{
+  static const char excess_mark[] = "Excess found";
+  static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark);
+  (void) handle;
+  (void) userptr;
+
+#ifdef _DEBUG
+  switch (type)
+  {
+  case CURLINFO_TEXT:
+    fprintf (stderr, "* %.*s", (int) size, data);
+    break;
+  case CURLINFO_HEADER_IN:
+    fprintf (stderr, "< %.*s", (int) size, data);
+    break;
+  case CURLINFO_HEADER_OUT:
+    fprintf (stderr, "> %.*s", (int) size, data);
+    break;
+  case CURLINFO_DATA_IN:
+#if 0
+    fprintf (stderr, "<| %.*s\n", (int) size, data);
+#endif
+    break;
+  case CURLINFO_DATA_OUT:
+  case CURLINFO_SSL_DATA_IN:
+  case CURLINFO_SSL_DATA_OUT:
+  case CURLINFO_END:
+  default:
+    break;
+  }
+#endif /* _DEBUG */
+  if (CURLINFO_TEXT == type)
+  {
+    if ((size >= excess_mark_len) &&
+        (0 == memcmp (data, excess_mark, excess_mark_len)))
+      mhdErrorExitDesc ("Extra data has been detected in MHD reply");
+  }
+  return 0;
+}
+
+
+static CURL *
+setupCURL (void *cbc, uint16_t port)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     ((long) TIMEOUTS_VAL))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) ||
+#ifdef _DEBUG
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) ||
+#endif /* _DEBUG */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION,
+                                     &libcurl_debug_cb)) ||
+#if CURL_AT_LEAST_VERSION (7, 85, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) ||
+#elif CURL_AT_LEAST_VERSION (7, 19, 4)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
+#if CURL_AT_LEAST_VERSION (7, 45, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) ||
+#endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK !=
+      curl_easy_setopt (c, CURLOPT_URL,
+                        URL_SCHEME_HOST EXPECTED_URI_BASE_PATH))
+    libcurlErrorExitDesc ("Cannot set request URI");
+
+  /* Set as a "custom" request, because no actual upload data is provided. */
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST,
+                                    MHD_HTTP_METHOD_PUT))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK !=
+      curl_easy_setopt (c, CURLOPT_HTTPHEADER,
+                        hdr_broken_cnt_len))
+    libcurlErrorExitDesc ("Cannot set '" MHD_HTTP_HEADER_CONTENT_LENGTH "'.\n");
+
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  if (NULL != *multi_reuse)
+    multi = *multi_reuse;
+  else
+  {
+    multi = curl_multi_init ();
+    if (multi == NULL)
+      libcurlErrorExitDesc ("curl_multi_init() failed");
+    *multi_reuse = multi;
+  }
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 200000;
+    if (0 == MHD_get_timeout64s (d))
+      tv.tv_usec = 0;
+    else
+    {
+      long curl_to = -1;
+      curl_multi_timeout (multi, &curl_to);
+      if (0 == curl_to)
+        tv.tv_usec = 0;
+    }
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep ((unsigned long) tv.tv_usec / 1000);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/**
+ * Check request result
+ * @param curl_code the CURL easy return code
+ * @param pcbc the pointer struct CBC
+ * @return non-zero if success, zero if failed
+ */
+static unsigned int
+check_result (CURLcode curl_code, CURL *c, long expected_code)
+{
+  long code;
+
+  if (CURLE_OK != curl_code)
+  {
+    fflush (stdout);
+    if (0 != libcurl_errbuf[0])
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n"
+               "libcurl error description: '%s'.\n",
+               curl_easy_strerror (curl_code),
+               libcurl_errbuf);
+    else
+      fprintf (stderr, "Request failed. "
+               "libcurl error: '%s'.\n",
+               curl_easy_strerror (curl_code));
+    fflush (stderr);
+    return 0;
+  }
+
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code))
+    libcurlErrorExit ();
+
+  if (expected_code != code)
+  {
+    fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n",
+             code, expected_code);
+    return 0;
+  }
+  else if (verbose)
+    printf ("The response has expected HTTP code: %ld\n", expected_code);
+
+  return ! 0;
+}
+
+
+static unsigned int
+performTest (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t port;
+  struct CBC cbc;
+  struct ahc_cls_type ahc_param;
+  char buf[2048];
+  CURL *c;
+  CURLM *multi_reuse;
+  int failed = 0;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 4220 + oneone ? 0 : 1;
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port, NULL, NULL,
+                        &ahcCheck, &ahc_param,
+                        MHD_OPTION_END);
+  if (d == NULL)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+
+    dinfo = MHD_get_daemon_info (d,
+                                 MHD_DAEMON_INFO_BIND_PORT);
+    if ( (NULL == dinfo) ||
+         (0 == dinfo->port) )
+      mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+    port = dinfo->port;
+  }
+
+  /* First request */
+  ahc_param.rq_method = MHD_HTTP_METHOD_PUT;
+  ahc_param.rq_url = EXPECTED_URI_BASE_PATH;
+  cbc.buf = buf;
+  cbc.size = sizeof (buf);
+  cbc.pos = 0;
+  memset (cbc.buf, 0, cbc.size);
+  c = setupCURL (&cbc, port);
+  multi_reuse = NULL;
+  /* First request */
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                    MHD_HTTP_BAD_REQUEST))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got first expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "First request FAILED.\n");
+    fflush (stderr);
+    failed = 1;
+  }
+  /* Second request */
+  cbc.pos = 0; /* Reset buffer position */
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                    MHD_HTTP_BAD_REQUEST))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got second expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "Second request FAILED.\n");
+    fflush (stderr);
+    failed = 1;
+  }
+  /* Third request */
+  cbc.pos = 0; /* Reset buffer position */
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+  multi_reuse = NULL; /* Force new connection */
+  if (check_result (performQueryExternal (d, c, &multi_reuse), c,
+                    MHD_HTTP_BAD_REQUEST))
+  {
+    fflush (stderr);
+    if (verbose)
+      printf ("Got third expected response.\n");
+    fflush (stdout);
+  }
+  else
+  {
+    fprintf (stderr, "Third request FAILED.\n");
+    fflush (stderr);
+    failed = 1;
+  }
+
+  curl_easy_cleanup (c);
+  if (NULL != multi_reuse)
+    curl_multi_cleanup (multi_reuse);
+
+  MHD_stop_daemon (d);
+  return failed ? 1 : 0;
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+
+  /* Test type and test parameters */
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+  oneone = ! has_in_name (argv[0], "10");
+
+  test_global_init ();
+
+  errorCount += performTest ();
+  if (errorCount != 0)
+    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  test_global_cleanup ();
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_put_chunked.c b/src/testcurl/test_put_chunked.c
index b2fa322..77b684f 100644
--- a/src/testcurl/test_put_chunked.c
+++ b/src/testcurl/test_put_chunked.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,8 +15,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -23,6 +24,7 @@
  * @brief Testcase for libmicrohttpd PUT operations with chunked encoding
  *        for the upload data
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -37,11 +39,11 @@
 #include <unistd.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 struct CBC
@@ -54,8 +56,8 @@
 static size_t
 putBuffer (void *stream, size_t size, size_t nmemb, void *ptr)
 {
-  unsigned int *pos = ptr;
-  unsigned int wrt;
+  size_t *pos = ptr;
+  size_t wrt;
 
   wrt = size * nmemb;
   if (wrt > 8 - (*pos))
@@ -67,6 +69,7 @@
   return wrt;
 }
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -79,101 +82,121 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
-  int *done = cls;
+  size_t *done = cls;
   struct MHD_Response *response;
-  int ret;
-  int have;
+  enum MHD_Result ret;
+  size_t have;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
 
   if (0 != strcmp ("PUT", method))
     return MHD_NO;              /* unexpected method */
   if ((*done) < 8)
+  {
+    have = *upload_data_size;
+    if (have + *done > 8)
     {
-      have = *upload_data_size;
-      if (have + *done > 8)
-        {
-          printf ("Invalid upload data `%8s'!\n", upload_data);
-          return MHD_NO;
-        }
-      if (0 == memcmp (upload_data, &"Hello123"[*done], have))
-        {
-          *done += have;
-          *upload_data_size = 0;
-        }
-      else
-        {
-          printf ("Invalid upload data `%8s'!\n", upload_data);
-          return MHD_NO;
-        }
-#if 0
-      fprintf (stderr, "Not ready for response: %u/%u\n", *done, 8);
-#endif
-      return MHD_YES;
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
     }
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+    if (0 == have)
+      return MHD_YES;
+    if (0 == memcmp (upload_data, &"Hello123"[*done], have))
+    {
+      *done += have;
+      *upload_data_size = 0;
+    }
+    else
+    {
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
+    }
+#if 0
+    fprintf (stderr, "Not ready for response: %u/%u\n", *done, 8);
+#endif
+    return MHD_YES;
+  }
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testInternalPut ()
+static unsigned int
+testInternalPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
-  int done_flag = 0;
+  size_t pos = 0;
+  size_t done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1440;
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        11080,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  /* by not giving the file size, we force chunking! */
   /*
-     // by not giving the file size, we force chunking!
      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
    */
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -183,53 +206,72 @@
   return 0;
 }
 
-static int
-testMultithreadedPut ()
+
+static unsigned int
+testMultithreadedPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
-  int done_flag = 0;
+  size_t pos = 0;
+  size_t done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1441;
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                        11081,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  /* by not giving the file size, we force chunking! */
   /*
-     // by not giving the file size, we force chunking!
      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
    */
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -240,54 +282,73 @@
   return 0;
 }
 
-static int
-testMultithreadedPoolPut ()
+
+static unsigned int
+testMultithreadedPoolPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
-  int done_flag = 0;
+  size_t pos = 0;
+  size_t done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1442;
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        11081,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag,
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
+                        MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  /* by not giving the file size, we force chunking! */
   /*
-     // by not giving the file size, we force chunking!
      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
    */
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -299,8 +360,8 @@
 }
 
 
-static int
-testExternalPut ()
+static unsigned int
+testExternalPut (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -311,115 +372,172 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
+  MHD_socket maxsock;
+#ifdef MHD_WINSOCK_SOCKETS
+  int maxposixs; /* Max socket number unused on W32 */
+#else  /* MHD_POSIX_SOCKETS */
+#define maxposixs maxsock
+#endif /* MHD_POSIX_SOCKETS */
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
-  unsigned int pos = 0;
-  int done_flag = 0;
+  size_t pos = 0;
+  size_t done_flag = 0;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1443;
 
   multi = NULL;
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        11082,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 256;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11082/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  /* by not giving the file size, we force chunking! */
   /*
-     // by not giving the file size, we force chunking!
      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
    */
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
 
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 512;
+  }
   mret = curl_multi_add_handle (multi, c);
   if (mret != CURLM_OK)
+  {
+    curl_multi_cleanup (multi);
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 1024;
+  }
+  start = time (NULL);
+  while ((time (NULL) - start < 5) && (multi != NULL))
+  {
+    maxsock = MHD_INVALID_SOCKET;
+    maxposixs = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    curl_multi_perform (multi, &running);
+    mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+    if (mret != CURLM_OK)
     {
+      curl_multi_remove_handle (multi, c);
       curl_multi_cleanup (multi);
       curl_easy_cleanup (c);
       MHD_stop_daemon (d);
-      return 1024;
+      return 2048;
     }
-  start = time (NULL);
-  while ((time (NULL) - start < 5) && (multi != NULL))
-    {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      curl_multi_perform (multi, &running);
-      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 2048;
-        }
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          MHD_stop_daemon (d);
-          return 4096;
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      select (max + 1, &rs, &ws, &es, &tv);
-      curl_multi_perform (multi, &running);
-      if (running == 0)
-        {
-          msg = curl_multi_info_read (multi, &running);
-          if (msg == NULL)
-            break;
-          if (msg->msg == CURLMSG_DONE)
-            {
-              if (msg->data.result != CURLE_OK)
-                printf ("%s failed at %s:%d: `%s'\n",
-                        "curl_multi_perform",
-                        __FILE__,
-                        __LINE__, curl_easy_strerror (msg->data.result));
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              c = NULL;
-              multi = NULL;
-            }
-        }
-      MHD_run (d);
-    }
-  if (multi != NULL)
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
     {
       curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
       curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      MHD_stop_daemon (d);
+      return 4096;
     }
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+    if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) errno, __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+      {
+        fprintf (stderr, "Unexpected select() error: %d. Line: %d\n",
+                 (int) WSAGetLastError (), __LINE__);
+        fflush (stderr);
+        exit (99);
+      }
+      Sleep (1);
+#endif
+    }
+    curl_multi_perform (multi, &running);
+    if (0 == running)
+    {
+      int pending;
+      int curl_fine = 0;
+      while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+      {
+        if (msg->msg == CURLMSG_DONE)
+        {
+          if (msg->data.result == CURLE_OK)
+            curl_fine = 1;
+          else
+          {
+            fprintf (stderr,
+                     "%s failed at %s:%d: `%s'\n",
+                     "curl_multi_perform",
+                     __FILE__,
+                     __LINE__, curl_easy_strerror (msg->data.result));
+            abort ();
+          }
+        }
+      }
+      if (! curl_fine)
+      {
+        fprintf (stderr, "libcurl haven't returned OK code\n");
+        abort ();
+      }
+      curl_multi_remove_handle (multi, c);
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      c = NULL;
+      multi = NULL;
+    }
+    MHD_run (d);
+  }
+  if (multi != NULL)
+  {
+    curl_multi_remove_handle (multi, c);
+    curl_easy_cleanup (c);
+    curl_multi_cleanup (multi);
+  }
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
     return 8192;
@@ -429,20 +547,23 @@
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPut ();
-  errorCount += testMultithreadedPut ();
-  errorCount += testMultithreadedPoolPut ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPut ();
+    errorCount += testMultithreadedPut ();
+    errorCount += testMultithreadedPoolPut ();
+  }
   errorCount += testExternalPut ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_quiesce.c b/src/testcurl/test_quiesce.c
index 17adcb2..bce1671 100644
--- a/src/testcurl/test_quiesce.c
+++ b/src/testcurl/test_quiesce.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2013, 2015 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,18 +15,18 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 /**
  * @file test_quiesce.c
  * @brief  Testcase for libmicrohttpd quiescing
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
 #include "platform.h"
-#include "platform_interface.h"
 #include <curl/curl.h>
 #include <microhttpd.h>
 #include <stdlib.h>
@@ -33,20 +34,193 @@
 #include <time.h>
 #include <sys/types.h>
 #include <pthread.h>
+#include "mhd_sockets.h" /* only macros used */
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+
 
 #ifndef WINDOWS
 #include <unistd.h>
 #include <sys/socket.h>
 #endif
 
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
 #endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
 #endif
 
 
+#ifndef _MHD_INSTRMACRO
+/* Quoted macro parameter */
+#define _MHD_INSTRMACRO(a) #a
+#endif /* ! _MHD_INSTRMACRO */
+#ifndef _MHD_STRMACRO
+/* Quoted expanded macro parameter */
+#define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
+#endif /* ! _MHD_STRMACRO */
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+    _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
+                        __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#define checkCURLE_OK(libcurlcall) \
+  _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  fflush (stdout);
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+static void
+_checkCURLE_OK_func (CURLcode code, const char *curlFunc,
+                     const char *funcName, int lineNum)
+{
+  if (CURLE_OK == code)
+    return;
+
+  fflush (stdout);
+  if ((NULL != curlFunc) && (0 != curlFunc[0]))
+    fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
+             curl_easy_strerror (code));
+  else
+    fprintf (stderr, "libcurl function call resulted in '%s'",
+             curl_easy_strerror (code));
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (9);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 4
+
+#define MHD_URI_BASE_PATH "/hello_world"
+
+/* Global parameters */
+static int verbose;                 /**< Be verbose */
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+static uint16_t global_port;        /**< MHD daemons listen port number */
+
 struct CBC
 {
   char *buf;
@@ -54,7 +228,6 @@
   size_t size;
 };
 
-
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -68,50 +241,65 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  (void) cls;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
-    return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
-  response = MHD_create_response_from_buffer (strlen (url),
-  				      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
+  {
+    fprintf (stderr, "Unexpected HTTP method '%s'. ", method);
+    externalErrorExit ();
+  }
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
+  if (NULL == response)
+    mhdErrorExitDesc ("MHD_create_response failed");
+  /* Make sure that connection will not be reused */
+  if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION,
+                                         "close"))
+    mhdErrorExitDesc ("MHD_add_response_header() failed");
+  if (MHD_NO == MHD_queue_response (connection, MHD_HTTP_OK, response))
+    mhdErrorExitDesc ("MHD_queue_response() failed");
   MHD_destroy_response (response);
-  if (ret == MHD_NO)
-    abort ();
-  return ret;
+  return MHD_YES;
 }
 
 
 static void
 request_completed (void *cls, struct MHD_Connection *connection,
-		   void **con_cls, enum MHD_RequestTerminationCode code)
+                   void **req_cls, enum MHD_RequestTerminationCode code)
 {
-  int *done = (int *)cls;
+  int *done = (int *) cls;
+  (void) connection; (void) req_cls; (void) code;    /* Unused. Silent compiler warning. */
+  if (MHD_REQUEST_TERMINATED_COMPLETED_OK != code)
+  {
+    fprintf (stderr, "Unexpected termination code: %d. ", (int) code);
+    mhdErrorExit ();
+  }
   *done = 1;
+  if (verbose)
+    printf ("Notify callback has been called with OK code.\n");
 }
 
 
 static void *
-ServeOneRequest(void *param)
+ServeOneRequest (void *param)
 {
   struct MHD_Daemon *d;
   fd_set rs;
@@ -120,38 +308,56 @@
   MHD_socket fd, max;
   time_t start;
   struct timeval tv;
-  int done = 0;
+  volatile int done = 0;
 
-  fd = (MHD_socket) (intptr_t) param;
+  if (NULL == param)
+    externalErrorExit ();
 
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, "GET",
+  fd = *((MHD_socket *) param);
+
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        0, NULL, NULL, &ahc_echo, NULL,
                         MHD_OPTION_LISTEN_SOCKET, fd,
                         MHD_OPTION_NOTIFY_COMPLETED, &request_completed, &done,
                         MHD_OPTION_END);
   if (d == NULL)
-    return "MHD_start_daemon() failed";
+    mhdErrorExit ();
+
+  if (verbose)
+    printf ("Started MHD daemon in ServeOneRequest().\n");
 
   start = time (NULL);
-  while ((time (NULL) - start < 5) && done == 0)
+  while ((time (NULL) - start < TIMEOUTS_VAL * 2) && done == 0)
+  {
+    max = 0;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      mhdErrorExit ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 100000;
+    if (-1 == MHD_SYS_select_ (max + 1, &rs, &ws, &es, &tv))
     {
-      max = 0;
-      FD_ZERO (&rs);
-      FD_ZERO (&ws);
-      FD_ZERO (&es);
-      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-        {
-          MHD_stop_daemon (d);
-          MHD_socket_close_(fd);
-          return "MHD_get_fdset() failed";
-        }
-      tv.tv_sec = 0;
-      tv.tv_usec = 1000;
-      MHD_SYS_select_ (max + 1, &rs, &ws, &es, &tv);
-      MHD_run (d);
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (tv.tv_sec * 1000 + tv.tv_usec / 1000);
+#endif
     }
+    MHD_run (d);
+  }
+  if (! done)
+    mhdErrorExit ("ServeOneRequest() failed and finished by timeout");
+  fd = MHD_quiesce_daemon (d);
+  if (MHD_INVALID_SOCKET == fd)
+    mhdErrorExit ("MHD_quiesce_daemon() failed in ServeOneRequest()");
+
   MHD_stop_daemon (d);
-  MHD_socket_close_(fd);
   return NULL;
 }
 
@@ -162,145 +368,166 @@
   CURL *c;
 
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11080/hello_world");
-  curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-  curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-  curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, 150L);
-  curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, 150L);
-  curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-  /* NOTE: use of CONNECTTIMEOUT without also
-     setting NOSIGNAL results in really weird
-     crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
 
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL,
+                                     "http://127.0.0.1" MHD_URI_BASE_PATH)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) global_port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) (TIMEOUTS_VAL / 2))) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) TIMEOUTS_VAL)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
   return c;
 }
 
 
-static int
-testGet (int type, int pool_count, int poll_flag)
+static unsigned int
+testGet (unsigned int type, int pool_count, uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  CURLcode errornum;
   MHD_socket fd;
   pthread_t thrd;
-  const char *thrdRet;
+  char *thrdRet;
+
+  if (verbose)
+    printf ("testGet(%u, %d, %u) test started.\n",
+            type, pool_count, (unsigned int) poll_flag);
 
   cbc.buf = buf;
-  cbc.size = 2048;
+  cbc.size = sizeof(buf);
   cbc.pos = 0;
-  if (pool_count > 0) {
-    d = MHD_start_daemon (type | MHD_USE_DEBUG | MHD_USE_PIPE_FOR_SHUTDOWN | poll_flag,
-                          11080, NULL, NULL, &ahc_echo, "GET",
-                          MHD_OPTION_THREAD_POOL_SIZE, pool_count, MHD_OPTION_END);
+  if (pool_count > 0)
+  {
+    d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC
+                          | (enum MHD_FLAG) poll_flag,
+                          global_port, NULL, NULL, &ahc_echo, NULL,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          (unsigned int) pool_count,
+                          MHD_OPTION_END);
 
-  } else {
-    d = MHD_start_daemon (type | MHD_USE_DEBUG | MHD_USE_PIPE_FOR_SHUTDOWN | poll_flag,
-                          11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  }
+  else
+  {
+    d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC
+                          | (enum MHD_FLAG) poll_flag,
+                          global_port, NULL, NULL, &ahc_echo, NULL,
+                          MHD_OPTION_END);
   }
   if (d == NULL)
-    return 1;
-
-  c = setupCURL(&cbc);
-
-  if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
-
-  if (cbc.pos != strlen ("/hello_world")) {
-    curl_easy_cleanup (c);
-    MHD_stop_daemon (d);
-    return 4;
+    mhdErrorExitDesc ("MHD_start_daemon() failed");
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      mhdErrorExit ();
+    global_port = dinfo->port;
   }
-  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) {
-    curl_easy_cleanup (c);
-    MHD_stop_daemon (d);
-    return 8;
+
+  c = setupCURL (&cbc);
+
+  checkCURLE_OK (curl_easy_perform (c));
+
+  if (cbc.pos != strlen (MHD_URI_BASE_PATH))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen (MHD_URI_BASE_PATH));
+    mhdErrorExitDesc ("Wrong returned data length");
   }
+  if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH)))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
+  if (verbose)
+    printf ("Received valid response data.\n");
 
   fd = MHD_quiesce_daemon (d);
-  if (0 != pthread_create(&thrd, NULL, &ServeOneRequest, (void*)(intptr_t) fd))
-    {
-      fprintf (stderr, "pthread_create failed\n");
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 16;
-    }
+  if (MHD_INVALID_SOCKET == fd)
+    mhdErrorExitDesc ("MHD_quiesce_daemon failed");
 
+  if (0 != pthread_create (&thrd, NULL, &ServeOneRequest,
+                           (void *) &fd))
+    externalErrorExitDesc ("pthread_create() failed");
+
+  /* No need for the thread sync as socket is already listening,
+   * so libcurl may start connecting before MHD is started in another thread */
   cbc.pos = 0;
-  if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  checkCURLE_OK (curl_easy_perform (c));
 
-  if (0 != pthread_join(thrd, (void**)&thrdRet))
-    {
-      fprintf (stderr, "pthread_join failed\n");
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 16;
-    }
+  if (cbc.pos != strlen (MHD_URI_BASE_PATH))
+  {
+    fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen (MHD_URI_BASE_PATH));
+    mhdErrorExitDesc ("Wrong returned data length");
+  }
+  if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH)))
+  {
+    fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
+    mhdErrorExitDesc ("Wrong returned data");
+  }
+
+  if (0 != pthread_join (thrd, (void **) &thrdRet))
+    externalErrorExitDesc ("pthread_join() failed");
   if (NULL != thrdRet)
-    {
-      fprintf (stderr, "ServeOneRequest() error: %s\n", thrdRet);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 16;
-    }
+    externalErrorExitDesc ("ServeOneRequest() returned non-NULL result");
 
-  if (cbc.pos != strlen ("/hello_world"))
-    {
-      fprintf(stderr, "%s\n", cbc.buf);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      MHD_socket_close_(fd);
-      return 4;
-    }
-  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    {
-      fprintf(stderr, "%s\n", cbc.buf);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      MHD_socket_close_(fd);
-      return 8;
-    }
+  if (verbose)
+  {
+    printf ("ServeOneRequest() thread was joined.\n");
+    fflush (stdout);
+  }
 
-  /* at this point, the forked server quit, and the new
-   * server has quiesced, so new requests should fail
+  /* at this point, the forked server quiesced and quit,
+   * so new requests should fail
    */
-  if (CURLE_OK == (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr, "curl_easy_perform should fail\n");
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      MHD_socket_close_(fd);
-      return 2;
-    }
+  cbc.pos = 0;
+  if (CURLE_OK == curl_easy_perform (c))
+  {
+    fprintf (stderr, "curl_easy_perform() succeed while it should fail. ");
+    fprintf (stderr, "Got %u bytes ('%.*s'), "
+             "valid data would be %u bytes (%s). ",
+             (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+             (unsigned) strlen (MHD_URI_BASE_PATH), MHD_URI_BASE_PATH);
+    mhdErrorExitDesc ("Unexpected succeed request");
+  }
+  if (verbose)
+    printf ("curl_easy_perform() failed as expected.\n");
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
-  MHD_socket_close_(fd);
+  MHD_socket_close_chk_ (fd);
+
+  if (verbose)
+  {
+    printf ("testGet(%u, %d, %u) test succeed.\n",
+            type, pool_count, (unsigned int) poll_flag);
+    fflush (stdout);
+  }
 
   return 0;
 }
 
 
-static int
-testExternalGet ()
+static unsigned int
+testExternalGet (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -311,119 +538,181 @@
   fd_set rs;
   fd_set ws;
   fd_set es;
-  MHD_socket max;
   int running;
   struct CURLMsg *msg;
   time_t start;
   struct timeval tv;
   int i;
-  MHD_socket fd;
+  MHD_socket fd = MHD_INVALID_SOCKET;
 
+  if (verbose)
+    printf ("testExternalGet test started.\n");
+
+  fd = MHD_INVALID_SOCKET;
   multi = NULL;
   cbc.buf = buf;
-  cbc.size = 2048;
+  cbc.size = sizeof(buf);
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
+                        global_port,
+                        NULL, NULL,
+                        &ahc_echo, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
-    return 256;
-  c = setupCURL(&cbc);
+    mhdErrorExitDesc ("Failed to start MHD daemon");
+  if (0 == global_port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+      mhdErrorExit ();
+    global_port = dinfo->port;
+  }
 
-  multi = curl_multi_init ();
-  if (multi == NULL)
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 512;
-    }
-  mret = curl_multi_add_handle (multi, c);
-  if (mret != CURLM_OK)
-    {
-      curl_multi_cleanup (multi);
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 1024;
-    }
+  for (i = 0; i < 2; i++)
+  {
+    c = setupCURL (&cbc);
 
-  for (i = 0; i < 2; i++) {
+    multi = curl_multi_init ();
+    if (multi == NULL)
+      libcurlErrorExit ();
+
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
+      libcurlErrorExit ();
+
     start = time (NULL);
-    while ((time (NULL) - start < 5) && (multi != NULL))
-      {
-        max = 0;
-        FD_ZERO (&rs);
-        FD_ZERO (&ws);
-        FD_ZERO (&es);
-        curl_multi_perform (multi, &running);
-        mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-        if (mret != CURLM_OK)
-          {
-            curl_multi_remove_handle (multi, c);
-            curl_multi_cleanup (multi);
-            curl_easy_cleanup (c);
-            MHD_stop_daemon (d);
-            return 2048;
-          }
-        if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-          {
-            curl_multi_remove_handle (multi, c);
-            curl_multi_cleanup (multi);
-            curl_easy_cleanup (c);
-            MHD_stop_daemon (d);
-            return 4096;
-          }
-        tv.tv_sec = 0;
-        tv.tv_usec = 1000;
-        select (max + 1, &rs, &ws, &es, &tv);
-        curl_multi_perform (multi, &running);
-        if (running == 0)
-          {
-            msg = curl_multi_info_read (multi, &running);
-            if (msg == NULL)
-              break;
-            if (msg->msg == CURLMSG_DONE)
-              {
-                if (i == 0 && msg->data.result != CURLE_OK)
-                  printf ("%s failed at %s:%d: `%s'\n",
-                          "curl_multi_perform",
-                          __FILE__,
-                          __LINE__, curl_easy_strerror (msg->data.result));
-                else if (i == 1 && msg->data.result == CURLE_OK)
-                  printf ("%s should have failed at %s:%d\n",
-                          "curl_multi_perform",
-                          __FILE__,
-                          __LINE__);
-                curl_multi_remove_handle (multi, c);
-                curl_multi_cleanup (multi);
-                curl_easy_cleanup (c);
-                c = NULL;
-                multi = NULL;
-              }
-          }
-        MHD_run (d);
-      }
-
-      if (i == 0) {
-        /* quiesce the daemon on the 1st iteration, so the 2nd should fail */
-        fd = MHD_quiesce_daemon(d);
-	if (MHD_INVALID_SOCKET == fd)
-	  abort ();
-	MHD_socket_close_ (fd);
-        c = setupCURL (&cbc);
-        multi = curl_multi_init ();
-        mret = curl_multi_add_handle (multi, c);
-      }
-    }
-  if (multi != NULL)
+    while ( (time (NULL) - start < TIMEOUTS_VAL * 2) &&
+            (NULL != multi) )
     {
-      curl_multi_remove_handle (multi, c);
-      curl_easy_cleanup (c);
-      curl_multi_cleanup (multi);
+      MHD_socket maxsock;
+      int maxposixs;
+      maxsock = MHD_INVALID_SOCKET;
+      maxposixs = -1;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
+      if (mret != CURLM_OK)
+        libcurlErrorExit ();
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
+        mhdErrorExit ();
+#ifndef MHD_WINSOCK_SOCKETS
+      if (maxsock > maxposixs)
+        maxposixs = maxsock;
+#endif /* MHD_POSIX_SOCKETS */
+      tv.tv_sec = 0;
+      tv.tv_usec = 100000;
+      if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
+      {
+#ifdef MHD_POSIX_SOCKETS
+        if (EINTR != errno)
+          externalErrorExitDesc ("Unexpected select() error");
+#else
+        if ((WSAEINVAL != WSAGetLastError ()) ||
+            (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+          externalErrorExitDesc ("Unexpected select() error");
+        Sleep (tv.tv_sec * 1000 + tv.tv_usec / 1000);
+#endif
+      }
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        int pending;
+        int curl_fine = 0;
+        while (NULL != (msg = curl_multi_info_read (multi, &pending)))
+        {
+          if (msg->msg == CURLMSG_DONE)
+          {
+            if (msg->data.result == CURLE_OK)
+            {
+              curl_fine = 1;
+              if (verbose)
+                printf ("libcurl reported success.\n");
+            }
+            else if (i == 0)
+            {
+              fprintf (stderr,
+                       "curl_multi_perform() failed with '%s'. ",
+                       curl_easy_strerror (msg->data.result));
+              mhdErrorExit ();
+            }
+          }
+        }
+        if (i == 0)
+        {
+          if (! curl_fine)
+          {
+            fprintf (stderr, "libcurl haven't returned OK code\n");
+            mhdErrorExit ();
+          }
+          /* MHD is running, result should be correct */
+          if (cbc.pos != strlen (MHD_URI_BASE_PATH))
+          {
+            fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
+                     (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
+                     (unsigned) strlen (MHD_URI_BASE_PATH));
+            mhdErrorExitDesc ("Wrong returned data length");
+          }
+          if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf,
+                            strlen (MHD_URI_BASE_PATH)))
+          {
+            fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos,
+                     cbc.buf);
+            mhdErrorExitDesc ("Wrong returned data");
+          }
+          if (verbose)
+          {
+            printf ("First request was successful.\n");
+            fflush (stdout);
+          }
+        }
+        else if (i == 1)
+        {
+          if  (curl_fine)
+          {
+            fprintf (stderr, "libcurl returned OK code, while it shouldn't\n");
+            mhdErrorExit ();
+          }
+          if (verbose)
+            printf ("Second request failed as expected.\n");
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        c = NULL;
+        multi = NULL;
+        break;
+      }
+      MHD_run (d);
     }
+
+    if (NULL != multi)
+      mhdErrorExitDesc ("Test failed and finished by timeout");
+
+    if (0 == i)
+    {
+      /* quiesce the daemon on the 1st iteration, so the 2nd should fail */
+      fd = MHD_quiesce_daemon (d);
+      if (MHD_INVALID_SOCKET == fd)
+        mhdErrorExitDesc ("MHD_quiesce_daemon() failed");
+    }
+  }
   MHD_stop_daemon (d);
-  if (cbc.pos != strlen ("/hello_world"))
-    return 8192;
-  if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
-    return 16384;
+  if (MHD_INVALID_SOCKET == fd)
+  {
+    fprintf (stderr, "Failed to MHD_quiesce_daemon() at some point. ");
+    externalErrorExit ();
+  }
+  MHD_socket_close_chk_ (fd);
+
+  if (verbose)
+  {
+    printf ("testExternalGet succeed.\n");
+    fflush (stdout);
+  }
+
   return 0;
 }
 
@@ -432,26 +721,47 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  oneone = ! has_in_name (argv[0], "10");
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
 
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testGet (MHD_USE_SELECT_INTERNALLY, 0, 0);
-  errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION, 0, 0);
-  errorCount += testGet (MHD_USE_SELECT_INTERNALLY, CPU_COUNT, 0);
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    global_port = 0;
+  else
+    global_port = 1480 + (oneone ? 1 : 0);
+
   errorCount += testExternalGet ();
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_POLL))
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, 0);
+    errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION
+                           | MHD_USE_INTERNAL_POLLING_THREAD, 0, 0);
+    errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, 0);
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
     {
-      errorCount += testGet(MHD_USE_SELECT_INTERNALLY, 0, MHD_USE_POLL);
-      errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION, 0, MHD_USE_POLL);
-      errorCount += testGet (MHD_USE_SELECT_INTERNALLY, CPU_COUNT, MHD_USE_POLL);
+      errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_POLL);
+      errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION
+                             | MHD_USE_INTERNAL_POLLING_THREAD, 0,
+                             MHD_USE_POLL);
+      errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT,
+                             MHD_USE_POLL);
     }
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_EPOLL))
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
     {
-      errorCount += testGet (MHD_USE_SELECT_INTERNALLY, 0, MHD_USE_EPOLL_LINUX_ONLY);
-      errorCount += testGet (MHD_USE_SELECT_INTERNALLY, CPU_COUNT, MHD_USE_EPOLL_LINUX_ONLY);
+      errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_EPOLL);
+      errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT,
+                             MHD_USE_EPOLL);
     }
-  if (errorCount != 0)
-    fprintf (stderr, "Error (code: %u)\n", errorCount);
+  }
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_quiesce_stream.c b/src/testcurl/test_quiesce_stream.c
new file mode 100644
index 0000000..888bff1
--- /dev/null
+++ b/src/testcurl/test_quiesce_stream.c
@@ -0,0 +1,257 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2016 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_quiesce_stream.c
+ * @brief  Testcase for libmicrohttpd quiescing
+ * @author Markus Doppelbauer
+ * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
+ */
+#include "mhd_options.h"
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <pthread.h>
+#include <microhttpd.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#elif defined(_WIN32)
+#include <windows.h>
+#define sleep(s) (Sleep ((s) * 1000), 0)
+#endif /* _WIN32 */
+
+
+static volatile unsigned int request_counter;
+
+
+static void
+http_PanicCallback (void *cls,
+                    const char *file,
+                    unsigned int line,
+                    const char *reason)
+{
+  (void) cls;    /* Unused. Silent compiler warning. */
+  fprintf (stderr,
+           "PANIC: exit process: %s at %s:%u\n",
+           reason,
+           file,
+           line);
+  exit (EXIT_FAILURE);
+}
+
+
+static void *
+resume_connection (void *arg)
+{
+  struct MHD_Connection *connection = arg;
+
+  /* fprintf (stderr, "Calling resume\n"); */
+  MHD_resume_connection (connection);
+  return NULL;
+}
+
+
+static void
+suspend_connection (struct MHD_Connection *connection)
+{
+  pthread_t thread_id;
+  int status;
+
+  /* fprintf (stderr, "Calling suspend\n"); */
+  MHD_suspend_connection (connection);
+  status = pthread_create (&thread_id,
+                           NULL,
+                           &resume_connection,
+                           connection);
+  if (0 != status)
+  {
+    fprintf (stderr,
+             "Could not create thead\n");
+    exit (EXIT_FAILURE);
+  }
+  pthread_detach (thread_id);
+}
+
+
+struct ContentReaderUserdata
+{
+  size_t bytes_written;
+  struct MHD_Connection *connection;
+};
+
+
+static ssize_t
+http_ContentReaderCallback (void *cls,
+                            uint64_t pos,
+                            char *buf,
+                            size_t max)
+{
+  static const char alphabet[] =
+    "\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+  struct ContentReaderUserdata *userdata = cls;
+  (void) pos; (void) max;  /* Unused. Silent compiler warning. */
+
+  if (userdata->bytes_written >= 1024)
+  {
+    fprintf (stderr,
+             "finish: %u\n",
+             request_counter);
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  }
+  userdata->bytes_written++;
+  buf[0] = alphabet[userdata->bytes_written % (sizeof(alphabet) - 1)];
+  suspend_connection (userdata->connection);
+
+  return 1;
+}
+
+
+static void
+free_crc_data (void *crc_data)
+{
+  struct ContentReaderUserdata *userdata = crc_data;
+
+  free (userdata);
+}
+
+
+static enum MHD_Result
+http_AccessHandlerCallback (void *cls,
+                            struct MHD_Connection *connection,
+                            const char *url,
+                            const char *method,
+                            const char *version,
+                            const char *upload_data,
+                            size_t *upload_data_size,
+                            void **req_cls)
+{
+  enum MHD_Result ret;
+  struct MHD_Response *response;
+  (void) cls; (void) url;                        /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size;                       /* Unused. Silent compiler warning. */
+
+  /* Never respond on first call */
+  if (NULL == *req_cls)
+  {
+    struct ContentReaderUserdata *userdata;
+    fprintf (stderr,
+             "start: %u\n",
+             ++request_counter);
+
+    userdata = malloc (sizeof(struct ContentReaderUserdata));
+
+    if (NULL == userdata)
+      return MHD_NO;
+    userdata->bytes_written = 0;
+    userdata->connection = connection;
+    *req_cls = userdata;
+    return MHD_YES;
+  }
+
+  /* Second call: create response */
+  response
+    = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
+                                         32 * 1024,
+                                         &http_ContentReaderCallback,
+                                         *req_cls,
+                                         &free_crc_data);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+
+  suspend_connection (connection);
+  return ret;
+}
+
+
+int
+main (void)
+{
+  uint16_t port;
+  char command_line[1024];
+  /* Flags */
+  unsigned int daemon_flags
+    = MHD_USE_INTERNAL_POLLING_THREAD
+      | MHD_USE_AUTO
+      | MHD_ALLOW_SUSPEND_RESUME
+      | MHD_USE_ITC;
+  struct MHD_Daemon *daemon;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1470;
+
+  /* Panic callback */
+  MHD_set_panic_func (&http_PanicCallback,
+                      NULL);
+
+
+  /* Create daemon */
+  daemon = MHD_start_daemon (daemon_flags,
+                             port,
+                             NULL,
+                             NULL,
+                             &http_AccessHandlerCallback,
+                             NULL,
+                             MHD_OPTION_END);
+  if (NULL == daemon)
+    return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (daemon); return 32;
+    }
+    port = dinfo->port;
+  }
+  snprintf (command_line,
+            sizeof (command_line),
+            "curl -s http://127.0.0.1:%u",
+            (unsigned int) port);
+
+  if (0 != system (command_line))
+  {
+    MHD_stop_daemon (daemon);
+    return 1;
+  }
+  /* wait for a request */
+  while (0 == request_counter)
+    (void) sleep (1);
+
+  fprintf (stderr,
+           "quiesce\n");
+  MHD_quiesce_daemon (daemon);
+
+  /* wait a second */
+  (void) sleep (1);
+
+  fprintf (stderr,
+           "stopping daemon\n");
+  MHD_stop_daemon (daemon);
+
+  return 0;
+}
diff --git a/src/testcurl/test_start_stop.c b/src/testcurl/test_start_stop.c
deleted file mode 100644
index a708341..0000000
--- a/src/testcurl/test_start_stop.c
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
-     This file is part of libmicrohttpd
-     Copyright (C) 2011 Christian Grothoff
-
-     libmicrohttpd 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 2, or (at your
-     option) any later version.
-
-     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
-*/
-
-/**
- * @file test_start_stop.c
- * @brief  test for #1901 (start+stop)
- * @author Christian Grothoff
- */
-#include "MHD_config.h"
-#include "platform.h"
-#include <curl/curl.h>
-#include <microhttpd.h>
-
-#if defined(CPU_COUNT) && (CPU_COUNT+0) < 2
-#undef CPU_COUNT
-#endif
-#if !defined(CPU_COUNT)
-#define CPU_COUNT 2
-#endif
-
-
-static int
-ahc_echo (void *cls,
-          struct MHD_Connection *connection,
-          const char *url,
-          const char *method,
-          const char *version,
-          const char *upload_data, size_t *upload_data_size,
-          void **unused)
-{
-  return MHD_NO;
-}
-
-
-static int
-testInternalGet (int poll_flag)
-{
-  struct MHD_Daemon *d;
-
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | poll_flag,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
-  if (d == NULL)
-    return 1;
-  MHD_stop_daemon (d);
-  return 0;
-}
-
-static int
-testMultithreadedGet (int poll_flag)
-{
-  struct MHD_Daemon *d;
-
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG  | poll_flag,
-                        1081, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
-  if (d == NULL)
-    return 2;
-  MHD_stop_daemon (d);
-  return 0;
-}
-
-static int
-testMultithreadedPoolGet (int poll_flag)
-{
-  struct MHD_Daemon *d;
-
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG | poll_flag,
-                        1081, NULL, NULL, &ahc_echo, "GET",
-                        MHD_OPTION_THREAD_POOL_SIZE, CPU_COUNT, MHD_OPTION_END);
-  if (d == NULL)
-    return 4;
-  MHD_stop_daemon (d);
-  return 0;
-}
-
-static int
-testExternalGet ()
-{
-  struct MHD_Daemon *d;
-
-  d = MHD_start_daemon (MHD_USE_DEBUG,
-                        1082, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
-  if (d == NULL)
-    return 8;
-  MHD_stop_daemon (d);
-  return 0;
-}
-
-
-int
-main (int argc, char *const *argv)
-{
-  unsigned int errorCount = 0;
-
-  errorCount += testInternalGet (0);
-  errorCount += testMultithreadedGet (0);
-  errorCount += testMultithreadedPoolGet (0);
-  errorCount += testExternalGet ();
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_POLL))
-    {
-      errorCount += testInternalGet(MHD_USE_POLL);
-      errorCount += testMultithreadedGet(MHD_USE_POLL);
-      errorCount += testMultithreadedPoolGet(MHD_USE_POLL);
-    }
-  if (MHD_YES == MHD_is_feature_supported(MHD_FEATURE_EPOLL))
-    {
-      errorCount += testInternalGet(MHD_USE_EPOLL_LINUX_ONLY);
-      errorCount += testMultithreadedPoolGet(MHD_USE_EPOLL_LINUX_ONLY);
-    }
-  if (errorCount != 0)
-    fprintf (stderr, "Error (code: %u)\n", errorCount);
-  return errorCount != 0;       /* 0 == pass */
-}
diff --git a/src/testcurl/test_termination.c b/src/testcurl/test_termination.c
index 25f9e61..396576c 100644
--- a/src/testcurl/test_termination.c
+++ b/src/testcurl/test_termination.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2009 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,16 +15,16 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_termination.c
  * @brief  Testcase for libmicrohttpd tolerating client not closing immediately
  * @author hollosig
+ * @author Karlson2k (Evgeny Grin)
  */
-#define PORT	12345
 
 #include "platform.h"
 #include <stdio.h>
@@ -48,75 +49,106 @@
 #include <windows.h>
 #endif
 
-static int
+static enum MHD_Result
 connection_handler (void *cls,
                     struct MHD_Connection *connection,
                     const char *url,
                     const char *method,
                     const char *version,
-                    const char *upload_data, size_t * upload_data_size,
-                    void **ptr)
+                    const char *upload_data, size_t *upload_data_size,
+                    void **req_cls)
 {
   static int i;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  (void) cls; (void) url;                        /* Unused. Silent compiler warning. */
+  (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */
+  (void) upload_data_size;                       /* Unused. Silent compiler warning. */
 
-  if (*ptr == NULL)
-    {
-      *ptr = &i;
-      return MHD_YES;
-    }
+  if (*req_cls == NULL)
+  {
+    *req_cls = &i;
+    return MHD_YES;
+  }
 
   if (*upload_data_size != 0)
-    {
-      (*upload_data_size) = 0;
-      return MHD_YES;
-    }
+  {
+    (*upload_data_size) = 0;
+    return MHD_YES;
+  }
 
-  struct MHD_Response *response =
-    MHD_create_response_from_buffer (strlen ("Response"), "Response",
-				     MHD_RESPMEM_PERSISTENT);
-  int ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  response =
+    MHD_create_response_from_buffer_static (strlen ("Response"), "Response");
+  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
 
   return ret;
 }
 
+
 static size_t
 write_data (void *ptr, size_t size, size_t nmemb, void *stream)
 {
+  (void) ptr; (void) stream;       /* Unused. Silent compiler warning. */
   return size * nmemb;
 }
 
+
 int
-main ()
+main (void)
 {
   struct MHD_Daemon *daemon;
+  uint16_t port;
+  char url[255];
+  CURL *curl;
+  CURLcode success;
 
-  daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
-                             PORT,
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+    port = 1490;
+
+
+  daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                             | MHD_USE_INTERNAL_POLLING_THREAD
+                             | MHD_USE_ERROR_LOG,
+                             port,
                              NULL,
                              NULL, connection_handler, NULL, MHD_OPTION_END);
 
   if (daemon == NULL)
+  {
+    fprintf (stderr, "Daemon cannot be started!");
+    exit (1);
+  }
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
     {
-      fprintf (stderr, "Daemon cannot be started!");
-      exit (1);
+      MHD_stop_daemon (daemon); return 32;
     }
+    port = dinfo->port;
+  }
 
-  CURL *curl = curl_easy_init ();
-  //curl_easy_setopt(curl, CURLOPT_POST, 1L);
-  char url[255];
-  sprintf (url, "http://127.0.0.1:%d", PORT);
+  curl = curl_easy_init ();
+  /* curl_easy_setopt(curl, CURLOPT_POST, 1L); */
+  snprintf (url,
+            sizeof (url),
+            "http://127.0.0.1:%u",
+            (unsigned int) port);
   curl_easy_setopt (curl, CURLOPT_URL, url);
   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_data);
 
-  CURLcode success = curl_easy_perform (curl);
+  success = curl_easy_perform (curl);
   if (success != 0)
-    {
-      fprintf (stderr, "CURL Error");
-      exit (1);
-    }
+  {
+    fprintf (stderr, "CURL Error");
+    exit (1);
+  }
   /* CPU used to go crazy here */
-  sleep (1);
+  (void) sleep (1);
 
   curl_easy_cleanup (curl);
   MHD_stop_daemon (daemon);
diff --git a/src/testcurl/test_timeout.c b/src/testcurl/test_timeout.c
index 006c1a8..53914e0 100644
--- a/src/testcurl/test_timeout.c
+++ b/src/testcurl/test_timeout.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007 Christian Grothoff
+     Copyright (C) 2016-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file test_timeout.c
  * @brief  Testcase for libmicrohttpd PUT operations
  * @author Matthias Wachs
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -30,17 +32,58 @@
 #include <microhttpd.h>
 #include <stdlib.h>
 #include <string.h>
-#include <time.h>
-
-#ifndef WINDOWS
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif /* HAVE_TIME_H */
+#include "mhd_has_in_name.h"
+
+
+/**
+ * Pause execution for specified number of milliseconds.
+ * @param ms the number of milliseconds to sleep
+ */
+static void
+_MHD_sleep (uint32_t ms)
+{
+#if defined(_WIN32)
+  Sleep (ms);
+#elif defined(HAVE_NANOSLEEP)
+  struct timespec slp = {ms / 1000, (ms % 1000) * 1000000};
+  struct timespec rmn;
+  int num_retries = 0;
+  while (0 != nanosleep (&slp, &rmn))
+  {
+    if (num_retries++ > 8)
+      break;
+    slp = rmn;
+  }
+#elif defined(HAVE_USLEEP)
+  uint64_t us = ms * 1000;
+  do
+  {
+    uint64_t this_sleep;
+    if (999999 < us)
+      this_sleep = 999999;
+    else
+      this_sleep = us;
+    /* Ignore return value as it could be void */
+    usleep (this_sleep);
+    us -= this_sleep;
+  } while (us > 0);
+#else
+  fprintf (stderr, "No sleep function available on this system.\n");
 #endif
+}
+
 
 static int oneone;
 
-static int withTimeout = 1;
+static int withTimeout = 0;
 
-static int withoutTimeout = 1;
+static int withoutTimeout = 0;
 
 struct CBC
 {
@@ -50,48 +93,68 @@
 };
 
 
-static void 
-termination_cb (void *cls, 
-		struct MHD_Connection *connection, 
-		void **con_cls, 
-		enum MHD_RequestTerminationCode toe)
+static void
+termination_cb (void *cls,
+                struct MHD_Connection *connection,
+                void **req_cls,
+                enum MHD_RequestTerminationCode toe)
 {
   int *test = cls;
+  (void) connection; (void) req_cls;       /* Unused. Silent compiler warning. */
 
   switch (toe)
+  {
+  case MHD_REQUEST_TERMINATED_COMPLETED_OK:
+    if (test == &withoutTimeout)
     {
-    case MHD_REQUEST_TERMINATED_COMPLETED_OK :
-      if (test == &withoutTimeout)
-	{
-	  withoutTimeout = 0;
-	}
-      break;
-    case MHD_REQUEST_TERMINATED_WITH_ERROR :
-    case MHD_REQUEST_TERMINATED_READ_ERROR :
-      break;
-    case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED :
-      if (test == &withTimeout)
-	{
-	  withTimeout = 0;
-	}
-      break;
-    case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN:
-      break;
-    case MHD_REQUEST_TERMINATED_CLIENT_ABORT:
-      break;
+      withoutTimeout = 1;
     }
+    else
+    {
+      fprintf (stderr, "Connection completed without errors while "
+               "timeout is expected.\n");
+    }
+    break;
+  case MHD_REQUEST_TERMINATED_WITH_ERROR:
+    fprintf (stderr, "Connection terminated with error.\n");
+    exit (4);
+    break;
+  case MHD_REQUEST_TERMINATED_READ_ERROR:
+    fprintf (stderr, "Connection terminated with read error.\n");
+    exit (4);
+    break;
+  case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED:
+    if (test == &withTimeout)
+    {
+      withTimeout = 1;
+    }
+    else
+    {
+      fprintf (stderr, "Connection terminated with timeout while expected "
+               "to be successfully completed.\n");
+    }
+    break;
+  case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN:
+    fprintf (stderr, "Connection terminated by daemon shutdown.\n");
+    exit (4);
+    break;
+  case MHD_REQUEST_TERMINATED_CLIENT_ABORT:
+    fprintf (stderr, "Connection terminated by client.\n");
+    exit (4);
+    break;
+  }
 }
 
 
 static size_t
 putBuffer (void *stream, size_t size, size_t nmemb, void *ptr)
 {
-  unsigned int *pos = ptr;
-  unsigned int wrt;
+  size_t *pos = ptr;
+  size_t wrt;
 
   wrt = size * nmemb;
   if (wrt > 8 - (*pos))
-	wrt = 8 - (*pos);
+    wrt = 8 - (*pos);
   memcpy (stream, &("Hello123"[*pos]), wrt);
   (*pos) += wrt;
   return wrt;
@@ -101,6 +164,8 @@
 static size_t
 putBuffer_fail (void *stream, size_t size, size_t nmemb, void *ptr)
 {
+  (void) stream; (void) size; (void) nmemb; (void) ptr;        /* Unused. Silent compiler warning. */
+  _MHD_sleep (100); /* Avoid busy-waiting */
   return 0;
 }
 
@@ -118,95 +183,125 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   int *done = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp ("PUT", method))
+  if (0 != strcmp (MHD_HTTP_METHOD_PUT, method))
     return MHD_NO;              /* unexpected method */
   if ((*done) == 0)
+  {
+    if (*upload_data_size != 8)
+      return MHD_YES;           /* not yet ready */
+    if (0 == memcmp (upload_data, "Hello123", 8))
     {
-      if (*upload_data_size != 8)
-        return MHD_YES;         /* not yet ready */
-      if (0 == memcmp (upload_data, "Hello123", 8))
-        {
-          *upload_data_size = 0;
-        }
-      else
-        {
-          printf ("Invalid upload data `%8s'!\n", upload_data);
-          return MHD_NO;
-        }
-      *done = 1;
-      return MHD_YES;
+      *upload_data_size = 0;
     }
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url, 
-					      MHD_RESPMEM_MUST_COPY);
+    else
+    {
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
+    }
+    *done = 1;
+    return MHD_YES;
+  }
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
-testWithoutTimeout ()
+static unsigned int
+testWithoutTimeout (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
-  unsigned int pos = 0;
+  size_t pos = 0;
   int done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1500;
+    if (oneone)
+      port += 5;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag,
                         MHD_OPTION_CONNECTION_TIMEOUT, 2,
-                        MHD_OPTION_NOTIFY_COMPLETED, &termination_cb, &withTimeout,
+                        MHD_OPTION_NOTIFY_COMPLETED, &termination_cb,
+                        &withoutTimeout,
                         MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
   curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  withoutTimeout = 0;
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr, "curl_easy_perform failed: '%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
+  if (0 == withoutTimeout)
+  {
+    fprintf (stderr, "Request wasn't processed successfully.\n");
+    return 2;
+  }
   if (cbc.pos != strlen ("/hello_world"))
     return 4;
   if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world")))
@@ -214,8 +309,9 @@
   return 0;
 }
 
-static int
-testWithTimeout ()
+
+static unsigned int
+testWithTimeout (void)
 {
   struct MHD_Daemon *d;
   CURL *c;
@@ -223,48 +319,81 @@
   struct CBC cbc;
   int done_flag = 0;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1501;
+    if (oneone)
+      port += 5;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
-                        1080,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
+                        port,
                         NULL, NULL, &ahc_echo, &done_flag,
                         MHD_OPTION_CONNECTION_TIMEOUT, 2,
-                        MHD_OPTION_NOTIFY_COMPLETED, &termination_cb, &withoutTimeout,
+                        MHD_OPTION_NOTIFY_COMPLETED, &termination_cb,
+                        &withTimeout,
                         MHD_OPTION_END);
   if (d == NULL)
     return 16;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1080/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer_fail);
   curl_easy_setopt (c, CURLOPT_READDATA, &testWithTimeout);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
   curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   if (oneone)
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   else
     curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+  withTimeout = 0;
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
+  {
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    if (errornum == CURLE_GOT_NOTHING)
     {
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      if (errornum == CURLE_GOT_NOTHING)
-    	  /* mhd had the timeout */
-    	  return 0;
+      if (0 != withTimeout)
+      {
+        /* mhd had the timeout */
+        return 0;
+      }
       else
-    	  /* curl had the timeout first */
-    	  return 32;
+      {
+        fprintf (stderr, "Timeout wasn't detected.\n");
+        return 8;
+      }
     }
+    else
+      /* curl had the timeout first */
+      return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   return 64;
@@ -275,20 +404,19 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 16;
   errorCount += testWithoutTimeout ();
   errorCount += testWithTimeout ();
   if (errorCount != 0)
-    fprintf (stderr, 
-	     "Error during test execution (code: %u)\n",
-	     errorCount);
+    fprintf (stderr,
+             "Error during test execution (code: %u)\n",
+             errorCount);
   curl_global_cleanup ();
-  if ((withTimeout == 0) && (withoutTimeout == 0))
-    return 0;
-  else
-    return errorCount;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testcurl/test_toolarge.c b/src/testcurl/test_toolarge.c
new file mode 100644
index 0000000..60a061e
--- /dev/null
+++ b/src/testcurl/test_toolarge.c
@@ -0,0 +1,1632 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+     Copyright (C) 2007, 2009, 2011 Christian Grothoff
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_toolarge.c
+ * @brief  Testcase for handling of data larger then buffers.
+ * @details Testcases for handling of various situations when data cannot fit
+ *          the buffers. Address sanitizers and debug asserts should increase
+ *          number of problems detected by this test (detect actual overrun).
+ *          Tests start with valid sizes to ensure that normal data is processed
+ *          correctly and then sizes are monotonically increased to ensure that
+ *          overflow is handled correctly at all stages in all codepaths.
+ *          Tests with valid sizes are repeated several times to ensure that
+ *          tests are failed because of overflow, but because of second run.
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+#include "mhd_options.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+#include "mhd_sockets.h" /* only macros used */
+
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif /* HAVE_STRINGS_H */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+#if MHD_CPU_COUNT > 32
+#undef MHD_CPU_COUNT
+/* Limit to reasonable value */
+#define MHD_CPU_COUNT 32
+#endif /* MHD_CPU_COUNT > 32 */
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+#define EXPECTED_URI_BASE_PATH  "/a"
+
+#define URL_SCHEME_HOST "http:/" "/127.0.0.1"
+
+#define N1_HEADER_NAME "n"
+#define N1_HEADER_VALUE "1"
+#define N1_HEADER N1_HEADER_NAME ": " N1_HEADER_VALUE
+#define N1_HEADER_CRLF N1_HEADER "\r\n"
+
+#define BUFFER_SIZE 1024
+
+/* The size of the test element that must pass the test */
+#ifndef MHD_ASAN_POISON_ACTIVE
+#define TEST_OK_SIZE (BUFFER_SIZE - 384)
+#else  /* MHD_ASAN_POISON_ACTIVE */
+#define TEST_OK_SIZE (BUFFER_SIZE - 384 - 80)
+#endif /* MHD_ASAN_POISON_ACTIVE */
+
+/* The size of the test element where tests are started */
+#define TEST_START_SIZE (TEST_OK_SIZE - 16)
+
+/* The size of the test element that must definitely fail */
+#define TEST_FAIL_SIZE (BUFFER_SIZE + 32)
+
+/* Special value for request many headers test.
+ * MHD uses the same buffer to store headers strings and pointers to the strings
+ * so allocation is multiplied for small request header. */
+/* The size of the test element that must pass the test */
+#define TEST_RQ_N1_OK_SIZE 50
+
+/* The size of the test element where tests are started */
+#define TEST_RQ_N1_START_SIZE (TEST_RQ_N1_OK_SIZE - 32)
+
+/* Global parameters */
+static int verbose;                 /**< Be verbose */
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+static uint16_t global_port;        /**< MHD daemons listen port number */
+static int large_req_method;        /**< Large request method */
+static int large_req_url;           /**< Large request URL */
+static int large_req_header_name; /**< Large request single header name */
+static int large_req_header_value; /**< Large request single header value */
+static int large_req_headers; /**< Large request headers */
+static int large_rsp_header_name; /**< Large response single header name */
+static int large_rsp_header_value; /**< Large response single header value */
+static int large_rsp_headers; /**< Large response headers */
+static int response_timeout_val = TIMEOUTS_VAL;
+
+/* Current test parameters */
+/* * Moved to local variables * */
+
+/* Static helper variables */
+/* * None for this test * */
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_global_cleanup ();
+}
+
+
+struct headers_check_result
+{
+  unsigned int num_n1_headers;
+  size_t large_header_name_size;
+  size_t large_header_value_size;
+  int large_header_valid;
+};
+
+static size_t
+lcurl_hdr_callback (char *buffer, size_t size, size_t nitems,
+                    void *userdata)
+{
+  const size_t data_size = size * nitems;
+  struct headers_check_result *check_res =
+    (struct headers_check_result *) userdata;
+
+  if ((6 == data_size) && (0 == memcmp (N1_HEADER_CRLF, buffer, 6)))
+    check_res->num_n1_headers++;
+  else if ((5 <= data_size) && ('0' == buffer[0]))
+  {
+    const char *const col_ptr = memchr (buffer, ':', data_size);
+    if (0 != check_res->large_header_value_size)
+      mhdErrorExitDesc ("Expected only one large header, " \
+                        "but found two large headers in the reply");
+    if (NULL == col_ptr)
+      check_res->large_header_valid = 0;
+    else if ((size_t) (col_ptr - buffer) >= data_size - 2)
+      check_res->large_header_valid = 0;
+    else if (*(col_ptr + 1) != ' ')
+      check_res->large_header_valid = 0;
+    else
+    {
+      const char *const name = buffer;
+      const size_t name_len = (size_t) (col_ptr - buffer);
+      const size_t val_pos = name_len + 2;
+      const size_t val_len = data_size - val_pos - 2; /* 2 = strlen("\r\n") */
+      const char *const value = buffer + val_pos;
+      size_t i;
+      check_res->large_header_name_size = name_len;
+      check_res->large_header_value_size = val_len;
+      check_res->large_header_valid = 1; /* To be reset if any problem found */
+      for (i = 1; i < name_len; i++)
+        if ('a' + (char) (i % ('z' - 'a' + 1)) != name[i])
+        {
+          fprintf (stderr, "Wrong sequence in reply header name " \
+                   "at position %u. Expected '%c', got '%c'\n",
+                   (unsigned int) i,
+                   'a' + (char) (i % ('z' - 'a' + 1)),
+                   name[i]);
+          check_res->large_header_valid = 0;
+          break;
+        }
+      for (i = 0; i < val_len; i++)
+        if ('Z' - (char) (i % ('Z' - 'A' + 1)) != value[i])
+        {
+          fprintf (stderr, "Wrong sequence in reply header value " \
+                   "at position %u. Expected '%c', got '%c'\n",
+                   (unsigned int) i,
+                   'Z' - (char) (i % ('Z' - 'A' + 1)),
+                   value[i]);
+          check_res->large_header_valid = 0;
+          break;
+        }
+    }
+  }
+
+  return data_size;
+}
+
+
+struct lcurl_data_cb_param
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct lcurl_data_cb_param *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    externalErrorExit ();  /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+struct check_uri_cls
+{
+  const char *volatile uri;
+};
+
+static void *
+check_uri_cb (void *cls,
+              const char *uri,
+              struct MHD_Connection *con)
+{
+  struct check_uri_cls *param = (struct check_uri_cls *) cls;
+  (void) con;
+
+  if (0 != strcmp (param->uri,
+                   uri))
+  {
+    fprintf (stderr,
+             "Wrong URI: `%s', line: %d\n",
+             uri, __LINE__);
+    exit (22);
+  }
+  return NULL;
+}
+
+
+struct mhd_header_checker_param
+{
+  unsigned int num_n1_headers;
+  size_t large_header_name_size;
+  size_t large_header_value_size;
+  int large_header_valid;
+};
+
+static enum MHD_Result
+headerCheckerInterator (void *cls,
+                        enum MHD_ValueKind kind,
+                        const char *key,
+                        size_t key_size,
+                        const char *value,
+                        size_t value_size)
+{
+  struct mhd_header_checker_param *const param =
+    (struct mhd_header_checker_param *) cls;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (MHD_HEADER_KIND != kind)
+    return MHD_YES; /* Continue iteration */
+
+  if (0 == key_size)
+    mhdErrorExitDesc ("Zero key length");
+
+  if ((1 == key_size) && (1 == value_size) &&
+      ('n' == key[0]) && ('1' == value[0]))
+    param->num_n1_headers++;
+  else if ('0' == key[0])
+  { /* Found 'large' header */
+    size_t i;
+    param->large_header_name_size = key_size;
+    param->large_header_value_size = value_size;
+    param->large_header_valid = 1;
+    for (i = 1; i < key_size; i++)
+      if ('a' + (char) (i % ('z' - 'a' + 1)) != key[i])
+      {
+        fprintf (stderr, "Wrong sequence in request header name " \
+                 "at position %u. Expected '%c', got '%c'\n",
+                 (unsigned int) i,
+                 'a' + (char) (i % ('z' - 'a' + 1)),
+                 key[i]);
+        param->large_header_valid = 0;
+        break;
+      }
+    for (i = 0; i < value_size; i++)
+      if ('Z' - (char) (i % ('Z' - 'A' + 1)) != value[i])
+      {
+        fprintf (stderr, "Wrong sequence in request header value " \
+                 "at position %u. Expected '%c', got '%c'\n",
+                 (unsigned int) i,
+                 'Z' - (char) (i % ('Z' - 'A' + 1)),
+                 value[i]);
+        param->large_header_valid = 0;
+        break;
+      }
+  }
+  return MHD_YES;
+}
+
+
+struct ahc_cls_type
+{
+  const char *volatile rp_data;
+  volatile size_t rp_data_size;
+  volatile size_t rp_num_n1_hdrs;
+  volatile size_t rp_large_hdr_name_size;
+  volatile size_t rp_large_hdr_value_size;
+  struct mhd_header_checker_param header_check_param;
+  const char *volatile rq_method;
+  const char *volatile rq_url;
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+  size_t i;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+    mhdErrorExitDesc ("Unexpected HTTP version");
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (NULL != upload_data)
+    mhdErrorExitDesc ("'upload_data' is not NULL");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+    mhdErrorExitDesc ("'*upload_data_size' value is not zero");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND,
+                                       &headerCheckerInterator,
+                                       &param->header_check_param))
+    mhdErrorExitDesc ("Wrong number of headers in the request");
+
+  response =
+    MHD_create_response_from_buffer_copy (param->rp_data_size,
+                                          (const void *) param->rp_data);
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  for (i = 0; i < param->rp_num_n1_hdrs; i++)
+    if (MHD_YES != MHD_add_response_header (response,
+                                            N1_HEADER_NAME,
+                                            N1_HEADER_VALUE))
+      mhdErrorExitDesc ("Cannot add header");
+
+  if (0 != param->rp_large_hdr_name_size)
+  {
+    const size_t large_hdr_name_size = param->rp_large_hdr_name_size;
+    char *large_hrd_name;
+    const size_t large_hdr_value_size = param->rp_large_hdr_value_size;
+    char *large_hrd_value;
+
+    large_hrd_name = malloc (large_hdr_name_size + 1);
+    if (NULL == large_hrd_name)
+      externalErrorExit ();
+    if (0 != large_hdr_value_size)
+      large_hrd_value = malloc (large_hdr_value_size + 1);
+    else
+      large_hrd_value = NULL;
+
+    if ((0 != large_hdr_value_size) && (NULL == large_hrd_value))
+      externalErrorExit ();
+    large_hrd_name[0] = '0'; /* Name starts with zero for unique identification */
+    for (i = 1; i < large_hdr_name_size; i++)
+      large_hrd_name[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1));
+    large_hrd_name[large_hdr_name_size] = 0;
+    for (i = 0; i < large_hdr_value_size; i++)
+      large_hrd_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1));
+    if (NULL != large_hrd_value)
+      large_hrd_value[large_hdr_value_size] = 0;
+    if (MHD_YES != MHD_add_response_header (response,
+                                            large_hrd_name,
+                                            large_hrd_value))
+      mhdErrorExitDesc ("Cannot add large header");
+
+    if (NULL != large_hrd_value)
+      free (large_hrd_value);
+    free (large_hrd_name);
+  }
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+
+  return ret;
+}
+
+
+static CURL *
+curlEasyInitForTest (const char *queryPath, const char *method,
+                     uint16_t port,
+                     struct lcurl_data_cb_param *dcbp,
+                     struct headers_check_result *hdr_chk_result,
+                     struct curl_slist *headers)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, dcbp)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION,
+                                     lcurl_hdr_callback)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA,
+                                     hdr_chk_result)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, method))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, headers))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  multi = NULL;
+  multi = curl_multi_init ();
+  if (multi == NULL)
+    libcurlErrorExitDesc ("curl_multi_init() failed");
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (1);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+struct curlQueryParams
+{
+  /* Destination path for CURL query */
+  const char *queryPath;
+
+  /* Custom query method, NULL for default */
+  const char *method;
+
+  /* Destination port for CURL query */
+  uint16_t queryPort;
+
+  /* List of additional request headers */
+  struct curl_slist *headers;
+
+  /* CURL query result error flag */
+  volatile unsigned int queryError;
+
+  /* Response HTTP code, zero if no response */
+  volatile int responseCode;
+};
+
+
+/* Returns zero for successful response and non-zero for failed response */
+static unsigned int
+doCurlQueryInThread (struct MHD_Daemon *d,
+                     struct curlQueryParams *p,
+                     struct headers_check_result *hdr_res,
+                     const char *expected_data,
+                     size_t expected_data_size)
+{
+  const union MHD_DaemonInfo *dinfo;
+  CURL *c;
+  struct lcurl_data_cb_param dcbp;
+  CURLcode errornum;
+  int use_external_poll;
+  long resp_code;
+
+  dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  use_external_poll = (0 == (dinfo->flags
+                             & MHD_USE_INTERNAL_POLLING_THREAD));
+
+  if (NULL == p->queryPath)
+    abort ();
+
+  if (0 == p->queryPort)
+    abort ();
+
+  /* Test must not fail due to test's internal buffer shortage */
+  dcbp.size = TEST_FAIL_SIZE * 2 + 1;
+  dcbp.buf = malloc (dcbp.size);
+  if (NULL == dcbp.buf)
+    externalErrorExit ();
+  dcbp.pos = 0;
+
+  memset (hdr_res, 0, sizeof(*hdr_res));
+
+  c = curlEasyInitForTest (p->queryPath, p->method, p->queryPort,
+                           &dcbp, hdr_res, p->headers);
+
+  if (! use_external_poll)
+    errornum = curl_easy_perform (c);
+  else
+    errornum = performQueryExternal (d, c);
+
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &resp_code))
+    libcurlErrorExitDesc ("curl_easy_getinfo() failed");
+
+  p->responseCode = (int) resp_code;
+  if ((CURLE_OK == errornum) && (200 != resp_code))
+  {
+    fprintf (stderr,
+             "Got reply with unexpected status code: %d\n",
+             p->responseCode);
+    mhdErrorExit ();
+  }
+
+  if (CURLE_OK != errornum)
+  {
+    if ((CURLE_GOT_NOTHING != errornum) && (CURLE_RECV_ERROR != errornum)
+        && (CURLE_HTTP_RETURNED_ERROR != errornum))
+    {
+      if (CURLE_OPERATION_TIMEDOUT == errornum)
+        mhdErrorExitDesc ("Request was aborted due to timeout");
+      fprintf (stderr, "libcurl returned unexpected error: %s\n",
+               curl_easy_strerror (errornum));
+      mhdErrorExitDesc ("Request failed due to unexpected error");
+    }
+    p->queryError = 1;
+    if ((0 != resp_code) &&
+        ((499 < resp_code) || (400 > resp_code))) /* TODO: add all expected error codes */
+    {
+      fprintf (stderr,
+               "Got reply with unexpected status code: %ld\n",
+               resp_code);
+      mhdErrorExit ();
+    }
+  }
+  else
+  {
+    if (dcbp.pos != expected_data_size)
+      mhdErrorExit ("libcurl reports wrong size of MHD reply body data");
+    else if (0 != memcmp (expected_data, dcbp.buf,
+                          expected_data_size))
+      mhdErrorExit ("libcurl reports wrong MHD reply body data");
+    else
+      p->queryError = 0;
+  }
+
+  curl_easy_cleanup (c);
+  free (dcbp.buf);
+
+  return p->queryError;
+}
+
+
+/* Perform test queries, shut down MHD daemon, and free parameters */
+static unsigned int
+performTestQueries (struct MHD_Daemon *d, uint16_t d_port,
+                    struct ahc_cls_type *ahc_param,
+                    struct check_uri_cls *uri_cb_param)
+{
+  struct curlQueryParams qParam;
+  unsigned int ret = 0;          /* Return value */
+  struct headers_check_result rp_headers_check;
+  char *buf;
+  size_t i;
+  size_t first_failed_at = 0;
+
+
+  buf = malloc (TEST_FAIL_SIZE + 1 + strlen (URL_SCHEME_HOST));
+  if (NULL == buf)
+    externalErrorExit ();
+
+  /* Common parameters, to be individually overridden by specific test cases */
+  qParam.queryPort = d_port;
+  qParam.method = NULL;  /* Use libcurl default: GET */
+  qParam.queryPath = URL_SCHEME_HOST EXPECTED_URI_BASE_PATH;
+  qParam.headers = NULL; /* No additional headers */
+  uri_cb_param->uri = EXPECTED_URI_BASE_PATH;
+  ahc_param->rq_url = EXPECTED_URI_BASE_PATH;
+  ahc_param->rq_method = "GET"; /* Default expected method */
+
+  ahc_param->rp_data = "~";
+  ahc_param->rp_data_size = 1;
+  ahc_param->rp_large_hdr_name_size = 0;
+  ahc_param->rp_large_hdr_value_size = 0;
+  ahc_param->rp_num_n1_hdrs = 0;
+
+  if (large_req_method)
+  {
+    for (i = 0; i < TEST_START_SIZE; i++)
+      buf[i] = 'A' + (char) (unsigned char) (i % ('Z' - 'A' + 1));
+    for (; i <= TEST_FAIL_SIZE; i++)
+    {
+      buf[i] = 0;
+
+      qParam.method = buf;
+      ahc_param->rq_method = buf;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != ahc_param->header_check_param.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large request header");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+      if (0 != rp_headers_check.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large reply header");
+
+      buf[i] = 'A' + (char) (unsigned char) (i % ('Z' - 'A' + 1));
+    }
+  }
+  else if (large_req_url)
+  {
+    const size_t base_size = strlen (URL_SCHEME_HOST);
+    char *const url = buf + base_size;
+
+    memcpy (buf, URL_SCHEME_HOST, base_size);
+    url[0] = '/';
+    for (i = 1; i < TEST_START_SIZE; i++)
+      url[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1));
+    for (; i <= TEST_FAIL_SIZE; i++)
+    {
+      url[i] = 0;
+
+      qParam.queryPath = buf;
+      uri_cb_param->uri = url;
+      ahc_param->rq_url = url;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != ahc_param->header_check_param.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large request header");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+      if (0 != rp_headers_check.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large reply header");
+
+      url[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1));
+    }
+  }
+  else if (large_req_header_name)
+  {
+    buf[0] = '0'; /* Name starts with zero for unique identification */
+    for (i = 1; i < TEST_START_SIZE; i++)
+      buf[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1));
+    for (; i <= TEST_FAIL_SIZE; i++)
+    {
+      struct curl_slist *curl_headers;
+      curl_headers = NULL;
+
+      memcpy (buf + i, ": Z", 3); /* Note: strlen(": Z") is less than strlen(URL_SCHEME_HOST) */
+      buf[i + 3] = 0;
+
+      curl_headers = curl_slist_append (curl_headers, buf);
+      if (NULL == curl_headers)
+        externalErrorExit ();
+
+      qParam.headers = curl_headers;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (0 != ahc_param->header_check_param.large_header_name_size)
+        { /* If large header was processed, it must be valid */
+          if (i != ahc_param->header_check_param.large_header_name_size)
+            mhdErrorExitDesc ("Detected wrong large request header name size");
+          if (1 != ahc_param->header_check_param.large_header_value_size)
+            mhdErrorExitDesc ("Detected wrong large request header value size");
+          if (0 == ahc_param->header_check_param.large_header_valid)
+            mhdErrorExitDesc ("Detected wrong large request header");
+        }
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (i != ahc_param->header_check_param.large_header_name_size)
+          mhdErrorExitDesc ("Detected wrong large request header name size");
+        if (1 != ahc_param->header_check_param.large_header_value_size)
+          mhdErrorExitDesc ("Detected wrong large request header value size");
+        if (0 == ahc_param->header_check_param.large_header_valid)
+          mhdErrorExitDesc ("Detected wrong large request header");
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+      if (0 != rp_headers_check.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large reply header");
+
+      curl_slist_free_all (curl_headers);
+      buf[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1));
+    }
+  }
+  else if (large_req_header_value)
+  {
+    char *const hdr_value = buf + 3;
+    /* Name starts with zero for unique identification */
+    memcpy (buf, "0: ", 3); /* Note: strlen(": Z") is less than strlen(URL_SCHEME_HOST) */
+    for (i = 0; i < TEST_START_SIZE; i++)
+      hdr_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1));
+    for (; i <= TEST_FAIL_SIZE; i++)
+    {
+      struct curl_slist *curl_headers;
+      curl_headers = NULL;
+
+      hdr_value[i] = 0;
+
+      curl_headers = curl_slist_append (curl_headers, buf);
+      if (NULL == curl_headers)
+        externalErrorExit ();
+
+      qParam.headers = curl_headers;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (0 != ahc_param->header_check_param.large_header_name_size)
+        { /* If large header was processed, it must be valid */
+          if (1 != ahc_param->header_check_param.large_header_name_size)
+            mhdErrorExitDesc ("Detected wrong large request header name size");
+          if (i != ahc_param->header_check_param.large_header_value_size)
+            mhdErrorExitDesc ("Detected wrong large request header value size");
+          if (0 == ahc_param->header_check_param.large_header_valid)
+            mhdErrorExitDesc ("Detected wrong large request header");
+        }
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (1 != ahc_param->header_check_param.large_header_name_size)
+          mhdErrorExitDesc ("Detected wrong large request header name size");
+        if (i != ahc_param->header_check_param.large_header_value_size)
+          mhdErrorExitDesc ("Detected wrong large request header value size");
+        if (0 == ahc_param->header_check_param.large_header_valid)
+          mhdErrorExitDesc ("Detected wrong large request header");
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+      if (0 != rp_headers_check.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large reply header");
+
+      curl_slist_free_all (curl_headers);
+      hdr_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1));
+    }
+  }
+  else if (large_req_headers)
+  {
+    unsigned int num_hdrs = 0;
+    struct curl_slist *curl_headers;
+    const size_t hdr_size = strlen (N1_HEADER_CRLF);
+
+    curl_headers = NULL;
+
+    for (i = 0; i < TEST_RQ_N1_START_SIZE; i += hdr_size)
+    {
+      curl_headers = curl_slist_append (curl_headers, N1_HEADER);
+      if (NULL == curl_headers)
+        externalErrorExit ();
+      num_hdrs++;
+    }
+    for (; i <= TEST_FAIL_SIZE; i += hdr_size)
+    {
+      qParam.headers = curl_headers;
+      ahc_param->header_check_param.num_n1_headers = num_hdrs;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (0 != ahc_param->header_check_param.num_n1_headers)
+        { /* If headers were processed, they must be valid */
+          if (num_hdrs != ahc_param->header_check_param.num_n1_headers)
+            mhdErrorExitDesc ("Detected wrong number of request headers");
+        }
+        if (TEST_RQ_N1_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (num_hdrs != ahc_param->header_check_param.num_n1_headers)
+          mhdErrorExitDesc ("Detected wrong number of request headers");
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large request header");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+      if (0 != rp_headers_check.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large reply header");
+
+      curl_headers = curl_slist_append (curl_headers, N1_HEADER);
+      if (NULL == curl_headers)
+        externalErrorExit ();
+      num_hdrs++;
+    }
+    curl_slist_free_all (curl_headers);
+  }
+  else if (large_rsp_header_name)
+  {
+    for (i = TEST_START_SIZE; i <= TEST_FAIL_SIZE; i++)
+    {
+      ahc_param->rp_large_hdr_name_size = i;
+      ahc_param->rp_large_hdr_value_size = 1;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (0 != rp_headers_check.large_header_name_size)
+          mhdErrorExitDesc ("Detected unexpected large reply header");
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (i != rp_headers_check.large_header_name_size)
+          mhdErrorExitDesc ("Detected wrong large reply header name size");
+        if (1 != rp_headers_check.large_header_value_size)
+          mhdErrorExitDesc ("Detected wrong large reply header value size");
+        if (0 == rp_headers_check.large_header_valid)
+          mhdErrorExitDesc ("Detected wrong large reply header");
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != ahc_param->header_check_param.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large request header");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+    }
+  }
+  else if (large_rsp_header_value)
+  {
+    for (i = TEST_START_SIZE; i <= TEST_FAIL_SIZE; i++)
+    {
+      ahc_param->rp_large_hdr_name_size = 1;
+      ahc_param->rp_large_hdr_value_size = i;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (0 != rp_headers_check.large_header_name_size)
+          mhdErrorExitDesc ("Detected unexpected large reply header");
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (1 != rp_headers_check.large_header_name_size)
+          mhdErrorExitDesc ("Detected wrong large reply header name size");
+        if (i != rp_headers_check.large_header_value_size)
+          mhdErrorExitDesc ("Detected wrong large reply header value size");
+        if (0 == rp_headers_check.large_header_valid)
+          mhdErrorExitDesc ("Detected wrong large reply header");
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != ahc_param->header_check_param.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large request header");
+      if (0 != rp_headers_check.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected reply headers");
+    }
+  }
+  else if (large_rsp_headers)
+  {
+    size_t num_hrds;
+    const size_t hdr_size = strlen (N1_HEADER_CRLF);
+
+    for (num_hrds = TEST_START_SIZE / hdr_size;
+         num_hrds * hdr_size <= TEST_FAIL_SIZE; num_hrds++)
+    {
+      i = num_hrds * hdr_size;
+      ahc_param->rp_num_n1_hdrs = num_hrds;
+
+      memset (&ahc_param->header_check_param, 0,
+              sizeof (ahc_param->header_check_param));
+      if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                    ahc_param->rp_data,
+                                    ahc_param->rp_data_size))
+      {
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        if (0 != rp_headers_check.num_n1_headers)
+          mhdErrorExitDesc ("Detected unexpected reply headers");
+        if (TEST_OK_SIZE >= i)
+        {
+          fprintf (stderr,
+                   "Request failed when running with the valid value size.\n");
+          ret = 1; /* Failed too early */
+        }
+        if (0 == first_failed_at)
+        {
+          if (verbose)
+            fprintf (stderr, "First failed size is %u.\n", (unsigned int) i);
+          first_failed_at = i;
+        }
+      }
+      else
+      {
+        if (num_hrds != rp_headers_check.num_n1_headers)
+          mhdErrorExitDesc ("Detected wrong number of reply headers");
+        if (TEST_FAIL_SIZE == i)
+        {
+          fprintf (stderr, "Request succeed with the largest size.\n");
+          ret = 1; /* Succeed with largest value */
+        }
+      }
+      if (0 != ahc_param->header_check_param.num_n1_headers)
+        mhdErrorExitDesc ("Detected unexpected request headers");
+      if (0 != ahc_param->header_check_param.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large request header");
+      if (0 != rp_headers_check.large_header_name_size)
+        mhdErrorExitDesc ("Detected unexpected large reply header");
+    }
+  }
+  else
+    externalErrorExitDesc ("No valid test test was selected");
+
+  MHD_stop_daemon (d);
+  free (buf);
+  free (uri_cb_param);
+  free (ahc_param);
+
+  return ret;
+}
+
+
+enum testMhdThreadsType
+{
+  testMhdThreadExternal              = 0,
+  testMhdThreadInternal              = MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION
+                                       | MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPool
+};
+
+enum testMhdPollType
+{
+  testMhdPollBySelect = 0,
+  testMhdPollByPoll   = MHD_USE_POLL,
+  testMhdPollByEpoll  = MHD_USE_EPOLL,
+  testMhdPollAuto     = MHD_USE_AUTO
+};
+
+/* Get number of threads for thread pool depending
+ * on used poll function and test type. */
+static unsigned int
+testNumThreadsForPool (enum testMhdPollType pollType)
+{
+  unsigned int numThreads = MHD_CPU_COUNT;
+  (void) pollType; /* Don't care about pollType for this test */
+  return numThreads; /* No practical limit for non-cleanup test */
+}
+
+
+static struct MHD_Daemon *
+startTestMhdDaemon (enum testMhdThreadsType thrType,
+                    enum testMhdPollType pollType, uint16_t *pport,
+                    struct ahc_cls_type **ahc_param,
+                    struct check_uri_cls **uri_cb_param)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *dinfo;
+
+  if ((NULL == ahc_param) || (NULL == uri_cb_param))
+    abort ();
+
+  *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type));
+  if (NULL == *ahc_param)
+    externalErrorExit ();
+  *uri_cb_param =
+    (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls));
+  if (NULL == *uri_cb_param)
+    externalErrorExit ();
+
+  if ( (0 == *pport) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    *pport = 4100;
+    if (large_req_method)
+      *pport += 1;
+    if (large_req_url)
+      *pport += 2;
+    if (large_req_header_name)
+      *pport += 3;
+    if (large_req_header_value)
+      *pport += 4;
+    if (large_req_headers)
+      *pport += 5;
+    if (large_rsp_header_name)
+      *pport += 6;
+    if (large_rsp_header_value)
+      *pport += 7;
+    if (large_rsp_headers)
+      *pport += 8;
+    if (! oneone)
+      *pport += 16;
+  }
+
+  if (testMhdThreadInternalPool != thrType)
+    d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb,
+                          *uri_cb_param,
+                          MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                          (size_t) BUFFER_SIZE,
+                          MHD_OPTION_END);
+  else
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                          | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          testNumThreadsForPool (pollType),
+                          MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb,
+                          *uri_cb_param,
+                          MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                          (size_t) BUFFER_SIZE,
+                          MHD_OPTION_END);
+
+  if (NULL == d)
+  {
+    fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno);
+    abort ();
+  }
+
+  if (0 == *pport)
+  {
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+      abort ();
+    }
+    *pport = dinfo->port;
+    if (0 == global_port)
+      global_port = *pport; /* Reuse the same port for all tests */
+  }
+
+  return d;
+}
+
+
+/* Test runners */
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port,
+                          &ahc_param, &uri_cb_param);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+static unsigned int
+testInternalGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+static unsigned int
+testMultithreadedGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  verbose = 0;
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = ! has_in_name (argv[0], "10");
+  large_req_method = has_in_name (argv[0], "_method") ? 1 : 0;
+  large_req_url = has_in_name (argv[0], "_url") ? 1 : 0;
+  large_req_header_name = has_in_name (argv[0], "_request_header_name") ?
+                          1 : 0;
+  large_req_header_value = has_in_name (argv[0], "_request_header_value") ?
+                           1 : 0;
+  large_req_headers = has_in_name (argv[0], "_request_headers") ? 1 : 0;
+  large_rsp_header_name = has_in_name (argv[0], "_reply_header_name") ?
+                          1 : 0;
+  large_rsp_header_value = has_in_name (argv[0], "_reply_header_value") ?
+                           1 : 0;
+  large_rsp_headers = has_in_name (argv[0], "_reply_headers") ? 1 : 0;
+  if (large_req_method + large_req_url + large_req_header_name
+      + large_req_header_value + large_req_headers + large_rsp_header_name
+      + large_rsp_header_value + large_rsp_headers != 1)
+    return 99;
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+
+  test_global_init ();
+
+  /* Could be set to non-zero value to enforce using specific port
+   * in the test */
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result = testInternalGet (testMhdPollAuto);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+#ifdef _MHD_HEAVY_TESTS
+    /* Actually tests are not heavy, but took too long to complete while
+     * not really provide any additional results. */
+    test_result = testInternalGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedPoolGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result = testInternalGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result = testInternalGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+    }
+#else
+    /* Mute compiler warnings */
+    (void) testMultithreadedGet;
+    (void) testMultithreadedPoolGet;
+#endif /* _MHD_HEAVY_TESTS */
+  }
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+
+  test_global_cleanup ();
+
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_tricky.c b/src/testcurl/test_tricky.c
new file mode 100644
index 0000000..88ecff0
--- /dev/null
+++ b/src/testcurl/test_tricky.c
@@ -0,0 +1,1177 @@
+/*
+     This file is part of libmicrohttpd
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
+     Copyright (C) 2007, 2009, 2011 Christian Grothoff
+
+     libmicrohttpd 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 2, or (at your
+     option) any later version.
+
+     libmicrohttpd 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 libmicrohttpd; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
+*/
+/**
+ * @file test_toolarge.c
+ * @brief  Testcase for handling of untypical data.
+ * @author Karlson2k (Evgeny Grin)
+ * @author Christian Grothoff
+ */
+#include "MHD_config.h"
+#include "platform.h"
+#include <curl/curl.h>
+#include <microhttpd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "mhd_has_in_name.h"
+#include "mhd_has_param.h"
+#include "mhd_sockets.h" /* only macros used */
+
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
+#endif /* HAVE_STRINGS_H */
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif /* !WIN32_LEAN_AND_MEAN */
+#include <windows.h>
+#endif
+
+#ifndef WINDOWS
+#include <unistd.h>
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif /* HAVE_LIMITS_H */
+
+#ifndef CURL_VERSION_BITS
+#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
+#endif /* ! CURL_VERSION_BITS */
+#ifndef CURL_AT_LEAST_VERSION
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+  (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
+#endif /* ! CURL_AT_LEAST_VERSION */
+
+#if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
+#undef MHD_CPU_COUNT
+#endif
+#if ! defined(MHD_CPU_COUNT)
+#define MHD_CPU_COUNT 2
+#endif
+#if MHD_CPU_COUNT > 32
+#undef MHD_CPU_COUNT
+/* Limit to reasonable value */
+#define MHD_CPU_COUNT 32
+#endif /* MHD_CPU_COUNT > 32 */
+
+
+#if defined(HAVE___FUNC__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __func__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __func__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __func__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __func__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __func__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __func__, __LINE__)
+#elif defined(HAVE___FUNCTION__)
+#define externalErrorExit(ignore) \
+    _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+    _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define libcurlErrorExit(ignore) \
+    _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+    _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#define mhdErrorExit(ignore) \
+    _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
+#define mhdErrorExitDesc(errDesc) \
+    _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
+#else
+#define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
+#define externalErrorExitDesc(errDesc) \
+  _externalErrorExit_func(errDesc, NULL, __LINE__)
+#define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
+#define libcurlErrorExitDesc(errDesc) \
+  _libcurlErrorExit_func(errDesc, NULL, __LINE__)
+#define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
+#define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
+#endif
+
+
+_MHD_NORETURN static void
+_externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "System or external library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+#ifdef MHD_WINSOCK_SOCKETS
+  fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
+#endif /* MHD_WINSOCK_SOCKETS */
+  fflush (stderr);
+  exit (99);
+}
+
+
+static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
+
+_MHD_NORETURN static void
+_libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "CURL library call failed");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+  if (0 != libcurl_errbuf[0])
+    fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf);
+
+  fflush (stderr);
+  exit (99);
+}
+
+
+_MHD_NORETURN static void
+_mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
+{
+  if ((NULL != errDesc) && (0 != errDesc[0]))
+    fprintf (stderr, "%s", errDesc);
+  else
+    fprintf (stderr, "MHD unexpected error");
+  if ((NULL != funcName) && (0 != funcName[0]))
+    fprintf (stderr, " in %s", funcName);
+  if (0 < lineNum)
+    fprintf (stderr, " at line %d", lineNum);
+
+  fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
+           strerror (errno));
+
+  fflush (stderr);
+  exit (8);
+}
+
+
+/* Could be increased to facilitate debugging */
+#define TIMEOUTS_VAL 5
+
+#define EXPECTED_URI_BASE_PATH  "/a"
+
+#define EXPECTED_URI_BASE_PATH_TRICKY  "/one\rtwo"
+
+#define URL_SCHEME "http:/" "/"
+
+#define URL_HOST "127.0.0.1"
+
+#define URL_SCHEME_HOST URL_SCHEME URL_HOST
+
+#define HEADER1_NAME "First"
+#define HEADER1_VALUE "1st"
+#define HEADER1 HEADER1_NAME ": " HEADER1_VALUE
+#define HEADER2_NAME "Second"
+#define HEADER2CR_VALUE "2\rnd"
+#define HEADER2CR HEADER2_NAME ": " HEADER2CR_VALUE
+/* Use headers when it would be properly supported by MHD
+#define HEADER3CR_NAME "Thi\rrd"
+#define HEADER3CR_VALUE "3r\rd"
+#define HEADER3CR HEADER3CR_NAME ": " HEADER3CR_VALUE
+*/
+#define HEADER4_NAME "Normal"
+#define HEADER4_VALUE "it's fine"
+#define HEADER4 HEADER4_NAME ": " HEADER4_VALUE
+
+/* Global parameters */
+static int verbose;                 /**< Be verbose */
+static int oneone;                  /**< If false use HTTP/1.0 for requests*/
+static uint16_t global_port;        /**< MHD daemons listen port number */
+static int response_timeout_val = TIMEOUTS_VAL;
+
+static int tricky_url;              /**< Tricky request URL */
+static int tricky_header2;          /**< Tricky request header2 */
+
+/* Current test parameters */
+/* * Moved to local variables * */
+
+/* Static helper variables */
+/* * None for this test * */
+
+static void
+test_global_init (void)
+{
+  libcurl_errbuf[0] = 0;
+
+  if (0 != curl_global_init (CURL_GLOBAL_WIN32))
+    externalErrorExit ();
+}
+
+
+static void
+test_global_cleanup (void)
+{
+  curl_global_cleanup ();
+}
+
+
+struct headers_check_result
+{
+  int dummy; /* no checks in this test */
+};
+
+
+static size_t
+lcurl_hdr_callback (char *buffer, size_t size, size_t nitems,
+                    void *userdata)
+{
+  const size_t data_size = size * nitems;
+  struct headers_check_result *check_res =
+    (struct headers_check_result *) userdata;
+
+  /* no checks in this test */
+  (void) check_res; (void) buffer;
+
+  return data_size;
+}
+
+
+struct lcurl_data_cb_param
+{
+  char *buf;
+  size_t pos;
+  size_t size;
+};
+
+
+static size_t
+copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
+{
+  struct lcurl_data_cb_param *cbc = ctx;
+
+  if (cbc->pos + size * nmemb > cbc->size)
+    externalErrorExit ();  /* overflow */
+  memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
+  cbc->pos += size * nmemb;
+  return size * nmemb;
+}
+
+
+struct check_uri_cls
+{
+  const char *volatile uri;
+};
+
+static void *
+check_uri_cb (void *cls,
+              const char *uri,
+              struct MHD_Connection *con)
+{
+  struct check_uri_cls *param = (struct check_uri_cls *) cls;
+  (void) con;
+
+  if (0 != strcmp (param->uri,
+                   uri))
+  {
+    fprintf (stderr,
+             "Wrong URI: `%s', line: %d\n",
+             uri, __LINE__);
+    exit (22);
+  }
+  return NULL;
+}
+
+
+struct mhd_header_checker_param
+{
+  int found_header1;
+  int found_header2;
+  int found_header4;
+};
+
+static enum MHD_Result
+headerCheckerInterator (void *cls,
+                        enum MHD_ValueKind kind,
+                        const char *key,
+                        size_t key_size,
+                        const char *value,
+                        size_t value_size)
+{
+  struct mhd_header_checker_param *const param =
+    (struct mhd_header_checker_param *) cls;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (MHD_HEADER_KIND != kind)
+    return MHD_YES; /* Continue iteration */
+
+  if (0 == key_size)
+    mhdErrorExitDesc ("Zero key length");
+
+  if ((strlen (HEADER1_NAME) == key_size) &&
+      (0 == memcmp (key, HEADER1_NAME, key_size)))
+  {
+    if ((strlen (HEADER1_VALUE) == value_size) &&
+        (0 == memcmp (value, HEADER1_VALUE, value_size)))
+      param->found_header1 = 1;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, HEADER1_VALUE);
+  }
+  else if ((strlen (HEADER2_NAME) == key_size) &&
+           (0 == memcmp (key, HEADER2_NAME, key_size)))
+  {
+    if ((strlen (HEADER2CR_VALUE) == value_size) &&
+        (0 == memcmp (value, HEADER2CR_VALUE, value_size)))
+      param->found_header2 = 1;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, HEADER2CR_VALUE);
+  }
+  else if ((strlen (HEADER4_NAME) == key_size) &&
+           (0 == memcmp (key, HEADER4_NAME, key_size)))
+  {
+    if ((strlen (HEADER4_VALUE) == value_size) &&
+        (0 == memcmp (value, HEADER4_VALUE, value_size)))
+      param->found_header4 = 1;
+    else
+      fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n",
+               (int) value_size, value, HEADER4_VALUE);
+  }
+  return MHD_YES;
+}
+
+
+struct ahc_cls_type
+{
+  const char *volatile rp_data;
+  volatile size_t rp_data_size;
+  struct mhd_header_checker_param header_check_param;
+  const char *volatile rq_method;
+  const char *volatile rq_url;
+};
+
+
+static enum MHD_Result
+ahcCheck (void *cls,
+          struct MHD_Connection *connection,
+          const char *url,
+          const char *method,
+          const char *version,
+          const char *upload_data, size_t *upload_data_size,
+          void **req_cls)
+{
+  static int ptr;
+  struct MHD_Response *response;
+  enum MHD_Result ret;
+  struct ahc_cls_type *const param = (struct ahc_cls_type *) cls;
+
+  if (NULL == param)
+    mhdErrorExitDesc ("cls parameter is NULL");
+
+  if (0 != strcmp (version, MHD_HTTP_VERSION_1_1))
+    mhdErrorExitDesc ("Unexpected HTTP version");
+
+  if (0 != strcmp (url, param->rq_url))
+    mhdErrorExitDesc ("Unexpected URI");
+
+  if (NULL != upload_data)
+    mhdErrorExitDesc ("'upload_data' is not NULL");
+
+  if (NULL == upload_data_size)
+    mhdErrorExitDesc ("'upload_data_size' pointer is NULL");
+
+  if (0 != *upload_data_size)
+    mhdErrorExitDesc ("'*upload_data_size' value is not zero");
+
+  if (0 != strcmp (param->rq_method, method))
+    mhdErrorExitDesc ("Unexpected request method");
+
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
+
+  if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND,
+                                       &headerCheckerInterator,
+                                       &param->header_check_param))
+    mhdErrorExitDesc ("Wrong number of headers in the request");
+
+  response =
+    MHD_create_response_from_buffer_copy (param->rp_data_size,
+                                          (const void *) param->rp_data);
+  if (NULL == response)
+    mhdErrorExitDesc ("Failed to create response");
+
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
+  MHD_destroy_response (response);
+  if (MHD_YES != ret)
+    mhdErrorExitDesc ("Failed to queue response");
+
+  return ret;
+}
+
+
+struct curlQueryParams
+{
+  /* Destination path for CURL query */
+  const char *queryPath;
+
+#if CURL_AT_LEAST_VERSION (7, 62, 0)
+  CURLU *url;
+#endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */
+
+  /* Custom query method, NULL for default */
+  const char *method;
+
+  /* Destination port for CURL query */
+  uint16_t queryPort;
+
+  /* List of additional request headers */
+  struct curl_slist *headers;
+
+  /* CURL query result error flag */
+  volatile unsigned int queryError;
+
+  /* Response HTTP code, zero if no response */
+  volatile int responseCode;
+};
+
+
+static CURL *
+curlEasyInitForTest (struct curlQueryParams *p,
+                     struct lcurl_data_cb_param *dcbp,
+                     struct headers_check_result *hdr_chk_result)
+{
+  CURL *c;
+
+  c = curl_easy_init ();
+  if (NULL == c)
+    libcurlErrorExitDesc ("curl_easy_init() failed");
+
+  if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, p->queryPath)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) p->queryPort)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
+                                     &copyBuffer)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, dcbp)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
+                                     (long) response_timeout_val)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
+                                     libcurl_errbuf)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION,
+                                     lcurl_hdr_callback)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA,
+                                     hdr_chk_result)) ||
+#if CURL_AT_LEAST_VERSION (7, 42, 0)
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_PATH_AS_IS,
+                                     (long) 1)) ||
+#endif /* CURL_AT_LEAST_VERSION(7, 42, 0) */
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
+      (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
+                                     (oneone) ?
+                                     CURL_HTTP_VERSION_1_1 :
+                                     CURL_HTTP_VERSION_1_0)))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, p->method))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+  if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, p->headers))
+    libcurlErrorExitDesc ("curl_easy_setopt() failed");
+
+#if CURL_AT_LEAST_VERSION (7, 62, 0)
+  if (NULL != p->url)
+  {
+    if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CURLU, p->url))
+      libcurlErrorExitDesc ("curl_easy_setopt() failed");
+  }
+#endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */
+  return c;
+}
+
+
+static CURLcode
+performQueryExternal (struct MHD_Daemon *d, CURL *c)
+{
+  CURLM *multi;
+  time_t start;
+  struct timeval tv;
+  CURLcode ret;
+
+  ret = CURLE_FAILED_INIT; /* will be replaced with real result */
+  multi = NULL;
+  multi = curl_multi_init ();
+  if (multi == NULL)
+    libcurlErrorExitDesc ("curl_multi_init() failed");
+  if (CURLM_OK != curl_multi_add_handle (multi, c))
+    libcurlErrorExitDesc ("curl_multi_add_handle() failed");
+
+  start = time (NULL);
+  while (time (NULL) - start <= TIMEOUTS_VAL)
+  {
+    fd_set rs;
+    fd_set ws;
+    fd_set es;
+    MHD_socket maxMhdSk;
+    int maxCurlSk;
+    int running;
+
+    maxMhdSk = MHD_INVALID_SOCKET;
+    maxCurlSk = -1;
+    FD_ZERO (&rs);
+    FD_ZERO (&ws);
+    FD_ZERO (&es);
+    if (NULL != multi)
+    {
+      curl_multi_perform (multi, &running);
+      if (0 == running)
+      {
+        struct CURLMsg *msg;
+        int msgLeft;
+        int totalMsgs = 0;
+        do
+        {
+          msg = curl_multi_info_read (multi, &msgLeft);
+          if (NULL == msg)
+            libcurlErrorExitDesc ("curl_multi_info_read() failed");
+          totalMsgs++;
+          if (CURLMSG_DONE == msg->msg)
+            ret = msg->data.result;
+        } while (msgLeft > 0);
+        if (1 != totalMsgs)
+        {
+          fprintf (stderr,
+                   "curl_multi_info_read returned wrong "
+                   "number of results (%d).\n",
+                   totalMsgs);
+          externalErrorExit ();
+        }
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        multi = NULL;
+      }
+      else
+      {
+        if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk))
+          libcurlErrorExitDesc ("curl_multi_fdset() failed");
+      }
+    }
+    if (NULL == multi)
+    { /* libcurl has finished, check whether MHD still needs to perform cleanup */
+      if (0 != MHD_get_timeout64s (d))
+        break; /* MHD finished as well */
+    }
+    if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk))
+      mhdErrorExitDesc ("MHD_get_fdset() failed");
+    tv.tv_sec = 0;
+    tv.tv_usec = 1000;
+#ifdef MHD_POSIX_SOCKETS
+    if (maxMhdSk > maxCurlSk)
+      maxCurlSk = maxMhdSk;
+#endif /* MHD_POSIX_SOCKETS */
+    if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv))
+    {
+#ifdef MHD_POSIX_SOCKETS
+      if (EINTR != errno)
+        externalErrorExitDesc ("Unexpected select() error");
+#else
+      if ((WSAEINVAL != WSAGetLastError ()) ||
+          (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
+        externalErrorExitDesc ("Unexpected select() error");
+      Sleep (1);
+#endif
+    }
+    if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es))
+      mhdErrorExitDesc ("MHD_run_from_select() failed");
+  }
+
+  return ret;
+}
+
+
+/* Returns zero for successful response and non-zero for failed response */
+static unsigned int
+doCurlQueryInThread (struct MHD_Daemon *d,
+                     struct curlQueryParams *p,
+                     struct headers_check_result *hdr_res,
+                     const char *expected_data,
+                     size_t expected_data_size)
+{
+  const union MHD_DaemonInfo *dinfo;
+  CURL *c;
+  struct lcurl_data_cb_param dcbp;
+  CURLcode errornum;
+  int use_external_poll;
+  long resp_code;
+
+  dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS);
+  if (NULL == dinfo)
+    mhdErrorExitDesc ("MHD_get_daemon_info() failed");
+  use_external_poll = (0 == (dinfo->flags
+                             & MHD_USE_INTERNAL_POLLING_THREAD));
+
+  if (NULL == p->queryPath
+#if CURL_AT_LEAST_VERSION (7, 62, 0)
+      && NULL == p->url
+#endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */
+      )
+    abort ();
+
+  if (0 == p->queryPort)
+    abort ();
+
+  /* Test must not fail due to test's internal buffer shortage */
+  dcbp.size = expected_data_size * 2 + 1;
+  dcbp.buf = malloc (dcbp.size);
+  if (NULL == dcbp.buf)
+    externalErrorExit ();
+  dcbp.pos = 0;
+
+  memset (hdr_res, 0, sizeof(*hdr_res));
+
+  c = curlEasyInitForTest (p,
+                           &dcbp, hdr_res);
+
+  if (! use_external_poll)
+    errornum = curl_easy_perform (c);
+  else
+    errornum = performQueryExternal (d, c);
+
+  if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &resp_code))
+    libcurlErrorExitDesc ("curl_easy_getinfo() failed");
+
+  p->responseCode = (int) resp_code;
+  if ((CURLE_OK == errornum) && (200 != resp_code))
+  {
+    fprintf (stderr,
+             "Got reply with unexpected status code: %d\n",
+             p->responseCode);
+    mhdErrorExit ();
+  }
+
+  if (CURLE_OK != errornum)
+  {
+    if ((CURLE_GOT_NOTHING != errornum) && (CURLE_RECV_ERROR != errornum)
+        && (CURLE_HTTP_RETURNED_ERROR != errornum))
+    {
+      if (CURLE_OPERATION_TIMEDOUT == errornum)
+        mhdErrorExitDesc ("Request was aborted due to timeout");
+      fprintf (stderr, "libcurl returned unexpected error: %s\n",
+               curl_easy_strerror (errornum));
+      mhdErrorExitDesc ("Request failed due to unexpected error");
+    }
+    p->queryError = 1;
+    if ((0 != resp_code) &&
+        ((499 < resp_code) || (400 > resp_code))) /* TODO: add all expected error codes */
+    {
+      fprintf (stderr,
+               "Got reply with unexpected status code: %ld\n",
+               resp_code);
+      mhdErrorExit ();
+    }
+  }
+  else
+  {
+    if (dcbp.pos != expected_data_size)
+      mhdErrorExit ("libcurl reports wrong size of MHD reply body data");
+    else if (0 != memcmp (expected_data, dcbp.buf,
+                          expected_data_size))
+      mhdErrorExit ("libcurl reports wrong MHD reply body data");
+    else
+      p->queryError = 0;
+  }
+
+  curl_easy_cleanup (c);
+  free (dcbp.buf);
+
+  return p->queryError;
+}
+
+
+/* Perform test queries, shut down MHD daemon, and free parameters */
+static unsigned int
+performTestQueries (struct MHD_Daemon *d, uint16_t d_port,
+                    struct ahc_cls_type *ahc_param,
+                    struct check_uri_cls *uri_cb_param)
+{
+  struct curlQueryParams qParam;
+  unsigned int ret = 0;          /* Return value */
+  struct headers_check_result rp_headers_check;
+  struct curl_slist *curl_headers;
+  curl_headers = NULL;
+
+  /* Common parameters, to be individually overridden by specific test cases */
+  qParam.queryPort = d_port;
+  qParam.method = NULL;  /* Use libcurl default: GET */
+  qParam.queryPath = URL_SCHEME_HOST EXPECTED_URI_BASE_PATH;
+#if CURL_AT_LEAST_VERSION (7, 62, 0)
+  qParam.url = NULL;
+#endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */
+  qParam.headers = NULL; /* No additional headers */
+  uri_cb_param->uri = EXPECTED_URI_BASE_PATH;
+  ahc_param->rq_url = EXPECTED_URI_BASE_PATH;
+  ahc_param->rq_method = "GET"; /* Default expected method */
+
+  ahc_param->rp_data = "~";
+  ahc_param->rp_data_size = 1;
+
+  curl_headers = curl_slist_append (curl_headers, HEADER1);
+  if (NULL == curl_headers)
+    externalErrorExit ();
+  curl_headers = curl_slist_append (curl_headers, HEADER4);
+  if (NULL == curl_headers)
+    externalErrorExit ();
+  qParam.headers = curl_headers;
+
+  memset (&ahc_param->header_check_param, 0,
+          sizeof (ahc_param->header_check_param));
+
+  if (tricky_url)
+  {
+#if CURL_AT_LEAST_VERSION (7, 62, 0)
+    CURLU *url;
+    url = curl_url ();
+    if (NULL == url)
+      externalErrorExit ();
+    qParam.url = url;
+
+    if ((CURLUE_OK != curl_url_set (qParam.url, CURLUPART_SCHEME, "http", 0)) ||
+        (CURLUE_OK != curl_url_set (qParam.url, CURLUPART_HOST, URL_HOST,
+                                    CURLU_PATH_AS_IS
+#ifdef CURLU_ALLOW_SPACE
+                                    | CURLU_ALLOW_SPACE
+#endif /* CURLU_ALLOW_SPACE */
+                                    )) ||
+        (CURLUE_OK != curl_url_set (qParam.url, CURLUPART_PATH,
+                                    EXPECTED_URI_BASE_PATH_TRICKY, 0)))
+      libcurlErrorExit ();
+
+    qParam.queryPath = NULL;
+    uri_cb_param->uri = EXPECTED_URI_BASE_PATH_TRICKY;
+    ahc_param->rq_url = EXPECTED_URI_BASE_PATH_TRICKY;
+
+    if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                  ahc_param->rp_data,
+                                  ahc_param->rp_data_size))
+    {
+      /* TODO: Allow fail only if relevant MHD mode set */
+      if (0 == qParam.responseCode)
+      {
+        fprintf (stderr, "Request failed without any valid response.\n");
+        ret = 1;
+      }
+      else
+      {
+        if (verbose)
+          printf ("Request failed with %d response code.\n",
+                  qParam.responseCode);
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        ret = 0;
+      }
+    }
+    else
+    {
+      if (200 != qParam.responseCode)
+      {
+        fprintf (stderr, "Request succeed with wrong response code: %d.\n",
+                 qParam.responseCode);
+        ret = 1;
+      }
+      else
+      {
+        ret = 0;
+        if (verbose)
+          printf ("Request succeed.\n");
+      }
+
+      if (! ahc_param->header_check_param.found_header1)
+        mhdErrorExitDesc ("Required header1 was not detected in request");
+      if (! ahc_param->header_check_param.found_header4)
+        mhdErrorExitDesc ("Required header4 was not detected in request");
+    }
+    curl_url_cleanup (url);
+#else
+    fprintf (stderr, "This test requires libcurl version 7.62.0 or newer.\n");
+    abort ();
+#endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */
+  }
+  else if (tricky_header2)
+  {
+    /* Reset libcurl headers */
+    qParam.headers = NULL;
+    curl_slist_free_all (curl_headers);
+    curl_headers = NULL;
+
+    /* Set special libcurl headers */
+    curl_headers = curl_slist_append (curl_headers, HEADER1);
+    if (NULL == curl_headers)
+      externalErrorExit ();
+    curl_headers = curl_slist_append (curl_headers, HEADER2CR);
+    if (NULL == curl_headers)
+      externalErrorExit ();
+    curl_headers = curl_slist_append (curl_headers, HEADER4);
+    if (NULL == curl_headers)
+      externalErrorExit ();
+    qParam.headers = curl_headers;
+
+    if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check,
+                                  ahc_param->rp_data,
+                                  ahc_param->rp_data_size))
+    {
+      /* TODO: Allow fail only if relevant MHD mode set */
+      if (0 == qParam.responseCode)
+      {
+        fprintf (stderr, "Request failed without any valid response.\n");
+        ret = 1;
+      }
+      else
+      {
+        if (verbose)
+          printf ("Request failed with %d response code.\n",
+                  qParam.responseCode);
+        (void) qParam.responseCode; /* TODO: check for the right response code */
+        ret = 0;
+      }
+    }
+    else
+    {
+      if (200 != qParam.responseCode)
+      {
+        fprintf (stderr, "Request succeed with wrong response code: %d.\n",
+                 qParam.responseCode);
+        ret = 1;
+      }
+      else
+      {
+        ret = 0;
+        if (verbose)
+          printf ("Request succeed.\n");
+      }
+
+      if (! ahc_param->header_check_param.found_header1)
+        mhdErrorExitDesc ("Required header1 was not detected in request");
+      if (! ahc_param->header_check_param.found_header2)
+        mhdErrorExitDesc ("Required header2 was not detected in request");
+      if (! ahc_param->header_check_param.found_header4)
+        mhdErrorExitDesc ("Required header4 was not detected in request");
+    }
+  }
+  else
+    externalErrorExitDesc ("No valid test test was selected");
+
+  MHD_stop_daemon (d);
+  curl_slist_free_all (curl_headers);
+  free (uri_cb_param);
+  free (ahc_param);
+
+  return ret;
+}
+
+
+enum testMhdThreadsType
+{
+  testMhdThreadExternal              = 0,
+  testMhdThreadInternal              = MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION
+                                       | MHD_USE_INTERNAL_POLLING_THREAD,
+  testMhdThreadInternalPool
+};
+
+enum testMhdPollType
+{
+  testMhdPollBySelect = 0,
+  testMhdPollByPoll   = MHD_USE_POLL,
+  testMhdPollByEpoll  = MHD_USE_EPOLL,
+  testMhdPollAuto     = MHD_USE_AUTO
+};
+
+/* Get number of threads for thread pool depending
+ * on used poll function and test type. */
+static unsigned int
+testNumThreadsForPool (enum testMhdPollType pollType)
+{
+  unsigned int numThreads = MHD_CPU_COUNT;
+  (void) pollType; /* Don't care about pollType for this test */
+  return numThreads; /* No practical limit for non-cleanup test */
+}
+
+
+static struct MHD_Daemon *
+startTestMhdDaemon (enum testMhdThreadsType thrType,
+                    enum testMhdPollType pollType, uint16_t *pport,
+                    struct ahc_cls_type **ahc_param,
+                    struct check_uri_cls **uri_cb_param)
+{
+  struct MHD_Daemon *d;
+  const union MHD_DaemonInfo *dinfo;
+
+  if ((NULL == ahc_param) || (NULL == uri_cb_param))
+    abort ();
+
+  *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type));
+  if (NULL == *ahc_param)
+    externalErrorExit ();
+  *uri_cb_param =
+    (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls));
+  if (NULL == *uri_cb_param)
+    externalErrorExit ();
+
+  if ( (0 == *pport) &&
+       (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) )
+  {
+    *pport = 4150;
+    if (tricky_url)
+      *pport += 1;
+    if (tricky_header2)
+      *pport += 2;
+    if (! oneone)
+      *pport += 16;
+  }
+
+  if (testMhdThreadInternalPool != thrType)
+    d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb,
+                          *uri_cb_param,
+                          MHD_OPTION_END);
+  else
+    d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD
+                          | ((unsigned int) pollType)
+                          | (verbose ? MHD_USE_ERROR_LOG : 0),
+                          *pport, NULL, NULL,
+                          &ahcCheck, *ahc_param,
+                          MHD_OPTION_THREAD_POOL_SIZE,
+                          testNumThreadsForPool (pollType),
+                          MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb,
+                          *uri_cb_param,
+                          MHD_OPTION_END);
+
+  if (NULL == d)
+  {
+    fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno);
+    abort ();
+  }
+
+  if (0 == *pport)
+  {
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      fprintf (stderr, "MHD_get_daemon_info() failed.\n");
+      abort ();
+    }
+    *pport = dinfo->port;
+    if (0 == global_port)
+      global_port = *pport; /* Reuse the same port for all tests */
+  }
+
+  return d;
+}
+
+
+/* Test runners */
+
+
+static unsigned int
+testExternalGet (void)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port,
+                          &ahc_param, &uri_cb_param);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+static unsigned int
+testInternalGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+static unsigned int
+testMultithreadedGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+static unsigned int
+testMultithreadedPoolGet (enum testMhdPollType pollType)
+{
+  struct MHD_Daemon *d;
+  uint16_t d_port = global_port; /* Daemon's port */
+  struct ahc_cls_type *ahc_param;
+  struct check_uri_cls *uri_cb_param;
+
+  d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port,
+                          &ahc_param, &uri_cb_param);
+  return performTestQueries (d, d_port, ahc_param, uri_cb_param);
+}
+
+
+int
+main (int argc, char *const *argv)
+{
+  unsigned int errorCount = 0;
+  unsigned int test_result = 0;
+  verbose = 0;
+
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = ! has_in_name (argv[0], "10");
+  tricky_url = has_in_name (argv[0], "_url") ? 1 : 0;
+  tricky_header2 = has_in_name (argv[0], "_header2") ? 1 : 0;
+  if (1 != tricky_url + tricky_header2)
+    return 99;
+  verbose = ! (has_param (argc, argv, "-q") ||
+               has_param (argc, argv, "--quiet") ||
+               has_param (argc, argv, "-s") ||
+               has_param (argc, argv, "--silent"));
+
+#if ! CURL_AT_LEAST_VERSION (7, 62, 0)
+  if (tricky_url)
+  {
+    fprintf (stderr, "This test requires libcurl version 7.62.0 or newer.\n");
+    return 77;
+  }
+#endif /* ! CURL_AT_LEAST_VERSION(7, 62, 0) */
+
+  test_global_init ();
+
+  /* Could be set to non-zero value to enforce using specific port
+   * in the test */
+  global_port = 0;
+  test_result = testExternalGet ();
+  if (test_result)
+    fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result);
+  else if (verbose)
+    printf ("PASSED: testExternalGet ().\n");
+  errorCount += test_result;
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    test_result = testInternalGet (testMhdPollAuto);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+#ifdef _MHD_HEAVY_TESTS
+    /* Actually tests are not heavy, but took too long to complete while
+     * not really provide any additional results. */
+    test_result = testInternalGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testInternalGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedPoolGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    test_result = testMultithreadedGet (testMhdPollBySelect);
+    if (test_result)
+      fprintf (stderr,
+               "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n",
+               test_result);
+    else if (verbose)
+      printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n");
+    errorCount += test_result;
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
+    {
+      test_result = testInternalGet (testMhdPollByPoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByPoll).\n");
+      errorCount += test_result;
+    }
+    if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
+    {
+      test_result = testInternalGet (testMhdPollByEpoll);
+      if (test_result)
+        fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n",
+                 test_result);
+      else if (verbose)
+        printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n");
+      errorCount += test_result;
+    }
+#else
+    /* Mute compiler warnings */
+    (void) testMultithreadedGet;
+    (void) testMultithreadedPoolGet;
+#endif /* _MHD_HEAVY_TESTS */
+  }
+  if (0 != errorCount)
+    fprintf (stderr,
+             "Error (code: %u)\n",
+             errorCount);
+  else if (verbose)
+    printf ("All tests passed.\n");
+
+  test_global_cleanup ();
+
+  return (errorCount == 0) ? 0 : 1;       /* 0 == pass */
+}
diff --git a/src/testcurl/test_urlparse.c b/src/testcurl/test_urlparse.c
index c48bff2..bc7b2a0 100644
--- a/src/testcurl/test_urlparse.c
+++ b/src/testcurl/test_urlparse.c
@@ -1,6 +1,7 @@
 /*
      This file is part of libmicrohttpd
      Copyright (C) 2007, 2009, 2011 Christian Grothoff
+     Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,14 +15,15 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
  * @file daemontest_urlparse.c
  * @brief  Testcase for libmicrohttpd url parsing
  * @author Christian Grothoff
+ * @author Karlson2k (Evgeny Grin)
  */
 
 #include "MHD_config.h"
@@ -31,6 +33,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include "mhd_has_in_name.h"
 
 #ifdef _WIN32
 #ifndef WIN32_LEAN_AND_MEAN
@@ -67,12 +70,14 @@
   return size * nmemb;
 }
 
-static int 
+
+static enum MHD_Result
 test_values (void *cls,
-	     enum MHD_ValueKind kind,
-	     const char *key,
-	     const char *value)
+             enum MHD_ValueKind kind,
+             const char *key,
+             const char *value)
 {
+  (void) cls; (void) kind;         /* Unused. Silent compiler warning. */
   if ( (0 == strcmp (key, "a")) &&
        (0 == strcmp (value, "b")) )
     matches += 1;
@@ -85,35 +90,36 @@
   return MHD_YES;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
-  const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
-  if (0 != strcmp (me, method))
+  if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
   MHD_get_connection_values (connection,
-			     MHD_GET_ARGUMENT_KIND,
-			     &test_values,
-			     NULL);
-  *unused = NULL;
-  response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+                             MHD_GET_ARGUMENT_KIND,
+                             &test_values,
+                             NULL);
+  *req_cls = NULL;
+  response = MHD_create_response_from_buffer_copy (strlen (url),
+                                                   (const void *) url);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
@@ -122,27 +128,49 @@
 }
 
 
-static int
-testInternalGet (int poll_flag)
+static unsigned int
+testInternalGet (uint32_t poll_flag)
 {
   struct MHD_Daemon *d;
   CURL *c;
   char buf[2048];
   struct CBC cbc;
   CURLcode errornum;
+  uint16_t port;
+
+  if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
+    port = 0;
+  else
+  {
+    port = 1510;
+    if (oneone)
+      port += 5;
+  }
 
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG  | poll_flag,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG
+                        | (enum MHD_FLAG) poll_flag,
+                        port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
   if (d == NULL)
     return 1;
+  if (0 == port)
+  {
+    const union MHD_DaemonInfo *dinfo;
+    dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
+    if ((NULL == dinfo) || (0 == dinfo->port) )
+    {
+      MHD_stop_daemon (d); return 32;
+    }
+    port = dinfo->port;
+  }
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11080/hello_world?a=b&c=&d");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world?a=b&c=&d");
+  curl_easy_setopt (c, CURLOPT_PORT, (long) port);
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L);
   if (oneone)
@@ -152,16 +180,16 @@
   /* NOTE: use of CONNECTTIMEOUT without also
      setting NOSIGNAL results in really weird
      crashes on my system!*/
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 2;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 2;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -178,14 +206,16 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  if ((NULL == argv) || (0 == argv[0]))
+    return 99;
+  oneone = has_in_name (argv[0], "11");
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   errorCount += testInternalGet (0);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testspdy/Makefile.am b/src/testspdy/Makefile.am
deleted file mode 100644
index 9d78bec..0000000
--- a/src/testspdy/Makefile.am
+++ /dev/null
@@ -1,115 +0,0 @@
-# This Makefile.am is in the public domain
-SUBDIRS  = .
-
-AM_CFLAGS = -DDATA_DIR=\"$(top_srcdir)/src/datadir/\"
-
-if USE_COVERAGE
-  AM_CFLAGS += -fprofile-arcs -ftest-coverage
-endif
-
-AM_CPPFLAGS = \
- -I$(top_srcdir) \
- -I$(top_srcdir)/src/include \
- -I$(top_srcdir)/src/applicationlayer \
- $(LIBCURL_CPPFLAGS)
-
-if !HAVE_W32
-PERF_GET_CONCURRENT=perf_get_concurrent
-endif
-
-if ENABLE_SPDY
-if HAVE_OPENSSL
-check_PROGRAMS = \
-  test_daemon_start_stop \
-  test_daemon_start_stop_many \
-  test_struct_namevalue
-
-if HAVE_SPDYLAY  
-check_PROGRAMS += \
-  test_new_connection  \
-  test_request_response \
-  test_notls \
-  test_request_response_with_callback \
-  test_misc \
-  test_session_timeout
-  #test_requests_with_assets 
-if HAVE_CURL_BINARY
-check_PROGRAMS +=  \
-  test_proxies
-endif 
-endif
-endif 
-endif 
-
-
-TESTS = $(check_PROGRAMS)
-
-
-SPDY_SOURCES= \
- common.h common.c
-
-SPDY_LDADD=  \
- $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-test_daemon_start_stop_SOURCES = \
- test_daemon_start_stop.c \
- $(SPDY_SOURCES) 
-test_daemon_start_stop_LDADD =  $(SPDY_LDADD)
-
-test_daemon_start_stop_many_SOURCES = \
- test_daemon_start_stop_many.c  \
- $(SPDY_SOURCES) 
-test_daemon_start_stop_many_LDADD = $(SPDY_LDADD)
-
-test_struct_namevalue_SOURCES = \
- test_struct_namevalue.c  \
- $(SPDY_SOURCES) 
-test_struct_namevalue_LDADD = $(SPDY_LDADD)
-
-if HAVE_SPDYLAY
-test_new_connection_SOURCES = \
- test_new_connection.c  \
- $(SPDY_SOURCES) 
-test_new_connection_LDADD = $(SPDY_LDADD) \
- -lspdylay
-
-test_request_response_SOURCES = \
- test_request_response.c  \
- $(SPDY_SOURCES) 
-test_request_response_LDADD = $(SPDY_LDADD) \
- -lspdylay
-
-test_notls_SOURCES = \
- test_notls.c  \
- $(SPDY_SOURCES) 
-test_notls_LDADD = $(SPDY_LDADD) \
- -lspdylay
-
-test_request_response_with_callback_SOURCES = \
- test_request_response_with_callback.c  \
- $(SPDY_SOURCES) 
-test_request_response_with_callback_LDADD = $(SPDY_LDADD)
-
-#test_requests_with_assets_SOURCES = \
-# test_requests_with_assets.c  \
-# $(SPDY_SOURCES) 
-#test_requests_with_assets_LDADD = $(SPDY_LDADD)
-
-test_misc_SOURCES = \
- test_misc.c  \
- $(SPDY_SOURCES) 
-test_misc_LDADD = $(SPDY_LDADD)
-
-test_session_timeout_SOURCES = \
- test_session_timeout.c  \
- $(SPDY_SOURCES) 
-test_session_timeout_LDADD = $(SPDY_LDADD)
-
-
-test_proxies_SOURCES = \
- test_proxies.c \
- $(SPDY_SOURCES) 
-test_proxies_LDADD = $(SPDY_LDADD)
-
-endif
diff --git a/src/testspdy/Makefile.in b/src/testspdy/Makefile.in
deleted file mode 100644
index 937e793..0000000
--- a/src/testspdy/Makefile.in
+++ /dev/null
@@ -1,1402 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-@USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@check_PROGRAMS = test_daemon_start_stop$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@	test_daemon_start_stop_many$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@	test_struct_namevalue$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@	$(am__EXEEXT_1) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@	$(am__EXEEXT_2)
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@am__append_2 = \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_new_connection  \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_request_response \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_notls \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_request_response_with_callback \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_misc \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_session_timeout
-
-@ENABLE_SPDY_TRUE@@HAVE_CURL_BINARY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@am__append_3 = \
-@ENABLE_SPDY_TRUE@@HAVE_CURL_BINARY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  test_proxies
-
-subdir = src/testspdy
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp $(top_srcdir)/test-driver
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@am__EXEEXT_1 = test_new_connection$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@	test_request_response$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@	test_notls$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@	test_request_response_with_callback$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@	test_misc$(EXEEXT) \
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@	test_session_timeout$(EXEEXT)
-@ENABLE_SPDY_TRUE@@HAVE_CURL_BINARY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@am__EXEEXT_2 = test_proxies$(EXEEXT)
-am__objects_1 = common.$(OBJEXT)
-am_test_daemon_start_stop_OBJECTS = test_daemon_start_stop.$(OBJEXT) \
-	$(am__objects_1)
-test_daemon_start_stop_OBJECTS = $(am_test_daemon_start_stop_OBJECTS)
-am__DEPENDENCIES_1 = $(top_builddir)/src/microspdy/libmicrospdy.la
-test_daemon_start_stop_DEPENDENCIES = $(am__DEPENDENCIES_1)
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-am_test_daemon_start_stop_many_OBJECTS =  \
-	test_daemon_start_stop_many.$(OBJEXT) $(am__objects_1)
-test_daemon_start_stop_many_OBJECTS =  \
-	$(am_test_daemon_start_stop_many_OBJECTS)
-test_daemon_start_stop_many_DEPENDENCIES = $(am__DEPENDENCIES_1)
-am__test_misc_SOURCES_DIST = test_misc.c common.h common.c
-@HAVE_SPDYLAY_TRUE@am_test_misc_OBJECTS = test_misc.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_misc_OBJECTS = $(am_test_misc_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_misc_DEPENDENCIES = $(am__DEPENDENCIES_1)
-am__test_new_connection_SOURCES_DIST = test_new_connection.c common.h \
-	common.c
-@HAVE_SPDYLAY_TRUE@am_test_new_connection_OBJECTS =  \
-@HAVE_SPDYLAY_TRUE@	test_new_connection.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_new_connection_OBJECTS = $(am_test_new_connection_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_new_connection_DEPENDENCIES =  \
-@HAVE_SPDYLAY_TRUE@	$(am__DEPENDENCIES_1)
-am__test_notls_SOURCES_DIST = test_notls.c common.h common.c
-@HAVE_SPDYLAY_TRUE@am_test_notls_OBJECTS = test_notls.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_notls_OBJECTS = $(am_test_notls_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_notls_DEPENDENCIES = $(am__DEPENDENCIES_1)
-am__test_proxies_SOURCES_DIST = test_proxies.c common.h common.c
-@HAVE_SPDYLAY_TRUE@am_test_proxies_OBJECTS = test_proxies.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_proxies_OBJECTS = $(am_test_proxies_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_proxies_DEPENDENCIES = $(am__DEPENDENCIES_1)
-am__test_request_response_SOURCES_DIST = test_request_response.c \
-	common.h common.c
-@HAVE_SPDYLAY_TRUE@am_test_request_response_OBJECTS =  \
-@HAVE_SPDYLAY_TRUE@	test_request_response.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_request_response_OBJECTS = $(am_test_request_response_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_request_response_DEPENDENCIES =  \
-@HAVE_SPDYLAY_TRUE@	$(am__DEPENDENCIES_1)
-am__test_request_response_with_callback_SOURCES_DIST =  \
-	test_request_response_with_callback.c common.h common.c
-@HAVE_SPDYLAY_TRUE@am_test_request_response_with_callback_OBJECTS = test_request_response_with_callback.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_request_response_with_callback_OBJECTS =  \
-	$(am_test_request_response_with_callback_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_request_response_with_callback_DEPENDENCIES =  \
-@HAVE_SPDYLAY_TRUE@	$(am__DEPENDENCIES_1)
-am__test_session_timeout_SOURCES_DIST = test_session_timeout.c \
-	common.h common.c
-@HAVE_SPDYLAY_TRUE@am_test_session_timeout_OBJECTS =  \
-@HAVE_SPDYLAY_TRUE@	test_session_timeout.$(OBJEXT) \
-@HAVE_SPDYLAY_TRUE@	$(am__objects_1)
-test_session_timeout_OBJECTS = $(am_test_session_timeout_OBJECTS)
-@HAVE_SPDYLAY_TRUE@test_session_timeout_DEPENDENCIES =  \
-@HAVE_SPDYLAY_TRUE@	$(am__DEPENDENCIES_1)
-am_test_struct_namevalue_OBJECTS = test_struct_namevalue.$(OBJEXT) \
-	$(am__objects_1)
-test_struct_namevalue_OBJECTS = $(am_test_struct_namevalue_OBJECTS)
-test_struct_namevalue_DEPENDENCIES = $(am__DEPENDENCIES_1)
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(test_daemon_start_stop_SOURCES) \
-	$(test_daemon_start_stop_many_SOURCES) $(test_misc_SOURCES) \
-	$(test_new_connection_SOURCES) $(test_notls_SOURCES) \
-	$(test_proxies_SOURCES) $(test_request_response_SOURCES) \
-	$(test_request_response_with_callback_SOURCES) \
-	$(test_session_timeout_SOURCES) \
-	$(test_struct_namevalue_SOURCES)
-DIST_SOURCES = $(test_daemon_start_stop_SOURCES) \
-	$(test_daemon_start_stop_many_SOURCES) \
-	$(am__test_misc_SOURCES_DIST) \
-	$(am__test_new_connection_SOURCES_DIST) \
-	$(am__test_notls_SOURCES_DIST) \
-	$(am__test_proxies_SOURCES_DIST) \
-	$(am__test_request_response_SOURCES_DIST) \
-	$(am__test_request_response_with_callback_SOURCES_DIST) \
-	$(am__test_session_timeout_SOURCES_DIST) \
-	$(test_struct_namevalue_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	check recheck distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-am__tty_colors_dummy = \
-  mgn= red= grn= lgn= blu= brg= std=; \
-  am__color_tests=no
-am__tty_colors = { \
-  $(am__tty_colors_dummy); \
-  if test "X$(AM_COLOR_TESTS)" = Xno; then \
-    am__color_tests=no; \
-  elif test "X$(AM_COLOR_TESTS)" = Xalways; then \
-    am__color_tests=yes; \
-  elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \
-    am__color_tests=yes; \
-  fi; \
-  if test $$am__color_tests = yes; then \
-    red=''; \
-    grn=''; \
-    lgn=''; \
-    blu=''; \
-    mgn=''; \
-    brg=''; \
-    std=''; \
-  fi; \
-}
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__recheck_rx = ^[ 	]*:recheck:[ 	]*
-am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
-am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
-# A command that, given a newline-separated list of test names on the
-# standard input, print the name of the tests that are to be re-run
-# upon "make recheck".
-am__list_recheck_tests = $(AWK) '{ \
-  recheck = 1; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-        { \
-          if ((getline line2 < ($$0 ".log")) < 0) \
-	    recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \
-        { \
-          recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \
-        { \
-          break; \
-        } \
-    }; \
-  if (recheck) \
-    print $$0; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# A command that, given a newline-separated list of test names on the
-# standard input, create the global log from their .trs and .log files.
-am__create_global_log = $(AWK) ' \
-function fatal(msg) \
-{ \
-  print "fatal: making $@: " msg | "cat >&2"; \
-  exit 1; \
-} \
-function rst_section(header) \
-{ \
-  print header; \
-  len = length(header); \
-  for (i = 1; i <= len; i = i + 1) \
-    printf "="; \
-  printf "\n\n"; \
-} \
-{ \
-  copy_in_global_log = 1; \
-  global_test_result = "RUN"; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-         fatal("failed to read from " $$0 ".trs"); \
-      if (line ~ /$(am__global_test_result_rx)/) \
-        { \
-          sub("$(am__global_test_result_rx)", "", line); \
-          sub("[ 	]*$$", "", line); \
-          global_test_result = line; \
-        } \
-      else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \
-        copy_in_global_log = 0; \
-    }; \
-  if (copy_in_global_log) \
-    { \
-      rst_section(global_test_result ": " $$0); \
-      while ((rc = (getline line < ($$0 ".log"))) != 0) \
-      { \
-        if (rc < 0) \
-          fatal("failed to read from " $$0 ".log"); \
-        print line; \
-      }; \
-      printf "\n"; \
-    }; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# Restructured Text title.
-am__rst_title = { sed 's/.*/   &   /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; }
-# Solaris 10 'make', and several other traditional 'make' implementations,
-# pass "-e" to $(SHELL), and POSIX 2008 even requires this.  Work around it
-# by disabling -e (using the XSI extension "set +e") if it's set.
-am__sh_e_setup = case $$- in *e*) set +e;; esac
-# Default flags passed to test drivers.
-am__common_driver_flags = \
-  --color-tests "$$am__color_tests" \
-  --enable-hard-errors "$$am__enable_hard_errors" \
-  --expect-failure "$$am__expect_failure"
-# To be inserted before the command running the test.  Creates the
-# directory for the log if needed.  Stores in $dir the directory
-# containing $f, in $tst the test, in $log the log.  Executes the
-# developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and
-# passes TESTS_ENVIRONMENT.  Set up options for the wrapper that
-# will run the test scripts (or their associated LOG_COMPILER, if
-# thy have one).
-am__check_pre = \
-$(am__sh_e_setup);					\
-$(am__vpath_adj_setup) $(am__vpath_adj)			\
-$(am__tty_colors);					\
-srcdir=$(srcdir); export srcdir;			\
-case "$@" in						\
-  */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;;	\
-    *) am__odir=.;; 					\
-esac;							\
-test "x$$am__odir" = x"." || test -d "$$am__odir" 	\
-  || $(MKDIR_P) "$$am__odir" || exit $$?;		\
-if test -f "./$$f"; then dir=./;			\
-elif test -f "$$f"; then dir=;				\
-else dir="$(srcdir)/"; fi;				\
-tst=$$dir$$f; log='$@'; 				\
-if test -n '$(DISABLE_HARD_ERRORS)'; then		\
-  am__enable_hard_errors=no; 				\
-else							\
-  am__enable_hard_errors=yes; 				\
-fi; 							\
-case " $(XFAIL_TESTS) " in				\
-  *[\ \	]$$f[\ \	]* | *[\ \	]$$dir$$f[\ \	]*) \
-    am__expect_failure=yes;;				\
-  *)							\
-    am__expect_failure=no;;				\
-esac; 							\
-$(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT)
-# A shell command to get the names of the tests scripts with any registered
-# extension removed (i.e., equivalently, the names of the test logs, with
-# the '.log' extension removed).  The result is saved in the shell variable
-# '$bases'.  This honors runtime overriding of TESTS and TEST_LOGS.  Sadly,
-# we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)",
-# since that might cause problem with VPATH rewrites for suffix-less tests.
-# See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'.
-am__set_TESTS_bases = \
-  bases='$(TEST_LOGS)'; \
-  bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \
-  bases=`echo $$bases`
-RECHECK_LOGS = $(TEST_LOGS)
-TEST_SUITE_LOG = test-suite.log
-TEST_EXTENSIONS = @EXEEXT@ .test
-LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)
-am__set_b = \
-  case '$@' in \
-    */*) \
-      case '$*' in \
-        */*) b='$*';; \
-          *) b=`echo '$@' | sed 's/\.log$$//'`; \
-       esac;; \
-    *) \
-      b='$*';; \
-  esac
-am__test_logs1 = $(TESTS:=.log)
-am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log)
-TEST_LOGS = $(am__test_logs2:.test.log=.log)
-TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
-	$(TEST_LOG_FLAGS)
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-AM_CFLAGS = -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" $(am__append_1)
-AM_CPPFLAGS = \
- -I$(top_srcdir) \
- -I$(top_srcdir)/src/include \
- -I$(top_srcdir)/src/applicationlayer \
- $(LIBCURL_CPPFLAGS)
-
-@HAVE_W32_FALSE@PERF_GET_CONCURRENT = perf_get_concurrent
-TESTS = $(check_PROGRAMS)
-SPDY_SOURCES = \
- common.h common.c
-
-SPDY_LDADD = \
- $(top_builddir)/src/microspdy/libmicrospdy.la \
- -lz
-
-test_daemon_start_stop_SOURCES = \
- test_daemon_start_stop.c \
- $(SPDY_SOURCES) 
-
-test_daemon_start_stop_LDADD = $(SPDY_LDADD)
-test_daemon_start_stop_many_SOURCES = \
- test_daemon_start_stop_many.c  \
- $(SPDY_SOURCES) 
-
-test_daemon_start_stop_many_LDADD = $(SPDY_LDADD)
-test_struct_namevalue_SOURCES = \
- test_struct_namevalue.c  \
- $(SPDY_SOURCES) 
-
-test_struct_namevalue_LDADD = $(SPDY_LDADD)
-@HAVE_SPDYLAY_TRUE@test_new_connection_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_new_connection.c  \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_new_connection_LDADD = $(SPDY_LDADD) \
-@HAVE_SPDYLAY_TRUE@ -lspdylay
-
-@HAVE_SPDYLAY_TRUE@test_request_response_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_request_response.c  \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_request_response_LDADD = $(SPDY_LDADD) \
-@HAVE_SPDYLAY_TRUE@ -lspdylay
-
-@HAVE_SPDYLAY_TRUE@test_notls_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_notls.c  \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_notls_LDADD = $(SPDY_LDADD) \
-@HAVE_SPDYLAY_TRUE@ -lspdylay
-
-@HAVE_SPDYLAY_TRUE@test_request_response_with_callback_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_request_response_with_callback.c  \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_request_response_with_callback_LDADD = $(SPDY_LDADD)
-
-#test_requests_with_assets_SOURCES = \
-# test_requests_with_assets.c  \
-# $(SPDY_SOURCES) 
-#test_requests_with_assets_LDADD = $(SPDY_LDADD)
-@HAVE_SPDYLAY_TRUE@test_misc_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_misc.c  \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_misc_LDADD = $(SPDY_LDADD)
-@HAVE_SPDYLAY_TRUE@test_session_timeout_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_session_timeout.c  \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_session_timeout_LDADD = $(SPDY_LDADD)
-@HAVE_SPDYLAY_TRUE@test_proxies_SOURCES = \
-@HAVE_SPDYLAY_TRUE@ test_proxies.c \
-@HAVE_SPDYLAY_TRUE@ $(SPDY_SOURCES) 
-
-@HAVE_SPDYLAY_TRUE@test_proxies_LDADD = $(SPDY_LDADD)
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testspdy/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/testspdy/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-checkPROGRAMS:
-	@list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-test_daemon_start_stop$(EXEEXT): $(test_daemon_start_stop_OBJECTS) $(test_daemon_start_stop_DEPENDENCIES) $(EXTRA_test_daemon_start_stop_DEPENDENCIES) 
-	@rm -f test_daemon_start_stop$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_daemon_start_stop_OBJECTS) $(test_daemon_start_stop_LDADD) $(LIBS)
-
-test_daemon_start_stop_many$(EXEEXT): $(test_daemon_start_stop_many_OBJECTS) $(test_daemon_start_stop_many_DEPENDENCIES) $(EXTRA_test_daemon_start_stop_many_DEPENDENCIES) 
-	@rm -f test_daemon_start_stop_many$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_daemon_start_stop_many_OBJECTS) $(test_daemon_start_stop_many_LDADD) $(LIBS)
-
-test_misc$(EXEEXT): $(test_misc_OBJECTS) $(test_misc_DEPENDENCIES) $(EXTRA_test_misc_DEPENDENCIES) 
-	@rm -f test_misc$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_misc_OBJECTS) $(test_misc_LDADD) $(LIBS)
-
-test_new_connection$(EXEEXT): $(test_new_connection_OBJECTS) $(test_new_connection_DEPENDENCIES) $(EXTRA_test_new_connection_DEPENDENCIES) 
-	@rm -f test_new_connection$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_new_connection_OBJECTS) $(test_new_connection_LDADD) $(LIBS)
-
-test_notls$(EXEEXT): $(test_notls_OBJECTS) $(test_notls_DEPENDENCIES) $(EXTRA_test_notls_DEPENDENCIES) 
-	@rm -f test_notls$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_notls_OBJECTS) $(test_notls_LDADD) $(LIBS)
-
-test_proxies$(EXEEXT): $(test_proxies_OBJECTS) $(test_proxies_DEPENDENCIES) $(EXTRA_test_proxies_DEPENDENCIES) 
-	@rm -f test_proxies$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_proxies_OBJECTS) $(test_proxies_LDADD) $(LIBS)
-
-test_request_response$(EXEEXT): $(test_request_response_OBJECTS) $(test_request_response_DEPENDENCIES) $(EXTRA_test_request_response_DEPENDENCIES) 
-	@rm -f test_request_response$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_request_response_OBJECTS) $(test_request_response_LDADD) $(LIBS)
-
-test_request_response_with_callback$(EXEEXT): $(test_request_response_with_callback_OBJECTS) $(test_request_response_with_callback_DEPENDENCIES) $(EXTRA_test_request_response_with_callback_DEPENDENCIES) 
-	@rm -f test_request_response_with_callback$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_request_response_with_callback_OBJECTS) $(test_request_response_with_callback_LDADD) $(LIBS)
-
-test_session_timeout$(EXEEXT): $(test_session_timeout_OBJECTS) $(test_session_timeout_DEPENDENCIES) $(EXTRA_test_session_timeout_DEPENDENCIES) 
-	@rm -f test_session_timeout$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_session_timeout_OBJECTS) $(test_session_timeout_LDADD) $(LIBS)
-
-test_struct_namevalue$(EXEEXT): $(test_struct_namevalue_OBJECTS) $(test_struct_namevalue_DEPENDENCIES) $(EXTRA_test_struct_namevalue_DEPENDENCIES) 
-	@rm -f test_struct_namevalue$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_struct_namevalue_OBJECTS) $(test_struct_namevalue_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/common.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_daemon_start_stop.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_daemon_start_stop_many.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_misc.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_new_connection.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_notls.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_proxies.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_request_response.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_request_response_with_callback.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_session_timeout.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_struct_namevalue.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-# Recover from deleted '.trs' file; this should ensure that
-# "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create
-# both 'foo.log' and 'foo.trs'.  Break the recipe in two subshells
-# to avoid problems with "make -n".
-.log.trs:
-	rm -f $< $@
-	$(MAKE) $(AM_MAKEFLAGS) $<
-
-# Leading 'am--fnord' is there to ensure the list of targets does not
-# expand to empty, as could happen e.g. with make check TESTS=''.
-am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck)
-am--force-recheck:
-	@:
-
-$(TEST_SUITE_LOG): $(TEST_LOGS)
-	@$(am__set_TESTS_bases); \
-	am__f_ok () { test -f "$$1" && test -r "$$1"; }; \
-	redo_bases=`for i in $$bases; do \
-	              am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \
-	            done`; \
-	if test -n "$$redo_bases"; then \
-	  redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \
-	  redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \
-	  if $(am__make_dryrun); then :; else \
-	    rm -f $$redo_logs && rm -f $$redo_results || exit 1; \
-	  fi; \
-	fi; \
-	if test -n "$$am__remaking_logs"; then \
-	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
-	       "recursion detected" >&2; \
-	else \
-	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
-	fi; \
-	if $(am__make_dryrun); then :; else \
-	  st=0;  \
-	  errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \
-	  for i in $$redo_bases; do \
-	    test -f $$i.trs && test -r $$i.trs \
-	      || { echo "$$errmsg $$i.trs" >&2; st=1; }; \
-	    test -f $$i.log && test -r $$i.log \
-	      || { echo "$$errmsg $$i.log" >&2; st=1; }; \
-	  done; \
-	  test $$st -eq 0 || exit 1; \
-	fi
-	@$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \
-	ws='[ 	]'; \
-	results=`for b in $$bases; do echo $$b.trs; done`; \
-	test -n "$$results" || results=/dev/null; \
-	all=`  grep "^$$ws*:test-result:"           $$results | wc -l`; \
-	pass=` grep "^$$ws*:test-result:$$ws*PASS"  $$results | wc -l`; \
-	fail=` grep "^$$ws*:test-result:$$ws*FAIL"  $$results | wc -l`; \
-	skip=` grep "^$$ws*:test-result:$$ws*SKIP"  $$results | wc -l`; \
-	xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \
-	xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \
-	error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \
-	if test `expr $$fail + $$xpass + $$error` -eq 0; then \
-	  success=true; \
-	else \
-	  success=false; \
-	fi; \
-	br='==================='; br=$$br$$br$$br$$br; \
-	result_count () \
-	{ \
-	    if test x"$$1" = x"--maybe-color"; then \
-	      maybe_colorize=yes; \
-	    elif test x"$$1" = x"--no-color"; then \
-	      maybe_colorize=no; \
-	    else \
-	      echo "$@: invalid 'result_count' usage" >&2; exit 4; \
-	    fi; \
-	    shift; \
-	    desc=$$1 count=$$2; \
-	    if test $$maybe_colorize = yes && test $$count -gt 0; then \
-	      color_start=$$3 color_end=$$std; \
-	    else \
-	      color_start= color_end=; \
-	    fi; \
-	    echo "$${color_start}# $$desc $$count$${color_end}"; \
-	}; \
-	create_testsuite_report () \
-	{ \
-	  result_count $$1 "TOTAL:" $$all   "$$brg"; \
-	  result_count $$1 "PASS: " $$pass  "$$grn"; \
-	  result_count $$1 "SKIP: " $$skip  "$$blu"; \
-	  result_count $$1 "XFAIL:" $$xfail "$$lgn"; \
-	  result_count $$1 "FAIL: " $$fail  "$$red"; \
-	  result_count $$1 "XPASS:" $$xpass "$$red"; \
-	  result_count $$1 "ERROR:" $$error "$$mgn"; \
-	}; \
-	{								\
-	  echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" |	\
-	    $(am__rst_title);						\
-	  create_testsuite_report --no-color;				\
-	  echo;								\
-	  echo ".. contents:: :depth: 2";				\
-	  echo;								\
-	  for b in $$bases; do echo $$b; done				\
-	    | $(am__create_global_log);					\
-	} >$(TEST_SUITE_LOG).tmp || exit 1;				\
-	mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG);			\
-	if $$success; then						\
-	  col="$$grn";							\
-	 else								\
-	  col="$$red";							\
-	  test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG);		\
-	fi;								\
-	echo "$${col}$$br$${std}"; 					\
-	echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}";	\
-	echo "$${col}$$br$${std}"; 					\
-	create_testsuite_report --maybe-color;				\
-	echo "$$col$$br$$std";						\
-	if $$success; then :; else					\
-	  echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}";		\
-	  if test -n "$(PACKAGE_BUGREPORT)"; then			\
-	    echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}";	\
-	  fi;								\
-	  echo "$$col$$br$$std";					\
-	fi;								\
-	$$success || exit 1
-
-check-TESTS:
-	@list='$(RECHECK_LOGS)';           test -z "$$list" || rm -f $$list
-	@list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	trs_list=`for i in $$bases; do echo $$i.trs; done`; \
-	log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \
-	exit $$?;
-recheck: all $(check_PROGRAMS)
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	bases=`for i in $$bases; do echo $$i; done \
-	         | $(am__list_recheck_tests)` || exit 1; \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	log_list=`echo $$log_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \
-	        am__force_recheck=am--force-recheck \
-	        TEST_LOGS="$$log_list"; \
-	exit $$?
-test_daemon_start_stop.log: test_daemon_start_stop$(EXEEXT)
-	@p='test_daemon_start_stop$(EXEEXT)'; \
-	b='test_daemon_start_stop'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_daemon_start_stop_many.log: test_daemon_start_stop_many$(EXEEXT)
-	@p='test_daemon_start_stop_many$(EXEEXT)'; \
-	b='test_daemon_start_stop_many'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_struct_namevalue.log: test_struct_namevalue$(EXEEXT)
-	@p='test_struct_namevalue$(EXEEXT)'; \
-	b='test_struct_namevalue'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_new_connection.log: test_new_connection$(EXEEXT)
-	@p='test_new_connection$(EXEEXT)'; \
-	b='test_new_connection'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_request_response.log: test_request_response$(EXEEXT)
-	@p='test_request_response$(EXEEXT)'; \
-	b='test_request_response'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_notls.log: test_notls$(EXEEXT)
-	@p='test_notls$(EXEEXT)'; \
-	b='test_notls'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_request_response_with_callback.log: test_request_response_with_callback$(EXEEXT)
-	@p='test_request_response_with_callback$(EXEEXT)'; \
-	b='test_request_response_with_callback'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_misc.log: test_misc$(EXEEXT)
-	@p='test_misc$(EXEEXT)'; \
-	b='test_misc'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_session_timeout.log: test_session_timeout$(EXEEXT)
-	@p='test_session_timeout$(EXEEXT)'; \
-	b='test_session_timeout'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_proxies.log: test_proxies$(EXEEXT)
-	@p='test_proxies$(EXEEXT)'; \
-	b='test_proxies'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-.test.log:
-	@p='$<'; \
-	$(am__set_b); \
-	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-@am__EXEEXT_TRUE@.test$(EXEEXT).log:
-@am__EXEEXT_TRUE@	@p='$<'; \
-@am__EXEEXT_TRUE@	$(am__set_b); \
-@am__EXEEXT_TRUE@	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-@am__EXEEXT_TRUE@	--log-file $$b.log --trs-file $$b.trs \
-@am__EXEEXT_TRUE@	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-@am__EXEEXT_TRUE@	"$$tst" $(AM_TESTS_FD_REDIRECT)
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
-	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-	-test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS)
-	-test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs)
-	-test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-checkPROGRAMS clean-generic clean-libtool \
-	mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) check-am install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-TESTS check-am clean clean-checkPROGRAMS clean-generic \
-	clean-libtool cscopelist-am ctags ctags-am distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \
-	uninstall uninstall-am
-
-@ENABLE_SPDY_TRUE@@HAVE_OPENSSL_TRUE@@HAVE_SPDYLAY_TRUE@  #test_requests_with_assets 
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/testspdy/common.c b/src/testspdy/common.c
deleted file mode 100644
index e150209..0000000
--- a/src/testspdy/common.c
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file common.c
- * @brief  Common functions used by the tests.
- * @author Andrey Uzunov
- */
- 
-
-#include "common.h"
-#include <sys/time.h>
-
-#ifdef __GNUC__
-#define FUNC_CONSTRUCTOR(f) static void __attribute__ ((constructor)) f
-#define FUNC_DESTRUCTOR(f) static void __attribute__ ((destructor)) f
-#else  // !__GNUC__
-#define FUNC_CONSTRUCTOR(f) _MHD_EXTERN void f
-#define FUNC_DESTRUCTOR(f) _MHD_EXTERN void f
-#endif  // __GNUC__
-
-FUNC_CONSTRUCTOR (constructor)()
-{
-	printf("\nTEST START -------------------------------------------------------\n");
-}
-
-FUNC_DESTRUCTOR (destructor)()
-{
-	printf("------------------------------------------------------- TEST END\n");
-}
-
-uint16_t
-get_port(uint16_t min)
-{
-	struct timeval tv;
-	gettimeofday(&tv, NULL);
-	if(2 > min) min=2;
-	uint16_t port =  min + (tv.tv_usec+10) % ((1 << 16)  - min);
-	
-	//port = 12345;
-	printf("Port used: %i\n", port);
-	
-	return port;
-}
diff --git a/src/testspdy/common.h b/src/testspdy/common.h
deleted file mode 100644
index 70ee261..0000000
--- a/src/testspdy/common.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file common.h
- * @brief  Common functions used by the tests.
- * @author Andrey Uzunov
- */
- 
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdint.h>
-#include <stdio.h>
-
-#define FAIL_TEST(msg) do{\
-	printf("%i:%s\n", __LINE__, msg);\
-	fflush(stdout);\
-	exit(-10);\
-	}\
-	while(0)
-	
-uint16_t
-get_port(uint16_t min);
diff --git a/src/testspdy/test_daemon_start_stop.c b/src/testspdy/test_daemon_start_stop.c
deleted file mode 100644
index d3aec6a..0000000
--- a/src/testspdy/test_daemon_start_stop.c
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file daemon_start_stop.c
- * @brief  starts and stops a SPDY daemon
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "common.h"
-
-int
-main()
-{
-	SPDY_init();
-	
-	struct SPDY_Daemon *daemon = SPDY_start_daemon(get_port(16123),
-	 DATA_DIR "cert-and-key.pem",
-	 DATA_DIR "cert-and-key.pem",
-	NULL,NULL,NULL,NULL,NULL,SPDY_DAEMON_OPTION_END);
-	
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-	
-	SPDY_stop_daemon(daemon);
-	
-	SPDY_deinit();
-	
-	return 0;
-}
diff --git a/src/testspdy/test_daemon_start_stop_many.c b/src/testspdy/test_daemon_start_stop_many.c
deleted file mode 100644
index b8788de..0000000
--- a/src/testspdy/test_daemon_start_stop_many.c
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file daemon_start_stop_many.c
- * @brief  starts and stops several SPDY daemons, reusing port numbers
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "common.h"
-
-int
-main()
-{
-	int i;
-	int j;
-	int num_daemons = 3;
-	int num_tries = 5;
-	int port = get_port(15123);
-	struct SPDY_Daemon *daemon[num_daemons];
-	
-	SPDY_init();
-	
-	for(i=0; i<num_tries; ++i)
-	{
-		for(j=0;j<num_daemons;++j)
-		{
-			daemon[j] = SPDY_start_daemon(port + j,
-			DATA_DIR "cert-and-key.pem",
-			DATA_DIR "cert-and-key.pem",
-			NULL,NULL,NULL,NULL,NULL,SPDY_DAEMON_OPTION_END);
-	
-			if(NULL==daemon[j]){
-				printf("no daemon\n");
-				return 1;
-			}
-		}
-		
-		
-		for(j=0;j<num_daemons;++j)
-		{
-			SPDY_stop_daemon(daemon[j]);
-		}
-	}
-	
-	SPDY_deinit();
-	
-	return 0;
-}
diff --git a/src/testspdy/test_misc.c b/src/testspdy/test_misc.c
deleted file mode 100644
index 39b672b..0000000
--- a/src/testspdy/test_misc.c
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file misc.c
- * @brief  tests a lot of small calls and callbacks. TODO mention what
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "stdio.h"
-#include <sys/wait.h>
-#include "common.h"
-
-int port;
-
-#define HTML "<html><head>\
-<link href=\"main.css\" rel=\"stylesheet\" type=\"text/css\" />\
-</head><body>This is libmicrospdy</body></html>"
-
-#define CSS "body{font-size:15px}"
-
-#define SESSION_CLS "1234567890"
-
-#define REQUEST_CLS "1234567890REQ"
-
-pid_t parent;
-pid_t child;
-
-struct SPDY_Session *session1;
-struct SPDY_Session *session2;
-
-void
-killchild()
-{
-	kill(child, SIGKILL);
-	exit(1);
-}
-
-void
-killparent()
-{
-	kill(parent, SIGKILL);
-	_exit(1);
-}
-
-
-void
-create_child()
-{
-	parent = getpid();
-
-	child = fork();
-	if (-1 == child)
-	{
-		fprintf(stderr, "can't fork, error %d\n", errno);
-		exit(EXIT_FAILURE);
-	}
-
-	if (child == 0)
-	{
-		int devnull;
-		char *uri;
-		fflush(stdout);
-		devnull = open("/dev/null", O_WRONLY);
-                if (-1 == devnull)
-                  abort ();
-		if (1 != devnull)
-		{
-			dup2(devnull, 1);
-			close(devnull);
-		}
-		asprintf(&uri,"https://127.0.0.1:%i/",port);
-		execlp("spdycat", "spdycat","-anv",uri,NULL );
-		printf("execlp failed\n");
-		killparent();
-	}
-}
-
-void
-response_done_callback(void *cls,
-								struct SPDY_Response * response,
-								struct SPDY_Request * request,
-								enum SPDY_RESPONSE_RESULT status,
-						bool streamopened)
-{
-  (void)status;
-  (void)streamopened;
-
-	if(strcmp(cls,"/main.css"))
-	{
-		session1 = SPDY_get_session_for_request(request);
-		if(NULL == session1)
-		{
-			printf("SPDY_get_session_for_request failed\n");
-			killchild();
-		}
-
-		char *session_cls = strdup(SESSION_CLS);
-		SPDY_set_cls_to_session(session1,session_cls);
-	}
-	else
-	{
-		session2 = SPDY_get_session_for_request(request);
-		if(session1 != session2)
-		{
-			printf("SPDY_get_session_for_request failed the second time\n");
-			killchild();
-		}
-		printf("SPDY_get_session_for_request tested...\n");
-
-		void *session_cls = SPDY_get_cls_from_session(session2);
-		if(NULL == session_cls || strcmp(session_cls, SESSION_CLS))
-		{
-			printf("SPDY_get_cls_from_session failed\n");
-			killchild();
-		}
-		printf("SPDY_set_cls_to_session tested...\n");
-		printf("SPDY_get_cls_from_session tested...\n");
-
-		void *request_cls = SPDY_get_cls_from_request(request);
-		if(NULL == request_cls || strcmp(request_cls, REQUEST_CLS))
-		{
-			printf("SPDY_get_cls_from_request failed\n");
-			killchild();
-		}
-		printf("SPDY_set_cls_to_request tested...\n");
-		printf("SPDY_get_cls_from_request tested...\n");
-	}
-
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-	free(cls);
-}
-
-void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-	(void)cls;
-	(void)request;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-	(void)headers;
-	(void)method;
-	(void)version;
-	(void)more;
-
-	struct SPDY_Response *response=NULL;
-	char *cls_path = strdup(path);
-
-	if(strcmp(path,"/main.css")==0)
-	{
-		char *request_cls = strdup(REQUEST_CLS);
-		SPDY_set_cls_to_request(request,request_cls);
-		response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,CSS,strlen(CSS));
-	}
-	else
-	{
-		response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,HTML,strlen(HTML));
-	}
-
-	if(NULL==response){
-		fprintf(stdout,"no response obj\n");
-		killchild();
-	}
-
-	if(SPDY_queue_response(request,response,true,false,&response_done_callback,cls_path)!=SPDY_YES)
-	{
-		fprintf(stdout,"queue\n");
-		killchild();
-	}
-}
-
-int
-parentproc()
-{
-	int childstatus;
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-
-	daemon = SPDY_start_daemon(port,
-								DATA_DIR "cert-and-key.pem",
-								DATA_DIR "cert-and-key.pem",
-								NULL,
-								NULL,
-								&standard_request_handler,
-								NULL,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								1800,
-								SPDY_DAEMON_OPTION_END);
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	create_child();
-
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set,
-								&except_fd_set);
-
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(waitpid(child,&childstatus,WNOHANG) != child);
-
-	SPDY_stop_daemon(daemon);
-
-	return WEXITSTATUS(childstatus);
-}
-
-
-int
-main()
-{
-	port = get_port(13123);
-	SPDY_init();
-
-	int ret = parentproc();
-
-	SPDY_deinit();
-
-	return ret;
-}
diff --git a/src/testspdy/test_new_connection.c b/src/testspdy/test_new_connection.c
deleted file mode 100644
index b848572..0000000
--- a/src/testspdy/test_new_connection.c
+++ /dev/null
@@ -1,1009 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file request_response.c
- * @brief  tests new connection callback. spdycli.c
- * 			code is reused here
- * @author Andrey Uzunov
- * @author Tatsuhiro Tsujikawa
- */
-
-//TODO child exits with ret val 1 sometimes
-
-#include "platform.h"
-#include "microspdy.h"
-#include <sys/wait.h>
-#include "common.h"
-
-#define RESPONSE_BODY "<html><body><b>Hi, this is libmicrospdy!</b></body></html>"
-
-#define CLS "anything"
-
-int port;
-int loop = 1;
-
-pid_t parent;
-pid_t child;
-
-int
-spdylay_printf(const char *format, ...)
-{
-  (void)format;
-
-	return 0;
-}
-
-int
-spdylay_fprintf(FILE *stream, const char *format, ...)
-{
-  (void)stream;
-  (void)format;
-
-	return 0;
-}
-
-void
-killchild(int pid, char *message)
-{
-	printf("%s\n",message);
-	kill(pid, SIGKILL);
-	exit(1);
-}
-
-void
-killparent(int pid, char *message)
-{
-	printf("%s\n",message);
-	kill(pid, SIGKILL);
-	_exit(2);
-}
-
-
-/*****
- * start of code needed to utilize spdylay
- */
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <poll.h>
-#include <signal.h>
-#include <stdio.h>
-#include <assert.h>
-
-#include <spdylay/spdylay.h>
-
-#include <openssl/ssl.h>
-#include <openssl/err.h>
-
-enum {
-  IO_NONE,
-  WANT_READ,
-  WANT_WRITE
-};
-
-struct Connection {
-  SSL *ssl;
-  spdylay_session *session;
-  /* WANT_READ if SSL connection needs more input; or WANT_WRITE if it
-     needs more output; or IO_NONE. This is necessary because SSL/TLS
-     re-negotiation is possible at any time. Spdylay API offers
-     similar functions like spdylay_session_want_read() and
-     spdylay_session_want_write() but they do not take into account
-     SSL connection. */
-  int want_io;
-};
-
-struct Request {
-  char *host;
-  uint16_t port;
-  /* In this program, path contains query component as well. */
-  char *path;
-  /* This is the concatenation of host and port with ":" in
-     between. */
-  char *hostport;
-  /* Stream ID for this request. */
-  int32_t stream_id;
-  /* The gzip stream inflater for the compressed response. */
-  spdylay_gzip *inflater;
-};
-
-struct URI {
-  const char *host;
-  size_t hostlen;
-  uint16_t port;
-  /* In this program, path contains query component as well. */
-  const char *path;
-  size_t pathlen;
-  const char *hostport;
-  size_t hostportlen;
-};
-
-/*
- * Returns copy of string |s| with the length |len|. The returned
- * string is NULL-terminated.
- */
-static char* strcopy(const char *s, size_t len)
-{
-  char *dst;
-  dst = malloc(len+1);
-  if (NULL == dst)
-    abort ();
-  memcpy(dst, s, len);
-  dst[len] = '\0';
-  return dst;
-}
-
-/*
- * Prints error message |msg| and exit.
- */
-static void die(const char *msg)
-{
-  fprintf(stderr, "FATAL: %s\n", msg);
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Prints error containing the function name |func| and message |msg|
- * and exit.
- */
-static void dief(const char *func, const char *msg)
-{
-  fprintf(stderr, "FATAL: %s: %s\n", func, msg);
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Prints error containing the function name |func| and error code
- * |error_code| and exit.
- */
-static void diec(const char *func, int error_code)
-{
-  fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
-          spdylay_strerror(error_code));
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Check response is content-encoding: gzip. We need this because SPDY
- * client is required to support gzip.
- */
-static void check_gzip(struct Request *req, char **nv)
-{
-  int gzip = 0;
-  size_t i;
-  for(i = 0; nv[i]; i += 2) {
-    if(strcmp("content-encoding", nv[i]) == 0) {
-      gzip = strcmp("gzip", nv[i+1]) == 0;
-      break;
-    }
-  }
-  if(gzip) {
-    int rv;
-    if(req->inflater) {
-      return;
-    }
-    rv = spdylay_gzip_inflate_new(&req->inflater);
-    if(rv != 0) {
-      die("Can't allocate inflate stream.");
-    }
-  }
-}
-
-/*
- * The implementation of spdylay_send_callback type. Here we write
- * |data| with size |length| to the network and return the number of
- * bytes actually written. See the documentation of
- * spdylay_send_callback for the details.
- */
-static ssize_t send_callback(spdylay_session *session,
-                             const uint8_t *data, size_t length, int flags,
-                             void *user_data)
-{
-  (void)session;
-  (void)flags;
-
-  struct Connection *connection;
-  ssize_t rv;
-  connection = (struct Connection*)user_data;
-  connection->want_io = IO_NONE;
-  ERR_clear_error();
-  rv = SSL_write(connection->ssl, data, length);
-  if(rv < 0) {
-    int err = SSL_get_error(connection->ssl, rv);
-    if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
-      connection->want_io = (err == SSL_ERROR_WANT_READ ?
-                             WANT_READ : WANT_WRITE);
-      rv = SPDYLAY_ERR_WOULDBLOCK;
-    } else {
-      rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-    }
-  }
-  return rv;
-}
-
-/*
- * The implementation of spdylay_recv_callback type. Here we read data
- * from the network and write them in |buf|. The capacity of |buf| is
- * |length| bytes. Returns the number of bytes stored in |buf|. See
- * the documentation of spdylay_recv_callback for the details.
- */
-static ssize_t recv_callback(spdylay_session *session,
-                             uint8_t *buf, size_t length, int flags,
-                             void *user_data)
-{
-  (void)session;
-  (void)flags;
-
-  struct Connection *connection;
-  ssize_t rv;
-  connection = (struct Connection*)user_data;
-  connection->want_io = IO_NONE;
-  ERR_clear_error();
-  rv = SSL_read(connection->ssl, buf, length);
-  if(rv < 0) {
-    int err = SSL_get_error(connection->ssl, rv);
-    if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
-      connection->want_io = (err == SSL_ERROR_WANT_READ ?
-                             WANT_READ : WANT_WRITE);
-      rv = SPDYLAY_ERR_WOULDBLOCK;
-    } else {
-      rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-    }
-  } else if(rv == 0) {
-    rv = SPDYLAY_ERR_EOF;
-  }
-  return rv;
-}
-
-/*
- * The implementation of spdylay_before_ctrl_send_callback type.  We
- * use this function to get stream ID of the request. This is because
- * stream ID is not known when we submit the request
- * (spdylay_submit_request).
- */
-static void before_ctrl_send_callback(spdylay_session *session,
-                                      spdylay_frame_type type,
-                                      spdylay_frame *frame,
-                                      void *user_data)
-{
-  (void)user_data;
-
-  if(type == SPDYLAY_SYN_STREAM) {
-    struct Request *req;
-    int stream_id = frame->syn_stream.stream_id;
-    req = spdylay_session_get_stream_user_data(session, stream_id);
-    if(req && req->stream_id == -1) {
-      req->stream_id = stream_id;
-      spdylay_printf("[INFO] Stream ID = %d\n", stream_id);
-    }
-  }
-}
-
-static void on_ctrl_send_callback(spdylay_session *session,
-                                  spdylay_frame_type type,
-                                  spdylay_frame *frame, void *user_data)
-{
-  (void)user_data;
-
-  char **nv;
-  const char *name = NULL;
-  int32_t stream_id;
-  size_t i;
-  switch(type) {
-  case SPDYLAY_SYN_STREAM:
-    nv = frame->syn_stream.nv;
-    name = "SYN_STREAM";
-    stream_id = frame->syn_stream.stream_id;
-    break;
-  default:
-    break;
-  }
-  if(name && spdylay_session_get_stream_user_data(session, stream_id)) {
-    spdylay_printf("[INFO] C ----------------------------> S (%s)\n", name);
-    for(i = 0; nv[i]; i += 2) {
-      spdylay_printf("       %s: %s\n", nv[i], nv[i+1]);
-    }
-  }
-}
-
-static void on_ctrl_recv_callback(spdylay_session *session,
-                                  spdylay_frame_type type,
-                                  spdylay_frame *frame, void *user_data)
-{
-  (void)user_data;
-
-  struct Request *req;
-  char **nv;
-  const char *name = NULL;
-  int32_t stream_id;
-  size_t i;
-  switch(type) {
-  case SPDYLAY_SYN_REPLY:
-    nv = frame->syn_reply.nv;
-    name = "SYN_REPLY";
-    stream_id = frame->syn_reply.stream_id;
-    break;
-  case SPDYLAY_HEADERS:
-    nv = frame->headers.nv;
-    name = "HEADERS";
-    stream_id = frame->headers.stream_id;
-    break;
-  default:
-    break;
-  }
-  if(!name) {
-    return;
-  }
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    check_gzip(req, nv);
-    spdylay_printf("[INFO] C <---------------------------- S (%s)\n", name);
-    for(i = 0; nv[i]; i += 2) {
-      spdylay_printf("       %s: %s\n", nv[i], nv[i+1]);
-    }
-  }
-}
-
-/*
- * The implementation of spdylay_on_stream_close_callback type. We use
- * this function to know the response is fully received. Since we just
- * fetch 1 resource in this program, after reception of the response,
- * we submit GOAWAY and close the session.
- */
-static void on_stream_close_callback(spdylay_session *session,
-                                     int32_t stream_id,
-                                     spdylay_status_code status_code,
-                                     void *user_data)
-{
-  (void)user_data;
-  (void)status_code;
-  struct Request *req;
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    int rv;
-    rv = spdylay_submit_goaway(session, SPDYLAY_GOAWAY_OK);
-    if(rv != 0) {
-      diec("spdylay_submit_goaway", rv);
-    }
-  }
-}
-
-#define MAX_OUTLEN 4096
-
-/*
- * The implementation of spdylay_on_data_chunk_recv_callback type. We
- * use this function to print the received response body.
- */
-static void on_data_chunk_recv_callback(spdylay_session *session, uint8_t flags,
-                                        int32_t stream_id,
-                                        const uint8_t *data, size_t len,
-                                        void *user_data)
-{
-  (void)user_data;
-  (void)flags;
-
-  struct Request *req;
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    spdylay_printf("[INFO] C <---------------------------- S (DATA)\n");
-    spdylay_printf("       %lu bytes\n", (unsigned long int)len);
-    if(req->inflater) {
-      while(len > 0) {
-        uint8_t out[MAX_OUTLEN];
-        size_t outlen = MAX_OUTLEN;
-        size_t tlen = len;
-        int rv;
-        rv = spdylay_gzip_inflate(req->inflater, out, &outlen, data, &tlen);
-        if(rv == -1) {
-          spdylay_submit_rst_stream(session, stream_id, SPDYLAY_INTERNAL_ERROR);
-          break;
-        }
-        fwrite(out, 1, outlen, stdout);
-        data += tlen;
-        len -= tlen;
-      }
-    } else {
-      /* TODO add support gzip */
-      fwrite(data, 1, len, stdout);
-
-      //check if the data is correct
-      if(strcmp(RESPONSE_BODY, (char *)data) != 0)
-		killparent(parent, "\nreceived data is not the same");
-    }
-    spdylay_printf("\n");
-  }
-}
-
-/*
- * Setup callback functions. Spdylay API offers many callback
- * functions, but most of them are optional. The send_callback is
- * always required. Since we use spdylay_session_recv(), the
- * recv_callback is also required.
- */
-static void setup_spdylay_callbacks(spdylay_session_callbacks *callbacks)
-{
-  memset(callbacks, 0, sizeof(spdylay_session_callbacks));
-  callbacks->send_callback = send_callback;
-  callbacks->recv_callback = recv_callback;
-  callbacks->before_ctrl_send_callback = before_ctrl_send_callback;
-  callbacks->on_ctrl_send_callback = on_ctrl_send_callback;
-  callbacks->on_ctrl_recv_callback = on_ctrl_recv_callback;
-  callbacks->on_stream_close_callback = on_stream_close_callback;
-  callbacks->on_data_chunk_recv_callback = on_data_chunk_recv_callback;
-}
-
-/*
- * Callback function for SSL/TLS NPN. Since this program only supports
- * SPDY protocol, if server does not offer SPDY protocol the Spdylay
- * library supports, we terminate program.
- */
-static int select_next_proto_cb(SSL* ssl,
-                                unsigned char **out, unsigned char *outlen,
-                                const unsigned char *in, unsigned int inlen,
-                                void *arg)
-{
-  (void)ssl;
-
-  int rv;
-  uint16_t *spdy_proto_version;
-  /* spdylay_select_next_protocol() selects SPDY protocol version the
-     Spdylay library supports. */
-  rv = spdylay_select_next_protocol(out, outlen, in, inlen);
-  if(rv <= 0) {
-    die("Server did not advertise spdy/2 or spdy/3 protocol.");
-  }
-  spdy_proto_version = (uint16_t*)arg;
-  *spdy_proto_version = rv;
-  return SSL_TLSEXT_ERR_OK;
-}
-
-/*
- * Setup SSL context. We pass |spdy_proto_version| to get negotiated
- * SPDY protocol version in NPN callback.
- */
-static void init_ssl_ctx(SSL_CTX *ssl_ctx, uint16_t *spdy_proto_version)
-{
-  /* Disable SSLv2 and enable all workarounds for buggy servers */
-  SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
-  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
-  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
-  /* Set NPN callback */
-  SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb,
-                                   spdy_proto_version);
-}
-
-static void ssl_handshake(SSL *ssl, int fd)
-{
-  int rv;
-  if(SSL_set_fd(ssl, fd) == 0) {
-    dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
-  }
-  ERR_clear_error();
-  rv = SSL_connect(ssl);
-  if(rv <= 0) {
-    dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL));
-  }
-}
-
-/*
- * Connects to the host |host| and port |port|.  This function returns
- * the file descriptor of the client socket.
- */
-static int connect_to(const char *host, uint16_t port)
-{
-  struct addrinfo hints;
-  int fd = -1;
-  int rv;
-  char service[NI_MAXSERV];
-  struct addrinfo *res, *rp;
-  snprintf(service, sizeof(service), "%u", port);
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;
-  hints.ai_socktype = SOCK_STREAM;
-  rv = getaddrinfo(host, service, &hints, &res);
-  if(rv != 0) {
-    dief("getaddrinfo", gai_strerror(rv));
-  }
-  for(rp = res; rp; rp = rp->ai_next) {
-    fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
-    if(fd == -1) {
-      continue;
-    }
-    while((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
-          errno == EINTR);
-    if(rv == 0) {
-      break;
-    }
-    close(fd);
-    fd = -1;
-  }
-  freeaddrinfo(res);
-  return fd;
-}
-
-static void make_non_block(int fd)
-{
-  int flags, rv;
-  while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
-  if(flags == -1) {
-    dief("fcntl", strerror(errno));
-  }
-  while((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR);
-  if(rv == -1) {
-    dief("fcntl", strerror(errno));
-  }
-}
-
-/*
- * Setting TCP_NODELAY is not mandatory for the SPDY protocol.
- */
-static void set_tcp_nodelay(int fd)
-{
-  int val = 1;
-  int rv;
-  rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
-  if(rv == -1) {
-    dief("setsockopt", strerror(errno));
-  }
-}
-
-/*
- * Update |pollfd| based on the state of |connection|.
- */
-static void ctl_poll(struct pollfd *pollfd, struct Connection *connection)
-{
-  pollfd->events = 0;
-  if(spdylay_session_want_read(connection->session) ||
-     connection->want_io == WANT_READ) {
-    pollfd->events |= POLLIN;
-  }
-  if(spdylay_session_want_write(connection->session) ||
-     connection->want_io == WANT_WRITE) {
-    pollfd->events |= POLLOUT;
-  }
-}
-
-/*
- * Submits the request |req| to the connection |connection|.  This
- * function does not send packets; just append the request to the
- * internal queue in |connection->session|.
- */
-static void submit_request(struct Connection *connection, struct Request *req)
-{
-  int pri = 0;
-  int rv;
-  const char *nv[15];
-  /* We always use SPDY/3 style header even if the negotiated protocol
-     version is SPDY/2. The library translates the header name as
-     necessary. Make sure that the last item is NULL! */
-  nv[0] = ":method";     nv[1] = "GET";
-  nv[2] = ":path";       nv[3] = req->path;
-  nv[4] = ":version";    nv[5] = "HTTP/1.1";
-  nv[6] = ":scheme";     nv[7] = "https";
-  nv[8] = ":host";       nv[9] = req->hostport;
-  nv[10] = "accept";     nv[11] = "*/*";
-  nv[12] = "user-agent"; nv[13] = "spdylay/"SPDYLAY_VERSION;
-  nv[14] = NULL;
-  rv = spdylay_submit_request(connection->session, pri, nv, NULL, req);
-  if(rv != 0) {
-    diec("spdylay_submit_request", rv);
-  }
-}
-
-/*
- * Performs the network I/O.
- */
-static void exec_io(struct Connection *connection)
-{
-  int rv;
-  rv = spdylay_session_recv(connection->session);
-  if(rv != 0) {
-    diec("spdylay_session_recv", rv);
-  }
-  rv = spdylay_session_send(connection->session);
-  if(rv != 0) {
-    diec("spdylay_session_send", rv);
-  }
-}
-
-static void request_init(struct Request *req, const struct URI *uri)
-{
-  req->host = strcopy(uri->host, uri->hostlen);
-  req->port = uri->port;
-  req->path = strcopy(uri->path, uri->pathlen);
-  req->hostport = strcopy(uri->hostport, uri->hostportlen);
-  req->stream_id = -1;
-  req->inflater = NULL;
-}
-
-static void request_free(struct Request *req)
-{
-  free(req->host);
-  free(req->path);
-  free(req->hostport);
-  spdylay_gzip_inflate_del(req->inflater);
-}
-
-/*
- * Fetches the resource denoted by |uri|.
- */
-static void fetch_uri(const struct URI *uri)
-{
-  spdylay_session_callbacks callbacks;
-  int fd;
-  SSL_CTX *ssl_ctx;
-  SSL *ssl;
-  struct Request req;
-  struct Connection connection;
-  int rv;
-  nfds_t npollfds = 1;
-  struct pollfd pollfds[1];
-  uint16_t spdy_proto_version;
-
-  request_init(&req, uri);
-
-  setup_spdylay_callbacks(&callbacks);
-
-  /* Establish connection and setup SSL */
-  fd = connect_to(req.host, req.port);
-  if (-1 == fd)
-    abort ();
-  ssl_ctx = SSL_CTX_new(SSLv23_client_method());
-  if(ssl_ctx == NULL) {
-    dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL));
-  }
-  init_ssl_ctx(ssl_ctx, &spdy_proto_version);
-  ssl = SSL_new(ssl_ctx);
-  if(ssl == NULL) {
-    dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
-  }
-  /* To simplify the program, we perform SSL/TLS handshake in blocking
-     I/O. */
-  ssl_handshake(ssl, fd);
-
-  connection.ssl = ssl;
-  connection.want_io = IO_NONE;
-
-  /* Here make file descriptor non-block */
-  make_non_block(fd);
-  set_tcp_nodelay(fd);
-
-  spdylay_printf("[INFO] SPDY protocol version = %d\n", spdy_proto_version);
-  rv = spdylay_session_client_new(&connection.session, spdy_proto_version,
-                                  &callbacks, &connection);
-  if(rv != 0) {
-    diec("spdylay_session_client_new", rv);
-  }
-
-  /* Submit the HTTP request to the outbound queue. */
-  submit_request(&connection, &req);
-
-  pollfds[0].fd = fd;
-  ctl_poll(pollfds, &connection);
-
-  /* Event loop */
-  while(spdylay_session_want_read(connection.session) ||
-        spdylay_session_want_write(connection.session)) {
-    int nfds = poll(pollfds, npollfds, -1);
-    if(nfds == -1) {
-      dief("poll", strerror(errno));
-    }
-    if(pollfds[0].revents & (POLLIN | POLLOUT)) {
-      exec_io(&connection);
-    }
-    if((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
-      die("Connection error");
-    }
-    ctl_poll(pollfds, &connection);
-  }
-
-  /* Resource cleanup */
-  spdylay_session_del(connection.session);
-  SSL_shutdown(ssl);
-  SSL_free(ssl);
-  SSL_CTX_free(ssl_ctx);
-  shutdown(fd, SHUT_WR);
-  close(fd);
-  request_free(&req);
-}
-
-static int parse_uri(struct URI *res, const char *uri)
-{
-  /* We only interested in https */
-  size_t len, i, offset;
-  memset(res, 0, sizeof(struct URI));
-  len = strlen(uri);
-  if(len < 9 || memcmp("https://", uri, 8) != 0) {
-    return -1;
-  }
-  offset = 8;
-  res->host = res->hostport = &uri[offset];
-  res->hostlen = 0;
-  if(uri[offset] == '[') {
-    /* IPv6 literal address */
-    ++offset;
-    ++res->host;
-    for(i = offset; i < len; ++i) {
-      if(uri[i] == ']') {
-        res->hostlen = i-offset;
-        offset = i+1;
-        break;
-      }
-    }
-  } else {
-    const char delims[] = ":/?#";
-    for(i = offset; i < len; ++i) {
-      if(strchr(delims, uri[i]) != NULL) {
-        break;
-      }
-    }
-    res->hostlen = i-offset;
-    offset = i;
-  }
-  if(res->hostlen == 0) {
-    return -1;
-  }
-  /* Assuming https */
-  res->port = 443;
-  if(offset < len) {
-    if(uri[offset] == ':') {
-      /* port */
-      const char delims[] = "/?#";
-      int port = 0;
-      ++offset;
-      for(i = offset; i < len; ++i) {
-        if(strchr(delims, uri[i]) != NULL) {
-          break;
-        }
-        if('0' <= uri[i] && uri[i] <= '9') {
-          port *= 10;
-          port += uri[i]-'0';
-          if(port > 65535) {
-            return -1;
-          }
-        } else {
-          return -1;
-        }
-      }
-      if(port == 0) {
-        return -1;
-      }
-      offset = i;
-      res->port = port;
-    }
-  }
-  res->hostportlen = uri+offset-res->host;
-  for(i = offset; i < len; ++i) {
-    if(uri[i] == '#') {
-      break;
-    }
-  }
-  if(i-offset == 0) {
-    res->path = "/";
-    res->pathlen = 1;
-  } else {
-    res->path = &uri[offset];
-    res->pathlen = i-offset;
-  }
-  return 0;
-}
-
-
-/*****
- * end of code needed to utilize spdylay
- */
-
-
-/*****
- * start of code needed to utilize microspdy
- */
-
-void
-new_session_callback (void *cls,
-						struct SPDY_Session * session)
-{
-	char ipstr[1024];
-
-	struct sockaddr *addr;
-	socklen_t addr_len = SPDY_get_remote_addr(session, &addr);
-
-	if(!addr_len)
-	{
-		printf("SPDY_get_remote_addr");
-		abort();
-	}
-
-	if(strcmp(CLS,cls)!=0)
-	{
-		killchild(child,"wrong cls");
-	}
-
-	if(AF_INET == addr->sa_family)
-	{
-		struct sockaddr_in * addr4 = (struct sockaddr_in *) addr;
-		if(NULL == inet_ntop(AF_INET, &(addr4->sin_addr), ipstr, sizeof(ipstr)))
-		{
-			killchild(child,"inet_ntop");
-		}
-		printf("New connection from: %s:%i\n", ipstr, ntohs(addr4->sin_port));
-
-		loop = 0;
-	}
-#if HAVE_INET6
-	else if(AF_INET6 == addr->sa_family)
-	{
-		struct sockaddr_in6 * addr6 = (struct sockaddr_in6 *) addr;
-		if(NULL == inet_ntop(AF_INET6, &(addr6->sin6_addr), ipstr, sizeof(ipstr)))
-		{
-			killchild(child,"inet_ntop");
-		}
-		printf("New connection from: %s:%i\n", ipstr, ntohs(addr6->sin6_port));
-
-		loop = 0;
-	}
-#endif
-	else
-	{
-		killchild(child,"wrong family");
-	}
-}
-
-/*****
- * end of code needed to utilize microspdy
- */
-
-//child process
-void
-childproc(int parent)
-{
-  struct URI uri;
-  struct sigaction act;
-  int rv;
-  char *uristr;
-
-  memset(&act, 0, sizeof(struct sigaction));
-  act.sa_handler = SIG_IGN;
-  sigaction(SIGPIPE, &act, 0);
-
-	asprintf(&uristr, "https://127.0.0.1:%i/",port);
-
-  SSL_load_error_strings();
-  SSL_library_init();
-
-  rv = parse_uri(&uri, uristr);
-  if(rv != 0) {
-    killparent(parent,"parse_uri failed");
-  }
-  fetch_uri(&uri);
-}
-
-//parent proc
-int
-parentproc(int child)
-{
-	int childstatus = 0;
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-
-	SPDY_init();
-
-	daemon = SPDY_start_daemon(port,
-								DATA_DIR "cert-and-key.pem",
-								DATA_DIR "cert-and-key.pem",
-								&new_session_callback,NULL,NULL,NULL,CLS,SPDY_DAEMON_OPTION_END);
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set,
-								&except_fd_set);
-
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				killchild(child, "select error");
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(loop && waitpid(child,&childstatus,WNOHANG) != child);
-
-	SPDY_stop_daemon(daemon);
-
-	SPDY_deinit();
-
-	if(loop)
-		return WEXITSTATUS(childstatus);
-	if(waitpid(child,&childstatus,WNOHANG) == child)
-		return WEXITSTATUS(childstatus);
-
-	kill(child,SIGKILL);
-
-	waitpid(child,&childstatus,0);
-
-	return 0;
-}
-
-int main()
-{
-	port = get_port(14123);
-	parent = getpid();
-
-   child = fork();
-   if (child == -1)
-   {
-      fprintf(stderr, "can't fork, error %d\n", errno);
-      exit(EXIT_FAILURE);
-   }
-
-   if (child == 0)
-   {
-      childproc(parent);
-      _exit(0);
-   }
-   else
-   {
-	   int ret = parentproc(child);
-      exit(ret);
-   }
-   return 1;
-}
diff --git a/src/testspdy/test_notls.c b/src/testspdy/test_notls.c
deleted file mode 100644
index 3f44d96..0000000
--- a/src/testspdy/test_notls.c
+++ /dev/null
@@ -1,973 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file request_response.c
- * @brief  tests receiving request and sending response. spdycli.c (spdylay)
- * 			code is reused here
- * @author Andrey Uzunov
- * @author Tatsuhiro Tsujikawa
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include <sys/wait.h>
-#include "common.h"
-
-#define RESPONSE_BODY "<html><body><b>Hi, this is libmicrospdy!</b></body></html>"
-
-#define CLS "anything"
-
-pid_t parent;
-pid_t child;
-char *rcvbuf;
-int rcvbuf_c = 0;
-
-int session_closed_called = 0;
-
-void
-killchild(int pid, char *message)
-{
-	printf("%s\n",message);
-	kill(pid, SIGKILL);
-	exit(1);
-}
-
-void
-killparent(int pid, char *message)
-{
-	printf("%s\n",message);
-	kill(pid, SIGKILL);
-	_exit(1);
-}
-
-
-/*****
- * start of code needed to utilize spdylay
- */
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <poll.h>
-#include <signal.h>
-#include <stdio.h>
-#include <assert.h>
-
-#include <spdylay/spdylay.h>
-
-enum {
-  IO_NONE,
-  WANT_READ,
-  WANT_WRITE
-};
-
-struct Connection {
-  spdylay_session *session;
-  /* WANT_READ if SSL connection needs more input; or WANT_WRITE if it
-     needs more output; or IO_NONE. This is necessary because SSL/TLS
-     re-negotiation is possible at any time. Spdylay API offers
-     similar functions like spdylay_session_want_read() and
-     spdylay_session_want_write() but they do not take into account
-     SSL connection. */
-  int want_io;
-  int fd;
-};
-
-struct Request {
-  char *host;
-  uint16_t port;
-  /* In this program, path contains query component as well. */
-  char *path;
-  /* This is the concatenation of host and port with ":" in
-     between. */
-  char *hostport;
-  /* Stream ID for this request. */
-  int32_t stream_id;
-  /* The gzip stream inflater for the compressed response. */
-  spdylay_gzip *inflater;
-};
-
-struct URI {
-  const char *host;
-  size_t hostlen;
-  uint16_t port;
-  /* In this program, path contains query component as well. */
-  const char *path;
-  size_t pathlen;
-  const char *hostport;
-  size_t hostportlen;
-};
-
-/*
- * Returns copy of string |s| with the length |len|. The returned
- * string is NULL-terminated.
- */
-static char* strcopy(const char *s, size_t len)
-{
-  char *dst;
-  dst = malloc(len+1);
-  if (NULL == dst)
-    abort ();
-  memcpy(dst, s, len);
-  dst[len] = '\0';
-  return dst;
-}
-
-/*
- * Prints error message |msg| and exit.
- */
-static void die(const char *msg)
-{
-  fprintf(stderr, "FATAL: %s\n", msg);
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Prints error containing the function name |func| and message |msg|
- * and exit.
- */
-static void dief(const char *func, const char *msg)
-{
-  fprintf(stderr, "FATAL: %s: %s\n", func, msg);
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Prints error containing the function name |func| and error code
- * |error_code| and exit.
- */
-static void diec(const char *func, int error_code)
-{
-  fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
-          spdylay_strerror(error_code));
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Check response is content-encoding: gzip. We need this because SPDY
- * client is required to support gzip.
- */
-static void check_gzip(struct Request *req, char **nv)
-{
-  int gzip = 0;
-  size_t i;
-  for(i = 0; nv[i]; i += 2) {
-    if(strcmp("content-encoding", nv[i]) == 0) {
-      gzip = strcmp("gzip", nv[i+1]) == 0;
-      break;
-    }
-  }
-  if(gzip) {
-    int rv;
-    if(req->inflater) {
-      return;
-    }
-    rv = spdylay_gzip_inflate_new(&req->inflater);
-    if(rv != 0) {
-      die("Can't allocate inflate stream.");
-    }
-  }
-}
-
-/*
- * The implementation of spdylay_send_callback type. Here we write
- * |data| with size |length| to the network and return the number of
- * bytes actually written. See the documentation of
- * spdylay_send_callback for the details.
- */
-static ssize_t send_callback(spdylay_session *session,
-                             const uint8_t *data, size_t length, int flags,
-                             void *user_data)
-{
-  (void)session;
-  (void)flags;
-
-  struct Connection *connection;
-  ssize_t rv;
-  connection = (struct Connection*)user_data;
-  connection->want_io = IO_NONE;
-
-    rv = write(connection->fd,
-            data,
-            length);
-
-    if (rv < 0)
-    {
-      switch(errno)
-      {
-        case EAGAIN:
-  #if EAGAIN != EWOULDBLOCK
-        case EWOULDBLOCK:
-  #endif
-          connection->want_io = WANT_WRITE;
-          rv = SPDYLAY_ERR_WOULDBLOCK;
-          break;
-
-        default:
-          rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-      }
-    }
-  return rv;
-}
-
-/*
- * The implementation of spdylay_recv_callback type. Here we read data
- * from the network and write them in |buf|. The capacity of |buf| is
- * |length| bytes. Returns the number of bytes stored in |buf|. See
- * the documentation of spdylay_recv_callback for the details.
- */
-static ssize_t recv_callback(spdylay_session *session,
-                             uint8_t *buf, size_t length, int flags,
-                             void *user_data)
-{
-  (void)session;
-  (void)flags;
-
-  struct Connection *connection;
-  ssize_t rv;
-  connection = (struct Connection*)user_data;
-  connection->want_io = IO_NONE;
-
-    rv = read(connection->fd,
-            buf,
-            length);
-
-    if (rv < 0)
-    {
-      switch(errno)
-      {
-        case EAGAIN:
-  #if EAGAIN != EWOULDBLOCK
-        case EWOULDBLOCK:
-  #endif
-          connection->want_io = WANT_READ;
-          rv = SPDYLAY_ERR_WOULDBLOCK;
-          break;
-
-        default:
-          rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-      }
-    }
-    else if(rv == 0)
-      rv = SPDYLAY_ERR_EOF;
-  return rv;
-}
-
-/*
- * The implementation of spdylay_before_ctrl_send_callback type.  We
- * use this function to get stream ID of the request. This is because
- * stream ID is not known when we submit the request
- * (spdylay_submit_request).
- */
-static void before_ctrl_send_callback(spdylay_session *session,
-                                      spdylay_frame_type type,
-                                      spdylay_frame *frame,
-                                      void *user_data)
-{
-  (void)user_data;
-
-  if(type == SPDYLAY_SYN_STREAM) {
-    struct Request *req;
-    int stream_id = frame->syn_stream.stream_id;
-    req = spdylay_session_get_stream_user_data(session, stream_id);
-    if(req && req->stream_id == -1) {
-      req->stream_id = stream_id;
-      printf("[INFO] Stream ID = %d\n", stream_id);
-    }
-  }
-}
-
-static void on_ctrl_send_callback(spdylay_session *session,
-                                  spdylay_frame_type type,
-                                  spdylay_frame *frame, void *user_data)
-{
-  (void)user_data;
-
-  char **nv;
-  const char *name = NULL;
-  int32_t stream_id;
-  size_t i;
-  switch(type) {
-  case SPDYLAY_SYN_STREAM:
-    nv = frame->syn_stream.nv;
-    name = "SYN_STREAM";
-    stream_id = frame->syn_stream.stream_id;
-    break;
-  default:
-    break;
-  }
-  if(name && spdylay_session_get_stream_user_data(session, stream_id)) {
-    printf("[INFO] C ----------------------------> S (%s)\n", name);
-    for(i = 0; nv[i]; i += 2) {
-      printf("       %s: %s\n", nv[i], nv[i+1]);
-    }
-  }
-}
-
-static void on_ctrl_recv_callback(spdylay_session *session,
-                                  spdylay_frame_type type,
-                                  spdylay_frame *frame, void *user_data)
-{
-  (void)user_data;
-
-  struct Request *req;
-  char **nv;
-  const char *name = NULL;
-  int32_t stream_id;
-  size_t i;
-  switch(type) {
-  case SPDYLAY_SYN_REPLY:
-    nv = frame->syn_reply.nv;
-    name = "SYN_REPLY";
-    stream_id = frame->syn_reply.stream_id;
-    break;
-  case SPDYLAY_HEADERS:
-    nv = frame->headers.nv;
-    name = "HEADERS";
-    stream_id = frame->headers.stream_id;
-    break;
-  default:
-    break;
-  }
-  if(!name) {
-    return;
-  }
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    check_gzip(req, nv);
-    printf("[INFO] C <---------------------------- S (%s)\n", name);
-    for(i = 0; nv[i]; i += 2) {
-      printf("       %s: %s\n", nv[i], nv[i+1]);
-    }
-  }
-}
-
-/*
- * The implementation of spdylay_on_stream_close_callback type. We use
- * this function to know the response is fully received. Since we just
- * fetch 1 resource in this program, after reception of the response,
- * we submit GOAWAY and close the session.
- */
-static void on_stream_close_callback(spdylay_session *session,
-                                     int32_t stream_id,
-                                     spdylay_status_code status_code,
-                                     void *user_data)
-{
-  (void)status_code;
-  (void)user_data;
-
-  struct Request *req;
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    int rv;
-    rv = spdylay_submit_goaway(session, SPDYLAY_GOAWAY_OK);
-    if(rv != 0) {
-      diec("spdylay_submit_goaway", rv);
-    }
-  }
-}
-
-#define MAX_OUTLEN 4096
-
-/*
- * The implementation of spdylay_on_data_chunk_recv_callback type. We
- * use this function to print the received response body.
- */
-static void on_data_chunk_recv_callback(spdylay_session *session, uint8_t flags,
-                                        int32_t stream_id,
-                                        const uint8_t *data, size_t len,
-                                        void *user_data)
-{
-  (void)flags;
-  (void)user_data;
-
-  struct Request *req;
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    printf("[INFO] C <---------------------------- S (DATA)\n");
-    printf("       %lu bytes\n", (unsigned long int)len);
-    if(req->inflater) {
-      while(len > 0) {
-        uint8_t out[MAX_OUTLEN];
-        size_t outlen = MAX_OUTLEN;
-        size_t tlen = len;
-        int rv;
-        rv = spdylay_gzip_inflate(req->inflater, out, &outlen, data, &tlen);
-        if(rv == -1) {
-          spdylay_submit_rst_stream(session, stream_id, SPDYLAY_INTERNAL_ERROR);
-          break;
-        }
-        fwrite(out, 1, outlen, stdout);
-        data += tlen;
-        len -= tlen;
-      }
-    } else {
-      /* TODO add support gzip */
-      fwrite(data, 1, len, stdout);
-
-      //check if the data is correct
-      //if(strcmp(RESPONSE_BODY, data) != 0)
-		//killparent(parent, "\nreceived data is not the same");
-      if(len + rcvbuf_c > strlen(RESPONSE_BODY))
-		killparent(parent, "\nreceived data is not the same");
-
-		strcpy(rcvbuf + rcvbuf_c,(char*)data);
-		rcvbuf_c+=len;
-    }
-    printf("\n");
-  }
-}
-
-/*
- * Setup callback functions. Spdylay API offers many callback
- * functions, but most of them are optional. The send_callback is
- * always required. Since we use spdylay_session_recv(), the
- * recv_callback is also required.
- */
-static void setup_spdylay_callbacks(spdylay_session_callbacks *callbacks)
-{
-  memset(callbacks, 0, sizeof(spdylay_session_callbacks));
-  callbacks->send_callback = send_callback;
-  callbacks->recv_callback = recv_callback;
-  callbacks->before_ctrl_send_callback = before_ctrl_send_callback;
-  callbacks->on_ctrl_send_callback = on_ctrl_send_callback;
-  callbacks->on_ctrl_recv_callback = on_ctrl_recv_callback;
-  callbacks->on_stream_close_callback = on_stream_close_callback;
-  callbacks->on_data_chunk_recv_callback = on_data_chunk_recv_callback;
-}
-
-
-/*
- * Connects to the host |host| and port |port|.  This function returns
- * the file descriptor of the client socket.
- */
-static int connect_to(const char *host, uint16_t port)
-{
-  struct addrinfo hints;
-  int fd = -1;
-  int rv;
-  char service[NI_MAXSERV];
-  struct addrinfo *res, *rp;
-  snprintf(service, sizeof(service), "%u", port);
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;
-  hints.ai_socktype = SOCK_STREAM;
-  rv = getaddrinfo(host, service, &hints, &res);
-  if(rv != 0) {
-    dief("getaddrinfo", gai_strerror(rv));
-  }
-  for(rp = res; rp; rp = rp->ai_next) {
-    fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
-    if(fd == -1) {
-      continue;
-    }
-    while((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
-          errno == EINTR);
-    if(rv == 0) {
-      break;
-    }
-    close(fd);
-    fd = -1;
-    dief("connect", strerror(errno));
-  }
-  freeaddrinfo(res);
-  return fd;
-}
-
-static void make_non_block(int fd)
-{
-  int flags, rv;
-  while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
-  if(flags == -1) {
-    dief("fcntl1", strerror(errno));
-  }
-  while((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR);
-  if(rv == -1) {
-    dief("fcntl2", strerror(errno));
-  }
-}
-
-/*
- * Setting TCP_NODELAY is not mandatory for the SPDY protocol.
- */
-static void set_tcp_nodelay(int fd)
-{
-  int val = 1;
-  int rv;
-  rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
-  if(rv == -1) {
-    dief("setsockopt", strerror(errno));
-  }
-}
-
-/*
- * Update |pollfd| based on the state of |connection|.
- */
-static void ctl_poll(struct pollfd *pollfd, struct Connection *connection)
-{
-  pollfd->events = 0;
-  if(spdylay_session_want_read(connection->session) ||
-     connection->want_io == WANT_READ) {
-    pollfd->events |= POLLIN;
-  }
-  if(spdylay_session_want_write(connection->session) ||
-     connection->want_io == WANT_WRITE) {
-    pollfd->events |= POLLOUT;
-  }
-}
-
-/*
- * Submits the request |req| to the connection |connection|.  This
- * function does not send packets; just append the request to the
- * internal queue in |connection->session|.
- */
-static void submit_request(struct Connection *connection, struct Request *req)
-{
-  int pri = 0;
-  int rv;
-  const char *nv[15];
-  /* We always use SPDY/3 style header even if the negotiated protocol
-     version is SPDY/2. The library translates the header name as
-     necessary. Make sure that the last item is NULL! */
-  nv[0] = ":method";     nv[1] = "GET";
-  nv[2] = ":path";       nv[3] = req->path;
-  nv[4] = ":version";    nv[5] = "HTTP/1.1";
-  nv[6] = ":scheme";     nv[7] = "https";
-  nv[8] = ":host";       nv[9] = req->hostport;
-  nv[10] = "accept";     nv[11] = "*/*";
-  nv[12] = "user-agent"; nv[13] = "spdylay/"SPDYLAY_VERSION;
-  nv[14] = NULL;
-  rv = spdylay_submit_request(connection->session, pri, nv, NULL, req);
-  if(rv != 0) {
-    diec("spdylay_submit_request", rv);
-  }
-}
-
-/*
- * Performs the network I/O.
- */
-static void exec_io(struct Connection *connection)
-{
-  int rv;
-  rv = spdylay_session_recv(connection->session);
-  if(rv != 0) {
-    diec("spdylay_session_recv", rv);
-  }
-  rv = spdylay_session_send(connection->session);
-  if(rv != 0) {
-    diec("spdylay_session_send", rv);
-  }
-}
-
-static void request_init(struct Request *req, const struct URI *uri)
-{
-  req->host = strcopy(uri->host, uri->hostlen);
-  req->port = uri->port;
-  req->path = strcopy(uri->path, uri->pathlen);
-  req->hostport = strcopy(uri->hostport, uri->hostportlen);
-  req->stream_id = -1;
-  req->inflater = NULL;
-}
-
-static void request_free(struct Request *req)
-{
-  free(req->host);
-  free(req->path);
-  free(req->hostport);
-  spdylay_gzip_inflate_del(req->inflater);
-}
-
-/*
- * Fetches the resource denoted by |uri|.
- */
-static void fetch_uri(const struct URI *uri)
-{
-  spdylay_session_callbacks callbacks;
-  int fd;
-  struct Request req;
-  struct Connection connection;
-  int rv;
-  nfds_t npollfds = 1;
-  struct pollfd pollfds[1];
-  uint16_t spdy_proto_version = 3;
-
-  request_init(&req, uri);
-
-  setup_spdylay_callbacks(&callbacks);
-
-  /* Establish connection and setup SSL */
-  fd = connect_to(req.host, req.port);
-  if (-1 == fd)
-    abort ();
-
-  connection.fd = fd;
-  connection.want_io = IO_NONE;
-
-  /* Here make file descriptor non-block */
-  make_non_block(fd);
-  set_tcp_nodelay(fd);
-
-  printf("[INFO] SPDY protocol version = %d\n", spdy_proto_version);
-  rv = spdylay_session_client_new(&connection.session, spdy_proto_version,
-                                  &callbacks, &connection);
-  if(rv != 0) {
-    diec("spdylay_session_client_new", rv);
-  }
-
-  /* Submit the HTTP request to the outbound queue. */
-  submit_request(&connection, &req);
-
-  pollfds[0].fd = fd;
-  ctl_poll(pollfds, &connection);
-
-  /* Event loop */
-  while(spdylay_session_want_read(connection.session) ||
-        spdylay_session_want_write(connection.session)) {
-    int nfds = poll(pollfds, npollfds, -1);
-    if(nfds == -1) {
-      dief("poll", strerror(errno));
-    }
-    if(pollfds[0].revents & (POLLIN | POLLOUT)) {
-      exec_io(&connection);
-    }
-    if((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
-      die("Connection error");
-    }
-    ctl_poll(pollfds, &connection);
-  }
-
-  /* Resource cleanup */
-  spdylay_session_del(connection.session);
-  shutdown(fd, SHUT_WR);
-  close(fd);
-  request_free(&req);
-}
-
-static int parse_uri(struct URI *res, const char *uri)
-{
-  /* We only interested in https */
-  size_t len, i, offset;
-  memset(res, 0, sizeof(struct URI));
-  len = strlen(uri);
-  if(len < 9 || memcmp("https://", uri, 8) != 0) {
-    return -1;
-  }
-  offset = 8;
-  res->host = res->hostport = &uri[offset];
-  res->hostlen = 0;
-  if(uri[offset] == '[') {
-    /* IPv6 literal address */
-    ++offset;
-    ++res->host;
-    for(i = offset; i < len; ++i) {
-      if(uri[i] == ']') {
-        res->hostlen = i-offset;
-        offset = i+1;
-        break;
-      }
-    }
-  } else {
-    const char delims[] = ":/?#";
-    for(i = offset; i < len; ++i) {
-      if(strchr(delims, uri[i]) != NULL) {
-        break;
-      }
-    }
-    res->hostlen = i-offset;
-    offset = i;
-  }
-  if(res->hostlen == 0) {
-    return -1;
-  }
-  /* Assuming https */
-  res->port = 443;
-  if(offset < len) {
-    if(uri[offset] == ':') {
-      /* port */
-      const char delims[] = "/?#";
-      int port = 0;
-      ++offset;
-      for(i = offset; i < len; ++i) {
-        if(strchr(delims, uri[i]) != NULL) {
-          break;
-        }
-        if('0' <= uri[i] && uri[i] <= '9') {
-          port *= 10;
-          port += uri[i]-'0';
-          if(port > 65535) {
-            return -1;
-          }
-        } else {
-          return -1;
-        }
-      }
-      if(port == 0) {
-        return -1;
-      }
-      offset = i;
-      res->port = port;
-    }
-  }
-  res->hostportlen = uri+offset-res->host;
-  for(i = offset; i < len; ++i) {
-    if(uri[i] == '#') {
-      break;
-    }
-  }
-  if(i-offset == 0) {
-    res->path = "/";
-    res->pathlen = 1;
-  } else {
-    res->path = &uri[offset];
-    res->pathlen = i-offset;
-  }
-  return 0;
-}
-
-
-/*****
- * end of code needed to utilize spdylay
- */
-
-
-/*****
- * start of code needed to utilize microspdy
- */
-
-
-void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-	(void)cls;
-	(void)request;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-	(void)headers;
-	(void)method;
-	(void)version;
-	(void)more;
-
-	struct SPDY_Response *response=NULL;
-
-	if(strcmp(CLS,cls)!=0)
-	{
-		killchild(child,"wrong cls");
-	}
-
-	response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,RESPONSE_BODY,strlen(RESPONSE_BODY));
-
-	if(NULL==response){
-		fprintf(stdout,"no response obj\n");
-		exit(3);
-	}
-
-	if(SPDY_queue_response(request,response,true,false,NULL,(void*)strdup(path))!=SPDY_YES)
-	{
-		fprintf(stdout,"queue\n");
-		exit(4);
-	}
-}
-
-void
-session_closed_handler (void *cls,
-						struct SPDY_Session * session,
-						int by_client)
-{
-	printf("session_closed_handler called\n");
-
-	if(strcmp(CLS,cls)!=0)
-	{
-		killchild(child,"wrong cls");
-	}
-
-	if(SPDY_YES != by_client)
-	{
-		//killchild(child,"wrong by_client");
-		printf("session closed by server\n");
-	}
-	else
-	{
-		printf("session closed by client\n");
-	}
-
-	if(NULL == session)
-	{
-		killchild(child,"session is NULL");
-	}
-
-	session_closed_called = 1;
-}
-
-
-/*****
- * end of code needed to utilize microspdy
- */
-
-//child process
-void
-childproc(int port)
-{
-  struct URI uri;
-  struct sigaction act;
-  int rv;
-  char *uristr;
-
-  memset(&act, 0, sizeof(struct sigaction));
-  act.sa_handler = SIG_IGN;
-  sigaction(SIGPIPE, &act, 0);
-
-	usleep(10000);
-	asprintf(&uristr, "https://127.0.0.1:%i/",port);
-	if(NULL == (rcvbuf = malloc(strlen(RESPONSE_BODY)+1)))
-		killparent(parent,"no memory");
-
-  rv = parse_uri(&uri, uristr);
-  if(rv != 0) {
-    killparent(parent,"parse_uri failed");
-  }
-  fetch_uri(&uri);
-
-  if(strcmp(rcvbuf, RESPONSE_BODY))
-    killparent(parent,"received data is different");
-}
-
-//parent proc
-int
-parentproc( int port)
-{
-	int childstatus;
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-
-	SPDY_init();
-
-	daemon = SPDY_start_daemon(port,
-								NULL,
-								NULL,
-								NULL,&session_closed_handler,&standard_request_handler,NULL,CLS,
-                SPDY_DAEMON_OPTION_IO_SUBSYSTEM, SPDY_IO_SUBSYSTEM_RAW,
-                SPDY_DAEMON_OPTION_FLAGS, SPDY_DAEMON_FLAG_NO_DELAY,
-                SPDY_DAEMON_OPTION_END);
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set,
-								&except_fd_set);
-
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				killchild(child, "select error");
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(waitpid(child,&childstatus,WNOHANG) != child);
-
-	//give chance to the client to close socket and handle this in run
-	usleep(100000);
-	SPDY_run(daemon);
-
-	SPDY_stop_daemon(daemon);
-
-	SPDY_deinit();
-
-	return WEXITSTATUS(childstatus);
-}
-
-int main()
-{
-	int port = get_port(12123);
-	parent = getpid();
-
-   child = fork();
-   if (child == -1)
-   {
-      fprintf(stderr, "can't fork, error %d\n", errno);
-      exit(EXIT_FAILURE);
-   }
-
-   if (child == 0)
-   {
-      childproc(port);
-      _exit(0);
-   }
-   else
-   {
-	   int ret = parentproc(port);
-	   if(1 == session_closed_called && 0 == ret)
-      exit(0);
-      else
-      exit(ret ? ret : 21);
-   }
-   return 1;
-}
diff --git a/src/testspdy/test_proxies.c b/src/testspdy/test_proxies.c
deleted file mode 100644
index 44a0c1b..0000000
--- a/src/testspdy/test_proxies.c
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file test_proxies.c
- * @brief  test curl > mhd2spdylay > microspdy2http > mhd
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "common.h"
-#include <sys/wait.h>
-#include <stdio.h>   /* printf, stderr, fprintf */
-#include <sys/types.h> /* pid_t */
-#include <unistd.h>  /* _exit, fork */
-#include <stdlib.h>  /* exit */
-#include <errno.h>   /* errno */
-#include <sys/wait.h> /* pid_t */
-#include "common.h"
-
-#ifdef _WIN32
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN 1
-#endif /* !WIN32_LEAN_AND_MEAN */
-#include <windows.h>
-#endif
-
-#define EXPECTED_BODY "<html><head><title>libmicrohttpd demo</title></head><body>libmicrohttpd demo</body></html>"
-
-
-pid_t parent;
-	pid_t child_mhd;
-	pid_t child_spdy2http;
-	pid_t child_mhd2spdy;
-	pid_t child_curl;
-
-	uint16_t mhd_port;
-	uint16_t spdy2http_port;
-	uint16_t mhd2spdy_port;
-
-void
-killproc(int pid, const char *message)
-{
-	printf("%s\nkilling %i\n",message,pid);
-	kill(pid, SIGKILL);
-}
-
-
-void killchildren()
-{
-    if(0 != child_mhd)
-      killproc(child_mhd,"kill mhd\n");
-    if(0 != child_spdy2http)
-      killproc(child_spdy2http,"kill spdy2http\n");
-    if(0 != child_mhd2spdy)
-      killproc(child_mhd2spdy,"kill mhd2spdy\n");
-    if(0 != child_curl)
-      killproc(child_curl,"kill curl\n");
-}
-
-pid_t au_fork()
-{
-  pid_t child = fork();
-	if (child == -1)
-	{
-    killchildren();
-
-		killproc(parent,"fork failed\n");
-	}
-
-	return child;
-}
-
-
-int main()
-{
-  //pid_t child;
-	int childstatus;
-	pid_t wpid;
-
-	parent = getpid();
-	mhd_port = get_port(4000);
-	spdy2http_port = get_port(4100);
-	mhd2spdy_port = get_port(4200);
-
-	child_mhd = au_fork();
-	if (child_mhd == 0)
-	{
-    //run MHD
-		pid_t devnull;
-    char *port_s;
-
-		close(1);
-		devnull = open("/dev/null", O_WRONLY);
-                if (-1 == devnull)
-                  abort();
-		if (1 != devnull)
-		{
-			dup2(devnull, 1);
-			close(devnull);
-		}
-    asprintf(&port_s, "%i", mhd_port);
-		execlp ("../examples/minimal_example", "minimal_example", port_s, NULL);
-		fprintf(stderr, "executing mhd failed\nFor this test 'make' must be run before 'make check'!\n");
-    //killchildren();
-    _exit(1);
-	}
-
-
-	child_spdy2http = au_fork();
-	if (child_spdy2http == 0)
-	{
-    //run spdy2http
-		pid_t devnull;
-    char *port_s;
-    //char *url;
-
-		close(1);
-		devnull = open("/dev/null", O_WRONLY);
-                if (-1 == devnull)
-                  abort();
-		if (1 != devnull)
-		{
-			dup2(devnull, 1);
-			close(devnull);
-		}
-    //asprintf(&url, "127.0.0.1:%i", mhd_port);
-    asprintf(&port_s, "%i", spdy2http_port);
-    sleep(1);
-		execlp ("../spdy2http/microspdy2http", "microspdy2http", "-v4rtT", "10", "-p", port_s, NULL);
-		fprintf(stderr, "executing microspdy2http failed\n");
-    //killchildren();
-    _exit(1);
-	}
-
-	child_mhd2spdy = au_fork();
-	if (child_mhd2spdy == 0)
-	{
-    //run MHD2sdpy
-		pid_t devnull;
-    char *port_s;
-    char *url;
-
-		close(1);
-		devnull = open("/dev/null", O_WRONLY);
-                if (-1 == devnull)
-                  abort();
-		if (1 != devnull)
-		{
-			dup2(devnull, 1);
-			close(devnull);
-		}
-    asprintf(&url, "http://127.0.0.1:%i", spdy2http_port);
-    asprintf(&port_s, "%i", mhd2spdy_port);
-    sleep(2);
-		execlp ("../examples/mhd2spdy", "mhd2spdy", "-vosb", url, "-p", port_s, NULL);
-		fprintf(stderr, "executing mhd2spdy failed\n");
-    //killchildren();
-    _exit(1);
-	}
-
-	child_curl = au_fork();
-	if (child_curl == 0)
-	{
-    //run curl
-    FILE *p;
-		pid_t devnull;
-		char *cmd;
-    unsigned int i;
-    int retc;
-    char buf[strlen(EXPECTED_BODY) + 1];
-
-		close(1);
-		devnull = open("/dev/null", O_WRONLY);
-                if (-1 == devnull)
-                  abort ();
-		if (1 != devnull)
-		{
-			dup2(devnull, 1);
-			close(devnull);
-		}
-
-		asprintf (&cmd, "curl --proxy http://127.0.0.1:%i http://127.0.0.1:%i/", mhd2spdy_port, mhd_port);
-    sleep(3);
-    p = popen(cmd, "r");
-    if (p != NULL)
-    {
-      for (i = 0; i < strlen(EXPECTED_BODY) && !feof(p); i++)
-      {
-          retc = fgetc (p);
-          if (EOF == retc)
-            abort (); /* what did feof(p) do there!? */
-          buf[i] = (char) retc;
-      }
-
-      pclose(p);
-      buf[i] = 0;
-      _exit(strcmp(EXPECTED_BODY, buf));
-    }
-		fprintf(stderr, "executing curl failed\n");
-    //killchildren();
-    _exit(1);
-	}
-
-  do
-  {
-    wpid = waitpid(child_mhd,&childstatus,WNOHANG);
-    if(wpid == child_mhd)
-    {
-      fprintf(stderr, "mhd died unexpectedly\n");
-      killchildren();
-      return 1;
-    }
-
-    wpid = waitpid(child_spdy2http,&childstatus,WNOHANG);
-    if(wpid == child_spdy2http)
-    {
-      fprintf(stderr, "spdy2http died unexpectedly\n");
-      killchildren();
-      return 1;
-    }
-
-    wpid = waitpid(child_mhd2spdy,&childstatus,WNOHANG);
-    if(wpid == child_mhd2spdy)
-    {
-      fprintf(stderr, "mhd2spdy died unexpectedly\n");
-      killchildren();
-      return 1;
-    }
-
-    if(waitpid(child_curl,&childstatus,WNOHANG) == child_curl)
-    {
-      killchildren();
-      return WEXITSTATUS(childstatus);
-    }
-    sleep(1);
-  }
-	while(true);
-}
diff --git a/src/testspdy/test_request_response.c b/src/testspdy/test_request_response.c
deleted file mode 100644
index 093da03..0000000
--- a/src/testspdy/test_request_response.c
+++ /dev/null
@@ -1,1029 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file request_response.c
- * @brief  tests receiving request and sending response. spdycli.c (spdylay)
- * 			code is reused here
- * @author Andrey Uzunov
- * @author Tatsuhiro Tsujikawa
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include <sys/wait.h>
-#include "common.h"
-
-#define RESPONSE_BODY "<html><body><b>Hi, this is libmicrospdy!</b></body></html>"
-
-#define CLS "anything"
-
-pid_t parent;
-pid_t child;
-char *rcvbuf;
-int rcvbuf_c = 0;
-
-int session_closed_called = 0;
-
-void
-killchild(int pid, char *message)
-{
-	printf("%s\n",message);
-	kill(pid, SIGKILL);
-	exit(1);
-}
-
-void
-killparent(int pid, char *message)
-{
-	printf("%s\n",message);
-	kill(pid, SIGKILL);
-	_exit(1);
-}
-
-
-/*****
- * start of code needed to utilize spdylay
- */
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <poll.h>
-#include <signal.h>
-#include <stdio.h>
-#include <assert.h>
-
-#include <spdylay/spdylay.h>
-
-#include <openssl/ssl.h>
-#include <openssl/err.h>
-
-enum {
-  IO_NONE,
-  WANT_READ,
-  WANT_WRITE
-};
-
-struct Connection {
-  SSL *ssl;
-  spdylay_session *session;
-  /* WANT_READ if SSL connection needs more input; or WANT_WRITE if it
-     needs more output; or IO_NONE. This is necessary because SSL/TLS
-     re-negotiation is possible at any time. Spdylay API offers
-     similar functions like spdylay_session_want_read() and
-     spdylay_session_want_write() but they do not take into account
-     SSL connection. */
-  int want_io;
-};
-
-struct Request {
-  char *host;
-  uint16_t port;
-  /* In this program, path contains query component as well. */
-  char *path;
-  /* This is the concatenation of host and port with ":" in
-     between. */
-  char *hostport;
-  /* Stream ID for this request. */
-  int32_t stream_id;
-  /* The gzip stream inflater for the compressed response. */
-  spdylay_gzip *inflater;
-};
-
-struct URI {
-  const char *host;
-  size_t hostlen;
-  uint16_t port;
-  /* In this program, path contains query component as well. */
-  const char *path;
-  size_t pathlen;
-  const char *hostport;
-  size_t hostportlen;
-};
-
-/*
- * Returns copy of string |s| with the length |len|. The returned
- * string is NULL-terminated.
- */
-static char* strcopy(const char *s, size_t len)
-{
-  char *dst;
-  dst = malloc(len+1);
-  if (NULL == dst)
-    abort ();
-  memcpy(dst, s, len);
-  dst[len] = '\0';
-  return dst;
-}
-
-/*
- * Prints error message |msg| and exit.
- */
-static void die(const char *msg)
-{
-  fprintf(stderr, "FATAL: %s\n", msg);
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Prints error containing the function name |func| and message |msg|
- * and exit.
- */
-static void dief(const char *func, const char *msg)
-{
-  fprintf(stderr, "FATAL: %s: %s\n", func, msg);
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Prints error containing the function name |func| and error code
- * |error_code| and exit.
- */
-static void diec(const char *func, int error_code)
-{
-  fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
-          spdylay_strerror(error_code));
-  exit(EXIT_FAILURE);
-}
-
-/*
- * Check response is content-encoding: gzip. We need this because SPDY
- * client is required to support gzip.
- */
-static void check_gzip(struct Request *req, char **nv)
-{
-  int gzip = 0;
-  size_t i;
-  for(i = 0; nv[i]; i += 2) {
-    if(strcmp("content-encoding", nv[i]) == 0) {
-      gzip = strcmp("gzip", nv[i+1]) == 0;
-      break;
-    }
-  }
-  if(gzip) {
-    int rv;
-    if(req->inflater) {
-      return;
-    }
-    rv = spdylay_gzip_inflate_new(&req->inflater);
-    if(rv != 0) {
-      die("Can't allocate inflate stream.");
-    }
-  }
-}
-
-/*
- * The implementation of spdylay_send_callback type. Here we write
- * |data| with size |length| to the network and return the number of
- * bytes actually written. See the documentation of
- * spdylay_send_callback for the details.
- */
-static ssize_t send_callback(spdylay_session *session,
-                             const uint8_t *data, size_t length, int flags,
-                             void *user_data)
-{
-  (void)session;
-  (void)flags;
-
-  struct Connection *connection;
-  ssize_t rv;
-  connection = (struct Connection*)user_data;
-  connection->want_io = IO_NONE;
-  ERR_clear_error();
-  rv = SSL_write(connection->ssl, data, length);
-  if(rv < 0) {
-    int err = SSL_get_error(connection->ssl, rv);
-    if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
-      connection->want_io = (err == SSL_ERROR_WANT_READ ?
-                             WANT_READ : WANT_WRITE);
-      rv = SPDYLAY_ERR_WOULDBLOCK;
-    } else {
-      rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-    }
-  }
-  return rv;
-}
-
-/*
- * The implementation of spdylay_recv_callback type. Here we read data
- * from the network and write them in |buf|. The capacity of |buf| is
- * |length| bytes. Returns the number of bytes stored in |buf|. See
- * the documentation of spdylay_recv_callback for the details.
- */
-static ssize_t recv_callback(spdylay_session *session,
-                             uint8_t *buf, size_t length, int flags,
-                             void *user_data)
-{
-  (void)session;
-  (void)flags;
-
-  struct Connection *connection;
-  ssize_t rv;
-  connection = (struct Connection*)user_data;
-  connection->want_io = IO_NONE;
-  ERR_clear_error();
-  rv = SSL_read(connection->ssl, buf, length);
-  if(rv < 0) {
-    int err = SSL_get_error(connection->ssl, rv);
-    if(err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
-      connection->want_io = (err == SSL_ERROR_WANT_READ ?
-                             WANT_READ : WANT_WRITE);
-      rv = SPDYLAY_ERR_WOULDBLOCK;
-    } else {
-      rv = SPDYLAY_ERR_CALLBACK_FAILURE;
-    }
-  } else if(rv == 0) {
-    rv = SPDYLAY_ERR_EOF;
-  }
-  return rv;
-}
-
-/*
- * The implementation of spdylay_before_ctrl_send_callback type.  We
- * use this function to get stream ID of the request. This is because
- * stream ID is not known when we submit the request
- * (spdylay_submit_request).
- */
-static void before_ctrl_send_callback(spdylay_session *session,
-                                      spdylay_frame_type type,
-                                      spdylay_frame *frame,
-                                      void *user_data)
-{
-  (void)user_data;
-
-  if(type == SPDYLAY_SYN_STREAM) {
-    struct Request *req;
-    int stream_id = frame->syn_stream.stream_id;
-    req = spdylay_session_get_stream_user_data(session, stream_id);
-    if(req && req->stream_id == -1) {
-      req->stream_id = stream_id;
-      printf("[INFO] Stream ID = %d\n", stream_id);
-    }
-  }
-}
-
-static void on_ctrl_send_callback(spdylay_session *session,
-                                  spdylay_frame_type type,
-                                  spdylay_frame *frame, void *user_data)
-{
-  (void)user_data;
-
-  char **nv;
-  const char *name = NULL;
-  int32_t stream_id;
-  size_t i;
-  switch(type) {
-  case SPDYLAY_SYN_STREAM:
-    nv = frame->syn_stream.nv;
-    name = "SYN_STREAM";
-    stream_id = frame->syn_stream.stream_id;
-    break;
-  default:
-    break;
-  }
-  if(name && spdylay_session_get_stream_user_data(session, stream_id)) {
-    printf("[INFO] C ----------------------------> S (%s)\n", name);
-    for(i = 0; nv[i]; i += 2) {
-      printf("       %s: %s\n", nv[i], nv[i+1]);
-    }
-  }
-}
-
-static void on_ctrl_recv_callback(spdylay_session *session,
-                                  spdylay_frame_type type,
-                                  spdylay_frame *frame, void *user_data)
-{
-  (void)user_data;
-
-  struct Request *req;
-  char **nv;
-  const char *name = NULL;
-  int32_t stream_id;
-  size_t i;
-  switch(type) {
-  case SPDYLAY_SYN_REPLY:
-    nv = frame->syn_reply.nv;
-    name = "SYN_REPLY";
-    stream_id = frame->syn_reply.stream_id;
-    break;
-  case SPDYLAY_HEADERS:
-    nv = frame->headers.nv;
-    name = "HEADERS";
-    stream_id = frame->headers.stream_id;
-    break;
-  default:
-    break;
-  }
-  if(!name) {
-    return;
-  }
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    check_gzip(req, nv);
-    printf("[INFO] C <---------------------------- S (%s)\n", name);
-    for(i = 0; nv[i]; i += 2) {
-      printf("       %s: %s\n", nv[i], nv[i+1]);
-    }
-  }
-}
-
-/*
- * The implementation of spdylay_on_stream_close_callback type. We use
- * this function to know the response is fully received. Since we just
- * fetch 1 resource in this program, after reception of the response,
- * we submit GOAWAY and close the session.
- */
-static void on_stream_close_callback(spdylay_session *session,
-                                     int32_t stream_id,
-                                     spdylay_status_code status_code,
-                                     void *user_data)
-{
-  (void)user_data;
-  (void)status_code;
-
-  struct Request *req;
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    int rv;
-    rv = spdylay_submit_goaway(session, SPDYLAY_GOAWAY_OK);
-    if(rv != 0) {
-      diec("spdylay_submit_goaway", rv);
-    }
-  }
-}
-
-#define MAX_OUTLEN 4096
-
-/*
- * The implementation of spdylay_on_data_chunk_recv_callback type. We
- * use this function to print the received response body.
- */
-static void on_data_chunk_recv_callback(spdylay_session *session, uint8_t flags,
-                                        int32_t stream_id,
-                                        const uint8_t *data, size_t len,
-                                        void *user_data)
-{
-  (void)user_data;
-  (void)flags;
-
-  struct Request *req;
-  req = spdylay_session_get_stream_user_data(session, stream_id);
-  if(req) {
-    printf("[INFO] C <---------------------------- S (DATA)\n");
-    printf("       %lu bytes\n", (unsigned long int)len);
-    if(req->inflater) {
-      while(len > 0) {
-        uint8_t out[MAX_OUTLEN];
-        size_t outlen = MAX_OUTLEN;
-        size_t tlen = len;
-        int rv;
-        rv = spdylay_gzip_inflate(req->inflater, out, &outlen, data, &tlen);
-        if(rv == -1) {
-          spdylay_submit_rst_stream(session, stream_id, SPDYLAY_INTERNAL_ERROR);
-          break;
-        }
-        fwrite(out, 1, outlen, stdout);
-        data += tlen;
-        len -= tlen;
-      }
-    } else {
-      /* TODO add support gzip */
-      fwrite(data, 1, len, stdout);
-
-      //check if the data is correct
-      //if(strcmp(RESPONSE_BODY, data) != 0)
-		//killparent(parent, "\nreceived data is not the same");
-      if(len + rcvbuf_c > strlen(RESPONSE_BODY))
-		killparent(parent, "\nreceived data is not the same");
-
-		strcpy(rcvbuf + rcvbuf_c,(char*)data);
-		rcvbuf_c+=len;
-    }
-    printf("\n");
-  }
-}
-
-/*
- * Setup callback functions. Spdylay API offers many callback
- * functions, but most of them are optional. The send_callback is
- * always required. Since we use spdylay_session_recv(), the
- * recv_callback is also required.
- */
-static void setup_spdylay_callbacks(spdylay_session_callbacks *callbacks)
-{
-  memset(callbacks, 0, sizeof(spdylay_session_callbacks));
-  callbacks->send_callback = send_callback;
-  callbacks->recv_callback = recv_callback;
-  callbacks->before_ctrl_send_callback = before_ctrl_send_callback;
-  callbacks->on_ctrl_send_callback = on_ctrl_send_callback;
-  callbacks->on_ctrl_recv_callback = on_ctrl_recv_callback;
-  callbacks->on_stream_close_callback = on_stream_close_callback;
-  callbacks->on_data_chunk_recv_callback = on_data_chunk_recv_callback;
-}
-
-/*
- * Callback function for SSL/TLS NPN. Since this program only supports
- * SPDY protocol, if server does not offer SPDY protocol the Spdylay
- * library supports, we terminate program.
- */
-static int select_next_proto_cb(SSL* ssl,
-                                unsigned char **out, unsigned char *outlen,
-                                const unsigned char *in, unsigned int inlen,
-                                void *arg)
-{
-  (void)ssl;
-
-  int rv;
-  uint16_t *spdy_proto_version;
-  /* spdylay_select_next_protocol() selects SPDY protocol version the
-     Spdylay library supports. */
-  rv = spdylay_select_next_protocol(out, outlen, in, inlen);
-  if(rv <= 0) {
-    die("Server did not advertise spdy/2 or spdy/3 protocol.");
-  }
-  spdy_proto_version = (uint16_t*)arg;
-  *spdy_proto_version = rv;
-  return SSL_TLSEXT_ERR_OK;
-}
-
-/*
- * Setup SSL context. We pass |spdy_proto_version| to get negotiated
- * SPDY protocol version in NPN callback.
- */
-static void init_ssl_ctx(SSL_CTX *ssl_ctx, uint16_t *spdy_proto_version)
-{
-  /* Disable SSLv2 and enable all workarounds for buggy servers */
-  SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL|SSL_OP_NO_SSLv2);
-  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
-  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
-  /* Set NPN callback */
-  SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb,
-                                   spdy_proto_version);
-}
-
-static void ssl_handshake(SSL *ssl, int fd)
-{
-  int rv;
-  if(SSL_set_fd(ssl, fd) == 0) {
-    dief("SSL_set_fd", ERR_error_string(ERR_get_error(), NULL));
-  }
-  ERR_clear_error();
-  rv = SSL_connect(ssl);
-  if(rv <= 0) {
-    dief("SSL_connect", ERR_error_string(ERR_get_error(), NULL));
-  }
-}
-
-/*
- * Connects to the host |host| and port |port|.  This function returns
- * the file descriptor of the client socket.
- */
-static int connect_to(const char *host, uint16_t port)
-{
-  struct addrinfo hints;
-  int fd = -1;
-  int rv;
-  char service[NI_MAXSERV];
-  struct addrinfo *res, *rp;
-  snprintf(service, sizeof(service), "%u", port);
-  memset(&hints, 0, sizeof(struct addrinfo));
-  hints.ai_family = AF_UNSPEC;
-  hints.ai_socktype = SOCK_STREAM;
-  rv = getaddrinfo(host, service, &hints, &res);
-  if(rv != 0) {
-    dief("getaddrinfo", gai_strerror(rv));
-  }
-  for(rp = res; rp; rp = rp->ai_next) {
-    fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
-    if(fd == -1) {
-      continue;
-    }
-    while((rv = connect(fd, rp->ai_addr, rp->ai_addrlen)) == -1 &&
-          errno == EINTR);
-    if(rv == 0) {
-      break;
-    }
-    close(fd);
-    fd = -1;
-  }
-  freeaddrinfo(res);
-  return fd;
-}
-
-static void make_non_block(int fd)
-{
-  int flags, rv;
-  while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR);
-  if(flags == -1) {
-    dief("fcntl", strerror(errno));
-  }
-  while((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR);
-  if(rv == -1) {
-    dief("fcntl", strerror(errno));
-  }
-}
-
-/*
- * Setting TCP_NODELAY is not mandatory for the SPDY protocol.
- */
-static void set_tcp_nodelay(int fd)
-{
-  int val = 1;
-  int rv;
-  rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
-  if(rv == -1) {
-    dief("setsockopt", strerror(errno));
-  }
-}
-
-/*
- * Update |pollfd| based on the state of |connection|.
- */
-static void ctl_poll(struct pollfd *pollfd, struct Connection *connection)
-{
-  pollfd->events = 0;
-  if(spdylay_session_want_read(connection->session) ||
-     connection->want_io == WANT_READ) {
-    pollfd->events |= POLLIN;
-  }
-  if(spdylay_session_want_write(connection->session) ||
-     connection->want_io == WANT_WRITE) {
-    pollfd->events |= POLLOUT;
-  }
-}
-
-/*
- * Submits the request |req| to the connection |connection|.  This
- * function does not send packets; just append the request to the
- * internal queue in |connection->session|.
- */
-static void submit_request(struct Connection *connection, struct Request *req)
-{
-  int pri = 0;
-  int rv;
-  const char *nv[15];
-  /* We always use SPDY/3 style header even if the negotiated protocol
-     version is SPDY/2. The library translates the header name as
-     necessary. Make sure that the last item is NULL! */
-  nv[0] = ":method";     nv[1] = "GET";
-  nv[2] = ":path";       nv[3] = req->path;
-  nv[4] = ":version";    nv[5] = "HTTP/1.1";
-  nv[6] = ":scheme";     nv[7] = "https";
-  nv[8] = ":host";       nv[9] = req->hostport;
-  nv[10] = "accept";     nv[11] = "*/*";
-  nv[12] = "user-agent"; nv[13] = "spdylay/"SPDYLAY_VERSION;
-  nv[14] = NULL;
-  rv = spdylay_submit_request(connection->session, pri, nv, NULL, req);
-  if(rv != 0) {
-    diec("spdylay_submit_request", rv);
-  }
-}
-
-/*
- * Performs the network I/O.
- */
-static void exec_io(struct Connection *connection)
-{
-  int rv;
-  rv = spdylay_session_recv(connection->session);
-  if(rv != 0) {
-    diec("spdylay_session_recv", rv);
-  }
-  rv = spdylay_session_send(connection->session);
-  if(rv != 0) {
-    diec("spdylay_session_send", rv);
-  }
-}
-
-static void request_init(struct Request *req, const struct URI *uri)
-{
-  req->host = strcopy(uri->host, uri->hostlen);
-  req->port = uri->port;
-  req->path = strcopy(uri->path, uri->pathlen);
-  req->hostport = strcopy(uri->hostport, uri->hostportlen);
-  req->stream_id = -1;
-  req->inflater = NULL;
-}
-
-static void request_free(struct Request *req)
-{
-  free(req->host);
-  free(req->path);
-  free(req->hostport);
-  spdylay_gzip_inflate_del(req->inflater);
-}
-
-/*
- * Fetches the resource denoted by |uri|.
- */
-static void fetch_uri(const struct URI *uri)
-{
-  spdylay_session_callbacks callbacks;
-  int fd;
-  SSL_CTX *ssl_ctx;
-  SSL *ssl;
-  struct Request req;
-  struct Connection connection;
-  int rv;
-  nfds_t npollfds = 1;
-  struct pollfd pollfds[1];
-  uint16_t spdy_proto_version;
-
-  request_init(&req, uri);
-
-  setup_spdylay_callbacks(&callbacks);
-
-  /* Establish connection and setup SSL */
-  fd = connect_to(req.host, req.port);
-  if (-1 == fd)
-    abort ();
-  ssl_ctx = SSL_CTX_new(SSLv23_client_method());
-  if(ssl_ctx == NULL) {
-    dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL));
-  }
-  init_ssl_ctx(ssl_ctx, &spdy_proto_version);
-  ssl = SSL_new(ssl_ctx);
-  if(ssl == NULL) {
-    dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
-  }
-  /* To simplify the program, we perform SSL/TLS handshake in blocking
-     I/O. */
-  ssl_handshake(ssl, fd);
-
-  connection.ssl = ssl;
-  connection.want_io = IO_NONE;
-
-  /* Here make file descriptor non-block */
-  make_non_block(fd);
-  set_tcp_nodelay(fd);
-
-  printf("[INFO] SPDY protocol version = %d\n", spdy_proto_version);
-  rv = spdylay_session_client_new(&connection.session, spdy_proto_version,
-                                  &callbacks, &connection);
-  if(rv != 0) {
-    diec("spdylay_session_client_new", rv);
-  }
-
-  /* Submit the HTTP request to the outbound queue. */
-  submit_request(&connection, &req);
-
-  pollfds[0].fd = fd;
-  ctl_poll(pollfds, &connection);
-
-  /* Event loop */
-  while(spdylay_session_want_read(connection.session) ||
-        spdylay_session_want_write(connection.session)) {
-    int nfds = poll(pollfds, npollfds, -1);
-    if(nfds == -1) {
-      dief("poll", strerror(errno));
-    }
-    if(pollfds[0].revents & (POLLIN | POLLOUT)) {
-      exec_io(&connection);
-    }
-    if((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
-      die("Connection error");
-    }
-    ctl_poll(pollfds, &connection);
-  }
-
-  /* Resource cleanup */
-  spdylay_session_del(connection.session);
-  SSL_shutdown(ssl);
-  SSL_free(ssl);
-  SSL_CTX_free(ssl_ctx);
-  shutdown(fd, SHUT_WR);
-  close(fd);
-  request_free(&req);
-}
-
-static int parse_uri(struct URI *res, const char *uri)
-{
-  /* We only interested in https */
-  size_t len, i, offset;
-  memset(res, 0, sizeof(struct URI));
-  len = strlen(uri);
-  if(len < 9 || memcmp("https://", uri, 8) != 0) {
-    return -1;
-  }
-  offset = 8;
-  res->host = res->hostport = &uri[offset];
-  res->hostlen = 0;
-  if(uri[offset] == '[') {
-    /* IPv6 literal address */
-    ++offset;
-    ++res->host;
-    for(i = offset; i < len; ++i) {
-      if(uri[i] == ']') {
-        res->hostlen = i-offset;
-        offset = i+1;
-        break;
-      }
-    }
-  } else {
-    const char delims[] = ":/?#";
-    for(i = offset; i < len; ++i) {
-      if(strchr(delims, uri[i]) != NULL) {
-        break;
-      }
-    }
-    res->hostlen = i-offset;
-    offset = i;
-  }
-  if(res->hostlen == 0) {
-    return -1;
-  }
-  /* Assuming https */
-  res->port = 443;
-  if(offset < len) {
-    if(uri[offset] == ':') {
-      /* port */
-      const char delims[] = "/?#";
-      int port = 0;
-      ++offset;
-      for(i = offset; i < len; ++i) {
-        if(strchr(delims, uri[i]) != NULL) {
-          break;
-        }
-        if('0' <= uri[i] && uri[i] <= '9') {
-          port *= 10;
-          port += uri[i]-'0';
-          if(port > 65535) {
-            return -1;
-          }
-        } else {
-          return -1;
-        }
-      }
-      if(port == 0) {
-        return -1;
-      }
-      offset = i;
-      res->port = port;
-    }
-  }
-  res->hostportlen = uri+offset-res->host;
-  for(i = offset; i < len; ++i) {
-    if(uri[i] == '#') {
-      break;
-    }
-  }
-  if(i-offset == 0) {
-    res->path = "/";
-    res->pathlen = 1;
-  } else {
-    res->path = &uri[offset];
-    res->pathlen = i-offset;
-  }
-  return 0;
-}
-
-
-/*****
- * end of code needed to utilize spdylay
- */
-
-
-/*****
- * start of code needed to utilize microspdy
- */
-
-
-void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-	(void)cls;
-	(void)request;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-	(void)headers;
-	(void)method;
-	(void)version;
-
-	struct SPDY_Response *response=NULL;
-
-	if(strcmp(CLS,cls)!=0)
-	{
-		killchild(child,"wrong cls");
-	}
-
-	if(false != more){
-		fprintf(stdout,"more has wrong value\n");
-		exit(5);
-	}
-
-	response = SPDY_build_response(200,NULL,SPDY_HTTP_VERSION_1_1,NULL,RESPONSE_BODY,strlen(RESPONSE_BODY));
-
-	if(NULL==response){
-		fprintf(stdout,"no response obj\n");
-		exit(3);
-	}
-
-	if(SPDY_queue_response(request,response,true,false,NULL,(void*)strdup(path))!=SPDY_YES)
-	{
-		fprintf(stdout,"queue\n");
-		exit(4);
-	}
-}
-
-void
-session_closed_handler (void *cls,
-						struct SPDY_Session * session,
-						int by_client)
-{
-	printf("session_closed_handler called\n");
-
-	if(strcmp(CLS,cls)!=0)
-	{
-		killchild(child,"wrong cls");
-	}
-
-	if(SPDY_YES != by_client)
-	{
-		//killchild(child,"wrong by_client");
-		printf("session closed by server\n");
-	}
-	else
-	{
-		printf("session closed by client\n");
-	}
-
-	if(NULL == session)
-	{
-		killchild(child,"session is NULL");
-	}
-
-	session_closed_called = 1;
-}
-
-
-/*****
- * end of code needed to utilize microspdy
- */
-
-//child process
-void
-childproc(int port)
-{
-  struct URI uri;
-  struct sigaction act;
-  int rv;
-  char *uristr;
-
-  memset(&act, 0, sizeof(struct sigaction));
-  act.sa_handler = SIG_IGN;
-  sigaction(SIGPIPE, &act, 0);
-
-	asprintf(&uristr, "https://127.0.0.1:%i/",port);
-	if(NULL == (rcvbuf = malloc(strlen(RESPONSE_BODY)+1)))
-		killparent(parent,"no memory");
-
-  SSL_load_error_strings();
-  SSL_library_init();
-
-  rv = parse_uri(&uri, uristr);
-  if(rv != 0) {
-    killparent(parent,"parse_uri failed");
-  }
-  fetch_uri(&uri);
-
-  if(strcmp(rcvbuf, RESPONSE_BODY))
-    killparent(parent,"received data is different");
-}
-
-//parent proc
-int
-parentproc( int port)
-{
-	int childstatus;
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-
-	SPDY_init();
-
-	daemon = SPDY_start_daemon(port,
-								DATA_DIR "cert-and-key.pem",
-								DATA_DIR "cert-and-key.pem",
-								NULL,&session_closed_handler,&standard_request_handler,NULL,CLS,SPDY_DAEMON_OPTION_END);
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set,
-								&except_fd_set);
-
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				killchild(child, "select error");
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(waitpid(child,&childstatus,WNOHANG) != child);
-
-	//give chance to the client to close socket and handle this in run
-	usleep(100000);
-	SPDY_run(daemon);
-
-	SPDY_stop_daemon(daemon);
-
-	SPDY_deinit();
-
-	return WEXITSTATUS(childstatus);
-}
-
-int main()
-{
-	int port = get_port(12123);
-	parent = getpid();
-
-   child = fork();
-   if (child == -1)
-   {
-      fprintf(stderr, "can't fork, error %d\n", errno);
-      exit(EXIT_FAILURE);
-   }
-
-   if (child == 0)
-   {
-      childproc(port);
-      _exit(0);
-   }
-   else
-   {
-	   int ret = parentproc(port);
-	   if(1 == session_closed_called && 0 == ret)
-      exit(0);
-      else
-      exit(ret ? ret : 21);
-   }
-   return 1;
-}
diff --git a/src/testspdy/test_request_response_with_callback.c b/src/testspdy/test_request_response_with_callback.c
deleted file mode 100644
index 95fc263..0000000
--- a/src/testspdy/test_request_response_with_callback.c
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file request_response_with_callback.c
- * @brief  tests responses with callbacks
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "stdio.h"
-#include <sys/wait.h>
-#include <ctype.h>
-#include "common.h"
-#include <sys/time.h>
-#include <sys/stat.h>
-
-int port;
-
-pid_t parent;
-pid_t child;
-
-int run = 1;
-int chunk_size=1;
-
-void
-killchild()
-{
-	kill(child, SIGKILL);
-	exit(1);
-}
-
-void
-killparent()
-{
-	kill(parent, SIGKILL);
-	_exit(1);
-}
-
-ssize_t
-response_callback (void *cls,
-						void *buffer,
-						size_t max,
-						bool *more)
-{
-	FILE *fd =(FILE*)cls;
-	
-	size_t n;
-	if(chunk_size % 2)
-		n = chunk_size;
-	else
-		n = max - chunk_size;
-	
-	if(n < 1) n = 1;
-	else if (n > max) n=max;
-	chunk_size++;
-	
-	int ret = fread(buffer,1,n,fd);
-	*more = feof(fd) == 0;
-	
-	//printf("more is %i\n",*more);
-	
-	if(!(*more))
-		fclose(fd);
-	
-	return ret;
-}
-
-
-void
-response_done_callback(void *cls,
-								struct SPDY_Response * response,
-								struct SPDY_Request * request,
-								enum SPDY_RESPONSE_RESULT status,
-						bool streamopened)
-{
-  (void)status;
-  (void)streamopened;
-  
-	printf("answer for %s was sent\n", (char*)cls);
-	
-	SPDY_destroy_request(request);
-	SPDY_destroy_response(response);
-	free(cls);
-	
-	run = 0;
-}
-
-void
-standard_request_handler(void *cls,
-						struct SPDY_Request * request,
-						uint8_t priority,
-                        const char *method,
-                        const char *path,
-                        const char *version,
-                        const char *host,
-                        const char *scheme,
-						struct SPDY_NameValue * headers,
-            bool more)
-{
-	(void)cls;
-	(void)request;
-	(void)priority;
-	(void)host;
-	(void)scheme;
-	(void)headers;
-	(void)method;
-	(void)version;
-	(void)more;
-  
-	struct SPDY_Response *response=NULL;
-	struct SPDY_NameValue *resp_headers;
-	
-	printf("received request for '%s %s %s'\n", method, path, version);
-	
-		FILE *fd = fopen(DATA_DIR "spdy-draft.txt","r");
-		
-		if(NULL == (resp_headers = SPDY_name_value_create()))
-		{
-			fprintf(stdout,"SPDY_name_value_create failed\n");
-			killchild();
-		}
-		if(SPDY_YES != SPDY_name_value_add(resp_headers,SPDY_HTTP_HEADER_CONTENT_TYPE,"text/plain"))
-		{
-			fprintf(stdout,"SPDY_name_value_add failed\n");
-			killchild();
-		}
-		
-		response = SPDY_build_response_with_callback(200,NULL,
-			SPDY_HTTP_VERSION_1_1,resp_headers,&response_callback,fd,SPDY_MAX_SUPPORTED_FRAME_SIZE);
-		SPDY_name_value_destroy(resp_headers);
-	
-	if(NULL==response){
-		fprintf(stdout,"no response obj\n");
-			killchild();
-	}
-	
-	void *clspath = strdup(path);
-	
-	if(SPDY_queue_response(request,response,true,false,&response_done_callback,clspath)!=SPDY_YES)
-	{
-		fprintf(stdout,"queue\n");
-			killchild();
-	}
-}
-
-int
-parentproc()
-{	
-	int childstatus;
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-	
-	SPDY_init();
-	
-	daemon = SPDY_start_daemon(port,
-								DATA_DIR "cert-and-key.pem",
-								DATA_DIR "cert-and-key.pem",
-								NULL,
-								NULL,
-								&standard_request_handler,
-								NULL,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								1800,
-								SPDY_DAEMON_OPTION_END);
-	
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	do
-	{
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-		if(SPDY_NO == ret || timeoutlong > 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-			timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-		
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set, 
-								&except_fd_set);
-								
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-		
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				break;
-			case 0:
-
-				break;
-			default:
-				SPDY_run(daemon);
-
-			break;
-		}
-	}
-	while(waitpid(child,&childstatus,WNOHANG) != child);
-
-	SPDY_stop_daemon(daemon);
-	
-	SPDY_deinit();
-	
-	return WEXITSTATUS(childstatus);
-}
-
-#define MD5_LEN 32
-
-int
-md5(char *cmd, char *md5_sum)
-{
-    FILE *p = popen(cmd, "r");
-    if (p == NULL) return 0;
-
-    int i, ch;
-    for (i = 0; i < MD5_LEN && isxdigit(ch = fgetc(p)); i++) {
-        *md5_sum++ = ch;
-    }
-
-    *md5_sum = '\0';
-    pclose(p);
-    return i == MD5_LEN;
-}
-
-int
-childproc()
-{
-	char *cmd1;
-	char *cmd2;
-	char md5_sum1[33];
-	char md5_sum2[33];
-	int ret;
-	struct timeval tv1;
-	struct timeval tv2;
-	struct stat st;
-	//int secs;
-	uint64_t usecs;
-	
-	asprintf(&cmd1, "spdycat https://127.0.0.1:%i/ | md5sum",port);
-	asprintf(&cmd2, "md5sum " DATA_DIR "spdy-draft.txt");
-	
-	gettimeofday(&tv1, NULL);
-	md5(cmd1,md5_sum1);
-	gettimeofday(&tv2, NULL);
-	md5(cmd2,md5_sum2);
-	
-	printf("downloaded file md5: %s\n", md5_sum1);
-	printf("original   file md5: %s\n", md5_sum2);
-	ret = strcmp(md5_sum1, md5_sum2);
-	
-	if(0 == ret && 0 == stat(DATA_DIR "spdy-draft.txt", &st))
-	{
-		usecs = (uint64_t)1000000 * (uint64_t)(tv2.tv_sec - tv1.tv_sec) + tv2.tv_usec - tv1.tv_usec;
-		printf("%lld bytes read in %llu usecs\n", (long long)st.st_size, (long long unsigned )usecs);
-	}
-	
-	return ret;
-}
-
-
-int
-main()
-{
-	port = get_port(11123);
-	parent = getpid();
-
-	child = fork();
-	if (-1 == child)
-	{   
-		fprintf(stderr, "can't fork, error %d\n", errno);
-		exit(EXIT_FAILURE);
-	}
-
-	if (child == 0)
-	{
-		int ret = childproc();
-		_exit(ret);
-	}
-	else
-	{ 
-		int ret = parentproc();
-		exit(ret);
-	}
-	return 1;
-}
diff --git a/src/testspdy/test_session_timeout.c b/src/testspdy/test_session_timeout.c
deleted file mode 100644
index ec1eced..0000000
--- a/src/testspdy/test_session_timeout.c
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2013 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file session_timeout.c
- * @brief  tests closing sessions after set timeout. Openssl is used for
- * 			client
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "stdio.h"
-#include <sys/wait.h>
-#include <ctype.h>
-#include "common.h"
-#include <sys/time.h>
-#include <sys/stat.h>
-#include "../microspdy/internal.h"
-
-#define TIMEOUT 2
-#define SELECT_MS_TIMEOUT 20
-
-int port;
-
-pid_t parent;
-pid_t child;
-
-int run = 1;
-int chunk_size=1;
-int new_session;
-int closed_session;
-int do_sleep;
-
-
-
-static unsigned long long
-monotonic_time (void)
-{
-#ifdef HAVE_CLOCK_GETTIME
-#ifdef CLOCK_MONOTONIC
-  struct timespec ts;
-  if (0 == clock_gettime (CLOCK_MONOTONIC, &ts))
-    return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
-#endif
-#endif
-  return time (NULL) * 1000;
-}
-
-
-static void
-killchild(char *msg)
-{
-	printf("%s\n",msg);
-	kill(child, SIGKILL);
-	exit(1);
-}
-
-
-static void
-killparent(char *msg)
-{
-	printf("%s\n",msg);
-	kill(parent, SIGKILL);
-	_exit(1);
-}
-
-
-static void
-new_session_cb (void *cls,
-                struct SPDY_Session * session)
-{
-  (void)cls;
-  (void)session;
-
-	if(!new_session)do_sleep = 1;
-	new_session = 1;
-	printf("new session\n");
-}
-
-
-static void
-closed_session_cb (void *cls,
-                   struct SPDY_Session * session,
-                   int by_client)
-{
-  (void)cls;
-  (void)session;
-
-	printf("closed_session_cb called\n");
-
-	if(SPDY_YES == by_client)
-	{
-		killchild("closed by the client");
-	}
-	if(closed_session)
-	{
-		killchild("closed_session_cb called twice");
-	}
-
-	closed_session = 1;
-}
-
-
-static int
-parentproc()
-{
-	int childstatus;
-	unsigned long long timeoutlong=0;
-	struct timeval timeout;
-	int ret;
-	fd_set read_fd_set;
-	fd_set write_fd_set;
-	fd_set except_fd_set;
-	int maxfd = -1;
-	struct SPDY_Daemon *daemon;
-  unsigned long long  beginning = 0;
-	unsigned long long now;
-
-	SPDY_init();
-
-	daemon = SPDY_start_daemon(port,
-								DATA_DIR "cert-and-key.pem",
-								DATA_DIR "cert-and-key.pem",
-								&new_session_cb,
-								&closed_session_cb,
-								NULL,
-								NULL,
-								NULL,
-								SPDY_DAEMON_OPTION_SESSION_TIMEOUT,
-								TIMEOUT,
-								SPDY_DAEMON_OPTION_END);
-
-	if(NULL==daemon){
-		printf("no daemon\n");
-		return 1;
-	}
-
-	do
-	{
-		do_sleep=0;
-		FD_ZERO(&read_fd_set);
-		FD_ZERO(&write_fd_set);
-		FD_ZERO(&except_fd_set);
-
-		ret = SPDY_get_timeout(daemon, &timeoutlong);
-
-		if(new_session && !closed_session)
-		{
-			if(SPDY_NO == ret)
-			{
-				killchild("SPDY_get_timeout returned wrong SPDY_NO");
-			}
-			/*if(timeoutlong)
-			{
-				killchild("SPDY_get_timeout returned wrong timeout");
-			}*/
-			now = monotonic_time ();
-      if(now - beginning > TIMEOUT*1000 + SELECT_MS_TIMEOUT)
-      {
-        printf("Started at: %llums\n",beginning);
-        printf("Now is: %llums\n",now);
-        printf("Timeout is: %i\n",TIMEOUT);
-        printf("Select Timeout is: %ims\n",SELECT_MS_TIMEOUT);
-        printf("SPDY_get_timeout gave: %llums\n",timeoutlong);
-				killchild("Timeout passed but session was not closed");
-      }
-      if(timeoutlong > beginning + TIMEOUT *1000)
-      {
-        printf("Started at: %llums\n",beginning);
-        printf("Now is: %llums\n",now);
-        printf("Timeout is: %i\n",TIMEOUT);
-        printf("Select Timeout is: %ims\n",SELECT_MS_TIMEOUT);
-        printf("SPDY_get_timeout gave: %llums\n",timeoutlong);
-				killchild("SPDY_get_timeout returned wrong timeout");
-      }
-		}
-		else
-		{
-			if(SPDY_YES == ret)
-			{
-				killchild("SPDY_get_timeout returned wrong SPDY_YES");
-			}
-		}
-
-		if(SPDY_NO == ret || timeoutlong >= 1000)
-		{
-			timeout.tv_sec = 1;
-      timeout.tv_usec = 0;
-		}
-		else
-		{
-			timeout.tv_sec = timeoutlong / 1000;
-      timeout.tv_usec = (timeoutlong % 1000) * 1000;
-		}
-
-    //ignore values
-    timeout.tv_sec = 0;
-    timeout.tv_usec = SELECT_MS_TIMEOUT * 1000;
-
-		maxfd = SPDY_get_fdset (daemon,
-								&read_fd_set,
-								&write_fd_set,
-								&except_fd_set);
-
-		ret = select(maxfd+1, &read_fd_set, &write_fd_set, &except_fd_set, &timeout);
-
-		switch(ret) {
-			case -1:
-				printf("select error: %i\n", errno);
-				break;
-			case 0:
-				/*if(new_session)
-				{
-					killchild("select returned wrong number");
-				}*/
-				break;
-			default:
-				SPDY_run(daemon);
-        if(0 == beginning)
-        {
-	  beginning = monotonic_time ();
-        }
-				/*if(do_sleep)
-				{
-					sleep(TIMEOUT);
-					do_sleep = 0;
-				}*/
-			break;
-		}
-	}
-	while(waitpid(child,&childstatus,WNOHANG) != child);
-
-	if(!new_session || !closed_session)
-	{
-		killchild("child is dead, callback wasn't called");
-	}
-
-	ret = SPDY_get_timeout(daemon, &timeoutlong);
-
-	if(SPDY_YES == ret)
-	{
-		killchild("SPDY_get_timeout returned wrong SPDY_YES after child died");
-	}
-
-	SPDY_stop_daemon(daemon);
-
-	SPDY_deinit();
-
-	return 0;
-}
-
-
-static int
-childproc()
-{
-	pid_t devnull;
-	int out;
-
-	out=dup(1);
-        if (-1 == out)
-          abort();
-	//close(0);
-	close(1);
-	close(2);
-	/*devnull = open("/dev/null", O_RDONLY);
-	if (0 != devnull)
-	{
-		dup2(devnull, 0);
-		close(devnull);
-	}*/
-	devnull = open("/dev/null", O_WRONLY);
-        if (-1 == devnull)
-          abort ();
-	if (1 != devnull)
-	{
-		dup2(devnull, 1);
-		close(devnull);
-	}
-	devnull = open("/dev/null", O_WRONLY);
-        if (-1 == devnull)
-          abort ();
-	if (2 != devnull)
-	{
-		dup2(devnull, 2);
-		close(devnull);
-	}
-	char *uri;
-	asprintf (&uri, "127.0.0.1:%i", port);
-	execlp ("openssl", "openssl", "s_client", "-connect", uri, NULL);
-	close(1);
-	dup2(out,1);
-	close(out);
-	killparent ("executing openssl failed");
-	return 1;
-}
-
-
-int
-main()
-{
-	port = get_port(11123);
-	parent = getpid();
-
-	child = fork();
-	if (-1 == child)
-	{
-		fprintf(stderr, "can't fork, error %d\n", errno);
-		exit(EXIT_FAILURE);
-	}
-
-	if (child == 0)
-	{
-		int ret = childproc();
-		_exit(ret);
-	}
-	else
-	{
-		int ret = parentproc();
-		exit(ret);
-	}
-	return 1;
-}
diff --git a/src/testspdy/test_struct_namevalue.c b/src/testspdy/test_struct_namevalue.c
deleted file mode 100644
index 54e7934..0000000
--- a/src/testspdy/test_struct_namevalue.c
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
-    This file is part of libmicrospdy
-    Copyright Copyright (C) 2012 Andrey Uzunov
-
-    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/>.
-*/
-
-/**
- * @file struct_namevalue.c
- * @brief  tests all the API functions for handling struct SPDY_NameValue
- * @author Andrey Uzunov
- */
-
-#include "platform.h"
-#include "microspdy.h"
-#include "common.h"
-#include "../microspdy/structures.h"
-#include "../microspdy/alstructures.h"
-
-char *pairs[] = {"one","1","two","2","three","3","four","4","five","5"};
-char *pairs_with_dups[] = {"one","1","two","2","one","11","two","22","three","3","two","222","two","2222","four","","five","5"};//82
-char *pairs_with_empty[] = {"name","","name","value"};
-char *pairs_different[] = {"30","thirty","40","fouthy"};
-int size;
-int size2;
-int brake_at = 3;
-bool flag;
-
-
-int
-iterate_cb (void *cls, const char *name, const char * const * value, int num_values)
-{
-	int *c = (int*)cls;
-
-	if(*c < 0 || *c > size)
-		exit(11);
-
-	if(strcmp(name,pairs[*c]) != 0)
-	{
-		FAIL_TEST("name is wrong\n");
-	}
-
-	if(1 != num_values)
-	{
-		FAIL_TEST("num_values is wrong\n");
-	}
-
-	if(strcmp(value[0],pairs[(*c)+1]) != 0)
-	{
-		FAIL_TEST("value is wrong\n");
-	}
-
-	(*c)+=2;
-
-	return SPDY_YES;
-}
-
-int
-iterate_brake_cb (void *cls, const char *name, const char * const *value, int num_values)
-{
-  (void)name;
-  (void)value;
-  (void)num_values;
-
-	int *c = (int*)cls;
-
-	if(*c < 0 || *c >= brake_at)
-	{
-		FAIL_TEST("iteration was not interrupted\n");
-	}
-
-	(*c)++;
-
-	if(*c == brake_at) return SPDY_NO;
-
-	return SPDY_YES;
-}
-
-int
-main()
-{
-	SPDY_init();
-
-	const char *const*value;
-	const char *const*value2;
-	int i;
-	int j;
-	int cls = 0;
-	int ret;
-	int ret2;
-	void *ob1;
-	void *ob2;
-	void *ob3;
-	void *stream;
-	char data[] = "anything";
-	struct SPDY_NameValue *container;
-	struct SPDY_NameValue *container2;
-	struct SPDY_NameValue *container3;
-	struct SPDY_NameValue *container_arr[2];
-
-	size = sizeof(pairs)/sizeof(pairs[0]);
-
-	if(NULL == (container = SPDY_name_value_create ()))
-	{
-		FAIL_TEST("SPDY_name_value_create failed\n");
-	}
-
-	if(NULL != SPDY_name_value_lookup (container, "anything", &ret))
-	{
-		FAIL_TEST("SPDY_name_value_lookup failed\n");
-	}
-
-	if(SPDY_name_value_iterate (container, NULL, NULL) != 0)
-	{
-		FAIL_TEST("SPDY_name_value_iterate failed\n");
-	}
-
-	for(i=0;i<size; i+=2)
-	{
-		if(SPDY_YES != SPDY_name_value_add(container,pairs[i],pairs[i+1]))
-		{
-			FAIL_TEST("SPDY_name_value_add failed\n");
-		}
-
-		if(SPDY_name_value_iterate (container, NULL, NULL) != ((i / 2) + 1))
-		{
-			FAIL_TEST("SPDY_name_value_iterate failed\n");
-		}
-	}
-
-	if(NULL != SPDY_name_value_lookup (container, "anything", &ret))
-	{
-		FAIL_TEST("SPDY_name_value_lookup failed\n");
-	}
-
-	for(i=size - 2; i >= 0; i-=2)
-	{
-		value = SPDY_name_value_lookup(container,pairs[i], &ret);
-		if(NULL == value || 1 !=ret || strcmp(value[0], pairs[i+1]) != 0)
-		{
-			printf("%p; %i; %i\n", value, ret,
-                               (NULL == value) ? -1 : strcmp(value[0], pairs[i+1]));
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-		}
-	}
-
-	SPDY_name_value_iterate (container, &iterate_cb, &cls);
-
-	cls = 0;
-	if(SPDY_name_value_iterate (container, &iterate_brake_cb, &cls) != brake_at)
-	{
-		FAIL_TEST("SPDY_name_value_iterate with brake failed\n");
-	}
-
-	SPDY_name_value_destroy(container);
-
-	//check everything with NULL values
-	for(i=0; i<7; ++i)
-	{
-		printf("%i ",i);
-		ob1 = (i & 4) ? data : NULL;
-		ob2 = (i & 2) ? data : NULL;
-		ob3 = (i & 1) ? data : NULL;
-		if(SPDY_INPUT_ERROR != SPDY_name_value_add(ob1,ob2,ob3))
-		{
-			FAIL_TEST("SPDY_name_value_add with NULLs failed\n");
-		}
-	}
-	printf("\n");
-	fflush(stdout);
-
-	if(SPDY_INPUT_ERROR != SPDY_name_value_iterate(NULL,NULL,NULL))
-	{
-		FAIL_TEST("SPDY_name_value_iterate with NULLs failed\n");
-	}
-
-	for(i=0; i<7; ++i)
-	{
-		printf("%i ",i);
-		ob1 = (i & 4) ? data : NULL;
-		ob2 = (i & 2) ? data : NULL;
-		ob3 = (i & 1) ? data : NULL;
-		if(NULL != SPDY_name_value_lookup(ob1,ob2,ob3))
-		{
-			FAIL_TEST("SPDY_name_value_lookup with NULLs failed\n");
-		}
-	}
-	printf("\n");
-	SPDY_name_value_destroy(NULL);
-
-	if(NULL == (container = SPDY_name_value_create ()))
-	{
-		FAIL_TEST("SPDY_name_value_create failed\n");
-	}
-
-	size = sizeof(pairs_with_dups)/sizeof(pairs_with_dups[0]);
-
-	for(i=0;i<size; i+=2)
-	{
-		if(SPDY_YES != SPDY_name_value_add(container,pairs_with_dups[i],pairs_with_dups[i+1]))
-		{
-			FAIL_TEST("SPDY_name_value_add failed\n");
-		}
-	}
-	if(SPDY_name_value_iterate (container, NULL, NULL) != atoi(pairs_with_dups[size - 1]))
-	{
-		FAIL_TEST("SPDY_name_value_iterate failed\n");
-	}
-	for(i=size - 2; i >= 0; i-=2)
-	{
-		value = SPDY_name_value_lookup(container,pairs_with_dups[i], &ret);
-		if(NULL == value)
-		{
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-		}
-		flag = false;
-		for(j=0; j<ret; ++j)
-			if(0 == strcmp(pairs_with_dups[i + 1], value[j]))
-			{
-				if(flag)
-					FAIL_TEST("SPDY_name_value_lookup failed\n");
-				flag=true;
-			}
-
-		if(!flag)
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-	}
-	if(SPDY_NO != SPDY_name_value_add(container,pairs_with_dups[0],pairs_with_dups[1]))
-		FAIL_TEST("SPDY_name_value_add failed\n");
-
-	SPDY_name_value_destroy(container);
-
-	if(NULL == (container = SPDY_name_value_create ()))
-	{
-		FAIL_TEST("SPDY_name_value_create failed\n");
-	}
-
-	size = sizeof(pairs_with_empty)/sizeof(pairs_with_empty[0]);
-
-	for(i=0;i<size; i+=2)
-	{
-		if(SPDY_YES != SPDY_name_value_add(container,pairs_with_empty[i],pairs_with_empty[i+1]))
-		{
-			FAIL_TEST("SPDY_name_value_add failed\n");
-		}
-		value = SPDY_name_value_lookup(container,pairs_with_empty[i], &ret);
-		if(NULL == value || 1 != ret)
-		{
-			printf("%p; %i\n", value, ret);
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-		}
-	}
-
-	ret = SPDY_name_value_iterate(container, NULL, NULL);
-	if(SPDY_INPUT_ERROR != SPDY_name_value_add(container, "capitalLeter","anything")
-		|| SPDY_name_value_iterate(container, NULL, NULL) != ret)
-	{
-		FAIL_TEST("SPDY_name_value_add failed\n");
-	}
-
-	SPDY_name_value_destroy(container);
-
-	if(NULL == (container = SPDY_name_value_create ()))
-	{
-		FAIL_TEST("SPDY_name_value_create failed\n");
-	}
-
-	size = sizeof(pairs_with_dups)/sizeof(pairs_with_dups[0]);
-
-	for(i=0;i<size; i+=2)
-	{
-		if(SPDY_YES != SPDY_name_value_add(container,pairs_with_dups[i],pairs_with_dups[i+1]))
-		{
-			FAIL_TEST("SPDY_name_value_add failed\n");
-		}
-	}
-
-	if(NULL == (container2 = SPDY_name_value_create ()))
-	{
-		FAIL_TEST("SPDY_name_value_create failed\n");
-	}
-
-	size2 = sizeof(pairs_different)/sizeof(pairs_different[0]);
-
-	for(i=0;i<size2; i+=2)
-	{
-		if(SPDY_YES != SPDY_name_value_add(container2,pairs_different[i],pairs_different[i+1]))
-		{
-			FAIL_TEST("SPDY_name_value_add failed\n");
-		}
-	}
-
-	container_arr[0] = container;
-	container_arr[1] = container2;
-	if(0 > (ret = SPDYF_name_value_to_stream(container_arr, 2, &stream)) || NULL == stream)
-		FAIL_TEST("SPDYF_name_value_to_stream failed\n");
-	ret = SPDYF_name_value_from_stream(stream, ret, &container3);
-	if(SPDY_YES != ret)
-		FAIL_TEST("SPDYF_name_value_from_stream failed\n");
-
-	if(SPDY_name_value_iterate(container3, NULL, NULL)
-		!= (SPDY_name_value_iterate(container, NULL, NULL) + SPDY_name_value_iterate(container2, NULL, NULL)))
-		FAIL_TEST("SPDYF_name_value_from_stream failed\n");
-
-	for(i=size - 2; i >= 0; i-=2)
-	{
-		value = SPDY_name_value_lookup(container,pairs_with_dups[i], &ret);
-		if(NULL == value)
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-		value2 = SPDY_name_value_lookup(container3,pairs_with_dups[i], &ret2);
-		if(NULL == value2)
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-
-		for(j=0; j<ret; ++j)
-			if(0 != strcmp(value2[j], value[j]))
-				FAIL_TEST("SPDY_name_value_lookup failed\n");
-	}
-	for(i=size2 - 2; i >= 0; i-=2)
-	{
-		value = SPDY_name_value_lookup(container2,pairs_different[i], &ret);
-		if(NULL == value)
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-		value2 = SPDY_name_value_lookup(container3,pairs_different[i], &ret2);
-		if(NULL == value2)
-			FAIL_TEST("SPDY_name_value_lookup failed\n");
-
-		for(j=0; j<ret; ++j)
-			if(0 != strcmp(value2[j], value[j]))
-				FAIL_TEST("SPDY_name_value_lookup failed\n");
-	}
-
-	SPDY_deinit();
-
-	return 0;
-}
diff --git a/src/testzzuf/.gitignore b/src/testzzuf/.gitignore
new file mode 100644
index 0000000..e57a176
--- /dev/null
+++ b/src/testzzuf/.gitignore
@@ -0,0 +1,44 @@
+/test_put_large11
+/test_put_large
+/test_put_chunked
+/test_put11
+/test_put
+/test_post_form11
+/test_post_form
+/test_post11
+/test_post
+/test_long_header
+/test_get_chunked
+/test_get11
+/test_get
+/daemontest_put.gcno
+/daemontest_long_header.gcda
+/daemontest_get.gcno
+/daemontest_postform.gcda
+/daemontest_put_chunked.gcda
+/daemontest_long_header
+/daemontest_large_put.gcno
+/daemontest_put
+/daemontest_put_chunked
+/daemontest_postform
+/daemontest_put11
+/daemontest_postform11
+/daemontest_get_chunked.gcda
+/daemontest_post.gcda
+/daemontest_large_put
+/daemontest_large_put11
+/daemontest_post
+/daemontest_post11
+/daemontest_long_header.gcno
+/daemontest_postform.gcno
+/daemontest_put_chunked.gcno
+/daemontest_get_chunked.gcno
+/daemontest_put.gcda
+/daemontest_post.gcno
+/daemontest_get.gcda
+/daemontest_large_put.gcda
+/daemontest_get
+/daemontest_get_chunked
+/daemontest_get11
+*.exe
+test_*[a-z0-9_][a-z0-9_][a-z0-9_]
diff --git a/src/testzzuf/Makefile.am b/src/testzzuf/Makefile.am
index 329fe04..69c6df8 100644
--- a/src/testzzuf/Makefile.am
+++ b/src/testzzuf/Makefile.am
@@ -1,16 +1,34 @@
 # This Makefile.am is in the public domain
 SUBDIRS  = .
 
+AM_CPPFLAGS = \
+  -I$(top_srcdir)/src/include \
+  -DMHD_CPU_COUNT=$(CPU_COUNT) \
+  $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS)
+
+AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@
+
+AM_LDFLAGS = $(LDFLAGS_ac)
+
+AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac)
+
 if USE_COVERAGE
-  AM_CFLAGS = -fprofile-arcs -ftest-coverage
+  AM_CFLAGS += -fprofile-arcs -ftest-coverage
 endif
 
+LDADD = \
+  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
+  @LIBCURL@
 
-AM_CPPFLAGS = -I$(top_srcdir)/src/include \
-  $(LIBCURL_CPPFLAGS)
+$(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile
+	@echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \
+	$(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la
 
 EXTRA_DIST = README socat.c
 
+THREAD_ONLY_TESTS = \
+  test_long_header
+
 check_PROGRAMS = \
   test_get \
   test_get_chunked \
@@ -23,87 +41,60 @@
   test_post11 \
   test_post_form11 \
   test_put11 \
-  test_put_large11 \
-  test_long_header 
+  test_put_large11
+
+.NOTPARALLEL:
+
+
+if USE_POSIX_THREADS
+check_PROGRAMS += \
+  $(THREAD_ONLY_TESTS)
+endif
+if USE_W32_THREADS
+check_PROGRAMS += \
+  $(THREAD_ONLY_TESTS)
+endif
+
 
 TESTS = $(check_PROGRAMS)
 
 test_get_SOURCES = \
   test_get.c
-test_get_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_get_chunked_SOURCES = \
   test_get_chunked.c
-test_get_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_post_SOURCES = \
   test_post.c
-test_post_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_post_form_SOURCES = \
   test_post_form.c
-test_post_form_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_put_SOURCES = \
   test_put.c
-test_put_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_put_chunked_SOURCES = \
   test_put_chunked.c
-test_put_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_put_large_SOURCES = \
   test_put_large.c
-test_put_large_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 
 
 test_get11_SOURCES = \
   test_get.c
-test_get11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_post11_SOURCES = \
   test_post.c
-test_post11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_post_form11_SOURCES = \
   test_post_form.c
-test_post_form11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_put11_SOURCES = \
   test_put.c
-test_put11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_put_large11_SOURCES = \
   test_put_large.c
-test_put_large11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
 
 test_long_header_SOURCES = \
   test_long_header.c
-test_long_header_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
diff --git a/src/testzzuf/Makefile.in b/src/testzzuf/Makefile.in
deleted file mode 100644
index da555b8..0000000
--- a/src/testzzuf/Makefile.in
+++ /dev/null
@@ -1,1420 +0,0 @@
-# Makefile.in generated by automake 1.14.1 from Makefile.am.
-# @configure_input@
-
-# Copyright (C) 1994-2013 Free Software Foundation, Inc.
-
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-@SET_MAKE@
-VPATH = @srcdir@
-am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
-am__make_running_with_option = \
-  case $${target_option-} in \
-      ?) ;; \
-      *) echo "am__make_running_with_option: internal error: invalid" \
-              "target option '$${target_option-}' specified" >&2; \
-         exit 1;; \
-  esac; \
-  has_opt=no; \
-  sane_makeflags=$$MAKEFLAGS; \
-  if $(am__is_gnu_make); then \
-    sane_makeflags=$$MFLAGS; \
-  else \
-    case $$MAKEFLAGS in \
-      *\\[\ \	]*) \
-        bs=\\; \
-        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
-          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
-    esac; \
-  fi; \
-  skip_next=no; \
-  strip_trailopt () \
-  { \
-    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
-  }; \
-  for flg in $$sane_makeflags; do \
-    test $$skip_next = yes && { skip_next=no; continue; }; \
-    case $$flg in \
-      *=*|--*) continue;; \
-        -*I) strip_trailopt 'I'; skip_next=yes;; \
-      -*I?*) strip_trailopt 'I';; \
-        -*O) strip_trailopt 'O'; skip_next=yes;; \
-      -*O?*) strip_trailopt 'O';; \
-        -*l) strip_trailopt 'l'; skip_next=yes;; \
-      -*l?*) strip_trailopt 'l';; \
-      -[dEDm]) skip_next=yes;; \
-      -[JT]) skip_next=yes;; \
-    esac; \
-    case $$flg in \
-      *$$target_option*) has_opt=yes; break;; \
-    esac; \
-  done; \
-  test $$has_opt = yes
-am__make_dryrun = (target_option=n; $(am__make_running_with_option))
-am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
-pkgdatadir = $(datadir)/@PACKAGE@
-pkgincludedir = $(includedir)/@PACKAGE@
-pkglibdir = $(libdir)/@PACKAGE@
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-build_triplet = @build@
-host_triplet = @host@
-check_PROGRAMS = test_get$(EXEEXT) test_get_chunked$(EXEEXT) \
-	test_post$(EXEEXT) test_post_form$(EXEEXT) test_put$(EXEEXT) \
-	test_put_chunked$(EXEEXT) test_put_large$(EXEEXT) \
-	test_get11$(EXEEXT) test_post11$(EXEEXT) \
-	test_post_form11$(EXEEXT) test_put11$(EXEEXT) \
-	test_put_large11$(EXEEXT) test_long_header$(EXEEXT)
-subdir = src/testzzuf
-DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
-	$(top_srcdir)/depcomp $(top_srcdir)/test-driver README
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \
-	$(top_srcdir)/m4/ax_append_flag.m4 \
-	$(top_srcdir)/m4/ax_check_compile_flag.m4 \
-	$(top_srcdir)/m4/ax_check_link_flag.m4 \
-	$(top_srcdir)/m4/ax_check_openssl.m4 \
-	$(top_srcdir)/m4/ax_count_cpus.m4 \
-	$(top_srcdir)/m4/ax_have_epoll.m4 \
-	$(top_srcdir)/m4/ax_pthread.m4 \
-	$(top_srcdir)/m4/ax_require_defined.m4 \
-	$(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \
-	$(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \
-	$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
-	$(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \
-	$(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
-	$(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/MHD_config.h
-CONFIG_CLEAN_FILES =
-CONFIG_CLEAN_VPATH_FILES =
-am_test_get_OBJECTS = test_get.$(OBJEXT)
-test_get_OBJECTS = $(am_test_get_OBJECTS)
-test_get_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_lt = $(am__v_lt_@AM_V@)
-am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
-am__v_lt_0 = --silent
-am__v_lt_1 = 
-am_test_get11_OBJECTS = test_get.$(OBJEXT)
-test_get11_OBJECTS = $(am_test_get11_OBJECTS)
-test_get11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_get_chunked_OBJECTS = test_get_chunked.$(OBJEXT)
-test_get_chunked_OBJECTS = $(am_test_get_chunked_OBJECTS)
-test_get_chunked_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_long_header_OBJECTS = test_long_header.$(OBJEXT)
-test_long_header_OBJECTS = $(am_test_long_header_OBJECTS)
-test_long_header_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post_OBJECTS = test_post.$(OBJEXT)
-test_post_OBJECTS = $(am_test_post_OBJECTS)
-test_post_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post11_OBJECTS = test_post.$(OBJEXT)
-test_post11_OBJECTS = $(am_test_post11_OBJECTS)
-test_post11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post_form_OBJECTS = test_post_form.$(OBJEXT)
-test_post_form_OBJECTS = $(am_test_post_form_OBJECTS)
-test_post_form_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_post_form11_OBJECTS = test_post_form.$(OBJEXT)
-test_post_form11_OBJECTS = $(am_test_post_form11_OBJECTS)
-test_post_form11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put_OBJECTS = test_put.$(OBJEXT)
-test_put_OBJECTS = $(am_test_put_OBJECTS)
-test_put_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put11_OBJECTS = test_put.$(OBJEXT)
-test_put11_OBJECTS = $(am_test_put11_OBJECTS)
-test_put11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put_chunked_OBJECTS = test_put_chunked.$(OBJEXT)
-test_put_chunked_OBJECTS = $(am_test_put_chunked_OBJECTS)
-test_put_chunked_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put_large_OBJECTS = test_put_large.$(OBJEXT)
-test_put_large_OBJECTS = $(am_test_put_large_OBJECTS)
-test_put_large_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-am_test_put_large11_OBJECTS = test_put_large.$(OBJEXT)
-test_put_large11_OBJECTS = $(am_test_put_large11_OBJECTS)
-test_put_large11_DEPENDENCIES =  \
-	$(top_builddir)/src/microhttpd/libmicrohttpd.la
-AM_V_P = $(am__v_P_@AM_V@)
-am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
-am__v_P_0 = false
-am__v_P_1 = :
-AM_V_GEN = $(am__v_GEN_@AM_V@)
-am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
-am__v_GEN_0 = @echo "  GEN     " $@;
-am__v_GEN_1 = 
-AM_V_at = $(am__v_at_@AM_V@)
-am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
-am__v_at_0 = @
-am__v_at_1 = 
-DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-am__mv = mv -f
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
-	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
-	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
-	$(AM_CFLAGS) $(CFLAGS)
-AM_V_CC = $(am__v_CC_@AM_V@)
-am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
-am__v_CC_0 = @echo "  CC      " $@;
-am__v_CC_1 = 
-CCLD = $(CC)
-LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
-	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
-	$(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CCLD = $(am__v_CCLD_@AM_V@)
-am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
-am__v_CCLD_0 = @echo "  CCLD    " $@;
-am__v_CCLD_1 = 
-SOURCES = $(test_get_SOURCES) $(test_get11_SOURCES) \
-	$(test_get_chunked_SOURCES) $(test_long_header_SOURCES) \
-	$(test_post_SOURCES) $(test_post11_SOURCES) \
-	$(test_post_form_SOURCES) $(test_post_form11_SOURCES) \
-	$(test_put_SOURCES) $(test_put11_SOURCES) \
-	$(test_put_chunked_SOURCES) $(test_put_large_SOURCES) \
-	$(test_put_large11_SOURCES)
-DIST_SOURCES = $(test_get_SOURCES) $(test_get11_SOURCES) \
-	$(test_get_chunked_SOURCES) $(test_long_header_SOURCES) \
-	$(test_post_SOURCES) $(test_post11_SOURCES) \
-	$(test_post_form_SOURCES) $(test_post_form11_SOURCES) \
-	$(test_put_SOURCES) $(test_put11_SOURCES) \
-	$(test_put_chunked_SOURCES) $(test_put_large_SOURCES) \
-	$(test_put_large11_SOURCES)
-RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
-	ctags-recursive dvi-recursive html-recursive info-recursive \
-	install-data-recursive install-dvi-recursive \
-	install-exec-recursive install-html-recursive \
-	install-info-recursive install-pdf-recursive \
-	install-ps-recursive install-recursive installcheck-recursive \
-	installdirs-recursive pdf-recursive ps-recursive \
-	tags-recursive uninstall-recursive
-am__can_run_installinfo = \
-  case $$AM_UPDATE_INFO_DIR in \
-    n|no|NO) false;; \
-    *) (install-info --version) >/dev/null 2>&1;; \
-  esac
-RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
-  distclean-recursive maintainer-clean-recursive
-am__recursive_targets = \
-  $(RECURSIVE_TARGETS) \
-  $(RECURSIVE_CLEAN_TARGETS) \
-  $(am__extra_recursive_targets)
-AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
-	check recheck distdir
-am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
-# Read a list of newline-separated strings from the standard input,
-# and print each of them once, without duplicates.  Input order is
-# *not* preserved.
-am__uniquify_input = $(AWK) '\
-  BEGIN { nonempty = 0; } \
-  { items[$$0] = 1; nonempty = 1; } \
-  END { if (nonempty) { for (i in items) print i; }; } \
-'
-# Make sure the list of sources is unique.  This is necessary because,
-# e.g., the same source file might be shared among _SOURCES variables
-# for different programs/libraries.
-am__define_uniq_tagged_files = \
-  list='$(am__tagged_files)'; \
-  unique=`for i in $$list; do \
-    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
-  done | $(am__uniquify_input)`
-ETAGS = etags
-CTAGS = ctags
-am__tty_colors_dummy = \
-  mgn= red= grn= lgn= blu= brg= std=; \
-  am__color_tests=no
-am__tty_colors = { \
-  $(am__tty_colors_dummy); \
-  if test "X$(AM_COLOR_TESTS)" = Xno; then \
-    am__color_tests=no; \
-  elif test "X$(AM_COLOR_TESTS)" = Xalways; then \
-    am__color_tests=yes; \
-  elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \
-    am__color_tests=yes; \
-  fi; \
-  if test $$am__color_tests = yes; then \
-    red=''; \
-    grn=''; \
-    lgn=''; \
-    blu=''; \
-    mgn=''; \
-    brg=''; \
-    std=''; \
-  fi; \
-}
-am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
-am__vpath_adj = case $$p in \
-    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
-    *) f=$$p;; \
-  esac;
-am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
-am__install_max = 40
-am__nobase_strip_setup = \
-  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
-am__nobase_strip = \
-  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
-am__nobase_list = $(am__nobase_strip_setup); \
-  for p in $$list; do echo "$$p $$p"; done | \
-  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
-  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
-    if (++n[$$2] == $(am__install_max)) \
-      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
-    END { for (dir in files) print dir, files[dir] }'
-am__base_list = \
-  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
-  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
-am__uninstall_files_from_dir = { \
-  test -z "$$files" \
-    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
-    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
-         $(am__cd) "$$dir" && rm -f $$files; }; \
-  }
-am__recheck_rx = ^[ 	]*:recheck:[ 	]*
-am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
-am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
-# A command that, given a newline-separated list of test names on the
-# standard input, print the name of the tests that are to be re-run
-# upon "make recheck".
-am__list_recheck_tests = $(AWK) '{ \
-  recheck = 1; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-        { \
-          if ((getline line2 < ($$0 ".log")) < 0) \
-	    recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \
-        { \
-          recheck = 0; \
-          break; \
-        } \
-      else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \
-        { \
-          break; \
-        } \
-    }; \
-  if (recheck) \
-    print $$0; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# A command that, given a newline-separated list of test names on the
-# standard input, create the global log from their .trs and .log files.
-am__create_global_log = $(AWK) ' \
-function fatal(msg) \
-{ \
-  print "fatal: making $@: " msg | "cat >&2"; \
-  exit 1; \
-} \
-function rst_section(header) \
-{ \
-  print header; \
-  len = length(header); \
-  for (i = 1; i <= len; i = i + 1) \
-    printf "="; \
-  printf "\n\n"; \
-} \
-{ \
-  copy_in_global_log = 1; \
-  global_test_result = "RUN"; \
-  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
-    { \
-      if (rc < 0) \
-         fatal("failed to read from " $$0 ".trs"); \
-      if (line ~ /$(am__global_test_result_rx)/) \
-        { \
-          sub("$(am__global_test_result_rx)", "", line); \
-          sub("[ 	]*$$", "", line); \
-          global_test_result = line; \
-        } \
-      else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \
-        copy_in_global_log = 0; \
-    }; \
-  if (copy_in_global_log) \
-    { \
-      rst_section(global_test_result ": " $$0); \
-      while ((rc = (getline line < ($$0 ".log"))) != 0) \
-      { \
-        if (rc < 0) \
-          fatal("failed to read from " $$0 ".log"); \
-        print line; \
-      }; \
-      printf "\n"; \
-    }; \
-  close ($$0 ".trs"); \
-  close ($$0 ".log"); \
-}'
-# Restructured Text title.
-am__rst_title = { sed 's/.*/   &   /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; }
-# Solaris 10 'make', and several other traditional 'make' implementations,
-# pass "-e" to $(SHELL), and POSIX 2008 even requires this.  Work around it
-# by disabling -e (using the XSI extension "set +e") if it's set.
-am__sh_e_setup = case $$- in *e*) set +e;; esac
-# Default flags passed to test drivers.
-am__common_driver_flags = \
-  --color-tests "$$am__color_tests" \
-  --enable-hard-errors "$$am__enable_hard_errors" \
-  --expect-failure "$$am__expect_failure"
-# To be inserted before the command running the test.  Creates the
-# directory for the log if needed.  Stores in $dir the directory
-# containing $f, in $tst the test, in $log the log.  Executes the
-# developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and
-# passes TESTS_ENVIRONMENT.  Set up options for the wrapper that
-# will run the test scripts (or their associated LOG_COMPILER, if
-# thy have one).
-am__check_pre = \
-$(am__sh_e_setup);					\
-$(am__vpath_adj_setup) $(am__vpath_adj)			\
-$(am__tty_colors);					\
-srcdir=$(srcdir); export srcdir;			\
-case "$@" in						\
-  */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;;	\
-    *) am__odir=.;; 					\
-esac;							\
-test "x$$am__odir" = x"." || test -d "$$am__odir" 	\
-  || $(MKDIR_P) "$$am__odir" || exit $$?;		\
-if test -f "./$$f"; then dir=./;			\
-elif test -f "$$f"; then dir=;				\
-else dir="$(srcdir)/"; fi;				\
-tst=$$dir$$f; log='$@'; 				\
-if test -n '$(DISABLE_HARD_ERRORS)'; then		\
-  am__enable_hard_errors=no; 				\
-else							\
-  am__enable_hard_errors=yes; 				\
-fi; 							\
-case " $(XFAIL_TESTS) " in				\
-  *[\ \	]$$f[\ \	]* | *[\ \	]$$dir$$f[\ \	]*) \
-    am__expect_failure=yes;;				\
-  *)							\
-    am__expect_failure=no;;				\
-esac; 							\
-$(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT)
-# A shell command to get the names of the tests scripts with any registered
-# extension removed (i.e., equivalently, the names of the test logs, with
-# the '.log' extension removed).  The result is saved in the shell variable
-# '$bases'.  This honors runtime overriding of TESTS and TEST_LOGS.  Sadly,
-# we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)",
-# since that might cause problem with VPATH rewrites for suffix-less tests.
-# See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'.
-am__set_TESTS_bases = \
-  bases='$(TEST_LOGS)'; \
-  bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \
-  bases=`echo $$bases`
-RECHECK_LOGS = $(TEST_LOGS)
-TEST_SUITE_LOG = test-suite.log
-TEST_EXTENSIONS = @EXEEXT@ .test
-LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)
-am__set_b = \
-  case '$@' in \
-    */*) \
-      case '$*' in \
-        */*) b='$*';; \
-          *) b=`echo '$@' | sed 's/\.log$$//'`; \
-       esac;; \
-    *) \
-      b='$*';; \
-  esac
-am__test_logs1 = $(TESTS:=.log)
-am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log)
-TEST_LOGS = $(am__test_logs2:.test.log=.log)
-TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver
-TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
-	$(TEST_LOG_FLAGS)
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-am__relativize = \
-  dir0=`pwd`; \
-  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
-  sed_rest='s,^[^/]*/*,,'; \
-  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
-  sed_butlast='s,/*[^/]*$$,,'; \
-  while test -n "$$dir1"; do \
-    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
-    if test "$$first" != "."; then \
-      if test "$$first" = ".."; then \
-        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
-        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
-      else \
-        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
-        if test "$$first2" = "$$first"; then \
-          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
-        else \
-          dir2="../$$dir2"; \
-        fi; \
-        dir0="$$dir0"/"$$first"; \
-      fi; \
-    fi; \
-    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
-  done; \
-  reldir="$$dir2"
-ACLOCAL = @ACLOCAL@
-AMTAR = @AMTAR@
-AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AR = @AR@
-AS = @AS@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
-AWK = @AWK@
-CC = @CC@
-CCDEPMODE = @CCDEPMODE@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-CPPFLAGS = @CPPFLAGS@
-CPU_COUNT = @CPU_COUNT@
-CYGPATH_W = @CYGPATH_W@
-DEFS = @DEFS@
-DEPDIR = @DEPDIR@
-DLLTOOL = @DLLTOOL@
-DSYMUTIL = @DSYMUTIL@
-DUMPBIN = @DUMPBIN@
-ECHO_C = @ECHO_C@
-ECHO_N = @ECHO_N@
-ECHO_T = @ECHO_T@
-EGREP = @EGREP@
-EXEEXT = @EXEEXT@
-FGREP = @FGREP@
-GNUTLS_CFLAGS = @GNUTLS_CFLAGS@
-GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@
-GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@
-GNUTLS_LIBS = @GNUTLS_LIBS@
-GREP = @GREP@
-HAVE_CURL_BINARY = @HAVE_CURL_BINARY@
-HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@
-HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@
-INSTALL = @INSTALL@
-INSTALL_DATA = @INSTALL_DATA@
-INSTALL_PROGRAM = @INSTALL_PROGRAM@
-INSTALL_SCRIPT = @INSTALL_SCRIPT@
-INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
-LD = @LD@
-LDFLAGS = @LDFLAGS@
-LIBCURL = @LIBCURL@
-LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@
-LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@
-LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@
-LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@
-LIBOBJS = @LIBOBJS@
-LIBS = @LIBS@
-LIBSPDY_VERSION_AGE = @LIBSPDY_VERSION_AGE@
-LIBSPDY_VERSION_CURRENT = @LIBSPDY_VERSION_CURRENT@
-LIBSPDY_VERSION_REVISION = @LIBSPDY_VERSION_REVISION@
-LIBTOOL = @LIBTOOL@
-LIB_VERSION_AGE = @LIB_VERSION_AGE@
-LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@
-LIB_VERSION_REVISION = @LIB_VERSION_REVISION@
-LIPO = @LIPO@
-LN_S = @LN_S@
-LTLIBOBJS = @LTLIBOBJS@
-MAKEINFO = @MAKEINFO@
-MANIFEST_TOOL = @MANIFEST_TOOL@
-MHD_LIBDEPS = @MHD_LIBDEPS@
-MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@
-MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@
-MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@
-MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@
-MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@
-MKDIR_P = @MKDIR_P@
-MS_LIB_TOOL = @MS_LIB_TOOL@
-NM = @NM@
-NMEDIT = @NMEDIT@
-OBJDUMP = @OBJDUMP@
-OBJEXT = @OBJEXT@
-OPENSSL_INCLUDES = @OPENSSL_INCLUDES@
-OPENSSL_LDFLAGS = @OPENSSL_LDFLAGS@
-OPENSSL_LIBS = @OPENSSL_LIBS@
-OTOOL = @OTOOL@
-OTOOL64 = @OTOOL64@
-PACKAGE = @PACKAGE@
-PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
-PACKAGE_NAME = @PACKAGE_NAME@
-PACKAGE_STRING = @PACKAGE_STRING@
-PACKAGE_TARNAME = @PACKAGE_TARNAME@
-PACKAGE_URL = @PACKAGE_URL@
-PACKAGE_VERSION = @PACKAGE_VERSION@
-PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@
-PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@
-PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@
-PATH_SEPARATOR = @PATH_SEPARATOR@
-PKG_CONFIG = @PKG_CONFIG@
-PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
-PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
-PTHREAD_CC = @PTHREAD_CC@
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-RANLIB = @RANLIB@
-RC = @RC@
-SED = @SED@
-SET_MAKE = @SET_MAKE@
-SHELL = @SHELL@
-SPDY_LIBDEPS = @SPDY_LIBDEPS@
-SPDY_LIB_CFLAGS = @SPDY_LIB_CFLAGS@
-SPDY_LIB_CPPFLAGS = @SPDY_LIB_CPPFLAGS@
-SPDY_LIB_LDFLAGS = @SPDY_LIB_LDFLAGS@
-STRIP = @STRIP@
-VERSION = @VERSION@
-_libcurl_config = @_libcurl_config@
-abs_builddir = @abs_builddir@
-abs_srcdir = @abs_srcdir@
-abs_top_builddir = @abs_top_builddir@
-abs_top_srcdir = @abs_top_srcdir@
-ac_ct_AR = @ac_ct_AR@
-ac_ct_CC = @ac_ct_CC@
-ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
-am__include = @am__include@
-am__leading_dot = @am__leading_dot@
-am__quote = @am__quote@
-am__tar = @am__tar@
-am__untar = @am__untar@
-ax_pthread_config = @ax_pthread_config@
-bindir = @bindir@
-build = @build@
-build_alias = @build_alias@
-build_cpu = @build_cpu@
-build_os = @build_os@
-build_vendor = @build_vendor@
-builddir = @builddir@
-datadir = @datadir@
-datarootdir = @datarootdir@
-docdir = @docdir@
-dvidir = @dvidir@
-exec_prefix = @exec_prefix@
-have_socat = @have_socat@
-have_zzuf = @have_zzuf@
-host = @host@
-host_alias = @host_alias@
-host_cpu = @host_cpu@
-host_os = @host_os@
-host_vendor = @host_vendor@
-htmldir = @htmldir@
-includedir = @includedir@
-infodir = @infodir@
-install_sh = @install_sh@
-libdir = @libdir@
-libexecdir = @libexecdir@
-localedir = @localedir@
-localstatedir = @localstatedir@
-lt_cv_objdir = @lt_cv_objdir@
-mandir = @mandir@
-mkdir_p = @mkdir_p@
-oldincludedir = @oldincludedir@
-pdfdir = @pdfdir@
-prefix = @prefix@
-program_transform_name = @program_transform_name@
-psdir = @psdir@
-sbindir = @sbindir@
-sharedstatedir = @sharedstatedir@
-srcdir = @srcdir@
-sysconfdir = @sysconfdir@
-target_alias = @target_alias@
-top_build_prefix = @top_build_prefix@
-top_builddir = @top_builddir@
-top_srcdir = @top_srcdir@
-
-# This Makefile.am is in the public domain
-SUBDIRS = .
-@USE_COVERAGE_TRUE@AM_CFLAGS = -fprofile-arcs -ftest-coverage
-AM_CPPFLAGS = -I$(top_srcdir)/src/include \
-  $(LIBCURL_CPPFLAGS)
-
-EXTRA_DIST = README socat.c
-TESTS = $(check_PROGRAMS)
-test_get_SOURCES = \
-  test_get.c
-
-test_get_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_get_chunked_SOURCES = \
-  test_get_chunked.c
-
-test_get_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_post_SOURCES = \
-  test_post.c
-
-test_post_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_post_form_SOURCES = \
-  test_post_form.c
-
-test_post_form_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_put_SOURCES = \
-  test_put.c
-
-test_put_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_put_chunked_SOURCES = \
-  test_put_chunked.c
-
-test_put_chunked_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_put_large_SOURCES = \
-  test_put_large.c
-
-test_put_large_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_get11_SOURCES = \
-  test_get.c
-
-test_get11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_post11_SOURCES = \
-  test_post.c
-
-test_post11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_post_form11_SOURCES = \
-  test_post_form.c
-
-test_post_form11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_put11_SOURCES = \
-  test_put.c
-
-test_put11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_put_large11_SOURCES = \
-  test_put_large.c
-
-test_put_large11_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-test_long_header_SOURCES = \
-  test_long_header.c
-
-test_long_header_LDADD = \
-  $(top_builddir)/src/microhttpd/libmicrohttpd.la \
-  @LIBCURL@ 
-
-all: all-recursive
-
-.SUFFIXES:
-.SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs
-$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
-	@for dep in $?; do \
-	  case '$(am__configure_deps)' in \
-	    *$$dep*) \
-	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
-	        && { if test -f $@; then exit 0; else break; fi; }; \
-	      exit 1;; \
-	  esac; \
-	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testzzuf/Makefile'; \
-	$(am__cd) $(top_srcdir) && \
-	  $(AUTOMAKE) --gnu src/testzzuf/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
-	@case '$?' in \
-	  *config.status*) \
-	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
-	  *) \
-	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
-	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
-	esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure:  $(am__configure_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
-	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(am__aclocal_m4_deps):
-
-clean-checkPROGRAMS:
-	@list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
-	echo " rm -f" $$list; \
-	rm -f $$list || exit $$?; \
-	test -n "$(EXEEXT)" || exit 0; \
-	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
-	echo " rm -f" $$list; \
-	rm -f $$list
-
-test_get$(EXEEXT): $(test_get_OBJECTS) $(test_get_DEPENDENCIES) $(EXTRA_test_get_DEPENDENCIES) 
-	@rm -f test_get$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_OBJECTS) $(test_get_LDADD) $(LIBS)
-
-test_get11$(EXEEXT): $(test_get11_OBJECTS) $(test_get11_DEPENDENCIES) $(EXTRA_test_get11_DEPENDENCIES) 
-	@rm -f test_get11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get11_OBJECTS) $(test_get11_LDADD) $(LIBS)
-
-test_get_chunked$(EXEEXT): $(test_get_chunked_OBJECTS) $(test_get_chunked_DEPENDENCIES) $(EXTRA_test_get_chunked_DEPENDENCIES) 
-	@rm -f test_get_chunked$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_get_chunked_OBJECTS) $(test_get_chunked_LDADD) $(LIBS)
-
-test_long_header$(EXEEXT): $(test_long_header_OBJECTS) $(test_long_header_DEPENDENCIES) $(EXTRA_test_long_header_DEPENDENCIES) 
-	@rm -f test_long_header$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_long_header_OBJECTS) $(test_long_header_LDADD) $(LIBS)
-
-test_post$(EXEEXT): $(test_post_OBJECTS) $(test_post_DEPENDENCIES) $(EXTRA_test_post_DEPENDENCIES) 
-	@rm -f test_post$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post_OBJECTS) $(test_post_LDADD) $(LIBS)
-
-test_post11$(EXEEXT): $(test_post11_OBJECTS) $(test_post11_DEPENDENCIES) $(EXTRA_test_post11_DEPENDENCIES) 
-	@rm -f test_post11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post11_OBJECTS) $(test_post11_LDADD) $(LIBS)
-
-test_post_form$(EXEEXT): $(test_post_form_OBJECTS) $(test_post_form_DEPENDENCIES) $(EXTRA_test_post_form_DEPENDENCIES) 
-	@rm -f test_post_form$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post_form_OBJECTS) $(test_post_form_LDADD) $(LIBS)
-
-test_post_form11$(EXEEXT): $(test_post_form11_OBJECTS) $(test_post_form11_DEPENDENCIES) $(EXTRA_test_post_form11_DEPENDENCIES) 
-	@rm -f test_post_form11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_post_form11_OBJECTS) $(test_post_form11_LDADD) $(LIBS)
-
-test_put$(EXEEXT): $(test_put_OBJECTS) $(test_put_DEPENDENCIES) $(EXTRA_test_put_DEPENDENCIES) 
-	@rm -f test_put$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put_OBJECTS) $(test_put_LDADD) $(LIBS)
-
-test_put11$(EXEEXT): $(test_put11_OBJECTS) $(test_put11_DEPENDENCIES) $(EXTRA_test_put11_DEPENDENCIES) 
-	@rm -f test_put11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put11_OBJECTS) $(test_put11_LDADD) $(LIBS)
-
-test_put_chunked$(EXEEXT): $(test_put_chunked_OBJECTS) $(test_put_chunked_DEPENDENCIES) $(EXTRA_test_put_chunked_DEPENDENCIES) 
-	@rm -f test_put_chunked$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put_chunked_OBJECTS) $(test_put_chunked_LDADD) $(LIBS)
-
-test_put_large$(EXEEXT): $(test_put_large_OBJECTS) $(test_put_large_DEPENDENCIES) $(EXTRA_test_put_large_DEPENDENCIES) 
-	@rm -f test_put_large$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put_large_OBJECTS) $(test_put_large_LDADD) $(LIBS)
-
-test_put_large11$(EXEEXT): $(test_put_large11_OBJECTS) $(test_put_large11_DEPENDENCIES) $(EXTRA_test_put_large11_DEPENDENCIES) 
-	@rm -f test_put_large11$(EXEEXT)
-	$(AM_V_CCLD)$(LINK) $(test_put_large11_OBJECTS) $(test_put_large11_LDADD) $(LIBS)
-
-mostlyclean-compile:
-	-rm -f *.$(OBJEXT)
-
-distclean-compile:
-	-rm -f *.tab.c
-
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_chunked.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_long_header.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post_form.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_chunked.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_large.Po@am__quote@
-
-.c.o:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
-
-.c.obj:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
-@am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-
-.c.lo:
-@am__fastdepCC_TRUE@	$(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
-@am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
-@am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
-
-mostlyclean-libtool:
-	-rm -f *.lo
-
-clean-libtool:
-	-rm -rf .libs _libs
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run 'make' without going through this Makefile.
-# To change the values of 'make' variables: instead of editing Makefiles,
-# (1) if the variable is set in 'config.status', edit 'config.status'
-#     (which will cause the Makefiles to be regenerated when you run 'make');
-# (2) otherwise, pass the desired values on the 'make' command line.
-$(am__recursive_targets):
-	@fail=; \
-	if $(am__make_keepgoing); then \
-	  failcom='fail=yes'; \
-	else \
-	  failcom='exit 1'; \
-	fi; \
-	dot_seen=no; \
-	target=`echo $@ | sed s/-recursive//`; \
-	case "$@" in \
-	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
-	  *) list='$(SUBDIRS)' ;; \
-	esac; \
-	for subdir in $$list; do \
-	  echo "Making $$target in $$subdir"; \
-	  if test "$$subdir" = "."; then \
-	    dot_seen=yes; \
-	    local_target="$$target-am"; \
-	  else \
-	    local_target="$$target"; \
-	  fi; \
-	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-	  || eval $$failcom; \
-	done; \
-	if test "$$dot_seen" = "no"; then \
-	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
-	fi; test -z "$$fail"
-
-ID: $(am__tagged_files)
-	$(am__define_uniq_tagged_files); mkid -fID $$unique
-tags: tags-recursive
-TAGS: tags
-
-tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	set x; \
-	here=`pwd`; \
-	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
-	  include_option=--etags-include; \
-	  empty_fix=.; \
-	else \
-	  include_option=--include; \
-	  empty_fix=; \
-	fi; \
-	list='$(SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    test ! -f $$subdir/TAGS || \
-	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
-	  fi; \
-	done; \
-	$(am__define_uniq_tagged_files); \
-	shift; \
-	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
-	  test -n "$$unique" || unique=$$empty_fix; \
-	  if test $$# -gt 0; then \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      "$$@" $$unique; \
-	  else \
-	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	      $$unique; \
-	  fi; \
-	fi
-ctags: ctags-recursive
-
-CTAGS: ctags
-ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
-	$(am__define_uniq_tagged_files); \
-	test -z "$(CTAGS_ARGS)$$unique" \
-	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$unique
-
-GTAGS:
-	here=`$(am__cd) $(top_builddir) && pwd` \
-	  && $(am__cd) $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) "$$here"
-cscopelist: cscopelist-recursive
-
-cscopelist-am: $(am__tagged_files)
-	list='$(am__tagged_files)'; \
-	case "$(srcdir)" in \
-	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
-	  *) sdir=$(subdir)/$(srcdir) ;; \
-	esac; \
-	for i in $$list; do \
-	  if test -f "$$i"; then \
-	    echo "$(subdir)/$$i"; \
-	  else \
-	    echo "$$sdir/$$i"; \
-	  fi; \
-	done >> $(top_builddir)/cscope.files
-
-distclean-tags:
-	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-# Recover from deleted '.trs' file; this should ensure that
-# "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create
-# both 'foo.log' and 'foo.trs'.  Break the recipe in two subshells
-# to avoid problems with "make -n".
-.log.trs:
-	rm -f $< $@
-	$(MAKE) $(AM_MAKEFLAGS) $<
-
-# Leading 'am--fnord' is there to ensure the list of targets does not
-# expand to empty, as could happen e.g. with make check TESTS=''.
-am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck)
-am--force-recheck:
-	@:
-
-$(TEST_SUITE_LOG): $(TEST_LOGS)
-	@$(am__set_TESTS_bases); \
-	am__f_ok () { test -f "$$1" && test -r "$$1"; }; \
-	redo_bases=`for i in $$bases; do \
-	              am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \
-	            done`; \
-	if test -n "$$redo_bases"; then \
-	  redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \
-	  redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \
-	  if $(am__make_dryrun); then :; else \
-	    rm -f $$redo_logs && rm -f $$redo_results || exit 1; \
-	  fi; \
-	fi; \
-	if test -n "$$am__remaking_logs"; then \
-	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
-	       "recursion detected" >&2; \
-	else \
-	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
-	fi; \
-	if $(am__make_dryrun); then :; else \
-	  st=0;  \
-	  errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \
-	  for i in $$redo_bases; do \
-	    test -f $$i.trs && test -r $$i.trs \
-	      || { echo "$$errmsg $$i.trs" >&2; st=1; }; \
-	    test -f $$i.log && test -r $$i.log \
-	      || { echo "$$errmsg $$i.log" >&2; st=1; }; \
-	  done; \
-	  test $$st -eq 0 || exit 1; \
-	fi
-	@$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \
-	ws='[ 	]'; \
-	results=`for b in $$bases; do echo $$b.trs; done`; \
-	test -n "$$results" || results=/dev/null; \
-	all=`  grep "^$$ws*:test-result:"           $$results | wc -l`; \
-	pass=` grep "^$$ws*:test-result:$$ws*PASS"  $$results | wc -l`; \
-	fail=` grep "^$$ws*:test-result:$$ws*FAIL"  $$results | wc -l`; \
-	skip=` grep "^$$ws*:test-result:$$ws*SKIP"  $$results | wc -l`; \
-	xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \
-	xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \
-	error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \
-	if test `expr $$fail + $$xpass + $$error` -eq 0; then \
-	  success=true; \
-	else \
-	  success=false; \
-	fi; \
-	br='==================='; br=$$br$$br$$br$$br; \
-	result_count () \
-	{ \
-	    if test x"$$1" = x"--maybe-color"; then \
-	      maybe_colorize=yes; \
-	    elif test x"$$1" = x"--no-color"; then \
-	      maybe_colorize=no; \
-	    else \
-	      echo "$@: invalid 'result_count' usage" >&2; exit 4; \
-	    fi; \
-	    shift; \
-	    desc=$$1 count=$$2; \
-	    if test $$maybe_colorize = yes && test $$count -gt 0; then \
-	      color_start=$$3 color_end=$$std; \
-	    else \
-	      color_start= color_end=; \
-	    fi; \
-	    echo "$${color_start}# $$desc $$count$${color_end}"; \
-	}; \
-	create_testsuite_report () \
-	{ \
-	  result_count $$1 "TOTAL:" $$all   "$$brg"; \
-	  result_count $$1 "PASS: " $$pass  "$$grn"; \
-	  result_count $$1 "SKIP: " $$skip  "$$blu"; \
-	  result_count $$1 "XFAIL:" $$xfail "$$lgn"; \
-	  result_count $$1 "FAIL: " $$fail  "$$red"; \
-	  result_count $$1 "XPASS:" $$xpass "$$red"; \
-	  result_count $$1 "ERROR:" $$error "$$mgn"; \
-	}; \
-	{								\
-	  echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" |	\
-	    $(am__rst_title);						\
-	  create_testsuite_report --no-color;				\
-	  echo;								\
-	  echo ".. contents:: :depth: 2";				\
-	  echo;								\
-	  for b in $$bases; do echo $$b; done				\
-	    | $(am__create_global_log);					\
-	} >$(TEST_SUITE_LOG).tmp || exit 1;				\
-	mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG);			\
-	if $$success; then						\
-	  col="$$grn";							\
-	 else								\
-	  col="$$red";							\
-	  test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG);		\
-	fi;								\
-	echo "$${col}$$br$${std}"; 					\
-	echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}";	\
-	echo "$${col}$$br$${std}"; 					\
-	create_testsuite_report --maybe-color;				\
-	echo "$$col$$br$$std";						\
-	if $$success; then :; else					\
-	  echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}";		\
-	  if test -n "$(PACKAGE_BUGREPORT)"; then			\
-	    echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}";	\
-	  fi;								\
-	  echo "$$col$$br$$std";					\
-	fi;								\
-	$$success || exit 1
-
-check-TESTS:
-	@list='$(RECHECK_LOGS)';           test -z "$$list" || rm -f $$list
-	@list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	trs_list=`for i in $$bases; do echo $$i.trs; done`; \
-	log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \
-	exit $$?;
-recheck: all $(check_PROGRAMS)
-	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-	@set +e; $(am__set_TESTS_bases); \
-	bases=`for i in $$bases; do echo $$i; done \
-	         | $(am__list_recheck_tests)` || exit 1; \
-	log_list=`for i in $$bases; do echo $$i.log; done`; \
-	log_list=`echo $$log_list`; \
-	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \
-	        am__force_recheck=am--force-recheck \
-	        TEST_LOGS="$$log_list"; \
-	exit $$?
-test_get.log: test_get$(EXEEXT)
-	@p='test_get$(EXEEXT)'; \
-	b='test_get'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get_chunked.log: test_get_chunked$(EXEEXT)
-	@p='test_get_chunked$(EXEEXT)'; \
-	b='test_get_chunked'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post.log: test_post$(EXEEXT)
-	@p='test_post$(EXEEXT)'; \
-	b='test_post'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post_form.log: test_post_form$(EXEEXT)
-	@p='test_post_form$(EXEEXT)'; \
-	b='test_post_form'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put.log: test_put$(EXEEXT)
-	@p='test_put$(EXEEXT)'; \
-	b='test_put'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put_chunked.log: test_put_chunked$(EXEEXT)
-	@p='test_put_chunked$(EXEEXT)'; \
-	b='test_put_chunked'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put_large.log: test_put_large$(EXEEXT)
-	@p='test_put_large$(EXEEXT)'; \
-	b='test_put_large'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_get11.log: test_get11$(EXEEXT)
-	@p='test_get11$(EXEEXT)'; \
-	b='test_get11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post11.log: test_post11$(EXEEXT)
-	@p='test_post11$(EXEEXT)'; \
-	b='test_post11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_post_form11.log: test_post_form11$(EXEEXT)
-	@p='test_post_form11$(EXEEXT)'; \
-	b='test_post_form11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put11.log: test_put11$(EXEEXT)
-	@p='test_put11$(EXEEXT)'; \
-	b='test_put11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_put_large11.log: test_put_large11$(EXEEXT)
-	@p='test_put_large11$(EXEEXT)'; \
-	b='test_put_large11'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test_long_header.log: test_long_header$(EXEEXT)
-	@p='test_long_header$(EXEEXT)'; \
-	b='test_long_header'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-.test.log:
-	@p='$<'; \
-	$(am__set_b); \
-	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-@am__EXEEXT_TRUE@.test$(EXEEXT).log:
-@am__EXEEXT_TRUE@	@p='$<'; \
-@am__EXEEXT_TRUE@	$(am__set_b); \
-@am__EXEEXT_TRUE@	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
-@am__EXEEXT_TRUE@	--log-file $$b.log --trs-file $$b.trs \
-@am__EXEEXT_TRUE@	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
-@am__EXEEXT_TRUE@	"$$tst" $(AM_TESTS_FD_REDIRECT)
-
-distdir: $(DISTFILES)
-	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
-	list='$(DISTFILES)'; \
-	  dist_files=`for file in $$list; do echo $$file; done | \
-	  sed -e "s|^$$srcdirstrip/||;t" \
-	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
-	case $$dist_files in \
-	  */*) $(MKDIR_P) `echo "$$dist_files" | \
-			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
-			   sort -u` ;; \
-	esac; \
-	for file in $$dist_files; do \
-	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-	  if test -d $$d/$$file; then \
-	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
-	    if test -d "$(distdir)/$$file"; then \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
-	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
-	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
-	    fi; \
-	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
-	  else \
-	    test -f "$(distdir)/$$file" \
-	    || cp -p $$d/$$file "$(distdir)/$$file" \
-	    || exit 1; \
-	  fi; \
-	done
-	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
-	  if test "$$subdir" = .; then :; else \
-	    $(am__make_dryrun) \
-	      || test -d "$(distdir)/$$subdir" \
-	      || $(MKDIR_P) "$(distdir)/$$subdir" \
-	      || exit 1; \
-	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
-	    $(am__relativize); \
-	    new_distdir=$$reldir; \
-	    dir1=$$subdir; dir2="$(top_distdir)"; \
-	    $(am__relativize); \
-	    new_top_distdir=$$reldir; \
-	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
-	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
-	    ($(am__cd) $$subdir && \
-	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir="$$new_top_distdir" \
-	        distdir="$$new_distdir" \
-		am__remove_distdir=: \
-		am__skip_length_check=: \
-		am__skip_mode_fix=: \
-	        distdir) \
-	      || exit 1; \
-	  fi; \
-	done
-check-am: all-am
-	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
-	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
-	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
-	if test -z '$(STRIP)'; then \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	      install; \
-	else \
-	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
-	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
-	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
-	fi
-mostlyclean-generic:
-	-test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS)
-	-test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs)
-	-test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
-
-clean-generic:
-
-distclean-generic:
-	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-
-maintainer-clean-generic:
-	@echo "This command is intended for maintainers to use"
-	@echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-checkPROGRAMS clean-generic clean-libtool \
-	mostlyclean-am
-
-distclean: distclean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
-	distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-html-am:
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-dvi: install-dvi-recursive
-
-install-dvi-am:
-
-install-exec-am:
-
-install-html: install-html-recursive
-
-install-html-am:
-
-install-info: install-info-recursive
-
-install-info-am:
-
-install-man:
-
-install-pdf: install-pdf-recursive
-
-install-pdf-am:
-
-install-ps: install-ps-recursive
-
-install-ps-am:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
-	-rm -rf ./$(DEPDIR)
-	-rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am:
-
-.MAKE: $(am__recursive_targets) check-am install-am install-strip
-
-.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
-	check-TESTS check-am clean clean-checkPROGRAMS clean-generic \
-	clean-libtool cscopelist-am ctags ctags-am distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am install-dvi \
-	install-dvi-am install-exec install-exec-am install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	installdirs-am maintainer-clean maintainer-clean-generic \
-	mostlyclean mostlyclean-compile mostlyclean-generic \
-	mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \
-	uninstall uninstall-am
-
-
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/src/testzzuf/socat.c b/src/testzzuf/socat.c
index 8743dc9..0ee1474 100644
--- a/src/testzzuf/socat.c
+++ b/src/testzzuf/socat.c
@@ -1,6 +1,6 @@
 /*
      This file is part of libmicrohttpd
-     Copyright (C) 2008 Christian Grothoff
+     Copyright (C) 2008,2016 Christian Grothoff
 
      libmicrohttpd is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -43,7 +43,11 @@
  * long for most user's patience.  So this small
  * value is the default.
  */
+#ifndef _MHD_VHEAVY_TESTS
 #define LOOP_COUNT 10
+#else  /* ! _MHD_VHEAVY_TESTS */
+#define LOOP_COUNT 200
+#endif /* ! _MHD_VHEAVY_TESTS */
 
 #define CURL_TIMEOUT 50L
 
@@ -58,7 +62,6 @@
     "--ratio=0.0:0.75",
     "-n",
     "-A",
-    "--",
     "socat",
     "-lf",
     "/dev/null",
@@ -68,31 +71,30 @@
   };
   zzuf_pid = fork ();
   if (zzuf_pid == -1)
+  {
+    fprintf (stderr, "fork failed: %s\n", strerror (errno));
+    exit (1);
+  }
+  if (zzuf_pid != 0)
+  {
+    (void) sleep (1);                 /* allow zzuf and socat to start */
+    status = 0;
+    if (0 < waitpid (zzuf_pid, &status, WNOHANG))
     {
-      fprintf (stderr, "fork failed: %s\n", strerror (errno));
+      if (WIFEXITED (status))
+        fprintf (stderr,
+                 "zzuf died with status code %d!\n",
+                 WEXITSTATUS (status));
+      if (WIFSIGNALED (status))
+        fprintf (stderr,
+                 "zzuf died from signal %d!\n", WTERMSIG (status));
       exit (1);
     }
-  if (zzuf_pid != 0)
-    {
-      sleep (1);                /* allow zzuf and socat to start */
-      status = 0;
-      if (0 < waitpid (zzuf_pid, &status, WNOHANG))
-        {
-          if (WIFEXITED (status))
-            fprintf (stderr,
-                     "zzuf died with status code %d!\n",
-                     WEXITSTATUS (status));
-          if (WIFSIGNALED (status))
-            fprintf (stderr,
-                     "zzuf died from signal %d!\n", WTERMSIG (status));
-          exit (1);
-        }
-      return;
-    }
-  setpgrp ();
+    return;
+  }
+  setpgid (0, 0);
   execvp ("zzuf", args);
   fprintf (stderr, "execution of `zzuf' failed: %s\n", strerror (errno));
-  zzuf_pid = 0;                 /* fork failed */
   exit (1);
 }
 
@@ -102,13 +104,14 @@
 {
   int status;
   if (zzuf_pid != 0)
-    {
-      if (0 != killpg (zzuf_pid, SIGINT))
-        fprintf (stderr, "Failed to killpg: %s\n", strerror (errno));
-      kill (zzuf_pid, SIGINT);
-      waitpid (zzuf_pid, &status, 0);
-      sleep (1);                /* allow socat to also die in peace */
-    }
+  {
+    if (0 != killpg (zzuf_pid, SIGINT))
+      fprintf (stderr, "Failed to killpg: %s\n", strerror (errno));
+    kill (zzuf_pid, SIGINT);
+    waitpid (zzuf_pid, &status, 0);
+    (void) sleep (1);                 /* allow socat to also die in peace */
+  }
 }
 
+
 /* end of socat.c */
diff --git a/src/testzzuf/test_get.c b/src/testzzuf/test_get.c
index 47cbe12..e2b86ff 100644
--- a/src/testzzuf/test_get.c
+++ b/src/testzzuf/test_get.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -59,31 +59,43 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int ptr;
   const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp (me, method))
     return MHD_NO;              /* unexpected method */
-  if (&ptr != *unused)
-    {
-      *unused = &ptr;
-      return MHD_YES;
-    }
-  *unused = NULL;
+  if (&ptr != *req_cls)
+  {
+    *req_cls = &ptr;
+    return MHD_YES;
+  }
+  *req_cls = NULL;
   response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+                                              (void *) url,
+                                              MHD_RESPMEM_MUST_COPY);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   if (ret == MHD_NO)
@@ -92,7 +104,7 @@
 }
 
 
-static int
+static unsigned int
 testInternalGet ()
 {
   struct MHD_Daemon *d;
@@ -104,39 +116,41 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
+
+static unsigned int
 testMultithreadedGet ()
 {
   struct MHD_Daemon *d;
@@ -148,32 +162,33 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
                         11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
   if (d == NULL)
     return 16;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -181,7 +196,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalGet ()
 {
   struct MHD_Daemon *d;
@@ -203,90 +218,90 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_ERROR_LOG */,
                         11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
   if (d == NULL)
     return 256;
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+  }
   fprintf (stderr, "\n");
   curl_multi_cleanup (multi);
   zzuf_socat_stop ();
@@ -299,16 +314,20 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
   oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+           (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalGet ();
-  errorCount += testMultithreadedGet ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet ();
+    errorCount += testMultithreadedGet ();
+  }
   errorCount += testExternalGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_get_chunked.c b/src/testzzuf/test_get_chunked.c
index faa2632..8013494 100644
--- a/src/testzzuf/test_get_chunked.c
+++ b/src/testzzuf/test_get_chunked.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -57,6 +57,7 @@
   return size * nmemb;
 }
 
+
 /**
  * MHD content reader callback that returns
  * data in chunks.
@@ -67,16 +68,17 @@
   struct MHD_Response **responseptr = cls;
 
   if (pos == 128 * 10)
-    {
-      MHD_add_response_header (*responseptr, "Footer", "working");
-      return MHD_CONTENT_READER_END_OF_STREAM;
-    }
+  {
+    MHD_add_response_header (*responseptr, "Footer", "working");
+    return MHD_CONTENT_READER_END_OF_STREAM;
+  }
   if (max < 128)
     abort ();                   /* should not happen in this testcase... */
   memset (buf, 'A' + (pos / 128), 128);
   return 128;
 }
 
+
 /**
  * Dummy function that does nothing.
  */
@@ -86,39 +88,65 @@
   free (ptr);
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
-          const char *upload_data, size_t *upload_data_size, void **ptr)
+          const char *upload_data, size_t *upload_data_size, void **req_cls)
 {
   static int aptr;
   const char *me = cls;
   struct MHD_Response *response;
   struct MHD_Response **responseptr;
-  int ret;
+  enum MHD_Result ret;
 
+  (void) url;
+  (void) version;              /* Unused. Silent compiler warning. */
+  (void) upload_data;
+  (void) upload_data_size;     /* Unused. Silent compiler warning. */
+
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp (me, method))
     return MHD_NO;              /* unexpected method */
-  if (&aptr != *ptr)
-    {
-      /* do never respond on first call */
-      *ptr = &aptr;
-      return MHD_YES;
-    }
+  if (&aptr != *req_cls)
+  {
+    /* do never respond on first call */
+    *req_cls = &aptr;
+    return MHD_YES;
+  }
   responseptr = malloc (sizeof (struct MHD_Response *));
+  if (NULL == responseptr)
+    return MHD_NO;
   response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
                                                 1024,
                                                 &crc, responseptr, &crcf);
+  if (NULL == response)
+  {
+    free (responseptr);
+    return MHD_NO;
+  }
   *responseptr = response;
-  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+  ret = MHD_queue_response (connection,
+                            MHD_HTTP_OK,
+                            response);
   MHD_destroy_response (response);
   return ret;
 }
 
-static int
+
+static unsigned int
 testInternalGet ()
 {
   struct MHD_Daemon *d;
@@ -130,36 +158,38 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
+
+static unsigned int
 testMultithreadedGet ()
 {
   struct MHD_Daemon *d;
@@ -171,29 +201,30 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
                         11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
   if (d == NULL)
     return 16;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -201,7 +232,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalGet ()
 {
   struct MHD_Daemon *d;
@@ -223,87 +254,87 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_ERROR_LOG */,
                         11080, NULL, NULL, &ahc_echo, "GET", MHD_OPTION_END);
   if (d == NULL)
     return 256;
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+  }
   fprintf (stderr, "\n");
   curl_multi_cleanup (multi);
   zzuf_socat_stop ();
@@ -312,19 +343,22 @@
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalGet ();
-  errorCount += testMultithreadedGet ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalGet ();
+    errorCount += testMultithreadedGet ();
+  }
   errorCount += testExternalGet ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_long_header.c b/src/testzzuf/test_long_header.c
index 2004138..c025939 100644
--- a/src/testzzuf/test_long_header.c
+++ b/src/testzzuf/test_long_header.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -43,16 +43,18 @@
  * half of this value, so the actual value does not have
  * to be big at all...
  */
-#define VERY_LONG (1024*10)
+#define VERY_LONG (1024 * 10)
 
 static int oneone;
 
-static int
+static enum MHD_Result
 apc_all (void *cls, const struct sockaddr *addr, socklen_t addrlen)
 {
+  (void) cls; (void) addr; (void) addrlen;   /* Unused. Silent compiler warning. */
   return MHD_YES;
 }
 
+
 struct CBC
 {
   char *buf;
@@ -63,34 +65,48 @@
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
+  (void) ptr; (void) ctx;  /* Unused. Silent compiler warning. */
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   const char *me = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) version; (void) upload_data;      /* Unused. Silent compiler warning. */
+  (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp (me, method))
     return MHD_NO;              /* unexpected method */
   response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+                                              (void *) url,
+                                              MHD_RESPMEM_MUST_COPY);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
+static unsigned int
 testLongUrlGet ()
 {
   struct MHD_Daemon *d;
@@ -103,55 +119,61 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080,
-                        &apc_all,
-                        NULL,
-                        &ahc_echo,
-                        "GET",
-                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
-                        (size_t) (VERY_LONG / 2), MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080,
+                      &apc_all,
+                      NULL,
+                      &ahc_echo,
+                      "GET",
+                      MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                      (size_t) (VERY_LONG / 2), MHD_OPTION_END);
 
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
+  {
+    fprintf (stderr, ".");
 
-      c = curl_easy_init ();
-      url = malloc (VERY_LONG);
-      memset (url, 'a', VERY_LONG);
-      url[VERY_LONG - 1] = '\0';
-      memcpy (url, "http://localhost:11081/",
-              strlen ("http://localhost:11081/"));
-      curl_easy_setopt (c, CURLOPT_URL, url);
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
+    c = curl_easy_init ();
+    url = malloc (VERY_LONG);
+    if (NULL == url)
+    {
+      zzuf_socat_stop ();
+      return 1;
     }
+    memset (url, 'a', VERY_LONG);
+    url[VERY_LONG - 1] = '\0';
+    memcpy (url, "http://127.0.0.1:11081/",
+            strlen ("http://127.0.0.1:11081/"));
+    curl_easy_setopt (c, CURLOPT_URL, url);
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+    free (url);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
 
   MHD_stop_daemon (d);
-  free (url);
   return 0;
 }
 
 
-static int
+static unsigned int
 testLongHeaderGet ()
 {
   struct MHD_Daemon *d;
@@ -165,53 +187,60 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080,
-                        &apc_all,
-                        NULL,
-                        &ahc_echo,
-                        "GET",
-                        MHD_OPTION_CONNECTION_MEMORY_LIMIT,
-                        (size_t) (VERY_LONG / 2), MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080,
+                      &apc_all,
+                      NULL,
+                      &ahc_echo,
+                      "GET",
+                      MHD_OPTION_CONNECTION_MEMORY_LIMIT,
+                      (size_t) (VERY_LONG / 2), MHD_OPTION_END);
   if (d == NULL)
     return 16;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    url = malloc (VERY_LONG);
+    if (NULL == url)
     {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      url = malloc (VERY_LONG);
-      memset (url, 'a', VERY_LONG);
-      url[VERY_LONG - 1] = '\0';
-      url[VERY_LONG / 2] = ':';
-      url[VERY_LONG / 2 + 1] = ' ';
-      header = curl_slist_append (header, url);
-
-      curl_easy_setopt (c, CURLOPT_HTTPHEADER, header);
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_slist_free_all (header);
-      header = NULL;
+      zzuf_socat_stop ();
       curl_easy_cleanup (c);
+      return 16;
     }
+    memset (url, 'a', VERY_LONG);
+    url[VERY_LONG - 1] = '\0';
+    url[VERY_LONG / 2] = ':';
+    url[VERY_LONG / 2 + 1] = ' ';
+    header = curl_slist_append (header, url);
+
+    curl_easy_setopt (c, CURLOPT_HTTPHEADER, header);
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_slist_free_all (header);
+    header = NULL;
+    curl_easy_cleanup (c);
+    free (url);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
 
   MHD_stop_daemon (d);
-  free (url);
   return 0;
 }
 
@@ -220,9 +249,11 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  const char *sl;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
-  oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+  sl = strrchr (argv[0], (int) '/');
+  oneone = (NULL != sl) ? (NULL != strstr (sl, "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   errorCount += testLongUrlGet ();
@@ -230,5 +261,5 @@
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_post.c b/src/testzzuf/test_post.c
index 632609f..895c5fc 100644
--- a/src/testzzuf/test_post.c
+++ b/src/testzzuf/test_post.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -53,15 +53,16 @@
 
 static void
 completed_cb (void *cls,
-	      struct MHD_Connection *connection,
-	      void **con_cls,
-	      enum MHD_RequestTerminationCode toe)
+              struct MHD_Connection *connection,
+              void **req_cls,
+              enum MHD_RequestTerminationCode toe)
 {
-  struct MHD_PostProcessor *pp = *con_cls;
+  struct MHD_PostProcessor *pp = *req_cls;
+  (void) cls; (void) connection; (void) toe; /* Unused. Silent compiler warning. */
 
   if (NULL != pp)
     MHD_destroy_post_processor (pp);
-  *con_cls = NULL;
+  *req_cls = NULL;
 }
 
 
@@ -83,7 +84,7 @@
  * in that it fails to support incremental processing.
  * (to be fixed in the future)
  */
-static int
+static enum MHD_Result
 post_iterator (void *cls,
                enum MHD_ValueKind kind,
                const char *key,
@@ -93,6 +94,8 @@
                const char *value, uint64_t off, size_t size)
 {
   int *eok = cls;
+  (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; (void) off;            /* Unused. Silent compiler warning. */
 
   if ((0 == strcmp (key, "name")) &&
       (size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size)))
@@ -103,49 +106,61 @@
   return MHD_YES;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int eok;
   struct MHD_Response *response;
   struct MHD_PostProcessor *pp;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) version;      /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp ("POST", method))
-    {
-      return MHD_NO;            /* unexpected method */
-    }
-  pp = *unused;
+  {
+    return MHD_NO;              /* unexpected method */
+  }
+  pp = *req_cls;
   if (pp == NULL)
-    {
-      eok = 0;
-      pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
-      *unused = pp;
-    }
+  {
+    eok = 0;
+    pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
+    *req_cls = pp;
+  }
   MHD_post_process (pp, upload_data, *upload_data_size);
   if ((eok == 3) && (0 == *upload_data_size))
-    {
-      response = MHD_create_response_from_buffer (strlen (url),
-						  (void *) url,
-						  MHD_RESPMEM_MUST_COPY);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
-      MHD_destroy_post_processor (pp);
-      *unused = NULL;
-      return ret;
-    }
+  {
+    response = MHD_create_response_from_buffer (strlen (url),
+                                                (void *) url,
+                                                MHD_RESPMEM_MUST_COPY);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+    MHD_destroy_post_processor (pp);
+    *req_cls = NULL;
+    return ret;
+  }
   *upload_data_size = 0;
   return MHD_YES;
 }
 
 
-static int
+static unsigned int
 testInternalPost ()
 {
   struct MHD_Daemon *d;
@@ -157,38 +172,39 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080, NULL, NULL, &ahc_echo, NULL,
+                      MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                      MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
+  {
+    fprintf (stderr, ".");
 
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -196,7 +212,8 @@
   return 0;
 }
 
-static int
+
+static unsigned int
 testMultithreadedPost ()
 {
   struct MHD_Daemon *d;
@@ -208,39 +225,40 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
-                        11080, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                        11080, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
 
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
+  {
+    fprintf (stderr, ".");
 
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
 
@@ -249,7 +267,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalPost ()
 {
   struct MHD_Daemon *d;
@@ -271,101 +289,101 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */ ,
-                        1082, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_ERROR_LOG */,
+                        1082, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
 
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+
+
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
+    curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
+    curl_easy_setopt (c, CURLOPT_POST, 1L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-
-
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:1082/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
-      curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
-      curl_easy_setopt (c, CURLOPT_POST, 1L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
-
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
-
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+
+  }
   fprintf (stderr, "\n");
   curl_multi_cleanup (multi);
   zzuf_socat_stop ();
@@ -379,16 +397,20 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
   oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+           (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPost ();
-  errorCount += testMultithreadedPost ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPost ();
+    errorCount += testMultithreadedPost ();
+  }
   errorCount += testExternalPost ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_post_form.c b/src/testzzuf/test_post_form.c
index 3e2cdff..b16b0cd 100644
--- a/src/testzzuf/test_post_form.c
+++ b/src/testzzuf/test_post_form.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -51,15 +51,16 @@
 
 static void
 completed_cb (void *cls,
-	      struct MHD_Connection *connection,
-	      void **con_cls,
-	      enum MHD_RequestTerminationCode toe)
+              struct MHD_Connection *connection,
+              void **req_cls,
+              enum MHD_RequestTerminationCode toe)
 {
-  struct MHD_PostProcessor *pp = *con_cls;
+  struct MHD_PostProcessor *pp = *req_cls;
+  (void) cls; (void) connection; (void) toe;            /* Unused. Silent compiler warning. */
 
   if (NULL != pp)
     MHD_destroy_post_processor (pp);
-  *con_cls = NULL;
+  *req_cls = NULL;
 }
 
 
@@ -75,12 +76,13 @@
   return size * nmemb;
 }
 
+
 /**
  * Note that this post_iterator is not perfect
  * in that it fails to support incremental processing.
  * (to be fixed in the future)
  */
-static int
+static enum MHD_Result
 post_iterator (void *cls,
                enum MHD_ValueKind kind,
                const char *key,
@@ -90,6 +92,8 @@
                const char *value, uint64_t off, size_t size)
 {
   int *eok = cls;
+  (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */
+  (void) transfer_encoding; (void) off;            /* Unused. Silent compiler warning. */
 
   if (key == NULL)
     return MHD_YES;
@@ -106,49 +110,61 @@
 }
 
 
-static int
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   static int eok;
   struct MHD_Response *response;
   struct MHD_PostProcessor *pp;
-  int ret;
+  enum MHD_Result ret;
+  (void) cls; (void) version;      /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp ("POST", method))
-    {
-      return MHD_NO;            /* unexpected method */
-    }
-  pp = *unused;
+  {
+    return MHD_NO;              /* unexpected method */
+  }
+  pp = *req_cls;
   if (pp == NULL)
-    {
-      eok = 0;
-      pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
-      if (pp == NULL)
-        return MHD_NO;
-      *unused = pp;
-    }
+  {
+    eok = 0;
+    pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
+    if (pp == NULL)
+      return MHD_NO;
+    *req_cls = pp;
+  }
   MHD_post_process (pp, upload_data, *upload_data_size);
   if ((eok == 3) && (0 == *upload_data_size))
-    {
-      response = MHD_create_response_from_buffer (strlen (url),
-						  (void *) url,
-						  MHD_RESPMEM_MUST_COPY);
-      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
-      MHD_destroy_response (response);
-      MHD_destroy_post_processor (pp);
-      *unused = NULL;
-      return ret;
-    }
+  {
+    response = MHD_create_response_from_buffer (strlen (url),
+                                                (void *) url,
+                                                MHD_RESPMEM_MUST_COPY);
+    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
+    MHD_destroy_response (response);
+    MHD_destroy_post_processor (pp);
+    *req_cls = NULL;
+    return ret;
+  }
   *upload_data_size = 0;
   return MHD_YES;
 }
 
+
 static struct curl_httppost *
 make_form ()
 {
@@ -163,7 +179,7 @@
 }
 
 
-static int
+static unsigned int
 testInternalPost ()
 {
   struct MHD_Daemon *d;
@@ -176,37 +192,38 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
-			MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080, NULL, NULL, &ahc_echo, NULL,
+                      MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                      MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      pd = make_form ();
-      curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-      curl_formfree (pd);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    pd = make_form ();
+    curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+    curl_formfree (pd);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -214,7 +231,7 @@
 }
 
 
-static int
+static unsigned int
 testMultithreadedPost ()
 {
   struct MHD_Daemon *d;
@@ -227,37 +244,38 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
-                        11080, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                        11080, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 16;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      pd = make_form ();
-      curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-      curl_formfree (pd);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    pd = make_form ();
+    curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+    curl_formfree (pd);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -265,7 +283,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalPost ()
 {
   struct MHD_Daemon *d;
@@ -288,103 +306,103 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */ ,
-                        1082, NULL, NULL, &ahc_echo, NULL, 
-			MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,			
-			MHD_OPTION_END);
+  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_ERROR_LOG */,
+                        1082, NULL, NULL, &ahc_echo, NULL,
+                        MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL,
+                        MHD_OPTION_END);
   if (d == NULL)
     return 256;
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:1082/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    pd = make_form ();
+    curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:1082/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      pd = make_form ();
-      curl_easy_setopt (c, CURLOPT_HTTPPOST, pd);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
-
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_formfree (pd);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              curl_formfree (pd);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              curl_formfree (pd);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
+      curl_multi_cleanup (multi);
       curl_formfree (pd);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        curl_formfree (pd);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        curl_formfree (pd);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+    curl_formfree (pd);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
+  curl_multi_cleanup (multi);
 
   MHD_stop_daemon (d);
   return 0;
@@ -395,16 +413,20 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
   oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+           (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPost ();
-  errorCount += testMultithreadedPost ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPost ();
+    errorCount += testMultithreadedPost ();
+  }
   errorCount += testExternalPost ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_put.c b/src/testzzuf/test_put.c
index c6240c4..9e3749d 100644
--- a/src/testzzuf/test_put.c
+++ b/src/testzzuf/test_put.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -62,6 +62,7 @@
   return wrt;
 }
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -74,47 +75,59 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   int *done = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp ("PUT", method))
     return MHD_NO;              /* unexpected method */
   if ((*done) == 0)
+  {
+    if (*upload_data_size != 8)
+      return MHD_YES;           /* not yet ready */
+    if (0 == memcmp (upload_data, "Hello123", 8))
     {
-      if (*upload_data_size != 8)
-        return MHD_YES;         /* not yet ready */
-      if (0 == memcmp (upload_data, "Hello123", 8))
-        {
-          *upload_data_size = 0;
-        }
-      else
-        {
-          printf ("Invalid upload data `%8s'!\n", upload_data);
-          return MHD_NO;
-        }
-      *done = 1;
-      return MHD_YES;
+      *upload_data_size = 0;
     }
+    else
+    {
+      printf ("Invalid upload data `%8s'!\n", upload_data);
+      return MHD_NO;
+    }
+    *done = 1;
+    return MHD_YES;
+  }
   response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+                                              (void *) url,
+                                              MHD_RESPMEM_MUST_COPY);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
+static unsigned int
 testInternalPut ()
 {
   struct MHD_Daemon *d;
@@ -128,44 +141,46 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080,
-                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080,
+                      NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
+
+static unsigned int
 testMultithreadedPut ()
 {
   struct MHD_Daemon *d;
@@ -179,37 +194,38 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
                         11080,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 16;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -217,7 +233,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalPut ()
 {
   struct MHD_Daemon *d;
@@ -241,99 +257,98 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_ERROR_LOG */,
                         11080,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 256;
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
-
-
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+  }
   fprintf (stderr, "\n");
   curl_multi_cleanup (multi);
   zzuf_socat_stop ();
@@ -346,16 +361,20 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc;   /* Unused. Silent compiler warning. */
 
   oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+           (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPut ();
-  errorCount += testMultithreadedPut ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPut ();
+    errorCount += testMultithreadedPut ();
+  }
   errorCount += testExternalPut ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_put_chunked.c b/src/testzzuf/test_put_chunked.c
index c023c5e..3dd67e4 100644
--- a/src/testzzuf/test_put_chunked.c
+++ b/src/testzzuf/test_put_chunked.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -62,6 +62,7 @@
   return wrt;
 }
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -74,53 +75,69 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   int *done = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
   int have;
+  (void) version; (void) req_cls;   /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp ("PUT", method))
     return MHD_NO;              /* unexpected method */
   if ((*done) < 8)
+  {
+    have = *upload_data_size;
+    if (have + *done > 8)
     {
-      have = *upload_data_size;
-      if (have + *done > 8)
-        {
-          return MHD_NO;
-        }
-      if (0 == memcmp (upload_data, &"Hello123"[*done], have))
-        {
-          *done += have;
-          *upload_data_size = 0;
-        }
-      else
-        {
-          return MHD_NO;
-        }
-#if 0
-      fprintf (stderr, "Not ready for response: %u/%u\n", *done, 8);
-#endif
-      return MHD_YES;
+      return MHD_NO;
     }
+    if (0 == have)
+    {
+      (void) 0; /* Do nothing - no data yet */
+    }
+    else if (0 == memcmp (upload_data, &"Hello123"[*done], have))
+    {
+      *done += have;
+      *upload_data_size = 0;
+    }
+    else
+    {
+      return MHD_NO;
+    }
+#if 0
+    fprintf (stderr, "Not ready for response: %u/%u\n", *done, 8);
+#endif
+    return MHD_YES;
+  }
   response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url,
-					      MHD_RESPMEM_MUST_COPY);
+                                              (void *) url,
+                                              MHD_RESPMEM_MUST_COPY);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
+static unsigned int
 testInternalPut ()
 {
   struct MHD_Daemon *d;
@@ -134,44 +151,46 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG,
+  d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
                         11080,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11080/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      /*
-         // by not giving the file size, we force chunking!
-         curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-       */
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+  {
+    fprintf (stderr, ".");
+    done_flag = 0;
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11080/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    /* by not giving the file size, we force chunking! */
+    /*
+       curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+     */
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
+
+static unsigned int
 testMultithreadedPut ()
 {
   struct MHD_Daemon *d;
@@ -185,39 +204,40 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG,
                         11081,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 16;
   c = curl_easy_init ();
-  curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
+  curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
   curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
   curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
   curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
   curl_easy_setopt (c, CURLOPT_READDATA, &pos);
   curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+  /* by not giving the file size, we force chunking! */
   /*
-     // by not giving the file size, we force chunking!
      curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
    */
-  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
+  curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
   curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L);
   curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L);
-  // NOTE: use of CONNECTTIMEOUT without also
-  //   setting NOSIGNAL results in really weird
-  //   crashes on my system!
-  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
+  /* NOTE: use of CONNECTTIMEOUT without also
+   *   setting NOSIGNAL results in really weird
+   *   crashes on my system! */
+  curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
   if (CURLE_OK != (errornum = curl_easy_perform (c)))
-    {
-      fprintf (stderr,
-               "curl_easy_perform failed: `%s'\n",
-               curl_easy_strerror (errornum));
-      curl_easy_cleanup (c);
-      MHD_stop_daemon (d);
-      return 32;
-    }
+  {
+    fprintf (stderr,
+             "curl_easy_perform failed: `%s'\n",
+             curl_easy_strerror (errornum));
+    curl_easy_cleanup (c);
+    MHD_stop_daemon (d);
+    return 32;
+  }
   curl_easy_cleanup (c);
   MHD_stop_daemon (d);
   if (cbc.pos != strlen ("/hello_world"))
@@ -229,7 +249,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalPut ()
 {
   struct MHD_Daemon *d;
@@ -253,7 +273,7 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_DEBUG,
+  d = MHD_start_daemon (MHD_USE_ERROR_LOG,
                         11082,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
@@ -261,90 +281,91 @@
 
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+    done_flag = 0;
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11082/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    /* by not giving the file size, we force chunking! */
+    /*
+       curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
+     */
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11082/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      /*
-         // by not giving the file size, we force chunking!
-         curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L);
-       */
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
-
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+  }
   fprintf (stderr, "\n");
   curl_multi_cleanup (multi);
   zzuf_socat_stop ();
@@ -353,19 +374,22 @@
 }
 
 
-
 int
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; (void) argv; /* Unused. Silent compiler warning. */
 
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
-  errorCount += testInternalPut ();
-  errorCount += testMultithreadedPut ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPut ();
+    errorCount += testMultithreadedPut ();
+  }
   errorCount += testExternalPut ();
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/src/testzzuf/test_put_large.c b/src/testzzuf/test_put_large.c
index 1fdc92a..900284e 100644
--- a/src/testzzuf/test_put_large.c
+++ b/src/testzzuf/test_put_large.c
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with libmicrohttpd; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
@@ -70,6 +70,7 @@
   return wrt;
 }
 
+
 static size_t
 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
 {
@@ -82,53 +83,65 @@
   return size * nmemb;
 }
 
-static int
+
+static enum MHD_Result
 ahc_echo (void *cls,
           struct MHD_Connection *connection,
           const char *url,
           const char *method,
           const char *version,
           const char *upload_data, size_t *upload_data_size,
-          void **unused)
+          void **req_cls)
 {
   int *done = cls;
   struct MHD_Response *response;
-  int ret;
+  enum MHD_Result ret;
+  (void) version; (void) req_cls; /* Unused. Silent compiler warning. */
 
+  if (NULL == url)
+    fprintf (stderr, "The \"url\" parameter is NULL.\n");
+  if (NULL == method)
+    fprintf (stderr, "The \"method\" parameter is NULL.\n");
+  if (NULL == version)
+    fprintf (stderr, "The \"version\" parameter is NULL.\n");
+  if (NULL == upload_data_size)
+    fprintf (stderr, "The \"upload_data_size\" parameter is NULL.\n");
+  if ((0 != *upload_data_size) && (NULL == upload_data))
+    fprintf (stderr, "Upload data is NULL with non-zero size.\n");
   if (0 != strcmp ("PUT", method))
     return MHD_NO;              /* unexpected method */
   if ((*done) == 0)
+  {
+    if (*upload_data_size != PUT_SIZE)
     {
-      if (*upload_data_size != PUT_SIZE)
-        {
 #if 0
-          fprintf (stderr,
-                   "Waiting for more data (%u/%u)...\n",
-                   *upload_data_size, PUT_SIZE);
+      fprintf (stderr,
+               "Waiting for more data (%u/%u)...\n",
+               *upload_data_size, PUT_SIZE);
 #endif
-          return MHD_YES;       /* not yet ready */
-        }
-      if (0 == memcmp (upload_data, put_buffer, PUT_SIZE))
-        {
-          *upload_data_size = 0;
-        }
-      else
-        {
-          return MHD_NO;
-        }
-      *done = 1;
-      return MHD_YES;
+      return MHD_YES;           /* not yet ready */
     }
+    if (0 == memcmp (upload_data, put_buffer, PUT_SIZE))
+    {
+      *upload_data_size = 0;
+    }
+    else
+    {
+      return MHD_NO;
+    }
+    *done = 1;
+    return MHD_YES;
+  }
   response = MHD_create_response_from_buffer (strlen (url),
-					      (void *) url, 
-					      MHD_RESPMEM_MUST_COPY);
+                                              (void *) url,
+                                              MHD_RESPMEM_MUST_COPY);
   ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
   MHD_destroy_response (response);
   return ret;
 }
 
 
-static int
+static unsigned int
 testInternalPut ()
 {
   struct MHD_Daemon *d;
@@ -142,45 +155,47 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
-                        11080,
-                        NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
+  d =
+    MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
+                      11080,
+                      NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 1;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
+  {
+    fprintf (stderr, ".");
 
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
   return 0;
 }
 
-static int
+
+static unsigned int
 testMultithreadedPut ()
 {
   struct MHD_Daemon *d;
@@ -194,38 +209,39 @@
   cbc.buf = buf;
   cbc.size = 2048;
   cbc.pos = 0;
-  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
+  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION
+                        | MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */,
                         11080,
                         NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END);
   if (d == NULL)
     return 16;
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
-    {
-      fprintf (stderr, ".");
+  {
+    fprintf (stderr, ".");
 
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-      curl_easy_perform (c);
-      curl_easy_cleanup (c);
-    }
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+    curl_easy_perform (c);
+    curl_easy_cleanup (c);
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   MHD_stop_daemon (d);
@@ -233,7 +249,7 @@
 }
 
 
-static int
+static unsigned int
 testExternalPut ()
 {
   struct MHD_Daemon *d;
@@ -257,7 +273,7 @@
   cbc.size = 2048;
   cbc.pos = 0;
   multi = NULL;
-  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */,
+  d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_ERROR_LOG */,
                         11080,
                         NULL, NULL, &ahc_echo, &done_flag,
                         MHD_OPTION_CONNECTION_MEMORY_LIMIT,
@@ -266,92 +282,91 @@
     return 256;
   multi = curl_multi_init ();
   if (multi == NULL)
-    {
-      MHD_stop_daemon (d);
-      return 512;
-    }
+  {
+    MHD_stop_daemon (d);
+    return 512;
+  }
   zzuf_socat_start ();
   for (i = 0; i < LOOP_COUNT; i++)
+  {
+    fprintf (stderr, ".");
+
+    c = curl_easy_init ();
+    curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1:11081/hello_world");
+    curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
+    curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
+    curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
+    curl_easy_setopt (c, CURLOPT_READDATA, &pos);
+    curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
+    curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
+    curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L);
+    curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
+    if (oneone)
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
+    else
+      curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
+    curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
+    /* NOTE: use of CONNECTTIMEOUT without also
+     *   setting NOSIGNAL results in really weird
+     *   crashes on my system! */
+    curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L);
+
+
+    mret = curl_multi_add_handle (multi, c);
+    if (mret != CURLM_OK)
     {
-      fprintf (stderr, ".");
-
-      c = curl_easy_init ();
-      curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
-      curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &copyBuffer);
-      curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
-      curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer);
-      curl_easy_setopt (c, CURLOPT_READDATA, &pos);
-      curl_easy_setopt (c, CURLOPT_UPLOAD, 1L);
-      curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE);
-      curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
-      curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
-      if (oneone)
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
-      else
-        curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
-      curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
-      // NOTE: use of CONNECTTIMEOUT without also
-      //   setting NOSIGNAL results in really weird
-      //   crashes on my system!
-      curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
-
-
-
-      mret = curl_multi_add_handle (multi, c);
-      if (mret != CURLM_OK)
-        {
-          curl_multi_cleanup (multi);
-          curl_easy_cleanup (c);
-          zzuf_socat_stop ();
-          MHD_stop_daemon (d);
-          return 1024;
-        }
-      start = time (NULL);
-      while ((time (NULL) - start < 5) && (c != NULL))
-        {
-          max = 0;
-          FD_ZERO (&rs);
-          FD_ZERO (&ws);
-          FD_ZERO (&es);
-          curl_multi_perform (multi, &running);
-          mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
-          if (mret != CURLM_OK)
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 2048;
-            }
-          if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
-            {
-              curl_multi_remove_handle (multi, c);
-              curl_multi_cleanup (multi);
-              curl_easy_cleanup (c);
-              zzuf_socat_stop ();
-              MHD_stop_daemon (d);
-              return 4096;
-            }
-          tv.tv_sec = 0;
-          tv.tv_usec = 1000;
-          select (max + 1, &rs, &ws, &es, &tv);
-          curl_multi_perform (multi, &running);
-          if (running == 0)
-            {
-              curl_multi_info_read (multi, &running);
-              curl_multi_remove_handle (multi, c);
-              curl_easy_cleanup (c);
-              c = NULL;
-            }
-          MHD_run (d);
-        }
-      if (c != NULL)
-        {
-          curl_multi_remove_handle (multi, c);
-          curl_easy_cleanup (c);
-        }
+      curl_multi_cleanup (multi);
+      curl_easy_cleanup (c);
+      zzuf_socat_stop ();
+      MHD_stop_daemon (d);
+      return 1024;
     }
+    start = time (NULL);
+    while ((time (NULL) - start < 5) && (c != NULL))
+    {
+      max = 0;
+      FD_ZERO (&rs);
+      FD_ZERO (&ws);
+      FD_ZERO (&es);
+      curl_multi_perform (multi, &running);
+      mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
+      if (mret != CURLM_OK)
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 2048;
+      }
+      if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
+      {
+        curl_multi_remove_handle (multi, c);
+        curl_multi_cleanup (multi);
+        curl_easy_cleanup (c);
+        zzuf_socat_stop ();
+        MHD_stop_daemon (d);
+        return 4096;
+      }
+      tv.tv_sec = 0;
+      tv.tv_usec = 1000;
+      select (max + 1, &rs, &ws, &es, &tv);
+      curl_multi_perform (multi, &running);
+      if (running == 0)
+      {
+        curl_multi_info_read (multi, &running);
+        curl_multi_remove_handle (multi, c);
+        curl_easy_cleanup (c);
+        c = NULL;
+      }
+      MHD_run (d);
+    }
+    if (c != NULL)
+    {
+      curl_multi_remove_handle (multi, c);
+      curl_easy_cleanup (c);
+    }
+  }
   fprintf (stderr, "\n");
   zzuf_socat_stop ();
   curl_multi_cleanup (multi);
@@ -364,19 +379,25 @@
 main (int argc, char *const *argv)
 {
   unsigned int errorCount = 0;
+  (void) argc; /* Unused. Silent compiler warning. */
 
   oneone = (NULL != strrchr (argv[0], (int) '/')) ?
-    (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
+           (NULL != strstr (strrchr (argv[0], (int) '/'), "11")) : 0;
   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
     return 2;
   put_buffer = malloc (PUT_SIZE);
+  if (0 == put_buffer)
+    return 77;
   memset (put_buffer, 1, PUT_SIZE);
-  errorCount += testInternalPut ();
-  errorCount += testMultithreadedPut ();
+  if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
+  {
+    errorCount += testInternalPut ();
+    errorCount += testMultithreadedPut ();
+  }
   errorCount += testExternalPut ();
   free (put_buffer);
   if (errorCount != 0)
     fprintf (stderr, "Error (code: %u)\n", errorCount);
   curl_global_cleanup ();
-  return errorCount != 0;       /* 0 == pass */
+  return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
 }
diff --git a/test-driver b/test-driver
deleted file mode 100755
index d306056..0000000
--- a/test-driver
+++ /dev/null
@@ -1,139 +0,0 @@
-#! /bin/sh
-# test-driver - basic testsuite driver script.
-
-scriptversion=2013-07-13.22; # UTC
-
-# Copyright (C) 2011-2013 Free Software Foundation, Inc.
-#
-# 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 2, 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/>.
-
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# This file is maintained in Automake, please report
-# bugs to <bug-automake@gnu.org> or send patches to
-# <automake-patches@gnu.org>.
-
-# Make unconditional expansion of undefined variables an error.  This
-# helps a lot in preventing typo-related bugs.
-set -u
-
-usage_error ()
-{
-  echo "$0: $*" >&2
-  print_usage >&2
-  exit 2
-}
-
-print_usage ()
-{
-  cat <<END
-Usage:
-  test-driver --test-name=NAME --log-file=PATH --trs-file=PATH
-              [--expect-failure={yes|no}] [--color-tests={yes|no}]
-              [--enable-hard-errors={yes|no}] [--]
-              TEST-SCRIPT [TEST-SCRIPT-ARGUMENTS]
-The '--test-name', '--log-file' and '--trs-file' options are mandatory.
-END
-}
-
-test_name= # Used for reporting.
-log_file=  # Where to save the output of the test script.
-trs_file=  # Where to save the metadata of the test run.
-expect_failure=no
-color_tests=no
-enable_hard_errors=yes
-while test $# -gt 0; do
-  case $1 in
-  --help) print_usage; exit $?;;
-  --version) echo "test-driver $scriptversion"; exit $?;;
-  --test-name) test_name=$2; shift;;
-  --log-file) log_file=$2; shift;;
-  --trs-file) trs_file=$2; shift;;
-  --color-tests) color_tests=$2; shift;;
-  --expect-failure) expect_failure=$2; shift;;
-  --enable-hard-errors) enable_hard_errors=$2; shift;;
-  --) shift; break;;
-  -*) usage_error "invalid option: '$1'";;
-   *) break;;
-  esac
-  shift
-done
-
-missing_opts=
-test x"$test_name" = x && missing_opts="$missing_opts --test-name"
-test x"$log_file"  = x && missing_opts="$missing_opts --log-file"
-test x"$trs_file"  = x && missing_opts="$missing_opts --trs-file"
-if test x"$missing_opts" != x; then
-  usage_error "the following mandatory options are missing:$missing_opts"
-fi
-
-if test $# -eq 0; then
-  usage_error "missing argument"
-fi
-
-if test $color_tests = yes; then
-  # Keep this in sync with 'lib/am/check.am:$(am__tty_colors)'.
-  red='' # Red.
-  grn='' # Green.
-  lgn='' # Light green.
-  blu='' # Blue.
-  mgn='' # Magenta.
-  std=''     # No color.
-else
-  red= grn= lgn= blu= mgn= std=
-fi
-
-do_exit='rm -f $log_file $trs_file; (exit $st); exit $st'
-trap "st=129; $do_exit" 1
-trap "st=130; $do_exit" 2
-trap "st=141; $do_exit" 13
-trap "st=143; $do_exit" 15
-
-# Test script is run here.
-"$@" >$log_file 2>&1
-estatus=$?
-if test $enable_hard_errors = no && test $estatus -eq 99; then
-  estatus=1
-fi
-
-case $estatus:$expect_failure in
-  0:yes) col=$red res=XPASS recheck=yes gcopy=yes;;
-  0:*)   col=$grn res=PASS  recheck=no  gcopy=no;;
-  77:*)  col=$blu res=SKIP  recheck=no  gcopy=yes;;
-  99:*)  col=$mgn res=ERROR recheck=yes gcopy=yes;;
-  *:yes) col=$lgn res=XFAIL recheck=no  gcopy=yes;;
-  *:*)   col=$red res=FAIL  recheck=yes gcopy=yes;;
-esac
-
-# Report outcome to console.
-echo "${col}${res}${std}: $test_name"
-
-# Register the test result, and other relevant metadata.
-echo ":test-result: $res" > $trs_file
-echo ":global-test-result: $res" >> $trs_file
-echo ":recheck: $recheck" >> $trs_file
-echo ":copy-in-global-log: $gcopy" >> $trs_file
-
-# Local Variables:
-# mode: shell-script
-# sh-indentation: 2
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/w32/.gitignore b/w32/.gitignore
new file mode 100644
index 0000000..f135e60
--- /dev/null
+++ b/w32/.gitignore
@@ -0,0 +1,14 @@
+*.suo
+*.sdf
+*.opensdf
+*.vcxproj.user
+*.obj
+*.lib
+*.dll
+*.pdb
+*.log
+*.tlog
+*.idb
+*.rc
+*.VC.db
+.vs
diff --git a/w32/VS-Any-Version/.gitignore b/w32/VS-Any-Version/.gitignore
new file mode 100644
index 0000000..c9144d0
--- /dev/null
+++ b/w32/VS-Any-Version/.gitignore
@@ -0,0 +1,6 @@
+/Output
+/libmicrohttpd
+/hellobrowser
+/largepost
+/simplepost
+/.vs
diff --git a/w32/VS-Any-Version/hellobrowser.vcxproj b/w32/VS-Any-Version/hellobrowser.vcxproj
new file mode 100644
index 0000000..1e07fc1
--- /dev/null
+++ b/w32/VS-Any-Version/hellobrowser.vcxproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <VCProjectVersion>16.0</VCProjectVersion>
+    <ProjectGuid>{310F39BD-A2D6-44FF-8344-37ADD0524CBD}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>hellobrowser</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS-Any-Version/hellobrowser.vcxproj.filters b/w32/VS-Any-Version/hellobrowser.vcxproj.filters
new file mode 100644
index 0000000..ef5a1fd
--- /dev/null
+++ b/w32/VS-Any-Version/hellobrowser.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS-Any-Version/largepost.vcxproj b/w32/VS-Any-Version/largepost.vcxproj
new file mode 100644
index 0000000..644259a
--- /dev/null
+++ b/w32/VS-Any-Version/largepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)largepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{77A27E6D-9A39-40B8-961B-40E63DB7FA65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>largepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS-Any-Version/libmicrohttpd.sln b/w32/VS-Any-Version/libmicrohttpd.sln
new file mode 100644
index 0000000..c68dfc1
--- /dev/null
+++ b/w32/VS-Any-Version/libmicrohttpd.sln
@@ -0,0 +1,174 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+MinimumVisualStudioVersion = 10.0.40219.1
+
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hellobrowser", "hellobrowser.vcxproj", "{310F39BD-A2D6-44FF-8344-37ADD0524CBD}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "simplepost", "simplepost.vcxproj", "{294D5317-E983-4682-8DB5-678EA4645E11}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "largepost", "largepost.vcxproj", "{77A27E6D-9A39-40B8-961B-40E63DB7FA65}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug-dll|Win32 = Debug-dll|Win32
+		Debug-dll|x64 = Debug-dll|x64
+		Debug-dll|ARM = Debug-dll|ARM
+		Debug-dll|ARM64 = Debug-dll|ARM64
+		Debug-static|Win32 = Debug-static|Win32
+		Debug-static|x64 = Debug-static|x64
+		Debug-static|ARM = Debug-static|ARM
+		Debug-static|ARM64 = Debug-static|ARM64
+		Release-dll|Win32 = Release-dll|Win32
+		Release-dll|x64 = Release-dll|x64
+		Release-dll|ARM = Release-dll|ARM
+		Release-dll|ARM64 = Release-dll|ARM64
+		Release-static|Win32 = Release-static|Win32
+		Release-static|x64 = Release-static|x64
+		Release-static|ARM = Release-static|ARM
+		Release-static|ARM64 = Release-static|ARM64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.Build.0 = Release-static|ARM64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/w32/VS-Any-Version/libmicrohttpd.vcxproj b/w32/VS-Any-Version/libmicrohttpd.vcxproj
new file mode 100644
index 0000000..5e18ce0
--- /dev/null
+++ b/w32/VS-Any-Version/libmicrohttpd.vcxproj
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>libmicrohttpd</RootNamespace>
+    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType Condition="$(Configuration.EndsWith('-static'))">StaticLibrary</ConfigurationType>
+    <ConfigurationType Condition="! $(Configuration.EndsWith('-static'))">DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <Lib />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS-Any-Version/libmicrohttpd.vcxproj.filters b/w32/VS-Any-Version/libmicrohttpd.vcxproj.filters
new file mode 100644
index 0000000..63f58bf
--- /dev/null
+++ b/w32/VS-Any-Version/libmicrohttpd.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS-Any-Version/simplepost.vcxproj b/w32/VS-Any-Version/simplepost.vcxproj
new file mode 100644
index 0000000..43943e5
--- /dev/null
+++ b/w32/VS-Any-Version/simplepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)simplepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{294D5317-E983-4682-8DB5-678EA4645E11}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>simplepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2013/.gitignore b/w32/VS2013/.gitignore
new file mode 100644
index 0000000..d3b4a91
--- /dev/null
+++ b/w32/VS2013/.gitignore
@@ -0,0 +1,5 @@
+/Output
+/libmicrohttpd
+/hellobrowser
+/largepost
+/simplepost
diff --git a/w32/VS2013/MHD_config.h b/w32/VS2013/MHD_config.h
deleted file mode 100644
index 07f1fbb..0000000
--- a/w32/VS2013/MHD_config.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/* MHD_config.h for W32 */
-/* Created manually. */
-
-/* *** Basic OS/compiler information *** */
-
-/* This is a Windows system */
-#define WINDOWS 1
-
-/* Define if MS VC compiler is used */
-#define MSVC 1
-
-/* *** MHD configuration *** */
-/* Undef to disable feature */
-
-/* Enable basic Auth support */
-#define BAUTH_SUPPORT 1
-
-/* Enable digest Auth support */
-#define DAUTH_SUPPORT 1
-
-/* Enable postprocessor.c */
-#define HAVE_POSTPROCESSOR 1
-
-/* Enable error messages */
-#define HAVE_MESSAGES 1
-
-/* Disable HTTPS support */
-#define HTTPS_SUPPORT 0
-
-
-/* *** OS features *** */
-
-/* Provides IPv6 headers */
-#define HAVE_INET6 1
-
-/* Define to use pair of sockets instead of pipes for signaling */
-#define MHD_DONT_USE_PIPES 1
-
-/* define to use W32 threads */
-#define MHD_USE_W32_THREADS 1
-
-#ifndef _WIN32_WINNT
-/* MHD supports Windows XP and later W32 systems*/
-#define _WIN32_WINNT 0x0501
-#endif /* _WIN32_WINNT */
-
-/* winsock poll is available only on Vista and later */
-#if _WIN32_WINNT >= 0x0600
-#define HAVE_POLL 1
-#endif /* _WIN32_WINNT >= 0x0600 */
-
-/* define to 0 to disable epoll support */
-#define EPOLL_SUPPORT 0
-
-/* Define to 1 if you have the <winsock2.h> header file. */
-#define HAVE_WINSOCK2_H 1
-
-/* Define to 1 if you have the <ws2tcpip.h> header file. */
-#define HAVE_WS2TCPIP_H 1
-
-/* Define to 1 if you have the declaration of `SOCK_NONBLOCK', and to 0 if you
-   don't. */
-#define HAVE_DECL_SOCK_NONBLOCK 0
-
-/* Define to 1 if you have the declaration of `TCP_CORK', and to 0 if you
-   don't. */
-#define HAVE_DECL_TCP_CORK 0
-
-/* Define to 1 if you have the declaration of `TCP_NOPUSH', and to 0 if you
-   don't. */
-#define HAVE_DECL_TCP_NOPUSH 0
-
-
-/* *** Headers information *** */
-/* Not really important as not used by code currently */
-
-/* Define to 1 if you have the <errno.h> header file. */
-#define HAVE_ERRNO_H 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the <limits.h> header file. */
-#define HAVE_LIMITS_H 1
-
-/* Define to 1 if you have the <locale.h> header file. */
-#define HAVE_LOCALE_H 1
-
-/* Define to 1 if you have the <math.h> header file. */
-#define HAVE_MATH_H 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <pthread.h> header file. */
-#define HAVE_PTHREAD_H 0
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdio.h> header file. */
-#define HAVE_STDIO_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <time.h> header file. */
-#define HAVE_TIME_H 1
-
-
-/* *** Other useful staff *** */
-
-#define _GNU_SOURCE  1
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-
-/* End of MHD_config.h */
diff --git a/w32/VS2013/hellobrowser.vcxproj b/w32/VS2013/hellobrowser.vcxproj
index df9d826..c6c0f0a 100644
--- a/w32/VS2013/hellobrowser.vcxproj
+++ b/w32/VS2013/hellobrowser.vcxproj
@@ -1,48 +1,17 @@
 <?xml version="1.0" encoding="utf-8"?>
 <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug-dll|Win32">
-      <Configuration>Debug-dll</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-dll|x64">
-      <Configuration>Debug-dll</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-static|Win32">
-      <Configuration>Debug-static</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-static|x64">
-      <Configuration>Debug-static</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-dll|Win32">
-      <Configuration>Release-dll</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-dll|x64">
-      <Configuration>Release-dll</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-static|Win32">
-      <Configuration>Release-static</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-static|x64">
-      <Configuration>Release-static</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\doc\examples\hellobrowser.c" />
-  </ItemGroup>
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-files.vcxproj" />
   <PropertyGroup Label="Globals">
     <ProjectGuid>{310F39BD-A2D6-44FF-8344-37ADD0524CBD}</ProjectGuid>
     <Keyword>Win32Proj</Keyword>
     <RootNamespace>hellobrowser</RootNamespace>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
@@ -75,103 +44,14 @@
   <ImportGroup Label="PropertySheets">
     <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
   </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <IncludePath>$(SolutionDir)..\..\src\include;$(SolutionDir);$(IncludePath)</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Platform)'=='Win32'">
-    <IntDir>$(SolutionDir)$(ProjectName)\$(Configuration)\</IntDir>
-    <OutDir>$(SolutionDir)\Output\</OutDir>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Platform)'=='x64'">
-    <IntDir>$(SolutionDir)$(ProjectName)\$(Configuration)\$(Platform)\</IntDir>
-    <OutDir>$(SolutionDir)\Output\$(Platform)\</OutDir>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(UseDebugLibraries)'=='true'">
-    <LinkIncremental>true</LinkIncremental>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(UseDebugLibraries)'!='true'">
-    <LinkIncremental>false</LinkIncremental>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'">
-    <TargetName>$(ProjectName)_d</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'">
-    <TargetName>$(ProjectName)-dll_d</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Release-static'">
-    <TargetName>$(ProjectName)</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'">
-    <TargetName>$(ProjectName)-dll</TargetName>
-  </PropertyGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
   <ItemDefinitionGroup>
-    <ClCompile>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <WarningLevel>Level3</WarningLevel>
-      <PreprocessorDefinitions>WIN32;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-    </Link>
+    <ClCompile />
+    <Link />
     <ProjectReference />
   </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(UseDebugLibraries)'=='true'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <ProjectReference />
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(UseDebugLibraries)'!='true'">
-    <ClCompile>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <Link>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-    <ProjectReference />
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-static'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>libmicrohttpd_d.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-    <ProjectReference />
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-dll'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>libmicrohttpd-dll_d.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-    <ProjectReference />
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Release-static'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>libmicrohttpd.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Release-dll'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>libmicrohttpd-dll.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
diff --git a/w32/VS2013/hellobrowser.vcxproj.filters b/w32/VS2013/hellobrowser.vcxproj.filters
index 0e1e02f..ef5a1fd 100644
--- a/w32/VS2013/hellobrowser.vcxproj.filters
+++ b/w32/VS2013/hellobrowser.vcxproj.filters
@@ -1,22 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
 <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
-      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
-      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\doc\examples\hellobrowser.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-filters.vcxproj" />
 </Project>
\ No newline at end of file
diff --git a/w32/VS2013/largepost.vcxproj b/w32/VS2013/largepost.vcxproj
new file mode 100644
index 0000000..ee5618c
--- /dev/null
+++ b/w32/VS2013/largepost.vcxproj
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)largepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{77A27E6D-9A39-40B8-961B-40E63DB7FA65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>largepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2013/libmicrohttpd.sln b/w32/VS2013/libmicrohttpd.sln
index 3a18af3..28df709 100644
--- a/w32/VS2013/libmicrohttpd.sln
+++ b/w32/VS2013/libmicrohttpd.sln
@@ -3,97 +3,307 @@
 # Visual Studio 2013
 VisualStudioVersion = 12.0.31101.0
 MinimumVisualStudioVersion = 10.0.40219.1
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
-EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hellobrowser", "hellobrowser.vcxproj", "{310F39BD-A2D6-44FF-8344-37ADD0524CBD}"
 	ProjectSection(ProjectDependencies) = postProject
 		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
 	EndProjectSection
 EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "simplepost", "simplepost.vcxproj", "{294D5317-E983-4682-8DB5-678EA4645E11}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "largepost", "largepost.vcxproj", "{77A27E6D-9A39-40B8-961B-40E63DB7FA65}"
+	77ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug-dll|Win32 = Debug-dll|Win32
 		Debug-dll|x64 = Debug-dll|x64
-		Debug-dll-xp|Win32 = Debug-dll-xp|Win32
+		Debug-dll|Win32 = Debug-dll|Win32
+		Debug-dll|ARM64 = Debug-dll|ARM64
+		Debug-dll|ARM = Debug-dll|ARM
 		Debug-dll-xp|x64 = Debug-dll-xp|x64
-		Debug-static|Win32 = Debug-static|Win32
+		Debug-dll-xp|Win32 = Debug-dll-xp|Win32
+		Debug-dll-xp|ARM64 = Debug-dll-xp|ARM64
+		Debug-dll-xp|ARM = Debug-dll-xp|ARM
 		Debug-static|x64 = Debug-static|x64
-		Debug-static-xp|Win32 = Debug-static-xp|Win32
+		Debug-static|Win32 = Debug-static|Win32
+		Debug-static|ARM64 = Debug-static|ARM64
+		Debug-static|ARM = Debug-static|ARM
 		Debug-static-xp|x64 = Debug-static-xp|x64
-		Release-dll|Win32 = Release-dll|Win32
+		Debug-static-xp|Win32 = Debug-static-xp|Win32
+		Debug-static-xp|ARM64 = Debug-static-xp|ARM64
+		Debug-static-xp|ARM = Debug-static-xp|ARM
 		Release-dll|x64 = Release-dll|x64
-		Release-dll-xp|Win32 = Release-dll-xp|Win32
+		Release-dll|Win32 = Release-dll|Win32
+		Release-dll|ARM64 = Release-dll|ARM64
+		Release-dll|ARM = Release-dll|ARM
 		Release-dll-xp|x64 = Release-dll-xp|x64
-		Release-static|Win32 = Release-static|Win32
+		Release-dll-xp|Win32 = Release-dll-xp|Win32
+		Release-dll-xp|ARM64 = Release-dll-xp|ARM64
+		Release-dll-xp|ARM = Release-dll-xp|ARM
 		Release-static|x64 = Release-static|x64
-		Release-static-xp|Win32 = Release-static-xp|Win32
+		Release-static|Win32 = Release-static|Win32
+		Release-static|ARM64 = Release-static|ARM64
+		Release-static|ARM = Release-static|ARM
 		Release-static-xp|x64 = Release-static-xp|x64
+		Release-static-xp|Win32 = Release-static-xp|Win32
+		Release-static-xp|ARM64 = Release-static-xp|ARM64
+		Release-static-xp|ARM = Release-static-xp|ARM
 	EndGlobalSection
 	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.Build.0 = Debug-dll-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.ActiveCfg = Debug-dll-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.Build.0 = Debug-dll-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Release-static|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Release-static|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.ActiveCfg = Debug-static-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.Build.0 = Debug-static-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.ActiveCfg = Debug-static-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.Build.0 = Debug-static-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.ActiveCfg = Release-dll-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.Build.0 = Release-dll-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.ActiveCfg = Release-dll-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.Build.0 = Release-dll-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.ActiveCfg = Release-static-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.Build.0 = Release-static-xp|Win32
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.ActiveCfg = Release-static-xp|x64
-		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.Build.0 = Release-static-xp|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.Build.0 = Debug-dll|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Debug-static|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.Build.0 = Debug-static|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Release-static|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Release-static|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.Build.0 = Debug-static|ARM
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|x64.Build.0 = Debug-static|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.ActiveCfg = Release-dll|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.Build.0 = Release-dll|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.Build.0 = Release-dll|ARM
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|x64.Build.0 = Release-dll|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.ActiveCfg = Release-static|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.Build.0 = Release-static|x64
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
-		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.Build.0 = Release-static|ARM
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|x64.ActiveCfg = Release-static|x64
 		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.ActiveCfg = Debug-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.Build.0 = Debug-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.Build.0 = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|ARM64.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|ARM.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.ActiveCfg = Debug-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.Build.0 = Debug-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.Build.0 = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|ARM64.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|ARM.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.ActiveCfg = Release-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.Build.0 = Release-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.Build.0 = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|ARM64.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|ARM.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.ActiveCfg = Release-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.Build.0 = Release-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.ActiveCfg = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.Build.0 = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|ARM64.ActiveCfg = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|ARM.ActiveCfg = Release-static-xp|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM.Build.0 = Release-static|ARM
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE
diff --git a/w32/VS2013/libmicrohttpd.vcxproj b/w32/VS2013/libmicrohttpd.vcxproj
index 827f9b3..630e578 100644
--- a/w32/VS2013/libmicrohttpd.vcxproj
+++ b/w32/VS2013/libmicrohttpd.vcxproj
@@ -1,145 +1,18 @@
 <?xml version="1.0" encoding="utf-8"?>
 <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug-dll-xp|Win32">
-      <Configuration>Debug-dll-xp</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-dll-xp|x64">
-      <Configuration>Debug-dll-xp</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-dll|Win32">
-      <Configuration>Debug-dll</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-dll|x64">
-      <Configuration>Debug-dll</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-static-xp|Win32">
-      <Configuration>Debug-static-xp</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-static-xp|x64">
-      <Configuration>Debug-static-xp</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-static|Win32">
-      <Configuration>Debug-static</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug-static|x64">
-      <Configuration>Debug-static</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-dll-xp|Win32">
-      <Configuration>Release-dll-xp</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-dll-xp|x64">
-      <Configuration>Release-dll-xp</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-dll|Win32">
-      <Configuration>Release-dll</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-dll|x64">
-      <Configuration>Release-dll</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-static-xp|Win32">
-      <Configuration>Release-static-xp</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-static-xp|x64">
-      <Configuration>Release-static-xp</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-static|Win32">
-      <Configuration>Release-static</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release-static|x64">
-      <Configuration>Release-static</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\src\microhttpd\base64.c" />
-    <ClCompile Include="..\..\src\microhttpd\basicauth.c" />
-    <ClCompile Include="..\..\src\microhttpd\connection.c" />
-    <ClCompile Include="..\..\src\microhttpd\daemon.c" />
-    <ClCompile Include="..\..\src\microhttpd\digestauth.c" />
-    <ClCompile Include="..\..\src\microhttpd\internal.c" />
-    <ClCompile Include="..\..\src\microhttpd\md5.c" />
-    <ClCompile Include="..\..\src\microhttpd\memorypool.c" />
-    <ClCompile Include="..\..\src\microhttpd\postprocessor.c" />
-    <ClCompile Include="..\..\src\microhttpd\reason_phrase.c" />
-    <ClCompile Include="..\..\src\microhttpd\response.c" />
-    <ClCompile Include="..\..\src\microhttpd\tsearch.c" />
-    <ClCompile Include="..\..\src\platform\w32functions.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\src\include\autoinit_funcs.h" />
-    <ClInclude Include="..\..\src\include\microhttpd.h" />
-    <ClInclude Include="..\..\src\include\platform.h" />
-    <ClInclude Include="..\..\src\include\platform_interface.h" />
-    <ClInclude Include="..\..\src\include\w32functions.h" />
-    <ClInclude Include="..\..\src\microhttpd\base64.h" />
-    <ClInclude Include="..\..\src\microhttpd\connection.h" />
-    <ClInclude Include="..\..\src\microhttpd\internal.h" />
-    <ClInclude Include="..\..\src\microhttpd\md5.h" />
-    <ClInclude Include="..\..\src\microhttpd\memorypool.h" />
-    <ClInclude Include="..\..\src\microhttpd\reason_phrase.h" />
-    <ClInclude Include="..\..\src\microhttpd\response.h" />
-    <ClInclude Include="..\..\src\microhttpd\tsearch.h" />
-    <ClInclude Include="MHD_config.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="microhttpd_dll_res_vc.rc">
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static-xp|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static-xp|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static-xp|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static-xp|x64'">true</ExcludedFromBuild>
-    </ResourceCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <CustomBuild Include="microhttpd_dll_res_vc.rc.in">
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static-xp|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static-xp|Win32'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-static-xp|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-static-xp|x64'">true</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-dll|Win32'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-dll-xp|Win32'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-dll|x64'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug-dll-xp|x64'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-dll|Win32'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-dll-xp|Win32'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-dll|x64'">false</ExcludedFromBuild>
-      <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release-dll-xp|x64'">false</ExcludedFromBuild>
-      <FileType>Document</FileType>
-      <Command>PowerShell.exe -Version 3.0 -NonInteractive -NoProfile -ExecutionPolicy Bypass -File "$(SolutionDir)gen_dll_res.ps1" -BasePath $(SolutionDir)</Command>
-      <Message>Generating .dll description resource</Message>
-      <Outputs>$(SolutionDir)microhttpd_dll_res_vc.rc</Outputs>
-      <AdditionalInputs>$(SolutionDir)gen_dll_res.ps1;$(SolutionDir).\..\..\configure.ac</AdditionalInputs>
-    </CustomBuild>
-  </ItemGroup>
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)project-configs-xp.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-files.vcxproj" />
   <PropertyGroup Label="Globals">
     <ProjectGuid>{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}</ProjectGuid>
     <Keyword>Win32Proj</Keyword>
     <RootNamespace>libmicrohttpd</RootNamespace>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
     <ConfigurationType>StaticLibrary</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
@@ -198,186 +71,13 @@
   <ImportGroup Label="PropertySheets">
     <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
   </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup>
-    <IncludePath>$(SolutionDir)..\..\src\include;$(SolutionDir);$(IncludePath)</IncludePath>
-    <CustomBuildBeforeTargets>ResourceCompile</CustomBuildBeforeTargets>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Platform)'=='Win32'">
-    <IntDir>$(SolutionDir)$(ProjectName)\$(Configuration)\</IntDir>
-    <OutDir>$(SolutionDir)\Output\</OutDir>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Platform)'=='x64'">
-    <IntDir>$(SolutionDir)$(ProjectName)\$(Configuration)\$(Platform)\</IntDir>
-    <OutDir>$(SolutionDir)\Output\$(Platform)\</OutDir>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'">
-    <TargetName>$(ProjectName)_d</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Debug-static-xp'">
-    <TargetName>$(ProjectName)_d</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'">
-    <TargetName>$(ProjectName)-dll_d</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll-xp'">
-    <TargetName>$(ProjectName)-dll_d</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Release-static'">
-    <TargetName>$(ProjectName)</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Release-static-xp'">
-    <TargetName>$(ProjectName)</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'">
-    <TargetName>$(ProjectName)-dll</TargetName>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)'=='Release-dll-xp'">
-    <TargetName>$(ProjectName)-dll</TargetName>
-  </PropertyGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-build-settings.props" />
+  <PropertyGroup />
   <ItemDefinitionGroup>
-    <ClCompile>
-      <PrecompiledHeader>NotUsing</PrecompiledHeader>
-      <WarningLevel>Level3</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;BUILDING_MHD_LIB;MHD_W32LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <DisableSpecificWarnings>4996</DisableSpecificWarnings>
-      <TreatSpecificWarningsAsErrors>4013</TreatSpecificWarningsAsErrors>
-      <ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
-    </ClCompile>
-    <Link>
-      <Subsystem>WINDOWS</Subsystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-    <CustomBuildStep>
-      <Message>Copy headers to output</Message>
-      <Command>xcopy /F /I /Y $(SolutionDir)\..\..\src\include\microhttpd.h $(OutputPath)</Command>
-      <Outputs>$(OutputPath)microhttpd.h;%(Outputs)</Outputs>
-      <Inputs>$(SolutionDir)\..\..\src\include\microhttpd.h</Inputs>
-    </CustomBuildStep>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(PlatformToolset)'!='v120_xp'">
-    <ClCompile>
-      <PreprocessorDefinitions>_WIN32_WINNT=0x0600;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <Link>
-      <MinimumRequiredVersion>6.00</MinimumRequiredVersion>
-      <AdditionalOptions>/SUBSYSTEM:WINDOWS,6.00 %(AdditionalOptions)</AdditionalOptions>
-    </Link>
-    <Lib>
-      <MinimumRequiredVersion>6.00</MinimumRequiredVersion>
-      <AdditionalOptions>/SUBSYSTEM:WINDOWS,6.00 %(AdditionalOptions)</AdditionalOptions>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(PlatformToolset)'=='v120_xp'">
-    <ClCompile>
-      <PreprocessorDefinitions>_WIN32_WINNT=0x0501;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <Link>
-      <MinimumRequiredVersion>5.01</MinimumRequiredVersion>
-      <AdditionalOptions>/SUBSYSTEM:WINDOWS,5.01 %(AdditionalOptions)</AdditionalOptions>
-    </Link>
-    <Lib>
-      <MinimumRequiredVersion>5.01</MinimumRequiredVersion>
-      <AdditionalOptions>/SUBSYSTEM:WINDOWS,5.01 %(AdditionalOptions)</AdditionalOptions>
-    </Lib>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(ConfigurationType)'=='StaticLibrary'">
-    <ClCompile>
-      <PreprocessorDefinitions>_LIB;BUILDING_MHD_LIB;MHD_W32LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <Lib>
-      <AdditionalDependencies>Ws2_32.lib</AdditionalDependencies>
-    </Lib>
-    <PostBuildEvent>
-      <Command>xcopy /F /I /Y $(IntermediateOutputPath)$(TargetName).pdb $(OutputPath)</Command>
-      <Message>Copy .pdb to output directory</Message>
-    </PostBuildEvent>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(ConfigurationType)'=='DynamicLibrary'">
-    <ClCompile>
-      <PreprocessorDefinitions>_USRDLL;BUILDING_MHD_LIB;MHD_W32DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ClCompile>
-    <Link>
-      <AdditionalDependencies>Ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(UseDebugLibraries)'=='true'">
-    <ClCompile>
-      <Optimization>Disabled</Optimization>
-      <SmallerTypeCheck>true</SmallerTypeCheck>
-    </ClCompile>
-    <ResourceCompile>
-      <PreprocessorDefinitions>_DEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ResourceCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(UseDebugLibraries)'!='true'">
-    <ClCompile>
-      <Optimization>Full</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
-      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
-      <OmitFramePointers>true</OmitFramePointers>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-    <ResourceCompile>
-      <PreprocessorDefinitions>NDEBUG;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-    </ResourceCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-static'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-static-xp'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-dll'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-dll-xp'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-static'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Debug-static-xp'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Release-static'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Release-static-xp'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Release-dll'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-    </ClCompile>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)'=='Release-dll-xp'">
-    <ClCompile>
-      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
-    </ClCompile>
+    <ClCompile />
+    <Link />
+    <Lib />
   </ItemDefinitionGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
diff --git a/w32/VS2013/libmicrohttpd.vcxproj.filters b/w32/VS2013/libmicrohttpd.vcxproj.filters
index cbe6380..63f58bf 100644
--- a/w32/VS2013/libmicrohttpd.vcxproj.filters
+++ b/w32/VS2013/libmicrohttpd.vcxproj.filters
@@ -1,119 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
 <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <Filter Include="Source Files">
-      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
-      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
-    </Filter>
-    <Filter Include="Header Files">
-      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
-      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
-    </Filter>
-    <Filter Include="Resource Files">
-      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
-      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
-    </Filter>
-    <Filter Include="Source Files\platform_interface">
-      <UniqueIdentifier>{af799bf7-9787-4134-8e56-9e5aae50c7e3}</UniqueIdentifier>
-    </Filter>
-    <Filter Include="Template Files">
-      <UniqueIdentifier>{df5ad836-e372-437b-a0e3-299d3675d6b4}</UniqueIdentifier>
-      <Extensions>in</Extensions>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\src\microhttpd\base64.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\basicauth.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\connection.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\daemon.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\digestauth.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\internal.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\md5.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\memorypool.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\postprocessor.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\reason_phrase.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\response.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\platform\w32functions.c">
-      <Filter>Source Files\platform_interface</Filter>
-    </ClCompile>
-    <ClCompile Include="..\..\src\microhttpd\tsearch.c">
-      <Filter>Source Files</Filter>
-    </ClCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\src\microhttpd\base64.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\connection.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\internal.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\md5.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\memorypool.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\reason_phrase.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\response.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\include\microhttpd.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\include\platform.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\include\platform_interface.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\include\w32functions.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="MHD_config.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\microhttpd\tsearch.h">
-      <Filter>Source Files</Filter>
-    </ClInclude>
-    <ClInclude Include="..\..\src\include\autoinit_funcs.h">
-      <Filter>Header Files</Filter>
-    </ClInclude>
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="microhttpd_dll_res_vc.rc">
-      <Filter>Resource Files</Filter>
-    </ResourceCompile>
-  </ItemGroup>
-  <ItemGroup>
-    <CustomBuild Include="microhttpd_dll_res_vc.rc.in">
-      <Filter>Template Files</Filter>
-    </CustomBuild>
-  </ItemGroup>
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-filters.vcxproj" />
 </Project>
\ No newline at end of file
diff --git a/w32/VS2013/microhttpd_dll_res_vc.rc b/w32/VS2013/microhttpd_dll_res_vc.rc
deleted file mode 100644
index 6224717..0000000
--- a/w32/VS2013/microhttpd_dll_res_vc.rc
+++ /dev/null
@@ -1,42 +0,0 @@
-/* W32 resources for .dll */
-
-#include <winresrc.h>
-
-LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
-VS_VERSION_INFO VERSIONINFO
-  FILEVERSION 0,9,42,0
-  PRODUCTVERSION 0,9,42,0
-  FILEFLAGSMASK  VS_FFI_FILEFLAGSMASK
-#if defined(_DEBUG)
-  FILEFLAGS      VS_FF_DEBUG
-#else
-  FILEFLAGS      0
-#endif
-  FILEOS         VOS_NT_WINDOWS32
-  FILETYPE       VFT_DLL
-  FILESUBTYPE    VFT2_UNKNOWN
-BEGIN
-    BLOCK "StringFileInfo"
-    BEGIN
-        BLOCK "04090000"  /* Lang = US English, Charset = ASCII */
-        BEGIN
-            VALUE "ProductName", "GNU libmicrohttpd\0"
-            VALUE "ProductVersion", "0.9.42\0"
-            VALUE "FileVersion", "0.9.42\0"
-            VALUE "FileDescription", "GNU libmicrohttpd dll for Windows (VC build)\0"
-            VALUE "InternalName", "libmicrohttpd\0"
-#if defined(_DEBUG)
-            VALUE "OriginalFilename", "libmicrohttpd_d.dll\0"
-#else
-            VALUE "OriginalFilename", "libmicrohttpd.dll\0"
-#endif
-            VALUE "CompanyName", "Free Software Foundation\0"
-            VALUE "LegalCopyright",  "Copyright (C) 2007-2015 Christian Grothoff and project contributors\0"
-            VALUE "Comments", "http://www.gnu.org/software/libmicrohttpd/\0"
-        END
-    END
-    BLOCK "VarFileInfo"
-    BEGIN
-        VALUE "Translation", 0x0409, 0  /* US English, ASCII */
-    END
-END
diff --git a/w32/VS2013/simplepost.vcxproj b/w32/VS2013/simplepost.vcxproj
new file mode 100644
index 0000000..8575bc3
--- /dev/null
+++ b/w32/VS2013/simplepost.vcxproj
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)simplepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{294D5317-E983-4682-8DB5-678EA4645E11}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>simplepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2015/.gitignore b/w32/VS2015/.gitignore
new file mode 100644
index 0000000..9745359
--- /dev/null
+++ b/w32/VS2015/.gitignore
@@ -0,0 +1,7 @@
+/Output
+/libmicrohttpd
+/hellobrowser
+/largepost
+/simplepost
+/*.VC.db
+/*.VC.opendb
diff --git a/w32/VS2015/hellobrowser.vcxproj b/w32/VS2015/hellobrowser.vcxproj
new file mode 100644
index 0000000..569a216
--- /dev/null
+++ b/w32/VS2015/hellobrowser.vcxproj
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{310F39BD-A2D6-44FF-8344-37ADD0524CBD}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>hellobrowser</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2015/hellobrowser.vcxproj.filters b/w32/VS2015/hellobrowser.vcxproj.filters
new file mode 100644
index 0000000..ef5a1fd
--- /dev/null
+++ b/w32/VS2015/hellobrowser.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2015/largepost.vcxproj b/w32/VS2015/largepost.vcxproj
new file mode 100644
index 0000000..60da77c
--- /dev/null
+++ b/w32/VS2015/largepost.vcxproj
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)largepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{77A27E6D-9A39-40B8-961B-40E63DB7FA65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>largepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2015/libmicrohttpd.sln b/w32/VS2015/libmicrohttpd.sln
new file mode 100644
index 0000000..620a195
--- /dev/null
+++ b/w32/VS2015/libmicrohttpd.sln
@@ -0,0 +1,311 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.23107.0
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hellobrowser", "hellobrowser.vcxproj", "{310F39BD-A2D6-44FF-8344-37ADD0524CBD}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "simplepost", "simplepost.vcxproj", "{294D5317-E983-4682-8DB5-678EA4645E11}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "largepost", "largepost.vcxproj", "{77A27E6D-9A39-40B8-961B-40E63DB7FA65}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug-dll|x64 = Debug-dll|x64
+		Debug-dll|Win32 = Debug-dll|Win32
+		Debug-dll|ARM64 = Debug-dll|ARM64
+		Debug-dll|ARM = Debug-dll|ARM
+		Debug-dll-xp|x64 = Debug-dll-xp|x64
+		Debug-dll-xp|Win32 = Debug-dll-xp|Win32
+		Debug-dll-xp|ARM64 = Debug-dll-xp|ARM64
+		Debug-dll-xp|ARM = Debug-dll-xp|ARM
+		Debug-static|x64 = Debug-static|x64
+		Debug-static|Win32 = Debug-static|Win32
+		Debug-static|ARM64 = Debug-static|ARM64
+		Debug-static|ARM = Debug-static|ARM
+		Debug-static-xp|x64 = Debug-static-xp|x64
+		Debug-static-xp|Win32 = Debug-static-xp|Win32
+		Debug-static-xp|ARM64 = Debug-static-xp|ARM64
+		Debug-static-xp|ARM = Debug-static-xp|ARM
+		Release-dll|x64 = Release-dll|x64
+		Release-dll|Win32 = Release-dll|Win32
+		Release-dll|ARM64 = Release-dll|ARM64
+		Release-dll|ARM = Release-dll|ARM
+		Release-dll-xp|x64 = Release-dll-xp|x64
+		Release-dll-xp|Win32 = Release-dll-xp|Win32
+		Release-dll-xp|ARM64 = Release-dll-xp|ARM64
+		Release-dll-xp|ARM = Release-dll-xp|ARM
+		Release-static|x64 = Release-static|x64
+		Release-static|Win32 = Release-static|Win32
+		Release-static|ARM64 = Release-static|ARM64
+		Release-static|ARM = Release-static|ARM
+		Release-static-xp|x64 = Release-static-xp|x64
+		Release-static-xp|Win32 = Release-static-xp|Win32
+		Release-static-xp|ARM64 = Release-static-xp|ARM64
+		Release-static-xp|ARM = Release-static-xp|ARM
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.ActiveCfg = Debug-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.Build.0 = Debug-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.Build.0 = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|ARM64.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|ARM.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.ActiveCfg = Debug-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.Build.0 = Debug-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.Build.0 = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|ARM64.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|ARM.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.ActiveCfg = Release-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.Build.0 = Release-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.Build.0 = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|ARM64.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|ARM.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.ActiveCfg = Release-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.Build.0 = Release-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.ActiveCfg = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.Build.0 = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|ARM64.ActiveCfg = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|ARM.ActiveCfg = Release-static-xp|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/w32/VS2015/libmicrohttpd.vcxproj b/w32/VS2015/libmicrohttpd.vcxproj
new file mode 100644
index 0000000..99469a7
--- /dev/null
+++ b/w32/VS2015/libmicrohttpd.vcxproj
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)project-configs-xp.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>libmicrohttpd</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static-xp'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140_xp</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll-xp'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140_xp</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static-xp'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140_xp</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll-xp'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140_xp</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <Lib />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2015/libmicrohttpd.vcxproj.filters b/w32/VS2015/libmicrohttpd.vcxproj.filters
new file mode 100644
index 0000000..63f58bf
--- /dev/null
+++ b/w32/VS2015/libmicrohttpd.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2015/simplepost.vcxproj b/w32/VS2015/simplepost.vcxproj
new file mode 100644
index 0000000..c59d8de
--- /dev/null
+++ b/w32/VS2015/simplepost.vcxproj
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)simplepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{294D5317-E983-4682-8DB5-678EA4645E11}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>simplepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2017/.gitignore b/w32/VS2017/.gitignore
new file mode 100644
index 0000000..c9144d0
--- /dev/null
+++ b/w32/VS2017/.gitignore
@@ -0,0 +1,6 @@
+/Output
+/libmicrohttpd
+/hellobrowser
+/largepost
+/simplepost
+/.vs
diff --git a/w32/VS2017/hellobrowser.vcxproj b/w32/VS2017/hellobrowser.vcxproj
new file mode 100644
index 0000000..2437daa
--- /dev/null
+++ b/w32/VS2017/hellobrowser.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{310F39BD-A2D6-44FF-8344-37ADD0524CBD}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>hellobrowser</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v141</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2017/hellobrowser.vcxproj.filters b/w32/VS2017/hellobrowser.vcxproj.filters
new file mode 100644
index 0000000..ef5a1fd
--- /dev/null
+++ b/w32/VS2017/hellobrowser.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2017/largepost.vcxproj b/w32/VS2017/largepost.vcxproj
new file mode 100644
index 0000000..50caf38
--- /dev/null
+++ b/w32/VS2017/largepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)largepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{77A27E6D-9A39-40B8-961B-40E63DB7FA65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>largepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v141</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2017/libmicrohttpd.sln b/w32/VS2017/libmicrohttpd.sln
new file mode 100644
index 0000000..5568686
--- /dev/null
+++ b/w32/VS2017/libmicrohttpd.sln
@@ -0,0 +1,311 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26228.9
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hellobrowser", "hellobrowser.vcxproj", "{310F39BD-A2D6-44FF-8344-37ADD0524CBD}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "simplepost", "simplepost.vcxproj", "{294D5317-E983-4682-8DB5-678EA4645E11}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "largepost", "largepost.vcxproj", "{77A27E6D-9A39-40B8-961B-40E63DB7FA65}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug-dll|x64 = Debug-dll|x64
+		Debug-dll|Win32 = Debug-dll|Win32
+		Debug-dll|ARM64 = Debug-dll|ARM64
+		Debug-dll|ARM = Debug-dll|ARM
+		Debug-dll-xp|x64 = Debug-dll-xp|x64
+		Debug-dll-xp|Win32 = Debug-dll-xp|Win32
+		Debug-dll-xp|ARM64 = Debug-dll-xp|ARM64
+		Debug-dll-xp|ARM = Debug-dll-xp|ARM
+		Debug-static|x64 = Debug-static|x64
+		Debug-static|Win32 = Debug-static|Win32
+		Debug-static|ARM64 = Debug-static|ARM64
+		Debug-static|ARM = Debug-static|ARM
+		Debug-static-xp|x64 = Debug-static-xp|x64
+		Debug-static-xp|Win32 = Debug-static-xp|Win32
+		Debug-static-xp|ARM64 = Debug-static-xp|ARM64
+		Debug-static-xp|ARM = Debug-static-xp|ARM
+		Release-dll|x64 = Release-dll|x64
+		Release-dll|Win32 = Release-dll|Win32
+		Release-dll|ARM64 = Release-dll|ARM64
+		Release-dll|ARM = Release-dll|ARM
+		Release-dll-xp|x64 = Release-dll-xp|x64
+		Release-dll-xp|Win32 = Release-dll-xp|Win32
+		Release-dll-xp|ARM64 = Release-dll-xp|ARM64
+		Release-dll-xp|ARM = Release-dll-xp|ARM
+		Release-static|x64 = Release-static|x64
+		Release-static|Win32 = Release-static|Win32
+		Release-static|ARM64 = Release-static|ARM64
+		Release-static|ARM = Release-static|ARM
+		Release-static-xp|x64 = Release-static-xp|x64
+		Release-static-xp|Win32 = Release-static-xp|Win32
+		Release-static-xp|ARM64 = Release-static-xp|ARM64
+		Release-static-xp|ARM = Release-static-xp|ARM
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.ActiveCfg = Debug-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|x64.Build.0 = Debug-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|Win32.Build.0 = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|ARM64.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll-xp|ARM.ActiveCfg = Debug-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.ActiveCfg = Debug-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|x64.Build.0 = Debug-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|Win32.Build.0 = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|ARM64.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static-xp|ARM.ActiveCfg = Debug-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.ActiveCfg = Release-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|x64.Build.0 = Release-dll-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|Win32.Build.0 = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|ARM64.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll-xp|ARM.ActiveCfg = Release-dll-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.ActiveCfg = Release-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|x64.Build.0 = Release-static-xp|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.ActiveCfg = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|Win32.Build.0 = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|ARM64.ActiveCfg = Release-static-xp|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static-xp|ARM.ActiveCfg = Release-static-xp|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll-xp|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM64.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM64.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static-xp|ARM.Build.0 = Release-static|ARM
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/w32/VS2017/libmicrohttpd.vcxproj b/w32/VS2017/libmicrohttpd.vcxproj
new file mode 100644
index 0000000..27f44be
--- /dev/null
+++ b/w32/VS2017/libmicrohttpd.vcxproj
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)project-configs-xp.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>libmicrohttpd</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType Condition="$(Configuration.Contains('-static'))">StaticLibrary</ConfigurationType>
+    <ConfigurationType Condition="! $(Configuration.Contains('-static'))">DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset Condition="! $(Configuration.EndsWith('-xp'))">v141</PlatformToolset>
+    <PlatformToolset Condition="$(Configuration.EndsWith('-xp'))">v141_xp</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <Lib />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2017/libmicrohttpd.vcxproj.filters b/w32/VS2017/libmicrohttpd.vcxproj.filters
new file mode 100644
index 0000000..63f58bf
--- /dev/null
+++ b/w32/VS2017/libmicrohttpd.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2017/simplepost.vcxproj b/w32/VS2017/simplepost.vcxproj
new file mode 100644
index 0000000..f956428
--- /dev/null
+++ b/w32/VS2017/simplepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)simplepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{294D5317-E983-4682-8DB5-678EA4645E11}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>simplepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v141</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2019/.gitignore b/w32/VS2019/.gitignore
new file mode 100644
index 0000000..c9144d0
--- /dev/null
+++ b/w32/VS2019/.gitignore
@@ -0,0 +1,6 @@
+/Output
+/libmicrohttpd
+/hellobrowser
+/largepost
+/simplepost
+/.vs
diff --git a/w32/VS2019/hellobrowser.vcxproj b/w32/VS2019/hellobrowser.vcxproj
new file mode 100644
index 0000000..2335b2e
--- /dev/null
+++ b/w32/VS2019/hellobrowser.vcxproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <VCProjectVersion>16.0</VCProjectVersion>
+    <ProjectGuid>{310F39BD-A2D6-44FF-8344-37ADD0524CBD}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>hellobrowser</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v142</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2019/hellobrowser.vcxproj.filters b/w32/VS2019/hellobrowser.vcxproj.filters
new file mode 100644
index 0000000..ef5a1fd
--- /dev/null
+++ b/w32/VS2019/hellobrowser.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2019/largepost.vcxproj b/w32/VS2019/largepost.vcxproj
new file mode 100644
index 0000000..afde61b
--- /dev/null
+++ b/w32/VS2019/largepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)largepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{77A27E6D-9A39-40B8-961B-40E63DB7FA65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>largepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v142</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2019/libmicrohttpd.sln b/w32/VS2019/libmicrohttpd.sln
new file mode 100644
index 0000000..b9d3b4c
--- /dev/null
+++ b/w32/VS2019/libmicrohttpd.sln
@@ -0,0 +1,175 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.28803.156
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hellobrowser", "hellobrowser.vcxproj", "{310F39BD-A2D6-44FF-8344-37ADD0524CBD}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "simplepost", "simplepost.vcxproj", "{294D5317-E983-4682-8DB5-678EA4645E11}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "largepost", "largepost.vcxproj", "{77A27E6D-9A39-40B8-961B-40E63DB7FA65}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug-dll|Win32 = Debug-dll|Win32
+		Debug-dll|x64 = Debug-dll|x64
+		Debug-dll|ARM = Debug-dll|ARM
+		Debug-dll|ARM64 = Debug-dll|ARM64
+		Debug-static|Win32 = Debug-static|Win32
+		Debug-static|x64 = Debug-static|x64
+		Debug-static|ARM = Debug-static|ARM
+		Debug-static|ARM64 = Debug-static|ARM64
+		Release-dll|Win32 = Release-dll|Win32
+		Release-dll|x64 = Release-dll|x64
+		Release-dll|ARM = Release-dll|ARM
+		Release-dll|ARM64 = Release-dll|ARM64
+		Release-static|Win32 = Release-static|Win32
+		Release-static|x64 = Release-static|x64
+		Release-static|ARM = Release-static|ARM
+		Release-static|ARM64 = Release-static|ARM64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.Build.0 = Release-static|ARM64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/w32/VS2019/libmicrohttpd.vcxproj b/w32/VS2019/libmicrohttpd.vcxproj
new file mode 100644
index 0000000..3d7d5a9
--- /dev/null
+++ b/w32/VS2019/libmicrohttpd.vcxproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>libmicrohttpd</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType Condition="$(Configuration.EndsWith('-static'))">StaticLibrary</ConfigurationType>
+    <ConfigurationType Condition="! $(Configuration.EndsWith('-static'))">DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v142</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <Lib />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2019/libmicrohttpd.vcxproj.filters b/w32/VS2019/libmicrohttpd.vcxproj.filters
new file mode 100644
index 0000000..63f58bf
--- /dev/null
+++ b/w32/VS2019/libmicrohttpd.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2019/simplepost.vcxproj b/w32/VS2019/simplepost.vcxproj
new file mode 100644
index 0000000..c674f65
--- /dev/null
+++ b/w32/VS2019/simplepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)simplepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{294D5317-E983-4682-8DB5-678EA4645E11}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>simplepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v142</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2022/.gitignore b/w32/VS2022/.gitignore
new file mode 100644
index 0000000..c9144d0
--- /dev/null
+++ b/w32/VS2022/.gitignore
@@ -0,0 +1,6 @@
+/Output
+/libmicrohttpd
+/hellobrowser
+/largepost
+/simplepost
+/.vs
diff --git a/w32/VS2022/hellobrowser.vcxproj b/w32/VS2022/hellobrowser.vcxproj
new file mode 100644
index 0000000..275ba5a
--- /dev/null
+++ b/w32/VS2022/hellobrowser.vcxproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <VCProjectVersion>16.0</VCProjectVersion>
+    <ProjectGuid>{310F39BD-A2D6-44FF-8344-37ADD0524CBD}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>hellobrowser</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v143</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2022/hellobrowser.vcxproj.filters b/w32/VS2022/hellobrowser.vcxproj.filters
new file mode 100644
index 0000000..ef5a1fd
--- /dev/null
+++ b/w32/VS2022/hellobrowser.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)hellobrowser-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2022/largepost.vcxproj b/w32/VS2022/largepost.vcxproj
new file mode 100644
index 0000000..067e7bc
--- /dev/null
+++ b/w32/VS2022/largepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)largepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{77A27E6D-9A39-40B8-961B-40E63DB7FA65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>largepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v143</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2022/libmicrohttpd.sln b/w32/VS2022/libmicrohttpd.sln
new file mode 100644
index 0000000..11bd03a
--- /dev/null
+++ b/w32/VS2022/libmicrohttpd.sln
@@ -0,0 +1,176 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31815.197
+MinimumVisualStudioVersion = 10.0.40219.1
+
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hellobrowser", "hellobrowser.vcxproj", "{310F39BD-A2D6-44FF-8344-37ADD0524CBD}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libmicrohttpd", "libmicrohttpd.vcxproj", "{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "simplepost", "simplepost.vcxproj", "{294D5317-E983-4682-8DB5-678EA4645E11}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "largepost", "largepost.vcxproj", "{77A27E6D-9A39-40B8-961B-40E63DB7FA65}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A} = {9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug-dll|Win32 = Debug-dll|Win32
+		Debug-dll|x64 = Debug-dll|x64
+		Debug-dll|ARM = Debug-dll|ARM
+		Debug-dll|ARM64 = Debug-dll|ARM64
+		Debug-static|Win32 = Debug-static|Win32
+		Debug-static|x64 = Debug-static|x64
+		Debug-static|ARM = Debug-static|ARM
+		Debug-static|ARM64 = Debug-static|ARM64
+		Release-dll|Win32 = Release-dll|Win32
+		Release-dll|x64 = Release-dll|x64
+		Release-dll|ARM = Release-dll|ARM
+		Release-dll|ARM64 = Release-dll|ARM64
+		Release-static|Win32 = Release-static|Win32
+		Release-static|x64 = Release-static|x64
+		Release-static|ARM = Release-static|ARM
+		Release-static|ARM64 = Release-static|ARM64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|x64.Build.0 = Debug-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|x64.Build.0 = Release-dll|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|Win32.Build.0 = Release-static|Win32
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.ActiveCfg = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|x64.Build.0 = Release-static|x64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM.Build.0 = Release-static|ARM
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|x64.Build.0 = Debug-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|x64.Build.0 = Release-dll|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|Win32.Build.0 = Release-static|Win32
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.ActiveCfg = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|x64.Build.0 = Release-static|x64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM.Build.0 = Release-static|ARM
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{310F39BD-A2D6-44FF-8344-37ADD0524CBD}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|x64.Build.0 = Debug-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|x64.Build.0 = Release-dll|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|Win32.Build.0 = Release-static|Win32
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.ActiveCfg = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|x64.Build.0 = Release-static|x64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM.Build.0 = Release-static|ARM
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{294D5317-E983-4682-8DB5-678EA4645E11}.Release-static|ARM64.Build.0 = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.ActiveCfg = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|Win32.Build.0 = Debug-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.ActiveCfg = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|x64.Build.0 = Debug-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.ActiveCfg = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM.Build.0 = Debug-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.ActiveCfg = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-dll|ARM64.Build.0 = Debug-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.ActiveCfg = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|Win32.Build.0 = Debug-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.ActiveCfg = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.ActiveCfg = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM.Build.0 = Debug-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.ActiveCfg = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|ARM64.Build.0 = Debug-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Debug-static|x64.Build.0 = Debug-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.ActiveCfg = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|Win32.Build.0 = Release-dll|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.ActiveCfg = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|x64.Build.0 = Release-dll|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.ActiveCfg = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM.Build.0 = Release-dll|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.ActiveCfg = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-dll|ARM64.Build.0 = Release-dll|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.ActiveCfg = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|Win32.Build.0 = Release-static|Win32
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.ActiveCfg = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|x64.Build.0 = Release-static|x64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.ActiveCfg = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM.Build.0 = Release-static|ARM
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.ActiveCfg = Release-static|ARM64
+		{77A27E6D-9A39-40B8-961B-40E63DB7FA65}.Release-static|ARM64.Build.0 = Release-static|ARM64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
diff --git a/w32/VS2022/libmicrohttpd.vcxproj b/w32/VS2022/libmicrohttpd.vcxproj
new file mode 100644
index 0000000..f7af58d
--- /dev/null
+++ b/w32/VS2022/libmicrohttpd.vcxproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{9CFB0342-A9E7-483E-BEE5-A1DE22584C5A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>libmicrohttpd</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType Condition="$(Configuration.EndsWith('-static'))">StaticLibrary</ConfigurationType>
+    <ConfigurationType Condition="! $(Configuration.EndsWith('-static'))">DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v143</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <Lib />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/VS2022/libmicrohttpd.vcxproj.filters b/w32/VS2022/libmicrohttpd.vcxproj.filters
new file mode 100644
index 0000000..63f58bf
--- /dev/null
+++ b/w32/VS2022/libmicrohttpd.vcxproj.filters
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)libmicrohttpd-filters.vcxproj" />
+</Project>
\ No newline at end of file
diff --git a/w32/VS2022/simplepost.vcxproj b/w32/VS2022/simplepost.vcxproj
new file mode 100644
index 0000000..8625c32
--- /dev/null
+++ b/w32/VS2022/simplepost.vcxproj
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(SolutionDir)..\common\vs_dirs.props" />
+  <Import Project="$(MhdW32Common)project-configs.props" />
+  <Import Project="$(MhdW32Common)simplepost-files.vcxproj" />
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{294D5317-E983-4682-8DB5-678EA4645E11}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>simplepost</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    <PreferredToolArchitecture>x64</PreferredToolArchitecture>
+  </PropertyGroup>
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries Condition="$(Configuration.StartsWith('Debug'))">true</UseDebugLibraries>
+    <UseDebugLibraries Condition="! $(Configuration.StartsWith('Debug'))">false</UseDebugLibraries>
+    <PlatformToolset>v143</PlatformToolset>
+    <WholeProgramOptimization Condition="! $(Configuration.StartsWith('Debug'))">true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <Import Project="$(MhdW32Common)common-build-settings.props" />
+  <Import Project="$(MhdW32Common)apps-build-settings.props" />
+  <PropertyGroup />
+  <ItemDefinitionGroup>
+    <ClCompile />
+    <Link />
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/w32/common/MHD_config.h b/w32/common/MHD_config.h
new file mode 100644
index 0000000..c6acf32
--- /dev/null
+++ b/w32/common/MHD_config.h
@@ -0,0 +1,254 @@
+/* MHD_config.h for W32 */
+/* Created manually. */
+
+/* *** Basic OS/compiler information *** */
+
+/* This is a Windows system */
+#define WINDOWS 1
+
+/* Define if MS VC compiler is used */
+#define MSVC 1
+
+#ifndef __clang__
+/* Define that MS VC does not support VLAs */
+#ifndef __STDC_NO_VLA__
+#define __STDC_NO_VLA__ 1
+#endif /* ! __STDC_NO_VLA__ */
+#else
+/* If clang is used then variable-length arrays are supported. */
+#define HAVE_C_VARARRAYS 1
+#endif
+
+/* Define to 1 if your C compiler supports inline functions. */
+#define INLINE_FUNC 1
+
+/* Define to prefix which will be used with MHD inline functions. */
+#define _MHD_static_inline static __forceinline
+
+#ifdef __clang__
+/* Define to 1 if you have __builtin_bswap32() builtin function */
+#define MHD_HAVE___BUILTIN_BSWAP32 1
+
+/* Define to 1 if you have __builtin_bswap64() builtin function */
+#define MHD_HAVE___BUILTIN_BSWAP64 1
+#endif /* __clang__ */
+
+/* The size of `size_t', as computed by sizeof. */
+#if defined(_M_X64) || defined(_M_AMD64) || defined(_M_ARM64) || defined(_WIN64)
+#define SIZEOF_SIZE_T 8
+#else  /* ! _WIN64 */
+#define SIZEOF_SIZE_T 4
+#endif /* ! _WIN64 */
+
+/* The size of `tv_sec' member of `struct timeval', as computed by sizeof */
+#define SIZEOF_STRUCT_TIMEVAL_TV_SEC 4
+
+/* The size of `int64_t', as computed by sizeof. */
+#define SIZEOF_INT64_T 8
+
+/* The size of `uint64_t', as computed by sizeof. */
+#define SIZEOF_UINT64_T 8
+
+/* The size of `int', as computed by sizeof. */
+#define SIZEOF_INT 4
+
+/* The size of `unsigned int', as computed by sizeof. */
+#define SIZEOF_UNSIGNED_INT 4
+
+/* The size of `unsigned long long', as computed by sizeof. */
+#define SIZEOF_UNSIGNED_LONG_LONG 8
+
+/* Define to supported 'noreturn' function declaration */
+#if defined(_STDC_VERSION__) && (__STDC_VERSION__ + 0) >= 201112L
+#define _MHD_NORETURN _Noreturn
+#else  /* before C11 */
+#define _MHD_NORETURN __declspec(noreturn)
+#endif /* before C11 */
+
+/* *** MHD configuration *** */
+/* Undef to disable feature */
+
+/* Enable basic Auth support */
+#define BAUTH_SUPPORT 1
+
+/* Enable digest Auth support */
+#define DAUTH_SUPPORT 1
+
+/* Enable MD5 hashing support. */
+#define MHD_MD5_SUPPORT 1
+
+/* Enable SHA-256 hashing support. */
+#define MHD_SHA256_SUPPORT 1
+
+/* Enable SHA-512/256 hashing support. */
+#define MHD_SHA512_256_SUPPORT 1
+
+/* Enable postprocessor.c */
+#define HAVE_POSTPROCESSOR 1
+
+/* Enable error messages */
+#define HAVE_MESSAGES 1
+
+/* Enable HTTP Upgrade support. */
+#define UPGRADE_SUPPORT 1
+
+/* Enable HTTP cookie parsing support. */
+#define COOKIE_SUPPORT 1
+
+/* *** OS features *** */
+
+/* Provides IPv6 headers */
+#define HAVE_INET6 1
+
+/* Define to use socketpair for inter-thread communication */
+#define _MHD_ITC_SOCKETPAIR 1
+
+/* define to use W32 threads */
+#define MHD_USE_W32_THREADS 1
+
+#ifndef _WIN32_WINNT
+/* MHD supports Windows XP and later W32 systems*/
+#define _WIN32_WINNT 0x0600
+#endif /* _WIN32_WINNT */
+
+/* winsock poll is available only on Vista and later */
+#if _WIN32_WINNT >= 0x0600
+#define HAVE_POLL 1
+#endif /* _WIN32_WINNT >= 0x0600 */
+
+/* Define to 1 if you have the <winsock2.h> header file. */
+#define HAVE_WINSOCK2_H 1
+
+/* Define to 1 if you have the <ws2tcpip.h> header file. */
+#define HAVE_WS2TCPIP_H 1
+
+/* Define to 1 if you have the `_lseeki64' function. */
+#define HAVE___LSEEKI64 1
+
+/* Define to 1 if you have the `gmtime_s' function in W32 form. */
+#define HAVE_W32_GMTIME_S 1
+
+/* Define to 1 if you have the usable `calloc' function. */
+#define HAVE_CALLOC 1
+
+/* Define if you have usable assert() and assert.h */
+#define HAVE_ASSERT 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <limits.h> header file. */
+#define HAVE_LIMITS_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H   1
+
+/* Define to 1 if you have the <time.h> header file. */
+#define HAVE_TIME_H       1
+
+#if _MSC_VER >= 1900 /* snprintf() supported natively since VS2015 */
+/* Define to 1 if you have the `snprintf' function. */
+#define HAVE_SNPRINTF 1
+#endif
+
+#if _MSC_VER >= 1800
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+#endif
+
+#if _MSC_VER + 0 >= 1800 /* VS 2013 and later */
+/* Define to 1 if you have the <stdbool.h> header file and <stdbool.h> defines
+   'bool' type. */
+#define HAVE_STDBOOL_H 1
+/* Define to 1 if you have the real boolean type. */
+#define HAVE_REAL_BOOL 1
+#else  /* before VS 2013 */
+
+/* Define to type name which will be used as boolean type. */
+#define bool int
+
+/* Define to value interpreted by compiler as boolean "false", if "false" is
+   not defined by system headers. */
+#define false 0
+
+/* Define to value interpreted by compiler as boolean "true", if "true" is not
+   defined by system headers. */
+#define true (!0)
+#endif /* before VS 2013 */
+
+/* Define to 1 if you have the `getsockname' function. */
+#define HAVE_GETSOCKNAME 1
+
+/* Define if you have usable `getsockname' function. */
+#define MHD_USE_GETSOCKNAME 1
+
+/* Define to 1 if your compiler supports __func__ magic-macro. */
+#define HAVE___FUNC__ 1
+
+#if _MSC_VER + 0 >= 1900 /* VS 2015 and later */
+#if defined(_STDC_VERSION__) && (__STDC_VERSION__ + 0) >= 201112L
+/* Define to 1 if your compiler supports 'alignof()' */
+#define HAVE_C_ALIGNOF 1
+/* Define to 1 if you have the <stdalign.h> header file. */
+#define HAVE_STDALIGN_H 1
+#endif /* C11 */
+#endif /* VS 2015 and later */
+
+/* Define to 1 if you have the 'rand' function. */
+#define HAVE_RAND 1
+
+/* *** Headers information *** */
+/* Not really important as not used by code currently */
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the <locale.h> header file. */
+#define HAVE_LOCALE_H 1
+
+/* Define to 1 if you have the <math.h> header file. */
+#define HAVE_MATH_H 1
+
+/* Define to 1 if you have the <sdkddkver.h> header file. */
+#define HAVE_SDKDDKVER_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdio.h> header file. */
+#define HAVE_STDIO_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <windows.h> header file. */
+#define HAVE_WINDOWS_H 1
+
+
+/* *** Other useful staff *** */
+
+#define _GNU_SOURCE  1
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+
+/* End of MHD_config.h */
diff --git a/w32/common/apps-build-settings.props b/w32/common/apps-build-settings.props
new file mode 100644
index 0000000..45e7ed7
--- /dev/null
+++ b/w32/common/apps-build-settings.props
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-static'">
+    <TargetName>$(ProjectName)_d</TargetName>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Debug-dll'">
+    <TargetName>$(ProjectName)-dll_d</TargetName>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-static'">
+    <TargetName>$(ProjectName)</TargetName>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)'=='Release-dll'">
+    <TargetName>$(ProjectName)-dll</TargetName>
+  </PropertyGroup>
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <PreprocessorDefinitions>_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+    </Link>
+    <ProjectReference />
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <RuntimeLibrary Condition="'$(Configuration)'=='Debug-static'">MultiThreadedDebug</RuntimeLibrary>
+      <RuntimeLibrary Condition="'$(Configuration)'=='Debug-dll'">MultiThreadedDebugDLL</RuntimeLibrary>
+      <RuntimeLibrary Condition="'$(Configuration)'=='Release-static'">MultiThreaded</RuntimeLibrary>
+      <RuntimeLibrary Condition="'$(Configuration)'=='Release-dll'">MultiThreadedDLL</RuntimeLibrary>
+    </ClCompile>
+  </ItemDefinitionGroup>
+</Project>
diff --git a/w32/common/common-build-settings.props b/w32/common/common-build-settings.props
new file mode 100644
index 0000000..4a702d1
--- /dev/null
+++ b/w32/common/common-build-settings.props
@@ -0,0 +1,136 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Label="UserMacros">
+    <!-- Target minimum OS version: WinXP = 0; Vista = 1; Win7 = 2; Win8 = 3...
+         Only 0, 1 and 3 are used currently -->
+    <TargetOSLevel Condition="$(Platform.ToLowerInvariant().StartsWith('arm'))">3</TargetOSLevel>
+    <TargetOSLevel Condition="! $(Platform.ToLowerInvariant().StartsWith('arm')) And $(PlatformToolset.EndsWith('_xp'))">0</TargetOSLevel>
+    <TargetOSLevel Condition="! $(Platform.ToLowerInvariant().StartsWith('arm')) And ! $(PlatformToolset.EndsWith('_xp'))">1</TargetOSLevel>
+    <MhdNumBits Condition="$(Platform.EndsWith('64'))">64</MhdNumBits>
+    <MhdNumBits Condition="! $(Platform.EndsWith('64'))">32</MhdNumBits>
+  </PropertyGroup>
+  <PropertyGroup>
+    <IncludePath>$(SolutionDir);$(MhdW32Common);$(MhdSrc)include;$(IncludePath)</IncludePath>
+  </PropertyGroup>
+  <PropertyGroup>
+    <IntDir>$(SolutionDir)$(ProjectName)\$(Configuration)\$(Platform)\</IntDir>
+    <OutDir>$(SolutionDir)Output\$(Platform)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(UseDebugLibraries)'=='true'">
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(UseDebugLibraries)'!='true'">
+    <LinkIncremental>false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <PrecompiledHeader>NotUsing</PrecompiledHeader>
+      <WarningLevel Condition="'%(ClCompile.ExternalWarningLevel)' != ''">EnableAllWarnings</WarningLevel>
+      <WarningLevel Condition="'%(ClCompile.ExternalWarningLevel)' == ''">Level4</WarningLevel>
+      <ExternalWarningLevel>Level3</ExternalWarningLevel>
+      <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <DisableSpecificWarnings>4996;4820;4127;5045</DisableSpecificWarnings>
+      <TreatSpecificWarningsAsErrors>4013</TreatSpecificWarningsAsErrors>
+      <ProgramDataBaseFileName>$(IntDir)$(TargetName).pdb</ProgramDataBaseFileName>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <LanguageStandard_C Condition="'%(ClCompile.LanguageStandard_C)' != ''">stdc17</LanguageStandard_C>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(MhdNumBits)' == '32'">
+    <ClCompile>
+      <PreprocessorDefinitions>WIN32;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(TargetOSLevel)'&gt;='3'">
+    <ClCompile>
+      <PreprocessorDefinitions>_WIN32_WINNT=0x0602;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <MinimumRequiredVersion>6.02</MinimumRequiredVersion>
+    </Link>
+    <Lib>
+      <MinimumRequiredVersion>6.02</MinimumRequiredVersion>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(TargetOSLevel)'&gt;'0' And '$(TargetOSLevel)'&lt;'3'">
+    <ClCompile>
+      <PreprocessorDefinitions>_WIN32_WINNT=0x0600;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <MinimumRequiredVersion>6.00</MinimumRequiredVersion>
+    </Link>
+    <Lib>
+      <MinimumRequiredVersion>6.00</MinimumRequiredVersion>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(TargetOSLevel)'=='0' And '$(Platform)'=='Win32'">
+    <ClCompile>
+      <PreprocessorDefinitions>_WIN32_WINNT=0x0501;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <MinimumRequiredVersion>5.01</MinimumRequiredVersion>
+    </Link>
+    <Lib>
+      <MinimumRequiredVersion>5.01</MinimumRequiredVersion>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(TargetOSLevel)'=='0' And '$(Platform)'=='x64'">
+    <ClCompile>
+      <PreprocessorDefinitions>_WIN32_WINNT=0x0502;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <MinimumRequiredVersion>5.02</MinimumRequiredVersion>
+    </Link>
+    <Lib>
+      <MinimumRequiredVersion>5.02</MinimumRequiredVersion>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(UseDebugLibraries)'=='true'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <SmallerTypeCheck>true</SmallerTypeCheck>
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <ResourceCompile>
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ResourceCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(UseDebugLibraries)'!='true'">
+    <ClCompile>
+      <Optimization>Full</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <OmitFramePointers>true</OmitFramePointers>
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+    </Link>
+    <ResourceCompile>
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ResourceCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
+    <Link>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+    <Lib>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Lib>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
+    <Link>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+    <Lib>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Lib>
+  </ItemDefinitionGroup>
+</Project>
diff --git a/w32/VS2013/gen_dll_res.ps1 b/w32/common/gen_dll_res.ps1
similarity index 84%
rename from w32/VS2013/gen_dll_res.ps1
rename to w32/common/gen_dll_res.ps1
index e51d103..da8e4c6 100644
--- a/w32/VS2013/gen_dll_res.ps1
+++ b/w32/common/gen_dll_res.ps1
@@ -8,7 +8,7 @@
 Write-Output "Processing: ${BasePath}..\..\configure.ac"
 foreach($line in Get-Content "${BasePath}..\..\configure.ac")
 {
-    if ($line -match '^AC_INIT\(\[libmicrohttpd\],\[((\d+).(\d+).(\d+))\]') 
+    if ($line -match '^AC_INIT\(\[(?:GNU )?libmicrohttpd\],\[((\d+).(\d+).(\d+))\]') 
     {
         [string]$MHD_ver = $Matches[1].ToString()
         [string]$MHD_ver_major = $Matches[2].ToString()
@@ -19,7 +19,8 @@
 }
 if ("$MHD_ver" -eq "" -or "$MHD_ver_major" -eq ""  -or "$MHD_ver_minor" -eq "" -or "$MHD_ver_patchlev" -eq "")
 {
-    Throw "Can't find MHD version in ${BasePath}..\..\configure.ac"
+    Write-Error -Message ("error MHDVSVER01 : Can't find MHD version")
+    Throw ($MyInvocation.MyCommand.Name + " : error MHDVSVER01 : Can't find MHD version")
 }
 
 Write-Output "Detected MHD version: $MHD_ver"
diff --git a/w32/common/hellobrowser-files.vcxproj b/w32/common/hellobrowser-files.vcxproj
new file mode 100644
index 0000000..f7caefb
--- /dev/null
+++ b/w32/common/hellobrowser-files.vcxproj
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="$(MhdRoot)doc\examples\hellobrowser.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="libmicrohttpd.vcxproj">
+      <Project>{9cfb0342-a9e7-483e-bee5-a1de22584c5a}</Project>
+    </ProjectReference>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/hellobrowser-filters.vcxproj b/w32/common/hellobrowser-filters.vcxproj
new file mode 100644
index 0000000..1438494
--- /dev/null
+++ b/w32/common/hellobrowser-filters.vcxproj
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="$(MhdRoot)doc\examples\hellobrowser.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/largepost-files.vcxproj b/w32/common/largepost-files.vcxproj
new file mode 100644
index 0000000..bb15f53
--- /dev/null
+++ b/w32/common/largepost-files.vcxproj
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="$(MhdRoot)doc\examples\largepost.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="libmicrohttpd.vcxproj">
+      <Project>{9cfb0342-a9e7-483e-bee5-a1de22584c5a}</Project>
+    </ProjectReference>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/libmicrohttpd-build-settings.props b/w32/common/libmicrohttpd-build-settings.props
new file mode 100644
index 0000000..76f2d0e
--- /dev/null
+++ b/w32/common/libmicrohttpd-build-settings.props
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <CustomBuildBeforeTargets>ResourceCompile</CustomBuildBeforeTargets>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(ConfigurationType)'=='StaticLibrary'">
+    <TargetName Condition="'$(UseDebugLibraries)'=='true'">$(ProjectName)_d</TargetName>
+    <TargetName Condition="'$(UseDebugLibraries)'!='true'">$(ProjectName)</TargetName>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(ConfigurationType)'=='DynamicLibrary'">
+    <TargetName Condition="'$(UseDebugLibraries)'=='true'">$(ProjectName)-dll_d</TargetName>
+    <TargetName Condition="'$(UseDebugLibraries)'!='true'">$(ProjectName)-dll</TargetName>
+  </PropertyGroup>
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <PreprocessorDefinitions>BUILDING_MHD_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <DisableSpecificWarnings>4746;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+    </ClCompile>
+    <Link>
+      <Subsystem>WINDOWS</Subsystem>
+    </Link>
+    <Lib>
+      <SubSystem>Windows</SubSystem>
+    </Lib>
+    <CustomBuildStep>
+      <Message>Copy headers to output</Message>
+      <Command>xcopy /F /I /Y "$(MhdSrc)include\microhttpd.h" "$(OutputPath)"</Command>
+      <Outputs>$(OutputPath)microhttpd.h;%(Outputs)</Outputs>
+      <Inputs>$(MhdSrc)include\microhttpd.h</Inputs>
+    </CustomBuildStep>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(ConfigurationType)'=='StaticLibrary'">
+    <ClCompile>
+      <PreprocessorDefinitions>_LIB;MHD_W32LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary Condition="'$(UseDebugLibraries)'=='true'">MultiThreadedDebug</RuntimeLibrary>
+      <RuntimeLibrary Condition="'$(UseDebugLibraries)'!='true'">MultiThreaded</RuntimeLibrary>
+    </ClCompile>
+    <Lib>
+      <AdditionalDependencies>Ws2_32.lib</AdditionalDependencies>
+    </Lib>
+    <PostBuildEvent>
+      <Command>xcopy /F /I /Y "$(IntermediateOutputPath)$(TargetName).pdb" "$(OutputPath)"</Command>
+      <Message>Copy .pdb to output directory</Message>
+    </PostBuildEvent>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(ConfigurationType)'=='DynamicLibrary'">
+    <ClCompile>
+      <PreprocessorDefinitions>_USRDLL;MHD_W32DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary Condition="'$(UseDebugLibraries)'=='true'">MultiThreadedDebugDLL</RuntimeLibrary>
+      <RuntimeLibrary Condition="'$(UseDebugLibraries)'!='true'">MultiThreadedDLL</RuntimeLibrary>
+    </ClCompile>
+    <Link>
+      <AdditionalDependencies>Ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+</Project>
diff --git a/w32/common/libmicrohttpd-files.vcxproj b/w32/common/libmicrohttpd-files.vcxproj
new file mode 100644
index 0000000..0790a3e
--- /dev/null
+++ b/w32/common/libmicrohttpd-files.vcxproj
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="$(MhdSrc)microhttpd\basicauth.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\connection.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\daemon.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\digestauth.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\gen_auth.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\internal.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\md5.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\sha256.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\sha512_256.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\memorypool.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_mono_clock.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\postprocessor.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\reason_phrase.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\response.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\tsearch.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\sysfdsetsize.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_str.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_threads.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_send.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_sockets.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_itc.c" />
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_compat.c">
+      <ExcludedFromBuild Condition="'$(PlatformToolsetVersion)'&gt;='140'">true</ExcludedFromBuild>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_panic.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="$(MhdSrc)include\autoinit_funcs.h" />
+    <ClInclude Include="$(MhdSrc)include\microhttpd.h" />
+    <ClInclude Include="$(MhdSrc)include\mhd_options.h" />
+    <ClInclude Include="$(MhdSrc)include\platform.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\basicauth.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\connection.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\digestauth.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\gen_auth.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\internal.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_md5_wrap.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\md5.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_sha256_wrap.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\sha256.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\sha512_256.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\memorypool.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_assert.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_align.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_bithelpers.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_byteorder.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_limits.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_mono_clock.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\response.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\postprocessor.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\tsearch.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\sysfdsetsize.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_str.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_str_types.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_threads.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_locks.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_send.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_sockets.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_itc.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_itc_types.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_compat.h" />
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_panic.h" />
+    <ClInclude Include="$(MhdW32Common)MHD_config.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="$(MhdW32Common)microhttpd_dll_res_vc.rc">
+      <ExcludedFromBuild Condition="'$(ConfigurationType)'=='StaticLibrary'">true</ExcludedFromBuild>
+    </ResourceCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <CustomBuild Include="$(MhdW32Common)microhttpd_dll_res_vc.rc.in">
+      <ExcludedFromBuild Condition="'$(ConfigurationType)'=='StaticLibrary'">true</ExcludedFromBuild>
+      <ExcludedFromBuild Condition="'$(ConfigurationType)'=='DynamicLibrary'">false</ExcludedFromBuild>
+      <FileType>Document</FileType>
+      <Command>PowerShell.exe -Version 3.0 -NonInteractive -NoProfile -ExecutionPolicy Bypass -File "$(MhdW32Common)gen_dll_res.ps1" -BasePath "$(MhdW32Common)\"</Command>
+      <Message>Generating .dll description resource</Message>
+      <Outputs>$(MhdW32Common)microhttpd_dll_res_vc.rc</Outputs>
+      <AdditionalInputs>$(MhdW32Common)gen_dll_res.ps1;$(MhdRoot)configure.ac</AdditionalInputs>
+    </CustomBuild>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/libmicrohttpd-filters.vcxproj b/w32/common/libmicrohttpd-filters.vcxproj
new file mode 100644
index 0000000..27fd6f1
--- /dev/null
+++ b/w32/common/libmicrohttpd-filters.vcxproj
@@ -0,0 +1,218 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Internal Headers">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Public Headers">
+      <UniqueIdentifier>{ec88d605-3383-4989-8e25-bc8efa824720}</UniqueIdentifier>
+      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+   <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+    <Filter Include="Template Files">
+      <UniqueIdentifier>{df5ad836-e372-437b-a0e3-299d3675d6b4}</UniqueIdentifier>
+      <Extensions>in</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="$(MhdSrc)include\microhttpd.h">
+      <Filter>Public Headers</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="$(MhdSrc)include\autoinit_funcs.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)include\platform.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)include\mhd_options.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdW32Common)MHD_config.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\basicauth.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\connection.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\digestauth.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\gen_auth.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\internal.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_md5_wrap.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\md5.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_sha256_wrap.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\sha256.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\sha512_256.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\memorypool.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\postprocessor.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\response.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\tsearch.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_assert.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_align.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_limits.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_bithelpers.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_byteorder.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_mono_clock.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\sysfdsetsize.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_str.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_str_types.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_threads.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_locks.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_sockets.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_itc_types.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_itc.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_send.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_compat.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+    <ClInclude Include="$(MhdSrc)microhttpd\mhd_panic.h">
+      <Filter>Internal Headers</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="$(MhdSrc)microhttpd\basicauth.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\connection.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\daemon.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\digestauth.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\gen_auth.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\internal.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\md5.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\sha256.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\sha512_256.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\memorypool.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\postprocessor.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\reason_phrase.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\response.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\tsearch.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_mono_clock.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\sysfdsetsize.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_str.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_threads.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_sockets.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_itc.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_send.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_compat.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="$(MhdSrc)microhttpd\mhd_panic.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="$(MhdW32Common)microhttpd_dll_res_vc.rc">
+      <Filter>Resource Files</Filter>
+    </ResourceCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <CustomBuild Include="$(MhdW32Common)microhttpd_dll_res_vc.rc.in">
+      <Filter>Template Files</Filter>
+    </CustomBuild>
+  </ItemGroup>
+</Project>
diff --git a/w32/VS2013/microhttpd_dll_res_vc.rc.in b/w32/common/microhttpd_dll_res_vc.rc.in
similarity index 78%
rename from w32/VS2013/microhttpd_dll_res_vc.rc.in
rename to w32/common/microhttpd_dll_res_vc.rc.in
index 19eb37c..ef016c7 100644
--- a/w32/VS2013/microhttpd_dll_res_vc.rc.in
+++ b/w32/common/microhttpd_dll_res_vc.rc.in
@@ -23,15 +23,15 @@
             VALUE "ProductName", "GNU libmicrohttpd\0"
             VALUE "ProductVersion", "@PACKAGE_VERSION@\0"
             VALUE "FileVersion", "@PACKAGE_VERSION@\0"
-            VALUE "FileDescription", "GNU libmicrohttpd dll for Windows (VC build)\0"
+            VALUE "FileDescription", "GNU libmicrohttpd DLL for Windows (VC build)\0"
             VALUE "InternalName", "libmicrohttpd\0"
 #if defined(_DEBUG)
-            VALUE "OriginalFilename", "libmicrohttpd_d.dll\0"
+            VALUE "OriginalFilename", "libmicrohttpd-dll_d.dll\0"
 #else
-            VALUE "OriginalFilename", "libmicrohttpd.dll\0"
+            VALUE "OriginalFilename", "libmicrohttpd-dll.dll\0"
 #endif
             VALUE "CompanyName", "Free Software Foundation\0"
-            VALUE "LegalCopyright",  "Copyright (C) 2007-2015 Christian Grothoff and project contributors\0"
+            VALUE "LegalCopyright",  "Copyright (C) 2007-2021 Christian Grothoff, Evgeny Grin, and project contributors\0"
             VALUE "Comments", "http://www.gnu.org/software/libmicrohttpd/\0"
         END
     END
diff --git a/w32/common/project-configs-xp.props b/w32/common/project-configs-xp.props
new file mode 100644
index 0000000..60aafb7
--- /dev/null
+++ b/w32/common/project-configs-xp.props
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug-dll-xp|Win32">
+      <Configuration>Debug-dll-xp</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-dll-xp|x64">
+      <Configuration>Debug-dll-xp</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static-xp|Win32">
+      <Configuration>Debug-static-xp</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static-xp|x64">
+      <Configuration>Debug-static-xp</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll-xp|Win32">
+      <Configuration>Release-dll-xp</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll-xp|x64">
+      <Configuration>Release-dll-xp</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static-xp|Win32">
+      <Configuration>Release-static-xp</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static-xp|x64">
+      <Configuration>Release-static-xp</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <!-- Next configurations are uselss, but VS requires the full set to function properly -->
+    <ProjectConfiguration Include="Debug-dll-xp|ARM">
+      <Configuration>Debug-dll-xp</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-dll-xp|ARM64">
+      <Configuration>Debug-dll-xp</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static-xp|ARM">
+      <Configuration>Debug-static-xp</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static-xp|ARM64">
+      <Configuration>Debug-static-xp</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll-xp|ARM">
+      <Configuration>Release-dll-xp</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll-xp|ARM64">
+      <Configuration>Release-dll-xp</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static-xp|ARM">
+      <Configuration>Release-static-xp</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static-xp|ARM64">
+      <Configuration>Release-static-xp</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/project-configs.props b/w32/common/project-configs.props
new file mode 100644
index 0000000..ca2dce6
--- /dev/null
+++ b/w32/common/project-configs.props
@@ -0,0 +1,69 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug-dll|Win32">
+      <Configuration>Debug-dll</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-dll|x64">
+      <Configuration>Debug-dll</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-dll|ARM">
+      <Configuration>Debug-dll</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-dll|ARM64">
+      <Configuration>Debug-dll</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static|Win32">
+      <Configuration>Debug-static</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static|x64">
+      <Configuration>Debug-static</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static|ARM">
+      <Configuration>Debug-static</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug-static|ARM64">
+      <Configuration>Debug-static</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll|Win32">
+      <Configuration>Release-dll</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll|x64">
+      <Configuration>Release-dll</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll|ARM">
+      <Configuration>Release-dll</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-dll|ARM64">
+      <Configuration>Release-dll</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static|Win32">
+      <Configuration>Release-static</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static|x64">
+      <Configuration>Release-static</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static|ARM">
+      <Configuration>Release-static</Configuration>
+      <Platform>ARM</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release-static|ARM64">
+      <Configuration>Release-static</Configuration>
+      <Platform>ARM64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/simplepost-files.vcxproj b/w32/common/simplepost-files.vcxproj
new file mode 100644
index 0000000..55182b0
--- /dev/null
+++ b/w32/common/simplepost-files.vcxproj
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="$(MhdRoot)doc\examples\simplepost.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="libmicrohttpd.vcxproj">
+      <Project>{9cfb0342-a9e7-483e-bee5-a1de22584c5a}</Project>
+    </ProjectReference>
+  </ItemGroup>
+</Project>
diff --git a/w32/common/vs_dirs.props b/w32/common/vs_dirs.props
new file mode 100644
index 0000000..f8d1c7a
--- /dev/null
+++ b/w32/common/vs_dirs.props
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Label="UserMacros">
+    <MhdRoot>$(SolutionDir)..\..\</MhdRoot>
+    <MhdSrc>$(SolutionDir)..\..\src\</MhdSrc>
+    <MhdW32Dir>$(SolutionDir)..\</MhdW32Dir>
+    <MhdW32Common>$(MhdW32Dir)common\</MhdW32Common>
+  </PropertyGroup>
+</Project>